text string | size int64 | token_count int64 |
|---|---|---|
#include "../asserts.hpp"
#include "as3_object.hpp"
#include "as3_value.hpp"
#include "../swf_player.hpp"
namespace avm2
{
as3_object::as3_object(swf::player_ptr player)
: player_(player)
{
}
double as3_object::to_number()
{
const char* str = to_string();
if(str) {
return atof(str);
}
return 0;
}
void as3_object::builtin(const std::string& name, const as3_value& value)
{
auto it = members_.find(name);
if(it != members_.end()) {
std::cerr << "Replacing builtin: " << name << std::endl;
}
members_[name] = value;
members_[name].set_flags(as3_value::DO_NOT_ENUM);
}
as3_value as3_object::default_value(HintType hint)
{
if(hint == NO_HINT || hint == HINT_NUMBER) {
return as3_value(to_number());
}
ASSERT_LOG(hint != HINT_STRING, "FATAL: hint value is unknown: " << hint);
// string hint
return as3_value(to_string());
}
}
| 879 | 384 |
#include <map>
#include <iostream>
#define DEBUG
#ifdef DEBUG
int newCount = 0;
int deleteCount = 0;
void *operator new(size_t size)
{
newCount++;
return malloc(size);
}
void operator delete(void *data)
{
deleteCount++;
free(data);
return ;
}
#endif
class LRUNode
{
public:
LRUNode(int key, int value)
: m_key(key), m_value(value), m_last(nullptr), m_next(nullptr)
{}
int m_key, m_value;
LRUNode *m_last, *m_next;
};
class LRUCache
{
public:
LRUCache(int capacity)
: m_size(0), m_max(capacity), m_head(new LRUNode(-1, -1)), m_end(new LRUNode(-1, -1))
{
m_head->m_next = m_end;
m_end->m_last = m_head;
m_end->m_next = nullptr;
}
~LRUCache()
{
auto temp = m_head;
while(temp)
{
auto temp2 = temp;
temp = temp->m_next;
delete temp2;
}
}
int get(int key)
{
auto it = m_map.find(key);
if(it != m_map.end())
{
auto temp =it->second;
temp->m_last->m_next = temp->m_next;
temp->m_next->m_last = temp->m_last;
temp->m_next = m_head->m_next;
temp->m_next->m_last = temp;
m_head->m_next = temp;
temp->m_last = m_head;
return temp->m_value;
}
else
{
return -1;
}
}
void put(int key, int value)
{
auto it = m_map.find(key);
if(it != m_map.end())
{
it->second->m_last->m_next = it->second->m_next;
it->second->m_next->m_last = it->second->m_last;
auto temp = it->second;
temp->m_next = m_head->m_next;
temp->m_next->m_last = temp;
m_head->m_next = temp;
temp->m_last = m_head;
temp->m_value = value;
return ;
}
if(m_size == m_max)
{
auto temp = m_end->m_last;
temp->m_last->m_next = temp->m_next;
temp->m_next->m_last = temp->m_last;
m_map.erase(m_map.find(temp->m_key));
delete temp;
m_size --;
}
auto temp = new LRUNode(key, value);
m_map[key] = temp;
temp->m_next = m_head->m_next;
temp->m_next->m_last = temp;
m_head->m_next = temp;
temp->m_last = m_head;
m_size ++;
return ;
}
std::map<int, LRUNode *> m_map;
LRUNode *m_head, *m_end;
int m_size;
int m_max;
};
int main()
{
LRUCache *cache = new LRUCache(2);
cache->put(1, 1);
cache->put(2, 2);
std::cout << cache->get(1) << std::endl;
cache->put(3, 3);
std::cout << cache->get(2) << std::endl;
cache->put(4, 4);
std::cout << cache->get(1) << std::endl;
std::cout << cache->get(3) << std::endl;
std::cout << cache->get(4) << std::endl;
delete cache;
#ifdef DEBUG
std::cout << (newCount == deleteCount) << std::endl;
#endif
return 0;
} | 3,121 | 1,154 |
#pragma once
#include "net/packet.hpp"
#include "net/socket.hpp"
#include "noncopyable.hpp"
#include "platform/types.hpp"
namespace gnet {
class engine;
class connection : public noncopyable<connection> {
friend class engine;
public:
enum class status {
none,
listening,
connecting,
connected,
};
connection() = default;
~connection() = default;
auto set_user_data(void* const data) -> void;
auto get_user_data(void) -> void*;
auto close(void) -> void;
protected:
socket m_sock;
status m_status = status::none;
void* m_user_data = nullptr;
u64 m_totoal_send_bytes = 0;
u64 m_totoal_recv_bytes = 0;
};
} // namespace gnet
| 689 | 251 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/web_applications/components/web_app_constants.h"
#include "base/compiler_specific.h"
#include "components/services/app_service/public/mojom/types.mojom.h"
namespace web_app {
static_assert(Source::kMinValue == 0, "Source enum should be zero based");
bool IsSuccess(InstallResultCode code) {
return code == InstallResultCode::kSuccessNewInstall ||
code == InstallResultCode::kSuccessAlreadyInstalled;
}
DisplayMode ResolveEffectiveDisplayMode(DisplayMode app_display_mode,
DisplayMode user_display_mode) {
switch (user_display_mode) {
case DisplayMode::kBrowser:
return user_display_mode;
case DisplayMode::kUndefined:
case DisplayMode::kMinimalUi:
case DisplayMode::kFullscreen:
NOTREACHED();
FALLTHROUGH;
case DisplayMode::kStandalone:
break;
}
switch (app_display_mode) {
case DisplayMode::kBrowser:
case DisplayMode::kMinimalUi:
return DisplayMode::kMinimalUi;
case DisplayMode::kUndefined:
NOTREACHED();
FALLTHROUGH;
case DisplayMode::kStandalone:
case DisplayMode::kFullscreen:
return DisplayMode::kStandalone;
}
}
apps::mojom::LaunchContainer ConvertDisplayModeToAppLaunchContainer(
DisplayMode display_mode) {
switch (display_mode) {
case DisplayMode::kBrowser:
return apps::mojom::LaunchContainer::kLaunchContainerTab;
case DisplayMode::kMinimalUi:
return apps::mojom::LaunchContainer::kLaunchContainerWindow;
case DisplayMode::kStandalone:
return apps::mojom::LaunchContainer::kLaunchContainerWindow;
case DisplayMode::kFullscreen:
return apps::mojom::LaunchContainer::kLaunchContainerWindow;
case DisplayMode::kUndefined:
return apps::mojom::LaunchContainer::kLaunchContainerNone;
}
}
} // namespace web_app
| 2,023 | 609 |
#ifndef MAIN_H
#define MAIN_H
#include "SDK/amx/amx.h"
#include "SDK/plugincommon.h"
#define BCRYPT_VERSION "v2.2.3"
#endif
| 127 | 65 |
/**************************************************************************
* *
* File : nvector.c *
* Programmers : Radu Serban, LLNL *
* Version of : 26 June 2002 *
*------------------------------------------------------------------------*
* Copyright (c) 2002, The Regents of the University of California *
* Produced at the Lawrence Livermore National Laboratory *
* All rights reserved *
* For details, see LICENSE below *
*------------------------------------------------------------------------*
* This is the implementation file for a generic NVECTOR *
* package. It contains the implementation of the N_Vector *
* kernels listed in nvector.h. *
* *
*------------------------------------------------------------------------*
* LICENSE *
*------------------------------------------------------------------------*
* Copyright (c) 2002, The Regents of the University of California. *
* Produced at the Lawrence Livermore National Laboratory. *
* Written by S.D. Cohen, A.C. Hindmarsh, R. Serban, *
* D. Shumaker, and A.G. Taylor. *
* UCRL-CODE-155951 (CVODE) *
* UCRL-CODE-155950 (CVODES) *
* UCRL-CODE-155952 (IDA) *
* UCRL-CODE-237203 (IDAS) *
* UCRL-CODE-155953 (KINSOL) *
* All rights reserved. *
* *
* This file is part of SUNDIALS. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the disclaimer below. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the disclaimer (as noted below) *
* in the documentation and/or other materials provided with the *
* distribution. *
* *
* 3. Neither the name of the UC/LLNL nor the names of its contributors *
* may be used to endorse or promote products derived from this software *
* without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS *
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE *
* REGENTS OF THE UNIVERSITY OF CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY *
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
**************************************************************************/
#include "nvector.h" /* generic M_Env and N_Vector */
#if defined(PHREEQCI_GUI)
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#endif
N_Vector
N_VNew(integertype n, M_Env machEnv)
{
N_Vector v_new;
v_new = machEnv->ops->nvnew(n, machEnv);
return (v_new);
}
N_Vector_S
N_VNew_S(integertype ns, integertype n, M_Env machEnv)
{
N_Vector_S vs_new;
vs_new = machEnv->ops->nvnewS(ns, n, machEnv);
return (vs_new);
}
void
N_VFree(N_Vector v)
{
v->menv->ops->nvfree(v);
}
void
N_VFree_S(integertype ns, N_Vector_S vs)
{
(*vs)->menv->ops->nvfreeS(ns, vs);
}
N_Vector
N_VMake(integertype n, realtype * v_data, M_Env machEnv)
{
N_Vector v_new;
v_new = machEnv->ops->nvmake(n, v_data, machEnv);
return (v_new);
}
void
N_VDispose(N_Vector v)
{
v->menv->ops->nvdispose(v);
}
realtype *
N_VGetData(N_Vector v)
{
realtype *data;
data = v->menv->ops->nvgetdata(v);
return (data);
}
void
N_VSetData(realtype * v_data, N_Vector v)
{
v->menv->ops->nvsetdata(v_data, v);
}
void
N_VLinearSum(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z)
{
z->menv->ops->nvlinearsum(a, x, b, y, z);
}
void
N_VConst(realtype c, N_Vector z)
{
z->menv->ops->nvconst(c, z);
}
void
N_VProd(N_Vector x, N_Vector y, N_Vector z)
{
z->menv->ops->nvprod(x, y, z);
}
void
N_VDiv(N_Vector x, N_Vector y, N_Vector z)
{
z->menv->ops->nvdiv(x, y, z);
}
void
N_VScale(realtype c, N_Vector x, N_Vector z)
{
z->menv->ops->nvscale(c, x, z);
}
void
N_VAbs(N_Vector x, N_Vector z)
{
z->menv->ops->nvabs(x, z);
}
void
N_VInv(N_Vector x, N_Vector z)
{
z->menv->ops->nvinv(x, z);
}
void
N_VAddConst(N_Vector x, realtype b, N_Vector z)
{
z->menv->ops->nvaddconst(x, b, z);
}
realtype
N_VDotProd(N_Vector x, N_Vector y)
{
realtype prod;
prod = y->menv->ops->nvdotprod(x, y);
return (prod);
}
realtype
N_VMaxNorm(N_Vector x)
{
realtype norm;
norm = x->menv->ops->nvmaxnorm(x);
return (norm);
}
realtype
N_VWrmsNorm(N_Vector x, N_Vector w)
{
realtype norm;
norm = x->menv->ops->nvwrmsnorm(x, w);
return (norm);
}
realtype
N_VMin(N_Vector x)
{
realtype minval;
minval = x->menv->ops->nvmin(x);
return (minval);
}
realtype
N_VWL2Norm(N_Vector x, N_Vector w)
{
realtype norm;
norm = x->menv->ops->nvwl2norm(x, w);
return (norm);
}
realtype
N_VL1Norm(N_Vector x)
{
realtype norm;
norm = x->menv->ops->nvl1norm(x);
return (norm);
}
void
N_VOneMask(N_Vector x)
{
x->menv->ops->nvonemask(x);
}
void
N_VCompare(realtype c, N_Vector x, N_Vector z)
{
z->menv->ops->nvcompare(c, x, z);
}
booleantype
N_VInvTest(N_Vector x, N_Vector z)
{
booleantype flag;
flag = z->menv->ops->nvinvtest(x, z);
return (flag);
}
booleantype
N_VConstrProdPos(N_Vector c, N_Vector x)
{
booleantype flag;
flag = x->menv->ops->nvconstrprodpos(c, x);
return (flag);
}
booleantype
N_VConstrMask(N_Vector c, N_Vector x, N_Vector m)
{
booleantype flag;
flag = x->menv->ops->nvconstrmask(c, x, m);
return (flag);
}
realtype
N_VMinQuotient(N_Vector num, N_Vector denom)
{
realtype quotient;
quotient = num->menv->ops->nvminquotient(num, denom);
return (quotient);
}
void
N_VPrint(N_Vector x)
{
x->menv->ops->nvprint(x);
}
| 7,729 | 2,697 |
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "SurfaceUtils.h"
using namespace android;
// # of buffer (frame 0 for LayerDim)
#define FRAME_COUNT 5
frame_t frames[FRAME_COUNT];
static void initFrames()
{
frame_t *f;
block_t *b;
const char img_name[] = "/data/android.png";
for (int i = 0; i < FRAME_COUNT; i++) {
f = &frames[i];
f->api_type = NATIVE_WINDOW_API_MEDIA;
strncpy(f->name, img_name, sizeof(img_name));
// blk 0
b = &f->blk[0];
b->rect = Rect(0, 220, 300, 300);
b->alpha = 0.0f;
// blk 1
b = &f->blk[1];
b->rect = Rect(100, 80, 200, 180);
b->alpha = 0.3f;
}
}
status_t main(int argc, char** argv)
{
// create our thread pool
sp<ProcessState> proc = ProcessState::self();
ProcessState::self()->startThreadPool();
// one layer per client
sp<SurfaceComposerClient> client[FRAME_COUNT];
for (int i = 0; i < FRAME_COUNT; i++) {
client[i] = new SurfaceComposerClient();
}
LOGD("end create client");
sp<SurfaceControl> surfaceControls[FRAME_COUNT];
// surface 1 (LayerDim)
surfaceControls[0] = client[0]->createSurface(
String8("test-surface2"),
DISPLAY_HANDLE,
DISPLAY_WIDTH,
DISPLAY_HEIGHT,
PIXEL_FORMAT_RGBA_8888,
ISurfaceComposer::eFXSurfaceDim & ISurfaceComposer::eFXSurfaceMask);
// surface 2 ~
for (int i = 1; i < FRAME_COUNT; i++) {
surfaceControls[i] = client[i]->createSurface(
String8("test-surface2"),
DISPLAY_HANDLE,
LAYER_WIDTH,
LAYER_HEIGHT,
PIXEL_FORMAT_RGBA_8888);
}
LOGD("end create surface");
SurfaceComposerClient::openGlobalTransaction();
// surface 1 (LayerDim)
surfaceControls[0]->setLayer(100000);
surfaceControls[0]->setPosition(0, 0);
surfaceControls[0]->setAlpha(0.6f);
// surace 2 ~
for (int i = 1; i < FRAME_COUNT; i++) {
surfaceControls[i]->setLayer(101000 + i * 10);
surfaceControls[i]->setPosition(i * 20, i * 50);
}
SurfaceComposerClient::closeGlobalTransaction();
LOGD("end transaction");
Parcel parcels[FRAME_COUNT]; // i = 1 means that we exclude LayerDim
sp<Surface> surfaces[FRAME_COUNT]; // 1 = 1 means that exclude LayerDim
// pretend it went cross-process
// surface 2 ~
for (int i = 1; i < FRAME_COUNT; i++) {
SurfaceControl::writeSurfaceToParcel(surfaceControls[i], &parcels[i]);
parcels[i].setDataPosition(0);
surfaces[i] = Surface::readFromParcel(parcels[i]);
}
LOGD("end IPC");
// surface 2 ~
SurfaceUtils surface_utils[FRAME_COUNT]; // i = 1 means that we exclude LayerDim
ANativeWindow *windows[FRAME_COUNT]; // i = 1 means that we exclude LayerDim
for (int i = 1; i < FRAME_COUNT; i++) {
windows[i] = surfaces[i].get();
LOGD("window = %p\n", windows[i]);
surface_utils[i].setWindow(windows[i]);
}
// set api connection type
//native_window_api_connect(window, frame.api_type);
// exclude LayerDim
for (int i = 1; i < FRAME_COUNT; i++) {
surface_utils[i].connectAPI(NATIVE_WINDOW_API_CPU);
}
// initialize input frames
initFrames();
// display
int loop = 0;
while (true) {
// surface 2 ~
for (int i = 1; i < FRAME_COUNT; i++) {
// show frame
surface_utils[i].showTestFrame(&frames[0], i % 4);
}
usleep(16667); // fsp = 60
loop = loop + 1;
if (loop == FRAME_COUNT) {
// printf("\nloop again...\n");
loop = 0;
}
};
IPCThreadState::self()->joinThreadPool();
return NO_ERROR;
}
| 6,597 | 2,410 |
#include "InverseGaussianRand.h"
#include "NormalRand.h"
#include "UniformRand.h"
InverseGaussianRand::InverseGaussianRand(double mean, double shape)
{
SetParameters(mean, shape);
}
String InverseGaussianRand::Name() const
{
return "Inverse-Gaussian(" + toStringWithPrecision(GetMean()) + ", " + toStringWithPrecision(GetShape()) + ")";
}
void InverseGaussianRand::SetParameters(double mean, double shape)
{
if (mean <= 0.0)
throw std::invalid_argument("Inverse-Gaussian distribution: mean should be positive");
if (shape <= 0.0)
throw std::invalid_argument("Inverse-Gaussian distribution: shape should be positive");
mu = mean;
lambda = shape;
pdfCoef = 0.5 * std::log(0.5 * lambda * M_1_PI);
cdfCoef = std::exp(2 * lambda / mu);
}
double InverseGaussianRand::f(const double & x) const
{
return (x > 0.0) ? std::exp(logf(x)) : 0.0;
}
double InverseGaussianRand::logf(const double & x) const
{
if (x <= 0.0)
return -INFINITY;
double y = -1.5 * std::log(x);
double z = (x - mu);
z *= z;
z *= -0.5 * lambda / (x * mu * mu);
z += pdfCoef;
return y + z;
}
double InverseGaussianRand::F(const double & x) const
{
if (x <= 0.0)
return 0.0;
double b = std::sqrt(0.5 * lambda / x);
double a = b * x / mu;
double y = std::erfc(b - a);
y += cdfCoef * std::erfc(a + b);
return 0.5 * y;
}
double InverseGaussianRand::S(const double & x) const
{
if (x <= 0.0)
return 1.0;
double b = std::sqrt(0.5 * lambda / x);
double a = b * x / mu;
double y = std::erfc(a - b);
y -= cdfCoef * std::erfc(a + b);
return 0.5 * y;
}
double InverseGaussianRand::Variate() const
{
double X = NormalRand::StandardVariate(localRandGenerator);
double U = UniformRand::StandardVariate(localRandGenerator);
X *= X;
double mupX = mu * X;
double y = 4 * lambda + mupX;
y = std::sqrt(y * mupX);
y -= mupX;
y *= -0.5 / lambda;
++y;
if (U * (1 + y) > 1.0)
y = 1.0 / y;
return mu * y;
}
double InverseGaussianRand::Mean() const
{
return mu;
}
double InverseGaussianRand::Variance() const
{
return mu * mu * mu / lambda;
}
std::complex<double> InverseGaussianRand::CFImpl(double t) const
{
double im = mu * mu;
im *= t / lambda;
std::complex<double> y(1, -im - im);
y = 1.0 - std::sqrt(y);
y *= lambda / mu;
return std::exp(y);
}
double InverseGaussianRand::Mode() const
{
double aux = 1.5 * mu / lambda;
double mode = 1 + aux * aux;
mode = std::sqrt(mode);
mode -= aux;
return mu * mode;
}
double InverseGaussianRand::Skewness() const
{
return 3 * std::sqrt(mu / lambda);
}
double InverseGaussianRand::ExcessKurtosis() const
{
return 15 * mu / lambda;
}
| 2,789 | 1,089 |
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include "ncbind/ncbind.hpp"
#include <map>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include "cxdec.h"
#include "tp_stub.h"
#include "XP3Archive.h"
#undef tTJSBinaryStream
class XP3Stream : public IStream {
public:
XP3Stream(CompatTJSBinaryStream *in_vfd)
{
ref_count = 1;
vfd = in_vfd;
}
// IUnknown
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject)
{
if (riid == IID_IUnknown || riid == IID_ISequentialStream || riid == IID_IStream)
{
if (ppvObject == NULL)
return E_POINTER;
*ppvObject = this;
AddRef();
return S_OK;
}
else
{
*ppvObject = 0;
return E_NOINTERFACE;
}
}
ULONG STDMETHODCALLTYPE AddRef(void)
{
ref_count++;
return ref_count;
}
ULONG STDMETHODCALLTYPE Release(void)
{
int ret = --ref_count;
if (ret <= 0) {
delete this;
ret = 0;
}
return ret;
}
// ISequentialStream
HRESULT STDMETHODCALLTYPE Read(void *pv, ULONG cb, ULONG *pcbRead)
{
try
{
ULONG read;
read = vfd->Read(pv, cb);
if(pcbRead) *pcbRead = read;
}
catch(...)
{
return E_FAIL;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE Write(const void *pv, ULONG cb, ULONG *pcbWritten)
{
return E_NOTIMPL;
}
// IStream
HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER dlibMove, DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition)
{
try
{
switch(dwOrigin)
{
case STREAM_SEEK_SET:
if(plibNewPosition)
(*plibNewPosition).QuadPart =
vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_SET);
else
vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_SET);
break;
case STREAM_SEEK_CUR:
if(plibNewPosition)
(*plibNewPosition).QuadPart =
vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_CUR);
else
vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_CUR);
break;
case STREAM_SEEK_END:
if(plibNewPosition)
(*plibNewPosition).QuadPart =
vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_END);
else
vfd->Seek(dlibMove.QuadPart, TJS_BS_SEEK_END);
break;
default:
return E_FAIL;
}
}
catch(...)
{
return E_FAIL;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE SetSize(ULARGE_INTEGER libNewSize)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CopyTo(IStream *pstm, ULARGE_INTEGER cb, ULARGE_INTEGER *pcbRead, ULARGE_INTEGER *pcbWritten)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE Commit(DWORD grfCommitFlags)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE Revert(void)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE LockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE UnlockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE Stat(STATSTG *pstatstg, DWORD grfStatFlag)
{
// This method imcompletely fills the target structure, because some
// informations like access mode or stream name are already lost
// at this point.
if(pstatstg)
{
ZeroMemory(pstatstg, sizeof(*pstatstg));
#if 0
// pwcsName
// this object's storage pointer does not have a name ...
if(!(grfStatFlag & STATFLAG_NONAME))
{
// anyway returns an empty string
LPWSTR str = (LPWSTR)CoTaskMemAlloc(sizeof(*str));
if(str == NULL) return E_OUTOFMEMORY;
*str = TJS_W('\0');
pstatstg->pwcsName = str;
}
#endif
// type
pstatstg->type = STGTY_STREAM;
// cbSize
pstatstg->cbSize.QuadPart = vfd->GetSize();
// mtime, ctime, atime unknown
// grfMode unknown
pstatstg->grfMode = STGM_DIRECT | STGM_READWRITE | STGM_SHARE_DENY_WRITE ;
// Note that this method always returns flags above, regardless of the
// actual mode.
// In the return value, the stream is to be indicated that the
// stream can be written, but of cource, the Write method will fail
// if the stream is read-only.
// grfLockSuppoted
pstatstg->grfLocksSupported = 0;
// grfStatBits unknown
}
else
{
return E_INVALIDARG;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE Clone(IStream **ppstm)
{
return E_NOTIMPL;
}
protected:
/**
* デストラクタ
*/
virtual ~XP3Stream()
{
delete vfd;
vfd = NULL;
}
private:
int ref_count;
CompatTJSBinaryStream *vfd;
};
class XP3Storage : public iTVPStorageMedia
{
public:
XP3Storage(tTVPXP3Archive *in_fs)
{
ref_count = 1;
fs = in_fs;
char buf[(sizeof(void *) * 2) + 1];
snprintf(buf, (sizeof(void *) * 2) + 1, "%p", this);
// The hash function does not work properly with numbers, so change to letters.
char *p = buf;
while(*p)
{
if(*p >= '0' && *p <= '9')
*p = 'g' + (*p - '0');
if(*p >= 'A' && *p <= 'Z')
*p |= 32;
p++;
}
name = ttstr(TJS_W("xpk")) + buf;
}
virtual ~XP3Storage()
{
if (fs)
{
delete fs;
fs = NULL;
}
}
public:
// -----------------------------------
// iTVPStorageMedia Intefaces
// -----------------------------------
virtual void TJS_INTF_METHOD AddRef()
{
ref_count++;
};
virtual void TJS_INTF_METHOD Release()
{
if (ref_count == 1)
{
delete this;
}
else
{
ref_count--;
}
};
// returns media name like "file", "http" etc.
virtual void TJS_INTF_METHOD GetName(ttstr &out_name)
{
out_name = name;
}
// virtual ttstr TJS_INTF_METHOD IsCaseSensitive() = 0;
// returns whether this media is case sensitive or not
// normalize domain name according with the media's rule
virtual void TJS_INTF_METHOD NormalizeDomainName(ttstr &name)
{
// normalize domain name
// make all characters small
tjs_char *p = name.Independ();
while(*p)
{
if(*p >= TJS_W('A') && *p <= TJS_W('Z'))
*p += TJS_W('a') - TJS_W('A');
p++;
}
}
// normalize path name according with the media's rule
virtual void TJS_INTF_METHOD NormalizePathName(ttstr &name)
{
// normalize path name
// make all characters small
tjs_char *p = name.Independ();
while(*p)
{
if(*p >= TJS_W('A') && *p <= TJS_W('Z'))
*p += TJS_W('a') - TJS_W('A');
p++;
}
}
// check file existence
virtual bool TJS_INTF_METHOD CheckExistentStorage(const ttstr &name)
{
const tjs_char *ptr = name.c_str();
// The domain name needs to be "."
if (!TJS_strncmp(ptr, TJS_W("./"), 2))
{
ptr += 2;
ttstr fname(ptr);
tTVPArchive::NormalizeInArchiveStorageName(fname);
return fs->IsExistent(fname);
}
return false;
}
// open a storage and return a tTJSBinaryStream instance.
// name does not contain in-archive storage name but
// is normalized.
virtual tTJSBinaryStream * TJS_INTF_METHOD Open(const ttstr & name, tjs_uint32 flags) {
if (flags == TJS_BS_READ)
{
const tjs_char *ptr = name.c_str();
// The domain name needs to be "."
if (!TJS_strncmp(ptr, TJS_W("./"), 2))
{
ptr += 2;
ttstr fname(ptr);
tTVPArchive::NormalizeInArchiveStorageName(fname);
CompatTJSBinaryStream *stream = fs->CreateStream(fname);
if (stream)
{
IStream *streamm = new XP3Stream(stream);
if (streamm)
{
tTJSBinaryStream *ret = TVPCreateBinaryStreamAdapter(streamm);
streamm->Release();
return ret;
}
}
}
}
return NULL;
}
// list files at given place
virtual void TJS_INTF_METHOD GetListAt(const ttstr &name, iTVPStorageLister * lister)
{
const tjs_char *ptr = name.c_str();
// The domain name needs to be "."
if (!TJS_strncmp(ptr, TJS_W("./"), 2))
{
ptr += 2;
// Skip extra slashes
while (*ptr)
{
if (!TJS_strncmp(ptr, TJS_W("/"), 1))
{
ptr += 1;
}
else
{
break;
}
}
ttstr fname(ptr);
tTVPArchive::NormalizeInArchiveStorageName(fname);
// TODO: handle directories correctly
// Basic logic: trim leading name
int count = fs->GetCount();
for (int i = 0; i < count; i += 1)
{
ttstr filename = fs->GetName(i);
tTVPArchive::NormalizeInArchiveStorageName(filename);
// Skip directory
if (filename.StartsWith(fname))
{
const tjs_char *ptr2 = filename.c_str() + fname.GetLen();
ttstr fname(ptr2);
// Only add files directly in level
if (!TJS_strstr(ptr2, TJS_W("/")))
{
lister->Add(ptr2);
}
}
}
}
else
{
TVPAddLog(ttstr("Unable to search in: '") + ttstr(name) + ttstr("'"));
}
}
// basically the same as above,
// check wether given name is easily accessible from local OS filesystem.
// if true, returns local OS native name. otherwise returns an empty string.
virtual void TJS_INTF_METHOD GetLocallyAccessibleName(ttstr &name)
{
name = "";
}
virtual void TJS_INTF_METHOD SetArchiveExtractionFilter(tTVPXP3ArchiveExtractionFilterWithUserdata filter, void *filterdata)
{
fs->SetArchiveExtractionFilter(filter, filterdata);
}
private:
tjs_uint ref_count;
ttstr name;
tTVPXP3Archive *fs;
};
static std::vector<XP3Storage*> storage_media_vector;
class XP3Encryption
{
public:
XP3Encryption()
{
char buf[(sizeof(void *) * 2) + 1];
snprintf(buf, (sizeof(void *) * 2) + 1, "%p", this);
// The hash function does not work properly with numbers, so change to letters.
char *p = buf;
while(*p)
{
if(*p >= '0' && *p <= '9')
*p = 'g' + (*p - '0');
if(*p >= 'A' && *p <= 'Z')
*p |= 32;
p++;
}
name = ttstr(TJS_W("enc")) + buf;
filter = NULL;
}
virtual ~XP3Encryption()
{
}
virtual void TJS_INTF_METHOD GetName(ttstr &out_name)
{
out_name = name;
}
virtual void TJS_INTF_METHOD Filter(tTVPXP3ExtractionFilterInfo *info)
{
}
static void TVP_tTVPXP3ArchiveExtractionFilter_CONVENTION FilterExec(tTVPXP3ExtractionFilterInfo *info, void *data)
{
if (info->SizeOfSelf != sizeof(tTVPXP3ExtractionFilterInfo))
{
TVPThrowExceptionMessage(TJS_W("Incompatible tTVPXP3ExtractionFilterInfo size"));
}
((XP3Encryption *)data)->Filter(info);
}
virtual void TJS_INTF_METHOD GetArchiveExtractionFilter(tTVPXP3ArchiveExtractionFilterWithUserdata &out_filter, void * &out_data)
{
out_filter = FilterExec;
out_data = this;
}
private:
ttstr name;
tTVPXP3ArchiveExtractionFilterWithUserdata filter;
};
static std::vector<XP3Encryption*> xp3_encryption_vector;
class XP3CxdecEncryption : public XP3Encryption
{
public:
XP3CxdecEncryption(cxdec_information *in_information) : XP3Encryption()
{
memcpy(&information, in_information, sizeof(*in_information));
memset(&state, 0, sizeof(state));
cxdec_init(&state, &information);
}
virtual ~XP3CxdecEncryption()
{
cxdec_release(&state);
}
virtual void TJS_INTF_METHOD Filter(tTVPXP3ExtractionFilterInfo *info)
{
cxdec_decode(&state, &information, info->FileHash, (DWORD)(info->Offset), (PBYTE)(info->Buffer), (DWORD)(info->BufferSize));
}
private:
cxdec_information information;
cxdec_state state;
};
class StoragesXP3File {
public:
static ttstr mountXP3(ttstr filename)
{
{
{
tTVPXP3Archive * arc = NULL;
try
{
if (TVPIsXP3Archive(filename))
{
arc = new tTVPXP3Archive(filename);
if (arc)
{
XP3Storage * xp3storage = new XP3Storage(arc);
TVPRegisterStorageMedia(xp3storage);
storage_media_vector.push_back(xp3storage);
ttstr xp3storage_name;
xp3storage->GetName(xp3storage_name);
return xp3storage_name;
}
}
}
catch(...)
{
return TJS_W("");
}
}
}
return TJS_W("");
}
static bool setEncryptionXP3(ttstr medianame, ttstr encryptionmethod)
{
for (auto i = storage_media_vector.begin();
i != storage_media_vector.end(); i += 1)
{
ttstr this_medianame;
(*i)->GetName(this_medianame);
if (medianame == this_medianame)
{
if (encryptionmethod.GetLen() == 0)
{
(*i)->SetArchiveExtractionFilter(NULL, NULL);
return true;
}
else
{
for (auto j = xp3_encryption_vector.begin();
j != xp3_encryption_vector.end(); j += 1)
{
ttstr this_encryptionmethod;
(*j)->GetName(this_encryptionmethod);
if (encryptionmethod == this_encryptionmethod)
{
tTVPXP3ArchiveExtractionFilterWithUserdata this_encryptionfilter;
void *this_encryptionfilterdata;
(*j)->GetArchiveExtractionFilter(this_encryptionfilter, this_encryptionfilterdata);
(*i)->SetArchiveExtractionFilter(this_encryptionfilter, this_encryptionfilterdata);
return true;
}
}
}
return false;
}
}
return false;
}
static ttstr loadEncryptionMethodCxdec(tTJSVariant encryption_var)
{
cxdec_information information_tmp;
ncbPropAccessor encryption_accessor(encryption_var);
int max_count = encryption_accessor.GetArrayCount();
if (max_count >= 6)
{
tTJSVariant tmp_var;
if (encryption_accessor.checkVariant(0, tmp_var))
{
ncbPropAccessor tmp_accessor(tmp_var);
if (tmp_accessor.GetArrayCount() >= (int)sizeof(information_tmp.xcode_building_first_stage_order))
{
for (int i = 0; i < (int)sizeof(information_tmp.xcode_building_first_stage_order); i += 1)
{
information_tmp.xcode_building_first_stage_order[i] = (uint8_t)tmp_accessor.getIntValue(i);
}
}
else
{
return TJS_W("");
}
}
else
{
return TJS_W("");
}
if (encryption_accessor.checkVariant(1, tmp_var))
{
ncbPropAccessor tmp_accessor(tmp_var);
if (tmp_accessor.GetArrayCount() >= (int)sizeof(information_tmp.xcode_building_stage_0_order))
{
for (int i = 0; i < (int)sizeof(information_tmp.xcode_building_stage_0_order); i += 1)
{
information_tmp.xcode_building_stage_0_order[i] = (uint8_t)tmp_accessor.getIntValue(i);
}
}
else
{
return TJS_W("");
}
}
else
{
return TJS_W("");
}
if (encryption_accessor.checkVariant(2, tmp_var))
{
ncbPropAccessor tmp_accessor(tmp_var);
if (tmp_accessor.GetArrayCount() >= (int)sizeof(information_tmp.xcode_building_stage_1_order))
{
for (int i = 0; i < (int)sizeof(information_tmp.xcode_building_stage_1_order); i += 1)
{
information_tmp.xcode_building_stage_1_order[i] = (uint8_t)tmp_accessor.getIntValue(i);
}
}
else
{
return TJS_W("");
}
}
else
{
return TJS_W("");
}
if (encryption_accessor.checkVariant(3, tmp_var))
{
information_tmp.boundary_mask = (uint16_t)tmp_var.AsInteger();
}
else
{
return TJS_W("");
}
if (encryption_accessor.checkVariant(4, tmp_var))
{
information_tmp.boundary_offset = (uint16_t)tmp_var.AsInteger();
}
else
{
return TJS_W("");
}
if (encryption_accessor.checkVariant(5, tmp_var))
{
if (tmp_var.Type() == tvtOctet)
{
const tTJSVariantOctet *oct = tmp_var.AsOctetNoAddRef();
if (oct->GetLength() == (int)sizeof(information_tmp.encryption_control_block))
{
memcpy(information_tmp.encryption_control_block, oct->GetData(), (int)sizeof(information_tmp.encryption_control_block));
}
else
{
return TJS_W("");
}
}
else
{
return TJS_W("");
}
}
else
{
return TJS_W("");
}
{
XP3CxdecEncryption * xp3cxdecencryption = new XP3CxdecEncryption(&information_tmp);
xp3_encryption_vector.push_back(xp3cxdecencryption);
ttstr xp3cxdecencryption_name;
xp3cxdecencryption->GetName(xp3cxdecencryption_name);
return xp3cxdecencryption_name;
}
}
return TJS_W("");
}
static bool unmountXP3(ttstr medianame)
{
for (auto i = storage_media_vector.begin();
i != storage_media_vector.end(); i += 1)
{
ttstr this_medianame;
(*i)->GetName(this_medianame);
if (medianame == this_medianame)
{
TVPUnregisterStorageMedia(*i);
(*i)->Release();
storage_media_vector.erase(i);
return true;
}
}
return false;
}
};
NCB_ATTACH_CLASS(StoragesXP3File, Storages) {
NCB_METHOD(mountXP3);
NCB_METHOD(loadEncryptionMethodCxdec);
NCB_METHOD(setEncryptionXP3);
NCB_METHOD(unmountXP3);
};
static void PreRegistCallback()
{
}
static void PostUnregistCallback()
{
for (auto i = storage_media_vector.begin();
i != storage_media_vector.end(); i += 1)
{
TVPUnregisterStorageMedia(*i);
}
}
NCB_PRE_REGIST_CALLBACK(PreRegistCallback);
NCB_POST_UNREGIST_CALLBACK(PostUnregistCallback);
| 16,234 | 7,610 |
#include "Function.h"
#include "vectorclass/vectorclass.h"
#include "vectorclass/vectormath_exp.h"
namespace NSMathModule {
namespace NSFunctions {
double CDensity0::compute0_AVX(const std::vector<double>& means, double arg) {
double tmp_result = 0;
size_t regular_part = means.size() & static_cast<size_t>(-4);
for (size_t index = 0; index < regular_part; index += 4) {
Vec4d means_block(means[index], means[index + 1], means[index + 2],
means[index + 3]);
tmp_result += find_derivative_0(means_block, arg);
}
for (size_t index = regular_part; index < means.size(); ++index) {
double mean = means[regular_part];
tmp_result += find_derivative_0(mean, arg);
}
return tmp_result / static_cast<double>(means.size());
}
double CDensity1::compute1_AVX(const std::vector<double>& means, double arg) {
double tmp_result = 0;
size_t regular_part = means.size() & static_cast<size_t>(-4);
for (size_t index = 0; index < regular_part; index += 4) {
Vec4d means_block(means[index], means[index + 1], means[index + 2],
means[index + 3]);
tmp_result += find_derivative_1(means_block, arg);
}
for (size_t index = regular_part; index < means.size(); ++index) {
double mean = means[regular_part];
tmp_result += find_derivative_1(mean, arg);
}
return tmp_result / static_cast<double>(means.size());
}
double CDensity2::compute2_AVX(const std::vector<double>& means, double arg) {
double tmp_result = 0;
size_t regular_part = means.size() & static_cast<size_t>(-4);
for (size_t index = 0; index < regular_part; index += 4) {
Vec4d means_block(means[index], means[index + 1], means[index + 2],
means[index + 3]);
tmp_result += find_derivative_2(means_block, arg);
}
for (size_t index = regular_part; index < means.size(); ++index) {
double mean = means[regular_part];
tmp_result += find_derivative_2(mean, arg);
}
return tmp_result / static_cast<double>(means.size());
}
}
}
| 2,192 | 733 |
#include "pch.h"
#include <ang/platform/platform.h>
#include <ang/core/time.h>
#include "dispatcher.h"
#include "core_app.h"
#include <comdef.h>
#include <windowsx.h>
using namespace ang;
using namespace ang::platform;
using namespace ang::platform::events;
using namespace ang::platform::windows;
namespace ang::platform {
extern icore_app* s_current_app;
}
LRESULT STDCALL core_app::wndproc(HWND hwnd, UINT m, WPARAM wprm, LPARAM lprm)
{
message msg((core_msg)m, wprm, lprm);
core_app_t wnd = null;
if ((core_msg::created == (core_msg)m) && (lprm != 0))
{
LPCREATESTRUCT pcs = (LPCREATESTRUCT)lprm;
if (pcs->lpCreateParams)
{
wnd = (core_app*)pcs->lpCreateParams;
wnd->m_hwnd = hwnd;
SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR)pcs->lpCreateParams);
}
}
else
{
wnd = reinterpret_cast<core_app*>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
}
if (!wnd.is_empty())
{
wnd->wndproc(msg);
return msg.result();
}
return DefWindowProcW(hwnd, m, wprm, lprm);
}
core_app::core_app()
: m_hint(null)
, m_hwnd(null)
{
s_current_app = this;
m_thread = core::async::thread::this_thread();
m_timer.reset();
m_controllers = new input::controller_manager();
}
core_app::~core_app()
{
m_controllers = null;
s_current_app = null;
}
pointer core_app::core_app_handle()const
{
return m_hint;
}
icore_view_t core_app::core_view()
{
return this;
}
input::ikeyboard_t core_app::keyboard()
{
return null;
}
ivar core_app::property(astring name)const
{
return null;
}
void core_app::property(astring name, ivar var)
{
}
pointer core_app::core_view_handle()const
{
return m_hwnd;
}
graphics::icore_context_t core_app::core_context()const
{
return new graphics::device_context(const_cast<core_app*>(this));
}
graphics::size<float> core_app::core_view_size()const
{
if (IsWindow(m_hwnd)) {
RECT rc;
GetClientRect(m_hwnd, &rc);
return { float(rc.right - rc.left), float(rc.bottom - rc.top) };
}
return{ 0,0 };
}
graphics::size<float> core_app::core_view_scale_factor()const
{
return{ 1.0f,1.0f };
}
imessage_listener_t core_app::dispatcher()const
{
return const_cast<core_app*>(this);
}
error core_app::run(function<error(icore_app_t)> setup, app_args_t& args)
{
//m_frm = frm;
m_thread = core::async::thread::this_thread();
error err = setup(this);
wstring name = args.name->cstr();
wstring title = args.title->cstr();
if (err.code() != error_code::success)
return err;
setup = null;//releasing scope
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_SAVEBITS;
wcex.lpfnWndProc = &core_app::wndproc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = m_hint;
wcex.hIcon = NULL;
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = name.cstr();
wcex.hIconSm = NULL;
RegisterClassExW(&wcex);;
HWND hwnd = CreateWindowExW(0, name.cstr(), title.cstr(), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, m_hint, this);
if (!hwnd)
{
_com_error err(GetLastError());
castr_t msg(err.ErrorMessage(), -1);
return error(err.Error(), msg, error_code::system_error);
}
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
core::time::step_timer timer;
if (args.fps > 0)
{
timer.frames_per_second(args.fps);
timer.fixed_time_step(true);
}
// Main message loop:
MSG msg;
while (true)
{
core::async::async_action_status_t status = m_thread->status();
if (status & core::async::async_action_status::canceled)
PostQuitMessage(0);
if (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
/*if (msg.hwnd == NULL)
{
events::message m{ (events::core_msg)msg.message, msg.wParam, msg.lParam };
wndproc(m);
}*/
}
if (msg.message == WM_QUIT)
break;
else timer.tick([&]() {
m_controllers->update(timer.elapsed_time());
SendMessageW(m_hwnd, (UINT)core_msg::update, timer.elapsed_time(), timer.total_time());
});
}
return error_code::success;
}
void core_app::wndproc(events::message& msg)
{
switch (msg.msg())
{
case core_msg::created: {
//auto cs = LPCREATESTRUCT((LPARAM)msg.lparam());
on_created(msg);
}break;
case core_msg::destroyed: {
on_destroyed(msg);
} break;
case (core_msg)WM_ERASEBKGND:
case core_msg::draw: {
on_draw(msg);
} break;
case core_msg::update: {
on_update(msg);
} break;
case core_msg::display_change:
case core_msg::orientation:
case core_msg::size: {
on_display_event(msg);
} break;
case core_msg::system_reserved_event: {
on_task_command(msg);
}
case core_msg::got_focus:
case core_msg::lost_focus: {
on_activate(msg);
} break;
case core_msg::pointer_entered:
case core_msg::pointer_pressed:
case core_msg::pointer_moved:
case core_msg::pointer_released:
case core_msg::pointer_leaved: {
on_pointer_event(msg);
} break;
case core_msg::mouse_move:
case core_msg::lbutton_down:
case core_msg::rbutton_down:
case (core_msg)WM_XBUTTONDOWN:
case core_msg::lbutton_up:
case core_msg::rbutton_up:
case (core_msg)WM_XBUTTONUP: {
on_mouse_event(msg);
} break;
case core_msg::key_down:
case core_msg::put_char:
case core_msg::key_up: {
on_key_event(msg);
break;
}
default: {
def_wndproc(msg);
} break;
}
}
void core_app::def_wndproc(events::message& msg)
{
msg.result(DefWindowProcW(m_hwnd, (uint)(core_msg)msg.msg(), (WPARAM)msg.wparam(), (LPARAM)msg.lparam()));
}
dword core_app::on_created(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
icreated_event_args_t args = new created_event_args(m, this, null);
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
def_wndproc(m);
return m.result();
}
dword core_app::on_destroyed(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
imsg_event_args_t args = new msg_event_args(m);
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
m_event_listeners.clear();
def_wndproc(m);
PostQuitMessage(m.lparam());
return m.result();
}
dword core_app::on_draw(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
graphics::device_context_t dc = new graphics::paint_dc(this);
if (dc->get_HDC() == null)
dc = new graphics::device_context(this);
idraw_event_args_t args = new draw_event_args(m, this, dc, core_view_size());
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
m.result(0);
return m.result();
}
dword core_app::on_update(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
imsg_event_args_t args = new msg_event_args(m);
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
m.result(0);
return m.result();
}
dword core_app::on_activate(events::message& m)
{
int handled = 0;
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
activate_status_t status = m.msg() == core_msg::got_focus ? activate_status::activated : activate_status::deactivated;
iactivate_event_args_t args = new activate_event_args(m, status);
try {
handled = it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
if (!handled) def_wndproc(m);
else m.result(0);
return m.result();
}
dword core_app::on_display_event(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
dword value = (dword)m.lparam();
display_invalidate_reason_t reason
= m.msg() == core_msg::size ? display_invalidate_reason::size_changed
: m.msg() == core_msg::display_change ? display_invalidate_reason::display_invalidate
: m.msg() == core_msg::orientation ? display_invalidate_reason::orientation_changed
: display_invalidate_reason::none;
display::display_info info = {
system_info::current_screen_orientation(),
system_info::current_screen_orientation(),
graphics::size<float>((float)LOWORD(value), (float)HIWORD(value)),
core_view_scale_factor(),
96
};
m.result(-1);
idisplay_info_event_args_t args = new display_info_event_args(m, this, reason, info);
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
def_wndproc(m);
return m.result();
}
dword core_app::on_pointer_event(events::message& m)
{
int handled = 0;
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
WPARAM wprm = (WPARAM)m.wparam();
LPARAM lprm = (LPARAM)m.lparam();
short id;
bool is_pa;
bool is_sa;
input::pointer_hardware_type_t type;
input::key_modifiers_t modifiers = input::key_modifiers::none;
POINTER_INFO pi;
id = (short)GET_POINTERID_WPARAM(wprm);
GetPointerInfo((uint)id, &pi);
type = (input::pointer_hardware_type)(pi.pointerType - 2);
is_pa = IS_POINTER_FIRSTBUTTON_WPARAM(wprm);
is_sa = IS_POINTER_SECONDBUTTON_WPARAM(wprm);
//POINTER_MOD_SHIFT
modifiers += ((POINTER_MOD_CTRL & pi.dwKeyStates) == POINTER_MOD_CTRL) ? input::key_modifiers::control : input::key_modifiers::none;
modifiers += ((POINTER_MOD_SHIFT & pi.dwKeyStates) == POINTER_MOD_SHIFT) ? input::key_modifiers::shift : input::key_modifiers::none;
ipointer_event_args_t args = new pointer_event_args(m, {
graphics::point<float>((float)GET_X_LPARAM(lprm), (float)GET_Y_LPARAM(lprm)),
id,
is_pa,
is_sa,
type,
modifiers,
});
int count = 0;
try {
handled = it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
if (!handled) def_wndproc(m);
else m.result(0);
return m.result();
}
dword core_app::on_mouse_event(events::message& m)
{
int handled = 0;
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
WPARAM wprm = (WPARAM)m.wparam();
LPARAM lprm = m.lparam();
short id;
bool is_pa;
bool is_sa;
input::pointer_hardware_type_t type;
input::key_modifiers_t modifiers = input::key_modifiers::none;
id = 1U;
is_pa = (MK_LBUTTON & wprm) == MK_LBUTTON;
is_sa = (MK_RBUTTON & wprm) == MK_RBUTTON;
type = input::pointer_hardware_type::mouse;
modifiers += ((MK_CONTROL & wprm) == MK_CONTROL) ? input::key_modifiers::control : input::key_modifiers::none;
modifiers += ((MK_SHIFT & wprm) == MK_SHIFT) ? input::key_modifiers::shift : input::key_modifiers::none;
ipointer_event_args_t args = new pointer_event_args(m, {
graphics::point<float>((float)GET_X_LPARAM(lprm), (float)GET_Y_LPARAM(lprm)),
id,
is_pa,
is_sa,
type,
modifiers,
});
int count = 0;
try {
handled = it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
if (!handled) def_wndproc(m);
else m.result(0);
return m.result();
}
dword core_app::on_key_event(events::message& m)
{
auto it = m_event_listeners.find(m.msg());
if (it.is_valid()) {
uint modifiers = 0;
if (GetKeyState(VK_CONTROL) && 0x8000)
modifiers |= (uint)input::key_modifiers::control;
if (GetKeyState(VK_SHIFT) && 0x8000)
modifiers |= (uint)input::key_modifiers::shift;
if (GetKeyState(VK_MENU) && 0x8000)
modifiers |= (uint)input::key_modifiers::alt;
if (GetKeyState(VK_CAPITAL) && 0x0001)
modifiers |= (uint)input::key_modifiers::caps_lock;
if (GetKeyState(VK_NUMLOCK) && 0x0001)
modifiers |= (uint)input::key_modifiers::num_lock;
ikey_event_args_t args = new key_event_args(m, {
(input::virtual_key)m.wparam(), //property<const virtual_key> key;
(char32_t)m.wparam(), //property<const virtual_key> key;
(word)(uint)m.lparam(), //property<const word> flags;
m.msg() == core_msg::key_down ? input::key_state::pressed
: m.msg() == core_msg::put_char ? input::key_state::pressed
: input::key_state::released,
(input::key_modifiers)modifiers //property<const key_modifiers> modifiers;
});
m.result(-1);
try {
it->value->invoke(args.get());
}
catch (const exception & e) {
}
}
def_wndproc(m);
return m.result();
}
dword core_app::on_task_command(events::message& m)
{
auto task = reinterpret_cast<async_task*>(m.lparam());
task->execute();
task->release();
m.result(0);
return 0;
}
| 12,144 | 5,401 |
// Given a string, find the number of different non-empty substrings in it.
// Example
// For inputString = "abac", the output should be
// differentSubstrings(inputString) = 9.
string substring(std::string inputString, int start, int end){
std::string resultString;
for(int i=start;i<end;i++)
resultString+=inputString[i];
return resultString;
}
int differentSubstrings(std::string inputString) {
std::vector<std::string> substrings;
int result = 1;
for (int i = 0; i < inputString.size(); i++) {
for (int j = i + 1; j <= inputString.size(); j++) {
substrings.push_back(substring(inputString,i,j));
}
}
sort(substrings.begin(),substrings.end());
for (int i = 1; i < substrings.size(); i++) {
if (substrings[i] != substrings[i - 1]) {
result++;
}
}
return result;
}
| 876 | 279 |
#pragma once
#include <LuminoGraphics/Animation/Common.hpp>
#include <LuminoGraphics/Animation/AnimationClip.hpp>
#include <LuminoEngine/Base/detail/RefObjectCache.hpp>
namespace ln {
class AnimationClock;
namespace detail {
class AnimationManager : public RefObject {
public:
struct Settings {
AssetManager* assetManager = nullptr;
};
static AnimationManager* initialize(const Settings& settings);
static void terminate();
static inline AnimationManager* instance() { return s_instance; }
// void setSceneManager(SceneManager* sceneManager) { m_sceneManager = sceneManager; }
const Ref<AnimationClipImportSettings>& defaultAnimationClipImportSettings() const { return m_defaultAnimationClipImportSettings; }
void addClockToAffiliation(AnimationClock* clock, AnimationClockAffiliation affiliation);
Ref<GenericTask<Ref<AnimationClip>>> loadAnimationClip(const StringView& filePath);
// Ref<AnimationClipPromise> loadAnimationClipAsync(const StringView& filePath);
// Ref<AnimationClip> acquireAnimationClip(const AssetPath& assetPath);
// void loadAnimationClip(AnimationClip* clip, const AssetPath& assetPath);
void updateFrame(float elapsedSeconds);
private:
AnimationManager();
virtual ~AnimationManager();
Result init(const Settings& settings);
void dispose();
AssetManager* m_assetManager;
// SceneManager* m_sceneManager;
ObjectCache<String, AnimationClip> m_animationClipCache;
Ref<AnimationClipImportSettings> m_defaultAnimationClipImportSettings;
static Ref<AnimationManager> s_instance;
};
} // namespace detail
} // namespace ln
| 1,648 | 461 |
#include "DX_12Image.hpp"
#include "DX_12RenderDevice.hpp"
#include "Core/ConversionUtils.hpp"
#include <algorithm>
DX_12Image::DX_12Image( RenderDevice* device,
const Format format,
const ImageUsage usage,
const uint32_t x,
const uint32_t y,
const uint32_t z,
const uint32_t mips,
const uint32_t levels,
const uint32_t samples,
const std::string& name) :
ImageBase(device, format, usage, x, y, z, mips, levels, samples, name),
mIsOwned(true)
{
D3D12_RESOURCE_DIMENSION type;
if (x != 0 && y == 0 && z == 0) type = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE1D;
if (x != 0 && y != 0 && z == 1) type = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE2D;
if (x != 0 && y != 0 && z > 1) type = D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE3D;
D3D12_RESOURCE_DESC imageDesc{};
imageDesc.Width = x;
imageDesc.Height = y;
imageDesc.DepthOrArraySize = std::max(z, levels);
imageDesc.Dimension = type;
imageDesc.Layout = D3D12_TEXTURE_LAYOUT::D3D12_TEXTURE_LAYOUT_UNKNOWN;
imageDesc.Format = getDX12ImageFormat(format);
imageDesc.MipLevels = mips;
imageDesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
imageDesc.Flags = getDX12ImageUsage(usage);
DXGI_SAMPLE_DESC sampleDesc{};
sampleDesc.Count = samples;
sampleDesc.Quality = 0;
imageDesc.SampleDesc = sampleDesc;
DX_12RenderDevice* dev = static_cast<DX_12RenderDevice*>(getDevice());
const D3D12MA::ALLOCATION_DESC allocDesc = dev->getResourceAllocationDescription(usage);
dev->createResource(imageDesc, allocDesc, D3D12_RESOURCE_STATE_COMMON , &mImage, &mImageMemory);
}
DX_12Image::DX_12Image(RenderDevice* device,
ID3D12Resource* resource,
const Format format,
const ImageUsage usage,
const uint32_t x,
const uint32_t y,
const uint32_t z,
const uint32_t mips,
const uint32_t levels,
const uint32_t samples,
const std::string& name) :
ImageBase(device, format, usage, x, y, z, mips, levels, samples, name)
{
mImage = resource;
mImageMemory = nullptr;
mIsOwned = false;
}
DX_12Image::~DX_12Image()
{
if(mIsOwned)
getDevice()->destroyImage(*this);
}
void DX_12Image::swap(ImageBase& other)
{
ImageBase::swap(other);
DX_12Image& DXImage = static_cast<DX_12Image&>(other);
ID3D12Resource* tmpImage = mImage;
D3D12MA::Allocation* tmpMemory = DXImage.mImageMemory;
mImage = DXImage.mImage;
mImageMemory = DXImage.mImageMemory;
DXImage.mImage = tmpImage;
DXImage.mImageMemory = tmpMemory;
}
void DX_12Image::setContents( const void* data,
const uint32_t xsize,
const uint32_t ysize,
const uint32_t zsize,
const uint32_t level,
const uint32_t lod,
const int32_t offsetx,
const int32_t offsety,
const int32_t offsetz)
{
BELL_LOG("DX_12Image::SetContents not implemented")
}
void DX_12Image::clear(const float4&)
{
BELL_LOG("DX_12Image::clear not implemented")
}
void DX_12Image::generateMips()
{
BELL_LOG("DX_12Image::generateMips not implemented")
} | 3,536 | 1,290 |
// Author: Stancioiu Nicu Razvan
// Problem: http://uva.onlinejudge.org/external/118/11879.html
#include <iostream>
#include <string>
#define MOD 17
using namespace std;
bool Divide(string a)
{
int t=0;
for(int i=0;i<a.length();++i)
{
t*=10;
t+=a[i]-'0';
t%=MOD;
}
if(t==0)
return true;
else return false;
}
int main()
{
string s;
while(cin>>s && s!="0")
{
cout<<Divide(s)<<endl;
}
return 0;
} | 418 | 212 |
#include "unit_morph.h"
#include <hook_tools.h>
#include <SCBW/api.h>
#include <cassert>
namespace {
//-------- CMDRECV_UnitMorph --------//
const u32 Func_AddUnitToBuildQueue = 0x00467250;
bool addUnitToBuildQueue(const CUnit *unit, u16 unitId) {
static u32 result;
u32 unitId_ = unitId;
__asm {
PUSHAD
PUSH unitId_
MOV EDI, unit
CALL Func_AddUnitToBuildQueue
MOV result, EAX
POPAD
}
return result != 0;
}
void __stdcall unitMorphWrapper_CMDRECV_UnitMorph(u8 *commandData) {
const u16 morphUnitId = *((u16*)&commandData[1]);
*selectionIndexStart = 0;
while (CUnit *unit = getActivePlayerNextSelection()) {
if (hooks::unitCanMorphHook(unit, morphUnitId)
&& unit->mainOrderId != OrderId::Morph1
&& addUnitToBuildQueue(unit, morphUnitId))
{
unit->orderTo(OrderId::Morph1);
}
}
scbw::refreshConsole();
}
//-------- BTNSCOND_CanBuildUnit --------//
s32 __fastcall unitMorphWrapper_BTNSCOND_CanBuildUnit(u16 buildUnitId, s32 playerId, const CUnit *unit) {
if (*clientSelectionCount <= 1
|| hooks::getUnitMorphEggTypeHook(unit->id) != UnitId::None)
return unit->canMakeUnit(buildUnitId, playerId);
return 0;
}
//-------- Orders_Morph1 --------//
const u32 Hook_Orders_Morph1_Check_Success = 0x0045DFCA;
void __declspec(naked) unitMorphWrapper_Orders_Morph1_Check() {
static CUnit *unit;
__asm {
PUSHAD
MOV EBP, ESP
MOV unit, ESI
}
if (hooks::getUnitMorphEggTypeHook(unit->id) != UnitId::None) {
__asm {
POPAD
JMP Hook_Orders_Morph1_Check_Success
}
}
else {
__asm {
POPAD
POP EDI
POP ESI
MOV ESP, EBP
POP EBP
RETN
}
}
}
const u32 Hook_Orders_Morph1_EggType_Return = 0x0045E048;
void __declspec(naked) unitMorphWrapper_Orders_Morph1_EggType() {
static CUnit *unit;
static u32 morphEggType;
__asm {
PUSHAD
MOV EBP, ESP
MOV unit, ESI
}
unit->status &= ~(UnitStatus::Completed);
morphEggType = hooks::getUnitMorphEggTypeHook(unit->id);
assert(hooks::isEggUnitHook(morphEggType));
__asm {
POPAD
PUSH morphEggType
JMP Hook_Orders_Morph1_EggType_Return
}
}
//-------- hasSuppliesForUnit --------//
Bool32 __stdcall hasSuppliesForUnitWrapper(u8 playerId, u16 unitId, Bool32 canShowErrorMessage) {
if (hooks::hasSuppliesForUnitHook(playerId, unitId, canShowErrorMessage != 0))
return 1;
else
return 0;
}
//-------- cancelBuild --------//
typedef void(__stdcall *CancelZergBuildingFunc)(CUnit*);
CancelZergBuildingFunc cancelZergBuilding = (CancelZergBuildingFunc)0x0045DA40;
const u32 Func_ChangeUnitType = 0x0049FED0;
void changeUnitType(CUnit *unit, u16 newUnitId) {
u32 newUnitId_ = newUnitId;
__asm {
PUSHAD
PUSH newUnitId_
MOV EAX, unit
CALL Func_ChangeUnitType
POPAD
}
}
const u32 Func_ReplaceSpriteImages = 0x00499BB0;
void replaceSpriteImages(CSprite *sprite, u16 imageId, u8 imageDirection) {
u32 imageId_ = imageId, imageDirection_ = imageDirection;
__asm {
PUSHAD
PUSH imageDirection_
PUSH imageId_
MOV EAX, sprite
CALL Func_ReplaceSpriteImages
POPAD
}
}
//-------- cancelUnit --------//
void __fastcall cancelUnitWrapper(CUnit *unit) {
//Default StarCraft behavior
if (unit->isDead())
return;
if (unit->status & UnitStatus::Completed)
return;
if (unit->id == UnitId::nydus_canal && unit->building.nydusExit)
return;
//Don't bother if unit is not morphed yet
if (unit->id == UnitId::mutalisk || unit->id == UnitId::hydralisk)
return;
//Don't bother if unit has finished morphing
if (unit->id == UnitId::guardian
|| unit->id == UnitId::devourer
|| unit->id == UnitId::lurker)
return;
if (unit->status & UnitStatus::GroundedBuilding) {
if (unit->getRace() == RaceId::Zerg) {
cancelZergBuilding(unit);
return;
}
resources->minerals[unit->playerId] += units_dat::MineralCost[unit->id] * 3 / 4;
resources->gas[unit->playerId] += units_dat::GasCost[unit->id] * 3 / 4;
}
else {
u16 refundUnitId;
if (hooks::isEggUnitHook(unit->id))
refundUnitId = unit->buildQueue[unit->buildQueueSlot % 5];
else
refundUnitId = unit->id;
resources->minerals[unit->playerId] += units_dat::MineralCost[refundUnitId];
resources->gas[unit->playerId] += units_dat::GasCost[refundUnitId];
}
u16 cancelChangeUnitId = hooks::getCancelMorphRevertTypeHook(unit);
if (cancelChangeUnitId == UnitId::None) {
if (unit->id == UnitId::nuclear_missile) {
CUnit *silo = unit->connectedUnit;
if (silo) {
silo->building.silo.nuke = NULL;
silo->mainOrderState = 0;
}
scbw::refreshConsole();
}
unit->remove();
}
else {
changeUnitType(unit, cancelChangeUnitId);
unit->remainingBuildTime = 0;
unit->buildQueue[unit->buildQueueSlot] = UnitId::None;
replaceSpriteImages(unit->sprite,
sprites_dat::ImageId[flingy_dat::SpriteID[units_dat::Graphic[unit->displayedUnitId]]], 0);
unit->orderSignal &= ~0x4;
unit->playIscriptAnim(IscriptAnimation::SpecialState2);
unit->orderTo(OrderId::ZergBirth);
}
}
//-------- getRemainingBuildTimePct --------//
s32 getRemainingBuildTimePctHook(const CUnit *unit) {
u16 unitId = unit->id;
if (hooks::isEggUnitHook(unitId) || unit->isRemorphingBuilding())
unitId = unit->buildQueue[unit->buildQueueSlot];
return 100 * (units_dat::TimeCost[unitId] - unit->remainingBuildTime) / units_dat::TimeCost[unitId];
}
//Inject @ 0x004669E0
void __declspec(naked) getRemainingBuildTimePctWrapper() {
static CUnit *unit;
static s32 percentage;
__asm {
PUSHAD
MOV unit, ESI
MOV EBP, ESP
}
percentage = getRemainingBuildTimePctHook(unit);
__asm {
POPAD
MOV EAX, percentage
RETN
}
}
//-------- orders_zergBirth --------//
//Inject @ 0x0045DE00
const u32 Hook_GetUnitVerticalOffsetOnBirth_Return = 0x0045DE2C;
void __declspec(naked) getUnitVerticalOffsetOnBirthWrapper() {
static CUnit *unit;
static s16 yOffset;
__asm {
PUSHAD
MOV unit, EDI
}
yOffset = hooks::getUnitVerticalOffsetOnBirth(unit);
__asm {
POPAD
MOVSX EAX, yOffset
JMP Hook_GetUnitVerticalOffsetOnBirth_Return
}
}
//Inject @ 0x0045DE57
const u32 Hook_IsRallyableEggUnit_Yes = 0x0045DE6C;
const u32 Hook_IsRallyableEggUnit_No = 0x0045DE8B;
void __declspec(naked) isRallyableEggUnitWrapper() {
static CUnit *unit;
__asm {
POP ESI
POP EBX
PUSHAD
MOV unit, EDI
}
if (hooks::isRallyableEggUnitHook(unit->displayedUnitId)) {
__asm {
POPAD
JMP Hook_IsRallyableEggUnit_Yes
}
}
else {
__asm {
POPAD
JMP Hook_IsRallyableEggUnit_No
}
}
}
} //unnamed namespace
namespace hooks {
void injectUnitMorphHooks() {
callPatch(unitMorphWrapper_CMDRECV_UnitMorph, 0x00486B50);
jmpPatch(unitMorphWrapper_BTNSCOND_CanBuildUnit, 0x00428E60);
jmpPatch(unitMorphWrapper_Orders_Morph1_Check, 0x0045DFB0);
jmpPatch(unitMorphWrapper_Orders_Morph1_EggType, 0x0045E019);
jmpPatch(hasSuppliesForUnitWrapper, 0x0042CF70);
jmpPatch(cancelUnitWrapper, 0x00468280);
jmpPatch(getRemainingBuildTimePctWrapper, 0x004669E0);
jmpPatch(getUnitVerticalOffsetOnBirthWrapper, 0x0045DE00);
jmpPatch(isRallyableEggUnitWrapper, 0x0045DE57);
}
} //hooks
| 7,594 | 3,543 |
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:18 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Security::Cryptography
namespace System::Security::Cryptography {
// Forward declaring type: OidGroup
struct OidGroup;
}
// Completed forward declares
// Type namespace: System.Security.Cryptography.X509Certificates
namespace System::Security::Cryptography::X509Certificates {
// Autogenerated type: System.Security.Cryptography.X509Certificates.X509Utils
class X509Utils : public ::Il2CppObject {
public:
// static System.String FindOidInfo(System.UInt32 keyType, System.String keyValue, System.Security.Cryptography.OidGroup oidGroup)
// Offset: 0x1206A30
static ::Il2CppString* FindOidInfo(uint keyType, ::Il2CppString* keyValue, System::Security::Cryptography::OidGroup oidGroup);
// static System.String FindOidInfoWithFallback(System.UInt32 key, System.String value, System.Security.Cryptography.OidGroup group)
// Offset: 0x12036A0
static ::Il2CppString* FindOidInfoWithFallback(uint key, ::Il2CppString* value, System::Security::Cryptography::OidGroup group);
}; // System.Security.Cryptography.X509Certificates.X509Utils
}
DEFINE_IL2CPP_ARG_TYPE(System::Security::Cryptography::X509Certificates::X509Utils*, "System.Security.Cryptography.X509Certificates", "X509Utils");
#pragma pack(pop)
| 1,661 | 563 |
#include <AMReX_EB_F.H>
#include <AMReX_MultiFab.H>
#include <AMReX_EB_utils.H>
#include <AMReX_Geometry.H>
#include <AMReX_MultiCutFab.H>
#include <AMReX_EBFabFactory.H>
namespace amrex {
void FillEBNormals(MultiFab & normals, const EBFArrayBoxFactory & eb_factory,
const Geometry & geom) {
BoxArray ba = normals.boxArray();
DistributionMapping dm = normals.DistributionMap();
int n_grow = normals.nGrow();
// Dummy array for MFIter
MultiFab dummy(ba, dm, 1, n_grow, MFInfo(), eb_factory);
// Area fraction data
std::array<const MultiCutFab*, AMREX_SPACEDIM> areafrac = eb_factory.getAreaFrac();
const auto & flags = eb_factory.getMultiEBCellFlagFab();
#ifdef _OPENMP
#pragma omp parallel
#endif
for(MFIter mfi(dummy, true); mfi.isValid(); ++mfi) {
Box tile_box = mfi.growntilebox();
const int * lo = tile_box.loVect();
const int * hi = tile_box.hiVect();
const auto & flag = flags[mfi];
if (flag.getType(tile_box) == FabType::singlevalued) {
// Target for compute_normals(...)
auto & norm_tile = normals[mfi];
// Area fractions in x, y, and z directions
const auto & af_x_tile = (* areafrac[0])[mfi];
const auto & af_y_tile = (* areafrac[1])[mfi];
const auto & af_z_tile = (* areafrac[2])[mfi];
amrex_eb_compute_normals(lo, hi,
BL_TO_FORTRAN_3D(flag),
BL_TO_FORTRAN_3D(norm_tile),
BL_TO_FORTRAN_3D(af_x_tile),
BL_TO_FORTRAN_3D(af_y_tile),
BL_TO_FORTRAN_3D(af_z_tile) );
}
}
normals.FillBoundary(geom.periodicity());
}
}
| 1,943 | 658 |
#ifndef TM_KIT_BASIC_CALCULATIONS_ON_INIT_HPP_
#define TM_KIT_BASIC_CALCULATIONS_ON_INIT_HPP_
#include <tm_kit/infra/RealTimeApp.hpp>
#include <tm_kit/infra/SinglePassIterationApp.hpp>
#include <tm_kit/infra/TopDownSinglePassIterationApp.hpp>
#include <tm_kit/infra/Environments.hpp>
#include <tm_kit/infra/TraceNodesComponent.hpp>
#include <type_traits>
namespace dev { namespace cd606 { namespace tm { namespace basic {
//Importers for calculating value on init
//Please notice that Func takes only one argument (the logger)
//This is deliberate choice. The reason is that if Func needs anything
//inside Env, it should be able to capture that by itself outside this
//logic. If we force Env to maintain something for use of Func, which is
//only executed at startup, there will be trickly resource-release timing
//questions, and by not doing that, we allow Func to manage resources by
//itself.
template <class App, class Func>
class ImporterOfValueCalculatedOnInit {};
template <class Env, class Func>
class ImporterOfValueCalculatedOnInit<infra::template RealTimeApp<Env>, Func>
: public infra::template RealTimeApp<Env>::template AbstractImporter<
decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
))
>
{
private:
Func f_;
public:
using OutputT = decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
));
ImporterOfValueCalculatedOnInit(Func &&f) : f_(std::move(f)) {}
virtual void start(Env *env) override final {
TM_INFRA_IMPORTER_TRACER(env);
this->publish(env, f_(
[env](infra::LogLevel level, std::string const &s) {
env->log(level, s);
}
));
}
};
template <class Env, class Func>
class ImporterOfValueCalculatedOnInit<infra::template SinglePassIterationApp<Env>, Func>
: public infra::template SinglePassIterationApp<Env>::template AbstractImporter<
decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
))
>
{
public:
using OutputT = decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
));
private:
Func f_;
typename infra::template SinglePassIterationApp<Env>::template Data<OutputT> data_;
public:
ImporterOfValueCalculatedOnInit(Func &&f) : f_(std::move(f)), data_(std::nullopt) {}
virtual void start(Env *env) override final {
TM_INFRA_IMPORTER_TRACER(env);
data_ = infra::template SinglePassIterationApp<Env>::template pureInnerData<OutputT>(
env
, f_(
[env](infra::LogLevel level, std::string const &s) {
env->log(level, s);
}
)
, true
);
}
virtual typename infra::template SinglePassIterationApp<Env>::template Data<OutputT> generate() override final {
return data_;
}
};
template <class Env, class Func>
class ImporterOfValueCalculatedOnInit<infra::template TopDownSinglePassIterationApp<Env>, Func>
: public infra::template TopDownSinglePassIterationApp<Env>::template AbstractImporter<
decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
))
>
{
public:
using OutputT = decltype((* ((Func *) nullptr))(
std::function<void(infra::LogLevel, std::string const &)>()
));
private:
Func f_;
typename infra::template TopDownSinglePassIterationApp<Env>::template Data<OutputT> data_;
public:
ImporterOfValueCalculatedOnInit(Func &&f) : f_(std::move(f)), data_(std::nullopt) {}
virtual void start(Env *env) override final {
TM_INFRA_IMPORTER_TRACER(env);
data_ = infra::template TopDownSinglePassIterationApp<Env>::template pureInnerData<OutputT>(
env
, f_(
[env](infra::LogLevel level, std::string const &s) {
env->log(level, s);
}
)
, true
);
}
virtual std::tuple<bool, typename infra::template TopDownSinglePassIterationApp<Env>::template Data<OutputT>> generate() override final {
return {false, std::move(data_)};
}
};
template <class App, class Func>
auto importerOfValueCalculatedOnInit(Func &&f)
-> std::shared_ptr<typename App::template Importer<
typename ImporterOfValueCalculatedOnInit<App,Func>::OutputT
>>
{
return App::importer(
new ImporterOfValueCalculatedOnInit<App,Func>(std::move(f))
);
}
//on order facilities for holding pre-calculated value and returning it on query
template <class App, class Req, class PreCalculatedResult>
class LocalOnOrderFacilityReturningPreCalculatedValue :
public App::template AbstractIntegratedLocalOnOrderFacility<Req, PreCalculatedResult, PreCalculatedResult>
{
private:
std::conditional_t<App::PossiblyMultiThreaded, std::mutex, bool> mutex_;
PreCalculatedResult preCalculatedRes_;
public:
LocalOnOrderFacilityReturningPreCalculatedValue()
: mutex_(), preCalculatedRes_()
{}
virtual void start(typename App::EnvironmentType *) {}
virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(req.environment, ":handle");
std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_);
this->publish(
req.environment
, typename App::template Key<PreCalculatedResult> {
req.timedData.value.id(), preCalculatedRes_
}
, true
);
}
virtual void handle(typename App::template InnerData<PreCalculatedResult> &&data) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(data.environment, ":input");
std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_);
preCalculatedRes_ = std::move(data.timedData.value);
}
};
template <class App, class Req, class PreCalculatedResult>
auto localOnOrderFacilityReturningPreCalculatedValue()
-> std::shared_ptr<typename App::template LocalOnOrderFacility<Req, PreCalculatedResult, PreCalculatedResult>>
{
return App::localOnOrderFacility(new LocalOnOrderFacilityReturningPreCalculatedValue<App,Req,PreCalculatedResult>());
}
template <class App, class Req, class PreCalculatedResult, class Func>
class LocalOnOrderFacilityUsingPreCalculatedValue :
public App::template AbstractIntegratedLocalOnOrderFacility<
Req
, decltype(
(* ((Func *) nullptr))(
* ((PreCalculatedResult const *) nullptr)
, * ((Req const *) nullptr)
)
)
, PreCalculatedResult
>
{
private:
Func f_;
std::conditional_t<App::PossiblyMultiThreaded, std::mutex, bool> mutex_;
PreCalculatedResult preCalculatedRes_;
public:
using OutputT = decltype(
(* ((Func *) nullptr))(
* ((PreCalculatedResult const *) nullptr)
, * ((Req const *) nullptr)
)
);
LocalOnOrderFacilityUsingPreCalculatedValue(Func &&f) :
f_(std::move(f)), mutex_(), preCalculatedRes_()
{}
virtual void start(typename App::EnvironmentType *) override final {}
virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(req.environment, ":handle");
std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_);
this->publish(
req.environment
, typename App::template Key<OutputT> {
req.timedData.value.id(), f_(preCalculatedRes_, req.timedData.value.key())
}
, true
);
}
virtual void handle(typename App::template InnerData<PreCalculatedResult> &&data) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(data.environment, ":input");
std::conditional_t<App::PossiblyMultiThreaded, std::lock_guard<std::mutex>, bool> _(mutex_);
preCalculatedRes_ = std::move(data.timedData.value);
}
};
template <class App, class Req, class PreCalculatedResult, class Func>
auto localOnOrderFacilityUsingPreCalculatedValue(Func &&f)
-> std::shared_ptr<typename App::template LocalOnOrderFacility<Req, typename LocalOnOrderFacilityUsingPreCalculatedValue<App,Req,PreCalculatedResult,Func>::OutputT, PreCalculatedResult>>
{
return App::localOnOrderFacility(new LocalOnOrderFacilityUsingPreCalculatedValue<App,Req,PreCalculatedResult,Func>(std::move(f)));
}
//combination of the two above, on order facilities for
//holding pre-calculated value which is calculated internally
//at init, and returning it on query
template <class App, class Req, class CalcFunc>
class OnOrderFacilityReturningInternallyPreCalculatedValue :
public virtual App::IExternalComponent
, public App::template AbstractOnOrderFacility<
Req
, decltype((std::declval<CalcFunc>())(
std::function<void(infra::LogLevel, std::string const &)>()
))
>
{
public:
using PreCalculatedResult = decltype((std::declval<CalcFunc>())(
std::function<void(infra::LogLevel, std::string const &)>()
));
private:
CalcFunc f_;
PreCalculatedResult preCalculatedRes_;
public:
OnOrderFacilityReturningInternallyPreCalculatedValue(CalcFunc &&f)
: f_(f), preCalculatedRes_()
{}
virtual void start(typename App::EnvironmentType *env) override final {
preCalculatedRes_ = f_(
[env](infra::LogLevel level, std::string const &s) {
env->log(level, s);
}
);
}
virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final {
this->publish(
req.environment
, typename App::template Key<PreCalculatedResult> {
req.timedData.value.id(), preCalculatedRes_
}
, true
);
}
};
template <class App, class Req, class CalcFunc>
auto onOrderFacilityReturningInternallyPreCalculatedValue(CalcFunc &&f)
-> std::shared_ptr<typename App::template OnOrderFacility<Req, typename OnOrderFacilityReturningInternallyPreCalculatedValue<App,Req,CalcFunc>::PreCalculatedResult>>
{
return App::fromAbstractOnOrderFacility(new OnOrderFacilityReturningInternallyPreCalculatedValue<App,Req,CalcFunc>(std::move(f)));
}
template <class App, class Req, class CalcFunc, class FetchFunc>
class OnOrderFacilityUsingInternallyPreCalculatedValue :
public virtual App::IExternalComponent
, public App::template AbstractOnOrderFacility<
Req
, decltype(
(std::declval<FetchFunc>())(
* ((typename OnOrderFacilityReturningInternallyPreCalculatedValue<App,Req,CalcFunc>::PreCalculatedResult const *) nullptr)
, * ((Req const *) nullptr)
)
)
>
{
public:
using PreCalculatedResult = decltype((std::declval<CalcFunc>())(
std::function<void(infra::LogLevel, std::string const &)>()
));
using OutputT = decltype(
(std::declval<FetchFunc>())(
* ((PreCalculatedResult const *) nullptr)
, * ((Req const *) nullptr)
)
);
private:
CalcFunc calcFunc_;
FetchFunc fetchFunc_;
PreCalculatedResult preCalculatedRes_;
public:
OnOrderFacilityUsingInternallyPreCalculatedValue(CalcFunc &&calcFunc, FetchFunc &&fetchFunc) :
calcFunc_(std::move(calcFunc)), fetchFunc_(std::move(fetchFunc)), preCalculatedRes_()
{}
virtual void start(typename App::EnvironmentType *env) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(env, ":start");
preCalculatedRes_ = calcFunc_(
[env](infra::LogLevel level, std::string const &s) {
env->log(level, s);
}
);
}
virtual void handle(typename App::template InnerData<typename App::template Key<Req>> &&req) override final {
TM_INFRA_FACILITY_TRACER_WITH_SUFFIX(req.environment, ":handle");
this->publish(
req.environment
, typename App::template Key<OutputT> {
req.timedData.value.id(), fetchFunc_(preCalculatedRes_, req.timedData.value.key())
}
, true
);
}
};
template <class App, class Req, class CalcFunc, class FetchFunc>
auto onOrderFacilityUsingInternallyPreCalculatedValue(CalcFunc &&calcFunc, FetchFunc &&fetchFunc)
-> std::shared_ptr<typename App::template OnOrderFacility<Req, typename OnOrderFacilityUsingInternallyPreCalculatedValue<App,Req,CalcFunc,FetchFunc>::OutputT>>
{
return App::fromAbstractOnOrderFacility(new OnOrderFacilityUsingInternallyPreCalculatedValue<App,Req,CalcFunc,FetchFunc>(std::move(calcFunc), std::move(fetchFunc)));
}
} } } }
#endif | 14,326 | 4,068 |
// URLWriter.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <cstdlib>
#include "URLWriter.h"
static struct
{
const char* url;
const char* post;
}g_data[] = {
{"http://v.juhe.cn/postcode/query?postcode=215001&key=%E7%94%B3%E8%AF%B7%E7%9A%84KEY",NULL},
{"http://v.juhe.cn/postcode/query","postcode=215001&key=%E7%94%B3%E8%AF%B7%E7%9A%84KEY"},
};
void OnURLRequestCallback(YTSvrLib::CURLRequest* pReq)
{
cout << "request index = " << pReq->m_ayParam[0] << endl;
cout << "request code = " << pReq->m_nReturnCode << endl;
cout << "return field = " << pReq->m_strReturn << endl;
}
void OnURLRequestSync()
{
std::string outdata;
int nResponseCode = YTSvrLib::CGlobalCURLRequest::GetInstance()->SendHTTPGETMessage(g_data[0].url, &outdata);
cout << "sync get request code = " << nResponseCode << endl;
cout << "sync get request return field = " << outdata << endl;
outdata.clear();
outdata.shrink_to_fit();
nResponseCode = YTSvrLib::CGlobalCURLRequest::GetInstance()->SendHTTPPOSTMessage(g_data[1].url, g_data[1].post, &outdata);
cout << "sync post request code = " << nResponseCode << endl;
cout << "sync post request return field = " << outdata << endl;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
OnURLRequestSync();
CURLWriter::GetInstance()->StartURLWriter(5);
int index = 0;
while (true)
{
index++;
for (int i = 0; i < _countof(g_data);++i)
{
CURLWriter::GetInstance()->AddURLRequest(g_data[i].url, g_data[i].post, (YTSvrLib::URLPARAM)index, 0, 0, 0, OnURLRequestCallback);
}
CURLWriter::GetInstance()->WaitForAllRequestDone();
}
return 0;
} | 1,608 | 684 |
/******************************************************************************
Copyright (c) 2017, Farbod Farshidian. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include <iostream>
#include <gtest/gtest.h>
#include <ocs2_core/initialization/OperatingPoints.h>
class InitializationTest : public testing::Test {
protected:
static constexpr size_t stateDim_ = 3;
static constexpr size_t inputDim_ = 2;
using OperatingPoints = ocs2::OperatingPoints;
using scalar_t = ocs2::scalar_t;
using scalar_array_t = ocs2::scalar_array_t;
using vector_t = ocs2::vector_t;
using vector_array_t = ocs2::vector_array_t;
InitializationTest() = default;
vector_t input, nextState;
};
TEST_F(InitializationTest, SingleOperatingPoint) {
const scalar_t t0 = 0.0;
const scalar_t tf = 1.0;
const vector_array_t xTraj = {vector_t::Random(stateDim_)};
const vector_array_t uTraj = {vector_t::Random(inputDim_)};
OperatingPoints operatingPoints({t0}, xTraj, uTraj);
operatingPoints.compute(t0, xTraj[0], tf, input, nextState);
ASSERT_TRUE(nextState.isApprox(xTraj[0]));
ASSERT_TRUE(input.isApprox(uTraj[0]));
}
TEST_F(InitializationTest, ZeroTimeInterval) {
const scalar_t t0 = 0.0;
const vector_array_t xTraj{vector_t::Random(stateDim_)};
const vector_array_t uTraj = {vector_t::Random(inputDim_)};
OperatingPoints operatingPoints({t0}, xTraj, uTraj);
operatingPoints.compute(t0, xTraj[0], t0, input, nextState);
ASSERT_TRUE(nextState.isApprox(xTraj[0]));
ASSERT_TRUE(input.isApprox(uTraj[0]));
}
TEST_F(InitializationTest, Trajectory) {
constexpr size_t N = 20;
scalar_array_t tTraj(N);
scalar_t n = 0;
std::generate(tTraj.begin(), tTraj.end(), [&n]() mutable { return n++; });
vector_array_t xTraj(N);
std::generate(xTraj.begin(), xTraj.end(), [&]() { return vector_t::Random(stateDim_); });
vector_array_t uTraj(N);
std::generate(uTraj.begin(), uTraj.end(), [&]() { return vector_t::Random(inputDim_); });
OperatingPoints operatingPoints(tTraj, xTraj, uTraj);
for (size_t i = 0; i < N - 1; i++) {
operatingPoints.compute(tTraj[i], xTraj[i], tTraj[i + 1], input, nextState);
ASSERT_TRUE(input.isApprox(uTraj[i]));
ASSERT_TRUE(nextState.isApprox(xTraj[i + 1]));
}
}
| 3,731 | 1,371 |
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>> &A,
vector<vector<int>> &B) {
int i = 0;
int j = 0;
int n1 = A.size();
int n2 = B.size();
vector<vector<int>> result;
while (i < n1 && j < n2) {
int r = min(A[i][1], B[j][1]);
int l = max(A[i][0], B[j][0]);
if (l <= r)
result.push_back({l, r});
if (A[i][1] < B[j][1])
i++;
else
j++;
}
return result;
}
};
| 525 | 204 |
#include "udpfwdclient.h"
#include <QNetworkDatagram>
#include <announcepeermessage.h>
#include <tunnelinmessage.h>
using namespace UdpFwdProto;
UdpFwdClient::UdpFwdClient(QObject *parent) :
UdpFwdClient{10000, parent}
{}
UdpFwdClient::UdpFwdClient(int replyCacheSize, QObject *parent) :
QObject{parent},
_socket{new QUdpSocket{this}},
_replyCache{replyCacheSize}
{
connect(_socket, qOverload<QAbstractSocket::SocketError>(&QUdpSocket::error),
this, &UdpFwdClient::socketError);
connect(_socket, &QUdpSocket::readyRead,
this, &UdpFwdClient::readyRead);
}
bool UdpFwdClient::setup(PrivateKey key, QHostAddress fwdSvcAddress, quint16 port)
{
_key = std::move(key);
_peerHost = std::move(fwdSvcAddress);
_peerPort = port;
if (_socket->isOpen())
_socket->close();
if (_socket->bind(QHostAddress::Any, 0, QAbstractSocket::DontShareAddress))
return true;
else {
_lastError = _socket->errorString();
emit error();
return false;
}
}
const PrivateKey &UdpFwdClient::key() const
{
return _key;
}
QString UdpFwdClient::errorString() const
{
return _lastError;
}
void UdpFwdClient::send(const PublicKey &peer, const QByteArray &data, quint16 replyCount)
{
sendImpl(peer, data, replyCount, false);
}
bool UdpFwdClient::reply(const QByteArray &peer, const QByteArray &data, quint16 replyCount, bool lastReply)
{
auto info = _replyCache.object(peer);
if (info) {
sendImpl(info->key, data, replyCount, lastReply);
if (lastReply || --info->limit == 0)
_replyCache.remove(peer);
return true;
} else
return false;
}
CryptoPP::RandomNumberGenerator &UdpFwdClient::rng()
{
return _rng;
}
void UdpFwdClient::socketError()
{
_lastError = _socket->errorString();
emit error();
}
void UdpFwdClient::readyRead()
{
while (_socket->hasPendingDatagrams()) {
const auto datagram = _socket->receiveDatagram();
try {
MsgHandler handler{this, datagram.senderAddress(), static_cast<quint16>(datagram.senderPort())};
std::visit(handler, Message::deserialize<TunnelOutMessage, ErrorMessage>(datagram.data()));
} catch (std::bad_variant_access &) {
qWarning() << "UdpFwdClient: Ignoring invalid message from"
<< datagram.senderAddress() << "on port"
<< datagram.senderPort();
}
}
}
void UdpFwdClient::sendImpl(const UdpFwdProto::PublicKey &peer, const QByteArray &data, quint16 replyCount, bool lastReply)
{
sendImpl(TunnelInMessage::createEncrypted(_rng, peer, data,
replyCount != 0 ?
PrivateReplyInfo{_key, replyCount} :
PrivateReplyInfo{},
lastReply));
}
void UdpFwdClient::MsgHandler::operator()(TunnelOutMessage &&message)
{
auto data = message.decrypt(self->_rng, self->_key);
if (message.replyInfo) {
if (message.replyInfo.key.Validate(self->_rng, 3)) {
const auto fp = fingerPrint(message.replyInfo.key);
self->_replyCache.insert(fp, new ReplyInfo{std::move(message.replyInfo)});
emit self->messageReceived(data, fp);
} else {
self->_lastError = tr("Received message with invalid reply key - message has been dropped!");
emit self->error();
}
} else
emit self->messageReceived(data);
}
void UdpFwdClient::MsgHandler::operator()(ErrorMessage &&message)
{
switch (message.error) {
case ErrorMessage::Error::InvalidPeer:
self->_lastError = tr("Unabled to deliver message - unknown peer!");
break;
case ErrorMessage::Error::InvalidSignature:
self->_lastError = tr("Message was rejected by the forward server - invalid signature!");
break;
case ErrorMessage::Error::InvalidKey:
self->_lastError = tr("Message was rejected by the forward server - invalid public key!");
break;
case ErrorMessage::Error::Unknown:
self->_lastError = self->_socket->errorString(); // maybe info is here
break;
}
emit self->error();
}
| 3,781 | 1,410 |
#include "production.h"
ostream& operator<<(ostream& output, const Production& production_in)
{
output << production_in.set_symbol_;
return output;
}
Production::Production(const string& string_in):
set_symbol_(string_in),
num_no_terminal_(0),
num_terminal_(0),
epsilon_symbol_(0)
{
Update();
}
Production::Production(const char* string_in):
set_symbol_(string_in),
num_no_terminal_(0),
num_terminal_(0),
epsilon_symbol_(0)
{
Update();
}
Production::~Production(){}
string Production::get_set_symbol() const
{
return set_symbol_;
}
int Production::get_num_terminal() const
{
return num_terminal_;
}
set<char> Production::get_set_no_terminal() const
{
set<char> set_no_terminal;
for(int i=0;i<set_symbol_.size();i++)
if(isupper(set_symbol_[i]))
set_no_terminal.insert(set_symbol_[i]);
return set_no_terminal;
}
int Production::get_num_no_terminal() const
{
return num_no_terminal_;
}
set<char> Production::get_set_terminal() const
{
set<char> set_terminal;
for(int i=0;i<set_symbol_.size();i++)
if(!isupper(set_symbol_[i]) && set_symbol_[i]!=' ')
set_terminal.insert(set_symbol_[i]);
return set_terminal;
}
bool Production::has_only_terminal_symbols() const
{
return (num_terminal_>0 && num_no_terminal_==0);
}
bool Production::has_epsilon_symbol() const
{
return epsilon_symbol_;
}
void Production::set_set_symbol_(const string& string_in)
{
set_symbol_=string_in;
Update();
}
void Production::Update()
{
for(int i=0; i<set_symbol_.size();i++){
if(isupper(set_symbol_[i]))
++num_no_terminal_;
else if (set_symbol_[i]=='~')
epsilon_symbol_=1;
else
++num_terminal_;
}
}
Production& Production::operator=(const Production& production_in)
{
this->set_symbol_= production_in.set_symbol_;
this->num_terminal_= production_in.num_terminal_;
this->num_no_terminal_= production_in.num_no_terminal_;
this->epsilon_symbol_= production_in.epsilon_symbol_;
return *this;
}
int Production::operator==(const Production& production_in) const
{
if( this->set_symbol_ == production_in.set_symbol_) return 0;
return 1;
}
int Production::operator<(const Production& production_in) const
{
if( this->set_symbol_.length() == production_in.set_symbol_.length()){
if (this->set_symbol_ < production_in.set_symbol_)
return 1;
}
else if( this->set_symbol_.length() > production_in.set_symbol_.length()) return 1;
return 0;
} | 2,603 | 913 |
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main(int argc, const char * argv[]) {
cout << factorial(5);
return 0;
}
// Outputs 120
| 241 | 102 |
/*
* stringdatum.cc
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* NEST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "stringdatum.h"
// C++ includes:
#include <algorithm>
#include <cctype>
// Includes from sli:
#include "tokenutils.h"
// initialization of static members requires template<>
// see Stroustrup C.13.1 --- HEP 2001-08-09
template <>
sli::pool AggregateDatum< std::string, &SLIInterpreter::Stringtype >::memory(
sizeof( AggregateDatum< std::string, &SLIInterpreter::Stringtype > ),
100,
1 );
template <>
void
AggregateDatum< std::string, &SLIInterpreter::Stringtype >::pprint(
std::ostream& out ) const
{
out << '(';
print( out );
out << ')';
}
// explicit template instantiation needed
// because otherwise methods defined in
// numericdatum_impl.h will not be instantiated
// Moritz, 2007-04-16
template class AggregateDatum< std::string, &SLIInterpreter::Stringtype >;
const ToUppercase_sFunction touppercase_sfunction;
const ToLowercase_sFunction tolowercase_sfunction;
/* BeginDocumentation
Name: ToUppercase - Convert a string to upper case.
Synopsis:
(string) ToUppercase -> (string)
Description:
ToUppercase converts a string to upper case. If no upper case
representation of a letter exists, the letter is kept unchanged.
Examples:
SLI ] (MiXeD cAsE) ToUppercase
(MIXED CASE)
Author: Jochen Martin Eppler
SeeAlso: ToLowercase
*/
void
ToUppercase_sFunction::execute( SLIInterpreter* i ) const
{
i->assert_stack_load( 1 );
StringDatum sd = getValue< StringDatum >( i->OStack.top() );
std::string* str = dynamic_cast< std::string* >( &sd );
std::transform( str->begin(), str->end(), str->begin(), toupper );
i->OStack.pop();
i->OStack.push( new StringDatum( str->c_str() ) );
i->EStack.pop();
}
/* BeginDocumentation
Name: ToLowercase - Convert a string to lower case.
Synopsis:
(string) ToLowercase -> (string)
Description:
ToLowercase converts a string to lower case. If no lower case
representation of a letter exists, the letter is kept unchanged.
Examples:
SLI ] (MiXeD cAsE) ToLowercase
(mixed case)
Author: Jochen Martin Eppler
SeeAlso: ToUppercase
*/
void
ToLowercase_sFunction::execute( SLIInterpreter* i ) const
{
i->assert_stack_load( 1 );
StringDatum sd = getValue< StringDatum >( i->OStack.top() );
std::string* str = dynamic_cast< std::string* >( &sd );
std::transform( str->begin(), str->end(), str->begin(), tolower );
i->OStack.pop();
i->OStack.push( new StringDatum( str->c_str() ) );
i->EStack.pop();
}
void
init_slistring( SLIInterpreter* i )
{
i->createcommand( "ToUppercase", &touppercase_sfunction );
i->createcommand( "ToLowercase", &tolowercase_sfunction );
}
| 3,370 | 1,162 |
#include "Basic/FileGroup.h"
#include "Basic/TasksManage.h"
#include "BSP.h"
static bool State_MotorVibrate = true;
static uint32_t MotorStop_TimePoint = 0;
static bool IsMotorRunning = false;
static uint8_t PWM_PIN;
static void Init_Motor()
{
uint8_t temp;
if(Motor_DIR)
{
PWM_PIN = Motor_IN1_Pin;
temp = Motor_IN2_Pin;
}else
{
PWM_PIN = Motor_IN2_Pin;
temp = Motor_IN1_Pin;
}
PWM_Init(PWM_PIN, 1000, 80);
pinMode(temp, OUTPUT);
pinMode(Motor_SLP_Pin, OUTPUT);
digitalWrite(temp, LOW);
digitalWrite(Motor_SLP_Pin, HIGH);
Motor_Vibrate(0.9f, 1000);
}
void Task_MotorRunning(TimerHandle_t xTimer)
{
__ExecuteOnce(Init_Motor());
if(IsMotorRunning && millis() >= MotorStop_TimePoint)
{
analogWrite(PWM_PIN, 0);
digitalWrite(Motor_SLP_Pin, LOW);
IsMotorRunning = false;
}
}
void Motor_SetEnable(bool en)
{
State_MotorVibrate = en;
}
void Motor_Vibrate(float strength, uint32_t time)
{
if(!State_MotorVibrate)
return;
__LimitValue(strength, 0.0f, 1.0f);
digitalWrite(Motor_SLP_Pin, HIGH);
analogWrite(PWM_PIN, strength * 1000);
IsMotorRunning = true;
MotorStop_TimePoint = millis() + time;
}
void Motor_SetState(bool state)
{
if(!State_MotorVibrate)
return;
analogWrite(PWM_PIN, state ? 1000 : 0);
}
| 1,332 | 618 |
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/imgui/imguimodule.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/globalscallbacks.h>
#include <openspace/engine/virtualpropertymanager.h>
#include <openspace/engine/windowdelegate.h>
#include <openspace/engine/moduleengine.h>
#include <openspace/interaction/navigationhandler.h>
#include <openspace/interaction/sessionrecording.h>
#include <openspace/network/parallelpeer.h>
#include <openspace/rendering/dashboard.h>
#include <openspace/rendering/luaconsole.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scene.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/misc/profiling.h>
namespace openspace {
ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) {
addPropertySubOwner(gui);
global::callback::initialize.emplace_back([&]() {
LDEBUGC("ImGUIModule", "Initializing GUI");
gui.initialize();
gui._globalProperty.setSource(
[]() {
std::vector<properties::PropertyOwner*> res = {
&global::navigationHandler,
&global::sessionRecording,
&global::timeManager,
&global::renderEngine,
&global::parallelPeer,
&global::luaConsole,
&global::dashboard
};
return res;
}
);
gui._screenSpaceProperty.setSource(
[]() {
return global::screenSpaceRootPropertyOwner.propertySubOwners();
}
);
gui._moduleProperty.setSource(
[]() {
std::vector<properties::PropertyOwner*> v;
v.push_back(&(global::moduleEngine));
return v;
}
);
gui._sceneProperty.setSource(
[]() {
const Scene* scene = global::renderEngine.scene();
const std::vector<SceneGraphNode*>& nodes = scene ?
scene->allSceneGraphNodes() :
std::vector<SceneGraphNode*>();
return std::vector<properties::PropertyOwner*>(
nodes.begin(),
nodes.end()
);
}
);
gui._virtualProperty.setSource(
[]() {
std::vector<properties::PropertyOwner*> res = {
&global::virtualPropertyManager
};
return res;
}
);
gui._featuredProperties.setSource(
[]() {
std::vector<SceneGraphNode*> nodes =
global::renderEngine.scene()->allSceneGraphNodes();
nodes.erase(
std::remove_if(
nodes.begin(),
nodes.end(),
[](SceneGraphNode* n) {
const std::vector<std::string>& tags = n->tags();
const auto it = std::find(
tags.begin(),
tags.end(),
"GUI.Interesting"
);
return it == tags.end();
}
),
nodes.end()
);
return std::vector<properties::PropertyOwner*>(
nodes.begin(),
nodes.end()
);
}
);
});
global::callback::deinitialize.emplace_back([&]() {
ZoneScopedN("ImGUI")
LDEBUGC("ImGui", "Deinitialize GUI");
gui.deinitialize();
});
global::callback::initializeGL.emplace_back([&]() {
ZoneScopedN("ImGUI")
LDEBUGC("ImGui", "Initializing GUI OpenGL");
gui.initializeGL();
});
global::callback::deinitializeGL.emplace_back([&]() {
ZoneScopedN("ImGUI")
LDEBUGC("ImGui", "Deinitialize GUI OpenGL");
gui.deinitializeGL();
});
global::callback::draw2D.emplace_back([&]() {
ZoneScopedN("ImGUI")
// TODO emiax: Make sure this is only called for one of the eyes, in the case
// of side-by-side / top-bottom stereo.
WindowDelegate& delegate = global::windowDelegate;
const bool showGui = delegate.hasGuiWindow() ? delegate.isGuiWindow() : true;
if (delegate.isMaster() && showGui) {
const glm::ivec2 windowSize = delegate.currentSubwindowSize();
const glm::ivec2 resolution = delegate.currentDrawBufferResolution();
if (windowSize.x <= 0 || windowSize.y <= 0) {
return;
}
glm::vec2 mousePosition = delegate.mousePosition();
uint32_t mouseButtons = delegate.mouseButtons(2);
const double dt = std::max(delegate.averageDeltaTime(), 0.0);
if (touchInput.active && mouseButtons == 0) {
mouseButtons = touchInput.action;
mousePosition = touchInput.pos;
}
// We don't do any collection of immediate mode user interface, so it
// is fine to open and close a frame immediately
gui.startFrame(
static_cast<float>(dt),
glm::vec2(windowSize),
resolution / windowSize,
mousePosition,
mouseButtons
);
gui.endFrame();
}
});
global::callback::keyboard.emplace_back(
[&](Key key, KeyModifier mod, KeyAction action) -> bool {
ZoneScopedN("ImGUI")
// A list of all the windows that can show up by themselves
if (gui.isEnabled() || gui._performance.isEnabled() ||
gui._sceneProperty.isEnabled())
{
return gui.keyCallback(key, mod, action);
}
else {
return false;
}
}
);
global::callback::character.emplace_back(
[&](unsigned int codepoint, KeyModifier modifier) -> bool {
ZoneScopedN("ImGUI")
// A list of all the windows that can show up by themselves
if (gui.isEnabled() || gui._performance.isEnabled() ||
gui._sceneProperty.isEnabled())
{
return gui.charCallback(codepoint, modifier);
}
else {
return false;
}
}
);
global::callback::mouseButton.emplace_back(
[&](MouseButton button, MouseAction action, KeyModifier) -> bool {
ZoneScopedN("ImGUI")
// A list of all the windows that can show up by themselves
if (gui.isEnabled() || gui._performance.isEnabled() ||
gui._sceneProperty.isEnabled())
{
return gui.mouseButtonCallback(button, action);
}
else {
return false;
}
}
);
global::callback::mouseScrollWheel.emplace_back(
[&](double, double posY) -> bool {
ZoneScopedN("ImGUI")
// A list of all the windows that can show up by themselves
if (gui.isEnabled() || gui._performance.isEnabled() ||
gui._sceneProperty.isEnabled())
{
return gui.mouseWheelCallback(posY);
}
else {
return false;
}
}
);
}
} // namespace openspace
| 9,574 | 2,432 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Clyde Stanfield
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <gtest/gtest.h>
#include <nyra/Vector2.h>
#include <nyra/Transform.h>
TEST(Transform, AccessorsMutators)
{
nyra::Transform transform;
EXPECT_EQ(transform.getPosition(), nyra::Vector2F(0.0f, 0.0f));
EXPECT_EQ(transform.getScale(), nyra::Vector2F(1.0f, 1.0f));
EXPECT_EQ(transform.getRotation(), 0.0f);
EXPECT_EQ(transform.getPivot(), nyra::Vector2F(0.5f, 0.5f));
const nyra::Vector2F testVec(567.909f, -345.234f);
transform.setPosition(testVec);
EXPECT_EQ(transform.getPosition(), testVec);
transform.setScale(testVec);
EXPECT_EQ(transform.getScale(), testVec);
transform.setRotation(testVec.x);
EXPECT_EQ(transform.getRotation(), testVec.x);
transform.setPivot(testVec);
EXPECT_EQ(transform.getPivot(), testVec);
}
TEST(Transform, Matrix)
{
//TODO: Test matrix
std::cout << "Need to add matrix tests\n";
}
| 2,033 | 729 |
/*******************************************************************************
* Copyright (c) 2015, 2018 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include <stdio.h>
#include "omr.h"
#include "omrutil.h"
#include "omrTest.h"
int
main(int argc, char **argv, char **envp)
{
::testing::InitGoogleTest(&argc, argv);
OMREventListener::setDefaultTestListener();
return RUN_ALL_TESTS();
}
TEST(UtilTest, detectVMDirectory)
{
#if defined(OMR_OS_WINDOWS)
void *token = NULL;
ASSERT_EQ(OMR_ERROR_NONE, OMR_Glue_GetVMDirectoryToken(&token));
wchar_t path[2048];
size_t pathMax = 2048;
wchar_t *pathEnd = NULL;
ASSERT_EQ(OMR_ERROR_NONE, detectVMDirectory(path, pathMax, &pathEnd));
ASSERT_TRUE((NULL == pathEnd) || (L'\0' == *pathEnd));
wprintf(L"VM Directory: '%s'\n", path);
if (NULL != pathEnd) {
size_t length = pathMax - wcslen(path) - 2;
_snwprintf(pathEnd, length, L"\\abc");
wprintf(L"Mangled VM Directory: '%s'\n", path);
}
#endif /* defined(OMR_OS_WINDOWS) */
}
| 2,033 | 695 |
// Copyright 2011 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/frame/v8_scanner/scanner-character-streams.h"
#include <memory>
#include <vector>
#include "third_party/blink/renderer/core/frame/v8_scanner/globals.h"
#include "third_party/blink/renderer/core/frame/v8_scanner/scanner.h"
#include "third_party/blink/renderer/core/frame/v8_scanner/unicode-inl.h"
namespace v8_scanner {
template <typename Char>
struct Range {
const Char* start;
const Char* end;
size_t length() { return static_cast<size_t>(end - start); }
bool unaligned_start() const {
return reinterpret_cast<intptr_t>(start) % sizeof(Char) == 1;
}
};
// A Char stream backed by a C array. Testing only.
template <typename Char>
class TestingStream {
public:
TestingStream(const Char* data, size_t length)
: data_(data), length_(length) {}
// The no_gc argument is only here because of the templated way this class
// is used along with other implementations that require V8 heap access.
Range<Char> GetDataAt(size_t pos) {
return {&data_[std::min(length_, pos)], &data_[length_]};
}
static const bool kCanBeCloned = true;
static const bool kCanAccessHeap = false;
private:
const Char* const data_;
const size_t length_;
};
// Provides a buffered utf-16 view on the bytes from the underlying ByteStream.
// Chars are buffered if either the underlying stream isn't utf-16 or the
// underlying utf-16 stream might move (is on-heap).
template <template <typename T> class ByteStream>
class BufferedCharacterStream : public Utf16CharacterStream {
public:
template <class... TArgs>
BufferedCharacterStream(size_t pos, TArgs... args) : byte_stream_(args...) {
buffer_pos_ = pos;
}
bool can_be_cloned() const final {
return ByteStream<uint16_t>::kCanBeCloned;
}
std::unique_ptr<Utf16CharacterStream> Clone() const override {
return std::unique_ptr<Utf16CharacterStream>(
new BufferedCharacterStream<ByteStream>(*this));
}
protected:
bool ReadBlock() final {
size_t position = pos();
buffer_pos_ = position;
buffer_start_ = &buffer_[0];
buffer_cursor_ = buffer_start_;
Range<uint8_t> range =
byte_stream_.GetDataAt(position);
if (range.length() == 0) {
buffer_end_ = buffer_start_;
return false;
}
size_t length = std::min({kBufferSize, range.length()});
for (unsigned int i = 0; i < length; ++i) {
buffer_[i] = *((uc16 *)(range.start) + i);
}
buffer_end_ = &buffer_[length];
return true;
}
bool can_access_heap() const final {
return ByteStream<uint8_t>::kCanAccessHeap;
}
private:
BufferedCharacterStream(const BufferedCharacterStream<ByteStream>& other)
: byte_stream_(other.byte_stream_) {}
static const size_t kBufferSize = 512;
uc16 buffer_[kBufferSize];
ByteStream<uint8_t> byte_stream_;
};
// Provides a unbuffered utf-16 view on the bytes from the underlying
// ByteStream.
template <template <typename T> class ByteStream>
class UnbufferedCharacterStream : public Utf16CharacterStream {
public:
template <class... TArgs>
UnbufferedCharacterStream(size_t pos, TArgs... args) : byte_stream_(args...) {
buffer_pos_ = pos;
}
bool can_access_heap() const final {
return ByteStream<uint16_t>::kCanAccessHeap;
}
bool can_be_cloned() const final {
return ByteStream<uint16_t>::kCanBeCloned;
}
std::unique_ptr<Utf16CharacterStream> Clone() const override {
return std::unique_ptr<Utf16CharacterStream>(
new UnbufferedCharacterStream<ByteStream>(*this));
}
protected:
bool ReadBlock() final {
size_t position = pos();
buffer_pos_ = position;
Range<uint16_t> range =
byte_stream_.GetDataAt(position);
buffer_start_ = range.start;
buffer_end_ = range.end;
buffer_cursor_ = buffer_start_;
if (range.length() == 0) return false;
return true;
}
UnbufferedCharacterStream(const UnbufferedCharacterStream<ByteStream>& other)
: byte_stream_(other.byte_stream_) {}
ByteStream<uint16_t> byte_stream_;
};
// ----------------------------------------------------------------------------
// BufferedUtf16CharacterStreams
//
// A buffered character stream based on a random access character
// source (ReadBlock can be called with pos() pointing to any position,
// even positions before the current).
//
// TODO(verwaest): Remove together with Utf8 external streaming streams.
class BufferedUtf16CharacterStream : public Utf16CharacterStream {
public:
BufferedUtf16CharacterStream();
protected:
static const size_t kBufferSize = 512;
bool ReadBlock() final;
// FillBuffer should read up to kBufferSize characters at position and store
// them into buffer_[0..]. It returns the number of characters stored.
virtual size_t FillBuffer(size_t position) = 0;
// Fixed sized buffer that this class reads from.
// The base class' buffer_start_ should always point to buffer_.
uc16 buffer_[kBufferSize];
};
BufferedUtf16CharacterStream::BufferedUtf16CharacterStream()
: Utf16CharacterStream(buffer_, buffer_, buffer_, 0) {}
bool BufferedUtf16CharacterStream::ReadBlock() {
size_t position = pos();
buffer_pos_ = position;
buffer_cursor_ = buffer_;
buffer_end_ = buffer_ + FillBuffer(position);
return buffer_cursor_ < buffer_end_;
}
std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting(
const char* data) {
return ScannerStream::ForTesting(data, strlen(data));
}
std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting(
const char* data, size_t length) {
if (data == nullptr) {
// We don't want to pass in a null pointer into the the character stream,
// because then the one-past-the-end pointer is undefined, so instead pass
// through this static array.
static const char non_null_empty_string[1] = {0};
data = non_null_empty_string;
}
return std::unique_ptr<Utf16CharacterStream>(
new BufferedCharacterStream<TestingStream>(
0, reinterpret_cast<const uint8_t*>(data), length));
}
std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting(
const uint16_t* data, size_t length) {
if (data == nullptr) {
// We don't want to pass in a null pointer into the the character stream,
// because then the one-past-the-end pointer is undefined, so instead pass
// through this static array.
static const uint16_t non_null_empty_uint16_t_string[1] = {0};
data = non_null_empty_uint16_t_string;
}
return std::unique_ptr<Utf16CharacterStream>(
new UnbufferedCharacterStream<TestingStream>(0, data, length));
}
}
| 6,747 | 2,174 |
/*
###############################################################################
# Copyright (c) 2018, PulseRain Technology LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (LGPL) as
# published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
*/
#include "M10SevenSeg.h"
static const uint8_t seven_seg_display_encoding [16] = {
0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71
};
//----------------------------------------------------------------------------
// seven_seg_on_off()
//
// Parameters:
// on_off_mask : mask for power on/off
//
// Return Value:
// None
//
// Remarks:
// This function assumes power on/off control is in the lower
// two bits of Port 2
//----------------------------------------------------------------------------
static void seven_seg_on_off (uint8_t on_off_mask) __reentrant
{
P2 &= 0xFC;
P2 |= on_off_mask & 0x3;
} // End of seven_seg_on_off()
//----------------------------------------------------------------------------
// seven_seg_init()
//
// Parameters:
// None
//
// Return Value:
// None
//
// Remarks:
// This function assumes Port 0 and Port 1 are connected to 7-seg display,
// and assumes on/off control is in the lower two bits of Port 2
//----------------------------------------------------------------------------
static void seven_seg_init() __reentrant
{
P0_DIRECTION = 0xFF;
P1_DIRECTION = 0xFF;
P2_DIRECTION |= 0x3;
seven_seg_on_off (3);
} // End of seven_seg_init()
//----------------------------------------------------------------------------
// seven_seg_dp()
//
// Parameters:
// mask : mask for the decimal points
//
// Return Value:
// None
//
// Remarks:
// This function assumes Port 0 and Port 1 are connected to 7-seg display,
// and assumes decimal point is controlled by bit 7 in each port
//----------------------------------------------------------------------------
static void seven_seg_dp (uint8_t mask) __reentrant
{
P0_7 = mask & 0x1;
P1_7 = (mask >> 1) & 0x1;
} // End of seven_seg_dp()
//----------------------------------------------------------------------------
// seven_seg_display()
//
// Parameters:
// number : hex number (0 ~ 15) to be displayed
// index : 0 or 1 for display position
//
// Return Value:
// None
//
// Remarks:
// This function assumes Port 0 and Port 1 are connected to 7-seg display.
//----------------------------------------------------------------------------
static void seven_seg_display (uint8_t number, uint8_t index) __reentrant
{
uint8_t t;
t = number & 0xF;
if (index == 0) {
P0 &= 0x80;
P0 |= seven_seg_display_encoding[t];
} else if (index == 1) {
P1 &= 0x80;
P1 |= seven_seg_display_encoding[t];
}
} // End of seven_seg_display()
//----------------------------------------------------------------------------
// seven_seg_hex_byte_display()
//
// Parameters:
// number : hex number (0 ~ 255) to be displayed
//
// Return Value:
// None
//
// Remarks:
// This function assumes Port 0 and Port 1 are connected to 7-seg display.
//----------------------------------------------------------------------------
static void seven_seg_hex_byte_display (uint8_t num) __reentrant
{
seven_seg_display (num, 1);
seven_seg_display (num >> 4, 0);
} // End of seven_seg_hex_byte_display()
const SEVEN_SEG_STRUCT SEVEN_SEG = {
.init = seven_seg_init,
.onOff = seven_seg_on_off,
.byteHex = seven_seg_hex_byte_display,
.decimalPoint = seven_seg_dp
};
| 4,242 | 1,363 |
//Program 4-6 What are pointers pointing to?
#include <iostream.h>
#include <iomanip.h>
int main()
{
//set up variables and assign addresses into pointers
int m , *m_ptr = &m;
float p, *p_ptr = &p;
//assign values where the pointers are pointing
*m_ptr = 4;
*p_ptr = (float)3.14159;
//write each pointer's value, address and what the pointer is pointing to
cout << "\nPtr Name Value Address Pointing to \n" <<
"\n m_ptr " << m_ptr << setw(12) << &m_ptr
<< setw(10) << *m_ptr <<
"\n p_ptr " << p_ptr << setw(12) << &p_ptr
<< setw(10) << *p_ptr << endl;
return 0;
}
| 664 | 277 |
/*
KRKR PSBFILE Compiler/Decompiler
Author:201724
QQ:495159
EMail:number201724@me.com
*/
#include "def.h"
#include "psb_cc_base.h"
psb_cc_base::psb_cc_base(psb_value_t::type_t type) : _data(NULL), _length(0), _type(type), _cc(NULL)
{
}
psb_cc_base::psb_cc_base(psb_cc* cc, psb_value_t::type_t type) :_cc(cc), _data(NULL), _length(0), _type(type)
{
}
psb_cc_base::psb_cc_base(psb_cc* cc, Json::Value &src, psb_value_t::type_t type) :_cc(cc), _src(src), _data(NULL), _length(0), _type(type)
{
}
psb_cc_base::~psb_cc_base()
{
if (_data)
{
delete[] _data;
}
}
unsigned char* psb_cc_base::get_data()
{
return _data;
}
void psb_cc_base::reset_data()
{
if (_data) {
delete[] _data;
_data = NULL;
}
_length = 0;
}
uint32_t psb_cc_base::get_length()
{
return _length;
}
psb_value_t::type_t psb_cc_base::get_type()
{
return _type;
}
Json::Value psb_cc_base::get_source()
{
return _src;
}
void psb_cc_base::dump()
{
#ifdef _DEBUG
printf("%s:", get_class_name());
for (uint32_t i = 0; i < _length; i++)
{
printf("%02X ", _data[i]);
}
printf("\n");
#endif
} | 1,080 | 550 |
#include "Keypad.h"
Keypad::Keypad(char *userKeymap, byte *row, byte *col, byte rows, byte cols)
{
/* nothing */
}
| 119 | 51 |
/*
* @author Michael Rapp (mrapp@ke.tu-darmstadt.de)
*/
#pragma once
#include "common/indices/index_forward_iterator.hpp"
/**
* Implements row-wise read-only access to binary values that are stored in a pre-allocated matrix in the compressed
* sparse row (CSR) format.
*/
class BinaryCsrConstView {
protected:
uint32 numRows_;
uint32 numCols_;
uint32* rowIndices_;
uint32* colIndices_;
public:
/**
* @param numRows The number of rows in the view
* @param numCols The number of columns in the view
* @param rowIndices A pointer to an array of type `uint32`, shape `(numRows + 1)`, that stores the indices
* of the first element in `colIndices` that corresponds to a certain row. The index at the
* last position is equal to `num_non_zero_values`
* @param colIndices A pointer to an array of type `uint32`, shape `(num_non_zero_values)`, that stores the
* column-indices, the non-zero elements correspond to
*/
BinaryCsrConstView(uint32 numRows, uint32 numCols, uint32* rowIndices, uint32* colIndices);
/**
* An iterator that provides read-only access to the indices in the view.
*/
typedef const uint32* index_const_iterator;
/**
* An iterator that provides read-only access to the values in the view.
*/
typedef IndexForwardIterator<index_const_iterator> value_const_iterator;
/**
* Returns an `index_const_iterator` to the beginning of the indices at a specific row.
*
* @param row The row
* @return An `index_const_iterator` to the beginning of the indices
*/
index_const_iterator row_indices_cbegin(uint32 row) const;
/**
* Returns an `index_const_iterator` to the end of the indices at a specific row.
*
* @param row The row
* @return An `index_const_iterator` to the end of the indices
*/
index_const_iterator row_indices_cend(uint32 row) const;
/**
* Returns a `value_const_iterator` to the beginning of the values at a specific row.
*
* @param row The row
* @return A `value_const_iterator` to the beginning of the values
*/
value_const_iterator row_values_cbegin(uint32 row) const;
/**
* Returns a `value_const_iterator` to the end of the values at a specific row.
*
* @param row The row
* @return A `value_const_iterator` to the end of the values
*/
value_const_iterator row_values_cend(uint32 row) const;
/**
* Returns the number of rows in the view.
*
* @return The number of rows
*/
uint32 getNumRows() const;
/**
* Returns the number of columns in the view.
*
* @return The number of columns
*/
uint32 getNumCols() const;
/**
* Returns the number of non-zero elements in the view.
*
* @return The number of non-zero elements
*/
uint32 getNumNonZeroElements() const;
};
/**
* Implements row-wise read and write access to binary values that are stored in a pre-allocated matrix in the
* compressed sparse row (CSR) format.
*/
class BinaryCsrView final : public BinaryCsrConstView {
public:
/**
* @param numRows The number of rows in the view
* @param numCols The number of columns in the view
* @param rowIndices A pointer to an array of type `uint32`, shape `(numRows + 1)`, that stores the indices
* of the first element in `colIndices` that corresponds to a certain row. The index at the
* last position is equal to `num_non_zero_values`
* @param colIndices A pointer to an array of type `uint32`, shape `(num_non_zero_values)`, that stores the
* column-indices, the non-zero elements correspond to
*/
BinaryCsrView(uint32 numRows, uint32 numCols, uint32* rowIndices, uint32* colIndices);
/**
* An iterator that provides access to the indices of the view and allows to modify them.
*/
typedef uint32* index_iterator;
/**
* Returns an `index_iterator` to the beginning of the indices at a specific row.
*
* @param row The row
* @return An `index_iterator` to the beginning of the indices
*/
index_iterator row_indices_begin(uint32 row);
/**
* Returns an `index_iterator` to the end of the indices at a specific row.
*
* @param row The row
* @return An `index_iterator` to the end of the indices
*/
index_iterator row_indices_end(uint32 row);
};
| 5,041 | 1,369 |
#include <Adv.H>
#include <Adv_F.H>
Real
Adv::advance (Real time,
Real dt,
int iteration,
int ncycle)
{
for (int k = 0; k < NUM_STATE_TYPE; k++) {
state[k].allocOldData();
state[k].swapTimeLevels(dt);
}
MultiFab& S_new = get_new_data(State_Type);
const Real prev_time = state[State_Type].prevTime();
const Real cur_time = state[State_Type].curTime();
const Real ctr_time = 0.5*(prev_time + cur_time);
const Real* dx = geom.CellSize();
const Real* prob_lo = geom.ProbLo();
//
// Get pointers to Flux registers, or set pointer to zero if not there.
//
FluxRegister *fine = 0;
FluxRegister *current = 0;
int finest_level = parent->finestLevel();
if (do_reflux && level < finest_level) {
fine = &getFluxReg(level+1);
fine->setVal(0.0);
}
if (do_reflux && level > 0) {
current = &getFluxReg(level);
}
MultiFab fluxes[BL_SPACEDIM];
if (do_reflux)
{
for (int j = 0; j < BL_SPACEDIM; j++)
{
BoxArray ba = S_new.boxArray();
ba.surroundingNodes(j);
fluxes[j].define(ba, NUM_STATE, 0, Fab_allocate);
}
}
// State with ghost cells
MultiFab Sborder(grids, NUM_STATE, NUM_GROW);
FillPatch(*this, Sborder, NUM_GROW, time, State_Type, 0, NUM_STATE);
#ifdef _OPENMP
#pragma omp parallel
#endif
{
FArrayBox flux[BL_SPACEDIM], uface[BL_SPACEDIM];
for (MFIter mfi(S_new, true); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.tilebox();
const FArrayBox& statein = Sborder[mfi];
FArrayBox& stateout = S_new[mfi];
// Allocate fabs for fluxes and Godunov velocities.
for (int i = 0; i < BL_SPACEDIM ; i++) {
const Box& bxtmp = BoxLib::surroundingNodes(bx,i);
flux[i].resize(bxtmp,NUM_STATE);
uface[i].resize(BoxLib::grow(bxtmp,1),1);
}
BL_FORT_PROC_CALL(GET_FACE_VELOCITY,get_face_velocity)
(level, ctr_time,
D_DECL(BL_TO_FORTRAN(uface[0]),
BL_TO_FORTRAN(uface[1]),
BL_TO_FORTRAN(uface[2])),
dx, prob_lo);
BL_FORT_PROC_CALL(ADVECT,advect)
(time, bx.loVect(), bx.hiVect(),
BL_TO_FORTRAN_3D(statein),
BL_TO_FORTRAN_3D(stateout),
D_DECL(BL_TO_FORTRAN_3D(uface[0]),
BL_TO_FORTRAN_3D(uface[1]),
BL_TO_FORTRAN_3D(uface[2])),
D_DECL(BL_TO_FORTRAN_3D(flux[0]),
BL_TO_FORTRAN_3D(flux[1]),
BL_TO_FORTRAN_3D(flux[2])),
dx, dt);
if (do_reflux) {
for (int i = 0; i < BL_SPACEDIM ; i++)
fluxes[i][mfi].copy(flux[i],mfi.nodaltilebox(i));
}
}
}
if (do_reflux) {
if (current) {
for (int i = 0; i < BL_SPACEDIM ; i++)
current->FineAdd(fluxes[i],i,0,0,NUM_STATE,1.);
}
if (fine) {
for (int i = 0; i < BL_SPACEDIM ; i++)
fine->CrseInit(fluxes[i],i,0,0,NUM_STATE,-1.);
}
}
return dt;
}
| 2,915 | 1,305 |
#include "globals.h"
#include "decoders/decoders.h"
#include "mx/mx.h"
#include "crc.h"
#include "fluxmap.h"
#include "decoders/fluxmapreader.h"
#include "sector.h"
#include "record.h"
#include "track.h"
#include <string.h>
const int SECTOR_SIZE = 256;
/*
* MX disks are a bunch of sectors glued together with no gaps or sync markers,
* following a single beginning-of-track synchronisation and identification
* sequence.
*/
/* FM beginning of track marker:
* 1010 1010 1010 1010 1111 1111 1010 1111
* a a a a f f a f
*/
const FluxPattern ID_PATTERN(32, 0xaaaaffaf);
void MxDecoder::beginTrack()
{
_currentSector = -1;
_clock = 0;
}
AbstractDecoder::RecordType MxDecoder::advanceToNextRecord()
{
if (_currentSector == -1)
{
/* First sector in the track: look for the sync marker. */
const FluxMatcher* matcher = nullptr;
_sector->clock = _clock = _fmr->seekToPattern(ID_PATTERN, matcher);
readRawBits(32); /* skip the ID mark */
_logicalTrack = decodeFmMfm(readRawBits(32)).reader().read_be16();
}
else if (_currentSector == 10)
{
/* That was the last sector on the disk. */
return UNKNOWN_RECORD;
}
else
{
/* Otherwise we assume the clock from the first sector is still valid.
* The decoder framwork will automatically stop when we hit the end of
* the track. */
_sector->clock = _clock;
}
_currentSector++;
return SECTOR_RECORD;
}
void MxDecoder::decodeSectorRecord()
{
auto bits = readRawBits((SECTOR_SIZE+2)*16);
auto bytes = decodeFmMfm(bits).slice(0, SECTOR_SIZE+2).swab();
uint16_t gotChecksum = 0;
ByteReader br(bytes);
for (int i=0; i<(SECTOR_SIZE/2); i++)
gotChecksum += br.read_le16();
uint16_t wantChecksum = br.read_le16();
_sector->logicalTrack = _logicalTrack;
_sector->logicalSide = _track->physicalSide;
_sector->logicalSector = _currentSector;
_sector->data = bytes.slice(0, SECTOR_SIZE);
_sector->status = (gotChecksum == wantChecksum) ? Sector::OK : Sector::BAD_CHECKSUM;
}
| 2,128 | 803 |
/*
* (C) Copyright 2021 Met Office UK
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include <memory>
#include "ioda/distribution/Accumulator.h"
#include "ioda/ObsDataVector.h"
#include "oops/util/missingValues.h"
#include "ufo/filters/ObsFilterData.h"
#include "ufo/filters/obsfunctions/BgdDepartureAnomaly.h"
#include "ufo/filters/Variable.h"
namespace ufo {
static ObsFunctionMaker<BgdDepartureAnomaly> makerBgdDepartureAnomaly_("BgdDepartureAnomaly");
BgdDepartureAnomaly::BgdDepartureAnomaly(const eckit::LocalConfiguration & conf)
: invars_() {
// Initialize options
options_.deserialize(conf);
// Get channels for computing the background departure
channels_ = {options_.obslow.value(), options_.obshigh.value()};
// Use default or test version of HofX
const std::string & hofxopt = options_.testHofX.value();
// Include list of required data from ObsSpace
invars_ += Variable("brightness_temperature@ObsValue", channels_);
invars_ += Variable("brightness_temperature@"+hofxopt, channels_);
if (options_.ObsBias.value().size()) {
// Get optional bias correction
const std::string & biasopt = options_.ObsBias.value();
invars_ += Variable("brightness_temperature@"+biasopt, channels_);
}
}
// -----------------------------------------------------------------------------
void BgdDepartureAnomaly::compute(const ObsFilterData & in,
ioda::ObsDataVector<float> & out) const {
// Get dimension
const size_t nlocs = in.nlocs();
const float missing = util::missingValue(missing);
// Get obs space
auto & obsdb = in.obsspace();
ASSERT(channels_.size() == 2);
// Get observation values for required channels
const std::string & hofxopt = options_.testHofX.value();
std::vector<float> obslow(nlocs), obshigh(nlocs);
std::vector<float> bgdlow(nlocs), bgdhigh(nlocs);
in.get(Variable("brightness_temperature@ObsValue", channels_)[0], obslow);
in.get(Variable("brightness_temperature@ObsValue", channels_)[1], obshigh);
in.get(Variable("brightness_temperature@"+hofxopt, channels_)[0], bgdlow);
in.get(Variable("brightness_temperature@"+hofxopt, channels_)[1], bgdhigh);
// Get bias correction if ObsBias is present in filter options
if (options_.ObsBias.value().size()) {
const std::string & biasopt = options_.ObsBias.value();
std::vector<float> biaslow(nlocs), biashigh(nlocs);
in.get(Variable("brightness_temperature@"+biasopt, channels_)[0], biaslow);
in.get(Variable("brightness_temperature@"+biasopt, channels_)[1], biashigh);
// Apply bias correction
for (size_t iloc = 0; iloc < nlocs; ++iloc) {
bgdlow[iloc] -= biaslow[iloc];
bgdhigh[iloc] -= biashigh[iloc];
}
}
// Compute background departures
// To calculate mean departures, we need to know the number of observations with non-missing
// departures (taking into account all MPI ranks)...
std::unique_ptr<ioda::Accumulator<size_t>> countAccumulator =
obsdb.distribution()->createAccumulator<size_t>();
// ... and the sum of all non-missing departures
enum {OMB_LOW, OMB_HIGH, NUM_OMBS};
std::unique_ptr<ioda::Accumulator<std::vector<double>>> totalsAccumulator =
obsdb.distribution()->createAccumulator<double>(NUM_OMBS);
// First, perform local reductions...
std::vector<float> omblow(nlocs), ombhigh(nlocs);
for (size_t iloc = 0; iloc < nlocs; ++iloc) {
if (obslow[iloc] == missing || bgdlow[iloc] == missing ||
obshigh[iloc] == missing || bgdhigh[iloc] == missing) {
omblow[iloc] = missing;
ombhigh[iloc] = missing;
} else {
omblow[iloc] = obslow[iloc] - bgdlow[iloc];
ombhigh[iloc] = obshigh[iloc] - bgdhigh[iloc];
totalsAccumulator->addTerm(iloc, OMB_LOW, omblow[iloc]);
totalsAccumulator->addTerm(iloc, OMB_HIGH, ombhigh[iloc]);
countAccumulator->addTerm(iloc, 1);
}
}
// ... and then global reductions.
const std::size_t count = countAccumulator->computeResult();
const std::vector<double> totals = totalsAccumulator->computeResult();
// Calculate the means
const double MeanOmbLow = totals[OMB_LOW] / count;
const double MeanOmbHigh = totals[OMB_HIGH] / count;
// Compute anomaly difference
for (size_t iloc = 0; iloc < nlocs; ++iloc) {
if (obslow[iloc] == missing || bgdlow[iloc] == missing ||
obshigh[iloc] == missing || bgdhigh[iloc] == missing) {
out[0][iloc] = missing;
} else {
out[0][iloc] = std::abs((omblow[iloc]-MeanOmbLow) - (ombhigh[iloc]-MeanOmbHigh));
}
}
}
// -----------------------------------------------------------------------------
const ufo::Variables & BgdDepartureAnomaly::requiredVariables() const {
return invars_;
}
// -----------------------------------------------------------------------------
} // namespace ufo
| 4,942 | 1,724 |
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <grpcpp/grpcpp.h>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include "api/Compiler.hh"
#include "api/DataFile.hh"
#include "api/Decoder.hh"
#include "api/Encoder.hh"
#include "api/Generic.hh"
#include "api/Specific.hh"
#include "api/ValidSchema.hh"
#include "google/cloud/bigquery/storage/v1beta1/storage.grpc.pb.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/platform/net.h"
#include "tensorflow_io/bigquery/kernels/bigquery_lib.h"
#include "tensorflow_io/bigquery/kernels/test_kernels/fake_bigquery_storage_service.h"
namespace tensorflow {
namespace {
namespace apiv1beta1 = ::google::cloud::bigquery::storage::v1beta1;
class BigQueryTestClientResource : public BigQueryClientResource {
public:
explicit BigQueryTestClientResource(
std::shared_ptr<apiv1beta1::BigQueryStorage::Stub> stub,
std::unique_ptr<grpc::Server> server,
std::unique_ptr<FakeBigQueryStorageService> fake_service)
: BigQueryClientResource(stub),
server_(std::move(server)),
fake_service_(std::move(fake_service)) {}
string DebugString() const override { return "BigQueryTestClientResource"; }
protected:
~BigQueryTestClientResource() override { server_->Shutdown(); }
private:
std::unique_ptr<grpc::Server> server_;
std::unique_ptr<FakeBigQueryStorageService> fake_service_;
};
class BigQueryTestClientOp : public OpKernel {
public:
explicit BigQueryTestClientOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("avro_schema", &avro_schema_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("avro_serialized_rows_per_stream",
&avro_serialized_rows_per_stream_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("avro_serialized_rows_count_per_stream",
&avro_serialized_rows_count_per_stream_));
OP_REQUIRES(
ctx,
avro_serialized_rows_per_stream_.size() ==
avro_serialized_rows_count_per_stream_.size(),
errors::InvalidArgument("avro_serialized_rows_per_stream and "
"avro_serialized_rows_count_per_stream lists "
"should have same length"));
}
~BigQueryTestClientOp() override {
if (cinfo_.resource_is_private_to_kernel()) {
if (!cinfo_.resource_manager()
->Delete<BigQueryClientResource>(cinfo_.container(),
cinfo_.name())
.ok()) {
// Do nothing; the resource can have been deleted by session resets.
}
}
}
void Compute(OpKernelContext* ctx) override LOCKS_EXCLUDED(mu_) {
mutex_lock l(mu_);
if (!initialized_) {
ResourceMgr* mgr = ctx->resource_manager();
OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def()));
BigQueryTestClientResource* test_resource;
OP_REQUIRES_OK(
ctx,
mgr->LookupOrCreate<BigQueryTestClientResource>(
cinfo_.container(), cinfo_.name(), &test_resource,
[this](BigQueryTestClientResource** ret) EXCLUSIVE_LOCKS_REQUIRED(
mu_) {
auto fake_service =
absl::make_unique<FakeBigQueryStorageService>();
fake_service->SetAvroSchema(this->avro_schema_);
fake_service->SetAvroRowsPerStream(
this->avro_serialized_rows_per_stream_,
this->avro_serialized_rows_count_per_stream_);
grpc::ServerBuilder server_builder;
int port = internal::PickUnusedPortOrDie();
string server_address = absl::StrCat("localhost:", port);
server_builder.AddListeningPort(
server_address, ::grpc::InsecureServerCredentials(), &port);
server_builder.RegisterService(fake_service.get());
std::unique_ptr<grpc::Server> server =
server_builder.BuildAndStart();
string address =
absl::StrCat("localhost:", port);
std::shared_ptr<grpc::Channel> channel = ::grpc::CreateChannel(
address, grpc::InsecureChannelCredentials());
auto stub =
absl::make_unique<apiv1beta1::BigQueryStorage::Stub>(
channel);
channel->WaitForConnected(
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_seconds(5, GPR_TIMESPAN)));
VLOG(3) << "Done creating Fake client";
*ret = new BigQueryTestClientResource(std::move(stub),
std::move(server),
std::move(fake_service));
return Status::OK();
}));
BigQueryClientResource* resource;
OP_REQUIRES_OK(ctx, mgr->LookupOrCreate<BigQueryClientResource>(
cinfo_.container(), cinfo_.name(), &resource,
[test_resource](BigQueryClientResource** ret)
EXCLUSIVE_LOCKS_REQUIRED(mu_) {
*ret = new BigQueryClientResource(
test_resource->get_stub());
return Status::OK();
}));
core::ScopedUnref unref_resource(resource);
core::ScopedUnref unref_test_resource(test_resource);
initialized_ = true;
}
OP_REQUIRES_OK(ctx, MakeResourceHandleToOutput(
ctx, 0, cinfo_.container(), cinfo_.name(),
MakeTypeIndex<BigQueryClientResource>()));
}
private:
mutex mu_;
ContainerInfo cinfo_ GUARDED_BY(mu_);
bool initialized_ GUARDED_BY(mu_) = false;
string avro_schema_;
std::vector<string> avro_serialized_rows_per_stream_;
std::vector<int> avro_serialized_rows_count_per_stream_;
};
REGISTER_KERNEL_BUILDER(Name("BigQueryTestClient").Device(DEVICE_CPU),
BigQueryTestClientOp);
} // namespace
} // namespace tensorflow
| 6,905 | 1,997 |
#ifndef _UART_HPP_
#define _UART_HPP_
#include <stdint.h>
// The GPIO registers base address.
constexpr uint32_t GPIO_BASE = 0x3F200000; // for raspi2 & 3, 0x20200000 for raspi1
// The offsets for reach register.
// Controls actuation of pull up/down to ALL GPIO pins.
constexpr uint32_t GPPUD = (GPIO_BASE + 0x94);
// Controls actuation of pull up/down for specific GPIO pin.
constexpr uint32_t GPPUDCLK0 = (GPIO_BASE + 0x98);
// The base address for UART.
constexpr uint32_t UART0_BASE = 0x3F201000; // for raspi2 & 3, 0x20201000 for raspi1
// The offsets for reach register for the UART.
constexpr uint32_t UART0_DR = (UART0_BASE + 0x00);
constexpr uint32_t UART0_RSRECR = (UART0_BASE + 0x04);
constexpr uint32_t UART0_FR = (UART0_BASE + 0x18);
constexpr uint32_t UART0_ILPR = (UART0_BASE + 0x20);
constexpr uint32_t UART0_IBRD = (UART0_BASE + 0x24);
constexpr uint32_t UART0_FBRD = (UART0_BASE + 0x28);
constexpr uint32_t UART0_LCRH = (UART0_BASE + 0x2C);
constexpr uint32_t UART0_CR = (UART0_BASE + 0x30);
constexpr uint32_t UART0_IFLS = (UART0_BASE + 0x34);
constexpr uint32_t UART0_IMSC = (UART0_BASE + 0x38);
constexpr uint32_t UART0_RIS = (UART0_BASE + 0x3C);
constexpr uint32_t UART0_MIS = (UART0_BASE + 0x40);
constexpr uint32_t UART0_ICR = (UART0_BASE + 0x44);
constexpr uint32_t UART0_DMACR = (UART0_BASE + 0x48);
constexpr uint32_t UART0_ITCR = (UART0_BASE + 0x80);
constexpr uint32_t UART0_ITIP = (UART0_BASE + 0x84);
constexpr uint32_t UART0_ITOP = (UART0_BASE + 0x88);
constexpr uint32_t UART0_TDR = (UART0_BASE + 0x8C);
#endif // _UART_HPP_
| 1,610 | 806 |
//==================================================================================================
//
// Copyright(c) 2013 - 2015 Naïo Technologies
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with This program.
// If not, see <http://www.gnu.org/licenses/>.
//
//==================================================================================================
#ifndef ENTRYPOINT_HPP
#define ENTRYPOINT_HPP
//==================================================================================================
// I N C L U D E F I L E S
#include "Core/COProcessUnit.hpp"
#include "Importer/IMImporter.hpp"
#include "IO/IOTiffWriter.hpp"
#include "HTCmdLineParser.h"
#include "HTLogger.h"
#include "HTSignalHandler.hpp"
#include "CLFileSystem.h"
#include "CLPrint.hpp"
//==================================================================================================
// F O R W A R D D E C L A R A T I O N S
//==================================================================================================
// C O N S T A N T S
//==================================================================================================
// C L A S S E S
class FileOutput
: public co::ProcessUnit
{
//--Methods-----------------------------------------------------------------------------------------
public:
FileOutput( const std::string& folderPath )
: folderPath_{ folderPath }
{ }
~FileOutput(){ }
virtual bool compute_result( co::ParamContext& context, const co::OutputResult& inResult ) final
{
const cm::BitmapPairEntry* bmEntry = dynamic_cast<cm::BitmapPairEntry*>(
&(*inResult.get_cached_entries().begin()->second) );
co::OutputResult result;
result.start_benchmark();
const cm::BitmapPairEntry::ID* id = dynamic_cast<cm::BitmapPairEntry::ID*>(
&(*inResult.get_cached_entries().begin()->first) );
std::string filepathL, filepathR;
bool generatedL = im::AsyncImporter::generate_filename( folderPath_, "",
id->get_index(),
id->get_timestamp(), "l",
"tif", filepathL );
bool generatedR = im::AsyncImporter::generate_filename( folderPath_, "",
id->get_index(),
id->get_timestamp(), "r",
"tif", filepathR );
if( generatedL && generatedR )
{
io::TiffWriter tiffWriterL{ filepathL };
tiffWriterL.write_to_file( bmEntry->bitmap_left(), id->get_index(),
id->get_timestamp(), 22.f );
io::TiffWriter tiffWriterR{ filepathR };
tiffWriterR.write_to_file( bmEntry->bitmap_right(), id->get_index(),
id->get_timestamp(), 22.f );
}
else
{
return false;
}
result.stop_benchmark();
//result.print_benchmark( "FileOuput:" );
for( auto& iter : get_output_list() )
{
if( iter )
{
if( !iter->compute_result( context, result ) )
{
return false;
}
}
}
return true;
}
virtual bool query_output_metrics( co::OutputMetrics& outputMetrics ) final
{
cl::ignore( outputMetrics );
return false;
}
virtual bool query_output_format( co::OutputFormat& outputFormat ) final
{
cl::ignore( outputFormat );
return false;
}
//--Data members------------------------------------------------------------------------------------
private:
const std::string folderPath_;
};
class EntryPoint
: private co::ProcessUnit
{
//--Methods-----------------------------------------------------------------------------------------
public:
EntryPoint();
~EntryPoint();
void set_signal();
bool is_signaled() const;
/// Outputs a header for the program on the standard output stream.
void print_header() const;
bool handle_parameters( const std::string& option, const std::string& type );
/// Main entry point of the application.
int32_t run( int32_t argc, const char** argv );
private:
virtual bool compute_result( co::ParamContext& context, const co::OutputResult& result ) final;
virtual bool query_output_metrics( co::OutputMetrics& om ) final;
virtual bool query_output_format( co::OutputFormat& of ) final;
//--Data members------------------------------------------------------------------------------------
private:
/// Command line parser, logger and debugger for the application
HTCmdLineParser parser_;
HTCmdLineParser::Visitor handler_;
ht::SignalHandler signalHandler_;
volatile bool signaled_;
};
//==================================================================================================
// I N L I N E F U N C T I O N S C O D E S E C T I O N
#endif // ENTRYPOINT_HPP
| 5,074 | 1,619 |
#include "stdafx.h"
#include "DUtil.h"
std::wstring_convert<std::codecvt_utf16<wchar_t>> DUtil::converter;
DUtil::DUtil()
{
}
DUtil::~DUtil()
{
}
std::wstring DUtil::StringAtoW(const std::string &Origin)
{
return DUtil::converter.from_bytes(Origin);
}
std::string DUtil::StringWtoA(const std::wstring &Origin)
{
return DUtil::converter.to_bytes(Origin);
}
std::wstring DUtil::ANSIToUnicode(const std::string& str)
{
int len = 0;
len = str.length();
int unicodeLen = ::MultiByteToWideChar(CP_ACP,
0,
str.c_str(),
-1,
NULL,
0);
wchar_t * pUnicode;
pUnicode = new wchar_t[unicodeLen + 1];
memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t));
::MultiByteToWideChar(CP_ACP,
0,
str.c_str(),
-1,
(LPWSTR)pUnicode,
unicodeLen);
std::wstring rt;
rt = (wchar_t*)pUnicode;
delete pUnicode;
return rt;
}
std::string DUtil::UnicodeToANSI(const std::wstring& str)
{
char* pElementText;
int iTextLen;
// wide char to multi char
iTextLen = WideCharToMultiByte(CP_ACP,
0,
str.c_str(),
-1,
NULL,
0,
NULL,
NULL);
pElementText = new char[iTextLen + 1];
memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1));
::WideCharToMultiByte(CP_ACP,
0,
str.c_str(),
-1,
pElementText,
iTextLen,
NULL,
NULL);
std::string strText;
strText = pElementText;
delete[] pElementText;
return strText;
} | 1,357 | 635 |
/**
** Copyright (c) 2014 Illumina, Inc.
**
** This file is part of Illumina's Enhanced Artificial Genome Engine (EAGLE),
** covered by the "BSD 2-Clause License" (see accompanying LICENSE file)
**
** \description Command line options for 'variantModelling'
**
** \author Mauricio Varea
**/
#ifndef EAGLE_MAIN_GENOME_MUTATOR_OPTIONS_HH
#define EAGLE_MAIN_GENOME_MUTATOR_OPTIONS_HH
#include <string>
#include <map>
#include <boost/filesystem.hpp>
#include "common/Program.hh"
namespace eagle
{
namespace main
{
class GenomeMutatorOptions : public eagle::common::Options
{
public:
enum Modes
{
SAFE_MODE,
WHOLE_DIR
};
GenomeMutatorOptions();
std::map<std::string,unsigned int> exceptionPloidy() const;
private:
std::string usagePrefix() const {return std::string("Usage:\n")
+ std::string(" applyVariants [parameters] [options]");}
std::string usageSuffix() const {std::stringstream usage;
usage << "Examples:" << std::endl;
usage << " * Safe Mode" << std::endl;
usage << " applyVariants -v /path/to/VariantList.vcf \\" << std::endl;
usage << " -r /path/to/ReferenceDir/reference_1.fa \\" << std::endl;
usage << " -r /path/to/ReferenceDir/reference_2.fa \\" << std::endl;
usage << " ... etc ... \\" << std::endl;
usage << " [options]" << std::endl;
usage << " * Whole-dir Mode" << std::endl;
usage << " applyVariants -v /path/to/VariantList.vcf \\" << std::endl;
usage << " -R /path/to/ReferenceDir \\" << std::endl;
usage << " [options]" << std::endl;
return usage.str();}
void postProcess(boost::program_options::variables_map &vm);
public:
std::vector<boost::filesystem::path> referenceGenome;
boost::filesystem::path wholeGenome;
boost::filesystem::path sampleGenome;
std::vector<boost::filesystem::path> variantList;
boost::filesystem::path annotatedVariantList;
unsigned int organismPloidy;
std::vector<std::string> ploidyChromosome;
std::vector<unsigned int> ploidyLevel;
std::string prefixToAdd;
bool noTranslocationError;
bool onlyPrintOutputContigNames;
//bool withGenomeSize;
bool force;
Modes mode;
};
} // namespace main
} // namespace eagle
#endif // EAGLE_MAIN_GENOME_MUTATOR_OPTIONS_HH
| 2,848 | 822 |
/*
* wallaby_regs_p.hpp
****
* Created on: Nov 2, 2015
* Author: Joshua Southerland
*/
namespace Private
{
#ifndef SRC_WALLABY_REGS_P_HPP_
#define SRC_WALLABY_REGS_P_HPP_
#define WALLABY_SPI_VERSION 4
// READ Only Registers ---------------------------------------------------------
#define REG_R_START 0
#define REG_R_VERSION_H 1
#define REG_R_VERSION_L 2
// READ/Write Registers --------------------------------------------------------
#define REG_RW_DIG_IN_H 3
#define REG_RW_DIG_IN_L 4
#define REG_RW_DIG_OUT_H 5
#define REG_RW_DIG_OUT_L 6
#define REG_RW_DIG_PE_H 7
#define REG_RW_DIG_PE_L 8
#define REG_RW_DIG_OE_H 9
#define REG_RW_DIG_OE_L 10
#define REG_RW_ADC_0_H 11
#define REG_RW_ADC_0_L 12
#define REG_RW_ADC_1_H 13
#define REG_RW_ADC_1_L 14
#define REG_RW_ADC_2_H 15
#define REG_RW_ADC_2_L 16
#define REG_RW_ADC_3_H 17
#define REG_RW_ADC_3_L 18
#define REG_RW_ADC_4_H 19
#define REG_RW_ADC_4_L 20
#define REG_RW_ADC_5_H 21
#define REG_RW_ADC_5_L 22
#define REG_RW_ADC_PE 23 // low 6 bits used
#define REG_RW_MAG_X_H 24
#define REG_RW_MAG_X_L 25
#define REG_RW_MAG_Y_H 26
#define REG_RW_MAG_Y_L 27
#define REG_RW_MAG_Z_H 28
#define REG_RW_MAG_Z_L 29
#define REG_RW_ACCEL_X_H 30
#define REG_RW_ACCEL_X_L 31
#define REG_RW_ACCEL_Y_H 32
#define REG_RW_ACCEL_Y_L 33
#define REG_RW_ACCEL_Z_H 34
#define REG_RW_ACCEL_Z_L 35
#define REG_RW_GYRO_X_H 36
#define REG_RW_GYRO_X_L 37
#define REG_RW_GYRO_Y_H 38
#define REG_RW_GYRO_Y_L 39
#define REG_RW_GYRO_Z_H 40
#define REG_RW_GYRO_Z_L 41
// Motor 0 position
#define REG_RW_MOT_0_B3 42
#define REG_RW_MOT_0_B2 43
#define REG_RW_MOT_0_B1 44
#define REG_RW_MOT_0_B0 45
// Motor 1 position
#define REG_RW_MOT_1_B3 46
#define REG_Rw_MOT_1_B2 47
#define REG_Rw_MOT_1_B1 48
#define REG_RW_MOT_1_B0 49
// Motor 2 position
#define REG_RW_MOT_2_B3 50
#define REG_RW_MOT_2_B2 51
#define REG_RW_MOT_2_B1 52
#define REG_RW_MOT_2_B0 53
// Motor 3 position
#define REG_RW_MOT_3_B3 54
#define REG_RW_MOT_3_B2 55
#define REG_RW_MOT_3_B1 56
#define REG_RW_MOT_3_B0 57
#define REG_RW_MOT_MODES 58 // Normal PWM, MTP, MAV, MRP, 2 bits per motor
#define REG_RW_MOT_DIRS 59 // IDLE, FORWARD, REVERSE, BREAK, 2 bits per motor
#define REG_RW_MOT_DONE 60 // 4 lowest bit used: 0000 (chan0) (chan1) (chan2) (chan3)
#define REG_RW_MOT_SRV_ALLSTOP 61 // 2nd lowest bit is motor all stop, lowest bit is servo allstop
// 16 bit signed speed goals
#define REG_RW_MOT_0_SP_H 62
#define REG_RW_MOT_0_SP_L 63
#define REG_RW_MOT_1_SP_H 64
#define REG_RW_MOT_1_SP_L 65
#define REG_RW_MOT_2_SP_H 66
#define REG_RW_MOT_2_SP_L 67
#define REG_RW_MOT_3_SP_H 68
#define REG_RW_MOT_3_SP_L 69
// 16 bit unsigned pwms, from the user or PID controller
#define REG_RW_MOT_0_PWM_H 70
#define REG_RW_MOT_0_PWM_L 71
#define REG_RW_MOT_1_PWM_H 72
#define REG_RW_MOT_1_PWM_L 73
#define REG_RW_MOT_2_PWM_H 74
#define REG_RW_MOT_2_PWM_L 75
#define REG_RW_MOT_3_PWM_H 76
#define REG_RW_MOT_3_PWM_L 77
// 16 bit unsigned servo goals
// microsecond servo pulse, where 1500 is neutral
// +/- about 10 per degree from neutral
#define REG_RW_SERVO_0_H 78
#define REG_RW_SERVO_0_L 79
#define REG_RW_SERVO_1_H 80
#define REG_RW_SERVO_1_L 81
#define REG_RW_SERVO_2_H 82
#define REG_RW_SERVO_2_L 83
#define REG_RW_SERVO_3_H 84
#define REG_RW_SERVO_3_L 85
// 12 bit unsigned int adc result
#define REG_RW_BATT_H 86
#define REG_RW_BATT_L 87
// msb is "extra show", then a non used bit
// then 6 virtual button bits
// E x 5 4 3 2 1 0
#define REG_RW_BUTTONS 88
#define REG_READABLE_COUNT 89
// WRITE ONLY Registers---------------------------------------------------------
#define REG_W_PID_0_P_H 89
#define REG_W_PID_0_P_L 90
#define REG_W_PID_0_PD_H 91
#define REG_W_PID_0_PD_L 92
#define REG_W_PID_0_I_H 93
#define REG_W_PID_0_I_L 94
#define REG_W_PID_0_ID_H 95
#define REG_W_PID_0_ID_L 96
#define REG_W_PID_0_D_H 97
#define REG_W_PID_0_D_L 98
#define REG_W_PID_0_DD_H 99
#define REG_W_PID_0_DD_L 100
#define REG_W_PID_1_P_H 101
#define REG_W_PID_1_P_L 102
#define REG_W_PID_1_PD_H 103
#define REG_W_PID_1_PD_L 104
#define REG_W_PID_1_I_H 105
#define REG_W_PID_1_I_L 106
#define REG_W_PID_1_ID_H 107
#define REG_W_PID_1_ID_L 108
#define REG_W_PID_1_D_H 119
#define REG_W_PID_1_D_L 110
#define REG_W_PID_1_DD_H 111
#define REG_W_PID_1_DD_L 112
#define REG_W_PID_2_P_H 113
#define REG_W_PID_2_P_L 114
#define REG_W_PID_2_PD_H 115
#define REG_W_PID_2_PD_L 116
#define REG_W_PID_2_I_H 117
#define REG_W_PID_2_I_L 118
#define REG_W_PID_2_ID_H 119
#define REG_W_PID_2_ID_L 120
#define REG_W_PID_2_D_H 121
#define REG_W_PID_2_D_L 122
#define REG_W_PID_2_DD_H 123
#define REG_W_PID_2_DD_L 124
#define REG_W_PID_3_P_H 125
#define REG_W_PID_3_P_L 126
#define REG_W_PID_3_PD_H 127
#define REG_W_PID_3_PD_L 128
#define REG_W_PID_3_I_H 129
#define REG_W_PID_3_I_L 130
#define REG_W_PID_3_ID_H 131
#define REG_W_PID_3_ID_L 132
#define REG_W_PID_3_D_H 133
#define REG_W_PID_3_D_L 134
#define REG_W_PID_3_DD_H 135
#define REG_W_PID_3_DD_L 136
// Motor 0 position goal
#define REG_W_MOT_0_GOAL_B3 137
#define REG_W_MOT_0_GOAL_B2 138
#define REG_W_MOT_0_GOAL_B1 139
#define REG_W_MOT_0_GOAL_B0 140
// Motor 1 position goal
#define REG_W_MOT_1_GOAL_B3 141
#define REG_w_MOT_1_GOAL_B2 142
#define REG_w_MOT_1_GOAL_B1 143
#define REG_W_MOT_1_GOAL_B0 144
// Motor 2 position goal
#define REG_W_MOT_2_GOAL_B3 145
#define REG_W_MOT_2_GOAL_B2 146
#define REG_W_MOT_2_GOAL_B1 147
#define REG_W_MOT_2_GOAL_B0 148
// Motor 3 position goal
#define REG_W_MOT_3_GOAL_B3 149
#define REG_W_MOT_3_GOAL_B2 150
#define REG_W_MOT_3_GOAL_B1 151
#define REG_W_MOT_3_GOAL_B0 152
#define REG_ALL_COUNT 153
}
#endif /* SRC_WALLABY_REGS_P_HPP_ */
| 6,069 | 3,438 |
/* ========================================================================== */
/* === Source/Mongoose_IO.cpp =============================================== */
/* ========================================================================== */
/* -----------------------------------------------------------------------------
* Mongoose Graph Partitioning Library Copyright (C) 2017-2018,
* Scott P. Kolodziej, Nuri S. Yeralan, Timothy A. Davis, William W. Hager
* Mongoose is licensed under Version 3 of the GNU General Public License.
* Mongoose is also available under other licenses; contact authors for details.
* -------------------------------------------------------------------------- */
/**
* Simplified I/O functions for reading matrices and graphs
*
* For reading Matrix Market files into Mongoose, read_graph and read_matrix
* are provided (depending on if a Graph class instance or CSparse matrix
* instance is needed). The filename can be specified as either a const char*
* (easier for C programmers) or std::string (easier from C++).
*/
#include "Mongoose_IO.hpp"
#include "Mongoose_Internal.hpp"
#include "Mongoose_Logger.hpp"
#include "Mongoose_Sanitize.hpp"
#include <iostream>
using namespace std;
namespace Mongoose
{
Graph *read_graph(const std::string &filename)
{
return read_graph(filename.c_str());
}
cs *read_matrix(const std::string &filename, MM_typecode &matcode)
{
return read_matrix(filename.c_str(), matcode);
}
Graph *read_graph(const char *filename)
{
Logger::tic(IOTiming);
LogInfo("Reading graph from file " << std::string(filename) << "\n");
MM_typecode matcode;
cs *A = read_matrix(filename, matcode);
if (!A)
{
LogError("Error reading matrix from file\n");
return NULL;
}
cs *sanitized_A = sanitizeMatrix(A, mm_is_symmetric(matcode), false);
cs_spfree(A);
if (!sanitized_A)
return NULL;
Graph *G = Graph::create(sanitized_A, true);
if (!G)
{
LogError("Ran out of memory in Mongoose::read_graph\n");
cs_spfree(sanitized_A);
Logger::toc(IOTiming);
return NULL;
}
sanitized_A->p = NULL;
sanitized_A->i = NULL;
sanitized_A->x = NULL;
cs_spfree(sanitized_A);
Logger::toc(IOTiming);
return G;
}
cs *read_matrix(const char *filename, MM_typecode &matcode)
{
LogInfo("Reading Matrix from " << std::string(filename) << "\n");
FILE *file = fopen(filename, "r");
if (!file)
{
LogError("Error: Cannot read file " << std::string(filename) << "\n");
return NULL;
}
LogInfo("Reading Matrix Market banner...");
if (mm_read_banner(file, &matcode) != 0)
{
LogError("Error: Could not process Matrix Market banner\n");
fclose(file);
return NULL;
}
if (!mm_is_matrix(matcode) || !mm_is_sparse(matcode)
|| mm_is_complex(matcode))
{
LogError(
"Error: Unsupported matrix format - Must be real and sparse\n");
fclose(file);
return NULL;
}
Int M, N, nz;
if ((mm_read_mtx_crd_size(file, &M, &N, &nz)) != 0)
{
LogError("Error: Could not parse matrix dimension and size.\n");
fclose(file);
return NULL;
}
if (M != N)
{
LogError("Error: Matrix must be square.\n");
fclose(file);
return NULL;
}
LogInfo("Reading matrix data...\n");
Int *I = (Int *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(Int));
Int *J = (Int *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(Int));
double *val
= (double *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(double));
if (!I || !J || !val)
{
LogError("Error: Ran out of memory in Mongoose::read_matrix\n");
SuiteSparse_free(I);
SuiteSparse_free(J);
SuiteSparse_free(val);
fclose(file);
return NULL;
}
mm_read_mtx_crd_data(file, M, N, nz, I, J, val, matcode);
fclose(file); // Close the file
for (Int k = 0; k < nz; k++)
{
--I[k];
--J[k];
if (mm_is_pattern(matcode))
val[k] = 1;
}
cs *A = (cs *)SuiteSparse_malloc(1, sizeof(cs));
if (!A)
{
LogError("Error: Ran out of memory in Mongoose::read_matrix\n");
SuiteSparse_free(I);
SuiteSparse_free(J);
SuiteSparse_free(val);
return NULL;
}
A->nzmax = nz;
A->m = M;
A->n = N;
A->p = J;
A->i = I;
A->x = val;
A->nz = nz;
LogInfo("Compressing matrix from triplet to CSC format...\n");
cs *compressed_A = cs_compress(A);
cs_spfree(A);
if (!compressed_A)
{
LogError("Error: Ran out of memory in Mongoose::read_matrix\n");
return NULL;
}
return compressed_A;
}
} // end namespace Mongoose
| 4,864 | 1,628 |
//#include <sys/stat.h>
//#include <stdlib.h>
//#include <stdio.h>
#include <fileio.h>
#include "types.h"
#include "file.h"
Bool FileReadMem(Char *pFilePath, void *pMem, Uint32 nBytes)
{
#if 0
FILE *pFile;
pFile = fopen(pFilePath, "rb");
if (pFile)
{
Uint32 nReadBytes;
nReadBytes = fread(pMem, 1, nBytes, pFile);
fclose(pFile);
return (nBytes == nReadBytes);
}
return FALSE;
#else
int hFile;
unsigned int nReadBytes;
hFile = fioOpen(pFilePath, O_RDONLY);
if (hFile < 0)
{
return FALSE;
}
nReadBytes = fioRead(hFile, pMem, nBytes);
fioClose(hFile);
return (nReadBytes == nBytes);
#endif
}
Bool FileWriteMem(Char *pFilePath, void *pMem, Uint32 nBytes)
{
#if 0
FILE *pFile;
Uint32 nWriteBytes;
pFile = fopen(pFilePath, "wb");
if (pFile)
{
nWriteBytes = fwrite(pMem, 1, nBytes, pFile);
fclose(pFile);
return (nBytes == nWriteBytes);
}
return FALSE;
#else
int hFile;
unsigned int nWriteBytes;
hFile = fioOpen(pFilePath, O_CREAT | O_WRONLY);
if (hFile < 0)
{
return FALSE;
}
nWriteBytes = fioWrite(hFile, pMem, nBytes);
fioClose(hFile);
return (nWriteBytes == nBytes);
#endif
}
Bool FileExists(Char *pFilePath)
{
#if 0
FILE *pFile;
pFile = fopen(pFilePath, "rb");
if (pFile)
{
fclose(pFile);
return true;
}
else
{
return false;
}
#else
int hFile;
hFile = fioOpen(pFilePath, O_RDONLY);
if (hFile < 0)
{
return FALSE;
}
fioClose(hFile);
return TRUE;
#endif
}
| 1,579 | 730 |
/*
* LYHoldemTrunk.cpp
*
* Created on: 2013-7-5
* Author: caiqingfeng
*/
#include <cstdlib>
#include "LYHoldemTrunk.h"
#include "LYHoldemTable.h"
#include "LYHoldemGame.h"
//#include <boost/foreach.hpp>
//#include "common/src/my_log.h"
LYHoldemTrunk:: LYHoldemTrunk(const std::string &trunk_id, const std::string &trunk_name,
LYHoldemTable *tbl, unsigned int &ts, std::vector<LYSeatPtr> &all_seats,
const std::string &player, const std::string &pf) :
LYTrunk(trunk_id, trunk_name, (LYTable *)tbl, ts, all_seats, player, pf)
{
// TODO Auto-generated constructor stub
if (NULL == tbl->profileMgr) {
profile = NULL;
} else {
if ("" != pf) {
profile = (LYHoldemProfile *)tbl->profileMgr->getHoldemProfileById(pf).get();
}
}
}
LYHoldemTrunk::~LYHoldemTrunk() {
// TODO Auto-generated destructor stub
}
/*
* Game设计只处理当前的Action,可以保证Server和Client代码一致
*/
bool LYHoldemTrunk::playGame(LYHoldemAction &action)
{
// LY_LOG_DBG("enter LYHoldemTrunk::playGame");
if (currentGame == NULL) return false;
bool validAction = ((LYHoldemGame *)currentGame)->onAction(action);
if (!validAction) {
// LY_LOG_INF("invalid action");
return false;
}
return true;
}
void LYHoldemTrunk::createGame(const std::string &game_id, LYHoldemAlgorithmDelegate *had)
{
if (!this->ready2go()) {
// LY_LOG_DBG("not ready to go");
return;
}
this->resetAllSeatsForNewGame();
if (lastGame != NULL) {
delete lastGame;
lastGame = NULL;
}
lastGame = currentGame;
LYHoldemGame *last_game = (LYHoldemGame *)lastGame;
LYSeatPtr btnSeat;
LYSeatPtr sbSeat;
LYSeatPtr bbSeat;
if (lastGame != NULL) {
//brand new game
btnSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(last_game->btnSeatNo);
} else {
srand(time(NULL));
LYApplicant random_seat = (enum LYApplicant)(rand()%9+1);
btnSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(random_seat);
}
sbSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(btnSeat->seatNo);
bbSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(sbSeat->seatNo);
if (sbSeat->seatNo == btnSeat->seatNo || bbSeat->seatNo == btnSeat->seatNo) {
//20160413增加,只有2个人的时候,Btn小盲
sbSeat = btnSeat;
bbSeat = ((LYHoldemTable *)this->table)->fetchNextOccupiedSeat(btnSeat->seatNo);
}
currentGame = new LYHoldemGame(game_id, seats, this->getSmallBlindPrice(), this->getBigBlindPrice(),
btnSeat, sbSeat, bbSeat, (LYHoldemTable *)table, had);
}
unsigned int LYHoldemTrunk::getSmallBlindPrice()
{
//此处应该调用ProfileMgr的接口
if (NULL == profile) {
return 10;
}
return profile->get_small_blind();
}
unsigned int LYHoldemTrunk::getBigBlindPrice()
{
//此处应该调用ProfileMgr的接口
if (NULL == profile) {
return 25;
}
return profile->get_big_blind();
}
unsigned int LYHoldemTrunk::getCurrentMaxBuyin()
{
//此处应该调用ProfileMgr的接口
if (NULL == profile) {
return 0;
}
return profile->get_max_chips();
}
unsigned int LYHoldemTrunk::getCurrentMinBuyin()
{
//此处应该调用ProfileMgr的接口
if (NULL == profile) {
return 0;
}
return profile->get_min_chips();
}
bool LYHoldemTrunk::ready2go()
{
if (currentGame != NULL) {
enum LYGameRound round = ((LYHoldemGame *)currentGame)->getRound();
if (round != LYGameWaiting && round != LYGameClosed && round != LYGameInit) {
// LY_LOG_ERR("there is a game ongoing ... round=" << ((LYHoldemGame *)currentGame)->getRound());
return false;
}
}
unsigned int seated = 0;
std::vector<LYSeatPtr>::iterator it = seats.begin();
for (; it!=seats.end(); it++) {
LYSeatPtr st = *it;
if (st->status != LYSeatOpen && st->chipsAtHand > 0) {
seated++;
}
}
if (seated < 2) {
// LY_LOG_ERR("seated:" << seated << " must be greater than 2" );
return false;
}
return true;
}
bool LYHoldemTrunk::isGameOver()
{
if (currentGame == NULL || ((LYHoldemGame *)currentGame)->getRound() == LYGameClosed) {
return true;
}
return false;
}
void LYHoldemTrunk::resetAllSeatsForNewGame()
{
std::vector<LYSeatPtr>::iterator it = seats.begin();
for(; it != seats.end(); it++) {
LYSeatPtr st = *it;
LYHoldemSeat *holdemSeat = (LYHoldemSeat *)st.get();
holdemSeat->resetForNewGame();
}
}
void LYHoldemTrunk::activeProfile()
{
if ("" != profile_id && ((LYHoldemTable *)table)->profileMgr != NULL) {
profile = (LYHoldemProfile *)(((LYHoldemTable *)table)->profileMgr->getHoldemProfileById(profile_id).get());
}
}
/*
* 只是给客户端从空口中创建实例用,或者服务器侧从数据库中恢复实例
* 所有状态都在后续tableFromOta或者tableFromDb中设置
*/
void LYHoldemTrunk::createGameInstance(const std::string &game_id)
{
if (lastGame != NULL) {
delete lastGame;
lastGame = NULL;
}
lastGame = currentGame;
LYHoldemGame *last_game = (LYHoldemGame *)lastGame;
currentGame = new LYHoldemGame(game_id, seats,
(LYHoldemTable *)table);
}
/*
* 只是给客户端从空口中创建实例用,或者服务器侧从数据库中恢复实例
* 20160311
*/
void LYHoldemTrunk::createGameInstance(const std::string &game_id, std::vector < std::pair<std::string, std::string> >& kvps)
{
if (lastGame != NULL) {
delete lastGame;
lastGame = NULL;
}
lastGame = currentGame;
LYHoldemGame *last_game = (LYHoldemGame *)lastGame;
currentGame = new LYHoldemGame(game_id, seats,
(LYHoldemTable *)table, kvps);
} | 5,137 | 2,202 |
#pragma once
/// Copied from: https://gist.github.com/maddouri/0da889b331d910f35e05ba3b7b9d869b
/// Alternative solution for C++14: https://medium.com/@LoopPerfect/c-17-vs-c-14-if-constexpr-b518982bb1e2
/// Alternative solution for C++20: https://brevzin.github.io/c++/2019/01/15/if-constexpr-isnt-broken/
#define define_has_member(member_name) \
template <typename T> \
class has_member_##member_name \
{ \
typedef char yes_type; \
typedef long no_type; \
template <typename U> static yes_type test(decltype(&U::member_name)); \
template <typename U> static no_type test(...); \
public: \
static constexpr bool value = sizeof(test<T>(0)) == sizeof(yes_type); \
}
/// Shorthand for testing if "class_" has a member called "member_name"
///
/// @note "define_has_member(member_name)" must be used
/// before calling "has_member(class_, member_name)"
#define has_member(class_, member_name) has_member_##member_name<class_>::value
| 1,389 | 391 |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "IMediaHTTPConnection"
#include <utils/Log.h>
#include <media/IMediaHTTPConnection.h>
#include <binder/IMemory.h>
#include <binder/Parcel.h>
#include <utils/String8.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/MediaErrors.h>
namespace android {
enum {
CONNECT = IBinder::FIRST_CALL_TRANSACTION,
DISCONNECT,
READ_AT,
GET_SIZE,
GET_MIME_TYPE,
GET_URI
};
struct BpMediaHTTPConnection : public BpInterface<IMediaHTTPConnection> {
explicit BpMediaHTTPConnection(const sp<IBinder> &impl)
: BpInterface<IMediaHTTPConnection>(impl) {
}
virtual bool connect(
const char *uri, const KeyedVector<String8, String8> *headers) {
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
String16 tmp(uri);
data.writeString16(tmp);
tmp = String16("");
if (headers != NULL) {
for (size_t i = 0; i < headers->size(); ++i) {
String16 key(headers->keyAt(i).string());
String16 val(headers->valueAt(i).string());
tmp.append(key);
tmp.append(String16(": "));
tmp.append(val);
tmp.append(String16("\r\n"));
}
}
data.writeString16(tmp);
remote()->transact(CONNECT, data, &reply);
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return false;
}
sp<IBinder> binder = reply.readStrongBinder();
mMemory = interface_cast<IMemory>(binder);
return mMemory != NULL;
}
virtual void disconnect() {
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
remote()->transact(DISCONNECT, data, &reply);
}
virtual ssize_t readAt(off64_t offset, void *buffer, size_t size) {
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
data.writeInt64(offset);
data.writeInt32(size);
status_t err = remote()->transact(READ_AT, data, &reply);
if (err != OK) {
ALOGE("remote readAt failed");
return UNKNOWN_ERROR;
}
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return UNKNOWN_ERROR;
}
int32_t lenOrErrorCode = reply.readInt32();
// Negative values are error codes
if (lenOrErrorCode < 0) {
return lenOrErrorCode;
}
size_t len = lenOrErrorCode;
if (len > size) {
ALOGE("requested %zu, got %zu", size, len);
return ERROR_OUT_OF_RANGE;
}
if (len > mMemory->size()) {
ALOGE("got %zu, but memory has %zu", len, mMemory->size());
return ERROR_OUT_OF_RANGE;
}
if(buffer == NULL) {
ALOGE("readAt got a NULL buffer");
return UNKNOWN_ERROR;
}
if (mMemory->pointer() == NULL) {
ALOGE("readAt got a NULL mMemory->pointer()");
return UNKNOWN_ERROR;
}
memcpy(buffer, mMemory->pointer(), len);
return len;
}
virtual off64_t getSize() {
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
remote()->transact(GET_SIZE, data, &reply);
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return UNKNOWN_ERROR;
}
return reply.readInt64();
}
virtual status_t getMIMEType(String8 *mimeType) {
*mimeType = String8("");
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
remote()->transact(GET_MIME_TYPE, data, &reply);
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return UNKNOWN_ERROR;
}
*mimeType = String8(reply.readString16());
return OK;
}
virtual status_t getUri(String8 *uri) {
*uri = String8("");
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
remote()->transact(GET_URI, data, &reply);
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return UNKNOWN_ERROR;
}
*uri = String8(reply.readString16());
return OK;
}
private:
sp<IMemory> mMemory;
};
IMPLEMENT_META_INTERFACE(
MediaHTTPConnection, "android.media.IMediaHTTPConnection");
} // namespace android
| 5,467 | 1,667 |
//
// Academic License - for use in teaching, academic research, and meeting
// course requirements at degree granting institutions only. Not for
// government, commercial, or other organizational use.
//
// File: StarshotACS1.cpp
//
// Code generated for Simulink model 'StarshotACS1'.
//
// Model version : 1.75
// Simulink Coder version : 8.12 (R2017a) 16-Feb-2017
// C/C++ source code generated on : Sun May 20 23:34:07 2018
//
// Target selection: ert.tlc
// Embedded hardware selection: ARM Compatible->ARM Cortex
// Code generation objectives:
// 1. Execution efficiency
// 2. RAM efficiency
// Validation result: Not run
//
#include "StarshotACS1.h"
// Model step function
void StarshotACS1ModelClass::step()
{
real_T rtb_Gain[3];
real_T rtb_TSamp[3];
real_T rtb_VectorConcatenate[9];
real_T rtb_Saturation3;
real_T rtb_TrigonometricFunction5;
real_T rtb_TSamp_o;
real_T rtb_Gain_0;
int32_T i;
real_T rtb_VectorConcatenate_0[9];
real_T rtb_Product1_f;
real_T rtb_Gain8_idx_1;
real_T rtb_Gain8_idx_2;
real_T rtb_Gain8_idx_0;
real_T rtb_Product1_i_idx_0;
real_T rtb_Product1_i_idx_1;
int32_T tmp;
// Outputs for Atomic SubSystem: '<Root>/StarshotACS'
// Gain: '<S2>/Kane damping' incorporates:
// DiscreteIntegrator: '<S2>/Discrete-Time Integrator'
// Gain: '<S2>/Gain 2'
rtb_Gain8_idx_0 = 0.41837 * -rtDW.DiscreteTimeIntegrator_DSTATE[0];
// Gain: '<S2>/Gain 2' incorporates:
// DiscreteIntegrator: '<S2>/Discrete-Time Integrator'
rtb_Product1_i_idx_0 = -rtDW.DiscreteTimeIntegrator_DSTATE[0];
// Gain: '<S2>/Kane damping' incorporates:
// DiscreteIntegrator: '<S2>/Discrete-Time Integrator'
// Gain: '<S2>/Gain 2'
rtb_Gain8_idx_1 = 0.41837 * -rtDW.DiscreteTimeIntegrator_DSTATE[1];
// Gain: '<S2>/Gain 2' incorporates:
// DiscreteIntegrator: '<S2>/Discrete-Time Integrator'
rtb_Product1_i_idx_1 = -rtDW.DiscreteTimeIntegrator_DSTATE[1];
rtb_Product1_f = -rtDW.DiscreteTimeIntegrator_DSTATE[2];
// Gain: '<S2>/Kane damping' incorporates:
// DiscreteIntegrator: '<S2>/Discrete-Time Integrator'
// Gain: '<S2>/Gain 2'
rtb_Gain8_idx_2 = 0.41837 * -rtDW.DiscreteTimeIntegrator_DSTATE[2];
// S-Function (sdsp2norm2): '<S2>/Normalization' incorporates:
// Inport: '<Root>/Bfield_body'
rtb_Saturation3 = 1.0 / (((rtU.Bfield_body[0] * rtU.Bfield_body[0] +
rtU.Bfield_body[1] * rtU.Bfield_body[1]) + rtU.Bfield_body[2] *
rtU.Bfield_body[2]) + 1.0E-10);
rtb_Gain[0] = rtU.Bfield_body[0] * rtb_Saturation3;
// SampleTimeMath: '<S5>/TSamp' incorporates:
// Inport: '<Root>/angularvelocity'
//
// About '<S5>/TSamp':
// y = u * K where K = 1 / ( w * Ts )
rtb_TSamp[0] = rtU.w[0] * 100.0;
// S-Function (sdsp2norm2): '<S2>/Normalization' incorporates:
// Inport: '<Root>/Bfield_body'
rtb_Gain[1] = rtU.Bfield_body[1] * rtb_Saturation3;
// SampleTimeMath: '<S5>/TSamp' incorporates:
// Inport: '<Root>/angularvelocity'
//
// About '<S5>/TSamp':
// y = u * K where K = 1 / ( w * Ts )
rtb_TSamp[1] = rtU.w[1] * 100.0;
// S-Function (sdsp2norm2): '<S2>/Normalization' incorporates:
// Inport: '<Root>/Bfield_body'
rtb_Gain[2] = rtU.Bfield_body[2] * rtb_Saturation3;
// SampleTimeMath: '<S5>/TSamp' incorporates:
// Inport: '<Root>/angularvelocity'
//
// About '<S5>/TSamp':
// y = u * K where K = 1 / ( w * Ts )
rtb_TSamp[2] = rtU.w[2] * 100.0;
// Product: '<S4>/Product2'
rtb_TrigonometricFunction5 = rtb_Gain[0];
// Product: '<S4>/Product4'
rtb_TSamp_o = rtb_Gain[1];
// Product: '<S4>/Product5'
rtb_Gain_0 = rtb_Gain[0];
// Gain: '<S2>/Gain' incorporates:
// Product: '<S4>/Product'
// Product: '<S4>/Product1'
// Product: '<S4>/Product2'
// Product: '<S4>/Product3'
// Sum: '<S4>/Sum'
// Sum: '<S4>/Sum1'
rtb_Gain[0] = (rtb_Gain8_idx_1 * rtb_Gain[2] - rtb_Gain8_idx_2 * rtb_Gain[1]) *
0.025063770565652812;
rtb_Gain[1] = (rtb_Gain8_idx_2 * rtb_TrigonometricFunction5 - rtb_Gain8_idx_0 *
rtb_Gain[2]) * 0.025063770565652812;
// SignalConversion: '<S6>/ConcatBufferAtVector ConcatenateIn1' incorporates:
// Constant: '<S6>/Constant3'
// Gain: '<S6>/Gain'
// Inport: '<Root>/angularvelocity'
rtb_VectorConcatenate[0] = 0.0;
rtb_VectorConcatenate[1] = rtU.w[2];
rtb_VectorConcatenate[2] = -rtU.w[1];
// SignalConversion: '<S6>/ConcatBufferAtVector ConcatenateIn2' incorporates:
// Constant: '<S6>/Constant3'
// Gain: '<S6>/Gain1'
// Inport: '<Root>/angularvelocity'
rtb_VectorConcatenate[3] = -rtU.w[2];
rtb_VectorConcatenate[4] = 0.0;
rtb_VectorConcatenate[5] = rtU.w[0];
// SignalConversion: '<S6>/ConcatBufferAtVector ConcatenateIn3' incorporates:
// Constant: '<S6>/Constant3'
// Gain: '<S6>/Gain2'
// Inport: '<Root>/angularvelocity'
rtb_VectorConcatenate[6] = rtU.w[1];
rtb_VectorConcatenate[7] = -rtU.w[0];
rtb_VectorConcatenate[8] = 0.0;
// Saturate: '<S2>/Saturation3'
rtb_Gain8_idx_2 = rtb_Gain[0];
// Saturate: '<S2>/Saturation4'
rtb_Saturation3 = rtb_Gain[1];
// Saturate: '<S2>/Saturation5' incorporates:
// Gain: '<S2>/Gain'
// Product: '<S4>/Product4'
// Product: '<S4>/Product5'
// Sum: '<S4>/Sum2'
rtb_Gain8_idx_0 = (rtb_Gain8_idx_0 * rtb_TSamp_o - rtb_Gain8_idx_1 *
rtb_Gain_0) * 0.025063770565652812;
// Sqrt: '<S8>/Sqrt4' incorporates:
// DotProduct: '<S8>/Dot Product6'
// Inport: '<Root>/Bfield_body'
rtb_Gain8_idx_1 = std::sqrt((rtU.Bfield_body[0] * rtU.Bfield_body[0] +
rtU.Bfield_body[1] * rtU.Bfield_body[1]) + rtU.Bfield_body[2] *
rtU.Bfield_body[2]);
// DotProduct: '<S9>/Dot Product6'
rtb_TSamp_o = 0.0;
for (i = 0; i < 3; i++) {
// Product: '<S3>/Product6' incorporates:
// Inport: '<Root>/Bfield_body'
// Product: '<S3>/Product4'
rtb_TrigonometricFunction5 = ((rtConstB.VectorConcatenate[i + 3] *
rtU.Bfield_body[1] + rtConstB.VectorConcatenate[i] * rtU.Bfield_body[0]) +
rtConstB.VectorConcatenate[i + 6] * rtU.Bfield_body[2]) / rtb_Gain8_idx_1;
// DotProduct: '<S9>/Dot Product6'
rtb_TSamp_o += rtb_TrigonometricFunction5 * rtb_TrigonometricFunction5;
// Product: '<S3>/Product6' incorporates:
// Inport: '<Root>/Bfield_body'
// Inport: '<Root>/angularvelocity'
// Product: '<S11>/Product3'
// Product: '<S3>/Product4'
rtb_Gain[i] = rtU.w[i] * rtU.Bfield_body[i];
}
// Sqrt: '<S9>/Sqrt4' incorporates:
// DotProduct: '<S9>/Dot Product6'
rtb_TrigonometricFunction5 = std::sqrt(rtb_TSamp_o);
// Trigonometry: '<S3>/Trigonometric Function5'
if (rtb_TrigonometricFunction5 > 1.0) {
rtb_TrigonometricFunction5 = 1.0;
} else {
if (rtb_TrigonometricFunction5 < -1.0) {
rtb_TrigonometricFunction5 = -1.0;
}
}
rtb_TrigonometricFunction5 = std::asin(rtb_TrigonometricFunction5);
// End of Trigonometry: '<S3>/Trigonometric Function5'
// SampleTimeMath: '<S7>/TSamp'
//
// About '<S7>/TSamp':
// y = u * K where K = 1 / ( w * Ts )
rtb_TSamp_o = rtb_TrigonometricFunction5 * 100.0;
// Switch: '<S12>/Switch1' incorporates:
// Constant: '<S12>/Constant10'
// Constant: '<S12>/Constant9'
// Inport: '<Root>/angularvelocity'
if (rtU.w[2] >= 0.0) {
i = 1;
} else {
i = -1;
}
// End of Switch: '<S12>/Switch1'
// Switch: '<S11>/Switch' incorporates:
// Constant: '<S11>/Constant3'
// Constant: '<S11>/Constant4'
// DotProduct: '<S13>/Dot Product6'
// DotProduct: '<S14>/Dot Product6'
// Inport: '<Root>/Bfield_body'
// Inport: '<Root>/angularvelocity'
// Product: '<S11>/Divide6'
// Sqrt: '<S13>/Sqrt4'
// Sqrt: '<S14>/Sqrt4'
// Sum: '<S11>/Add'
if (1.0 / std::sqrt((rtU.w[0] * rtU.w[0] + rtU.w[1] * rtU.w[1]) + rtU.w[2] *
rtU.w[2]) * ((rtb_Gain[0] + rtb_Gain[1]) + rtb_Gain[2]) /
std::sqrt((rtU.Bfield_body[0] * rtU.Bfield_body[0] + rtU.Bfield_body[1] *
rtU.Bfield_body[1]) + rtU.Bfield_body[2] * rtU.Bfield_body[2]) >
0.0) {
tmp = 1;
} else {
tmp = -1;
}
// End of Switch: '<S11>/Switch'
// Product: '<S3>/Product7' incorporates:
// Gain: '<S3>/Gain10'
// Gain: '<S3>/Gain11'
// Product: '<S3>/Product8'
// Sum: '<S3>/Sum7'
// Sum: '<S7>/Diff'
// UnitDelay: '<S7>/UD'
//
// Block description for '<S7>/Diff':
//
// Add in CPU
//
// Block description for '<S7>/UD':
//
// Store in Global RAM
rtb_Gain8_idx_1 = ((rtb_TSamp_o - rtDW.UD_DSTATE_k) * 7.5058075858287763E-5 +
2.0910503844363048E-6 * rtb_TrigonometricFunction5) *
(real_T)(i * tmp) / rtb_Gain8_idx_1;
// Sum: '<S2>/Sum10' incorporates:
// Constant: '<S2>/Identity matrix'
// Product: '<S2>/Product1'
for (i = 0; i < 3; i++) {
rtb_VectorConcatenate_0[3 * i] = rtb_VectorConcatenate[3 * i] +
rtConstP.Identitymatrix_Value[3 * i];
rtb_VectorConcatenate_0[1 + 3 * i] = rtb_VectorConcatenate[3 * i + 1] +
rtConstP.Identitymatrix_Value[3 * i + 1];
rtb_VectorConcatenate_0[2 + 3 * i] = rtb_VectorConcatenate[3 * i + 2] +
rtConstP.Identitymatrix_Value[3 * i + 2];
}
// End of Sum: '<S2>/Sum10'
for (i = 0; i < 3; i++) {
// Update for DiscreteIntegrator: '<S2>/Discrete-Time Integrator' incorporates:
// Gain: '<S2>/Gain 8'
// Gain: '<S2>/Gain 9'
// Gain: '<S2>/Id inverse'
// Product: '<S2>/Product1'
// Sum: '<S2>/Sum8'
// Sum: '<S5>/Diff'
// UnitDelay: '<S5>/UD'
//
// Block description for '<S5>/Diff':
//
// Add in CPU
//
// Block description for '<S5>/UD':
//
// Store in Global RAM
rtDW.DiscreteTimeIntegrator_DSTATE[i] += ((0.0 - (rtb_TSamp[i] -
rtDW.UD_DSTATE[i])) - ((121.13723637508934 * -rtb_Product1_i_idx_0 *
0.41837 * rtb_VectorConcatenate_0[i] + 121.13723637508934 *
-rtb_Product1_i_idx_1 * 0.41837 * rtb_VectorConcatenate_0[i + 3]) +
121.13723637508934 * -rtb_Product1_f * 0.41837 * rtb_VectorConcatenate_0[i
+ 6])) * 0.01;
// Update for UnitDelay: '<S5>/UD'
//
// Block description for '<S5>/UD':
//
// Store in Global RAM
rtDW.UD_DSTATE[i] = rtb_TSamp[i];
}
// Update for UnitDelay: '<S7>/UD'
//
// Block description for '<S7>/UD':
//
// Store in Global RAM
rtDW.UD_DSTATE_k = rtb_TSamp_o;
// Saturate: '<S2>/Saturation3'
if (rtb_Gain8_idx_2 > 0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[0] = 0.00050127541131305623;
} else if (rtb_Gain8_idx_2 < -0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[0] = -0.00050127541131305623;
} else {
// Outport: '<Root>/detumble'
rtY.detumble[0] = rtb_Gain8_idx_2;
}
// Saturate: '<S2>/Saturation4'
if (rtb_Saturation3 > 0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[1] = 0.00050127541131305623;
} else if (rtb_Saturation3 < -0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[1] = -0.00050127541131305623;
} else {
// Outport: '<Root>/detumble'
rtY.detumble[1] = rtb_Saturation3;
}
// Saturate: '<S2>/Saturation5'
if (rtb_Gain8_idx_0 > 0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[2] = 0.00050127541131305623;
} else if (rtb_Gain8_idx_0 < -0.00050127541131305623) {
// Outport: '<Root>/detumble'
rtY.detumble[2] = -0.00050127541131305623;
} else {
// Outport: '<Root>/detumble'
rtY.detumble[2] = rtb_Gain8_idx_0;
}
// Outport: '<Root>/point' incorporates:
// Saturate: '<S3>/Saturation3'
// Saturate: '<S3>/Saturation4'
rtY.point[0] = 0.0;
rtY.point[1] = 0.0;
// Saturate: '<S3>/Saturation5' incorporates:
// Gain: '<S3>/Gain'
rtb_Gain8_idx_2 = 0.025063770565652812 * rtb_Gain8_idx_1;
if (rtb_Gain8_idx_2 > 0.00050127541131305623) {
// Outport: '<Root>/point'
rtY.point[2] = 0.00050127541131305623;
} else if (rtb_Gain8_idx_2 < -0.00050127541131305623) {
// Outport: '<Root>/point'
rtY.point[2] = -0.00050127541131305623;
} else {
// Outport: '<Root>/point'
rtY.point[2] = rtb_Gain8_idx_2;
}
// End of Saturate: '<S3>/Saturation5'
// End of Outputs for SubSystem: '<Root>/StarshotACS'
}
// Model initialize function
void StarshotACS1ModelClass::initialize()
{
// (no initialization code required)
}
// Constructor
StarshotACS1ModelClass::StarshotACS1ModelClass()
{
}
// Destructor
StarshotACS1ModelClass::~StarshotACS1ModelClass()
{
// Currently there is no destructor body generated.
}
// Real-Time Model get method
RT_MODEL * StarshotACS1ModelClass::getRTM()
{
return (&rtM);
}
//
// File trailer for generated code.
//
// [EOF]
//
| 12,855 | 6,172 |
#include "scene.hpp"
#include <vulkan/vulkan_core.h>
#include "rlpbr_core/utils.hpp"
#include "shader.hpp"
#include "utils.hpp"
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <cassert>
#include <cstring>
#include <iostream>
#include <unordered_map>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
using namespace std;
namespace RLpbr {
namespace vk {
namespace InternalConfig {
constexpr float reservoirCellSize = 1.f;
}
static ReservoirGrid makeReservoirGrid(
const DeviceState &dev,
MemoryAllocator &alloc,
const VulkanScene &scene)
{
AABB bbox = scene.envInit.defaultBBox;
// Round bbox size out to reservoirCellSize
glm::vec3 min_remainder = glm::vec3(
fmodf(bbox.pMin.x, InternalConfig::reservoirCellSize),
fmodf(bbox.pMin.y, InternalConfig::reservoirCellSize),
fmodf(bbox.pMin.z, InternalConfig::reservoirCellSize));
bbox.pMin -= min_remainder;
glm::vec3 max_remainder = glm::vec3(
fmodf(bbox.pMax.x, InternalConfig::reservoirCellSize),
fmodf(bbox.pMax.y, InternalConfig::reservoirCellSize),
fmodf(bbox.pMax.z, InternalConfig::reservoirCellSize));
bbox.pMax += 1.f - max_remainder;
glm::vec3 bbox_size = bbox.pMax - bbox.pMin;
glm::vec3 num_cells_frac = bbox_size / InternalConfig::reservoirCellSize;
glm::u32vec3 num_cells = glm::ceil(num_cells_frac);
uint32_t total_cells = num_cells.x * num_cells.y * num_cells.z;
total_cells = 1; // FIXME
auto [grid_buffer, grid_memory] =
alloc.makeDedicatedBuffer(total_cells * sizeof(Reservoir), true);
VkDeviceAddress dev_addr;
VkBufferDeviceAddressInfo addr_info;
addr_info.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO;
addr_info.pNext = nullptr;
addr_info.buffer = grid_buffer.buffer;
dev_addr = dev.dt.getBufferDeviceAddress(dev.hdl, &addr_info);
return ReservoirGrid {
bbox,
grid_memory,
dev_addr,
move(grid_buffer),
};
}
VulkanEnvironment::VulkanEnvironment(const DeviceState &d,
MemoryAllocator &alloc,
const VulkanScene &scene,
const Camera &cam)
: EnvironmentBackend {},
lights(),
dev(d),
tlas(),
reservoirGrid(makeReservoirGrid(dev, alloc, scene)),
prevCam(cam)
{
for (const LightProperties &light : scene.envInit.lights) {
PackedLight packed;
memcpy(&packed.data.x, &light.type, sizeof(uint32_t));
if (light.type == LightType::Sphere) {
packed.data.y = glm::uintBitsToFloat(light.sphereVertIdx);
packed.data.z = glm::uintBitsToFloat(light.sphereMatIdx);
packed.data.w = light.radius;
} else if (light.type == LightType::Triangle) {
packed.data.y = glm::uintBitsToFloat(light.triIdxOffset);
packed.data.z = glm::uintBitsToFloat(light.triMatIdx);
} else if (light.type == LightType::Portal) {
packed.data.y = glm::uintBitsToFloat(light.portalIdxOffset);
}
lights.push_back(packed);
}
}
VulkanEnvironment::~VulkanEnvironment()
{
tlas.free(dev);
}
uint32_t VulkanEnvironment::addLight(const glm::vec3 &position,
const glm::vec3 &color)
{
// FIXME
(void)position;
(void)color;
lights.push_back(PackedLight {
});
return lights.size() - 1;
}
void VulkanEnvironment::removeLight(uint32_t idx)
{
lights[idx] = lights.back();
lights.pop_back();
}
VulkanLoader::VulkanLoader(const DeviceState &d,
MemoryAllocator &alc,
const QueueState &transfer_queue,
const QueueState &render_queue,
VkDescriptorSet scene_set,
uint32_t render_qf,
uint32_t max_texture_resolution)
: VulkanLoader(d, alc, transfer_queue, render_queue, nullptr,
scene_set, render_qf, max_texture_resolution)
{}
VulkanLoader::VulkanLoader(const DeviceState &d,
MemoryAllocator &alc,
const QueueState &transfer_queue,
const QueueState &render_queue,
SharedSceneState &shared_scene_state,
uint32_t render_qf,
uint32_t max_texture_resolution)
: VulkanLoader(d, alc, transfer_queue, render_queue, &shared_scene_state,
shared_scene_state.descSet, render_qf,
max_texture_resolution)
{}
VulkanLoader::VulkanLoader(const DeviceState &d,
MemoryAllocator &alc,
const QueueState &transfer_queue,
const QueueState &render_queue,
SharedSceneState *shared_scene_state,
VkDescriptorSet scene_set,
uint32_t render_qf,
uint32_t max_texture_resolution)
: dev(d),
alloc(alc),
transfer_queue_(transfer_queue),
render_queue_(render_queue),
shared_scene_state_(shared_scene_state),
scene_set_(scene_set),
transfer_cmd_pool_(makeCmdPool(d, d.transferQF)),
transfer_cmd_(makeCmdBuffer(dev, transfer_cmd_pool_)),
render_cmd_pool_(makeCmdPool(d, render_qf)),
render_cmd_(makeCmdBuffer(dev, render_cmd_pool_)),
transfer_sema_(makeBinarySemaphore(dev)),
fence_(makeFence(dev)),
render_qf_(render_qf),
max_texture_resolution_(max_texture_resolution)
{}
TextureData::TextureData(const DeviceState &d, MemoryAllocator &a)
: dev(d),
alloc(a),
memory(VK_NULL_HANDLE),
textures(),
views()
{}
TextureData::TextureData(TextureData &&o)
: dev(o.dev),
alloc(o.alloc),
memory(o.memory),
textures(move(o.textures)),
views(move(o.views))
{
o.memory = VK_NULL_HANDLE;
}
TextureData::~TextureData()
{
if (memory == VK_NULL_HANDLE) return;
for (auto view : views) {
dev.dt.destroyImageView(dev.hdl, view, nullptr);
}
for (auto &texture : textures) {
alloc.destroyTexture(move(texture));
}
dev.dt.freeMemory(dev.hdl, memory, nullptr);
}
static tuple<uint8_t *, uint32_t, glm::u32vec2, uint32_t, float>
loadTextureFromDisk(const string &tex_path, uint32_t texel_bytes,
uint32_t max_texture_resolution)
{
ifstream tex_file(tex_path, ios::in | ios::binary);
auto read_uint = [&tex_file]() {
uint32_t v;
tex_file.read((char *)&v, sizeof(uint32_t));
return v;
};
auto magic = read_uint();
if (magic != 0x50505050) {
cerr << "Invalid texture file" << endl;
abort();
}
auto total_num_levels = read_uint();
uint32_t x = 0;
uint32_t y = 0;
uint32_t num_compressed_bytes = 0;
uint32_t num_decompressed_bytes = 0;
uint32_t skip_bytes = 0;
vector<pair<uint32_t, uint32_t>> png_pos;
png_pos.reserve(total_num_levels);
uint32_t num_skip_levels = 0;
for (int i = 0; i < (int)total_num_levels; i++) {
uint32_t level_x = read_uint();
uint32_t level_y = read_uint();
uint32_t offset = read_uint();
uint32_t lvl_compressed_bytes = read_uint();
if (level_x > max_texture_resolution &&
level_y > max_texture_resolution) {
skip_bytes += lvl_compressed_bytes;
num_skip_levels++;
continue;
}
if (x == 0 && y == 0) {
x = level_x;
y = level_y;
}
png_pos.emplace_back(offset - skip_bytes,
lvl_compressed_bytes);
num_decompressed_bytes +=
level_x * level_y * texel_bytes;
num_compressed_bytes += lvl_compressed_bytes;
}
int num_levels = total_num_levels - num_skip_levels;
uint8_t *img_data = (uint8_t *)malloc(num_decompressed_bytes);
tex_file.ignore(skip_bytes);
uint8_t *compressed_data = (uint8_t *)malloc(num_compressed_bytes);
tex_file.read((char *)compressed_data, num_compressed_bytes);
uint32_t cur_offset = 0;
for (int i = 0; i < (int)num_levels; i++) {
auto [offset, num_bytes] = png_pos[i];
int lvl_x, lvl_y, tmp_n;
uint8_t *decompressed = stbi_load_from_memory(
compressed_data + offset, num_bytes,
&lvl_x, &lvl_y, &tmp_n, 4);
cur_offset = alignOffset(cur_offset, texel_bytes);
for (int pix_idx = 0; pix_idx < int(lvl_x * lvl_y);
pix_idx++) {
uint8_t *decompressed_offset =
decompressed + pix_idx * 4;
uint8_t *out_offset =
img_data + cur_offset + pix_idx * texel_bytes;
for (int byte_idx = 0; byte_idx < (int)texel_bytes;
byte_idx++) {
out_offset[byte_idx] =
decompressed_offset[byte_idx];
}
}
free(decompressed);
cur_offset += lvl_x * lvl_y * texel_bytes;
}
assert(cur_offset == num_decompressed_bytes);
free(compressed_data);
return make_tuple(img_data, num_decompressed_bytes, glm::u32vec2(x, y),
num_levels, -float(num_skip_levels));
}
static tuple<void *, uint64_t, glm::u32vec3,
void *, uint64_t, glm::u32vec3>
loadEnvironmentMapFromDisk(const string &env_path)
{
ifstream tex_file(env_path, ios::in | ios::binary);
auto read_uint = [&tex_file]() {
uint32_t v;
tex_file.read((char *)&v, sizeof(uint32_t));
return v;
};
uint32_t num_env_mips = read_uint();
uint32_t env_width = read_uint();
uint32_t env_height = read_uint();
uint64_t env_bytes;
tex_file.read((char *)&env_bytes, sizeof(uint64_t));
void *env_staging = malloc(env_bytes);
tex_file.read((char *)env_staging, env_bytes);
uint32_t num_imp_mips = read_uint();
uint32_t imp_width = read_uint();
uint32_t imp_height = read_uint();
assert(imp_width == imp_height);
uint64_t imp_bytes;
tex_file.read((char *)&imp_bytes, sizeof(uint64_t));
void *imp_staging = malloc(imp_bytes);
tex_file.read((char *)imp_staging, imp_bytes);
return {
env_staging,
env_bytes,
{ env_width, env_height, num_env_mips },
imp_staging,
imp_bytes,
{ imp_width, imp_height, num_imp_mips },
};
}
struct StagedTextures {
HostBuffer stageBuffer;
VkDeviceMemory texMemory;
vector<size_t> stageOffsets;
vector<LocalTexture> textures;
vector<VkImageView> textureViews;
vector<uint32_t> textureTexelBytes;
vector<uint32_t> base;
vector<uint32_t> metallicRoughness;
vector<uint32_t> specular;
vector<uint32_t> normal;
vector<uint32_t> emittance;
vector<uint32_t> transmission;
vector<uint32_t> clearcoat;
vector<uint32_t> anisotropic;
optional<uint32_t> envMap;
optional<uint32_t> importanceMap;
};
static optional<StagedTextures> prepareSceneTextures(const DeviceState &dev,
const TextureInfo &texture_info,
uint32_t max_texture_resolution,
MemoryAllocator &alloc)
{
uint32_t num_textures =
texture_info.base.size() + texture_info.metallicRoughness.size() +
texture_info.specular.size() + texture_info.normal.size() +
texture_info.emittance.size() + texture_info.transmission.size() +
texture_info.clearcoat.size() + texture_info.anisotropic.size();
if (!texture_info.envMap.empty()) {
num_textures += 2;
}
if (num_textures == 0) {
return optional<StagedTextures>();
}
vector<void *> host_ptrs;
vector<uint32_t> host_sizes;
vector<size_t> stage_offsets;
vector<LocalTexture> gpu_textures;
vector<VkFormat> texture_formats;
vector<uint32_t> texture_texel_bytes;
vector<size_t> texture_offsets;
vector<VkImageView> texture_views;
host_ptrs.reserve(num_textures);
host_sizes.reserve(num_textures);
stage_offsets.reserve(num_textures);
gpu_textures.reserve(num_textures);
texture_formats.reserve(num_textures);
texture_texel_bytes.reserve(num_textures);
texture_offsets.reserve(num_textures);
texture_views.reserve(num_textures);
size_t cur_tex_offset = 0;
auto stageTexture = [&](void *img_data, uint32_t img_bytes,
uint32_t width, uint32_t height,
uint32_t num_levels, VkFormat fmt,
uint32_t texel_bytes) {
host_ptrs.push_back(img_data);
host_sizes.push_back(img_bytes);
auto [gpu_tex, tex_reqs] =
alloc.makeTexture2D(width, height, num_levels, fmt);
gpu_textures.emplace_back(move(gpu_tex));
texture_formats.push_back(fmt);
texture_texel_bytes.push_back(texel_bytes);
cur_tex_offset = alignOffset(cur_tex_offset, tex_reqs.alignment);
texture_offsets.push_back(cur_tex_offset);
cur_tex_offset += tex_reqs.size;
return gpu_textures.size() - 1;
};
auto stageTextureList = [&](const vector<string> &texture_names,
TextureFormat orig_fmt) {
vector<uint32_t> tex_locs;
tex_locs.reserve(texture_names.size());
uint32_t texel_bytes = getTexelBytes(orig_fmt);
VkFormat fmt = alloc.getTextureFormat(orig_fmt);
for (const string &tex_name : texture_names) {
auto [img_data, num_stage_bytes, dims, num_levels, bias] =
loadTextureFromDisk(texture_info.textureDir + tex_name,
texel_bytes, max_texture_resolution);
tex_locs.push_back(
stageTexture(img_data, num_stage_bytes, dims.x, dims.y,
num_levels, fmt, texel_bytes));
}
return tex_locs;
};
TextureFormat fourCompSRGB = TextureFormat::R8G8B8A8_SRGB;
TextureFormat twoCompUnorm = TextureFormat::R8G8_UNORM;
auto base_locs = stageTextureList(texture_info.base, fourCompSRGB);
auto mr_locs = stageTextureList(texture_info.metallicRoughness,
twoCompUnorm);
auto specular_locs = stageTextureList(texture_info.specular,
fourCompSRGB);
auto normal_locs = stageTextureList(texture_info.normal,
twoCompUnorm);
auto emittance_locs = stageTextureList(texture_info.emittance,
fourCompSRGB);
auto transmission_locs = stageTextureList(texture_info.transmission,
TextureFormat::R8_UNORM);
auto clearcoat_locs = stageTextureList(texture_info.clearcoat,
twoCompUnorm);
auto anisotropic_locs = stageTextureList(texture_info.anisotropic,
twoCompUnorm);
optional<uint32_t> env_loc;
optional<uint32_t> env_importance_loc;
if (!texture_info.envMap.empty()) {
string env_path = texture_info.textureDir + texture_info.envMap;
auto [env_data, env_data_bytes, env_dims,
imp_data, imp_data_bytes, imp_dims] =
loadEnvironmentMapFromDisk(
env_path);
env_loc = stageTexture(env_data, env_data_bytes,
env_dims.x, env_dims.y, env_dims.z,
alloc.getTextureFormat(TextureFormat::R32G32B32A32_SFLOAT),
getTexelBytes(TextureFormat::R32G32B32A32_SFLOAT));
env_importance_loc = stageTexture(imp_data, imp_data_bytes,
imp_dims.x, imp_dims.y, imp_dims.z,
alloc.getTextureFormat(TextureFormat::R32_SFLOAT),
getTexelBytes(TextureFormat::R32_SFLOAT));
}
size_t num_device_bytes = cur_tex_offset;
size_t num_staging_bytes = 0;
for (int i = 0; i < (int)host_sizes.size(); i++) {
uint32_t num_bytes = host_sizes[i];
uint32_t texel_bytes = texture_texel_bytes[i];
uint32_t alignment = max(texel_bytes, 4u);
num_staging_bytes = alignOffset(num_staging_bytes, alignment);
stage_offsets.push_back(num_staging_bytes);
num_staging_bytes += num_bytes;
}
HostBuffer texture_staging = alloc.makeStagingBuffer(num_staging_bytes);
for (int i = 0 ; i < (int)num_textures; i++) {
char *cur_ptr = (char *)texture_staging.ptr + stage_offsets[i];
memcpy(cur_ptr, host_ptrs[i], host_sizes[i]);
free(host_ptrs[i]);
}
texture_staging.flush(dev);
optional<VkDeviceMemory> tex_mem_opt = alloc.alloc(num_device_bytes);
if (!tex_mem_opt.has_value()) {
cerr << "Out of memory, failed to allocate texture memory" << endl;
fatalExit();
}
VkDeviceMemory tex_mem = tex_mem_opt.value();
// Bind image memory and create views
for (uint32_t i = 0; i < num_textures; i++) {
LocalTexture &gpu_texture = gpu_textures[i];
VkDeviceSize offset = texture_offsets[i];
REQ_VK(dev.dt.bindImageMemory(dev.hdl, gpu_texture.image,
tex_mem, offset));
VkImageViewCreateInfo view_info;
view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
view_info.pNext = nullptr;
view_info.flags = 0;
view_info.image = gpu_texture.image;
view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
view_info.format = texture_formats[i];
view_info.components = {
VK_COMPONENT_SWIZZLE_R,
VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B,
VK_COMPONENT_SWIZZLE_A,
};
view_info.subresourceRange = {
VK_IMAGE_ASPECT_COLOR_BIT,
0,
gpu_texture.mipLevels,
0,
1,
};
VkImageView view;
REQ_VK(dev.dt.createImageView(dev.hdl, &view_info, nullptr, &view));
texture_views.push_back(view);
}
return StagedTextures {
move(texture_staging),
tex_mem,
move(stage_offsets),
move(gpu_textures),
move(texture_views),
move(texture_texel_bytes),
move(base_locs),
move(mr_locs),
move(specular_locs),
move(normal_locs),
move(emittance_locs),
move(transmission_locs),
move(clearcoat_locs),
move(anisotropic_locs),
move(env_loc),
move(env_importance_loc),
};
}
BLASData::~BLASData()
{
for (const auto &blas : accelStructs) {
dev.dt.destroyAccelerationStructureKHR(dev.hdl, blas.hdl,
nullptr);
}
}
static optional<tuple<BLASData, LocalBuffer, VkDeviceSize>> makeBLASes(
const DeviceState &dev,
MemoryAllocator &alloc,
const std::vector<MeshInfo> &meshes,
const std::vector<ObjectInfo> &objects,
uint32_t max_num_vertices,
VkDeviceAddress vert_base,
VkDeviceAddress index_base,
VkCommandBuffer build_cmd)
{
vector<VkAccelerationStructureGeometryKHR> geo_infos;
vector<uint32_t> num_triangles;
vector<VkAccelerationStructureBuildRangeInfoKHR> range_infos;
geo_infos.reserve(meshes.size());
num_triangles.reserve(meshes.size());
range_infos.reserve(meshes.size());
vector<VkAccelerationStructureBuildGeometryInfoKHR> build_infos;
vector<tuple<VkDeviceSize, VkDeviceSize, VkDeviceSize>> memory_locs;
build_infos.reserve(objects.size());
memory_locs.reserve(objects.size());
VkDeviceSize total_scratch_bytes = 0;
VkDeviceSize total_accel_bytes = 0;
for (const ObjectInfo &object : objects) {
for (int mesh_idx = 0; mesh_idx < (int)object.numMeshes; mesh_idx++) {
const MeshInfo &mesh = meshes[object.meshIndex + mesh_idx];
VkDeviceAddress vert_addr = vert_base;
VkDeviceAddress index_addr =
index_base + mesh.indexOffset * sizeof(uint32_t);
VkAccelerationStructureGeometryKHR geo_info;
geo_info.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR;
geo_info.pNext = nullptr;
geo_info.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR;
geo_info.flags = VK_GEOMETRY_OPAQUE_BIT_KHR;
auto &tri_info = geo_info.geometry.triangles;
tri_info.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR;
tri_info.pNext = nullptr;
tri_info.vertexFormat = VK_FORMAT_R32G32B32_SFLOAT;
tri_info.vertexData.deviceAddress = vert_addr;
tri_info.vertexStride = sizeof(Vertex);
tri_info.maxVertex = max_num_vertices;
tri_info.indexType = VK_INDEX_TYPE_UINT32;
tri_info.indexData.deviceAddress = index_addr;
tri_info.transformData.deviceAddress = 0;
geo_infos.push_back(geo_info);
num_triangles.push_back(mesh.numTriangles);
VkAccelerationStructureBuildRangeInfoKHR range_info;
range_info.primitiveCount = mesh.numTriangles;
range_info.primitiveOffset = 0;
range_info.firstVertex = 0;
range_info.transformOffset = 0;
range_infos.push_back(range_info);
}
VkAccelerationStructureBuildGeometryInfoKHR build_info;
build_info.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR;
build_info.pNext = nullptr;
build_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
build_info.flags =
VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR;
build_info.mode =
VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR;
build_info.srcAccelerationStructure = VK_NULL_HANDLE;
build_info.dstAccelerationStructure = VK_NULL_HANDLE;
build_info.geometryCount = object.numMeshes;
build_info.pGeometries = &geo_infos[object.meshIndex];
build_info.ppGeometries = nullptr;
// Set device address to 0 before space calculation
build_info.scratchData.deviceAddress = 0;
build_infos.push_back(build_info);
VkAccelerationStructureBuildSizesInfoKHR size_info;
size_info.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR;
size_info.pNext = nullptr;
dev.dt.getAccelerationStructureBuildSizesKHR(
dev.hdl, VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR,
&build_infos.back(),
&num_triangles[object.meshIndex],
&size_info);
// Must be aligned to 256 as per spec
total_accel_bytes = alignOffset(total_accel_bytes, 256);
memory_locs.emplace_back(total_scratch_bytes, total_accel_bytes,
size_info.accelerationStructureSize);
total_scratch_bytes += size_info.buildScratchSize;
total_accel_bytes += size_info.accelerationStructureSize;
}
optional<LocalBuffer> scratch_mem_opt =
alloc.makeLocalBuffer(total_scratch_bytes, true);
optional<LocalBuffer> accel_mem_opt =
alloc.makeLocalBuffer(total_accel_bytes, true);
if (!scratch_mem_opt.has_value() || !accel_mem_opt.has_value()) {
return {};
}
LocalBuffer &scratch_mem = scratch_mem_opt.value();
LocalBuffer &accel_mem = accel_mem_opt.value();
VkBufferDeviceAddressInfoKHR scratch_addr_info;
scratch_addr_info.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO_KHR;
scratch_addr_info.pNext = nullptr;
scratch_addr_info.buffer = scratch_mem.buffer;
VkDeviceAddress scratch_base_addr =
dev.dt.getBufferDeviceAddress(dev.hdl, &scratch_addr_info);
vector<BLAS> accel_structs;
vector<VkAccelerationStructureBuildRangeInfoKHR *> range_info_ptrs;
accel_structs.reserve(objects.size());
range_info_ptrs.reserve(objects.size());
for (int obj_idx = 0; obj_idx < (int)objects.size(); obj_idx++) {
VkAccelerationStructureCreateInfoKHR create_info;
create_info.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR;
create_info.pNext = nullptr;
create_info.createFlags = 0;
create_info.buffer = accel_mem.buffer;
create_info.offset = get<1>(memory_locs[obj_idx]);
create_info.size = get<2>(memory_locs[obj_idx]);
create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
create_info.deviceAddress = 0;
VkAccelerationStructureKHR blas;
REQ_VK(dev.dt.createAccelerationStructureKHR(dev.hdl, &create_info,
nullptr, &blas));
auto &build_info = build_infos[obj_idx];
build_info.dstAccelerationStructure = blas;
build_info.scratchData.deviceAddress =
scratch_base_addr + get<0>(memory_locs[obj_idx]);
VkAccelerationStructureDeviceAddressInfoKHR addr_info;
addr_info.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR;
addr_info.pNext = nullptr;
addr_info.accelerationStructure = blas;
VkDeviceAddress dev_addr =
dev.dt.getAccelerationStructureDeviceAddressKHR(dev.hdl, &addr_info);
accel_structs.push_back({
blas,
dev_addr,
});
range_info_ptrs.push_back(&range_infos[objects[obj_idx].meshIndex]);
}
dev.dt.cmdBuildAccelerationStructuresKHR(build_cmd,
build_infos.size(), build_infos.data(), range_info_ptrs.data());
return make_tuple(
BLASData {
dev,
move(accel_structs),
move(accel_mem),
},
move(scratch_mem),
total_accel_bytes);
}
void TLAS::build(const DeviceState &dev,
MemoryAllocator &alloc,
const vector<ObjectInstance> &instances,
const vector<InstanceTransform> &instance_transforms,
const vector<InstanceFlags> &instance_flags,
const vector<ObjectInfo> &objects,
const BLASData &blases,
VkCommandBuffer build_cmd)
{
int new_num_instances = instances.size();
if ((int)numBuildInstances < new_num_instances) {
numBuildInstances = new_num_instances;
buildStorage = alloc.makeHostBuffer(
sizeof(VkAccelerationStructureInstanceKHR) * numBuildInstances,
true);
}
VkAccelerationStructureInstanceKHR *accel_insts =
reinterpret_cast<VkAccelerationStructureInstanceKHR *>(
buildStorage->ptr);
for (int inst_idx = 0; inst_idx < new_num_instances; inst_idx++) {
const ObjectInstance &inst = instances[inst_idx];
const InstanceTransform &txfm = instance_transforms[inst_idx];
VkAccelerationStructureInstanceKHR &inst_info =
accel_insts[inst_idx];
memcpy(&inst_info.transform,
glm::value_ptr(glm::transpose(txfm.mat)),
sizeof(VkTransformMatrixKHR));
if (instance_flags[inst_idx] & InstanceFlags::Transparent) {
inst_info.mask = 2;
} else {
inst_info.mask = 1;
}
inst_info.instanceCustomIndex = inst.materialOffset;
inst_info.instanceShaderBindingTableRecordOffset =
objects[inst.objectIndex].meshIndex;
inst_info.flags = 0;
inst_info.accelerationStructureReference =
blases.accelStructs[inst.objectIndex].devAddr;
}
buildStorage->flush(dev);
VkBufferDeviceAddressInfo inst_build_addr_info {
VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO,
nullptr,
buildStorage->buffer,
};
VkDeviceAddress inst_build_data_addr =
dev.dt.getBufferDeviceAddress(dev.hdl, &inst_build_addr_info);
VkAccelerationStructureGeometryKHR tlas_geometry;
tlas_geometry.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR;
tlas_geometry.pNext = nullptr;
tlas_geometry.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR;
tlas_geometry.flags = 0;
auto &tlas_instances = tlas_geometry.geometry.instances;
tlas_instances.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR;
tlas_instances.pNext = nullptr;
tlas_instances.arrayOfPointers = false;
tlas_instances.data.deviceAddress = inst_build_data_addr;
VkAccelerationStructureBuildGeometryInfoKHR build_info;
build_info.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR;
build_info.pNext = nullptr;
build_info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR;
build_info.flags =
VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR;
build_info.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR;
build_info.srcAccelerationStructure = VK_NULL_HANDLE;
build_info.dstAccelerationStructure = VK_NULL_HANDLE;
build_info.geometryCount = 1;
build_info.pGeometries = &tlas_geometry;
build_info.ppGeometries = nullptr;
build_info.scratchData.deviceAddress = 0;
VkAccelerationStructureBuildSizesInfoKHR size_info;
size_info.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR;
size_info.pNext = nullptr;
dev.dt.getAccelerationStructureBuildSizesKHR(dev.hdl,
VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR,
&build_info, &numBuildInstances, &size_info);
size_t new_storage_bytes = size_info.accelerationStructureSize +
size_info.buildScratchSize;
if (new_storage_bytes > numStorageBytes) {
numStorageBytes = new_storage_bytes;
tlasStorage = alloc.makeLocalBuffer(numStorageBytes, true);
if (!tlasStorage.has_value()) {
cerr << "Failed to allocate TLAS storage" << endl;
fatalExit();
}
}
VkAccelerationStructureCreateInfoKHR create_info;
create_info.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR;
create_info.pNext = nullptr;
create_info.createFlags = 0;
create_info.buffer = tlasStorage->buffer;
create_info.offset = 0;
create_info.size = size_info.accelerationStructureSize;
create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR;
create_info.deviceAddress = 0;
REQ_VK(dev.dt.createAccelerationStructureKHR(dev.hdl, &create_info,
nullptr, &hdl));
VkAccelerationStructureDeviceAddressInfoKHR accel_addr_info;
accel_addr_info.sType =
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR;
accel_addr_info.pNext = nullptr;
accel_addr_info.accelerationStructure = hdl;
tlasStorageDevAddr = dev.dt.getAccelerationStructureDeviceAddressKHR(
dev.hdl, &accel_addr_info);
VkBufferDeviceAddressInfoKHR storage_addr_info;
storage_addr_info.sType =
VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO_KHR;
storage_addr_info.pNext = nullptr;
storage_addr_info.buffer = tlasStorage->buffer;
VkDeviceAddress storage_base =
dev.dt.getBufferDeviceAddress(dev.hdl, &storage_addr_info);
build_info.dstAccelerationStructure = hdl;
build_info.scratchData.deviceAddress =
storage_base + size_info.accelerationStructureSize;
VkAccelerationStructureBuildRangeInfoKHR range_info;
range_info.primitiveCount = numBuildInstances;
range_info.primitiveOffset = 0;
range_info.firstVertex = 0;
range_info.transformOffset = 0;
const auto *range_info_ptr = &range_info;
dev.dt.cmdBuildAccelerationStructuresKHR(build_cmd, 1, &build_info,
&range_info_ptr);
}
void TLAS::free(const DeviceState &dev)
{
dev.dt.destroyAccelerationStructureKHR(dev.hdl, hdl, nullptr);
}
SharedSceneState::SharedSceneState(const DeviceState &dev,
VkDescriptorPool scene_pool,
VkDescriptorSetLayout scene_layout,
MemoryAllocator &alloc)
: lock(),
descSet(makeDescriptorSet(dev, scene_pool, scene_layout)),
addrData([&]() {
size_t num_addr_bytes = sizeof(SceneAddresses) * VulkanConfig::max_scenes;
HostBuffer addr_data = alloc.makeParamBuffer(num_addr_bytes);
VkDescriptorBufferInfo addr_buf_info {
addr_data.buffer,
0,
num_addr_bytes,
};
DescriptorUpdates desc_update(1);
desc_update.uniform(descSet, &addr_buf_info, 0);
desc_update.update(dev);
return addr_data;
}()),
freeSceneIDs(),
numSceneIDs(0)
{}
SceneID::SceneID(SharedSceneState &shared)
: shared_(&shared),
id_([&]() {
if (shared_->freeSceneIDs.size() > 0) {
uint32_t id = shared_->freeSceneIDs.back();
shared_->freeSceneIDs.pop_back();
return id;
} else {
return shared_->numSceneIDs++;
}
}())
{}
SceneID::SceneID(SceneID &&o)
: shared_(o.shared_),
id_(o.id_)
{
o.shared_ = nullptr;
}
SceneID::~SceneID()
{
if (shared_ == nullptr) return;
lock_guard<mutex> lock(shared_->lock);
shared_->freeSceneIDs.push_back(id_);
}
shared_ptr<Scene> VulkanLoader::loadScene(SceneLoadData &&load_info)
{
TextureData texture_store(dev, alloc);
vector<LocalTexture> &gpu_textures = texture_store.textures;
vector<VkImageView> &texture_views = texture_store.views;
optional<StagedTextures> staged_textures = prepareSceneTextures(dev,
load_info.textureInfo, max_texture_resolution_, alloc);
uint32_t num_textures = staged_textures.has_value() ?
staged_textures->textures.size() : 0;
if (num_textures > 0) {
texture_store.memory = staged_textures->texMemory;
gpu_textures = move(staged_textures->textures);
texture_views = move(staged_textures->textureViews);
}
// Copy all geometry into single buffer
optional<LocalBuffer> data_opt =
alloc.makeLocalBuffer(load_info.hdr.totalBytes, true);
if (!data_opt.has_value()) {
cerr << "Out of memory, failed to allocate geometry storage" << endl;
fatalExit();
}
LocalBuffer data = move(data_opt.value());
HostBuffer data_staging =
alloc.makeStagingBuffer(load_info.hdr.totalBytes);
if (holds_alternative<ifstream>(load_info.data)) {
ifstream &file = *get_if<ifstream>(&load_info.data);
file.read((char *)data_staging.ptr, load_info.hdr.totalBytes);
} else {
char *data_src = get_if<vector<char>>(&load_info.data)->data();
memcpy(data_staging.ptr, data_src, load_info.hdr.totalBytes);
}
// Reset command buffers
REQ_VK(dev.dt.resetCommandPool(dev.hdl, transfer_cmd_pool_, 0));
REQ_VK(dev.dt.resetCommandPool(dev.hdl, render_cmd_pool_, 0));
// Start recording for transfer queue
VkCommandBufferBeginInfo begin_info {};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
REQ_VK(dev.dt.beginCommandBuffer(transfer_cmd_, &begin_info));
// Copy vertex/index buffer onto GPU
VkBufferCopy copy_settings {};
copy_settings.size = load_info.hdr.totalBytes;
dev.dt.cmdCopyBuffer(transfer_cmd_, data_staging.buffer, data.buffer,
1, ©_settings);
// Set initial texture layouts
DynArray<VkImageMemoryBarrier> texture_barriers(num_textures);
for (size_t i = 0; i < num_textures; i++) {
const LocalTexture &gpu_texture = gpu_textures[i];
VkImageMemoryBarrier &barrier = texture_barriers[i];
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.pNext = nullptr;
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = gpu_texture.image;
barrier.subresourceRange = {
VK_IMAGE_ASPECT_COLOR_BIT, 0, gpu_texture.mipLevels, 0, 1,
};
}
if (num_textures > 0) {
dev.dt.cmdPipelineBarrier(
transfer_cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr,
texture_barriers.size(), texture_barriers.data());
// Record cpu -> gpu copies
vector<VkBufferImageCopy> copy_infos;
for (size_t i = 0; i < num_textures; i++) {
const LocalTexture &gpu_texture = gpu_textures[i];
uint32_t base_width = gpu_texture.width;
uint32_t base_height = gpu_texture.height;
uint32_t num_levels = gpu_texture.mipLevels;
uint32_t texel_bytes = staged_textures->textureTexelBytes[i];
copy_infos.resize(num_levels);
size_t cur_lvl_offset = staged_textures->stageOffsets[i];
for (uint32_t level = 0; level < num_levels; level++) {
uint32_t level_div = 1 << level;
uint32_t level_width = max(1U, base_width / level_div);
uint32_t level_height = max(1U, base_height / level_div);
cur_lvl_offset = alignOffset(cur_lvl_offset, texel_bytes);
// Set level copy
VkBufferImageCopy copy_info {};
copy_info.bufferOffset = cur_lvl_offset;
copy_info.imageSubresource.aspectMask =
VK_IMAGE_ASPECT_COLOR_BIT;
copy_info.imageSubresource.mipLevel = level;
copy_info.imageSubresource.baseArrayLayer = 0;
copy_info.imageSubresource.layerCount = 1;
copy_info.imageExtent = {
level_width,
level_height,
1,
};
copy_infos[level] = copy_info;
cur_lvl_offset += level_width * level_height *
texel_bytes;
}
dev.dt.cmdCopyBufferToImage(
transfer_cmd_, staged_textures->stageBuffer.buffer,
gpu_texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
copy_infos.size(), copy_infos.data());
}
// Transfer queue relinquish texture barriers
for (VkImageMemoryBarrier &barrier : texture_barriers) {
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = 0;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.srcQueueFamilyIndex = dev.transferQF;
barrier.dstQueueFamilyIndex = render_qf_;
}
}
// Transfer queue relinquish geometry
VkBufferMemoryBarrier geometry_barrier;
geometry_barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
geometry_barrier.pNext = nullptr;
geometry_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
geometry_barrier.dstAccessMask = 0;
geometry_barrier.srcQueueFamilyIndex = dev.transferQF;
geometry_barrier.dstQueueFamilyIndex = render_qf_;
geometry_barrier.buffer = data.buffer;
geometry_barrier.offset = 0;
geometry_barrier.size = load_info.hdr.totalBytes;
// Geometry & texture barrier execute.
dev.dt.cmdPipelineBarrier(
transfer_cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, &geometry_barrier,
texture_barriers.size(), texture_barriers.data());
REQ_VK(dev.dt.endCommandBuffer(transfer_cmd_));
VkSubmitInfo copy_submit {};
copy_submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
copy_submit.waitSemaphoreCount = 0;
copy_submit.pWaitSemaphores = nullptr;
copy_submit.pWaitDstStageMask = nullptr;
copy_submit.commandBufferCount = 1;
copy_submit.pCommandBuffers = &transfer_cmd_;
copy_submit.signalSemaphoreCount = 1;
copy_submit.pSignalSemaphores = &transfer_sema_;
transfer_queue_.submit(dev, 1, ©_submit, VK_NULL_HANDLE);
// Start recording for transferring to rendering queue
REQ_VK(dev.dt.beginCommandBuffer(render_cmd_, &begin_info));
// Finish moving geometry onto render queue family
// geometry and textures need separate barriers due to different
// dependent stages
geometry_barrier.srcAccessMask = 0;
geometry_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
VkPipelineStageFlags dst_geo_render_stage =
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
dev.dt.cmdPipelineBarrier(render_cmd_, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
dst_geo_render_stage, 0, 0, nullptr, 1,
&geometry_barrier, 0, nullptr);
if (num_textures > 0) {
for (VkImageMemoryBarrier &barrier : texture_barriers) {
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcQueueFamilyIndex = dev.transferQF;
barrier.dstQueueFamilyIndex = render_qf_;
}
// Finish acquiring mips on render queue and transition layout
dev.dt.cmdPipelineBarrier(
render_cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr,
texture_barriers.size(), texture_barriers.data());
}
VkBufferDeviceAddressInfo addr_info;
addr_info.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO;
addr_info.pNext = nullptr;
addr_info.buffer = data.buffer;
VkDeviceAddress geometry_addr =
dev.dt.getBufferDeviceAddress(dev.hdl, &addr_info);
auto blas_result = makeBLASes(dev, alloc,
load_info.meshInfo,
load_info.objectInfo,
load_info.hdr.numVertices,
geometry_addr,
geometry_addr + load_info.hdr.indexOffset,
render_cmd_);
if (!blas_result.has_value()) {
cerr <<
"OOM while constructing bottom level acceleration structures"
<< endl;
}
auto [blases, scratch, total_blas_bytes] = move(*blas_result);
// Repurpose geometry_barrier for blas barrier
geometry_barrier.srcAccessMask =
VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR;
geometry_barrier.dstAccessMask =
VK_ACCESS_SHADER_READ_BIT;
geometry_barrier.srcQueueFamilyIndex = render_qf_;
geometry_barrier.dstQueueFamilyIndex = render_qf_;
geometry_barrier.buffer = blases.storage.buffer;
geometry_barrier.offset = 0;
geometry_barrier.size = total_blas_bytes;
dev.dt.cmdPipelineBarrier(
render_cmd_, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0, 0, nullptr,
1, &geometry_barrier,
0, nullptr);
REQ_VK(dev.dt.endCommandBuffer(render_cmd_));
VkSubmitInfo render_submit {};
render_submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
render_submit.waitSemaphoreCount = 1;
render_submit.pWaitSemaphores = &transfer_sema_;
VkPipelineStageFlags sema_wait_mask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
render_submit.pWaitDstStageMask = &sema_wait_mask;
render_submit.commandBufferCount = 1;
render_submit.pCommandBuffers = &render_cmd_;
render_queue_.submit(dev, 1, &render_submit, fence_);
waitForFenceInfinitely(dev, fence_);
resetFence(dev, fence_);
// Set Layout
// 0: Scene addresses uniform
// 1: textures
DescriptorUpdates desc_updates(1);
vector<VkDescriptorImageInfo> descriptor_views;
descriptor_views.reserve(load_info.hdr.numMaterials * 8 + 2);
VkDescriptorImageInfo null_img {
VK_NULL_HANDLE,
VK_NULL_HANDLE,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
if (staged_textures->envMap.has_value()) {
descriptor_views.push_back({
VK_NULL_HANDLE,
texture_views[staged_textures->envMap.value()],
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
});
descriptor_views.push_back({
VK_NULL_HANDLE,
texture_views[staged_textures->importanceMap.value()],
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
});
} else {
descriptor_views.push_back(null_img);
descriptor_views.push_back(null_img);
}
for (int mat_idx = 0; mat_idx < (int)load_info.hdr.numMaterials;
mat_idx++) {
const MaterialTextures &tex_indices =
load_info.textureIndices[mat_idx];
auto appendDescriptor = [&](uint32_t idx, const auto &texture_list) {
if (idx != ~0u) {
VkImageView tex_view = texture_views[texture_list[idx]];
descriptor_views.push_back({
VK_NULL_HANDLE,
tex_view,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
});
} else {
descriptor_views.push_back(null_img);
}
};
appendDescriptor(tex_indices.baseColorIdx, staged_textures->base);
appendDescriptor(tex_indices.metallicRoughnessIdx,
staged_textures->metallicRoughness);
appendDescriptor(tex_indices.specularIdx, staged_textures->specular);
appendDescriptor(tex_indices.normalIdx, staged_textures->normal);
appendDescriptor(tex_indices.emittanceIdx, staged_textures->emittance);
appendDescriptor(tex_indices.transmissionIdx,
staged_textures->transmission);
appendDescriptor(tex_indices.clearcoatIdx, staged_textures->clearcoat);
appendDescriptor(tex_indices.anisoIdx, staged_textures->anisotropic);
}
optional<SceneID> scene_id_tracker;
uint32_t scene_id;
VkDescriptorBufferInfo vert_info;
VkDescriptorBufferInfo mat_info;
if (shared_scene_state_) {
shared_scene_state_->lock.lock();
scene_id_tracker.emplace(*shared_scene_state_);
scene_id = scene_id_tracker->getID();
} else {
// FIXME, this entire special codepath for the editor needs to be
// removed
scene_id = 0;
vert_info.buffer = data.buffer;
vert_info.offset = 0;
vert_info.range =
load_info.hdr.numVertices * sizeof(PackedVertex);
desc_updates.storage(scene_set_, &vert_info, 0);
mat_info.buffer = data.buffer;
mat_info.offset = load_info.hdr.materialOffset;
mat_info.range = load_info.hdr.numMaterials * sizeof(MaterialParams);
desc_updates.storage(scene_set_, &mat_info, 2);
}
if (load_info.hdr.numMaterials > 0) {
assert(load_info.hdr.numMaterials < VulkanConfig::max_materials);
uint32_t texture_offset = scene_id *
(2 + VulkanConfig::max_materials *
VulkanConfig::textures_per_material);
desc_updates.textures(scene_set_,
descriptor_views.data(),
descriptor_views.size(), 1,
texture_offset);
}
desc_updates.update(dev);
if (shared_scene_state_) {
SceneAddresses &scene_dev_addrs =
((SceneAddresses *)shared_scene_state_->addrData.ptr)[scene_id];
scene_dev_addrs.vertAddr = geometry_addr;
scene_dev_addrs.idxAddr = geometry_addr + load_info.hdr.indexOffset;
scene_dev_addrs.matAddr = geometry_addr + load_info.hdr.materialOffset;
scene_dev_addrs.meshAddr = geometry_addr + load_info.hdr.meshOffset;
shared_scene_state_->addrData.flush(dev);
shared_scene_state_->lock.unlock();
}
uint32_t num_meshes = load_info.meshInfo.size();
return make_shared<VulkanScene>(VulkanScene {
{
move(load_info.meshInfo),
move(load_info.objectInfo),
move(load_info.envInit),
},
move(texture_store),
move(data),
load_info.hdr.indexOffset,
num_meshes,
move(scene_id_tracker),
move(blases),
});
}
}
}
| 49,004 | 16,784 |
/*
This file is part of ethash.
ethash is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethash is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ethash. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file sha3.cpp
* @author Tim Hughes <tim@twistedfury.com>
* @date 2015
*/
#include <stdint.h>
#include <cryptopp/sha3.h>
extern "C" {
struct ethash_h256;
typedef struct ethash_h256 ethash_h256_t;
void SHA3_256(ethash_h256_t const* ret, uint8_t const* data, size_t size)
{
CryptoPP::SHA3_256().CalculateDigest((uint8_t*)ret, data, size);
}
void SHA3_512(uint8_t* const ret, uint8_t const* data, size_t size)
{
CryptoPP::SHA3_512().CalculateDigest(ret, data, size);
}
}
| 1,166 | 443 |
#include "extern.hpp"
#include <MonoEngine/core/log.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
#pragma GCC diagnostic ignored "-Wconversion"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#pragma GCC diagnostic pop
#include <assimp/postprocess.h>
#include <glm/glm.hpp>
namespace renderer {
namespace rt {
Extern::Extern(const std::string & path) {
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate);
if (!scene) {
LOG(importer.GetErrorString());
} else {
LOG_ASSERT(scene->HasMeshes(), "imported scene has no meshes");
const auto * meshes = scene->mMeshes;
LOG("numMeshes:" + std::to_string(scene->mNumMeshes));
for (auto i {0u}; i < scene->mNumMeshes; ++i) {
LOG_ASSERT(meshes[i]->HasPositions() && meshes[i]->HasFaces(), "mesh does not have positions or faces");
const auto hasColors {meshes[i]->HasVertexColors(0)};
const auto * faces = meshes[i]->mFaces;
LOG("numFaces:" + std::to_string(meshes[i]->mNumFaces));
// for (auto j {0u}; j < meshes[i]->mNumFaces; ++j) {
for (auto j {0u}; j < 125000; ++j) {
LOG_ASSERT(faces[j].mNumIndices == 3, "face is not a triangle");
const auto aVec {meshes[i]->mVertices[faces[j].mIndices[0]]};
auto a {glm::vec3(aVec[0], aVec[1], aVec[2])};
const auto bVec {meshes[i]->mVertices[faces[j].mIndices[1]]};
auto b {glm::vec3(bVec[0], bVec[1], bVec[2])};
const auto cVec {meshes[i]->mVertices[faces[j].mIndices[2]]};
auto c {glm::vec3(cVec[0], cVec[1], cVec[2])};
// scaling
a *= 30.f;
b *= 30.f;
c *= 30.f;
// moving
a += glm::vec3(0.f, -6.5f, -7.f);
b += glm::vec3(0.f, -6.5f, -7.f);
c += glm::vec3(0.f, -6.5f, -7.f);
m_vertices.emplace_back(a.x);
m_vertices.emplace_back(a.y);
m_vertices.emplace_back(a.z);
m_vertices.emplace_back(0.f);
m_vertices.emplace_back(b.x);
m_vertices.emplace_back(b.y);
m_vertices.emplace_back(b.z);
m_vertices.emplace_back(0.f);
m_vertices.emplace_back(c.x);
m_vertices.emplace_back(c.y);
m_vertices.emplace_back(c.z);
m_vertices.emplace_back(0.f);
const auto n {glm::normalize(glm::cross(b - a, c - a))};
m_normals.emplace_back(n.x);
m_normals.emplace_back(n.y);
m_normals.emplace_back(n.z);
m_normals.emplace_back(0.f);
m_normals.emplace_back(n.x);
m_normals.emplace_back(n.y);
m_normals.emplace_back(n.z);
m_normals.emplace_back(0.f);
m_normals.emplace_back(n.x);
m_normals.emplace_back(n.y);
m_normals.emplace_back(n.z);
m_normals.emplace_back(0.f);
glm::vec4 col;
if (!hasColors) {
col = glm::vec4(1.f, 0.f, 0.f, 1.f); // default color
} else {
const auto color {meshes[i]->mColors[0][faces[j].mIndices[0]]};
col = glm::vec4(color.r, color.g, color.b, 1.f);
}
m_colors.emplace_back(col.r);
m_colors.emplace_back(col.g);
m_colors.emplace_back(col.b);
m_colors.emplace_back(col.a);
m_colors.emplace_back(col.r);
m_colors.emplace_back(col.g);
m_colors.emplace_back(col.b);
m_colors.emplace_back(col.a);
m_colors.emplace_back(col.r);
m_colors.emplace_back(col.g);
m_colors.emplace_back(col.b);
m_colors.emplace_back(col.a);
}
}
}
}
}
} // namespace renderer | 3,323 | 1,683 |
#pragma once
#include <condition_variable>
#include <mutex>
template <class T> class WaitGroup {
std::mutex m;
std::condition_variable cv;
T counter;
public:
WaitGroup() : counter(0) {};
~WaitGroup(){};
void add(T n) {
std::lock_guard<std::mutex> lk(m);
counter += n;
}
void done() {
bool notify = false;
{
std::lock_guard<std::mutex> lk(m);
counter -= 1;
assert(counter>=0);
if (counter == 0)
notify = true;
}
if (notify)
cv.notify_one();
}
void wait() {
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, [this] { return this->counter <= 0; });
}
};
| 646 | 249 |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
//
// Copyright (C) 2012, Takuya MINAGAWA.
// Third party copyrights are property of their respective owners.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//M*/
#include "cameraCalibration.h"
#include <stdio.h>
#include <iostream>
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/highgui.hpp"
#include "commonCvFunctions.h"
using namespace std;
using namespace cv;
using namespace cvar;
cameraCalibration::cameraCalibration(void)
{
max_img_num = 25;
pat_row = 7;
pat_col = 10;
chess_size = 23.0;
camera_matrix.create(3, 3, CV_32FC1);
distortion.create(1, 5, CV_32FC1);
}
cameraCalibration::~cameraCalibration(void)
{
}
void cameraCalibration::setMaxImageNum(int num)
{
max_img_num = num;
}
void cameraCalibration::setBoardColsAndRows(int r, int c)
{
pat_row = r;
pat_col = c;
}
void cameraCalibration::setChessSize(float size)
{
chess_size = size;
}
bool cameraCalibration::addCheckerImage(Mat& img)
{
if(checker_image_list.size() >= max_img_num)
return false;
else
checker_image_list.push_back(img);
return true;
}
void cameraCalibration::releaseCheckerImage()
{
checker_image_list.clear();
}
bool cameraCalibration::doCalibration()
{
int i, j, k;
bool found;
int image_num = checker_image_list.size();
// int pat_size = pat_row * pat_col;
// int all_points = image_num * pat_size;
if(image_num < 3){
cout << "please add checkker pattern image!" << endl;
return false;
}
// int *p_count = new int[image_num];
rotation.clear();
translation.clear();
cv::Size pattern_size(pat_col,pat_row);
// Point3f *objects = new Point3f[all_points];
// Point2f *corners = new Point2f[all_points];
Point3f obj;
vector<Point3f> objects;
vector<vector<Point3f>> object_points;
// 3D set of spatial coordinates
for (j = 0; j < pat_row; j++) {
for (k = 0; k < pat_col; k++) {
obj.x = j * chess_size;
obj.y = k * chess_size;
obj.z = 0.0;
objects.push_back(obj);
}
}
vector<Point2f> corners;
vector<vector<Point2f>> image_points;
int found_num = 0;
cvNamedWindow ("Calibration", CV_WINDOW_AUTOSIZE);
auto img_itr = checker_image_list.begin();
i = 0;
while (img_itr != checker_image_list.end()) {
// Corner detection of chess board (calibration pattern)
found = cv::findChessboardCorners(*img_itr, pattern_size, corners);
cout << i << "...";
if (found) {
cout << "ok" << endl;
found_num++;
}
else {
cout << "fail" << endl;
}
// Fixed a corner position in the sub-pixel accuracy, drawing
Mat src_gray(img_itr->size(), CV_8UC1, 1);
cvtColor(*img_itr, src_gray, CV_BGR2GRAY);
// cvCvtColor (src_img[i], src_gray, CV_BGR2GRAY);
cornerSubPix(src_gray, corners, cv::Size(3,3), cv::Size(-1,-1), TermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03));
// cvFindCornerSubPix (src_gray, &corners[i * PAT_SIZE], corner_count,
// cvSize (3, 3), cvSize (-1, -1), cvTermCriteria (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03));
drawChessboardCorners(*img_itr, pattern_size, transPointVecToMat2D(corners), found);
// cvDrawChessboardCorners (src_img[i], pattern_size, &corners[i * PAT_SIZE], corner_count, found);
// p_count[i] = corner_count;
if(found){
image_points.push_back(corners);
object_points.push_back(objects);
}
corners.clear();
imshow("Calibration", *img_itr);
cvWaitKey (0);
i++;
img_itr++;
}
cvDestroyWindow ("Calibration");
if (found_num < 3){
return false;
}
// cvInitMatHeader (&image_points, ALL_POINTS, 1, CV_32FC2, corners);
// cvInitMatHeader (&point_counts, IMAGE_NUM, 1, CV_32SC1, p_count);
// Internal parameters, distortion factor, the estimation of the external parameters
// cvCalibrateCamera2 (&object_points, &image_points, &point_counts, cvSize (640, 480), intrinsic, distortion);
calibrateCamera(object_points, image_points, checker_image_list[0].size(), camera_matrix, distortion, rotation, translation);
/* CvMat sub_image_points, sub_object_points;
int base = 0;
cvGetRows (&image_points, &sub_image_points, base * PAT_SIZE, (base + 1) * PAT_SIZE);
cvGetRows (&object_points, &sub_object_points, base * PAT_SIZE, (base + 1) * PAT_SIZE);
cvFindExtrinsicCameraParams2 (&sub_object_points, &sub_image_points, intrinsic, distortion, rotation, translation);
// (7) Export to XML file
CvFileStorage *fs;
fs = cvOpenFileStorage ("camera.xml", 0, CV_STORAGE_WRITE);
cvWrite (fs, "intrinsic", intrinsic);
cvWrite (fs, "rotation", rotation);
cvWrite (fs, "translation", translation);
cvWrite (fs, "distortion", distortion);
cvReleaseFileStorage (&fs);
*/
return true;
}
void cameraCalibration::saveCameraMatrix(const string& filename)
{
FileStorage fs(filename, FileStorage::WRITE);
writeCameraMatrix(fs, "camera_matrix");
}
void cameraCalibration::writeCameraMatrix(FileStorage& cvfs, const string& name)
{
cvfs << name << camera_matrix;
} | 6,327 | 2,415 |
/*
* This file is part of ImageToMapMC project
*
* Copyright (c) 2021 Agustin San Roman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "map_nbt.h"
#include <fstream>
#include <io/stream_reader.h>
#include <io/stream_writer.h>
#include <io/izlibstream.h>
#include <io/ozlibstream.h>
#include <nbt_tags.h>
using namespace std;
using namespace nbt;
using namespace colors;
using namespace mapart;
using namespace minecraft;
std::vector<map_color_t> mapart::readMapNBTFile(std::string fileName)
{
std::vector<map_color_t> result(MAP_WIDTH * MAP_HEIGHT);
std::ifstream file(fileName, std::ios::binary);
if (!file)
{
throw -1;
}
try
{
zlib::izlibstream igzs(file);
auto pair = nbt::io::read_compound(igzs);
nbt::tag_compound comp = *pair.second;
nbt::value *colorsArray = &comp.at(std::string("data")).at(std::string("colors"));
nbt::tag_byte_array colorsBytes = colorsArray->as<nbt::tag_byte_array>();
size_t map_size = MAP_WIDTH * MAP_HEIGHT;
for (size_t i = 0; i < map_size; i++)
{
result[i] = uint8_t(colorsBytes.at(i));
}
}
catch (...)
{
throw -2;
}
return result;
}
void mapart::writeMapNBTFile(std::string fileName, const std::vector<map_color_t> &mapColors, minecraft::McVersion version)
{
nbt::tag_compound root;
nbt::tag_compound data;
// Set meta data
data.insert("width", nbt::tag_int(MAP_WIDTH));
data.insert("height", nbt::tag_int(MAP_HEIGHT));
data.insert("dimension", nbt::tag_int(0));
data.insert("scale", nbt::tag_int(0));
data.insert("trackingPosition:", nbt::tag_int(0));
data.insert("unlimitedTracking", nbt::tag_int(0));
if (version >= McVersion::MC_1_14)
{
// If we can, prevent the map from being modified
data.insert("locked", nbt::tag_int(1));
}
// Set the center far away to prevent issues (20M)
data.insert("xCenter", nbt::tag_int(20000000));
data.insert("zCenter", nbt::tag_int(20000000));
// Set colors array
nbt::tag_byte_array byteArray;
size_t size = MAP_WIDTH * MAP_HEIGHT;
for (size_t i = 0; i < size; i++)
{
short val = mapColors[i];
int8_t ip = static_cast<int8_t>((val > 127) ? (val - 256) : val);
byteArray.push_back(ip);
}
data.insert("colors", byteArray.clone());
// Insert tags to root
root.insert("data", data.clone());
root.insert("DataVersion", minecraft::versionToDataVersion(version));
std::ofstream file(fileName, std::ios::binary);
if (!file)
{
throw -1;
}
try
{
zlib::ozlibstream ogzs(file, -1, true);
nbt::io::write_tag("", root, ogzs);
}
catch (...)
{
throw -2;
}
}
| 3,838 | 1,361 |
#include "EniConfig.h"
#if defined(ENI_USB_DEVICE) && defined(ENI_STM)
#include "UsbDDevice.h"
#include "usbd_conf.h"
#include "Core/usbd_def.h"
#include "Core/usbd_ioreq.h"
#include "Core/usbd_ctlreq.h"
#include "Core/usbd_core.h"
#include ENI_HAL_INCLUDE_FILE
#include "USBTypes.h"
#include "UsbMicrosoftTypes.h"
#include <type_traits>
#include <new>
using namespace Eni;
extern "C" {
extern PCD_HandleTypeDef hpcd_USB_OTG_FS;
}
namespace Eni::USB {
__attribute__((used)) USBD_HandleTypeDef UsbDevice::hUsbDevice{};
__attribute__((used)) UsbDDeviceContext* _context = nullptr;
//For other-speed description
__ALIGN_BEGIN volatile USB::DeviceQualifierDescriptor USBD_NDC_DeviceQualifierDesc __ALIGN_END {
USB::UsbVersion(2),
USB::UsbClass::Device::UseInterfaceClass(),
64,
1,
0
};
#define USB_VENDOR_CODE_WINUSB 'P'
__ALIGN_BEGIN volatile USB::Microsoft::MicrosoftStringDescriptor NDC_StringDescriptor __ALIGN_END = {
(uint8_t)USB_VENDOR_CODE_WINUSB
};
extern volatile USB::DeviceQualifierDescriptor USBD_NDC_DeviceQualifierDesc;
extern volatile USB::Microsoft::MicrosoftStringDescriptor NDC_StringDescriptor;
__attribute__((used)) std::aligned_storage_t<USBD_MAX_STR_DESC_SIZ, 4> _descriptorsBuffer;
UsbDDeviceContext* UsbDevice::getContext(){
return _context;
}
void hang(){
while(true){
asm("nop");
}
}
__attribute__((used)) const USBD_DescriptorsTypeDef UsbDevice::_descriptorsTable = {
&UsbDevice::getDeviceDescriptor,
&UsbDevice::getLangidStrDescriptor,
&UsbDevice::getManufacturerStringDescriptor,
&UsbDevice::getProductStringDescriptor,
&UsbDevice::getSerialStringDescriptor,
&UsbDevice::getConfigStringDescriptor,
&UsbDevice::getInterfaceStringDescriptor
};
__attribute__((used)) const USBD_ClassTypeDef UsbDevice::_usbClassBinding = {
&UsbDevice::coreInit,
&UsbDevice::coreDeinit,
&UsbDevice::coreSetup,
0, //USBD_NDC_EP0_TxReady,
&UsbDevice::coreEp0RxReady,
&UsbDevice::coreDataIn,
&UsbDevice::coreDataOut,
&UsbDevice::coreSof,
&UsbDevice::coreIsoInIncomplete,
&UsbDevice::coreIsoOutIncomplete,
&UsbDevice::coreGetCfgDesc,
&UsbDevice::coreGetCfgDesc,
&UsbDevice::coreGetCfgDesc,
&UsbDevice::coreGetDeviceQualifierDesc,
&UsbDevice::coreGetUserStringDesc
};
uint8_t UsbDevice::coreInit(USBD_HandleTypeDef* pdev, uint8_t cfgidx){
//TODO: use configuration id
for(size_t i = 0; i < _context->getInterfaceCount(); ++i){
auto interface = _context->getInterface(i);
if(interface != nullptr){
if(!interface->init(pdev)){
return USBD_FAIL;
}
}
}
return USBD_OK;
}
uint8_t UsbDevice::coreDeinit(USBD_HandleTypeDef* pdev, uint8_t cfgidx){
//TODO: use configuration id
for(size_t i = 0; i < _context->getInterfaceCount(); ++i){
auto interface = _context->getInterface(i);
if(interface != nullptr){
if(!interface->deinit(pdev)){
//return USBD_FAIL;
}
}
}
return USBD_OK;
}
uint8_t UsbDevice::coreImplSetup(USBD_SetupReqTypedef request, void* data){
switch ( request.bmRequest & USB_REQ_RECIPIENT_MASK ){
case USB_REQ_RECIPIENT_INTERFACE:{
if(_context != nullptr){
auto* interface = _context->getInterface(request.wValue);
if(interface != nullptr){
hang();
/*if(interface->control(&hUsbDevice, request.bRequest, (uint8_t*)data, request.wLength)){
return USBD_OK;
}*/
}
}
break;
}
case USB_REQ_RECIPIENT_ENDPOINT:
hang();
/*if(_usb_device_context != nullptr){
if(request.bRequest == USB_REQ_CLEAR_FEATURE){ //reset pipe is called at host side
//do reset pipe
if(_clearFeatureCallback != nullptr){
_clearFeatureCallback(request.wIndex);
}
}
}*/
break;
case USB_REQ_RECIPIENT_DEVICE:
default:
break;
}
return USBD_OK;
}
uint8_t UsbDevice::coreSetup(USBD_HandleTypeDef* pdev, USBD_SetupReqTypedef *req){
hang();
/*if (req->wLength){
//Request with data stage{
if((req->bmRequest & USB_REQ_DATA_PHASE_MASK) == USB_REQ_DATA_PHASE_DEVICE_TO_HOST){
//device to host data stage => handler should send data
return coreImplSetup(*req, 0);
}else{ //host to device data stage! Can't execute now, read data first & execute later in Ep0Receive callback
last_request = *req;
USBD_CtlPrepareRx (pdev, (uint8_t*)&ep0Buffer[0], req->wLength);
}
} else {//No data stage => simple request => execute now
return coreImplSetup(*req, 0);
}*/
return USBD_OK;
}
uint8_t UsbDevice::coreEp0RxReady(USBD_HandleTypeDef* pdev){
hang();
//coreImplSetup(last_request, &ep0Buffer[0]); //data in stage complete => execute request
//last_request.bRequest = 0xff;
return USBD_OK;
}
UsbDInterface* UsbDevice::findInterfaceByEndpointAddress(uint8_t address){
if(_context == nullptr){
return nullptr;
}
auto if_cnt = _context->getInterfaceCount();
for(uint32_t i = 0; i < if_cnt; ++i){
auto interface = _context->getInterface(i);
if(interface != nullptr){
auto endpoint = interface->getEndpoint(address);
if(endpoint != nullptr){
return interface;
}
}
}
return nullptr;
}
uint8_t UsbDevice::coreDataIn(USBD_HandleTypeDef* pdev, uint8_t epnum){
auto interface = findInterfaceByEndpointAddress(USB::EndpointAddress::makeIn(epnum));//TODO: cleanup
if(interface != nullptr){
interface->txComplete(epnum | 0x80);
}
return USBD_OK;
}
uint8_t UsbDevice::coreDataOut(USBD_HandleTypeDef* pdev, uint8_t epnum){
uint32_t rxLen = USBD_LL_GetRxDataSize (pdev, epnum);
auto interface = findInterfaceByEndpointAddress(USB::EndpointAddress::makeOut(epnum));
if(interface != nullptr){
interface->rxComplete(rxLen, epnum);
}
return USBD_OK;
}
uint8_t UsbDevice::coreSof(USBD_HandleTypeDef* pdev){
hang();
return USBD_OK;
}
uint8_t UsbDevice::coreIsoInIncomplete(USBD_HandleTypeDef* pdev, uint8_t epnum){
hang();
return USBD_OK;
}
uint8_t UsbDevice::coreIsoOutIncomplete(USBD_HandleTypeDef* pdev, uint8_t epnum){
hang();
return USBD_OK;
}
uint8_t* UsbDevice::coreGetCfgDesc(uint16_t* length){
auto* mem = reinterpret_cast<uint8_t*>(&_descriptorsBuffer);
auto* buffer = mem;
USB::ConfigurationDescriptor* cd = new(buffer) USB::ConfigurationDescriptor();
cd->wTotalLength = 0;
cd->bNumInterfaces = (uint8_t)_context->getInterfaceCount();
cd->bConfigurationValue = 0x01;
cd->iConfiguration = USBD_IDX_CONFIG_STR;
cd->bmAttributes = USB::UsbAttributes().value;
cd->bMaxPower = 500;
buffer += sizeof(USB::ConfigurationDescriptor);
for(uint32_t i = 0; i < _context->getInterfaceCount(); ++i){
auto emptySize = (mem + sizeof(_descriptorsBuffer)) - buffer;
auto size = _context->getInterface(i)->getDescriptor(buffer, emptySize, i);
buffer += size;
cd->wTotalLength += size;
}
cd->wTotalLength += sizeof(USB::ConfigurationDescriptor);
*length = cd->wTotalLength;
return reinterpret_cast<uint8_t*>(&_descriptorsBuffer);
}
uint8_t* UsbDevice::getDeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
auto mem = reinterpret_cast<uint8_t*>(&_descriptorsBuffer);
auto& desc = *new(mem) USB::DeviceDescriptor();
*length = sizeof(USB::DeviceDescriptor);
desc.bcdUSB = 0x0200;
desc.classDescription = USB::UsbClassDescriptor(0,0,0);
desc.bMaxPacketSize0 = 64;
desc.idVendor = _context->vid;
desc.idProduct = _context->pid;
desc.bcdDevice = USB::UsbVersion(2);
desc.iManufacturer = USBD_IDX_MFC_STR;
desc.iProduct = USBD_IDX_PRODUCT_STR;
desc.iSerialNumber = USBD_IDX_SERIAL_STR;
desc.bNumConfigurations = 1;
return reinterpret_cast<uint8_t*>(&desc);
}
struct USBDDummyClassData{
uint32_t reserved;
};
__attribute__((used)) static USBDDummyClassData _classData = {};
void UsbDevice::start(UsbDDeviceContext* context){
_context = context;
hUsbDevice.pClassData = &_classData; //Otherwise USBD_Reset handler would not disable interfaces ((
//hUsbDevice.pClassData = nullptr; //Init?
hUsbDevice.dev_speed = USBD_SPEED_FULL;
USBD_Init(&hUsbDevice, const_cast<USBD_DescriptorsTypeDef*>(&_descriptorsTable), 0);
USBD_RegisterClass(&hUsbDevice, const_cast<USBD_ClassTypeDef*>(&_usbClassBinding));
USBD_Start(&hUsbDevice);
}
uint8_t* UsbDevice::coreGetDeviceQualifierDesc (uint16_t *length){
*length = sizeof (USBD_NDC_DeviceQualifierDesc);
return (uint8_t*)&USBD_NDC_DeviceQualifierDesc;
}
uint8_t* UsbDevice::coreGetUserStringDesc(USBD_HandleTypeDef* pdev, uint8_t index, uint16_t* length){
*length = 0;
if ( 0xEE == index ){
*length = sizeof (NDC_StringDescriptor);
return (uint8_t*)&NDC_StringDescriptor;
}
return NULL;
}
uint8_t* UsbDevice::getLangidStrDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
auto mem = static_cast<void*>(&_descriptorsBuffer);
auto& desc = *new(mem) USB::LanguageIDStringDescriptor<1>();
*length = sizeof(USB::LanguageIDStringDescriptor<1>);
desc.languages[0] = USB::LanguageID::EnglishUnitedStates;
return reinterpret_cast<uint8_t*>(&desc);
}
uint8_t* UsbDevice::getManufacturerStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
return USB::MakeStringDescriptor(_context->manufacturerStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length);
}
uint8_t* UsbDevice::getProductStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
return USB::MakeStringDescriptor(_context->productStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length);
}
uint8_t* UsbDevice::getSerialStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
return USB::MakeStringDescriptor(_context->serialStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length);
}
uint8_t* UsbDevice::getConfigStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
return USB::MakeStringDescriptor(_context->configurationStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length);
}
uint8_t* UsbDevice::getInterfaceStringDescriptor(USBD_SpeedTypeDef speed, uint16_t* length){
return USB::MakeStringDescriptor(_context->interfaceStringDescriptor, &_descriptorsBuffer, sizeof(_descriptorsBuffer), length);
}
USBD_StatusTypeDef UsbDevice::interfaceRequest(USBD_HandleTypeDef* pdev, USBD_SetupReqTypedef* req){
uint8_t interface_id = (uint8_t)req->wValue; //TODO: bug! wIndex == interface id
auto interface = _context->getInterface(interface_id);
if(interface == nullptr){
return USBD_FAIL;
}
return interface->interfaceRequest(pdev, req);
}
}
#endif
| 10,247 | 3,973 |
#include <iostream>
#include "logger.h"
int main()
{
// Simple log message
qlog::log("Hello world!");
// Select log_level
qlog::log(log_level::level::debug, "Debuging: ", "Selected log level");
// Debug log
qlog::debug("This is a debug message.");
// Info log
qlog::info("Information");
// Error log
qlog::error("Error");
// Crititcal log
qlog::critical("Critical operator: ", "1");
// Set log level to filter the output log
log_level::set_level(log_level::level::critical);
// Any information will not output if the the level is lower than setting level
qlog::info("This message unable to log.", "Log failed");
return 0;
} | 706 | 223 |
#ifndef SHASTA_MARKER_INTERVAL_HPP
#define SHASTA_MARKER_INTERVAL_HPP
// Shasta.
#include "ReadId.hpp"
#include"tuple.hpp"
// Standard library.
#include "array.hpp"
namespace shasta {
class MarkerInterval;
class MarkerIntervalWithRepeatCounts;
}
// Class to describe the interval between
// two markers on an oriented read.
// The two markers are not necessarily consecutive.
// HOoever, the second marker has a higher ordinal
// than the first.
class shasta::MarkerInterval {
public:
OrientedReadId orientedReadId;
// The ordinals of the two markers.
array<uint32_t, 2> ordinals;
MarkerInterval() {}
MarkerInterval(
OrientedReadId orientedReadId,
uint32_t ordinal0,
uint32_t ordinal1) :
orientedReadId(orientedReadId)
{
ordinals[0] = ordinal0;
ordinals[1] = ordinal1;
}
bool operator==(const MarkerInterval& that) const
{
return
tie(orientedReadId, ordinals[0], ordinals[1])
==
tie(that.orientedReadId, that.ordinals[0], that.ordinals[1]);
}
bool operator<(const MarkerInterval& that) const
{
return
tie(orientedReadId, ordinals[0], ordinals[1])
<
tie(that.orientedReadId, that.ordinals[0], that.ordinals[1]);
}
};
class shasta::MarkerIntervalWithRepeatCounts :
public MarkerInterval {
public:
vector<uint8_t> repeatCounts;
// The constructor does not fill in the repeat counts.
MarkerIntervalWithRepeatCounts(const MarkerInterval& markerInterval) :
MarkerInterval(markerInterval){}
};
#endif
| 1,627 | 525 |
/**
* @author : Maruf Tuhin
* @College : CUET CSE 11
* @Topcoder : the_redback
* @CodeForces : the_redback
* @UVA : the_redback
* @link : http://www.fb.com/maruf.2hin
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
#define ft first
#define sd second
#define mp make_pair
#define pb(x) push_back(x)
#define all(x) x.begin(),x.end()
#define allr(x) x.rbegin(),x.rend()
#define mem(a,b) memset(a,b,sizeof(a))
#define repv(i,a) for(i=0;i<(ll)a.size();i++)
#define revv(i,a) for(i=(ll)a.size()-1;i>=0;i--)
#define rep(i,a,b) for(i=a;i<=b;i++)
#define rev(i,a,b) for(i=a;i>=b;i--)
#define sf(a) scanf("%lld",&a)
#define sf2(a,b) scanf("%lld %lld",&a,&b)
#define sf3(a,b,c) scanf("%lld %lld %lld",&a,&b,&c)
#define inf 1e9
#define eps 1e-9
#define mod 1000000007
#define NN 100010
#ifdef redback
#define bug printf("line=%d\n",__LINE__);
#define debug(args...) {cout<<":: "; dbg,args; cerr<<endl;}
struct debugger{template<typename T>debugger& operator ,(const T& v){cerr<<v<<" ";return *this;}}dbg;
#else
#define bug
#define debug(args...)
#endif //debugging macros
#define NN 70000
bool p[NN+7]; //Hashing
vector<ll>pr,facts; //storing prime
void sieve(ll n)
{
ll i,j,k,l;
p[1]=1;
pr.push_back(2);
for(i=4;i<=n;i+=2)
p[i]=1;
for(i=3;i<=n;i+=2)
{
if(p[i]==0)
{
pr.push_back(i);
for(j=i*i;j<=n;j+=2*i)
p[j]=1;
}
}
}
ll factor(ll n)
{
facts.clear();
ll count,k,i;
for(i=0;i<pr.size() && pr[i]*pr[i]<=n;i++)
{
k=pr[i];
count=0;
while(n%k==0)
{
n/=k;
count++;
}
facts.pb(count);
if(n==1)
break;
}
if(n>1)
facts.pb(1);
}
int main()
{
//ios_base::sync_with_stdio(0); cin.tie(0);
#ifdef redback
freopen("C:\\Users\\Maruf\\Desktop\\in.txt","r",stdin);
#endif
sieve(NN);
ll t=1,tc;
sf(tc);
ll l,m,n;
while(tc--) {
ll i,j,l;
sf(n);
ll minusFlag=0;
if(n<0)
{
n*=-1;
minusFlag=1;
}
factor(n);
ll ans=0;
for(i=1;i<34;i++)
{
ll flag=1;
for(j=0;j<facts.size();j++)
{
if(facts[j]%i!=0)
{
flag=0;
break;
}
}
if(minusFlag && i%2==0)
continue;
if(flag)
ans=max(ans,i);
}
printf("Case %lld: %lld\n",t++,ans);
}
return 0;
}
| 2,788 | 1,190 |
#pragma once
#include <string>
namespace dawn
{
inline void string_pop_front(std::string& s, size_t n)
{
s = s.substr(n);
}
inline bool string_pop_front_if_find(std::string& s, std::string const& w)
{
size_t const pos = s.find(w);
if (pos == std::string::npos) return false;
string_pop_front(s, pos + w.size());
return true;
}
inline bool string_pop_front_if_find_backward(std::string& s, std::string const& w)
{
size_t const pos = s.rfind(w);
if (pos == std::string::npos) return false;
string_pop_front(s, pos + w.size());
return true;
}
inline bool string_pop_front_equal(std::string& s, std::string const& w)
{
if (w.empty()) return true;
if (s.size() >= w.size() && s.compare(0, w.size() - 1, w))
{
s = s.substr(w.size());
return true;
}
return false;
}
}
| 948 | 330 |
#include <iostream>
#include "numbers.dat"
void sieve(bool *primes, int len)
{
for(int i = 0; i < len; i++)
primes[i] = true;
primes[0] = primes[1] = false;
for (int i = 2; i < len; i++)
{
if (primes[i])
{
for (int j = 2 * i; j < len; j += i)
primes[j] = false;
}
}
}
int left(int edge)
{
int l = 0, r = Size, med;
while(r - l > 1)
{
med = (l + r) / 2;
if(Data[med] >= edge)
r = med;
else
l = med;
}
if(edge == Data[l])
return l;
if(edge == Data[r])
return r;
return -1;
}
int right(int edge)
{
int l = 0, r = Size, med;
while(r - l > 1)
{
med = (l + r) / 2;
if(Data[med] <= edge)
l = med;
else
r = med;
}
if(edge == Data[l])
return l;
if(edge == Data[r])
return r;
return -1;
}
int main(int argc, char *argv[])
{
if(!(argc & 1) || argc == 1)
return -1;
const int n = Data[Size - 1];
bool *primes = new bool[n];
sieve(primes, n);
int l, r, ld, rd;
for(int i = 1; i < argc; i += 2)
{
l = std::atoi(argv[i]);
r = std::atoi(argv[i + 1]);
ld = left(l);
rd = right(r);
if(ld == -1 || rd == -1)
continue;
int counter = 0;
for(int j = ld; j <= rd; ++j)
counter += primes[Data[j]];
std::cout << counter << std::endl;
}
delete [] primes;
return 0;
}
| 1,560 | 636 |
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// $Id: PhysListParticles.cc 68007 2013-03-13 11:28:03Z gcosmo $
//
/// \file radioactivedecay/rdecay02/src/PhysListParticles.cc
/// \brief Implementation of the PhysListParticles class
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "PhysListParticles.hh"
// Bosons
#include "G4ChargedGeantino.hh"
#include "G4Geantino.hh"
#include "G4Gamma.hh"
#include "G4OpticalPhoton.hh"
// leptons
#include "G4MuonPlus.hh"
#include "G4MuonMinus.hh"
#include "G4NeutrinoMu.hh"
#include "G4AntiNeutrinoMu.hh"
#include "G4Electron.hh"
#include "G4Positron.hh"
#include "G4NeutrinoE.hh"
#include "G4AntiNeutrinoE.hh"
// Hadrons
#include "G4MesonConstructor.hh"
#include "G4BaryonConstructor.hh"
#include "G4IonConstructor.hh"
//ShortLived
#include "G4ShortLivedConstructor.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
PhysListParticles::PhysListParticles(const G4String& name)
: G4VPhysicsConstructor(name)
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
PhysListParticles::~PhysListParticles()
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void PhysListParticles::ConstructParticle()
{
// pseudo-particles
G4Geantino::GeantinoDefinition();
G4ChargedGeantino::ChargedGeantinoDefinition();
// gamma
G4Gamma::GammaDefinition();
// optical photon
G4OpticalPhoton::OpticalPhotonDefinition();
// leptons
G4Electron::ElectronDefinition();
G4Positron::PositronDefinition();
G4MuonPlus::MuonPlusDefinition();
G4MuonMinus::MuonMinusDefinition();
G4NeutrinoE::NeutrinoEDefinition();
G4AntiNeutrinoE::AntiNeutrinoEDefinition();
G4NeutrinoMu::NeutrinoMuDefinition();
G4AntiNeutrinoMu::AntiNeutrinoMuDefinition();
// mesons
G4MesonConstructor mConstructor;
mConstructor.ConstructParticle();
// barions
G4BaryonConstructor bConstructor;
bConstructor.ConstructParticle();
// ions
G4IonConstructor iConstructor;
iConstructor.ConstructParticle();
// Construct resonaces and quarks
G4ShortLivedConstructor pShortLivedConstructor;
pShortLivedConstructor.ConstructParticle();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| 3,900 | 1,361 |
// Copyright (C) 2020 T. Zachary Laine
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "curses_interface.hpp"
extern "C" {
#include <ncurses.h>
}
curses_interface_t::curses_interface_t() : win_(initscr())
{
if (win_ != stdscr)
throw std::runtime_error("ncurses initscr() failed.");
raw();
noecho();
keypad(stdscr, true);
start_color();
use_default_colors();
mmask_t old_mouse_events;
mousemask(
BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED | BUTTON1_TRIPLE_CLICKED |
REPORT_MOUSE_POSITION,
&old_mouse_events);
set_tabsize(1);
}
curses_interface_t::~curses_interface_t() { endwin(); }
screen_pos_t curses_interface_t::screen_size() const
{
return {getmaxy(stdscr), getmaxx(stdscr)};
}
event_t curses_interface_t::next_event() const
{
int const k = wgetch(win_);
// Mouse events.
if (k == KEY_MOUSE) {
MEVENT e;
if (getmouse(&e) == ERR)
return {key_code_t{KEY_MAX}, screen_size()};
return {key_code_t{(int)e.bstate, e.x, e.y}, screen_size()};
}
// Everything else.
return {key_code_t{k}, screen_size()};
}
namespace {
void render_text(snapshot_t const & snapshot, screen_pos_t screen_size)
{
int row = 0;
std::vector<char> buf;
std::ptrdiff_t pos = snapshot.first_char_index_;
auto line_first = snapshot.first_row_;
auto const line_last = std::min<std::ptrdiff_t>(
line_first + screen_size.row_ - 2, snapshot.lines_.size());
for (; line_first != line_last; ++line_first) {
auto const line = snapshot.lines_[line_first];
auto first = snapshot.content_.begin().base().base() + pos;
auto const last = first + line.code_units_;
move(row, 0);
buf.clear();
std::copy(first, last, std::back_inserter(buf));
if (!buf.empty() && buf.back() == '\n')
buf.pop_back();
if (!buf.empty() && buf.back() == '\r')
buf.pop_back();
buf.push_back('\0');
addstr(&buf[0]);
pos += line.code_units_;
++row;
}
}
}
void render(buffer_t const & buffer, screen_pos_t screen_size)
{
erase();
auto const size = screen_pos_t{screen_size.row_ - 2, screen_size.col_};
render_text(buffer.snapshot_, screen_size);
// render the info line
move(size.row_, 0);
attron(A_REVERSE);
printw(
" %s %s (%d, %d)",
dirty(buffer) ? "**" : "--",
buffer.path_.c_str(),
buffer.snapshot_.first_row_ + buffer.snapshot_.cursor_pos_.row_ + 1,
buffer.snapshot_.cursor_pos_.col_);
attroff(A_REVERSE);
hline(' ', size.col_);
move(buffer.snapshot_.cursor_pos_.row_, buffer.snapshot_.cursor_pos_.col_);
curs_set(true);
refresh();
}
| 2,983 | 1,082 |
#include "HttpContext.h"
#include <unistd.h>
#include <iostream>
#include <bits/types/struct_iovec.h>
using namespace sing;
HttpContext::HttpContext(int fd)
:state(REQUEST_LINE),fd(fd),working(false){
assert(fd>=0);
}
HttpContext::~HttpContext(){
close(fd);// FIX ME
}
bool HttpContext::parseRequest(){
bool ok = true;
bool hasMore = true;
while (hasMore)
{
if (state == REQUEST_LINE)
{
const char* crlf = input.findCRLF();
if(crlf){
ok = parseRequestLine(input.peek(),crlf);
if(ok){
input.retrieveUntil(crlf + 2);
state = HEADERS;
}else{
hasMore = false;
}
}else{
hasMore = false;
}
}else if (state == HEADERS)
{
const char* crlf = input.findCRLF();
if(crlf){
const char* colon = std::find(input.peek(),crlf,':');
if(colon!=crlf){
request.addHeader(input.peek(),colon,crlf);
}else{
state = BODY;
hasMore = true;
}
input.retrieveUntil(crlf + 2);
}else{
hasMore = false;
}
}else if (state==BODY)
{
//TO ADD: process requestbody
state = FINSH;
hasMore = false;
}
}
return ok;
}
bool HttpContext::parseRequestLine(const char* begin, const char* end){
bool success = false;
const char* start = begin;
const char* space = std::find(start, end, ' ');//find the 1st space in a line
if(space!=end && request.setMethod(start,space)){
start = space + 1;
space = std::find(start, end, ' ');
if(space!=end){
const char* quest = std::find(start, space, '?');
if (quest!=space)
{
request.setPath(start,quest);
request.setQuery(quest, space);
}else{
request.setPath(start, space);
}
//parse http version
start = space + 1;
success = end-start == 8 && std::equal(start, end-1, "HTTP/1.");
if(success){
if(*(end-1)=='1'){
request.setVersion(HttpRequest::HTTP11);
}else if(*(end-1)=='0'){
request.setVersion(HttpRequest::HTTP10);
}else{
success = false;
}
}
}
}
return success;
}
bool HttpContext::parseFinsh(){
return state == FINSH;
}
void HttpContext::reset(){
state = REQUEST_LINE;
input.retrieveAll();
output.retrieveAll();
output.setWriteFile(NULL, 0);
request.reset();
response.reset();
}
| 2,887 | 867 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mp4/video_codecs.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
namespace media {
// The names come from src/third_party/ffmpeg/libavcodec/codec_desc.c
std::string GetCodecName(VideoCodec codec) {
switch (codec) {
case kUnknownVideoCodec:
return "unknown";
case kCodecH264:
return "h264";
case kCodecHEVC:
return "hevc";
case kCodecVC1:
return "vc1";
case kCodecMPEG2:
return "mpeg2video";
case kCodecMPEG4:
return "mpeg4";
case kCodecTheora:
return "theora";
case kCodecVP8:
return "vp8";
case kCodecVP9:
return "vp9";
}
NOTREACHED();
return "";
}
std::string GetProfileName(VideoCodecProfile profile) {
switch (profile) {
case VIDEO_CODEC_PROFILE_UNKNOWN:
return "unknown";
case H264PROFILE_BASELINE:
return "h264 baseline";
case H264PROFILE_MAIN:
return "h264 main";
case H264PROFILE_EXTENDED:
return "h264 extended";
case H264PROFILE_HIGH:
return "h264 high";
case H264PROFILE_HIGH10PROFILE:
return "h264 high 10";
case H264PROFILE_HIGH422PROFILE:
return "h264 high 4:2:2";
case H264PROFILE_HIGH444PREDICTIVEPROFILE:
return "h264 high 4:4:4 predictive";
case H264PROFILE_SCALABLEBASELINE:
return "h264 scalable baseline";
case H264PROFILE_SCALABLEHIGH:
return "h264 scalable high";
case H264PROFILE_STEREOHIGH:
return "h264 stereo high";
case H264PROFILE_MULTIVIEWHIGH:
return "h264 multiview high";
case HEVCPROFILE_MAIN:
return "hevc main";
case HEVCPROFILE_MAIN10:
return "hevc main 10";
case HEVCPROFILE_MAIN_STILL_PICTURE:
return "hevc main still-picture";
case VP8PROFILE_ANY:
return "vp8";
case VP9PROFILE_PROFILE0:
return "vp9 profile0";
case VP9PROFILE_PROFILE1:
return "vp9 profile1";
case VP9PROFILE_PROFILE2:
return "vp9 profile2";
case VP9PROFILE_PROFILE3:
return "vp9 profile3";
}
NOTREACHED();
return "";
}
bool ParseAVCCodecId(const std::string& codec_id,
VideoCodecProfile* profile,
uint8_t* level_idc) {
// Make sure we have avc1.xxxxxx or avc3.xxxxxx , where xxxxxx are hex digits
if (!base::StartsWith(codec_id, "avc1.", base::CompareCase::SENSITIVE) &&
!base::StartsWith(codec_id, "avc3.", base::CompareCase::SENSITIVE)) {
return false;
}
uint32_t elem = 0;
if (codec_id.size() != 11 ||
!base::HexStringToUInt(base::StringPiece(codec_id).substr(5), &elem)) {
DVLOG(4) << __FUNCTION__ << ": invalid avc codec id (" << codec_id << ")";
return false;
}
uint8_t level_byte = elem & 0xFF;
uint8_t constraints_byte = (elem >> 8) & 0xFF;
uint8_t profile_idc = (elem >> 16) & 0xFF;
// Check that the lower two bits of |constraints_byte| are zero (those are
// reserved and must be zero according to ISO IEC 14496-10).
if (constraints_byte & 3) {
DVLOG(4) << __FUNCTION__ << ": non-zero reserved bits in codec id "
<< codec_id;
return false;
}
VideoCodecProfile out_profile = VIDEO_CODEC_PROFILE_UNKNOWN;
// profile_idc values for each profile are taken from ISO IEC 14496-10 and
// https://en.wikipedia.org/wiki/H.264/MPEG-4_AVC#Profiles
switch (profile_idc) {
case 66:
out_profile = H264PROFILE_BASELINE;
break;
case 77:
out_profile = H264PROFILE_MAIN;
break;
case 83:
out_profile = H264PROFILE_SCALABLEBASELINE;
break;
case 86:
out_profile = H264PROFILE_SCALABLEHIGH;
break;
case 88:
out_profile = H264PROFILE_EXTENDED;
break;
case 100:
out_profile = H264PROFILE_HIGH;
break;
case 110:
out_profile = H264PROFILE_HIGH10PROFILE;
break;
case 118:
out_profile = H264PROFILE_MULTIVIEWHIGH;
break;
case 122:
out_profile = H264PROFILE_HIGH422PROFILE;
break;
case 128:
out_profile = H264PROFILE_STEREOHIGH;
break;
case 244:
out_profile = H264PROFILE_HIGH444PREDICTIVEPROFILE;
break;
default:
DVLOG(1) << "Warning: unrecognized AVC/H.264 profile " << profile_idc;
return false;
}
// TODO(servolk): Take into account also constraint set flags 3 through 5.
uint8_t constraint_set0_flag = (constraints_byte >> 7) & 1;
uint8_t constraint_set1_flag = (constraints_byte >> 6) & 1;
uint8_t constraint_set2_flag = (constraints_byte >> 5) & 1;
if (constraint_set2_flag && out_profile > H264PROFILE_EXTENDED) {
out_profile = H264PROFILE_EXTENDED;
}
if (constraint_set1_flag && out_profile > H264PROFILE_MAIN) {
out_profile = H264PROFILE_MAIN;
}
if (constraint_set0_flag && out_profile > H264PROFILE_BASELINE) {
out_profile = H264PROFILE_BASELINE;
}
if (level_idc)
*level_idc = level_byte;
if (profile)
*profile = out_profile;
return true;
}
} // namespace media
| 5,230 | 2,090 |
//
// q9.cpp
// Algorithm
//
// Created by Mohd Shoaib Rayeen on 13/11/18.
// Copyright © 2018 Shoaib Rayeen. All rights reserved.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class triathlon {
/*
------------------------------------------------------------------------------------------------
objective : class to decide the order to minimize completion time
------------------------------------------------------------------------------------------------
input parameter : none
------------------------------------------------------------------------------------------------
output parameter : none
------------------------------------------------------------------------------------------------
approach : declaring member functions which can ve accessed publicly -
mainFunction() -> to decide order
display() -> print user's data
helper() -> to insert dara and call member functions
------------------------------------------------------------------------------------------------
*/
public:
int n;
void mainFunction(vector<vector<int>> &data);
void display(vector<vector<int>> data);
void helper();
};
bool selectColumn(const vector<int>& v1, const vector<int>& v2) {
/*
------------------------------------------------------------------------------------------------
objective : select column by which sorting can be applied -> increasing order
------------------------------------------------------------------------------------------------
input parameter : none
------------------------------------------------------------------------------------------------
output parameter : false -> decreasing order
true -> increasing order
------------------------------------------------------------------------------------------------
approach : return bool value which detmines which column has to sorted
------------------------------------------------------------------------------------------------
*/
return v1[1] < v2[1];
}
void triathlon::mainFunction(vector<vector<int>> &data) {
/*
------------------------------------------------------------------------------------------------
objective : main function to decide the order
------------------------------------------------------------------------------------------------
input parameter : none
------------------------------------------------------------------------------------------------
output parameter : none
------------------------------------------------------------------------------------------------
approach : sorting according to swim time and displaying order
------------------------------------------------------------------------------------------------
*/
sort(data.begin() , data.end() , selectColumn );
cout << "\nFollowings are the order of contestants for small completion time\n\n";
for (int i = 0; i < data.size(); i++) {
cout << data[i][0] << "\t";
}
cout << endl;
}
void triathlon::display(vector<vector<int>> data) {
/*
------------------------------------------------------------------------------------------------
objective : print the data
------------------------------------------------------------------------------------------------
input parameter : none
------------------------------------------------------------------------------------------------
output parameter : none
------------------------------------------------------------------------------------------------
approach : displaying using loop
------------------------------------------------------------------------------------------------
*/
cout << "\n-----------------------------------------------------------------";
cout << "\nContestant Number\t|\tSwim Time\t|\tBike Time\t|\tRun Time\n";
cout << "-----------------------------------------------------------------\n";
for ( int i = 0; i < data.size(); i++ ) {
cout << "\t\t" << data[i][0] << "\t\t\t|\t\t" << data[i][1] << "\t\t|\t\t" << data[i][2] << "\t\t|\t" << data[i][3];
cout << endl;
}
}
void triathlon::helper() {
/*
------------------------------------------------------------------------------------------------
objective : insert the data and call member functions
------------------------------------------------------------------------------------------------
input parameter : none
------------------------------------------------------------------------------------------------
output parameter : none
------------------------------------------------------------------------------------------------
approach : insertion using loop and then calling member functions
------------------------------------------------------------------------------------------------
*/
/*
vector<vector<int>> data{
{ 1 , 52 , 13 , 15} ,
{ 2 , 19 , 17 , 13} ,
{ 3 , 99 , 13 , 10 } ,
{ 4 , 79 , 18 , 17 } ,
{ 5 , 37 , 13 , 14 } ,
{ 6 , 67 , 10 , 14 } ,
{ 7 , 89 , 13 , 19}
};
*/
cout << "\nEnter Number of contestants\t:\t";
cin >> n;
vector<vector<int>> data(n);
cout << "\nEnter Value in this form\n";
cout << "\nSwim Time , Bike Time and then Run Time\n";
for ( int i = 0; i < n; i++) {
data[i] = vector<int>(4);
data[i][0] = i + 1;
cin >> data[i][1];
cin >> data[i][2];
cin >> data[i][3];
}
display(data);
mainFunction(data);
data.clear();
}
int main() {
triathlon obj;
obj.helper();
return 0;
}
| 6,046 | 1,383 |
#include "core/events.h"
#include <algorithm>
#include "core/logger.h"
#include "ui/imgui_wrapper.h" //<! used for UI events preemption.
// ----------------------------------------------------------------------------
void Events::prepareNextFrame() {
// Reset per-frame values.
mouse_moved_ = false;
mouse_hover_ui_ = false;
has_resized_ = false;
last_input_char_ = 0;
mouse_wheel_delta_ = 0.0f;
dropped_filenames_.clear();
// Detect if any mouse buttons are still "Pressed" or "Down".
mouse_button_down_ = std::any_of(buttons_.cbegin(), buttons_.cend(), [](auto const& btn) {
auto const state(btn.second);
return (state == KeyState::Down) || (state == KeyState::Pressed);
});
// Update "Pressed" states to "Down", "Released" states to "Up".
auto const update_state{ [](auto& btn) {
auto const state(btn.second);
btn.second = (state == KeyState::Pressed) ? KeyState::Down :
(state == KeyState::Released) ? KeyState::Up : state;
}};
std::for_each(buttons_.begin(), buttons_.end(), update_state);
std::for_each(keys_.begin(), keys_.end(), update_state);
}
// ----------------------------------------------------------------------------
/* Bypass events capture when pointer hovers UI. */
#define EVENTS_IMGUI_BYPASS_( code, bMouse, bKeyboard ) \
{ \
auto &io{ImGui::GetIO()}; \
mouse_hover_ui_ = io.WantCaptureMouse; \
{ code ;} \
if ((bMouse) && (bKeyboard)) { return; } \
}
/* Bypass if the UI want the mouse */
#define EVENTS_IMGUI_BYPASS_MOUSE( code ) \
EVENTS_IMGUI_BYPASS_(code, io.WantCaptureMouse, true)
/* Bypass if the UI want the pointer or the keyboard. */
#define EVENTS_IMGUI_BYPASS_MOUSE_KB( code ) \
EVENTS_IMGUI_BYPASS_(code, io.WantCaptureMouse, io.WantCaptureKeyboard)
/* Do not bypass. */
#define EVENTS_IMGUI_CONTINUE( code ) \
EVENTS_IMGUI_BYPASS_(code, false, false)
/* Dispatch event signal to sub callbacks handlers. */
#define EVENTS_DISPATCH_SIGNAL( funcName, ... ) \
static_assert( std::string_view(#funcName)==__func__, "Incorrect dispatch signal used."); \
std::for_each(event_callbacks_.begin(), event_callbacks_.end(), [__VA_ARGS__](auto &e){ e->funcName(__VA_ARGS__); })
// ----------------------------------------------------------------------------
void Events::onKeyPressed(KeyCode_t key) {
EVENTS_IMGUI_CONTINUE(
if (io.WantCaptureKeyboard || io.WantCaptureMouse) {
io.KeysDown[key] = true;
}
);
keys_[key] = KeyState::Pressed;
key_pressed_.push( key );
EVENTS_DISPATCH_SIGNAL(onKeyPressed, key);
}
void Events::onKeyReleased(KeyCode_t key) {
EVENTS_IMGUI_CONTINUE(
if (io.WantCaptureKeyboard || io.WantCaptureMouse) {
io.KeysDown[key] = false;
}
);
keys_[key] = KeyState::Released;
EVENTS_DISPATCH_SIGNAL(onKeyReleased, key);
}
void Events::onInputChar(uint16_t c) {
EVENTS_IMGUI_BYPASS_MOUSE_KB(
if (io.WantCaptureKeyboard) { io.AddInputCharacter(c); }
);
last_input_char_ = c;
EVENTS_DISPATCH_SIGNAL(onInputChar, c);
}
void Events::onMousePressed(int x, int y, KeyCode_t button) {
EVENTS_IMGUI_BYPASS_MOUSE(
io.MouseDown[button] = true;
io.MousePos = ImVec2((float)x, (float)y);
);
buttons_[button] = KeyState::Pressed;
EVENTS_DISPATCH_SIGNAL(onMousePressed, x, y, button);
}
void Events::onMouseReleased(int x, int y, KeyCode_t button) {
EVENTS_IMGUI_BYPASS_MOUSE(
io.MouseDown[button] = false;
io.MousePos = ImVec2((float)x, (float)y);
);
buttons_[button] = KeyState::Released;
EVENTS_DISPATCH_SIGNAL(onMouseReleased, x, y, button);
}
void Events::onMouseEntered(int x, int y) {
EVENTS_DISPATCH_SIGNAL(onMouseEntered, x, y);
}
void Events::onMouseExited(int x, int y) {
EVENTS_DISPATCH_SIGNAL(onMouseExited, x, y);
}
void Events::onMouseMoved(int x, int y) {
EVENTS_IMGUI_BYPASS_MOUSE();
mouse_x_ = x;
mouse_y_ = y;
mouse_moved_ = true;
EVENTS_DISPATCH_SIGNAL(onMouseMoved, x, y);
}
void Events::onMouseDragged(int x, int y, KeyCode_t button) {
EVENTS_IMGUI_BYPASS_MOUSE(
io.MouseDown[button] = true;
io.MousePos = ImVec2((float)x, (float)y);
);
mouse_x_ = x;
mouse_y_ = y;
mouse_moved_ = true;
// (note : the button should already be registered as pressed / down)
EVENTS_DISPATCH_SIGNAL(onMouseDragged, x, y, button);
}
void Events::onMouseWheel(float dx, float dy) {
EVENTS_IMGUI_BYPASS_MOUSE(
io.MouseWheelH += dx;
io.MouseWheel += dy;
);
mouse_wheel_delta_ = dy;
mouse_wheel_ += dy;
EVENTS_DISPATCH_SIGNAL(onMouseWheel, dx, dy);
}
void Events::onResize(int w, int h) {
// EVENTS_IMGUI_CONTINUE(
// io.DisplaySize = ImVec2(static_cast<float>(w), static_cast<float>(h));
// io.DisplayFramebufferScale = ImVec2( 1.0f, 1.0f); //
// );
// [beware : downcast from int32 to int16]
surface_w_ = static_cast<SurfaceSize>(w);
surface_h_ = static_cast<SurfaceSize>(h);
has_resized_ = true;
EVENTS_DISPATCH_SIGNAL(onResize, w, h);
}
void Events::onFilesDropped(int count, char const** paths) {
for (int i=0; i<count; ++i) {
dropped_filenames_.push_back(std::string(paths[i]));
}
EVENTS_DISPATCH_SIGNAL(onFilesDropped, count, paths);
}
#undef EVENTS_IMGUI_BYPASS
#undef EVENTS_DISPATCH_SIGNAL
// ----------------------------------------------------------------------------
bool Events::buttonDown(KeyCode_t button) const noexcept {
return checkButtonState( button, [](KeyState state) {
return (state == KeyState::Pressed) || (state == KeyState::Down);
});
}
bool Events::buttonPressed(KeyCode_t button) const noexcept {
return checkButtonState( button, [](KeyState state) {
return (state == KeyState::Pressed);
});
}
bool Events::buttonReleased(KeyCode_t button) const noexcept {
return checkButtonState( button, [](KeyState state) {
return (state == KeyState::Released);
});
}
// ----------------------------------------------------------------------------
bool Events::keyDown(KeyCode_t key) const noexcept {
return checkKeyState( key, [](KeyState state) {
return (state == KeyState::Pressed) || (state == KeyState::Down);
});
}
bool Events::keyPressed(KeyCode_t key) const noexcept {
return checkKeyState( key, [](KeyState state) {
return (state == KeyState::Pressed);
});
}
bool Events::keyReleased(KeyCode_t key) const noexcept {
return checkKeyState( key, [](KeyState state) {
return (state == KeyState::Released);
});
}
// ----------------------------------------------------------------------------
bool Events::checkButtonState(KeyCode_t button, StatePredicate_t predicate) const noexcept {
if (auto search = buttons_.find(button); search != buttons_.end()) {
return predicate(search->second);
}
return false;
}
bool Events::checkKeyState(KeyCode_t key, StatePredicate_t predicate) const noexcept {
if (auto search = keys_.find(key); search != keys_.end()) {
return predicate(search->second);
}
return false;
}
// ----------------------------------------------------------------------------
#if 0
namespace {
void keyboard_cb(GLFWwindow *window, int key, int, int action, int) {
// [temporary]
if ((key >= GLFW_KEY_KP_0) && (key <= GLFW_KEY_KP_9)) {
s_Global.bKeypad |= (action == GLFW_PRESS);
s_Global.bKeypad &= (action != GLFW_RELEASE);
}
// When the UI capture keyboard, don't process it.
ImGuiIO& io = ImGui::GetIO();
if (io.WantCaptureKeyboard || io.WantCaptureMouse) {
io.KeysDown[key] = (action == GLFW_PRESS);
io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
//return;
}
UpdateButton(key, action, GLFW_KEY_LEFT_CONTROL, s_Global.bLeftCtrl);
UpdateButton(key, action, GLFW_KEY_LEFT_ALT, s_Global.bLeftAlt);
UpdateButton(key, action, GLFW_KEY_LEFT_SHIFT, s_Global.bLeftShift);
}
} // namespace
// ----------------------------------------------------------------------------
#endif
| 8,234 | 3,098 |
#include "gtest/gtest.h"
#include <fstream>
#include "polytope.hpp"
#include "polytope_examples.hpp"
using namespace OB;
TEST(TESTConvexPolytope, basicTest) {
std::vector<Point> points;
points.push_back(Point(-1, -1, -1));
points.push_back(Point(-1, -1, 1));
points.push_back(Point(-1, 1, -1));
points.push_back(Point(-1, 1, 1));
points.push_back(Point(1, -1, -1));
points.push_back(Point(1, -1, 1));
points.push_back(Point(1, 1, -1));
points.push_back(Point(1, 1, 1));
ConvexPolytope poly;
poly.generate_from_vertices(points);
ASSERT_EQ(poly.euler_number_correct(), true);
//TODO ASSERT, 8 VERTICES, 6 FACES
//TODO CHECK ONE FACE CCW.
//TODO ASSERT EULER NUMBER
std::vector<std::pair<Feature, Plane>> allfacesplanes = poly.get_faces_with_planes();
ASSERT_EQ(allfacesplanes.size(), 6);
Feature f0 = allfacesplanes[0].first;
ASSERT_EQ(poly.get_face_edgepoints(f0).size(), 4);
ASSERT_EQ(poly.get_scan_face(f0).size(), 8);
std::cout << poly << std::endl;
}
TEST(TESTConvexPolytope, testPrismPolytope) {
std::shared_ptr<OB::ConvexPolytope> prism = std::make_shared<OB::ConvexPolytope>(create_prism_polytope (3));
//std::cout << "PRISM: " << *prism << std::endl;
}
TEST(TESTConvexPolytope, shortestBetweenPointEdge) {
// distance equal segment and line
Point point{1,1,1};
Point tail{7, 7, 7};
Point head{1, 0, -1};
Vector director = head - tail;
EdgePoints edge {tail, head};
std::cout << "distance from point " << point.transpose()
<< " to segment: " << edge << std::endl;
ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 1.2040201117631721);
// now one in which the distance is smaller in the head
head = head + (tail - director*0.3);
edge = EdgePoints{tail, head};
std::cout << "distance from point " << point.transpose()
<< " to segment: " << edge << std::endl;
ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 10.392304);
// now one in which the distance is smaller in the tail
head = Point{1, 0, -1} + (tail + director*10);
tail = tail + (tail + director*10);
edge = EdgePoints{tail, head};
std::cout << "distance from point " << point.transpose()
<< " to segment: " << edge << std::endl;
ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 99.73465);
// one with the point in the line
point = Point {1,1,1};
edge = EdgePoints{{0,1,1}, {2,1,1}};
ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 0.0);
// one with the point in the line not in segment
point = Point {0,1,1};
edge = EdgePoints{{1,1,1}, {2,1,1}};
ASSERT_FLOAT_EQ(dist_point_edge(point, edge), 1.0);
}
TEST(TESTConvexPolytope, shortestBetweenEdgeEdge) {
// for line - line, we can use https://keisan.casio.com/exec/system/1223531414#
// caso degenerado, segmentos paralelos
EdgePoints edge1{Point{0, 0, 1}, Point{0, 2, 1}};
EdgePoints edge2{Point{1, 1, 0}, Point{1, -1, 0}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 1.4142135);
// otro caso degenerado, pero el punto mas cercano
// no pertenece a los segmentos.
edge1 = EdgePoints{Point{0, 0, 1}, Point{0, 2, 1}};
edge2 = EdgePoints{Point{1, -1, 0}, Point{1, -2, 0}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 1.7320508);
// mismo segmento
edge1 = EdgePoints{Point{0, 0, 1}, Point{0, 2, 1}};
edge2 = EdgePoints{Point{0, 0, 1}, Point{0, 2, 1}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 0.0);
// minimum points inside both segments
edge1 = EdgePoints{Point{0,4,2}, Point{0,0,2}};
edge2 = EdgePoints{Point{-1,3,0}, Point{2,0,0}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 2.0);
// minimum points in only one segment and one of the edges
edge1 = EdgePoints{Point{0,1.5,2}, Point{0,0,2}};
edge2 = EdgePoints{Point{-1,3,0}, Point{2,0,0}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 2.0310097);
// minimum points in two edge points
edge1 = EdgePoints{Point{0,0,1}, Point{0,0,0}};
edge2 = EdgePoints{Point{1,1,-1}, Point{1,2,-1}};
std::cout << "distance from segment: " << edge1
<< " to segment: " << edge2 << std::endl;
ASSERT_FLOAT_EQ(dist_edge_edge(edge1, edge2), 1.7320508);
}
TEST(TESTConvexPolytope, readwritefromfile) {
std::ostringstream oss;
OB::ConvexPolytope tetrahedron = create_tetrahedron_polytope(1.0);
tetrahedron.write(oss);
std::string first = oss.str();
std::istringstream iss{first};
OB::ConvexPolytope leido = OB::ConvexPolytope::create(iss);
std::ostringstream oss2;
leido.write(oss2);
std::string second = oss2.str();
ASSERT_EQ(first, second);
}
| 5,063 | 2,109 |
//
// Return CLHEP::Hep3Vector objects that are unit vectors uniformly
// distributed over the unit sphere.
//
//
// Original author Rob Kutschke
//
#include "Offline/Mu2eUtilities/inc/RandomUnitSphere.hh"
#include "Offline/Mu2eUtilities/inc/ThreeVectorUtil.hh"
namespace CLHEP { class HepRandomEngine; }
using CLHEP::Hep3Vector;
using CLHEP::RandFlat;
namespace mu2e{
RandomUnitSphere::RandomUnitSphere( CLHEP::HepRandomEngine& engine,
double czmin,
double czmax,
double phimin,
double phimax):
_czmin(czmin),
_czmax(czmax),
_phimin(phimin),
_phimax(phimax),
_randFlat( engine ){
}
RandomUnitSphere::RandomUnitSphere( CLHEP::HepRandomEngine& engine,
const RandomUnitSphereParams& pars):
_czmin(pars.czmin),
_czmax(pars.czmax),
_phimin(pars.phimin),
_phimax(pars.phimax),
_randFlat( engine ){
}
CLHEP::Hep3Vector RandomUnitSphere::fire(){
double cz = _czmin + ( _czmax - _czmin )*_randFlat.fire();
double phi = _phimin + ( _phimax - _phimin )*_randFlat.fire();
return polar3Vector ( 1., cz, phi);
}
}
| 1,269 | 438 |
#include "hypch.h"
#include <Hydra/Debug/Logging/Logger.h>
#include "spdlog/sinks/stdout_color_sinks.h"
void Hydra::Debug::Logger::Initialize()
{
const auto consoleSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
consoleSink->set_level(static_cast<spdlog::level::level_enum>(LOGGER_ACTIVE_LEVEL));
consoleSink->set_pattern("%^[%H:%M:%S] [%n] [%s:%#] %8l:%$ %v");
const spdlog::sinks_init_list sinkList = { consoleSink };
s_EngineLogger = std::make_shared<spdlog::logger>("ENGINE:CORE", sinkList.begin(), sinkList.end());
s_EngineLogger->set_level(static_cast<spdlog::level::level_enum>(LOGGER_ACTIVE_LEVEL));
s_ApplicationLogger = std::make_shared<spdlog::logger>("APPLICATION", sinkList.begin(), sinkList.end());
s_ApplicationLogger->set_level(static_cast<spdlog::level::level_enum>(LOGGER_ACTIVE_LEVEL));
spdlog::register_logger(s_EngineLogger);
spdlog::register_logger(s_ApplicationLogger);
spdlog::set_default_logger(s_EngineLogger);
spdlog::set_level(static_cast<spdlog::level::level_enum>(LOGGER_ACTIVE_LEVEL));
spdlog::set_pattern("%^[%H:%M:%S] [%n] [%s:%#] %8l:%$ %v");
LOG_ENGINE_DEBUG("Logging initialized");
}
void Hydra::Debug::Logger::Shutdown()
{
spdlog::shutdown();
}
| 1,273 | 501 |
#include "core_headers.h"
ParameterMap::ParameterMap( ) {
phi = false;
theta = false;
psi = false;
x_shift = false;
y_shift = false;
}
void ParameterMap::SetAllTrue( ) {
phi = true;
theta = true;
psi = true;
x_shift = true;
y_shift = true;
}
Particle::Particle( ) {
Init( );
}
Particle::Particle(int wanted_logical_x_dimension, int wanted_logical_y_dimension) {
Init( );
AllocateImage(wanted_logical_x_dimension, wanted_logical_y_dimension);
}
Particle::~Particle( ) {
if ( particle_image != NULL ) {
delete particle_image;
}
if ( ctf_image != NULL ) {
delete ctf_image;
}
if ( beamtilt_image != NULL ) {
delete beamtilt_image;
}
if ( bin_index != NULL ) {
delete[] bin_index;
}
}
void Particle::CopyAllButImages(const Particle* other_particle) {
// Check for self assignment
if ( this != other_particle ) {
origin_micrograph = other_particle->origin_micrograph;
origin_x_coordinate = other_particle->origin_x_coordinate;
origin_y_coordinate = other_particle->origin_y_coordinate;
location_in_stack = other_particle->location_in_stack;
pixel_size = other_particle->pixel_size;
sigma_signal = other_particle->sigma_signal;
sigma_noise = other_particle->sigma_noise;
snr = other_particle->snr;
logp = other_particle->logp;
particle_occupancy = other_particle->particle_occupancy;
particle_score = other_particle->particle_score;
alignment_parameters = other_particle->alignment_parameters;
scaled_noise_variance = other_particle->scaled_noise_variance;
parameter_constraints = other_particle->parameter_constraints;
ctf_parameters = other_particle->ctf_parameters;
current_ctf = other_particle->current_ctf;
ctf_is_initialized = other_particle->ctf_is_initialized;
ctf_image_calculated = false;
beamtilt_image_calculated = false;
includes_reference_ssnr_weighting = false;
is_normalized = false;
is_phase_flipped = false;
is_masked = false;
mask_radius = other_particle->mask_radius;
mask_falloff = other_particle->mask_falloff;
mask_volume = other_particle->mask_volume;
molecular_mass_kDa = other_particle->molecular_mass_kDa;
is_filtered = false;
filter_radius_low = other_particle->filter_radius_low;
filter_radius_high = other_particle->filter_radius_high;
filter_falloff = other_particle->filter_falloff;
filter_volume = other_particle->filter_volume;
signed_CC_limit = other_particle->signed_CC_limit;
is_ssnr_filtered = false;
is_centered_in_box = true;
shift_counter = 0;
insert_even = other_particle->insert_even;
target_phase_error = other_particle->target_phase_error;
current_parameters = other_particle->current_parameters;
temp_parameters = other_particle->temp_parameters;
parameter_average = other_particle->parameter_average;
parameter_variance = other_particle->parameter_variance;
parameter_map = other_particle->parameter_map;
constraints_used = other_particle->constraints_used;
number_of_search_dimensions = other_particle->number_of_search_dimensions;
mask_center_2d_x = other_particle->mask_center_2d_x;
mask_center_2d_y = other_particle->mask_center_2d_y;
mask_center_2d_z = other_particle->mask_center_2d_z;
mask_radius_2d = other_particle->mask_radius_2d;
apply_2D_masking = other_particle->apply_2D_masking;
no_ctf_weighting = false;
complex_ctf = other_particle->complex_ctf;
if ( particle_image != NULL ) {
delete particle_image;
particle_image = NULL;
}
if ( ctf_image != NULL ) {
delete ctf_image;
ctf_image = NULL;
}
if ( beamtilt_image != NULL ) {
delete beamtilt_image;
beamtilt_image = NULL;
}
if ( bin_index != NULL ) {
delete[] bin_index;
bin_index = NULL;
}
}
}
void Particle::Init( ) {
target_phase_error = 45.0;
origin_micrograph = -1;
origin_x_coordinate = -1;
origin_y_coordinate = -1;
location_in_stack = -1;
pixel_size = 0.0;
sigma_signal = 0.0;
sigma_noise = 0.0;
snr = 0.0;
logp = -std::numeric_limits<float>::max( );
;
particle_occupancy = 0.0;
particle_score = 0.0;
particle_image = NULL;
scaled_noise_variance = 0.0;
ctf_is_initialized = false;
ctf_image = NULL;
ctf_image_calculated = false;
beamtilt_image = NULL;
beamtilt_image_calculated = false;
includes_reference_ssnr_weighting = false;
is_normalized = false;
is_phase_flipped = false;
is_masked = false;
mask_radius = 0.0;
mask_falloff = 0.0;
mask_volume = 0.0;
molecular_mass_kDa = 0.0;
is_filtered = false;
filter_radius_low = 0.0;
filter_radius_high = 0.0;
filter_falloff = 0.0;
filter_volume = 0.0;
signed_CC_limit = 0.0;
is_ssnr_filtered = false;
is_centered_in_box = true;
shift_counter = 0;
insert_even = false;
number_of_search_dimensions = 0;
bin_index = NULL;
mask_center_2d_x = 0.0;
mask_center_2d_y = 0.0;
mask_center_2d_z = 0.0;
mask_radius_2d = 0.0;
apply_2D_masking = false;
no_ctf_weighting = false;
complex_ctf = false;
}
void Particle::AllocateImage(int wanted_logical_x_dimension, int wanted_logical_y_dimension) {
if ( particle_image == NULL ) {
particle_image = new Image;
}
particle_image->Allocate(wanted_logical_x_dimension, wanted_logical_y_dimension, 1, true);
}
void Particle::AllocateCTFImage(int wanted_logical_x_dimension, int wanted_logical_y_dimension) {
if ( ctf_image == NULL ) {
ctf_image = new Image;
}
ctf_image->Allocate(wanted_logical_x_dimension, wanted_logical_y_dimension, 1, false);
if ( beamtilt_image == NULL ) {
beamtilt_image = new Image;
}
beamtilt_image->Allocate(wanted_logical_x_dimension, wanted_logical_y_dimension, 1, false);
}
void Particle::Allocate(int wanted_logical_x_dimension, int wanted_logical_y_dimension) {
AllocateImage(wanted_logical_x_dimension, wanted_logical_y_dimension);
AllocateCTFImage(wanted_logical_x_dimension, wanted_logical_y_dimension);
}
void Particle::Deallocate( ) {
if ( particle_image != NULL ) {
delete particle_image;
particle_image = NULL;
}
if ( ctf_image != NULL ) {
delete ctf_image;
ctf_image = NULL;
}
if ( beamtilt_image != NULL ) {
delete beamtilt_image;
beamtilt_image = NULL;
}
}
void Particle::ResetImageFlags( ) {
includes_reference_ssnr_weighting = false;
is_normalized = false;
is_phase_flipped = false;
if ( is_masked ) {
is_masked = false;
mask_radius = 0.0;
mask_falloff = 0.0;
mask_volume = 0.0;
};
if ( is_filtered ) {
is_filtered = false;
filter_radius_low = 0.0;
filter_radius_high = 0.0;
filter_falloff = 0.0;
filter_volume = 0.0;
};
is_ssnr_filtered = false;
is_centered_in_box = true;
shift_counter = 0;
logp = -std::numeric_limits<float>::max( );
;
insert_even = false;
no_ctf_weighting = false;
}
void Particle::PhaseShift( ) {
MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated");
MyDebugAssertTrue(abs(shift_counter) < 2, "Image already shifted");
if ( particle_image->is_in_real_space )
particle_image->ForwardFFT( );
particle_image->PhaseShift(alignment_parameters.ReturnShiftX( ) / pixel_size, alignment_parameters.ReturnShiftY( ) / pixel_size);
shift_counter += 1;
}
void Particle::PhaseShiftInverse( ) {
MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated");
MyDebugAssertTrue(abs(shift_counter) < 2, "Image already shifted");
if ( particle_image->is_in_real_space )
particle_image->ForwardFFT( );
particle_image->PhaseShift(-alignment_parameters.ReturnShiftX( ) / pixel_size, -alignment_parameters.ReturnShiftY( ) / pixel_size);
shift_counter -= 1;
}
void Particle::Whiten(float resolution_limit) {
MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated");
MyDebugAssertTrue(! particle_image->is_in_real_space, "Image not in Fourier space");
particle_image->Whiten(resolution_limit);
}
void Particle::ForwardFFT(bool do_scaling) {
MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated");
MyDebugAssertTrue(particle_image->is_in_real_space, "Image not in real space");
particle_image->ForwardFFT(do_scaling);
}
void Particle::BackwardFFT( ) {
MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated");
MyDebugAssertTrue(! particle_image->is_in_real_space, "Image not in Fourier space");
particle_image->BackwardFFT( );
}
void Particle::CosineMask(bool invert, bool force_mask_value, float wanted_mask_value) {
MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated");
MyDebugAssertTrue(! is_masked, "Image already masked");
if ( ! particle_image->is_in_real_space )
particle_image->BackwardFFT( );
mask_volume = particle_image->CosineMask(mask_radius / pixel_size, mask_falloff / pixel_size, invert, force_mask_value, wanted_mask_value);
is_masked = true;
}
void Particle::CenterInBox( ) {
MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated");
MyDebugAssertTrue(! particle_image->object_is_centred_in_box, "Image already centered");
MyDebugAssertTrue(! is_centered_in_box, "Image already centered");
if ( particle_image->is_in_real_space )
particle_image->ForwardFFT( );
particle_image->SwapRealSpaceQuadrants( );
is_centered_in_box = true;
}
void Particle::CenterInCorner( ) {
MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated");
MyDebugAssertTrue(particle_image->object_is_centred_in_box, "Image already centered");
MyDebugAssertTrue(is_centered_in_box, "Image already in corner");
if ( particle_image->is_in_real_space )
particle_image->ForwardFFT( );
particle_image->SwapRealSpaceQuadrants( );
is_centered_in_box = false;
}
void Particle::InitCTF(float voltage_kV, float spherical_aberration_mm, float amplitude_contrast, float defocus_1, float defocus_2, float astigmatism_angle, float phase_shift, float beam_tilt_x, float beam_tilt_y, float particle_shift_x, float particle_shift_y) {
// MyDebugAssertTrue(! ctf_is_initialized, "CTF already initialized");
ctf_parameters.Init(voltage_kV, spherical_aberration_mm, amplitude_contrast, defocus_1, defocus_2, astigmatism_angle, 0.0, 0.0, 0.0, pixel_size, phase_shift, beam_tilt_x, beam_tilt_y, particle_shift_x, particle_shift_y);
ctf_is_initialized = true;
}
void Particle::SetDefocus(float defocus_1, float defocus_2, float astigmatism_angle, float phase_shift) {
MyDebugAssertTrue(ctf_is_initialized, "CTF not initialized");
ctf_parameters.SetDefocus(defocus_1 / pixel_size, defocus_2 / pixel_size, deg_2_rad(astigmatism_angle));
ctf_parameters.SetAdditionalPhaseShift(phase_shift);
}
void Particle::SetBeamTilt(float beam_tilt_x, float beam_tilt_y, float particle_shift_x, float particle_shift_y) {
MyDebugAssertTrue(ctf_is_initialized, "CTF not initialized");
ctf_parameters.SetBeamTilt(beam_tilt_x, beam_tilt_y, particle_shift_x / pixel_size, particle_shift_y / pixel_size);
}
void Particle::SetLowResolutionContrast(float low_resolution_contrast) {
MyDebugAssertTrue(ctf_is_initialized, "CTF not initialized");
ctf_parameters.SetLowResolutionContrast(low_resolution_contrast);
}
void Particle::InitCTFImage(float voltage_kV, float spherical_aberration_mm, float amplitude_contrast, float defocus_1, float defocus_2, float astigmatism_angle, float phase_shift, float beam_tilt_x, float beam_tilt_y, float particle_shift_x, float particle_shift_y, bool calculate_complex_ctf) {
MyDebugAssertTrue(ctf_image->is_in_memory, "ctf_image memory not allocated");
MyDebugAssertTrue(beamtilt_image->is_in_memory, "beamtilt_image memory not allocated");
MyDebugAssertTrue(! ctf_image->is_in_real_space, "ctf_image not in Fourier space");
MyDebugAssertTrue(! beamtilt_image->is_in_real_space, "beamtilt_image not in Fourier space");
InitCTF(voltage_kV, spherical_aberration_mm, amplitude_contrast, defocus_1, defocus_2, astigmatism_angle, phase_shift, beam_tilt_x, beam_tilt_y, particle_shift_x, particle_shift_y);
complex_ctf = calculate_complex_ctf;
if ( ctf_parameters.IsAlmostEqualTo(¤t_ctf, 1 / pixel_size) == false || ! ctf_image_calculated )
// Need to calculate current_ctf_image to be inserted into ctf_reconstruction
{
current_ctf = ctf_parameters;
ctf_image->CalculateCTFImage(current_ctf, complex_ctf);
}
if ( ctf_parameters.BeamTiltIsAlmostEqualTo(¤t_ctf) == false || ! beamtilt_image_calculated )
// Need to calculate current_beamtilt_image to correct input image for beam tilt
{
beamtilt_image->CalculateBeamTiltImage(current_ctf);
}
ctf_image_calculated = true;
beamtilt_image_calculated = true;
}
void Particle::PhaseFlipImage( ) {
MyDebugAssertTrue(ctf_image_calculated, "CTF image not calculated");
if ( particle_image->is_in_real_space )
particle_image->ForwardFFT( );
particle_image->PhaseFlipPixelWise(*ctf_image);
}
void Particle::CTFMultiplyImage( ) {
MyDebugAssertTrue(ctf_image_calculated, "CTF image not calculated");
if ( particle_image->is_in_real_space )
particle_image->ForwardFFT( );
particle_image->MultiplyPixelWiseReal(*ctf_image);
}
void Particle::BeamTiltMultiplyImage( ) {
MyDebugAssertTrue(beamtilt_image_calculated, "Beamtilt image not calculated");
if ( particle_image->is_in_real_space )
particle_image->ForwardFFT( );
particle_image->MultiplyPixelWise(*beamtilt_image);
}
void Particle::SetIndexForWeightedCorrelation(bool limit_resolution) {
MyDebugAssertTrue(particle_image->is_in_memory, "Image memory not allocated");
int i;
int j;
int k;
int bin;
float x;
float y;
float z;
float frequency;
float frequency_squared;
float low_limit2;
float high_limit2 = fminf(powf(pixel_size / filter_radius_high, 2), 0.25);
int number_of_bins = particle_image->ReturnLargestLogicalDimension( ) / 2 + 1;
int number_of_bins2 = 2 * (number_of_bins - 1);
long pixel_counter = 0;
low_limit2 = 0.0;
if ( filter_radius_low != 0.0 )
low_limit2 = powf(pixel_size / filter_radius_low, 2);
if ( bin_index != NULL )
delete[] bin_index;
bin_index = new int[particle_image->real_memory_allocated / 2];
for ( k = 0; k <= particle_image->physical_upper_bound_complex_z; k++ ) {
z = powf(particle_image->ReturnFourierLogicalCoordGivenPhysicalCoord_Z(k) * particle_image->fourier_voxel_size_z, 2);
for ( j = 0; j <= particle_image->physical_upper_bound_complex_y; j++ ) {
y = powf(particle_image->ReturnFourierLogicalCoordGivenPhysicalCoord_Y(j) * particle_image->fourier_voxel_size_y, 2);
for ( i = 0; i <= particle_image->physical_upper_bound_complex_x; i++ ) {
x = powf(i * particle_image->fourier_voxel_size_x, 2);
frequency_squared = x + y + z;
if ( (frequency_squared >= low_limit2 && frequency_squared <= high_limit2) || ! limit_resolution ) {
bin_index[pixel_counter] = int(sqrtf(frequency_squared) * number_of_bins2);
}
else {
bin_index[pixel_counter] = -1;
}
pixel_counter++;
}
}
}
}
void Particle::WeightBySSNR(Curve& SSNR, int include_reference_weighting, bool no_ctf) {
MyDebugAssertTrue(particle_image->is_in_memory, "Memory not allocated");
MyDebugAssertTrue(ctf_image->is_in_memory, "CTF image memory not allocated");
MyDebugAssertTrue(ctf_image_calculated, "CTF image not initialized");
MyDebugAssertTrue(! is_ssnr_filtered, "Already SSNR filtered");
int i;
// mask_volume = number of pixels in 2D mask applied to input images
// (4.0 * PI / 3.0 * powf(mask_volume / PI, 1.5)) = volume (number of voxels) inside sphere with radius of 2D mask
// kDa_to_Angstrom3(molecular_mass_kDa) / powf(pixel_size,3) = volume (number of pixels) inside the particle envelope
float particle_area_in_pixels = PI * powf(3.0 * (kDa_to_Angstrom3(molecular_mass_kDa) / powf(pixel_size, 3)) / 4.0 / PI, 2.0 / 3.0);
// float ssnr_scale_factor = particle_area_in_pixels / mask_volume;
float ssnr_scale_factor = particle_area_in_pixels / particle_image->logical_x_dimension / particle_image->logical_y_dimension;
// wxPrintf("particle_area_in_pixels = %g, mask_volume = %g\n", particle_area_in_pixels, mask_volume);
// float ssnr_scale_factor_old = kDa_to_Angstrom3(molecular_mass_kDa) / 4.0 / PI / powf(pixel_size,3) / (4.0 * PI / 3.0 * powf(mask_volume / PI, 1.5));
// wxPrintf("old = %g, new = %g\n", ssnr_scale_factor_old, ssnr_scale_factor);
// float ssnr_scale_factor = PI * powf( powf(3.0 * kDa_to_Angstrom3(molecular_mass_kDa) / 4.0 / PI / powf(pixel_size,3) ,1.0 / 3.0) ,2) / mask_volume;
// float ssnr_scale_factor = particle_image->logical_x_dimension * particle_image->logical_y_dimension / mask_volume;
if ( particle_image->is_in_real_space )
particle_image->ForwardFFT( );
Image* snr_image = new Image;
snr_image->Allocate(ctf_image->logical_x_dimension, ctf_image->logical_y_dimension, false);
particle_image->Whiten( );
// snr_image->CopyFrom(ctf_image);
if ( no_ctf ) {
snr_image->SetToConstant(1.0);
no_ctf_weighting = true;
}
else {
for ( i = 0; i < ctf_image->real_memory_allocated / 2; i++ ) {
snr_image->complex_values[i] = ctf_image->complex_values[i] * conj(ctf_image->complex_values[i]);
}
no_ctf_weighting = false;
}
snr_image->MultiplyByWeightsCurve(SSNR, ssnr_scale_factor);
particle_image->OptimalFilterBySNRImage(*snr_image, include_reference_weighting);
is_ssnr_filtered = true;
if ( include_reference_weighting != 0 )
includes_reference_ssnr_weighting = true;
else
includes_reference_ssnr_weighting = false;
// Apply cosine filter to reduce ringing when resolution limit higher than 7 A
// if (filter_radius_high > 0.0) particle_image->CosineMask(std::max(pixel_size / filter_radius_high, pixel_size / 7.0f + pixel_size / mask_falloff) - pixel_size / (2.0 * mask_falloff), pixel_size / mask_falloff);
delete snr_image;
}
void Particle::WeightBySSNR(Curve& SSNR, Image& projection_image, bool weight_particle_image, bool weight_projection_image) {
MyDebugAssertTrue(ctf_image_calculated, "CTF image not initialized");
MyDebugAssertTrue(! is_ssnr_filtered, "Already SSNR filtered");
particle_image->WeightBySSNR(*ctf_image, molecular_mass_kDa, pixel_size, SSNR, projection_image, weight_particle_image, weight_projection_image);
if ( weight_particle_image )
is_ssnr_filtered = true;
else
is_ssnr_filtered = false;
includes_reference_ssnr_weighting = false;
}
void Particle::CalculateProjection(Image& projection_image, ReconstructedVolume& input_3d) {
MyDebugAssertTrue(projection_image.is_in_memory, "Projection image memory not allocated");
MyDebugAssertTrue(input_3d.density_map->is_in_memory, "3D reconstruction memory not allocated");
MyDebugAssertTrue(ctf_image->is_in_memory, "CTF image memory not allocated");
MyDebugAssertTrue(ctf_image_calculated, "CTF image not initialized");
input_3d.CalculateProjection(projection_image, *ctf_image, alignment_parameters, 0.0, 0.0, 1.0, true, true, false, true, false);
if ( current_ctf.GetBeamTiltX( ) != 0.0f || current_ctf.GetBeamTiltY( ) != 0.0f )
projection_image.ConjugateMultiplyPixelWise(*beamtilt_image);
}
void Particle::GetParameters(cisTEMParameterLine& output_parameters) {
output_parameters = current_parameters;
}
void Particle::SetParameters(cisTEMParameterLine& wanted_parameters, bool initialize_scores) {
current_parameters = wanted_parameters;
if ( initialize_scores ) {
current_parameters.logp = -std::numeric_limits<float>::max( );
current_parameters.sigma = -std::numeric_limits<float>::max( );
current_parameters.score = -std::numeric_limits<float>::max( );
}
alignment_parameters.Init(current_parameters.phi, current_parameters.theta, current_parameters.psi, current_parameters.x_shift, current_parameters.y_shift);
}
void Particle::SetAlignmentParameters(float wanted_euler_phi, float wanted_euler_theta, float wanted_euler_psi, float wanted_shift_x, float wanted_shift_y) {
alignment_parameters.Init(wanted_euler_phi, wanted_euler_theta, wanted_euler_psi, wanted_shift_x, wanted_shift_y);
}
void Particle::SetParameterStatistics(cisTEMParameterLine& wanted_averages, cisTEMParameterLine& wanted_variances) {
parameter_average = wanted_averages;
parameter_variance = wanted_variances;
}
void Particle::SetParameterConstraints(float wanted_noise_variance) {
MyDebugAssertTrue(! constraints_used.phi || parameter_variance.phi > 0.0, "Phi variance not positive");
MyDebugAssertTrue(! constraints_used.theta || parameter_variance.theta > 0.0, "Theta variance not positive");
MyDebugAssertTrue(! constraints_used.psi || parameter_variance.psi > 0.0, "Psi variance not positive");
MyDebugAssertTrue(! constraints_used.x_shift || parameter_variance.x_shift > 0.0, "Shift_X variance not positive");
MyDebugAssertTrue(! constraints_used.y_shift || parameter_variance.y_shift > 0.0, "Shift_Y variance not positive");
scaled_noise_variance = wanted_noise_variance;
if ( constraints_used.phi )
parameter_constraints.InitPhi(parameter_average.phi, parameter_variance.phi, scaled_noise_variance);
if ( constraints_used.theta )
parameter_constraints.InitTheta(parameter_average.theta, parameter_variance.theta, scaled_noise_variance);
if ( constraints_used.psi )
parameter_constraints.InitPsi(parameter_average.psi, parameter_variance.psi, scaled_noise_variance);
if ( constraints_used.x_shift )
parameter_constraints.InitShiftX(parameter_average.x_shift, parameter_variance.x_shift, scaled_noise_variance);
if ( constraints_used.y_shift )
parameter_constraints.InitShiftY(parameter_average.y_shift, parameter_variance.y_shift, scaled_noise_variance);
}
float Particle::ReturnParameterPenalty(cisTEMParameterLine& parameters) {
float penalty = 0.0;
// Assume that sigma_noise is approximately equal to sigma_image, i.e. the SNR in the image is very low
if ( constraints_used.phi )
penalty += sigma_noise / mask_volume * parameter_constraints.ReturnPhiAngleLogP(parameters.phi);
if ( constraints_used.theta )
penalty += sigma_noise / mask_volume * parameter_constraints.ReturnThetaAngleLogP(parameters.theta);
if ( constraints_used.psi )
penalty += sigma_noise / mask_volume * parameter_constraints.ReturnPsiAngleLogP(parameters.psi);
if ( constraints_used.x_shift )
penalty += sigma_noise / mask_volume * parameter_constraints.ReturnShiftXLogP(parameters.x_shift);
if ( constraints_used.y_shift )
penalty += sigma_noise / mask_volume * parameter_constraints.ReturnShiftYLogP(parameters.y_shift);
return penalty;
}
float Particle::ReturnParameterLogP(cisTEMParameterLine& parameters) {
float logp = 0.0;
if ( constraints_used.phi )
logp += parameter_constraints.ReturnPhiAngleLogP(parameters.phi);
if ( constraints_used.theta )
logp += parameter_constraints.ReturnThetaAngleLogP(parameters.theta);
if ( constraints_used.psi )
logp += parameter_constraints.ReturnPsiAngleLogP(parameters.psi);
if ( constraints_used.x_shift )
logp += parameter_constraints.ReturnShiftXLogP(parameters.x_shift);
if ( constraints_used.y_shift )
logp += parameter_constraints.ReturnShiftYLogP(parameters.y_shift);
return logp;
}
int Particle::MapParameterAccuracy(float* accuracies) {
cisTEMParameterLine accuracy_line;
accuracy_line.psi = target_phase_error / (1.0 / filter_radius_high * 2.0 * PI * mask_radius) / 5.0;
accuracy_line.theta = target_phase_error / (1.0 / filter_radius_high * 2.0 * PI * mask_radius) / 5.0;
accuracy_line.phi = target_phase_error / (1.0 / filter_radius_high * 2.0 * PI * mask_radius) / 5.0;
accuracy_line.x_shift = deg_2_rad(target_phase_error) / (1.0 / filter_radius_high * 2.0 * PI * pixel_size) / 5.0;
accuracy_line.y_shift = deg_2_rad(target_phase_error) / (1.0 / filter_radius_high * 2.0 * PI * pixel_size) / 5.0;
number_of_search_dimensions = MapParametersFromExternal(accuracy_line, accuracies);
return number_of_search_dimensions;
}
int Particle::MapParametersFromExternal(cisTEMParameterLine& input_parameters, float* mapped_parameters) {
int i;
int j = 0;
if ( parameter_map.phi == true ) {
mapped_parameters[j] = input_parameters.phi;
j++;
}
if ( parameter_map.theta == true ) {
mapped_parameters[j] = input_parameters.theta;
j++;
}
if ( parameter_map.psi == true ) {
mapped_parameters[j] = input_parameters.psi;
j++;
}
if ( parameter_map.x_shift == true ) {
mapped_parameters[j] = input_parameters.x_shift;
j++;
}
if ( parameter_map.y_shift == true ) {
mapped_parameters[j] = input_parameters.y_shift;
j++;
}
return j;
}
int Particle::MapParameters(float* mapped_parameters) {
int i;
int j = 0;
if ( parameter_map.phi == true ) {
mapped_parameters[j] = current_parameters.phi;
j++;
}
if ( parameter_map.theta == true ) {
mapped_parameters[j] = current_parameters.theta;
j++;
}
if ( parameter_map.psi == true ) {
mapped_parameters[j] = current_parameters.psi;
j++;
}
if ( parameter_map.x_shift == true ) {
mapped_parameters[j] = current_parameters.x_shift;
j++;
}
if ( parameter_map.y_shift == true ) {
mapped_parameters[j] = current_parameters.y_shift;
j++;
}
return j;
}
int Particle::UnmapParametersToExternal(cisTEMParameterLine& output_parameters, float* mapped_parameters) {
int i;
int j = 0;
if ( parameter_map.phi == true ) {
output_parameters.phi = mapped_parameters[j];
j++;
}
if ( parameter_map.theta == true ) {
output_parameters.theta = mapped_parameters[j];
j++;
}
if ( parameter_map.psi == true ) {
output_parameters.psi = mapped_parameters[j];
j++;
}
if ( parameter_map.x_shift == true ) {
output_parameters.x_shift = mapped_parameters[j];
j++;
}
if ( parameter_map.y_shift == true ) {
output_parameters.y_shift = mapped_parameters[j];
j++;
}
return j;
}
int Particle::UnmapParameters(float* mapped_parameters) {
int i;
int j = 0;
if ( parameter_map.phi == true ) {
current_parameters.phi = mapped_parameters[j];
j++;
}
if ( parameter_map.theta == true ) {
current_parameters.theta = mapped_parameters[j];
j++;
}
if ( parameter_map.psi == true ) {
current_parameters.psi = mapped_parameters[j];
j++;
}
if ( parameter_map.x_shift == true ) {
current_parameters.x_shift = mapped_parameters[j];
j++;
}
if ( parameter_map.y_shift == true ) {
current_parameters.y_shift = mapped_parameters[j];
j++;
}
alignment_parameters.Init(current_parameters.phi, current_parameters.theta, current_parameters.psi, current_parameters.x_shift, current_parameters.y_shift);
return j;
}
float Particle::ReturnLogLikelihood(Image& input_image, CTF& input_ctf, ReconstructedVolume& input_3d, ResolutionStatistics& statistics,
float classification_resolution_limit, float* frealign_score) {
//!!! MyDebugAssertTrue(is_ssnr_filtered, "particle_image not filtered");
float number_of_independent_pixels;
float variance_masked;
float variance_difference;
float variance_particle;
float variance_projection;
float rotated_center_x;
float rotated_center_y;
float rotated_center_z;
float alpha;
float sigma;
float original_pixel_size = pixel_size * float(particle_image->logical_x_dimension) / float(input_image.logical_x_dimension);
// float effective_bfactor;
float pixel_center_2d_x = mask_center_2d_x / original_pixel_size - input_image.physical_address_of_box_center_x;
float pixel_center_2d_y = mask_center_2d_y / original_pixel_size - input_image.physical_address_of_box_center_y;
// Assumes cubic reference volume
float pixel_center_2d_z = mask_center_2d_z / original_pixel_size - input_image.physical_address_of_box_center_x;
float pixel_radius_2d = mask_radius_2d / original_pixel_size;
Image* temp_image1 = new Image;
temp_image1->Allocate(particle_image->logical_x_dimension, particle_image->logical_y_dimension, false);
Image* temp_image2 = new Image;
// temp_image2->Allocate(binned_image_box_size, binned_image_box_size, false);
Image* projection_image = new Image;
projection_image->Allocate(input_image.logical_x_dimension, input_image.logical_y_dimension, false);
Image* temp_projection = new Image;
temp_projection->Allocate(input_image.logical_x_dimension, input_image.logical_y_dimension, false);
Image* temp_particle = new Image;
temp_particle->Allocate(input_image.logical_x_dimension, input_image.logical_y_dimension, false);
Image* ctf_input_image = new Image;
ctf_input_image->Allocate(input_image.logical_x_dimension, input_image.logical_y_dimension, false);
Image* beamtilt_input_image = new Image;
beamtilt_input_image->Allocate(input_image.logical_x_dimension, input_image.logical_y_dimension, false);
// if (filter_radius_high != 0.0)
// {
// effective_bfactor = 2.0 * powf(original_pixel_size / filter_radius_high, 2);
// }
// else
// {
// effective_bfactor = 0.0;
// }
// ResetImageFlags();
// mask_volume = PI * powf(mask_radius / original_pixel_size, 2);
// is_ssnr_filtered = false;
// is_centered_in_box = true;
// CenterInCorner();
// input_3d.CalculateProjection(*projection_image, *ctf_image, alignment_parameters, mask_radius, mask_falloff, original_pixel_size / filter_radius_high, false, true);
input_3d.density_map->ExtractSlice(*temp_image1, alignment_parameters, pixel_size / filter_radius_high);
if ( frealign_score != NULL ) {
temp_image2->Allocate(particle_image->logical_x_dimension, particle_image->logical_y_dimension, false);
temp_image2->CopyFrom(temp_image1);
if ( no_ctf_weighting )
input_3d.CalculateProjection(*temp_image2, *ctf_image, alignment_parameters, 0.0, 0.0, pixel_size / filter_radius_high, false, false, false, false, false, false);
// Case for normal parameter refinement with weighting applied to particle images and 3D reference
else if ( includes_reference_ssnr_weighting )
input_3d.CalculateProjection(*temp_image2, *ctf_image, alignment_parameters, 0.0, 0.0, pixel_size / filter_radius_high, false, true, true, false, false, false);
// Case for normal parameter refinement with weighting applied only to particle images
else
input_3d.CalculateProjection(*temp_image2, *ctf_image, alignment_parameters, 0.0, 0.0, pixel_size / filter_radius_high, false, true, false, true, true, false);
*frealign_score = -particle_image->GetWeightedCorrelationWithImage(*temp_image2, bin_index, pixel_size / signed_CC_limit) - ReturnParameterPenalty(current_parameters);
// wxPrintf("pixel_size, signed_CC_limit, filter_radius_high, frealign_score = %g %g %g\n", pixel_size, signed_CC_limit, filter_radius_high, *frealign_score);
}
temp_image1->SwapRealSpaceQuadrants( );
temp_image1->BackwardFFT( );
temp_image1->AddConstant(-temp_image1->ReturnAverageOfRealValues(mask_radius / pixel_size, true));
temp_image1->CosineMask(mask_radius / pixel_size, mask_falloff / pixel_size, false, true, 0.0);
temp_image1->ForwardFFT( );
temp_image2->CopyFrom(temp_image1);
ctf_input_image->CalculateCTFImage(input_ctf);
beamtilt_input_image->CalculateBeamTiltImage(input_ctf);
if ( includes_reference_ssnr_weighting )
temp_image1->Whiten(pixel_size / filter_radius_high);
// temp_image1->PhaseFlipPixelWise(*ctf_image);
// if (input_3d.density_map->logical_x_dimension != padded_unbinned_image.logical_x_dimension) temp_image1->CosineMask(0.5 - pixel_size / 20.0, pixel_size / 10.0);
if ( input_3d.density_map->logical_x_dimension != input_image.logical_x_dimension )
temp_image1->CosineMask(0.45, 0.1);
// temp_image1->ClipInto(&padded_unbinned_image);
// padded_unbinned_image.BackwardFFT();
// padded_unbinned_image.ClipInto(projection_image);
// projection_image->ForwardFFT();
temp_image1->ClipInto(projection_image);
projection_image->PhaseFlipPixelWise(*ctf_input_image);
projection_image->MultiplyPixelWise(*beamtilt_input_image);
// temp_image2->MultiplyPixelWiseReal(*ctf_image);
// if (input_3d.density_map->logical_x_dimension != padded_unbinned_image.logical_x_dimension) temp_image2->CosineMask(0.5 - pixel_size / 20.0, pixel_size / 10.0);
if ( particle_image->logical_x_dimension != input_image.logical_x_dimension )
temp_image2->CosineMask(0.45, 0.1);
// temp_image2->ClipInto(&padded_unbinned_image);
// padded_unbinned_image.BackwardFFT();
// padded_unbinned_image.ClipInto(temp_projection);
// temp_projection->ForwardFFT();
temp_image2->ClipInto(temp_projection);
temp_projection->MultiplyPixelWiseReal(*ctf_input_image);
temp_projection->MultiplyPixelWise(*beamtilt_input_image);
// temp_projection->CopyFrom(projection_image);
// projection_image->PhaseFlipPixelWise(*ctf_image);
// temp_projection->MultiplyPixelWiseReal(*ctf_image);
// temp_projection->CopyFrom(projection_image);
if ( input_image.is_in_real_space )
input_image.ForwardFFT( );
input_image.PhaseShift(-current_parameters.x_shift / original_pixel_size, -current_parameters.y_shift / original_pixel_size);
temp_particle->CopyFrom(&input_image);
// if (includes_reference_ssnr_weighting) temp_projection->Whiten(pixel_size / filter_radius_high);
// WeightBySSNR(statistics.part_SSNR, *temp_projection, false, includes_reference_ssnr_weighting);
input_image.WeightBySSNR(*ctf_input_image, molecular_mass_kDa, original_pixel_size, statistics.part_SSNR, *projection_image, true, includes_reference_ssnr_weighting);
// if (includes_reference_ssnr_weighting) projection_image->Whiten(original_pixel_size / filter_radius_high);
// WeightBySSNR(statistics.part_SSNR, *projection_image, true, includes_reference_ssnr_weighting);
// particle_image->SwapRealSpaceQuadrants();
// particle_image->PhaseShift(- current_parameters[4] / pixel_size, - current_parameters[5] / pixel_size);
input_image.BackwardFFT( );
// temp_particle->BackwardFFT();
// projection_image->SwapRealSpaceQuadrants();
projection_image->BackwardFFT( );
// Apply some low-pass filtering to improve classification
// temp_projection->ApplyBFactor(effective_bfactor);
// temp_projection->BackwardFFT();
// input_image.QuickAndDirtyWriteSlice("part.mrc", 1);
// projection_image->QuickAndDirtyWriteSlice("proj.mrc", 1);
// temp_particle->QuickAndDirtyWriteSlice("part2.mrc", 1);
// temp_projection->QuickAndDirtyWriteSlice("proj2.mrc", 1);
// exit(0);
// Calculate LogP
// variance_masked = temp_particle->ReturnVarianceOfRealValues(mask_radius / pixel_size, 0.0, 0.0, 0.0, true);
// wxPrintf("variance_masked = %g\n", variance_masked);
// temp_particle->MultiplyByConstant(1.0 / sqrtf(variance_masked));
// alpha = temp_particle->ReturnImageScale(*temp_projection, mask_radius / pixel_size);
// temp_projection->MultiplyByConstant(alpha);
// This scaling according to the average sqrtf(SNR) should take care of variable signal strength in the images
// However, it seems to lead to some oscillatory behavior of the occupancies (from cycle to cycle)
// if (current_parameters[7] >= 0 && current_parameters[14] > 0.0) temp_projection->MultiplyByConstant(parameter_average[14] / current_parameters[14]);
// wxPrintf("alpha for logp, scaling factor = %g %g\n", alpha, parameter_average[14] / current_parameters[14]);
if ( apply_2D_masking ) {
AnglesAndShifts reverse_alignment_parameters;
reverse_alignment_parameters.Init(-current_parameters.psi, -current_parameters.theta, -current_parameters.phi, 0.0, 0.0);
reverse_alignment_parameters.euler_matrix.RotateCoords(pixel_center_2d_x, pixel_center_2d_y, pixel_center_2d_z, rotated_center_x, rotated_center_y, rotated_center_z);
// variance_masked = particle_image->ReturnVarianceOfRealValues(pixel_radius_2d, rotated_center_x + particle_image->physical_address_of_box_center_x,
// rotated_center_y + particle_image->physical_address_of_box_center_y, 0.0);
}
// else
// {
// variance_masked = particle_image->ReturnVarianceOfRealValues(mask_radius / pixel_size);
// }
temp_particle->BackwardFFT( );
temp_projection->BackwardFFT( );
// temp_particle->QuickAndDirtyWriteSlice("temp_particle.mrc", 1);
// temp_projection->QuickAndDirtyWriteSlice("temp_projection.mrc", 1);
// phase_difference->QuickAndDirtyWriteSlice("phase_difference.mrc", 1);
// exit(0);
temp_particle->SubtractImage(temp_projection);
// particle_image->QuickAndDirtyWriteSlice("diff.mrc", 1);
// This low-pass filter reduces the number of independent pixels. It should therefore be applied only to
// the reference (temp_projection), and not to the difference (temp_particle - temp_projection), as is done here...
// temp_particle->ForwardFFT();
// if (classification_resolution_limit < 20.0f) temp_particle->CosineMask(original_pixel_size / 20.0f, original_pixel_size / 10.0f, true);
if ( classification_resolution_limit > 0.0f ) {
temp_particle->ForwardFFT( );
temp_particle->CosineMask(original_pixel_size / classification_resolution_limit, original_pixel_size / mask_falloff);
// temp_particle->CosineMask(0.75f * original_pixel_size / classification_resolution_limit, original_pixel_size / classification_resolution_limit);
temp_particle->BackwardFFT( );
}
// temp_particle->BackwardFFT();
if ( apply_2D_masking ) {
variance_difference = temp_particle->ReturnSumOfSquares(pixel_radius_2d, rotated_center_x + temp_particle->physical_address_of_box_center_x,
rotated_center_y + temp_particle->physical_address_of_box_center_y, 0.0);
// sigma = sqrtf(variance_difference / temp_projection->ReturnVarianceOfRealValues(pixel_radius_2d, rotated_center_x + temp_particle->physical_address_of_box_center_x,
// rotated_center_y + temp_particle->physical_address_of_box_center_y, 0.0));
number_of_independent_pixels = PI * powf(pixel_radius_2d, 2);
}
else {
variance_difference = temp_particle->ReturnSumOfSquares(mask_radius / original_pixel_size);
// sigma = sqrtf(variance_difference / temp_projection->ReturnVarianceOfRealValues(mask_radius / pixel_size));
number_of_independent_pixels = PI * powf(mask_radius / original_pixel_size, 2);
// number_of_independent_pixels = mask_volume;
}
logp = -0.5 * (variance_difference + logf(2.0 * PI)) * number_of_independent_pixels;
// This penalty term assumes a Gaussian x,y distribution that is probably not correct in most cases. Better to leave it out.
// + ReturnParameterLogP(current_parameters);
// Calculate SNR used for particle weighting during reconstruction
input_image.CosineMask(mask_radius / original_pixel_size, mask_falloff / original_pixel_size);
// alpha = input_image.ReturnImageScale(*projection_image);
// variance_masked = projection_image->ReturnVarianceOfRealValues(mask_radius / original_pixel_size);
// projection_image->MultiplyByConstant(1.0 / sqrtf(variance_masked));
// wxPrintf("var = %g\n", variance_masked);
// alpha = input_image.ReturnImageScale(*projection_image, mask_radius / original_pixel_size);
alpha = input_image.ReturnImageScale(*projection_image);
projection_image->MultiplyByConstant(alpha);
// if (origin_micrograph < 0) origin_micrograph = 0;
// origin_micrograph++;
// input_image.QuickAndDirtyWriteSlice("part.mrc", origin_micrograph);
// projection_image->QuickAndDirtyWriteSlice("proj.mrc", origin_micrograph);
input_image.SubtractImage(projection_image);
// input_image.QuickAndDirtyWriteSlice("diff.mrc", origin_micrograph);
// exit(0);
// variance_difference = input_image.ReturnVarianceOfRealValues();
// sigma = sqrtf(variance_difference / projection_image->ReturnVarianceOfRealValues());
// variance_difference = input_image.ReturnVarianceOfRealValues(mask_radius / original_pixel_size);
// sigma = sqrtf(variance_difference / projection_image->ReturnVarianceOfRealValues(mask_radius / original_pixel_size));
variance_difference = input_image.ReturnVarianceOfRealValues( );
sigma = sqrtf(variance_difference / projection_image->ReturnVarianceOfRealValues( ));
// sigma = sqrtf(variance_difference / powf(alpha, 2));
// wxPrintf("variance_difference, alpha for sigma, sigma = %g %g %g\n", variance_difference, alpha, sigma);
// Prevent rare occurrences of unrealistically high sigmas
if ( sigma > 100.0 )
sigma = 100.0;
if ( sigma > 0.0 )
snr = powf(1.0 / sigma, 2);
else
snr = 0.0;
// wxPrintf("number_of_independent_pixels = %g, variance_difference = %g, variance_masked = %g, logp = %g\n", number_of_independent_pixels,
// variance_difference, variance_masked, -number_of_independent_pixels * variance_difference / variance_masked / 2.0);
// exit(0);
// return - number_of_independent_pixels * variance_difference / variance_masked / 2.0
// + ReturnParameterLogP(current_parameters);
delete temp_image1;
delete temp_image2;
delete projection_image;
delete temp_particle;
delete temp_projection;
delete ctf_input_image;
delete beamtilt_input_image;
return logp;
}
void Particle::CalculateMaskedLogLikelihood(Image& projection_image, ReconstructedVolume& input_3d, float classification_resolution_limit) {
//!!! MyDebugAssertTrue(is_ssnr_filtered, "particle_image not filtered");
// float ssq_XA, ssq_A2;
float alpha;
float variance_masked;
float variance_difference;
float rotated_center_x;
float rotated_center_y;
float rotated_center_z;
float pixel_center_2d_x = mask_center_2d_x / pixel_size - particle_image->physical_address_of_box_center_x;
float pixel_center_2d_y = mask_center_2d_y / pixel_size - particle_image->physical_address_of_box_center_y;
// Assumes cubic reference volume
float pixel_center_2d_z = mask_center_2d_z / pixel_size - particle_image->physical_address_of_box_center_x;
float pixel_radius_2d = mask_radius_2d / pixel_size;
AnglesAndShifts reverse_alignment_parameters;
reverse_alignment_parameters.Init(-current_parameters.psi, -current_parameters.theta, -current_parameters.phi, 0.0, 0.0);
reverse_alignment_parameters.euler_matrix.RotateCoords(pixel_center_2d_x, pixel_center_2d_y, pixel_center_2d_z, rotated_center_x, rotated_center_y, rotated_center_z);
input_3d.CalculateProjection(projection_image, *ctf_image, alignment_parameters, 0.0, 0.0, pixel_size / classification_resolution_limit, false, false, false, true, is_phase_flipped);
particle_image->PhaseShift(-current_parameters.x_shift / pixel_size, -current_parameters.y_shift / pixel_size);
particle_image->BackwardFFT( );
// wxPrintf("ssq part = %g var part = %g\n", particle_image->ReturnSumOfSquares(pixel_radius_2d, rotated_center_x + particle_image->physical_address_of_box_center_x,
// rotated_center_y + particle_image->physical_address_of_box_center_y, 0.0), particle_image->ReturnVarianceOfRealValues());
projection_image.SwapRealSpaceQuadrants( );
projection_image.BackwardFFT( );
// particle_image->QuickAndDirtyWriteSlice("part2.mrc", 1);
// projection_image.QuickAndDirtyWriteSlice("proj2.mrc", 1);
// exit(0);
// variance_masked = particle_image->ReturnVarianceOfRealValues(pixel_radius_2d, rotated_center_x + particle_image->physical_address_of_box_center_x,
// rotated_center_y + particle_image->physical_address_of_box_center_y, 0.0);
// particle_image->QuickAndDirtyWriteSlice("part.mrc", 1);
// projection_image.AddConstant(- projection_image.ReturnAverageOfRealValues(0.45 * projection_image.logical_x_dimension, true));
// projection_image.MultiplyByConstant(0.02);
// float min = 100.0;
// for (int i = 0; i < 100; i++)
// {
// particle_image->SubtractImage(&projection_image);
// sigma_signal = sqrtf(projection_image.ReturnVarianceOfRealValues(mask_radius / pixel_size));
// sigma_noise = sqrtf(particle_image->ReturnVarianceOfRealValues(mask_radius / pixel_size));
// if (sigma_noise < min) {min = sigma_noise; wxPrintf("i, sigma_noise = %i %g\n", i, sigma_noise);}
// }
// ssq_XA = particle_image->ReturnPixelWiseProduct(projection_image);
// ssq_A2 = projection_image.ReturnPixelWiseProduct(projection_image);
// alpha = ssq_XA / ssq_A2;
alpha = particle_image->ReturnImageScale(projection_image, mask_radius / pixel_size);
projection_image.MultiplyByConstant(alpha);
particle_image->SubtractImage(&projection_image);
sigma_signal = sqrtf(projection_image.ReturnVarianceOfRealValues(mask_radius / pixel_size));
sigma_noise = sqrtf(particle_image->ReturnVarianceOfRealValues(mask_radius / pixel_size));
if ( sigma_noise > 0.0 )
snr = powf(sigma_signal / sigma_noise, 2);
else
snr = 0.0;
// wxPrintf("mask_radius, pixel_size, alpha, sigma_noise = %g %g %g %g\n", mask_radius, pixel_size, alpha, sigma_noise);
// particle_image->QuickAndDirtyWriteSlice("diff.mrc", 1);
// exit(0);
// wxPrintf("number_of_independent_pixels = %g, variance_difference = %g, variance_masked = %g, logp = %g\n", number_of_independent_pixels,
// variance_difference, variance_masked, -number_of_independent_pixels * variance_difference / variance_masked / 2.0);
// wxPrintf("sum = %g pix = %li penalty = %g indep = %g\n", particle_image->ReturnSumOfSquares(pixel_radius_2d, rotated_center_x + particle_image->physical_address_of_box_center_x,
// rotated_center_y + particle_image->physical_address_of_box_center_y, 0.0), particle_image->number_of_real_space_pixels,
// ReturnParameterLogP(current_parameters), mask_volume);
// exit(0);
if ( mask_radius_2d > 0.0 ) {
logp = -0.5 * (particle_image->ReturnSumOfSquares(pixel_radius_2d, rotated_center_x + particle_image->physical_address_of_box_center_x, rotated_center_y + particle_image->physical_address_of_box_center_y, 0.0) + logf(2.0 * PI)) * PI * powf(pixel_radius_2d, 2) + ReturnParameterLogP(current_parameters);
}
else {
logp = -0.5 * (particle_image->ReturnSumOfSquares(mask_radius / pixel_size) + logf(2.0 * PI)) * PI * powf(mask_radius / pixel_size, 2) + ReturnParameterLogP(current_parameters);
}
}
float Particle::MLBlur(Image* input_classes_cache, float ssq_X, Image& cropped_input_image, Image* rotation_cache, Image& blurred_image,
int current_class, int number_of_rotations, float psi_step, float psi_start, float smoothing_factor, float& max_logp_particle,
int best_class, float best_psi, Image& best_correlation_map, bool calculate_correlation_map_only, bool uncrop, bool apply_ctf_to_classes,
Image* image_to_blur, Image* diff_image_to_blur, float max_shift_in_angstroms) {
MyDebugAssertTrue(cropped_input_image.is_in_memory, "cropped_input_image: memory not allocated");
MyDebugAssertTrue(rotation_cache[0].is_in_memory, "rotation_cache: memory not allocated");
MyDebugAssertTrue(blurred_image.is_in_memory, "blurred_image: memory not allocated");
MyDebugAssertTrue(input_classes_cache[0].is_in_memory, "input_classes_cache: memory not allocated");
MyDebugAssertTrue(! ctf_image->is_in_real_space, "ctf_image in real space");
MyDebugAssertTrue(! input_classes_cache[0].is_in_real_space, "input_classes_cache not in Fourier space");
int i, j;
int pixel_counter;
int current_rotation;
int non_zero_pixels;
float binning_factor;
float snr_psi = -std::numeric_limits<float>::max( );
float snr_class;
float log_threshold;
float old_max_logp;
float log_range = 20.0;
float var_A;
float ssq_A;
float ssq_A_rot0;
float ssq_XA2;
float psi;
float rmdr;
float number_of_pixels = particle_image->number_of_real_space_pixels * smoothing_factor;
bool new_max_found;
bool use_best_psi;
float dx, dy;
float mid_x;
float mid_y;
float rvar2_x = powf(pixel_size, 2) / parameter_variance.x_shift / 2.0;
float rvar2_y = powf(pixel_size, 2) / parameter_variance.y_shift / 2.0;
float penalty_x, penalty_y;
float number_of_independent_pixels;
float norm_X, norm_A;
double sump_psi;
double sump_class;
double min_float = std::numeric_limits<float>::min( );
double scale;
AnglesAndShifts rotation_angle;
Image* correlation_map = new Image;
correlation_map->Allocate(particle_image->logical_x_dimension, particle_image->logical_y_dimension, false);
Image* temp_image = new Image;
temp_image->Allocate(particle_image->logical_x_dimension, particle_image->logical_y_dimension, false);
Image* sum_image = new Image;
sum_image->Allocate(particle_image->logical_x_dimension, particle_image->logical_y_dimension, true);
// wxPrintf("Max shift in angstoms = %f\n", max_shift_in_angstroms);
float max_radius_squared = powf(max_shift_in_angstroms / pixel_size, 2);
float current_squared_radius;
#ifndef MKL
float* temp_k1 = new float[particle_image->real_memory_allocated];
float* temp_k2;
temp_k2 = temp_k1 + 1;
float* real_a;
float* real_b;
float* real_c;
float* real_d;
float* real_r;
float* real_i;
#endif
if ( is_filtered )
number_of_independent_pixels = filter_volume;
else
number_of_independent_pixels = particle_image->number_of_real_space_pixels;
if ( is_masked )
number_of_independent_pixels *= mask_volume / particle_image->number_of_real_space_pixels;
// Determine sum of squares of reference after CTF multiplication
temp_image->CopyFrom(&input_classes_cache[current_class]);
if ( apply_ctf_to_classes )
temp_image->MultiplyPixelWiseReal(*ctf_image);
ssq_A = temp_image->ReturnSumOfSquares( );
temp_image->BackwardFFT( );
var_A = temp_image->ReturnVarianceOfRealValues( );
norm_A = 0.5 * number_of_pixels * ssq_A;
ssq_XA2 = sqrtf(ssq_X * ssq_A);
// Prevent collapse of x,y distribution to 0 due to limited resolution
if ( rvar2_x > 1.0 )
rvar2_x = 1.0;
if ( rvar2_y > 1.0 )
rvar2_y = 1.0;
rvar2_x *= smoothing_factor;
rvar2_y *= smoothing_factor;
snr_class = -std::numeric_limits<float>::max( );
sum_image->SetToConstant(0.0);
sump_class = 0.0;
old_max_logp = max_logp_particle;
if ( log_range == 0.0 ) {
log_range = 0.0001;
}
for ( current_rotation = 0; current_rotation < number_of_rotations; current_rotation++ ) {
if ( calculate_correlation_map_only ) {
psi = best_psi;
current_rotation = number_of_rotations;
}
else
psi = 360.0 - current_rotation * psi_step - psi_start;
rotation_angle.GenerateRotationMatrix2D(psi);
rotation_angle.euler_matrix.RotateCoords2D(parameter_average.x_shift, parameter_average.y_shift, mid_x, mid_y);
mid_x /= pixel_size;
mid_y /= pixel_size;
rotation_angle.GenerateRotationMatrix2D(-psi);
// wxPrintf("current_rotation = %i ssq_X = %g ssq_A = %g\n", current_rotation, rotation_cache[current_rotation].ReturnSumOfSquares(), input_classes_cache[current_class].ReturnSumOfSquares());
// wxPrintf("number_of_pixels = %g, ssq_X = %g ssq_A = %g\n", number_of_pixels, ssq_X, ssq_A);
// Calculate X.A
#ifdef MKL
vmcMulByConj(particle_image->real_memory_allocated / 2, reinterpret_cast<MKL_Complex8*>(input_classes_cache[current_class].complex_values), reinterpret_cast<MKL_Complex8*>(rotation_cache[current_rotation].complex_values), reinterpret_cast<MKL_Complex8*>(correlation_map->complex_values), VML_EP | VML_FTZDAZ_ON | VML_ERRMODE_IGNORE);
#else
real_a = input_classes_cache[current_class].real_values;
real_b = input_classes_cache[current_class].real_values + 1;
real_c = rotation_cache[current_rotation].real_values;
real_d = rotation_cache[current_rotation].real_values + 1;
real_r = correlation_map->real_values;
real_i = correlation_map->real_values + 1;
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
temp_k1[pixel_counter] = real_a[pixel_counter] + real_b[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
temp_k2[pixel_counter] = real_b[pixel_counter] - real_a[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
real_r[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] - real_d[pixel_counter]) + real_d[pixel_counter] * temp_k1[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
real_i[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] - real_d[pixel_counter]) + real_c[pixel_counter] * temp_k2[pixel_counter];
};
#endif
correlation_map->is_in_real_space = false;
correlation_map->BackwardFFT( );
temp_image->CopyFrom(correlation_map);
// Calculate LogP (excluding -0.5 * number_of_independent_pixels * (logf(2.0 * PI) + ssq_X) and apply hierarchical prior f(x,y)
// ssq_X_minus_A = (ssq_X - 2.0 * correlation_map->real_values[0] + ssq_A) / 2
pixel_counter = 0;
penalty_x = 0.0;
penalty_y = 0.0;
// The following is divided by 2 according to the LogP formula
for ( j = 0; j < particle_image->logical_y_dimension; j++ ) {
if ( constraints_used.y_shift ) {
if ( j > particle_image->physical_address_of_box_center_y )
dy = j - particle_image->logical_y_dimension;
else
dy = j;
penalty_y = powf(dy - mid_y, 2) * rvar2_y;
}
for ( i = 0; i < particle_image->logical_x_dimension; i++ ) {
if ( constraints_used.x_shift ) {
if ( i > particle_image->physical_address_of_box_center_x )
dx = i - particle_image->logical_y_dimension;
else
dx = i;
penalty_x = powf(dx - mid_x, 2) * rvar2_x;
}
correlation_map->real_values[pixel_counter] = correlation_map->real_values[pixel_counter] * number_of_pixels - norm_A - penalty_x - penalty_y;
pixel_counter++;
}
pixel_counter += particle_image->padding_jump_value;
}
// Find correlation maximum to threshold LogP, and find best alignment parameters
pixel_counter = 0;
new_max_found = false;
for ( j = 0; j < particle_image->logical_y_dimension; j++ ) {
if ( j > particle_image->physical_address_of_box_center_y )
dy = j - particle_image->logical_y_dimension;
else
dy = j;
for ( i = 0; i < particle_image->logical_x_dimension; i++ ) {
if ( i > particle_image->physical_address_of_box_center_x )
dx = i - particle_image->logical_y_dimension;
else
dx = i;
current_squared_radius = powf(dx, 2) + powf(dy, 2);
if ( current_squared_radius > max_radius_squared ) {
correlation_map->real_values[pixel_counter] = 0.0f;
}
else if ( correlation_map->real_values[pixel_counter] > max_logp_particle ) {
new_max_found = true;
max_logp_particle = correlation_map->real_values[pixel_counter];
// Store correlation coefficient that corresponds to highest likelihood
snr_psi = temp_image->real_values[pixel_counter];
rotation_angle.euler_matrix.RotateCoords2D(dx, dy, current_parameters.x_shift, current_parameters.y_shift);
current_parameters.x_shift *= pixel_size;
current_parameters.y_shift *= pixel_size;
current_parameters.psi = psi;
current_parameters.best_2d_class = current_class + 1;
}
pixel_counter++;
}
pixel_counter += particle_image->padding_jump_value;
}
// // To get normalized correlation coefficient, need to divide by sigmas of particle and reference
// To get sigma^2, need to calculate ssq_X - 2XA + ssq_A
if ( new_max_found ) {
// wxPrintf("ssq_X, snr_psi, ssq_A, number_of_real_space_pixels, number_of_independent_pixels, var_A = %g %g %g %li %g %g\n",
// ssq_X, snr_psi, ssq_A, particle_image->number_of_real_space_pixels, number_of_independent_pixels, var_A);
snr_psi = (ssq_X - 2.0 * snr_psi + ssq_A) * particle_image->number_of_real_space_pixels / number_of_independent_pixels / var_A;
// Update SIGMA (SNR)
if ( snr_psi >= 0.0 )
current_parameters.sigma = sqrtf(snr_psi);
// Update SCORE
current_parameters.score = 100.0 * (max_logp_particle + norm_A) / number_of_pixels / ssq_XA2;
}
rmdr = remainderf(best_psi - psi, 360.0);
use_best_psi = false;
if ( ! calculate_correlation_map_only && best_class == current_class && ! new_max_found && rmdr < psi_step / 2.0 && rmdr >= -psi_step / 2.0 ) {
use_best_psi = true;
snr_psi = snr;
correlation_map->CopyFrom(&best_correlation_map);
}
if ( calculate_correlation_map_only ) {
snr = snr_psi;
best_correlation_map.CopyFrom(correlation_map);
// Update SIGMA (SNR)
if ( snr_psi >= 0.0 )
current_parameters.sigma = sqrtf(snr_psi);
// Update SCORE
current_parameters.score = 100.0 * (max_logp_particle + norm_A) / number_of_pixels / ssq_XA2;
break;
}
else {
// Calculate thresholded LogP
log_threshold = max_logp_particle - log_range;
pixel_counter = 0;
non_zero_pixels = 0;
sump_psi = 0.0;
for ( j = 0; j < particle_image->logical_y_dimension; j++ ) {
if ( j > particle_image->physical_address_of_box_center_y )
dy = particle_image->logical_y_dimension - j;
else
dy = j;
for ( i = 0; i < particle_image->logical_x_dimension; i++ ) {
if ( i > particle_image->physical_address_of_box_center_x )
dx = particle_image->logical_y_dimension - i;
else
dx = i;
if ( correlation_map->real_values[pixel_counter] >= log_threshold && correlation_map->real_values[pixel_counter] != 0.0f ) {
correlation_map->real_values[pixel_counter] = exp(correlation_map->real_values[pixel_counter] - max_logp_particle);
sump_psi += correlation_map->real_values[pixel_counter];
non_zero_pixels++;
}
else {
correlation_map->real_values[pixel_counter] = 0.0;
}
pixel_counter++;
}
pixel_counter += particle_image->padding_jump_value;
}
if ( non_zero_pixels > 0 ) {
// correlation_map->QuickAndDirtyWriteSlice("corr.mrc", 1);
// exit(0);
// correlation_map->SetToConstant(0.0);
// correlation_map->real_values[0] = 1.0;
// sump_psi = 1.0;
// if (! uncrop) correlation_map->real_values[0] += 0.01;
correlation_map->ForwardFFT( );
if ( use_best_psi )
i = number_of_rotations;
else
i = current_rotation;
if ( image_to_blur == NULL ) {
#ifdef MKL
vmcMul(particle_image->real_memory_allocated / 2, reinterpret_cast<MKL_Complex8*>(correlation_map->complex_values), reinterpret_cast<MKL_Complex8*>(rotation_cache[i].complex_values), reinterpret_cast<MKL_Complex8*>(temp_image->complex_values), VML_EP | VML_FTZDAZ_ON | VML_ERRMODE_IGNORE);
#else
real_a = correlation_map->real_values;
real_b = correlation_map->real_values + 1;
real_c = rotation_cache[i].real_values;
real_d = rotation_cache[i].real_values + 1;
real_r = temp_image->real_values;
real_i = temp_image->real_values + 1;
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
temp_k1[pixel_counter] = real_a[pixel_counter] + real_b[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
temp_k2[pixel_counter] = real_b[pixel_counter] - real_a[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
real_r[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) - real_d[pixel_counter] * temp_k1[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
real_i[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) + real_c[pixel_counter] * temp_k2[pixel_counter];
};
#endif
}
else {
if ( diff_image_to_blur != NULL ) {
#ifdef MKL
vmcMul(particle_image->real_memory_allocated / 2, reinterpret_cast<MKL_Complex8*>(correlation_map->complex_values), reinterpret_cast<MKL_Complex8*>(diff_image_to_blur->complex_values), reinterpret_cast<MKL_Complex8*>(temp_image->complex_values), VML_EP | VML_FTZDAZ_ON | VML_ERRMODE_IGNORE);
#else
real_a = correlation_map->real_values;
real_b = correlation_map->real_values + 1;
real_c = diff_image_to_blur->real_values;
real_d = diff_image_to_blur->real_values + 1;
real_r = temp_image->real_values;
real_i = temp_image->real_values + 1;
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
temp_k1[pixel_counter] = real_a[pixel_counter] + real_b[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
temp_k2[pixel_counter] = real_b[pixel_counter] - real_a[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
real_r[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) - real_d[pixel_counter] * temp_k1[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
real_i[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) + real_c[pixel_counter] * temp_k2[pixel_counter];
};
#endif
diff_image_to_blur->CopyFrom(temp_image);
}
#ifdef MKL
vmcMul(particle_image->real_memory_allocated / 2, reinterpret_cast<MKL_Complex8*>(correlation_map->complex_values), reinterpret_cast<MKL_Complex8*>(image_to_blur->complex_values), reinterpret_cast<MKL_Complex8*>(temp_image->complex_values), VML_EP | VML_FTZDAZ_ON | VML_ERRMODE_IGNORE);
#else
real_a = correlation_map->real_values;
real_b = correlation_map->real_values + 1;
real_c = image_to_blur->real_values;
real_d = image_to_blur->real_values + 1;
real_r = temp_image->real_values;
real_i = temp_image->real_values + 1;
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
temp_k1[pixel_counter] = real_a[pixel_counter] + real_b[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
temp_k2[pixel_counter] = real_b[pixel_counter] - real_a[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
real_r[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) - real_d[pixel_counter] * temp_k1[pixel_counter];
};
for ( pixel_counter = 0; pixel_counter < particle_image->real_memory_allocated; pixel_counter += 2 ) {
real_i[pixel_counter] = real_a[pixel_counter] * (real_c[pixel_counter] + real_d[pixel_counter]) + real_c[pixel_counter] * temp_k2[pixel_counter];
};
#endif
}
// max_logp_particle is the current best LogP found over all tested references, angles and x,y positions.
// It is also the offset of the likelihoods in correlation_map and sump_psi (the sum of likelihoods).
// old_max_log is the previous best logP and correlation_map offset used to calculate sum_image and sump_class.
// First deal with case where the old offset is so low that the previous sums are not significant compared with the current reference.
temp_image->is_in_real_space = false;
temp_image->BackwardFFT( );
if ( old_max_logp < max_logp_particle - log_range ) {
sum_image->CopyFrom(temp_image);
old_max_logp = max_logp_particle;
snr_class = snr_psi;
sump_class = sump_psi;
}
else
// If the old and new offsets are similar, need to calculate a weighted sum
if ( fabsf(old_max_logp - max_logp_particle) <= log_range ) {
// Case of old offset smaller than or equal new offset
if ( old_max_logp <= max_logp_particle ) {
scale = expf(old_max_logp - max_logp_particle);
pixel_counter = 0;
for ( j = 0; j < sum_image->logical_y_dimension; j++ ) {
for ( i = 0; i < sum_image->logical_x_dimension; i++ ) {
sum_image->real_values[pixel_counter] = sum_image->real_values[pixel_counter] * scale + temp_image->real_values[pixel_counter];
pixel_counter++;
}
pixel_counter += sum_image->padding_jump_value;
}
old_max_logp = max_logp_particle;
snr_class = snr_psi;
sump_class = sump_class * scale + sump_psi;
}
// Case of old offset larger than new offset
else {
scale = expf(max_logp_particle - old_max_logp);
pixel_counter = 0;
for ( j = 0; j < sum_image->logical_y_dimension; j++ ) {
for ( i = 0; i < sum_image->logical_x_dimension; i++ ) {
sum_image->real_values[pixel_counter] = sum_image->real_values[pixel_counter] + temp_image->real_values[pixel_counter] * scale;
pixel_counter++;
}
pixel_counter += sum_image->padding_jump_value;
}
sump_class = sump_class + sump_psi * scale;
}
}
}
}
}
if ( sump_class > 0.0 ) {
// Divide rotationally & translationally blurred image by sum of probabilities
binning_factor = float(cropped_input_image.logical_x_dimension) / float(sum_image->logical_x_dimension);
sum_image->MultiplyByConstant(sum_image->number_of_real_space_pixels / binning_factor / sump_class);
if ( diff_image_to_blur != NULL )
diff_image_to_blur->MultiplyByConstant(sum_image->number_of_real_space_pixels / binning_factor / sump_class);
sum_image->ForwardFFT( );
if ( uncrop ) {
sum_image->CosineMask(0.45, 0.1);
// sum_image->CosineMask(0.3, 0.4);
sum_image->ClipInto(&cropped_input_image);
cropped_input_image.BackwardFFT( );
cropped_input_image.ClipIntoLargerRealSpace2D(&blurred_image, cropped_input_image.ReturnAverageOfRealValuesOnEdges( ));
}
else {
blurred_image.CopyFrom(sum_image);
temp_image->CopyFrom(image_to_blur);
temp_image->MultiplyByConstant(sump_class / temp_image->number_of_real_space_pixels / temp_image->number_of_real_space_pixels);
blurred_image.AddImage(temp_image);
}
// wxPrintf("log sump_class = %g old_max_logp = %g number_of_independent_pixels = %g ssq_X = %g\n", logf(sump_class), old_max_logp, number_of_independent_pixels, ssq_X);
logp = logf(sump_class) + old_max_logp - 0.5 * (number_of_independent_pixels * logf(2.0 * PI) + number_of_pixels * ssq_X);
current_parameters.logp = logp;
}
else {
blurred_image.SetToConstant(0.0);
if ( diff_image_to_blur != NULL )
diff_image_to_blur->SetToConstant(0.0);
logp = -std::numeric_limits<float>::max( );
}
// wxPrintf("log_sum = %g, old = %g, n = %g, var = %g\n", logf(sump_class), old_max_log, number_of_independent_pixels, norm_A);
delete correlation_map;
delete temp_image;
delete sum_image;
#ifndef MKL
delete[] temp_k1;
#endif
return logp;
}
void Particle::EstimateSigmaNoise( ) {
MyDebugAssertTrue(particle_image->is_in_memory, "particle_image memory not allocated");
sigma_noise = particle_image->ReturnSigmaNoise( );
}
| 75,396 | 25,156 |
//---------------------------------------------------------------------------
// File:
// BFFileHelper.cpp BFFileHelper.hpp
//
// Module:
// CBFFileHelper
//
// History:
// May. 7, 2002 Created by Benjamin Fung
//---------------------------------------------------------------------------
#include "BFPch.h"
#if !defined(BFFILEHELPER_H)
#include "BFFileHelper.h"
#endif
//--------------------------------------------------------------------
//--------------------------------------------------------------------
CBFFileHelper::CBFFileHelper()
{
}
CBFFileHelper::~CBFFileHelper()
{
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
bool CBFFileHelper::removeFile(LPCTSTR filename)
{
return _tremove(filename) == 0;
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
void CBFFileHelper::splitPath(LPCTSTR fullPath, CString& drive, CString& dir, CString& fname, CString& ext)
{
TCHAR tDrive[_MAX_DRIVE];
TCHAR tDir[_MAX_DIR];
TCHAR tFname[_MAX_FNAME];
TCHAR tExt[_MAX_EXT];
_tsplitpath_s(fullPath, tDrive, tDir, tFname, tExt);
drive = tDrive;
dir = tDir;
fname = tFname;
ext = tExt;
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
bool CBFFileHelper::replaceExtension(LPCTSTR fname, LPCTSTR ext, CString& res)
{
res = fname;
int dotPos = res.ReverseFind(TCHAR('.'));
if (dotPos == -1) {
res.Empty();
return false;
}
res = res.Left(dotPos + 1);
res += ext;
return true;
} | 1,818 | 522 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated by codegen project: GenerateModuleH.js
*/
#include "NativeModules.h"
namespace facebook {
namespace react {
static jsi::Value __hostFunction_CommCoreModuleSchemaCxxSpecJSI_getDraft(
jsi::Runtime &rt,
TurboModule &turboModule,
const jsi::Value *args,
size_t count) {
return static_cast<CommCoreModuleSchemaCxxSpecJSI *>(&turboModule)
->getDraft(rt, args[0].getString(rt));
}
static jsi::Value __hostFunction_CommCoreModuleSchemaCxxSpecJSI_updateDraft(
jsi::Runtime &rt,
TurboModule &turboModule,
const jsi::Value *args,
size_t count) {
return static_cast<CommCoreModuleSchemaCxxSpecJSI *>(&turboModule)
->updateDraft(rt, args[0].getObject(rt));
}
static jsi::Value __hostFunction_CommCoreModuleSchemaCxxSpecJSI_moveDraft(
jsi::Runtime &rt,
TurboModule &turboModule,
const jsi::Value *args,
size_t count) {
return static_cast<CommCoreModuleSchemaCxxSpecJSI *>(&turboModule)
->moveDraft(rt, args[0].getString(rt), args[1].getString(rt));
}
static jsi::Value __hostFunction_CommCoreModuleSchemaCxxSpecJSI_getAllDrafts(
jsi::Runtime &rt,
TurboModule &turboModule,
const jsi::Value *args,
size_t count) {
return static_cast<CommCoreModuleSchemaCxxSpecJSI *>(&turboModule)
->getAllDrafts(rt);
}
static jsi::Value __hostFunction_CommCoreModuleSchemaCxxSpecJSI_removeAllDrafts(
jsi::Runtime &rt,
TurboModule &turboModule,
const jsi::Value *args,
size_t count) {
return static_cast<CommCoreModuleSchemaCxxSpecJSI *>(&turboModule)
->removeAllDrafts(rt);
}
CommCoreModuleSchemaCxxSpecJSI::CommCoreModuleSchemaCxxSpecJSI(
std::shared_ptr<CallInvoker> jsInvoker)
: TurboModule("CommTurboModule", jsInvoker) {
methodMap_["getDraft"] =
MethodMetadata{1, __hostFunction_CommCoreModuleSchemaCxxSpecJSI_getDraft};
methodMap_["updateDraft"] = MethodMetadata{
1, __hostFunction_CommCoreModuleSchemaCxxSpecJSI_updateDraft};
methodMap_["moveDraft"] = MethodMetadata{
2, __hostFunction_CommCoreModuleSchemaCxxSpecJSI_moveDraft};
methodMap_["getAllDrafts"] = MethodMetadata{
0, __hostFunction_CommCoreModuleSchemaCxxSpecJSI_getAllDrafts};
methodMap_["removeAllDrafts"] = MethodMetadata{
0, __hostFunction_CommCoreModuleSchemaCxxSpecJSI_removeAllDrafts};
}
} // namespace react
} // namespace facebook
| 2,552 | 876 |
// Copyright (c) 2019 The Felicia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "felicia/core/lib/unit/bytes.h"
namespace felicia {
Bytes::Bytes() = default;
Bytes::Bytes(int64_t bytes) : bytes_(bytes) {}
bool Bytes::operator==(Bytes other) const { return bytes_ == other.bytes_; }
bool Bytes::operator!=(Bytes other) const { return bytes_ != other.bytes_; }
bool Bytes::operator<(Bytes other) const { return bytes_ < other.bytes_; }
bool Bytes::operator<=(Bytes other) const { return bytes_ <= other.bytes_; }
bool Bytes::operator>(Bytes other) const { return bytes_ > other.bytes_; }
bool Bytes::operator>=(Bytes other) const { return bytes_ >= other.bytes_; }
Bytes Bytes::operator+(Bytes other) const {
return Bytes(internal::SaturateAdd(bytes_, other.bytes_));
}
Bytes Bytes::operator-(Bytes other) const {
return Bytes(internal::SaturateSub(bytes_, other.bytes_));
}
Bytes& Bytes::operator+=(Bytes other) { return *this = (*this + other); }
Bytes& Bytes::operator-=(Bytes other) { return *this = (*this - other); }
double Bytes::operator/(Bytes a) const { return bytes_ / a.bytes_; }
int64_t Bytes::bytes() const { return bytes_; }
// static
Bytes Bytes::FromBytes(int64_t bytes) { return Bytes(bytes); }
// static
Bytes Bytes::FromKilloBytes(int64_t killo_bytes) {
return Bytes(internal::FromProduct(killo_bytes, kKilloBytes));
}
// static
Bytes Bytes::FromKilloBytesD(double killo_bytes) {
return FromDouble(killo_bytes * kKilloBytes);
}
// static
Bytes Bytes::FromMegaBytes(int64_t mega_bytes) {
return Bytes(internal::FromProduct(mega_bytes, kMegaBytes));
}
// static
Bytes Bytes::FromMegaBytesD(double mega_bytes) {
return FromDouble(mega_bytes * kMegaBytes);
}
// static
Bytes Bytes::FromGigaBytes(int64_t giga_bytes) {
return Bytes(internal::FromProduct(giga_bytes, kGigaBytes));
}
// static
Bytes Bytes::FromGigaBytesD(double giga_bytes) {
return FromDouble(giga_bytes * kGigaBytes);
}
// static
Bytes Bytes::Max() { return Bytes(std::numeric_limits<int64_t>::max()); }
// static
Bytes Bytes::Min() { return Bytes(std::numeric_limits<int64_t>::min()); }
// static
Bytes Bytes::FromDouble(double value) {
return Bytes(base::saturated_cast<int64_t>(value));
}
std::ostream& operator<<(std::ostream& os, Bytes bytes) {
os << base::NumberToString(bytes.bytes()) << " bytes";
return os;
}
} // namespace felicia | 2,459 | 836 |
#include "Register.h"
| 25 | 11 |
/*
* Copyright (c) 2017-2019, 2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @file surface_properties.hpp
*
* @brief Vulkan WSI surface query interfaces.
*/
#pragma once
#include <vulkan/vulkan.h>
#include <util/extension_list.hpp>
namespace wsi
{
/**
* @brief The base surface property query interface.
*/
class surface_properties
{
public:
/**
* @brief Implementation of vkGetPhysicalDeviceSurfaceCapabilitiesKHR for the specific VkSurface type.
*/
virtual VkResult get_surface_capabilities(VkPhysicalDevice physical_device, VkSurfaceKHR surface,
VkSurfaceCapabilitiesKHR *surface_capabilities) = 0;
/**
* @brief Implementation of vkGetPhysicalDeviceSurfaceFormatsKHR for the specific VkSurface type.
*/
virtual VkResult get_surface_formats(VkPhysicalDevice physical_device, VkSurfaceKHR surface,
uint32_t *surface_format_count, VkSurfaceFormatKHR *surface_formats) = 0;
/**
* @brief Implementation of vkGetPhysicalDeviceSurfacePresentModesKHR for the specific VkSurface type.
*/
virtual VkResult get_surface_present_modes(VkPhysicalDevice physical_device, VkSurfaceKHR surface,
uint32_t *present_mode_count, VkPresentModeKHR *present_modes) = 0;
/**
* @brief Return the device extensions that this surface_properties implementation needs.
*/
virtual const util::extension_list &get_required_device_extensions()
{
static const util::extension_list empty{util::allocator::get_generic()};
return empty;
}
};
} /* namespace wsi */
| 2,742 | 866 |
#ifndef Rice__Data_Type__ipp_
#define Rice__Data_Type__ipp_
#include "Class.hpp"
#include "String.hpp"
#include "Data_Object.hpp"
#include "detail/default_allocation_func.hpp"
#include "detail/creation_funcs.hpp"
#include "detail/method_data.hpp"
#include "detail/Caster.hpp"
#include "detail/demangle.hpp"
#include <stdexcept>
#include <typeinfo>
template<typename T>
VALUE Rice::Data_Type<T>::klass_ = Qnil;
template<typename T>
std::auto_ptr<Rice::detail::Abstract_Caster> Rice::Data_Type<T>::caster_;
template<typename T>
template<typename Base_T>
inline Rice::Data_Type<T> Rice::Data_Type<T>::
bind(Module const & klass)
{
if(klass.value() == klass_)
{
return Data_Type<T>();
}
if(is_bound())
{
std::string s;
s = "Data type ";
s += detail::demangle(typeid(T).name());
s += " is already bound to a different type";
throw std::runtime_error(s.c_str());
}
// TODO: Make sure base type is bound; throw an exception otherwise.
// We can't do this just yet, because we don't have a specialization
// for binding to void.
klass_ = klass;
// TODO: do we need to unregister when the program exits? we have to
// be careful if we do, because the ruby interpreter might have
// already shut down. The correct behavior is probably to register an
// exit proc with the interpreter, so the proc gets called before the
// GC shuts down.
rb_gc_register_address(&klass_);
for(typename Instances::iterator it = unbound_instances().begin(),
end = unbound_instances().end();
it != end;
unbound_instances().erase(it++))
{
(*it)->set_value(klass);
}
detail::Abstract_Caster * base_caster = Data_Type<Base_T>().caster();
caster_.reset(new detail::Caster<T, Base_T>(base_caster, klass));
Data_Type_Base::casters().insert(std::make_pair(klass, caster_.get()));
return Data_Type<T>();
}
template<typename T>
inline Rice::Data_Type<T>::
Data_Type()
: Module_impl<Data_Type_Base, Data_Type<T> >(
klass_ == Qnil ? rb_cObject : klass_)
{
if(!is_bound())
{
unbound_instances().insert(this);
}
}
template<typename T>
inline Rice::Data_Type<T>::
Data_Type(Module const & klass)
: Module_impl<Data_Type_Base, Data_Type<T> >(
klass)
{
this->bind<void>(klass);
}
template<typename T>
inline Rice::Data_Type<T>::
~Data_Type()
{
unbound_instances().erase(this);
}
template<typename T>
Rice::Module
Rice::Data_Type<T>::
klass() {
if(is_bound())
{
return klass_;
}
else
{
std::string s;
s += detail::demangle(typeid(T *).name());
s += " is unbound";
throw std::runtime_error(s.c_str());
}
}
template<typename T>
Rice::Data_Type<T> & Rice::Data_Type<T>::
operator=(Module const & klass)
{
this->bind<void>(klass);
return *this;
}
template<typename T>
template<typename Constructor_T>
inline Rice::Data_Type<T> & Rice::Data_Type<T>::
define_constructor(
Constructor_T /* constructor */,
Arguments* arguments)
{
check_is_bound();
// Normal constructor pattern with new/initialize
rb_define_alloc_func(
static_cast<VALUE>(*this),
detail::default_allocation_func<T>);
this->define_method(
"initialize",
&Constructor_T::construct,
arguments
);
return *this;
}
template<typename T>
template<typename Constructor_T>
inline Rice::Data_Type<T> & Rice::Data_Type<T>::
define_constructor(
Constructor_T constructor,
Arg const& arg)
{
Arguments* args = new Arguments();
args->add(arg);
return define_constructor(constructor, args);
}
template<typename T>
template<typename Director_T>
inline Rice::Data_Type<T>& Rice::Data_Type<T>::
define_director()
{
Rice::Data_Type<Director_T>::template bind<T>(*this);
return *this;
}
template<typename T>
inline T * Rice::Data_Type<T>::
from_ruby(Object x)
{
check_is_bound();
void * v = DATA_PTR(x.value());
Class klass = x.class_of();
if(klass.value() == klass_)
{
// Great, not converting to a base/derived type
Data_Type<T> data_klass;
Data_Object<T> obj(x, data_klass);
return obj.get();
}
Data_Type_Base::Casters::const_iterator it = Data_Type_Base::casters().begin();
Data_Type_Base::Casters::const_iterator end = Data_Type_Base::casters().end();
// Finding the bound type that relates to the given klass is
// a two step process. We iterate over the list of known type casters,
// looking for:
//
// 1) casters that handle this direct type
// 2) casters that handle types that are ancestors of klass
//
// Step 2 allows us to handle the case where a Rice-wrapped class
// is subclassed in Ruby but then an instance of that class is passed
// back into C++ (say, in a Listener / callback construction)
//
VALUE ancestors = rb_mod_ancestors(klass.value());
long earliest = RARRAY_LEN(ancestors) + 1;
int index;
VALUE indexFound;
Data_Type_Base::Casters::const_iterator toUse = end;
for(; it != end; it++) {
// Do we match directly?
if(klass.value() == it->first) {
toUse = it;
break;
}
// Check for ancestors. Trick is, we need to find the lowest
// ancestor that does have a Caster to make sure that we're casting
// to the closest C++ type that the Ruby class is subclassing.
// There might be multiple ancestors that are also wrapped in
// the extension, so find the earliest in the list and use that one.
indexFound = rb_funcall(ancestors, rb_intern("index"), 1, it->first);
if(indexFound != Qnil) {
index = NUM2INT(indexFound);
if(index < earliest) {
earliest = index;
toUse = it;
}
}
}
if(toUse == end)
{
std::string s = "Class ";
s += klass.name().str();
s += " is not registered/bound in Rice";
throw std::runtime_error(s);
}
detail::Abstract_Caster * caster = toUse->second;
if(caster)
{
T * result = static_cast<T *>(caster->cast_to_base(v, klass_));
return result;
}
else
{
return static_cast<T *>(v);
}
}
template<typename T>
inline bool Rice::Data_Type<T>::
is_bound()
{
return klass_ != Qnil;
}
template<typename T>
inline Rice::detail::Abstract_Caster * Rice::Data_Type<T>::
caster() const
{
check_is_bound();
return caster_.get();
}
namespace Rice
{
template<>
inline detail::Abstract_Caster * Data_Type<void>::
caster() const
{
return 0;
}
template<typename T>
void Data_Type<T>::
check_is_bound()
{
if(!is_bound())
{
std::string s;
s = "Data type ";
s += detail::demangle(typeid(T).name());
s += " is not bound";
throw std::runtime_error(s.c_str());
}
}
} // Rice
template<typename T>
inline Rice::Data_Type<T> Rice::
define_class_under(
Object module,
char const * name)
{
Class c(define_class_under(module, name, rb_cObject));
c.undef_creation_funcs();
return Data_Type<T>::template bind<void>(c);
}
template<typename T, typename Base_T>
inline Rice::Data_Type<T> Rice::
define_class_under(
Object module,
char const * name)
{
Data_Type<Base_T> base_dt;
Class c(define_class_under(module, name, base_dt));
c.undef_creation_funcs();
return Data_Type<T>::template bind<Base_T>(c);
}
template<typename T>
inline Rice::Data_Type<T> Rice::
define_class(
char const * name)
{
Class c(define_class(name, rb_cObject));
c.undef_creation_funcs();
return Data_Type<T>::template bind<void>(c);
}
template<typename T, typename Base_T>
inline Rice::Data_Type<T> Rice::
define_class(
char const * name)
{
Data_Type<Base_T> base_dt;
Class c(define_class(name, base_dt));
c.undef_creation_funcs();
return Data_Type<T>::template bind<Base_T>(c);
}
template<typename From_T, typename To_T>
inline void
Rice::define_implicit_cast()
{
// As Rice currently expects only one entry into
// this list for a given klass VALUE, we need to get
// the current caster for From_T and insert in our
// new caster as the head of the caster list
Class from_class = Data_Type<From_T>::klass().value();
Class to_class = Data_Type<To_T>::klass().value();
detail::Abstract_Caster* from_caster =
Data_Type<From_T>::caster_.release();
detail::Abstract_Caster* new_caster =
new detail::Implicit_Caster<To_T, From_T>(from_caster, to_class);
// Insert our new caster into the list for the from class
Data_Type_Base::casters().erase(from_class);
Data_Type_Base::casters().insert(
std::make_pair(
from_class,
new_caster
)
);
// And make sure the from_class has direct access to the
// updated caster list
Data_Type<From_T>::caster_.reset(new_caster);
}
#endif // Rice__Data_Type__ipp_
| 8,601 | 3,073 |
// Copyright (c) 2020 Spencer Melnick
#include "Inventory/DataTypes/StackData.h"
bool FInventoryStackData::NetSerialize(FArchive& Ar, UPackageMap* PackageMap, bool& bOutSuccess)
{
Ar << StackCount;
bOutSuccess = true;
return true;
}
| 240 | 93 |
#ifndef COLORSKIN_HPP
#define COLORSKIN_HPP
class MainFrame;
using namespace DuiLib;
class ColorSkinWindow : public WindowImplBase
{
public:
ColorSkinWindow(MainFrame* main_frame, RECT rcParentWindow);
LPCTSTR GetWindowClassName() const;
virtual void OnFinalMessage(HWND hWnd);
void Notify(TNotifyUI& msg);
virtual void InitWindow();
virtual CDuiString GetSkinFile();
virtual CDuiString GetSkinFolder();
virtual LRESULT OnKillFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
private:
RECT parent_window_rect_;
MainFrame* main_frame_;
};
#endif // COLORSKIN_HPP | 597 | 220 |
#ifndef __TEST_AVL_01_HPP__
#define __TEST_AVL_01_HPP__
#include <iostream>
#include "testbase.hpp"
#include "binarytree/avltree.hpp"
using namespace my::test;
using namespace my::bt;
namespace my
{
namespace test
{
namespace avl01
{
void doTask()
{
auto avl = AvlTree<int>();
for ( auto &&value : {10, 20, 30, 40, 50, 25} )
avl.insert(value);
std::cout << "\n size: " << avl.size() << std::endl;
std::cout << "\n min: " << avl.min() << std::endl;
std::cout << "\n max: " << avl.max() << std::endl;
std::cout << "\n contain: " << avl.contain(50) << std::endl;
std::cout << "\n height: " << avl.height() << std::endl;
std::cout << "\n print tree:" << std::endl;
base::printTree(avl);
std::cout << std::endl;
}
}
} // test
} // my
#endif
| 803 | 338 |
//Marcos Herrro
#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
void resuelveCaso() {
std::unordered_map<int, int> tabla;
std::queue<std::string> instrucciones;
std::queue<int> lineasSaltos;
int num, renum = 10; std::string instr;
std::cin >> num;
while (num != 0) {
tabla[num] = renum;
renum += 10;
std::cin >> instr;
instrucciones.push(instr);
if (instr == "GOTO" || instr == "GOSUB") {
std::cin >> num;
lineasSaltos.push(num);
}
std::cin>> num;
}
renum = 10;
while (!instrucciones.empty()) {
std::cout <<renum<<' '<< instrucciones.front();
if (instrucciones.front() == "GOTO" || instrucciones.front() == "GOSUB") {
std::cout <<' '<< tabla[lineasSaltos.front()];
lineasSaltos.pop();
}
std::cout << '\n';
renum += 10;
instrucciones.pop();
}
std::cout << "---\n";
}
int main() {
int n;
std::cin >> n;
for (int i = 0; i < n; ++i)resuelveCaso();
} | 980 | 438 |
/*
Copyright (c) 2005-2021, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TESTEXTENDEDBIDOMAINPROBLEM_HPP_
#define _TESTEXTENDEDBIDOMAINPROBLEM_HPP_
#include "UblasIncludes.hpp"
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include "PetscSetupAndFinalize.hpp"
#include "HeartConfig.hpp"
#include "SimpleStimulus.hpp"
#include "CorriasBuistSMCModified.hpp"
#include "CorriasBuistICCModified.hpp"
#include "CompareHdf5ResultsFiles.hpp"
#include "ExtendedBidomainProblem.hpp"
#include "PlaneStimulusCellFactory.hpp"
#include "LuoRudy1991.hpp"
#include "FaberRudy2000.hpp"
#include "OutputFileHandler.hpp"
#include "Hdf5DataReader.hpp"
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
class ICC_Cell_factory : public AbstractCardiacCellFactory<1>
{
public:
ICC_Cell_factory() : AbstractCardiacCellFactory<1>()
{
}
AbstractCardiacCell* CreateCardiacCellForTissueNode(Node<1>* pNode)
{
CorriasBuistICCModified *cell;
cell = new CorriasBuistICCModified(mpSolver, mpZeroStimulus);
double x = pNode->rGetLocation()[0];
double IP3_initial = 0.00067;
double IP3_final = 0.00065;
double cable_length = 10.0;
//calculate the concentration gradient...
double IP3_conc = IP3_initial + x*(IP3_final - IP3_initial)/cable_length;
//..and set it
cell->SetIP3Concentration(IP3_conc);
cell->SetFractionOfVDDRInPU(0.04);
return cell;
}
};
class SMC_Cell_factory : public AbstractCardiacCellFactory<1>
{
public:
SMC_Cell_factory() : AbstractCardiacCellFactory<1>()
{
}
AbstractCardiacCell* CreateCardiacCellForTissueNode(Node<1>* pNode)
{
CorriasBuistSMCModified *cell;
cell = new CorriasBuistSMCModified(mpSolver, mpZeroStimulus);
cell->SetFakeIccStimulusPresent(false);//it will get it from the real ICC, via gap junction
return cell;
}
};
class TestExtendedBidomainProblem: public CxxTest::TestSuite
{
public:
void SetupParameters()
{
HeartConfig::Instance()->Reset();
HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(5.0));
HeartConfig::Instance()->SetExtracellularConductivities(Create_c_vector(1.0));
HeartConfig::Instance()->SetOdePdeAndPrintingTimeSteps(0.1,0.1,10.0);
//HeartConfig::Instance()->SetKSPSolver("gmres");
HeartConfig::Instance()->SetUseAbsoluteTolerance(1e-5);
HeartConfig::Instance()->SetKSPPreconditioner("bjacobi");
}
/**
* This test is aimed at comparing the extended bidomain implementation in Chaste with
* the original Finite Difference code developed by Martin Buist.
*
* All the parameters are chosen to replicate the same conditions as in his code.
*/
void TestExtendedProblemVsMartincCode()
{
SetupParameters();
TetrahedralMesh<1,1> mesh;
unsigned number_of_elements = 100;//this is nGrid in Martin's code
double length = 10.0;//100mm as in Martin's code
mesh.ConstructRegularSlabMesh(length/number_of_elements, length);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), number_of_elements + 1);
double Am_icc = 1000.0;
double Am_smc = 1000.0;
double Am_gap = 1.0;
double Cm_icc = 1.0;
double Cm_smc = 1.0;
double G_gap = 20.0;//mS/cm^2
HeartConfig::Instance()->SetSimulationDuration(1000.0); //ms.
ICC_Cell_factory icc_factory;
SMC_Cell_factory smc_factory;
std::string dir = "ICCandSMC";
std::string filename = "extended1d";
HeartConfig::Instance()->SetOutputDirectory(dir);
HeartConfig::Instance()->SetOutputFilenamePrefix(filename);
ExtendedBidomainProblem<1> extended_problem( &icc_factory , &smc_factory);
extended_problem.SetMesh(&mesh);
extended_problem.SetExtendedBidomainParameters(Am_icc,Am_smc, Am_gap, Cm_icc, Cm_smc, G_gap);
extended_problem.SetIntracellularConductivitiesForSecondCell(Create_c_vector(1.0));
std::vector<unsigned> outputnodes;
outputnodes.push_back(50u);
HeartConfig::Instance()->SetRequestedNodalTimeTraces(outputnodes);
extended_problem.Initialise();
extended_problem.Solve();
HeartEventHandler::Headings();
HeartEventHandler::Report();
/**
* Compare with valid data.
* As Martin's code is an FD code, results will never match exactly.
* The comparison below is done against a 'valid' h5 file.
*
* The h5 file (1DValid.h5) is a Chaste (old phi_i formulation) file with is valid because, when extrapolating results from it, they look very similar
* (except for a few points at the end of the upstroke) to the results taken
* directly from Martin's code.
* A plot of Chaste results versus Martin's result (at node 50) is stored
* in the file 1DChasteVsMartin.eps for reference.
*
* A second plot comparing the old formulation (with phi_i) to the new formulation with V_m is contained in
*.1DChasteNewFormulation.png
*
*/
TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/extendedbidomain", "1DValid", false,
dir, filename, true,
0.2));
/*
* Here we compare the new formulation (V_m1, V_m2, phi_e)
* with the previous formulation (phi_i1, phi_i2, phi_e) running with GMRES and an absolute KSP tolerance of 1e-8.
*/
TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/extendedbidomain", "extended1d_previous_chaste_formulation_abs_tol_1e-8", false,
dir, filename, true,
1e-2));
}
// Test the functionality for outputting the values of requested cell state variables
void TestExtendedBidomainProblemPrintsMultipleVariables()
{
// Get the singleton in a clean state
HeartConfig::Instance()->Reset();
// Set configuration file
std::string dir = "ExtBidoMultiVars";
std::string filename = "extended";
HeartConfig::Instance()->SetOutputDirectory(dir);
HeartConfig::Instance()->SetOutputFilenamePrefix(filename);
HeartConfig::Instance()->SetSimulationDuration(0.1);
// HeartConfig::Instance()->SetKSPSolver("gmres");
HeartConfig::Instance()->SetUseAbsoluteTolerance(2e-4);
HeartConfig::Instance()->SetKSPPreconditioner("jacobi");
/** Check that also the converters handle multiple variables**/
HeartConfig::Instance()->SetVisualizeWithCmgui(true);
HeartConfig::Instance()->SetVisualizeWithMeshalyzer(true);
TetrahedralMesh<1,1> mesh;
unsigned number_of_elements = 100;
double length = 10.0;
mesh.ConstructRegularSlabMesh(length/number_of_elements, length);
// Override the variables we are interested in writing.
std::vector<std::string> output_variables;
output_variables.push_back("calcium_dynamics__Ca_NSR");
output_variables.push_back("ionic_concentrations__Nai");
output_variables.push_back("fast_sodium_current_j_gate__j");
output_variables.push_back("ionic_concentrations__Ki");
HeartConfig::Instance()->SetOutputVariables( output_variables );
// Set up problem
PlaneStimulusCellFactory<CellFaberRudy2000FromCellML, 1> cell_factory_1(-60, 0.5);
PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory_2(0.0,0.5);
ExtendedBidomainProblem<1> ext_problem( &cell_factory_1, &cell_factory_2 );
ext_problem.SetMesh(&mesh);
// Solve
ext_problem.Initialise();
ext_problem.Solve();
// Get a reference to a reader object for the simulation results
Hdf5DataReader data_reader1 = ext_problem.GetDataReader();
std::vector<double> times = data_reader1.GetUnlimitedDimensionValues();
// Check there is information about 11 timesteps (0, 0.01, 0.02, ...)
unsigned num_steps = 11u;
TS_ASSERT_EQUALS( times.size(), num_steps);
TS_ASSERT_DELTA( times[0], 0.0, 1e-12);
TS_ASSERT_DELTA( times[1], 0.01, 1e-12);
TS_ASSERT_DELTA( times[2], 0.02, 1e-12);
TS_ASSERT_DELTA( times[3], 0.03, 1e-12);
// There should be 11 values per variable and node.
std::vector<double> node_5_v = data_reader1.GetVariableOverTime("V", 5);
TS_ASSERT_EQUALS( node_5_v.size(), num_steps);
std::vector<double> node_5_v_2 = data_reader1.GetVariableOverTime("V_2", 5);
TS_ASSERT_EQUALS( node_5_v_2.size(), num_steps);
std::vector<double> node_5_phi = data_reader1.GetVariableOverTime("Phi_e", 5);
TS_ASSERT_EQUALS( node_5_phi.size(), num_steps);
for (unsigned i=0; i<output_variables.size(); i++)
{
unsigned global_index = 2+i*2;
std::vector<double> values = data_reader1.GetVariableOverTime(output_variables[i], global_index);
TS_ASSERT_EQUALS( values.size(), num_steps);
// Check the last values match the cells' state
if (ext_problem.rGetMesh().GetDistributedVectorFactory()->IsGlobalIndexLocal(global_index))
{
AbstractCardiacCellInterface* p_cell = ext_problem.GetTissue()->GetCardiacCell(global_index);
TS_ASSERT_DELTA(values.back(), p_cell->GetAnyVariable(output_variables[i],0), 1e-12);
}
//check the extra files for extra variables are there (the content is tested in the converter's tests)
FileFinder file(dir + "/output/"+ filename +"_"+ output_variables[i] + ".dat", RelativeTo::ChasteTestOutput);
TS_ASSERT(file.Exists());
}
}
};
#endif /*_TESTEXTENDEDBIDOMAINPROBLEM_HPP_*/
| 11,690 | 3,837 |
#include <functional> // reference_wrapper
#include <iostream>
#include <string>
#include <vector>
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Association @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//Object composition is used to model relationships where a complex object is built from one or more simpler
//objects (parts). In this lesson, we’ll take a look at a weaker type of relationship between two otherwise
//unrelated objects, called an association. Unlike object composition relationships, in an association, there is
//no implied whole/part relationship.
//To qualify as an association, an object and another object must have the following relationship:
// The associated object (member) is otherwise unrelated to the object (class) ==> not part of the object
// The associated object (member) can belong to more than one object (class) at a time
// The associated object (member) does not have its existence managed by the object (class)
// The associated object (member) may or may not know about the existence of the object (class)
//The relationship between doctors and patients is a great example of an association. The doctor clearly has a
//relationship with his patients, but conceptually it’s not a part/whole (object composition) relationship. A
//doctor can see many patients in a day, and a patient can see many doctors (perhaps they want a second opinion,
//or they are visiting different types of doctors). Neither of the object’s lifespans are tied to the other.
//We can say that association models as “uses-a” relationship. The doctor “uses” the patient (to earn income).
//The patient uses the doctor (for whatever health purposes they need).
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Composition ==> part-of
// Aggregation ==> has-a
// Association ==> uses-a
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//Because associations are a broad type of relationship, they can be implemented in
//many different ways. However, most often, associations are implemented using pointers,
//where the object points at the associated object.
//In this example, we’ll implement a bi-directional Doctor/Patient relationship, since it
//makes sense for the Doctors to know who their Patients are, and vice-versa.
// Since Doctor and Patient have a circular dependency, we're going to forward declare Patient
class Patient;
class Doctor
{
private:
std::string m_name{};
std::vector<std::reference_wrapper<const Patient>> m_patient{};
public:
Doctor(const std::string& name) :
m_name{ name }
{
}
void addPatient(Patient& patient);
// We'll implement this function below Patient since we need Patient to be defined at that point
friend std::ostream& operator<<(std::ostream& out, const Doctor& doctor);
const std::string& getName() const { return m_name; }
};
class Patient
{
private:
std::string m_name{};
std::vector<std::reference_wrapper<const Doctor>> m_doctor{}; // so that we can use it here
// We're going to make addDoctor private because we don't want the public to use it.
// They should use Doctor::addPatient() instead, which is publicly exposed
void addDoctor(const Doctor& doctor)
{
m_doctor.push_back(doctor);
}
public:
Patient(const std::string& name)
: m_name{ name }
{
}
// We'll implement this function below Doctor since we need Doctor to be defined at that point
friend std::ostream& operator<<(std::ostream& out, const Patient& patient);
const std::string& getName() const { return m_name; }
// We'll friend Doctor::addPatient() so it can access the private function Patient::addDoctor()
friend void Doctor::addPatient(Patient& patient);
};
void Doctor::addPatient(Patient& patient)
{
// Our doctor will add this patient
m_patient.push_back(patient);
// and the patient will also add this doctor
patient.addDoctor(*this);
}
std::ostream& operator<<(std::ostream& out, const Doctor& doctor)
{
if (doctor.m_patient.empty())
{
out << doctor.m_name << " has no patients right now";
return out;
}
out << doctor.m_name << " is seeing patients: ";
for (const auto& patient : doctor.m_patient)
out << patient.get().getName() << ' ';
return out;
}
std::ostream& operator<<(std::ostream& out, const Patient& patient)
{
if (patient.m_doctor.empty())
{
out << patient.getName() << " has no doctors right now";
return out;
}
out << patient.m_name << " is seeing doctors: ";
for (const auto& doctor : patient.m_doctor)
out << doctor.get().getName() << ' ';
return out;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//In general, you should avoid bidirectional associations if a unidirectional one will do, as they add complexity
//and tend to be harder to write without making errors.
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//******************************************************************************************************************
//************************************* Reflexive association ****************************************************
//******************************************************************************************************************
//Sometimes objects may have a relationship with other objects of the same type. This is called a reflexive
//association. A good example of a reflexive association is the relationship between a university course and
//its prerequisites (which are also university courses).
//******************************************************************************************************************
//Consider the simplified case where a Course can only have one prerequisite. We can do something like this:
class Course
{
private:
std::string m_name;
const Course* m_prerequisite;
public:
Course(const std::string& name, const Course* prerequisite = nullptr):
m_name{ name }, m_prerequisite{ prerequisite }
{
}
void printPrerequisites() const
{
if (m_prerequisite)
{
std::cout << m_name << " has a prerequisite of " << m_prerequisite->m_name << std::endl;
}
else
{
std::cout << m_name << " has no prerequisite" << std::endl;
}
}
};
//This can lead to a chain of associations (a course has a prerequisite, which has a prerequisite, etc…)
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//Associations can be indirect
//In all of the previous cases, we’ve used either pointers or references to directly link objects together.
//However, in an association, this is not strictly required. Any kind of data that allows you to link two
//objects together suffices. In the following example, we show how a Driver class can have a unidirectional
//association with a Car without actually including a Car pointer or reference member:
class Car
{
private:
std::string m_name;
int m_id;
public:
Car(const std::string& name, int id)
: m_name{ name }, m_id{ id }
{
}
const std::string& getName() const { return m_name; }
int getId() const { return m_id; }
};
// Our CarLot is essentially just a static array of Cars and a lookup function to retrieve them.
// Because it's static, we don't need to allocate an object of type CarLot to use it
class CarLot
{
private:
static Car s_carLot[4];
public:
CarLot() = delete; // Ensure we don't try to create a CarLot
static Car* getCar(int id)
{
for (int count{ 0 }; count < 4; ++count)
{
if (s_carLot[count].getId() == id)
{
return &(s_carLot[count]);
}
}
return nullptr;
}
};
Car CarLot::s_carLot[4]{ { "Prius", 4 }, { "Corolla", 17 }, { "Accord", 84 }, { "Matrix", 62 } };
class Driver
{
private:
std::string m_name;
int m_carId; // we're associated with the Car by ID rather than pointer
public:
Driver(const std::string& name, int carId)
: m_name{ name }, m_carId{ carId }
{
}
const std::string& getName() const { return m_name; }
int getCarId() const { return m_carId; }
};
int main()
{
// Create a Patient outside the scope of the Doctor
Patient dave{ "Dave" };
Patient frank{ "Frank" };
Patient betsy{ "Betsy" };
Patient jane{ "Jane" };
Patient john{ "John" };
Patient joan{ "Joan" };
Patient sally{ "Sally" };
Patient raj{ "Raj" };
Doctor james{ "James" };
Doctor scott{ "Scott" };
Doctor karim{ "Karim" };
Doctor akram{ "Akram" };
Doctor collete{ "Collete" };
james.addPatient(dave);
scott.addPatient(dave);
scott.addPatient(betsy);
karim.addPatient(jane);
karim.addPatient(betsy);
akram.addPatient(john);
akram.addPatient(joan);
collete.addPatient(joan);
collete.addPatient(sally);
collete.addPatient(raj);
//doctors
std::cout << "==========================================================" << '\n';
std::cout << "======================== Doctors =========================" << '\n';
std::cout << "==========================================================" << '\n';
std::cout << james << '\n';
std::cout << scott << '\n';
std::cout << karim << '\n';
std::cout << akram << '\n';
std::cout << collete << '\n';
//patients
std::cout << "==========================================================" << '\n';
std::cout << "======================== Patients ========================" << '\n';
std::cout << "==========================================================" << '\n';
std::cout << dave << '\n';
std::cout << frank << '\n';
std::cout << betsy << '\n';
std::cout << jane << '\n';
std::cout << john << '\n';
std::cout << joan << '\n';
std::cout << sally << '\n';
std::cout << raj << '\n';
std::cout << "==========================================================" << '\n';
std::cout << "==========================================================" << '\n';
//********************************************************************************
Course computerArch { "Computer Architecture" };
Course advancedComputerArch{ "Advanced Computer Architecture" , &computerArch };
computerArch.printPrerequisites();
advancedComputerArch.printPrerequisites();
//********************************************************************************
Driver d{ "Franz", 17 }; // Franz is driving the car with ID 17
Car* car{ CarLot::getCar(d.getCarId()) }; // Get that car from the car lot
if (car)
std::cout << d.getName() << " is driving a " << car->getName() << '\n';
else
std::cout << d.getName() << " couldn't find his car\n";
return 0;
}
| 11,053 | 3,503 |
#include "hoWaveletOperator.h"
namespace Gadgetron
{
template <typename T>
hoWaveletOperator<T>::hoWaveletOperator(std::vector<size_t> *dims) : input_in_kspace_(false), no_null_space_(true), num_of_wav_levels_(1), with_approx_coeff_(false), proximity_across_cha_(false), BaseClass(dims)
{
p_active_wav_ = &harr_wav_;
//gt_timer1_.set_timing_in_destruction(false);
//gt_timer2_.set_timing_in_destruction(false);
//gt_timer3_.set_timing_in_destruction(false);
}
template <typename T>
hoWaveletOperator<T>::~hoWaveletOperator()
{
}
template <typename T>
void hoWaveletOperator<T>::select_wavelet(const std::string& wav_name)
{
if (wav_name == "db2" || wav_name == "db3" || wav_name == "db4" || wav_name == "db5")
{
redundant_wav_.compute_wavelet_filter(wav_name);
p_active_wav_ = &redundant_wav_;
}
else
{
p_active_wav_ = &harr_wav_;
}
}
template <typename T>
void hoWaveletOperator<T>::restore_acquired_kspace(const ARRAY_TYPE& acquired, ARRAY_TYPE& y)
{
try
{
GADGET_CHECK_THROW(acquired.get_number_of_elements() == y.get_number_of_elements());
size_t N = acquired.get_number_of_elements();
const T* pA = acquired.get_data_ptr();
T* pY = y.get_data_ptr();
int n(0);
#pragma omp parallel for default(none) private(n) shared(N, pA, pY)
for (n = 0; n<(int)N; n++)
{
if (std::abs(pA[n]) > 0)
{
pY[n] = pA[n];
}
}
}
catch (...)
{
GADGET_THROW("Errors happened in hoWaveletOperator<T>::restore_acquired_kspace(...) ... ");
}
}
template <typename T>
void hoWaveletOperator<T>::restore_acquired_kspace(ARRAY_TYPE& y)
{
this->restore_acquired_kspace(acquired_points_, y);
}
template <typename T>
void hoWaveletOperator<T>::set_acquired_points(ARRAY_TYPE& kspace)
{
try
{
std::vector<size_t> dim;
kspace.get_dimensions(dim);
acquired_points_.create(dim, kspace.begin());
acquired_points_indicator_.create(kspace.dimensions());
Gadgetron::clear(acquired_points_indicator_);
unacquired_points_indicator_.create(kspace.dimensions());
Gadgetron::clear(unacquired_points_indicator_);
size_t N = kspace.get_number_of_elements();
long long ii(0);
#pragma omp parallel for default(shared) private(ii) shared(N, kspace)
for (ii = 0; ii<(long long)N; ii++)
{
if (std::abs(kspace(ii)) < DBL_EPSILON)
{
unacquired_points_indicator_(ii) = T(1.0);
}
else
{
acquired_points_indicator_(ii) = T(1.0);
}
}
// allocate the helper memory
kspace_.create(kspace.dimensions());
complexIm_.create(kspace.dimensions());
}
catch (...)
{
GADGET_THROW("Errors in hoWaveletOperator<T>::set_acquired_points(...) ... ");
}
}
// ------------------------------------------------------------
// Instantiation
// ------------------------------------------------------------
template class EXPORTCPUOPERATOR hoWaveletOperator< float >;
template class EXPORTCPUOPERATOR hoWaveletOperator< double >;
template class EXPORTCPUOPERATOR hoWaveletOperator< std::complex<float> >;
template class EXPORTCPUOPERATOR hoWaveletOperator< std::complex<double> >;
}
| 3,773 | 1,233 |
/// ---------------------------------------------------------------------------
/// @section LICENSE
///
/// Copyright (c) 2016 Georgia Tech Research Institute (GTRI)
/// All Rights Reserved
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
/// DEALINGS IN THE SOFTWARE.
/// ---------------------------------------------------------------------------
/// @file filename.ext
/// @author Kevin DeMarco <kevin.demarco@gtri.gatech.edu>
/// @author Eric Squires <eric.squires@gtri.gatech.edu>
/// @version 1.0
/// ---------------------------------------------------------------------------
/// @brief A brief description.
///
/// @section DESCRIPTION
/// A long description.
/// ---------------------------------------------------------------------------
#include <scrimmage/common/Utilities.h>
#include <scrimmage/plugin_manager/RegisterPlugin.h>
#include <scrimmage/math/State.h>
#include <scrimmage/parse/ParseUtils.h>
#include "Straight.h"
#include <iostream>
using std::cout;
using std::endl;
REGISTER_PLUGIN(scrimmage::Autonomy, Straight, Straight_plugin)
Straight::Straight()
{
}
void Straight::init(std::map<std::string,std::string> ¶ms)
{
speed_ = scrimmage::get("speed", params, 0.0);
desired_state_->vel() = speed_*Eigen::Vector3d::UnitX();
desired_state_->quat().set(0,0,state_->quat().yaw());
desired_state_->pos() = (state_->pos()(2))*Eigen::Vector3d::UnitZ();
// Project goal in front...
Eigen::Vector3d rel_pos = Eigen::Vector3d::UnitX()*2000;
Eigen::Vector3d unit_vector = rel_pos.normalized();
unit_vector = state_->quat().rotate(unit_vector);
goal_ = state_->pos() + unit_vector * rel_pos.norm();
}
bool Straight::step_autonomy(double t, double dt)
{
Eigen::Vector3d diff = goal_ - state_->pos();
Eigen::Vector3d v = speed_ * diff.normalized();
///////////////////////////////////////////////////////////////////////////
// Convert desired velocity to desired speed, heading, and pitch controls
///////////////////////////////////////////////////////////////////////////
desired_state_->vel()(0) = v.norm();
// Desired heading
double heading = scrimmage::Angles::angle_2pi(atan2(v(1), v(0)));
// Desired pitch
Eigen::Vector2d xy(v(0), v(1));
double pitch = scrimmage::Angles::angle_2pi(atan2(v(2), xy.norm()));
// Set Desired Altitude to goal's z-position
desired_state_->pos()(2) = goal_(2);
// Set the desired pitch and heading
desired_state_->quat().set(0, pitch, heading);
return true;
}
| 3,090 | 1,014 |
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 1991-2000, University of Groningen, The Netherlands.
* Copyright (c) 2001-2013, The GROMACS development team.
* Copyright (c) 2013,2014,2015,2016,2017, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
#include "gmxpre.h"
#include "dialogs.h"
#include "config.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for fork()
#endif
#include "gromacs/mdtypes/md_enums.h"
#include "gromacs/utility/arraysize.h"
#include "gromacs/utility/cstringutil.h"
#include "gromacs/utility/dir_separator.h"
#include "gromacs/utility/fatalerror.h"
#include "gromacs/utility/futil.h"
#include "gromacs/utility/smalloc.h"
#include "manager.h"
#include "nmol.h"
#include "x11.h"
#include "xdlghi.h"
#include "xmb.h"
#define MBFLAGS /* MB_APPLMODAL | */ MB_DONTSHOW
void write_gmx(t_x11 *x11, t_gmx *gmx, int mess)
{
XEvent letter;
letter.type = ClientMessage;
letter.xclient.display = x11->disp;
letter.xclient.window = gmx->wd->self;
letter.xclient.message_type = 0;
letter.xclient.format = 32;
letter.xclient.data.l[0] = mess;
letter.xclient.data.l[1] = Button1;
XSendEvent(x11->disp, letter.xclient.window, True, 0, &letter);
}
static void shell_comm(const char *title, const char *script, int nsleep)
{
FILE *tfil;
char command[STRLEN];
char tmp[32];
std::strcpy(tmp, "dialogXXXXXX");
tfil = gmx_fopen_temporary(tmp);
fprintf(tfil, "%s\n", script);
fprintf(tfil, "sleep %d\n", nsleep);
gmx_ffclose(tfil);
std::sprintf(command, "xterm -title %s -e sh %s", title, tmp);
#ifdef DEBUG
std::fprintf(stderr, "command: %s\n", command);
#endif
if (0 != std::system(command))
{
gmx_fatal(FARGS, "Failed to execute command: %s", command);
}
#ifdef DEBUG
unlink(tmp)
#endif
}
void show_mb(t_gmx *gmx, int mb)
{
if (mb >= 0 && mb < emNR)
{
gmx->which_mb = mb;
ShowDlg(gmx->mboxes[mb]);
}
}
static void hide_mb(t_gmx *gmx)
{
if (gmx->which_mb >= 0 && gmx->which_mb < emNR)
{
HideDlg(gmx->mboxes[gmx->which_mb]);
gmx->which_mb = -1;
}
}
static void MBCallback(t_x11 * /*x11*/, int dlg_mess, int /*item_id*/,
char * /*set*/, void *data)
{
t_gmx *gmx;
gmx = static_cast<t_gmx *>(data);
if (dlg_mess == DLG_EXIT)
{
hide_mb(gmx);
}
}
static t_dlg *about_mb(t_x11 *x11, t_gmx *gmx)
{
const char *lines[] = {
" G R O M A C S",
" Machine for Simulating Chemistry",
" Copyright (c) 1992-2013",
" Berk Hess, David van der Spoel, Erik Lindahl",
" and many collaborators!"
};
return MessageBox(x11, gmx->wd->self, gmx->wd->text,
asize(lines), lines, MB_OK | MB_ICONGMX | MBFLAGS,
MBCallback, gmx);
}
static void QuitCB(t_x11 *x11, int dlg_mess, int /*item_id*/,
char *set, void *data)
{
t_gmx *gmx;
gmx = static_cast<t_gmx *>(data);
hide_mb(gmx);
if (dlg_mess == DLG_EXIT)
{
if (gmx_strcasecmp("yes", set) == 0)
{
write_gmx(x11, gmx, IDTERM);
}
}
}
static t_dlg *quit_mb(t_x11 *x11, t_gmx *gmx)
{
const char *lines[] = {
" Do you really want to Quit ?"
};
return MessageBox(x11, gmx->wd->self, gmx->wd->text,
asize(lines), lines,
MB_YESNO | MB_ICONSTOP | MBFLAGS,
QuitCB, gmx);
}
static t_dlg *help_mb(t_x11 *x11, t_gmx *gmx)
{
const char *lines[] = {
" Help will soon be added"
};
return MessageBox(x11, gmx->wd->self, gmx->wd->text,
asize(lines), lines,
MB_OK | MB_ICONINFORMATION | MBFLAGS,
MBCallback, gmx);
}
static t_dlg *ni_mb(t_x11 *x11, t_gmx *gmx)
{
const char *lines[] = {
" This feature has not been",
" implemented yet."
};
return MessageBox(x11, gmx->wd->self, gmx->wd->text,
asize(lines), lines,
MB_OK | MB_ICONEXCLAMATION | MBFLAGS,
MBCallback, gmx);
}
enum {
eExE, eExGrom, eExPdb, eExConf, eExNR
};
static void ExportCB(t_x11 *x11, int dlg_mess, int item_id,
char *set, void *data)
{
bool bOk;
t_gmx *gmx;
t_dlg *dlg;
gmx = static_cast<t_gmx *>(data);
dlg = gmx->dlgs[edExport];
switch (dlg_mess)
{
case DLG_SET:
switch (item_id)
{
case eExGrom:
gmx->ExpMode = eExpGromos;
break;
case eExPdb:
gmx->ExpMode = eExpPDB;
break;
default:
break;
}
#ifdef DEBUG
std::fprintf(stderr, "exportcb: item_id=%d\n", item_id);
#endif
break;
case DLG_EXIT:
if ((bOk = gmx_strcasecmp("ok", set)) == 0)
{
std::strcpy(gmx->confout, EditText(dlg, eExConf));
}
HideDlg(dlg);
if (bOk)
{
write_gmx(x11, gmx, IDDOEXPORT);
}
break;
}
}
enum {
eg0, egTOPOL, egCONFIN, egPARAM, eg1, eg1PROC, eg32PROC
};
enum bond_set {
ebShowH = 11, ebDPlus, ebRMPBC, ebCue, ebSkip, ebWait
};
static void BondsCB(t_x11 *x11, int dlg_mess, int item_id,
char *set, void *data)
{
static int ebond = -1;
static int ebox = -1;
bool bOk, bBond = false;
int nskip, nwait;
t_gmx *gmx;
char *endptr;
gmx = static_cast<t_gmx *>(data);
if (ebond == -1)
{
ebond = gmx->man->molw->bond_type;
ebox = gmx->man->molw->boxtype;
}
switch (dlg_mess)
{
case DLG_SET:
if (item_id <= eBNR)
{
ebond = item_id-1;
bBond = false;
}
else if (item_id <= eBNR+esbNR+1)
{
ebox = item_id-eBNR-2;
bBond = true;
}
else
{
#define DO_NOT(b) (b) = (!(b))
switch (item_id)
{
case ebShowH:
toggle_hydrogen(x11, gmx->man->molw);
break;
case ebDPlus:
DO_NOT(gmx->man->bPlus);
#ifdef DEBUG
std::fprintf(stderr, "gmx->man->bPlus=%s\n",
gmx->man->bPlus ? "true" : "false");
#endif
break;
case ebRMPBC:
toggle_pbc(gmx->man);
break;
case ebCue:
DO_NOT(gmx->man->bSort);
#ifdef DEBUG
std::fprintf(stderr, "gmx->man->bSort=%s\n",
gmx->man->bSort ? "true" : "false");
#endif
break;
case ebSkip:
nskip = std::strtol(set, &endptr, 10);
if (endptr != set)
{
#ifdef DEBUG
std::fprintf(stderr, "nskip: %d frames\n", nskip);
#endif
if (nskip >= 0)
{
gmx->man->nSkip = nskip;
}
}
break;
case ebWait:
nwait = std::strtol(set, &endptr, 10);
if (endptr != set)
{
#ifdef DEBUG
std::fprintf(stderr, "wait: %d ms\n", nwait);
#endif
if (nwait >= 0)
{
gmx->man->nWait = nwait;
}
}
default:
#ifdef DEBUG
std::fprintf(stderr, "item_id: %d, set: %s\n", item_id, set);
#endif
break;
}
}
break;
case DLG_EXIT:
bOk = (gmx_strcasecmp("ok", set) == 0);
HideDlg(gmx->dlgs[edBonds]);
if (bOk)
{
if (bBond)
{
switch (ebond)
{
case eBThin:
write_gmx(x11, gmx, IDTHIN);
break;
case eBFat:
write_gmx(x11, gmx, IDFAT);
break;
case eBVeryFat:
write_gmx(x11, gmx, IDVERYFAT);
break;
case eBSpheres:
write_gmx(x11, gmx, IDBALLS);
break;
default:
gmx_fatal(FARGS, "Invalid bond type %d at %s, %d",
ebond, __FILE__, __LINE__);
}
}
else
{
switch (ebox)
{
case esbNone:
write_gmx(x11, gmx, IDNOBOX);
break;
case esbRect:
write_gmx(x11, gmx, IDRECTBOX);
break;
case esbTri:
write_gmx(x11, gmx, IDTRIBOX);
break;
case esbTrunc:
write_gmx(x11, gmx, IDTOBOX);
break;
default:
gmx_fatal(FARGS, "Invalid box type %d at %s, %d",
ebox, __FILE__, __LINE__);
}
}
}
break;
}
}
enum {
esFUNCT = 1, esBSHOW, esINFIL, esINDEXFIL, esLSQ, esSHOW, esPLOTFIL
};
typedef t_dlg *t_mmb (t_x11 *x11, t_gmx *gmx);
typedef struct {
const char *dlgfile;
DlgCallback *cb;
} t_dlginit;
void init_dlgs(t_x11 *x11, t_gmx *gmx)
{
static t_dlginit di[] = {
{ "export.dlg", ExportCB },
{ "bonds.dlg", BondsCB }
};
static t_mmb *mi[emNR] = { quit_mb, help_mb, about_mb, ni_mb };
unsigned int i;
snew(gmx->dlgs, edNR);
for (i = 0; (i < asize(di)); i++)
{
gmx->dlgs[i] = ReadDlg(x11, gmx->wd->self, di[i].dlgfile,
di[i].dlgfile,
0, 0, true, false, di[i].cb, gmx);
}
gmx->dlgs[edFilter] = select_filter(x11, gmx);
snew(gmx->mboxes, emNR);
for (i = 0; (i < emNR); i++)
{
gmx->mboxes[i] = mi[i](x11, gmx);
}
gmx->which_mb = -1;
}
void done_dlgs(t_gmx *gmx)
{
int i;
for (i = 0; (i < edNR); i++)
{
FreeDlg(gmx->dlgs[i]);
}
for (i = 0; (i < emNR); i++)
{
FreeDlg(gmx->mboxes[i]);
}
}
void edit_file(const char *fn)
{
if (fork() == 0)
{
char script[256];
std::sprintf(script, "vi %s", fn);
shell_comm(fn, script, 0);
std::exit(0);
}
}
| 13,064 | 4,599 |
#include "toppane.h"
#include "engine.h"
#include "enginep.h"
#include "surface.h"
/////////////////////////////////////////////////////////////////////////////
//
// TopPane
//
/////////////////////////////////////////////////////////////////////////////
class TopPaneSurfaceSite : public SurfaceSite {
private:
TopPane* m_ptopPane;
public:
TopPaneSurfaceSite(TopPane* ptopPane) :
m_ptopPane(ptopPane)
{
}
void UpdateSurface(Surface* psurface)
{
m_ptopPane->RepaintSurface();
}
};
/////////////////////////////////////////////////////////////////////////////
//
// TopPane
//
/////////////////////////////////////////////////////////////////////////////
TopPane::TopPane(Engine* pengine, bool bColorKey, TopPaneSite* psite, Pane* pchild) :
Pane(pchild),
m_pengine(pengine),
// m_psurface(pengine->CreateSurface(WinPoint(1, 1), stype, new TopPaneSurfaceSite(this))),
m_psurface(NULL),
m_psite(psite),
m_bColorKey(bColorKey),
m_bNeedLayout(true)
{ //Fix memory leak -Imago 8/2/09
SetSize(WinPoint(0, 0));
}
void TopPane::RepaintSurface()
{
m_bNeedPaint = true;
m_bPaintAll = true;
}
void TopPane::NeedLayout()
{
if (!m_bNeedLayout) {
m_bNeedLayout = true;
m_psite->SizeChanged();
}
}
void TopPane::NeedPaintInternal()
{
if (!m_bNeedPaint) {
m_bNeedPaint = true;
m_psite->SurfaceChanged();
}
}
void TopPane::Paint(Surface* psurface)
{
// psurface->FillSurface(Color(0.8f, 0.5f, 1.0f));
}
void TopPane::Evaluate()
{
if (m_bNeedLayout) {
m_bNeedLayout = false;
WinPoint sizeOld = GetSize();
UpdateLayout();
WinPoint sizeNew = GetSize();
// This creates the top level surface. Create a new render target for now.
if ( ( sizeNew != sizeOld ) && ( sizeNew != WinPoint(0,0) ) )
{
m_bNeedPaint = true;
m_bPaintAll = true;
/* if( sizeNew == CD3DDevice9::GetCurrentResolution() )
{
m_psurface = m_pengine->CreateDummySurface(
sizeNew,
new TopPaneSurfaceSite( this ) );
}
else*/
{
m_psurface = m_pengine->CreateRenderTargetSurface(
sizeNew,
new TopPaneSurfaceSite( this ) );
}
}
}
}
void TopPane::UpdateLayout()
{
DefaultUpdateLayout();
}
bool g_bPaintAll = false;
bool g_bUpdateOffset = false;
void TopPane::UpdateBits()
{
/* ORIGINAL ALLEGIANCE VERSION.
ZEnter("TopPane::UpdateBits()");
if (m_bNeedPaint) {
ZTrace("m_bNeedPaint == true");
if (CalcPaint()) {
m_bNeedPaint = true;
m_bPaintAll = true;
}
ZTrace("after CalcPaint() m_bNeedPaint ==" + ZString(m_bNeedPaint));
ZTrace("after CalcPaint() m_bPaintAll ==" + ZString(m_bPaintAll ));
m_bPaintAll |= g_bPaintAll;
InternalPaint(m_psurface);
m_bNeedPaint = false;
}
ZExit("TopPane::UpdateBits()");*/
ZEnter("TopPane::UpdateBits()");
{
HRESULT hr;
bool bRenderTargetRequired;
ZAssert(m_psurface != NULL);
PrivateSurface* pprivateSurface; CastTo(pprivateSurface, m_psurface);
bRenderTargetRequired = pprivateSurface->GetSurfaceType().Test(SurfaceTypeRenderTarget() ) == true;
if( bRenderTargetRequired == true )
{
TEXHANDLE hTexture = pprivateSurface->GetTexHandle( );
ZAssert( hTexture != INVALID_TEX_HANDLE );
hr = CVRAMManager::Get()->PushRenderTarget( hTexture );
}
ZTrace("m_bNeedPaint == true");
CalcPaint();
m_bNeedPaint = true;
m_bPaintAll = true;
ZTrace("after CalcPaint() m_bPaintAll ==" + ZString(m_bPaintAll ));
WinPoint offset( 0, 0 );
// Call InternalPaint() with the child offset and parent size as params and create initial clipping rect.
WinRect rectClip( 0,
0,
(int) m_psurface->GetSize().X(),
(int) m_psurface->GetSize().Y() );
m_bPaintAll |= g_bPaintAll;
InternalPaint( m_psurface );
m_bNeedPaint = false;
if( bRenderTargetRequired == true )
{
CVRAMManager::Get()->PopRenderTarget( );
}
}
ZExit("TopPane::UpdateBits()");
/* {
ZTrace("m_bNeedPaint == true");
CalcPaint();
m_bNeedPaint = true;
m_bPaintAll = true;
ZTrace("after CalcPaint() m_bNeedPaint ==" + ZString(m_bNeedPaint));
ZTrace("after CalcPaint() m_bPaintAll ==" + ZString(m_bPaintAll ));
m_bPaintAll |= g_bPaintAll;
// localOffset.SetY( localOffset.Y() - (int)m_psurface->GetSize().Y() );
// localOffset += globalOffset;
WinPoint offset( localOffset );
// Remove offset now.
offset.SetY( offset.Y() - (int)m_psurface->GetSize().Y() );
// Call InternalPaint() with the child offset and parent size as params and create initial clipping rect.
WinRect rectClip( offset.X(),
offset.Y(),
offset.X() + (int) m_psurface->GetSize().X(),
offset.Y() + (int) m_psurface->GetSize().Y() );
// m_psurface is a dummy surface. Store the context.
InternalPaint( m_psurface, offset, rectClip );
m_bNeedPaint = false;
}
ZExit("TopPane::UpdateBits()");*/
}
const WinPoint& TopPane::GetSurfaceSize()
{
Evaluate();
return GetSize();
}
Surface* TopPane::GetSurface()
{
Evaluate();
//when the size is zero, the surface is not initialized
if (m_size.X() == 0 || m_size.Y() == 0) {
return NULL;
}
UpdateBits();
return m_psurface;
}
Point TopPane::TransformLocalToImage(const WinPoint& point)
{
return
m_psite->TransformLocalToImage(
GetPanePoint(
Point::Cast(point)
)
);
}
Point TopPane::GetPanePoint(const Point& point)
{
return
Point(
point.X(),
(float)GetSize().Y() - 1.0f - point.Y()
);
}
void TopPane::MouseEnter(IInputProvider* pprovider, const Point& point)
{
// m_bInside = true;
/* if( m_psurface->GetSurfaceType().Test( SurfaceTypeDummy() ) == false )
{
OutputDebugString("MouseEnter\n");
}*/
}
MouseResult TopPane::HitTest(IInputProvider* pprovider, const Point& point, bool bCaptured)
{
return Pane::HitTest(pprovider, GetPanePoint(point), bCaptured);
}
MouseResult TopPane::Button(
IInputProvider* pprovider,
const Point& point,
int button,
bool bCaptured,
bool bInside,
bool bDown
) {
return Pane::Button(pprovider, GetPanePoint(point), button, bCaptured, bInside, bDown);
}
| 6,436 | 2,406 |
#include<iostream>
using namespace std;
const int MAXN = 128;
const int MOD = 101;
char state1[MAXN*MAXN], state2[MAXN*MAXN];
int field[MAXN][MAXN];
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
for(int i = 1; i<=n; i++)
for(int j = 1; j<=n; j++)
cin >> field[i][j];
char *curState = state1, *nextState = state2;
if(field[1][1] == field[n][n])
nextState[1*MAXN + 1] = 1;
for(int diag = 3; diag<n+2; diag++)
{
swap(curState, nextState);
for(int x = 1; x<diag; x++)
{
int y = diag - x;
for(int x_0 = min(diag-1, n+1-x); x_0>=1 && diag + y <= n+1 + x_0; x_0--)
{
int x0 = n+1 - x_0;
int y0 = n+1 - (diag - x_0);
if(field[x][y] == field[x0][y0])
nextState[x*MAXN + x_0] = (curState[(x )*MAXN + (x_0 )]+
curState[(x )*MAXN + (x_0-1)]+
curState[(x-1)*MAXN + (x_0 )]+
curState[(x-1)*MAXN + (x_0-1)])%MOD;
else
nextState[x*MAXN + x_0] = 0;
}
}
}
int ans = 0;
for(int i = 1; i<=n; i++)
ans+=nextState[i*MAXN + n + 1 - i];
cout << ans%MOD;
return 0;
}
| 1,468 | 599 |
#include <glm/gtc/matrix_transform.hpp>
#include "entities/splatmap.hpp"
#include "shader_exception.hpp"
#include "geometries/terrain.hpp"
Splatmap::Splatmap():
// terrain textures (used by same shader) need to be attached to different texture units
m_texture_terrain_water(Image("assets/images/terrain/water.jpg"), GL_TEXTURE0),
m_texture_terrain_grass(Image("assets/images/terrain/grass.jpg"), GL_TEXTURE1),
m_texture_terrain_rock(Image("assets/images/terrain/rock.jpg"), GL_TEXTURE2),
m_texture_terrain_splatmap(Image("assets/images/terrain/splatmap.png"), GL_TEXTURE3),
m_program("assets/shaders/light_terrain.vert", "assets/shaders/light_terrain.frag"),
m_image("assets/images/terrain/heightmap.png"),
m_vbo(Terrain(m_image)),
m_renderer(m_program, m_vbo, {{0, "position", 3, 8, 0}, {1, "normal", 3, 8, 3}, {2, "texture_coord", 2, 8, 6}})
{
// vertex or fragment shaders failed to compile
if (m_program.has_failed()) {
throw ShaderException();
}
}
/* delegate drawing with OpenGL (buffers & shaders) to renderer */
void Splatmap::draw(const Uniforms& uniforms) {
// draw terrain using triangle strips
glm::vec3 color_light(1.0f, 1.0f, 1.0f);
glm::vec3 position_light(10.0f, 6.0f, 6.0f);
m_renderer.draw(
{
{"texture2d_water", m_texture_terrain_water},
{"texture2d_grass", m_texture_terrain_grass},
{"texture2d_rock", m_texture_terrain_rock},
{"texture2d_splatmap", m_texture_terrain_splatmap},
{"light.position", position_light},
{"light.ambiant", 0.2f * color_light},
{"light.diffuse", 0.5f * color_light},
{"light.specular", color_light},
}, GL_TRIANGLE_STRIP
);
}
/* delegate transform to renderer */
void Splatmap::set_transform(const Transformation& t) {
m_renderer.set_transform(t);
}
/* Free textures, renderer (vao/vbo buffers), and shader program */
void Splatmap::free() {
m_image.free();
m_texture_terrain_water.free();
m_texture_terrain_grass.free();
m_texture_terrain_rock.free();
m_texture_terrain_splatmap.free();
m_program.free();
m_renderer.free();
}
| 2,091 | 828 |
#include <Arduino.h>
#include "RTClib.h"
#include <FastLED.h>
#include <TM1637Display.h>
#define LED_PIN 7
#define CLK_PIN 2
#define DIO_PIN 3
#define NUM_LEDS 120
CRGB leds[NUM_LEDS];
RTC_DS3231 rtc;
TM1637Display display = TM1637Display(CLK_PIN, DIO_PIN);
void setup()
{
rtc.begin();
display.clear();
display.setBrightness(2);
FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(5);
// Check if the RTC lost power and if so, set the time to when sketch was compiled:
if (rtc.lostPower())
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
void loop()
{
// Get current date and time:
DateTime now = rtc.now();
// Display the current time in 24 hour format with leading zeros enabled and a center colon:
int displaytime = (now.hour() * 100) + now.minute();
display.showNumberDecEx(displaytime, 0b11100000, true);
// make every 5s red
if (now.second() % 5 || now.second() == 0)
leds[now.second()] = CRGB(0, 0, 255);
else
leds[now.second()] = CRGB(255, 0, 0);
FastLED.show();
} | 1,052 | 456 |
#include "gtest/gtest.h"
#include "logs/logs.hpp"
const std::string log_level_ret = "103272";
struct TestLogger : public logs::iLogger
{
static std::string latest_warning_;
static std::string latest_error_;
static std::string latest_fatal_;
static std::string latest_log_msg_;
static std::string set_log_level_;
std::string get_log_level (void) const override
{
return log_level_ret;
}
void set_log_level (const std::string& log_level) override
{
set_log_level_ = log_level;
}
bool supports_level (size_t msg_level) const override
{
return true;
}
bool supports_level (const std::string& msg_level) const override
{
return true;
}
void log (size_t msg_level, const std::string& msg,
const logs::SrcLocT& location = logs::SrcLocT::current()) override
{
switch (msg_level)
{
case logs::WARN:
warn(msg);
break;
case logs::ERROR:
error(msg);
break;
case logs::FATAL:
fatal(msg);
break;
default:
std::stringstream ss;
ss << msg_level << msg;
latest_log_msg_ = ss.str();
}
}
void log (const std::string& msg_level, const std::string& msg,
const logs::SrcLocT& location = logs::SrcLocT::current()) override
{
log(logs::enum_log(msg_level), msg);
}
void warn (const std::string& msg) const
{
latest_warning_ = msg;
}
void error (const std::string& msg) const
{
latest_error_ = msg;
}
void fatal (const std::string& msg) const
{
latest_fatal_ = msg;
}
};
std::string TestLogger::latest_warning_;
std::string TestLogger::latest_error_;
std::string TestLogger::latest_fatal_;
std::string TestLogger::latest_log_msg_;
std::string TestLogger::set_log_level_ = "0";
std::shared_ptr<TestLogger> tlogger = std::make_shared<TestLogger>();
int main (int argc, char** argv)
{
logs::set_logger(std::static_pointer_cast<logs::iLogger>(tlogger));
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
#ifndef DISABLE_LOGS_TEST
struct LOGS : public ::testing::Test
{
protected:
void TearDown (void) override
{
TestLogger::latest_warning_ = "";
TestLogger::latest_error_ = "";
TestLogger::latest_fatal_ = "";
TestLogger::set_log_level_ = "0";
}
};
TEST_F(LOGS, Default)
{
logs::DefLogger log;
EXPECT_STREQ("info", log.get_log_level().c_str());
log.set_log_level("debug");
EXPECT_STREQ("debug", log.get_log_level().c_str());
log.log(logs::INFO, "log info message");
log.log(logs::WARN, "log warn message");
log.log(logs::ERROR, "log error message");
try
{
log.log(logs::FATAL, "log fatal message");
FAIL() << "log.fatal failed to throw error";
}
catch (std::runtime_error& e)
{
const char* msg = e.what();
EXPECT_STREQ("log fatal message", msg);
}
catch (...)
{
FAIL() << "expected to throw runtime_error";
}
}
TEST_F(LOGS, Trace)
{
logs::trace("tracing message");
const char* cmsg = TestLogger::latest_log_msg_.c_str();
auto expect = fmts::sprintf("%dtracing message", logs::TRACE);
EXPECT_STREQ(expect.c_str(), cmsg);
}
TEST_F(LOGS, TraceFmt)
{
logs::tracef("tracing %.2f message %d with format %s",
4.15, 33, "applepie");
const char* cmsg = TestLogger::latest_log_msg_.c_str();
auto expect = fmts::sprintf(
"%dtracing 4.15 message 33 with format applepie", logs::TRACE);
EXPECT_STREQ(expect.c_str(), cmsg);
}
TEST_F(LOGS, Debug)
{
logs::debug("debugging message");
const char* cmsg = TestLogger::latest_log_msg_.c_str();
auto expect = fmts::sprintf("%ddebugging message", logs::DEBUG);
EXPECT_STREQ(expect.c_str(), cmsg);
}
TEST_F(LOGS, DebugFmt)
{
logs::debugf("debugging %.3f message %d with format %s",
0.31, 7, "orange");
const char* cmsg = TestLogger::latest_log_msg_.c_str();
auto expect = fmts::sprintf(
"%ddebugging 0.310 message 7 with format orange", logs::DEBUG);
EXPECT_STREQ(expect.c_str(), cmsg);
}
TEST_F(LOGS, Info)
{
logs::info("infoing message");
const char* cmsg = TestLogger::latest_log_msg_.c_str();
auto expect = fmts::sprintf("%dinfoing message", logs::INFO);
EXPECT_STREQ(expect.c_str(), cmsg);
}
TEST_F(LOGS, InfoFmt)
{
logs::infof("infoing %.4f message %d with format %s", 3.1415967, -1,
"plum");
const char* cmsg = TestLogger::latest_log_msg_.c_str();
auto expect = fmts::sprintf(
"%dinfoing 3.1416 message -1 with format plum", logs::INFO);
EXPECT_STREQ(expect.c_str(), cmsg);
}
TEST_F(LOGS, Warn)
{
logs::warn("warning message");
const char* cmsg = TestLogger::latest_warning_.c_str();
EXPECT_STREQ("warning message", cmsg);
}
TEST_F(LOGS, WarnFmt)
{
logs::warnf("warning %.2f message %d with format %s", 4.15, 33,
"applepie");
const char* cmsg = TestLogger::latest_warning_.c_str();
EXPECT_STREQ("warning 4.15 message 33 with format applepie", cmsg);
}
TEST_F(LOGS, Error)
{
logs::error("erroring message");
const char* emsg = TestLogger::latest_error_.c_str();
EXPECT_STREQ("erroring message", emsg);
}
TEST_F(LOGS, ErrorFmt)
{
logs::errorf("erroring %.3f message %d with format %s", 0.31, 7, "orange");
const char* emsg = TestLogger::latest_error_.c_str();
EXPECT_STREQ("erroring 0.310 message 7 with format orange", emsg);
}
TEST_F(LOGS, Fatal)
{
logs::fatal("fatal message");
const char* fmsg = TestLogger::latest_fatal_.c_str();
EXPECT_STREQ("fatal message", fmsg);
}
TEST_F(LOGS, FatalFmt)
{
logs::fatalf("fatal %.4f message %d with format %s", 3.1415967, -1,
"plum");
const char* fmsg = TestLogger::latest_fatal_.c_str();
EXPECT_STREQ("fatal 3.1416 message -1 with format plum", fmsg);
}
TEST_F(LOGS, GlobalGetSet)
{
EXPECT_STREQ(log_level_ret.c_str(), logs::get_log_level().c_str());
logs::set_log_level("1231");
EXPECT_STREQ("1231", TestLogger::set_log_level_.c_str());
}
TEST(DEFAULT, Logger)
{
logs::DefLogger logger;
EXPECT_TRUE(logger.supports_level(logs::INFO));
EXPECT_TRUE(logger.supports_level("info"));
logger.log(logs::INFO, "hello");
logger.log("warn", "world");
logger.log("error", "oh no");
try
{
logger.log(logs::FATAL, "death");
FAIL() << "not expecting fatal to succeed";
}
catch (std::exception& e)
{
EXPECT_STREQ("death", e.what());
}
}
TEST(DEFAULT, Conversions)
{
EXPECT_EQ(logs::INFO, logs::enum_log("info"));
EXPECT_EQ(logs::WARN, logs::enum_log("warn"));
EXPECT_EQ(logs::ERROR, logs::enum_log("error"));
EXPECT_EQ(logs::FATAL, logs::enum_log("fatal"));
EXPECT_EQ(logs::NOT_SET, logs::enum_log("hello"));
EXPECT_STREQ("info", logs::name_log(logs::INFO).c_str());
EXPECT_STREQ("warn", logs::name_log(logs::WARN).c_str());
EXPECT_STREQ("error", logs::name_log(logs::ERROR).c_str());
EXPECT_STREQ("fatal", logs::name_log(logs::FATAL).c_str());
EXPECT_STREQ("", logs::name_log(logs::NOT_SET).c_str());
}
#endif // DISABLE_LOGS_TEST
| 6,678 | 2,803 |
//
// Created by psi on 2019/11/24.
//
#pragma once
#include <optional>
#include <string>
namespace avif {
struct Box {
struct Header {
uint32_t offset = {};
uint32_t size = {};
uint32_t type = {};
[[ nodiscard ]] uint32_t end() const {
return this->offset + this->size;
}
};
public:
Header hdr = {};
public:
Box() = default;
Box(Box&&) = default;
Box(Box const&) = default;
Box& operator=(Box&&) = default;
Box& operator=(Box const&) = default;
};
}
| 498 | 193 |
// SPDX-License-Identifier: BSD-3-Clause
// SPDX-FileCopyrightText: 2020-2022 The Monero Project
#include "XMRigWidget.h"
#include "ui_XMRigWidget.h"
#include <QDesktopServices>
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QScrollBar>
#include <QStandardItemModel>
#include <QTableWidget>
#include "utils/Icons.h"
XMRigWidget::XMRigWidget(QSharedPointer<AppContext> ctx, QWidget *parent)
: QWidget(parent)
, ui(new Ui::XMRigWidget)
, m_ctx(std::move(ctx))
, m_XMRig(new XmRig(Config::defaultConfigDir().path()))
, m_model(new QStandardItemModel(this))
, m_contextMenu(new QMenu(this))
{
ui->setupUi(this);
connect(m_XMRig, &XmRig::stateChanged, this, &XMRigWidget::onXMRigStateChanged);
connect(m_XMRig, &XmRig::output, this, &XMRigWidget::onProcessOutput);
connect(m_XMRig, &XmRig::error, this, &XMRigWidget::onProcessError);
connect(m_XMRig, &XmRig::hashrate, this, &XMRigWidget::onHashrate);
// [Downloads] tab
ui->tableView->setModel(m_model);
m_contextMenu->addAction(icons()->icon("network.png"), "Download file", this, &XMRigWidget::linkClicked);
connect(ui->tableView, &QHeaderView::customContextMenuRequested, this, &XMRigWidget::showContextMenu);
connect(ui->tableView, &QTableView::doubleClicked, this, &XMRigWidget::linkClicked);
// [Settings] tab
ui->poolFrame->show();
ui->soloFrame->hide();
// XMRig executable
connect(ui->btn_browse, &QPushButton::clicked, this, &XMRigWidget::onBrowseClicked);
ui->lineEdit_path->setText(config()->get(Config::xmrigPath).toString());
// Run as admin/root
bool elevated = config()->get(Config::xmrigElevated).toBool();
if (elevated) {
ui->radio_elevateYes->setChecked(true);
} else {
ui->radio_elevateNo->setChecked(true);
}
connect(ui->radio_elevateYes, &QRadioButton::toggled, this, &XMRigWidget::onXMRigElevationChanged);
#if defined(Q_OS_WIN)
ui->radio_elevateYes->setToolTip("Not supported on Windows, yet.");
ui->radio_elevateYes->setEnabled(false);
ui->radio_elevateNo->setChecked(true);
#endif
// CPU threads
ui->threadSlider->setMinimum(1);
ui->threadSlider->setMaximum(QThread::idealThreadCount());
int threads = config()->get(Config::xmrigThreads).toInt();
ui->threadSlider->setValue(threads);
ui->label_threads->setText(QString("CPU threads: %1").arg(threads));
connect(ui->threadSlider, &QSlider::valueChanged, this, &XMRigWidget::onThreadsValueChanged);
// Mining mode
connect(ui->combo_miningMode, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &XMRigWidget::onMiningModeChanged);
ui->combo_miningMode->setCurrentIndex(config()->get(Config::miningMode).toInt());
// Pool/node address
this->updatePools();
connect(ui->combo_pools, &QComboBox::currentTextChanged, this, &XMRigWidget::onPoolChanged);
connect(ui->btn_poolConfig, &QPushButton::clicked, [this]{
QStringList pools = config()->get(Config::pools).toStringList();
bool ok;
QString poolStr = QInputDialog::getMultiLineText(this, "Pool addresses", "Set pool addresses (one per line):", pools.join("\n"), &ok);
if (!ok) {
return;
}
QStringList newPools = poolStr.split("\n");
newPools.removeAll("");
newPools.removeDuplicates();
config()->set(Config::pools, newPools);
this->updatePools();
});
// Network settings
connect(ui->check_tls, &QCheckBox::toggled, this, &XMRigWidget::onNetworkTLSToggled);
connect(ui->relayTor, &QCheckBox::toggled, this, &XMRigWidget::onNetworkTorToggled);
ui->check_tls->setChecked(config()->get(Config::xmrigNetworkTLS).toBool());
ui->relayTor->setChecked(config()->get(Config::xmrigNetworkTor).toBool());
// Receiving address
auto username = m_ctx->wallet->getCacheAttribute("feather.xmrig_username");
if (!username.isEmpty()) {
ui->lineEdit_address->setText(username);
}
connect(ui->lineEdit_address, &QLineEdit::textChanged, [=]() {
m_ctx->wallet->setCacheAttribute("feather.xmrig_username", ui->lineEdit_address->text());
});
connect(ui->btn_fillPrimaryAddress, &QPushButton::clicked, this, &XMRigWidget::onUsePrimaryAddressClicked);
// Password
auto password = m_ctx->wallet->getCacheAttribute("feather.xmrig_password");
if (!password.isEmpty()) {
ui->lineEdit_password->setText(password);
} else {
ui->lineEdit_password->setText("featherwallet");
m_ctx->wallet->setCacheAttribute("feather.xmrig_password", ui->lineEdit_password->text());
}
connect(ui->lineEdit_password, &QLineEdit::textChanged, [=]() {
m_ctx->wallet->setCacheAttribute("feather.xmrig_password", ui->lineEdit_password->text());
});
// [Status] tab
connect(ui->btn_start, &QPushButton::clicked, this, &XMRigWidget::onStartClicked);
connect(ui->btn_stop, &QPushButton::clicked, this, &XMRigWidget::onStopClicked);
connect(ui->btn_clear, &QPushButton::clicked, this, &XMRigWidget::onClearClicked);
ui->btn_stop->setEnabled(false);
ui->check_autoscroll->setChecked(true);
ui->label_status->setTextInteractionFlags(Qt::TextSelectableByMouse);
ui->label_status->hide();
this->printConsoleInfo();
}
bool XMRigWidget::isMining() {
return m_isMining;
}
void XMRigWidget::onWalletClosed() {
this->onStopClicked();
}
void XMRigWidget::onThreadsValueChanged(int threads) {
config()->set(Config::xmrigThreads, threads);
ui->label_threads->setText(QString("CPU threads: %1").arg(threads));
}
void XMRigWidget::onPoolChanged(const QString &pool) {
if (!pool.isEmpty()) {
config()->set(Config::xmrigPool, pool);
}
}
void XMRigWidget::onXMRigElevationChanged(bool elevated) {
config()->set(Config::xmrigElevated, elevated);
}
void XMRigWidget::onBrowseClicked() {
QString fileName = QFileDialog::getOpenFileName(this, "Path to XMRig executable", QDir::homePath());
if (fileName.isEmpty()) {
return;
}
config()->set(Config::xmrigPath, fileName);
ui->lineEdit_path->setText(fileName);
}
void XMRigWidget::onClearClicked() {
ui->console->clear();
}
void XMRigWidget::onUsePrimaryAddressClicked() {
ui->lineEdit_address->setText(m_ctx->wallet->address(0, 0));
}
void XMRigWidget::onStartClicked() {
QString xmrigPath = config()->get(Config::xmrigPath).toString();
if (!this->checkXMRigPath()) {
return;
}
QString address = [this](){
if (ui->combo_miningMode->currentIndex() == Config::MiningMode::Pool) {
return config()->get(Config::xmrigPool).toString();
} else {
return ui->lineEdit_solo->text().trimmed();
}
}();
if (address.isEmpty()) {
ui->console->appendPlainText("No pool or node address set. Please configure on the Settings tab.");
return;
}
// username is receiving address usually
auto username = m_ctx->wallet->getCacheAttribute("feather.xmrig_username");
auto password = m_ctx->wallet->getCacheAttribute("feather.xmrig_password");
if (username.isEmpty()) {
ui->console->appendPlainText("Please specify a receiving address on the Settings screen.");
return;
}
if (address.contains("cryptonote.social") && !username.contains(".")) {
// cryptonote social requires <addr>.<username>, we'll just grab a few chars from primary addy
username = QString("%1.%2").arg(username, m_ctx->wallet->address(0, 0).mid(0, 6));
}
int threads = ui->threadSlider->value();
m_XMRig->start(xmrigPath, threads, address, username, password, ui->relayTor->isChecked(), ui->check_tls->isChecked(),
ui->radio_elevateYes->isChecked());
}
void XMRigWidget::onStopClicked() {
m_XMRig->stop();
}
void XMRigWidget::onProcessOutput(const QByteArray &data) {
auto output = Utils::barrayToString(data);
if(output.endsWith("\n"))
output = output.trimmed();
ui->console->appendPlainText(output);
if(ui->check_autoscroll->isChecked())
ui->console->verticalScrollBar()->setValue(ui->console->verticalScrollBar()->maximum());
}
void XMRigWidget::onProcessError(const QString &msg) {
ui->console->appendPlainText("\n" + msg);
ui->btn_start->setEnabled(true);
ui->btn_stop->setEnabled(false);
this->setMiningStopped();
}
void XMRigWidget::onHashrate(const QString &hashrate) {
ui->label_status->show();
ui->label_status->setText(QString("Mining at %1").arg(hashrate));
}
void XMRigWidget::onDownloads(const QJsonObject &data) {
// For the downloads table we'll manually update the table
// with items once, as opposed to creating a class in
// src/models/. Saves effort; full-blown model
// is unnecessary in this case.
m_model->clear();
m_urls.clear();
auto version = data.value("version").toString();
ui->label_latest_version->setText(QString("Latest version: %1").arg(version));
QJsonObject assets = data.value("assets").toObject();
const auto _linux = assets.value("linux").toArray();
const auto macos = assets.value("macos").toArray();
const auto windows = assets.value("windows").toArray();
auto info = QSysInfo::productType();
QJsonArray *os_assets;
if(info == "osx") {
os_assets = const_cast<QJsonArray *>(&macos);
} else if (info == "windows") {
os_assets = const_cast<QJsonArray *>(&windows);
} else {
// assume linux
os_assets = const_cast<QJsonArray *>(&_linux);
}
int i = 0;
for(const auto &entry: *os_assets) {
auto _obj = entry.toObject();
auto _name = _obj.value("name").toString();
auto _url = _obj.value("url").toString();
auto _created_at = _obj.value("created_at").toString();
m_urls.append(_url);
auto download_count = _obj.value("download_count").toInt();
m_model->setItem(i, 0, Utils::qStandardItem(_name));
m_model->setItem(i, 1, Utils::qStandardItem(_created_at));
m_model->setItem(i, 2, Utils::qStandardItem(QString::number(download_count)));
i++;
}
m_model->setHeaderData(0, Qt::Horizontal, tr("Filename"), Qt::DisplayRole);
m_model->setHeaderData(1, Qt::Horizontal, tr("Date"), Qt::DisplayRole);
m_model->setHeaderData(2, Qt::Horizontal, tr("Downloads"), Qt::DisplayRole);
ui->tableView->verticalHeader()->setVisible(false);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
ui->tableView->setColumnWidth(2, 100);
}
void XMRigWidget::showContextMenu(const QPoint &pos) {
QModelIndex index = ui->tableView->indexAt(pos);
if (!index.isValid()) {
return;
}
m_contextMenu->exec(ui->tableView->viewport()->mapToGlobal(pos));
}
void XMRigWidget::updatePools() {
QStringList pools = config()->get(Config::pools).toStringList();
if (pools.isEmpty()) {
pools = m_defaultPools;
config()->set(Config::pools, pools);
}
ui->combo_pools->clear();
ui->combo_pools->insertItems(0, pools);
QString preferredPool = config()->get(Config::xmrigPool).toString();
if (pools.contains(preferredPool)) {
ui->combo_pools->setCurrentIndex(pools.indexOf(preferredPool));
} else {
preferredPool = pools.at(0);
config()->set(Config::xmrigPool, preferredPool);
}
}
void XMRigWidget::printConsoleInfo() {
ui->console->appendPlainText(QString("Detected %1 CPU threads.").arg(QThread::idealThreadCount()));
if (this->checkXMRigPath()) {
QString path = config()->get(Config::xmrigPath).toString();
ui->console->appendPlainText(QString("XMRig path set to %1").arg(path));
}
}
void XMRigWidget::onMiningModeChanged(int mode) {
config()->set(Config::miningMode, mode);
if (mode == Config::MiningMode::Pool) {
ui->poolFrame->show();
ui->soloFrame->hide();
ui->label_poolNodeAddress->setText("Pool address:");
ui->check_tls->setChecked(true);
} else { // Solo mining
ui->poolFrame->hide();
ui->soloFrame->show();
ui->label_poolNodeAddress->setText("Node address:");
ui->check_tls->setChecked(false);
}
}
void XMRigWidget::onNetworkTLSToggled(bool checked) {
config()->set(Config::xmrigNetworkTLS, checked);
}
void XMRigWidget::onNetworkTorToggled(bool checked) {
config()->set(Config::xmrigNetworkTor, checked);
}
void XMRigWidget::onXMRigStateChanged(QProcess::ProcessState state) {
if (state == QProcess::ProcessState::Starting) {
ui->btn_start->setEnabled(false);
ui->btn_stop->setEnabled(false);
this->setMiningStarted();
}
else if (state == QProcess::ProcessState::Running) {
ui->btn_start->setEnabled(false);
ui->btn_stop->setEnabled(true);
this->setMiningStarted();
}
else if (state == QProcess::ProcessState::NotRunning) {
ui->btn_start->setEnabled(true); // todo
ui->btn_stop->setEnabled(false);
ui->label_status->hide();
this->setMiningStopped();
}
}
void XMRigWidget::setMiningStopped() {
m_isMining = false;
emit miningEnded();
}
void XMRigWidget::setMiningStarted() {
m_isMining = true;
emit miningStarted();
}
bool XMRigWidget::checkXMRigPath() {
QString path = config()->get(Config::xmrigPath).toString();
if (path.isEmpty()) {
ui->console->appendPlainText("No XMRig executable is set. Please configure on the Settings tab.");
return false;
} else if (!Utils::fileExists(path)) {
ui->console->appendPlainText("Invalid path to XMRig executable detected. Please reconfigure on the Settings tab.");
return false;
} else {
return true;
}
}
void XMRigWidget::linkClicked() {
QModelIndex index = ui->tableView->currentIndex();
auto download_link = m_urls.at(index.row());
Utils::externalLinkWarning(this, download_link);
}
QStandardItemModel *XMRigWidget::model() {
return m_model;
}
XMRigWidget::~XMRigWidget() = default; | 14,333 | 4,727 |
/**
* @file application.cpp
* @brief
* @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org)
* @date 2001-12-25
* @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#include "o3d/core/precompiled.h"
#include "o3d/core/application.h"
#include "o3d/core/classfactory.h"
#include "o3d/core/taskmanager.h"
#include "o3d/core/display.h"
#include "o3d/core/filemanager.h"
#include "o3d/core/thread.h"
#include "o3d/core/timer.h"
#include "o3d/core/uuid.h"
#include "o3d/core/date.h"
#include "o3d/core/datetime.h"
#include "o3d/core/math.h"
#include "o3d/core/stringmap.h"
#include "o3d/core/appwindow.h"
#include "o3d/core/debug.h"
#include "o3d/core/gl.h"
#include <algorithm>
using namespace o3d;
String *Application::ms_appsName = nullptr;
String *Application::ms_appsPath = nullptr;
Application::T_AppWindowMap Application::ms_appWindowMap;
_DISP Application::ms_display = NULL_DISP;
Activity *Application::ms_activity = nullptr;
void* Application::ms_app = nullptr;
Int32 Application::ms_appState = 0;
AppWindow* Application::ms_currAppWindow = nullptr;
CommandLine *Application::ms_appsCommandLine = nullptr;
Bool Application::ms_init = False;
Bool Application::ms_displayInit = False;
StringMap<BaseObject*> *ms_mappedObject = nullptr;
Bool Application::ms_displayError = False;
Activity::~Activity()
{
}
// Objective-3D initialization
void Application::init(AppSettings settings, Int32 argc, Char **argv, void *app)
{
if (ms_init) {
return;
}
ms_appState = 0;
ms_app = app;
ms_mappedObject = new StringMap<BaseObject*>;
// get the main thread id
ThreadManager::init();
System::initTime();
Date::init();
DateTime::init();
Uuid::init();
// Get the application name and path
getBaseNamePrivate(argc, argv);
if (settings.clearLog) {
Debug::instance()->getDefaultLog().clearLog();
}
// Log start time
DateTime current(True);
O3D_MESSAGE(String("Starting of application on ") + current.buildString("%Y-%m-%d %H:%M:%S.%f"));
// Initialize fast memory allocator
MemoryManager::instance()->initFastAllocator(
settings.sizeOfFastAlloc16,
settings.sizeOfFastAlloc32,
settings.sizeOfFastAlloc64);
// Registration of the main thread to activate events
EvtManager::instance()->registerThread(nullptr);
#ifdef O3D_ANDROID
// @todo
ms_appsCommandLine = new CommandLine("");
#elif defined(O3D_WINDOWS)
String commandLine(GetCommandLineW());
ms_appsCommandLine = new CommandLine(commandLine);
#else
ms_appsCommandLine = new CommandLine(argc, argv);
#endif
// Math initialization
Math::init();
// only if display
if (settings.useDisplay) {
apiInitPrivate();
ms_displayInit = True;
GL::init();
String typeString = "Undefined";
if (GL::getType() == GL::API_GL) {
typeString = "GL3+";
} else if (GL::getType() == GL::API_GLES_3) {
typeString = "GLES3+";
}
O3D_MESSAGE(String("Choose {0} implementation with a {1} API").arg(GL::getImplementationName()).arg(typeString));
Display::instance();
}
// Active the PostMessage
EvtManager::instance()->enableAutoWakeUp();
ms_init = True;
}
// Objective-3D terminate
void Application::quit()
{
deletePtr(ms_activity);
if (!ms_init) {
return;
}
// Log quit time
DateTime current(True);
O3D_MESSAGE(String("Terminating of application on ") + current.buildString("%Y-%m-%d at %H:%M:%S.%f"));
ms_init = False;
// Disable the PostMessage
EvtManager::instance()->disableAutoWakeUp();
if (!ms_appWindowMap.empty()) {
O3D_WARNING("Still always exists application windows");
}
if (!ms_mappedObject->empty()) {
O3D_WARNING("Still always exists mapped object");
}
// terminate the task manager if running
TaskManager::destroy();
// timer manager before thread
TimerManager::destroy();
// wait all threads terminate
ThreadManager::waitEndThreads();
// delete class factory
ClassFactory::destroy();
// display manager
Display::destroy();
// Specific quit
if (ms_displayInit) {
apiQuitPrivate();
GL::quit();
ms_displayInit = False;
}
// deletion of the main thread
EvtManager::instance()->unRegisterThread(nullptr);
// debug manager
Debug::destroy();
// file manager
FileManager::destroy();
// event manager
EvtManager::destroy();
// math release
Math::quit();
// date quit
Date::quit();
DateTime::quit();
Uuid::quit();
// object mapping
deletePtr(ms_mappedObject);
// release memory manager allocators
MemoryManager::instance()->releaseFastAllocator();
// common members
deletePtr(ms_appsCommandLine);
deletePtr(ms_appsName);
deletePtr(ms_appsPath);
ms_app = nullptr;
}
Bool Application::isInit()
{
return ms_init;
}
// Return the command line
CommandLine* Application::getCommandLine()
{
return ms_appsCommandLine;
}
// Get the application name
const String& Application::getAppName()
{
if (ms_appsName) {
return *ms_appsName;
} else {
return String::getNull();
}
}
const String &Application::getAppPath()
{
if (ms_appsPath) {
return *ms_appsPath;
} else {
return String::getNull();
}
}
void Application::addAppWindow(AppWindow *appWindow)
{
if (appWindow && appWindow->getHWND()) {
if (ms_appWindowMap.find(appWindow->getHWND()) != ms_appWindowMap.end()) {
O3D_ERROR(E_InvalidParameter("Cannot add an application window with a similar handle"));
}
ms_appWindowMap[appWindow->getHWND()] = appWindow;
} else {
O3D_ERROR(E_InvalidParameter("Cannot add an invalid application window"));
}
}
void Application::removeAppWindow(_HWND hWnd)
{
IT_AppWindowMap it = ms_appWindowMap.find(hWnd);
if (it != ms_appWindowMap.end()) {
AppWindow *appWindow = it->second;
ms_appWindowMap.erase(it);
// and delete it
deletePtr(appWindow);
} else {
O3D_ERROR(E_InvalidParameter("Unable to find the window handle"));
}
}
Activity *Application::getActivity()
{
return ms_activity;
}
AppWindow* Application::getAppWindow(_HWND window)
{
IT_AppWindowMap it = ms_appWindowMap.find(window);
if (it != ms_appWindowMap.end()) {
return it->second;
} else {
return nullptr;
}
}
void Application::throwDisplayError(void *generic_data)
{
ms_displayError = True;
}
// Get the default primary display.
_DISP Application::getDisplay()
{
return ms_display;
}
void *Application::getApp()
{
return ms_app;
}
Bool Application::isDisplayError()
{
return ms_displayError;
}
void Application::registerObject(const String &name, BaseObject *object)
{
if (ms_mappedObject) {
if (ms_mappedObject->find(name) != ms_mappedObject->end()) {
O3D_ERROR(E_InvalidOperation(name + " is a registred object"));
}
ms_mappedObject->insert(std::make_pair(name, object));
}
}
void Application::unregisterObject(const String &name)
{
if (ms_mappedObject) {
auto it = ms_mappedObject->find(name);
if (it != ms_mappedObject->end()) {
ms_mappedObject->erase(it);
}
}
}
BaseObject *Application::getObject(const String &name)
{
if (ms_mappedObject) {
auto it = ms_mappedObject->find(name);
if (it != ms_mappedObject->end()) {
return it->second;
}
}
return nullptr;
}
void Application::setState(Int32 state)
{
ms_appState = state;
}
Int32 Application::getState()
{
return ms_appState;
}
#ifndef O3D_ANDROID
Int32 Application::startPrivate()
{
if (ms_activity) {
return ms_activity->onStart();
} else {
return 0;
}
}
Int32 Application::stopPrivate()
{
if (ms_activity) {
return ms_activity->onStop();
} else {
return 0;
}
}
#endif
void Application::setActivity(Activity *activity)
{
if (ms_activity) {
delete ms_activity;
}
ms_activity = activity;
}
void Application::start()
{
if (startPrivate() != 0) {
// @todo need exit now
}
}
void Application::run(Bool runOnce)
{
runPrivate(runOnce);
}
void Application::stop()
{
if (stopPrivate() != 0) {
// @todo need exit now
}
}
void Application::pushEvent(Application::EventType type, _HWND hWnd, void *data)
{
pushEventPrivate(type, hWnd, data);
}
| 8,490 | 2,883 |
#include <iostream>
#include <string>
void prefix_name_suffix(std::string &name, const std::string &prefix, const std::string &suffix) {
name.insert(name.begin(), 1, ' ');
name.insert(name.begin(), prefix.cbegin(), prefix.cend());
name.append(1, ' ');
name.append(suffix);
}
int main() {
std::string test("Stephen Inverter");
prefix_name_suffix(test, "Mr.", "III");
std::cout << test << '\n';
return 0;
}
| 440 | 162 |
#include "ExtSequencer.h"
std::vector<pdsp::ExtSequencer*> pdsp::ExtSequencer::instances;
pdsp::ExtSequencer::ExtSequencer() {
instances.push_back(this);
}
pdsp::ExtSequencer::~ExtSequencer() {
for (size_t i = 0; i < instances.size(); ++i) {
if (instances[i] == this) {
instances.erase(instances.begin() + i);
break;
}
}
}
| 379 | 140 |
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include <sstream>
#include "LoginToken.h"
#include "NebulaUtil.h"
#include "ObjectXML.h"
using namespace std;
bool LoginToken::is_valid(const string& user_token) const
{
return ((user_token == token) &&
((expiration_time == -1) || (time(0) < expiration_time)));
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
const std::string& LoginToken::set(const std::string& user_token, time_t valid)
{
if (valid == -1)
{
expiration_time = -1;
}
else if (valid > 0 )
{
expiration_time = time(0) + valid;
}
else
{
expiration_time = 0;
}
if (!user_token.empty())
{
token = user_token;
}
else
{
token = one_util::random_password();
}
return token;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void LoginToken::reset()
{
token.clear();
expiration_time = 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
std::string& LoginToken::to_xml(std::string& sxml) const
{
std::ostringstream xml;
if ( expiration_time == 0 )
{
xml << "<LOGIN_TOKEN/>";
}
else
{
xml << "<LOGIN_TOKEN>"
<< "<TOKEN>" << token << "</TOKEN>"
<< "<EXPIRATION_TIME>" << expiration_time << "</EXPIRATION_TIME>"
<< "</LOGIN_TOKEN>";
}
sxml = xml.str();
return sxml;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void LoginToken::from_xml_node(const xmlNodePtr node)
{
ObjectXML oxml(node);
oxml.xpath(token, "/LOGIN_TOKEN/TOKEN", "");
oxml.xpath<time_t>(expiration_time, "/LOGIN_TOKEN/EXPIRATION_TIME", 0);
}
| 3,290 | 858 |
/******************************************************************************/
/*!
\file Graph.cpp
\author Oliver Ryan Chong
\par email: oliver.chong\@digipen.edu
\par oliver.chong 900863
\par Course: CS1150
\par Project #02
\date 01/03/2012
\brief
This is the graph class that will be used to generate the graph to be used by the algorithm to find the shortest path
Copyright (C) 2011 DigiPen Institute of Technology Singapore
*/
/******************************************************************************/
#include "Graph.h"
#include "MathUtility.h"
//Edge class
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The constructor for the Edge class
\param
\return
*/
/******************************************************************************/
Edge::Edge()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The destructor for the Edge class
\param
\return
*/
/******************************************************************************/
Edge::~Edge()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The copy constructor for the Edge class
\param ed
the Edge class to be assigned
\return
*/
/******************************************************************************/
Edge::Edge(const Edge & ed)
{
from = ed.from;
to = ed.to;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The assignment operator overload for the Edge class
\param ed
the Edge class to be assigned
\return Edge
the Edge
*/
/******************************************************************************/
Edge & Edge::operator=(const Edge & ed)
{
if(this != &ed)
{
from = ed.from;
to = ed.to;
}
return *this;
}
//State class
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The constructor for the State class
\param
\return
*/
/******************************************************************************/
State::State()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The destructor for the State class
\param
\return
*/
/******************************************************************************/
State::~State()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The copy constructor for the State class
\param st
the State class to be assigned
\return
*/
/******************************************************************************/
State::State(const State & st)
{
worldPositionX = st.worldPositionX;
worldPositionY = st.worldPositionY;
edges = st.edges;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The assignment operator overload for the State class
\param st
the State class to be assigned
\return State
the State
*/
/******************************************************************************/
State & State::operator=(const State & st)
{
if(this != &st)
{
worldPositionX = st.worldPositionX;
worldPositionY = st.worldPositionY;
edges = st.edges;
}
return *this;
}
//Path class
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The constructor for the Path class
\param
\return
*/
/******************************************************************************/
Path::Path()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The destructor for the Path class
\param
\return
*/
/******************************************************************************/
Path::~Path()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
The assignment operator overload for the Path class
\param pa1
the Path class to be assigned
\return Path
the Path
*/
/******************************************************************************/
Path & Path::operator=(Path & pa1)
{
if(this != &pa1)
{
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Initializes the distance and path matrices based on the number of states in the path
\param
\return
*/
/******************************************************************************/
void Path::InitMatrix( void )
{
unsigned noOfStates = this->states.size();
//initialize the distance matrix based on the number of states in the path
std::vector< float > floatVec;
floatVec.reserve( noOfStates );
std::vector< int > intVec;
intVec.reserve( noOfStates );
for ( unsigned int y = 0; y < noOfStates; ++y )
{
floatVec.push_back( MAX_DISTANCE );
intVec.push_back( NO_LINK );
}//end for loop
this->m_distanceMtx.reserve( noOfStates );
this->m_pathMtx.reserve( noOfStates );
for ( unsigned int x = 0; x < noOfStates; ++x )
{
this->m_distanceMtx.push_back( floatVec );
this->m_pathMtx.push_back( intVec );
}//end for loop
//set to identity
for ( unsigned int x = 0; x < noOfStates; ++x )
{
for ( unsigned int y = 0; y < noOfStates; ++y )
{
if ( x == y )
{
this->m_distanceMtx.at( x ).at( y ) = 0;
this->m_pathMtx.at( x ).at( y ) = DIRECT_LINK;
break;
}
}//end for loop
}//end for loop
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Populates the distance and path matrices based on the edges of each state in the path
\param
\return
*/
/******************************************************************************/
void Path::PopulateMatrix( void )
{
unsigned noOfStates = this->states.size();
//populate the distance matrix based on the edges of each state in the path
//loop through the states
for ( unsigned stateIndex = 0; stateIndex < noOfStates; ++stateIndex )
{
//get the current state
const State & currState = this->states.at( stateIndex );
//loop through the edges
for ( unsigned edgeIndex = 0; edgeIndex < currState.edges.size(); ++edgeIndex )
{
//get the current edge
const Edge & currEdge = currState.edges.at( edgeIndex );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//traverse the row
for ( unsigned x = 0; x < this->m_distanceMtx.size(); ++x )
{
//if row found ( from )
if ( currEdge.from == static_cast<int>( x ) )
{
std::vector< float > & colVecDM = this->m_distanceMtx.at( x );
std::vector< int> & colVecPath = this->m_pathMtx.at( x );
//traverse the column
for ( unsigned y = 0; colVecDM.size(); ++y )
{
//if column found ( to )
if ( currEdge.to == static_cast<int>( y ) )
{
//get the x and y positions of the from and to states
const State & fromState = this->states.at( currEdge.from );
const State & toState = this->states.at( currEdge.to );
//compute the distance between from and to states
float xDiff = toState.worldPositionX - fromState.worldPositionX;
float yDiff = toState.worldPositionY - fromState.worldPositionY;
float distanceSquared = ( xDiff * xDiff ) + ( yDiff * yDiff );
//store the distance ( cost ) between the states
colVecDM.at( y ) = distanceSquared;
//to identify a direct path between states
colVecPath.at( y ) = DIRECT_LINK;
break;
}
}//end for loop
break;
}
}//end for loop
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}//end for loop
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Generate the distance and path matrices to be used by Floyd's algorithm
\param
\return
*/
/******************************************************************************/
void Path::GenerateMatrix( void )
{
this->InitMatrix();
this->PopulateMatrix();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Floyd (or Floyd-Warshall) algorithm is a dynamic algorithm that finds the shortest paths between all pairs in a graph.
\param
\return
*/
/******************************************************************************/
void Path::FloydAlgorithm( void )
{
unsigned noOfStates = this->states.size();
//loop through the intermediate nodes that could possible provide the shortest path
for ( unsigned interIndex = 0; interIndex < noOfStates; ++interIndex )
{
for ( unsigned fromIndex = 0; fromIndex < noOfStates; ++fromIndex )
{
for ( unsigned toIndex = 0; toIndex < noOfStates; ++toIndex )
{
float distFromTo = this->m_distanceMtx.at( fromIndex).at( toIndex );
float distFromInter = this->m_distanceMtx.at( fromIndex ).at( interIndex );
float distInterTo = this->m_distanceMtx.at( interIndex ).at( toIndex );
//validate if the intermediate state node will give a shorter path to the destination
if ( distFromTo > distFromInter + distInterTo )
{
//update the distance cost based on the new shorter path
distFromTo = distFromInter + distInterTo;
this->m_distanceMtx.at( fromIndex).at( toIndex ) = distFromTo;
//update the path
this->m_pathMtx.at( fromIndex ).at( toIndex ) = interIndex;
}
}//end for loop
}//end for loop
}//end for loop
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Finds the shortest path based on the start and end indices.
This uses the path matrix generated by Floyd's algorithm
\param startIndex
the start index of the path
\param endIndex
the end index of the path
\return
*/
/******************************************************************************/
void Path::ComputeShortestPath( const int startIndex, const int endIndex )
{
//get the path node index based on the start and end index
int pathNodeIndex = this->m_pathMtx.at( startIndex ).at( endIndex );
//if there is no path
if ( pathNodeIndex == NO_LINK )
{
//do nothing
}
//if there is a direct path from start to end
else if ( pathNodeIndex == DIRECT_LINK )
{
//add the starting state
this->shortestPathIndices.push_back( startIndex );
//add the ending state
this->shortestPathIndices.push_back( endIndex );
}
//if there is an intermediate node
else
{
//find the intermediate nodes between the start and the middle state
this->FindIntermediateNodes( startIndex, pathNodeIndex, true );
//find the intermediate nodes between the middle and end state
this->FindIntermediateNodes( pathNodeIndex, endIndex, false );
//add the starting state
//this->shortestPathIndices.push_back( startIndex );
//add the intermediate nodes
for ( unsigned index = 0; index < this->intermediateNodes.size(); ++index )
{
this->shortestPathIndices.push_back( this->intermediateNodes.at( index ) );
}//end for loop
//clear the intermediate nodes
this->intermediateNodes.clear();
//add the ending state
//this->shortestPathIndices.push_back( endIndex );
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Finds the intermediate nodes between a specified start and end state
\param startIndex
the start index of the path
\param endIndex
the end index of the path
\param leftToRight
if true, traverse nodes from left to right.
if false, traverse from right to left
\return
*/
/******************************************************************************/
void Path::FindIntermediateNodes( const int startIndex, const int endIndex, bool leftToRight )
{
//get the path node index based on the start and end index
int pathNodeIndex = this->m_pathMtx.at( startIndex ).at( endIndex );
//if there is no path
if ( pathNodeIndex == NO_LINK )
{
//do nothing
}
//if there is a direct path from start to end
else if ( pathNodeIndex == DIRECT_LINK )
{
int firstStateIndex = 0;
int secondStateIndex = 0;
if ( leftToRight == true )
{
firstStateIndex = startIndex;
secondStateIndex = endIndex;
}
else
{
firstStateIndex = endIndex;
secondStateIndex = startIndex;
}
this->AddNodeIndex( firstStateIndex );
this->AddNodeIndex( secondStateIndex );
}
//if there is an intermediate node
else
{
//invoke function recursively to check for possible succeeding intermediate nodes
this->FindIntermediateNodes( startIndex, pathNodeIndex, true );
this->FindIntermediateNodes( pathNodeIndex, endIndex, false );
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/******************************************************************************/
/*!
Adds the state node index to the list
\param stateIndex
the state node index of the path
\return
*/
/******************************************************************************/
void Path::AddNodeIndex( const int stateIndex )
{
bool isExisting = false;
//validate if the node to be is already existing
for ( unsigned index = 0; index < this->intermediateNodes.size(); ++index )
{
if ( stateIndex == this->intermediateNodes.at( index ) )
{
isExisting = true;
break;
}
}//end for loop
if ( isExisting == false )
{
this->intermediateNodes.push_back( stateIndex );
}
} | 15,723 | 4,233 |