hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f6051aa5ea824d6e84e52a74093c14fb4fe0ec35 | 5,987 | cpp | C++ | src/renderer/Shader.cpp | AndrijaAda99/Bubo | 662bb8e602f18a81ea6d8f367cb697c60b3e6670 | [
"Apache-2.0"
] | null | null | null | src/renderer/Shader.cpp | AndrijaAda99/Bubo | 662bb8e602f18a81ea6d8f367cb697c60b3e6670 | [
"Apache-2.0"
] | null | null | null | src/renderer/Shader.cpp | AndrijaAda99/Bubo | 662bb8e602f18a81ea6d8f367cb697c60b3e6670 | [
"Apache-2.0"
] | null | null | null | #include <fstream>
#include "renderer/Shader.h"
#include "glad/glad.h"
#include <glm/gtc/type_ptr.hpp>
namespace bubo {
Shader::Shader(const std::string& vertexShaderPath, const std::string& fragmentShaderPath) {
init(parseShader(vertexShaderPath), parseShader(fragmentShaderPath));
}
Shader::~Shader() {
destroy();
}
unsigned int Shader::compileShader(unsigned int type, const char *shaderSrc) {
unsigned int shaderID = glCreateShader(type);
glShaderSource(shaderID, 1, &shaderSrc, nullptr);
glCompileShader(shaderID);
checkShaderCompilationError(type, shaderID);
return shaderID;
}
void Shader::init(const std::string& vertexShaderSource, const std::string& fragmentShaderSource) {
unsigned int vertexShader = compileShader(GL_VERTEX_SHADER, vertexShaderSource.c_str());
unsigned int fragmentShader = compileShader(GL_FRAGMENT_SHADER, fragmentShaderSource.c_str());
m_shaderProgramID = glCreateProgram();
glAttachShader(m_shaderProgramID, vertexShader);
glAttachShader(m_shaderProgramID, fragmentShader);
glLinkProgram(m_shaderProgramID);
checkProgramLinkError();
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
void Shader::destroy() const {
glDeleteProgram(m_shaderProgramID);
}
void Shader::checkShaderCompilationError(unsigned int type, unsigned int shaderID) {
int success;
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &success);
if (!success) {
GLint length;
glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &length);
std::vector<GLchar> infoLog(length);
glGetShaderInfoLog(shaderID, length, nullptr, &infoLog[0]);
BUBO_DEBUG_ERROR("Error while compiling shader source!\n{0}", infoLog.data());
glDeleteShader(shaderID);
switch (type) {
case GL_VERTEX_SHADER:
BUBO_ASSERT(success, "Failed to compile vertex shader!")
case GL_FRAGMENT_SHADER:
BUBO_ASSERT(success, "Failed to compile fragment shader!")
default:
BUBO_ASSERT(success, "Failed to compile unknown shader!")
}
}
}
void Shader::checkProgramLinkError() {
int success;
glGetProgramiv(m_shaderProgramID, GL_LINK_STATUS, &success);
if (!success) {
GLint length;
glGetProgramiv(m_shaderProgramID, GL_INFO_LOG_LENGTH, &length);
std::vector<GLchar> infoLog(length);
glGetProgramInfoLog(m_shaderProgramID, length, nullptr, &infoLog[0]);
BUBO_DEBUG_ERROR("{0}", infoLog.data());
BUBO_ASSERT(success, "Failed to compile shader program!")
}
}
std::string Shader::parseShader(const std::string& filepath) {
std::stringstream source;
std::fstream stream(filepath);
std::string line;
while (getline(stream, line)) {
source << line << std::endl;
}
return source.str();
}
void Shader::bind() const {
glUseProgram(m_shaderProgramID);
}
void Shader::unbind() const {
glUseProgram(0);
}
void Shader::setInt(const std::string &name, int value) {
GLint location = glGetUniformLocation(m_shaderProgramID, name.c_str());
glUniform1i(location, value);
}
void Shader::setFloat(const std::string &name, float value) {
GLint location = glGetUniformLocation(m_shaderProgramID, name.c_str());
glUniform1f(location, value);
}
void Shader::setVec2(const std::string &name, const glm::vec2 &value) {
GLint location = glGetUniformLocation(m_shaderProgramID, name.c_str());
glUniform2f(location, value.x, value.y);
}
void Shader::setVec3(const std::string &name, const glm::vec3 &value) {
GLint location = glGetUniformLocation(m_shaderProgramID, name.c_str());
glUniform3f(location, value.x, value.y, value.z);
}
void Shader::setVec4(const std::string &name, const glm::vec4 &value) {
GLint location = glGetUniformLocation(m_shaderProgramID, name.c_str());
glUniform4f(location, value.x, value.y, value.z, value.w);
}
void Shader::setMat3(const std::string &name, const glm::mat3 &value) {
GLint location = glGetUniformLocation(m_shaderProgramID, name.c_str());
glUniformMatrix3fv(location, 1, GL_FALSE, glm::value_ptr(value));
}
void Shader::setMat4(const std::string &name, const glm::mat4 &value) {
GLint location = glGetUniformLocation(m_shaderProgramID, name.c_str());
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(value));
}
std::map<std::string, Shader*> ShaderLibrary::m_shaders;
void ShaderLibrary::makeDefaultShaders() {
ShaderLibrary::m_shaders["defaultShader"] = new Shader("../../res/shaders/vertex.shader", "../../res/shaders/fragment.shader");
ShaderLibrary::m_shaders["framebufferShader"] = new Shader("../../res/shaders/framebuffer_vertex.shader", "../../res/shaders/framebuffer_fragment.shader");
ShaderLibrary::m_shaders["posterizationShader"] = new Shader("../../res/shaders/posterization_vertex.shader", "../../res/shaders/posterization_fragment.shader");
ShaderLibrary::m_shaders["skyboxShader"] = new Shader("../../res/shaders/skybox_vertex.shader", "../../res/shaders/skybox_fragment.shader");
}
void ShaderLibrary::add(const std::string &name, Shader *shader) {
if (m_shaders.find(name) != m_shaders.end()) {
m_shaders[name] = shader;
}
}
Shader *ShaderLibrary::get(const std::string &name) {
return m_shaders.find(name)->second;
}
void ShaderLibrary::destroyShaders() {
for (auto shader : m_shaders) {
delete shader.second;
}
}
}
| 34.017045 | 169 | 0.645231 | [
"vector"
] |
f60dd26c29eeade56307d5c54efa246e40a52f22 | 2,970 | hpp | C++ | include/codegen/include/GlobalNamespace/SafeAreaRectChecker.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/SafeAreaRectChecker.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/SafeAreaRectChecker.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Transform
class Transform;
// Forward declaring type: GameObject
class GameObject;
// Forward declaring type: RectTransform
class RectTransform;
// Skipping declaration: Vector3 because it is already included!
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: SafeAreaRectChecker
class SafeAreaRectChecker : public UnityEngine::MonoBehaviour {
public:
// Nested type: GlobalNamespace::SafeAreaRectChecker::InitData
class InitData;
// private System.Single _minAngleX
// Offset: 0x18
float minAngleX;
// private System.Single _maxAngleX
// Offset: 0x1C
float maxAngleX;
// private System.Single _minAngleY
// Offset: 0x20
float minAngleY;
// private System.Single _maxAngleY
// Offset: 0x24
float maxAngleY;
// private UnityEngine.Transform _cameraTransform
// Offset: 0x28
UnityEngine::Transform* cameraTransform;
// private UnityEngine.GameObject _activeObjectWhenInsideSafeArea
// Offset: 0x30
UnityEngine::GameObject* activeObjectWhenInsideSafeArea;
// private UnityEngine.GameObject _activeObjectWhenNotInsideSafeArea
// Offset: 0x38
UnityEngine::GameObject* activeObjectWhenNotInsideSafeArea;
// private UnityEngine.RectTransform _rectTransformToCheck
// Offset: 0x40
UnityEngine::RectTransform* rectTransformToCheck;
// private UnityEngine.Vector3[] _corners
// Offset: 0x48
::Array<UnityEngine::Vector3>* corners;
// private SafeAreaRectChecker/InitData _initData
// Offset: 0x50
GlobalNamespace::SafeAreaRectChecker::InitData* initData;
// public System.Void Start()
// Offset: 0xC2A8C8
void Start();
// protected System.Void Update()
// Offset: 0xC2A93C
void Update();
// public System.Void .ctor()
// Offset: 0xC2AB6C
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static SafeAreaRectChecker* New_ctor();
}; // SafeAreaRectChecker
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::SafeAreaRectChecker*, "", "SafeAreaRectChecker");
#pragma pack(pop)
| 35.783133 | 89 | 0.715152 | [
"object",
"transform"
] |
f6145a3ed62d4aa36d4399f8af450577940830ea | 383 | cpp | C++ | jp.atcoder/abc141/abc141_c/12001296.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-09T03:06:25.000Z | 2022-02-09T03:06:25.000Z | jp.atcoder/abc141/abc141_c/12001296.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-05T22:53:18.000Z | 2022-02-09T01:29:30.000Z | jp.atcoder/abc141/abc141_c/12001296.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, k, q; cin >> n >> k >> q;
vector<int> res(n, k - q);
for (int i = 0; i < q; i++) {
int a; cin >> a; a--;
res[a]++;
}
for (int i = 0; i < n; i++) {
string ans = (res[i] > 0) ? "Yes" : "No";
cout << ans << '\n';
}
return 0;
}
| 20.157895 | 46 | 0.43342 | [
"vector"
] |
f61e8bdcaf7275ae1bb621cf9d1aa556905d477f | 209 | cpp | C++ | 3DGame01/Vector.cpp | Craigspaz/RTS | f44fe0ead901ae64434e85080723d6465841676e | [
"MIT"
] | 1 | 2018-07-05T09:22:13.000Z | 2018-07-05T09:22:13.000Z | 3DGame01/Vector.cpp | Craigspaz/RTS | f44fe0ead901ae64434e85080723d6465841676e | [
"MIT"
] | null | null | null | 3DGame01/Vector.cpp | Craigspaz/RTS | f44fe0ead901ae64434e85080723d6465841676e | [
"MIT"
] | null | null | null | #include "Vector.h"
Vector2f newVector2f(float x, float y)
{
Vector2f n;
n.x = x;
n.y = y;
return n;
}
Vector2f add(Vector2f a, Vector2f b)
{
Vector2f n;
n.x = a.x + b.x;
n.y = a.y + b.y;
return n;
} | 12.294118 | 38 | 0.593301 | [
"vector"
] |
f61ee6b266781efeb9b4d1eadf657038a3bb60c2 | 2,052 | cpp | C++ | core/blockchain/impl/types.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | core/blockchain/impl/types.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | core/blockchain/impl/types.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "blockchain/impl/common.hpp"
#include "blockchain/impl/storage_util.hpp"
#include "common/visitor.hpp"
#include "storage/in_memory/in_memory_storage.hpp"
#include "storage/trie/polkadot_trie/polkadot_trie_impl.hpp"
#include "storage/trie/serialization/trie_serializer_impl.hpp"
OUTCOME_CPP_DEFINE_CATEGORY(kagome::blockchain, Error, e) {
switch (e) {
case kagome::blockchain::Error::BLOCK_NOT_FOUND:
return "Block with such ID is not found";
}
return "Unknown error";
}
namespace kagome::blockchain {
outcome::result<common::Buffer> idToLookupKey(const ReadableBufferMap &map,
const primitives::BlockId &id) {
auto key = visit_in_place(
id,
[&map](const primitives::BlockNumber &n) {
auto key = prependPrefix(numberToIndexKey(n),
prefix::Prefix::ID_TO_LOOKUP_KEY);
return map.get(key);
},
[&map](const common::Hash256 &hash) {
return map.get(prependPrefix(common::Buffer{hash},
prefix::Prefix::ID_TO_LOOKUP_KEY));
});
if (!key && isNotFoundError(key.error())) {
return Error::BLOCK_NOT_FOUND;
}
return key;
}
storage::trie::RootHash trieRoot(
const std::vector<std::pair<common::Buffer, common::Buffer>> &key_vals) {
auto trie = storage::trie::PolkadotTrieImpl();
auto codec = storage::trie::PolkadotCodec();
for (const auto &[key, val] : key_vals) {
[[maybe_unused]] auto res = trie.put(key, val);
BOOST_ASSERT_MSG(res.has_value(), "Insertion into trie failed");
}
auto root = trie.getRoot();
if (root == nullptr) {
return codec.hash256({0});
}
auto encode_res = codec.encodeNode(*root);
BOOST_ASSERT_MSG(encode_res.has_value(), "Trie encoding failed");
return codec.hash256(encode_res.value());
}
} // namespace kagome::blockchain
| 34.2 | 80 | 0.636452 | [
"vector"
] |
f61f36ad28e33d64d0bcdecd06481961e318ced4 | 1,505 | cpp | C++ | LG/P4427.cpp | ImChinaNB/code | 9c6940093cb480bd381c17557db87078e0efd740 | [
"MIT"
] | null | null | null | LG/P4427.cpp | ImChinaNB/code | 9c6940093cb480bd381c17557db87078e0efd740 | [
"MIT"
] | null | null | null | LG/P4427.cpp | ImChinaNB/code | 9c6940093cb480bd381c17557db87078e0efd740 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 300005;
const LL P = 998244353;
int n; vector<int> G[N];
inline LL pw(LL x, LL k) {
if (k == 0) return 1; if (k == 1) return x % P;
if (k & 1) return pw(x, k ^ 1) * x % P;
LL _ = pw(x, k >> 1); return _ * _ % P;
}
int dep[N], fa[20][N]; LL f[51][N];
void dfs(int x, int fa = 1) {
::fa[0][x] = fa;
for (int i = 1; i <= 50; ++i)
f[i][x] = (pw(dep[x], i) + f[i][fa]) % P;
for (int y : G[x]) {
if (y == fa) continue;
dep[y] = dep[x] + 1;
dfs(y, x);
}
}
void makelca() {
for (int i = 1; i < 20; ++i)
for (int j = 1; j <= n; ++j)
fa[i][j] = fa[i-1][fa[i-1][j]];
}
inline int getlca(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
for (int det = dep[x] - dep[y], i = 0; i < 20; ++i)
if (det & 1 << i) x = fa[i][x];
if (x == y) return x;
for (int i = 19; i >= 0; --i) {
if (fa[i][x] != fa[i][y]) {
x = fa[i][x];
y = fa[i][y];
}
}
return fa[0][x];
}
inline int answer(int x, int y, int k) {
int lca = getlca(x, y);
LL ret = f[k][x] + f[k][y] - f[k][fa[0][lca]] - f[k][lca];
ret %= P; ret += P; ret %= P;
return static_cast<int>(ret);
}
int main() {
scanf("%d", &n);
for (int i = 1; i < n; ++i) {
int x, y; scanf("%d%d", &x, &y);
G[x].push_back(y); G[y].push_back(x);
}
dfs(1); makelca();
int m; scanf("%d", &m);
while (m--) {
int i,j,k; scanf("%d%d%d", &i,&j,&k);
printf("%d\n", answer(i,j,k));
}
return 0;
}
| 23.153846 | 60 | 0.451827 | [
"vector"
] |
f6210c48ca4dd5e6324876add97071437b1adf70 | 34,505 | cpp | C++ | rdkat.cpp | rdkcmf/rdk-rdkat | b7d1488ac9652a5709c8656b199ba0bf035a8ba8 | [
"Apache-2.0"
] | null | null | null | rdkat.cpp | rdkcmf/rdk-rdkat | b7d1488ac9652a5709c8656b199ba0bf035a8ba8 | [
"Apache-2.0"
] | null | null | null | rdkat.cpp | rdkcmf/rdk-rdkat | b7d1488ac9652a5709c8656b199ba0bf035a8ba8 | [
"Apache-2.0"
] | null | null | null | /*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2017 RDK Management
*
* 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 "rdkat.h"
#include "logger.h"
#include "TTSClient.h"
#include <glib.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <atk/atk.h>
#include <sstream>
#define EVENT_OBJECT "rdkat.Event.Object"
#define EVENT_WINDOW "rdkat.Event.Window"
#define EVENT_DOCUMENT "rdkat.Event.Document"
#define EVENT_FOCUS "rdkat.Event.Focus"
#define PROPERTY_CHANGE "PropertyChange"
#define STATE_CHANGED "state-changed"
using namespace std;
namespace RDK_AT {
class RDKAt : public TTS::TTSConnectionCallback, public TTS::TTSSessionCallback {
enum val_type {
STRING,
INT,
POINTER
};
public:
static RDKAt& Instance() {
static RDKAt rdk_at;
return rdk_at;
}
~RDKAt() {
if(m_ttsClient) {
delete m_ttsClient;
m_ttsClient = NULL;
}
uninitialize();
}
void initialize(void);
void enableProcessing(bool enable);
void setVolumeControlCallback(MediaVolumeControlCallback cb, void *data);
void uninitialize(void);
void ensureTTSConnection();
void createOrDestroySession();
bool processingEnabled() { return m_process; }
void resetMediaVolume() {
if(RDKAt::Instance().m_mediaVolumeUpdated && RDKAt::Instance().m_mediaVolumeControlCB) {
RDKAt::Instance().m_mediaVolumeControlCB(RDKAt::Instance().m_mediaVolumeControlCBData, 1);
RDKAt::Instance().m_mediaVolumeUpdated = false;
}
}
// TTS Session Callbacks
virtual void onTTSServerConnected() {
RDKLOG_INFO("Connection to TTSManager got established");
// Handle TTSEngine crash & reconnection
if(processingEnabled())
m_shouldCreateSession = true;
}
virtual void onTTSServerClosed() {
RDKLOG_ERROR("Connection to TTSManager got closed!!!");
m_sessionId = 0;
m_shouldCreateSession = false;
}
virtual void onTTSStateChanged(bool enabled) {
m_ttsEnabled = enabled;
RDKLOG_INFO("TTS is %s", m_ttsEnabled ? "enabled" : "disabled");
}
virtual void onTTSSessionCreated(uint32_t, uint32_t) {};
virtual void onResourceAcquired(uint32_t, uint32_t) {};
virtual void onResourceReleased(uint32_t, uint32_t) {};
virtual void onSpeechStart(uint32_t appid, uint32_t sessionid, TTS::SpeechData &data) {
RDKLOG_INFO("appid=%d, sessionid=%d, speechid=%d, text=%s", appid, sessionid, data.id, data.text.c_str());
}
virtual void onNetworkError(uint32_t appId, uint32_t sessionId, uint32_t speechId) {
RDKLOG_INFO("appid=%d, sessionid=%d, speechid=%d", appId, sessionId, speechId);
resetMediaVolume();
}
virtual void onPlaybackError(uint32_t appId, uint32_t sessionId, uint32_t speechId) {
RDKLOG_INFO("appid=%d, sessionid=%d, speechid=%d", appId, sessionId, speechId);
resetMediaVolume();
}
virtual void onSpeechComplete(uint32_t appid, uint32_t sessionid, TTS::SpeechData &data) {
RDKLOG_INFO("appid=%d, sessionid=%d, speechid=%d, text=%s", appid, sessionid, data.id, data.text.c_str());
resetMediaVolume();
}
MediaVolumeControlCallback m_mediaVolumeControlCB;
void *m_mediaVolumeControlCBData;
private:
RDKAt() :
m_mediaVolumeControlCB(NULL),
m_mediaVolumeControlCBData(NULL),
m_listenerIds(NULL),
m_focusTrackerId(0),
m_keyEventListenerId(0),
m_initialized(false),
m_process(false),
m_ttsEnabled(false),
m_mediaVolumeUpdated(false),
m_appId(this),
m_sessionId(0),
m_shouldCreateSession(false),
m_ttsClient(NULL),
m_connectionAttempt(0) { }
RDKAt(RDKAt &) {}
inline static void printEventInfo(std::string &klass, std::string &major, std::string &minor,
guint32 d1, guint32 d2, const void *val, int type);
inline static void printAccessibilityInfo(std::string &name, std::string &desc, std::string &role);
static void HandleEvent(AtkObject *obj, std::string klass,
std::string major, std::string minor, guint32 d1, guint32 d2, const void *val, int type);
static gint KeyListener(AtkKeyEventStruct *event, gpointer data);
static void FocusTracker(AtkObject *accObj);
static gboolean PropertyEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean StateEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean WindowEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean DocumentEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean BoundsEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean ActiveDescendantEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean LinkSelectedEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean TextChangedEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean TextInsertEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean TextRemoveEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean TextSelectionChangedEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean ChildrenChangedEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
static gboolean GenericEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data);
guint addSignalListener(GSignalEmissionHook listener, const char *signal_name);
GArray *m_listenerIds;
gint m_focusTrackerId;
gint m_keyEventListenerId;
bool m_initialized;
bool m_process;
bool m_ttsEnabled;
bool m_mediaVolumeUpdated;
uint32_t m_appId;
uint32_t m_sessionId;
bool m_shouldCreateSession;
TTS::TTSClient *m_ttsClient;
uint8_t m_connectionAttempt;
};
gint RDKAt::KeyListener(AtkKeyEventStruct *event, gpointer data)
{
RDKLOG_TRACE("RDKAt::KeyListener()");
return 0;
}
inline std::string checkNullAndReturnStr(char* temp){
return (temp != NULL)? temp : std::string();
}
inline void getAccessibilityInfo(AtkObject *obj, std::string &name, std::string &desc, std::string &role) {
name = checkNullAndReturnStr(atk_object_get_name(obj));
desc = checkNullAndReturnStr(atk_object_get_description(obj));
role = checkNullAndReturnStr(atk_role_get_name(atk_object_get_role(obj)));
}
#define PRINT_HELPER(ss, c, key, value) do {\
if(!value.empty()) { \
ss << (c ? ", " : "") << key << "=\"" << value << "\""; \
c = true; \
} \
} while(0)
inline static void RDKAt::printEventInfo(std::string &klass, std::string &major, std::string &minor,
guint32 d1, guint32 d2, const void *val, int type) {
if (!is_log_level_enabled(RDK_AT::VERBOSE_LEVEL))
return;
bool c = false;
std::stringstream ss;
PRINT_HELPER(ss, c, "class", klass);
PRINT_HELPER(ss, c, "major", major);
PRINT_HELPER(ss, c, "minor", minor);
PRINT_HELPER(ss, c, "d1", std::to_string(d1));
PRINT_HELPER(ss, c, "d2", std::to_string(d2));
if(type == POINTER) {
char buff[16] = {0};
sprintf(buff, "%p", val);
PRINT_HELPER(ss, c, "data", std::string(buff));
} else if(type == INT) {
PRINT_HELPER(ss, c, "data", std::to_string((int)val));
} else if(type == STRING) {
PRINT_HELPER(ss, c, "data", std::string((char *)val));
}
RDKLOG_VERBOSE("%s", ss.str().c_str());
}
inline void RDKAt::printAccessibilityInfo(std::string &name, std::string &desc, std::string &role) {
if (!is_log_level_enabled(RDK_AT::VERBOSE_LEVEL))
return;
bool c = false;
std::stringstream ss;
PRINT_HELPER(ss, c, "name", name);
PRINT_HELPER(ss, c, "desc", desc);
PRINT_HELPER(ss, c, "role", role);
RDKLOG_VERBOSE("%s", ss.str().c_str());
}
std::string getCellDescription(AtkObject *cell, AtkRole role) {
static AtkObject *pCell = NULL;
static AtkTable *pTableObj = NULL;
static AtkObject *pRowObj = NULL;
// On focusing a non-cell element, forget previous cell details
if(role != ATK_ROLE_TABLE_CELL) {
pCell = NULL;
pTableObj = NULL;
pRowObj = NULL;
return string();
}
AtkObject *obj = cell;
AtkTable *tableObj = NULL;
AtkObject *rowObj = NULL;
// Find Table Object
while(obj) {
obj = atk_object_get_parent(obj);
if(!obj)
break;
role = atk_object_get_role(obj);
if(role == ATK_ROLE_TABLE) {
tableObj = ATK_TABLE(obj);
break;
} else if(role == ATK_ROLE_TABLE_ROW) {
rowObj = obj;
}
}
// Retrieve Table Caption
std::string caption;
if(tableObj) {
AtkObject *captionObj = atk_table_get_caption(tableObj);
if(captionObj && (cell == pCell || tableObj != pTableObj))
caption = checkNullAndReturnStr(atk_object_get_name(captionObj));
}
// Retrieve Row Heading
// Note : this is not the not Row Header element, but the accessible name of Row element
std::string rowHeader;
if(rowObj && (cell == pCell || rowObj != pRowObj)) {
rowHeader = checkNullAndReturnStr(atk_object_get_name(rowObj));
}
// Remember Table information
pTableObj = tableObj;
pRowObj = rowObj;
pCell = cell;
std::string res;
if(!caption.empty())
res = caption + ". ";
if(!rowHeader.empty())
res += rowHeader + ". ";
return res;
}
void RDKAt::ensureTTSConnection()
{
if(!m_ttsClient) {
if(m_connectionAttempt > 0)
return;
m_connectionAttempt++;
m_ttsClient = TTS::TTSClient::create(this);
}
}
void RDKAt::createOrDestroySession()
{
if(!m_ttsClient)
return;
if(processingEnabled()) {
if(m_sessionId == 0 && m_shouldCreateSession) {
m_sessionId = m_ttsClient->createSession(m_appId, "WPE", this);
}
} else {
if(m_sessionId != 0) {
if(m_mediaVolumeControlCBData)
m_mediaVolumeControlCB(m_mediaVolumeControlCBData, 1);
m_ttsClient->abort(m_sessionId);
m_ttsClient->destroySession(m_sessionId);
m_sessionId = 0;
}
}
m_shouldCreateSession = false;
}
void RDKAt::HandleEvent(AtkObject *obj, std::string klass,
std::string major, std::string minor,
guint32 d1, guint32 d2, const void *val, int type)
{
static bool logProcessingError = true;
if(!RDKAt::Instance().processingEnabled()) {
if(logProcessingError)
RDKLOG_ERROR("Processing ARIA Accessibility events are not enabled");
logProcessingError = false;
return;
}
logProcessingError = true;
printEventInfo(klass, major, minor, d1, d2, val, type);
RDKAt::Instance().ensureTTSConnection();
RDKAt::Instance().createOrDestroySession();
// If TTS is not enabled, skip costly dom traversals as part of name & desc retrieval
static bool enableDebugging = getenv("ENABLE_RDKAT_DEBUGGING");
static bool logDebuggingDisabled = true;
if(!RDKAt::Instance().m_ttsEnabled) {
if(!enableDebugging) {
if(logDebuggingDisabled)
RDKLOG_ERROR("Both TTS & RDK-AT Debugging are disabled, not fetching accessibility info");
logDebuggingDisabled = false;
return;
}
}
logDebuggingDisabled = true;
TTS::SpeechData d;
bool speak = false;
std::string name, desc, role;
static unsigned int counter = 0;
if(major == "state-changed") {
if(minor == "focused" && d1 == 1) {
getAccessibilityInfo(obj, name, desc, role);
printAccessibilityInfo(name, desc, role);
d.text = name;
if(!d.text.empty() && (role == "button" || role == "push button")) {
d.text += " button";
} else if(!d.text.empty() && (role == "check" || role == "check box")) {
bool md = false;
AtkStateSet *set = atk_object_ref_state_set(obj);
md = set ? atk_state_set_contains_state(set, ATK_STATE_CHECKED) : false;
d.text += (md ? " check box is checked" : " check box is unchecked");
}
if(!name.empty() && !desc.empty() && name != desc)
d.text += (". " + desc);
std::string cellDesc = getCellDescription(obj, atk_object_get_role(obj));
if(!cellDesc.empty()) {
RDKLOG_VERBOSE("Table Cell Description = \"%s\"", cellDesc.c_str());
d.text = cellDesc + d.text;
}
speak = true;
} else if(minor == "checked") {
getAccessibilityInfo(obj, name, desc, role);
printAccessibilityInfo(name, desc, role);
d.text = name;
if(!d.text.empty() && (role == "check" || role == "check box"))
d.text += (d1 ? " check box is checked" : " check box is unchecked");
speak = true;
}
} else if(major == "load-complete") {
AtkRole atkrole = atk_object_get_role(obj);
if(atkrole == ATK_ROLE_DOCUMENT_FRAME)
return;
getAccessibilityInfo(obj, name, desc, role);
printAccessibilityInfo(name, desc, role);
if(!name.empty()) {
d.text = std::string(name) + " is loaded";
speak = true;
}
}
TTS::TTSClient *ttsClient = RDKAt::Instance().m_ttsClient;
//it is temporary fix to Skip the duplication Text for YouTubeApp
static std::string oldText;
static AtkObject *oldObj = NULL;
if(speak && !d.text.empty()) {
if(d.text == oldText && obj == oldObj) {
RDKLOG_VERBOSE("Skipping the duplication Text : \"%s\"", d.text.c_str());
} else if(ttsClient) {
if(ttsClient->isActiveSession(RDKAt::Instance().m_sessionId)) {
if(!RDKAt::Instance().m_mediaVolumeUpdated && RDKAt::Instance().m_mediaVolumeControlCB) {
RDKAt::Instance().m_mediaVolumeControlCB(RDKAt::Instance().m_mediaVolumeControlCBData, 0.25);
RDKAt::Instance().m_mediaVolumeUpdated = true;
}
d.id = ++counter;
ttsClient->speak(RDKAt::Instance().m_sessionId, d);
} else {
RDKLOG_WARNING("Session has not acquired resource to speak");
}
} else {
RDKLOG_INFO("Text to Speak : \"%s\"", d.text.c_str());
}
oldText = d.text;
oldObj = obj;
}
}
void RDKAt::FocusTracker(AtkObject *accObj)
{
RDKLOG_TRACE("RDKAt::FocusTracker()");
HandleEvent(accObj, EVENT_FOCUS, "focus", "", 0, 0, 0, INT);
}
gboolean RDKAt::PropertyEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::PropertyEventListener()");
gint i;
const gchar *s1;
AtkObject *tObj;
AtkObject *accObj;
const gchar *propName = NULL;
AtkPropertyValues *propValues;
accObj = (AtkObject*)g_value_get_object(¶ms[0]);
propValues = (AtkPropertyValues *)g_value_get_pointer(¶ms[1]);
propName = propValues[0].property_name;
if(strcmp(propName, "accessible-name") == 0) {
s1 = atk_object_get_name(accObj);
if(s1 != NULL)
HandleEvent(accObj, EVENT_OBJECT, PROPERTY_CHANGE, propName, 0, 0, s1, STRING);
} else if(strcmp(propName, "accessible-description") == 0) {
s1 = atk_object_get_description(accObj);
if(s1 != NULL)
HandleEvent(accObj, EVENT_OBJECT, PROPERTY_CHANGE, propName, 0, 0, s1, STRING);
} else if(strcmp(propName, "accessible-parent") == 0) {
tObj = atk_object_get_parent(accObj);
if(tObj != NULL)
HandleEvent(accObj, EVENT_OBJECT, PROPERTY_CHANGE, propName, 0, 0, tObj, POINTER);
} else if(strcmp(propName, "accessible-role") == 0) {
i = atk_object_get_role(accObj);
HandleEvent(accObj, EVENT_OBJECT, PROPERTY_CHANGE, propName, 0, 0, GINT_TO_POINTER(i), INT);
} else if(strcmp(propName, "accessible-table-summary") == 0) {
tObj = atk_table_get_summary(ATK_TABLE(accObj));
if(tObj != NULL)
HandleEvent(accObj, EVENT_OBJECT, PROPERTY_CHANGE, propName, 0, 0, tObj, POINTER);
} else if(strcmp(propName, "accessible-table-column-header") == 0) {
i = g_value_get_int(&(propValues->new_value));
tObj = atk_table_get_column_header(ATK_TABLE(accObj), i);
if(tObj != NULL)
HandleEvent(accObj, EVENT_OBJECT, PROPERTY_CHANGE, propName, 0, 0, tObj, POINTER);
} else if(strcmp(propName, "accessible-table-row-header") == 0) {
i = g_value_get_int(&(propValues->new_value));
tObj = atk_table_get_row_header(ATK_TABLE(accObj), i);
if(tObj != NULL)
HandleEvent(accObj, EVENT_OBJECT, PROPERTY_CHANGE, propName, 0, 0, tObj, POINTER);
} else if(strcmp(propName, "accessible-table-row-description") == 0) {
i = g_value_get_int(&(propValues->new_value));
s1 = atk_table_get_row_description(ATK_TABLE(accObj), i);
HandleEvent(accObj, EVENT_OBJECT, PROPERTY_CHANGE, propName, 0, 0, s1, STRING);
} else if(strcmp(propName, "accessible-table-column-description") == 0) {
i = g_value_get_int(&(propValues->new_value));
s1 = atk_table_get_column_description(ATK_TABLE(accObj), i);
HandleEvent(accObj, EVENT_OBJECT, PROPERTY_CHANGE, propName, 0, 0, s1, STRING);
} else if(strcmp(propName, "accessible-table-caption-object") == 0) {
tObj = atk_table_get_caption(ATK_TABLE(accObj));
HandleEvent(accObj, EVENT_OBJECT, PROPERTY_CHANGE, propName, 0, 0, tObj, POINTER);
} else {
HandleEvent(accObj, EVENT_OBJECT, PROPERTY_CHANGE, propName, 0, 0, 0, INT);
}
return TRUE;
}
gboolean RDKAt::StateEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::StateEventListener()");
AtkObject *accObj;
const gchar *propName;
guint d1;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
propName = g_value_get_string(¶ms[1]);
d1 = (g_value_get_boolean(¶ms[2])) ? 1 : 0;
HandleEvent(accObj, EVENT_OBJECT, STATE_CHANGED, propName, d1, 0, 0, INT);
return TRUE;
}
gboolean RDKAt::WindowEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::WindowEventListener()");
AtkObject *accObj;
GSignalQuery signalQuery;
const gchar *major, *str;
g_signal_query(signal->signal_id, &signalQuery);
major = signalQuery.signal_name;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
str = atk_object_get_name(accObj);
HandleEvent(accObj, EVENT_WINDOW, major, "", 0, 0, str, STRING);
return TRUE;
}
gboolean RDKAt::DocumentEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::DocumentEventListener()");
AtkObject *accObj;
GSignalQuery signalQuery;
const gchar *major, *str;
g_signal_query(signal->signal_id, &signalQuery);
major = signalQuery.signal_name;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
str = atk_object_get_name(accObj);
HandleEvent(accObj, EVENT_DOCUMENT, major, "", 0, 0, str, STRING);
return TRUE;
}
gboolean RDKAt::BoundsEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::BoundsEventListener()");
AtkObject *accObj;
AtkRectangle *atk_rect;
GSignalQuery signalQuery;
const gchar *major;
g_signal_query(signal->signal_id, &signalQuery);
major = signalQuery.signal_name;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
if(G_VALUE_HOLDS_BOXED(params + 1)) {
atk_rect = (AtkRectangle*)g_value_get_boxed(params + 1);
HandleEvent(accObj, EVENT_OBJECT, major, "", 0, 0, atk_rect, POINTER);
}
return TRUE;
}
gboolean RDKAt::ActiveDescendantEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::ActiveDescendantEventListener()");
AtkObject *accObj;
AtkObject *childObj;
GSignalQuery signalQuery;
const gchar *major;
gint d1;
g_signal_query(signal->signal_id, &signalQuery);
major = signalQuery.signal_name;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
childObj = ATK_OBJECT(g_value_get_pointer(¶ms[1]));
g_return_val_if_fail(ATK_IS_OBJECT(childObj), TRUE);
d1 = atk_object_get_index_in_parent(childObj);
HandleEvent(accObj, EVENT_OBJECT, major, "", d1, 0, childObj, POINTER);
return TRUE;
}
gboolean RDKAt::LinkSelectedEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::LinkSelectedEventListener()");
AtkObject *accObj;
GSignalQuery signalQuery;
const gchar *major, *minor;
gint d1 = 0;
g_signal_query(signal->signal_id, &signalQuery);
major = signalQuery.signal_name;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
minor = g_quark_to_string(signal->detail);
if(G_VALUE_TYPE(¶ms[1]) == G_TYPE_INT)
d1 = g_value_get_int(¶ms[1]);
HandleEvent(accObj, EVENT_OBJECT, major, minor, d1, 0, 0, INT);
return TRUE;
}
gboolean RDKAt::TextChangedEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::TextChangedEventListener()");
AtkObject *accObj;
GSignalQuery signalQuery;
const gchar *major, *minor;
gchar *selected;
gint d1 = 0, d2 = 0;
g_signal_query(signal->signal_id, &signalQuery);
major = signalQuery.signal_name;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
minor = g_quark_to_string(signal->detail);
if(G_VALUE_TYPE(¶ms[1]) == G_TYPE_INT)
d1 = g_value_get_int(¶ms[1]);
if(G_VALUE_TYPE(¶ms[2]) == G_TYPE_INT)
d2 = g_value_get_int(¶ms[2]);
selected = atk_text_get_text(ATK_TEXT(accObj), d1, d1 + d2);
HandleEvent(accObj, EVENT_OBJECT, major, minor, d1, d2, selected, STRING);
g_free(selected);
return TRUE;
}
gboolean RDKAt::TextInsertEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::TextInsertEventListener()");
AtkObject *accObj;
guint text_changed_signal_id;
GSignalQuery signalQuery;
const gchar *major = NULL;
const gchar *minor_raw = NULL, *text = NULL;
gchar *minor;
gint d1 = 0, d2 = 0;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
text_changed_signal_id = g_signal_lookup("text-changed", G_OBJECT_TYPE(accObj));
g_signal_query(text_changed_signal_id, &signalQuery);
major = signalQuery.signal_name;
minor_raw = g_quark_to_string(signal->detail);
if(minor_raw)
minor = g_strconcat("insert:", minor_raw, NULL);
else
minor = g_strdup("insert");
if(G_VALUE_TYPE(¶ms[1]) == G_TYPE_INT)
d1 = g_value_get_int(¶ms[1]);
if(G_VALUE_TYPE(¶ms[2]) == G_TYPE_INT)
d2 = g_value_get_int(¶ms[2]);
if(G_VALUE_TYPE(¶ms[3]) == G_TYPE_STRING)
text = g_value_get_string(¶ms[3]);
HandleEvent(accObj, EVENT_OBJECT, major, minor, d1, d2, text, STRING);
g_free(minor);
return TRUE;
}
gboolean RDKAt::TextRemoveEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::TextRemoveEventListener()");
AtkObject *accObj;
guint text_changed_signal_id;
GSignalQuery signalQuery;
const gchar *major;
const gchar *minor_raw = NULL, *text = NULL;
gchar *minor;
gint d1 = 0, d2 = 0;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
text_changed_signal_id = g_signal_lookup("text-changed", G_OBJECT_TYPE(accObj));
g_signal_query(text_changed_signal_id, &signalQuery);
major = signalQuery.signal_name;
minor_raw = g_quark_to_string(signal->detail);
if(minor_raw)
minor = g_strconcat("delete:", minor_raw, NULL);
else
minor = g_strdup("delete");
if(G_VALUE_TYPE(¶ms[1]) == G_TYPE_INT)
d1 = g_value_get_int(¶ms[1]);
if(G_VALUE_TYPE(¶ms[2]) == G_TYPE_INT)
d2 = g_value_get_int(¶ms[2]);
if(G_VALUE_TYPE(¶ms[3]) == G_TYPE_STRING)
text = g_value_get_string(¶ms[3]);
HandleEvent(accObj, EVENT_OBJECT, major, minor, d1, d2, text, STRING);
g_free(minor);
return TRUE;
}
gboolean RDKAt::TextSelectionChangedEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::TextSelectionChangedEventListener()");
AtkObject *accObj;
GSignalQuery signalQuery;
const gchar *major, *minor;
gint d1 = 0, d2 = 0;
g_signal_query(signal->signal_id, &signalQuery);
major = signalQuery.signal_name;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
minor = g_quark_to_string(signal->detail);
if(G_VALUE_TYPE(¶ms[1]) == G_TYPE_INT)
d1 = g_value_get_int(¶ms[1]);
if(G_VALUE_TYPE(¶ms[2]) == G_TYPE_INT)
d2 = g_value_get_int(¶ms[2]);
HandleEvent(accObj, EVENT_OBJECT, major, minor, d1, d2, "", STRING);
return TRUE;
}
gboolean RDKAt::ChildrenChangedEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::ChildrenChangedEventListener()");
GSignalQuery signalQuery;
const gchar *major, *minor;
gint d1 = 0, d2 = 0;
AtkObject *accObj, *tObj=NULL;
gpointer pChild;
g_signal_query(signal->signal_id, &signalQuery);
major = signalQuery.signal_name;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
minor = g_quark_to_string(signal->detail);
d1 = g_value_get_uint(params + 1);
pChild = g_value_get_pointer(params + 2);
if(ATK_IS_OBJECT(pChild)) {
tObj = ATK_OBJECT(pChild);
HandleEvent(accObj, EVENT_OBJECT, major, minor, d1, d2, tObj, POINTER);
} else if((minor != NULL) && (strcmp(minor, "add") == 0)) {
tObj = atk_object_ref_accessible_child(accObj, d1);
HandleEvent(accObj, EVENT_OBJECT, major, minor, d1, d2, tObj, POINTER);
g_object_unref(tObj);
} else {
HandleEvent(accObj, EVENT_OBJECT, major, minor, d1, d2, tObj, POINTER);
}
return TRUE;
}
gboolean RDKAt::GenericEventListener(GSignalInvocationHint *signal,
guint param_count, const GValue *params, gpointer data)
{
RDKLOG_TRACE("RDKAt::GenericEventListener()");
const gchar *major;
AtkObject *accObj;
GSignalQuery signalQuery;
int d1 = 0, d2 = 0;
g_signal_query(signal->signal_id, &signalQuery);
major = signalQuery.signal_name;
accObj = ATK_OBJECT(g_value_get_object(¶ms[0]));
if(param_count > 1 && G_VALUE_TYPE(¶ms[1]) == G_TYPE_INT)
d1 = g_value_get_int(¶ms[1]);
if(param_count > 2 && G_VALUE_TYPE(¶ms[2]) == G_TYPE_INT)
d2 = g_value_get_int(¶ms[2]);
HandleEvent(accObj, EVENT_OBJECT, major, "", d1, d2, 0, INT);
return TRUE;
}
guint RDKAt::addSignalListener(GSignalEmissionHook listener, const char *signal_name)
{
RDKLOG_TRACE("RDKAt::addSignalListener()");
guint id = atk_add_global_event_listener(listener, signal_name);
if(id > 0)
g_array_append_val(m_listenerIds, id);
return id;
}
void RDKAt::initialize()
{
RDKLOG_TRACE("RDKAt::initialize()");
if(m_initialized)
return;
m_initialized = true;
GObject *gObject = (GObject*)g_object_new(ATK_TYPE_OBJECT, NULL);
AtkObject *atkObject = atk_no_op_object_new(gObject);
guint id = 0;
g_object_unref(G_OBJECT(atkObject));
g_object_unref(gObject);
if(m_listenerIds) {
g_warning("rdkat-register_event_listeners called multiple times");
return;
}
m_listenerIds = g_array_sized_new(FALSE, TRUE, sizeof(guint), 16);
m_focusTrackerId = atk_add_focus_tracker(FocusTracker);
addSignalListener(PropertyEventListener, "Atk:AtkObject:property-change");
id = addSignalListener(WindowEventListener, "window:create");
if(id != 0) {
addSignalListener(WindowEventListener, "window:destroy");
addSignalListener(WindowEventListener, "window:minimize");
addSignalListener(WindowEventListener, "window:maximize");
addSignalListener(WindowEventListener, "window:restore");
addSignalListener(WindowEventListener, "window:activate");
addSignalListener(WindowEventListener, "window:deactivate");
} else {
addSignalListener(WindowEventListener, "Atk:AtkWindow:create");
addSignalListener(WindowEventListener, "Atk:AtkWindow:destroy");
addSignalListener(WindowEventListener, "Atk:AtkWindow:minimize");
addSignalListener(WindowEventListener, "Atk:AtkWindow:maximize");
addSignalListener(WindowEventListener, "Atk:AtkWindow:restore");
addSignalListener(WindowEventListener, "Atk:AtkWindow:activate");
addSignalListener(WindowEventListener, "Atk:AtkWindow:deactivate");
}
addSignalListener(DocumentEventListener, "Atk:AtkDocument:load-complete");
addSignalListener(DocumentEventListener, "Atk:AtkDocument:reload");
addSignalListener(DocumentEventListener, "Atk:AtkDocument:load-stopped");
addSignalListener(StateEventListener, "Atk:AtkObject:state-change");
addSignalListener(GenericEventListener, "Atk:AtkObject:visible-data-changed");
addSignalListener(ChildrenChangedEventListener, "Atk:AtkObject:children-changed");
addSignalListener(ActiveDescendantEventListener, "Atk:AtkObject:active-descendant-changed");
addSignalListener(GenericEventListener, "Atk:AtkTable:row-inserted");
addSignalListener(GenericEventListener, "Atk:AtkTable:row-reordered");
addSignalListener(GenericEventListener, "Atk:AtkTable:row-deleted");
addSignalListener(GenericEventListener, "Atk:AtkTable:column-inserted");
addSignalListener(GenericEventListener, "Atk:AtkTable:column-reordered");
addSignalListener(GenericEventListener, "Atk:AtkTable:column-deleted");
addSignalListener(GenericEventListener, "Atk:AtkTable:model-changed");
addSignalListener(TextInsertEventListener, "Atk:AtkText:text-insert");
addSignalListener(TextRemoveEventListener, "Atk:AtkText:text-remove");
addSignalListener(TextChangedEventListener, "Atk:AtkText:text-changed");
addSignalListener(GenericEventListener, "Atk:AtkText:text-caret-moved");
addSignalListener(GenericEventListener, "Atk:AtkText:text-attributes-changed");
addSignalListener(TextSelectionChangedEventListener, "Atk:AtkText:text-selection-changed");
addSignalListener(BoundsEventListener, "Atk:AtkComponent:bounds-changed");
addSignalListener(GenericEventListener, "Atk:AtkSelection:selection-changed");
addSignalListener(LinkSelectedEventListener, "Atk:AtkHypertext:link-selected");
m_keyEventListenerId = atk_add_key_event_listener(KeyListener, NULL);
}
void RDKAt::enableProcessing(bool enable)
{
RDKLOG_INFO("processingEnabled=%d, enable=%d", processingEnabled(), enable);
m_process = enable;
m_shouldCreateSession = enable;
createOrDestroySession();
if(m_sessionId)
m_ttsClient->abort(m_sessionId);
}
void RDKAt::setVolumeControlCallback(MediaVolumeControlCallback cb, void *data)
{
RDKAt::Instance().m_mediaVolumeControlCB = cb;
RDKAt::Instance().m_mediaVolumeControlCBData = data;
}
void RDKAt::uninitialize(void)
{
RDKLOG_TRACE("RDKAt::uninitialize()");
guint i;
GArray *ids = m_listenerIds;
m_listenerIds = NULL;
if(m_focusTrackerId) {
atk_remove_focus_tracker(m_focusTrackerId);
m_focusTrackerId = 0;
}
if(ids) {
for(i = 0; i < ids->len; i++) {
atk_remove_global_event_listener(g_array_index(ids, guint, i));
}
g_array_free(ids, TRUE);
}
if(m_keyEventListenerId) {
atk_remove_key_event_listener(m_keyEventListenerId);
m_keyEventListenerId = 0;
}
}
void Initialize()
{
logger_init();
RDKLOG_INFO("RDK_AT::Initialize()");
RDKAt::Instance().initialize();
}
void EnableProcessing(bool enable)
{
RDKLOG_INFO("RDK_AT::EnableProcessing()");
RDKAt::Instance().enableProcessing(enable);
}
void SetVolumeControlCallback(MediaVolumeControlCallback cb, void *data)
{
RDKLOG_INFO("RDK_AT::SetVolumeControlCallback()");
RDKAt::Instance().setVolumeControlCallback(cb, data);
}
void Uninitialize()
{
RDKLOG_TRACE("RDK_AT::Uninitialize()");
RDKAt::Instance().uninitialize();
}
} // namespace RDK_AT
| 34.197225 | 114 | 0.672077 | [
"object",
"model"
] |
f6278c3870dafd99ef7de74323fc2585659b5e16 | 3,328 | cpp | C++ | src/plugins/lmp/stdartistactionsmanager.cpp | devel29a/leechcraft | faf5e856010fb785e4bbf3ce7b5c6a5c49f3239a | [
"BSL-1.0"
] | null | null | null | src/plugins/lmp/stdartistactionsmanager.cpp | devel29a/leechcraft | faf5e856010fb785e4bbf3ce7b5c6a5c49f3239a | [
"BSL-1.0"
] | null | null | null | src/plugins/lmp/stdartistactionsmanager.cpp | devel29a/leechcraft | faf5e856010fb785e4bbf3ce7b5c6a5c49f3239a | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "stdartistactionsmanager.h"
#include <QQuickWidget>
#include <QQuickItem>
#include <util/xpc/util.h>
#include <interfaces/core/icoreproxy.h>
#include <interfaces/core/ientitymanager.h>
#include "core.h"
#include "previewhandler.h"
namespace LeechCraft
{
namespace LMP
{
StdArtistActionsManager::StdArtistActionsManager (const ICoreProxy_ptr& proxy,
QQuickWidget *view, QObject* parent)
: QObject { parent }
, Proxy_ { proxy }
{
connect (view->rootObject (),
SIGNAL (bookmarkArtistRequested (QString, QString, QString)),
this,
SLOT (handleBookmark (QString, QString, QString)));
connect (view->rootObject (),
SIGNAL (previewRequested (QString)),
Core::Instance ().GetPreviewHandler (),
SLOT (previewArtist (QString)));
connect (view->rootObject (),
SIGNAL (linkActivated (QString)),
this,
SLOT (handleLink (QString)));
connect (view->rootObject (),
SIGNAL (browseInfo (QString)),
&Core::Instance (),
SIGNAL (artistBrowseRequested (QString)));
}
void StdArtistActionsManager::handleBookmark (const QString& name, const QString& page, const QString& tags)
{
auto e = Util::MakeEntity (tr ("Check out \"%1\"").arg (name),
{},
FromUserInitiated | OnlyHandle,
"x-leechcraft/todo-item");
e.Additional_ ["TodoBody"] = tags + "<br />" + QString ("<a href='%1'>%1</a>").arg (page);
e.Additional_ ["Tags"] = QStringList ("music");
Proxy_->GetEntityManager ()->HandleEntity (e);
}
void StdArtistActionsManager::handleLink (const QString& link)
{
Proxy_->GetEntityManager ()->HandleEntity (Util::MakeEntity (QUrl (link),
{},
FromUserInitiated | OnlyHandle));
}
}
}
| 39.152941 | 109 | 0.69351 | [
"object"
] |
f62dad363276905c9b3bce5d6f10f2f45c91529b | 17,737 | cpp | C++ | Blindmode/CPP/Targets/MapLib/Shared/src/MapProjection.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 6 | 2015-12-01T01:12:33.000Z | 2021-07-24T09:02:34.000Z | Blindmode/CPP/Targets/MapLib/Shared/src/MapProjection.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | null | null | null | Blindmode/CPP/Targets/MapLib/Shared/src/MapProjection.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 2 | 2017-02-02T19:31:29.000Z | 2018-12-17T21:00:45.000Z | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd 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 "MapProjection.h"
#include "PixelBox.h"
#define TOP_LAT 912909609
#define BOTTOM_LAT -912909609
using namespace std;
MapProjection::
MapProjection() : TransformMatrix(),
m_screenSize(100,100),
m_dpiCorrectionFactor( 1 )
{
m_angle = 0.0;
MC2Coordinate lower( 664609150, 157263143 );
MC2Coordinate upper( 664689150, 157405144 );
MC2BoundingBox bbox(lower, upper);
setBoundingBox(bbox);
}
MapProjection::
MapProjection(const MC2Coordinate& centerCoord,
int screenX, int screenY, double scale,
double angle) : TransformMatrix(), m_centerCoord(centerCoord),
m_screenSize(screenX, screenY),
m_scale(scale),
m_angle(angle),
m_dpiCorrectionFactor( 1 )
{
}
void
MapProjection::updateBBox()
{
// static const double mc2scaletometer = 6378137.0*2.0*
// 3.14159265358979323846 / 4294967296.0;
// static const float meterstomc2scale = 1.0 / mc2scaletometer;
pair<float,float> widthAndHeight = getWidthAndHeight();
const float width = widthAndHeight.first;
const float height = widthAndHeight.second;
{
const int32 centerLat = getCenter().lat;
const float halfHeight = height * 0.5;
const int32 intHalfHeight = int32( halfHeight );
if ( halfHeight + centerLat > ( MAX_INT32 / 2 ) ) {
m_bbox.setMaxLat( MAX_INT32 / 2 );
} else {
m_bbox.setMaxLat( centerLat + intHalfHeight );
}
if ( centerLat - halfHeight < ( MIN_INT32 / 2 ) ) {
m_bbox.setMinLat( MIN_INT32 / 2 );
} else {
m_bbox.setMinLat( centerLat - intHalfHeight );
}
m_bbox.updateCosLat();
}
{
if ( width >= MAX_UINT32 - 1) {
m_bbox.setMinLon( MIN_INT32 );
m_bbox.setMaxLon( MAX_INT32 );
} else {
int32 intWidth = int32(width * 0.5 );
int32 centerLon = getCenter().lon;
m_bbox.setMinLon( centerLon - intWidth );
m_bbox.setMaxLon( centerLon + intWidth );
}
}
// MC2Coordinate coord1;
// inverseTranformCosLatSupplied( coord1,
// m_screenSize.getX(),
// 0,
// getCosLat(getCenter().lat));
// MC2Coordinate coord2;
// inverseTranformCosLatSupplied( coord2,
// 0,
// m_screenSize.getY(),
// getCosLat(getCenter().lat));
// MC2Coordinate coord3;
// inverseTranformCosLatSupplied( coord3,
// m_screenSize.getX(),
// m_screenSize.getY(),
// getCosLat(getCenter().lat));
// MC2Coordinate coord4;
// inverseTranformCosLatSupplied( coord4,
// 0,
// 0,
// getCosLat(getCenter().lat) );
#if 0
#ifdef __unix__
mc2dbg8 << "[TMH]: m_centerCoord = " << m_centerCoord
<< " and center of m_bbox = "
<< m_bbox.getCenter() << endl;
MC2Point corner1(0,0);
MC2Point corner2(corner1);
MC2Point corner3(corner2);
MC2Point corner4(corner3);
transformPointCosLatSupplied(corner1, coord1, getCosLat(getCenter().lat));
transformPointCosLatSupplied(corner2, coord2, getCosLat(getCenter().lat));
transformPointCosLatSupplied(corner3, coord3, getCosLat(getCenter().lat));
transformPointCosLatSupplied(corner4, coord4, getCosLat(getCenter().lat));
mc2dbg << "[TMH]: Corners are "
<< corner1.getX() << "," << corner1.getY() << " + "
<< corner2.getX() << "," << corner2.getY() << " + "
<< corner3.getX() << "," << corner3.getY() << " + "
<< corner4.getX() << "," << corner4.getY() << " + "
<< endl;
#endif
#endif
}
void
MapProjection::updateTransformMatrix()
{
// Constant forever
static const float mc2scaletometer = 6378137.0*2.0*
3.14159265358979323846 / 4294967296.0;
static const float meterstomc2scale = 1.0 / mc2scaletometer;
float radAngle = getAngle() / 180 * M_PI;
float maxScale = getCosLat( m_centerCoord.lat) * float(MAX_UINT32-1000) / (
( fabs( m_screenSize.getX() *
meterstomc2scale * cos(radAngle) ) +
fabs( m_screenSize.getY() *
meterstomc2scale * sin(radAngle) ) ) );
m_scale = MIN( (float)m_scale, maxScale );
const double invScale = 1.0/m_scale;
const double mc2scale = mc2scaletometer * invScale;
updateBBox();
TransformMatrix::updateMatrix( m_angle, mc2scale, m_centerCoord,
m_screenSize.getX(),
m_screenSize.getY() );
}
float64
MapProjection::getPixelScaleFromBBoxAndSize( int screenXSize,
int screenYSize,
MC2BoundingBox& bbox )
{
static const double mc2scaletometer = 6378137.0*2.0*
3.14159265358979323846 / 4294967296.0;
// Strech out the bbox to fit the screen size.
// This is copied from GfxUtility. I don't want that dependency
// so I have copied it here. I might want to change it though.
int32 minLat = bbox.getMinLat();
int32 minLon = bbox.getMinLon();
int32 maxLat = bbox.getMaxLat();
int32 maxLon = bbox.getMaxLon();
int width = screenXSize;
int height = screenYSize;
// width and height should have same proportions as
// bbox.width and bbox.height
float64 bboxHeight = bbox.getHeight();
float64 bboxWidth = bbox.getWidth();
if ( bboxHeight == 0.0 ) {
bboxHeight = 1.0;
}
if ( bboxWidth == 0.0 ) {
bboxWidth = 1.0;
}
float64 factor = bboxHeight / bboxWidth * width / height;
if ( factor < 1 ) {
// Compensate for that the display is higher than the bbox
// height = uint16( height * factor );
int32 extraHeight =
int32( rint( ( (bboxHeight / factor ) -
bboxHeight ) / 2 ) );
minLat -= extraHeight;
maxLat += extraHeight;
} else {
// Compensate for that the display is wider than the bbox
// width = uint16( width / factor );
uint32 lonDiff = bbox.getLonDiff();
if ( lonDiff == 0 ) {
lonDiff = 1;
}
int32 extraWidth =
int32( rint( ( (lonDiff * factor ) -
lonDiff ) / 2 ) );
minLon -= extraWidth;
maxLon += extraWidth;
bbox.setMinLon( minLon );
bbox.setMaxLon( maxLon );
}
bbox.setMinLat( MAX( minLat, (int32) BOTTOM_LAT ) );
bbox.setMaxLat( MIN( maxLat, (int32) TOP_LAT ) );
bbox.setMinLon( minLon );
bbox.setMaxLon( maxLon );
float64 scale =
double(bbox.getHeight() * mc2scaletometer) /
screenYSize; // unit meters map / pixel
// Ugglefix.
if ( scale < 0 || scale > 24000.0 ) {
scale = 24000.0;
}
return scale;
}
MC2BoundingBox
MapProjection::setBoundingBox(const MC2BoundingBox& inbbox)
{
MC2BoundingBox bbox(inbbox);
// Set the scale
m_scale = getPixelScaleFromBBoxAndSize( m_screenSize.getX(),
m_screenSize.getY(),
bbox );
// Save the corner
setCenter( bbox.getCenter() );
return bbox;
}
pair<float,float>
MapProjection::getWidthAndHeight() const
{
static const double mc2scaletometer = 6378137.0*2.0*
3.14159265358979323846 / 4294967296.0;
static const float meterstomc2scale = 1.0 / mc2scaletometer;
const float radAngle = ( getAngle() ) / 180.0 * M_PI;
const float scale = getPixelScale() * meterstomc2scale;
const float b = m_screenSize.getX() * scale;
const float h = m_screenSize.getY() * scale;
const float width =
( fabs( b * cos(radAngle) ) +
fabs( h * sin(radAngle) ) ) / m_cosLat;
const float height =
fabs( b * sin(radAngle) ) +
fabs( h * cos(radAngle) );
return pair<float,float>(width,height);
}
void
MapProjection::getDrawingBBoxes( vector<MC2BoundingBox>& outBoxes ) const
{
pair<float,float> widthAndHeight = getWidthAndHeight();
const float height = widthAndHeight.second;
// Height
MC2BoundingBox bbox;
{
const int32 centerLat = getCenter().lat;
const float halfHeight = height * 0.5 ;
const int32 intHalfHeight = int32( halfHeight );
if ( halfHeight + centerLat > ( MAX_INT32 / 2 ) ) {
bbox.setMaxLat( MAX_INT32 / 2 );
} else {
bbox.setMaxLat( centerLat + intHalfHeight );
}
if ( centerLat - halfHeight < ( MIN_INT32 / 2 ) ) {
bbox.setMinLat( MIN_INT32 / 2 );
} else {
bbox.setMinLat( centerLat - intHalfHeight );
}
bbox.updateCosLat();
}
// Widths
{
float width = MIN( widthAndHeight.first, float(MAX_UINT32) );
int32 centerLon = getCenter().lon;
int32 curMinLon = int32(int64(centerLon) - int64(width / 2) );
// Add bounding boxes until there is no width left
while ( width > 0.0 ) {
outBoxes.push_back( bbox );
MC2BoundingBox& curBox = outBoxes.back();
int32 curWidth = int32( MIN( width, float( MAX_INT32 / 4 ) ) );
if ( curWidth == 0 ) {
outBoxes.pop_back();
break;
}
curBox.setMinLon( curMinLon );
curBox.setMaxLon( curMinLon + curWidth );
if ( curBox.getMinLon() > curBox.getMaxLon() ) {
curBox.setMaxLon( MAX_INT32 );
curMinLon = MIN_INT32;
width -= ( curBox.getMaxLon() - curBox.getMinLon() );
} else {
curMinLon += curWidth;
width -= curWidth;
}
}
}
}
double
MapProjection::setPixelScale(double scale)
{
m_scale = scale;
const double minScale = 0.1;
const double maxScale = 24000.0;
if ( m_scale < minScale ) {
m_scale = minScale;
} else if ( m_scale > maxScale ) {
m_scale = maxScale;
}
updateTransformMatrix();
return m_scale;
}
double
MapProjection::getPixelScale() const
{
return m_scale;
}
void
MapProjection::setDPICorrectionFactor( uint32 factor )
{
m_dpiCorrectionFactor = factor;
}
uint32
MapProjection::getDPICorrectionFactor() const
{
return m_dpiCorrectionFactor;
}
double
MapProjection::setDPICorrectedScale( double scale )
{
setPixelScale( scale / double( getDPICorrectionFactor() ) );
return getDPICorrectedScale();
}
double
MapProjection::getDPICorrectedScale() const
{
double scale = getPixelScale() * double( getDPICorrectionFactor() );
if ( scale > 24000.0 ) {
scale = 24000.0;
}
return scale;
}
double
MapProjection::zoom(double factor)
{
setPixelScale( factor * getPixelScale() );
return m_scale;
}
double
MapProjection::zoom(double factor,
const MC2Coordinate& zoomCoord,
const MC2Point& zoomPoint )
{
double newScale = zoom( factor );
setPoint( zoomCoord, zoomPoint );
return newScale;
}
void
MapProjection::setPixelBox( const MC2Point& oneCorner,
const MC2Point& otherCorner )
{
PixelBox pixBox( oneCorner, otherCorner );
MC2BoundingBox bbox;
for( int i = 0; i < 4; ++i ) {
MC2Coordinate tmpCoord;
inverseTranformUsingCosLat( tmpCoord, pixBox.getCorner(i) );
bbox.update( tmpCoord );
}
double oldangle = m_angle;
setAngle(0);
setBoundingBox( bbox );
setAngle( oldangle );
}
void
MapProjection::move(int deltaX,
int deltaY )
{
#if 0
// Only move one pixel.
if ( deltaX ) {
deltaX = deltaX/abs<int>(deltaX);
}
if ( deltaY ) {
deltaY = deltaY/abs<int>(deltaY);
}
#endif
// Translate the screen coordinates into lat/lon.
MC2Coordinate center;
inverseTranformCosLatSupplied(
center,
deltaX + (m_screenSize.getX() >> 1),
deltaY + (m_screenSize.getY() >> 1),
getCosLat( m_centerCoord.lat ) );
setCenter( center );
}
void
MapProjection::setCenter(const MC2Coordinate& newCenter)
{
m_centerCoord = newCenter;
if ( m_centerCoord.lat > TOP_LAT ) {
m_centerCoord.lat = TOP_LAT;
} else if ( m_centerCoord.lat < BOTTOM_LAT ) {
m_centerCoord.lat = BOTTOM_LAT;
}
updateTransformMatrix();
}
void
MapProjection::setPoint(const MC2Coordinate& newCoord,
const MC2Point& screenPoint )
{
// Translate the center to a screen coord.
MC2Point centerPoint(0,0);
transformPointInternalCosLat( centerPoint,
m_centerCoord );
// Check the first part of
// TransformMatrix::inverseTranformUsingCosLat
// m_Ty is calculated from this using the screen point and coord.
m_Ty = - 1.0/m_Sy * m_C * screenPoint.getX()
+ 1.0/m_Sy * m_D * screenPoint.getY()
+ 1.0/m_Sy * m_C * m_tx
- 1.0/m_Sy * m_D * m_ty
- newCoord.lat;
// Now the calculated m_Ty is used to get the latitude of the center.
// Also check the first part of inverseTranformUsingCosLat for this.
m_centerCoord.lat =
int32(int64(( - 1.0/m_Sy * m_C * centerPoint.getX()
+ 1.0/m_Sy * m_D * centerPoint.getY()
+ 1.0/m_Sy * m_C * m_tx
- 1.0/m_Sy * m_D * m_ty
- m_Ty ) ) );
// Now that the center latitude is known, the coslat can be
// calcualted.
m_cosLat = getCosLat( m_centerCoord.lat );
double S_x = m_Sx * m_cosLat;
// This next step is from the second part of that method.
// m_Tx is solved from that equation using the screenpoint and coord.
m_Tx = 1.0 / S_x * m_A * screenPoint.getX()
- 1.0 / S_x * m_B * screenPoint.getY()
- 1.0 / S_x * m_A * m_tx
+ 1.0 / S_x * m_B * m_ty
- newCoord.lon;
// Now explicitly calculate the center longitude.
// This is done since we want to be able to use setCenter
// to set all the different members etc.
m_centerCoord.lon = int32( int64( + 1.0 / S_x * m_A * centerPoint.getX()
- 1.0 / S_x * m_B * centerPoint.getY()
- 1.0 / S_x * m_A * m_tx
+ 1.0 / S_x * m_B * m_ty
- m_Tx) );
// Now set the center to that center coordinate. Will update
// all the members.
setCenter( m_centerCoord );
}
void
MapProjection::setAngle(double angleDeg)
{
m_angle = angleDeg;
updateTransformMatrix();
}
void
MapProjection::setAngle(double angleDeg,
const MC2Point& rotationPoint )
{
// Translate the center to a screen coord.
MC2Point centerPoint(0,0);
transformPointInternalCosLat( centerPoint,
m_centerCoord );
int deltaX = centerPoint.getX() - rotationPoint.getX();
int deltaY = centerPoint.getY() - rotationPoint.getY();
move(-deltaX, -deltaY);
setAngle( angleDeg );
move(deltaX, deltaY);
}
double
MapProjection::getAngle() const
{
return m_angle;
}
void
MapProjection::setScreenSize(const MC2Point& size)
{
if ( size != m_screenSize && size != MC2Point(0,0) ) {
m_screenSize = size;
updateTransformMatrix();
}
}
MC2Coordinate
MapProjection::calcLowerLeft() const
{
// Constant forever
static const double mc2scaletometer = 6378137.0*2.0*
3.14159265358979323846 / 4294967296.0;
const double invScale = 1.0/m_scale;
const double mc2scale = mc2scaletometer * invScale;
const int screenWidth = m_screenSize.getX();
const int screenHeight = m_screenSize.getY();
return MC2Coordinate( int32(double(m_centerCoord.lat) -
(1/mc2scale * screenHeight * 0.5)),
int32(double(m_centerCoord.lon) -
(1/mc2scale/getCosLat(m_centerCoord.lat) *
screenWidth * 0.5 ) ) );
}
| 31.673214 | 757 | 0.60292 | [
"vector"
] |
f634181046b9b6c80dfbbc88464912dc5922d99e | 2,328 | cpp | C++ | 5. Very Hard/SupperEggDrop.cpp | vachan-maker/Edabit-Solutions | b8598f15b981b58d42bf5220042b7e0e576bb668 | [
"MIT"
] | 36 | 2020-09-25T15:03:23.000Z | 2020-10-08T14:25:53.000Z | 5. Very Hard/SupperEggDrop.cpp | vachan-maker/Edabit-Solutions | b8598f15b981b58d42bf5220042b7e0e576bb668 | [
"MIT"
] | 212 | 2020-09-25T13:15:59.000Z | 2020-10-12T20:35:05.000Z | 5. Very Hard/SupperEggDrop.cpp | vachan-maker/Edabit-Solutions | b8598f15b981b58d42bf5220042b7e0e576bb668 | [
"MIT"
] | 240 | 2020-09-25T13:20:02.000Z | 2020-10-12T04:20:47.000Z | #include<bits/stdc++.h>
/* Problem task : You are given K eggs, and you have access to a building with N floors from 1 to N. Each egg is identical in function, and if an egg breaks, you cannot drop it again.
You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break.
Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N).
Your goal is to know with certainty what the value of F is.
What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F?
Problem link : https://leetcode.com/problems/super-egg-drop/
*/
using namespace std;
int superEggDrop(int K, int N) {
/*Create a 2D dp matrix where jth cell of ith row represents the minimum number of trials needed to check i floors using j eggs. */
int eggs = K, floors = N;
vector<vector<int>> dp(floors+1,vector<int>(eggs+1,0));
// case 1: when there are 0 floors
for(int egg = 0; egg<=eggs; egg++) dp[0][egg] = 0;
// case 2: when there are 1 floors
for(int egg = 0; egg<=eggs; egg++) dp[1][egg] = 1;
// case 3: when there are 0 eggs
for(int floor=0; floor<=floors; floor++) dp[floor][0] = 0;
// case 4: when there are 1 eggs
for(int floor=0; floor<=floors; floor++) dp[floor][1] = floor;
for(int egg=2; egg<=eggs; egg++) {
for(int floor=2; floor<=floors; floor++) {
int mn = INT_MAX;
// choosing an ith floor between 1 to floor
for(int i=1; i<=floor; i++) {
// dp[i - 1][egg-1] means to find the answer when
// the egg is broken at ith floor
// dp[floor - i][egg] means to find the answer
// when the egg is not broken at ith floor
int ans = 1 + max(dp[i-1][egg-1],dp[floor-i][egg]);
mn = min(ans,mn);
}
dp[floor][egg] = mn;
}
}
return dp[floors][eggs];
}
int main(){
int n,k;
cin>>n>>k;
cout<<supperEggDrop(k,n)<<endl;
return 0;
}
| 41.571429 | 184 | 0.560567 | [
"vector"
] |
f64437e241aa1e23c54b50e56721bb5d9882abeb | 3,537 | hh | C++ | gunns-ts-models/common/sensors/TsLimitSwitch.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 18 | 2020-01-23T12:14:09.000Z | 2022-02-27T22:11:35.000Z | gunns-ts-models/common/sensors/TsLimitSwitch.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 39 | 2020-11-20T12:19:35.000Z | 2022-02-22T18:45:55.000Z | gunns-ts-models/common/sensors/TsLimitSwitch.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 7 | 2020-02-10T19:25:43.000Z | 2022-03-16T01:10:00.000Z | #ifndef TsLimitSwitch_EXISTS
#define TsLimitSwitch_EXISTS
/**
@defgroup TSM_SENSORS_LimitSwitch Limit Switch
@ingroup TSM_SENSORS
@copyright Copyright 2019 United States Government as represented by the Administrator of the
National Aeronautics and Space Administration. All Rights Reserved.
@details
PURPOSE:
- (A LimitSwitch takes inputs of a boolean value, is powered or is failed and produces as boolean
sensed value. If not powered the sensed value is the not powered value, from config data. If
powered and is failed the sensed value is the value of the failed variable.)
REFERENCE:
- ()
ASSUMPTIONS AND LIMITATIONS:
- ()
LIBRARY DEPENDENCY:
- (
(TsLimitSwitch.o)
)
PROGRAMMERS:
- ((Chuck Sorensen) (LZT) (Dec 2011) (TS21) (initial))
@{
*/
#include "software/SimCompatibility/TsSimCompatibility.hh"
/// @brief ConfigData for model
class TsLimitSwitchConfigData {
public:
bool mNotPoweredValue; /**< (--) trick_chkpnt_io(**) value when not powered */
TsLimitSwitchConfigData();
virtual ~TsLimitSwitchConfigData();
protected:
private:
/// @brief Unimplemented
TsLimitSwitchConfigData(const TsLimitSwitchConfigData &rhs);
/// @brief Unimplemented
TsLimitSwitchConfigData& operator =(const TsLimitSwitchConfigData &rhs);
};
/// @brief InputData for model
class TsLimitSwitchInputData {
public:
bool mTrueValue; /**< (--) true value */
bool mSensedValue; /**< (--) sensed value */
bool mFailedValue; /**< (--) value when failed */
TsLimitSwitchInputData(const bool trueValue = false,
const bool sensedValue = false,
const bool failedValue = false);
virtual ~TsLimitSwitchInputData();
protected:
private:
/// @brief Unimplemented
TsLimitSwitchInputData(const TsLimitSwitchInputData &rhs);
/// @brief Unimplemented
TsLimitSwitchInputData& operator =(const TsLimitSwitchInputData &rhs);
};
/// @brief A limit switch
class TsLimitSwitch {
TS_MAKE_SIM_COMPATIBLE(TsLimitSwitch);
public:
TsLimitSwitch(void);
virtual ~TsLimitSwitch( void );
void initialize(const TsLimitSwitchConfigData &configData,
const TsLimitSwitchInputData &inputData);
bool getValue() const ;
bool isInitialized() const ;
void setFailedValue(const bool fail);
void update(const bool realValue,
const bool isPowered,
const bool isFailied);
protected:
bool mInitialized; /**< (--) indicates switch has been initialized */
bool mTrueValue; /**< (--) true value */
bool mSensedValue; /**< (--) sensed value */
bool mFailedValue; /**< (--) value when failed */
bool mNotPoweredValue; /**< (--) trick_chkpnt_io(**) value when not powered */
private:
/// @brief keep private, never used
TsLimitSwitch(const TsLimitSwitch &rhs);
/// @brief keep private, never used
TsLimitSwitch& operator= (const TsLimitSwitch &rhs);
};
/// @}
/// @brief returns the sensed value
inline bool TsLimitSwitch::getValue() const {
return mSensedValue;
}
/// @brief returns the initialization flag
inline bool TsLimitSwitch::isInitialized() const {
return mInitialized;
}
/// @param[in] fail -- fail value
/// @brief set the value to return when failed
inline void TsLimitSwitch::setFailedValue(const bool fail) {
mFailedValue = fail;
}
#endif //TsLimitSwitch_EXISTS
| 28.991803 | 98 | 0.67119 | [
"model"
] |
f645277498dd91f0f9d32a812cc02f5c4f3be6da | 7,284 | hpp | C++ | include/GlobalNamespace/DynamicBone_Particle.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/DynamicBone_Particle.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/DynamicBone_Particle.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: DynamicBone
#include "GlobalNamespace/DynamicBone.hpp"
// Including type: UnityEngine.Vector3
#include "UnityEngine/Vector3.hpp"
// Including type: UnityEngine.Quaternion
#include "UnityEngine/Quaternion.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Transform
class Transform;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x74
#pragma pack(push, 1)
// Autogenerated type: DynamicBone/Particle
// [TokenAttribute] Offset: FFFFFFFF
class DynamicBone::Particle : public ::Il2CppObject {
public:
// public UnityEngine.Transform m_Transform
// Size: 0x8
// Offset: 0x10
UnityEngine::Transform* m_Transform;
// Field size check
static_assert(sizeof(UnityEngine::Transform*) == 0x8);
// public System.Int32 m_ParentIndex
// Size: 0x4
// Offset: 0x18
int m_ParentIndex;
// Field size check
static_assert(sizeof(int) == 0x4);
// public System.Single m_Damping
// Size: 0x4
// Offset: 0x1C
float m_Damping;
// Field size check
static_assert(sizeof(float) == 0x4);
// public System.Single m_Elasticity
// Size: 0x4
// Offset: 0x20
float m_Elasticity;
// Field size check
static_assert(sizeof(float) == 0x4);
// public System.Single m_Stiffness
// Size: 0x4
// Offset: 0x24
float m_Stiffness;
// Field size check
static_assert(sizeof(float) == 0x4);
// public System.Single m_Inert
// Size: 0x4
// Offset: 0x28
float m_Inert;
// Field size check
static_assert(sizeof(float) == 0x4);
// public System.Single m_Radius
// Size: 0x4
// Offset: 0x2C
float m_Radius;
// Field size check
static_assert(sizeof(float) == 0x4);
// public System.Single m_BoneLength
// Size: 0x4
// Offset: 0x30
float m_BoneLength;
// Field size check
static_assert(sizeof(float) == 0x4);
// public UnityEngine.Vector3 m_Position
// Size: 0xC
// Offset: 0x34
UnityEngine::Vector3 m_Position;
// Field size check
static_assert(sizeof(UnityEngine::Vector3) == 0xC);
// public UnityEngine.Vector3 m_PrevPosition
// Size: 0xC
// Offset: 0x40
UnityEngine::Vector3 m_PrevPosition;
// Field size check
static_assert(sizeof(UnityEngine::Vector3) == 0xC);
// public UnityEngine.Vector3 m_EndOffset
// Size: 0xC
// Offset: 0x4C
UnityEngine::Vector3 m_EndOffset;
// Field size check
static_assert(sizeof(UnityEngine::Vector3) == 0xC);
// public UnityEngine.Vector3 m_InitLocalPosition
// Size: 0xC
// Offset: 0x58
UnityEngine::Vector3 m_InitLocalPosition;
// Field size check
static_assert(sizeof(UnityEngine::Vector3) == 0xC);
// public UnityEngine.Quaternion m_InitLocalRotation
// Size: 0x10
// Offset: 0x64
UnityEngine::Quaternion m_InitLocalRotation;
// Field size check
static_assert(sizeof(UnityEngine::Quaternion) == 0x10);
// Creating value type constructor for type: Particle
Particle(UnityEngine::Transform* m_Transform_ = {}, int m_ParentIndex_ = {}, float m_Damping_ = {}, float m_Elasticity_ = {}, float m_Stiffness_ = {}, float m_Inert_ = {}, float m_Radius_ = {}, float m_BoneLength_ = {}, UnityEngine::Vector3 m_Position_ = {}, UnityEngine::Vector3 m_PrevPosition_ = {}, UnityEngine::Vector3 m_EndOffset_ = {}, UnityEngine::Vector3 m_InitLocalPosition_ = {}, UnityEngine::Quaternion m_InitLocalRotation_ = {}) noexcept : m_Transform{m_Transform_}, m_ParentIndex{m_ParentIndex_}, m_Damping{m_Damping_}, m_Elasticity{m_Elasticity_}, m_Stiffness{m_Stiffness_}, m_Inert{m_Inert_}, m_Radius{m_Radius_}, m_BoneLength{m_BoneLength_}, m_Position{m_Position_}, m_PrevPosition{m_PrevPosition_}, m_EndOffset{m_EndOffset_}, m_InitLocalPosition{m_InitLocalPosition_}, m_InitLocalRotation{m_InitLocalRotation_} {}
// Get instance field reference: public UnityEngine.Transform m_Transform
UnityEngine::Transform*& dyn_m_Transform();
// Get instance field reference: public System.Int32 m_ParentIndex
int& dyn_m_ParentIndex();
// Get instance field reference: public System.Single m_Damping
float& dyn_m_Damping();
// Get instance field reference: public System.Single m_Elasticity
float& dyn_m_Elasticity();
// Get instance field reference: public System.Single m_Stiffness
float& dyn_m_Stiffness();
// Get instance field reference: public System.Single m_Inert
float& dyn_m_Inert();
// Get instance field reference: public System.Single m_Radius
float& dyn_m_Radius();
// Get instance field reference: public System.Single m_BoneLength
float& dyn_m_BoneLength();
// Get instance field reference: public UnityEngine.Vector3 m_Position
UnityEngine::Vector3& dyn_m_Position();
// Get instance field reference: public UnityEngine.Vector3 m_PrevPosition
UnityEngine::Vector3& dyn_m_PrevPosition();
// Get instance field reference: public UnityEngine.Vector3 m_EndOffset
UnityEngine::Vector3& dyn_m_EndOffset();
// Get instance field reference: public UnityEngine.Vector3 m_InitLocalPosition
UnityEngine::Vector3& dyn_m_InitLocalPosition();
// Get instance field reference: public UnityEngine.Quaternion m_InitLocalRotation
UnityEngine::Quaternion& dyn_m_InitLocalRotation();
// public System.Void .ctor()
// Offset: 0x23F9410
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static DynamicBone::Particle* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::DynamicBone::Particle::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<DynamicBone::Particle*, creationType>()));
}
}; // DynamicBone/Particle
#pragma pack(pop)
static check_size<sizeof(DynamicBone::Particle), 100 + sizeof(UnityEngine::Quaternion)> __GlobalNamespace_DynamicBone_ParticleSizeCheck;
static_assert(sizeof(DynamicBone::Particle) == 0x74);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::DynamicBone::Particle*, "", "DynamicBone/Particle");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::DynamicBone::Particle::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 45.525 | 835 | 0.705107 | [
"object",
"transform"
] |
f648d6791350494d05e9979ca793ecf0b9e014ea | 69,878 | cpp | C++ | OCREngine/FindString/FindString.cpp | gustavkkk/EngineTester | c5632e4011b669efff5fcaac7b3a3cc8c2988b85 | [
"MIT"
] | null | null | null | OCREngine/FindString/FindString.cpp | gustavkkk/EngineTester | c5632e4011b669efff5fcaac7b3a3cc8c2988b85 | [
"MIT"
] | null | null | null | OCREngine/FindString/FindString.cpp | gustavkkk/EngineTester | c5632e4011b669efff5fcaac7b3a3cc8c2988b85 | [
"MIT"
] | 1 | 2020-09-25T07:40:46.000Z | 2020-09-25T07:40:46.000Z | #include "stdafx.h"
#include "FindString.h"
#include "FilterContours.h"
#include "Array.h"
#include "Binarization.h"
#include "RemoveNoise.h"
#include "InclCorr.h"
#include "ExtractBlack.h"
#include "PosterEdge.h"
#include "opencv2/highgui/highgui.hpp"
//#define OCR_DEBUG
//#define OCR_ONCE
//#define OCR_TEST
#define OCR_GOODFEATURES
#define OCR_STRING_COUNT_ESTIMATE 5//10
void calcProjection(Mat thresh_output,int* sum_h,int* sum_v)
{
if(!thresh_output.data || !sum_h || !sum_v) return;
for( int i = 0; i< thresh_output.rows; i++ )
{
sum_h[i] = 0;
for(int j = 0; j < thresh_output.cols; j++ )
if(*thresh_output.ptr(i,j) == 0)
sum_h[i]++;
}
for( int i = 0; i< thresh_output.cols; i++ )
{
sum_v[i] = 0;
for(int j = 0; j < thresh_output.rows; j++ )
if(*thresh_output.ptr(j,i) == 0)
sum_v[i]++;
}
}
void calcProjection_t(Mat thresh_output,int* sum_h,int* sum_v)
{
if(!thresh_output.data || !sum_h || !sum_v) return;
for( int i = 0; i< thresh_output.rows; i++ )
{
sum_h[i] = 0;
for(int j = 0; j < thresh_output.cols; j++ )
if(*thresh_output.ptr(i,j) == 255)
sum_h[i]++;
}
for( int i = 0; i< thresh_output.cols; i++ )
{
sum_v[i] = 0;
for(int j = 0; j < thresh_output.rows; j++ )
if(*thresh_output.ptr(j,i) == 255)
sum_v[i]++;
}
}
void calcHorizontalProjection(Mat thresh_output,int* sum_h,int value)
{
if(!thresh_output.data || !sum_h || value < 0 || value > 255) return;
for( int i = 0; i< thresh_output.rows; i++ )
{
sum_h[i] = 0;
for(int j = 0; j < thresh_output.cols; j++ )
if(*thresh_output.ptr(i,j) == value)
sum_h[i]++;
}
return;
}
void calcVerticalProjection(Mat thresh_output,int* sum_v,int value)
{
if(!thresh_output.data ||!sum_v || value < 0 || value > 255) return;
for( int i = 0; i< thresh_output.cols; i++ )
{
sum_v[i] = 0;
for(int j = 0; j < thresh_output.rows; j++ )
if(*thresh_output.ptr(j,i) == value)
sum_v[i]++;
}
return;
}
void findString(int* array_x,int rows,int* array_y,int cols,int& top,int& bottom,int& left,int& right)
{
top = getFirstIndex(array_x,rows,1);
bottom = getLastIndex(array_x,rows,1);
left = getFirstIndex(array_y,cols,1);
right = getLastIndex(array_y,cols,1);
return;
}
#define USER_DEFINED_STRING_HEIGHT 150
#define USER_DEFINED_STRING_WIDTH 130
void findTopBottom(int* array_x,int rows,int& top,int& bottom)
{
//calcGroupCount(array_x,rows,biggest_x);
////calcSize(array_x,rows,top,bottom);
//top = biggest_x.firstindex;
//bottom = biggest_x.lastindex;
//if((bottom - top) > USER_DEFINED_STRING_HEIGHT)
calcSize(array_x,rows,top,bottom);
if(top < 0)
top = 0;
if(bottom >= rows)
bottom = rows;
if(top > bottom)
{
top = 0;
bottom = rows - 1;
}
return;
}
void findLeftRight(int* array_y,int cols,int& left,int& right)
{
left = getFirstIndex(array_y,cols,1);
right = getLastIndex(array_y,cols,1);
////////////////////////////////////
if(left > right)
{
left = 0;
right = cols - 1;
}
return;
}
#define OCR_STRING_DENSITY 1
void findStringinBinaryImage(int* array_x,int rows,int* array_y,int cols,int& top,int& bottom,int& left,int& right)
{
top = getFirstIndex(array_x,rows,OCR_STRING_DENSITY);
bottom = getLastIndex(array_x,rows,OCR_STRING_DENSITY);
left = getFirstIndex(array_y,cols,OCR_STRING_DENSITY);
right = getLastIndex(array_y,cols,OCR_STRING_DENSITY);
////////////////////////////////////////
if(top > bottom)
{
top = 0;
bottom = rows - 1;
}
if(left > right)
{
left = 0;
right = cols - 1;
}
}
void DrawIntegralProject(Mat thresh_output,Mat& integral_projection_x,Mat& integral_projection_y,int* sum_h,int* sum_v)
{
if(!thresh_output.data || !sum_h || !sum_v || !integral_projection_x.data || !integral_projection_y.data)
return;
for( int i = 0; i< thresh_output.rows; i++ )
line( integral_projection_x,cv::Point(0,i),cv::Point(sum_h[i],i),Scalar( 255, 0, 0),2,8,0);
for( int i = 0; i< thresh_output.cols; i++ )
line( integral_projection_y,cv::Point(i,0),cv::Point(i,sum_v[i]),Scalar( 255, 0, 0),2,8,0);
return;
}
Mat FindString::Rotation(Mat in,double angle,double scale)
{
Mat out;
//Corr1
int nRadius, nWidth, nHeight,nHalfWidth,nHalfHeight,nWidth_, nHeight_,nHalfWidth_,nHalfHeight_,nHalfWidth_tmp,nHalfHeight_tmp,nMIN;
nWidth = in.cols;
nHeight = in.rows;
nHalfWidth = nWidth >> 1;
nHalfHeight = nHeight >> 1;
nRadius = (int)sqrt(double(nHalfWidth * nHalfWidth + nHalfHeight * nHalfHeight));
double angle_ ;
angle_ = atan2(double(nHalfHeight),double(nHalfWidth));
float fAngle1,fAngle2;
fAngle1 = float(angle * RATIO + angle_);
fAngle2 = float(angle * RATIO - angle_);
nMIN = MIN(nHalfWidth,nHalfHeight);
nHalfWidth_ = (int)abs(nRadius * cos(fAngle1));//
nHalfWidth_tmp = (int)abs(nRadius * cos(fAngle2));
nHalfHeight_ = (int)abs(nRadius * sin(fAngle1));//
nHalfHeight_tmp = (int)abs(nRadius * sin(fAngle2));//
nHalfWidth_ = MAX(nHalfWidth,MAX(nHalfWidth_,nHalfWidth_tmp));
nHalfHeight_ = MAX(nHalfHeight,MAX(nHalfHeight_,nHalfHeight_tmp));
//nHalfWidth_ = nHalfWidth_ / 4 * 4;
//nHalfHeight_ = nHalfHeight_ / 4 * 4;
nWidth_ = nHalfWidth_ << 1;
nHeight_ = nHalfHeight_ << 1;
Mat in_corr(nHeight_,nWidth_,CV_8UC3);
int DeltaX,DeltaY;
DeltaX = abs(nHalfWidth_ - nHalfWidth);
DeltaY = abs(nHalfHeight_ - nHalfHeight);
for(int j = 0; j < nHeight_; j++)
for(int i = 0; i < nWidth_; i++)
for(int k = 0; k < 3; k++)
{
if(j < DeltaY ||
j >= (nHeight_ - DeltaY) ||
i < DeltaX ||
i >= (nWidth_ - DeltaX))
*(in_corr.ptr(j,i) + k) = 255;
else{
*(in_corr.ptr(j,i) + k) = *(in.ptr(j - DeltaY,i - DeltaX) + k);
}
}
//imshow("test",in_corr);
cv::Point center = cv::Point(nHalfWidth_, nHalfHeight_);
Mat rotationMat(2,3,CV_32FC1);
rotationMat = getRotationMatrix2D(center,angle,scale);
warpAffine(in_corr,out,rotationMat,out.size());
//
#if 0
if ((out.cols % 4) || (out.rows % 4))
{
cv::resize(out, out, cv::Size(in_corr.cols/4*4, in_corr.rows/4*4));
}
#endif
//
return out;
}
void showHistogram(char* title,Mat input)
{
int histSize = 256;
float range[] = {0,256};
const float* histRange = {range};
Mat hist;
////////////////////////////////////////////////
int hist_w = 512; int hist_h = 400;
int bin_w = cvRound( (double) hist_w/histSize );
Mat histImage( hist_h, hist_w, CV_8UC3, Scalar( 0,0,0) );
calcHist(&input,1,0,Mat(),hist,1,&histSize,&histRange,true,false);
normalize(hist, hist, 0, 1, NORM_MINMAX, -1, Mat() );
cv::Point start_p,end_p;
int* array_ = new int[histSize];
///////////////////////////////////////////////
for( int i = 1; i < histSize; i++ )
{
start_p.x = bin_w*(i-1);
start_p.y = hist_h - cvRound(hist.at<float>(i-1));
end_p.x = bin_w*(i);
end_p.y = hist_h - cvRound(hist.at<float>(i));
line( histImage,
start_p,
end_p,
Scalar(255, 0, 0),
2,
8,
0 );
/////
array_[i] = cvRound(hist.at<float>(i));
}
delete []array_;
imshow(title,histImage);
}
bool needEqualizing(Mat input)
{
int histSize = 256;
float range[] = {0,256};
const float* histRange = {range};
Mat hist;
////////////////////////////////////////////////
int hist_w = 512; int hist_h = 400;
Mat histImage( hist_h, hist_w, CV_8UC3, Scalar(0,0,0) );
calcHist(&input,1,0,Mat(),hist,1,&histSize,&histRange,true,false);
normalize(hist, hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
int nonZeroCount = 0;
for(int i = 1; i < histSize; i++)
if(cvRound(hist.at<float>(i - 1)) != 0)
nonZeroCount++;
if(double(nonZeroCount) / double(histSize) < 0.5)
return true;
return false;
}
#define OCR_SHOWARRAY_HEIGHT 400
void showArray_h(char* title,int* array_h,int arraySize)
{
Mat ip_h(arraySize,OCR_SHOWARRAY_HEIGHT,CV_8UC3);
if(!array_h)
return;
for( int i = 0; i< arraySize; i++ )
line( ip_h,cv::Point(0,i),cv::Point(array_h[i],i),Scalar( 255, 0, 0),2,8,0);
imshow(title,ip_h);
waitKey(4000);
}
void showArray_v(char* title,int* array_v,int arraySize)
{
Mat ip_v(OCR_SHOWARRAY_HEIGHT,arraySize,CV_8UC3);
if(!array_v)
return;
for( int i = 0; i< arraySize; i++ )
line( ip_v,cv::Point(i,0),cv::Point(i,array_v[i]),Scalar( 255, 0, 0),2,8,0);
imshow(title,ip_v);
waitKey(4000);
}
#define OCR_BINARY_ORNOT 5
bool isBinaryImage(Mat gray)
{
int histSize = 256;
float range[] = {0,256};
const float* histRange = {range};
Mat hist;
////////////////////////////////////////////////
int hist_w = 512; int hist_h = 400;
Mat histImage( hist_h, hist_w, CV_8UC3, Scalar( 0,0,0) );
calcHist(&gray,1,0,Mat(),hist,1,&histSize,&histRange,true,false);
normalize(hist, hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
int cumulated_amount = 0;
int firstandlast = 0;
firstandlast = cvRound(hist.at<float>(0)) + cvRound(hist.at<float>(histSize - 1));
for(int i = 1; i < histSize - 1; i++)
cumulated_amount += cvRound(hist.at<float>(i));
if(cumulated_amount * OCR_BINARY_ORNOT < firstandlast)
return true;
return false;
}
void HSV2GRAY(Mat HSV,Mat& Gray)
{
if(!HSV.data) return;
uchar* pointer;
Gray = Mat(HSV.rows,HSV.cols,CV_8UC1);
for(int j = 0; j < HSV.rows; j++)
for(int i = 0; i < HSV.cols; i++)
{
pointer = HSV.ptr(j,i) + 2;
*Gray.ptr(j,i) = *pointer;
}
return;
}
#define OCR_STRING_RECT_TOP 0.4
#define OCR_STRING_RECT_LEFT 0.15
#define OCR_STRING_RECT_WIDTH 0.7
#define OCR_STRING_RECT_HEIGHT 0.2
void findStrinRectinBinaryImage(Mat thr,int& top,int& bottom,int& left,int& right)
{
if(thr.empty()) return;
int *sum_h, *sum_v;
sum_h = new int[thr.rows];
sum_v = new int[thr.cols];
calcProjection(thr,sum_h,sum_v);
findStringinBinaryImage(sum_h,thr.rows,sum_v,thr.cols,top,bottom,left,right);
delete []sum_h;
delete []sum_v;
return;
}
#define USER_DEFINED_DELTA2 15
#define USER_DEFINED_DELTA3 2
FindString::FindString()
{
Init();
}
FindString::~FindString()
{
Init();
}
bool FindString::isEmpty()
{
if(image.empty() ||
image_cv_gray.empty() ||
image_hsv.empty() ||
image_hjh_gray.empty())
return true;
return false;
}
bool FindString::isZoomed()
{
if(zoomout == 1)
return true;
return false;
}
void FindString::Init()
{
zoomout = 1;
zoomin = 1;
flag = false;
flag_ = false;//true if vertical pattern is stronger than horizontal pattern,false if not
flag_needEqualization = false;
m_bIscropped = false;
image.release();
image_cv_gray.release();
image_hsv.release();
image_hsv_gray.release();
image_hjh_gray.release();
image_eroded.release();
image_eroded_gray.release();
image_resized.release();
image_cv_gray_resized.release();
image_hsv_resized.release();
image_hsv_gray_resized.release();
image_hjh_gray_resized.release();
image_eroded_resized.release();
image_eroded_gray_resized.release();
m_goodfeatures.release();
////////////////////////////////////////
m_rData.clear();
subStringList.clear();
StringList.clear();
rectlist.clear();
pointlist.clear();
///////////////////////////////////////
return;
}
std::vector<cv::Point2f> ocr_test_goodfeatures_as_points(Mat in)
{
std::vector<cv::Point2f> corners;
if(in.empty() ||
in.type() > 1)
return corners;
// Compute good features to track
cv::goodFeaturesToTrack(in,corners,
1000, // maximum number of corners to be returned
0.1, // quality level
1); // minimum allowed distance between points
return corners;
}
Mat ocr_test_goodfeatures_3division(Mat in)
{
if(in.empty() ||
in.type() > 1)
return Mat();
Mat result = Mat::zeros(cv::Size(in.cols,in.rows), CV_8UC1);
std::vector<cv::Point2f> pointlist;
Mat leftwing,body,rightwing;
Mat(in,cv::Rect(0,0,in.cols / 3,in.rows)).copyTo(leftwing);
Mat(in,cv::Rect(in.cols / 3,0,in.cols / 3,in.rows)).copyTo(body);
Mat(in,cv::Rect(in.cols * 2 / 3,0,in.cols / 3,in.rows)).copyTo(rightwing);
std::vector<cv::Point2f> pl_body,pl_right;
pl_body = ocr_test_goodfeatures_as_points(body);
pl_right = ocr_test_goodfeatures_as_points(rightwing);
pointlist = ocr_test_goodfeatures_as_points(leftwing);
for (std::vector<cv::Point2f>::iterator iter = pl_body.begin(); iter != pl_body.end(); iter++)
{
cv::Point2f point = *iter;
pointlist.push_back(cv::Point2f(point.x + in.cols /3,point.y));
}
for (std::vector<cv::Point2f>::iterator iter = pl_right.begin(); iter != pl_right.end(); iter++)
{
cv::Point2f point = *iter;
pointlist.push_back(cv::Point2f(point.x + in.cols * 2 / 3,point.y));
}
std::vector<cv::Point2f> corners = pointlist;
std::vector<cv::Point2f> neighbors;
std::vector<cv::Point2f>::iterator itc;
#if 0
//step 2----->removing noise-diameter = 15///-kjy-todo-2015.4.28
neighbors = corners;
itc= corners.begin();
int thr_dis,thr_con;
//if(m_bIscropped)
//{
thr_dis = 10;
thr_con = 4;
//}
//{
// thr_dis = 15;
// thr_con = 6;
//}
while (itc!=corners.end()) {
//Create bounding rect of object
cv::Point2f observingpoint = *itc;
bool isIsolated = true;
int count = 0;
for (std::vector<cv::Point2f>::iterator iter = neighbors.begin(); iter != neighbors.end(); iter++)
{
cv::Point2f neighbor = *iter;
double delta_x = abs(observingpoint.x - neighbor.x);
double delta_y = abs(observingpoint.y - neighbor.y);
delta_x *= 1;
delta_y *= 4;
double distance = sqrt(delta_x * delta_x +delta_y * delta_y);
if(distance < thr_dis)//10.0)//8.0)
count ++;
}
if(count < thr_con)//3)//5)
itc= corners.erase(itc);
else
++itc;
}
#endif
#if 1
//step 1----->removing noise-diameter = 3///-kjy-todo-2015.4.28
neighbors = corners;
itc= corners.begin();
while (itc!=corners.end()) {
//Create bounding rect of object
cv::Point2f observingpoint = *itc;
int count = 0;
for (std::vector<cv::Point2f>::iterator iter = neighbors.begin(); iter != neighbors.end(); iter++)
{
cv::Point2f neighbor = *iter;
double delta_x = abs(observingpoint.x - neighbor.x);
double delta_y = abs(observingpoint.y - neighbor.y);
double distance = sqrt(delta_x * delta_x +delta_y * delta_y);
if(distance < 25.0)//8.0)
count ++;
}
if(count < 5)//5)
itc= corners.erase(itc);
else
++itc;
}
#endif
pointlist = corners;
/////////////
for (unsigned int i=0;i<corners.size();++i)
{
cv::ellipse(result,corners[i],cv::Size(1,1),0,0,360,cv::Scalar(255),2,8,0);
}
threshold(result,result,128,255,THRESH_BINARY_INV);
#ifdef OCR_TEST
imshow("goodfeatures",result);
waitKey(1000);
#endif
return result;
}
Mat ocr_test_goodfeatures(Mat in)
{
if(in.empty() || in.type() != CV_8UC1)
return Mat::zeros(cv::Size(in.cols,in.rows), CV_8UC1);
Mat result = Mat::zeros(cv::Size(in.cols,in.rows), CV_8UC1);
//in.copyTo(result);
// Compute good features to track
std::vector<cv::Point2f> corners;
cv::goodFeaturesToTrack(in,corners,
3000, // maximum number of corners to be returned
0.05, // quality level
1); // minimum allowed distance between points
///removing noise///-kjy-todo-2015.4.28
std::vector<cv::Point2f> neighbors;
std::vector<cv::Point2f>::iterator itc;
#if 1
//step 2----->removing noise-diameter = 15///-kjy-todo-2015.4.28
neighbors = corners;
itc= corners.begin();
while (itc!=corners.end()) {
//Create bounding rect of object
cv::Point2f observingpoint = *itc;
int count = 0;
for (std::vector<cv::Point2f>::iterator iter = neighbors.begin(); iter != neighbors.end(); iter++)
{
cv::Point2f neighbor = *iter;
double delta_x = abs(observingpoint.x - neighbor.x);
double delta_y = abs(observingpoint.y - neighbor.y);
delta_x *= 1;
delta_y *= 4;
double distance = sqrt(delta_x * delta_x +delta_y * delta_y);
if(distance < 20.0)//8.0)
count ++;
}
if(count < 4)//5)
itc= corners.erase(itc);
else
++itc;
}
#endif
for (unsigned int i=0;i<corners.size();++i)
{
cv::ellipse(result,corners[i],cv::Size(4,0/*.5*/),0,0,360,cv::Scalar(255),2,8,0);
}
threshold(result,result,128,255,THRESH_BINARY_INV);
imshow("goodfeatures",result);
waitKey(1000);
return result;
}
#define OCR_FILTER_UPPER 0.1
#define OCR_FILTER_LOWER 0.2
#define OCR_FILTER_RATIO 0.3
void calcSize_t(int* array_,int arraySize,int& firstindex,int& lastindex)
{
//blur_(array_,arraySize);
//Gradient_(array_,arraySize);
int min = calcMin(array_,arraySize);
min = min < 0 ? 0: min;
int max = calcMax(array_,arraySize);
int mean = (int)(min * 0.95 + max * 0.05);//calcMean(array_,arraySize);//(int)(float(max - min) / 1.4142);//
int maxindex = int(arraySize / 2) ;//getFirstIndex(array_,arraySize,max);//kjy-todo-2015.3.27
//int oldfirstindex = getFirstIndex(array_,arraySize,mean - 1),oldlastindex = getLastIndex(array_,arraySize,mean - 1);
for(int i = maxindex; i < arraySize - 1; i++)
if((array_[i] >= mean && array_[i + 1] <= mean) || i == arraySize - 1)
{
lastindex = i;
break;
}
for(int j = maxindex; j > 0; j--)
if((array_[j] >= mean && array_[j - 1] <= mean) || j == 1)
{
firstindex = j;
break;
}
return;
}
#define OCR_REASONABLE_COUNT 100
#define OCR_FILTER_2 0.5
//kjy-todo-2015.3.21--it's for filtering non-string outputs
void DrawIntegralProject_v(Mat thresh_output,Mat& integral_projection_v,int* sum_v)
{
if(!thresh_output.data || !sum_v)// || !integral_projection_v.data)
return;
for( int i = 0; i< thresh_output.cols; i++ )
line( integral_projection_v,cv::Point(i,0),cv::Point(i,sum_v[i]),Scalar( 255, 0, 0),2,8,0);
return;
}
void calcVerticalProjection_t(Mat thresh_output,int* sum_v)
{
if(!thresh_output.data ||!sum_v) return;
for( int i = 0; i< thresh_output.cols; i++ )
{
sum_v[i] = 0;
for(int j = 0; j < thresh_output.rows; j++ )
if(*thresh_output.ptr(j,i) == 0)
sum_v[i]++;
}
return;
}
//kjy-todo-2015.3.21
#define OCR_REASONABLE_STRING_COUNT 3
cv::Rect getLockLocation(cv::Rect rect1,cv::Rect subrect)
{
int x,y,width,height;
x = rect1.x + subrect.x;
y = rect1.y + subrect.y;
width = subrect.width;
height = subrect.height;
return cv::Rect(x,y,width,height);
}
#define OCR_REASONABLE_STRING_HEIGHT_LOWER_BOUND 0.03
#define OCR_REASONABLE_STRING_WIDTH_LOWER_BOUND 0.2
#define OCR_REASONABLE_LOCK_HEIGHT_LOWER_BOUND 0.2//0.01
#define OCR_REASONABLE_LOCK_WIDTH_LOWER_BOUND 0.01
#define OCR_REASONABLE_LOCK_HEIGHT_UPPER_BOUND 0.1
#define OCR_REASONABLE_LOCK_WIDTH_UPPER_BOUND 0.1
Mat FindString::getBinaryImage(cv::Rect rect)
{
#if 1
Mat cropped;//(original_binary,rect);
Mat tmp;
if(!flag_needEqualization)
{
//Mat cropped_temp(image_hsv_gray,cv::Rect(rect.x * zoomout,rect.y * zoomout,rect.width * zoomout,rect.height * zoomout));
resize(image_hsv_gray_resized,tmp,cv::Size(image_size_zoomed.width * 2,image_size_zoomed.height * 2));
Mat cropped_temp(tmp,cv::Rect(rect.x * 2,rect.y * 2,rect.width * 2,rect.height * 2));
cropped_temp.copyTo(cropped);
cropped_temp.release();
}
else{
resize(original_binary,tmp,cv::Size(image_size_zoomed.width * 2,image_size_zoomed.height * 2));
Mat cropped_temp(tmp,cv::Rect(rect.x * 2,rect.y * 2,rect.width * 2,rect.height * 2));
cropped_temp.copyTo(cropped);
cropped_temp.release();
}
Mat thr = Mat::zeros(cropped.size(),CV_8UC1);
windowthreshold_new(cropped,thr);
Mat adpthr_resized;
resize(adaptiveThresholded,adpthr_resized,cv::Size(image_size_zoomed.width * 2,image_size_zoomed.height * 2));
Mat croppedinAdaptivethd(adpthr_resized,cv::Rect(rect.x * 2,rect.y * 2,rect.width * 2,rect.height * 2));
threshold(croppedinAdaptivethd,croppedinAdaptivethd,128,255,THRESH_BINARY);
min(croppedinAdaptivethd,thr,thr);
#else
Mat thr;
m_cropped_thr.copyTo(thr);
#endif
removeBoundaryNoise(thr);
////////////////////////////////////
Mat original_thr;
thr.copyTo(original_thr);
removeNoise_revised(thr,(zoomout == 1 ? false:true));
#ifdef OCR_DEBUG
imshow("thr",thr);
imshow("original_thr",original_thr);
waitKey(10000);
#endif
/////////////InclCorr///////////////////////
double alphaRotate, alphaSkew;
ProcLinearInterpolation(thr);
ProcTransformAlpha(thr, alphaRotate, alphaSkew);
ProcTransformCompensation(thr, alphaRotate, alphaSkew);
ProcTransformCompensation(original_thr, alphaRotate, alphaSkew);
//////////////findstring///////////////////////////////////////////////////////////
int left,right,top = 0,bottom = thr.rows;
findStrinRectinBinaryImage(thr,top,bottom,left,right);
////////////////////////////////////////////////////////////////////
int width = right - left,height = thr.rows - 1;//bottom - top;
width = (left + width + USER_DEFINED_DELTA3) > thr.cols ? width:(width + USER_DEFINED_DELTA3);
int refined_left = left,refined_right = right;
int refined_width = width;
if(!isBinaryImage(image_cv_gray_resized))
{
refined_left -= USER_DEFINED_DELTA2;
refined_right += USER_DEFINED_DELTA2;
if(refined_left < 0) refined_left = 0;
if(refined_right > thr.cols) refined_right = thr.cols;
refined_width = refined_right - refined_left;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
removeGaussianNoisebyWindow(thr,original_thr,1,10);//20);
int* sum_h;
sum_h = new int[thr.rows];
calcHorizontalProjection(thr,sum_h,OCR_PIXEL_MIN);
calcSize_t(sum_h,thr.rows,top,bottom);
delete []sum_h;
//kjy-todo-2015.4.1
///////////////kjy-todo-20150314//////////////
//removeGaussianNoisebyWindow(thr,original_thr,10,3);
height = bottom - top + 40;
top -= 20;
if(top < 0) top = 0;
if((height + top) > thr.rows)
{
height = thr.rows - top - 1;
}
Mat output(original_thr,cv::Rect(refined_left < 0 ? 0:refined_left,top,(refined_left + refined_width) > thr.cols ? width:refined_width,height));
////////////////////////////////////////////////////////////////////
return output;
}
cv::Rect getLockRemovedRect(Substitute_String substring)
{
int left = substring.rect.x,
top = substring.rect.y,
right = left + substring.rect.width,
bottom = top + substring.rect.height;
if(substring.existFirstLock)
left = substring.firstLock.x + substring.firstLock.width + 1;
if(substring.existFirstLock)
right = substring.lastLock.x;
return cv::Rect(left,top,right - left,bottom - top);
}
void FindString::findStringList(std::vector<Mat>& outputList)
{
Substitute_String substring;
Mat output;
for (std::vector<Substitute_String>::iterator iter = subStringList.begin(); iter != subStringList.end(); iter++)
{
substring = *iter;
output = getBinaryImage(getLockRemovedRect(substring));
outputList.push_back(output);
#ifdef OCR_DEBUG
imshow("output",output);
waitKey(1000);
#endif
}
return;
}
void FindString::insertSubString(Substitute_String substring)
{
subStringList.push_back(substring);
return;
}
void FindString::getGoodFeaturesAsPoints_new(Mat in)
{
if(in.empty() || in.type() != CV_8UC1)
return;
Mat leftwing,body,rightwing;
Mat(in,cv::Rect(0,0,in.cols / 2,in.rows)).copyTo(leftwing);
Mat(in,cv::Rect(in.cols / 2,0,in.cols / 3,in.rows)).copyTo(rightwing);
std::vector<cv::Point2f> pl_body,pl_right;
getGoodFeaturesAsPoints(rightwing);
pl_right = pointlist;
getGoodFeaturesAsPoints(leftwing);
for (std::vector<cv::Point2f>::iterator iter = pl_right.begin(); iter != pl_right.end(); iter++)
{
cv::Point2f point = *iter;
pointlist.push_back(cv::Point2f(point.x + in.cols /2,point.y));
}
std::vector<cv::Point2f> corners = pointlist;
std::vector<cv::Point2f> neighbors;
std::vector<cv::Point2f>::iterator itc;
#if 0
if(!m_bIscropped)
{
itc= corners.begin();
while (itc!=corners.end()) {
cv::Point2f point = *itc;
if((point.y < in.rows * USER_DEFINED_ERASE_REGION_TOPBOTTOM) ||
(point.y > in.rows * (1 - USER_DEFINED_ERASE_REGION_TOPBOTTOM)) ||
(point.x < in.cols * USER_DEFINED_ERASE_REGION_LEFTRIGHT) ||
(point.x > in.cols * (1 - USER_DEFINED_ERASE_REGION_LEFTRIGHT)))
itc= corners.erase(itc);
else
++itc;
}
}
//step 2----->removing noise-diameter = 15///-kjy-todo-2015.4.28
neighbors = corners;
itc= corners.begin();
int thr_dis,thr_con;
if(m_bIscropped)
{
thr_dis = 10;
thr_con = 4;
}
else
{
thr_dis = 15;
thr_con = 6;
}
while (itc!=corners.end()) {
//Create bounding rect of object
cv::Point2f observingpoint = *itc;
bool isIsolated = true;
int count = 0;
for (std::vector<cv::Point2f>::iterator iter = neighbors.begin(); iter != neighbors.end(); iter++)
{
cv::Point2f neighbor = *iter;
double delta_x = abs(observingpoint.x - neighbor.x);
double delta_y = abs(observingpoint.y - neighbor.y);
delta_x *= 1;
delta_y *= 4;
double distance = sqrt(delta_x * delta_x +delta_y * delta_y);
if(distance < thr_dis)//10.0)//8.0)
count ++;
}
if(count < thr_con)//3)//5)
itc= corners.erase(itc);
else
++itc;
}
//step 1----->removing noise-diameter = 3///-kjy-todo-2015.4.28
neighbors = corners;
itc= corners.begin();
while (itc!=corners.end()) {
//Create bounding rect of object
cv::Point2f observingpoint = *itc;
bool isIsolated = true;
int count = 0;
for (std::vector<cv::Point2f>::iterator iter = neighbors.begin(); iter != neighbors.end(); iter++)
{
cv::Point2f neighbor = *iter;
double delta_x = abs(observingpoint.x - neighbor.x);
double delta_y = abs(observingpoint.y - neighbor.y);
double distance = sqrt(delta_x * delta_x +delta_y * delta_y);
if(distance < 20.0)//8.0)
count ++;
}
if(count < 5)//5)
itc= corners.erase(itc);
else
++itc;
}
#endif
pointlist = corners;
////////////////////////////////
return;
}
///////////////////////////////////////////////////////////////new
void FindString::getGoodFeaturesAsPoints(Mat in)
{
if(in.empty() || in.type() != CV_8UC1)
return;
//
pointlist.clear();
// Compute good features to track
std::vector<cv::Point2f> corners;
cv::goodFeaturesToTrack(in,corners,
1000,//500,// // maximum number of corners to be returned
0.01, // quality level
1); // minimum allowed distance between points
////////////////////////////////////////////////////////////////
std::vector<cv::Point2f> neighbors;
std::vector<cv::Point2f>::iterator itc;
#if 1
if(!m_bIscropped)
{
itc= corners.begin();
while (itc!=corners.end()) {
cv::Point2f point = *itc;
if((point.y < in.rows * USER_DEFINED_ERASE_REGION_TOPBOTTOM) ||
(point.y > in.rows * (1 - USER_DEFINED_ERASE_REGION_TOPBOTTOM)) ||
(point.x < in.cols * USER_DEFINED_ERASE_REGION_LEFTRIGHT) ||
(point.x > in.cols * (1 - USER_DEFINED_ERASE_REGION_LEFTRIGHT)))
itc= corners.erase(itc);
else
++itc;
}
}
//step 2----->removing noise-diameter = 15///-kjy-todo-2015.4.28
neighbors = corners;
itc= corners.begin();
int thr_dis,thr_con;
if(m_bIscropped)
{
thr_dis = 10;
thr_con = 5;//4;
}
else
{
thr_dis = 16;//15;
thr_con = 7;//6;
}
while (itc!=corners.end()) {
//Create bounding rect of object
cv::Point2f observingpoint = *itc;
int count = 0;
for (std::vector<cv::Point2f>::iterator iter = neighbors.begin(); iter != neighbors.end(); iter++)
{
cv::Point2f neighbor = *iter;
double delta_x = abs(observingpoint.x - neighbor.x);
double delta_y = abs(observingpoint.y - neighbor.y);
delta_x *= 1;
delta_y *= 2;
double distance = sqrt(delta_x * delta_x +delta_y * delta_y);
if(distance < thr_dis)//10.0)//8.0)
count ++;
}
if(count < thr_con)//3)//5)
itc= corners.erase(itc);
else
++itc;
}
#endif
#if 1
if(!m_bIscropped)
{
itc= corners.begin();
while (itc!=corners.end()) {
cv::Point2f point = *itc;
if((point.y < in.rows * USER_DEFINED_ERASE_REGION_TOPBOTTOM) ||
(point.y > in.rows * (1 - USER_DEFINED_ERASE_REGION_TOPBOTTOM)) ||
(point.x < in.cols * USER_DEFINED_ERASE_REGION_LEFTRIGHT) ||
(point.x > in.cols * (1 - USER_DEFINED_ERASE_REGION_LEFTRIGHT)))
itc= corners.erase(itc);
else
++itc;
}
}
//step 2----->removing noise-diameter = 15///-kjy-todo-2015.4.28
neighbors = corners;
itc= corners.begin();
while (itc!=corners.end()) {
//Create bounding rect of object
cv::Point2f observingpoint = *itc;
int count = 0;
for (std::vector<cv::Point2f>::iterator iter = neighbors.begin(); iter != neighbors.end(); iter++)
{
cv::Point2f neighbor = *iter;
double delta_x = abs(observingpoint.x - neighbor.x);
double delta_y = abs(observingpoint.y - neighbor.y);
delta_x *= 1;
delta_y *= 2;
double distance = sqrt(delta_x * delta_x +delta_y * delta_y);
if(distance < thr_dis)//10.0)//8.0)
count ++;
}
if(count < thr_con)//3)//5)
itc= corners.erase(itc);
else
++itc;
}
#endif
#if 0
//step 1----->removing noise-diameter = 3///-kjy-todo-2015.4.28
neighbors = corners;
itc= corners.begin();
while (itc!=corners.end()) {
//Create bounding rect of object
cv::Point2f observingpoint = *itc;
int count = 0;
for (std::vector<cv::Point2f>::iterator iter = neighbors.begin(); iter != neighbors.end(); iter++)
{
cv::Point2f neighbor = *iter;
double delta_x = abs(observingpoint.x - neighbor.x);
double delta_y = abs(observingpoint.y - neighbor.y);
double distance = sqrt(delta_x * delta_x +delta_y * delta_y);
if(distance < 20.0)//8.0)
count ++;
}
if(count < 5)//5)
itc= corners.erase(itc);
else
++itc;
}
#endif
////////fill the pointlist and m_goodfeatures(Create an Engine)///////////////////
pointlist = corners;
////////////////////////////////
return;
}
#define OCR_THR_RATIO_COUNTBYSIZE 0.01
cv::Rect FindString::GetHighDensityRect()
{
cv::Rect HDR;
int max = 0;
double ratio = 0;
std::vector<cv::Rect>::iterator iter_rect;
iter_rect = rectlist.begin();
while(iter_rect != rectlist.end())
{
//for (std::vector<cv::Rect>::iterator iter_rect = rectlist.begin(); iter_rect != rectlist.end(); iter_rect++)
//{
int count = 0;
cv::Rect rect = *iter_rect;
for (std::vector<cv::Point2f>::iterator iter_point = pointlist.begin(); iter_point != pointlist.end(); iter_point++)
{
Point2f point = *iter_point;
if(rect.x < point.x &&
rect.y < point.y &&
point.x < (rect.x + rect.width) &&
point.y < (rect.y + rect.height))
count++;
}
/////////////////////kjy-todo-2015.05.08//////////////////////////
ratio = double(count) / double(rect.width * rect.height);
if(ratio < OCR_THR_RATIO_COUNTBYSIZE)
iter_rect= rectlist.erase(iter_rect);
else
++iter_rect;
////////////////////////////////////////////////////////////
if(count > max)
{
HDR = rect;
max = count;
}
}
return HDR;
}
bool isCropped(Mat in)
{
if(in.empty())
return FALSE;
if(double(in.rows) / double(in.cols + 1) > 2||
double(in.cols) / double(in.rows + 1) > 2)
return TRUE;
return FALSE;
}
void ocr_test_harris(Mat in)
{
// Detect Harris Corners
cv::Mat cornerStrength;
cv::cornerHarris(in,cornerStrength,
3, // neighborhood size
3, // aperture size
0.01); // Harris parameter
// threshold the corner strengths
cv::Mat harrisCorners;
double threshold= 0.0001;
cv::threshold(cornerStrength,harrisCorners,
threshold,255,cv::THRESH_BINARY);
imshow("harrisCorners",harrisCorners);
return;
}
void Degrading(Mat& in)
{
if(in.empty() || in.type() == 1)
return;
//calc V of image//
double sum = 0;
for(int j = 0; j < in.rows; j++)
for(int i = 0; i < in.cols; i++)
{
double value = *in.ptr(j,i);
value += *(in.ptr(j,i) + 1);
value += *(in.ptr(j,i) + 2);
value /= (255.0 * 3.0);
sum += value;
}
sum /= double(in.rows * in.cols);
if(sum < 0.5)
return;
//////////////////////////////////////////
for(int j = 0; j < in.rows; j++)
for(int i = 0; i < in.cols; i++)
{
if(*in.ptr(j,i) > 80)
*in.ptr(j,i) -= 80;
else
*in.ptr(j,i) = 0;
//////////
if(*(in.ptr(j,i) + 1) > 80)
*(in.ptr(j,i) + 1) -= 80;
else
*(in.ptr(j,i) + 1) = 0;
/////////////////
if(*(in.ptr(j,i) + 2) > 80)
*(in.ptr(j,i) + 2) -= 80;
else
*(in.ptr(j,i) + 2) = 0;
}
return;
}
void Upgrade(Mat& in)
{
if(in.empty() || in.type() == 1)
return;
//calc V of image//
double sum = 0;
for(int j = 0; j < in.rows; j++)
for(int i = 0; i < in.cols; i++)
{
double value = *in.ptr(j,i);
value += *(in.ptr(j,i) + 1);
value += *(in.ptr(j,i) + 2);
value /= (255.0 * 3.0);
sum += value;
}
sum /= double(in.rows * in.cols);
if(sum > 0.85)
return;
//////////////////////////////////////////
for(int j = 0; j < in.rows; j++)
for(int i = 0; i < in.cols; i++)
{
if(*in.ptr(j,i) >= 155)
*in.ptr(j,i) = 255;
else
*in.ptr(j,i) += 100;
//////////
if(*(in.ptr(j,i) + 1) >= 155)
*(in.ptr(j,i) + 1) = 255;
else
*(in.ptr(j,i) + 1) += 100;
/////////////////
if(*(in.ptr(j,i) + 2) >= 155)
*(in.ptr(j,i) + 2) = 255;
else
*(in.ptr(j,i) + 2) += 100;
}
return;
}
Mat ocr_resizeByProjection(Mat in)
{
Mat goodfeatures = ocr_test_goodfeatures_3division(in);//ocr_test_goodfeatures(in);
int* sum_v,*sum_h;
sum_v = new int[in.cols];
sum_h = new int[in.rows];
calcVerticalProjection(goodfeatures,sum_v,OCR_PIXEL_MIN);
calcHorizontalProjection(goodfeatures,sum_h,OCR_PIXEL_MIN);
int left,right,top,bottom;
findLeftRight(sum_v,in.cols,left,right);
findTopBottom(sum_h,in.rows,top,bottom);
delete []sum_v;
delete []sum_h;
if(left >= right ||
(right - left) < double(goodfeatures.cols) * 0.2||
top >= bottom ||
(bottom - top) < double(goodfeatures.rows) * 0.2)
return Mat();
Mat cropped(in,cv::Rect(left,top,right - left,bottom - top));
return cropped;
}
cv::Rect ocr_resizeByProjection_as_rect(Mat in)
{
Mat goodfeatures = ocr_test_goodfeatures_3division(in);//ocr_test_goodfeatures(in);
#ifdef OCR_INTEST
imshow("goodfeatures",goodfeatures);
waitKey(1000);
#endif
int* sum_v,*sum_h;
sum_v = new int[in.cols];
sum_h = new int[in.rows];
calcVerticalProjection(goodfeatures,sum_v,OCR_PIXEL_MIN);
calcHorizontalProjection(goodfeatures,sum_h,OCR_PIXEL_MIN);
int left,right,top,bottom;
findLeftRight(sum_v,in.cols,left,right);
findTopBottom(sum_h,in.rows,top,bottom);
#ifdef OCR_INTEST
//if()
{
line(goodfeatures,Point(right,0),Point(right,goodfeatures.rows), Scalar(0,0,255));
imshow("goodfeatures",goodfeatures);
waitKey(1000);
}
#endif
delete []sum_v;
delete []sum_h;
if(left >= right ||
(right - left) < double(goodfeatures.cols) * 0.2||
top >= bottom ||
(bottom - top) < double(goodfeatures.rows) * 0.2)
return cv::Rect();
return cv::Rect(left,top,right - left,bottom - top);
}
Mat ocr_test_canny(Mat in)
{
if(in.empty() || in.type() > 1)
return Mat();
//////////////////////////
// Apply Canny algorithm
cv::Mat contours;
cv::Canny(in, // gray-level image
contours, // output contours
225, // low threshold
350); // high threshold
cv::Mat contoursInv; // inverted image
cv::threshold(contours,contoursInv,
128, // values below this
255, // becomes this
cv::THRESH_BINARY);//_INV);
//imshow("canny",contoursInv);
return contoursInv;
}
Mat FindString::findString_kojy(Mat img_)
{
if(img_.empty())
return Mat();
img_.copyTo(m_img_);
m_bIscropped = isCropped(img_);
////////////////////////
image_size = cv::Size(img_.cols,img_.rows);
//step1---------->zoom in an input image/////////////////////////////////////////////////
zoomin = cvRound(3096 / img_.cols);
if(zoomin < 1)
zoomin = 1;
resize(img_,image,cv::Size(img_.cols * zoomin,img_.rows * zoomin));
erode(image,image_eroded,Mat(),cv::Point(-1,-1),2,1);
//step2---------->zoom out an input image/////////////////////////////////////////////////
if(image.rows > image.cols)
zoomout = cvRound(image.rows / 450);
else
zoomout = cvRound(image.cols / 450);
if(zoomout < 1)
zoomout = 1;
image_size_zoomed = cv::Size(image.cols/zoomout,image.rows/zoomout);
//step3---------->resize an image////////////////////////////////
resize(image,image_resized,image_size_zoomed);
resize(image_eroded,image_eroded_resized,image_size_zoomed);
//step4---------->create an engine/////////////////////////////////////////////
//Degrading(image_resized);
poster_edge = posterEdgefilter(image_resized);
//equalizeHist(poster_edge,poster_edge);
Mat hongjh;
image_resized.copyTo(hongjh);
Convert2Gray(hongjh);
//////////////////////////////////
getGoodFeaturesAsPoints(poster_edge);
m_goodfeatures = Mat::zeros(poster_edge.rows,poster_edge.cols,CV_8UC1);
for (unsigned int i=0;i<pointlist.size();++i)
{
cv::ellipse(m_goodfeatures,pointlist[i],cv::Size(4,1),0,0,360,cv::Scalar(255),1,8,0);
}
/////////kojy-todo-2015.5.4/////////////////////////////////////////////////////////////////////////
//if(!isCropped(image))
// eraseMargin(m_goodfeatures);
#ifndef OCR_ONCE
imshow("m_goodfeatures",m_goodfeatures);
waitKey(1000);
#endif
//step5---------->get a list of suspicious string rects///////////////////////////////////////
getRectList();
if(rectlist.empty())
return Mat();
/**/
refineRectList();
/**/
//step6---------->checkLock
getSSList();
//step7---------->pick up the highest-density rect////////////////
cv::Rect rect = GetHighDensityRect();
//step8---------->final processing(Form an output)////////////////////////////////////////////////////////
double ratio = double(zoomout) / double(zoomin);
Mat test(img_,cv::Rect((int)(rect.x * ratio),(int)(rect.y * ratio),(int)(rect.width * ratio),(int)(rect.height * ratio)));
//
double proportional = test.rows / 80.0;
if(proportional <= 1.0)
proportional = 1.0;
Mat test_resized;
resize(test,test_resized,cv::Size((int)(test.cols/proportional),(int)(test.rows/proportional)));
Mat cropped;
test_resized.copyTo(cropped);
//Degrading(cropped);
///////////////BLACK & WHITE//////////////////////////////////////////////
#if 0
Mat bw_t;
resize(cropped,bw_t,cv::Size(cropped.cols / 3,cropped.rows / 3));
//Degrading(bw_t);
cv::Size size = cv::Size(bw_t.cols,bw_t.rows);
bw_t.copyTo(image_hjh_gray_resized);
Convert2Gray(image_hjh_gray_resized);
cvtColor(bw_t,image_hsv_resized,COLOR_BGR2HSV);
HSV2GRAY(image_hsv_resized,image_hsv_gray_resized);
//////////////////////////////////////////////////
tess = Mat::zeros(size, CV_8UC1);
windowthreshold_new(image_hjh_gray_resized,tess);
threshold(image_hjh_gray_resized, tess, 0, 255,CV_THRESH_OTSU+CV_THRESH_BINARY);
threshold(tess, tess, 128, 255, THRESH_BINARY);
windowthreshold_new(image_hsv_gray_resized,tess);
threshold(tess, tess, 128, 255, THRESH_BINARY);
//Mat tmp = Mat::zeros(image_size_zoomed, CV_8UC1);
//windowthreshold(poster_edge,tmp);
//threshold(tmp, original_binary, 128, 255, THRESH_BINARY);
//min(tess,original_binary,original_binary);
imshow("tess",tess);
waitKey(1000);
#endif
imshow("cropped",cropped);
#if 0
Convert2Gray(cropped);
//adaptiveBilateralFilter(test,cropped,cv::Size(7,7),10.0);
#else
cropped = posterEdgefilter(test_resized);
#endif
Mat croppedincropped;
croppedincropped = cropped;//ocr_resizeByProjection(cropped);//
if(croppedincropped.empty())
return Mat();
#ifdef OCR_DEBUG
imshow("croppedincropped",croppedincropped);
waitKey(1000);
#endif
Mat thr = Mat::zeros(croppedincropped.size(),CV_8UC1);
windowthreshold_new(croppedincropped,thr);
threshold(thr,thr,128,255,THRESH_BINARY);
removeBoundaryNoise(thr);
#ifdef OCR_DEBUG
imshow("thr",thr);
waitKey(1000);
#endif
//InclCorr
double alphaRotate, alphaSkew;
ProcLinearInterpolation(thr);
ProcTransformAlpha(thr, alphaRotate, alphaSkew);
ProcTransformCompensation(thr, alphaRotate, alphaSkew);
return thr;
}
#define REASONABLE 15
void FindString::RefineString(Mat& in)
{
Mat thr;
threshold(in,thr,128,255,THRESH_BINARY_INV);
int *sum_h = new int[thr.rows],top,bottom;
calcHorizontalProjection(thr,sum_h,OCR_PIXEL_MAX);
findTopBottom(sum_h,thr.rows,top,bottom);
#ifdef IN_DEV
if((top + LINE_HEIGHT) > bottom &&
top > 0 &&
bottom < in.rows)
{
for(int i = top; i <= bottom; i++)
sum_h[i] = 0;
findTopBottom(sum_h,thr.rows,top,bottom);
}
#endif
top -= 2;
bottom += 2;
if(top < 0)
top = 0;
if(bottom >= thr.rows)
bottom = thr.rows - 1;
Mat tmp(thr,cv::Rect(0,top,thr.cols,bottom - top));
int *sum_v = new int[tmp.cols],left,right;
calcVerticalProjection(tmp,sum_v,OCR_PIXEL_MAX);
findLeftRight(sum_v,tmp.cols,left,right);
left -= 2;
right += 2;
if(left < 0)
left = 0;
if(right >= tmp.cols)
right = tmp.cols - 1;
if((bottom - top) * REASONABLE < (right - left))
{
delete []sum_h;
delete []sum_v;
return;
}
Mat tmp2(tmp,cv::Rect(left, 0, right - left, tmp.rows));
threshold(tmp2,in,128,255,THRESH_BINARY_INV);
delete []sum_v;
delete []sum_h;
return;
}
void FindString::getRectList()
{
int top,left,right,bottom;
int *sum_h, *sum_v;
sum_h = new int[m_goodfeatures.rows];
sum_v = new int[m_goodfeatures.cols];
for(int i = 0; i < OCR_STRING_COUNT_ESTIMATE; i++)
{
if(countNonZero(m_goodfeatures) < OCR_REASONABLE_COUNT)
break;
////////Get Top & Bottom (an info about the horizontal location of an assumed StringRect)///////////////////////////
calcHorizontalProjection(m_goodfeatures,sum_h,OCR_PIXEL_MAX);
blur_(sum_h,m_goodfeatures.rows);
lower(sum_h,m_goodfeatures.rows);//added by kojy-20150725
///
#ifdef OCR_ONCE
showArray_h("horizontal",sum_h,m_goodfeatures.rows);
#endif
///
findTopBottom(sum_h,m_goodfeatures.rows,top,bottom);
top -= USER_DEFINED__H_MARGIN;
bottom += USER_DEFINED__H_MARGIN;
if(top < 0) top = 0;
if(bottom >= m_goodfeatures.rows) bottom = m_goodfeatures.rows - 1;
/////////Get Left & Right (an info about the vertical location of an assumed StringRect)///////////////////////////
Mat croppedbyTopBottom(m_goodfeatures,cv::Rect(0,top,m_goodfeatures.cols,bottom - top));
calcVerticalProjection(croppedbyTopBottom,sum_v,OCR_PIXEL_MAX);
#ifdef OCR_ONCE
imshow("cropped",croppedbyTopBottom);
waitKey(4000);
showArray_v("TEst",sum_v,croppedbyTopBottom.cols);
#endif
findLeftRight(sum_v,croppedbyTopBottom.cols,left,right);
////////////////////////////kjy-todo-2015.05.08///////////
int adaptvie_margin = (int)(USER_DEFINED__W_MARGIN * (double(bottom - top) / 21.0));
adaptvie_margin = adaptvie_margin > USER_DEFINED__W_MARGIN ? (int)USER_DEFINED__W_MARGIN:adaptvie_margin;
left -= adaptvie_margin;
right += adaptvie_margin;
////////////////////////////////////////////////
if(left < 0) left = 0;
if(right >= m_goodfeatures.cols) right = m_goodfeatures.cols - 1;
/////////Form the rect of the suspicious StringRect///////////////////////////////
cv::Rect rect = cv::Rect(left,top,right - left,bottom - top);
/////////Reflect the Engine//////////////////////////////////////////////////////////
for(int j = top; j < bottom; j++)
for(int i = 0; i < m_goodfeatures.cols; i++)
{
*m_goodfeatures.ptr(j,i) = 0;
}
//////////////////////////////////////////////////
if(top == 0 &&
bottom == (m_goodfeatures.rows - 1))
continue;
if(rect.width < 1 ||
rect.height < 1)
continue;
if(double(rect.width) / double(rect.height + 1) < 2)
continue;
#ifdef OCR_ONCE
Mat cropped(image_resized,rect);
imshow("cropped",cropped);
waitKey(1000);
#endif
rectlist.push_back(rect);
}
delete []sum_v;
delete []sum_h;
return;
}
void fillinside(Mat& in)
{
if(in.empty() || in.type() > 1)
return;
#if 0
#if 1
threshold(in,in,128,255,THRESH_BINARY_INV);
dilate(in,in,Mat());
//dilate(in,in,Mat());
//dilate(in,in,Mat());
threshold(in,in,128,255,THRESH_BINARY_INV);
#else
erode(in,in,Mat());
threshold(in,in,128,255,THRESH_BINARY);
#endif
#endif
#if 0
Mat black = Mat::zeros(in.rows,in.cols,CV_8UC1);
int first = 0,last = 0;
bool exist_f = false,exist_l = false;
for(int j = 1; j < in.rows - 1; j++)
{
for(int i = 0; i < in.cols; i++)
{
exist_f = false;
if(*in.ptr(j,i) == 0 ||
*in.ptr(j - 1,i) == 0 ||
*in.ptr(j + 1,i) == 0)
{
first = i;
exist_f = true;
break;
}
}
for(int i = (in.cols - 1); i <= 0; i--)
{
exist_l = false;
if(*in.ptr(j,i) == 0 ||
*in.ptr(j - 1,i) == 0 ||
*in.ptr(j + 1,i) == 0)
{
last = i;
exist_l = true;
break;
}
}
if(first != last)
line(black,cv::Point(first,j),cv::Point(last,j),cv::Scalar(255),1.5);
}
for(int i = 1; i < in.cols - 1; i++)
{
for(int j = 0; j < in.rows; j++)
{
exist_f = false;
if(*in.ptr(j,i) == 0 ||
*in.ptr(j,i - 1) == 0 ||
*in.ptr(j,i + 1) == 0 )
{
first = j;
exist_f = true;
break;
}
}
for(int j = (in.rows - 1); j <= 0; j--)
{
exist_l = false;
if(*in.ptr(j,i) == 0 ||
*in.ptr(j,i - 1) == 0 ||
*in.ptr(j,i + 1) == 0 )
{
last = j;
exist_l = true;
break;
}
}
if(first != last)
line(black,cv::Point(i,first),cv::Point(i,last),cv::Scalar(255),1.5);
}
threshold(black,black,128,255,THRESH_BINARY_INV);
black.copyTo(in);
#endif
return;
}
void removeabove100pixels(Mat& binary,Mat color)
{
if(color.empty() || color.type() != CV_8UC3)
return;
for(int j = 0; j < color.rows; j++)
for(int i = 0; i < color.cols; i++)
{
if(*color.ptr(j,i) > 100 ||
*(color.ptr(j,i) + 1) > 100 ||
*(color.ptr(j,i) + 2)> 100 )
*binary.ptr(j,i) = 255;
}
}
bool resizeImg(Mat& img)
{
Mat tmp;
Mat tmp_reduced;
img.copyTo(tmp);
///
removeBoundaryNoise(tmp);
tmp.copyTo(tmp_reduced);
///
int left, right, top, bottom;
for(int i = 3; i < 15; i += 2)
removeGaussianNoiseByWindow(tmp_reduced,255,0,i);
//
int* array_h,* array_v;
array_h = new int[tmp_reduced.rows];
array_v = new int[tmp_reduced.cols];
calcVerticalProjection(tmp_reduced,array_v,0);
calcHorizontalProjection(tmp_reduced,array_h,0);
findStringinBinaryImage(array_h,tmp_reduced.rows,array_v,tmp.cols,top,bottom,left,right);
//calcSize_t(array_h,tmp.rows,top,bottom);
delete []array_h;
delete []array_v;
//
if(bottom - top <= 0 || right - left <= 0)
return false;
Mat cropped(tmp,cv::Rect(left,top,right-left,bottom-top));
if(cropped.rows * 3 > cropped.cols)
return false;
#ifdef OCR_TEST
imshow("tmp_reduced",tmp_reduced);
imshow("cropped",cropped);
waitKey(1000);
#endif
img = cropped;
return true;
}
#define OCR_PLUS 0.5
void FindString::getlocks_new(cv::Rect rect,Mat& string,Mat& firstL,Mat& lastL,cv::Rect& fll,cv::Rect& lll)
{
if(rect.width == 0||
rect.height == 0)
return;
double ratio = double(zoomout) / double(zoomin);
//
Mat test(m_img_,cv::Rect((int)(rect.x * ratio),(int)(rect.y * ratio - OCR_PLUS),(int)(rect.width * ratio),(int)((rect.height + 2 * OCR_PLUS) * ratio)));//-->original
//Mat test(m_jon,cv::Rect(rect.x * ratio,(rect.y * ratio - OCR_PLUS),rect.width * ratio,(rect.height + 2 * OCR_PLUS) * ratio));//-replaced
#ifdef OCR_TEST
imshow("TEST",test);
waitKey(1000);
#endif
double proportional = test.rows / 160.0;//80
if(proportional <= 1.0)
proportional = 1.0;
Mat test_resized;//(test);
resize(test,test_resized,cv::Size((int)(test.cols / proportional),(int)(test.rows / proportional)));
Mat cropped;
test_resized.copyTo(cropped);
///////////////BLACK & WHITE//////////////////////////////////////////////
Mat bw_t = cropped;
double comp_ratio = 1.0;//1.0
resize(cropped,bw_t,cv::Size((int)(cropped.cols / comp_ratio),(int)(cropped.rows / comp_ratio)));
cv::Size size = cv::Size(bw_t.cols,bw_t.rows);
//
#if 1
Mat pe = posterEdgefilter(bw_t);//original
#else
Mat pe = posterEdgefilter(posterEdgefilterJON(bw_t));//replaced
#endif
tess = Mat::zeros(size, CV_8UC1);
windowthreshold_new(pe,tess);
threshold(tess, tess, 128, 255, THRESH_BINARY);
Mat roi_;//(tess,rect);
tess.copyTo(roi_);
removeBoundaryNoise(roi_);
//-added
//removeabove100pixels(roi_,bw_t);
//-by kjy 6.28
///InclCorr-process
double alphaRotate, alphaSkew;
ProcLinearInterpolation(roi_);
ProcTransformAlpha(roi_, alphaRotate, alphaSkew);
#if 1//kojy-todo-save Rotation data-20151121-for 90%
m_rData.push_back(alphaRotate);
#endif
ProcTransformCompensation(roi_, alphaRotate, alphaSkew);
//
string = roi_;
// imwrite("/home/joonyong/Downloads/before.jpg",string);
#ifdef OCR_TEST
bool isStringbySize = resizeImg(string);
if(!isStringbySize)
return;
#endif
////imshow("string",string);
////waitKey(1000);
#if 0
comp_ratio = 1.0;//1.0
Mat string_tmp;
resize(string,string_tmp,cv::Size((int)(string.cols / comp_ratio),(int)(string.rows / comp_ratio)));
string_tmp.copyTo(string);
#endif
//
size.width = string.cols;
size.height = string.rows;
//Search-process
int left,right,top = 0,height = string.rows,width = string.cols;
int top_,bottom_;
int* sum_v,* sum_h;;
sum_v = new int[width];
sum_h = new int[height];
calcVerticalProjection(string,sum_v,OCR_PIXEL_MIN);
lower(sum_v,string.cols);
//blur_(sum_v,string.cols);
#ifdef OCR_DEBUG
showArray_v("v",sum_v,string.cols);//
#endif
cv::Rect fl1,fl2,ll1,ll2;
Mat croppedfirstlock,croppedlastlock;
getFirstLock(sum_v,string.cols,left,right);
///kjy-todo-2015.4.28//////
if(left < right)
{
fl1 = cv::Rect(left,top,right - left,height);
#if 1
Mat firstLock(string,fl1);
#else
Mat firstLock;
Mat(pe, fl1).copyTo(firstLock);
#endif
threshold(firstLock,firstLock,128,255,THRESH_BINARY);
///////////////////removing background///////////////////
//
removeBoundaryNoise(firstLock);
//
calcHorizontalProjection(firstLock,sum_h,OCR_PIXEL_MIN);
findLeftRight(sum_h,height,top_,bottom_);
if(top_ < bottom_)
{
fl2 = cv::Rect(0,top_,firstLock.cols,bottom_ - top_);
Mat croppedfirst_lock(firstLock,fl2);
croppedfirst_lock.copyTo(croppedfirstlock);
#ifdef OCR_TEST
imshow("croppedfirstlock",croppedfirstlock);
waitKey(1000);
#endif
}
}
////////////////////////////////////
getLastLock(sum_v,string.cols,left,right);
if(left < right)
{
ll1 = cv::Rect(left,top,right - left,string.rows);
#if 1
Mat lastLock(string,ll1);
#else
Mat lastLock;
Mat(pe,ll1).copyTo(lastLock);
#endif
threshold(lastLock,lastLock,128,255,THRESH_BINARY);
//
removeBoundaryNoise(lastLock);
//
calcHorizontalProjection(lastLock,sum_h,OCR_PIXEL_MIN);
findLeftRight(sum_h,height,top_,bottom_);
if(top_ < bottom_)
{
ll2 = cv::Rect(0,top_,lastLock.cols,bottom_ - top_);
Mat croppedlast_lock(lastLock,ll2);
croppedlast_lock.copyTo(croppedlastlock);
#ifdef OCR_TEST
imshow("croppedlastlock",croppedlastlock);
waitKey(1000);
#endif
}
}
//////////////////////////////////
#ifdef OCR_NEVER
imshow("croppedfirstlock",croppedfirstlock);
imshow("croppedlastlock",croppedlastlock);
waitKey(1000);
#endif
if(croppedfirstlock.rows > OCR_REASONABLE_LOCK_HEIGHT_LOWER_BOUND * double(size.height) &&
croppedfirstlock.cols > OCR_REASONABLE_LOCK_WIDTH_LOWER_BOUND * double(size.width) &&
croppedfirstlock.cols < OCR_REASONABLE_LOCK_WIDTH_UPPER_BOUND * double(size.width) &&
(croppedfirstlock.rows / (croppedfirstlock.cols + 1) < 7) &&
(croppedfirstlock.cols / (croppedfirstlock.rows + 1) < 7) &&
croppedfirstlock.rows > 4 && croppedfirstlock.cols > 4)
{
fillinside(croppedlastlock);
resize(croppedfirstlock,firstL,cv::Size(croppedfirstlock.cols * 2,croppedfirstlock.rows * 2));
threshold(firstL,firstL,128,255,THRESH_BINARY);
fll = fl1;//getLockLocation(rect,fl1);
}
if(croppedlastlock.rows > OCR_REASONABLE_LOCK_HEIGHT_LOWER_BOUND * double(size.height) &&
croppedlastlock.cols > OCR_REASONABLE_LOCK_WIDTH_LOWER_BOUND * double(size.width) &&
croppedlastlock.cols < OCR_REASONABLE_LOCK_WIDTH_UPPER_BOUND * double(size.width) &&
(croppedlastlock.rows / (croppedlastlock.cols + 1) < 4) &&
(croppedlastlock.cols / (croppedlastlock.rows + 1) < 4) &&
croppedlastlock.rows > 4 && croppedlastlock.cols > 4)
{
fillinside(croppedlastlock);
resize(croppedlastlock,lastL,cv::Size(croppedlastlock.cols * 2,croppedlastlock.rows * 2));
threshold(lastL,lastL,128,255,THRESH_BINARY);
lll = ll1;//getLockLocation(rect,ll1);
}
////////////////////
delete []sum_h;
delete []sum_v;
return;
}
void SortByHeight(std::vector<Substitute_String>& sublist)
{
if(sublist.size() == 0)
return;
std::vector<Substitute_String> tmp;
std::vector<Substitute_String>::iterator itc_tmp;
tmp = sublist;
sublist.clear();
int stringcount = tmp.size();
for(int i = 0; i < stringcount; i++)
{
int min = 100000;
for (std::vector<Substitute_String>::iterator iter = tmp.begin(); iter != tmp.end(); iter++)
{
Substitute_String substring = *iter;
if(substring.rect.y < min)
{
min = substring.rect.y;
itc_tmp = iter;
}
}
sublist.push_back(*itc_tmp);
tmp.erase(itc_tmp);
}
return;
}
void FindString::getSSList()
{
if(rectlist.empty())
return;
////
//std::vector<Substitute_String> tmp;
////
for (std::vector<cv::Rect>::iterator iter = rectlist.begin(); iter != rectlist.end(); iter++)
{
cv::Rect rect = *iter;
if(rect.width == 0 ||
rect.height == 0)
continue;
Mat string;
Mat firstMark,lastMark;
cv::Rect fmLocation,lmLocation;
getlocks_new(rect,string,firstMark,lastMark,fmLocation,lmLocation);
if((fmLocation.width == 0 || fmLocation.height == 0) &&
(lmLocation.width == 0 || lmLocation.height == 0))
continue;
OCR_Substitute_String substring(rect,string,firstMark,lastMark,fmLocation,lmLocation);
subStringList.push_back(substring);
}
//SortByHeight(subStringList);
//SortByLocks'relation
return;
}
void FindString::refineRectList()
{
if(rectlist.empty())
return;
std::vector<cv::Rect> tmp;
for (std::vector<cv::Rect>::iterator iter = rectlist.begin(); iter != rectlist.end(); iter++)
{
cv::Rect rect = *iter;
Mat cropped(image_resized,rect);
Mat gray;
#ifdef OCR_INTEST//kojy
gray = posterEdgefilter(posterEdgefilterJON(cropped));
#else
gray = posterEdgefilter(cropped);
#endif
cv::Rect subrect = ocr_resizeByProjection_as_rect(gray);
tmp.push_back(cv::Rect(rect.x + subrect.x,rect.y + subrect.y,subrect.width,subrect.height));
}
rectlist.clear();
rectlist = tmp;
return;
}
Mat FindString::removeLocks(OCR_Substitute_String& substring)
{
if(substring.thr.empty())
return Mat();
int left = 0, right = substring.thr.cols;
if(substring.existFirstLock)
left = substring.firstLock.x + substring.firstLock.width + 1;
if(substring.existLastLock)
right = substring.lastLock.x;
if(left >= right)
{
left = 0;
right = substring.thr.cols;
}
return Mat(substring.thr,cv::Rect(left,0,right - left,substring.thr.rows));
}
void ocr_canny_goodfeatures_filter(Mat canny,Mat& goodfeatures)
{
if(canny.empty() ||
canny.type() > 1||
goodfeatures.empty() ||
goodfeatures.type() > 1 ||
canny.rows != goodfeatures.rows ||
canny.cols != goodfeatures.cols)
return;
for(int j = 0; j < canny.rows; j++)
{
int nonzerocount = 0;
for(int i = 0; i < canny.cols; i++)
{
if(*canny.ptr(j,i) != 0)
nonzerocount++;
}
if(nonzerocount == 0)
for(int i = 0; i < canny.cols; i++)
*goodfeatures.ptr(j,i) = 0;
}
return;
}
void FindString::GetWhatYouWantFirst(Mat img_)
{
//qDebug("inGWYWF");
if(img_.empty())
return;
//qDebug("to be about to do GWYWF!");
#define USE_POSTER
#ifdef USE_POSTER
m_jon = posterEdgefilterJON(img_);//-added
//m_jon = posterEdgefilterJON(m_jon);//-added
//m_jon = posterEdgefilterJON(m_jon);//-added
m_jon.copyTo(m_img_);
#else
img_.copyTo(m_img_);
#endif
m_bIscropped = isCropped(m_img_);
////////////////////////
image_size = cv::Size(m_img_.cols,m_img_.rows);
//step1---------->zoom in an input image/////////////////////////////////////////////////
zoomin = cvRound(3096 / m_img_.cols);
if(zoomin < 1)
zoomin = 1;
resize(m_img_,image,cv::Size(m_img_.cols * zoomin,m_img_.rows * zoomin));
erode(image,image_eroded,Mat(),cv::Point(-1,-1),2,1);
//qDebug("step1 finished");
//step2---------->zoom out an input image/////////////////////////////////////////////////
if(image.rows > image.cols)
zoomout = cvRound(image.rows / 450);
else
zoomout = cvRound(image.cols / 450);
if(zoomout < 1)
zoomout = 1;
image_size_zoomed = cv::Size(image.cols/zoomout,image.rows/zoomout);
//qDebug("step2 finised!");
//step3---------->resize an image////////////////////////////////
resize(image,image_resized,image_size_zoomed);
resize(image_eroded,image_eroded_resized,image_size_zoomed);
//qDebug("step3");
//step4---------->create an engine/////////////////////////////////////////////
//Degrading(image_resized);
poster_edge = posterEdgefilter(image_resized);
#ifdef OCR_TEST
imshow("posterE",poster_edge);
waitKey(4000);
#endif
getGoodFeaturesAsPoints(poster_edge);
m_goodfeatures = Mat::zeros(poster_edge.rows,poster_edge.cols,CV_8UC1);
for (unsigned int i=0;i<pointlist.size();++i)
{
cv::ellipse(m_goodfeatures,pointlist[i],cv::Size(4,1),0,0,360,cv::Scalar(255),1,8,0);
}
#ifndef OCR_TEST
Mat test_kjy = Mat::zeros(poster_edge.rows,poster_edge.cols,CV_8UC1);
memset(test_kjy.data, 255, poster_edge.rows * poster_edge.cols);
for (unsigned int i=0;i<pointlist.size();++i)
{
cv::ellipse(test_kjy,pointlist[i],cv::Size(4,1),0,0,360,cv::Scalar(0),1,8,0);
//*test_kjy.ptr(int(pointlist[i].y), int(pointlist[i].x)) = 0;
}
//imwrite("/home/joonyong/Downloads/goodf.jpg",test_kjy);
//cvtColor(test_kjy,test_kjy,CV_BGR2GRAY);
//threshold(test_kjy,test_kjy,128,255,THRESH_BINARY_INV);
double alphaSkew;
ProcLinearInterpolation(test_kjy);
ProcTransformAlpha(test_kjy, m_Rotation, alphaSkew);
////imshow("posterE",test_kjy);
////waitKey(1000);
#endif
//step5---------->get a list of suspicious string rects///////////////////////////////////////
getRectList();
if(rectlist.empty())
return;
/**/
//step6---------->refine suspicious string rects///////////////////////////////////////
refineRectList();
/**/
//step7---------->get a list of suspicious strings///////////////////////////////////////
getSSList();
return;
}
void FindString::GetOutputList(Mat image, vector<Mat> &outputList)
{
vector<Substitute_String> subStringList;
subStringList = GetSubstituteStringList(image);
Substitute_String substring;
for (vector<Substitute_String>::iterator iter = subStringList.begin(); iter != subStringList.end(); iter++)
{
substring = *iter;
if(CheckLockSymbol_Revised(g_pDicData, substring.firstMark.data,substring.firstMark.rows,substring.firstMark.cols))
substring.existFirstLock = true;
if(CheckLockSymbol_Revised(g_pDicData, substring.lastMark.data,substring.lastMark.rows,substring.lastMark.cols))
substring.existLastLock = true;
if(substring.existFirstLock || substring.existLastLock)
outputList.push_back(removeLocks(substring));
}
return;
}
double Recommended_Angle[8] = {0.0872,0.1744,0.2617,0.3488,0.4363,0.5233,0.6105,0.6977};
void FindString::RefineRotationData()
{
BOOL clock_wised = FALSE;
int count_clw = 0,count_uclw = 0;//clockwise,unclockwise
/////////////////////////////////////
vector<double>::iterator itc;
itc= m_rData.begin();
while (itc!=m_rData.end()) {
//if(abs(*itc) < 0.02)
//{
// itc= m_rData.erase(itc);
//}
//else
//{
if(double(*itc) < 0)
count_clw++;
else
count_uclw++;
++itc;
//}
}
///////////delete unnecessary///////////////////////////
int flag = m_Rotation > 0 ? 1 : -1;//(count_clw > count_uclw) ? -1 : 1;
double prev = -1;
#if 0
itc= m_rData.begin();
while (itc!=m_rData.end()) {
int clw = *itc < 0 ? -1 : 1;
if(clw != flag || abs(prev - *itc) < 0.03)
itc = m_rData.erase(itc);
else
++itc;
prev = *itc;
}
#endif
////////////////////////////////////////////////
for(int i = 0; i < 8; i++)
{
if(Recommended_Angle[i] < abs(m_Rotation))
continue;
bool available = true;
for(vector<double>::iterator itc = m_rData.begin(); itc != m_rData.end(); itc++)
if(abs(*itc - flag * Recommended_Angle[i]) < 0.03)
available = false;
if(available)
m_rData.push_back(flag * Recommended_Angle[i]);
}
}
void FindString::GetOutputListEx(Mat image, vector<Mat>& outputList)
{
Mat rotated;
vector<Substitute_String> SSL;
SSL = GetSubstituteStringList(image);
////////////////////////////////////////////////////////////////////////////
RefineRotationData();
vector<double> rData = GetRotationData();
int i = 0;
FindString Next;
do
{
Substitute_String substring;
for (vector<Substitute_String>::iterator iter = SSL.begin(); iter != SSL.end(); iter++)
{
substring = *iter;
if(CheckLockSymbol_Revised(g_pDicData, substring.firstMark.data,substring.firstMark.rows,substring.firstMark.cols))
substring.existFirstLock = true;
if(CheckLockSymbol_Revised(g_pDicData, substring.lastMark.data,substring.lastMark.rows,substring.lastMark.cols))
substring.existLastLock = true;
if(substring.existFirstLock || substring.existLastLock)
outputList.push_back(removeLocks(substring));
}
if(outputList.size() > 0)
return;//break;
SSL.clear();
double Angle = rData[i] / double(RATIO);
rotated = Rotation(image,Angle);
SSL = Next.GetSubstituteStringList(rotated);
i++;
}
while(i < (int)rData.size());
}
void FindString::GetLockList(Mat image,vector<Mat>& locklist)
{
GetSubstituteStringList(image);
for (vector<Substitute_String>::iterator iter = subStringList.begin(); iter != subStringList.end(); iter++)
{
Substitute_String substring = *iter;
if(!substring.firstMark.empty())
locklist.push_back(substring.firstMark);
if(!substring.lastMark.empty())
locklist.push_back(substring.lastMark);
}
return;
}
void FindString::GetLockListEx(Mat image,vector<Mat>& locklist)
{
vector<Substitute_String> SSL;
SSL = GetSubstituteStringList(image);
RefineRotationData();
vector<double> rData = GetRotationData();
int i = 0;
FindString Next;
do{
for (vector<Substitute_String>::iterator iter = SSL.begin(); iter != SSL.end(); iter++)
{
Substitute_String substring = *iter;
if(!substring.firstMark.empty())
locklist.push_back(substring.firstMark);
if(!substring.lastMark.empty())
locklist.push_back(substring.lastMark);
}
Mat rotated;
double Angle = rData[i] / double(RATIO);
rotated = Rotation(image,Angle);
SSL = Next.GetSubstituteStringList(rotated);
i++;
}
while(i < (int)rData.size());
return;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
void Refinebyfeatures(Mat in,Mat& out)
{
#if 0
int top,left,right,bottom;
int *sum_h, *sum_v;
sum_h = new int[in.rows];
sum_v = new int[in.cols];
if(countNonZero(in) < OCR_REASONABLE_COUNT)
return;
////////Get Top & Bottom (an info about the horizontal location of an assumed StringRect)///////////////////////////
calcHorizontalProjection(in,sum_h,OCR_PIXEL_MAX);
blur_(sum_h,in.rows);
lower(sum_h,in.rows);//added by kojy-20150725
findTopBottom(sum_h,in.rows,top,bottom);
//top -= USER_DEFINED__H_MARGIN;
//bottom += USER_DEFINED__H_MARGIN;
if(top < 0) top = 0;
if(bottom >= in.rows) bottom = in.rows - 1;
/////////Get Left & Right (an info about the vertical location of an assumed StringRect)///////////////////////////
Mat croppedbyTopBottom(in,cv::Rect(0,top,in.cols,bottom - top));
calcVerticalProjection(croppedbyTopBottom,sum_v,OCR_PIXEL_MAX);
findLeftRight(sum_v,croppedbyTopBottom.cols,left,right);
////////////////////////////kjy-todo-2015.05.08///////////
//int adaptvie_margin = (int)(USER_DEFINED__W_MARGIN * (double(bottom - top) / 21.0));
//adaptvie_margin = adaptvie_margin > USER_DEFINED__W_MARGIN ? (int)USER_DEFINED__W_MARGIN:adaptvie_margin;
//left -= adaptvie_margin;
//right += adaptvie_margin;
////////////////////////////////////////////////
if(left < 0) left = 0;
if(right >= in.cols) right = in.cols - 1;
if( 2 * (bottom - top ) < in.rows|| 2 * (right - left) < in.cols)
{
delete []sum_v;
delete []sum_h;
return;
}
/////////Form the rect of the suspicious StringRect///////////////////////////////
cv::Rect rect = cv::Rect(left,top,right - left,bottom - top);
Mat cropped(out,rect);
#ifndef OCR_ONCE
imshow("cropped",cropped);
waitKey(1000);
#endif
cropped.copyTo(out);
delete []sum_v;
delete []sum_h;
return;
#else
Mat thr;
threshold(in,thr,128,255,THRESH_BINARY_INV);
int *sum_h = new int[thr.rows],top,bottom;
calcHorizontalProjection(thr,sum_h,OCR_PIXEL_MAX);
findTopBottom(sum_h,thr.rows,top,bottom);
#ifdef IN_DEV
if((top + LINE_HEIGHT) > bottom &&
top > 0 &&
bottom < in.rows)
{
for(int i = top; i <= bottom; i++)
sum_h[i] = 0;
findTopBottom(sum_h,thr.rows,top,bottom);
}
#endif
top -= 2;//USER_DEFINED__H_MARGIN;
bottom += 2;//USER_DEFINED__H_MARGIN;
if(top < 0)
top = 0;
if(bottom >= thr.rows)
bottom = thr.rows - 1;
Mat tmp(thr,cv::Rect(0,top,thr.cols,bottom - top));
int *sum_v = new int[tmp.cols],left,right;
calcVerticalProjection(tmp,sum_v,OCR_PIXEL_MAX);
findLeftRight(sum_v,tmp.cols,left,right);
left -= 2;//USER_DEFINED__W_MARGIN;
right += 2;//USER_DEFINED__W_MARGIN;
if(left < 0)
left = 0;
if(right >= tmp.cols)
right = tmp.cols - 1;
if((bottom - top) * REASONABLE < (right - left))
{
delete []sum_h;
delete []sum_v;
return;
}
Mat tmp_(out,cv::Rect(left, top, right - left, bottom - top));
tmp_.copyTo(out);
/*threshold(tmp_,out,128,255,THRESH_BINARY_INV);*/
imshow("cropped",out);
waitKey(1000);
delete []sum_v;
delete []sum_h;
return;
#endif
}
BOOL existsLockSymbol(Mat& roi_)
{
/////////////////////////////////////////////////////////
BOOL hasHeadLock = FALSE;
BOOL hasTailLock = FALSE;
/////////////////////////////////////////////
Mat string = roi_;
cv::Size size;
size.width = string.cols;
size.height = string.rows;
//Search-process
int left,right,top = 0,bottom,height = string.rows,width = string.cols;
int top_,bottom_;
int* sum_v,* sum_h;;
sum_v = new int[width];
sum_h = new int[height];
calcVerticalProjection(string,sum_v,OCR_PIXEL_MIN);
lower(sum_v,string.cols);
#ifdef OCR_DEBUG
showArray_v("v",sum_v,string.cols);//
#endif
cv::Rect fl1,fl2,ll1,ll2;
Mat croppedfirstlock,croppedlastlock;
getFirstLock(sum_v,string.cols,left,right);
///kjy-todo-2015.4.28//////
if(left < right)
{
fl1 = cv::Rect(left,top,right - left,height);
#if 1
Mat firstLock(string,fl1);
#else
Mat firstLock;
Mat(pe, fl1).copyTo(firstLock);
#endif
threshold(firstLock,firstLock,128,255,THRESH_BINARY);
///////////////////removing background///////////////////
removeBoundaryNoise(firstLock);
//
calcHorizontalProjection(firstLock,sum_h,OCR_PIXEL_MIN);
findLeftRight(sum_h,height,top_,bottom_);
if(top_ < bottom_)
{
fl2 = cv::Rect(0,top_,firstLock.cols,bottom_ - top_);
Mat croppedfirst_lock(firstLock,fl2);
croppedfirst_lock.copyTo(croppedfirstlock);
}
}
////////////////////////////////////
getLastLock(sum_v,string.cols,left,right);
if(left < right)
{
ll1 = cv::Rect(left,top,right - left,string.rows);
#if 1
Mat lastLock(string,ll1);
#else
Mat lastLock;
Mat(pe,ll1).copyTo(lastLock);
#endif
threshold(lastLock,lastLock,128,255,THRESH_BINARY);
//
removeBoundaryNoise(lastLock);
//
calcHorizontalProjection(lastLock,sum_h,OCR_PIXEL_MIN);
findLeftRight(sum_h,height,top_,bottom_);
if(top_ < bottom_)
{
ll2 = cv::Rect(0,top_,lastLock.cols,bottom_ - top_);
Mat croppedlast_lock(lastLock,ll2);
croppedlast_lock.copyTo(croppedlastlock);
#ifdef OCR_TEST
imshow("croppedlastlock",croppedlastlock);
waitKey(1000);
#endif
}
}
//////////////////////////////////
#ifdef OCR_NEVER
imshow("croppedfirstlock",croppedfirstlock);
imshow("croppedlastlock",croppedlastlock);
waitKey(1000);
#endif
if(croppedfirstlock.rows > OCR_REASONABLE_LOCK_HEIGHT_LOWER_BOUND * double(size.height) &&
croppedfirstlock.cols > OCR_REASONABLE_LOCK_WIDTH_LOWER_BOUND * double(size.width) &&
croppedfirstlock.cols < OCR_REASONABLE_LOCK_WIDTH_UPPER_BOUND * double(size.width) &&
(croppedfirstlock.rows / (croppedfirstlock.cols + 1) < 7) &&
(croppedfirstlock.cols / (croppedfirstlock.rows + 1) < 7) &&
croppedfirstlock.rows > 4 && croppedfirstlock.cols > 4)
{
resize(croppedfirstlock,croppedfirstlock,cv::Size(croppedfirstlock.cols * 2,croppedfirstlock.rows * 2));
threshold(croppedfirstlock,croppedfirstlock,128,255,THRESH_BINARY);
if(CheckLockSymbol_Revised(g_pDicData, croppedfirstlock.data,croppedfirstlock.rows,croppedfirstlock.cols))
hasHeadLock = TRUE;
}
if(croppedlastlock.rows > OCR_REASONABLE_LOCK_HEIGHT_LOWER_BOUND * double(size.height) &&
croppedlastlock.cols > OCR_REASONABLE_LOCK_WIDTH_LOWER_BOUND * double(size.width) &&
croppedlastlock.cols < OCR_REASONABLE_LOCK_WIDTH_UPPER_BOUND * double(size.width) &&
(croppedlastlock.rows / (croppedlastlock.cols + 1) < 4) &&
(croppedlastlock.cols / (croppedlastlock.rows + 1) < 4) &&
croppedlastlock.rows > 4 && croppedlastlock.cols > 4)
{
resize(croppedlastlock,croppedlastlock,cv::Size(croppedlastlock.cols * 2,croppedlastlock.rows * 2));
threshold(croppedlastlock,croppedlastlock,128,255,THRESH_BINARY);
if(CheckLockSymbol_Revised(g_pDicData, croppedlastlock.data,croppedlastlock.rows,croppedlastlock.cols))
hasTailLock = TRUE;
}
////////////////////
delete []sum_h;
delete []sum_v;
//cropping the origins
left = fl1.x + fl1.width;
right = ll1.x;
top = fl1.y < ll1.y ? fl1.y : ll1.y;
bottom = (fl1.y + fl1.height);
bottom_ = (ll1.y + ll1.height);
bottom = bottom > bottom_ ? bottom : bottom_;
if(hasHeadLock && hasTailLock)
{
Mat cropped_roi(string,cv::Rect(left,top,right - left,bottom - top));
cropped_roi.copyTo(roi_);
return TRUE;
}
if(hasHeadLock)
{
Mat cropped_roi(string,cv::Rect(left ,0, string.cols - left, string.rows));
cropped_roi.copyTo(roi_);
return TRUE;
}
if(hasTailLock)
{
Mat cropped_roi(string,cv::Rect(0, 0, right, string.rows));
cropped_roi.copyTo(roi_);
return TRUE;
}
return FALSE;
} | 29.697408 | 166 | 0.642162 | [
"object",
"vector"
] |
f648e5e8df544e478363be8aa40b482d743a041b | 9,349 | hxx | C++ | admin/netui/common/h/blttd.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/netui/common/h/blttd.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/netui/common/h/blttd.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**********************************************************************/
/** Microsoft Windows/NT **/
/** Copyright(c) Microsoft Corp., 1991 **/
/**********************************************************************/
/*
blttd.hxx
BLT time/date control object header file
FILE HISTORY:
terryk 01-Jun-91 Created
terryk 11-Jul-91 Set up as a group
terryk 12-Aug-91 Remove BLT_TIMER class from the TIME_DATE
control
terryk 17-Apr-92 passed intlprof object to the classes
beng 13-Aug-1992 Disabled unused TIME_DATE_DIALOG
Yi-HsinS 08-Dec-1992 Fix due to WIN_TIME class change
*/
#ifndef _BLTTD_HXX_
#define _BLTTD_HXX_
#include "ctime.hxx"
#include "intlprof.hxx"
/**********************************************************************
NAME: BLT_TIME_SPIN_GROUP
SYNOPSIS: display the current time and let the user uses the
spin button to change the time
INTERFACE: BLT_TIME_SPIN_GROUP() - constructor
~BLT_TIME_SPIN_GROUP() - destructor
IsValid() - return TRUE if the time in the time control
panel is valid
TimeClick() - set the group values to the current time
IsModified() - return whether the group has been changed
by the user or not
QueryHour() - return the hour value
QueryMin() - return the minute value
QuerySec() - return the second value
PARENT: PUSH_BUTTON, CUSTOM_CONTROL
USES: SPIN_GROUP, SPIN_SLE_NUM, SPIN_SLT_SEPARATOR, XYPOINT,
XYDIMENSION, OWNER_WINDOW
HISTORY:
terryk 01-Jun-91 Created
terryk 11-Jul-91 Make it to a group
beng 14-Aug-1992 Pretty up the painting a bit
jonn 5-Sep-95 Use BLT_BACKGROUND_EDIT
**********************************************************************/
DLL_CLASS BLT_TIME_SPIN_GROUP: public CONTROL_GROUP
{
private:
SPIN_GROUP _sbControl; // spin button
SPIN_SLE_NUM_VALID _ssnHour; // hour field
SPIN_SLT_SEPARATOR _ssltSeparator1; // separator 1
SPIN_SLE_NUM_VALID _ssnMin; // minute field
SPIN_SLT_SEPARATOR _ssltSeparator2; // separator 2
SPIN_SLE_NUM_VALID _ssnSec; // second field
SPIN_SLE_STR *_psssAMPM; // AMPM field
BLT_BACKGROUND_EDIT _bkgndFrame; // framing rectangle
BOOL _f24Hour; // 24 hour format flag
BOOL IsConstructionFail( CONTROL_WINDOW * pwin );
protected:
virtual VOID SaveValue( BOOL fInvisible = TRUE );
virtual VOID RestoreValue( BOOL fInvisible = TRUE );
virtual VOID SetControlValueFocus();
public:
BLT_TIME_SPIN_GROUP( OWNER_WINDOW *powin, const INTL_PROFILE & intlprof,
CID cidSpinButton,
CID cidUpArrow, CID cidDownArrow, CID cidHour,
CID cidSeparator1, CID cidMin, CID cidSeparator2,
CID cidSec, CID cidAMPM, CID cidFrame );
~BLT_TIME_SPIN_GROUP();
BOOL IsValid();
APIERR SetCurrentTime();
BOOL IsModified()
{ return _sbControl.IsModified();}
INT QueryHour() const;
INT QueryMin() const;
INT QuerySec() const;
VOID SetHour( INT nHour );
VOID SetMinute( INT nMinute );
VOID SetSecond( INT nSecond );
};
/**********************************************************************
NAME: BLT_DATE_SPIN_GROUP
SYNOPSIS: display the current month/day/year and let the user uses
the spin button to change the time
INTERFACE: BLT_DATE_SPIN_GROUP() - constructor
~BLT_DATE_SPIN_GROUP() - destructor
IsValid() - check the inputed date is correct or not
TimeClick() - update the spin group values
IsModified() - return whether the spin group has been
modified by the user
QueryYear() - return the year
QueryMonth() - return the month
QueryDay() - return the day
PARENT: PUSH_BUTTON, CUSTOM_CONTROL
USES: SPIN_GROUP, SPIN_SLE_NUM, SPIN_SLT_SEPARATOR, OWNER_WINDOW,
XYPOINT, XYDIMENSION
HISTORY:
terryk 1-Jun-91 Created
beng 14-Aug-1992 Pretty up the painting a bit
jonn 5-Sep-95 Use BLT_BACKGROUND_EDIT
**********************************************************************/
DLL_CLASS BLT_DATE_SPIN_GROUP: public CONTROL_GROUP
{
private:
SPIN_GROUP _sbControl; // spin group
SPIN_SLE_NUM_VALID _ssnMonth; // month field
SPIN_SLT_SEPARATOR _ssltSeparator1; // separator1
SPIN_SLE_NUM_VALID _ssnDay; // day field
SPIN_SLT_SEPARATOR _ssltSeparator2; // separator2
SPIN_SLE_NUM_VALID _ssnYear; // Year field
BLT_BACKGROUND_EDIT _bkgndFrame; // framing rectangle
BOOL _fYrCentury; // Year 4 digits or 2 digits
APIERR PlaceControl( INT nPos, OWNER_WINDOW * powin,
const INTL_PROFILE & intlprof,
const XYPOINT & xyYear, const XYDIMENSION & dxyYear,
const XYPOINT & xyMonth, const XYDIMENSION & dxyMonth,
const XYPOINT & xyDay, const XYDIMENSION & dxyDay);
BOOL IsConstructionFail( CONTROL_WINDOW * pwin );
protected:
virtual VOID SaveValue( BOOL fInvisible = TRUE );
virtual VOID RestoreValue( BOOL fInvisible = TRUE );
virtual VOID SetControlValueFocus();
public:
BLT_DATE_SPIN_GROUP( OWNER_WINDOW *powin, const INTL_PROFILE & intlprof,
CID cidSpinButton,
CID cidUpArrow, CID cidDownArrow, CID cidMonth,
CID cidSeparator1, CID cidDay, CID cidSeparator2,
CID cidYear, CID cidFrame);
~BLT_DATE_SPIN_GROUP();
BOOL IsValid();
APIERR SetCurrentDay();
BOOL IsModified()
{
return _sbControl.IsModified();
}
INT QueryYear() const;
INT QueryMonth() const;
INT QueryDay() const;
VOID SetYear( INT nYear );
VOID SetMonth( INT nMonth );
VOID SetDay( INT nDay );
};
#if 0
/**********************************************************************
NAME: TIME_DATE_DIALOG
SYNOPSIS: Time and date control panel
INTERFACE:
TIME_DATE_DIALOG() - constructor
~TIME_DATE_DIALOG() - destructor
QueryHour() - return hour (0-24)
QueryMin() - return minute (0-59)
QuerySec() - return second (0-59)
QueryYear() - return year
QueryMonth() - return month(1-12)
QueryDay() - return Day (1-31)
PARENT: DIALOG_WINDOW
USES: BLT_TIME_SPIN_GROUP, BLT_DATE_SPIN_GROUP, WINDOW_TIMER
CAVEATS: This class should be the parent class of TIME/DATE
control panel. The user can add OK or Cancel button
into the dialog book by subclassing this class.
HISTORY:
terryk 11-Jul-91 Created
rustanl 11-Sep-91 Changed BLT_TIMER to WINDOW_TIMER
beng 05-Oct-1991 Win32 conversion
**********************************************************************/
DLL_CLASS TIME_DATE_DIALOG: public DIALOG_WINDOW
{
private:
BLT_TIME_SPIN_GROUP _TimeSG;
BLT_DATE_SPIN_GROUP _DateSG;
WINDOW_TIMER *_pTimer;
protected:
virtual BOOL OnTimer( const TIMER_EVENT & e );
public:
TIME_DATE_DIALOG( const TCHAR * pszResourceName, HWND hwndOwner,
const INTL_PROFILE & intlprof,
CID cidTimeSpinButton,
CID cidTimeUpArrow, CID cidTimeDownArrow, CID cidHour,
CID cidTimeSeparator1, CID cidMin, CID cidTimeSeparator2,
CID cidSec, CID cidAMPM,
CID cidDateSpinButton,
CID cidDateUpArrow, CID cidDateDownArrow, CID cidMonth,
CID cidDateSeparator1, CID cidDay, CID cidDateSeparator2,
CID cidYear);
~TIME_DATE_DIALOG();
INT QueryHour() const
{ return _TimeSG.QueryHour(); }
INT QueryMin() const
{ return _TimeSG.QueryMin(); }
INT QuerySec() const
{ return _TimeSG.QuerySec(); }
INT QueryYear() const
{ return _DateSG.QueryYear(); }
INT QueryMonth() const
{ return _DateSG.QueryMonth(); }
INT QueryDay() const
{ return _DateSG.QueryDay(); }
BOOL IsValid()
{
// TimerSG is always valid
return _DateSG.IsValid();
}
};
#endif // disabled unused code
#endif // _BLTTD_HXX_
| 34.884328 | 80 | 0.536207 | [
"object"
] |
f64b4164b9e6d75eabccdf6a423889c52c86b04d | 45,147 | cpp | C++ | src/ascent/runtimes/flow_filters/ascent_runtime_dray_filters.cpp | ax3l/ascent | 2c70bac3b9ee21e9472c4725841bd096e9da653d | [
"BSD-3-Clause"
] | null | null | null | src/ascent/runtimes/flow_filters/ascent_runtime_dray_filters.cpp | ax3l/ascent | 2c70bac3b9ee21e9472c4725841bd096e9da653d | [
"BSD-3-Clause"
] | null | null | null | src/ascent/runtimes/flow_filters/ascent_runtime_dray_filters.cpp | ax3l/ascent | 2c70bac3b9ee21e9472c4725841bd096e9da653d | [
"BSD-3-Clause"
] | null | null | null | //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2015-2019, Lawrence Livermore National Security, LLC.
//
// Produced at the Lawrence Livermore National Laboratory
//
// LLNL-CODE-716457
//
// All rights reserved.
//
// This file is part of Ascent.
//
// For details, see: http://ascent.readthedocs.io/.
//
// Please also read ascent/LICENSE
//
// 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 disclaimer below.
//
// * 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.
//
// * Neither the name of the LLNS/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 LAWRENCE LIVERMORE NATIONAL SECURITY,
// LLC, 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.
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//-----------------------------------------------------------------------------
///
/// file: ascent_runtime_dray_filters.cpp
///
//-----------------------------------------------------------------------------
#include "ascent_runtime_dray_filters.hpp"
//-----------------------------------------------------------------------------
// thirdparty includes
//-----------------------------------------------------------------------------
// conduit includes
#include <conduit.hpp>
#include <conduit_blueprint.hpp>
//-----------------------------------------------------------------------------
// ascent includes
//-----------------------------------------------------------------------------
#include <ascent_logging.hpp>
#include <ascent_string_utils.hpp>
#include <ascent_runtime_param_check.hpp>
#include <ascent_runtime_utils.hpp>
#include <ascent_png_encoder.hpp>
#include <flow_graph.hpp>
#include <flow_workspace.hpp>
// mpi
#ifdef ASCENT_MPI_ENABLED
#include <mpi.h>
#endif
#if defined(ASCENT_VTKM_ENABLED)
#include <ascent_vtkh_data_adapter.hpp>
#include <ascent_runtime_conduit_to_vtkm_parsing.hpp>
#include <ascent_runtime_blueprint_filters.hpp>
#endif
#if defined(ASCENT_MFEM_ENABLED)
#include <ascent_mfem_data_adapter.hpp>
#endif
#include <runtimes/ascent_data_object.hpp>
#include <runtimes/ascent_dray_data_adapter.hpp>
#include <dray/dray.hpp>
#include <dray/data_set.hpp>
#include <dray/filters/mesh_boundary.hpp>
#include <dray/filters/reflect.hpp>
#include <dray/rendering/renderer.hpp>
#include <dray/rendering/surface.hpp>
#include <dray/rendering/slice_plane.hpp>
#include <dray/rendering/scalar_renderer.hpp>
#include <dray/rendering/partial_renderer.hpp>
#include <dray/io/blueprint_reader.hpp>
#include <vtkh/vtkh.hpp>
#include <vtkh/compositing/Compositor.hpp>
#include <vtkh/compositing/PartialCompositor.hpp>
#include <vtkh/compositing/PayloadCompositor.hpp>
using namespace conduit;
using namespace std;
using namespace flow;
//-----------------------------------------------------------------------------
// -- begin ascent:: --
//-----------------------------------------------------------------------------
namespace ascent
{
//-----------------------------------------------------------------------------
// -- begin ascent::runtime --
//-----------------------------------------------------------------------------
namespace runtime
{
//-----------------------------------------------------------------------------
// -- begin ascent::runtime::filters --
//-----------------------------------------------------------------------------
namespace filters
{
namespace detail
{
std::string
dray_color_table_surprises(const conduit::Node &color_table)
{
std::string surprises;
std::vector<std::string> valid_paths;
valid_paths.push_back("name");
valid_paths.push_back("reverse");
std::vector<std::string> ignore_paths;
ignore_paths.push_back("control_points");
surprises += surprise_check(valid_paths, ignore_paths, color_table);
if(color_table.has_path("control_points"))
{
std::vector<std::string> c_valid_paths;
c_valid_paths.push_back("type");
c_valid_paths.push_back("alpha");
c_valid_paths.push_back("color");
c_valid_paths.push_back("position");
const conduit::Node &control_points = color_table["control_points"];
const int num_points = control_points.number_of_children();
for(int i = 0; i < num_points; ++i)
{
const conduit::Node &point = control_points.child(i);
surprises += surprise_check(c_valid_paths, point);
}
}
return surprises;
}
std::vector<dray::Vec<float,3>>
planes(const conduit::Node ¶ms, const dray::AABB<3> bounds)
{
using Vec3f = dray::Vec<float,3>;
Vec3f center = bounds.center();
Vec3f x_point = center;
Vec3f y_point = center;
Vec3f z_point = center;
const float eps = 1e-5; // ensure that the slice is always inside the data set
if(params.has_path("x_offset"))
{
float offset = params["x_offset"].to_float32();
std::max(-1.f, std::min(1.f, offset));
float t = (offset + 1.f) / 2.f;
t = std::max(0.f + eps, std::min(1.f - eps, t));
x_point[0] = bounds.m_ranges[0].min() + t * (bounds.m_ranges[0].length());
}
if(params.has_path("y_offset"))
{
float offset = params["y_offset"].to_float32();
std::max(-1.f, std::min(1.f, offset));
float t = (offset + 1.f) / 2.f;
t = std::max(0.f + eps, std::min(1.f - eps, t));
y_point[1] = bounds.m_ranges[1].min() + t * (bounds.m_ranges[1].length());
}
if(params.has_path("z_offset"))
{
float offset = params["z_offset"].to_float32();
std::max(-1.f, std::min(1.f, offset));
float t = (offset + 1.f) / 2.f;
t = std::max(0.f + eps, std::min(1.f - eps, t));
z_point[2] = bounds.m_ranges[2].min() + t * (bounds.m_ranges[2].length());
}
std::vector<Vec3f> points;
points.push_back(x_point);
points.push_back(y_point);
points.push_back(z_point);
return points;
}
std::vector<float>
parse_camera(const conduit::Node camera_node, dray::Camera &camera)
{
typedef dray::Vec<float,3> Vec3f;
//
// Get the optional camera parameters
//
if(camera_node.has_child("look_at"))
{
conduit::Node n;
camera_node["look_at"].to_float64_array(n);
const float64 *coords = n.as_float64_ptr();
Vec3f look_at{float(coords[0]), float(coords[1]), float(coords[2])};
camera.set_look_at(look_at);
}
if(camera_node.has_child("position"))
{
conduit::Node n;
camera_node["position"].to_float64_array(n);
const float64 *coords = n.as_float64_ptr();
Vec3f position{float(coords[0]), float(coords[1]), float(coords[2])};
camera.set_pos(position);
}
if(camera_node.has_child("up"))
{
conduit::Node n;
camera_node["up"].to_float64_array(n);
const float64 *coords = n.as_float64_ptr();
Vec3f up{float(coords[0]), float(coords[1]), float(coords[2])};
up.normalize();
camera.set_up(up);
}
if(camera_node.has_child("fov"))
{
camera.set_fov(camera_node["fov"].to_float64());
}
// this is an offset from the current azimuth
if(camera_node.has_child("azimuth"))
{
double azimuth = camera_node["azimuth"].to_float64();
camera.azimuth(azimuth);
}
if(camera_node.has_child("elevation"))
{
double elevation = camera_node["elevation"].to_float64();
camera.elevate(elevation);
}
if(camera_node.has_child("zoom"))
{
float zoom = camera_node["zoom"].to_float32();
camera.set_zoom(zoom);
}
//
// With a new potential camera position. We need to reset the
// clipping plane as not to cut out part of the data set
//
// clipping defaults
std::vector<float> clipping(2);
clipping[0] = 0.01f;
clipping[1] = 1000.f;
if(camera_node.has_child("near_plane"))
{
clipping[0] = camera_node["near_plane"].to_float64();
}
if(camera_node.has_child("far_plane"))
{
clipping[1] = camera_node["far_plane"].to_float64();
}
return clipping;
}
dray::ColorTable
parse_color_table(const conduit::Node &color_table_node)
{
// default name
std::string color_map_name = "cool2warm";
if(color_table_node.number_of_children() == 0)
{
ASCENT_INFO("Color table node is empty (no children). Defaulting to "
<<color_map_name);
}
bool name_provided = false;
if(color_table_node.has_child("name"))
{
std::string name = color_table_node["name"].as_string();
name_provided = true;
std::vector<std::string> valid_names = dray::ColorTable::get_presets();
auto loc = find(valid_names.begin(), valid_names.end(), name);
if(loc != valid_names.end())
{
color_map_name = name;
}
else
{
std::stringstream ss;
ss<<"[";
for(int i = 0; i < valid_names.size(); ++i)
{
ss<<valid_names[i];
if(i==valid_names.size()-1)
{
ss<<"]";
}
else
{
ss<<",";
}
}
ASCENT_INFO("Invalid color table name '"<<name
<<"'. Defaulting to "<<color_map_name
<<". known names: "<<ss.str());
}
}
dray::ColorTable color_table(color_map_name);
if(color_table_node.has_child("control_points"))
{
bool clear = false;
bool clear_alphas = false;
// check to see if we have rgb points and clear the table
NodeConstIterator itr = color_table_node.fetch("control_points").children();
while(itr.has_next())
{
const Node &peg = itr.next();
if (peg["type"].as_string() == "rgb")
{
clear = true;
}
if (peg["type"].as_string() == "alpha")
{
clear_alphas = true;
}
}
if(clear && !name_provided)
{
color_table.clear_colors();
}
if(clear_alphas)
{
color_table.clear_alphas();
}
itr = color_table_node.fetch("control_points").children();
while(itr.has_next())
{
const Node &peg = itr.next();
if(!peg.has_child("position"))
{
ASCENT_WARN("Color map control point must have a position");
}
float64 position = peg["position"].to_float64();
if(position > 1.0 || position < 0.0)
{
ASCENT_WARN("Cannot add color map control point position "
<< position
<< ". Must be a normalized scalar.");
}
if (peg["type"].as_string() == "rgb")
{
conduit::Node n;
peg["color"].to_float32_array(n);
const float *color = n.as_float32_ptr();
dray::Vec<float,3> ecolor({color[0], color[1], color[2]});
for(int i = 0; i < 3; ++i)
{
ecolor[i] = std::min(1.f, std::max(ecolor[i], 0.f));
}
color_table.add_point(position, ecolor);
}
else if (peg["type"].as_string() == "alpha")
{
float alpha = peg["alpha"].to_float32();
alpha = std::min(1.f, std::max(alpha, 0.f));
color_table.add_alpha(position, alpha);
}
else
{
ASCENT_WARN("Unknown color table control point type " << peg["type"].as_string()<<
"\nValid types are 'alpha' and 'rgb'");
}
}
}
if(color_table_node.has_child("reverse"))
{
if(color_table_node["reverse"].as_string() == "true")
{
color_table.reverse();
}
}
return color_table;
}
dray::Framebuffer partials_to_framebuffer(const std::vector<vtkh::VolumePartial<float>> &input,
const int width,
const int height)
{
dray::Framebuffer fb(width, height);
fb.clear();
const int size = input.size();
dray::Vec<float,4> *colors = fb.colors().get_host_ptr();
float *depths = fb.depths().get_host_ptr();
#ifdef ASCENT_USE_OPENMP
#pragma omp parallel for
#endif
for(int i = 0; i < size; ++i)
{
const int id = input[i].m_pixel_id;
colors[id][0] = input[i].m_pixel[0];
colors[id][1] = input[i].m_pixel[1];
colors[id][2] = input[i].m_pixel[2];
colors[id][3] = input[i].m_alpha;
depths[id] = input[i].m_depth;
}
return fb;
}
void
parse_params(const conduit::Node ¶ms,
DRayCollection *dcol,
const conduit::Node *meta,
dray::Camera &camera,
dray::ColorMap &color_map,
std::string &field_name,
std::string &image_name)
{
field_name = params["field"].as_string();
int width = 512;
int height = 512;
if(params.has_path("image_width"))
{
width = params["image_width"].to_int32();
}
if(params.has_path("image_height"))
{
height = params["image_height"].to_int32();
}
camera.set_width(width);
camera.set_height(height);
dray::AABB<3> bounds = dcol->get_global_bounds();
camera.reset_to_bounds(bounds);
std::vector<float> clipping(2);
clipping[0] = 0.01f;
clipping[1] = 1000.f;
if(params.has_path("camera"))
{
const conduit::Node &n_camera = params["camera"];
clipping = detail::parse_camera(n_camera, camera);
}
dray::Range scalar_range = dcol->get_global_range(field_name);
dray::Range range;
if(params.has_path("min_value"))
{
range.include(params["min_value"].to_float32());
}
else
{
range.include(scalar_range.min());
}
if(params.has_path("max_value"))
{
range.include(params["max_value"].to_float32());
}
else
{
range.include(scalar_range.max());
}
color_map.scalar_range(range);
bool log_scale = false;
if(params.has_path("log_scale"))
{
if(params["log_scale"].as_string() == "true")
{
log_scale = true;
}
}
color_map.log_scale(log_scale);
if(params.has_path("color_table"))
{
color_map.color_table(parse_color_table(params["color_table"]));
}
int cycle = 0;
if(meta->has_path("cycle"))
{
cycle = (*meta)["cycle"].as_int32();
}
image_name = params["image_prefix"].as_string();
image_name = expand_family_name(image_name, cycle);
}
void convert_partials(std::vector<dray::Array<dray::VolumePartial>> &input,
std::vector<std::vector<vtkh::VolumePartial<float>>> &output)
{
size_t total_size = 0;
const int in_size = input.size();
std::vector<size_t> offsets;
offsets.resize(in_size);
output.resize(1);
for(size_t i = 0; i< in_size; ++i)
{
offsets[i] = total_size;
total_size += input[i].size();
}
output[0].resize(total_size);
for(size_t a = 0; a < in_size; ++a)
{
const dray::VolumePartial *partial_ptr = input[a].get_host_ptr_const();
const size_t offset = offsets[a];
const size_t size = input[a].size();
#ifdef ASCENT_USE_OPENMP
#pragma omp parallel for
#endif
for(int i = 0; i < size; ++i)
{
const size_t index = offset + i;
const dray::VolumePartial p = partial_ptr[i];
output[0][index].m_pixel_id = p.m_pixel_id;
output[0][index].m_depth = p.m_depth;
output[0][index].m_pixel[0] = p.m_color[0];
output[0][index].m_pixel[1] = p.m_color[1];
output[0][index].m_pixel[2] = p.m_color[2];
output[0][index].m_alpha = p.m_color[3];
}
}
}
vtkh::PayloadImage * convert(dray::ScalarBuffer &result)
{
const int num_fields = result.m_scalars.size();
const int payload_size = num_fields * sizeof(float);
vtkm::Bounds bounds;
bounds.X.Min = 1;
bounds.Y.Min = 1;
bounds.X.Max = result.m_width;
bounds.Y.Max = result.m_height;
const size_t size = result.m_width * result.m_height;
vtkh::PayloadImage *image = new vtkh::PayloadImage(bounds, payload_size);
unsigned char *loads = &image->m_payloads[0];
const float* dbuffer = result.m_depths.get_host_ptr();
memcpy(&image->m_depths[0], dbuffer, sizeof(float) * size);
// copy scalars into payload
std::vector<float*> buffers;
for(int i = 0; i < num_fields; ++i)
{
float* buffer = result.m_scalars[i].get_host_ptr();
buffers.push_back(buffer);
}
#ifdef ASCENT_USE_OPENMP
#pragma omp parallel for
#endif
for(size_t x = 0; x < size; ++x)
{
for(int i = 0; i < num_fields; ++i)
{
const size_t offset = x * payload_size + i * sizeof(float);
memcpy(loads + offset, &buffers[i][x], sizeof(float));
}
}
return image;
}
dray::ScalarBuffer convert(vtkh::PayloadImage &image, std::vector<std::string> &names)
{
dray::ScalarBuffer result;
result.m_names = names;
const int num_fields = names.size();
const int dx = image.m_bounds.X.Max - image.m_bounds.X.Min + 1;
const int dy = image.m_bounds.Y.Max - image.m_bounds.Y.Min + 1;
const int size = dx * dy;
result.m_width = dx;
result.m_height = dy;
std::vector<float*> buffers;
for(int i = 0; i < num_fields; ++i)
{
dray::Array<float> array;
array.resize(size);
result.m_scalars.push_back(array);
float* buffer = result.m_scalars[i].get_host_ptr();
buffers.push_back(buffer);
}
const unsigned char *loads = &image.m_payloads[0];
const size_t payload_size = image.m_payload_bytes;
for(size_t x = 0; x < size; ++x)
{
for(int i = 0; i < num_fields; ++i)
{
const size_t offset = x * payload_size + i * sizeof(float);
memcpy(&buffers[i][x], loads + offset, sizeof(float));
}
}
//
result.m_depths.resize(size);
float* dbuffer = result.m_depths.get_host_ptr();
memcpy(dbuffer, &image.m_depths[0], sizeof(float) * size);
return result;
}
}; // namespace detail
//-----------------------------------------------------------------------------
DRayPseudocolor::DRayPseudocolor()
:Filter()
{
// empty
}
//-----------------------------------------------------------------------------
DRayPseudocolor::~DRayPseudocolor()
{
// empty
}
//-----------------------------------------------------------------------------
void
DRayPseudocolor::declare_interface(Node &i)
{
i["type_name"] = "dray_pseudocolor";
i["port_names"].append() = "in";
i["output_port"] = "false";
}
//-----------------------------------------------------------------------------
bool
DRayPseudocolor::verify_params(const conduit::Node ¶ms,
conduit::Node &info)
{
info.reset();
bool res = true;
res &= check_string("field",params, info, true);
res &= check_string("image_prefix",params, info, true);
res &= check_numeric("min_value",params, info, false);
res &= check_numeric("max_value",params, info, false);
res &= check_numeric("image_width",params, info, false);
res &= check_numeric("image_height",params, info, false);
res &= check_string("log_scale",params, info, false);
std::vector<std::string> valid_paths;
std::vector<std::string> ignore_paths;
valid_paths.push_back("field");
valid_paths.push_back("image_prefix");
valid_paths.push_back("min_value");
valid_paths.push_back("max_value");
valid_paths.push_back("image_width");
valid_paths.push_back("image_height");
valid_paths.push_back("log_scale");
// filter knobs
valid_paths.push_back("draw_mesh");
valid_paths.push_back("line_thickness");
valid_paths.push_back("line_color");
res &= check_numeric("line_color",params, info, false);
res &= check_numeric("line_thickness",params, info, false);
res &= check_string("draw_mesh",params, info, false);
ignore_paths.push_back("camera");
ignore_paths.push_back("color_table");
std::string surprises = surprise_check(valid_paths, ignore_paths, params);
if(params.has_path("color_table"))
{
surprises += detail::dray_color_table_surprises(params["color_table"]);
}
if(surprises != "")
{
res = false;
info["errors"].append() = surprises;
}
return res;
}
//-----------------------------------------------------------------------------
void
DRayPseudocolor::execute()
{
if(!input(0).check_type<DataObject>())
{
ASCENT_ERROR("dray pseudocolor input must be a DataObject");
}
DataObject *d_input = input<DataObject>(0);
DRayCollection *dcol = d_input->as_dray_collection().get();
int comm_id = -1;
#ifdef ASCENT_MPI_ENABLED
comm_id = flow::Workspace::default_mpi_comm();
#endif
dcol->mpi_comm(comm_id);
bool is_3d = dcol->topo_dims() == 3;
DRayCollection faces = dcol->boundary();
faces.mpi_comm(comm_id);
dray::Camera camera;
dray::ColorMap color_map("cool2warm");
std::string field_name;
std::string image_name;
conduit::Node * meta = graph().workspace().registry().fetch<Node>("metadata");
detail::parse_params(params(),
&faces,
meta,
camera,
color_map,
field_name,
image_name);
bool draw_mesh = false;
if(params().has_path("draw_mesh"))
{
if(params()["draw_mesh"].as_string() == "true")
{
draw_mesh = true;
}
}
float line_thickness = 0.05f;
if(params().has_path("line_thickness"))
{
line_thickness = params()["line_thickness"].to_float32();
}
dray::Vec<float,4> vcolor = {0.f, 0.f, 0.f, 1.f};
if(params().has_path("line_color"))
{
conduit::Node n;
params()["line_color"].to_float32_array(n);
if(n.dtype().number_of_elements() != 4)
{
ASCENT_ERROR("line_color is expected to be 4 floating "
"point values (RGBA)");
}
const float32 *color = n.as_float32_ptr();
vcolor[0] = color[0];
vcolor[1] = color[1];
vcolor[2] = color[2];
vcolor[3] = color[3];
}
std::vector<dray::Array<dray::Vec<dray::float32,4>>> color_buffers;
std::vector<dray::Array<dray::float32>> depth_buffers;
const int num_domains = faces.m_domains.size();
for(int i = 0; i < num_domains; ++i)
{
dray::Array<dray::Vec<dray::float32,4>> color_buffer;
std::shared_ptr<dray::Surface> surface =
std::make_shared<dray::Surface>(faces.m_domains[i]);
surface->field(field_name);
surface->color_map(color_map);
surface->line_thickness(line_thickness);
surface->line_color(vcolor);
surface->draw_mesh(draw_mesh);
dray::Renderer renderer;
renderer.add(surface);
renderer.use_lighting(is_3d);
dray::Framebuffer fb = renderer.render(camera);
std::vector<float> clipping(2);
float dist = (camera.get_look_at() - camera.get_pos()).magnitude();
clipping[0] = 0.01*dist;
clipping[1] = 100.f*dist;
dray::Array<float32> depth = camera.gl_depth(fb.depths(), clipping[0], clipping[1]);
depth_buffers.push_back(depth);
color_buffers.push_back(fb.colors());
}
#ifdef ASCENT_MPI_ENABLED
vtkh::SetMPICommHandle(comm_id);
#endif
vtkh::Compositor compositor;
compositor.SetCompositeMode(vtkh::Compositor::Z_BUFFER_SURFACE);
for(int i = 0; i < num_domains; ++i)
{
const float * cbuffer =
reinterpret_cast<const float*>(color_buffers[i].get_host_ptr_const());
compositor.AddImage(cbuffer,
depth_buffers[i].get_host_ptr_const(),
camera.get_width(),
camera.get_height());
}
vtkh::Image result = compositor.Composite();
if(vtkh::GetMPIRank() == 0)
{
const float bg_color[4] = {1.f, 1.f, 1.f, 1.f};
result.CompositeBackground(bg_color);
PNGEncoder encoder;
encoder.Encode(&result.m_pixels[0], camera.get_width(), camera.get_height());
image_name = output_dir(image_name, graph());
encoder.Save(image_name + ".png");
}
}
//-----------------------------------------------------------------------------
DRay3Slice::DRay3Slice()
:Filter()
{
// empty
}
//-----------------------------------------------------------------------------
DRay3Slice::~DRay3Slice()
{
// empty
}
//-----------------------------------------------------------------------------
void
DRay3Slice::declare_interface(Node &i)
{
i["type_name"] = "dray_3slice";
i["port_names"].append() = "in";
i["output_port"] = "false";
}
//-----------------------------------------------------------------------------
bool
DRay3Slice::verify_params(const conduit::Node ¶ms,
conduit::Node &info)
{
info.reset();
bool res = true;
res &= check_string("field",params, info, true);
res &= check_string("image_prefix",params, info, true);
res &= check_numeric("min_value",params, info, false);
res &= check_numeric("max_value",params, info, false);
res &= check_numeric("image_width",params, info, false);
res &= check_numeric("image_height",params, info, false);
res &= check_string("log_scale",params, info, false);
std::vector<std::string> valid_paths;
std::vector<std::string> ignore_paths;
valid_paths.push_back("field");
valid_paths.push_back("image_prefix");
valid_paths.push_back("min_value");
valid_paths.push_back("max_value");
valid_paths.push_back("image_width");
valid_paths.push_back("image_height");
valid_paths.push_back("log_scale");
// filter knobs
res &= check_numeric("x_offset",params, info, false);
res &= check_numeric("y_offset",params, info, false);
res &= check_numeric("z_offset",params, info, false);
valid_paths.push_back("x_offset");
valid_paths.push_back("y_offset");
valid_paths.push_back("z_offset");
ignore_paths.push_back("camera");
ignore_paths.push_back("color_table");
std::string surprises = surprise_check(valid_paths, ignore_paths, params);
if(params.has_path("color_table"))
{
surprises += detail::dray_color_table_surprises(params["color_table"]);
}
if(surprises != "")
{
res = false;
info["errors"].append() = surprises;
}
return res;
}
//-----------------------------------------------------------------------------
void
DRay3Slice::execute()
{
if(!input(0).check_type<DataObject>())
{
ASCENT_ERROR("dray 3slice input must be a DataObject");
}
DataObject *d_input = input<DataObject>(0);
DRayCollection *dcol = d_input->as_dray_collection().get();
int comm_id = -1;
#ifdef ASCENT_MPI_ENABLED
comm_id = flow::Workspace::default_mpi_comm();
#endif
dcol->mpi_comm(comm_id);
dray::Camera camera;
dray::ColorMap color_map("cool2warm");
std::string field_name;
std::string image_name;
conduit::Node * meta = graph().workspace().registry().fetch<Node>("metadata");
detail::parse_params(params(),
dcol,
meta,
camera,
color_map,
field_name,
image_name);
dray::AABB<3> bounds = dcol->get_global_bounds();
std::vector<dray::Array<dray::Vec<dray::float32,4>>> color_buffers;
std::vector<dray::Array<dray::float32>> depth_buffers;
using Vec3f = dray::Vec<float,3>;
Vec3f x_normal({1.f, 0.f, 0.f});
Vec3f y_normal({0.f, 1.f, 0.f});
Vec3f z_normal({0.f, 0.f, 1.f});
std::vector<Vec3f> points = detail::planes(params(), bounds);
const int num_domains = dcol->m_domains.size();
for(int i = 0; i < num_domains; ++i)
{
std::shared_ptr<dray::SlicePlane> slicer_x
= std::make_shared<dray::SlicePlane>(dcol->m_domains[i]);
std::shared_ptr<dray::SlicePlane> slicer_y
= std::make_shared<dray::SlicePlane>(dcol->m_domains[i]);
std::shared_ptr<dray::SlicePlane> slicer_z
= std::make_shared<dray::SlicePlane>(dcol->m_domains[i]);
slicer_x->field(field_name);
slicer_y->field(field_name);
slicer_z->field(field_name);
slicer_x->color_map(color_map);
slicer_y->color_map(color_map);
slicer_z->color_map(color_map);
slicer_x->point(points[0]);
slicer_x->normal(x_normal);
slicer_y->point(points[1]);
slicer_y->normal(y_normal);
slicer_z->point(points[2]);
slicer_z->normal(z_normal);
dray::Renderer renderer;
renderer.add(slicer_x);
renderer.add(slicer_y);
renderer.add(slicer_z);
dray::Framebuffer fb = renderer.render(camera);
std::vector<float> clipping(2);
float dist = (camera.get_look_at() - camera.get_pos()).magnitude();
clipping[0] = 0.01*dist;
clipping[1] = 100.f*dist;
dray::Array<float32> depth = camera.gl_depth(fb.depths(), clipping[0], clipping[1]);
depth_buffers.push_back(depth);
color_buffers.push_back(fb.colors());
}
#ifdef ASCENT_MPI_ENABLED
vtkh::SetMPICommHandle(comm_id);
#endif
vtkh::Compositor compositor;
compositor.SetCompositeMode(vtkh::Compositor::Z_BUFFER_SURFACE);
for(int i = 0; i < num_domains; ++i)
{
const float * cbuffer =
reinterpret_cast<const float*>(color_buffers[i].get_host_ptr_const());
compositor.AddImage(cbuffer,
depth_buffers[i].get_host_ptr_const(),
camera.get_width(),
camera.get_height());
}
vtkh::Image result = compositor.Composite();
if(vtkh::GetMPIRank() == 0)
{
const float bg_color[4] = {1.f, 1.f, 1.f, 1.f};
result.CompositeBackground(bg_color);
PNGEncoder encoder;
encoder.Encode(&result.m_pixels[0], camera.get_width(), camera.get_height());
image_name = output_dir(image_name, graph());
encoder.Save(image_name + ".png");
}
}
//-----------------------------------------------------------------------------
DRayVolume::DRayVolume()
:Filter()
{
// empty
}
//-----------------------------------------------------------------------------
DRayVolume::~DRayVolume()
{
// empty
}
//-----------------------------------------------------------------------------
void
DRayVolume::declare_interface(Node &i)
{
i["type_name"] = "dray_volume";
i["port_names"].append() = "in";
i["output_port"] = "false";
}
//-----------------------------------------------------------------------------
bool
DRayVolume::verify_params(const conduit::Node ¶ms,
conduit::Node &info)
{
info.reset();
bool res = true;
res &= check_string("field",params, info, true);
res &= check_string("image_prefix",params, info, true);
res &= check_numeric("min_value",params, info, false);
res &= check_numeric("max_value",params, info, false);
res &= check_numeric("image_width",params, info, false);
res &= check_numeric("image_height",params, info, false);
res &= check_string("log_scale",params, info, false);
std::vector<std::string> valid_paths;
std::vector<std::string> ignore_paths;
valid_paths.push_back("field");
valid_paths.push_back("image_prefix");
valid_paths.push_back("min_value");
valid_paths.push_back("max_value");
valid_paths.push_back("image_width");
valid_paths.push_back("image_height");
valid_paths.push_back("log_scale");
// filter knobs
res &= check_numeric("samples",params, info, false);
res &= check_string("use_lighing",params, info, false);
valid_paths.push_back("samples");
valid_paths.push_back("use_lighting");
ignore_paths.push_back("camera");
ignore_paths.push_back("color_table");
std::string surprises = surprise_check(valid_paths, ignore_paths, params);
if(params.has_path("color_table"))
{
surprises += detail::dray_color_table_surprises(params["color_table"]);
}
if(surprises != "")
{
res = false;
info["errors"].append() = surprises;
}
return res;
}
//-----------------------------------------------------------------------------
void
DRayVolume::execute()
{
if(!input(0).check_type<DataObject>())
{
ASCENT_ERROR("dray 3slice input must be a DataObject");
}
DataObject *d_input = input<DataObject>(0);
DRayCollection *dcol = d_input->as_dray_collection().get();
int comm_id = -1;
#ifdef ASCENT_MPI_ENABLED
comm_id = flow::Workspace::default_mpi_comm();
#endif
dcol->mpi_comm(comm_id);
dray::Camera camera;
dray::ColorMap color_map("cool2warm");
std::string field_name;
std::string image_name;
conduit::Node * meta = graph().workspace().registry().fetch<Node>("metadata");
detail::parse_params(params(),
dcol,
meta,
camera,
color_map,
field_name,
image_name);
dray::AABB<3> bounds = dcol->get_global_bounds();
if(color_map.color_table().number_of_alpha_points() == 0)
{
color_map.color_table().add_alpha (0.f, 0.00f);
color_map.color_table().add_alpha (0.1f, 0.00f);
color_map.color_table().add_alpha (0.3f, 0.05f);
color_map.color_table().add_alpha (0.4f, 0.21f);
color_map.color_table().add_alpha (1.0f, 0.9f);
}
bool use_lighting = false;
if(params().has_path("use_lighting"))
{
if(params()["use_lighting"].as_string() == "true")
{
use_lighting = true;
}
}
int samples = 100;
if(params().has_path("samples"))
{
samples = params()["samples"].to_int32();
}
std::vector<dray::Array<dray::VolumePartial>> dom_partials;
dray::PointLight plight;
plight.m_pos = { 1.2f, -0.15f, 0.4f };
plight.m_amb = { 1.0f, 1.0f, 1.f };
plight.m_diff = { 0.5f, 0.5f, 0.5f };
plight.m_spec = { 0.0f, 0.0f, 0.0f };
plight.m_spec_pow = 90.0;
dray::Array<dray::PointLight> lights;
lights.resize(1);
dray::PointLight *l_ptr = lights.get_host_ptr();
l_ptr[0] = plight;
const int num_domains = dcol->m_domains.size();
for(int i = 0; i < num_domains; ++i)
{
std::shared_ptr<dray::PartialRenderer> volume
= std::make_shared<dray::PartialRenderer>(dcol->m_domains[i]);
dray::Array<dray::Ray> rays;
camera.create_rays (rays);
volume->samples(samples,bounds);
volume->use_lighting(use_lighting);
volume->field(field_name);
volume->color_map() = color_map;
dray::Array<dray::VolumePartial> partials = volume->integrate(rays, lights);
dom_partials.push_back(partials);
}
std::vector<std::vector<vtkh::VolumePartial<float>>> c_partials;
detail::convert_partials(dom_partials, c_partials);
std::vector<vtkh::VolumePartial<float>> result;
vtkh::PartialCompositor<vtkh::VolumePartial<float>> compositor;
#ifdef ASCENT_MPI_ENABLED
compositor.set_comm_handle(comm_id);
#endif
compositor.composite(c_partials, result);
if(vtkh::GetMPIRank() == 0)
{
dray::Framebuffer fb = detail::partials_to_framebuffer(result,
camera.get_width(),
camera.get_height());
fb.composite_background();
image_name = output_dir(image_name, graph());
fb.save(image_name);
}
}
//-----------------------------------------------------------------------------
DRayReflect::DRayReflect()
:Filter()
{
// empty
}
//-----------------------------------------------------------------------------
DRayReflect::~DRayReflect()
{
// empty
}
//-----------------------------------------------------------------------------
void
DRayReflect::declare_interface(Node &i)
{
i["type_name"] = "dray_reflect";
i["port_names"].append() = "in";
i["output_port"] = "true";
}
//-----------------------------------------------------------------------------
bool
DRayReflect::verify_params(const conduit::Node ¶ms,
conduit::Node &info)
{
info.reset();
bool res = true;
res &= check_numeric("point/x",params, info, true);
res &= check_numeric("point/y",params, info, true);
res &= check_numeric("point/z",params, info, false);
res &= check_numeric("normal/x",params, info, true);
res &= check_numeric("normal/y",params, info, true);
res &= check_numeric("normal/z",params, info, false);
std::vector<std::string> valid_paths;
std::vector<std::string> ignore_paths;
valid_paths.push_back("point/x");
valid_paths.push_back("point/y");
valid_paths.push_back("point/z");
valid_paths.push_back("normal/x");
valid_paths.push_back("normal/y");
valid_paths.push_back("normal/z");
std::string surprises = surprise_check(valid_paths, params);
if(surprises != "")
{
res = false;
info["errors"].append() = surprises;
}
return res;
}
//-----------------------------------------------------------------------------
void
DRayReflect::execute()
{
if(!input(0).check_type<DataObject>())
{
ASCENT_ERROR("dray reflect input must be a DataObject");
}
DataObject *d_input = input<DataObject>(0);
DRayCollection *dcol = d_input->as_dray_collection().get();
int comm_id = -1;
#ifdef ASCENT_MPI_ENABLED
comm_id = flow::Workspace::default_mpi_comm();
#endif
dcol->mpi_comm(comm_id);
dray::Vec<float,3> point = {0.f, 0.f, 0.f};
point[0] = params()["point/x"].to_float32();
point[1] = params()["point/y"].to_float32();
if(params().has_path("point/z"))
{
point[2] = params()["point/z"].to_float32();
}
dray::Vec<float,3> normal= {0.f, 1.f, 0.f};
normal[0] = params()["normal/x"].to_float32();
normal[1] = params()["normal/y"].to_float32();
if(params().has_path("normal/z"))
{
normal[2] = params()["normal/z"].to_float32();
}
dray::Reflect reflector;
reflector.plane(point,normal);
DRayCollection *output = new DRayCollection();
const int num_domains = dcol->m_domains.size();
for(int i = 0; i < num_domains; ++i)
{
dray::DataSet dset = reflector.execute(dcol->m_domains[i]);
output->m_domains.push_back(dset);
}
for(int i = 0; i < num_domains; ++i)
{
output->m_domains.push_back(dcol->m_domains[i]);
}
DataObject *res = new DataObject(output);
set_output<DataObject>(res);
}
//-----------------------------------------------------------------------------
DRayProject2d::DRayProject2d()
:Filter()
{
// empty
}
//-----------------------------------------------------------------------------
DRayProject2d::~DRayProject2d()
{
// empty
}
//-----------------------------------------------------------------------------
void
DRayProject2d::declare_interface(Node &i)
{
i["type_name"] = "dray_project_2d";
i["port_names"].append() = "in";
i["output_port"] = "true";
}
//-----------------------------------------------------------------------------
bool
DRayProject2d::verify_params(const conduit::Node ¶ms,
conduit::Node &info)
{
info.reset();
bool res = true;
res &= check_numeric("image_width",params, info, false);
res &= check_numeric("image_height",params, info, false);
std::vector<std::string> valid_paths;
std::vector<std::string> ignore_paths;
valid_paths.push_back("image_width");
valid_paths.push_back("image_height");
valid_paths.push_back("fields");
ignore_paths.push_back("camera");
ignore_paths.push_back("fields");
std::string surprises = surprise_check(valid_paths, ignore_paths, params);
if(surprises != "")
{
res = false;
info["errors"].append() = surprises;
}
return res;
}
//-----------------------------------------------------------------------------
void
DRayProject2d::execute()
{
if(!input(0).check_type<DataObject>())
{
ASCENT_ERROR("dray_project2d input must be a DataObject");
}
DataObject *d_input = input<DataObject>(0);
DRayCollection *dcol = d_input->as_dray_collection().get();
int comm_id = -1;
#ifdef ASCENT_MPI_ENABLED
comm_id = flow::Workspace::default_mpi_comm();
#endif
dcol->mpi_comm(comm_id);
DRayCollection faces = dcol->boundary();
faces.mpi_comm(comm_id);
std::string image_name;
conduit::Node * meta = graph().workspace().registry().fetch<Node>("metadata");
int width = 512;
int height = 512;
if(params().has_path("image_width"))
{
width = params()["image_width"].to_int32();
}
if(params().has_path("image_height"))
{
height = params()["image_height"].to_int32();
}
std::vector<std::string> field_selection;
if(params().has_path("fields"))
{
const conduit::Node &flist = params()["fields"];
const int num_fields = flist.number_of_children();
if(num_fields == 0)
{
ASCENT_ERROR("dray_project_2d field selection list must be non-empty");
}
for(int i = 0; i < num_fields; ++i)
{
const conduit::Node &f = flist.child(i);
if(!f.dtype().is_string())
{
ASCENT_ERROR("relay_io_save field selection list values must be a string");
}
field_selection.push_back(f.as_string());
}
}
dray::Camera camera;
camera.set_width(width);
camera.set_height(height);
dray::AABB<3> bounds = dcol->get_global_bounds();
camera.reset_to_bounds(bounds);
std::vector<float> clipping(2);
clipping[0] = 0.01f;
clipping[1] = 1000.f;
if(params().has_path("camera"))
{
const conduit::Node &n_camera = params()["camera"];
clipping = detail::parse_camera(n_camera, camera);
}
std::vector<dray::ScalarBuffer> buffers;
// basic sanity checking
int min_p = std::numeric_limits<int>::max();
int max_p = std::numeric_limits<int>::min();
std::vector<std::string> field_names;
vtkh::PayloadCompositor compositor;
const int num_domains = dcol->m_domains.size();
for(int i = 0; i < num_domains; ++i)
{
std::shared_ptr<dray::Surface> surface =
std::make_shared<dray::Surface>(faces.m_domains[i]);
dray::ScalarRenderer renderer(surface);
if(field_selection.size() == 0)
{
field_names = faces.m_domains[i].fields();
}
else
{
field_names = field_selection;
}
renderer.field_names(field_names);
dray::ScalarBuffer buffer = renderer.render(camera);
vtkh::PayloadImage *pimage = detail::convert(buffer);
min_p = std::min(min_p, pimage->m_payload_bytes);
max_p = std::max(max_p, pimage->m_payload_bytes);
compositor.AddImage(*pimage);
delete pimage;
}
if(min_p != max_p)
{
ASCENT_ERROR("VERY BAD "<<min_p<<" "<<max_p<<" contact someone.");
}
vtkh::PayloadImage final_image = compositor.Composite();
conduit::Node *output = new conduit::Node();
if(vtkh::GetMPIRank() == 0)
{
dray::ScalarBuffer final_result = detail::convert(final_image, field_names);
conduit::Node &dom = output->append();
final_result.to_node(dom);
dom["state/domain_id"] = 0;
int cycle = 0;
if(meta->has_path("cycle"))
{
cycle = (*meta)["cycle"].as_int32();
}
dom["state/cycle"] = cycle;
}
DataObject *res = new DataObject(output);
set_output<DataObject>(res);
}
//-----------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
// -- end ascent::runtime::filters --
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
// -- end ascent::runtime --
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
// -- end ascent:: --
//-----------------------------------------------------------------------------
| 28.664762 | 95 | 0.574523 | [
"render",
"vector"
] |
f64b56524bb3267be30e3d252cf3196da53bddf7 | 726 | cpp | C++ | src/RHI/Backend/OpenGL/IndexBuffer.cpp | ArnoChenFx/SkelAnimation | d814ac12aeca0bb9364c48064ce2ba06a9718141 | [
"MIT"
] | 3 | 2021-07-25T01:53:18.000Z | 2022-01-13T02:21:02.000Z | src/RHI/Backend/OpenGL/IndexBuffer.cpp | ArnoChenFx/SkelAnimation | d814ac12aeca0bb9364c48064ce2ba06a9718141 | [
"MIT"
] | null | null | null | src/RHI/Backend/OpenGL/IndexBuffer.cpp | ArnoChenFx/SkelAnimation | d814ac12aeca0bb9364c48064ce2ba06a9718141 | [
"MIT"
] | 2 | 2021-07-21T14:35:32.000Z | 2021-11-09T02:10:10.000Z | #include "RHI/IndexBuffer.h"
#include <glad/gl.h>
IndexBuffer::IndexBuffer() {
glGenBuffers(1, &mHandle);
mCount = 0;
}
IndexBuffer::~IndexBuffer() {
glDeleteBuffers(1, &mHandle);
}
void IndexBuffer::Set(unsigned int* inputArray, unsigned int arrayLengt) {
mCount = arrayLengt;
unsigned int size = sizeof(unsigned int);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mHandle);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size * mCount, inputArray, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void IndexBuffer::Set(std::vector<unsigned int>& input) {
Set(&input[0], (unsigned int)input.size());
}
unsigned int IndexBuffer::Count() {
return mCount;
}
unsigned int IndexBuffer::GetHandle() {
return mHandle;
} | 22.6875 | 82 | 0.743802 | [
"vector"
] |
f6511ca1b19fd7dcdb4fed0acbe1c6a0148c7e04 | 20,529 | cpp | C++ | LUMA/tools/post_processors/h5mgm/src/h5mgm.cpp | paulakash24/LUMA | f31b9197c17befe5880b6f1d636d21aa39d66018 | [
"Apache-2.0"
] | 29 | 2017-12-01T14:39:43.000Z | 2020-09-03T00:12:36.000Z | LUMA/tools/post_processors/h5mgm/src/h5mgm.cpp | ExuberantWitness/LUMA | 15f2319a67ebb8e3ff577bdd0f93890c3c0e8d0b | [
"Apache-2.0"
] | 14 | 2018-08-31T09:12:37.000Z | 2020-06-08T11:46:06.000Z | LUMA/tools/post_processors/h5mgm/src/h5mgm.cpp | ExuberantWitness/LUMA | 15f2319a67ebb8e3ff577bdd0f93890c3c0e8d0b | [
"Apache-2.0"
] | 15 | 2018-01-15T09:33:47.000Z | 2020-08-04T08:29:42.000Z | /*
* --------------------------------------------------------------
*
* ------ Lattice Boltzmann @ The University of Manchester ------
*
* -------------------------- L-U-M-A ---------------------------
*
* Copyright (C) The University of Manchester 2017
* E-mail contact: info@luma.manchester.ac.uk
*
* This software is for academic use only and not available for
* further distribution commericially or otherwise without written consent.
*
*/
#include "VelocitySorter.h"
#include "ThirdParty/vtkCleanUnstructuredGrid.h"
// Method to construct a 3D polyhedron out of faces and add to an unstructured grid
size_t addCell(vtkSmartPointer<vtkPoints> global_pts,
vtkSmartPointer<vtkUnstructuredGrid> grid,
std::vector<vtkIdType>& global_ids,
std::vector< std::vector<double> >& cell_pts,
int *point_count, int dimensions_p)
{
// Local declarations
vtkSmartPointer<vtkCellArray> face_array = vtkSmartPointer<vtkCellArray>::New();
std::vector<vtkIdType> face_ids;
size_t status = 0;
// Add new points to global points and assign new id
for (size_t c = 0; c < cell_pts.size(); c++) {
global_pts->InsertNextPoint(cell_pts[c][0], cell_pts[c][1], cell_pts[c][2]);
global_ids.push_back(*point_count + c);
}
if (dimensions_p == 3)
{
// Specify points that make up voxel in specific order
face_ids.push_back(*point_count + 0);
face_ids.push_back(*point_count + 4);
face_ids.push_back(*point_count + 2);
face_ids.push_back(*point_count + 6);
face_ids.push_back(*point_count + 1);
face_ids.push_back(*point_count + 5);
face_ids.push_back(*point_count + 3);
face_ids.push_back(*point_count + 7);
// Update offset
*point_count += 8;
}
else
{
// Specify points that make up quad in specific order
face_ids.push_back(*point_count + 0);
face_ids.push_back(*point_count + 2);
face_ids.push_back(*point_count + 1);
face_ids.push_back(*point_count + 3);
// Update offset
*point_count += 4;
}
// Update grid with new point list and add cell
grid->SetPoints(global_pts);
if (dimensions_p == 3) {
grid->InsertNextCell(VTK_VOXEL, 8, &face_ids[0]);
}
else {
grid->InsertNextCell(VTK_PIXEL, 4, &face_ids[0]);
}
// Free face array (forces destructor to be called)
face_array = NULL;
return status;
}
/* H5 Multi-Grid Merge Tool for post-processing HDF5 files written by LUMA */
int main(int argc, char* argv[])
{
// Parse arguments and handle
std::string case_num("000");
for (int a = 1; a < argc; ++a)
{
std::string arg_str = std::string(argv[a]);
if (arg_str == "version")
{
std::cout << "H5MultiGridMerge (h5mgm) Version " << H5MGM_VERSION << std::endl;
return 0;
}
else if (arg_str == "quiet")
{
bQuiet = true;
}
else if (arg_str == "loud")
{
bLoud = true;
}
else if (arg_str == "cut")
{
bCutSolid = true;
}
else if (arg_str == "legacy")
{
bLegacy = true;
}
else if (arg_str == "sorter")
{
bSorter = true;
}
else
{
case_num = std::string(argv[a]);
}
}
// Print out to screen
std::cout << "H5MultiGridMerge (h5mgm) Version " << H5MGM_VERSION << ". Running..." << std::endl;
// Path for output
std::string path_str(H5MGM_OUTPUT_PATH);
// Create directory
std::string command = "mkdir -p " + path_str;
#ifdef _WIN32 // Running on Windows
CreateDirectoryA((LPCSTR)path_str.c_str(), NULL);
#else // Running on Unix system
system(command.c_str());
#endif // _WIN32
// Open log file if not set to quiet
if (bQuiet == false)
{
std::string logpath = H5MGM_OUTPUT_PATH;
logpath += "/h5mgm.log";
logfile.open(logpath, std::ios::out | std::ios::app);
logfile << "---------------------------------------" << std::endl;
}
// Start process
std::cout << "Reconstructing HDF data..." << std::endl;
// Turn auto error printing off
H5Eset_auto(H5E_DEFAULT, NULL, NULL);
// If using the sorter use the standalone class then return
if (bSorter)
{
VelocitySorter<double> *vs = new VelocitySorter<double>();
vs->readAndSort();
delete vs;
return 0;
}
// Construct L0 filename
std::string IN_FILE_NAME("./hdf_R0N0.h5");
// Set T = 0 time string
std::string TIME_STRING = "/Time_0";
// Declarations
herr_t status = 0;
hid_t output_fid = NULL;
hid_t input_fid = NULL;
hid_t input_aid = NULL;
int dimensions_p, levels, regions, timesteps, out_every, mpi_flag;
double dx;
std::string VAR;
int* LatTyp = nullptr;
double *dummy_d = nullptr;
int *dummy_i = nullptr;
// Open L0 input file
input_fid = H5Fopen(IN_FILE_NAME.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
if (input_fid == NULL) writeInfo("Cannot open input file!", eHDF);
// Read in key attributes from the file
input_aid = H5Aopen(input_fid, "Dimensions", H5P_DEFAULT);
if (input_aid == NULL) writeInfo("Cannot open attribute!", eHDF);
status = H5Aread(input_aid, H5T_NATIVE_INT, &dimensions_p);
if (status != 0) writeInfo("Cannot read attribute!", eHDF);
status = H5Aclose(input_aid);
if (status != 0) writeInfo("Cannot close attribute!", eHDF);
input_aid = H5Aopen(input_fid, "NumberOfGrids", H5P_DEFAULT);
if (input_aid <= 0) writeInfo("Cannot open attribute!", eHDF);
status = H5Aread(input_aid, H5T_NATIVE_INT, &levels);
if (status != 0) writeInfo("Cannot read attribute!", eHDF);
status = H5Aclose(input_aid);
if (status != 0) writeInfo("Cannot close attribute!", eHDF);
input_aid = H5Aopen(input_fid, "NumberOfRegions", H5P_DEFAULT);
if (input_aid <= 0) writeInfo("Cannot open attribute!", eHDF);
status = H5Aread(input_aid, H5T_NATIVE_INT, ®ions);
if (status != 0) writeInfo("Cannot read attribute!", eHDF);
status = H5Aclose(input_aid);
if (status != 0) writeInfo("Cannot close attribute!", eHDF);
input_aid = H5Aopen(input_fid, "Timesteps", H5P_DEFAULT);
if (input_aid <= 0) writeInfo("Cannot open attribute!", eHDF);
status = H5Aread(input_aid, H5T_NATIVE_INT, ×teps);
if (status != 0) writeInfo("Cannot read attribute!", eHDF);
status = H5Aclose(input_aid);
if (status != 0) writeInfo("Cannot close attribute!", eHDF);
input_aid = H5Aopen(input_fid, "OutputFrequency", H5P_DEFAULT);
if (input_aid <= 0) writeInfo("Cannot open attribute!", eHDF);
status = H5Aread(input_aid, H5T_NATIVE_INT, &out_every);
if (status != 0) writeInfo("Cannot read attribute!", eHDF);
status = H5Aclose(input_aid);
if (status != 0) writeInfo("Cannot close attribute!", eHDF);
input_aid = H5Aopen(input_fid, "Mpi", H5P_DEFAULT);
if (input_aid == NULL) writeInfo("Cannot open attribute!", eHDF);
status = H5Aread(input_aid, H5T_NATIVE_INT, &mpi_flag);
if (status != 0) writeInfo("Cannot read attribute!", eHDF);
status = H5Aclose(input_aid);
if (status != 0) writeInfo("Cannot close attribute!", eHDF);
// Store basic data
int *gridsize = (int*)malloc(3 * sizeof(int)); // Space for grid size
gridsize[2] = 1; // Set 3D dimension to 1, will get overwritten if actually 3D
int num_grids = ((levels - 1) * regions + 1); // Total number of grids
// Close file
status = H5Fclose(input_fid);
if (status != 0) writeInfo("Cannot close file!", eHDF);
// Create cell node position list for VTK
std::vector< std::vector<double> > cell_points;
if (dimensions_p == 3) {
cell_points.resize(8, std::vector<double>(3));
}
else {
cell_points.resize(4, std::vector<double>(3));
}
// Create VTK grid
vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid =
vtkSmartPointer<vtkUnstructuredGrid>::New();
// Create VTK grid points
vtkSmartPointer<vtkPoints> points =
vtkSmartPointer<vtkPoints>::New();
// Create point ID list
std::vector<vtkIdType> *pointIds =
new std::vector<vtkIdType>();
// Total point count
int point_count = 0;
// Status indicator
size_t res = 0;
std::cout << "Building mesh..." << std::endl;
// Loop 1 to get mesh details
for (int lev = 0; lev < levels; lev++) {
for (int reg = 0; reg < regions; reg++) {
// L0 doesn't have different regions
if (lev == 0 && reg != 0) continue;
// Debug
int local_point_count = 0;
std::cout << "Adding cells from L" << lev << " R" << reg << "..." << std::endl;
// Construct input file name
std::string IN_FILE_NAME("./hdf_R" + std::to_string(reg) + "N" + std::to_string(lev) + ".h5");
input_fid = H5Fopen(IN_FILE_NAME.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
if (input_fid <= 0) writeInfo("Cannot open input file!", eHDF);
// Get local grid size
input_aid = H5Aopen(input_fid, "GridSize", H5P_DEFAULT);
if (input_aid <= 0) writeInfo("Cannot open attribute!", eHDF);
status = H5Aread(input_aid, H5T_NATIVE_INT, gridsize);
if (status != 0) writeInfo("Cannot read attribute!", eHDF);
status = H5Aclose(input_aid);
if (status != 0) writeInfo("Cannot close attribute!", eHDF);
// Get local dx
input_aid = H5Aopen(input_fid, "Dx", H5P_DEFAULT);
if (input_aid == NULL) writeInfo("Cannot open attribute!", eHDF);
status = H5Aread(input_aid, H5T_NATIVE_DOUBLE, &dx);
if (status != 0) writeInfo("Cannot read attribute!", eHDF);
status = H5Aclose(input_aid);
if (status != 0) writeInfo("Cannot close attribute!", eHDF);
// Allocate space for LatTyp data
int *Type = (int*)malloc((gridsize[0] * gridsize[1] * gridsize[2]) * sizeof(int));
if (Type == NULL) {
writeInfo("Not enough Memory!!!!", eFatal);
exit(EXIT_FAILURE);
}
// Allocate space for X, Y, Z coordinates
double *X = (double*)malloc((gridsize[0] * gridsize[1] * gridsize[2]) * sizeof(double));
if (X == NULL) {
writeInfo("Not enough Memory!!!!", eFatal);
exit(EXIT_FAILURE);
}
double *Y = (double*)malloc((gridsize[0] * gridsize[1] * gridsize[2]) * sizeof(double));
if (Y == NULL) {
writeInfo("Not enough Memory!!!!", eFatal);
exit(EXIT_FAILURE);
}
double *Z = (double*)malloc((gridsize[0] * gridsize[1] * gridsize[2]) * sizeof(double));
if (Z == NULL) {
writeInfo("Not enough Memory!!!!", eFatal);
exit(EXIT_FAILURE);
}
// Create input dataspace
hsize_t dims_input[1];
dims_input[0] = gridsize[0] * gridsize[1] * gridsize[2];
hid_t input_sid = H5Screate_simple(1, dims_input, NULL);
if (input_sid <= 0) writeInfo("Cannot create input dataspace!", eHDF);
// Open, read into buffers information required for mesh definition and close input datasets
status = readDataset("/LatTyp", TIME_STRING, input_fid, input_sid, H5T_NATIVE_INT, Type);
if (status != 0)
{
writeInfo("Typing matrix read failed -- exiting early.", eFatal);
exit(EARLY_EXIT);
}
status = readDataset("/XPos", TIME_STRING, input_fid, input_sid, H5T_NATIVE_DOUBLE, X);
if (status != 0)
{
writeInfo("X position vector read failed -- exiting early.", eFatal);
exit(EARLY_EXIT);
}
status = readDataset("/YPos", TIME_STRING, input_fid, input_sid, H5T_NATIVE_DOUBLE, Y);
if (status != 0)
{
writeInfo("Y position vector read failed -- exiting early.", eFatal);
exit(EARLY_EXIT);
}
if (dimensions_p == 3) {
status = readDataset("/ZPos", TIME_STRING, input_fid, input_sid, H5T_NATIVE_DOUBLE, Z);
if (status != 0)
{
writeInfo("Z position vector read failed -- exiting early.", eFatal);
exit(EARLY_EXIT);
}
}
// Loop over grid sites
for (int c = 0; c < gridsize[0] * gridsize[1] * gridsize[2]; c++) {
if (bLoud || c % 100000 == 0) {
std::cout << "\r" << "Examining cell " << std::to_string(c) << "/" <<
std::to_string(gridsize[0] * gridsize[1] * gridsize[2]) << std::flush;
}
// Ignore list
if (isOnIgnoreList(static_cast<eType>(Type[c]))) continue;
local_point_count++;
if (dimensions_p == 3) {
// Find positions of corner points and store
for (int p = 0; p < 8; ++p) {
cell_points[p][0] = X[c] + e[0][p] * (dx / 2);
cell_points[p][1] = Y[c] + e[1][p] * (dx / 2);
cell_points[p][2] = Z[c] + e[2][p] * (dx / 2);
}
}
else {
// Find positions of corner points and store
for (int p = 0; p < 4; ++p) {
cell_points[p][0] = X[c] + e2[0][p] * (dx / 2);
cell_points[p][1] = Y[c] + e2[1][p] * (dx / 2);
cell_points[p][2] = 0.0;
}
}
// Build cell from points and add to mesh
res = addCell(points, unstructuredGrid, *pointIds, cell_points, &point_count, dimensions_p);
}
std::cout << "\r" << "Examining cell " << std::to_string(gridsize[0] * gridsize[1] * gridsize[2]) << "/" <<
std::to_string(gridsize[0] * gridsize[1] * gridsize[2]) << std::flush;
std::cout << std::endl;
// Close input dataspace
status = H5Sclose(input_sid);
if (status != 0) writeInfo("Cannot close input dataspace!", eHDF);
// Close input file
status = H5Fclose(input_fid);
if (status != 0) writeInfo("Cannot close input file!", eHDF);
// Free memory
free(Type);
free(X);
free(Y);
free(Z);
// Debug
std::cout << "Valid Point Count = " << local_point_count << std::endl;
}
}
// Delete pointIds as we are finished with them
delete pointIds;
// Debug
std::cout << "Total number of cells retained for merged mesh = " << unstructuredGrid->GetNumberOfCells() << std::endl;
std::cout << "Adding data for each time step to mesh..." << std::endl;
// Clean mesh to remove duplicate points (Paraview not VTK)
vtkSmartPointer<vtkCleanUnstructuredGrid> cleaner =
vtkSmartPointer<vtkCleanUnstructuredGrid>::New();
cleaner->SetInputData(unstructuredGrid);
cleaner->Update();
// Replace the unstructured grid with the cleaned version
unstructuredGrid->Reset();
unstructuredGrid = cleaner->GetOutput();
// Time loop and data addition
int count = 0;
for (size_t t = 0; t <= (size_t)timesteps; t += out_every)
{
// Create filename
std::string vtkFilename = path_str + "/luma_" + case_num + "." + std::to_string(t);
if (bLegacy)
vtkFilename += ".vtk";
else
vtkFilename += ".vtu";
// Add data
vtkSmartPointer<vtkIntArray> LatTyp = vtkSmartPointer<vtkIntArray>::New();
LatTyp->Allocate(unstructuredGrid->GetNumberOfCells());
LatTyp->SetName("LatTyp");
status = addDataToGrid("/LatTyp", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_i, H5T_NATIVE_INT, LatTyp);
// If no typing matrix then assume the time step is not available and exit
if (status == DATASET_READ_FAIL)
{
writeInfo("Couldn't find time step " + std::to_string(t) + ". Read failed -- exiting early.", eFatal);
exit(EARLY_EXIT);
}
// MPI block data always read from Time_0
if (mpi_flag)
{
vtkSmartPointer<vtkIntArray> Block = vtkSmartPointer<vtkIntArray>::New();
Block->Allocate(unstructuredGrid->GetNumberOfCells());
Block->SetName("MpiBlockNumber");
status = addDataToGrid("/MpiBlock", "/Time_0", levels, regions, gridsize, unstructuredGrid, dummy_i, H5T_NATIVE_INT, Block);
}
vtkSmartPointer<vtkDoubleArray> RhoArray = vtkSmartPointer<vtkDoubleArray>::New();
RhoArray->Allocate(unstructuredGrid->GetNumberOfCells());
RhoArray->SetName("Rho");
status = addDataToGrid("/Rho", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, RhoArray);
vtkSmartPointer<vtkDoubleArray> Rho_TimeAv = vtkSmartPointer<vtkDoubleArray>::New();
Rho_TimeAv->Allocate(unstructuredGrid->GetNumberOfCells());
Rho_TimeAv->SetName("Rho_TimeAv");
status = addDataToGrid("/Rho_TimeAv", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, Rho_TimeAv);
vtkSmartPointer<vtkDoubleArray> Ux = vtkSmartPointer<vtkDoubleArray>::New();
Ux->Allocate(unstructuredGrid->GetNumberOfCells());
Ux->SetName("Ux");
status = addDataToGrid("/Ux", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, Ux);
vtkSmartPointer<vtkDoubleArray> Uy = vtkSmartPointer<vtkDoubleArray>::New();
Uy->Allocate(unstructuredGrid->GetNumberOfCells());
Uy->SetName("Uy");
status = addDataToGrid("/Uy", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, Uy);
vtkSmartPointer<vtkDoubleArray> Ux_TimeAv = vtkSmartPointer<vtkDoubleArray>::New();
Ux_TimeAv->Allocate(unstructuredGrid->GetNumberOfCells());
Ux_TimeAv->SetName("Ux_TimeAv");
status = addDataToGrid("/Ux_TimeAv", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, Ux_TimeAv);
vtkSmartPointer<vtkDoubleArray> Uy_TimeAv = vtkSmartPointer<vtkDoubleArray>::New();
Uy_TimeAv->Allocate(unstructuredGrid->GetNumberOfCells());
Uy_TimeAv->SetName("Uy_TimeAv");
status = addDataToGrid("/Uy_TimeAv", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, Uy_TimeAv);
vtkSmartPointer<vtkDoubleArray> UxUx_TimeAv = vtkSmartPointer<vtkDoubleArray>::New();
UxUx_TimeAv->Allocate(unstructuredGrid->GetNumberOfCells());
UxUx_TimeAv->SetName("UxUx_TimeAv");
status = addDataToGrid("/UxUx_TimeAv", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, UxUx_TimeAv);
vtkSmartPointer<vtkDoubleArray> UxUy_TimeAv = vtkSmartPointer<vtkDoubleArray>::New();
UxUy_TimeAv->Allocate(unstructuredGrid->GetNumberOfCells());
UxUy_TimeAv->SetName("UxUy_TimeAv");
status = addDataToGrid("/UxUy_TimeAv", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, UxUy_TimeAv);
vtkSmartPointer<vtkDoubleArray> UyUy_TimeAv = vtkSmartPointer<vtkDoubleArray>::New();
UyUy_TimeAv->Allocate(unstructuredGrid->GetNumberOfCells());
UyUy_TimeAv->SetName("UyUy_TimeAv");
status = addDataToGrid("/UyUy_TimeAv", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, UyUy_TimeAv);
if (dimensions_p == 3)
{
vtkSmartPointer<vtkDoubleArray> Uz = vtkSmartPointer<vtkDoubleArray>::New();
Uz->Allocate(unstructuredGrid->GetNumberOfCells());
Uz->SetName("Uz");
status = addDataToGrid("/Uz", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, Uz);
vtkSmartPointer<vtkDoubleArray> Uz_TimeAv = vtkSmartPointer<vtkDoubleArray>::New();
Uz_TimeAv->Allocate(unstructuredGrid->GetNumberOfCells());
Uz_TimeAv->SetName("Uz_TimeAv");
status = addDataToGrid("/Uz_TimeAv", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, Uz_TimeAv);
vtkSmartPointer<vtkDoubleArray> UxUz_TimeAv = vtkSmartPointer<vtkDoubleArray>::New();
UxUz_TimeAv->Allocate(unstructuredGrid->GetNumberOfCells());
UxUz_TimeAv->SetName("UxUz_TimeAv");
status = addDataToGrid("/UxUz_TimeAv", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, UxUz_TimeAv);
vtkSmartPointer<vtkDoubleArray> UyUz_TimeAv = vtkSmartPointer<vtkDoubleArray>::New();
UyUz_TimeAv->Allocate(unstructuredGrid->GetNumberOfCells());
UyUz_TimeAv->SetName("UyUz_TimeAv");
status = addDataToGrid("/UyUz_TimeAv", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, UyUz_TimeAv);
vtkSmartPointer<vtkDoubleArray> UzUz_TimeAv = vtkSmartPointer<vtkDoubleArray>::New();
UzUz_TimeAv->Allocate(unstructuredGrid->GetNumberOfCells());
UzUz_TimeAv->SetName("UzUz_TimeAv");
status = addDataToGrid("/UzUz_TimeAv", TIME_STRING, levels, regions, gridsize, unstructuredGrid, dummy_d, H5T_NATIVE_DOUBLE, UzUz_TimeAv);
}
// Otherwise, must be simply a missing dataset so continue to next time step
TIME_STRING = "/Time_" + std::to_string(t + out_every);
// Print progress to screen
std::cout << "\r" << std::to_string((int)(((float)(t + out_every) /
(float)(timesteps + out_every)) * 100.0f)) << "% complete." << std::flush;
// Write grid to file
void *writer = nullptr;
if (bLegacy)
{
vtkSmartPointer<vtkUnstructuredGridWriter> writer =
vtkSmartPointer<vtkUnstructuredGridWriter>::New();
writer->SetFileName(vtkFilename.c_str());
writer->SetFileTypeToBinary();
writer->SetFileName(vtkFilename.c_str());
#if VTK_MAJOR_VERSION <= 5
writer->SetInput(unstructuredGrid);
#else
writer->SetInputData(unstructuredGrid);
#endif
writer->Write();
}
else
{
vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer =
vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();
writer->SetFileName(vtkFilename.c_str());
#if VTK_MAJOR_VERSION <= 5
writer->SetInput(unstructuredGrid);
#else
writer->SetInputData(unstructuredGrid);
#endif
writer->Write();
}
// Free the memory used (forces destructor call)
LatTyp = NULL;
RhoArray = NULL;
Rho_TimeAv = NULL;
Ux = NULL;
Uy = NULL;
Ux_TimeAv = NULL;
Uy_TimeAv = NULL;
UxUx_TimeAv = NULL;
UxUy_TimeAv = NULL;
UyUy_TimeAv = NULL;
}
return 0;
}
| 33.988411 | 141 | 0.684641 | [
"mesh",
"vector",
"3d"
] |
f6575229b6c9097cd6553f653cc2add2928c1313 | 58,020 | cpp | C++ | lib/Parser/CharSet.cpp | aneeshdk/ChakraCore | 24c24262816db8b7dc9097e718eae16c22062f08 | [
"MIT"
] | null | null | null | lib/Parser/CharSet.cpp | aneeshdk/ChakraCore | 24c24262816db8b7dc9097e718eae16c22062f08 | [
"MIT"
] | null | null | null | lib/Parser/CharSet.cpp | aneeshdk/ChakraCore | 24c24262816db8b7dc9097e718eae16c22062f08 | [
"MIT"
] | null | null | null | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "ParserPch.h"
namespace UnifiedRegex
{
// ----------------------------------------------------------------------
// CharBitVec
// ----------------------------------------------------------------------
inline uint32 popcnt(uint32 x)
{
// sum set bits in every bit pair
x -= (x >> 1) & 0x55555555u;
// sum pairs into quads
x = (x & 0x33333333u) + ((x >> 2) & 0x33333333u);
// sum quads into octets
x = (x + (x >> 4)) & 0x0f0f0f0fu;
// sum octets into topmost octet
x *= 0x01010101u;
return x >> 24;
}
uint CharBitvec::Count() const
{
uint n = 0;
for (int w = 0; w < vecSize; w++)
{
n += popcnt(vec[w]);
}
return n;
}
int CharBitvec::NextSet(int k) const
{
if (k < 0 || k >= Size)
return -1;
uint w = k / wordSize;
uint o = k % wordSize;
uint32 v = vec[w] >> o;
do
{
if (v == 0)
{
k += wordSize - o;
break;
}
else if ((v & 0x1) != 0)
return k;
else
{
v >>= 1;
o++;
k++;
}
}
while (o < wordSize);
w++;
while (w < vecSize)
{
o = 0;
v = vec[w];
do
{
if (v == 0)
{
k += wordSize - o;
break;
}
else if ((v & 0x1) != 0)
return k;
else
{
v >>= 1;
o++;
k++;
}
}
while (o < wordSize);
w++;
}
return -1;
}
int CharBitvec::NextClear(int k) const
{
if (k < 0 || k >= Size)
return -1;
uint w = k / wordSize;
uint o = k % wordSize;
uint32 v = vec[w] >> o;
do
{
if (v == ones)
{
k += wordSize - o;
break;
}
else if ((v & 0x1) == 0)
return k;
else
{
v >>= 1;
o++;
k++;
}
}
while (o < wordSize);
w++;
while (w < vecSize)
{
o = 0;
v = vec[w];
do
{
if (v == ones)
{
k += wordSize - o;
break;
}
else if ((v & 0x1) == 0)
return k;
else
{
v >>= 1;
o++;
k++;
}
}
while (o < wordSize);
w++;
}
return -1;
}
template <typename C>
void CharBitvec::ToComplement(ArenaAllocator* allocator, uint base, CharSet<C>& result) const
{
int hi = -1;
while (true)
{
// Find the next range of clear bits in vector
int li = NextClear(hi + 1);
if (li < 0)
return;
hi = NextSet(li + 1);
if (hi < 0)
hi = Size - 1;
else
{
Assert(hi > 0);
hi--;
}
// Add range as characters
result.SetRange(allocator, Chars<C>::ITC(base + li), Chars<C>::ITC(base + hi));
}
}
template <typename C>
void CharBitvec::ToEquivClass(ArenaAllocator* allocator, uint base, uint& tblidx, CharSet<C>& result, codepoint_t baseOffset) const
{
int hi = -1;
while (true)
{
// Find the next range of set bits in vector
int li = NextSet(hi + 1);
if (li < 0)
return;
hi = NextClear(li + 1);
if (hi < 0)
hi = Size - 1;
else
{
Assert(hi > 0);
hi--;
}
// Convert to character codes
uint l = base + li + baseOffset;
uint h = base + hi + baseOffset;
do
{
uint acth;
C equivl[CaseInsensitive::EquivClassSize];
CaseInsensitive::RangeToEquivClass(tblidx, l, h, acth, equivl);
uint n = acth - l;
for (int i = 0; i < CaseInsensitive::EquivClassSize; i++)
{
result.SetRange(allocator, equivl[i], Chars<C>::Shift(equivl[i], n));
}
// Go around again for rest of this range
l = acth + 1;
}
while (l <= h);
}
}
// ----------------------------------------------------------------------
// CharSetNode
// ----------------------------------------------------------------------
inline CharSetNode* CharSetNode::For(ArenaAllocator* allocator, int level)
{
if (level == 0)
return Anew(allocator, CharSetLeaf);
else
return Anew(allocator, CharSetInner);
}
// ----------------------------------------------------------------------
// CharSetFull
// ----------------------------------------------------------------------
CharSetFull CharSetFull::Instance;
CharSetFull* const CharSetFull::TheFullNode = &CharSetFull::Instance;
CharSetFull::CharSetFull() {}
void CharSetFull::FreeSelf(ArenaAllocator* allocator)
{
Assert(this == TheFullNode);
// Never allocated
}
CharSetNode* CharSetFull::Clone(ArenaAllocator* allocator) const
{
// Always shared
return (CharSetNode*)this;
}
CharSetNode* CharSetFull::Set(ArenaAllocator* allocator, uint level, uint l, uint h)
{
return this;
}
CharSetNode* CharSetFull::ClearRange(ArenaAllocator* allocator, uint level, uint l, uint h)
{
AssertMsg(h <= lim(level), "The range for clearing provided is invalid for this level.");
AssertMsg(l <= h, "Can't clear where lower is bigger than the higher.");
if (l == 0 && h == lim(level))
{
return nullptr;
}
CharSetNode* toReturn = For(allocator, level);
if (l > 0)
{
AssertVerify(toReturn->Set(allocator, level, 0, l - 1) == toReturn);
}
if (h < lim(level))
{
AssertVerify(toReturn->Set(allocator, level, h + 1, lim(level)) == toReturn);
}
return toReturn;
}
CharSetNode* CharSetFull::UnionInPlace(ArenaAllocator* allocator, uint level, const CharSetNode* other)
{
return this;
}
bool CharSetFull::Get(uint level, uint k) const
{
return true;
}
void CharSetFull::ToComplement(ArenaAllocator* allocator, uint level, uint base, CharSet<Char>& result) const
{
// Empty, so add nothing
}
void CharSetFull::ToEquivClassW(ArenaAllocator* allocator, uint level, uint base, uint& tblidx, CharSet<wchar_t>& result) const
{
this->ToEquivClass<wchar_t>(allocator, level, base, tblidx, result);
}
void CharSetFull::ToEquivClassCP(ArenaAllocator* allocator, uint level, uint base, uint& tblidx, CharSet<codepoint_t>& result, codepoint_t baseOffset) const
{
this->ToEquivClass<codepoint_t>(allocator, level, base, tblidx, result, baseOffset);
}
template <typename C>
void CharSetFull::ToEquivClass(ArenaAllocator* allocator, uint level, uint base, uint& tblidx, CharSet<C>& result, codepoint_t baseOffset) const
{
uint l = base + (CharSetNode::levels - 1 == level ? 0xff : 0) + baseOffset;
uint h = base + lim(level) + baseOffset;
do
{
uint acth;
C equivl[CaseInsensitive::EquivClassSize];
CaseInsensitive::RangeToEquivClass(tblidx, l, h, acth, equivl);
uint n = acth - l;
for (int i = 0; i < CaseInsensitive::EquivClassSize; i++)
{
result.SetRange(allocator, equivl[i], Chars<C>::Shift(equivl[i], n));
}
// Go around again for rest of this range
l = acth + 1;
}
while (l <= h);
}
bool CharSetFull::IsSubsetOf(uint level, const CharSetNode* other) const
{
Assert(other != nullptr);
return other == TheFullNode;
}
bool CharSetFull::IsEqualTo(uint level, const CharSetNode* other) const
{
Assert(other != nullptr);
return other == TheFullNode;
}
uint CharSetFull::Count(uint level) const
{
return lim(level) + 1;
}
_Success_(return)
bool CharSetFull::GetNextRange(uint level, Char searchCharStart, _Out_ Char *outLowerChar, _Out_ Char *outHigherChar) const
{
Assert(searchCharStart < this->Count(level));
*outLowerChar = searchCharStart;
*outHigherChar = (Char)this->Count(level) - 1;
return true;
}
#if DBG
bool CharSetFull::IsLeaf() const
{
return false;
}
#endif
// ----------------------------------------------------------------------
// CharSetInner
// ----------------------------------------------------------------------
CharSetInner::CharSetInner()
{
for (uint i = 0; i < branchingPerInnerLevel; i++)
children[i] = 0;
}
void CharSetInner::FreeSelf(ArenaAllocator* allocator)
{
for (uint i = 0; i < branchingPerInnerLevel; i++)
{
if (children[i] != 0)
{
children[i]->FreeSelf(allocator);
#if DBG
children[i] = 0;
#endif
}
}
Adelete(allocator, this);
}
CharSetNode* CharSetInner::Clone(ArenaAllocator* allocator) const
{
CharSetInner* res = Anew(allocator, CharSetInner);
for (uint i = 0; i < branchingPerInnerLevel; i++)
{
if (children[i] != 0)
res->children[i] = children[i]->Clone(allocator);
}
return res;
}
CharSetNode* CharSetInner::ClearRange(ArenaAllocator* allocator, uint level, uint l, uint h)
{
Assert(level > 0);
AssertMsg(h <= lim(level), "The range for clearing provided is invalid for this level.");
AssertMsg(l <= h, "Can't clear where lower is bigger than the higher.");
if (l == 0 && h == lim(level))
{
return nullptr;
}
uint lowerIndex = innerIdx(level, l);
uint higherIndex = innerIdx(level--, h);
l = l & lim(level);
h = h & lim(level);
if (lowerIndex == higherIndex)
{
if (children[lowerIndex] != nullptr)
{
children[lowerIndex] = children[lowerIndex]->ClearRange(allocator, level, l, h);
}
}
else
{
if (children[lowerIndex] != nullptr)
{
children[lowerIndex] = children[lowerIndex]->ClearRange(allocator, level, l, lim(level));
}
for (uint i = lowerIndex + 1; i < higherIndex; i++)
{
if (children[i] != nullptr)
{
children[i]->FreeSelf(allocator);
}
children[i] = nullptr;
}
if (children[higherIndex] != nullptr)
{
children[higherIndex] = children[higherIndex]->ClearRange(allocator, level, 0, h);
}
}
for (int i = 0; i < branchingPerInnerLevel; i++)
{
if (children[i] != nullptr)
{
return this;
}
}
return nullptr;
}
CharSetNode* CharSetInner::Set(ArenaAllocator* allocator, uint level, uint l, uint h)
{
Assert(level > 0);
uint li = innerIdx(level, l);
uint hi = innerIdx(level--, h);
bool couldBeFull = true;
if (li == hi)
{
if (children[li] == nullptr)
{
if (remain(level, l) == 0 && remain(level, h + 1) == 0)
children[li] = CharSetFull::TheFullNode;
else
{
children[li] = For(allocator, level);
children[li] = children[li]->Set(allocator, level, l, h);
couldBeFull = false;
}
}
else
children[li] = children[li]->Set(allocator, level, l, h);
}
else
{
if (children[li] == nullptr)
{
if (remain(level, l) == 0)
children[li] = CharSetFull::TheFullNode;
else
{
children[li] = For(allocator, level);
children[li] = children[li]->Set(allocator, level, l, lim(level));
couldBeFull = false;
}
}
else
children[li] = children[li]->Set(allocator, level, l, lim(level));
for (uint i = li + 1; i < hi; i++)
{
if (children[i] != nullptr)
children[i]->FreeSelf(allocator);
children[i] = CharSetFull::TheFullNode;
}
if (children[hi] == nullptr)
{
if (remain(level, h + 1) == 0)
children[hi] = CharSetFull::TheFullNode;
else
{
children[hi] = For(allocator, level);
children[hi] = children[hi]->Set(allocator, level, 0, h);
couldBeFull = false;
}
}
else
children[hi] = children[hi]->Set(allocator, level, 0, h);
}
if (couldBeFull)
{
for (uint i = 0; i < branchingPerInnerLevel; i++)
{
if (children[i] != CharSetFull::TheFullNode)
return this;
}
FreeSelf(allocator);
return CharSetFull::TheFullNode;
}
else
return this;
}
CharSetNode* CharSetInner::UnionInPlace(ArenaAllocator* allocator, uint level, const CharSetNode* other)
{
Assert(level > 0);
Assert(other != nullptr && other != CharSetFull::TheFullNode && !other->IsLeaf());
CharSetInner* otherInner = (CharSetInner*)other;
level--;
bool isFull = true;
for (uint i = 0; i < branchingPerInnerLevel; i++)
{
if (otherInner->children[i] != nullptr)
{
if (otherInner->children[i] == CharSetFull::TheFullNode)
{
if (children[i] != nullptr)
children[i]->FreeSelf(allocator);
children[i] = CharSetFull::TheFullNode;
}
else
{
if (children[i] == nullptr)
children[i] = For(allocator, level);
children[i] = children[i]->UnionInPlace(allocator, level, otherInner->children[i]);
if (children[i] != CharSetFull::TheFullNode)
isFull = false;
}
}
else if (children[i] != CharSetFull::TheFullNode)
isFull = false;
}
if (isFull)
{
FreeSelf(allocator);
return CharSetFull::TheFullNode;
}
else
return this;
}
bool CharSetInner::Get(uint level, uint k) const
{
Assert(level > 0);
uint i = innerIdx(level--, k);
if (children[i] == nullptr)
return false;
else
return children[i]->Get(level, k);
}
void CharSetInner::ToComplement(ArenaAllocator* allocator, uint level, uint base, CharSet<Char>& result) const
{
Assert(level > 0);
level--;
uint delta = lim(level) + 1;
for (uint i = 0; i < branchingPerInnerLevel; i++)
{
if (children[i] == nullptr)
// Caution: Part of the range for this child may overlap with direct vector
result.SetRange(allocator, UTC(max(base, directSize)), UTC(base + delta - 1));
else
children[i]->ToComplement(allocator, level, base, result);
base += delta;
}
}
void CharSetInner::ToEquivClassW(ArenaAllocator* allocator, uint level, uint base, uint& tblidx, CharSet<wchar_t>& result) const
{
Assert(level > 0);
level--;
uint delta = lim(level) + 1;
for (uint i = 0; i < branchingPerInnerLevel; i++)
{
if (children[i] != nullptr)
{
children[i]->ToEquivClassW(allocator, level, base, tblidx, result);
}
base += delta;
}
}
void CharSetInner::ToEquivClassCP(ArenaAllocator* allocator, uint level, uint base, uint& tblidx, CharSet<codepoint_t>& result, codepoint_t baseOffset) const
{
Assert(level > 0);
level--;
uint delta = lim(level) + 1;
for (uint i = 0; i < branchingPerInnerLevel; i++)
{
if (children[i] != nullptr)
{
children[i]->ToEquivClassCP(allocator, level, base, tblidx, result, baseOffset);
}
base += delta;
}
}
bool CharSetInner::IsSubsetOf(uint level, const CharSetNode* other) const
{
Assert(level > 0);
Assert(other != nullptr && !other->IsLeaf());
if (other == CharSetFull::TheFullNode)
return true;
level--;
const CharSetInner* otherInner = (CharSetInner*)other;
for (uint i = 0; i < branchingPerInnerLevel; i++)
{
if (children[i] != nullptr)
{
if (otherInner->children[i] == nullptr)
return false;
if (children[i]->IsSubsetOf(level, otherInner->children[i]))
return false;
}
}
return true;
}
bool CharSetInner::IsEqualTo(uint level, const CharSetNode* other) const
{
Assert(level > 0);
Assert(other != nullptr && !other->IsLeaf());
if (other == CharSetFull::TheFullNode)
return false;
level--;
const CharSetInner* otherInner = (CharSetInner*)other;
for (uint i = 0; i < branchingPerInnerLevel; i++)
{
if (children[i] != 0)
{
if (otherInner->children[i] == nullptr)
return false;
if (children[i]->IsSubsetOf(level, otherInner->children[i]))
return false;
}
}
return true;
}
uint CharSetInner::Count(uint level) const
{
uint n = 0;
Assert(level > 0);
level--;
for (uint i = 0; i < branchingPerInnerLevel; i++)
{
if (children[i] != nullptr)
n += children[i]->Count(level);
}
return n;
}
_Success_(return)
bool CharSetInner::GetNextRange(uint level, Char searchCharStart, _Out_ Char *outLowerChar, _Out_ Char *outHigherChar) const
{
Assert(searchCharStart < this->lim(level) + 1);
uint innerIndex = innerIdx(level--, searchCharStart);
Char currentLowChar = 0, currentHighChar = 0;
for (; innerIndex < branchingPerInnerLevel; innerIndex++)
{
if (children[innerIndex] != nullptr && children[innerIndex]->GetNextRange(level, (Char)remain(level, searchCharStart), ¤tLowChar, ¤tHighChar))
{
break;
}
if (innerIndex < branchingPerInnerLevel - 1)
{
searchCharStart = (Char)indexToValue(level + 1, innerIndex + 1, 0);
}
}
if (innerIndex == branchingPerInnerLevel)
{
return false;
}
currentLowChar = (Char)indexToValue(level + 1, innerIndex, currentLowChar);
currentHighChar = (Char)indexToValue(level + 1, innerIndex, currentHighChar);
innerIndex += 1;
for (; remain(level, currentHighChar) == lim(level) && innerIndex < branchingPerInnerLevel; innerIndex++)
{
Char tempLower, tempHigher;
if (children[innerIndex] == nullptr || !children[innerIndex]->GetNextRange(level, 0x0, &tempLower, &tempHigher) || remain(level, tempLower) != 0)
{
break;
}
currentHighChar = (Char)indexToValue(level + 1, innerIndex, tempHigher);
}
*outLowerChar = currentLowChar;
*outHigherChar = currentHighChar;
return true;
}
#if DBG
bool CharSetInner::IsLeaf() const
{
return false;
}
#endif
// ----------------------------------------------------------------------
// CharSetLeaf
// ----------------------------------------------------------------------
CharSetLeaf::CharSetLeaf()
{
vec.Clear();
}
void CharSetLeaf::FreeSelf(ArenaAllocator* allocator)
{
Adelete(allocator, this);
}
CharSetNode* CharSetLeaf::Clone(ArenaAllocator* allocator) const
{
return Anew(allocator, CharSetLeaf, *this);
}
CharSetNode* CharSetLeaf::Set(ArenaAllocator* allocator, uint level, uint l, uint h)
{
Assert(level == 0);
vec.SetRange(leafIdx(l), leafIdx(h));
if (vec.IsFull())
{
FreeSelf(allocator);
return CharSetFull::TheFullNode;
}
else
return this;
}
CharSetNode* CharSetLeaf::ClearRange(ArenaAllocator* allocator, uint level, uint l, uint h)
{
Assert(level == 0);
AssertMsg(h <= lim(level), "The range for clearing provided is invalid for this level.");
AssertMsg(l <= h, "Can't clear where lower is bigger than the higher.");
if (l == 0 && h == lim(level))
{
return nullptr;
}
vec.ClearRange(leafIdx(l), leafIdx(h));
if (vec.IsEmpty())
{
FreeSelf(allocator);
return nullptr;
}
return this;
}
CharSetNode* CharSetLeaf::UnionInPlace(ArenaAllocator* allocator, uint level, const CharSetNode* other)
{
Assert(level == 0);
Assert(other != nullptr && other->IsLeaf());
CharSetLeaf* otherLeaf = (CharSetLeaf*)other;
if (vec.UnionInPlaceFullCheck(otherLeaf->vec))
{
FreeSelf(allocator);
return CharSetFull::TheFullNode;
}
else
return this;
}
bool CharSetLeaf::Get(uint level, uint k) const
{
Assert(level == 0);
return vec.Get(leafIdx(k));
}
void CharSetLeaf::ToComplement(ArenaAllocator* allocator, uint level, uint base, CharSet<Char>& result) const
{
Assert(level == 0);
vec.ToComplement<wchar_t>(allocator, base, result);
}
void CharSetLeaf::ToEquivClassW(ArenaAllocator* allocator, uint level, uint base, uint& tblidx, CharSet<wchar_t>& result) const
{
this->ToEquivClass<wchar_t>(allocator, level, base, tblidx, result);
}
void CharSetLeaf::ToEquivClassCP(ArenaAllocator* allocator, uint level, uint base, uint& tblidx, CharSet<codepoint_t>& result, codepoint_t baseOffset) const
{
this->ToEquivClass<codepoint_t>(allocator, level, base, tblidx, result, baseOffset);
}
template <typename C>
void CharSetLeaf::ToEquivClass(ArenaAllocator* allocator, uint level, uint base, uint& tblidx, CharSet<C>& result, codepoint_t baseOffset) const
{
Assert(level == 0);
vec.ToEquivClass<C>(allocator, base, tblidx, result, baseOffset);
}
bool CharSetLeaf::IsSubsetOf(uint level, const CharSetNode* other) const
{
Assert(level == 0);
Assert(other != nullptr);
if (other == CharSetFull::TheFullNode)
return true;
Assert(other->IsLeaf());
CharSetLeaf* otherLeaf = (CharSetLeaf*)other;
return vec.IsSubsetOf(otherLeaf->vec);
}
bool CharSetLeaf::IsEqualTo(uint level, const CharSetNode* other) const
{
Assert(level == 0);
Assert(other != nullptr);
if (other == CharSetFull::TheFullNode)
return false;
Assert(other->IsLeaf());
CharSetLeaf* otherLeaf = (CharSetLeaf*)other;
return vec.IsSubsetOf(otherLeaf->vec);
}
uint CharSetLeaf::Count(uint level) const
{
Assert(level == 0);
return vec.Count();
}
_Success_(return)
bool CharSetLeaf::GetNextRange(uint level, Char searchCharStart, _Out_ Char *outLowerChar, _Out_ Char *outHigherChar) const
{
Assert(searchCharStart < lim(level) + 1);
int nextSet = vec.NextSet(searchCharStart);
if (nextSet == -1)
{
return false;
}
*outLowerChar = (wchar_t)nextSet;
int nextClear = vec.NextClear(nextSet);
*outHigherChar = UTC(nextClear == -1 ? lim(level) : nextClear - 1);
return true;
}
#if DBG
bool CharSetLeaf::IsLeaf() const
{
return true;
}
#endif
// ----------------------------------------------------------------------
// CharSet<wchar_t>
// ----------------------------------------------------------------------
void CharSet<wchar_t>::SwitchRepresentations(ArenaAllocator* allocator)
{
Assert(IsCompact());
uint existCount = this->GetCompactLength();
__assume(existCount <= MaxCompact);
if (existCount <= MaxCompact)
{
Char existCs[MaxCompact];
for (uint i = 0; i < existCount; i++)
{
existCs[i] = GetCompactChar(i);
}
rep.full.root = nullptr;
rep.full.direct.Clear();
for (uint i = 0; i < existCount; i++)
Set(allocator, existCs[i]);
}
}
void CharSet<wchar_t>::Sort()
{
Assert(IsCompact());
__assume(this->GetCompactLength() <= MaxCompact);
for (uint i = 1; i < this->GetCompactLength(); i++)
{
uint curr = GetCompactCharU(i);
for (uint j = 0; j < i; j++)
{
if (GetCompactCharU(j) > curr)
{
for (int k = i; k > (int)j; k--)
{
this->ReplaceCompactCharU(k, this->GetCompactCharU(k - 1));
}
this->ReplaceCompactCharU(j, curr);
break;
}
}
}
}
CharSet<wchar_t>::CharSet()
{
Assert(sizeof(Node*) == sizeof(size_t));
Assert(sizeof(CompactRep) == sizeof(FullRep));
rep.compact.countPlusOne = 1;
for (int i = 0; i < MaxCompact; i++)
rep.compact.cs[i] = emptySlot;
}
void CharSet<wchar_t>::FreeBody(ArenaAllocator* allocator)
{
if (!IsCompact() && rep.full.root != nullptr)
{
rep.full.root->FreeSelf(allocator);
#if DBG
rep.full.root = nullptr;
#endif
}
}
void CharSet<wchar_t>::Clear(ArenaAllocator* allocator)
{
if (!IsCompact() && rep.full.root != nullptr)
rep.full.root->FreeSelf(allocator);
rep.compact.countPlusOne = 1;
for (int i = 0; i < MaxCompact; i++)
rep.compact.cs[i] = emptySlot;
}
void CharSet<wchar_t>::CloneFrom(ArenaAllocator* allocator, const CharSet<Char>& other)
{
Clear(allocator);
Assert(IsCompact());
if (other.IsCompact())
{
this->SetCompactLength(other.GetCompactLength());
for (uint i = 0; i < other.GetCompactLength(); i++)
{
this->ReplaceCompactCharU(i, other.GetCompactCharU(i));
}
}
else
{
rep.full.root = other.rep.full.root == nullptr ? nullptr : other.rep.full.root->Clone(allocator);
rep.full.direct.CloneFrom(other.rep.full.direct);
}
}
void CharSet<wchar_t>::CloneNonSurrogateCodeUnitsTo(ArenaAllocator* allocator, CharSet<Char>& other)
{
if (this->IsCompact())
{
for (uint i = 0; i < this->GetCompactLength(); i++)
{
Char c = this->GetCompactChar(i);
uint uChar = CTU(c);
if (uChar < 0xD800 || uChar > 0xDFFF)
{
other.Set(allocator, c);
}
}
}
else
{
other.rep.full.direct.CloneFrom(rep.full.direct);
if (rep.full.root == nullptr)
{
other.rep.full.root = nullptr;
}
else
{
other.rep.full.root = rep.full.root->Clone(allocator);
other.rep.full.root->ClearRange(allocator, CharSetNode::levels - 1, 0xD800, 0XDFFF);
}
}
}
void CharSet<wchar_t>::CloneSurrogateCodeUnitsTo(ArenaAllocator* allocator, CharSet<Char>& other)
{
if (this->IsCompact())
{
for (uint i = 0; i < this->GetCompactLength(); i++)
{
Char c = this->GetCompactChar(i);
uint uChar = CTU(c);
if (0xD800 <= uChar && uChar <= 0xDFFF)
{
other.Set(allocator, c);
}
}
}
else
{
other.rep.full.direct.CloneFrom(rep.full.direct);
if (rep.full.root == nullptr)
{
other.rep.full.root = nullptr;
}
else
{
other.rep.full.root = rep.full.root->Clone(allocator);
other.rep.full.root->ClearRange(allocator, CharSetNode::levels - 1, 0, 0xD7FF);
}
}
}
void CharSet<wchar_t>::SubtractRange(ArenaAllocator* allocator, Char lowerChar, Char higherChar)
{
uint lowerValue = CTU(lowerChar);
uint higherValue = CTU(higherChar);
if (higherValue < lowerValue)
return;
if (IsCompact())
{
for (uint i = 0; i < this->GetCompactLength(); )
{
uint value = this->GetCompactCharU(i);
if (value >= lowerValue && value <= higherValue)
{
this->RemoveCompactChar(i);
}
else
{
i++;
}
}
}
else if(lowerValue == 0 && higherValue == MaxUChar)
{
this->Clear(allocator);
}
else
{
if (lowerValue < CharSetNode::directSize)
{
uint maxDirectValue = min(higherValue, CharSetNode::directSize - 1);
rep.full.direct.ClearRange(lowerValue, maxDirectValue);
}
if (rep.full.root != nullptr)
{
rep.full.root = rep.full.root->ClearRange(allocator, CharSetNode::levels - 1, lowerValue, higherValue);
}
}
}
void CharSet<wchar_t>::SetRange(ArenaAllocator* allocator, Char lc, Char hc)
{
uint l = CTU(lc);
uint h = CTU(hc);
if (h < l)
return;
if (IsCompact())
{
if (h - l < MaxCompact)
{
do
{
uint i;
for (i = 0; i < this->GetCompactLength(); i++)
{
__assume(l <= MaxUChar);
if (l <= MaxUChar && i < MaxCompact)
{
if (this->GetCompactCharU(i) == l)
break;
}
}
if (i == this->GetCompactLength())
{
// Character not already in compact set
if (i < MaxCompact)
{
this->AddCompactCharU(l);
}
else
// Must switch representations
break;
}
l++;
}
while (l <= h);
if (h < l)
// All chars are now in compact set
return;
// else: fall-through to general case for remaining chars
}
// else: no use even trying
SwitchRepresentations(allocator);
}
Assert(!IsCompact());
if (l == 0 && h == MaxUChar)
{
rep.full.direct.SetRange(0, CharSetNode::directSize - 1);
if (rep.full.root != nullptr)
rep.full.root->FreeSelf(allocator);
rep.full.root = CharSetFull::TheFullNode;
}
else
{
if (l < CharSetNode::directSize)
{
if (h < CharSetNode::directSize)
{
rep.full.direct.SetRange(l, h);
return;
}
rep.full.direct.SetRange(l, CharSetNode::directSize - 1);
l = CharSetNode::directSize;
}
if (rep.full.root == nullptr)
rep.full.root = Anew(allocator, CharSetInner);
rep.full.root = rep.full.root->Set(allocator, CharSetNode::levels - 1, l, h);
}
}
void CharSet<wchar_t>::SetRanges(ArenaAllocator* allocator, int numSortedPairs, const Char* sortedPairs)
{
for (int i = 0; i < numSortedPairs * 2; i += 2)
{
Assert(i == 0 || sortedPairs[i-1] < sortedPairs[i]);
Assert(sortedPairs[i] <= sortedPairs[i+1]);
SetRange(allocator, sortedPairs[i], sortedPairs[i+1]);
}
}
void CharSet<wchar_t>::SetNotRanges(ArenaAllocator* allocator, int numSortedPairs, const Char* sortedPairs)
{
if (numSortedPairs == 0)
SetRange(allocator, MinChar, MaxChar);
else
{
if (sortedPairs[0] != MinChar)
SetRange(allocator, MinChar, sortedPairs[0] - 1);
for (int i = 1; i < numSortedPairs * 2 - 1; i += 2)
SetRange(allocator, sortedPairs[i] + 1, sortedPairs[i+1] - 1);
if (sortedPairs[numSortedPairs * 2 - 1] != MaxChar)
SetRange(allocator, sortedPairs[numSortedPairs * 2 - 1] + 1, MaxChar);
}
}
void CharSet<wchar_t>::UnionInPlace(ArenaAllocator* allocator, const CharSet<Char>& other)
{
if (other.IsCompact())
{
for (uint i = 0; i < other.GetCompactLength(); i++)
{
Set(allocator, other.GetCompactChar(i));
}
return;
}
if (IsCompact())
SwitchRepresentations(allocator);
Assert(!IsCompact() && !other.IsCompact());
rep.full.direct.UnionInPlace(other.rep.full.direct);
if (other.rep.full.root != nullptr)
{
if (other.rep.full.root == CharSetFull::TheFullNode)
{
if (rep.full.root != nullptr)
rep.full.root->FreeSelf(allocator);
rep.full.root = CharSetFull::TheFullNode;
}
else
{
if (rep.full.root == nullptr)
rep.full.root = Anew(allocator, CharSetInner);
rep.full.root = rep.full.root->UnionInPlace(allocator, CharSetNode::levels - 1, other.rep.full.root);
}
}
}
_Success_(return)
bool CharSet<wchar_t>::GetNextRange(Char searchCharStart, _Out_ Char *outLowerChar, _Out_ Char *outHigherChar)
{
int count = this->Count();
if (count == 0)
{
return false;
}
else if (count == 1)
{
Char singleton = this->Singleton();
if (singleton < searchCharStart)
{
return false;
}
*outLowerChar = *outHigherChar = singleton;
return true;
}
if (IsCompact())
{
this->Sort();
uint i = 0;
size_t compactLength = this->GetCompactLength();
for (; i < compactLength; i++)
{
Char nextChar = this->GetCompactChar(i);
if (nextChar >= searchCharStart)
{
*outLowerChar = *outHigherChar = nextChar;
break;
}
}
if (i == compactLength)
{
return false;
}
i++;
for (; i < compactLength; i++)
{
Char nextChar = this->GetCompactChar(i);
if (nextChar != *outHigherChar + 1)
{
return true;
}
*outHigherChar += 1;
}
return true;
}
else
{
bool found = false;
if (CTU(searchCharStart) < CharSetNode::directSize)
{
int nextSet = rep.full.direct.NextSet(searchCharStart);
if (nextSet != -1)
{
found = true;
*outLowerChar = (wchar_t)nextSet;
int nextClear = rep.full.direct.NextClear(nextSet);
if (nextClear != -1)
{
*outHigherChar = UTC(nextClear - 1);
return true;
}
*outHigherChar = CharSetNode::directSize - 1;
}
}
if (rep.full.root == nullptr)
{
return found;
}
Char tempLowChar = 0, tempHighChar = 0;
if (found)
{
searchCharStart = *outHigherChar + 1;
}
else
{
searchCharStart = searchCharStart > CharSetNode::directSize ? searchCharStart : CharSetNode::directSize;
}
if (rep.full.root->GetNextRange(CharSetNode::levels - 1, searchCharStart, &tempLowChar, &tempHighChar) && (!found || tempLowChar == *outHigherChar + 1))
{
if (!found)
{
*outLowerChar = tempLowChar;
}
*outHigherChar = tempHighChar;
return true;
}
return found;
}
}
bool CharSet<wchar_t>::Get_helper(uint k) const
{
Assert(!IsCompact());
CharSetNode* curr = rep.full.root;
for (int level = CharSetNode::levels - 1; level > 0; level--)
{
if (curr == CharSetFull::TheFullNode)
return true;
CharSetInner* inner = (CharSetInner*)curr;
uint i = CharSetNode::innerIdx(level, k);
if (inner->children[i] == 0)
return false;
else
curr = inner->children[i];
}
if (curr == CharSetFull::TheFullNode)
return true;
CharSetLeaf* leaf = (CharSetLeaf*)curr;
return leaf->vec.Get(CharSetNode::leafIdx(k));
}
void CharSet<wchar_t>::ToComplement(ArenaAllocator* allocator, CharSet<Char>& result)
{
if (IsCompact())
{
Sort();
if (this->GetCompactLength() > 0)
{
if (this->GetCompactCharU(0) > 0)
result.SetRange(allocator, UTC(0), UTC(this->GetCompactCharU(0) - 1));
for (uint i = 0; i < this->GetCompactLength() - 1; i++)
{
result.SetRange(allocator, UTC(this->GetCompactCharU(i) + 1), UTC(this->GetCompactCharU(i + 1) - 1));
}
if (this->GetCompactCharU(this->GetCompactLength() - 1) < MaxUChar)
{
result.SetRange(allocator, UTC(this->GetCompactCharU(this->GetCompactLength() - 1) + 1), UTC(MaxUChar));
}
}
else if (this->GetCompactLength() == 0)
{
result.SetRange(allocator, UTC(0), UTC(MaxUChar));
}
}
else
{
rep.full.direct.ToComplement<wchar_t>(allocator, 0, result);
if (rep.full.root == nullptr)
result.SetRange(allocator, UTC(CharSetNode::directSize), MaxChar);
else
rep.full.root->ToComplement(allocator, CharSetNode::levels - 1, 0, result);
}
}
void CharSet<wchar_t>::ToEquivClass(ArenaAllocator* allocator, CharSet<Char>& result)
{
uint tblidx = 0;
if (IsCompact())
{
Sort();
for (uint i = 0; i < this->GetCompactLength(); i++)
{
uint acth;
Char equivs[CaseInsensitive::EquivClassSize];
if (CaseInsensitive::RangeToEquivClass(tblidx, this->GetCompactCharU(i), this->GetCompactCharU(i), acth, equivs))
{
for (int j = 0; j < CaseInsensitive::EquivClassSize; j++)
{
result.Set(allocator, equivs[j]);
}
}
else
{
result.Set(allocator, this->GetCompactChar(i));
}
}
}
else
{
rep.full.direct.ToEquivClass<wchar_t>(allocator, 0, tblidx, result);
if (rep.full.root != nullptr)
{
rep.full.root->ToEquivClassW(allocator, CharSetNode::levels - 1, 0, tblidx, result);
}
}
}
void CharSet<wchar_t>::ToEquivClassCP(ArenaAllocator* allocator, CharSet<codepoint_t>& result, codepoint_t baseOffset)
{
uint tblidx = 0;
if (IsCompact())
{
Sort();
for (uint i = 0; i < this->GetCompactLength(); i++)
{
uint acth;
codepoint_t equivs[CaseInsensitive::EquivClassSize];
if (CaseInsensitive::RangeToEquivClass(tblidx, this->GetCompactCharU(i) + baseOffset, this->GetCompactCharU(i) + baseOffset, acth, equivs))
{
for (int j = 0; j < CaseInsensitive::EquivClassSize; j++)
{
result.Set(allocator, equivs[j]);
}
}
else
{
result.Set(allocator, this->GetCompactChar(i) + baseOffset);
}
}
}
else
{
rep.full.direct.ToEquivClass<codepoint_t>(allocator, 0, tblidx, result, baseOffset);
if (rep.full.root != nullptr)
{
rep.full.root->ToEquivClassCP(allocator, CharSetNode::levels - 1, 0, tblidx, result, baseOffset);
}
}
}
int CharSet<wchar_t>::GetCompactEntries(uint max, __out_ecount(max) Char* entries) const
{
Assert(max <= MaxCompact);
if (!IsCompact())
return -1;
uint count = min(max, (uint)(this->GetCompactLength()));
__analysis_assume(count <= max);
for (uint i = 0; i < count; i++)
{
// Bug in oacr. it can't figure out count is less than or equal to max
#pragma warning(suppress: 22102)
entries[i] = this->GetCompactChar(i);
}
return static_cast<int>(rep.compact.countPlusOne - 1);
}
bool CharSet<wchar_t>::IsSubsetOf(const CharSet<Char>& other) const
{
if (IsCompact())
{
for (uint i = 0; i < this->GetCompactLength(); i++)
{
if (!other.Get(this->GetCompactChar(i)))
return false;
}
return true;
}
else
{
if (other.IsCompact())
return false;
if (!rep.full.direct.IsSubsetOf(other.rep.full.direct))
return false;
if (rep.full.root == nullptr)
return true;
if (other.rep.full.root == nullptr)
return false;
return rep.full.root->IsSubsetOf(CharSetNode::levels - 1, other.rep.full.root);
}
}
bool CharSet<wchar_t>::IsEqualTo(const CharSet<Char>& other) const
{
if (IsCompact())
{
if (!other.IsCompact())
return false;
if (rep.compact.countPlusOne != other.rep.compact.countPlusOne)
return false;
for (uint i = 0; i < this->GetCompactLength(); i++)
{
if (!other.Get(this->GetCompactChar(i)))
return false;
}
return true;
}
else
{
if (other.IsCompact())
return false;
if (!rep.full.direct.IsEqualTo(other.rep.full.direct))
return false;
if ((rep.full.root == nullptr) != (other.rep.full.root == nullptr))
return false;
if (rep.full.root == nullptr)
return true;
return rep.full.root->IsEqualTo(CharSetNode::levels - 1, other.rep.full.root);
}
}
#if ENABLE_REGEX_CONFIG_OPTIONS
// CAUTION: This method is very slow.
void CharSet<wchar_t>::Print(DebugWriter* w) const
{
w->Print(L"[");
int start = -1;
for (uint i = 0; i < NumChars; i++)
{
if (Get(UTC(i)))
{
if (start < 0)
{
start = i;
w->PrintEscapedChar(UTC(i));
}
}
else
{
if (start >= 0)
{
if (i > (uint)(start + 1))
{
if (i > (uint)(start + 2))
w->Print(L"-");
w->PrintEscapedChar(UTC(i - 1));
}
start = -1;
}
}
}
if (start >= 0)
{
if ((uint)start < MaxUChar - 1)
w->Print(L"-");
w->PrintEscapedChar(MaxChar);
}
w->Print(L"]");
}
#endif
// ----------------------------------------------------------------------
// CharSet<codepoint_t>
// ----------------------------------------------------------------------
CharSet<codepoint_t>::CharSet()
{
#if DBG
for (int i = 0; i < NumberOfPlanes; i++)
{
this->characterPlanes[i].IsEmpty();
}
#endif
}
void CharSet<codepoint_t>::FreeBody(ArenaAllocator* allocator)
{
for (int i = 0; i < NumberOfPlanes; i++)
{
this->characterPlanes[i].FreeBody(allocator);
}
}
void CharSet<codepoint_t>::Clear(ArenaAllocator* allocator)
{
for (int i = 0; i < NumberOfPlanes; i++)
{
this->characterPlanes[i].Clear(allocator);
}
}
void CharSet<codepoint_t>::CloneFrom(ArenaAllocator* allocator, const CharSet<Char>& other)
{
for (int i = 0; i < NumberOfPlanes; i++)
{
this->characterPlanes[i].Clear(allocator);
this->characterPlanes[i].CloneFrom(allocator, other.characterPlanes[i]);
}
}
void CharSet<codepoint_t>::CloneSimpleCharsTo(ArenaAllocator* allocator, CharSet<wchar_t>& other) const
{
other.CloneFrom(allocator, this->characterPlanes[0]);
}
void CharSet<codepoint_t>::SetRange(ArenaAllocator* allocator, Char lc, Char hc)
{
Assert(lc <= hc);
int lowerIndex = this->CharToIndex(lc);
int upperIndex = this->CharToIndex(hc);
if (lowerIndex == upperIndex)
{
this->characterPlanes[lowerIndex].SetRange(allocator, this->RemoveOffset(lc), this->RemoveOffset(hc));
}
else
{
// Do the partial ranges
wchar_t partialLower = this->RemoveOffset(lc);
wchar_t partialHigher = this->RemoveOffset(hc);
if (partialLower != 0)
{
this->characterPlanes[lowerIndex].SetRange(allocator, partialLower, Chars<wchar_t>::MaxUChar);
lowerIndex++;
}
for(; lowerIndex < upperIndex; lowerIndex++)
{
this->characterPlanes[lowerIndex].SetRange(allocator, 0, Chars<wchar_t>::MaxUChar);
}
this->characterPlanes[upperIndex].SetRange(allocator, 0, partialHigher);
}
}
void CharSet<codepoint_t>::SetRanges(ArenaAllocator* allocator, int numSortedPairs, const Char* sortedPairs)
{
for (int i = 0; i < numSortedPairs * 2; i += 2)
{
Assert(i == 0 || sortedPairs[i-1] < sortedPairs[i]);
Assert(sortedPairs[i] <= sortedPairs[i+1]);
SetRange(allocator, sortedPairs[i], sortedPairs[i+1]);
}
}
void CharSet<codepoint_t>::SetNotRanges(ArenaAllocator* allocator, int numSortedPairs, const Char* sortedPairs)
{
if (numSortedPairs == 0)
{
for (int i = 0; i < NumberOfPlanes; i++)
{
this->characterPlanes[i].SetRange(allocator, 0, Chars<wchar_t>::MaxUChar);
}
}
else
{
if (sortedPairs[0] != MinChar)
{
SetRange(allocator, MinChar, sortedPairs[0] - 1);
}
for (int i = 1; i < numSortedPairs * 2 - 1; i += 2)
{
SetRange(allocator, sortedPairs[i] + 1, sortedPairs[i+1] - 1);
}
if (sortedPairs[numSortedPairs * 2 - 1] != MaxChar)
{
SetRange(allocator, sortedPairs[numSortedPairs * 2 - 1] + 1, MaxChar);
}
}
}
void CharSet<codepoint_t>::UnionInPlace(ArenaAllocator* allocator, const CharSet<Char>& other)
{
for (int i = 0; i < NumberOfPlanes; i++)
{
this->characterPlanes[i].UnionInPlace(allocator, other.characterPlanes[i]);
}
}
void CharSet<codepoint_t>::UnionInPlace(ArenaAllocator* allocator, const CharSet<wchar_t>& other)
{
this->characterPlanes[0].UnionInPlace(allocator, other);
}
_Success_(return)
bool CharSet<codepoint_t>::GetNextRange(Char searchCharStart, _Out_ Char *outLowerChar, _Out_ Char *outHigherChar)
{
Assert(outLowerChar != nullptr);
Assert(outHigherChar != nullptr);
if (searchCharStart >= 0x110000)
{
return false;
}
wchar_t currentLowChar = 1, currentHighChar = 0;
int index = this->CharToIndex(searchCharStart);
wchar_t offsetLessSearchCharStart = this->RemoveOffset(searchCharStart);
for (; index < NumberOfPlanes; index++)
{
if (this->characterPlanes[index].GetNextRange(offsetLessSearchCharStart, ¤tLowChar, ¤tHighChar))
{
break;
}
offsetLessSearchCharStart = 0x0;
}
if (index == NumberOfPlanes)
{
return false;
}
Assert(currentHighChar >= currentLowChar);
// else found range
*outLowerChar = this->AddOffset(currentLowChar, index);
*outHigherChar = this->AddOffset(currentHighChar, index);
// Check if range crosses plane boundaries
index ++;
for (; index < NumberOfPlanes; index++)
{
if (!this->characterPlanes[index].GetNextRange(0x0, ¤tLowChar, ¤tHighChar) || *outHigherChar + 1 != this->AddOffset(currentLowChar, index))
{
break;
}
Assert(this->AddOffset(currentHighChar, index) > *outHigherChar);
*outHigherChar = this->AddOffset(currentHighChar, index);
}
return true;
}
void CharSet<codepoint_t>::ToComplement(ArenaAllocator* allocator, CharSet<Char>& result)
{
for (int i = 0; i < NumberOfPlanes; i++)
{
this->characterPlanes[i].ToComplement(allocator, result.characterPlanes[i]);
}
}
void CharSet<codepoint_t>::ToSimpleComplement(ArenaAllocator* allocator, CharSet<Char>& result)
{
this->characterPlanes[0].ToComplement(allocator, result.characterPlanes[0]);
}
void CharSet<codepoint_t>::ToSimpleComplement(ArenaAllocator* allocator, CharSet<wchar_t>& result)
{
this->characterPlanes[0].ToComplement(allocator, result);
}
void CharSet<codepoint_t>::ToEquivClass(ArenaAllocator* allocator, CharSet<Char>& result)
{
for (int i = 0; i < NumberOfPlanes; i++)
{
this->characterPlanes[i].ToEquivClassCP(allocator, result, AddOffset(0, i));
}
}
void CharSet<codepoint_t>::ToSurrogateEquivClass(ArenaAllocator* allocator, CharSet<Char>& result)
{
this->CloneSimpleCharsTo(allocator, result.characterPlanes[0]);
for (int i = 1; i < NumberOfPlanes; i++)
{
this->characterPlanes[i].ToEquivClassCP(allocator, result, AddOffset(0, i));
}
}
#if ENABLE_REGEX_CONFIG_OPTIONS
void CharSet<codepoint_t>::Print(DebugWriter* w) const
{
w->Print(L"Characters 0 - 65535");
for (int i = 0; i < NumberOfPlanes; i++)
{
int base = (i + 1) * 0x10000;
w->Print(L"Characters %d - %d", base, base + 0xFFFF);
this->characterPlanes[i].Print(w);
}
}
#endif
// ----------------------------------------------------------------------
// RuntimeCharSet<wchar_t>
// ----------------------------------------------------------------------
RuntimeCharSet<wchar_t>::RuntimeCharSet()
{
root = nullptr;
direct.Clear();
}
void RuntimeCharSet<wchar_t>::FreeBody(ArenaAllocator* allocator)
{
if (root != nullptr)
{
root->FreeSelf(allocator);
#if DBG
root = nullptr;
#endif
}
}
void RuntimeCharSet<wchar_t>::CloneFrom(ArenaAllocator* allocator, const CharSet<Char>& other)
{
Assert(root == nullptr);
Assert(direct.Count() == 0);
if (other.IsCompact())
{
for (uint i = 0; i < other.GetCompactLength(); i++)
{
uint k = other.GetCompactCharU(i);
if (k < CharSetNode::directSize)
direct.Set(k);
else
{
if (root == nullptr)
root = Anew(allocator, CharSetInner);
#if DBG
CharSetNode* newRoot =
#endif
root->Set(allocator, CharSetNode::levels - 1, k, k);
#if DBG
// NOTE: Since we can add at most MaxCompact characters, we can never fill a leaf or inner node,
// thus we will never need to reallocated nodes
Assert(newRoot == root);
#endif
}
}
}
else
{
root = other.rep.full.root == nullptr ? nullptr : other.rep.full.root->Clone(allocator);
direct.CloneFrom(other.rep.full.direct);
}
}
bool RuntimeCharSet<wchar_t>::Get_helper(uint k) const
{
CharSetNode* curr = root;
for (int level = CharSetNode::levels - 1; level > 0; level--)
{
if (curr == CharSetFull::TheFullNode)
return true;
CharSetInner* inner = (CharSetInner*)curr;
uint i = CharSetNode::innerIdx(level, k);
if (inner->children[i] == 0)
return false;
else
curr = inner->children[i];
}
if (curr == CharSetFull::TheFullNode)
return true;
CharSetLeaf* leaf = (CharSetLeaf*)curr;
return leaf->vec.Get(CharSetNode::leafIdx(k));
}
#if ENABLE_REGEX_CONFIG_OPTIONS
// CAUTION: This method is very slow.
void RuntimeCharSet<wchar_t>::Print(DebugWriter* w) const
{
w->Print(L"[");
int start = -1;
for (uint i = 0; i < NumChars; i++)
{
if (Get(UTC(i)))
{
if (start < 0)
{
start = i;
w->PrintEscapedChar(UTC(i));
}
}
else
{
if (start >= 0)
{
if (i > (uint)(start + 1))
{
if (i > (uint)(start + 2))
w->Print(L"-");
w->PrintEscapedChar(UTC(i - 1));
}
start = -1;
}
}
}
if (start >= 0)
{
if ((uint)start < MaxUChar - 1)
w->Print(L"-");
w->PrintEscapedChar(MaxChar);
}
w->Print(L"]");
}
#endif
}
| 30.960512 | 166 | 0.477318 | [
"vector"
] |
f658310539dad706518afa3742b76555c65fe9a3 | 12,262 | cpp | C++ | 2D_RPG/2D_RPG/main.cpp | AustenBrooks/2D_RPG | 16d1cdecd764298dcef33391ef795f64ea9e6147 | [
"MIT"
] | null | null | null | 2D_RPG/2D_RPG/main.cpp | AustenBrooks/2D_RPG | 16d1cdecd764298dcef33391ef795f64ea9e6147 | [
"MIT"
] | null | null | null | 2D_RPG/2D_RPG/main.cpp | AustenBrooks/2D_RPG | 16d1cdecd764298dcef33391ef795f64ea9e6147 | [
"MIT"
] | null | null | null | #include <SDL.h>
#include "window.h"
#include "input.h"
#include "game.h"
#include "sprite.h"
#include "character.h"
#include "text.h"
#include "settings.h"
int main(int argc, char* args[]) {
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Event events;
window gameWindow;
input inputs;
sprite background("Sprites/forest.png");
vector<sprite> platforms;
vector<sprite> unloadedPlatforms;
vector<character> actors;
vector<character> unloadedActors;
{
character austen("austen", player);
character enemy("enemy", player);
austen.moveTo(175, 550);
enemy.moveTo(300, 576);
enemy.turnLeft();
actors.push_back(austen);
unloadedActors.push_back(enemy);
sprite bottom(0, 720, 1280, 1, true, "Sprites/blu.bmp");
sprite floor(160, 640, 410, 32, true, "Sprites/blu.bmp");
sprite ceiling(160, 448, 224, 32, true, "Sprites/blu.bmp");
sprite box(32, 4, true, "Sprites/blu.bmp");
platforms.push_back(bottom);
platforms.push_back(floor);
platforms.push_back(ceiling);
for (int i = 0; i < 7; i++) {
platforms.push_back(box);
}
platforms.at(3).moveTo(400, 608);
platforms.at(4).moveTo(448, 592);
platforms.at(5).moveTo(516, 532);
platforms.at(6).moveTo(432, 480);
platforms.at(7).moveTo(400, 432);
platforms.at(8).moveTo(120, 624);
platforms.at(9).moveTo(720, 700);
}
bool isMainMenu = true;
bool isQuitting = false;
while (1) {
if (isMainMenu) {
isQuitting = mainMenu(gameWindow);
isMainMenu = false;
}
if (isQuitting) {
return 0;
}
int timeStart = SDL_GetTicks();
int elapsedTime = SDL_GetTicks() - timeStart;
inputs.clearKeys();
SDL_PollEvent(&events);
if (events.type == SDL_KEYDOWN && events.key.repeat == false) {
inputs.pressKey(events.key.keysym.scancode);
}
if (events.type == SDL_KEYUP) {
inputs.releaseKey(events.key.keysym.scancode);
}
if (events.type == SDL_QUIT) {
return 0;
}
//if you're not grounded and not already jumping/falling, then fall
if (!isGrounded(actors.at(0), platforms) && actors.at(0).getCurrentAnimation() != falling && actors.at(0).getCurrentAnimation() != fallingStill && actors.at(0).getCurrentAnimation() != jumping && actors.at(0).getCurrentAnimation() != jumpingStill) {
actors.at(0).fall();
}
//correction frame is only used when moving everything but the player
int correctionFrame = actors.at(0).getAnimationFrame();
//used for storing jump/fall direction/distance
int sideDistance = 0;
//check if the player is animating
if (actors.at(0).getCurrentAnimation() != none) {
if (actors.at(0).getCurrentAnimation() == crouching) {
if (inputs.isKeyReleased(KEY_JUMP)) {
actors.at(0).jump();
}
}
else if (actors.at(0).getCurrentAnimation() == jumping) {
if (willCollide(actors.at(0), platforms, up)) {
actors.at(0).fall();
}
else if (actors.at(0).getSprite().getRectangle().x > (WINDOW_WIDTH / 2 - 32) && actors.at(0).getSprite().getRectangle().x < (WINDOW_WIDTH / 2 + 32)) {
actors.at(0).vertJump();
}
}
if (actors.at(0).getCurrentAnimation() == jumpingStill) {
if (willCollide(actors.at(0), platforms, up)) {
actors.at(0).fall();
}
else if (actors.at(0).getSprite().getRectangle().x > (WINDOW_WIDTH / 2 - 32) && actors.at(0).getSprite().getRectangle().x < (WINDOW_WIDTH / 2 + 32)) {
if (actors.at(0).getDirection() == left) {
sideDistance = 1;
}
if (actors.at(0).getDirection() == right) {
sideDistance = -1;
}
correctionFrame++;
if (!(correctionFrame % 2)) {
background.moveBy(sideDistance, 0);
for (int i = 0; i < platforms.size(); i++) {
platforms.at(i).moveBy(sideDistance, 0);
}
for (int i = 0; i < unloadedPlatforms.size(); i++) {
unloadedPlatforms.at(i).moveBy(sideDistance, 0);
}
for (int i = 1; i < actors.size(); i++) {
actors.at(i).moveBy(sideDistance, 0);
}
for (int i = 0; i < unloadedActors.size(); i++) {
unloadedActors.at(i).moveBy(sideDistance, 0);
}
}
}
}
if (actors.at(0).getCurrentAnimation() == falling) {
if (willCollide(actors.at(0), platforms, down)) {
actors.at(0).stop();
}
else if (actors.at(0).getSprite().getRectangle().x > (WINDOW_WIDTH / 2 - 32) && actors.at(0).getSprite().getRectangle().x < (WINDOW_WIDTH / 2 + 32)) {
actors.at(0).vertFall();
}
}
if (actors.at(0).getCurrentAnimation() == fallingStill) {
if (willCollide(actors.at(0), platforms, down)) {
actors.at(0).stop();
}
else if (actors.at(0).getSprite().getRectangle().x > (WINDOW_WIDTH / 2 - 32) && actors.at(0).getSprite().getRectangle().x < (WINDOW_WIDTH / 2 + 32)) {
if (actors.at(0).getDirection() == left) {
sideDistance = 1;
}
if (actors.at(0).getDirection() == right) {
sideDistance = -1;
}
correctionFrame++;
if (!(correctionFrame % 2)) {
background.moveBy(sideDistance, 0);
for (int i = 0; i < platforms.size(); i++) {
platforms.at(i).moveBy(sideDistance, 0);
}
for (int i = 0; i < unloadedPlatforms.size(); i++) {
unloadedPlatforms.at(i).moveBy(sideDistance, 0);
}
for (int i = 1; i < actors.size(); i++) {
actors.at(i).moveBy(sideDistance, 0);
}
for (int i = 0; i < unloadedActors.size(); i++) {
unloadedActors.at(i).moveBy(sideDistance, 0);
}
}
}
}
else if (actors.at(0).getCurrentAnimation() == walkingRight) {
if (inputs.isKeyReleased(KEY_RIGHT)) {
actors.at(0).stop();
}
//if the player is within a 64 pixel box centered in the middle of the screen
else if (actors.at(0).getSprite().getRectangle().x > (WINDOW_WIDTH / 2 - 32) && actors.at(0).getSprite().getRectangle().x < (WINDOW_WIDTH / 2 + 32)) {
actors.at(0).stop();
actors.at(0).walkRightStill();
}
else if (willCollide(actors.at(0), platforms, right)) {
actors.at(0).stop();
actors.at(0).walkRightStill();
}
}
else if (actors.at(0).getCurrentAnimation() == walkingRightStill) {
if (inputs.isKeyReleased(KEY_RIGHT)) {
actors.at(0).stop();
}
else if (willCollide(actors.at(0), platforms, right));
//if the player is within a 64 pixel box centered in the middle of the screen
else if (actors.at(0).getSprite().getRectangle().x > (WINDOW_WIDTH / 2 - 32) && actors.at(0).getSprite().getRectangle().x < (WINDOW_WIDTH / 2 + 32)) {
//move everything other than the player over
correctionFrame++;
if (!(correctionFrame % 3)) {
background.moveBy(-1, 0);
for (int i = 0; i < platforms.size(); i++) {
platforms.at(i).moveBy(-1, 0);
}
for (int i = 0; i < unloadedPlatforms.size(); i++) {
unloadedPlatforms.at(i).moveBy(-1, 0);
}
for (int i = 1; i < actors.size(); i++) {
actors.at(i).moveBy(-1, 0);
}
for (int i = 0; i < unloadedActors.size(); i++) {
unloadedActors.at(i).moveBy(-1, 0);
}
}
}
}
else if (actors.at(0).getCurrentAnimation() == walkingLeft) {
if (inputs.isKeyReleased(KEY_LEFT)) {
actors.at(0).stop();
}
//if the player is within a 64 pixel box centered in the middle of the screen
else if (actors.at(0).getSprite().getRectangle().x > (WINDOW_WIDTH / 2 - 32) && actors.at(0).getSprite().getRectangle().x < (WINDOW_WIDTH / 2 + 32)) {
actors.at(0).stop();
actors.at(0).walkLeftStill();
}
else if (willCollide(actors.at(0), platforms, left)) {
actors.at(0).stop();
actors.at(0).walkLeftStill();
}
}
else if (actors.at(0).getCurrentAnimation() == walkingLeftStill) {
if (inputs.isKeyReleased(KEY_LEFT)) {
actors.at(0).stop();
}
else if (willCollide(actors.at(0), platforms, left));
//if the player is within a 64 pixel box centered in the middle of the screen
else if (actors.at(0).getSprite().getRectangle().x > (WINDOW_WIDTH / 2 - 32) && actors.at(0).getSprite().getRectangle().x < (WINDOW_WIDTH / 2 + 32)) {
//move everything other than the player over
correctionFrame++;
if (!(correctionFrame % 3)) {
background.moveBy(1, 0);
for (int i = 0; i < platforms.size(); i++) {
platforms.at(i).moveBy(1, 0);
}
for (int i = 0; i < unloadedPlatforms.size(); i++) {
unloadedPlatforms.at(i).moveBy(1, 0);
}
for (int i = 1; i < actors.size(); i++) {
actors.at(i).moveBy(1, 0);
}
for (int i = 0; i < unloadedActors.size(); i++) {
unloadedActors.at(i).moveBy(1, 0);
}
}
}
}
actors.at(0).animate();
}
//collect input
if (inputs.isKeyPressed(KEY_JUMP) || inputs.isKeyHeld(KEY_JUMP)) {
actors.at(0).crouch();
}
else if (inputs.isKeyPressed(KEY_RIGHT) || inputs.isKeyHeld(KEY_RIGHT)) {
actors.at(0).walkRight();
}
else if (inputs.isKeyPressed(KEY_LEFT) || inputs.isKeyHeld(KEY_LEFT)) {
actors.at(0).walkLeft();
}
if (inputs.isKeyPressed(SDL_SCANCODE_F)) {
if (actors.size() >= 2 && actors.at(1).isAlive()) {
fight(gameWindow, actors.at(0), actors.at(1));
}
inputs.clearKeys();
}
if (inputs.isKeyPressed(SDL_SCANCODE_R)) {
while(!(actors.at(1).isAlive())){
actors.at(1).regen();
}
}
//TODO: add the game lol
//unload offscreen sprites
vector<int> unloadIndex;
for (int i = 0; i < platforms.size(); i++) {
int platLeft = platforms.at(i).getRectangle().x;
int platRight = platforms.at(i).getRectangle().x + platforms.at(i).getRectangle().w;
if (platRight < 0 || platLeft > WINDOW_WIDTH) {
unloadIndex.push_back(i);
}
}
for (int i = unloadIndex.size() - 1; i >= 0; i--) {
int index = unloadIndex.at(i);
unloadedPlatforms.push_back(platforms.at(index));
platforms.erase(platforms.begin() + index);
}
unloadIndex.clear();
//reload onscreen sprites
vector<int> loadIndex;
for (int i = 0; i < unloadedPlatforms.size(); i++) {
int platLeft = unloadedPlatforms.at(i).getRectangle().x;
int platRight = unloadedPlatforms.at(i).getRectangle().x + unloadedPlatforms.at(i).getRectangle().w;
if (platRight > 0 && platLeft < WINDOW_WIDTH) {
loadIndex.push_back(i);
}
}
for (int i = loadIndex.size() - 1; i >= 0; i--) {
int index = loadIndex.at(i);
platforms.push_back(unloadedPlatforms.at(index));
unloadedPlatforms.erase(unloadedPlatforms.begin() + index);
}
loadIndex.clear();
//unload offscreen actors
for (int i = 1; i < actors.size(); i++) {
int actorLeft = actors.at(i).getSprite().getRectangle().x;
int actorRight = actors.at(i).getSprite().getRectangle().x + actors.at(i).getSprite().getRectangle().w;
if (actorRight < 0 || actorLeft > WINDOW_WIDTH) {
unloadIndex.push_back(i);
}
}
for (int i = unloadIndex.size() - 1; i >= 0; i--) {
int index = unloadIndex.at(i);
unloadedActors.push_back(actors.at(index));
actors.erase(actors.begin() + index);
}
unloadIndex.clear();
//reload onscreen actors
for (int i = 0; i < unloadedActors.size(); i++) {
int actorLeft = unloadedActors.at(i).getSprite().getRectangle().x;
int actorRight = unloadedActors.at(i).getSprite().getRectangle().x + unloadedActors.at(i).getSprite().getRectangle().w;
if (actorRight > 0 && actorLeft < WINDOW_WIDTH) {
loadIndex.push_back(i);
}
}
for (int i = loadIndex.size() - 1; i >= 0; i--) {
int index = loadIndex.at(i);
actors.push_back(unloadedActors.at(index));
unloadedActors.erase(unloadedActors.begin() + index);
}
loadIndex.clear();
//update all textures for sprites
for (int i = 0; i < actors.size(); i++) {
actors.at(i).createTexture(gameWindow.getRenderer());
}
for (int i = 0; i < platforms.size(); i++) {
platforms.at(i).createTexture(gameWindow.getRenderer());
}
background.createTexture(gameWindow.getRenderer());
//draw 1 frame
gameWindow.renderBackground(background);
gameWindow.renderPlatforms(platforms);
gameWindow.renderActors(actors);
gameWindow.drawFrame();
//this is to ensure the game doesn't run > fps, doing it this way does tie physics to fps, which isn't ideal
elapsedTime = SDL_GetTicks() - timeStart;
if (elapsedTime < FRAME_TIME) {
SDL_Delay(FRAME_TIME - elapsedTime);
}
}
return 0;
} | 31.849351 | 251 | 0.621024 | [
"vector"
] |
2cec13deceff92ed3a0cdcc90dc7f8100dce3178 | 5,619 | cpp | C++ | src/add-ons/kernel/bus_managers/pci/arch/arm64/pci_controller.cpp | Milek7/haiku-work | cb94bdc0817e3eeaad7f515161a94e073d4d886f | [
"MIT"
] | 2 | 2022-03-27T20:52:12.000Z | 2022-03-27T21:12:52.000Z | src/add-ons/kernel/bus_managers/pci/arch/arm64/pci_controller.cpp | Milek7/haiku-work | cb94bdc0817e3eeaad7f515161a94e073d4d886f | [
"MIT"
] | null | null | null | src/add-ons/kernel/bus_managers/pci/arch/arm64/pci_controller.cpp | Milek7/haiku-work | cb94bdc0817e3eeaad7f515161a94e073d4d886f | [
"MIT"
] | null | null | null | /*
* Copyright 2009, Haiku Inc.
* Distributed under the terms of the MIT License.
*/
#include "pci_controller.h"
#include <kernel/debug.h>
#include <kernel/int.h>
#include <util/Vector.h>
#include "pci_private.h"
#include <ACPI.h> // module
#include "acpi.h" // acpica
#include "irq_routing_table.h"
addr_t gPCIeBase;
uint8 gStartBusNumber;
uint8 gEndBusNumber;
addr_t gPCIioBase;
extern pci_controller pci_controller_ecam;
enum RangeType
{
RANGE_IO,
RANGE_MEM
};
struct PciRange
{
RangeType type;
phys_addr_t hostAddr;
phys_addr_t pciAddr;
size_t length;
};
static Vector<PciRange> *sRanges;
template<typename T>
ACPI_ADDRESS64_ATTRIBUTE AcpiCopyAddressAttr(const T &src)
{
ACPI_ADDRESS64_ATTRIBUTE dst;
dst.Granularity = src.Granularity;
dst.Minimum = src.Minimum;
dst.Maximum = src.Maximum;
dst.TranslationOffset = src.TranslationOffset;
dst.AddressLength = src.AddressLength;
return dst;
}
static acpi_status
AcpiCrsScanCallback(ACPI_RESOURCE *res, void *context)
{
Vector<PciRange> &ranges = *(Vector<PciRange>*)context;
ACPI_ADDRESS64_ATTRIBUTE address;
if (res->Type == ACPI_RESOURCE_TYPE_ADDRESS16)
address = AcpiCopyAddressAttr(((ACPI_RESOURCE_ADDRESS16*)&res->Data)->Address);
else if (res->Type == ACPI_RESOURCE_TYPE_ADDRESS32)
address = AcpiCopyAddressAttr(((ACPI_RESOURCE_ADDRESS32*)&res->Data)->Address);
else if (res->Type == ACPI_RESOURCE_TYPE_ADDRESS64)
address = AcpiCopyAddressAttr(((ACPI_RESOURCE_ADDRESS64*)&res->Data)->Address);
else
return AE_OK;
ACPI_RESOURCE_ADDRESS &common = *((ACPI_RESOURCE_ADDRESS*)&res->Data);
if (common.ResourceType != 0 && common.ResourceType != 1)
return AE_OK;
ASSERT(address.Minimum + address.AddressLength - 1 == address.Maximum);
PciRange range;
range.type = (common.ResourceType == 0 ? RANGE_MEM : RANGE_IO);
range.hostAddr = address.Minimum + address.TranslationOffset;
range.pciAddr = address.Minimum;
range.length = address.AddressLength;
ranges.PushBack(range);
return AE_OK;
}
static bool
is_interrupt_available(int32 gsi)
{
return true;
}
status_t
pci_controller_init(void)
{
if (gPCIRootNode == NULL)
return B_NO_INIT;
dprintf("PCI: pci_controller_init\n");
status_t res;
acpi_module_info *acpiModule;
acpi_device_module_info *acpiDeviceModule;
acpi_device acpiDevice;
res = get_module(B_ACPI_MODULE_NAME, (module_info**)&acpiModule);
if (res != B_OK)
return B_ERROR;
ACPI_TABLE_MCFG *mcfg;
res = acpiModule->get_table(ACPI_SIG_MCFG, 0, (void**)&mcfg);
if (res != B_OK)
return B_ERROR;
{
device_node* acpiParent = gDeviceManager->get_parent_node(gPCIRootNode);
if (acpiParent == NULL)
return B_ERROR;
res = gDeviceManager->get_driver(acpiParent,
(driver_module_info**)&acpiDeviceModule, (void**)&acpiDevice);
if (res != B_OK)
return B_ERROR;
gDeviceManager->put_node(acpiParent);
}
sRanges = new Vector<PciRange>();
acpi_status acpi_res = acpiDeviceModule->walk_resources(acpiDevice,
(ACPI_STRING)METHOD_NAME__CRS, AcpiCrsScanCallback, sRanges);
if (ACPI_FAILURE(acpi_res))
return B_ERROR;
for (Vector<PciRange>::Iterator it = sRanges->Begin(); it != sRanges->End(); it++) {
if (it->type != RANGE_IO)
continue;
if (gPCIioBase != 0) {
dprintf("PCI: multiple io ranges not supported!");
continue;
}
area_id area = map_physical_memory("pci io",
it->hostAddr, it->length, B_ANY_KERNEL_ADDRESS,
B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, (void **)&gPCIioBase);
if (area < 0)
return B_ERROR;
}
ACPI_MCFG_ALLOCATION* end = (ACPI_MCFG_ALLOCATION*) ((char*)mcfg + mcfg->Header.Length);
ACPI_MCFG_ALLOCATION* alloc = (ACPI_MCFG_ALLOCATION*) (mcfg + 1);
if (alloc + 1 != end)
dprintf("PCI: multiple host bridges not supported!");
for (; alloc < end; alloc++) {
dprintf("PCI: mechanism addr: %" B_PRIx64 ", seg: %x, start: %x, end: %x\n",
alloc->Address, alloc->PciSegment, alloc->StartBusNumber, alloc->EndBusNumber);
if (alloc->PciSegment != 0) {
dprintf("PCI: multiple segments not supported!");
continue;
}
gStartBusNumber = alloc->StartBusNumber;
gEndBusNumber = alloc->EndBusNumber;
area_id area = map_physical_memory("pci config",
alloc->Address, (gEndBusNumber - gStartBusNumber + 1) << 20, B_ANY_KERNEL_ADDRESS,
B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, (void **)&gPCIeBase);
if (area < 0)
break;
dprintf("PCI: ecam controller found\n");
return pci_controller_add(&pci_controller_ecam, NULL);
}
return B_ERROR;
}
status_t
pci_controller_finalize(void)
{
status_t res;
acpi_module_info *acpiModule;
res = get_module(B_ACPI_MODULE_NAME, (module_info**)&acpiModule);
if (res != B_OK)
return B_ERROR;
IRQRoutingTable table;
res = prepare_irq_routing(acpiModule, table, &is_interrupt_available);
if (res != B_OK) {
dprintf("PCI: irq routing preparation failed\n");
return B_ERROR;
}
for (Vector<irq_routing_entry>::Iterator it = table.Begin(); it != table.End(); it++)
reserve_io_interrupt_vectors(1, it->irq, INTERRUPT_TYPE_IRQ);
res = enable_irq_routing(acpiModule, table);
if (res != B_OK) {
dprintf("PCI: irq routing failed\n");
return B_ERROR;
}
print_irq_routing_table(table);
return B_OK;
}
phys_addr_t
pci_ram_address(phys_addr_t addr)
{
for (Vector<PciRange>::Iterator it = sRanges->Begin(); it != sRanges->End(); it++) {
if (addr >= it->pciAddr && addr < it->pciAddr + it->length) {
phys_addr_t result = addr - it->pciAddr;
if (it->type != RANGE_IO)
result += it->hostAddr;
return result;
}
}
dprintf("PCI: requested translation of invalid address %" B_PRIxPHYSADDR "\n", addr);
return 0;
}
| 24.11588 | 89 | 0.723972 | [
"vector"
] |
2cf8ac13d388caef6f1e1378020809ea31c00f34 | 11,017 | cpp | C++ | soundlib/Load_okt.cpp | ev3dev/libopenmpt | 06d2c8b26a148dc6e87ccfe2ab4bcb82a55d6714 | [
"BSD-3-Clause"
] | null | null | null | soundlib/Load_okt.cpp | ev3dev/libopenmpt | 06d2c8b26a148dc6e87ccfe2ab4bcb82a55d6714 | [
"BSD-3-Clause"
] | null | null | null | soundlib/Load_okt.cpp | ev3dev/libopenmpt | 06d2c8b26a148dc6e87ccfe2ab4bcb82a55d6714 | [
"BSD-3-Clause"
] | null | null | null | /*
* Load_okt.cpp
* ------------
* Purpose: OKT (Oktalyzer) module loader
* Notes : (currently none)
* Authors: Storlek (Original author - http://schismtracker.org/ - code ported with permission)
* Johannes Schultz (OpenMPT Port, tweaks)
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "Loaders.h"
OPENMPT_NAMESPACE_BEGIN
#ifdef NEEDS_PRAGMA_PACK
#pragma pack(push, 1)
#endif
struct PACKED OktIffChunk
{
// IFF chunk names
enum ChunkIdentifiers
{
idCMOD = MAGIC4BE('C','M','O','D'),
idSAMP = MAGIC4BE('S','A','M','P'),
idSPEE = MAGIC4BE('S','P','E','E'),
idSLEN = MAGIC4BE('S','L','E','N'),
idPLEN = MAGIC4BE('P','L','E','N'),
idPATT = MAGIC4BE('P','A','T','T'),
idPBOD = MAGIC4BE('P','B','O','D'),
idSBOD = MAGIC4BE('S','B','O','D'),
};
uint32 signature; // IFF chunk name
uint32 chunksize; // chunk size without header
// Convert all multi-byte numeric values to current platform's endianness or vice versa.
void ConvertEndianness()
{
SwapBytesBE(signature);
SwapBytesBE(chunksize);
}
};
STATIC_ASSERT(sizeof(OktIffChunk) == 8);
struct PACKED OktSample
{
char name[20];
uint32 length; // length in bytes
uint16 loopStart; // *2 for real value
uint16 loopLength; // ditto
uint16 volume; // default volume
uint16 type; // 7-/8-bit sample
// Convert all multi-byte numeric values to current platform's endianness or vice versa.
void ConvertEndianness()
{
SwapBytesBE(length);
SwapBytesBE(loopStart);
SwapBytesBE(loopLength);
SwapBytesBE(volume);
SwapBytesBE(type);
}
};
STATIC_ASSERT(sizeof(OktSample) == 32);
#ifdef NEEDS_PRAGMA_PACK
#pragma pack(pop)
#endif
// Parse the sample header block
static void ReadOKTSamples(FileReader &chunk, std::vector<bool> &sample7bit, CSoundFile *pSndFile)
//------------------------------------------------------------------------------------------------
{
pSndFile->m_nSamples = MIN((SAMPLEINDEX)(chunk.BytesLeft() / sizeof(OktSample)), MAX_SAMPLES - 1); // typically 36
sample7bit.resize(pSndFile->GetNumSamples());
for(SAMPLEINDEX nSmp = 1; nSmp <= pSndFile->GetNumSamples(); nSmp++)
{
ModSample &mptSmp = pSndFile->GetSample(nSmp);
OktSample oktSmp;
chunk.ReadConvertEndianness(oktSmp);
oktSmp.length = oktSmp.length;
oktSmp.loopStart = oktSmp.loopStart * 2;
oktSmp.loopLength = oktSmp.loopLength * 2;
oktSmp.volume = oktSmp.volume;
oktSmp.type = oktSmp.type;
mptSmp.Initialize();
mpt::String::Read<mpt::String::maybeNullTerminated>(pSndFile->m_szNames[nSmp], oktSmp.name);
mptSmp.nC5Speed = 8287;
mptSmp.nGlobalVol = 64;
mptSmp.nVolume = MIN(oktSmp.volume, 64) * 4;
mptSmp.nLength = oktSmp.length & ~1; // round down
// parse loops
if (oktSmp.loopLength > 2 && static_cast<SmpLength>(oktSmp.loopStart) + static_cast<SmpLength>(oktSmp.loopLength) <= mptSmp.nLength)
{
mptSmp.nSustainStart = oktSmp.loopStart;
mptSmp.nSustainEnd = oktSmp.loopStart + oktSmp.loopLength;
if (mptSmp.nSustainStart < mptSmp.nLength && mptSmp.nSustainEnd <= mptSmp.nLength)
mptSmp.uFlags |= CHN_SUSTAINLOOP;
else
mptSmp.nSustainStart = mptSmp.nSustainEnd = 0;
}
sample7bit[nSmp - 1] = (oktSmp.type == 0 || oktSmp.type == 2);
}
}
// Parse a pattern block
static void ReadOKTPattern(FileReader &chunk, PATTERNINDEX nPat, CSoundFile &sndFile)
//-----------------------------------------------------------------------------------
{
if(!chunk.CanRead(2))
{
return;
}
ROWINDEX rows = Clamp(static_cast<ROWINDEX>(chunk.ReadUint16BE()), ROWINDEX(1), MAX_PATTERN_ROWS);
if(!sndFile.Patterns.Insert(nPat, rows))
{
return;
}
const CHANNELINDEX chns = sndFile.GetNumChannels();
for(ROWINDEX row = 0; row < rows; row++)
{
ModCommand *m = sndFile.Patterns[nPat].GetRow(row);
for(CHANNELINDEX chn = 0; chn < chns; chn++, m++)
{
uint8 note = chunk.ReadUint8();
uint8 instr = chunk.ReadUint8();
uint8 effect = chunk.ReadUint8();
m->param = chunk.ReadUint8();
if(note > 0 && note <= 36)
{
m->note = note + 48;
m->instr = instr + 1;
} else
{
m->instr = 0;
}
switch(effect)
{
case 0: // Nothing
m->param = 0;
break;
case 1: // 1 Portamento Down (Period)
m->command = CMD_PORTAMENTOUP;
m->param &= 0x0F;
break;
case 2: // 2 Portamento Up (Period)
m->command = CMD_PORTAMENTODOWN;
m->param &= 0x0F;
break;
#if 0
/* these aren't like Jxx: "down" means to *subtract* the offset from the note.
For now I'm going to leave these unimplemented. */
case 10: // A Arpeggio 1 (down, orig, up)
case 11: // B Arpeggio 2 (orig, up, orig, down)
if (m->param)
m->command = CMD_ARPEGGIO;
break;
#endif
// This one is close enough to "standard" arpeggio -- I think!
case 12: // C Arpeggio 3 (up, up, orig)
if (m->param)
m->command = CMD_ARPEGGIO;
break;
case 13: // D Slide Down (Notes)
if (m->param)
{
m->command = CMD_NOTESLIDEDOWN;
m->param = 0x10 | MIN(0x0F, m->param);
}
break;
case 30: // U Slide Up (Notes)
if (m->param)
{
m->command = CMD_NOTESLIDEUP;
m->param = 0x10 | MIN(0x0F, m->param);
}
break;
/* We don't have fine note slide, but this is supposed to happen once
per row. Sliding every 5 (non-note) ticks kind of works (at least at
speed 6), but implementing fine slides would of course be better. */
case 21: // L Slide Down Once (Notes)
if (m->param)
{
m->command = CMD_NOTESLIDEDOWN;
m->param = 0x50 | MIN(0x0F, m->param);
}
break;
case 17: // H Slide Up Once (Notes)
if (m->param)
{
m->command = CMD_NOTESLIDEUP;
m->param = 0x50 | MIN(0x0F, m->param);
}
break;
case 15: // F Set Filter <>00:ON
// Not implemented, but let's import it anyway...
m->command = CMD_MODCMDEX;
m->param = !!m->param;
break;
case 25: // P Pos Jump
m->command = CMD_POSITIONJUMP;
break;
case 27: // R Release sample (apparently not listed in the help!)
m->Clear();
m->note = NOTE_KEYOFF;
break;
case 28: // S Speed
m->command = CMD_SPEED; // or tempo?
break;
case 31: // V Volume
m->command = CMD_VOLUMESLIDE;
switch (m->param >> 4)
{
case 4:
if (m->param != 0x40)
{
m->param &= 0x0F; // D0x
break;
}
// 0x40 is set volume -- fall through
MPT_FALLTHROUGH;
case 0: case 1: case 2: case 3:
m->volcmd = VOLCMD_VOLUME;
m->vol = m->param;
m->command = CMD_NONE;
m->param = 0;
break;
case 5:
m->param = (m->param & 0x0F) << 4; // Dx0
break;
case 6:
m->param = 0xF0 | MIN(m->param & 0x0F, 0x0E); // DFx
break;
case 7:
m->param = (MIN(m->param & 0x0F, 0x0E) << 4) | 0x0F; // DxF
break;
default:
// Junk.
m->command = m->param = 0;
break;
}
break;
#if 0
case 24: // O Old Volume (???)
m->command = CMD_VOLUMESLIDE;
m->param = 0;
break;
#endif
default:
m->command = m->param = 0;
//MPT_ASSERT_NOTREACHED();
break;
}
}
}
}
bool CSoundFile::ReadOKT(FileReader &file, ModLoadingFlags loadFlags)
//-------------------------------------------------------------------
{
file.Rewind();
if(!file.ReadMagic("OKTASONG"))
{
return false;
}
// prepare some arrays to store offsets etc.
std::vector<FileReader> patternChunks;
std::vector<FileReader> sampleChunks;
std::vector<bool> sample7bit; // 7-/8-bit sample
ORDERINDEX nOrders = 0;
InitializeGlobals(MOD_TYPE_OKT);
// Go through IFF chunks...
while(file.CanRead(sizeof(OktIffChunk)))
{
OktIffChunk iffHead;
if(!file.ReadConvertEndianness(iffHead))
{
break;
}
FileReader chunk = file.ReadChunk(iffHead.chunksize);
if(!chunk.IsValid())
{
break;
}
switch(iffHead.signature)
{
case OktIffChunk::idCMOD:
// read that weird channel setup table
if(m_nChannels > 0 || chunk.GetLength() < 8)
{
break;
}
for(CHANNELINDEX nChn = 0; nChn < 4; nChn++)
{
uint8 ch1 = chunk.ReadUint8(), ch2 = chunk.ReadUint8();
if(ch1 || ch2)
{
ChnSettings[m_nChannels].Reset();
ChnSettings[m_nChannels++].nPan = (((nChn & 3) == 1) || ((nChn & 3) == 2)) ? 0xC0 : 0x40;
}
ChnSettings[m_nChannels].Reset();
ChnSettings[m_nChannels++].nPan = (((nChn & 3) == 1) || ((nChn & 3) == 2)) ? 0xC0 : 0x40;
}
if(loadFlags == onlyVerifyHeader)
{
return true;
}
break;
case OktIffChunk::idSAMP:
// convert sample headers
if(m_nSamples > 0)
{
break;
}
ReadOKTSamples(chunk, sample7bit, this);
break;
case OktIffChunk::idSPEE:
// read default speed
if(chunk.GetLength() >= 2)
{
m_nDefaultSpeed = Clamp(chunk.ReadUint16BE(), uint16(1), uint16(255));
}
break;
case OktIffChunk::idSLEN:
// number of patterns, we don't need this.
break;
case OktIffChunk::idPLEN:
// read number of valid orders
if(chunk.GetLength() >= 2)
{
nOrders = chunk.ReadUint16BE();
}
break;
case OktIffChunk::idPATT:
// read the orderlist
Order.ReadAsByte(chunk, chunk.GetLength(), ORDERINDEX_MAX, 0xFF, 0xFE);
break;
case OktIffChunk::idPBOD:
// don't read patterns for now, as the number of channels might be unknown at this point.
if(patternChunks.size() < MAX_PATTERNS)
{
patternChunks.push_back(chunk);
}
break;
case OktIffChunk::idSBOD:
// sample data - same as with patterns, as we need to know the sample format / length
if(sampleChunks.size() < MAX_SAMPLES - 1 && chunk.GetLength() > 0)
{
sampleChunks.push_back(chunk);
}
break;
}
}
// If there wasn't even a CMOD chunk, we can't really load this.
if(m_nChannels == 0)
return false;
m_nDefaultTempo.Set(125);
m_nDefaultGlobalVolume = MAX_GLOBAL_VOLUME;
m_nSamplePreAmp = m_nVSTiVolume = 48;
m_nMinPeriod = 0x71 * 4;
m_nMaxPeriod = 0x358 * 4;
// Fix orderlist
for(ORDERINDEX nOrd = nOrders; nOrd < Order.GetLengthTailTrimmed(); nOrd++)
{
Order[nOrd] = Order.GetInvalidPatIndex();
}
// Read patterns
if(loadFlags & loadPatternData)
{
for(PATTERNINDEX nPat = 0; nPat < patternChunks.size(); nPat++)
{
if(patternChunks[nPat].GetLength() > 0)
ReadOKTPattern(patternChunks[nPat], nPat, *this);
else
Patterns.Insert(nPat, 64); // invent empty pattern
}
}
// Read samples
size_t nFileSmp = 0;
for(SAMPLEINDEX nSmp = 1; nSmp < m_nSamples; nSmp++)
{
if(nFileSmp >= sampleChunks.size() || !(loadFlags & loadSampleData))
break;
ModSample &mptSample = Samples[nSmp];
if(mptSample.nLength == 0)
continue;
// weird stuff?
mptSample.nLength = MIN(mptSample.nLength, sampleChunks[nFileSmp].GetLength());
SampleIO(
SampleIO::_8bit,
SampleIO::mono,
SampleIO::bigEndian,
sample7bit[nSmp - 1] ? SampleIO::PCM7to8 : SampleIO::signedPCM)
.ReadSample(mptSample, sampleChunks[nFileSmp]);
nFileSmp++;
}
return true;
}
OPENMPT_NAMESPACE_END
| 24.320088 | 134 | 0.622129 | [
"vector"
] |
2cfec40e07488cba0c7ca2e362252e1c78cfcdb6 | 391 | hpp | C++ | src/emu/program.hpp | wgml/emulators | b7afc44920da6b1120149926ef712ec3ebb74b8c | [
"MIT"
] | null | null | null | src/emu/program.hpp | wgml/emulators | b7afc44920da6b1120149926ef712ec3ebb74b8c | [
"MIT"
] | null | null | null | src/emu/program.hpp | wgml/emulators | b7afc44920da6b1120149926ef712ec3ebb74b8c | [
"MIT"
] | null | null | null | #pragma once
#include <cstddef>
#include <string>
#include <vector>
namespace emu {
struct Program
{
std::vector<uint8_t> content;
auto begin() const
{
return std::begin(content);
}
auto end() const
{
return std::end(content);
}
auto size() const
{
return std::size(content);
}
static Program read(std::string const& filename);
};
} // namespace emu
| 13.033333 | 51 | 0.634271 | [
"vector"
] |
fa0291e0be3c50ef85e14d1c501eb1b142925fde | 3,471 | cpp | C++ | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/fields/all-fields-cpp.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/fields/all-fields-cpp.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/fields/all-fields-cpp.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | /**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) by Kongsberg Oil & Gas Technologies.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Kongsberg Oil & Gas Technologies
* about acquiring a Coin Professional Edition License.
*
* See http://www.coin3d.org/ for more information.
*
* Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.
* http://www.sim.no/ sales@sim.no coin-support@coin3d.org
*
\**************************************************************************/
#include "SoField.cpp"
#include "SoFieldContainer.cpp"
#include "SoFieldData.cpp"
#include "SoMFBitMask.cpp"
#include "SoMFBool.cpp"
#include "SoMFColor.cpp"
#include "SoMFColorRGBA.cpp"
#include "SoMFDouble.cpp"
#include "SoMFEngine.cpp"
#include "SoMFEnum.cpp"
#include "SoMFFloat.cpp"
#include "SoMFInt32.cpp"
#include "SoMFMatrix.cpp"
#include "SoMFName.cpp"
#include "SoMFNode.cpp"
#include "SoMFPath.cpp"
#include "SoMFPlane.cpp"
#include "SoMFRotation.cpp"
#include "SoMFShort.cpp"
#include "SoMFString.cpp"
#include "SoMFTime.cpp"
#include "SoMFUInt32.cpp"
#include "SoMFUShort.cpp"
#include "SoMFVec2b.cpp"
#include "SoMFVec2s.cpp"
#include "SoMFVec2i32.cpp"
#include "SoMFVec2f.cpp"
#include "SoMFVec2d.cpp"
#include "SoMFVec3b.cpp"
#include "SoMFVec3s.cpp"
#include "SoMFVec3i32.cpp"
#include "SoMFVec3f.cpp"
#include "SoMFVec3d.cpp"
#include "SoMFVec4b.cpp"
#include "SoMFVec4ub.cpp"
#include "SoMFVec4s.cpp"
#include "SoMFVec4us.cpp"
#include "SoMFVec4i32.cpp"
#include "SoMFVec4ui32.cpp"
#include "SoMFVec4f.cpp"
#include "SoMFVec4d.cpp"
#include "SoMField.cpp"
#include "SoSFBitMask.cpp"
#include "SoSFBool.cpp"
#include "SoSFColor.cpp"
#include "SoSFColorRGBA.cpp"
#include "SoSFDouble.cpp"
#include "SoSFEngine.cpp"
#include "SoSFEnum.cpp"
#include "SoSFFloat.cpp"
#include "SoSFImage.cpp"
#include "SoSFImage3.cpp"
#include "SoSFInt32.cpp"
#include "SoSFMatrix.cpp"
#include "SoSFName.cpp"
#include "SoSFNode.cpp"
#include "SoSFPath.cpp"
#include "SoSFPlane.cpp"
#include "SoSFRotation.cpp"
#include "SoSFShort.cpp"
#include "SoSFString.cpp"
#include "SoSFTime.cpp"
#include "SoSFTrigger.cpp"
#include "SoSFUInt32.cpp"
#include "SoSFUShort.cpp"
#include "SoSFVec2b.cpp"
#include "SoSFVec2s.cpp"
#include "SoSFVec2i32.cpp"
#include "SoSFVec2f.cpp"
#include "SoSFVec2d.cpp"
#include "SoSFVec3b.cpp"
#include "SoSFVec3s.cpp"
#include "SoSFVec3i32.cpp"
#include "SoSFVec3f.cpp"
#include "SoSFVec3d.cpp"
#include "SoSFVec4b.cpp"
#include "SoSFVec4ub.cpp"
#include "SoSFVec4s.cpp"
#include "SoSFVec4us.cpp"
#include "SoSFVec4i32.cpp"
#include "SoSFVec4ui32.cpp"
#include "SoSFVec4f.cpp"
#include "SoSFVec4d.cpp"
#include "SoSFBox2s.cpp"
#include "SoSFBox2i32.cpp"
#include "SoSFBox2f.cpp"
#include "SoSFBox2d.cpp"
#include "SoSFBox3s.cpp"
#include "SoSFBox3i32.cpp"
#include "SoSFBox3f.cpp"
#include "SoSFBox3d.cpp"
#include "SoSField.cpp"
#include "SoGlobalField.cpp"
#include "shared.cpp"
| 29.415254 | 76 | 0.722558 | [
"3d"
] |
fa11fa29231032d62389a93fd00b0ec782bf8a3b | 3,794 | cc | C++ | runtime/core/test/post_processor_test.cc | realzhangm/wenet | d4d201710308e0bb54f7d59fafb74850a9f701eb | [
"Apache-2.0"
] | null | null | null | runtime/core/test/post_processor_test.cc | realzhangm/wenet | d4d201710308e0bb54f7d59fafb74850a9f701eb | [
"Apache-2.0"
] | null | null | null | runtime/core/test/post_processor_test.cc | realzhangm/wenet | d4d201710308e0bb54f7d59fafb74850a9f701eb | [
"Apache-2.0"
] | 1 | 2022-02-08T07:39:13.000Z | 2022-02-08T07:39:13.000Z | // Copyright (c) 2021 Xingchen Song sxc19@mails.tsinghua.edu.cn
//
// 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 "post_processor/post_processor.h"
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "utils/utils.h"
TEST(PostProcessorTest, ProcessSpacekMandarinEnglishTest) {
wenet::PostProcessOptions opts_lowercase;
wenet::PostProcessor post_processor_lowercase(opts_lowercase);
wenet::PostProcessOptions opts_uppercase;
opts_uppercase.lowercase = false;
wenet::PostProcessor post_processor_uppercase(opts_uppercase);
std::vector<std::string> input = {
// modeling unit: mandarin character
// decode type: CtcPrefixBeamSearch, "".join()
"震东好帅",
// modeling unit: mandarin word
// decode type: CtcWfstBeamSearch, " ".join()
" 吴迪 也 好帅",
// modeling unit: english wordpiece
// decode type: CtcPrefixBeamSearch, "".join()
"▁binbin▁is▁also▁handsome",
// modeling unit: english word
// decode type: CtcWfstBeamSearch, " ".join()
" life is short i use wenet",
// modeling unit: mandarin character + english wordpiece
// decode type: CtcPrefixBeamSearch, "".join()
"超哥▁is▁the▁most▁handsome",
// modeling unit: mandarin word + english word
// decode type: CtcWfstBeamSearch, " ".join()
" 人生 苦短 i use wenet",
};
std::vector<std::string> result_lowercase = {
"震东好帅",
"吴迪也好帅",
"binbin is also handsome",
"life is short i use wenet",
"超哥 is the most handsome",
"人生苦短i use wenet",
};
std::vector<std::string> result_uppercase = {
"震东好帅",
"吴迪也好帅",
"BINBIN IS ALSO HANDSOME",
"LIFE IS SHORT I USE WENET",
"超哥 IS THE MOST HANDSOME",
"人生苦短I USE WENET",
};
for (size_t i = 0; i < input.size(); ++i) {
EXPECT_EQ(post_processor_lowercase.ProcessSpace(input[i]),
result_lowercase[i]);
EXPECT_EQ(post_processor_uppercase.ProcessSpace(input[i]),
result_uppercase[i]);
}
}
TEST(PostProcessorTest, ProcessSpacekIndoEuropeanTest) {
wenet::PostProcessOptions opts_lowercase;
opts_lowercase.language_type = wenet::kIndoEuropean;
wenet::PostProcessor post_processor_lowercase(opts_lowercase);
wenet::PostProcessOptions opts_uppercase;
opts_uppercase.language_type = wenet::kIndoEuropean;
opts_uppercase.lowercase = false;
wenet::PostProcessor post_processor_uppercase(opts_uppercase);
std::vector<std::string> input = {
// modeling unit: wordpiece
// decode type: CtcPrefixBeamSearch, "".join()
"▁zhendong▁ist▁so▁schön",
// modeling unit: word
// decode type: CtcWfstBeamSearch, " ".join()
" zhendong ist so schön"};
std::vector<std::string> result_lowercase = {"zhendong ist so schön",
"zhendong ist so schön"};
std::vector<std::string> result_uppercase = {"ZHENDONG IST SO SCHÖN",
"ZHENDONG IST SO SCHÖN"};
for (size_t i = 0; i < input.size(); ++i) {
EXPECT_EQ(post_processor_lowercase.ProcessSpace(input[i]),
result_lowercase[i]);
EXPECT_EQ(post_processor_uppercase.ProcessSpace(input[i]),
result_uppercase[i]);
}
}
| 34.18018 | 75 | 0.666315 | [
"vector"
] |
fa1272c444111dff9dd64d10f0b0136bf9d69a3e | 470 | cpp | C++ | src/request/list.cpp | kele/graphbase | 7f2eaced4b3ed8324f35edcc84c2eb774bb87ed3 | [
"MIT"
] | null | null | null | src/request/list.cpp | kele/graphbase | 7f2eaced4b3ed8324f35edcc84c2eb774bb87ed3 | [
"MIT"
] | 3 | 2018-07-02T07:39:57.000Z | 2019-10-11T20:20:09.000Z | src/request/list.cpp | kele/graphbase | 7f2eaced4b3ed8324f35edcc84c2eb774bb87ed3 | [
"MIT"
] | null | null | null | #include "request/list.hpp"
#include "request/expression.hpp"
namespace graphbase {
namespace request {
std::shared_ptr<const query::List> list(const oracle::List &lpb) {
std::vector<std::shared_ptr<const query::IExpression>> expressions(lpb.elements_size());
for (const auto &e : lpb.elements()) {
expressions.emplace_back(std::move(expression(e)));
}
return query::List::build(std::move(expressions));
}
} // namespace request
} // namespace graphbase
| 26.111111 | 90 | 0.719149 | [
"vector"
] |
fa19cf43f079ede0a0aa30105a1236f0af2ee0b8 | 17,980 | cc | C++ | mysqlshdk/libs/rest/rest_service.cc | mysql/mysql-shell | 7a299599a79ef2b2f578ffa41cbc901a88fc6b62 | [
"Apache-2.0"
] | 119 | 2016-04-14T14:16:22.000Z | 2022-03-08T20:24:38.000Z | mysqlshdk/libs/rest/rest_service.cc | mysql/mysql-shell | 7a299599a79ef2b2f578ffa41cbc901a88fc6b62 | [
"Apache-2.0"
] | 9 | 2017-04-26T20:48:42.000Z | 2021-09-07T01:52:44.000Z | mysqlshdk/libs/rest/rest_service.cc | mysql/mysql-shell | 7a299599a79ef2b2f578ffa41cbc901a88fc6b62 | [
"Apache-2.0"
] | 51 | 2016-07-20T05:06:48.000Z | 2022-03-09T01:20:53.000Z | /*
* Copyright (c) 2019, 2021, Oracle and/or its affiliates.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.0,
* as published by the Free Software Foundation.
*
* This program is also distributed with certain software (including
* but not limited to OpenSSL) that is licensed under separate terms, as
* designated in a particular file or component or in included license
* documentation. The authors of MySQL hereby grant you an additional
* permission to link the program and your derivative works with the
* separately licensed software that they have included with MySQL.
* 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, version 2.0, for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mysqlshdk/libs/rest/rest_service.h"
#include <curl/curl.h>
#include <utility>
#include <vector>
#include "mysqlshdk/include/shellcore/scoped_contexts.h"
#include "mysqlshdk/libs/rest/retry_strategy.h"
#include "mysqlshdk/libs/utils/logger.h"
#include "mysqlshdk/libs/utils/utils_general.h"
#include "mysqlshdk/libs/utils/utils_string.h"
#ifdef _WIN32
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <wincrypt.h>
#endif // _WIN32
namespace mysqlshdk {
namespace rest {
namespace {
static constexpr auto k_content_type = "Content-Type";
static constexpr auto k_application_json = "application/json";
std::string get_user_agent() { return "mysqlsh/" MYSH_VERSION; }
size_t request_callback(char *, size_t, size_t, void *) {
// some older versions of CURL may call this callback when performing
// POST-like request with Content-Length set to 0
return 0;
}
size_t response_data_callback(char *ptr, size_t size, size_t nmemb,
void *userdata) {
auto buffer = static_cast<Base_response_buffer *>(userdata);
const auto bytes = size * nmemb;
// If a handler for the response was set, the data is passed there
if (buffer) buffer->append_data(ptr, bytes);
return bytes;
}
size_t response_header_callback(char *ptr, size_t size, size_t nmemb,
void *userdata) {
auto data = static_cast<std::string *>(userdata);
const auto bytes = size * nmemb;
data->append(ptr, bytes);
return bytes;
}
Headers parse_headers(const std::string &s) {
Headers headers;
if (!s.empty()) {
const auto lines = shcore::str_split(s, "\r\n", -1, true);
// first line is the status line, can be skipped
// header-field = field-name ":" OWS field-value OWS
// OWS = *( SP / HTAB )
for (auto it = std::next(lines.begin()); it != lines.end(); ++it) {
const auto colon = it->find(':');
if (std::string::npos != colon) {
const auto begin = it->find_first_not_of(" \t", colon + 1);
const auto end = it->find_last_not_of(" \t");
// if `begin` is std::string::npos, header has an empty value
headers[it->substr(0, colon)] = std::string::npos != begin
? it->substr(begin, end - begin + 1)
: "";
}
}
}
return headers;
}
#ifdef _WIN32
static CURLcode sslctx_function(CURL *curl, void *sslctx, void *parm) {
const auto store = CertOpenSystemStore(NULL, "ROOT");
if (store) {
PCCERT_CONTEXT context = nullptr;
X509_STORE *cts = SSL_CTX_get_cert_store((SSL_CTX *)sslctx);
while (context = CertEnumCertificatesInStore(store, context)) {
// temporary variable is mandatory
const unsigned char *encoded_cert = context->pbCertEncoded;
const auto x509 =
d2i_X509(nullptr, &encoded_cert, context->cbCertEncoded);
if (x509) {
X509_STORE_add_cert(cts, x509);
X509_free(x509);
}
}
CertCloseStore(store, 0);
}
return CURLE_OK;
}
#endif // _WIN32
} // namespace
std::string type_name(Type method) {
switch (method) {
case Type::DELETE:
return "delete";
case Type::GET:
return "get";
case Type::HEAD:
return "head";
case Type::PATCH:
return "patch";
case Type::POST:
return "post";
case Type::PUT:
return "put";
}
throw std::logic_error("Unknown method received");
}
class Rest_service::Impl {
public:
/**
* Type of the HTTP request.
*/
Impl(const Masked_string &base_url, bool verify, const std::string &label)
: m_handle(curl_easy_init(), &curl_easy_cleanup),
m_base_url{base_url},
m_request_sequence(0) {
// Disable signal handlers used by libcurl, we're potentially going to use
// timeouts and background threads.
curl_easy_setopt(m_handle.get(), CURLOPT_NOSIGNAL, 1L);
// we're going to automatically follow redirections
curl_easy_setopt(m_handle.get(), CURLOPT_FOLLOWLOCATION, 1L);
// most modern browsers allow for more or less 20 redirections
curl_easy_setopt(m_handle.get(), CURLOPT_MAXREDIRS, 20L);
// introduce ourselves to the server
curl_easy_setopt(m_handle.get(), CURLOPT_USERAGENT,
get_user_agent().c_str());
#if LIBCURL_VERSION_NUM >= 0x071900
// CURLOPT_TCP_KEEPALIVE was added in libcurl 7.25.0
curl_easy_setopt(m_handle.get(), CURLOPT_TCP_KEEPALIVE, 1L);
#endif
// error buffer, once set, must be available until curl_easy_cleanup() is
// called
curl_easy_setopt(m_handle.get(), CURLOPT_ERRORBUFFER, m_error_buffer);
verify_ssl(verify);
// Default timeout for HEAD/DELETE: 30000 milliseconds
// The rest of the operations will timeout if transfer rate is lower than
// one byte in 5 minutes (300 seconds)
set_timeout(30000, 1, 300);
// set the callbacks
curl_easy_setopt(m_handle.get(), CURLOPT_READDATA, nullptr);
curl_easy_setopt(m_handle.get(), CURLOPT_READFUNCTION, request_callback);
curl_easy_setopt(m_handle.get(), CURLOPT_WRITEFUNCTION,
response_data_callback);
curl_easy_setopt(m_handle.get(), CURLOPT_HEADERFUNCTION,
response_header_callback);
#ifdef _WIN32
curl_easy_setopt(m_handle.get(), CURLOPT_CAINFO, nullptr);
curl_easy_setopt(m_handle.get(), CURLOPT_CAPATH, nullptr);
curl_easy_setopt(m_handle.get(), CURLOPT_SSL_CTX_FUNCTION,
*sslctx_function);
#endif // _WIN32
// Initializes the ID for this Rest Service Instance
m_id = "REST-";
if (!label.empty()) m_id += label + "-";
m_id += shcore::get_random_string(
5, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890");
}
~Impl() = default;
void log_request(const Request &request) {
if (shcore::current_logger()->get_log_level() >=
shcore::Logger::LOG_LEVEL::LOG_DEBUG) {
log_debug("%s-%d: %s %s %s", m_id.c_str(), m_request_sequence,
m_base_url.masked().c_str(),
shcore::str_upper(type_name(request.type)).c_str(),
request.path().masked().c_str());
if (!request.headers().empty() &&
shcore::current_logger()->get_log_level() >=
shcore::Logger::LOG_LEVEL::LOG_DEBUG2) {
std::vector<std::string> header_data;
for (const auto &header : request.headers()) {
header_data.push_back("'" + header.first + "' : '" + header.second +
"'");
}
log_debug2("%s-%d: REQUEST HEADERS:\n %s", m_id.c_str(),
m_request_sequence,
shcore::str_join(header_data, "\n ").c_str());
}
}
}
void log_response(int sequence, Response::Status_code code,
const std::string &headers) {
if (shcore::current_logger()->get_log_level() >=
shcore::Logger::LOG_LEVEL::LOG_DEBUG) {
log_debug("%s-%d: %d-%s", m_id.c_str(), sequence, static_cast<int>(code),
Response::status_code(code).c_str());
if (!headers.empty()) {
log_debug2("%s-%d: RESPONSE HEADERS:\n %s", m_id.c_str(), sequence,
headers.c_str());
}
}
}
Response::Status_code execute(bool synch, Request *request,
Response *response = nullptr) {
assert(request);
m_request_sequence++;
log_request(*request);
set_url(request->path().real());
// body needs to be set before the type, because it implicitly sets type
// to POST
set_body(request->body, request->size, synch);
set_type(request->type);
const auto headers_deleter =
set_headers(request->headers(), request->size != 0);
// set callbacks which will receive the response
std::string header_data;
curl_easy_setopt(m_handle.get(), CURLOPT_HEADERDATA, &header_data);
curl_easy_setopt(m_handle.get(), CURLOPT_WRITEDATA,
response ? response->body : nullptr);
// execute the request
auto ret_val = curl_easy_perform(m_handle.get());
if (ret_val != CURLE_OK) {
log_error("%s-%d: %s (CURLcode = %i)", m_id.c_str(), m_request_sequence,
m_error_buffer, ret_val);
throw Connection_error{m_error_buffer};
}
const auto status = get_status_code();
log_response(m_request_sequence, status, header_data);
if (response) {
response->status = status;
response->headers = parse_headers(header_data);
}
return status;
}
void set_body(const char *body, size_t size, bool synch) {
curl_easy_setopt(m_handle.get(), CURLOPT_POSTFIELDSIZE, size);
if (synch) {
curl_easy_setopt(m_handle.get(), CURLOPT_COPYPOSTFIELDS, NULL);
curl_easy_setopt(m_handle.get(), CURLOPT_POSTFIELDS, body);
} else {
curl_easy_setopt(m_handle.get(), CURLOPT_COPYPOSTFIELDS, body);
}
}
void set(const Basic_authentication &basic) {
curl_easy_setopt(m_handle.get(), CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(m_handle.get(), CURLOPT_USERNAME,
basic.username().c_str());
curl_easy_setopt(m_handle.get(), CURLOPT_PASSWORD,
basic.password().c_str());
}
void set_default_headers(const Headers &headers) {
m_default_headers = headers;
}
void set_timeout(long timeout, long low_speed_limit, long low_speed_time) {
m_default_timeout = timeout;
curl_easy_setopt(m_handle.get(), CURLOPT_LOW_SPEED_LIMIT,
static_cast<long>(low_speed_limit));
curl_easy_setopt(m_handle.get(), CURLOPT_LOW_SPEED_TIME,
static_cast<long>(low_speed_time));
}
std::string get_last_request_id() const {
return m_id + "-" + std::to_string(m_request_sequence);
}
private:
void verify_ssl(bool verify) {
curl_easy_setopt(m_handle.get(), CURLOPT_SSL_VERIFYHOST, verify ? 2L : 0L);
curl_easy_setopt(m_handle.get(), CURLOPT_SSL_VERIFYPEER, verify ? 1L : 0L);
}
void set_type(Type type) {
// custom request overwrites any other option, make sure it's set to
// default
curl_easy_setopt(m_handle.get(), CURLOPT_CUSTOMREQUEST, nullptr);
curl_easy_setopt(m_handle.get(), CURLOPT_TIMEOUT_MS, 0);
switch (type) {
case Type::GET:
curl_easy_setopt(m_handle.get(), CURLOPT_HTTPGET, 1L);
break;
case Type::HEAD:
curl_easy_setopt(m_handle.get(), CURLOPT_HTTPGET, 1L);
curl_easy_setopt(m_handle.get(), CURLOPT_NOBODY, 1L);
curl_easy_setopt(m_handle.get(), CURLOPT_TIMEOUT_MS, m_default_timeout);
break;
case Type::POST:
curl_easy_setopt(m_handle.get(), CURLOPT_NOBODY, 0L);
curl_easy_setopt(m_handle.get(), CURLOPT_POST, 1L);
break;
case Type::PUT:
curl_easy_setopt(m_handle.get(), CURLOPT_NOBODY, 0L);
// We could use CURLOPT_UPLOAD here, but that would mean we have to
// provide request data using CURLOPT_READDATA. Using custom request
// allows to always use CURLOPT_COPYPOSTFIELDS.
curl_easy_setopt(m_handle.get(), CURLOPT_CUSTOMREQUEST, "PUT");
break;
case Type::PATCH:
curl_easy_setopt(m_handle.get(), CURLOPT_NOBODY, 0L);
curl_easy_setopt(m_handle.get(), CURLOPT_CUSTOMREQUEST, "PATCH");
break;
case Type::DELETE:
curl_easy_setopt(m_handle.get(), CURLOPT_NOBODY, 0L);
curl_easy_setopt(m_handle.get(), CURLOPT_CUSTOMREQUEST, "DELETE");
curl_easy_setopt(m_handle.get(), CURLOPT_TIMEOUT_MS, m_default_timeout);
break;
}
}
void set_url(const std::string &path) {
curl_easy_setopt(m_handle.get(), CURLOPT_URL,
(m_base_url.real() + path).c_str());
}
std::unique_ptr<curl_slist, void (*)(curl_slist *)> set_headers(
const Headers &headers, bool has_body) {
// create the headers list
curl_slist *header_list = nullptr;
{
// headers which are going to be sent with the request
Headers merged_headers;
// if body is set assume 'application/json' content type
if (has_body) {
merged_headers.emplace(k_content_type, k_application_json);
}
// add default headers
for (const auto &h : m_default_headers) {
merged_headers[h.first] = h.second;
}
// add request-specific headers
for (const auto &h : headers) {
merged_headers[h.first] = h.second;
}
// initialize CURL list
for (const auto &h : merged_headers) {
// empty headers are delimited with semicolons
header_list = curl_slist_append(
header_list,
(h.first + (h.second.empty() ? ";" : ": " + h.second)).c_str());
}
}
// set the headers
curl_easy_setopt(m_handle.get(), CURLOPT_HTTPHEADER, header_list);
// automatically delete the headers when leaving the scope
return std::unique_ptr<curl_slist, void (*)(curl_slist *)>{
header_list, &curl_slist_free_all};
}
Response::Status_code get_status_code() const {
long response_code = 0;
curl_easy_getinfo(m_handle.get(), CURLINFO_RESPONSE_CODE, &response_code);
return static_cast<Response::Status_code>(response_code);
}
std::unique_ptr<CURL, void (*)(CURL *)> m_handle;
char m_error_buffer[CURL_ERROR_SIZE];
Masked_string m_base_url;
Headers m_default_headers;
std::string m_id;
int m_request_sequence;
long m_default_timeout;
};
Rest_service::Rest_service(const Masked_string &base_url, bool verify_ssl,
const std::string &service_label)
: m_impl(std::make_unique<Impl>(base_url, verify_ssl, service_label)) {}
Rest_service::Rest_service(Rest_service &&) = default;
Rest_service &Rest_service::operator=(Rest_service &&) = default;
Rest_service::~Rest_service() = default;
Rest_service &Rest_service::set(const Basic_authentication &basic) {
m_impl->set(basic);
return *this;
}
Rest_service &Rest_service::set_default_headers(const Headers &headers) {
m_impl->set_default_headers(headers);
return *this;
}
Rest_service &Rest_service::set_timeout(long timeout, long low_speed_limit,
long low_speed_time) {
m_impl->set_timeout(timeout, low_speed_limit, low_speed_time);
return *this;
}
String_response Rest_service::get(Request *request) {
request->type = Type::GET;
request->body = nullptr;
request->size = 0;
return execute_internal(request);
}
String_response Rest_service::head(Request *request) {
request->type = Type::HEAD;
request->body = nullptr;
request->size = 0;
return execute_internal(request);
}
String_response Rest_service::post(Request *request) {
request->type = Type::POST;
return execute_internal(request);
}
String_response Rest_service::put(Request *request) {
request->type = Type::PUT;
return execute_internal(request);
}
String_response Rest_service::patch(Request *request) {
request->type = Type::PATCH;
return execute_internal(request);
}
String_response Rest_service::delete_(Request *request) {
request->type = Type::DELETE;
return execute_internal(request);
}
String_response Rest_service::execute_internal(Request *request) {
String_response response;
execute(request, &response);
return response;
}
Response::Status_code Rest_service::execute(Request *request,
Response *response) {
const auto retry_strategy = request->retry_strategy;
if (retry_strategy) {
retry_strategy->init();
}
const auto retry = [&response, &retry_strategy, this](const char *msg) {
if (response && response->body) response->body->clear();
retry_strategy->wait_for_retry();
// this log is to have visibility of the error
log_info("RETRYING %s: %s", m_impl->get_last_request_id().c_str(), msg);
};
while (true) {
try {
const auto code = m_impl->execute(true, request, response);
std::optional<Response_error> error;
if (response) {
error = response->get_error();
}
if (retry_strategy && retry_strategy->should_retry(
code, error ? error.value().what() : "")) {
// A retriable error occurred
retry(shcore::str_format("%d-%s", static_cast<int>(code),
Response::status_code(code).c_str())
.c_str());
} else {
return code;
}
} catch (const std::exception &error) {
if (retry_strategy && retry_strategy->should_retry()) {
// A unexpected error occurred but the retry strategy indicates we
// should retry
retry(error.what());
} else {
throw;
}
}
}
}
} // namespace rest
} // namespace mysqlshdk
| 32.222222 | 80 | 0.656507 | [
"vector"
] |
fa1f7edd4a90aeac37c1dcb709caf7dd600f4fc4 | 7,347 | cc | C++ | src/ir/switch-inst.cc | lung21/llvm-node | e1b800e8023370134684e33ef700dc0e2a83bac2 | [
"MIT"
] | null | null | null | src/ir/switch-inst.cc | lung21/llvm-node | e1b800e8023370134684e33ef700dc0e2a83bac2 | [
"MIT"
] | null | null | null | src/ir/switch-inst.cc | lung21/llvm-node | e1b800e8023370134684e33ef700dc0e2a83bac2 | [
"MIT"
] | null | null | null | #include <nan.h>
#include <llvm/IR/Instructions.h>
#include "basic-block.h"
#include "constant-int.h"
#include "value.h"
#include "switch-inst.h"
NAN_MODULE_INIT(SwitchInstWrapper::Init) {
auto switchInst = Nan::GetFunction(Nan::New(switchInstTemplate())).ToLocalChecked();
Nan::Set(target, Nan::New("SwitchInst").ToLocalChecked(), switchInst);
}
NAN_METHOD(SwitchInstWrapper::New) {
if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Constructor needs to be called with new");
}
if (info.Length() != 1 || !info[0]->IsExternal()) {
return Nan::ThrowTypeError("constructor needs to be called with: SwitchInst: external");
}
auto* switchInst = static_cast<llvm::SwitchInst*>(v8::External::Cast(*info[0])->Value());
auto* wrapper = new SwitchInstWrapper { switchInst };
wrapper->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(SwitchInstWrapper::create) {
if (info.Length() < 3 || !ValueWrapper::isInstance(info[0]) || !BasicBlockWrapper::isInstance(info[1]) || !info[2]->IsUint32() ||
(info.Length() > 3 && !BasicBlockWrapper::isInstance(info[3])) ||
info.Length() > 4) {
return Nan::ThrowTypeError("create needs to be called with: value: Value, default: BasicBlock, numCases: number, insertAtEnd?: BasicBlock");
}
auto* value = ValueWrapper::FromValue(info[0])->getValue();
auto* defaultBasicBlock = BasicBlockWrapper::FromValue(info[1])->getBasicBlock();
uint32_t numCases = Nan::To<uint32_t>(info[2]).FromJust();
llvm::SwitchInst* switchInst = nullptr;
if (info.Length() > 3) {
switchInst = llvm::SwitchInst::Create(value, defaultBasicBlock, numCases);
} else {
auto* insertionPoint = BasicBlockWrapper::FromValue(info[3])->getBasicBlock();
switchInst = llvm::SwitchInst::Create(value, defaultBasicBlock, numCases, insertionPoint);
}
info.GetReturnValue().Set(SwitchInstWrapper::of(switchInst));
}
NAN_GETTER(SwitchInstWrapper::getCondition) {
auto* switchInst = SwitchInstWrapper::FromValue(info.Holder())->getSwitchInst();
info.GetReturnValue().Set(ValueWrapper::of(switchInst->getCondition()));
}
NAN_SETTER(SwitchInstWrapper::setCondition) {
if (!ValueWrapper::isInstance(value)) {
return Nan::ThrowTypeError("setCondition needs to be called with condition: Value");
}
auto* switchInst = SwitchInstWrapper::FromValue(info.Holder())->getSwitchInst();
auto* condition = ValueWrapper::FromValue(value)->getValue();
switchInst->setCondition(condition);
}
NAN_GETTER(SwitchInstWrapper::getDefaultDest) {
auto* switchInst = SwitchInstWrapper::FromValue(info.Holder())->getSwitchInst();
auto* defaultDest = switchInst->getDefaultDest();
info.GetReturnValue().Set(BasicBlockWrapper::of(defaultDest));
}
NAN_SETTER(SwitchInstWrapper::setDefaultDest) {
if (!BasicBlockWrapper::isInstance(value)) {
return Nan::ThrowTypeError("setDefaultDest needs to be called with defaultDest: BasicBlock");
}
auto* defaultDest = BasicBlockWrapper::FromValue(value)->getBasicBlock();
auto* switchInst = SwitchInstWrapper::FromValue(info.Holder())->getSwitchInst();
switchInst->setDefaultDest(defaultDest);
}
NAN_GETTER(SwitchInstWrapper::getNumCases) {
auto* switchInst = SwitchInstWrapper::FromValue(info.Holder())->getSwitchInst();
uint32_t numCases = switchInst->getNumCases();
info.GetReturnValue().Set(numCases);
}
NAN_METHOD(SwitchInstWrapper::addCase) {
if (info.Length() < 2 || !ConstantIntWrapper::isInstance(info[0]) || !BasicBlockWrapper::isInstance(info[1]) || info.Length() > 2) {
return Nan::ThrowTypeError("addCase needs to be called with onVal: ConstantInt, dest: BasicBlock");
}
auto* onVal = ConstantIntWrapper::FromValue(info[0])->getConstantInt();
auto* dest = BasicBlockWrapper::FromValue(info[1])->getBasicBlock();
auto* switchInst = SwitchInstWrapper::FromValue(info.Holder())->getSwitchInst();
switchInst->addCase(onVal, dest);
}
NAN_GETTER(SwitchInstWrapper::getNumSuccessors) {
auto* switchInst = SwitchInstWrapper::FromValue(info.Holder())->getSwitchInst();
uint32_t numSuccessors = switchInst->getNumSuccessors();
info.GetReturnValue().Set(numSuccessors);
}
NAN_METHOD(SwitchInstWrapper::getSuccessor) {
if (info.Length() != 1 || !info[0]->IsUint32()) {
return Nan::ThrowTypeError("getSuccessor needs to be called with idx: number");
}
uint32_t idx = Nan::To<uint32_t>(info[0]).FromJust();
auto* switchInst = SwitchInstWrapper::FromValue(info.Holder())->getSwitchInst();
auto* successor = switchInst->getSuccessor(idx);
info.GetReturnValue().Set(BasicBlockWrapper::of(successor));
}
NAN_METHOD(SwitchInstWrapper::setSuccessor) {
if (info.Length() != 2 || !info[0]->IsUint32() || !BasicBlockWrapper::isInstance(info[1])) {
return Nan::ThrowTypeError("getSuccessor needs to be called with idx: number");
}
auto* switchInst = SwitchInstWrapper::FromValue(info.Holder())->getSwitchInst();
uint32_t idx = Nan::To<uint32_t>(info[0]).FromJust();
auto* newSuccessor = BasicBlockWrapper::FromValue(info[1])->getBasicBlock();
switchInst->setSuccessor(idx, newSuccessor);
}
Nan::Persistent<v8::FunctionTemplate>& SwitchInstWrapper::switchInstTemplate() {
static Nan::Persistent<v8::FunctionTemplate> functionTemplate {};
if (functionTemplate.IsEmpty()) {
auto localTemplate = Nan::New<v8::FunctionTemplate>(SwitchInstWrapper::New);
localTemplate->SetClassName(Nan::New("SwitchInst").ToLocalChecked());
localTemplate->Inherit(Nan::New(valueTemplate()));
localTemplate->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetMethod(localTemplate, "create", SwitchInstWrapper::create);
Nan::SetPrototypeMethod(localTemplate, "addCase", SwitchInstWrapper::addCase);
Nan::SetPrototypeMethod(localTemplate, "setSuccessor", SwitchInstWrapper::setSuccessor);
Nan::SetPrototypeMethod(localTemplate, "setSuccessor", SwitchInstWrapper::setSuccessor);
Nan::SetAccessor(localTemplate->InstanceTemplate(), Nan::New("condition").ToLocalChecked(), SwitchInstWrapper::getCondition, SwitchInstWrapper::setCondition);
Nan::SetAccessor(localTemplate->InstanceTemplate(), Nan::New("defaultDest").ToLocalChecked(), SwitchInstWrapper::getDefaultDest, SwitchInstWrapper::setDefaultDest);
Nan::SetAccessor(localTemplate->InstanceTemplate(), Nan::New("numCases").ToLocalChecked(), SwitchInstWrapper::getNumCases);
Nan::SetAccessor(localTemplate->InstanceTemplate(), Nan::New("numSuccessors").ToLocalChecked(), SwitchInstWrapper::getNumSuccessors);
functionTemplate.Reset(localTemplate);
}
return functionTemplate;
}
v8::Local<v8::Object> SwitchInstWrapper::of(llvm::SwitchInst *switchInst) {
auto constructorFunction = Nan::GetFunction(Nan::New(switchInstTemplate())).ToLocalChecked();
v8::Local<v8::Value> args[1] = { Nan::New<v8::External>(switchInst) };
auto instance = Nan::NewInstance(constructorFunction, 1, args).ToLocalChecked();
Nan::EscapableHandleScope escapeScpoe {};
return escapeScpoe.Escape(instance);
}
llvm::SwitchInst* SwitchInstWrapper::getSwitchInst() {
return static_cast<llvm::SwitchInst*>(getValue());
} | 45.07362 | 172 | 0.713897 | [
"object"
] |
fa2ec669af72ce6e1cf38dd0ec2e776533ac50b6 | 930 | cc | C++ | all_perms_agency_2.cc | lljbash/AllPerms | 72e2ddaa2a74fc39d0d46ef0f7e4746840244288 | [
"MIT"
] | 1 | 2018-11-11T10:02:11.000Z | 2018-11-11T10:02:11.000Z | all_perms_agency_2.cc | lljbash/AllPerms | 72e2ddaa2a74fc39d0d46ef0f7e4746840244288 | [
"MIT"
] | null | null | null | all_perms_agency_2.cc | lljbash/AllPerms | 72e2ddaa2a74fc39d0d46ef0f7e4746840244288 | [
"MIT"
] | null | null | null | #include "all_perms_agency_2.h"
#include <algorithm>
#include <numeric>
using namespace all_perms;
void AllPermsAgency2::initialize(int n) {
perms_.resize(n);
std::iota(perms_.begin(), perms_.end(), 0);
agency_ = std::vector<int>(n - 1);
position_ = perms_;
}
void AllPermsAgency2::step() {
int n = perms_.size();
++agency_.back();
int i = n - 2;
for (; i >= 0 && agency_[i] > n-i-1; --i) {
agency_[i] = 0;
if (i > 0) {
++agency_[i-1];
}
}
if (i < 0) {
initialize(n);
}
else {
int k = n - i - 1;
int j = k - agency_[i];
for (int l = 0, r = k-1; l < r; ++l, --r) {
std::swap(perms_[position_[l]], perms_[position_[r]]);
std::swap(position_[l], position_[r]);
}
std::swap(perms_[position_[j]], perms_[position_[k]]);
std::swap(position_[j], position_[k]);
}
}
| 23.846154 | 66 | 0.503226 | [
"vector"
] |
fa3c26791863e971871b3179d08dd8c829921f4a | 2,241 | cpp | C++ | SPOJ/CODESPTB - Insertion Sort.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 6 | 2018-11-26T02:38:07.000Z | 2021-07-28T00:16:41.000Z | SPOJ/CODESPTB - Insertion Sort.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 1 | 2021-05-30T09:25:53.000Z | 2021-06-05T08:33:56.000Z | SPOJ/CODESPTB - Insertion Sort.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 4 | 2020-04-16T07:15:01.000Z | 2020-12-04T06:26:07.000Z | /*CODESPTB - Insertion Sort
#tree
Insertion Sort is a classical sorting technique. One variant of insertion sort works as follows when sorting an array a[1..N] in non-descending order:
for i <- 2 to N
j <- i
while j > 1 and a[j] < a[j - 1]
swap a[j] and a[j - 1]
j <- j - 1
The pseudocode is simple to follow. In the ith step, element a[i] is inserted in the sorted sequence a[1..i - 1]. This is done by moving a[i] backward by swapping it with the previous element until it ends up in it's right position.
As you probably already know, the algorithm can be really slow. To study this more, you want to find out the number of times the swap operation is performed when sorting an array.
Input
The first line contains the number of test cases T. T test cases follow. The first line for each case contains N, the number of elements to be sorted. The next line contains N integers a[1],a[2]...,a[N].
Output
Output T lines, containing the required answer for each test case.
Constraints
1 <= T <= 5
1 <= N <= 100000
1 <= a[i] <= 1000000
Example
Sample Input:
2
5
1 1 1 2 2
5
2 1 3 1 2
Sample Output:
0
4
*/
#include <algorithm>
#include <cstring>
#include <iostream>
#include <vector>
#include <utility>
long BIT[100001];
void update_bit(int pos, int n)
{
while (pos <= n)
{
BIT[pos]++;
pos += (pos & -pos);
}
}
long query_bit(int pos)
{
long sum = 0;
while (pos > 0)
{
sum += BIT[pos];
pos -= (pos & -pos);
}
return sum;
}
int main()
{
int tests;
std::cin >> tests;
while (tests--)
{
int n;
std::cin >> n;
std::memset(BIT, 0, sizeof(long) * (n+1));
std::vector<std::pair<int,int>> arr (n);
for (int i = 0; i < n; ++i)
{
std::cin >> arr[i].first; // Value
arr[i].second = i+1; // 1 based index
}
std::sort(arr.rbegin(), arr.rend());
long res = 0;
for (int i = 0; i < n; ++i)
{
res += query_bit(arr[i].second);
update_bit(arr[i].second, n);
}
std::cout << res << std::endl;
}
return 0;
}
| 21.342857 | 232 | 0.560464 | [
"vector"
] |
fa3c65b054a6008126c6a0ad9fa5b3c149895f84 | 8,444 | cpp | C++ | ms-utils/simulation/hs/TsHsMsgStdFilter.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 18 | 2020-01-23T12:14:09.000Z | 2022-02-27T22:11:35.000Z | ms-utils/simulation/hs/TsHsMsgStdFilter.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 39 | 2020-11-20T12:19:35.000Z | 2022-02-22T18:45:55.000Z | ms-utils/simulation/hs/TsHsMsgStdFilter.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 7 | 2020-02-10T19:25:43.000Z | 2022-03-16T01:10:00.000Z | /****************************************** TRICK HEADER ******************************************
@copyright Copyright 2019 United States Government as represented by the Administrator of the
National Aeronautics and Space Administration. All Rights Reserved.
PURPOSE:
(Extends the TsHsMsgFilter class and implements its shouldSendMessage filter method.)
REQUIREMENTS:
()
REFERENCE:
()
ASSUMPTIONS AND LIMITATIONS:
()
LIBRARY DEPENDENCY:
(
(simulation/hs/TsHsMsgStdFilter.o)
(simulation/hs/TsHsMsgFilter.o)
)
PROGRAMMERS:
(((Wesley A. White) (Tietronix Software) (August 2011)))
**************************************************************************************************/
#include <iostream>
#include <sstream>
#include "sim_services/Message/include/message_proto.h"
#include "TsHsMsgStdFilter.hh"
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Constructor
////////////////////////////////////////////////////////////////////////////////////////////////////
TsHsMsgStdFilter::TsHsMsgStdFilter() :
mMessageMap(),
mTryLockFailures(0),
mResourceLock()
{
pthread_mutex_init(&mResourceLock, NULL);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Reinitialize the message filter after a restart. The data structure used to
/// store the message history is too complicated for trick to checkpoint. So we
/// reinitialize here by clearing the history. This means we might get a few more
/// redundant messages until the message history repopulates.
////////////////////////////////////////////////////////////////////////////////////////////////////
void TsHsMsgStdFilter::restart()
{
// Clear the message history
if (mMessageMap.size() > 0)
{
mMessageMap.clear();
}
// Reset try-lock failure count. Maybe we should checkpoint and restore this value?
mTryLockFailures = 0;
// Reset the mutex. Not sure if this gains us anything. The checkpoint wouldn't have been cut until
// all the model threads were in freeze, i.e. all HS clients had released their resource locks.
pthread_mutex_destroy(&mResourceLock);
pthread_mutex_init(&mResourceLock, NULL);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Destructor
////////////////////////////////////////////////////////////////////////////////////////////////////
TsHsMsgStdFilter::~TsHsMsgStdFilter()
{
// Empty
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Removes times from the deque which precede the current interval of interest.
///
/// @param[in,out] times (--) The deque containing times that a particular message occurred.
/// @param[in] intervalStart (--) We are not interested in times earlier that this.
////////////////////////////////////////////////////////////////////////////////////////////////////
void TsHsMsgStdFilter::purgeTimes(TsHsTimesDeque& times, double intervalStart)
{
while (!times.empty() && times.front() < intervalStart)
{
times.pop_front();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Finds and removes the oldest message in the map.
////////////////////////////////////////////////////////////////////////////////////////////////////
void TsHsMsgStdFilter::purgeMessages()
{
if (mMessageMap.size() == 0)
{
return;
}
TsHsMessageMap::iterator oldest = mMessageMap.begin();
for (TsHsMessageMap::iterator iter = ++oldest; iter != mMessageMap.end(); iter++)
{
if ((*iter).second.back() < (*oldest).second.back())
{
oldest = iter;
}
}
mMessageMap.erase(oldest);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Compares a message with previous ones to see the message should be suppressed or not.
/// The assumption is that the timestamp also represents the current time.
///
/// @param[in] timestamp (--) Time that message was received by filter. The MET "seconds" field
/// of a TS_TIMER_TYPE structure which is created by the HS sim object.
/// @param[in] file (--) Source file name invoking 'send'; typically __FILE__ macro is used.
/// @param[in] line (--) Line in file invoking 'send'; typically __LINE__ macro is used.
/// @param[in] type (--) Enumeration constant that represents the type of message.
/// @param[in] subsys (--) The subsystem that is logging the message.
/// @param[in] mtext (--) The message text.
///
/// @return true if message should be displayed; false if message should be suppressed.
///
/// @note The algorithm expects that in consecutive calls to this method, the value of timestamp
/// is increasing. The algorithm will not function correctly if time is moving backwards.
////////////////////////////////////////////////////////////////////////////////////////////////////
bool TsHsMsgStdFilter::shouldSendMessage(
const double timestamp,
const std::string& file,
const int line,
TS_HS_MSG_TYPE type,
const std::string& subsys,
const std::string& mtext
)
{
typedef std::pair< std::string,TsHsTimesDeque > TsHsMessageMapPair;
if (!mEnabled)
{
return true;
}
if (mBlocking)
{
// Wait for resource
if (pthread_mutex_lock(&mResourceLock) != 0) // non-0 means lock failed
{
// This should never happen. If we wait, we should eventually get the lock.
message_publish(MSG_ERROR, "TsHsMsgStdFilter::shouldSendMessage failed to get resource lock\n");
}
}
else
{
// Skip logging the message if there's a mutex conflict
if (pthread_mutex_trylock(&mResourceLock) != 0) // non-0 means lock failed
{
++mTryLockFailures;
return false;
}
}
++mMessagesProcessed;
// If the message we are attempting to log is of a type that has been categorically filtering out, then
// suppress the message.
if (isTypeFiltered(type))
{
++mMessagesSuppressed;
pthread_mutex_unlock(&mResourceLock);
return false;
}
// Construct a message string to present to the filter. This doesn't have to
// be identical to the message string that actually gets output to the log.
std::ostringstream oss;
oss << file << "|" << line << "|" << subsys << "|" << mtext << std::ends;
std::string message(oss.str());
// Attempt to locate this message in the message map.
TsHsMessageMap::iterator iter = mMessageMap.find(message);
if (iter == mMessageMap.end())
{
// The message was not found in map. If the map is full, bump the oldest message.
// Insert the new message/time. Return a value indicating the message should be displayed.
while (static_cast<int>(mMessageMap.size()) >= mHistory)
{
purgeMessages();
}
TsHsTimesDeque times;
times.push_back(timestamp);
mMessageMap.insert(TsHsMessageMapPair(message, times));
pthread_mutex_unlock(&mResourceLock);
return true;
}
else
{
// The message was found in map. Compute the beginning of the interval
// and get rid of any times that precede it. If the deque is not full,
// add the new time to it. Otherwise, if the deque is full, then the count has
// been reached or exceeded, so suppress the message.
double interval_start = timestamp - mInterval;
purgeTimes((*iter).second, interval_start);
if (static_cast<int>((*iter).second.size()) < mCount)
{
(*iter).second.push_back(timestamp);
pthread_mutex_unlock(&mResourceLock);
return true;
}
else
{
++mMessagesSuppressed;
pthread_mutex_unlock(&mResourceLock);
return false;
}
}
pthread_mutex_unlock(&mResourceLock);
return false; // compiler thinks it can get here so it wants a value returned
}
| 37.198238 | 108 | 0.539792 | [
"object",
"model"
] |
fa4d16919f33ac2628a9e5a251a8baf9a37585f2 | 45,276 | hxx | C++ | VTK/ThirdParty/vtkm/vtk-m/vtkm/rendering/raytracing/ConnectivityTracer.hxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | VTK/ThirdParty/vtkm/vtk-m/vtkm/rendering/raytracing/ConnectivityTracer.hxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | VTK/ThirdParty/vtkm/vtk-m/vtkm/rendering/raytracing/ConnectivityTracer.hxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | //============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
// Copyright 2015 UT-Battelle, LLC.
// Copyright 2015 Los Alamos National Security.
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#include <vtkm/cont/DeviceAdapterAlgorithm.h>
#include <vtkm/cont/ErrorBadValue.h>
#include <vtkm/cont/Timer.h>
#include <vtkm/cont/TryExecute.h>
#include <vtkm/rendering/raytracing/Camera.h>
#include <vtkm/rendering/raytracing/CellIntersector.h>
#include <vtkm/rendering/raytracing/CellSampler.h>
#include <vtkm/rendering/raytracing/CellTables.h>
#include <vtkm/rendering/raytracing/ConnectivityBase.h>
#include <vtkm/rendering/raytracing/MeshConnectivityStructures.h>
#include <vtkm/rendering/raytracing/Ray.h>
#include <vtkm/rendering/raytracing/RayOperations.h>
#include <vtkm/rendering/raytracing/RayTracingTypeDefs.h>
#include <vtkm/rendering/raytracing/Worklets.h>
#include <vtkm/worklet/DispatcherMapField.h>
#include <vtkm/worklet/DispatcherMapTopology.h>
#include <vtkm/worklet/WorkletMapField.h>
#include <vtkm/worklet/WorkletMapTopology.h>
namespace vtkm
{
namespace rendering
{
namespace raytracing
{
namespace detail
{
template <typename FloatType>
template <typename Device>
void RayTracking<FloatType>::Compact(vtkm::cont::ArrayHandle<FloatType>& compactedDistances,
vtkm::cont::ArrayHandle<UInt8>& masks,
Device)
{
//
// These distances are stored in the rays, and it has
// already been compacted.
//
CurrentDistance = compactedDistances;
vtkm::cont::ArrayHandleCast<vtkm::Id, vtkm::cont::ArrayHandle<vtkm::UInt8>> castedMasks(masks);
bool distance1IsEnter = EnterDist == &Distance1;
vtkm::cont::ArrayHandle<FloatType> compactedDistance1;
vtkm::cont::DeviceAdapterAlgorithm<Device>::CopyIf(Distance1, masks, compactedDistance1);
Distance1 = compactedDistance1;
vtkm::cont::ArrayHandle<FloatType> compactedDistance2;
vtkm::cont::DeviceAdapterAlgorithm<Device>::CopyIf(Distance2, masks, compactedDistance2);
Distance2 = compactedDistance2;
vtkm::cont::ArrayHandle<vtkm::Int32> compactedExitFace;
vtkm::cont::DeviceAdapterAlgorithm<Device>::CopyIf(ExitFace, masks, compactedExitFace);
ExitFace = compactedExitFace;
if (distance1IsEnter)
{
EnterDist = &Distance1;
ExitDist = &Distance2;
}
else
{
EnterDist = &Distance2;
ExitDist = &Distance1;
}
}
template <typename FloatType>
template <typename Device>
void RayTracking<FloatType>::Init(const vtkm::Id size,
vtkm::cont::ArrayHandle<FloatType>& distances,
Device)
{
ExitFace.PrepareForOutput(size, Device());
Distance1.PrepareForOutput(size, Device());
Distance2.PrepareForOutput(size, Device());
CurrentDistance = distances;
//
// Set the initial Distances
//
vtkm::worklet::DispatcherMapField<CopyAndOffset<FloatType>, Device>(
CopyAndOffset<FloatType>(0.0f))
.Invoke(distances, *EnterDist);
//
// Init the exit faces. This value is used to load the next cell
// base on the cell and face it left
//
vtkm::worklet::DispatcherMapField<MemSet<vtkm::Int32>, Device>(MemSet<vtkm::Int32>(-1))
.Invoke(ExitFace);
vtkm::worklet::DispatcherMapField<MemSet<FloatType>, Device>(MemSet<FloatType>(-1))
.Invoke(*ExitDist);
}
template <typename FloatType>
void RayTracking<FloatType>::Swap()
{
vtkm::cont::ArrayHandle<FloatType>* tmpPtr;
tmpPtr = EnterDist;
EnterDist = ExitDist;
ExitDist = tmpPtr;
}
} //namespace detail
//
// Advance Ray
// After a ray leaves the mesh, we need to check to see
// of the ray re-enters the mesh within this domain. This
// function moves the ray forward some offset to prevent
// "shadowing" and hitting the same exit point.
//
template <typename FloatType>
class AdvanceRay : public vtkm::worklet::WorkletMapField
{
FloatType Offset;
public:
VTKM_CONT
AdvanceRay(const FloatType offset = 0.00001)
: Offset(offset)
{
}
using ControlSignature = void(FieldIn<>, FieldInOut<>);
using ExecutionSignature = void(_1, _2);
VTKM_EXEC inline void operator()(const vtkm::UInt8& status, FloatType& distance) const
{
if (status == RAY_EXITED_MESH)
distance += Offset;
}
}; //class AdvanceRay
template <vtkm::Int32 CellType, typename FloatType, typename MeshType>
class LocateCell : public vtkm::worklet::WorkletMapField
{
private:
MeshType MeshConn;
CellIntersector<CellType> Intersector;
public:
template <typename ConnectivityType>
LocateCell(ConnectivityType& meshConn)
: MeshConn(meshConn)
{
}
using ControlSignature = void(FieldInOut<>,
WholeArrayIn<>,
FieldIn<>,
FieldInOut<>,
FieldInOut<>,
FieldInOut<>,
FieldInOut<>,
FieldIn<>);
using ExecutionSignature = void(_1, _2, _3, _4, _5, _6, _7, _8);
template <typename PointPortalType>
VTKM_EXEC inline void operator()(vtkm::Id& currentCell,
PointPortalType& vertices,
const vtkm::Vec<FloatType, 3>& dir,
FloatType& enterDistance,
FloatType& exitDistance,
vtkm::Int32& enterFace,
vtkm::UInt8& rayStatus,
const vtkm::Vec<FloatType, 3>& origin) const
{
if (enterFace != -1 && rayStatus == RAY_ACTIVE)
{
currentCell = MeshConn.GetConnectingCell(currentCell, enterFace);
if (currentCell == -1)
rayStatus = RAY_EXITED_MESH;
enterFace = -1;
}
//This ray is dead or exited the mesh and needs re-entry
if (rayStatus != RAY_ACTIVE)
{
return;
}
FloatType xpoints[8];
FloatType ypoints[8];
FloatType zpoints[8];
vtkm::Id cellConn[8];
FloatType distances[6];
const vtkm::Int32 numIndices = MeshConn.GetCellIndices(cellConn, currentCell);
//load local cell data
for (int i = 0; i < numIndices; ++i)
{
BOUNDS_CHECK(vertices, cellConn[i]);
vtkm::Vec<FloatType, 3> point = vtkm::Vec<FloatType, 3>(vertices.Get(cellConn[i]));
xpoints[i] = point[0];
ypoints[i] = point[1];
zpoints[i] = point[2];
}
const vtkm::UInt8 cellShape = MeshConn.GetCellShape(currentCell);
Intersector.IntersectCell(xpoints, ypoints, zpoints, dir, origin, distances, cellShape);
CellTables tables;
const vtkm::Int32 numFaces = tables.FaceLookUp(tables.CellTypeLookUp(cellShape), 1);
//vtkm::Int32 minFace = 6;
vtkm::Int32 maxFace = -1;
FloatType minDistance = static_cast<FloatType>(1e32);
FloatType maxDistance = static_cast<FloatType>(-1);
int hitCount = 0;
for (vtkm::Int32 i = 0; i < numFaces; ++i)
{
FloatType dist = distances[i];
if (dist != -1)
{
hitCount++;
if (dist < minDistance)
{
minDistance = dist;
//minFace = i;
}
if (dist > maxDistance)
{
maxDistance = dist;
maxFace = i;
}
}
}
if (maxDistance <= enterDistance || minDistance == maxDistance)
{
rayStatus = RAY_LOST;
}
else
{
enterDistance = minDistance;
exitDistance = maxDistance;
enterFace = maxFace;
}
} //operator
}; //class LocateCell
template <vtkm::Int32 CellType, typename FloatType, typename Device, typename MeshType>
class RayBumper : public vtkm::worklet::WorkletMapField
{
private:
using FloatTypeHandle = typename vtkm::cont::ArrayHandle<FloatType>;
using FloatTypePortal = typename FloatTypeHandle::template ExecutionTypes<Device>::Portal;
FloatTypePortal DirectionsX;
FloatTypePortal DirectionsY;
FloatTypePortal DirectionsZ;
MeshType MeshConn;
CellIntersector<CellType> Intersector;
const vtkm::UInt8 FailureStatus; // the status to assign ray if we fail to find the intersection
public:
template <typename ConnectivityType>
RayBumper(FloatTypeHandle dirsx,
FloatTypeHandle dirsy,
FloatTypeHandle dirsz,
ConnectivityType meshConn,
vtkm::UInt8 failureStatus = RAY_ABANDONED)
: DirectionsX(dirsx.PrepareForInPlace(Device()))
, DirectionsY(dirsy.PrepareForInPlace(Device()))
, DirectionsZ(dirsz.PrepareForInPlace(Device()))
, MeshConn(meshConn)
, FailureStatus(failureStatus)
{
}
using ControlSignature = void(FieldInOut<>,
WholeArrayIn<>,
FieldInOut<>,
FieldInOut<>,
FieldInOut<>,
FieldInOut<>,
FieldIn<>);
using ExecutionSignature = void(_1, _2, _3, _4, _5, WorkIndex, _6, _7);
template <typename PointPortalType>
VTKM_EXEC inline void operator()(vtkm::Id& currentCell,
PointPortalType& vertices,
FloatType& enterDistance,
FloatType& exitDistance,
vtkm::Int32& enterFace,
const vtkm::Id& pixelIndex,
vtkm::UInt8& rayStatus,
const vtkm::Vec<FloatType, 3>& origin) const
{
// We only process lost rays
if (rayStatus != RAY_LOST)
{
return;
}
FloatType xpoints[8];
FloatType ypoints[8];
FloatType zpoints[8];
vtkm::Id cellConn[8];
FloatType distances[6];
vtkm::Vec<FloatType, 3> centroid(0., 0., 0.);
const vtkm::Int32 numIndices = MeshConn.GetCellIndices(cellConn, currentCell);
//load local cell data
for (int i = 0; i < numIndices; ++i)
{
BOUNDS_CHECK(vertices, cellConn[i]);
vtkm::Vec<FloatType, 3> point = vtkm::Vec<FloatType, 3>(vertices.Get(cellConn[i]));
centroid = centroid + point;
xpoints[i] = point[0];
ypoints[i] = point[1];
zpoints[i] = point[2];
}
FloatType invNumIndices = static_cast<FloatType>(1.) / static_cast<FloatType>(numIndices);
centroid[0] = centroid[0] * invNumIndices;
centroid[1] = centroid[1] * invNumIndices;
centroid[2] = centroid[2] * invNumIndices;
vtkm::Vec<FloatType, 3> toCentroid = centroid - origin;
vtkm::Normalize(toCentroid);
vtkm::Vec<FloatType, 3> dir(
DirectionsX.Get(pixelIndex), DirectionsY.Get(pixelIndex), DirectionsZ.Get(pixelIndex));
vtkm::Vec<FloatType, 3> bump = toCentroid - dir;
dir = dir + RAY_TUG_EPSILON * bump;
vtkm::Normalize(dir);
DirectionsX.Set(pixelIndex, dir[0]);
DirectionsY.Set(pixelIndex, dir[1]);
DirectionsZ.Set(pixelIndex, dir[2]);
const vtkm::UInt8 cellShape = MeshConn.GetCellShape(currentCell);
Intersector.IntersectCell(xpoints, ypoints, zpoints, dir, origin, distances, cellShape);
CellTables tables;
const vtkm::Int32 numFaces = tables.FaceLookUp(tables.CellTypeLookUp(cellShape), 1);
//vtkm::Int32 minFace = 6;
vtkm::Int32 maxFace = -1;
FloatType minDistance = static_cast<FloatType>(1e32);
FloatType maxDistance = static_cast<FloatType>(-1);
int hitCount = 0;
for (int i = 0; i < numFaces; ++i)
{
FloatType dist = distances[i];
if (dist != -1)
{
hitCount++;
if (dist < minDistance)
{
minDistance = dist;
//minFace = i;
}
if (dist >= maxDistance)
{
maxDistance = dist;
maxFace = i;
}
}
}
if (minDistance >= maxDistance)
{
rayStatus = FailureStatus;
}
else
{
enterDistance = minDistance;
exitDistance = maxDistance;
enterFace = maxFace;
rayStatus = RAY_ACTIVE; //re-activate ray
}
} //operator
}; //class RayBumper
template <typename FloatType>
class AddPathLengths : public vtkm::worklet::WorkletMapField
{
public:
VTKM_CONT
AddPathLengths() {}
using ControlSignature = void(FieldIn<RayStatusType>, // ray status
FieldIn<ScalarRenderingTypes>, // cell enter distance
FieldIn<ScalarRenderingTypes>, // cell exit distance
FieldInOut<ScalarRenderingTypes>); // ray absorption data
using ExecutionSignature = void(_1, _2, _3, _4);
VTKM_EXEC inline void operator()(const vtkm::UInt8& rayStatus,
const FloatType& enterDistance,
const FloatType& exitDistance,
FloatType& distance) const
{
if (rayStatus != RAY_ACTIVE)
{
return;
}
if (exitDistance <= enterDistance)
{
return;
}
FloatType segmentLength = exitDistance - enterDistance;
distance += segmentLength;
}
};
template <typename FloatType>
class Integrate : public vtkm::worklet::WorkletMapField
{
private:
const vtkm::Int32 NumBins;
public:
VTKM_CONT
Integrate(const vtkm::Int32 numBins)
: NumBins(numBins)
{
}
using ControlSignature = void(FieldIn<RayStatusType>, // ray status
FieldIn<ScalarRenderingTypes>, // cell enter distance
FieldIn<ScalarRenderingTypes>, // cell exit distance
FieldInOut<ScalarRenderingTypes>, // current distance
WholeArrayIn<ScalarRenderingTypes>, // cell absorption data array
WholeArrayInOut<ScalarRenderingTypes>, // ray absorption data
FieldIn<IdType>); // current cell
using ExecutionSignature = void(_1, _2, _3, _4, _5, _6, _7, WorkIndex);
template <typename CellDataPortalType, typename RayDataPortalType>
VTKM_EXEC inline void operator()(const vtkm::UInt8& rayStatus,
const FloatType& enterDistance,
const FloatType& exitDistance,
FloatType& currentDistance,
const CellDataPortalType& cellData,
RayDataPortalType& energyBins,
const vtkm::Id& currentCell,
const vtkm::Id& rayIndex) const
{
if (rayStatus != RAY_ACTIVE)
{
return;
}
if (exitDistance <= enterDistance)
{
return;
}
FloatType segmentLength = exitDistance - enterDistance;
vtkm::Id rayOffset = NumBins * rayIndex;
vtkm::Id cellOffset = NumBins * currentCell;
for (vtkm::Int32 i = 0; i < NumBins; ++i)
{
BOUNDS_CHECK(cellData, cellOffset + i);
FloatType absorb = static_cast<FloatType>(cellData.Get(cellOffset + i));
absorb = vtkm::Exp(-absorb * segmentLength);
BOUNDS_CHECK(energyBins, rayOffset + i);
FloatType intensity = static_cast<FloatType>(energyBins.Get(rayOffset + i));
energyBins.Set(rayOffset + i, intensity * absorb);
}
currentDistance = exitDistance;
}
};
template <typename FloatType>
class IntegrateEmission : public vtkm::worklet::WorkletMapField
{
private:
const vtkm::Int32 NumBins;
bool DivideEmisByAbsorb;
public:
VTKM_CONT
IntegrateEmission(const vtkm::Int32 numBins, const bool divideEmisByAbsorb)
: NumBins(numBins)
, DivideEmisByAbsorb(divideEmisByAbsorb)
{
}
using ControlSignature = void(FieldIn<>, // ray status
FieldIn<>, // cell enter distance
FieldIn<>, // cell exit distance
FieldInOut<>, // current distance
WholeArrayIn<ScalarRenderingTypes>, // cell absorption data array
WholeArrayIn<ScalarRenderingTypes>, // cell emission data array
WholeArrayInOut<>, // ray absorption data
WholeArrayInOut<>, // ray emission data
FieldIn<>); // current cell
using ExecutionSignature = void(_1, _2, _3, _4, _5, _6, _7, _8, _9, WorkIndex);
template <typename CellAbsPortalType, typename CellEmisPortalType, typename RayDataPortalType>
VTKM_EXEC inline void operator()(const vtkm::UInt8& rayStatus,
const FloatType& enterDistance,
const FloatType& exitDistance,
FloatType& currentDistance,
const CellAbsPortalType& absorptionData,
const CellEmisPortalType& emissionData,
RayDataPortalType& absorptionBins,
RayDataPortalType& emissionBins,
const vtkm::Id& currentCell,
const vtkm::Id& rayIndex) const
{
if (rayStatus != RAY_ACTIVE)
{
return;
}
if (exitDistance <= enterDistance)
{
return;
}
FloatType segmentLength = exitDistance - enterDistance;
vtkm::Id rayOffset = NumBins * rayIndex;
vtkm::Id cellOffset = NumBins * currentCell;
for (vtkm::Int32 i = 0; i < NumBins; ++i)
{
BOUNDS_CHECK(absorptionData, cellOffset + i);
FloatType absorb = static_cast<FloatType>(absorptionData.Get(cellOffset + i));
BOUNDS_CHECK(emissionData, cellOffset + i);
FloatType emission = static_cast<FloatType>(emissionData.Get(cellOffset + i));
if (DivideEmisByAbsorb)
{
emission /= absorb;
}
FloatType tmp = vtkm::Exp(-absorb * segmentLength);
BOUNDS_CHECK(absorptionBins, rayOffset + i);
//
// Traditionally, we would only keep track of a single intensity value per ray
// per bin and we would integrate from the beginning to end of the ray. In a
// distributed memory setting, we would move cell data around so that the
// entire ray could be traced, but in situ, moving that much cell data around
// could blow memory. Here we are keeping track of two values. Total absorption
// through this contiguous segment of the mesh, and the amount of emitted energy
// that makes it out of this mesh segment. If this is really run on a single node,
// we can get the final energy value by multiplying the background intensity by
// the total absorption of the mesh segment and add in the amount of emitted
// energy that escapes.
//
FloatType absorbIntensity = static_cast<FloatType>(absorptionBins.Get(rayOffset + i));
FloatType emissionIntensity = static_cast<FloatType>(emissionBins.Get(rayOffset + i));
absorptionBins.Set(rayOffset + i, absorbIntensity * tmp);
emissionIntensity = emissionIntensity * tmp + emission * (1.f - tmp);
BOUNDS_CHECK(emissionBins, rayOffset + i);
emissionBins.Set(rayOffset + i, emissionIntensity);
}
currentDistance = exitDistance;
}
};
//
// IdentifyMissedRay is a debugging routine that detects
// rays that fail to have any value because of a external
// intersection and cell intersection mismatch
//
//
class IdentifyMissedRay : public vtkm::worklet::WorkletMapField
{
public:
vtkm::Id Width;
vtkm::Id Height;
vtkm::Vec<vtkm::Float32, 4> BGColor;
IdentifyMissedRay(const vtkm::Id width,
const vtkm::Id height,
vtkm::Vec<vtkm::Float32, 4> bgcolor)
: Width(width)
, Height(height)
, BGColor(bgcolor)
{
}
using ControlSignature = void(FieldIn<>, WholeArrayIn<>);
using ExecutionSignature = void(_1, _2);
VTKM_EXEC inline bool IsBGColor(const vtkm::Vec<vtkm::Float32, 4> color) const
{
bool isBG = false;
if (color[0] == BGColor[0] && color[1] == BGColor[1] && color[2] == BGColor[2] &&
color[3] == BGColor[3])
isBG = true;
return isBG;
}
template <typename ColorBufferType>
VTKM_EXEC inline void operator()(const vtkm::Id& pixelId, ColorBufferType& buffer) const
{
vtkm::Id x = pixelId % Width;
vtkm::Id y = pixelId / Width;
// Conservative check, we only want to check pixels in the middle
if (x <= 0 || y <= 0)
return;
if (x >= Width - 1 || y >= Height - 1)
return;
vtkm::Vec<vtkm::Float32, 4> pixel;
pixel[0] = static_cast<vtkm::Float32>(buffer.Get(pixelId * 4 + 0));
pixel[1] = static_cast<vtkm::Float32>(buffer.Get(pixelId * 4 + 1));
pixel[2] = static_cast<vtkm::Float32>(buffer.Get(pixelId * 4 + 2));
pixel[3] = static_cast<vtkm::Float32>(buffer.Get(pixelId * 4 + 3));
if (!IsBGColor(pixel))
return;
vtkm::Id p0 = (y)*Width + (x + 1);
vtkm::Id p1 = (y)*Width + (x - 1);
vtkm::Id p2 = (y + 1) * Width + (x);
vtkm::Id p3 = (y - 1) * Width + (x);
pixel[0] = static_cast<vtkm::Float32>(buffer.Get(p0 * 4 + 0));
pixel[1] = static_cast<vtkm::Float32>(buffer.Get(p0 * 4 + 1));
pixel[2] = static_cast<vtkm::Float32>(buffer.Get(p0 * 4 + 2));
pixel[3] = static_cast<vtkm::Float32>(buffer.Get(p0 * 4 + 3));
if (IsBGColor(pixel))
return;
pixel[0] = static_cast<vtkm::Float32>(buffer.Get(p1 * 4 + 0));
pixel[1] = static_cast<vtkm::Float32>(buffer.Get(p1 * 4 + 1));
pixel[2] = static_cast<vtkm::Float32>(buffer.Get(p1 * 4 + 2));
pixel[3] = static_cast<vtkm::Float32>(buffer.Get(p1 * 4 + 3));
if (IsBGColor(pixel))
return;
pixel[0] = static_cast<vtkm::Float32>(buffer.Get(p2 * 4 + 0));
pixel[1] = static_cast<vtkm::Float32>(buffer.Get(p2 * 4 + 1));
pixel[2] = static_cast<vtkm::Float32>(buffer.Get(p2 * 4 + 2));
pixel[3] = static_cast<vtkm::Float32>(buffer.Get(p2 * 4 + 3));
if (IsBGColor(pixel))
return;
pixel[0] = static_cast<vtkm::Float32>(buffer.Get(p3 * 4 + 0));
pixel[1] = static_cast<vtkm::Float32>(buffer.Get(p3 * 4 + 1));
pixel[2] = static_cast<vtkm::Float32>(buffer.Get(p3 * 4 + 2));
pixel[3] = static_cast<vtkm::Float32>(buffer.Get(p3 * 4 + 3));
if (IsBGColor(pixel))
return;
printf("Possible error ray missed ray %d\n", (int)pixelId);
}
};
template <vtkm::Int32 CellType, typename FloatType, typename Device, typename MeshType>
class SampleCellAssocCells : public vtkm::worklet::WorkletMapField
{
private:
using ColorHandle = typename vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 4>>;
using ColorBuffer = typename vtkm::cont::ArrayHandle<FloatType>;
using ColorConstPortal = typename ColorHandle::ExecutionTypes<Device>::PortalConst;
using ColorPortal = typename ColorBuffer::template ExecutionTypes<Device>::Portal;
CellSampler<CellType> Sampler;
FloatType SampleDistance;
FloatType MinScalar;
FloatType InvDeltaScalar;
ColorPortal FrameBuffer;
ColorConstPortal ColorMap;
MeshType MeshConn;
vtkm::Int32 ColorMapSize;
public:
template <typename ConnectivityType>
SampleCellAssocCells(const FloatType& sampleDistance,
const FloatType& minScalar,
const FloatType& maxScalar,
ColorHandle& colorMap,
ColorBuffer& frameBuffer,
ConnectivityType& meshConn)
: SampleDistance(sampleDistance)
, MinScalar(minScalar)
, ColorMap(colorMap.PrepareForInput(Device()))
, MeshConn(meshConn)
{
InvDeltaScalar = (minScalar == maxScalar) ? 1.f : 1.f / (maxScalar - minScalar);
ColorMapSize = static_cast<vtkm::Int32>(ColorMap.GetNumberOfValues());
this->FrameBuffer = frameBuffer.PrepareForOutput(frameBuffer.GetNumberOfValues(), Device());
}
using ControlSignature = void(FieldIn<>,
WholeArrayIn<ScalarRenderingTypes>,
FieldIn<>,
FieldIn<>,
FieldInOut<>,
FieldInOut<>);
using ExecutionSignature = void(_1, _2, _3, _4, _5, _6, WorkIndex);
template <typename ScalarPortalType>
VTKM_EXEC inline void operator()(const vtkm::Id& currentCell,
ScalarPortalType& scalarPortal,
const FloatType& enterDistance,
const FloatType& exitDistance,
FloatType& currentDistance,
vtkm::UInt8& rayStatus,
const vtkm::Id& pixelIndex) const
{
if (rayStatus != RAY_ACTIVE)
return;
vtkm::Vec<vtkm::Float32, 4> color;
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 0);
color[0] = static_cast<vtkm::Float32>(FrameBuffer.Get(pixelIndex * 4 + 0));
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 1);
color[1] = static_cast<vtkm::Float32>(FrameBuffer.Get(pixelIndex * 4 + 1));
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 2);
color[2] = static_cast<vtkm::Float32>(FrameBuffer.Get(pixelIndex * 4 + 2));
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 3);
color[3] = static_cast<vtkm::Float32>(FrameBuffer.Get(pixelIndex * 4 + 3));
vtkm::Float32 scalar;
BOUNDS_CHECK(scalarPortal, currentCell);
scalar = vtkm::Float32(scalarPortal.Get(currentCell));
//
// There can be mismatches in the initial enter distance and the current distance
// due to lost rays at cell borders. For now,
// we will just advance the current position to the enter distance, since otherwise,
// the pixel would never be sampled.
//
if (currentDistance < enterDistance)
currentDistance = enterDistance;
vtkm::Float32 lerpedScalar;
lerpedScalar = static_cast<vtkm::Float32>((scalar - MinScalar) * InvDeltaScalar);
vtkm::Id colorIndex = vtkm::Id(lerpedScalar * vtkm::Float32(ColorMapSize));
if (colorIndex < 0)
colorIndex = 0;
if (colorIndex >= ColorMapSize)
colorIndex = ColorMapSize - 1;
BOUNDS_CHECK(ColorMap, colorIndex);
vtkm::Vec<vtkm::Float32, 4> sampleColor = ColorMap.Get(colorIndex);
while (enterDistance <= currentDistance && currentDistance <= exitDistance)
{
//composite
sampleColor[3] *= (1.f - color[3]);
color[0] = color[0] + sampleColor[0] * sampleColor[3];
color[1] = color[1] + sampleColor[1] * sampleColor[3];
color[2] = color[2] + sampleColor[2] * sampleColor[3];
color[3] = sampleColor[3] + color[3];
if (color[3] > 1.)
{
rayStatus = RAY_TERMINATED;
break;
}
currentDistance += SampleDistance;
}
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 0);
FrameBuffer.Set(pixelIndex * 4 + 0, color[0]);
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 1);
FrameBuffer.Set(pixelIndex * 4 + 1, color[1]);
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 2);
FrameBuffer.Set(pixelIndex * 4 + 2, color[2]);
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 3);
FrameBuffer.Set(pixelIndex * 4 + 3, color[3]);
}
}; //class Sample cell
template <vtkm::Int32 CellType, typename FloatType, typename Device, typename MeshType>
class SampleCellAssocPoints : public vtkm::worklet::WorkletMapField
{
private:
using ColorHandle = typename vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 4>>;
using ColorBuffer = typename vtkm::cont::ArrayHandle<FloatType>;
using ColorConstPortal = typename ColorHandle::ExecutionTypes<Device>::PortalConst;
using ColorPortal = typename ColorBuffer::template ExecutionTypes<Device>::Portal;
CellSampler<CellType> Sampler;
FloatType SampleDistance;
MeshType MeshConn;
FloatType MinScalar;
FloatType InvDeltaScalar;
ColorPortal FrameBuffer;
ColorConstPortal ColorMap;
vtkm::Id ColorMapSize;
public:
template <typename ConnectivityType>
SampleCellAssocPoints(const FloatType& sampleDistance,
const FloatType& minScalar,
const FloatType& maxScalar,
ColorHandle& colorMap,
ColorBuffer& frameBuffer,
ConnectivityType& meshConn)
: SampleDistance(sampleDistance)
, MeshConn(meshConn)
, MinScalar(minScalar)
, ColorMap(colorMap.PrepareForInput(Device()))
{
InvDeltaScalar = (minScalar == maxScalar) ? 1.f : 1.f / (maxScalar - minScalar);
ColorMapSize = ColorMap.GetNumberOfValues();
this->FrameBuffer = frameBuffer.PrepareForOutput(frameBuffer.GetNumberOfValues(), Device());
}
using ControlSignature = void(FieldIn<>,
WholeArrayIn<Vec3>,
WholeArrayIn<ScalarRenderingTypes>,
FieldIn<>,
FieldIn<>,
FieldInOut<>,
FieldIn<>,
FieldInOut<>,
FieldIn<>);
using ExecutionSignature = void(_1, _2, _3, _4, _5, _6, _7, _8, WorkIndex, _9);
template <typename PointPortalType, typename ScalarPortalType>
VTKM_EXEC inline void operator()(const vtkm::Id& currentCell,
PointPortalType& vertices,
ScalarPortalType& scalarPortal,
const FloatType& enterDistance,
const FloatType& exitDistance,
FloatType& currentDistance,
const vtkm::Vec<vtkm::Float32, 3>& dir,
vtkm::UInt8& rayStatus,
const vtkm::Id& pixelIndex,
const vtkm::Vec<FloatType, 3>& origin) const
{
if (rayStatus != RAY_ACTIVE)
return;
vtkm::Vec<vtkm::Float32, 4> color;
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 0);
color[0] = static_cast<vtkm::Float32>(FrameBuffer.Get(pixelIndex * 4 + 0));
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 1);
color[1] = static_cast<vtkm::Float32>(FrameBuffer.Get(pixelIndex * 4 + 1));
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 2);
color[2] = static_cast<vtkm::Float32>(FrameBuffer.Get(pixelIndex * 4 + 2));
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 3);
color[3] = static_cast<vtkm::Float32>(FrameBuffer.Get(pixelIndex * 4 + 3));
if (color[3] >= 1.f)
{
rayStatus = RAY_TERMINATED;
return;
}
vtkm::Vec<vtkm::Float32, 8> scalars;
vtkm::Vec<vtkm::Vec<FloatType, 3>, 8> points;
// silence "may" be uninitialized warning
for (vtkm::Int32 i = 0; i < 8; ++i)
{
scalars[i] = 0.f;
points[i] = vtkm::Vec<FloatType, 3>(0.f, 0.f, 0.f);
}
//load local scalar cell data
vtkm::Id cellConn[8];
const vtkm::Int32 numIndices = MeshConn.GetCellIndices(cellConn, currentCell);
for (int i = 0; i < numIndices; ++i)
{
BOUNDS_CHECK(scalarPortal, cellConn[i]);
scalars[i] = static_cast<vtkm::Float32>(scalarPortal.Get(cellConn[i]));
BOUNDS_CHECK(vertices, cellConn[i]);
points[i] = vtkm::Vec<FloatType, 3>(vertices.Get(cellConn[i]));
}
//
// There can be mismatches in the initial enter distance and the current distance
// due to lost rays at cell borders. For now,
// we will just advance the current position to the enter distance, since otherwise,
// the pixel would never be sampled.
//
if (currentDistance < enterDistance)
{
currentDistance = enterDistance;
}
const vtkm::Int32 cellShape = MeshConn.GetCellShape(currentCell);
while (enterDistance <= currentDistance && currentDistance <= exitDistance)
{
vtkm::Vec<FloatType, 3> sampleLoc = origin + currentDistance * dir;
vtkm::Float32 lerpedScalar;
bool validSample =
Sampler.SampleCell(points, scalars, sampleLoc, lerpedScalar, *this, cellShape);
if (!validSample)
{
//
// There is a slight mismatch between intersections and parametric coordinates
// which results in a invalid sample very close to the cell edge. Just throw
// this sample away, and move to the next sample.
//
//There should be a sample here, so offset and try again.
currentDistance += 0.00001f;
continue;
}
lerpedScalar = static_cast<vtkm::Float32>((lerpedScalar - MinScalar) * InvDeltaScalar);
vtkm::Id colorIndex = vtkm::Id(lerpedScalar * vtkm::Float32(ColorMapSize));
colorIndex = vtkm::Min(vtkm::Max(colorIndex, vtkm::Id(0)), ColorMapSize - 1);
BOUNDS_CHECK(ColorMap, colorIndex);
vtkm::Vec<vtkm::Float32, 4> sampleColor = ColorMap.Get(colorIndex);
//composite
sampleColor[3] *= (1.f - color[3]);
color[0] = color[0] + sampleColor[0] * sampleColor[3];
color[1] = color[1] + sampleColor[1] * sampleColor[3];
color[2] = color[2] + sampleColor[2] * sampleColor[3];
color[3] = sampleColor[3] + color[3];
if (color[3] >= 1.0)
{
rayStatus = RAY_TERMINATED;
break;
}
currentDistance += SampleDistance;
}
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 0);
FrameBuffer.Set(pixelIndex * 4 + 0, color[0]);
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 1);
FrameBuffer.Set(pixelIndex * 4 + 1, color[1]);
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 2);
FrameBuffer.Set(pixelIndex * 4 + 2, color[2]);
BOUNDS_CHECK(FrameBuffer, pixelIndex * 4 + 3);
FrameBuffer.Set(pixelIndex * 4 + 3, color[3]);
}
}; //class Sample cell
template <vtkm::Int32 CellType, typename ConnectivityType>
template <typename FloatType, typename Device>
void ConnectivityTracer<CellType, ConnectivityType>::IntersectCell(
Ray<FloatType>& rays,
detail::RayTracking<FloatType>& tracker,
Device)
{
using LocateC = LocateCell<CellType, FloatType, MeshConnExec<ConnectivityType, Device>>;
vtkm::cont::Timer<Device> timer;
vtkm::worklet::DispatcherMapField<LocateC, Device>(LocateC(MeshConn))
.Invoke(rays.HitIdx,
this->MeshConn.GetCoordinates(),
rays.Dir,
*(tracker.EnterDist),
*(tracker.ExitDist),
tracker.ExitFace,
rays.Status,
rays.Origin);
if (this->CountRayStatus)
RaysLost = RayOperations::GetStatusCount(rays, RAY_LOST, Device());
this->IntersectTime += timer.GetElapsedTime();
}
template <vtkm::Int32 CellType, typename ConnectivityType>
template <typename FloatType, typename Device>
void ConnectivityTracer<CellType, ConnectivityType>::AccumulatePathLengths(
Ray<FloatType>& rays,
detail::RayTracking<FloatType>& tracker,
Device)
{
vtkm::worklet::DispatcherMapField<AddPathLengths<FloatType>, Device>(AddPathLengths<FloatType>())
.Invoke(rays.Status,
*(tracker.EnterDist),
*(tracker.ExitDist),
rays.GetBuffer("path_lengths").Buffer);
}
template <vtkm::Int32 CellType, typename ConnectivityType>
template <typename FloatType, typename Device>
void ConnectivityTracer<CellType, ConnectivityType>::FindLostRays(
Ray<FloatType>& rays,
detail::RayTracking<FloatType>& tracker,
Device)
{
using RayB = RayBumper<CellType, FloatType, Device, MeshConnExec<ConnectivityType, Device>>;
vtkm::cont::Timer<Device> timer;
vtkm::worklet::DispatcherMapField<RayB, Device>(
RayB(rays.DirX, rays.DirY, rays.DirZ, this->MeshConn))
.Invoke(rays.HitIdx,
this->MeshConn.GetCoordinates(),
*(tracker.EnterDist),
*(tracker.ExitDist),
tracker.ExitFace,
rays.Status,
rays.Origin);
this->LostRayTime += timer.GetElapsedTime();
}
template <vtkm::Int32 CellType, typename ConnectivityType>
template <typename FloatType, typename Device>
void ConnectivityTracer<CellType, ConnectivityType>::SampleCells(
Ray<FloatType>& rays,
detail::RayTracking<FloatType>& tracker,
Device)
{
using SampleP =
SampleCellAssocPoints<CellType, FloatType, Device, MeshConnExec<ConnectivityType, Device>>;
using SampleC =
SampleCellAssocCells<CellType, FloatType, Device, MeshConnExec<ConnectivityType, Device>>;
vtkm::cont::Timer<Device> timer;
VTKM_ASSERT(rays.Buffers.at(0).GetNumChannels() == 4);
if (FieldAssocPoints)
{
vtkm::worklet::DispatcherMapField<SampleP, Device>(
SampleP(this->SampleDistance,
vtkm::Float32(this->ScalarBounds.Min),
vtkm::Float32(this->ScalarBounds.Max),
this->ColorMap,
rays.Buffers.at(0).Buffer,
this->MeshConn))
.Invoke(rays.HitIdx,
this->MeshConn.GetCoordinates(),
this->ScalarField.GetData(),
*(tracker.EnterDist),
*(tracker.ExitDist),
tracker.CurrentDistance,
rays.Dir,
rays.Status,
rays.Origin);
}
else
{
vtkm::worklet::DispatcherMapField<SampleC, Device>(
SampleC(this->SampleDistance,
vtkm::Float32(this->ScalarBounds.Min),
vtkm::Float32(this->ScalarBounds.Max),
this->ColorMap,
rays.Buffers.at(0).Buffer,
this->MeshConn))
.Invoke(rays.HitIdx,
this->ScalarField.GetData(),
*(tracker.EnterDist),
*(tracker.ExitDist),
tracker.CurrentDistance,
rays.Status);
}
this->SampleTime += timer.GetElapsedTime();
}
template <vtkm::Int32 CellType, typename ConnectivityType>
template <typename FloatType, typename Device>
void ConnectivityTracer<CellType, ConnectivityType>::IntegrateCells(
Ray<FloatType>& rays,
detail::RayTracking<FloatType>& tracker,
Device)
{
vtkm::cont::Timer<Device> timer;
if (HasEmission)
{
bool divideEmisByAbsorp = false;
vtkm::cont::ArrayHandle<FloatType> absorp = rays.Buffers.at(0).Buffer;
vtkm::cont::ArrayHandle<FloatType> emission = rays.GetBuffer("emission").Buffer;
vtkm::worklet::DispatcherMapField<IntegrateEmission<FloatType>, Device>(
IntegrateEmission<FloatType>(rays.Buffers.at(0).GetNumChannels(), divideEmisByAbsorp))
.Invoke(rays.Status,
*(tracker.EnterDist),
*(tracker.ExitDist),
rays.Distance,
this->ScalarField.GetData(),
this->EmissionField.GetData(),
absorp,
emission,
rays.HitIdx);
}
else
{
vtkm::worklet::DispatcherMapField<Integrate<FloatType>, Device>(
Integrate<FloatType>(rays.Buffers.at(0).GetNumChannels()))
.Invoke(rays.Status,
*(tracker.EnterDist),
*(tracker.ExitDist),
rays.Distance,
this->ScalarField.GetData(),
rays.Buffers.at(0).Buffer,
rays.HitIdx);
}
IntegrateTime += timer.GetElapsedTime();
}
// template <vtkm::Int32 CellType, typename ConnectivityType>
// template <typename FloatType>
// void ConnectivityTracer<CellType,ConnectivityType>::PrintDebugRay(Ray<FloatType>& rays, vtkm::Id rayId)
// {
// vtkm::Id index = -1;
// for (vtkm::Id i = 0; i < rays.NumRays; ++i)
// {
// if (rays.PixelIdx.GetPortalControl().Get(i) == rayId)
// {
// index = i;
// break;
// }
// }
// if (index == -1)
// {
// return;
// }
// std::cout << "++++++++RAY " << rayId << "++++++++\n";
// std::cout << "Status: " << (int)rays.Status.GetPortalControl().Get(index) << "\n";
// std::cout << "HitIndex: " << rays.HitIdx.GetPortalControl().Get(index) << "\n";
// std::cout << "Dist " << rays.Distance.GetPortalControl().Get(index) << "\n";
// std::cout << "MinDist " << rays.MinDistance.GetPortalControl().Get(index) << "\n";
// std::cout << "Origin " << rays.Origin.GetPortalConstControl().Get(index) << "\n";
// std::cout << "Dir " << rays.Dir.GetPortalConstControl().Get(index) << "\n";
// std::cout << "+++++++++++++++++++++++++\n";
// }
template <vtkm::Int32 CellType, typename ConnectivityType>
template <typename FloatType, typename Device>
void ConnectivityTracer<CellType, ConnectivityType>::OffsetMinDistances(Ray<FloatType>& rays,
Device)
{
vtkm::worklet::DispatcherMapField<AdvanceRay<FloatType>, Device>(
AdvanceRay<FloatType>(FloatType(0.001)))
.Invoke(rays.Status, rays.MinDistance);
}
template <vtkm::Int32 CellType, typename ConnectivityType>
template <typename Device, typename FloatType>
void ConnectivityTracer<CellType, ConnectivityType>::RenderOnDevice(Ray<FloatType>& rays, Device)
{
Logger* logger = Logger::GetInstance();
logger->OpenLogEntry("conn_tracer");
logger->AddLogData("device", GetDeviceString(Device()));
this->ResetTimers();
vtkm::cont::Timer<Device> renderTimer;
this->SetBoundingBox(Device());
bool hasPathLengths = rays.HasBuffer("path_lengths");
vtkm::cont::Timer<Device> timer;
this->Init();
//
// All Rays begin as exited to force intersection
//
RayOperations::ResetStatus(rays, RAY_EXITED_MESH, Device());
detail::RayTracking<FloatType> rayTracker;
rayTracker.Init(rays.NumRays, rays.Distance, Device());
vtkm::Float64 time = timer.GetElapsedTime();
logger->AddLogData("init", time);
MeshConn.Construct(Device());
bool cullMissedRays = true;
bool workRemaining = true;
if (this->CountRayStatus)
{
this->PrintRayStatus(rays, Device());
}
do
{
{
vtkm::cont::Timer<Device> entryTimer;
//
// if ray misses the external face it will be marked RAY_EXITED_MESH
//
MeshConn.FindEntry(rays, Device());
MeshEntryTime += entryTimer.GetElapsedTime();
}
if (this->CountRayStatus)
{
this->PrintRayStatus(rays, Device());
}
if (cullMissedRays)
{
//TODO: if we always call this after intersection, then
// we could make a specialized version that only compacts
// hitIdx distance and status, resizing everything else.
vtkm::cont::ArrayHandle<UInt8> activeRays;
activeRays = RayOperations::CompactActiveRays(rays, Device());
rayTracker.Compact(rays.Distance, activeRays, Device());
cullMissedRays = false;
}
if (this->CountRayStatus)
{
this->PrintRayStatus(rays, Device());
}
// TODO: we should compact out exited rays once below a threshold
while (RayOperations::RaysInMesh(rays, Device()))
{
//
// Rays the leave the mesh will be marked as RAYEXITED_MESH
this->IntersectCell(rays, rayTracker, Device());
//
// If the ray was lost due to precision issues, we find it.
// If it is marked RAY_ABANDONED, then something went wrong.
//
this->FindLostRays(rays, rayTracker, Device());
//
// integrate along the ray
//
if (this->Integrator == Volume)
this->SampleCells(rays, rayTracker, Device());
else
this->IntegrateCells(rays, rayTracker, Device());
if (hasPathLengths)
{
this->AccumulatePathLengths(rays, rayTracker, Device());
}
//swap enter and exit distances
rayTracker.Swap();
if (this->CountRayStatus)
this->PrintRayStatus(rays, Device());
} //for
workRemaining = RayOperations::RaysProcessed(rays, Device()) != rays.NumRays;
//
// Ensure that we move the current distance forward some
// epsilon so we don't re-enter the cell we just left.
//
if (workRemaining)
{
RayOperations::CopyDistancesToMin(rays, Device());
this->OffsetMinDistances(rays, Device());
}
} while (workRemaining);
if (rays.DebugWidth != -1 && this->Integrator == Volume)
{
vtkm::cont::ArrayHandleCounting<vtkm::Id> pCounter(0, 1, rays.NumRays);
vtkm::worklet::DispatcherMapField<IdentifyMissedRay, Device>(
IdentifyMissedRay(rays.DebugWidth, rays.DebugHeight, this->BackgroundColor))
.Invoke(pCounter, rays.Buffers.at(0).Buffer);
}
vtkm::Float64 renderTime = renderTimer.GetElapsedTime();
this->LogTimers();
logger->AddLogData("active_pixels", rays.NumRays);
logger->CloseLogEntry(renderTime);
} //Render
}
}
} // namespace vtkm::rendering::raytracing
| 35.706625 | 106 | 0.618275 | [
"mesh",
"render"
] |
fa4f121247900f42118564734adfb874c7e7bbc8 | 2,801 | cpp | C++ | fpsgame/graphics/SkeletonAnimManager.cpp | mrlitong/CPP-Game-engine-usage | 95697c4bfb507cfb38dbe0f632740e2a7eac71fb | [
"MIT"
] | 186 | 2017-07-26T12:53:29.000Z | 2021-09-10T04:00:39.000Z | fpsgame/graphics/SkeletonAnimManager.cpp | mrlitong/CPP-Game-engine-usage | 95697c4bfb507cfb38dbe0f632740e2a7eac71fb | [
"MIT"
] | 1 | 2017-08-15T13:12:27.000Z | 2017-08-16T06:14:57.000Z | fpsgame/graphics/SkeletonAnimManager.cpp | mrlitong/CPP-Game-engine-usage | 95697c4bfb507cfb38dbe0f632740e2a7eac71fb | [
"MIT"
] | 6 | 2017-02-15T10:19:26.000Z | 2017-03-15T03:17:15.000Z | /* Copyright (C) 2012 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. 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.
*
* 0 A.D. 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 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Owner of all skeleton animations
*/
#include "precompiled.h"
#include "SkeletonAnimManager.h"
#include "graphics/ColladaManager.h"
#include "graphics/Model.h"
#include "graphics/SkeletonAnimDef.h"
#include "ps/CLogger.h"
#include "ps/FileIo.h"
///////////////////////////////////////////////////////////////////////////////
// CSkeletonAnimManager constructor
CSkeletonAnimManager::CSkeletonAnimManager(CColladaManager& colladaManager)
: m_ColladaManager(colladaManager)
{
}
///////////////////////////////////////////////////////////////////////////////
// CSkeletonAnimManager destructor
CSkeletonAnimManager::~CSkeletonAnimManager()
{
typedef boost::unordered_map<VfsPath,CSkeletonAnimDef*>::iterator Iter;
for (Iter i = m_Animations.begin(); i != m_Animations.end(); ++i)
delete i->second;
}
///////////////////////////////////////////////////////////////////////////////
// GetAnimation: return a given animation by filename; return null if filename
// doesn't refer to valid animation file
CSkeletonAnimDef* CSkeletonAnimManager::GetAnimation(const VfsPath& pathname)
{
VfsPath name = pathname.ChangeExtension(L"");
// Find if it's already been loaded
boost::unordered_map<VfsPath, CSkeletonAnimDef*>::iterator iter = m_Animations.find(name);
if (iter != m_Animations.end())
return iter->second;
CSkeletonAnimDef* def = NULL;
// Find the file to load
VfsPath psaFilename = m_ColladaManager.GetLoadablePath(name, CColladaManager::PSA);
if (psaFilename.empty())
{
LOGERROR("Could not load animation '%s'", pathname.string8());
def = NULL;
}
else
{
try
{
def = CSkeletonAnimDef::Load(psaFilename);
}
catch (PSERROR_File&)
{
LOGERROR("Could not load animation '%s'", psaFilename.string8());
}
}
if (def)
LOGMESSAGE("CSkeletonAnimManager::GetAnimation(%s): Loaded successfully", pathname.string8());
else
LOGERROR("CSkeletonAnimManager::GetAnimation(%s): Failed loading, marked file as bad", pathname.string8());
// Add to map
m_Animations[name] = def; // NULL if failed to load - we won't try loading it again
return def;
}
| 30.445652 | 109 | 0.670475 | [
"model"
] |
fa5be13b576166851dfb3d576a1e97ac64e08e95 | 980 | cpp | C++ | GameFramework/src/BehaviourTrees/Actions/FindClosest.cpp | lcomstive/AIE_AIForGames | 4128b9984a86111871864c904a34da04c12c3293 | [
"MIT"
] | null | null | null | GameFramework/src/BehaviourTrees/Actions/FindClosest.cpp | lcomstive/AIE_AIForGames | 4128b9984a86111871864c904a34da04c12c3293 | [
"MIT"
] | null | null | null | GameFramework/src/BehaviourTrees/Actions/FindClosest.cpp | lcomstive/AIE_AIForGames | 4128b9984a86111871864c904a34da04c12c3293 | [
"MIT"
] | null | null | null | #include <Framework/BehaviourTrees/Actions/FindClosest.hpp>
using namespace std;
using namespace Framework::BT;
BehaviourResult FindClosest::Execute(GameObject* go)
{
if (GetTargetFromContext)
{
Sight = GetContext<float>("Sight", 10000.0f);
TargetTag = GetContext<string>("TargetTag");
}
vector<GameObject*> queryList = TargetTag.empty() ? GameObject::GetAll() : GameObject::GetTag(TargetTag);
if (queryList.size() == 0)
return BehaviourResult::Failure;
Vec2 position = go->GetPosition();
GameObject* closest = queryList[0];
float closestDistance = closest->GetPosition().Distance(position);
for (unsigned int i = 1; i < queryList.size(); i++)
{
float distance = queryList[i]->GetPosition().Distance(position);
if (distance >= closestDistance || distance >= Sight)
continue;
closest = queryList[i];
closestDistance = distance;
}
SetContext("Target", closest->GetID());
SetContext("Found", closest->GetID());
return BehaviourResult::Success;
} | 28 | 106 | 0.720408 | [
"vector"
] |
fa63b4cde0004752a241ed2cad8a07b94f89b614 | 9,342 | cpp | C++ | tests/LinAlg/matrixTestsDense.cpp | pelesh/hiop | 26bf95fc380dfee6d251d6c870cf1b4c76841828 | [
"BSD-3-Clause"
] | null | null | null | tests/LinAlg/matrixTestsDense.cpp | pelesh/hiop | 26bf95fc380dfee6d251d6c870cf1b4c76841828 | [
"BSD-3-Clause"
] | null | null | null | tests/LinAlg/matrixTestsDense.cpp | pelesh/hiop | 26bf95fc380dfee6d251d6c870cf1b4c76841828 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2017, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory (LLNL).
// Written by Cosmin G. Petra, petra1@llnl.gov.
// LLNL-CODE-742473. All rights reserved.
//
// This file is part of HiOp. For details, see https://github.com/LLNL/hiop. HiOp
// is released under the BSD 3-clause license (https://opensource.org/licenses/BSD-3-Clause).
// Please also read “Additional BSD Notice” below.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// i. Redistributions of source code must retain the above copyright notice, this list
// of conditions and the disclaimer below.
// ii. 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.
// iii. Neither the name of the LLNS/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 LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, 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.
//
// Additional BSD Notice
// 1. This notice is required to be provided under our contract with the U.S. Department
// of Energy (DOE). This work was produced at Lawrence Livermore National Laboratory under
// Contract No. DE-AC52-07NA27344 with the DOE.
// 2. Neither the United States Government nor Lawrence Livermore National Security, LLC
// nor any of their employees, makes any warranty, express or implied, or assumes any
// liability or responsibility for the accuracy, completeness, or usefulness of any
// information, apparatus, product, or process disclosed, or represents that its use would
// not infringe privately-owned rights.
// 3. Also, reference herein to any specific commercial products, process, or services by
// trade name, trademark, manufacturer or otherwise does not necessarily constitute or
// imply its endorsement, recommendation, or favoring by the United States Government or
// Lawrence Livermore National Security, LLC. The views and opinions of authors expressed
// herein do not necessarily state or reflect those of the United States Government or
// Lawrence Livermore National Security, LLC, and shall not be used for advertising or
// product endorsement purposes.
/**
* @file matrixTestsDense.cpp
*
* @author Asher Mancinelli <asher.mancinelli@pnnl.gov>, PNNL
* @author Slaven Peles <slaven.peles@pnnl.gov>, PNNL
*
*/
#include <hiopMatrix.hpp>
#include "matrixTestsDense.hpp"
namespace hiop::tests {
/// Method to set matrix _A_ element (i,j) to _val_.
/// First need to retrieve hiopMatrixDense from the abstract interface
void MatrixTestsDense::setLocalElement(
hiop::hiopMatrix* A,
local_ordinal_type i,
local_ordinal_type j,
real_type val)
{
hiop::hiopMatrixDense* amat = dynamic_cast<hiop::hiopMatrixDense*>(A);
if(amat != nullptr)
{
real_type** data = amat->get_M();
data[i][j] = val;
}
else THROW_NULL_DEREF;
}
void MatrixTestsDense::setLocalElement(
hiop::hiopVector* _x,
const local_ordinal_type i,
const real_type val)
{
auto x = dynamic_cast<hiop::hiopVectorPar*>(_x);
if(x != nullptr)
{
real_type* data = x->local_data();
data[i] = val;
}
else THROW_NULL_DEREF;
}
/// Method to set a single row of matrix to a constant value
void MatrixTestsDense::setLocalRow(
hiop::hiopMatrixDense* A,
const local_ordinal_type row,
const real_type val)
{
const local_ordinal_type N = getNumLocCols(A);
for (int i=0; i<N; i++)
{
setLocalElement(A, row, i, val);
}
}
/// Returns element (i,j) of matrix _A_.
/// First need to retrieve hiopMatrixDense from the abstract interface
real_type MatrixTestsDense::getLocalElement(
const hiop::hiopMatrix* A,
local_ordinal_type i,
local_ordinal_type j)
{
const hiop::hiopMatrixDense* amat = dynamic_cast<const hiop::hiopMatrixDense*>(A);
if(amat != nullptr)
return amat->local_data()[i][j];
else THROW_NULL_DEREF;
}
/// Returns element _i_ of vector _x_.
/// First need to retrieve hiopVectorPar from the abstract interface
real_type MatrixTestsDense::getLocalElement(
const hiop::hiopVector* x,
local_ordinal_type i)
{
const hiop::hiopVectorPar* xvec = dynamic_cast<const hiop::hiopVectorPar*>(x);
if(xvec != nullptr)
return xvec->local_data_const()[i];
else THROW_NULL_DEREF;
}
local_ordinal_type MatrixTestsDense::getNumLocRows(hiop::hiopMatrix* A)
{
hiop::hiopMatrixDense* amat = dynamic_cast<hiop::hiopMatrixDense*>(A);
if(amat != nullptr)
return amat->get_local_size_m();
// ^^^
else THROW_NULL_DEREF;
}
local_ordinal_type MatrixTestsDense::getNumLocCols(hiop::hiopMatrix* A)
{
hiop::hiopMatrixDense* amat = dynamic_cast<hiop::hiopMatrixDense*>(A);
if(amat != nullptr)
return amat->get_local_size_n();
// ^^^
else THROW_NULL_DEREF;
}
/// Returns size of local data array for vector _x_
int MatrixTestsDense::getLocalSize(const hiop::hiopVector* x)
{
const hiop::hiopVectorPar* xvec = dynamic_cast<const hiop::hiopVectorPar*>(x);
if(xvec != nullptr)
return static_cast<int>(xvec->get_local_size());
else THROW_NULL_DEREF;
}
#ifdef HIOP_USE_MPI
/// Get communicator
MPI_Comm MatrixTestsDense::getMPIComm(hiop::hiopMatrix* _A)
{
const hiop::hiopMatrixDense* A = dynamic_cast<const hiop::hiopMatrixDense*>(_A);
if(A != nullptr)
return A->get_mpi_comm();
else THROW_NULL_DEREF;
}
#endif
// Every rank returns failure if any individual rank fails
bool MatrixTestsDense::reduceReturn(int failures, hiop::hiopMatrix* A)
{
int fail = 0;
#ifdef HIOP_USE_MPI
MPI_Allreduce(&failures, &fail, 1, MPI_INT, MPI_SUM, getMPIComm(A));
#else
(void) A;
fail = failures;
#endif
return (fail != 0);
}
[[nodiscard]]
int MatrixTestsDense::verifyAnswer(hiop::hiopMatrix* A, const double answer)
{
const local_ordinal_type M = getNumLocRows(A);
const local_ordinal_type N = getNumLocCols(A);
int fail = 0;
for (local_ordinal_type i=0; i<M; i++)
{
for (local_ordinal_type j=0; j<N; j++)
{
if (!isEqual(getLocalElement(A, i, j), answer))
{
std::cout << i << " " << j << " = " << getLocalElement(A, i, j) << " != " << answer << "\n";
fail++;
}
}
}
return fail;
}
/*
* Pass a function-like object to calculate the expected
* answer dynamically, based on the row and column
*/
[[nodiscard]]
int MatrixTestsDense::verifyAnswer(
hiop::hiopMatrix* A,
std::function<real_type(local_ordinal_type, local_ordinal_type)> expect)
{
const local_ordinal_type M = getNumLocRows(A);
const local_ordinal_type N = getNumLocCols(A);
int fail = 0;
for (local_ordinal_type i=0; i<M; i++)
{
for (local_ordinal_type j=0; j<N; j++)
{
if (!isEqual(getLocalElement(A, i, j), expect(i, j)))
{
fail++;
}
}
}
return fail;
}
/// Checks if _local_ vector elements are set to `answer`.
[[nodiscard]]
int MatrixTestsDense::verifyAnswer(hiop::hiopVector* x, double answer)
{
const local_ordinal_type N = getLocalSize(x);
int local_fail = 0;
for(local_ordinal_type i=0; i<N; ++i)
{
if(!isEqual(getLocalElement(x, i), answer))
{
++local_fail;
}
}
return local_fail;
}
[[nodiscard]]
int MatrixTestsDense::verifyAnswer(
hiop::hiopVector* x,
std::function<real_type(local_ordinal_type)> expect)
{
const local_ordinal_type N = getLocalSize(x);
int local_fail = 0;
for (int i=0; i<N; i++)
{
if(!isEqual(getLocalElement(x, i), expect(i)))
{
++local_fail;
}
}
return local_fail;
}
bool MatrixTestsDense::globalToLocalMap(
hiop::hiopMatrix* A,
const global_ordinal_type row,
const global_ordinal_type col,
local_ordinal_type& local_row,
local_ordinal_type& local_col)
{
#ifdef HIOP_USE_MPI
int rank = 0;
MPI_Comm comm = getMPIComm(A);
MPI_Comm_rank(comm, &rank);
const local_ordinal_type n_local = getNumLocCols(A);
const global_ordinal_type local_col_start = n_local * rank;
if (col >= local_col_start && col < local_col_start + n_local)
{
local_row = row;
local_col = col % n_local;
return true;
}
else
{
return false;
}
#else
(void) A; // surpresses waring as A is not needed here without MPI
local_row = row;
local_col = col;
return true;
#endif
}
// End helper methods
} // namespace hiop::tests
| 31.14 | 100 | 0.711732 | [
"object",
"vector"
] |
fa645de9f52b0e616026b3a69dfe04da2a899607 | 2,292 | cpp | C++ | cv_wrappers/source/cv_io.cpp | hyu754/CV | b60a99ca1df9ae102baaa80a046b898ec0230b32 | [
"MIT"
] | null | null | null | cv_wrappers/source/cv_io.cpp | hyu754/CV | b60a99ca1df9ae102baaa80a046b898ec0230b32 | [
"MIT"
] | null | null | null | cv_wrappers/source/cv_io.cpp | hyu754/CV | b60a99ca1df9ae102baaa80a046b898ec0230b32 | [
"MIT"
] | null | null | null |
#include "cv_io.h"
//Function will write points to file, it is able to write 2d and 3d points
//Input: file_name - file to save to
// pnts - vector of points
int write_2d_points_to_file(std::string filename, imagePointVector pnts){
std::ofstream output_file(filename);
for (auto iter = pnts.begin(); iter != pnts.end(); ++iter){
output_file << iter->x << " " << iter->y << std::endl;
}
output_file.close();
return 1;
}
int write_d_points_to_file(std::string filename, std::vector<int> id, imagePointVector pnts){
std::ofstream output_file(filename);
for (auto iter = pnts.begin(); iter != pnts.end(); ++iter){
output_file << iter->x << " " << iter->y << std::endl;
}
output_file.close();
return 1;
}
//Function will write points to file, it is able to write 3d points
//Input: file_name - file to save to
// pnts - vector of points
int write_3d_points_to_file(std::string filename, worldPointVector pnts){
std::ofstream output_file(filename);
for (auto iter = pnts.begin(); iter != pnts.end(); ++iter){
output_file << iter->x << " " << iter->y << " " << iter->z << std::endl;
}
output_file.close();
return 1;
}
int write_3d_points_to_file(std::string filename, float time, int counter, worldPointVector pnts){
std::string counter_string;
if (counter < 10){
counter_string = "000"+std::to_string(counter);
}
else if (counter < 100){
counter_string ="00"+ std::to_string(counter) ;
}
else if (counter < 1000){
counter_string = "0"+std::to_string(counter);
}
std::ofstream output_file("../matlab/AFEM_OUTPUT/" + filename + counter_string + ".txt");
output_file << time << std::endl;
for (auto iter = pnts.begin(); iter != pnts.end(); ++iter){
output_file << iter->x << " " << iter->y << " " << iter->z << std::endl;
}
output_file.close();
return 1;
}
int write_3d_points_to_file(std::string filename, std::vector<int> id, worldPointVector pnts){
if (id.size() != pnts.size()){
std::cout << "Error: vector of ids and pnts must be same size . " << std::endl;
return -1;
}
std::ofstream output_file(filename);
int _c = 0;
for (auto iter = pnts.begin(); iter != pnts.end(); ++iter){
output_file<< std::to_string(_c) << iter->x << " " << iter->y << " " << iter->z << std::endl;
_c++;
}
output_file.close();
return 1;
}
| 27.285714 | 98 | 0.650087 | [
"vector",
"3d"
] |
fa68191e5f2e978f662a8e7bed94cf1cc43b556b | 1,074 | cpp | C++ | 0352. Data Stream as Disjoint Intervals/solution_bits.cpp | Pluto-Zy/LeetCode | 3bb39fc5c000b344fd8727883b095943bd29c247 | [
"MIT"
] | null | null | null | 0352. Data Stream as Disjoint Intervals/solution_bits.cpp | Pluto-Zy/LeetCode | 3bb39fc5c000b344fd8727883b095943bd29c247 | [
"MIT"
] | null | null | null | 0352. Data Stream as Disjoint Intervals/solution_bits.cpp | Pluto-Zy/LeetCode | 3bb39fc5c000b344fd8727883b095943bd29c247 | [
"MIT"
] | null | null | null | class SummaryRanges {
public:
SummaryRanges() : _bits{} { }
void addNum(int val) {
auto idx = static_cast<std::make_unsigned_t<decltype(val)>>(val);
_bits[idx >> 3] |= 1 << (idx - ((idx >> 3) << 3));
}
vector<vector<int>> getIntervals() {
std::vector<std::vector<int>> result;
bool last = false;
bool flag = false;
for (std::size_t i = 0; i < sizeof(_bits); ++i) {
for (std::uint8_t val = _bits[i], idx = 0; idx < 8; val >>= 1, ++idx) {
flag = val & 1;
if (!last && flag) {
result.emplace_back(std::vector<int>(2));
result.back()[0] = (i << 3) + idx;
}
else if (last && !flag) {
result.back()[1] = (i << 3) + idx - 1;
}
last = flag;
if (!val)
break;
}
}
return result;
}
private:
std::uint8_t _bits[10000 / 8 + 1];
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges* obj = new SummaryRanges();
* obj->addNum(val);
* vector<vector<int>> param_2 = obj->getIntervals();
*/ | 26.85 | 77 | 0.523277 | [
"object",
"vector"
] |
fa68b088f12e26a97a6bc8e3b4139332ea97e717 | 1,797 | cpp | C++ | iref/iref.cpp | ZEMUSHKA/pydoop | e3d3378ae9921561f6c600c79364c2ad42ec206d | [
"Apache-2.0"
] | 1 | 2017-11-16T02:13:15.000Z | 2017-11-16T02:13:15.000Z | iref/iref.cpp | ZEMUSHKA/pydoop | e3d3378ae9921561f6c600c79364c2ad42ec206d | [
"Apache-2.0"
] | null | null | null | iref/iref.cpp | ZEMUSHKA/pydoop | e3d3378ae9921561f6c600c79364c2ad42ec206d | [
"Apache-2.0"
] | null | null | null | // BEGIN_COPYRIGHT
//
// Copyright 2009-2014 CRS4.
//
// 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.
//
// END_COPYRIGHT
#include <boost/python.hpp>
#include <iostream>
namespace bp = boost::python;
struct payload {
int v;
payload(int x) : v(x){}
int get() {
return v;
}
void set(int x){
v = x;
}
virtual ~payload() {
std::cerr << "payload::Destroying payload(" << v << ")\n" << std::endl;
}
};
void payload_user(bp::object payload_maker){
typedef std::auto_ptr<payload> auto_payload;
std::cerr << "payload_user: -- 0 --" << std::endl;
bp::object pl = payload_maker(20);
std::cerr << "payload_user: -- 1 --" << std::endl;
payload* p = bp::extract<payload*>(pl);
std::cerr << "payload_user: extract -> " << p << std::endl;
std::cerr << "payload_user: p->get() " << p->get() << std::endl;
auto_payload ap = bp::extract<auto_payload>(pl);
p = ap.get();
std::cerr << "payload_user: ap.get() -> " << p << std::endl;
ap.release();
delete p;
std::cerr << "payload_user: -- 2 --" << std::endl;
}
BOOST_PYTHON_MODULE(iref)
{
using namespace boost::python;
class_<payload, std::auto_ptr<payload> >("payload", init<int>())
.def("get", &payload::get)
.def("set", &payload::set)
;
def("payload_user", payload_user);
}
| 26.820896 | 78 | 0.639955 | [
"object"
] |
fa6d385ff13bdd96306ea6dd59559e140d0246fd | 5,649 | cpp | C++ | src/enji/common.cpp | aptakhin/enji | 603675cf39f254eb9d888d0442cd085bf0f4e8f6 | [
"MIT"
] | 1 | 2018-07-11T01:45:24.000Z | 2018-07-11T01:45:24.000Z | src/enji/common.cpp | aptakhin/enji | 603675cf39f254eb9d888d0442cd085bf0f4e8f6 | [
"MIT"
] | null | null | null | src/enji/common.cpp | aptakhin/enji | 603675cf39f254eb9d888d0442cd085bf0f4e8f6 | [
"MIT"
] | null | null | null | #include "common.h"
namespace enji {
void run_thread(void* arg) {
Thread* thread = reinterpret_cast<Thread*>(arg);
thread->func_();
}
void Thread::run(Func&& thread_func) {
func_ = std::move(thread_func);
uv_thread_create(&thread_, run_thread, this);
}
TransferBlock::TransferBlock()
: data{nullptr},
size{0} {
}
TransferBlock::TransferBlock(const char* data, size_t size)
: data{data},
size{size} {
}
void TransferBlock::free() {
if (data) {
deleter(const_cast<char*>(data));
}
}
void TransferBlock::to_uv_buf(uv_buf_t* cpy) {
cpy->base = (char*) data;
cpy->len = size_t(size);
}
bool is_slash(const char c) {
return c == '/' || c == '\\';
}
String path_dirname(const String& filename) {
auto last_slash = filename.find_last_of('/');
if (last_slash == String::npos) {
last_slash = filename.find_last_of("\\\\");
if (last_slash == String::npos) {
return filename;
}
}
return filename.substr(0, last_slash);
}
String path_extension(const String& filename) {
auto last_dot = filename.find_last_of('.');
if (last_dot == String::npos) {
return "";
} else {
return filename.substr(last_dot + 1);
}
}
Value::Value()
: type_(ValueType::NONE) {}
Value::Value(std::map<Value, Value> dict)
: type_(ValueType::DICT),
dict_(dict) {}
Value::Value(std::vector<Value> arr)
: type_(ValueType::ARRAY),
array_(arr) {}
Value::Value(double real)
: type_(ValueType::REAL),
real_(real) {}
Value::Value(int integer)
: type_(ValueType::INTEGER),
integer_(integer) {}
Value::Value(String str)
: type_(ValueType::STR),
str_(str) {}
Value::Value(const char* str)
: type_(ValueType::STR),
str_(str) {}
Value Value::make_dict() {
return Value(std::map<Value, Value>{});
}
Value Value::make_array() {
return Value(std::vector<Value>{});
}
std::map<Value, Value>& Value::dict() {
if (type_ != ValueType::DICT)
throw std::logic_error("Value is not a dict!");
return dict_;
}
std::vector<Value>& Value::array() {
if (type_ != ValueType::ARRAY)
throw std::logic_error("Value is not an array!");
return array_;
}
double& Value::real() {
if (type_ != ValueType::REAL)
throw std::logic_error("Value is not a real!");
return real_;
}
int& Value::integer() {
if (type_ != ValueType::INTEGER)
throw std::logic_error("Value is not a real!");
return integer_;
}
String& Value::str() {
if (type_ != ValueType::STR)
throw std::logic_error("Value is not a string!");
return str_;
}
const std::map<Value, Value>& Value::dict() const {
if (type_ != ValueType::DICT)
throw std::logic_error("Value is not a dict!");
return dict_;
}
const std::vector<Value>& Value::array() const {
if (type_ != ValueType::ARRAY)
throw std::logic_error("Value is not an array!");
return array_;
}
const double& Value::real() const {
if (type_ != ValueType::REAL)
throw std::logic_error("Value is not a real!");
return real_;
}
const int& Value::integer() const {
if (type_ != ValueType::INTEGER)
throw std::logic_error("Value is not a integer!");
return integer_;
}
const String& Value::str() const {
if (type_ != ValueType::STR)
throw std::logic_error("Value is not a string!");
return str_;
}
const std::map<Value, Value>* Value::is_dict() const {
return type_ == ValueType::DICT ? &dict_ : nullptr;
}
const std::vector<Value>* Value::is_array() const {
return type_ == ValueType::ARRAY ? &array_ : nullptr;
}
const double* Value::is_real() const {
return type_ == ValueType::REAL ? &real_ : nullptr;
}
const int* Value::is_integer() const {
return type_ == ValueType::INTEGER ? &integer_ : nullptr;
}
const String* Value::is_str() const {
return type_ == ValueType::STR ? &str_ : nullptr;
}
Value& Value::operator [] (const char* key) {
if (type_ != ValueType::DICT)
throw std::logic_error("Value is not a dict!");
return dict_[key];
}
const Value& Value::operator [] (const char* key) const {
if (type_ != ValueType::DICT)
throw std::logic_error("Value is not a dict!");
return dict_.at(key);
}
bool operator < (const Value& a, const Value& b) {
if (a.is_real() && b.is_real()) {
return a.real() < b.real();
}
else if (a.is_str() && b.is_str()) {
return a.str() < b.str();
}
return true;
}
bool operator == (const Value& a, const Value& b) {
if (a.type() != b.type()) {
return false;
}
if (a.is_dict() && b.is_dict()) {
auto u = a.dict();
auto v = b.dict();
if (u.size() != v.size()) {
return false;
}
for (auto&& cmp : zip(u, v)) {
if (cmp.fst->first != cmp.snd->first || cmp.fst->second != cmp.snd->second) {
return false;
}
}
}
else if (a.is_array() && b.is_array()) {
if (a.array().size() != b.array().size()) {
return false;
}
auto u = a.array();
auto v = b.array();
if (u.size() != v.size()) {
return false;
}
for (auto&& cmp : zip(u, v)) {
if (cmp.fst != cmp.snd) {
return false;
}
}
}
else if (a.is_str() && b.is_str()) {
return a.str() == b.str();
}
else if (a.is_real() && b.is_real()) {
return a.real() == b.real();
}
return true;
}
bool operator != (const Value& a, const Value& b) {
return !(a == b);
}
} // namespace enji
| 23.151639 | 89 | 0.571429 | [
"vector"
] |
fa72c7b142659cfc111f4c5307b2a1ed9620cf80 | 599 | cpp | C++ | Examples.cpp | rnsheehan/slab_wg_solver | 04f5be013ef769b0487f9e8534cd34499e75f8ee | [
"MIT"
] | null | null | null | Examples.cpp | rnsheehan/slab_wg_solver | 04f5be013ef769b0487f9e8534cd34499e75f8ee | [
"MIT"
] | null | null | null | Examples.cpp | rnsheehan/slab_wg_solver | 04f5be013ef769b0487f9e8534cd34499e75f8ee | [
"MIT"
] | null | null | null | #ifndef ATTACH_H
#include "Attach.h"
#endif
void examples::slab_wg_test()
{
// Example to illustrate the use of the slab wg solver
// define parameters
double width = 2.0;
double wavelength = 1.55;
double core = 3.38;
double sub = 3.17;
double clad = 3.17;
// Declarate slab_wg object
slab_wg the_slab(width, wavelength, core, sub, clad);
std::string null_string = "";
//the_slab.calculate_all_neffs(null_string);
the_slab.calculate_all_modes(50, 10, null_string);
/*the_slab.clearbeta(TE);
the_slab.clearbeta(TM);*/
std::cout<<"\n";
} | 19.966667 | 56 | 0.657763 | [
"object"
] |
fa73fcc51799905b22de01eb69521a338df575d8 | 10,503 | cpp | C++ | pcl/src/other/bluerov_nestdetect.cpp | lukechencqu/bluerov_zed_tracking | 75d87cfc183839615fada0731724cf0a230a0970 | [
"Apache-2.0"
] | 2 | 2021-07-21T12:21:26.000Z | 2021-12-02T00:57:02.000Z | pcl/src/other/bluerov_nestdetect.cpp | lukechencqu/bluerov_zed_tracking | 75d87cfc183839615fada0731724cf0a230a0970 | [
"Apache-2.0"
] | null | null | null | pcl/src/other/bluerov_nestdetect.cpp | lukechencqu/bluerov_zed_tracking | 75d87cfc183839615fada0731724cf0a230a0970 | [
"Apache-2.0"
] | null | null | null | #include "opencv2/objdetect.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include <iostream>
using namespace std;
using namespace cv;
static void help()
{
cout << "\nThis program demonstrates the use of cv::CascadeClassifier class to detect objects (Face + eyes). You can use Haar or LBP features.\n"
"This classifier can recognize many kinds of rigid objects, once the appropriate classifier is trained.\n"
"It's most known use is for faces.\n"
"Usage:\n"
"./facedetect [--cascade=<cascade_path> this is the primary trained classifier such as frontal face]\n"
" [--nested-cascade[=nested_cascade_path this an optional secondary classifier such as eyes]]\n"
" [--scale=<image scale greater or equal to 1, try 1.3 for example>]\n"
" [--try-flip]\n"
" [filename|camera_index]\n\n"
"see facedetect.cmd for one call:\n"
"./facedetect --cascade=\"data/haarcascades/haarcascade_frontalface_alt.xml\" --nested-cascade=\"data/haarcascades/haarcascade_eye_tree_eyeglasses.xml\" --scale=1.3\n\n"
"During execution:\n\tHit any key to quit.\n"
"\tUsing OpenCV version " << CV_VERSION << "\n" << endl;
}
void detectAndDraw( Mat& img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade,
double scale, bool tryflip );
string cascadeName;
string nestedCascadeName;
int main( int argc, const char** argv )
{
VideoCapture capture;
Mat frame, image;
string inputName;
bool tryflip;
CascadeClassifier cascade, nestedCascade;
double scale;
cv::CommandLineParser parser(argc, argv,
"{help h||}"
"{cascade|data/haarcascades/haarcascade_frontalface_alt.xml|}"
"{nested-cascade|data/haarcascades/haarcascade_eye_tree_eyeglasses.xml|}"
"{scale|1|}{try-flip||}{@filename||}"
);
if (parser.has("help"))
{
help();
return 0;
}
cascadeName = parser.get<string>("cascade");
nestedCascadeName = parser.get<string>("nested-cascade");
scale = parser.get<double>("scale");
if (scale < 1)
scale = 1;
tryflip = parser.has("try-flip");
inputName = parser.get<string>("@filename");
if (!parser.check())
{
parser.printErrors();
return 0;
}
if (!nestedCascade.load(samples::findFileOrKeep(nestedCascadeName)))
cerr << "WARNING: Could not load classifier cascade for nested objects" << endl;
if (!cascade.load(samples::findFile(cascadeName)))
{
cerr << "ERROR: Could not load classifier cascade" << endl;
help();
return -1;
}
if( inputName.empty() || (isdigit(inputName[0]) && inputName.size() == 1) )
{
int camera = inputName.empty() ? 0 : inputName[0] - '0';
if(!capture.open(camera))
{
cout << "Capture from camera #" << camera << " didn't work" << endl;
return 1;
}
}
else if (!inputName.empty())
{
image = imread(samples::findFileOrKeep(inputName), IMREAD_COLOR);
if (image.empty())
{
if (!capture.open(samples::findFileOrKeep(inputName)))
{
cout << "Could not read " << inputName << endl;
return 1;
}
}
}
else
{
image = imread(samples::findFile("lena.jpg"), IMREAD_COLOR);
if (image.empty())
{
cout << "Couldn't read lena.jpg" << endl;
return 1;
}
}
if( capture.isOpened() )
{
cout << "Video capturing has been started ..." << endl;
for(;;)
{
capture >> frame;
if( frame.empty() )
break;
Mat frame1 = frame.clone();
detectAndDraw( frame1, cascade, nestedCascade, scale, tryflip );
char c = (char)waitKey(10);
if( c == 27 || c == 'q' || c == 'Q' )
break;
}
}
else
{
cout << "Detecting face(s) in " << inputName << endl;
if( !image.empty() )
{
detectAndDraw( image, cascade, nestedCascade, scale, tryflip );
waitKey(0);
}
else if( !inputName.empty() )
{
/* assume it is a text file containing the
list of the image filenames to be processed - one per line */
FILE* f = fopen( inputName.c_str(), "rt" );
if( f )
{
char buf[1000+1];
while( fgets( buf, 1000, f ) )
{
int len = (int)strlen(buf);
while( len > 0 && isspace(buf[len-1]) )
len--;
buf[len] = '\0';
cout << "file " << buf << endl;
image = imread( buf, 1 );
if( !image.empty() )
{
detectAndDraw( image, cascade, nestedCascade, scale, tryflip );
char c = (char)waitKey(0);
if( c == 27 || c == 'q' || c == 'Q' )
break;
}
else
{
cerr << "Aw snap, couldn't read image " << buf << endl;
}
}
fclose(f);
}
}
}
return 0;
}
void detectAndDraw( Mat& img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade,
double scale, bool tryflip )
{
double t = 0;
vector<Rect> faces, faces2;
Mat gray, smallImg;
Size minSize = Size(smallImg.cols*0.1, smallImg.rows*0.1);
Size maxSize = Size(smallImg.cols*0.3, smallImg.rows*0.3);
int nearNum1 = 50, nearNum2 = 10;
cvtColor( img, gray, COLOR_BGR2GRAY );
double fx = 1 / scale;
resize( gray, smallImg, Size(), fx, fx, INTER_LINEAR_EXACT );
equalizeHist( smallImg, smallImg );
cout<<"img w,h: "<<img.cols<<" "<<img.rows<<endl;
cout<<"smallimg w,h: "<<smallImg.cols<<" "<<smallImg.rows<<endl;
t = (double)getTickCount();
cascade.detectMultiScale( smallImg, faces,
1.1, nearNum1, 0
|CASCADE_FIND_BIGGEST_OBJECT,
//|CASCADE_DO_ROUGH_SEARCH
// |CASCADE_SCALE_IMAGE,
minSize, maxSize);
// if( tryflip )
// {
// flip(smallImg, smallImg, 1);
// cascade.detectMultiScale( smallImg, faces2,
// 1.1, nearNum1, 0
// //|CASCADE_FIND_BIGGEST_OBJECT
// //|CASCADE_DO_ROUGH_SEARCH
// |CASCADE_SCALE_IMAGE,
// Size(30, 30) );
// for( vector<Rect>::const_iterator r = faces2.begin(); r != faces2.end(); ++r )
// {
// faces.push_back(Rect(smallImg.cols - r->x - r->width, r->y, r->width, r->height));
// }
// }
t = (double)getTickCount() - t;
printf( "1st round detection time = %g ms\n", t*1000/getTickFrequency());
for ( size_t i = 0; i < faces.size(); i++ )
{
Rect r = faces[i];
cout<<"r origin: "<<r.x<<" "<<r.y<<endl;
cout<<"r w h: "<<r.width<<" "<<r.height<<endl;
Rect r2;
r2 = r;
cout<<"r2 origin: "<<r2.x<<" "<<r2.y<<endl;
cout<<"r2 w h: "<<r2.width<<" "<<r2.height<<endl;
float rScale = 1.2;
r2.width = r.width*rScale;
r2.height = r.height*1;
float rCenter = r.x + r.width/2;
// cout<<"r center = "<<rCenter<<endl;
// cout<<"r2 width/2 = "<<r2.width*0.5<<endl;
r2.x = rCenter - r2.width/2;
cout<<"r22 origin: "<<r2.x<<" "<<r2.y<<endl;
cout<<"r22 w h: "<<r2.width<<" "<<r2.height<<endl;
Mat smallImgROI;
vector<Rect> nestedObjects;
Scalar color1 = Scalar(0,255,0); //BLUE
// rectangle( img, Point(cvRound(r.x*scale), cvRound(r.y*scale)),
// Point(cvRound((r.x + r.width-1)*scale), cvRound((r.y + r.height-1)*scale)),
// color1, 3, 8, 0);
rectangle( img, Point(cvRound(r2.x*scale), cvRound(r2.y*scale)),
Point(cvRound((r2.x + r2.width-1)*scale), cvRound((r2.y + r2.height-1)*scale)),
color1, 3, 8, 0);
cout<<endl;
if( nestedCascade.empty() )
continue;
smallImgROI = smallImg( r2 );
cout<<"smallImgROI w,h: "<<smallImgROI.cols<<" "<<smallImgROI.rows<<endl;
Size minSize2 = Size(smallImgROI.cols*0.6, smallImgROI.rows*0.2);
Size maxSize2 = Size(smallImgROI.cols*1, smallImgROI.rows*0.5);
t = (double)getTickCount();
nestedCascade.detectMultiScale( smallImgROI, nestedObjects,
1.1, nearNum2, 0
|CASCADE_FIND_BIGGEST_OBJECT,
//|CASCADE_DO_ROUGH_SEARCH
//|CASCADE_DO_CANNY_PRUNING
// |CASCADE_SCALE_IMAGE,
minSize2, maxSize2 );
t = (double)getTickCount() - t;
printf( "2nd round detection time = %g ms\n", t*1000/getTickFrequency());
for ( size_t j = 0; j < nestedObjects.size(); j++ )
{
Rect nr = nestedObjects[j];
Scalar color2 = Scalar(255,0,0); //BGR
Scalar color12 = Scalar(0,0,255); //BGR
// nested object
// rectangle( img, Point(cvRound((r.x+nr.x)*scale), cvRound((r.y+nr.y)*scale)),
// Point(cvRound((r.x + nr.width-1)*scale), cvRound((r.y + nr.height-1)*scale)),
// color2, 3, 8, 0);
rectangle( img, Point(cvRound((r2.x+nr.x)*scale), cvRound((r2.y+nr.y)*scale)),
Point(cvRound((r2.x + nr.width-1)*scale), cvRound((r2.y + nr.height-1)*scale)),
color2, 3, 8, 0);
// confirmed object
rectangle( img, Point(cvRound(r.x*scale), cvRound(r.y*scale)),
Point(cvRound((r.x + r.width-1)*scale), cvRound((r.y + r.height-1)*scale)),
color12, 3, 8, 0);
}
cout<<"---------------------------"<<endl;
}
cout<<"=================================="<<endl;
imshow( "result", img );
}
| 36.092784 | 181 | 0.503856 | [
"object",
"vector"
] |
fa767f26724e452cd8979e72328d3d038bd43af2 | 769 | cpp | C++ | src/rtcore/IAccStructBuilder.cpp | potato3d/rtrt2 | 5c135c1aea0ded2898e16220cec5ed2860dcc9b3 | [
"MIT"
] | 1 | 2021-11-06T06:13:05.000Z | 2021-11-06T06:13:05.000Z | src/rtcore/IAccStructBuilder.cpp | potato3d/rtrt2 | 5c135c1aea0ded2898e16220cec5ed2860dcc9b3 | [
"MIT"
] | null | null | null | src/rtcore/IAccStructBuilder.cpp | potato3d/rtrt2 | 5c135c1aea0ded2898e16220cec5ed2860dcc9b3 | [
"MIT"
] | null | null | null | #include <rti/IAccStructBuilder.h>
using namespace rti;
void IAccStructBuilder::buildGeometry( rt::Geometry* geometry )
{
rt::Aabb bbox;
if( !geometry->vertices.empty() )
bbox.buildFrom( &geometry->vertices[0], geometry->vertices.size() );
geometry->accStruct = new IAccStruct();
geometry->accStruct->setBoundingBox( bbox );
}
IAccStruct* IAccStructBuilder::buildInstance( const std::vector<rt::Instance> instances )
{
// Default degenerate box
rt::Aabb bbox;
vr::vec3f boxVertices[8];
// Compute general bounding box of entire scene
for( uint32 i = 0; i < instances.size(); ++i )
{
const rt::Instance& instance = instances[i];
bbox.expandBy( instances[i].bbox );
}
IAccStruct* st = new IAccStruct;
st->setBoundingBox( bbox );
return st;
}
| 22.617647 | 89 | 0.706112 | [
"geometry",
"vector"
] |
fa7b50372fa5ddf516f56708cb4cdaed8a200ec8 | 1,344 | cpp | C++ | lumino/LuminoEngine/src/Animation/AnimationClock.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 113 | 2020-03-05T01:27:59.000Z | 2022-03-28T13:20:51.000Z | lumino/LuminoEngine/src/Animation/AnimationClock.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 13 | 2020-03-23T20:36:44.000Z | 2022-02-28T11:07:32.000Z | lumino/LuminoEngine/src/Animation/AnimationClock.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 12 | 2020-12-21T12:03:59.000Z | 2021-12-15T02:07:49.000Z |
#include "Internal.hpp"
#include <LuminoEngine/Animation/AnimationClock.hpp>
#include <LuminoEngine/Animation/AnimationTrack.hpp>
#include "AnimationManager.hpp"
namespace ln {
//==============================================================================
// AnimationClock
AnimationClock::AnimationClock()
{
}
AnimationClock::~AnimationClock()
{
}
void AnimationClock::init(AnimationClockAffiliation affiliation)
{
Object::init();
detail::EngineDomain::animationManager()->addClockToAffiliation(this, affiliation);
}
bool AnimationClock::isFinished() const
{
LN_NOTIMPLEMENTED();
return false;
//return m_timelineInstance == nullptr || m_timelineInstance->isFinished();
}
void AnimationClock::advanceTime(float deltaTime)
{
LN_NOTIMPLEMENTED();
//if (m_timelineInstance != nullptr)
//{
// m_timelineInstance->advanceTime(deltaTime);
//}
}
//==============================================================================
// SingleAnimationClock
SingleAnimationClock::SingleAnimationClock()
{
}
SingleAnimationClock::~SingleAnimationClock()
{
}
void SingleAnimationClock::init()
{
AnimationClock::init(AnimationClockAffiliation::ActiveWorld);
}
void SingleAnimationClock::setTrack(AnimationTrack* track)
{
m_track = track;
}
} // namespace ln | 21.333333 | 88 | 0.635417 | [
"object"
] |
fa8a82bba5b36db777e8788f6d6cc5fd2a117a94 | 293 | cpp | C++ | codes/src/tool/ModelImport.cpp | liangpengcheng/tng | 01c6517f734d5db01f7d59bf95b225f6d1642b6e | [
"BSD-3-Clause"
] | 3 | 2016-04-16T06:24:20.000Z | 2018-09-29T13:36:51.000Z | codes/src/tool/ModelImport.cpp | liangpengcheng/tng | 01c6517f734d5db01f7d59bf95b225f6d1642b6e | [
"BSD-3-Clause"
] | null | null | null | codes/src/tool/ModelImport.cpp | liangpengcheng/tng | 01c6517f734d5db01f7d59bf95b225f6d1642b6e | [
"BSD-3-Clause"
] | 3 | 2016-04-29T11:46:08.000Z | 2019-09-16T03:27:30.000Z | #include "tool/ModelImport.h"
#include "graphics/model.h"
#include "core/os.h"
namespace tng
{
bool ImportModel(const string src,const string dest)
{
AutoPtr<FileModel> model = FileModel::LoadResource(src, false);
FileOutputStream saver(dest);
model->Save(saver);
return true;
}
} | 20.928571 | 65 | 0.726962 | [
"model"
] |
fa8b4c4f22eb7ec74ced1be29c9f00d45e1499e9 | 802 | cpp | C++ | JEBMath/UnitTest/GeometryTest/test_CubicHermiteSpline.cpp | jebreimo/JEBLib | 9066403a9372951aa8ce4f129cd4877e2ae779ab | [
"BSD-3-Clause"
] | 1 | 2019-12-25T05:30:20.000Z | 2019-12-25T05:30:20.000Z | JEBMath/UnitTest/GeometryTest/test_CubicHermiteSpline.cpp | jebreimo/JEBLib | 9066403a9372951aa8ce4f129cd4877e2ae779ab | [
"BSD-3-Clause"
] | null | null | null | JEBMath/UnitTest/GeometryTest/test_CubicHermiteSpline.cpp | jebreimo/JEBLib | 9066403a9372951aa8ce4f129cd4877e2ae779ab | [
"BSD-3-Clause"
] | null | null | null | #include "JEBMath/Geometry/CubicHermiteSpline.hpp"
// #include "JEBMath/Geometry/Point.hpp"
#include "JEBMath/Geometry/Vector.hpp"
#include <JEBTest/JEBTest.hpp>
using namespace JEBMath;
static void test_Dim2()
{
// typedef Point<double, 2> P;
// typedef CubicHermiteSpline<2> CHS;
auto p1 = vector2(1.0, 1.0);
auto v1 = vector2(1.0, 1.0);
auto p2 = vector2(3.0, 1.0);
auto v2 = vector2(1.0, -1.0);
CubicHermiteSpline<2> spline(p1, v1, p2, v2);
JT_EQUAL(spline.getStart(), p1);
JT_EQUAL(spline.getStartTangent(), v1);
JT_ASSERT(areEquivalent(spline.getEnd(), p2, 1e-12));
JT_ASSERT(areEquivalent(spline.getEndTangent(), v2, 1e-12));
JT_EQUIVALENT(getX(spline.getPointAt(0.5)), 2, 1e-12);
}
JT_SUBTEST("Geometry", test_Dim2);
| 30.846154 | 65 | 0.657107 | [
"geometry",
"vector"
] |
fa8b711d7cd0f3e406e38f3215e3c297a69008d0 | 1,628 | hpp | C++ | src/object.hpp | takah29/path-tracer | 85b86db109428b9d54cf60877fc9971ff1660a38 | [
"MIT"
] | 6 | 2019-09-20T00:19:14.000Z | 2022-03-11T11:06:24.000Z | src/object.hpp | takah29/path-tracer | 85b86db109428b9d54cf60877fc9971ff1660a38 | [
"MIT"
] | 1 | 2018-11-26T11:55:24.000Z | 2018-11-26T11:55:24.000Z | src/object.hpp | takah29/path-tracer | 85b86db109428b9d54cf60877fc9971ff1660a38 | [
"MIT"
] | null | null | null | #ifndef _OBJECT_H_
#define _OBJECT_H_
#include "material.hpp"
#include "ray.hpp"
struct BBox {
Vec corner0;
Vec corner1;
Vec center;
BBox();
BBox(const Vec &corner0, const Vec &corner1);
~BBox();
void set_corner(const Vec &corner0, const Vec &corner1);
void empty();
bool hit(const Ray &ray) const;
};
struct Object {
Vec center;
BBox bbox;
Material *material_ptr;
Object();
Object(const Vec ¢er, const BBox &bbox, Material *material_ptr);
virtual ~Object();
void set_material(Material *material_ptr);
virtual bool intersect(const Ray &ray, Hitpoint &hitpoint) const = 0;
};
struct Sphere : public Object {
double radius;
Sphere();
Sphere(const double radius, const Vec ¢er, Material *material_ptr);
~Sphere();
bool intersect(const Ray &ray, Hitpoint &hitpoint) const;
};
struct Plane : public Object {
Vec normal;
Plane();
Plane(const Vec ¢er, const Vec &normal, Material *material_ptr);
~Plane();
bool intersect(const Ray &ray, Hitpoint &hitpoint) const;
};
struct Box : public Object {
Vec corner0;
Vec corner1;
Box();
Box(const Vec &corner0, const Vec &corner1, Material *material_ptr);
~Box();
Vec get_normal(const int face_hit) const;
bool intersect(const Ray &ray, Hitpoint &hitpoint) const;
};
struct Triangle : public Object {
Vec v0, v1, v2;
Vec normal;
Triangle();
Triangle(const Vec &v0, const Vec &v1, const Vec &v2, Material *material_ptr);
~Triangle();
bool intersect(const Ray &ray, Hitpoint &hitpoint) const;
};
#endif
| 20.871795 | 82 | 0.655405 | [
"object"
] |
fa8e3bcaf009e8be02c2a1eedbb890758e3aa281 | 1,175 | cpp | C++ | src/wasm.cpp | zandaqo/iswasmfast | 54bbb7b539c127185c974a47d7dd9e2431ddf9ff | [
"MIT"
] | 182 | 2017-06-24T10:38:03.000Z | 2022-02-03T09:38:11.000Z | src/wasm.cpp | zandaqo/iswasmfast | 54bbb7b539c127185c974a47d7dd9e2431ddf9ff | [
"MIT"
] | 8 | 2017-09-19T16:14:02.000Z | 2021-06-17T12:01:32.000Z | src/wasm.cpp | zandaqo/iswasmfast | 54bbb7b539c127185c974a47d7dd9e2431ddf9ff | [
"MIT"
] | 17 | 2017-08-23T11:17:23.000Z | 2021-12-09T03:47:18.000Z | #include <vector>
#include <iterator>
#include <emscripten/bind.h>
#include "../lib/levenstein.cpp"
#include "../lib/fibonacci.cpp"
#include "../lib/fermat.cpp"
#include "../lib/regression.cpp"
#include "../lib/sha256.cpp"
using namespace emscripten;
std::vector<double> vecFromArray(const val &arr) {
unsigned int length = arr["length"].as<unsigned int>();
std::vector<double> vec(length);
val memory = val::module_property("buffer");
val memoryView = val::global("Float64Array").new_(memory, reinterpret_cast<std::uintptr_t>(vec.data()), length);
memoryView.call<void>("set", arr);
return vec;
}
val slr(const val& a, const val& b) {
auto y = vecFromArray(a);
auto x = vecFromArray(b);
auto result = regression(y, x);
val r(val::object());
r.set("slope", val(result.slope));
r.set("intercept", val(result.intercept));
r.set("r2", val(result.r2));
return r;
}
EMSCRIPTEN_BINDINGS(my_module) {
emscripten::function("levenstein", &levenstein);
emscripten::function("fibonacci", &fibonacci);
emscripten::function("fermat", &isPrime);
emscripten::function("regression", &slr);
emscripten::function("sha256", &SHA256);
}
| 30.128205 | 114 | 0.68 | [
"object",
"vector"
] |
fa92298312cbed90fe7031c8a9f31137d8787b3c | 7,072 | cpp | C++ | SatisfactoryPlanner/opengl.cpp | yeshjho/SatisfactoryPlanner | 15b1bbe22959fb8d89f0c2508cca969062c9cd6e | [
"MIT"
] | null | null | null | SatisfactoryPlanner/opengl.cpp | yeshjho/SatisfactoryPlanner | 15b1bbe22959fb8d89f0c2508cca969062c9cd6e | [
"MIT"
] | null | null | null | SatisfactoryPlanner/opengl.cpp | yeshjho/SatisfactoryPlanner | 15b1bbe22959fb8d89f0c2508cca969062c9cd6e | [
"MIT"
] | null | null | null | #include <chrono>
#include <iostream>
#include <random>
#include <thread>
#include <GLFW/glfw3.h>
#include <glm/gtx/transform.hpp>
#include "BatchRenderer.h"
#include "Camera.h"
#include "InputCallback.h"
#include "Model.h"
#include "Window.h"
glm::mat4 rotate(const float xAngle, const float yAngle, const float zAngle)
{
const float cosX = cos(xAngle);
const float cosY = cos(yAngle);
const float cosZ = cos(zAngle);
const float sinX = sin(xAngle);
const float sinY = sin(yAngle);
const float sinZ = sin(zAngle);
return {
cosZ * cosY, sinZ * cosY, -sinY, 0,
cosZ * sinY * sinX - sinZ * cosX, sinZ * sinY * sinX + cosZ * cosX, cosY * sinX, 0,
cosZ * sinY * cosX + sinZ * sinX, sinZ * sinY * cosX - cosZ * sinX, cosY * cosX, 0,
0, 0, 0, 1
};
}
int main()
{
const Window window = create_window();
BatchRenderer renderer{ "resource/texture/textures.yaml" };
Camera camera{ glm::vec3{ 0, 0, 9 }, glm::vec3{ 0, 0, -1 }, glm::vec3{ 0, 1, 0 },
glm::pi<float>() / 2, 16.f / 9.f, 0.1f, 100000 };
std::vector<ObjectHandle> handles;
handles.reserve(317 * 317);
const TextureSet::TextureInfo model1TextureInfo = renderer.GetTextureSet().GetTextureInfo("first_texture");
const TextureSet::TextureInfo::Texel model1Texel = model1TextureInfo.texel;
const TextureSet::TextureInfo model2TextureInfo = renderer.GetTextureSet().GetTextureInfo("second_texture");
const TextureSet::TextureInfo::Texel model2Texel = model2TextureInfo.texel;
const Model model1{
{
{ { 0, 1, 0, 1 }, { 0, 1, 0, 1 }, { model1Texel.x, model1Texel.y + model1Texel.height }, model1TextureInfo.textureIndex },
{ { 0, 0, 0, 1 }, { 1, 0, 0, 1 }, { model1Texel.x, model1Texel.y }, model1TextureInfo.textureIndex },
{ { 1, 1, 0, 1 }, { 0, 0, 1, 1 }, { model1Texel.x + model1Texel.width, model1Texel.y + model1Texel.height }, model1TextureInfo.textureIndex },
{ { 1, 0, 0, 1 }, { 1, 1, 1, 1 }, { model1Texel.x + model1Texel.width, model1Texel.y }, model1TextureInfo.textureIndex },
},
{ 0, 1, 2, 3 }
};
const Model model2{
{
{ { 0, 1, 0, 1 }, { 0, 1, 0, 1 }, { model2Texel.x, model2Texel.y + model2Texel.height }, model2TextureInfo.textureIndex },
{ { 0, 0, 0, 1 }, { 1, 0, 0, 1 }, { model2Texel.x, model2Texel.y }, model2TextureInfo.textureIndex },
{ { 1, 1, 0, 1 }, { 0, 0, 1, 1 }, { model2Texel.x + model2Texel.width, model2Texel.y + model2Texel.height }, model2TextureInfo.textureIndex },
{ { 1, 0, 0, 1 }, { 1, 1, 1, 1 }, { model2Texel.x + model2Texel.width, model2Texel.y }, model2TextureInfo.textureIndex },
},
{ 0, 1, 2, 3 }
};
float x = -0.5f;
float z = 0.5f;
float y = 0;
const EMouseButton cameraOperateButton = EMouseButton::RIGHT;
InputCallback camRotationCallback{ EInputType::MOUSE_MOVE,
[&camera, cameraOperateButton](const float moveX, const float moveY)
{
if (InputManager::IsMouseDown(cameraOperateButton))
{
camera.Yaw(-static_cast<float>(moveX) * glm::pi<float>() / 180 / 2)
.Pitch(-static_cast<float>(moveY) * glm::pi<float>() / 180 / 2);
}
}
};
InputCallback camZoomCallback{
EInputType::MOUSE_SCROLL,
[&camera](float, const float yMove)
{
if (yMove < 0)
{
camera.Zoom(-yMove * 1.5f);
}
else
{
camera.Zoom(1 / yMove / 2);
}
}
};
InputCallback camRollClockwiseCallback{
[&camera, cameraOperateButton]()
{
if (InputManager::IsMouseDown(cameraOperateButton))
{
camera.Roll(glm::pi<float>() / 180 / 2);
}
},
EKeyButton::E, EButtonAction::REPEAT
};
InputCallback camRollCounterClockwiseCallback{
[&camera, cameraOperateButton]()
{
if (InputManager::IsMouseDown(cameraOperateButton))
{
camera.Roll(-glm::pi<float>() / 180 / 2);
}
},
EKeyButton::Q, EButtonAction::REPEAT
};
InputCallback camForwardCallback {
[&camera, cameraOperateButton]()
{
if (InputManager::IsMouseDown(cameraOperateButton))
{
camera.MoveForward(1.f);
}
},
EKeyButton::W, EButtonAction::REPEAT
};
InputCallback camBackwardCallback{
[&camera, cameraOperateButton]()
{
if (InputManager::IsMouseDown(cameraOperateButton))
{
camera.MoveBackward(1.f);
}
},
EKeyButton::S, EButtonAction::REPEAT
};
InputCallback camRightCallback{
[&camera, cameraOperateButton]()
{
if (InputManager::IsMouseDown(cameraOperateButton))
{
camera.MoveRight(1.f);
}
},
EKeyButton::D, EButtonAction::REPEAT
};
InputCallback camLeftCallback{
[&camera, cameraOperateButton]()
{
if (InputManager::IsMouseDown(cameraOperateButton))
{
camera.MoveLeft(1.f);
}
},
EKeyButton::A, EButtonAction::REPEAT
};
InputCallback addFirstModelCallback{
[&]()
{
handles.emplace_back(renderer.AddObject(model1, glm::translate(glm::vec3{ x += 0.5f, 0, z -= 0.5f }) * rotate(0, 0, 0) * glm::scale(glm::vec3{ 1, 1, 1 })));
},
EKeyButton::NUM_1
};
InputCallback addSecondModelCallback{
[&]()
{
handles.emplace_back(renderer.AddObject(model2, glm::translate(glm::vec3{ 1.5f, y += 1.5f, 0 }) * rotate(0, 0, 0) * glm::scale(glm::vec3{ 1, 1, 1 })));
},
EKeyButton::NUM_2
};
//InputCallback removeModelCallback{
// [&]()
// {
// renderer.RemoveObject(handleQueue.front());
// handleQueue.pop();
// },
// EKeyButton::NUM_0
//};
for (int i = 0; i < 317; i++)
{
for (int j = 0; j < 317; j++)
{
handles.emplace_back(renderer.AddObject(model1,
glm::translate(glm::vec3{ i, j, 0 }) *
rotate(0, 0, 0) *
glm::scale(glm::vec3{ 1, 1, 1 })));
}
}
std::atomic<bool> shouldEnd = false;
std::thread t{
[&shouldEnd, handles, &renderer]()
{
using namespace std::chrono_literals;
std::this_thread::sleep_for(5s);
std::random_device rd{};
const std::uniform_real_distribution<float> locDist{ -3.f / 144, 3.f / 144 };
const std::uniform_real_distribution<float> angleDist{ -glm::pi<float>() / 2, glm::pi<float>() / 2 };
const std::uniform_real_distribution<float> scaleDist{ 0.5f, 2.f };
while (!shouldEnd)
{
for (int i = 0; i < 317; i++)
{
for (int j = 0; j < 317; j++)
{
const ObjectHandle handle = handles[i * 317 + j];
renderer.ApplyMatrixToObject(handle,
/*glm::translate(glm::vec3{ locDist(rd), locDist(rd), 0 }) **/
glm::translate(glm::vec3{ i, j, 0 }) *
rotate(angleDist(rd), angleDist(rd), angleDist(rd)) *
glm::scale(glm::vec3{ scaleDist(rd), scaleDist(rd), 1 })*
glm::translate(glm::vec3{ -i, -j, 0 })
);
}
}
}
}
};
while (!window.ShouldClose())
{
using namespace std::chrono;
static time_point<steady_clock> previous = steady_clock::now();
const time_point<steady_clock> current = steady_clock::now();
const long long deltaTimeInNanosecond = duration_cast<nanoseconds>(current - previous).count();
previous = current;
std::cout << "FPS: " << 1'000'000'000 / static_cast<double>(deltaTimeInNanosecond) << '\n';
window.SwapBuffers();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glfwPollEvents();
InputManager::_Update();
renderer.Render(camera);
}
shouldEnd = true;
t.join();
}
| 28.631579 | 159 | 0.642534 | [
"render",
"vector",
"model",
"transform"
] |
fa956b10482d64bb4bd4ddcb2cfb5047fd53447f | 3,375 | cpp | C++ | source/gui.cpp | cool-school/opencv-project | bd38413521caacd4aa4fcac8e9c5c9d49c3d0d06 | [
"MIT"
] | null | null | null | source/gui.cpp | cool-school/opencv-project | bd38413521caacd4aa4fcac8e9c5c9d49c3d0d06 | [
"MIT"
] | null | null | null | source/gui.cpp | cool-school/opencv-project | bd38413521caacd4aa4fcac8e9c5c9d49c3d0d06 | [
"MIT"
] | null | null | null | #include "head.h"
/** globals */
VideoCapture capture(0);
Mat3b canvas;
const double FONT_SIZE = 0.7;
string winName = "GUI v0.1";
vector <pair <int, int> > points;
/** description
* 0 = esc, 1 = mode_pendulum, 2 = mode_rolling, 3 = set_mask, 4 = Start!
*/
const int N_buttons = 5;
Rect buttons[N_buttons];
string buttons_names[N_buttons] = {"esc", "pendulum", "rolling", "mask", "select points"};
Mat choose_mask();
void select_points();
Mat mask;
string state = "work";
void CallBackFunc(int event, int x, int y, int flags, void* userdata)
{
if( event == EVENT_LBUTTONDOWN)
{
points.emplace_back(x, y);
printf(".");
}
}
void callBackFunc(int event, int x, int y, int flags, void* userdata)
{
if (event == EVENT_LBUTTONDOWN)
{
for(int i = 0; i < N_buttons; i++)
{
if(buttons[i].contains(Point(x, y)))
{
//cout << buttons_names[i] << endl;
if(i == 0) state = "end";
if(i == 1) state = "pendulum";
if(i == 2) state = "friction";
if(i == 3) choose_mask();
if(i == 4) select_points();
}
}
}
imshow(winName, canvas);
waitKey(1);
}
Mat choose_mask()
{
printf("click at the left upper conner and then right lower conner of the desired mask\n");
Mat result, frame, mm;
while( points.size() < 2)
{
capture.retrieve(frame);
imshow("result", frame);
waitKey(1);
cvtColor(frame, mm, COLOR_RGB2GRAY);
setMouseCallback("result", CallBackFunc, nullptr);
}
result = mm(Rect(points[0].first, points[0].second, points[1].first- points[0].first, points[1].second - points[0].second));
imwrite("saved_photo/mask.png", result);
mask = imread("saved_photo/mask.png", IMREAD_GRAYSCALE);
printf("mask has been set!");
points.clear();
return result;
}
void select_points()
{
points.clear();
int n;
printf("enter number of points: ");
cin >> n;
printf("click %d times\n", n);
Mat result, frame, mm;
while(points.size() < n)
{
capture.retrieve(frame);
imshow("result", frame);
setMouseCallback("result", CallBackFunc, nullptr);
waitKey(1);
}
printf("all points selected!!!\n");
}
int main()
{
Mat frame, mm, img;
namedWindow(winName);
// Your buttons
int button_length = 100, button_height = 50;
for(int i = 0; i < N_buttons; i++)
buttons[i] = Rect(10, (button_height + 10) * i + 10, button_length, button_height);
// The canvas
canvas = Mat3b(CAMERA_HEIGHT, CAMERA_WIDTH + button_length + 20, Vec3b(0,0,0));
// Draw the button
for(int i = 0; i < N_buttons; i++)
{
canvas(buttons[i]) = Vec3b(200,200,200);
putText(canvas(buttons[i]), buttons_names[i], Point(0, button_height/2), FONT_HERSHEY_TRIPLEX, FONT_SIZE, Scalar(0,0,0));
}
/*capture init*/
capture.set(CAP_PROP_FRAME_WIDTH, CAMERA_WIDTH);
capture.set(CAP_PROP_FRAME_HEIGHT, CAMERA_HEIGHT);
//createTrackbar("brightness", "result", &a ,255, NULL);
mask = imread("saved_photo/mask.png", IMREAD_GRAYSCALE);
int coef = 30;
createTrackbar("coef", winName, &coef ,255, nullptr);
while(state != "end")
{
capture.retrieve(frame);
cvtColor(frame, mm, COLOR_RGB2GRAY);
init(mm, mask, "found!");
img = Result(frame, 1, coef);
if(state == "pendulum")
pendulum();
if(state == "friction")
friction();
imshow("result", img);
setMouseCallback(winName, callBackFunc);
imshow(winName, canvas);
waitKey(1);
}
return 0;
} | 24.635036 | 125 | 0.641481 | [
"vector"
] |
fa96a55d933e1c8b022ca97b28b432e235a32172 | 304 | hpp | C++ | apps/novc/compiler.hpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 14 | 2020-04-14T17:00:56.000Z | 2021-08-30T08:29:26.000Z | apps/novc/compiler.hpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 27 | 2020-12-27T16:00:44.000Z | 2021-08-01T13:12:14.000Z | apps/novc/compiler.hpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 1 | 2020-05-29T18:33:37.000Z | 2020-05-29T18:33:37.000Z | #pragma once
#include "filesystem.hpp"
#include <vector>
namespace novc {
struct CompileOptions {
filesystem::path srcPath;
filesystem::path destPath;
const std::vector<filesystem::path>& searchPaths;
bool optimize;
};
auto compile(const CompileOptions& options) -> bool;
} // namespace novc
| 17.882353 | 52 | 0.736842 | [
"vector"
] |
fa97d179810428cb12a6817ea49c09447939afda | 8,495 | cpp | C++ | src/main.cpp | CaffeineViking/chip-8 | a4fe5e6313448d4f43d4b824dc44192737c0139b | [
"MIT"
] | 3 | 2017-08-07T20:48:26.000Z | 2019-12-31T10:33:08.000Z | src/main.cpp | CaffeineViking/chip-8 | a4fe5e6313448d4f43d4b824dc44192737c0139b | [
"MIT"
] | 3 | 2021-01-06T14:37:43.000Z | 2021-01-06T14:44:48.000Z | src/main.cpp | CaffeineViking/chip-8 | a4fe5e6313448d4f43d4b824dc44192737c0139b | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <SDL.h>
#include "memory.hpp"
#include "processor.hpp"
#include "definitions.hpp"
// Load ROM file to memory.
ch8::Memory load(const char* path) {
char* program;
std::size_t program_size;
std::ifstream program_stream { path, std::ios::binary };
if (program_stream) {
program_stream.seekg(0, std::ios::end);
program_size = program_stream.tellg();
program_stream.seekg(0, std::ios::beg);
program = new char[program_size];
program_stream.read(program, program_size);
} program_stream.close();
std::cout << path << " loaded, occupying " << program_size << " bytes." << std::endl;
ch8::Memory memory { reinterpret_cast<ch8::byte*>(program), program_size };
delete[] program; // Program already copied.
return memory; // Should use RVO semantics.
}
// Print the next instruction to be executed by the processor at current PC.
void print_instruction(const ch8::Memory& memory, ch8::addr program_counter) {
std::cout << "Next instruction: 0x" << std::setw(2) << std::setfill('0') << std::hex << static_cast<ch8::addr>(memory.read(program_counter))
<< std::setw(2) << std::setfill('0') << std::hex << static_cast<ch8::addr>(memory.read(program_counter + 1)) << std::endl;
}
// Prints display buffer (for debugging)...
void print_display(const ch8::byte* buffer) {
for (std::size_t y {0}; y < 32; ++y) {
for (std::size_t x {0}; x < 64; ++x) {
std::cout << static_cast<unsigned>(buffer[x + y * 64]);
} std::cout << std::endl;
}
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0]
<< " <rom path>" << std::endl;
return 1;
}
ch8::Memory memory { load(argv[1]) }; // Loads specified ROM with program.
ch8::Processor processor { memory }; // Processor needs to know about memory.
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cerr << "SDL_Init failed: "
<< SDL_GetError() << std::endl;
return 1;
}
std::string title { "chip-8 @ " + std::string{ argv[1] } };
SDL_Window* window { SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 320, 0) };
if (window == nullptr) {
std::cerr << "SDL_CreateWindow failed: "
<< SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, 0); // Nearest-neighbor filtering for textures (when scaled up).
SDL_Renderer* renderer { SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC) };
if (renderer == nullptr) {
std::cerr << "SDL_CreateRenderer failed: "
<< SDL_GetError() << std::endl;
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 1;
}
int display_buffer_width = -1; // The size of a row in the texture below (queried by SDL_LockTexture).
ch8::byte* display_buffer = nullptr; // We will load the buffer of the texture that is created in SDL_CreateTexture below, here.
SDL_Texture* display_buffer_texture { SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, 64, 32) };
if (display_buffer_texture == nullptr) {
std::cerr << "SDL_CreateTexture failed.: "
<< SDL_GetError() << std::endl;
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
bool step_mode { false };
bool force_exit { false };
unsigned current_time { SDL_GetTicks() };
unsigned interrupt_time { SDL_GetTicks() };
while (processor.running() && !force_exit) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_1: processor.key_released(0x01); break;
case SDLK_2: processor.key_released(0x02); break;
case SDLK_3: processor.key_released(0x03); break;
case SDLK_4: processor.key_released(0x0C); break;
case SDLK_q: processor.key_released(0x04); break;
case SDLK_w: processor.key_released(0x05); break;
case SDLK_e: processor.key_released(0x06); break;
case SDLK_r: processor.key_released(0x0D); break;
case SDLK_a: processor.key_released(0x07); break;
case SDLK_s: processor.key_released(0x08); break;
case SDLK_d: processor.key_released(0x09); break;
case SDLK_f: processor.key_released(0x0E); break;
case SDLK_z: processor.key_released(0x0A); break;
case SDLK_x: processor.key_released(0x00); break;
case SDLK_c: processor.key_released(0x0B); break;
case SDLK_v: processor.key_released(0x0F); break;
} break;
case SDL_KEYDOWN:
ch8::addr program_counter;
switch (event.key.keysym.sym) {
case SDLK_1: processor.key_pressed(0x01); break;
case SDLK_2: processor.key_pressed(0x02); break;
case SDLK_3: processor.key_pressed(0x03); break;
case SDLK_4: processor.key_pressed(0x0C); break;
case SDLK_q: processor.key_pressed(0x04); break;
case SDLK_w: processor.key_pressed(0x05); break;
case SDLK_e: processor.key_pressed(0x06); break;
case SDLK_r: processor.key_pressed(0x0D); break;
case SDLK_a: processor.key_pressed(0x07); break;
case SDLK_s: processor.key_pressed(0x08); break;
case SDLK_d: processor.key_pressed(0x09); break;
case SDLK_f: processor.key_pressed(0x0E); break;
case SDLK_z: processor.key_pressed(0x0A); break;
case SDLK_x: processor.key_pressed(0x00); break;
case SDLK_c: processor.key_pressed(0x0B); break;
case SDLK_v: processor.key_pressed(0x0F); break;
case SDLK_ESCAPE: force_exit = true; break;
case SDLK_j:
processor.step(); // Very useful for debugging chip-8 programs :D.
processor.dump(); // Print the current state of the processor at the PC.
program_counter = processor.register_state(ch8::Processor::Register::PC);
print_instruction(memory, program_counter);
std::cout << std::endl;
step_mode = true;
break;
case SDLK_k: step_mode = false; break;
}
default: break;
}
}
current_time = SDL_GetTicks();
// Both timers go at around 60 Hz~~16ms.
if (current_time - interrupt_time >= 16) {
if (processor.sound_issued()) processor.tick_sound();
if (processor.delay_issued()) processor.tick_delay();
interrupt_time = current_time;
}
// Actually emulate the Chip-8 :)
if (!step_mode) processor.step();
if (processor.display_updated()) {
SDL_LockTexture(display_buffer_texture, nullptr,
reinterpret_cast<void**>(&display_buffer),
&display_buffer_width);
for (std::size_t i { 0 }; i < 64 * 32; ++i) {
// Only vary the game screen between black and white for now...
display_buffer[i*4] = 0xFF; // Alpha channel for some reason...
display_buffer[i*4 + 1] = processor.display_buffer()[i] * 0xFF;
display_buffer[i*4 + 2] = processor.display_buffer()[i] * 0xFF;
display_buffer[i*4 + 3] = processor.display_buffer()[i] * 0xFF;
} SDL_UnlockTexture(display_buffer_texture);
SDL_RenderClear(renderer);
// Render the display buffer texture with nearest neighbor scaling.
SDL_RenderCopy(renderer, display_buffer_texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
processor.updated_display();
}
}
// As always, don't forget to free stuff :)
SDL_DestroyTexture(display_buffer_texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
| 43.341837 | 144 | 0.597646 | [
"render"
] |
fa98f58e9dd502582ad0daf776e1fb5489d83c73 | 11,173 | cpp | C++ | Classes/NetWork/Client.cpp | Moonlor/SQLS | 1db5c8a8bc36b9e25b20ba550cff64d448827659 | [
"MIT"
] | 29 | 2017-04-22T07:08:48.000Z | 2022-03-24T03:17:49.000Z | Classes/NetWork/Client.cpp | Moonlor/SQLS | 1db5c8a8bc36b9e25b20ba550cff64d448827659 | [
"MIT"
] | null | null | null | Classes/NetWork/Client.cpp | Moonlor/SQLS | 1db5c8a8bc36b9e25b20ba550cff64d448827659 | [
"MIT"
] | 18 | 2017-04-21T13:01:06.000Z | 2022-03-24T03:17:57.000Z | /*****************************************************************************
* Copyright (C) 2017 李坤 1061152718@qq.com
*
* 此文件属于软件学院2017c++大项目泡泡堂选题的项目文件.
*
* 此项目是开源项目, 在期末答辩之后, 我们可能会在假期里对一些因时间不够未完成的功能进
* 行补充, 以及适配windows平台, 在未来如果技术允许的情况下, 会酌情开发ios版本和anroid
* 版本, 期待您能够为这个开源项目提供宝贵意见, 帮助我们做得更好, 如果能够贡献宝贵的代
* 码那就更令人开心了.
*
* 本项目遵守MIT开源协议, 这也就是说, 您需要遵守的唯一条件就是在修改后的代码或者发行
* 包包含原作者的许可信息. 除非获得原作者的特殊许可, 在任何项目(包括商业项目)里使用
* 本项目的文件都需要包含作者的许可.
*
* 如果对项目有疑问或者其他建议, 欢迎联系13167211978@163.com, 1061152718@qq.com,
* 我们期待能和您互相交流合作, 学习更多的知识.
*
* 另外注意: 此项目需要您自行配置cocos环境,安装boost库, 如果遇到相关问题的话, 欢迎将
* 错误日志发给我们, 您的帮助将有助于改善游戏的体验.
*
* @file client.cpp
* @brief 对建立的client进行操作和管理
*
* @author 李坤
* @email 1061152718@qq.com
* @version 4.0.1.5
* @date 2017/06/02
* @license Massachusetts Institute of Technology License (MIT)
*
*----------------------------------------------------------------------------
* Remark : Description
*----------------------------------------------------------------------------
* Change History :
* <Date> | <Version> | <Author> | <Description>
*----------------------------------------------------------------------------
* 2017/06/02 | 3.0.0.1 | 李坤 | Create file
*----------------------------------------------------------------------------
*
*****************************************************************************/
#include <stdio.h>
#include "Client.h"
#include "MessageCode.h"
int ipindex; ///能正确连接的ip地址在ip列表里的索引
int serverIndex; ///server所在的ip地址在ip列表里的索引
int client_mode; ///当前client的运行模式
std::string ipOut; ///能成功建立连接的ip地址字符串
std::string currentIp; ///当前连接的ip地址字符串
std::vector<std::string> ipList; ///所有连接到该网段的设备的ip地址表
std::vector<std::string> serverIpList; ///能够连接上的, 存在server的ip地址表
static Client* this_client = nullptr; ///指向client对象的指针
/**
* @name MAC平台下的标识码
* @{
*/
#define MAC 1
/** @} */
/**
* @name WINDOWS平台下的标识码
* @{
*/
#define WIN 2
/** @} */
#ifdef _WIN32
int system_type = WIN;
#else
int system_type = MAC;
#endif
void chat_client::handle_connect(const boost::system::error_code& error)
{
if (!error)
{
serverIndex = ipindex;
serverIpList.push_back(ipOut);
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), chat_message::header_length),
boost::bind(&chat_client::handle_read_header, this,
boost::asio::placeholders::error));
}
else{
}
}
void chat_client::handle_write(const boost::system::error_code& error)
{
if (!error)
{
write_msgs_.pop_front();
if (!write_msgs_.empty())
{
boost::asio::async_write(socket_,
boost::asio::buffer(write_msgs_.front().data(),
write_msgs_.front().length()),
boost::bind(&chat_client::handle_write, this,
boost::asio::placeholders::error));
}
}
else
{
do_close();
}
}
void chat_client::handle_read_header(const boost::system::error_code& error)
{
if (!error && read_msg_.decode_header())
{
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
boost::bind(&chat_client::handle_read_body, this,
boost::asio::placeholders::error));
}
else
{
do_close();
}
}
void chat_client::handle_read_body(const boost::system::error_code& error)
{
if (!error)
{
std::string temp1(read_msg_.body());
if(temp1 == ipOut){
serverIndex = ipindex;
// std::cout << ipOut << " succeed \n";
// std::cout << "==========================\n";
}
this_client->t_lock.lock();
std::string temp (read_msg_.body(), read_msg_.body_length());
// std::cout << "client get: " << temp << "==========";
this_client->_orderList.push_back(temp);
this_client->t_lock.unlock();
std::cout.write(read_msg_.body(), read_msg_.body_length());
// std::cout << "\n";
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), chat_message::header_length),
boost::bind(&chat_client::handle_read_header, this,
boost::asio::placeholders::error));
}
else
{
do_close();
}
}
void chat_client::do_write(chat_message msg)
{
bool write_in_progress = !write_msgs_.empty();
write_msgs_.push_back(msg);
if (!write_in_progress)
{
boost::asio::async_write(socket_,
boost::asio::buffer(write_msgs_.front().data(),
write_msgs_.front().length()),
boost::bind(&chat_client::handle_write, this,
boost::asio::placeholders::error));
}
}
int Client::client(void)
{
if (system(NULL)){
puts ("Ok");
}else{
exit (EXIT_FAILURE);
}
if(client_mode == 2)
{
system("ping -c 1 255.255.255.255");
// std::cout << "ping done" << std::endl;
system("arp -a > arp.txt");
// std::cout << "arp done" << std::endl;
std::ifstream in("arp.txt");
if(!in.is_open()){
// std::cout << "Search Error! \n";
}
if(system_type == MAC)
{
while (!in.eof() )
{
std::string temp;
getline (in, temp);
if(in.eof()){
break;
}
int i = temp.find(')');
temp = temp.substr(3,i - 3);
// std::cout << temp << std::endl;
currentIp = temp;
ipList.push_back(temp);
}
}
else
{
bool start_read = false;
while (!in.eof())
{
std::string temp;
getline(in, temp);
if (in.eof()) {
break;
}
if (temp.size() >= 3)
{
if (temp[2] == 'I')
{
start_read = true;
continue;
}
}
if (!start_read) {
continue;
}
int i = temp.find(' ', 3);
temp = temp.substr(2, i - 2);
// std::cout << temp << std::endl;
currentIp = temp;
ipList.push_back(temp);
}
}
}
std::vector<chat_client> cc;
std::vector<boost::thread> t;
for (int i = 0; i < ipList.size() - 1; i++)
{
if(client_mode == 1)
{
break;
}
if(ipList.size() == 0){
return 0;
}
bool if_wrong = false;
int point_count = 0;
for(int j = 0; j < ipList.at(i).size(); j++)
{
if(ipList.at(i).at(j) > '9' || ipList.at(i).at(j) < '0')
{
if(ipList.at(i).at(j) != '.')
{
if_wrong = true;
break;
}
if(ipList.at(i).at(j) == '.')
{
point_count++;
}
}
}
if(point_count != 3 || if_wrong)
{
continue;
}
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(ipList.at(i), "11332");
ipOut = ipList.at(i);
tcp::resolver::iterator iterator = resolver.resolve(query);
chat_client c(io_service, iterator);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
ipindex = i;
usleep(100000);
c.close();
t.join();
}
if(ipList.size() != 0){
// std::cout << ">>>>>>>>" << ipList.at(serverIndex) << ">>>>>>>>>>\n";
}
try
{
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
std::string ip;
if(client_mode == 1)
{
ip = "115.159.90.65";
}
else{
ip = ipList.at(serverIndex);
}
_search_finished = true;
tcp::resolver::query query(ip, "11332");
tcp::resolver::iterator iterator = resolver.resolve(query);
chat_client c(io_service, iterator);
_clientInstance = &c;
this_client = this;
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
char line[chat_message::max_body_length + 1];
while (1)
{
;
}
c.close();
t.join();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
void Client::runClient(int mode)
{
client_mode = mode;
_search_finished = false;
_filter_mode = false;
std::thread t(&Client::client, this);
t.detach();
}
void Client::sendMessage(const std::string & code, const std::string & message)
{
chat_message msg;
std::string temp;
if(_filter_mode == true && code[0] != ANSWER_FOR_ROOM[0])
{
temp.append(sensitive_word.substr(0, 4));
}
temp.append(code);
temp.append(message);
msg.body_length(temp.size());
memcpy(msg.body(), temp.c_str(), msg.body_length());
msg.encode_header();
_clientInstance->write(msg);
}
std::string Client::executeOrder (void)
{
t_lock.lock();
std::string temp;
if(_orderList.size() != 0){
// std::cout << "order list :" << _orderList.front() << std::endl;
temp = _orderList.front();
_orderList.pop_front();
if(_filter_mode == true){
std::string filter_word = temp.substr(0,4);
if(filter_word == sensitive_word.substr(0,4)){
std::string real_order = temp.substr(4, temp.size() - 4);
temp = real_order;
}
else if(temp[0] != QUERY_FOR_ROOM[0])
{
temp = "no";
}
}
}
else{
temp = "no";
}
t_lock.unlock();
return temp;
}
| 27.452088 | 100 | 0.441511 | [
"vector"
] |
fa9be2fc0c3a21edcb3cab5d80d306dbc402b2d3 | 628 | hpp | C++ | math/convolution/or_convolution.hpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | 1 | 2021-12-26T14:17:29.000Z | 2021-12-26T14:17:29.000Z | math/convolution/or_convolution.hpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | 3 | 2020-07-13T06:23:02.000Z | 2022-02-16T08:54:26.000Z | math/convolution/or_convolution.hpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | null | null | null | /**
* @brief 添え字 or での畳み込み
* @docs docs/math/convolution/convolution.md
*/
#pragma once
#include <algorithm>
#include <vector>
#include "fast_zeta_transform.hpp"
#include "fast_mobius_transform.hpp"
template <typename T>
std::vector<T> or_convolution(std::vector<T> a, std::vector<T> b, const T ID = 0) {
int n = std::max(a.size(), b.size());
a.resize(n, ID);
b.resize(n, ID);
std::vector<T> fzt_a = fast_zeta_transform(a, false, ID), fzt_b = fast_zeta_transform(b, false, ID);
n = a.size();
for (int i = 0; i < n; ++i) fzt_a[i] *= fzt_b[i];
return fast_mobius_transform(fzt_a, false);
}
| 28.545455 | 103 | 0.64172 | [
"vector"
] |
b7030c2e2e3fb571c17435d6adcab7ca752df98e | 1,940 | cpp | C++ | src/updater.cpp | takat0m0/practice_word2vec | 7aee413e1aaaf707ec4166c6150af670a764c93f | [
"MIT"
] | 2 | 2017-02-21T06:29:34.000Z | 2018-04-23T13:41:48.000Z | src/updater.cpp | takat0m0/practice_word2vec | 7aee413e1aaaf707ec4166c6150af670a764c93f | [
"MIT"
] | null | null | null | src/updater.cpp | takat0m0/practice_word2vec | 7aee413e1aaaf707ec4166c6150af670a764c93f | [
"MIT"
] | null | null | null | #include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<vector>
#include <typeinfo>
#include "updater.hpp"
#include "DefVector.hpp"
#include "DefScalar.hpp"
#include "functions.hpp"
void Updater::update(const ItemIndex& item1, const ItemIndex& item2){
Dim2Real& v1 = item2vec[item1];
Dim2Real& v2 = item2vec[item2];
Real grad = d_log_sigmoid(v1 * v2);
square_grad[item1] += grad * grad;
square_grad[item2] += grad * grad;
// positive sampling
for(DimIndex d(0); d < dim; ++d){
v1[d] += lr * grad * v2[d]/sqrt(square_grad[item1].get_val());
v2[d] += lr * grad * v1[d]/sqrt(square_grad[item2].get_val());
}
// negative sampling
const Real& real_nss = scalar_type_change<LoopIndex, Real>(ns_size);
for(LoopIndex i(0); i < ns_size; ++i){
const ItemIndex neg_index = get_negative_sampling_index(tree);
Dim2Real& v_neg = item2vec[neg_index];
Real neg_grad = d_log_sigmoid(Real(-1.0) * (v1 * v_neg));
square_grad[item1] += neg_grad * neg_grad;
square_grad[neg_index] += neg_grad * neg_grad;
for(DimIndex d(0); d < dim; ++d){
v1[d] -= lr * neg_grad * v_neg[d]/sqrt(square_grad[item1].get_val())/real_nss;
v_neg[d] -= lr * neg_grad * v1[d]/sqrt(square_grad[neg_index].get_val())/real_nss;
}
}
return;
}
void one_epoch(Updater& updater, std::string file_name){
std::ifstream ifs(file_name);
std::string str;
while(getline(ifs,str)){
std::string token;
std::istringstream stream(str);
std::vector<ItemIndex> target;
while(getline(stream, token, ',')){
target.push_back(ItemIndex(token));
}
updater.update(target[0], target[1]);
}
}
#include <random>
const ItemIndex get_negative_sampling_index(const HuffmanTree& tree){
std::random_device rnd;
std::mt19937 mt(rnd());
std::uniform_real_distribution<double> tmp_rand(0.0, 1.0);
return tree.search(Probability(tmp_rand(mt)));
}
| 26.575342 | 88 | 0.667526 | [
"vector"
] |
b70abe2fbbb836a06aab40cc87a28eac7963af04 | 21,471 | cpp | C++ | VulkanSupport/Source/EditorSystem.cpp | xRiveria/Crescent-Engine | b6512b6a8dab2d27cf542c562ccc28f21bf2345d | [
"Apache-2.0"
] | 2 | 2020-12-18T03:43:07.000Z | 2020-12-23T12:20:00.000Z | VulkanSupport/Source/EditorSystem.cpp | xRiveria/Crescent-Engine | b6512b6a8dab2d27cf542c562ccc28f21bf2345d | [
"Apache-2.0"
] | null | null | null | VulkanSupport/Source/EditorSystem.cpp | xRiveria/Crescent-Engine | b6512b6a8dab2d27cf542c562ccc28f21bf2345d | [
"Apache-2.0"
] | null | null | null | #include "EditorSystem.h"
#include <vulkan/vulkan.h>
#include "Vulkan/VulkanUtilities.h"
/*
To Do: Abstract current Vulkan resource creations to construct Editor resources without explicit doings here.
*/
namespace Crescent
{
static int g_MinimumImageCount = 3;
EditorSystem::EditorSystem(GLFWwindow* window, VkInstance* instance, VkPhysicalDevice* physicalDevice, VkDevice* logicalDevice, VkQueue* graphicsQueue, VkSurfaceKHR* presentationSurface, VkDescriptorPool* descriptorPool, std::shared_ptr<VulkanSwapchain> swapchain, VkFormat swapchainImageFormat) : m_Window(window), m_VulkanInstance(instance), m_PhysicalDevice(physicalDevice), m_LogicalDevice(logicalDevice),
m_GraphicsQueue(graphicsQueue), m_PresentationSurface(presentationSurface), m_DescriptorPool(descriptorPool), m_Swapchain(swapchain), m_SwapchainImageFormat(swapchainImageFormat)
{
//Setup ImGui Context.
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
//io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
io.Fonts->AddFontFromFileTTF("Resources/Fonts/opensans/OpenSans-Bold.ttf", 17.0f);
io.FontDefault = io.Fonts->AddFontFromFileTTF("Resources/Fonts/opensans/OpenSans-Regular.ttf", 17.0f);
(void)io;
//Setup Dear ImGui Style.
ImGui::StyleColorsDark();
//When viewports are enabled, we tweak WindowRounding/WindowBg so Window platforms can look identifical to regular ones.
ImGuiStyle& style = ImGui::GetStyle();
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
//SetEditorDarkThemeColors();
io.FontDefault = io.Fonts->Fonts.back();
//Initialize some ImGui Specific Resources
CreateEditorDescriptorPool();
CreateEditorRenderPass();
/*
VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT allows any command buffer allocated from a pool to be individually reset to the initial state, either by calling
vkResetCommandBuffer, or via the implicit when calling vkBeginCommandBuffer
*/
CreateEditorCommandPool(&m_EditorCommandPool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT);
CreateEditorCommandBuffers();
CreateEditorFramebuffers();
//Setup Platform/Renderer Bindings
ImGui_ImplGlfw_InitForVulkan(window, true);
ImGui_ImplVulkan_InitInfo initializationInfo{};
initializationInfo.Instance = *m_VulkanInstance;
initializationInfo.PhysicalDevice = *m_PhysicalDevice;
initializationInfo.Device = *m_LogicalDevice;
QueueFamilyIndices queueFamilies = QueryQueueFamilySupport(*m_PhysicalDevice, *m_PresentationSurface);
initializationInfo.QueueFamily = queueFamilies.m_GraphicsFamily.value();
initializationInfo.Queue = *m_GraphicsQueue;
initializationInfo.PipelineCache = VK_NULL_HANDLE; //Empty.
initializationInfo.DescriptorPool = m_EditorDescriptorPool;
initializationInfo.Allocator = VK_NULL_HANDLE; //Empty.
initializationInfo.MinImageCount = g_MinimumImageCount;
initializationInfo.ImageCount = g_MinimumImageCount;
initializationInfo.CheckVkResultFn = VK_NULL_HANDLE;
ImGui_ImplVulkan_Init(&initializationInfo, m_EditorRenderPass);
//Upload Fonts
{
VkCommandBuffer commandBuffer = BeginSingleTimeCommands(*m_LogicalDevice, m_EditorCommandPool);
if (ImGui_ImplVulkan_CreateFontsTexture(commandBuffer) != true)
{
throw std::runtime_error("Failed to create Fonts for ImGui.");
}
else
{
std::cout << "Successfully created Fonts for ImGui.\n";
}
EndSingleTimeCommands(commandBuffer, m_EditorCommandPool, *m_LogicalDevice, *m_GraphicsQueue);
ImGui_ImplVulkan_DestroyFontUploadObjects();
}
}
void EditorSystem::ShutdownEditor()
{
CleanupEditorResources();
vkDestroyCommandPool(*m_LogicalDevice, m_EditorCommandPool, nullptr);
vkDestroyRenderPass(*m_LogicalDevice, m_EditorRenderPass, nullptr);
vkDestroyDescriptorPool(*m_LogicalDevice, m_EditorDescriptorPool, nullptr);
ImGui_ImplVulkan_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void EditorSystem::CleanupEditorResources()
{
for (int i = 0; i < m_EditorFramebuffers.size(); i++)
{
vkDestroyFramebuffer(*m_LogicalDevice, m_EditorFramebuffers[i], nullptr);
}
vkFreeCommandBuffers(*m_LogicalDevice, m_EditorCommandPool, static_cast<uint32_t>(m_EditorCommandBuffers.size()), m_EditorCommandBuffers.data());
}
void EditorSystem::RecreateEditorResources()
{
CreateEditorCommandBuffers();
CreateEditorFramebuffers();
}
void EditorSystem::OnUpdate(std::shared_ptr<VulkanTexture> texture)
{
BeginEditorRenderLoop();
//RenderDockingContext();
//1) Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow().
bool showDemoWindow = true;
ImGui::ShowDemoWindow(&showDemoWindow);
//2) Shows a simple window that we create ourselves.
ImGui::Begin("Diagnostics");
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
//ImGui::Image(ImGui_ImplVulkan_AddTexture(*texture->RetrieveTextureSampler(), *texture->RetrieveTextureView(), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL), ImVec2(300, 300));
ImGui::End();
//ImGui::End(); //Docking.
EndEditorRenderLoop();
}
//Allocate command buffers equivalent to the size of the amount of textures in our swapchain.
void EditorSystem::CreateEditorCommandBuffers()
{
m_EditorCommandBuffers.resize(m_Swapchain->m_SwapchainTextures.size());
VkCommandBufferAllocateInfo commandBufferAllocateInfo = {};
commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
commandBufferAllocateInfo.commandPool = m_EditorCommandPool;
commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
commandBufferAllocateInfo.commandBufferCount = static_cast<uint32_t>(m_EditorCommandBuffers.size());
if (vkAllocateCommandBuffers(*m_LogicalDevice, &commandBufferAllocateInfo, m_EditorCommandBuffers.data()) != VK_SUCCESS) {
throw std::runtime_error("Unable to allocate UI command buffers!");
}
}
//Record our ImGui Draw Data into the allocated Command Buffers.
void EditorSystem::RecordEditorCommands(uint32_t bufferIndex)
{
VkCommandBufferBeginInfo bufferBeginInfo = {};
bufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
//Specifies that each recording of the command buffer will only be submitted once, and the buffer is then reset and rerecorded again between each submission.
bufferBeginInfo.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
if (vkBeginCommandBuffer(m_EditorCommandBuffers[bufferIndex], &bufferBeginInfo) != VK_SUCCESS) //Begins recording state.
{
throw std::runtime_error("Unable to begin recording of Editor Command Buffer.\n");
}
VkClearValue clearColor = { 1.0f, 1.0f, 1.0f, 1.0f };
VkRenderPassBeginInfo renderPassBeginInfo = {};
renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassBeginInfo.renderPass = m_EditorRenderPass;
renderPassBeginInfo.framebuffer = m_EditorFramebuffers[bufferIndex];
renderPassBeginInfo.renderArea.extent = m_Swapchain->m_SwapchainExtent;
//No need for depth here as this is simply an overlay UI.
renderPassBeginInfo.clearValueCount = 1;
renderPassBeginInfo.pClearValues = &clearColor;
//VK_SUBPASS_CONTENTS_INLINE pecifies that the contents of the subpass will be recorded inline in the primary command buffer, and secondary command buffers must not be executed within the subpass.
vkCmdBeginRenderPass(m_EditorCommandBuffers[bufferIndex], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
// Grab and record the draw data from ImGui.
ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), m_EditorCommandBuffers[bufferIndex]);
// End and submit render pass
vkCmdEndRenderPass(m_EditorCommandBuffers[bufferIndex]);
if (vkEndCommandBuffer(m_EditorCommandBuffers[bufferIndex]) != VK_SUCCESS) //Ends recording state.
{
throw std::runtime_error("Failed to record Editor Command Buffer.\n");
}
}
void EditorSystem::CreateEditorCommandPool(VkCommandPool* commandPool, VkCommandPoolCreateFlags flags)
{
VkCommandPoolCreateInfo commandPoolCreateInfo = {};
commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
/*
Remember that command buffers are executed by submitting them on one of the device queues, like the graphics or presentation queues. Each command pool can only
allocate command buffers that are submitted on a single type of queue. As we are currently recording commands for drawing, hence we are going with the graphics
queue family.
*/
QueueFamilyIndices queueFamilies = QueryQueueFamilySupport(*m_PhysicalDevice, *m_PresentationSurface);
commandPoolCreateInfo.queueFamilyIndex = queueFamilies.m_GraphicsFamily.value();
commandPoolCreateInfo.flags = flags;
if (vkCreateCommandPool(*m_LogicalDevice, &commandPoolCreateInfo, nullptr, &m_EditorCommandPool) != VK_SUCCESS)
{
throw std::runtime_error("Could not create Editor Command Pool.");
}
}
void EditorSystem::CreateEditorDescriptorPool()
{
VkDescriptorPoolSize poolSizes[] =
{
{ VK_DESCRIPTOR_TYPE_SAMPLER, 1000 },
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 },
{ VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 },
{ VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 }
};
VkDescriptorPoolCreateInfo pool_info = {};
pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
/*
VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT specifies that descriptor sets can return their individual allocations to the pool, i.e. all of vkAllocateDescriptorSets,
vkFreeDescriptorSets and vkResetDescriptorPool are allowed. Otherwise, descriptor sets allocated from the pool must not be individually freed back to the pool, i.e. only
vkAllocateDescriptorSets and vkResetDescriptorPool are allowed.
*/
pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
pool_info.maxSets = 5000 * IM_ARRAYSIZE(poolSizes);
pool_info.poolSizeCount = static_cast<uint32_t>(IM_ARRAYSIZE(poolSizes));
pool_info.pPoolSizes = poolSizes;
if (vkCreateDescriptorPool(*m_LogicalDevice, &pool_info, nullptr, &m_EditorDescriptorPool) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create Editor Descriptor Pool.\n");
}
}
void EditorSystem::CreateEditorFramebuffers()
{
m_EditorFramebuffers.resize(m_Swapchain->m_SwapchainTextures.size());
VkImageView attachment[1]; //Dummy Array.
VkFramebufferCreateInfo framebufferInfo = {};
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferInfo.renderPass = m_EditorRenderPass;
framebufferInfo.attachmentCount = 1;
framebufferInfo.pAttachments = attachment;
framebufferInfo.width = m_Swapchain->m_SwapchainExtent.width;
framebufferInfo.height = m_Swapchain->m_SwapchainExtent.height;
framebufferInfo.layers = 1;
for (uint32_t i = 0; i < m_Swapchain->m_SwapchainTextures.size(); ++i)
{
attachment[0] = *m_Swapchain->m_SwapchainTextures[i]->RetrieveTextureView();
if (vkCreateFramebuffer(*m_LogicalDevice, &framebufferInfo, nullptr, &m_EditorFramebuffers[i]) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create Editor Framebuffer.\n");
}
}
}
void EditorSystem::CreateEditorRenderPass()
{
// Create an attachment description for the render pass.
VkAttachmentDescription attachmentDescription = {};
attachmentDescription.format = m_SwapchainImageFormat;
attachmentDescription.samples = VK_SAMPLE_COUNT_1_BIT;
attachmentDescription.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; //We need our Editor to be drawn on top of our main content. Thus, we preserve the existing data in the attachment.
attachmentDescription.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachmentDescription.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; //We will transition our contents to a presentation layout when the render pass completes.
attachmentDescription.storeOp = VK_ATTACHMENT_STORE_OP_STORE; //Specifies that the rendered contents will be stored in memory to be read later.
attachmentDescription.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachmentDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
//Create a color attachment reference. Every subpass references one or more of the attachments that we've created.
VkAttachmentReference attachmentReference = {};
attachmentReference.attachment = 0;
attachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
// Create a subpass
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &attachmentReference;
/*
Here, we create a subpass dependency to synchronize our main and UI render passes. We want to render the UI after the geometry has been written to the framebuffer.
Thus, we need to configure a subpass dependency as such.
*/
VkSubpassDependency subpassDependency = {};
subpassDependency.srcSubpass = VK_SUBPASS_EXTERNAL; //Refers to the subpass that happens before the render pass.
subpassDependency.dstSubpass = 0; //Refers to our subpass here.
subpassDependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; //Specifies the operations to wait on and the stages in which these operations occur.
subpassDependency.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; //We are waiting for writing to be completed in the color attachment before transition.
subpassDependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; //The operations that should wait on this to be completed are in the color attachment stage.
subpassDependency.dstStageMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; //It involves the writing of the color attachment. This will prevent the transition from happening until its necessary and allowed.
// Finally, we create our editor render pass
VkRenderPassCreateInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = 1;
renderPassInfo.pAttachments = &attachmentDescription;
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 1;
renderPassInfo.pDependencies = &subpassDependency;
if (vkCreateRenderPass(*m_LogicalDevice, &renderPassInfo, nullptr, &m_EditorRenderPass) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create Editor Render Pass.\n");
}
}
void EditorSystem::SetEditorDarkThemeColors()
{
auto& colors = ImGui::GetStyle().Colors;
colors[ImGuiCol_WindowBg] = ImVec4{ 0.1f, 0.105f, 0.11f, 1.0f };
// Headers
colors[ImGuiCol_Header] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f };
colors[ImGuiCol_HeaderHovered] = ImVec4{ 0.3f, 0.305f, 0.31f, 1.0f };
colors[ImGuiCol_HeaderActive] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
// Buttons
colors[ImGuiCol_Button] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f };
colors[ImGuiCol_ButtonHovered] = ImVec4{ 0.3f, 0.305f, 0.31f, 1.0f };
colors[ImGuiCol_ButtonActive] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
// Frame BG
colors[ImGuiCol_FrameBg] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f };
colors[ImGuiCol_FrameBgHovered] = ImVec4{ 0.3f, 0.305f, 0.31f, 1.0f };
colors[ImGuiCol_FrameBgActive] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
// Tabs
colors[ImGuiCol_Tab] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
colors[ImGuiCol_TabHovered] = ImVec4{ 0.38f, 0.3805f, 0.381f, 1.0f };
colors[ImGuiCol_TabActive] = ImVec4{ 0.28f, 0.2805f, 0.281f, 1.0f };
colors[ImGuiCol_TabUnfocused] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
colors[ImGuiCol_TabUnfocusedActive] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f };
// Title
colors[ImGuiCol_TitleBg] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
colors[ImGuiCol_TitleBgActive] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
colors[ImGuiCol_TitleBgCollapsed] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f };
}
void EditorSystem::BeginEditorRenderLoop()
{
ImGui_ImplVulkan_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
void EditorSystem::EndEditorRenderLoop()
{
ImGui::Render();
//ImGuiIO& io = ImGui::GetIO();
//io.DisplaySize = ImVec2(m_Swapchain->m_SwapchainExtent.width, m_Swapchain->m_SwapchainExtent.height); //For default viewport.
/*
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
GLFWwindow* backupCurrentContext = m_Window;
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
glfwMakeContextCurrent(backupCurrentContext);
}
*/
}
void EditorSystem::RenderDockingContext()
{
static bool dockSpaceOpen = true;
static bool opt_fullscreen = true;
static bool opt_padding = false;
static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;
// We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into,
// because it would be confusing to have two docking targets within each others.
ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;
if (opt_fullscreen)
{
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->GetWorkPos());
ImGui::SetNextWindowSize(viewport->GetWorkSize());
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
}
else
{
dockspace_flags &= ~ImGuiDockNodeFlags_PassthruCentralNode;
}
// When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background
// and handle the pass-thru hole, so we ask Begin() to not render a background.
if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
window_flags |= ImGuiWindowFlags_NoBackground;
// Important: note that we proceed even if Begin() returns false (aka window is collapsed).
// This is because we want to keep our DockSpace() active. If a DockSpace() is inactive,
// all active windows docked into it will lose their parent and become undocked.
// We cannot preserve the docking relationship between an active window and an inactive docking, otherwise
// any change of dockspace/settings would lead to windows being stuck in limbo and never being visible.
if (!opt_padding)
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace Demo", &dockSpaceOpen, window_flags);
if (!opt_padding)
ImGui::PopStyleVar();
if (opt_fullscreen)
ImGui::PopStyleVar(2);
// DockSpace
ImGuiIO& io = ImGui::GetIO();
ImGuiStyle& style = ImGui::GetStyle();
float minimumWindowsize = style.WindowMinSize.x;
style.WindowMinSize.x = 250.0f;
if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable)
{
ImGuiID dockspace_id = ImGui::GetID("MyDockSpace");
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);
}
style.WindowMinSize.x = minimumWindowsize;
}
} | 49.132723 | 411 | 0.709748 | [
"geometry",
"render"
] |
b70b9caa88eeaf5ed871ade1bdd3b223e7c1c1f3 | 934 | cpp | C++ | Olympiad Solutions/DMOJ/coci14c4p5.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | Olympiad Solutions/DMOJ/coci14c4p5.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | Olympiad Solutions/DMOJ/coci14c4p5.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | // Ivan Carvalho
// Solution to https://dmoj.ca/problem/coci14c4p5
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2*1e5 + 10;
vector<int> grafo[MAXN];
int cor[MAXN],N;
int calcula_erro(int v){
int total = 0;
for(int u : grafo[v]) total += (cor[v] == cor[u]);
return total;
}
void dfs(int v){
int erros = calcula_erro(v);
if(erros <= 2){
return;
}
cor[v] ^= 1;
for(int u : grafo[v]){
dfs(u);
}
}
int main(){
scanf("%d",&N);
for(int dia = 1;dia<=5;dia++){
int pares;
scanf("%d",&pares);
while(pares--){
int u,v;
scanf("%d %d",&u,&v);
grafo[u].push_back(v);
grafo[v].push_back(u);
}
}
for(int i = 1;i<=N;i++){
sort(grafo[i].begin(),grafo[i].end());
grafo[i].erase(unique(grafo[i].begin(),grafo[i].end()),grafo[i].end());
}
for(int i = 1;i<=N;i++){
dfs(i);
}
for(int i = 1;i<=N;i++){
if(cor[i] == 0) printf("A");
else printf("B");
}
printf("\n");
return 0;
} | 16.103448 | 73 | 0.551392 | [
"vector"
] |
b70ce3463e7c96e0ee797c75f05b47a0c79456c8 | 1,093 | cpp | C++ | Mathematics/counting_divisors.cpp | DannyAntonelli/CSES-Problem-Set | 599b5efb2d7efb9b7e1bfde3142702dc5d0c3988 | [
"MIT"
] | null | null | null | Mathematics/counting_divisors.cpp | DannyAntonelli/CSES-Problem-Set | 599b5efb2d7efb9b7e1bfde3142702dc5d0c3988 | [
"MIT"
] | null | null | null | Mathematics/counting_divisors.cpp | DannyAntonelli/CSES-Problem-Set | 599b5efb2d7efb9b7e1bfde3142702dc5d0c3988 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define RFOR(i, a, b) for (int i = (a); i > (b); --i)
#define ALL(x) x.begin(), x.end()
#define F first
#define S second
#define PB push_back
#define MP make_pair
using namespace std;
using ll = long long;
using ld = long double;
typedef vector<int> vi;
typedef pair<int, int> pi;
void fast_io() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int main() {
fast_io();
int n;
cin >> n;
const int DIM = 1e6 + 1;
vi spf(DIM);
FOR (i, 0, DIM) spf[i] = i;
for (int i = 2; i * i < DIM; ++i) {
if (spf[i] == i) {
for (int j = i * i; j < DIM; j += i) {
if (spf[j] == j) spf[j] = i;
}
}
}
while (n--) {
int x;
cin >> x;
map<int, int> factors;
while (x > 1) {
++factors[spf[x]];
x /= spf[x];
}
ll res = 1;
for (pi p : factors) {
res *= (p.S + 1);
}
cout << res << "\n";
}
return 0;
} | 18.216667 | 53 | 0.431839 | [
"vector"
] |
b7122445cc96a2bcbc1c9ca3d72246e97a998d04 | 2,688 | cpp | C++ | src/core/bus/service_base.cpp | webosce/sam | bddc1e646d729920350f69e44105e02d1c5422d4 | [
"Apache-2.0"
] | null | null | null | src/core/bus/service_base.cpp | webosce/sam | bddc1e646d729920350f69e44105e02d1c5422d4 | [
"Apache-2.0"
] | null | null | null | src/core/bus/service_base.cpp | webosce/sam | bddc1e646d729920350f69e44105e02d1c5422d4 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2012-2018 LG Electronics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#include "core/bus/service_base.h"
#include <glib.h>
#include <luna-service2/lunaservice.h>
#include "core/base/logging.h"
#include "core/base/lsutils.h"
ServiceBase::ServiceBase(const std::string& name) : name_(name), handle_(NULL) {
services_.push_back({name, NULL});
}
ServiceBase::~ServiceBase() {
}
void ServiceBase::AddCompatibleNames(const std::vector<std::string>& names) {
for (const auto& n : names) {
services_.push_back({n, NULL});
}
}
bool ServiceBase::Attach(GMainLoop * gml) {
bool first_handle = true;
for (auto& it : services_) {
LSErrorSafe lse;
const std::string& name = it.first;
if (!LSRegister(name.c_str(), &(it.second), &lse)) {
LOG_ERROR(MSGID_SRVC_REGISTER_FAIL, 1, PMLOGKS("service", name.c_str()), "err: %s", lse.message);
return false;
}
std::vector<std::string> categories;
get_categories(categories);
for (const auto& category : categories) {
if (!LSRegisterCategory(it.second, category.c_str(), get_methods(category), NULL, NULL, &lse)) {
LOG_ERROR(MSGID_SRVC_CATEGORY_FAIL, 1, PMLOGKS("service", name.c_str()), "err: %s", lse.message);
return false;
}
if (!LSCategorySetData(it.second, category.c_str(), this, &lse)) {
LOG_ERROR(MSGID_SRVC_CATEGORY_FAIL, 1, PMLOGKS("service", name.c_str()), "err: %s", lse.message);
return false;
}
}
if (!LSGmainAttach(it.second, gml, &lse)) {
LOG_ERROR(MSGID_SRVC_ATTACH_FAIL, 1, PMLOGKS("service", name.c_str()), "err: %s", lse.message);
return false;
}
if (first_handle) {
handle_ = it.second;
first_handle = false;
}
}
return true;
}
void ServiceBase::Detach() {
for (auto& it : services_) {
LSErrorSafe lse;
if (!LSUnregister(it.second, &lse)) {
LOG_WARNING(MSGID_SRVC_DETACH_FAIL, 1, PMLOGKS("service", it.first.c_str()), "err: %s", lse.message);
return;
}
it.second = NULL;
}
handle_ = NULL;
}
bool ServiceBase::IsAttached() {
return (NULL != handle_);
}
| 27.71134 | 107 | 0.662574 | [
"vector"
] |
b7259750c9c0b2a7330cb71ac5716f9149499cfa | 927 | cpp | C++ | Cpp/695.max-area-of-island.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | 1 | 2015-12-19T23:05:35.000Z | 2015-12-19T23:05:35.000Z | Cpp/695.max-area-of-island.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | null | null | null | Cpp/695.max-area-of-island.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | null | null | null | class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
if (grid.empty() || grid[0].empty()) return 0;
int m = grid.size(), n = grid[0].size();
vector<vector<bool>> visited(m, vector<bool>(n, false));
int res = 0;
for (int i = 0; i < m; ++ i) {
for (int j = 0; j < n; ++ j) {
res = std::max(res, getArea(grid, visited, i, j));
}
}
return res;
}
int getArea(vector<vector<int>> &grid, vector<vector<bool>> &visited, int i, int j) {
if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || visited[i][j] || grid[i][j] == 0) return 0;
visited[i][j] = true;
return 1 + getArea(grid, visited, i-1, j)
+ getArea(grid, visited, i+1, j)
+ getArea(grid, visited, i, j-1)
+ getArea(grid, visited, i, j+1);
}
}; | 37.08 | 116 | 0.461704 | [
"vector"
] |
b728215e40aa250477b8fd09daf8f854c574f093 | 3,737 | cpp | C++ | libs/core/algorithms/tests/unit/algorithms/findifnot.cpp | bhumitattarde/hpx | 5b34d8d77b1664fa552445d44cd98e51dc69a74a | [
"BSL-1.0"
] | 1 | 2022-02-08T05:55:09.000Z | 2022-02-08T05:55:09.000Z | libs/core/algorithms/tests/unit/algorithms/findifnot.cpp | deepaksuresh1411/hpx | aa18024d35fe9884a977d4b6076c764dbb8b26d1 | [
"BSL-1.0"
] | null | null | null | libs/core/algorithms/tests/unit/algorithms/findifnot.cpp | deepaksuresh1411/hpx | aa18024d35fe9884a977d4b6076c764dbb8b26d1 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2021 Srinivas Yadav
// copyright (c) 2014 Grant Mercer
//
// SPDX-License-Identifier: BSL-1.0
// 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 <hpx/local/init.hpp>
#include <iostream>
#include <string>
#include <vector>
#include "findifnot_tests.hpp"
//////////////////////////////////////////////////////////////////////////////
template <typename IteratorTag>
void test_find_if_not()
{
using namespace hpx::execution;
test_find_if_not(IteratorTag());
test_find_if_not(seq, IteratorTag());
test_find_if_not(par, IteratorTag());
test_find_if_not(par_unseq, IteratorTag());
test_find_if_not_async(seq(task), IteratorTag());
test_find_if_not_async(par(task), IteratorTag());
}
void find_if_not_test()
{
test_find_if_not<std::random_access_iterator_tag>();
test_find_if_not<std::forward_iterator_tag>();
}
//////////////////////////////////////////////////////////////////////////////
template <typename IteratorTag>
void test_find_if_not_exception()
{
using namespace hpx::execution;
test_find_if_not_exception(IteratorTag());
// If the execution policy object is of type vector_execution_policy,
// std::terminate shall be called. therefore we do not test exceptions
// with a vector execution policy
test_find_if_not_exception(seq, IteratorTag());
test_find_if_not_exception(par, IteratorTag());
test_find_if_not_exception_async(seq(task), IteratorTag());
test_find_if_not_exception_async(par(task), IteratorTag());
}
void find_if_not_exception_test()
{
test_find_if_not_exception<std::random_access_iterator_tag>();
test_find_if_not_exception<std::forward_iterator_tag>();
}
//////////////////////////////////////////////////////////////////////////////
template <typename IteratorTag>
void test_find_if_not_bad_alloc()
{
using namespace hpx::execution;
// If the execution policy object is of type vector_execution_policy,
// std::terminate shall be called. therefore we do not test exceptions
// with a vector execution policy
test_find_if_not_bad_alloc(seq, IteratorTag());
test_find_if_not_bad_alloc(par, IteratorTag());
test_find_if_not_bad_alloc_async(seq(task), IteratorTag());
test_find_if_not_bad_alloc_async(par(task), IteratorTag());
}
void find_if_not_bad_alloc_test()
{
test_find_if_not_bad_alloc<std::random_access_iterator_tag>();
test_find_if_not_bad_alloc<std::forward_iterator_tag>();
}
int hpx_main(hpx::program_options::variables_map& vm)
{
if (vm.count("seed"))
seed = vm["seed"].as<unsigned int>();
std::cout << "using seed: " << seed << std::endl;
gen.seed(seed);
find_if_not_test();
find_if_not_exception_test();
find_if_not_bad_alloc_test();
return hpx::local::finalize();
}
int main(int argc, char* argv[])
{
// add command line option which controls the random number generator seed
using namespace hpx::program_options;
options_description desc_commandline(
"Usage: " HPX_APPLICATION_STRING " [options]");
desc_commandline.add_options()("seed,s", value<unsigned int>(),
"the random number generator seed to use for this run");
// By default this test should run on all available cores
std::vector<std::string> const cfg = {"hpx.os_threads=all"};
// Initialize and run HPX
hpx::local::init_params init_args;
init_args.desc_cmdline = desc_commandline;
init_args.cfg = cfg;
HPX_TEST_EQ_MSG(hpx::local::init(hpx_main, argc, argv, init_args), 0,
"HPX main exited with non-zero status");
return hpx::util::report_errors();
}
| 30.884298 | 80 | 0.682098 | [
"object",
"vector"
] |
b72e9d1b70608acf00668254a882f46db33a2c29 | 584 | cpp | C++ | CodingInterviews/cpp/61_find_nums_appear_once.cpp | YorkFish/git_study | 6e023244daaa22e12b24e632e76a13e5066f2947 | [
"MIT"
] | null | null | null | CodingInterviews/cpp/61_find_nums_appear_once.cpp | YorkFish/git_study | 6e023244daaa22e12b24e632e76a13e5066f2947 | [
"MIT"
] | null | null | null | CodingInterviews/cpp/61_find_nums_appear_once.cpp | YorkFish/git_study | 6e023244daaa22e12b24e632e76a13e5066f2947 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> findNumsAppearOnce(vector<int>& nums) {
int all_xor = 0;
for (int num : nums) all_xor ^= num;
int low_bit = -all_xor & all_xor;
int first = 0;
for (int num : nums) if (num & low_bit) first ^= num;
return vector<int> {first, all_xor ^ first};
}
};
int main() {
vector<int> nums{1, 2, 3, 3, 4, 4};
Solution s;
vector<int> ans = s.findNumsAppearOnce(nums);
cout << ans[0] << ' ' << ans[1] << endl;
return 0;
}
| 21.62963 | 61 | 0.563356 | [
"vector"
] |
b732a998bff6d0d8231ba2c8d4b952ac256d9afd | 8,005 | cpp | C++ | src/alt.cpp | edvardsp/libproxc- | aea543d7de50a26fb424485a9eed458004f57510 | [
"BSL-1.0"
] | 1 | 2022-03-10T16:25:29.000Z | 2022-03-10T16:25:29.000Z | src/alt.cpp | edvardsp/libproxc- | aea543d7de50a26fb424485a9eed458004f57510 | [
"BSL-1.0"
] | null | null | null | src/alt.cpp | edvardsp/libproxc- | aea543d7de50a26fb424485a9eed458004f57510 | [
"BSL-1.0"
] | null | null | null | // Copyright Edvard Severin Pettersen 2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at
// https://www.boost.org/LICENSE_1_0.txt)
#include <deque>
#include <memory>
#include <random>
#include <vector>
#include <proxc/config.hpp>
#include <proxc/runtime/scheduler.hpp>
#include <proxc/alt.hpp>
#include <proxc/alt/sync.hpp>
#include <proxc/alt/choice_base.hpp>
PROXC_NAMESPACE_BEGIN
////////////////////////////////////////////////////////////////////////////////
// Alt impl
////////////////////////////////////////////////////////////////////////////////
Alt::Alt()
: ctx_{ runtime::Scheduler::running() }
{
choices_.reserve( 8 );
select_flag_.clear( std::memory_order_relaxed );
}
void Alt::select()
{
std::vector< ChoiceT * > choices;
for ( const auto& kv : ch_audit_ ) {
auto& audit = kv.second;
if ( audit.state_ != ChoiceAudit::State::Clash ) {
static thread_local std::minstd_rand rng{ std::random_device{}() };
auto size = audit.vec_.size();
auto ind = ( size > 1 )
? std::uniform_int_distribution< std::size_t >{ 0, size-1 }( rng )
: 0 ;
choices.push_back( audit.vec_[ ind ] );
}
}
Winner winner;
bool skip = has_skip_.load( std::memory_order_relaxed );
std::size_t size = choices.size();
if ( size == 0 ) { winner = select_0( skip ); }
else if ( size == 1 ) { winner = select_1( skip, *choices.begin() ); }
else { winner = select_n( skip, choices ); }
switch ( winner ) {
case Winner::Choice: {
auto selected = selected_.exchange( nullptr, std::memory_order_acq_rel );
BOOST_ASSERT( selected != nullptr );
selected->run_func();
break;
} case Winner::Timeout: {
BOOST_ASSERT( time_point_ < TimePointT::max() );
if ( timer_fn_ ) { timer_fn_(); }
break;
} case Winner::Skip: {
if ( skip_fn_ ) { skip_fn_(); }
break;
}}
}
Alt & Alt::skip( SkipFn fn ) noexcept
{
if ( ! has_skip_.exchange( true, std::memory_order_relaxed ) ) {
skip_fn_ = std::move( fn );
}
return *this;
}
Alt & Alt::skip_if( bool guard, SkipFn fn ) noexcept
{
return ( guard )
? skip( std::move( fn ) )
: *this ;
}
auto Alt::select_0( bool skip )
-> Winner
{
if ( skip ) {
return Winner::Skip;
} else if ( time_point_ < TimePointT::max() ) {
runtime::Scheduler::self()->wait_until( time_point_ );
return Winner::Timeout;
} else {
// suspend indefinitely, should never return
runtime::Scheduler::self()->wait();
BOOST_ASSERT_MSG( false, "unreachable" );
throw UnreachableError{};
}
}
auto Alt::select_1( bool skip, ChoiceT * choice ) noexcept
-> Winner
{
std::unique_lock< LockT > lk{ splk_ };
choice->enter();
while ( choice->is_ready() ) {
switch ( choice->try_complete() ) {
case ChoiceT::Result::TryLater:
continue;
case ChoiceT::Result::Ok:
select_flag_.test_and_set( std::memory_order_relaxed );
selected_.store( choice, std::memory_order_release );
/* [[fallthrough]]; */
case ChoiceT::Result::Failed:
break;
}
break;
}
bool timeout = false;
if ( selected_.load( std::memory_order_acquire ) == nullptr ) {
// choice is not ready
if ( skip ) {
return Winner::Skip;
}
state_.store( alt::State::Waiting, std::memory_order_release );
timeout = runtime::Scheduler::self()->alt_wait( this, lk );
state_.store( alt::State::Done, std::memory_order_release );
} else {
// choice is ready
state_.store( alt::State::Done, std::memory_order_release );
lk.unlock();
}
choice->leave();
return ( timeout )
? Winner::Timeout
: Winner::Choice ;
}
auto Alt::select_n( bool skip, std::vector< ChoiceT * > & choices ) noexcept
-> Winner
{
std::unique_lock< LockT > lk{ splk_ };
for ( const auto& choice : choices ) {
choice->enter();
}
while ( selected_.load( std::memory_order_acquire ) == nullptr ) {
std::vector< ChoiceT * > ready;
for ( const auto& choice : choices ) {
if ( choice->is_ready() ) {
ready.push_back( choice );
}
}
const auto size = ready.size();
if ( size == 0 ) {
break;
}
if ( size > 1 ) {
static thread_local std::minstd_rand rng{ std::random_device{}() };
std::shuffle( ready.begin(), ready.end(), rng );
}
for ( const auto& choice : ready ) {
auto res = choice->try_complete();
if ( res == ChoiceT::Result::Ok ) {
select_flag_.test_and_set( std::memory_order_relaxed );
selected_.store( choice, std::memory_order_relaxed );
break;
}
}
}
bool timeout = false;
if ( selected_.load( std::memory_order_relaxed ) == nullptr ) {
// no choices were ready
if ( skip ) {
return Winner::Skip;
}
state_.store( alt::State::Waiting, std::memory_order_release );
timeout = runtime::Scheduler::self()->alt_wait( this, lk );
// one or more choices should be ready,
// and selected_ should be set. If set,
// this is the winning choice.
state_.store( alt::State::Done, std::memory_order_release );
} else {
// a choice was ready
state_.store( alt::State::Done, std::memory_order_release );
lk.unlock();
}
for ( const auto& choice : choices ) {
choice->leave();
}
return ( timeout )
? Winner::Timeout
: Winner::Choice ;
}
// called by external non-alting choices
bool Alt::try_select( ChoiceT * choice ) noexcept
{
std::unique_lock< LockT > lk{ splk_ };
if ( select_flag_.test_and_set( std::memory_order_acq_rel ) ) {
return false;
}
selected_.store( choice, std::memory_order_release );
return true;
}
// called by external alting choices
bool Alt::try_alt_select( ChoiceT * choice ) noexcept
{
BOOST_ASSERT( choice != nullptr );
std::unique_lock< LockT > lk{ splk_ };
if ( select_flag_.test_and_set( std::memory_order_acq_rel ) ) {
return false;
}
selected_.store( choice, std::memory_order_release );
return true;
}
bool Alt::try_timeout() noexcept
{
// FIXME: necessary with spinlock? This is called by
// Scheduler, which means the Alting process is already
// waiting. spinlocking on try_select() is used to force
// ready choices to wait for the alting process to go to
// wait before trying to set selected_.
std::unique_lock< LockT > lk{ splk_ };
return ! select_flag_.test_and_set( std::memory_order_acq_rel );
}
namespace alt {
////////////////////////////////////////////////////////////////////////////////
// ChoiceBase impl
////////////////////////////////////////////////////////////////////////////////
ChoiceBase::ChoiceBase( Alt * alt ) noexcept
: alt_{ alt }
{}
bool ChoiceBase::same_alt( Alt * alt ) const noexcept
{
return alt == alt_;
}
bool ChoiceBase::try_select() noexcept
{
return alt_->try_select( this );
}
bool ChoiceBase::try_alt_select() noexcept
{
return alt_->try_alt_select( this );
}
alt::State ChoiceBase::get_state() const noexcept
{
return alt_->state_.load( std::memory_order_acquire );
}
bool ChoiceBase::operator < ( ChoiceBase const & other ) const noexcept
{
return ( alt_->tp_start_ < other.alt_->tp_start_ )
? true
: ( alt_->tp_start_ > other.alt_->tp_start_ )
? false
: ( alt_ < other.alt_ ) ;
}
} // namespace alt
PROXC_NAMESPACE_END
| 27.135593 | 82 | 0.559026 | [
"vector"
] |
b73413fb90bb9e0b3f51fd094ea0c3b46011ac52 | 43,370 | cpp | C++ | Total Control/meshingalgs.cpp | legalian/tbd-game | 6b4a2e6109ebbc7d561da3b1953dbd308342b746 | [
"MIT"
] | null | null | null | Total Control/meshingalgs.cpp | legalian/tbd-game | 6b4a2e6109ebbc7d561da3b1953dbd308342b746 | [
"MIT"
] | null | null | null | Total Control/meshingalgs.cpp | legalian/tbd-game | 6b4a2e6109ebbc7d561da3b1953dbd308342b746 | [
"MIT"
] | null | null | null | ////
//// meshingalgs.cpp
//// Total Control
////
//// Created by Parker Lawrence on 8/23/15.
//// Copyright (c) 2015 Parker Lawrence. All rights reserved.
////
//
//#include "meshingalgs.h"
//
//
////
//// Marching Cubes Example Program
//// by Cory Bloyd (corysama@yahoo.com)
////
//// A simple, portable and complete implementation of the Marching Cubes
//// and Marching Tetrahedrons algorithms in a single source file.
//// There are many ways that this code could be made faster, but the
//// intent is for the code to be easy to understand.
////
//// For a description of the algorithm go to
//// http://astronomy.swin.edu.au/pbourke/modelling/polygonise/
////
//// This code is public domain.
////
//
//#include "stdio.h"
//#include "math.h"
////This program requires the OpenGL and GLUT libraries
//// You can obtain them for free from http://www.opengl.org
//
//
//#include </usr/include/GL/glew.h>
//
//#include <GLFW/glfw3.h>
//
//
//struct GLvector
//{
// GLfloat fX;
// GLfloat fY;
// GLfloat fZ;
//};
//
////These tables are used so that everything can be done in little loops that you can look at all at once
//// rather than in pages and pages of unrolled code.
//
////a2fVertexOffset lists the positions, relative to vertex0, of each of the 8 vertices of a cube
//static const int a2fVertexOffset[8][3] =
//{
// {0, 0, 0},{1, 0, 0},{1, 1, 0},{0, 1, 0},
// {0, 0, 1},{1, 0, 1},{1, 1, 1},{0, 1, 1}
//};
//
////a2iEdgeConnection lists the index of the endpoint vertices for each of the 12 edges of the cube
//static const GLint a2iEdgeConnection[12][2] =
//{
// {0,1}, {1,2}, {2,3}, {3,0},
// {4,5}, {5,6}, {6,7}, {7,4},
// {0,4}, {1,5}, {2,6}, {3,7}
//};
//
////a2fEdgeDirection lists the direction vector (vertex1-vertex0) for each edge in the cube
//static const GLfloat a2fEdgeDirection[12][3] =
//{
// {1.0, 0.0, 0.0},{0.0, 1.0, 0.0},{-1.0, 0.0, 0.0},{0.0, -1.0, 0.0},
// {1.0, 0.0, 0.0},{0.0, 1.0, 0.0},{-1.0, 0.0, 0.0},{0.0, -1.0, 0.0},
// {0.0, 0.0, 1.0},{0.0, 0.0, 1.0},{ 0.0, 0.0, 1.0},{0.0, 0.0, 1.0}
//};
//
////a2iTetrahedronEdgeConnection lists the index of the endpoint vertices for each of the 6 edges of the tetrahedron
//static const GLint a2iTetrahedronEdgeConnection[6][2] =
//{
// {0,1}, {1,2}, {2,0}, {0,3}, {1,3}, {2,3}
//};
//
////a2iTetrahedronEdgeConnection lists the index of verticies from a cube
//// that made up each of the six tetrahedrons within the cube
//static const GLint a2iTetrahedronsInACube[6][4] =
//{
// {0,5,1,6},
// {0,1,2,6},
// {0,2,3,6},
// {0,3,7,6},
// {0,7,4,6},
// {0,4,5,6},
//};
//
//
//GLenum ePolygonMode = GL_FILL;
//GLint iDataSetSize = 16;
//GLfloat fStepSize = 1.0/iDataSetSize;
//GLfloat fTargetValue = 48.0;
//GLfloat fTime = 0.0;
//GLvector sSourcePoint[3];
//GLboolean bSpin = true;
//GLboolean bMove = true;
//GLboolean bLight = true;
//
//
//void vIdle();
//void vDrawScene();
//void vResize(GLsizei, GLsizei);
//void vKeyboard(unsigned char cKey, int iX, int iY);
//void vSpecial(int iKey, int iX, int iY);
//
//GLvoid vPrintHelp();
//GLvoid vSetTime(GLfloat fTime);
////GLfloat fSample1(GLfloat fX, GLfloat fY, GLfloat fZ);
////GLfloat fSample2(GLfloat fX, GLfloat fY, GLfloat fZ);
////GLfloat fSample3(GLfloat fX, GLfloat fY, GLfloat fZ);
////GLfloat (*fSample)(GLfloat fX, GLfloat fY, GLfloat fZ) = fSample1;
//
//GLvoid vMarchingCubes();
//GLvoid vMarchCube1(GLfloat fX, GLfloat fY, GLfloat fZ, GLfloat fScale);
//GLvoid vMarchCube2(GLfloat fX, GLfloat fY, GLfloat fZ, GLfloat fScale);
//GLvoid (*vMarchCube)(GLfloat fX, GLfloat fY, GLfloat fZ, GLfloat fScale) = vMarchCube1;
////
////void main(int argc, char **argv)
////{
//// GLfloat afPropertiesAmbient [] = {0.50, 0.50, 0.50, 1.00};
//// GLfloat afPropertiesDiffuse [] = {0.75, 0.75, 0.75, 1.00};
//// GLfloat afPropertiesSpecular[] = {1.00, 1.00, 1.00, 1.00};
////
//// GLsizei iWidth = 640.0;
//// GLsizei iHeight = 480.0;
////
//// glutInit(&argc, argv);
//// glutInitWindowPosition( 0, 0);
//// glutInitWindowSize(iWidth, iHeight);
//// glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
//// glutCreateWindow( "Marching Cubes" );
//// glutDisplayFunc( vDrawScene );
//// glutIdleFunc( vIdle );
//// glutReshapeFunc( vResize );
//// glutKeyboardFunc( vKeyboard );
//// glutSpecialFunc( vSpecial );
////
//// glClearColor( 0.0, 0.0, 0.0, 1.0 );
//// glClearDepth( 1.0 );
////
//// glEnable(GL_DEPTH_TEST);
//// glEnable(GL_LIGHTING);
//// glPolygonMode(GL_FRONT_AND_BACK, ePolygonMode);
////
//// glLightfv( GL_LIGHT0, GL_AMBIENT, afPropertiesAmbient);
//// glLightfv( GL_LIGHT0, GL_DIFFUSE, afPropertiesDiffuse);
//// glLightfv( GL_LIGHT0, GL_SPECULAR, afPropertiesSpecular);
//// glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, 1.0);
////
//// glEnable( GL_LIGHT0 );
////
//// glMaterialfv(GL_BACK, GL_AMBIENT, afAmbientGreen);
//// glMaterialfv(GL_BACK, GL_DIFFUSE, afDiffuseGreen);
//// glMaterialfv(GL_FRONT, GL_AMBIENT, afAmbientBlue);
//// glMaterialfv(GL_FRONT, GL_DIFFUSE, afDiffuseBlue);
//// glMaterialfv(GL_FRONT, GL_SPECULAR, afSpecularWhite);
//// glMaterialf( GL_FRONT, GL_SHININESS, 25.0);
////
//// vResize(iWidth, iHeight);
////
//// vPrintHelp();
//// glutMainLoop();
////}
//
////GLvoid vPrintHelp()
////{
//// printf("Marching Cubes Example by Cory Bloyd (dejaspaminacan@my-deja.com)\n\n");
////
//// printf("+/- increase/decrease sample density\n");
//// printf("PageUp/PageDown increase/decrease surface value\n");
//// printf("s change sample function\n");
//// printf("c toggle marching cubes / marching tetrahedrons\n");
//// printf("w wireframe on/off\n");
//// printf("l toggle lighting / color-by-normal\n");
//// printf("Home spin scene on/off\n");
//// printf("End source point animation on/off\n");
////}
//
////
////void vResize( GLsizei iWidth, GLsizei iHeight )
////{
//// GLfloat fAspect, fHalfWorldSize = (1.4142135623730950488016887242097/2);
////
//// glViewport( 0, 0, iWidth, iHeight );
//// glMatrixMode (GL_PROJECTION);
//// glLoadIdentity ();
////
//// if(iWidth <= iHeight)
//// {
//// fAspect = (GLfloat)iHeight / (GLfloat)iWidth;
//// glOrtho(-fHalfWorldSize, fHalfWorldSize, -fHalfWorldSize*fAspect,
//// fHalfWorldSize*fAspect, -10*fHalfWorldSize, 10*fHalfWorldSize);
//// }
//// else
//// {
//// fAspect = (GLfloat)iWidth / (GLfloat)iHeight;
//// glOrtho(-fHalfWorldSize*fAspect, fHalfWorldSize*fAspect, -fHalfWorldSize,
//// fHalfWorldSize, -10*fHalfWorldSize, 10*fHalfWorldSize);
//// }
////
//// glMatrixMode( GL_MODELVIEW );
////}
//
////void vKeyboard(unsigned char cKey, int iX, int iY)
////{
//// switch(cKey)
//// {
//// case 'w' :
//// {
//// if(ePolygonMode == GL_LINE)
//// {
//// ePolygonMode = GL_FILL;
//// }
//// else
//// {
//// ePolygonMode = GL_LINE;
//// }
//// glPolygonMode(GL_FRONT_AND_BACK, ePolygonMode);
//// } break;
//// case '+' :
//// case '=' :
//// {
//// ++iDataSetSize;
//// fStepSize = 1.0/iDataSetSize;
//// } break;
//// case '-' :
//// {
//// if(iDataSetSize > 1)
//// {
//// --iDataSetSize;
//// fStepSize = 1.0/iDataSetSize;
//// }
//// } break;
//// case 'c' :
//// {
//// if(vMarchCube == vMarchCube1)
//// {
//// vMarchCube = vMarchCube2;//Use Marching Tetrahedrons
//// }
//// else
//// {
//// vMarchCube = vMarchCube1;//Use Marching Cubes
//// }
//// } break;
//// case 's' :
//// {
//// if(fSample == fSample1)
//// {
//// fSample = fSample2;
//// }
//// else if(fSample == fSample2)
//// {
//// fSample = fSample3;
//// }
//// else
//// {
//// fSample = fSample1;
//// }
//// } break;
//// case 'l' :
//// {
//// if(bLight)
//// {
//// glDisable(GL_LIGHTING);//use vertex colors
//// }
//// else
//// {
//// glEnable(GL_LIGHTING);//use lit material color
//// }
////
//// bLight = !bLight;
//// };
//// }
////}
//
////
////void vSpecial(int iKey, int iX, int iY)
////{
//// switch(iKey)
//// {
//// case GLUT_KEY_PAGE_UP :
//// {
//// if(fTargetValue < 1000.0)
//// {
//// fTargetValue *= 1.1;
//// }
//// } break;
//// case GLUT_KEY_PAGE_DOWN :
//// {
//// if(fTargetValue > 1.0)
//// {
//// fTargetValue /= 1.1;
//// }
//// } break;
//// case GLUT_KEY_HOME :
//// {
//// bSpin = !bSpin;
//// } break;
//// case GLUT_KEY_END :
//// {
//// bMove = !bMove;
//// } break;
//// }
////}
//
////void vIdle()
////{
//// glutPostRedisplay();
////}
//
////void vDrawScene()
////{
//// static GLfloat fPitch = 0.0;
//// static GLfloat fYaw = 0.0;
//// static GLfloat fTime = 0.0;
////
//// glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
////
//// glPushMatrix();
////
//// if(bSpin)
//// {
//// fPitch += 4.0;
//// fYaw += 2.5;
//// }
//// if(bMove)
//// {
//// fTime += 0.025;
//// }
////
//// vSetTime(fTime);
////
//// glTranslatef(0.0, 0.0, -1.0);
//// glRotatef( -fPitch, 1.0, 0.0, 0.0);
//// glRotatef( 0.0, 0.0, 1.0, 0.0);
//// glRotatef( fYaw, 0.0, 0.0, 1.0);
////
//// glPushAttrib(GL_LIGHTING_BIT);
//// glDisable(GL_LIGHTING);
//// glColor3f(1.0, 1.0, 1.0);
//// glutWireCube(1.0);
//// glPopAttrib();
////
////
//// glPushMatrix();
//// glTranslatef(-0.5, -0.5, -0.5);
//// glBegin(GL_TRIANGLES);
//// vMarchingCubes();
//// glEnd();
//// glPopMatrix();
////
////
//// glPopMatrix();
////
//// glutSwapBuffers();
////}
//
////fGetOffset finds the approximate point of intersection of the surface
//// between two points with the values fValue1 and fValue2
//GLfloat fGetOffset(GLfloat fValue1, GLfloat fValue2, GLfloat fValueDesired)
//{
// GLdouble fDelta = fValue2 - fValue1;
//
// if(fDelta == 0.0)
// {
// return 0.5;
// }
// return (fValueDesired - fValue1)/fDelta;
//}
//
//
////vGetColor generates a color from a given position and normal of a point
//GLvoid vGetColor(GLvector &rfColor, GLvector &rfPosition, GLvector &rfNormal)
//{
// GLfloat fX = rfNormal.fX;
// GLfloat fY = rfNormal.fY;
// GLfloat fZ = rfNormal.fZ;
// rfColor.fX = (fX > 0.0 ? fX : 0.0) + (fY < 0.0 ? -0.5*fY : 0.0) + (fZ < 0.0 ? -0.5*fZ : 0.0);
// rfColor.fY = (fY > 0.0 ? fY : 0.0) + (fZ < 0.0 ? -0.5*fZ : 0.0) + (fX < 0.0 ? -0.5*fX : 0.0);
// rfColor.fZ = (fZ > 0.0 ? fZ : 0.0) + (fX < 0.0 ? -0.5*fX : 0.0) + (fY < 0.0 ? -0.5*fY : 0.0);
//}
//
//GLvoid vNormalizeVector(GLvector &rfVectorResult, GLvector &rfVectorSource)
//{
// GLfloat fOldLength;
// GLfloat fScale;
//
// fOldLength = sqrtf( (rfVectorSource.fX * rfVectorSource.fX) +
// (rfVectorSource.fY * rfVectorSource.fY) +
// (rfVectorSource.fZ * rfVectorSource.fZ) );
//
// if(fOldLength == 0.0)
// {
// rfVectorResult.fX = rfVectorSource.fX;
// rfVectorResult.fY = rfVectorSource.fY;
// rfVectorResult.fZ = rfVectorSource.fZ;
// }
// else
// {
// fScale = 1.0/fOldLength;
// rfVectorResult.fX = rfVectorSource.fX*fScale;
// rfVectorResult.fY = rfVectorSource.fY*fScale;
// rfVectorResult.fZ = rfVectorSource.fZ*fScale;
// }
//}
//
////
//////Generate a sample data set. fSample1(), fSample2() and fSample3() define three scalar fields whose
////// values vary by the X,Y and Z coordinates and by the fTime value set by vSetTime()
////GLvoid vSetTime(GLfloat fNewTime)
////{
//// GLfloat fOffset;
//// GLint iSourceNum;
////
//// for(iSourceNum = 0; iSourceNum < 3; iSourceNum++)
//// {
//// sSourcePoint[iSourceNum].fX = 0.5;
//// sSourcePoint[iSourceNum].fY = 0.5;
//// sSourcePoint[iSourceNum].fZ = 0.5;
//// }
////
//// fTime = fNewTime;
//// fOffset = 1.0 + sinf(fTime);
//// sSourcePoint[0].fX *= fOffset;
//// sSourcePoint[1].fY *= fOffset;
//// sSourcePoint[2].fZ *= fOffset;
////}
////
//////fSample1 finds the distance of (fX, fY, fZ) from three moving points
////GLfloat fSample1(GLfloat fX, GLfloat fY, GLfloat fZ)
////{
//// GLdouble fResult = 0.0;
//// GLdouble fDx, fDy, fDz;
//// fDx = fX - sSourcePoint[0].fX;
//// fDy = fY - sSourcePoint[0].fY;
//// fDz = fZ - sSourcePoint[0].fZ;
//// fResult += 0.5/(fDx*fDx + fDy*fDy + fDz*fDz);
////
//// fDx = fX - sSourcePoint[1].fX;
//// fDy = fY - sSourcePoint[1].fY;
//// fDz = fZ - sSourcePoint[1].fZ;
//// fResult += 1.0/(fDx*fDx + fDy*fDy + fDz*fDz);
////
//// fDx = fX - sSourcePoint[2].fX;
//// fDy = fY - sSourcePoint[2].fY;
//// fDz = fZ - sSourcePoint[2].fZ;
//// fResult += 1.5/(fDx*fDx + fDy*fDy + fDz*fDz);
////
//// return fResult;
////}
////
//////fSample2 finds the distance of (fX, fY, fZ) from three moving lines
////GLfloat fSample2(GLfloat fX, GLfloat fY, GLfloat fZ)
////{
//// GLdouble fResult = 0.0;
//// GLdouble fDx, fDy, fDz;
//// fDx = fX - sSourcePoint[0].fX;
//// fDy = fY - sSourcePoint[0].fY;
//// fResult += 0.5/(fDx*fDx + fDy*fDy);
////
//// fDx = fX - sSourcePoint[1].fX;
//// fDz = fZ - sSourcePoint[1].fZ;
//// fResult += 0.75/(fDx*fDx + fDz*fDz);
////
//// fDy = fY - sSourcePoint[2].fY;
//// fDz = fZ - sSourcePoint[2].fZ;
//// fResult += 1.0/(fDy*fDy + fDz*fDz);
////
//// return fResult;
////}
////
////
//////fSample2 defines a height field by plugging the distance from the center into the sin and cos functions
////GLfloat fSample3(GLfloat fX, GLfloat fY, GLfloat fZ)
////{
//// GLfloat fHeight = 20.0*(fTime + sqrt((0.5-fX)*(0.5-fX) + (0.5-fY)*(0.5-fY)));
//// fHeight = 1.5 + 0.1*(sinf(fHeight) + cosf(fHeight));
//// GLdouble fResult = (fHeight - fZ)*50.0;
////
//// return fResult;
////}
//
////
//////vGetNormal() finds the gradient of the scalar field at a point
//////This gradient can be used as a very accurate vertx normal for lighting calculations
////GLvoid vGetNormal(GLvector &rfNormal, GLfloat fX, GLfloat fY, GLfloat fZ)
////{
//// rfNormal.fX = fSample(fX-0.01, fY, fZ) - fSample(fX+0.01, fY, fZ);
//// rfNormal.fY = fSample(fX, fY-0.01, fZ) - fSample(fX, fY+0.01, fZ);
//// rfNormal.fZ = fSample(fX, fY, fZ-0.01) - fSample(fX, fY, fZ+0.01);
//// vNormalizeVector(rfNormal, rfNormal);
////}
//
//
////vMarchCube1 performs the Marching Cubes algorithm on a single cube
//GLvoid vMarchCube1(GLfloat fX, GLfloat fY, GLfloat fZ, GLfloat fScale)
//{
// extern GLint aiCubeEdgeFlags[256];
// extern GLint a2iTriangleConnectionTable[256][16];
//
// GLint iCorner, iVertex, iVertexTest, iEdge, iTriangle, iFlagIndex, iEdgeFlags;
// GLfloat fOffset;
// GLvector sColor;
// GLfloat afCubeValue[8];
// GLvector asEdgeVertex[12];
// GLvector asEdgeNorm[12];
//
// //Make a local copy of the values at the cube's corners
// for(iVertex = 0; iVertex < 8; iVertex++)
// {
// afCubeValue[iVertex] = 28;//fSample(fX + a2fVertexOffset[iVertex][0]*fScale,
// // fY + a2fVertexOffset[iVertex][1]*fScale,
// // fZ + a2fVertexOffset[iVertex][2]*fScale);
// }
//
// //Find which vertices are inside of the surface and which are outside
// iFlagIndex = 0;
// for(iVertexTest = 0; iVertexTest < 8; iVertexTest++)
// {
// if(afCubeValue[iVertexTest] <= fTargetValue)
// iFlagIndex |= 1<<iVertexTest;
// }
//
// //Find which edges are intersected by the surface
// iEdgeFlags = aiCubeEdgeFlags[iFlagIndex];
//
// //If the cube is entirely inside or outside of the surface, then there will be no intersections
// if(iEdgeFlags == 0)
// {
// return;
// }
//
// //Find the point of intersection of the surface with each edge
// //Then find the normal to the surface at those points
// for(iEdge = 0; iEdge < 12; iEdge++)
// {
// //if there is an intersection on this edge
// if(iEdgeFlags & (1<<iEdge))
// {
// fOffset = fGetOffset(afCubeValue[ a2iEdgeConnection[iEdge][0] ],
// afCubeValue[ a2iEdgeConnection[iEdge][1] ], fTargetValue);
//
// asEdgeVertex[iEdge].fX = fX + (a2fVertexOffset[ a2iEdgeConnection[iEdge][0] ][0] + fOffset * a2fEdgeDirection[iEdge][0]) * fScale;
// asEdgeVertex[iEdge].fY = fY + (a2fVertexOffset[ a2iEdgeConnection[iEdge][0] ][1] + fOffset * a2fEdgeDirection[iEdge][1]) * fScale;
// asEdgeVertex[iEdge].fZ = fZ + (a2fVertexOffset[ a2iEdgeConnection[iEdge][0] ][2] + fOffset * a2fEdgeDirection[iEdge][2]) * fScale;
//
// }
// }
//
//
// //Draw the triangles that were found. There can be up to five per cube
// for(iTriangle = 0; iTriangle < 5; iTriangle++)
// {
// if(a2iTriangleConnectionTable[iFlagIndex][3*iTriangle] < 0)
// break;
//
// for(iCorner = 0; iCorner < 3; iCorner++)
// {
// iVertex = a2iTriangleConnectionTable[iFlagIndex][3*iTriangle+iCorner];
//
// vGetColor(sColor, asEdgeVertex[iVertex], asEdgeNorm[iVertex]);
// glColor3f(sColor.fX, sColor.fY, sColor.fZ);
// glNormal3f(asEdgeNorm[iVertex].fX, asEdgeNorm[iVertex].fY, asEdgeNorm[iVertex].fZ);
// glVertex3f(asEdgeVertex[iVertex].fX, asEdgeVertex[iVertex].fY, asEdgeVertex[iVertex].fZ);
// }
// }
//}
//
//
//
//
//
////vertexIndices.push_back(vertexIndex[0]);
////vertexIndices.push_back(vertexIndex[1]);
////vertexIndices.push_back(vertexIndex[2]);
////uvIndices .push_back(uvIndex[0]);
////uvIndices .push_back(uvIndex[1]);
////uvIndices .push_back(uvIndex[2]);
////normalIndices.push_back(normalIndex[0]);
////normalIndices.push_back(normalIndex[1]);
////normalIndices.push_back(normalIndex[2]);
//
//
//
//
//
//
//
//
////
//////vMarchTetrahedron performs the Marching Tetrahedrons algorithm on a single tetrahedron
////GLvoid vMarchTetrahedron(GLvector *pasTetrahedronPosition, GLfloat *pafTetrahedronValue)
////{
//// extern GLint aiTetrahedronEdgeFlags[16];
//// extern GLint a2iTetrahedronTriangles[16][7];
////
//// GLint iEdge, iVert0, iVert1, iEdgeFlags, iTriangle, iCorner, iVertex, iFlagIndex = 0;
//// GLfloat fOffset, fInvOffset, fValue = 0.0;
//// GLvector asEdgeVertex[6];
//// GLvector asEdgeNorm[6];
//// GLvector sColor;
////
//// //Find which vertices are inside of the surface and which are outside
//// for(iVertex = 0; iVertex < 4; iVertex++)
//// {
//// if(pafTetrahedronValue[iVertex] <= fTargetValue)
//// iFlagIndex |= 1<<iVertex;
//// }
////
//// //Find which edges are intersected by the surface
//// iEdgeFlags = aiTetrahedronEdgeFlags[iFlagIndex];
////
//// //If the tetrahedron is entirely inside or outside of the surface, then there will be no intersections
//// if(iEdgeFlags == 0)
//// {
//// return;
//// }
//// //Find the point of intersection of the surface with each edge
//// // Then find the normal to the surface at those points
//// for(iEdge = 0; iEdge < 6; iEdge++)
//// {
//// //if there is an intersection on this edge
//// if(iEdgeFlags & (1<<iEdge))
//// {
//// iVert0 = a2iTetrahedronEdgeConnection[iEdge][0];
//// iVert1 = a2iTetrahedronEdgeConnection[iEdge][1];
//// fOffset = fGetOffset(pafTetrahedronValue[iVert0], pafTetrahedronValue[iVert1], fTargetValue);
//// fInvOffset = 1.0 - fOffset;
////
//// asEdgeVertex[iEdge].fX = fInvOffset*pasTetrahedronPosition[iVert0].fX + fOffset*pasTetrahedronPosition[iVert1].fX;
//// asEdgeVertex[iEdge].fY = fInvOffset*pasTetrahedronPosition[iVert0].fY + fOffset*pasTetrahedronPosition[iVert1].fY;
//// asEdgeVertex[iEdge].fZ = fInvOffset*pasTetrahedronPosition[iVert0].fZ + fOffset*pasTetrahedronPosition[iVert1].fZ;
////
//// vGetNormal(asEdgeNorm[iEdge], asEdgeVertex[iEdge].fX, asEdgeVertex[iEdge].fY, asEdgeVertex[iEdge].fZ);
//// }
//// }
//// //Draw the triangles that were found. There can be up to 2 per tetrahedron
//// for(iTriangle = 0; iTriangle < 2; iTriangle++)
//// {
//// if(a2iTetrahedronTriangles[iFlagIndex][3*iTriangle] < 0)
//// break;
////
//// for(iCorner = 0; iCorner < 3; iCorner++)
//// {
//// iVertex = a2iTetrahedronTriangles[iFlagIndex][3*iTriangle+iCorner];
////
//// vGetColor(sColor, asEdgeVertex[iVertex], asEdgeNorm[iVertex]);
//// glColor3f(sColor.fX, sColor.fY, sColor.fZ);
//// glNormal3f(asEdgeNorm[iVertex].fX, asEdgeNorm[iVertex].fY, asEdgeNorm[iVertex].fZ);
//// glVertex3f(asEdgeVertex[iVertex].fX, asEdgeVertex[iVertex].fY, asEdgeVertex[iVertex].fZ);
//// }
//// }
////}
////
////
////
//////vMarchCube2 performs the Marching Tetrahedrons algorithm on a single cube by making six calls to vMarchTetrahedron
////GLvoid vMarchCube2(GLfloat fX, GLfloat fY, GLfloat fZ, GLfloat fScale)
////{
//// GLint iVertex, iTetrahedron, iVertexInACube;
//// GLvector asCubePosition[8];
//// GLfloat afCubeValue[8];
//// GLvector asTetrahedronPosition[4];
//// GLfloat afTetrahedronValue[4];
////
//// //Make a local copy of the cube's corner positions
//// for(iVertex = 0; iVertex < 8; iVertex++)
//// {
//// asCubePosition[iVertex].fX = fX + a2fVertexOffset[iVertex][0]*fScale;
//// asCubePosition[iVertex].fY = fY + a2fVertexOffset[iVertex][1]*fScale;
//// asCubePosition[iVertex].fZ = fZ + a2fVertexOffset[iVertex][2]*fScale;
//// }
////
//// //Make a local copy of the cube's corner values
//// for(iVertex = 0; iVertex < 8; iVertex++)
//// {
//// afCubeValue[iVertex] = fSample(asCubePosition[iVertex].fX,
//// asCubePosition[iVertex].fY,
//// asCubePosition[iVertex].fZ);
//// }
////
//// for(iTetrahedron = 0; iTetrahedron < 6; iTetrahedron++)
//// {
//// for(iVertex = 0; iVertex < 4; iVertex++)
//// {
//// iVertexInACube = a2iTetrahedronsInACube[iTetrahedron][iVertex];
//// asTetrahedronPosition[iVertex].fX = asCubePosition[iVertexInACube].fX;
//// asTetrahedronPosition[iVertex].fY = asCubePosition[iVertexInACube].fY;
//// asTetrahedronPosition[iVertex].fZ = asCubePosition[iVertexInACube].fZ;
//// afTetrahedronValue[iVertex] = afCubeValue[iVertexInACube];
//// }
//// vMarchTetrahedron(asTetrahedronPosition, afTetrahedronValue);
//// }
////}
////
//
////vMarchingCubes iterates over the entire dataset, calling vMarchCube on each cube
//GLvoid vMarchingCubes()
//{
// GLint iX, iY, iZ;
// for(iX = 0; iX < iDataSetSize; iX++)
// for(iY = 0; iY < iDataSetSize; iY++)
// for(iZ = 0; iZ < iDataSetSize; iZ++)
// {
// vMarchCube(iX*fStepSize, iY*fStepSize, iZ*fStepSize, fStepSize);
// }
//}
////
////Voxel8x8x8::recalculate()
////{
////
////}
////
////
////GLint aiCubeEdgeFlags[256]=
////{
//// 0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,
//// 0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,
//// 0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,
//// 0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,
//// 0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,
//// 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,
//// 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,
//// 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,
//// 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0x0cc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,
//// 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x055, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,
//// 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,
//// 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460,
//// 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0,
//// 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230,
//// 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190,
//// 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000
////};
////
////
////GLint a2iTriangleConnectionTable[256][16] =
////{
//// {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1},
//// {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1},
//// {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1},
//// {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1},
//// {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1},
//// {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1},
//// {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1},
//// {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1},
//// {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1},
//// {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1},
//// {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1},
//// {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1},
//// {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1},
//// {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1},
//// {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1},
//// {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1},
//// {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1},
//// {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1},
//// {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1},
//// {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1},
//// {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1},
//// {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1},
//// {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1},
//// {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1},
//// {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1},
//// {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1},
//// {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1},
//// {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1},
//// {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1},
//// {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1},
//// {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1},
//// {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1},
//// {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1},
//// {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1},
//// {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1},
//// {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1},
//// {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1},
//// {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1},
//// {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1},
//// {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1},
//// {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1},
//// {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1},
//// {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1},
//// {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1},
//// {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1},
//// {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1},
//// {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1},
//// {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1},
//// {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1},
//// {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1},
//// {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1},
//// {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1},
//// {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1},
//// {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1},
//// {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1},
//// {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1},
//// {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1},
//// {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1},
//// {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1},
//// {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1},
//// {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1},
//// {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1},
//// {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1},
//// {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1},
//// {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1},
//// {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1},
//// {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1},
//// {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1},
//// {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1},
//// {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1},
//// {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1},
//// {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1},
//// {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1},
//// {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1},
//// {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1},
//// {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1},
//// {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1},
//// {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1},
//// {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1},
//// {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1},
//// {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1},
//// {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1},
//// {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1},
//// {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1},
//// {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1},
//// {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1},
//// {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1},
//// {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1},
//// {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1},
//// {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1},
//// {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1},
//// {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1},
//// {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1},
//// {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1},
//// {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1},
//// {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1},
//// {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1},
//// {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1},
//// {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1},
//// {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1},
//// {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1},
//// {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1},
//// {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1},
//// {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1},
//// {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1},
//// {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1},
//// {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1},
//// {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1},
//// {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1},
//// {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1},
//// {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1},
//// {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1},
//// {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1},
//// {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1},
//// {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1},
//// {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1},
//// {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1},
//// {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1},
//// {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1},
//// {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1},
//// {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1},
//// {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1},
//// {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1},
//// {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1},
//// {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1},
//// {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1},
//// {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1},
//// {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1},
//// {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1},
//// {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1},
//// {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1},
//// {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1},
//// {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1},
//// {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1},
//// {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1},
//// {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1},
//// {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1},
//// {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1},
//// {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1},
//// {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1},
//// {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1},
//// {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1},
//// {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1},
//// {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1},
//// {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1},
//// {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1},
//// {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1},
//// {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1},
//// {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1},
//// {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1},
//// {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1},
//// {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1},
//// {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1},
//// {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1},
//// {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1},
//// {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1},
//// {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1},
//// {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1},
//// {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1},
//// {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1},
//// {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1},
//// {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1},
//// {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1},
//// {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1},
//// {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1},
//// {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1},
//// {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1},
//// {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1},
//// {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1},
//// {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1},
//// {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1},
//// {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1},
//// {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1},
//// {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1},
//// {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1},
//// {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1},
//// {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1},
//// {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1},
//// {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1},
//// {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1},
//// {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1},
//// {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1},
//// {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1},
//// {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
//// {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
////};
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
| 41.984511 | 146 | 0.445446 | [
"vector"
] |
b73baceb1b92d2a7d259f8e0c4d8ee9a070c08e7 | 4,018 | cc | C++ | sortsim.cc | Kingsford-Group/jellyfishsim | c1b24b728e5e8d06acbfa91447702984177023f4 | [
"BSD-3-Clause"
] | null | null | null | sortsim.cc | Kingsford-Group/jellyfishsim | c1b24b728e5e8d06acbfa91447702984177023f4 | [
"BSD-3-Clause"
] | null | null | null | sortsim.cc | Kingsford-Group/jellyfishsim | c1b24b728e5e8d06acbfa91447702984177023f4 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <vector>
#include <fstream>
#include <iterator>
#include <iomanip>
#include <string>
#include <jellyfish/jellyfish.hpp>
#include <gzstream.h>
using jellyfish::mer_dna;
struct mercount {
uint64_t mer;
uint64_t count;
};
bool operator<(const mercount& m1, const mercount& m2) {
return m1.mer < m2.mer;
}
struct hashinfo {
std::vector<mercount> mers;
double norm;
hashinfo() : norm(0.0) {
mers.reserve(100000);
}
};
std::vector<hashinfo> readKmerCounts(std::vector<std::string> argv) {
int argc = argv.size();
std::vector<hashinfo> res(argc);
#pragma omp parallel for
for(int i = 0; i < argc; ++i) {
auto& mers = res[i].mers;
igzstream in(argv[i].c_str());
if(!in.good()) {
#pragma omp critical
std::cerr << "Error openinig file '" << argv[i] << '\'' << std::endl;
exit(1);
}
mer_dna mer;
uint64_t value;
double norm = 0.0;
while(true) {
in >> mer >> value;
if(in.eof())
break;
if(!in.good()) {
#pragma omp critical
std::cerr << "Error reading file '" << argv[i] << '\'' << std::endl;
exit(1);
}
mers.push_back({ mer.get_bits(0, 2*mer_dna::k()), value });
norm += value * value;
}
std::sort(mers.begin(), mers.end());
res[i].norm = std::sqrt(norm);
}
return res;
}
std::vector<std::string> readDatasetsFile(char *filename) {
std::vector<std::string> list_datasets;
std::ifstream datasets_file(filename);
if (!datasets_file.is_open()) {
std::cerr << "Error openinig file '" << filename << '\'' << std::endl;
exit(1);
}
std::string dataset;
while (datasets_file >> dataset) {
list_datasets.push_back(dataset);
}
datasets_file.close();
return list_datasets;
}
// Position in a vector representing a lower triangular matrix (with
// diagonal). Pre-condition: i >= j
inline size_t triangle(size_t i, size_t j = 0) {
return i * (i + 1) / 2 + j;
}
inline void invTriangle(size_t index, size_t& i, size_t& j) {
i = std::floor((std::sqrt(8*index + 1) - 1.0) / 2);
j = index - triangle(i);
}
double computeSimilarity(const hashinfo& mers1, const hashinfo& mers2) {
auto it1 = mers1.mers.begin(), it2 = mers2.mers.begin();
const auto end1 = mers1.mers.end(), end2 = mers2.mers.end();
double product = 0.0;
while(it1 != end1 && it2 != end2) {
if(*it1 < *it2) {
++it1;
} else if(*it2 < *it1) {
++it2;
} else {
product += it1->count * it2->count;
++it1;
++it2;
}
}
return product / (mers1.norm * mers2.norm);
}
int main(int argc, char *argv[]) {
if(argc < 3) {
std::cerr << "Usage: " << argv[0] << " klen list_datasets_file" << std::endl;
exit(1);
}
const int klen = std::atoi(argv[1]);
if(klen <= 0) {
std::cerr << "Invalid k-mer length '" << klen << '\'' << std::endl;
exit(1);
}
std::vector<std::string> list_datasets = readDatasetsFile(argv[2]);
jellyfish::mer_dna::k(klen); // Set k-mer length for Jellyfish
std::vector<hashinfo> counts = readKmerCounts(list_datasets);
std::vector<double> matrix(triangle(counts.size()));
#pragma omp parallel for
for(size_t k = 0; k < matrix.size(); ++k) {
size_t i, j;
invTriangle(k, i, j);
if(i != j)
matrix[k] = computeSimilarity(counts[i], counts[j]);
else
matrix[k] = 1.0;
}
std::vector<std::vector<double> > sim_matrix( counts.size(), std::vector<double> (counts.size()));
auto elt = matrix.cbegin();
for(size_t i = 0; i < counts.size(); ++i) {
for(size_t j = 0; j <= i; ++j, ++elt) {
sim_matrix[i][j] = *elt;
sim_matrix[j][i] = *elt;
}
}
std::ofstream output_file("similarity_matrix");
output_file << std::fixed << std::setprecision(9);
std::ostream_iterator<double> output_iterator(output_file, " ");
for(const auto& vt : sim_matrix) {
std::copy(vt.cbegin(), vt.cend(), output_iterator);
output_file << '\n';
}
return 0;
}
| 24.351515 | 100 | 0.590592 | [
"vector"
] |
b73cb279de947d8fa7ebb218be62bab93b096910 | 6,764 | cpp | C++ | example3 - powersystem/PowerSystem-HelicsFed/NonisolatedFault.cpp | GMLC-TDC/helics-omnetpp | 705ad31d999c51725163c654b67930f0a8b99838 | [
"BSD-3-Clause"
] | 1 | 2020-02-11T18:49:43.000Z | 2020-02-11T18:49:43.000Z | example3 - powersystem/PowerSystem-HelicsFed/NonisolatedFault.cpp | GMLC-TDC/helics-omnetpp | 705ad31d999c51725163c654b67930f0a8b99838 | [
"BSD-3-Clause"
] | null | null | null | example3 - powersystem/PowerSystem-HelicsFed/NonisolatedFault.cpp | GMLC-TDC/helics-omnetpp | 705ad31d999c51725163c654b67930f0a8b99838 | [
"BSD-3-Clause"
] | null | null | null | // NonisolatedFault.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "MessageFederate.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <stdlib.h>
#include<stdio.h>
#include<sstream>
#include<algorithm>
#include<string>
enum MSGTYPE
{
//Msgtype between PowerGrid and Comms
pingMessageType = 1,
replyMessageType = 2
};
enum MSGCODE
{
//PowerGrid commands for Comms
LOCAL_FAULT_EVENT = 403,
REMOTE_FAULT_EVENT = 404,
//Comms commands for Power Grid
BREAKER_TRIP_COMMAND = 409,
BREAKER_CLOSE_COMMAND = 410,
BREAKER_OOS_COMMAND = 411,
//PowerGrid confirmation to Comms
BREAKER_TRIP_EVENT = 405,
BREAKER_CLOSE_EVENT = 406,
LOCAL_FAULT_CLEARED = 407,
REMOTE_FAULT_CLEARED = 408
};
void sendFault(std::string relayName, helics_endpoint endpoint, helics_message_object msgTo, MSGCODE confCode, helics_error thisErr)
{
helicsMessageSetSource(msgTo, relayName.c_str(), &thisErr);
helicsMessageSetDestination(msgTo, "commEndpt", &thisErr);
std::string msg;
switch (confCode)
{
case LOCAL_FAULT_EVENT:
msg = "mtype:1,mcode:403";
break;
case REMOTE_FAULT_EVENT:
msg = "mtype:1,mcode:404";
break;
}
helicsMessageSetData(msgTo, msg.c_str(), 128, &thisErr);
helicsEndpointSendMessageObject(endpoint, msgTo, &thisErr);
std::cout << "Message sent!" << std::endl;
}
void confirmationMsg(std::string relayName, helics_endpoint endpoint, helics_message_object msgTo, MSGCODE confCode, helics_error thisErr)
{
helicsMessageSetSource(msgTo, relayName.c_str(), &thisErr);
helicsMessageSetDestination(msgTo, "commEndpt", &thisErr);
std::string msg;
switch (confCode)
{
case BREAKER_TRIP_EVENT:
msg = "mtype:2,mcode:405";
break;
case BREAKER_CLOSE_EVENT:
msg = "mtype:2,mcode:406";
break;
case LOCAL_FAULT_CLEARED:
msg = "mtype:2,mcode:407";
break;
case REMOTE_FAULT_CLEARED:
msg = "mtype:2,mcode:408";
break;
}
helicsMessageSetData(msgTo, msg.c_str(), 128, &thisErr);
helicsEndpointSendMessageObject(endpoint, msgTo, &thisErr);
std::cout << "Message sent!" << std::endl;
}
void parseMsg(std::vector<std::string>& separateStrings, std::string msg) {
std::stringstream parse(msg);
std::string portion;
while (getline(parse, portion, ','))
{
separateStrings.push_back(portion);
}
}
void query(helics_time time, helics_federate fed, bool update, helics_error thisErr)
{
time = helicsFederateRequestTime(fed, 4.0, &thisErr);
helics_message_object bufferMsg;
if (thisErr.error_code != helics_ok)
{
fprintf(stderr, "HELICS request time failed:%s\n", thisErr.message);
}
else
{
fprintf(stdout, "HELICS granted time: %f\n", time);
}
update = helicsFederateHasMessage(fed);
printf("%d\n", update);
int numMessages = helicsFederatePendingMessages(fed);
std::cout << "Total number of messages: " << numMessages << std::endl;
if (update)
{
while (numMessages != 0)
{
bufferMsg = helicsFederateGetMessageObject(fed);
fprintf(stdout, "Message: %s\n", helicsMessageGetString(bufferMsg));
std::string bufferString = helicsMessageGetString(bufferMsg);
int mtype;
int mcode;
std::vector<std::string> strings;
std::cout << "This is source: " << helicsMessageGetSource(bufferMsg) << std::endl;
parseMsg(strings, bufferString);
std::string mtypeString = strings[0].substr(6, strings[0].size() - 1);
mtype = std::stoi(mtypeString);
std::string mcodeString = strings[1].substr(6, strings[1].size() - 1);
mcode = std::stoi(mcodeString);
std::cout << "This is mytpe: " << mtype << std::endl;
std::cout << "This is mcode: " << mcode << std::endl;
std::string bufferDest = helicsMessageGetDestination(bufferMsg);
helics_message_object confirmMsg = helicsFederateCreateMessageObject(fed, &thisErr);
if (mtype == replyMessageType)
{
if (mcode == BREAKER_TRIP_COMMAND)
{
confirmationMsg(bufferDest, helicsFederateGetEndpoint(fed, bufferDest.c_str(), &thisErr), confirmMsg, BREAKER_TRIP_EVENT, thisErr);
std::cout << "Sent break trip event" << std::endl;
}
else if (mcode == BREAKER_CLOSE_COMMAND)
{
confirmationMsg(bufferDest, helicsFederateGetEndpoint(fed, bufferDest.c_str(), &thisErr), confirmMsg, BREAKER_CLOSE_EVENT, thisErr);
std::cout << "Sent break close event" << std::endl;
}
else if (mcode == BREAKER_OOS_COMMAND)
{
std::cout << "Sent breaker out of service event" << std::endl;
}
else
{
}
}
else
{
std::cout << "Invalid message type!" << std::endl;
}
numMessages--;
}
}
else
{
printf("No Message\n");
}
}
int main()
{
std::vector<std::string> agentsList;
helics_federate_info infoStruct;
const char* fedinitstring = "--federates=1"; //tells the broker to expect 1 federate
helics_federate subFed;
helics_endpoint _14_4;
helics_endpoint _3_4;
helics_endpoint _5_4;
helics_message_object sendMsg;
helics_message_object rcvdMsg;
helics_time currenttime = 0.0;
bool msgUpdate;
helics_error err = helicsErrorInitialize();
infoStruct = helicsCreateFederateInfo();
helicsFederateInfoSetCoreTypeFromString(infoStruct, "zmq", &err);
helicsFederateInfoSetCoreInitString(infoStruct, fedinitstring, &err);
helicsFederateInfoSetTimeProperty(infoStruct, helicsGetPropertyIndex("period"), 2.0, &err);
subFed = helicsCreateMessageFederate("NonisolatedFault.exe", infoStruct, &err);
helicsFederateInfoFree(infoStruct);
if (err.error_code != helics_ok)
{
return (-2);
}
_14_4 = helicsFederateRegisterGlobalEndpoint(subFed, "_14_4", NULL, &err);
_3_4 = helicsFederateRegisterGlobalEndpoint(subFed, "_3_4", NULL, &err);
_5_4 = helicsFederateRegisterGlobalEndpoint(subFed, "_5_4", NULL, &err);
rcvdMsg = helicsFederateCreateMessageObject(subFed, &err);
sendMsg = helicsFederateCreateMessageObject(subFed, &err);
//Initialize all variables
helicsFederateEnterInitializingMode(subFed, &err);
if (err.error_code != helics_ok)
{
fprintf(stderr, "HELICS failed to enter initialization mode:%s\n", err.message);
}
else
{
printf("Initializing...\n");
}
// Enter simulation execution
helicsFederateEnterExecutingMode(subFed, &err);
if (err.error_code != helics_ok)
{
fprintf(stderr, "HELICS failed to enter execution mode:%s\n", err.message);
}
else
{
printf("Executing...\n");
}
/*Sending out fault messages*/
sendFault("_14_4", _14_4, sendMsg, LOCAL_FAULT_EVENT, err);
sendFault("_3_4", _3_4, sendMsg, REMOTE_FAULT_EVENT, err);
sendFault("_5_4", _5_4, sendMsg, REMOTE_FAULT_EVENT, err);
/*Request time & query for messages*/
query(currenttime, subFed, &msgUpdate, err);
helicsFederateFinalize(subFed, &err);
helicsFederateFree(subFed);
helicsCloseLibrary();
return 0;
}
| 25.144981 | 138 | 0.719988 | [
"vector"
] |
b73da15dba2b5eb42e657b2fcab07260e18c9338 | 1,210 | cpp | C++ | USACO/Silver/S-snowboots.cpp | klxu03/CompetitiveProgramming | fd83200b5c8af3542fb639d504e3948427f69efc | [
"MIT"
] | null | null | null | USACO/Silver/S-snowboots.cpp | klxu03/CompetitiveProgramming | fd83200b5c8af3542fb639d504e3948427f69efc | [
"MIT"
] | null | null | null | USACO/Silver/S-snowboots.cpp | klxu03/CompetitiveProgramming | fd83200b5c8af3542fb639d504e3948427f69efc | [
"MIT"
] | null | null | null | //http://www.usaco.org/index.php?page=viewproblem2&cpid=811
#include <bits/stdc++.h>
using namespace std;
#define f0r(a, b) for (long long a = 0; a < b; a++)
#define f1r(a, b, c) for (long long a = b; a < c; a++)
#define max3(a, b, c) max(a, max(b, c))
#define pb push_back
#define f first
#define s second
#define mp(a, b) make_pair(a, b)
using ll = long long;
/* Print a vector */
template<typename A> ostream& operator<<(ostream &cout, vector<A> const &v) {
cout << "[";
for(int i = 0; i < v.size(); i++) {
if (i) cout << ", "; cout << v[i];
}
return cout << "]";
}
int main() {
ll n, b;
cin >> n >> b;
vector<ll> f(n), d(b), s(b);
f0r(i, n) {
cin >> f[i];
}
f0r(i, b) {
cin >> d[i] >> s[i];
}
vector<vector<bool>> dp(b, vector<bool>(n));
dp[0][0] = true;
f0r(y, b) {
next:
f0r(x, n) {
f0r(x1, s[y]) {
f0r(y1, y + 1) {
if (dp[x - x1][y - y1]) {
dp[x][y] = true;
goto next;
}
}
}
}
}
ll ret = 252;
f0r(y, b) {
if (dp[n - 1][y]) {
ret = y;
}
}
cout << ret << endl;
return 0;
} | 18.059701 | 78 | 0.438017 | [
"vector"
] |
b748390a18cb538c3f5906415edf902a4b1cee34 | 844 | hpp | C++ | tests/approval_tests/renderer/svg_renderer.hpp | cpp-niel/mfl | d22d698b112b95d102150d5f3a5f35d8eb7fb0f3 | [
"MIT"
] | 4 | 2021-04-02T02:52:05.000Z | 2021-12-11T00:42:35.000Z | tests/approval_tests/renderer/svg_renderer.hpp | cpp-niel/mfl | d22d698b112b95d102150d5f3a5f35d8eb7fb0f3 | [
"MIT"
] | null | null | null | tests/approval_tests/renderer/svg_renderer.hpp | cpp-niel/mfl | d22d698b112b95d102150d5f3a5f35d8eb7fb0f3 | [
"MIT"
] | null | null | null | #pragma once
#include "fonts_for_tests/freetype.hpp"
#include "mfl/layout.hpp"
#include <iosfwd>
#include <memory>
#include <string>
namespace mfl
{
class svg_renderer
{
public:
svg_renderer(std::ostream& os, const pixels width, const pixels height, const dots_per_inch dpi,
const fft::freetype& ft);
~svg_renderer();
svg_renderer(const svg_renderer&) = delete;
svg_renderer& operator=(const svg_renderer&) = delete;
svg_renderer(svg_renderer&&) = delete;
svg_renderer& operator=(svg_renderer&&) = delete;
void render(const pixels x, const pixels y, const layout_elements& elements);
void render_tt_text(const pixels x, const pixels y, const std::string& text);
private:
class impl;
std::unique_ptr<impl> impl_;
};
} | 26.375 | 104 | 0.651659 | [
"render"
] |
b758468a0d2f369cec8cfe065c7fd748133f5229 | 2,697 | cc | C++ | net/base/x509_certificate_openssl_android.cc | qumaciel/android_external_chromium | 7602059d4c4fc5de88abfbd8a28cc8ce532f97a0 | [
"BSD-3-Clause"
] | null | null | null | net/base/x509_certificate_openssl_android.cc | qumaciel/android_external_chromium | 7602059d4c4fc5de88abfbd8a28cc8ce532f97a0 | [
"BSD-3-Clause"
] | null | null | null | net/base/x509_certificate_openssl_android.cc | qumaciel/android_external_chromium | 7602059d4c4fc5de88abfbd8a28cc8ce532f97a0 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010 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 "net/base/x509_certificate.h"
#include "base/logging.h"
#include "net/base/android_network_library.h"
#include "net/base/cert_status_flags.h"
#include "net/base/cert_verify_result.h"
#include "net/base/net_errors.h"
namespace net {
int X509Certificate::Verify(const std::string& hostname,
int flags,
CertVerifyResult* verify_result) const {
verify_result->Reset();
AndroidNetworkLibrary* lib = AndroidNetworkLibrary::GetSharedInstance();
if (!lib) {
LOG(ERROR) << "Rejecting verify as no net library installed";
verify_result->cert_status |= ERR_CERT_INVALID;
return MapCertStatusToNetError(verify_result->cert_status);
}
OSCertHandles cert_handles(intermediate_ca_certs_);
// Make sure the peer's own cert is the first in the chain, if it's not
// already there.
if (cert_handles.empty() || cert_handles[0] != cert_handle_)
cert_handles.insert(cert_handles.begin(), cert_handle_);
std::vector<std::string> cert_bytes;
cert_bytes.reserve(cert_handles.size());
for (OSCertHandles::const_iterator it = cert_handles.begin();
it != cert_handles.end(); ++it) {
cert_bytes.push_back(GetDEREncodedBytes(*it));
}
if (IsPublicKeyBlacklisted(verify_result->public_key_hashes)) {
verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
return MapCertStatusToNetError(verify_result->cert_status);
}
// TODO(joth): Fetch the authentication type from SSL rather than hardcode.
AndroidNetworkLibrary::VerifyResult result =
lib->VerifyX509CertChain(cert_bytes, hostname, "RSA");
switch (result) {
case AndroidNetworkLibrary::VERIFY_OK:
return OK;
case AndroidNetworkLibrary::VERIFY_BAD_HOSTNAME:
verify_result->cert_status |= CERT_STATUS_COMMON_NAME_INVALID;
break;
case AndroidNetworkLibrary::VERIFY_NO_TRUSTED_ROOT:
verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
break;
// WTL_EDM_START - MDM 3.1
case AndroidNetworkLibrary::VERIFY_REVOKED:
verify_result->cert_status |= CERT_STATUS_REVOKED;
break;
case AndroidNetworkLibrary::VERIFY_UNABLE_TO_CHECK_REVOCATION:
verify_result->cert_status |= CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
break;
// WTL_EDM_END - MDM 3.1
case AndroidNetworkLibrary::VERIFY_INVOCATION_ERROR:
default:
verify_result->cert_status |= ERR_CERT_INVALID;
break;
}
return MapCertStatusToNetError(verify_result->cert_status);
}
} // namespace net
| 35.486842 | 77 | 0.731183 | [
"vector"
] |
b763dc9fc141de6eef252ba3a04e71ea3b737cc9 | 3,002 | hpp | C++ | src/simple_command.hpp | allenh1/hsh | 9ed8dc3ebcc1d7f4a8d236cb389b8e823c831fdd | [
"Apache-2.0"
] | 9 | 2016-09-12T00:21:30.000Z | 2019-04-25T23:39:13.000Z | src/simple_command.hpp | allenh1/hsh | 9ed8dc3ebcc1d7f4a8d236cb389b8e823c831fdd | [
"Apache-2.0"
] | 14 | 2017-10-01T20:27:48.000Z | 2019-10-04T01:04:04.000Z | src/simple_command.hpp | allenh1/hsh | 9ed8dc3ebcc1d7f4a8d236cb389b8e823c831fdd | [
"Apache-2.0"
] | 2 | 2016-10-20T18:36:03.000Z | 2017-03-01T15:18:47.000Z | // Copyright 2016 Hunter L. Allen
//
// 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.
#ifndef SIMPLE_COMMAND_HPP_
#define SIMPLE_COMMAND_HPP_
#pragma once
/* UNIX Includes */
#include <sys/resource.h>
#include <sys/signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/stat.h>
/* Linux Includes */
#include <termios.h>
#include <unistd.h>
#include <signal.h>
#include <dirent.h>
#include <fcntl.h>
#include <pwd.h>
/* C includes */
#include <stdio.h>
/* STL (C++) includes */
#include <functional>
#include <algorithm>
#include <typeinfo>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <sstream>
#include <memory>
#include <stack>
#include <string>
#include <thread>
#include <vector>
#include <map>
/* File Includes */
#include "shell-utils.hpp"
#include "wildcard.hpp"
#include "job.hpp"
#ifdef __APPLE__
constexpr bool is_os_x = true;
#else
constexpr bool is_os_x = false;
#endif
/* Command Data Structure */
struct SimpleCommand
{
SimpleCommand();
~SimpleCommand() {release();}
std::vector<char *> arguments;
void insertArgument(const std::shared_ptr<char> argument);
ssize_t numOfArguments = 0;
void release()
{
for (size_t x = 0; x < arguments.size(); ++x) {delete[] arguments[x];}
arguments.clear();
arguments.shrink_to_fit();
numOfArguments = 0;
}
void launch(
const int & fdin, const int & fdout, const int & fderr,
const int & pgid, const bool & background, const bool & interactive);
void setup_process_io(const int & fdin, const int & fdout, const int & fderr);
void save_io(
const int & fdin, const int & fdout, const int & fderr,
int & saved_fdin, int & saved_fdout, int & saved_fderr);
void resume_io(const int & fdin, const int & fdout, const int & fderr);
bool handle_builtins(const int &, const int &, const int &);
void handle_modified_commands();
bool handle_cd(const int &, const int &, const int &);
bool handle_cl(const int &, const int &, const int &);
bool handle_setenv(const int &, const int &, const int &);
bool handle_unsetenv(const int &, const int &, const int &);
void handle_ls();
void handle_grep();
void handle_jobs();
void handle_history();
void handle_printenv();
bool completed = false;
bool stopped = false;
int status = -1;
static std::shared_ptr<std::vector<std::string>> history;
static std::shared_ptr<std::vector<job>> p_jobs;
pid_t pid;
};
#endif // SIMPLE_COMMAND_HPP_
| 26.803571 | 80 | 0.698867 | [
"vector"
] |
b7668889521ddc44b57601f1f0d18bb8dd8e842e | 2,786 | hpp | C++ | cppe/string.hpp | kyasu0118/cppe | 9ea59efe4c9c4a543a7d57a3604d1e2d47f24dfc | [
"Unlicense"
] | 2 | 2017-04-28T05:23:05.000Z | 2017-05-02T05:12:41.000Z | cppe/string.hpp | kyasu0118/cppe | 9ea59efe4c9c4a543a7d57a3604d1e2d47f24dfc | [
"Unlicense"
] | null | null | null | cppe/string.hpp | kyasu0118/cppe | 9ea59efe4c9c4a543a7d57a3604d1e2d47f24dfc | [
"Unlicense"
] | null | null | null | #pragma once
namespace cppe
{
class string : public object
{
private:
wchar_t* value;
string(const size_t _lenght) : length(_lenght)
{
value = new wchar_t[length+1];
value[length] = L'\0';
}
public:
const size_t length;
string() : length(0)
{
value = new wchar_t[1];
value[0] = L'\0';
}
string(const string& copy) : length(copy.length)
{
value = new wchar_t[length+1];
for( size_t i=0; i<=length; ++i )
{
value[i] = copy.value[i];
}
}
string(const wchar_t* text) : length(0)
{
while( text[length] != L'\0' )
{
++((size_t&)length);
}
value = new wchar_t[length+1];
for( size_t i=0; i<=length; ++i )
{
value[i] = text[i];
}
}
virtual ~string()
{
delete[] value;
}
virtual const string& toString() const
{
return *this;
}
inline operator const wchar_t*() const
{
return value;
}
inline const wchar_t& operator[]( size_t index ) const
{
return value[index];
}
inline string operator+( const string& right ) const
{
string result( length + right.length );
size_t i=0;
for( ; i<length; ++i )
{
result.value[i] = value[i];
}
for( ; i<length+right.length; ++i )
{
result.value[i] = right.value[i-length];
}
return result;
}
inline string& operator=( const string& right )
{
delete[] value;
((size_t&)length) = right.length;
value = new wchar_t[length+1];
for( size_t i=0; i<=length; ++i )
{
value[i] = right[i];
}
return *this;
}
inline bool operator==( const string& right ) const
{
if( length != right.length )
{
return false;
}
for( size_t i=0; i<length; ++i )
{
if( value[i] != right.value[i] )
{
return false;
}
}
return true;
}
};
}
cppe::string operator +( const cppe::object& left, const cppe::object& right )
{
return left.toString() + right.toString();
}
| 22.836066 | 78 | 0.389447 | [
"object"
] |
b769ab76bfe1e1ba2bb97eee65aaba231694fd01 | 1,840 | cpp | C++ | main.cpp | MeirKatz613/Gematria-Calculator-C-- | 985ba65667be5a79fce56457abbe365f37ba996f | [
"MIT"
] | null | null | null | main.cpp | MeirKatz613/Gematria-Calculator-C-- | 985ba65667be5a79fce56457abbe365f37ba996f | [
"MIT"
] | null | null | null | main.cpp | MeirKatz613/Gematria-Calculator-C-- | 985ba65667be5a79fce56457abbe365f37ba996f | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_map>
#include <string>
[[maybe_unused]] std::string AskGematria(){
std::cout << "What do you want the gematria of?\n";
std::string Gematria;
std::getline(std::cin, Gematria);
return Gematria;
}
[[maybe_unused]] int ConvertLetters(const std::string & Letters){
// Converts letters to numerical value.
std::unordered_map <char, double > Gematria_Values = {
{' ', 0},
{'א', 1},
{'ב', 2},
{'ג', 3},
{'ד', 4},
{'ה', 5},
{'ו', 6},
{'ז', 7},
{'ח', 8},
{'ט', 9},
{'י', 10},
{'כ', 20},
{'ך', 20},
{'ל', 30},
{'מ', 40},
{'מ', 40},
{'ם', 40},
{'נ', 50},
{'ן', 50},
{'ס', 60},
{'ע', 70},
{'פ', 80},
{'ף', 80},
{'צ', 90},
{'ץ', 90},
{'ק', 100},
{'ר', 200},
{'ש', 300},
{'ת', 400}
};
// Creates string Gematria
// converts to uppercase
// transform(Gematria.begin(), Gematria.end(), Gematria.begin(),::toupper);
//std::cin >> Gematria;
int sum = 0;
for (auto ch : Letters)
sum += Gematria_Values[ch];
return sum;
}
void PrintGematria(){
std::string Gematria = AskGematria();
if(!Gematria.empty()){
std::cout << "The gematria of " << Gematria << " is " << ConvertLetters(Gematria) << " \n";
std::cout << "Enter nothing to end program.\n";
PrintGematria();
}
else {
std::cout << "Hope you enjoyed\n";
}
}
int main() {
// Gives the value to the user.
PrintGematria();
return 0;
}
| 24.210526 | 106 | 0.414674 | [
"transform"
] |
b76f36af13226e4492510e6034dfecfd9550b027 | 3,673 | hpp | C++ | inc/parser.hpp | bergentroll/otus-cpp-10 | b4cd069584eeb9bc7f07a57f8577e7838f1b9861 | [
"CC0-1.0"
] | null | null | null | inc/parser.hpp | bergentroll/otus-cpp-10 | b4cd069584eeb9bc7f07a57f8577e7838f1b9861 | [
"CC0-1.0"
] | null | null | null | inc/parser.hpp | bergentroll/otus-cpp-10 | b4cd069584eeb9bc7f07a57f8577e7838f1b9861 | [
"CC0-1.0"
] | null | null | null | #ifndef OTUS_PARSER_HPP
#define OTUS_PARSER_HPP
#include <iostream>
#include <memory>
#include <stdexcept>
#include <sstream>
#include <string>
#include <vector>
#include "logger.hpp"
namespace otus {
class Parser {
public:
class InvalidToken: public std::logic_error {
public:
explicit InvalidToken(const std::string &input):
std::logic_error("unexpected token: " + input) { }
};
Parser(int packSize, ILogger &logger):
packSize(packSize), logger(logger) { commands.reserve(packSize); }
~Parser() {
std::stringstream ss { };
ss
<< "Thread main: "
<< linesCounter
<< " lines, "
<< blocksCounter
<< " blocks, "
<< commandsCounter
<< " commands."
<< std::endl;
logger.setMainStatistics(ss.str());
}
Parser& operator <<(std::string const &token) {
handler = handler->readToken(token);
++linesCounter;
return *this;
}
size_t getBufferSize() { return commands.size(); }
private:
class Handler; class Plain; class Block; class Nested;
using HandlerPtr = std::unique_ptr<Handler>;
class Handler {
public: virtual ~Handler() = default;
[[ nodiscard ]]
virtual HandlerPtr readToken(std::string const & token) = 0;
};
class Plain: public Handler {
public:
Plain(Parser &parser): parser(parser) { }
HandlerPtr readToken(std::string const & token) override {
if (token == "{") {
if (parser.getBufferSize() > 0) parser.flushCommands();
return HandlerPtr(new Block(parser));
}
else if (token == "}") {
throw InvalidToken(token);
} else {
parser.commands.push_back(token);
if (parser.getBufferSize() >= parser.packSize) parser.flushCommands();
}
return HandlerPtr(new Plain(parser));
}
private:
Parser &parser;
};
class Block: public Handler {
public:
Block(Parser &parser): parser(parser) { }
HandlerPtr readToken(std::string const & token) override {
if (token == "{") {
return HandlerPtr(new Nested(parser, 1));
} else if (token == "}") {
if (parser.getBufferSize() > 0) parser.flushCommands();
return HandlerPtr(new Plain(parser));
} else {
parser.commands.push_back(token);
}
return HandlerPtr(new Block(parser));
}
private:
Parser &parser;
};
class Nested: public Handler {
public:
Nested(Parser &parser, int level): parser(parser), level(level) { }
HandlerPtr readToken(std::string const & token) override {
if (token == "{") {
++level;
} else if (token == "}") {
--level;
if (level == 0) return HandlerPtr(new Block(parser));
} else {
parser.commands.push_back(token);
}
return HandlerPtr(new Nested(parser, level));
}
private:
Parser &parser;
int level;
};
HandlerPtr handler { new Plain(*this) };
std::size_t const packSize;
ILogger &logger;
std::vector<std::string> commands;
unsigned linesCounter { }, blocksCounter { }, commandsCounter { };
void flushCommands() {
std::stringstream stream { };
stream << "bulk: ";
for (size_t i { }; i < commands.size(); ++i) {
stream << commands[i];
if (i < commands.size() - 1) stream << ", ";
}
stream << std::endl;
logger.print(stream.str(), commands.size());
commandsCounter += commands.size();
++blocksCounter;
commands.clear();
}
};
}
#endif
| 25.506944 | 80 | 0.568473 | [
"vector"
] |
b7762660748ec856195b8c35deaf99fe8fe9ea7c | 21,144 | cpp | C++ | src/PIdFQLSocketServer/PIdFQLSocketServer.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | 1 | 2022-03-24T19:57:00.000Z | 2022-03-24T19:57:00.000Z | src/PIdFQLSocketServer/PIdFQLSocketServer.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | src/PIdFQLSocketServer/PIdFQLSocketServer.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.
// Copyright (c) 2006 by BBN Technologies, Inc.
// All Rights Reserved.
/*
This is the interface to the Active Learning functions that QuickLearn
uses. When this executable is called, a socket server starts up and
is ready to accept commands. A command is invoked by opening up a socket
to the server, sending in a command name and a list of parameters.
Commands have between 0 and 4 parameters.
*/
#include "Generic/common/leak_detection.h" //This must be the first #include
#include "Generic/names/discmodel/PIdFActiveLearning.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
void initializeWinsock();
void initializeListenSocket(SOCKET& sock, const char *port);
wstring getRetVal(bool ok, const char* txt);
void writeToSocket(SOCKET& sock, wstring wstr);
int getCommand(SOCKET& sock, char *command, int max_length);
int getIntParameter(SOCKET &sock);
bool getBoolParameter(SOCKET &sock);
wstring getStringParameter(SOCKET &sock);
int getNumber(SOCKET &sock);
wchar_t getNextUTF8Char(char * text, size_t & pos, size_t max_pos);
void makeUTF8CharArray(const wchar_t* input, char* output, size_t max_len);
int main(int argc, char **argv)
{
PIdFActiveLearning *_trainer = 0;
initializeWinsock();
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
printf ("This is PIdFQuickLearnServer v1.0\n");
printf ("Copyright (c) 2006 by BBN Technologies, Inc.\n\n");
if (argc != 2) {
printf ("PIdFQuickLearnServer.exe is invoked with a single argument - a port number\n");
return -1;
}
initializeListenSocket(ListenSocket, argv[1]);
bool close = false;
while (!close) {
printf ("\nWaiting for a connection...\n");
ClientSocket = accept(ListenSocket, NULL, NULL);
char command[100];
int rv = getCommand(ClientSocket, command, 99);
if (rv) {
printf ("Could not get command from socket. Returning error string.\n\n");
wstring returnString = getRetVal(false, "Could not get command");
writeToSocket(ClientSocket, returnString);
continue;
}
printf ("Received command: %s\n", command);
// The function to start the pIdF server
if (!strcmp(command, "StartPIdFService")) {
try {
if (_trainer != 0)
delete _trainer;
_trainer = _new PIdFActiveLearning();
writeToSocket(ClientSocket, getRetVal(true, "The service has been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
// The function to stop the pIdF server
/*else if (!strcmp(command, "StopPIdFService")) {
try {
if (_trainer != 0)
delete _trainer;
writeToSocket(ClientSocket, getRetVal(true, "The service has been stopped."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}*/
// The function to initialize a project
else if (!strcmp(command, "Initialize")) {
wstring param_path = getStringParameter(ClientSocket);
char *ch_string = new char[param_path.length() + 1];
size_t num_converted = 0;
wcstombs_s(&num_converted, ch_string, param_path.length() + 1, param_path.c_str(), param_path.length() + 1);
try {
if (_trainer != 0) {
wstring return_value = _trainer->Initialize(ch_string);
writeToSocket(ClientSocket, return_value);
}
else {
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
// The function to read the corpus file
else if (!strcmp(command, "ReadCorpus")) {
wstring corpus_file = getStringParameter(ClientSocket);
char *ch_string = new char[corpus_file.length() + 1];
size_t num_converted = 0;
wcstombs_s(&num_converted, ch_string, corpus_file.length() + 1, corpus_file.c_str(), corpus_file.length() + 1);
// check if file exists
ifstream inp;
inp.open(ch_string, ifstream::in);
inp.close();
if (inp.fail()) {
printf ("Could not open corpus file: %s. Returning error string.\n", ch_string);
writeToSocket(ClientSocket,
getRetVal(false, "Could not open corpus file"));
} else {
try {
if (_trainer != 0) {
wstring return_value = _trainer->ReadCorpus(ch_string);
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
}
// The function to read the corpus file
else if (!strcmp(command, "ReadDefaultCorpus")) {
try {
if (_trainer != 0) {
wstring return_value = _trainer->ReadCorpus();
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
// The function to train a model with the annotated sentences
else if (!strcmp(command, "Train")) {
//UTF8OutputStream file("C:/temp/out");
wstring ann_sents = getStringParameter(ClientSocket);
//file << ann_sents.c_str() << L"\n";
//file.close();
wstring token_sents = getStringParameter(ClientSocket);
int epochs = getIntParameter(ClientSocket);
bool isIncremental = getBoolParameter(ClientSocket);
try {
if (_trainer != 0) {
wstring return_value =
_trainer->Train(ann_sents.c_str(), ann_sents.length(),
token_sents.c_str(), token_sents.length(), epochs, isIncremental);
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
else if (!strcmp(command, "AddToTestSet")) {
wstring ann_sents = getStringParameter(ClientSocket);
wstring token_sents = getStringParameter(ClientSocket);
try {
if (_trainer != 0) {
wstring return_value =
_trainer->AddToTestSet(ann_sents.c_str(), ann_sents.length(),
token_sents.c_str(), token_sents.length());
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
// The function saves the training and the model files
else if (!strcmp(command, "Save")) {
try {
if (_trainer != 0) {
wstring return_value = _trainer->Save();
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
// The function saves the tokens for the passed sentences
else if (!strcmp(command, "SaveSentences")) {
wstring ann_sents = getStringParameter(ClientSocket);
wstring token_sents = getStringParameter(ClientSocket);
wstring tokens_file = getStringParameter(ClientSocket);
try {
if (_trainer != 0) {
wstring return_value =
_trainer->SaveSentences(ann_sents.c_str(), ann_sents.length(),
token_sents.c_str(), token_sents.length(),
tokens_file.c_str());
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
// The function returns the next sentence id in the corpus file
else if (!strcmp(command, "GetCorpusPointer")) {
try {
if (_trainer != 0) {
wstring return_value = _trainer->GetCorpusPointer();
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
// The function selects and returns new sentences to annotate.
else if (!strcmp(command, "SelectSentences")) {
int training_pool_size = getIntParameter(ClientSocket);
int num_to_select = getIntParameter(ClientSocket);
int context_size = getIntParameter(ClientSocket);
int min_positive_cases = getIntParameter(ClientSocket);
//printf("Got params: %d %d %d %d\n", training_pool_size, num_to_select, context_size, min_positive_cases);
try {
if (_trainer != 0) {
wstring return_value =
_trainer->SelectSentences(training_pool_size, num_to_select, context_size, min_positive_cases);
writeToSocket(ClientSocket, return_value);
//wprintf(L"returned: %s\n", return_value.c_str());
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
else if (!strcmp(command, "GetNextSentences")) {
int num_to_select = getIntParameter(ClientSocket);
int context_size = getIntParameter(ClientSocket);
//printf("Got params: %d %d %d %d\n", training_pool_size, num_to_select, context_size, min_positive_cases);
try {
if (_trainer != 0) {
wstring return_value =
_trainer->GetNextSentences(num_to_select, context_size);
writeToSocket(ClientSocket, return_value);
//wprintf(L"returned: %s\n", return_value.c_str());
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
// The function closes the current project
else if (!strcmp(command, "Close")) {
try {
if (_trainer != 0) {
//printf("before close call\n");
wstring return_value = _trainer->Close();
//printf("after close call\n");
writeToSocket(ClientSocket, return_value);
//printf("after write to socket\n");
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
// The function changes the corpus file to a new one
else if (!strcmp(command, "ChangeCorpus")) {
wstring corpus_path = getStringParameter(ClientSocket);
try {
if (_trainer != 0) {
char * buffer = _new char[1024];
wcstombs(buffer, corpus_path.c_str(), 1024);
wstring return_value = _trainer->ChangeCorpus(buffer);
delete buffer;
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
// The function returns model-decoded sentences
else if (!strcmp(command, "DecodeTraining")) {
wstring sentences = getStringParameter(ClientSocket);
try {
if (_trainer != 0) {
wstring return_value = _trainer->DecodeTraining(sentences.c_str(), sentences.length());
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
else if (!strcmp(command, "DecodeTestSet")) {
wstring sentences = getStringParameter(ClientSocket);
try {
if (_trainer != 0) {
wstring return_value = _trainer->DecodeTestSet(sentences.c_str(), sentences.length());
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
else if (!strcmp(command, "DecodeFromCorpus")) {
wstring sentences = getStringParameter(ClientSocket);
try {
if (_trainer != 0) {
wstring return_value = _trainer->DecodeFromCorpus(sentences.c_str(), sentences.length());
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
// The function returns model-decoded sentences
else if (!strcmp(command, "DecodeFile")) {
wstring input_file = getStringParameter(ClientSocket);
try {
if (_trainer != 0) {
//wprintf(L"Decoding file: %s\n", input_file.c_str());
wstring return_value = _trainer->DecodeFile(input_file.c_str());
//wprintf(L"Results: %s\n", return_value.c_str());
writeToSocket(ClientSocket, return_value);
}
else
writeToSocket(ClientSocket,
getRetVal(false, "The PIdF service has not been started."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
}
else if (!strcmp(command, "ShutdownPIdFServer")) {
try {
if (_trainer != 0)
delete _trainer;
writeToSocket(ClientSocket, getRetVal(true, "The service has been shutdown."));
}
catch (UnrecoverableException &e) {
writeToSocket(ClientSocket, getRetVal(false, e.getMessage()));
}
close = true;
}
else {
printf ("Unknown command: %s. Returning error string.\n\n", command);
wstring returnString = getRetVal(false, "Unknown command");
writeToSocket(ClientSocket, returnString);
}
closesocket(ClientSocket);
}
}
int getIntParameter(SOCKET &sock) {
wstring str = getStringParameter(sock);
return _wtoi(str.c_str());
}
bool getBoolParameter(SOCKET &sock) {
wstring str = getStringParameter(sock);
if (!wcscmp(str.c_str(), L"true")) {
return true;
}
else {
return false;
}
}
wstring getStringParameter(SOCKET &sock) {
int length = getNumber(sock);
if (length < 0) {
// error
return L"";
}
char *param = new char[length + 1];
char recvbuf[2];
int iResult;
int i;
for (i = 0; i < length; i++) {
iResult = recv(sock, recvbuf, 1, 0);
param[i] = recvbuf[0];
}
// get empty space
iResult = recv(sock, recvbuf, 1, 0);
param[i] = '\0';
//printf("Found param: %s\n", param);
size_t pos = 0;
int utf8_pointer = 0;
wchar_t *output = new wchar_t[length + 1];
while ((int)pos < length) {
output[utf8_pointer] = getNextUTF8Char(param, pos, length);
utf8_pointer++;
}
output[utf8_pointer] = L'\0';
delete param;
wstring rv(output);
delete [] output;
return rv;
}
int getNumber(SOCKET &sock)
{
char recvbuf[2];
char buffer[10];
int iResult;
char c;
int i = 0;
do {
// grab one character at a time until you see a space
iResult = recv(sock, recvbuf, 1, 0);
c = recvbuf[0];
if (i >= 9) {
return -1;
}
buffer[i++] = c;
} while (c != ' ');
buffer[i-1] = '\0';
return atoi(buffer);
}
int getCommand(SOCKET& sock, char *command, int max_length)
{
char recvbuf[2];
int iResult;
char c;
int i = 0;
do {
// grab one character at a time until you see a space
iResult = recv(sock, recvbuf, 1, 0);
c = recvbuf[0];
if (i >= max_length) {
return 1;
}
command[i++] = c;
} while (c != ' ');
command[i-1] = '\0';
return 0;
}
void initializeWinsock()
{
WSADATA wsaData;
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
exit(1);
}
}
void initializeListenSocket(SOCKET &sock, const char *port)
{
struct addrinfo *result = NULL,
hints;
int iResult;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, port, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
exit(1);
}
// Create a SOCKET for connecting to server
sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (sock == INVALID_SOCKET) {
printf("socket failed: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
exit(1);
}
// Setup the TCP listening socket
iResult = bind( sock, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(sock);
WSACleanup();
exit(1);
}
freeaddrinfo(result);
iResult = listen(sock, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
exit(1);
}
}
wstring getRetVal(bool ok, const char* txt){
wstring retval(L"<RETURN>\n");
if(strlen(txt) >999){
char errbuffer[1000];
strcpy_s(errbuffer, "Invalid Conversion, String too long\nFirst 900 characters: ");
strncat_s(errbuffer, txt, 900);
return getRetVal(false, errbuffer);
}
wchar_t conversionbuffer[1000];
size_t num_converted;
mbstowcs_s(&num_converted, conversionbuffer, txt, 1000);
if(ok){
retval +=L"\t<RETURN_CODE>OK</RETURN_CODE>\n";
}
else{
retval += L"\t<RETURN_CODE>ERROR</RETURN_CODE>\n";
}
retval +=L"\t<RETURN_VALUE>";
retval += conversionbuffer;
retval += L"</RETURN_VALUE>\n";
retval += L"</RETURN>";
return retval;
}
void writeToSocket(SOCKET& sock, wstring wstr)
{
size_t wchar_length = (wstr.length() + 1) * 3;
char *buffer = new char[wchar_length];
makeUTF8CharArray(wstr.c_str(), buffer, wchar_length);
char char_length[10];
_itoa_s((int)(strlen(buffer)), char_length, 9, 10);
send(sock, char_length, (int)(strlen(char_length)), 0);
send(sock, " ", 1, 0);
send(sock, buffer, (int)(strlen(buffer)), 0);
delete [] buffer;
}
wchar_t getNextUTF8Char(char * text, size_t & pos, size_t max_pos) {
unsigned char c[4];
unsigned char headMask1 = 0x1f;
unsigned char headMask2 = 0x0f;
unsigned char mask = 0x3f;
if (pos == max_pos)
return 0x0000;
c[0] = text[pos];
pos++;
int readSize = 0;
// check the lead byte to see how many more we should read in
if (c[0] >= 0xe0)
readSize = 2;
else if (c[0] >= 0xc0)
readSize = 1;
if (readSize > 0) {
if (pos == max_pos) {
char message[130];
strcpy_s(message, "Unexpected EOL in char stream! ");
return 0;
//throw UnexpectedInputException("SocketsClient::getNextUTF8Char()", message);
}
for (int i = 0; i < readSize; i++) {
c[i+1] = text[pos];
pos++;
}
}
wchar_t wc = 0x0000;
// 0xxxxxxx
if (readSize == 0) {
wc = c[0];
}
// 110xxxxx 10xxxxxx
else if (readSize == 1)
wc = ((headMask1 & c[0]) << 6) | (mask & c[1]);
// 1110xxxx 10xxxxxx 10xxxxxx
else if (readSize == 2)
wc = ((headMask2 & c[0]) << 12) | ((mask & c[1]) << 6) | (mask & c[2]);
return wc;
}
void makeUTF8CharArray(const wchar_t* input, char* output, size_t max_len)
{
size_t len = wcslen(input);
size_t i;
int pos = 0;
unsigned char c[4];
for(i = 0; i< len; i++){
// < 7f => 0xxxxxxx
unsigned char baseMask = 0x80;
unsigned char lowMask = 0x3f;
wchar_t ch = input[i];
if (ch <= 0x007f) {
c[0] = (char)ch;
output[pos++] = c[0];
}
// < 7ff => 110xxxxx 10xxxxxx
else if (ch <= 0x07ff) {
c[1] = (baseMask | (lowMask&((char) ch)));
c[0] = (0xc0 | ((char)(ch >> 6)));
output[pos++] = c[0];
output[pos++] = c[1];
}
// < ffff => 1110xxxx 10xxxxxx 10xxxxxx
else if (ch <= 0xffff) {
c[2] = (baseMask | (lowMask&((char) ch)));
c[1] = (baseMask | (lowMask&((char) (ch >> 6))));
c[0] = (0xe0 | ((char)(ch >> 12)));
output[pos++] = c[0];
output[pos++] = c[1];
output[pos++] = c[2];
}
if((pos + 4) > max_len){
break;
}
}
output[pos++] = '\0';
}
| 28.419355 | 115 | 0.641364 | [
"model"
] |
b77ec03ee156a577e12e011a804d52e97653cff8 | 6,547 | cpp | C++ | src/model/ModelMesh.cpp | JoaoBaptMG/INF443-Project | 8c43007a8092931b125cc7feae2adf162e04534e | [
"MIT"
] | 8 | 2020-06-09T00:43:39.000Z | 2021-09-27T13:55:46.000Z | src/model/ModelMesh.cpp | JoaoBaptMG/INF443-Project | 8c43007a8092931b125cc7feae2adf162e04534e | [
"MIT"
] | 1 | 2020-06-09T02:38:55.000Z | 2020-06-09T13:28:13.000Z | src/model/ModelMesh.cpp | JoaoBaptMG/INF443-Project | 8c43007a8092931b125cc7feae2adf162e04534e | [
"MIT"
] | 3 | 2020-06-09T00:28:11.000Z | 2020-12-30T08:07:34.000Z | #include "ModelMesh.hpp"
#include "Model.hpp"
#include "ModelUtils.hpp"
#include "resources/bufferUtils.hpp"
#include "wrappers/glParamFromType.hpp"
#include "assimpVectorTraits.hpp"
using namespace model;
ModelMesh::ModelMesh(const gl::Program& program, const aiMesh* mesh)
{
materialIndex = mesh->mMaterialIndex;
// Generate the vertex array
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
// generate the first attributes
positionBuffer = gl::createAndConfigureVertexArray(mesh->mVertices, mesh->mNumVertices,
program.getAttributeLocation("inPosition"));
normalBuffer = gl::createAndConfigureVertexArray(mesh->mNormals, mesh->mNumVertices,
program.getAttributeLocation("inNormal"));
// Now, generate the colors and texcoords
auto numColors = mesh->GetNumColorChannels();
colorBuffers.resize(numColors);
for (unsigned int i = 0; i < numColors; i++)
{
std::string name = "inColor[" + std::to_string(i) + ']';
colorBuffers[i] = gl::createAndConfigureVertexArray(mesh->mColors[i], mesh->mNumVertices,
program.getAttributeLocation(name.c_str()));
}
auto numTexcoords = mesh->GetNumUVChannels();
texcoordBuffers.resize(numTexcoords);
for (unsigned int i = 0; i < numTexcoords; i++)
{
std::string name = "inTexcoord[" + std::to_string(i) + ']';
texcoordBuffers[i] = gl::createAndConfigureVertexArray(mesh->mTextureCoords[i], mesh->mNumVertices,
program.getAttributeLocation(name.c_str()));
}
configureAnimationBones(mesh, program);
// Check the primitive type
elementBuffer = 0;
switch (mesh->mPrimitiveTypes)
{
case aiPrimitiveType_POINT: primitiveType = gl::PrimitiveType::Points; numElements = mesh->mNumFaces; break;
case aiPrimitiveType_LINE: primitiveType = gl::PrimitiveType::Lines; numElements = 2 * mesh->mNumFaces; break;
case aiPrimitiveType_TRIANGLE: primitiveType = gl::PrimitiveType::Triangles; numElements = 3 * mesh->mNumFaces; break;
default: throw ModelException("Unrecognized primitive type!");
}
// Build the element buffer
std::vector<unsigned int> elements;
elements.reserve(numElements);
for (unsigned int i = 0; i < mesh->mNumFaces; i++)
for (unsigned int j = 0; j < mesh->mFaces[i].mNumIndices; j++)
elements.push_back(mesh->mFaces[i].mIndices[j]);
elementBuffer = gl::createAndFillBuffer(elements, GL_ELEMENT_ARRAY_BUFFER);
// Unbind the vertex array
glBindVertexArray(0);
}
void model::ModelMesh::configureAnimationBones(const aiMesh* mesh, const gl::Program& program)
{
// Now, onwards to do the bone and the weight buffer
std::vector<glm::ivec4> bones(mesh->mNumVertices, glm::ivec4(-1, -1, -1, -1));
std::vector<glm::vec4> weights(mesh->mNumVertices, glm::vec4(0, 0, 0, 0));
// Attach names to the nodes
boneMatrices.resize(mesh->mNumBones);
boneNames.resize(mesh->mNumBones);
boneNodeIndices.resize(mesh->mNumBones);
for (unsigned int i = 0; i < mesh->mNumBones; i++)
{
auto bone = mesh->mBones[i];
boneMatrices[i] = toGlm(mesh->mBones[i]->mOffsetMatrix);
boneNames[i] = mesh->mBones[i]->mName.C_Str();
for (unsigned int j = 0; j < bone->mNumWeights; j++)
{
// Try to find an empty slot
auto idx = bone->mWeights[j].mVertexId;
float weight = bone->mWeights[j].mWeight;
for (unsigned int k = 0; k < 4; k++)
if (bones[idx][k] == -1)
{
bones[idx][k] = i;
weights[idx][k] = weight;
break;
}
}
}
// Fill the bone buffer with zeros
for (auto& bone : bones)
{
if (bone.x == -1) bone.x = 0;
if (bone.y == -1) bone.y = 0;
if (bone.z == -1) bone.z = 0;
if (bone.w == -1) bone.w = 0;
}
// Create the bone buffer
boneBuffer = gl::createAndConfigureVertexArrayInteger(bones, program.getAttributeLocation("inBoneIDs"));
weightBuffer = gl::createAndConfigureVertexArray(weights, program.getAttributeLocation("inBoneWeights"));
}
ModelMesh::~ModelMesh()
{
// Cleanup everything
glDeleteVertexArrays(1, &vertexArray);
glDeleteBuffers(1, &positionBuffer);
glDeleteBuffers(1, &normalBuffer);
glDeleteBuffers(colorBuffers.size(), colorBuffers.data());
glDeleteBuffers(texcoordBuffers.size(), texcoordBuffers.data());
glDeleteBuffers(1, &boneBuffer);
glDeleteBuffers(1, &weightBuffer);
glDeleteBuffers(1, &elementBuffer);
}
ModelMesh::ModelMesh(ModelMesh&& o) noexcept
: vertexArray(o.vertexArray), positionBuffer(o.positionBuffer), normalBuffer(o.normalBuffer),
colorBuffers(std::move(o.colorBuffers)), texcoordBuffers(std::move(o.texcoordBuffers)),
boneBuffer(o.boneBuffer), weightBuffer(o.weightBuffer), elementBuffer(o.elementBuffer),
numElements(o.numElements), primitiveType(o.primitiveType), materialIndex(o.materialIndex),
boneMatrices(std::move(o.boneMatrices)), boneNames(std::move(o.boneNames)), boneNodeIndices(std::move(o.boneNodeIndices))
{
o.vertexArray = 0;
o.positionBuffer = 0;
o.normalBuffer = 0;
o.boneBuffer = 0;
o.weightBuffer = 0;
o.elementBuffer = 0;
}
ModelMesh& ModelMesh::operator=(ModelMesh&& o) noexcept
{
using std::swap;
swap(vertexArray, o.vertexArray);
swap(positionBuffer, o.positionBuffer);
swap(normalBuffer, o.normalBuffer);
swap(colorBuffers, o.colorBuffers);
swap(texcoordBuffers, o.texcoordBuffers);
swap(boneBuffer, o.boneBuffer);
swap(weightBuffer, o.weightBuffer);
swap(elementBuffer, o.elementBuffer);
swap(numElements, o.numElements);
swap(primitiveType, o.primitiveType);
swap(materialIndex, o.materialIndex);
swap(boneMatrices, o.boneMatrices);
swap(boneNames, o.boneNames);
swap(boneNodeIndices, o.boneNodeIndices);
return *this;
}
void ModelMesh::draw(const glm::mat4& model) const
{
if (numElements == 0) return;
// Bind the vertex array
glBindVertexArray(vertexArray);
// Bind the vertex attribute
glVertexAttrib4fv(4, glm::value_ptr(model[0]));
glVertexAttrib4fv(5, glm::value_ptr(model[1]));
glVertexAttrib4fv(6, glm::value_ptr(model[2]));
glVertexAttrib4fv(7, glm::value_ptr(model[3]));
// Use the appropriate draw function
glDrawElements(static_cast<GLenum>(primitiveType), numElements, GL_UNSIGNED_INT, nullptr);
}
| 36.372222 | 125 | 0.670689 | [
"mesh",
"vector",
"model"
] |
b7800976cf09e965148322fb4ff006a94cc8b151 | 8,716 | cpp | C++ | cryptone_web/cryptone_web1/cryptone_web.cpp | oxfemale/cryptone_web | 3afa0db7bdad83e1ac4f8ff9ea356cdc5bb15fe1 | [
"Apache-2.0"
] | 5 | 2018-02-03T10:08:10.000Z | 2020-03-30T04:03:28.000Z | cryptone_web/cryptone_web1/cryptone_web.cpp | oxfemale/cryptone_web | 3afa0db7bdad83e1ac4f8ff9ea356cdc5bb15fe1 | [
"Apache-2.0"
] | null | null | null | cryptone_web/cryptone_web1/cryptone_web.cpp | oxfemale/cryptone_web | 3afa0db7bdad83e1ac4f8ff9ea356cdc5bb15fe1 | [
"Apache-2.0"
] | 2 | 2019-01-30T20:59:12.000Z | 2020-03-30T04:03:29.000Z | /*
twitter: @oxfemale
emails: root@eas7.ru or root@kitsune.online
telegram: https://t.me/BelousovaAlisa
*/
#include "stdafx.h"
#include "globalvars.h"
#include "cryptone_web.h"
#include "PacketFactory.h"
#include "SystemInfo.h"
#include "Container.h"
#include "AskPasswords.h"
#include "AskUsername.h"
#include "http.h"
#include "Randoms.h"
#include "UserRegistration.h"
#include "AddNewClient.h"
#include "ClientFunctions.h"
#include "ReadCfgFiles.h"
#include "KeysExchange.h"
#include "console.h"
#pragma comment (lib, "Wininet.lib")
int SetMenu()
{
ConsoleOutput(__FILE__, __FUNCTION__, __LINE__, "Begin.", 3);
char iSelect[2] = {0};
char* cLongLine = " ";
for (;;)
{
gotoxy(35, 35);
clear_screen(0, 0);
printf("[Default server is %s ]",gServername);
gotoxy(0, 1);
miniLogo();
printf("Menu for user [%s]:\r\n", gUsername);
printf("0 - Online subclients list. \t1 - Get all subclients list. \t2 - Set client alias.\r\n");
printf("3 - Delete old offline subclients.\r\n");
printf("4 - Upload File.\r\n");
printf("q - Exit from program.\r\n");
iSelect[0] = _getch();
if (iSelect[0] == '3')
{
printf("%c\r\n", iSelect[0]);
DeleteOldSubclients();
printf("press any key to continue... %s", cLongLine);
_getch();
continue;
}
if (iSelect[0] == '0')
{
printf("%c\r\n", iSelect[0]);
GetSubclientsListOnline();
printf("press any key to continue... %s", cLongLine);
_getch();
continue;
}
if (iSelect[0] == '1')
{
printf("%c\r\n", iSelect[0]);
GetSubclientsList();
printf("press any key to continue... %s", cLongLine);
_getch();
continue;
}
if (iSelect[0] == '2')
{
printf("%c\r\n", iSelect[0]);
SetSubclientsAlias();
printf("press any key to continue... %s", cLongLine);
_getch();
continue;
}
if ( iSelect[0] == 3 )
{
printf("\r\nCancel and exit.\r\n");
fclose(gLogFile);
return 0;
}
if (iSelect[0] == 26)
{
printf("\r\nCancel and exit.\r\n");
return 0;
}
if (iSelect[0] == 13)
{
printf("\r\nCancel and exit.\r\n");
fclose(gLogFile);
return 0;
}
if (iSelect[0] == 'q')
{
printf("%c\r\n", iSelect[0]);
printf("\r\nExit.\r\n");
fclose(gLogFile);
return 0;
}
printf("\r\n");
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
char* cryptone = "cryptone.dll";
hModuleCRYPT = NULL;
unsigned char* strPwd = NULL;
FILE* pFile = NULL;
char* Servername = NULL;
gAESkey = NULL;
gAESVector = NULL;
gUseridhash = NULL;
gUsername = NULL;
gServerPassword = NULL;
gLogFile = fopen("logfile.txt", "ab");
clear_screen(0,0);
ConsoleOutput(__FILE__, __FUNCTION__, __LINE__, "Start client.", 0);
gotoxy(0,2);
LogoPrint();
hModuleCRYPT = LoadLibraryA(cryptone);
if (hModuleCRYPT == NULL)
{
printf("Error[%d] load [%s] dll\r\n", GetLastError(), cryptone);
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Load library cryptone.dll error.", 1);
return 0;
}
if (SetDefaultAESVector() == 0)
{
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Error set default aes vector.", 1);
return 0;
}
if (ServersList() == 0)
{
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Error set default servername.", 1);
return 0;
}
Servername = gServername;
if( doPingServer(Servername) == 1 )
{
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Server is Alive.", 0);
bestType = SelectBestHttpTraffic(Servername);
}else
{
printf("Server is Down.\r\n");
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Server is Down.", 1);
return 0;
}
pFile = fopen("file.cfg", "rb");
if(pFile != NULL)
{
fclose(pFile);
FILE* pasFile = NULL;
pasFile = fopen("pass.cfg", "rb");
if(pasFile == NULL)
{
strPwd = (unsigned char*)AskContainerPassword( NULL );
if (strPwd == NULL)
{
fclose(gLogFile);
return 0;
}
}else{
strPwd = (unsigned char*)VirtualAlloc( NULL, 32, MEM_COMMIT, PAGE_READWRITE );
if( strPwd == NULL )
{
fclose(pFile);
fclose(pasFile);
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Error VirtualAlloc for password buffer.", 1);
fclose(gLogFile);
return 0;
}
memset( strPwd, '-', 32 );
fread( strPwd, 1, 32, pasFile);
fclose(pasFile);
}
if( IsContainer() == 1 )
{
if( TestCfgVars( strPwd ) == 0 )
{
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Error test Container vars. Container keys is deleted, please, goto login/register again.", 1);
remove( "file.cfg" );
fclose(gLogFile);
return 0;
}
if ( isRegUser( strPwd ) == 0 )
{
remove( "file.cfg" );
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Not reggged user. Container keys is deleted, please, goto login/register again.", 1);
fclose(gLogFile);
return 0;
}else{
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Found reggged user.", 0);
SetKeysMem(strPwd);
ClientPingServer();
HANDLE hPingThread = CreateThread(0, 0, &MainThreadPing, 0, 0, 0);
if (hPingThread == NULL)
{
printf("Error Start ping server.\r\n");
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Start thread ping server error.", 1);
fclose(gLogFile);
return 0;
}
CloseHandle(hPingThread);
HANDLE hKeysThread = CreateThread(0, 0, &MainThreadKeysExchange, strPwd, 0, 0);
if (hPingThread == NULL)
{
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Start Client/Server Keys Exchange thread error.", 1);
fclose(gLogFile);
return 0;
}
CloseHandle(hKeysThread);
SetMenu();
fclose(gLogFile);
return 1;
}
}else{
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Container password is wrong or container file is bad.", 1);
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Delete file.cfg if not remebers container password.", 1);
fclose(gLogFile);
return 0;
}
}else
{
if ( NewUserRegistration( Servername ) == 0 )
{
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Registration error.", 1);
remove("file.cfg");
fclose(gLogFile);
return 0;
}else
{
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Registration Ok, cfg file container crypted.", 0);
strPwd = (unsigned char*)AskContainerPassword("Please, enter container password again ");
if (strPwd == NULL)
{
ConsoleOutput(__FILE__, __FUNCTION__, __LINE__, "Container password is NULL.", 1);
fclose(gLogFile);
return 0;
}
SetKeysMem(strPwd);
ClientPingServer();
HANDLE hPingThread = CreateThread(0, 0, &MainThreadPing, 0, 0, 0);
if (hPingThread == NULL)
{
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Start thread ping server error.", 1);
fclose(gLogFile);
return 0;
}
CloseHandle(hPingThread);
HANDLE hKeysThread = CreateThread(0, 0, &MainThreadKeysExchange, strPwd, 0, 0);
if (hPingThread == NULL)
{
ConsoleOutput(__FILE__,__FUNCTION__, __LINE__, "Start Client/Server Keys Exchange thread error.", 1);
fclose(gLogFile);
return 0;
}
CloseHandle(hKeysThread);
SetMenu();
fclose(gLogFile);
return 1;
}
VirtualFree( strPwd, 0, MEM_RELEASE );
}
fclose(gLogFile);
return 0;
}
| 29.445946 | 147 | 0.526962 | [
"vector"
] |
b7848514fddc297149cb2489f4e1c62f9896a898 | 3,700 | cpp | C++ | test/obfuscation-e2e/ProguardFieldObfuscationTest.cpp | parind/redex | a919919298f45e7ff33f03be7f819dc04e533182 | [
"MIT"
] | null | null | null | test/obfuscation-e2e/ProguardFieldObfuscationTest.cpp | parind/redex | a919919298f45e7ff33f03be7f819dc04e533182 | [
"MIT"
] | null | null | null | test/obfuscation-e2e/ProguardFieldObfuscationTest.cpp | parind/redex | a919919298f45e7ff33f03be7f819dc04e533182 | [
"MIT"
] | null | null | null | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <cstdint>
#include <cstdlib>
#include <gtest/gtest.h>
#include <iostream>
#include <memory>
#include <string>
#include <array>
#include "DexClass.h"
#include "DexLoader.h"
#include "Match.h"
#include "ProguardConfiguration.h"
#include "ProguardMap.h"
#include "ProguardMatcher.h"
#include "ProguardObfuscationTest.h"
#include "ProguardParser.h"
#include "ReachableClasses.h"
#include "RedexTest.h"
void testClass(
ProguardObfuscationTest* tester,
const std::string& class_name,
const std::vector<std::string>& fields,
bool expects_found = false) {
auto clazz = tester->find_class_named(class_name);
ASSERT_NE(nullptr, clazz) << class_name << " not found.";
for (const std::string &fieldName : fields) {
ASSERT_EQ(expects_found, tester->field_found(
clazz->get_ifields(),
class_name + fieldName)) << class_name + fieldName << (expects_found ? "" : " not") << " obfuscated";
}
}
class ProguardFieldObfuscationTest : public RedexTest {};
/**
* Check renaming has been properly applied.
*/
TEST_F(ProguardFieldObfuscationTest, obfuscation) {
const char* dexfile = std::getenv("pg_config_e2e_dexfile");
const char* mapping_file = std::getenv("pg_config_e2e_mapping");
const char* configuration_file = std::getenv("pg_config_e2e_pgconfig");
const char* refl_strategy = std::getenv("reflection_strategy");
ASSERT_NE(nullptr, dexfile);
ASSERT_NE(nullptr, configuration_file);
ASSERT_NE(nullptr, refl_strategy);
ProguardObfuscationTest tester(dexfile, mapping_file);
ASSERT_TRUE(tester.configure_proguard(configuration_file))
<< "Proguard configuration failed";
// Make sure the fields class Alpha are renamed.
std::vector<std::string> reflectedNames = {
".reflected1:I",
".reflected2:I",
".reflected3:I",
".reflected4:J",
".reflected5:Ljava/lang/Object;"
};
std::vector<std::string> alphaNames = {
".wombat:I",
".numbat:I",
".reflected6:I",
".omega:Ljava/lang/String;",
".theta:Ljava/util/List;"};
if (!strcmp(refl_strategy, "rename")) {
alphaNames.insert(alphaNames.end(), reflectedNames.begin(), reflectedNames.end());
} else {
// Ensure reflectedNames are NOT renamed
testClass(&tester,
"Lcom/facebook/redex/test/proguard/Alpha;",
reflectedNames,
true);
}
const std::vector<std::string> helloNames = {
".hello:Ljava/lang/String;" };
const std::vector<std::string> worldNames = {
".world:Ljava/lang/String;" };
testClass(&tester,
"Lcom/facebook/redex/test/proguard/Alpha;",
alphaNames);
testClass(&tester,
"Lcom/facebook/redex/test/proguard/Hello;",
helloNames);
testClass(&tester,
"Lcom/facebook/redex/test/proguard/World;",
worldNames);
// Because of the all() call in Beta, there should be refs created in the
// bytecode of all() to All.hello and All.world which should be updated
// to Hello.[renamed] and World.[renamed]
ASSERT_FALSE(tester.refs_to_field_found(helloNames[0]))
<< "Refs to " << helloNames[0] << " not properly modified";
ASSERT_FALSE(tester.refs_to_field_found(worldNames[0]))
<< "Refs to " << worldNames[0] << " not properly modified";
// Make sure the fields in the class Beta are not renamed.
auto beta = tester.find_class_named(
"Lcom/facebook/redex/test/proguard/Beta;");
ASSERT_NE(nullptr, beta);
ASSERT_TRUE(tester.field_found(
beta->get_ifields(),
"Lcom/facebook/redex/test/proguard/Beta;.wombatBeta:I"));
}
| 32.743363 | 109 | 0.693514 | [
"object",
"vector"
] |
b786a02e7e7c59c37958b782fbae3992b0011cb5 | 9,780 | cc | C++ | src/utils/api_c/windows_api.cc | SxLewandowski/pmdk-tests | eb58fb8e7d4471b8958f1ead8874e41341df1005 | [
"BSD-3-Clause"
] | null | null | null | src/utils/api_c/windows_api.cc | SxLewandowski/pmdk-tests | eb58fb8e7d4471b8958f1ead8874e41341df1005 | [
"BSD-3-Clause"
] | null | null | null | src/utils/api_c/windows_api.cc | SxLewandowski/pmdk-tests | eb58fb8e7d4471b8958f1ead8874e41341df1005 | [
"BSD-3-Clause"
] | 1 | 2019-01-29T12:18:36.000Z | 2019-01-29T12:18:36.000Z | /*
* Copyright 2017-2018, Intel Corporation
*
* 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
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef _WIN32
#include <windows.h>
#include <codecvt>
#include <fstream>
#include <locale>
#include <sstream>
#include "api_c.h"
int ApiC::AllocateFileSpace(const std::string &path, size_t length) {
if (length < 0) {
std::cerr << "length should be >= 0" << std::endl;
return -1;
}
HANDLE h = CreateFile(path.c_str(), GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, CREATE_NEW,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
std::cerr << "INVALID_HANDLE_VALUE occurs\nError message: "
<< GetLastError() << std::endl;
return -1;
}
/* check if sparse files are supported */
DWORD flags = 0;
BOOL ret = GetVolumeInformationByHandleW(h, nullptr, 0, nullptr, nullptr,
&flags, nullptr, 0);
if (!ret) {
std::cerr << "GetVolumeInformationByHandleW: ";
goto err;
} else if ((flags & FILE_SUPPORTS_SPARSE_FILES) == 0) {
std::cerr << "Filesystem does not support sparse files" << std::endl;
goto err;
}
/* mark file as sparse */
DWORD nbytes;
ret = DeviceIoControl(h, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &nbytes,
nullptr);
if (!ret) {
std::cerr << "DeviceIoControl: ";
goto err;
}
/* set file length */
LARGE_INTEGER llen;
llen.QuadPart = length;
DWORD ptr = SetFilePointerEx(h, llen, nullptr, FILE_BEGIN);
if (ptr == INVALID_SET_FILE_POINTER) {
std::cerr << "SetFilePointerEx: ";
goto err;
}
ret = SetEndOfFile(h);
if (!ret) {
std::cerr << "SetEndOfFile: ";
goto err;
}
return 0;
err:
std::cerr << GetLastError() << std::endl;
CloseHandle(h);
std::remove(path.c_str());
return -1;
}
int ApiC::GetExecutableDirectory(std::string &path) {
char file_path[MAX_PATH + 1] = {0};
auto count = GetModuleFileName(nullptr, file_path, MAX_PATH);
if (count == 0 || count == MAX_PATH) {
return -1;
}
file_path[count] = '\0';
char dir[MAX_PATH + 1] = {0};
_splitpath(file_path, nullptr, dir, nullptr, nullptr);
path = std::string{dir} + "\\";
return 0;
}
long long ApiC::GetFreeSpaceT(const std::string &path) {
__int64 free_bytes_available, total_number_of_bytes,
total_number_of_free_bytes;
LPCSTR drive = path.c_str();
int result =
GetDiskFreeSpaceExA(drive, (PULARGE_INTEGER)&free_bytes_available,
(PULARGE_INTEGER)&total_number_of_bytes,
(PULARGE_INTEGER)&total_number_of_free_bytes);
if (result == 0) {
std::cerr << "Unable to get file system statistics: " << GetLastError()
<< std::endl;
return -1;
}
return total_number_of_free_bytes;
}
int ApiC::CreateDirectoryT(const std::string &path) {
BOOL ret = CreateDirectory(path.c_str(), nullptr);
if (ret) {
return 0;
}
std::cerr << "Unable to create directory: " << GetLastError() << std::endl;
return -1;
}
int ApiC::CleanDirectory(const std::string &path) {
int ret = 0;
HANDLE h = nullptr;
WIN32_FIND_DATA f_d;
h = FindFirstFile((path + "*").c_str(), &f_d);
if (h == INVALID_HANDLE_VALUE) {
std::cerr << "INVALID_HANDLE_VALUE occurs\nError message: "
<< GetLastError() << std::endl;
return -1;
}
do {
const std::string file_name = f_d.cFileName;
const std::string full_file_name = path + file_name;
if (!lstrcmp(f_d.cFileName, ".") || !lstrcmp(f_d.cFileName, "..")) {
continue;
}
SetFilePermission(path + f_d.cFileName, 0600);
if (DirectoryExists(path + f_d.cFileName) &&
!RemoveDirectory((path + f_d.cFileName).c_str())) {
std::cerr << "Unable to remove directory: " << GetLastError()
<< std::endl;
ret = -1;
} else if (RemoveFile(path + f_d.cFileName) != 0) {
std::cerr << "File " << f_d.cFileName << " removing failed" << std::endl;
ret = -1;
}
} while (FindNextFile(h, &f_d));
if (h != INVALID_HANDLE_VALUE && !FindClose(h)) {
std::cerr << "Closing dir failed: " << GetLastError() << std::endl;
return -1;
}
return ret;
}
int ApiC::RemoveDirectoryT(const std::string &path) {
BOOL ret = RemoveDirectory(path.c_str());
if (!ret) {
std::cerr << "Unable to remove directory: " << GetLastError() << std::endl;
return -1;
}
return 0;
}
int ApiC::SetEnv(const std::string &name, const std::string &value) {
return _putenv_s(name.c_str(), value.c_str());
}
int ApiC::UnsetEnv(const std::string &name) {
return _putenv_s(name.c_str(), "");
}
int ApiC::CreateFileT(const std::wstring &path, const std::wstring &content,
bool is_bom) {
std::locale utf8_locale;
if (is_bom) {
utf8_locale = std::locale(
std::locale(),
new std::codecvt_utf8<wchar_t, 0x10ffff,
std::codecvt_mode::generate_header>());
} else {
utf8_locale =
std::locale(std::locale(),
new std::codecvt_utf8<wchar_t, 0x10ffff,
std::codecvt_mode::consume_header>());
}
std::wofstream file{path, std::ios::out | std::ios::trunc};
file.imbue(utf8_locale);
if (!file.good()) {
std::wcerr << "File opening failed" << std::endl;
return -1;
}
file << content;
return 0;
}
int ApiC::CreateFileT(const std::wstring &path,
const std::vector<std::wstring> &content, bool is_bom) {
std::wstring temp_content;
for (const auto &line : content) {
temp_content += line + L"\r\n";
}
return CreateFileT(path, temp_content, is_bom);
}
int ApiC::ReadFile(const std::wstring &path, std::wstring &content) {
std::wifstream file{path, std::ios::binary | std::ios::ate};
if (!file.good()) {
std::wcerr << L"File opening failed" << std::endl;
return -1;
}
std::wstring line;
while (std::getline(file, line)) {
content += line;
}
return 0;
}
bool ApiC::RegularFileExists(const std::wstring &path) {
struct _stat64 file_stat;
int result = _wstat64(path.c_str(), &file_stat);
if (result != 0) {
if (errno != ENOENT) {
std::wcerr << L"Unexpected error in _wstat. Errno: " << _wcserror(errno)
<< std::endl;
}
return false;
}
return (file_stat.st_mode & S_IFREG) != 0;
}
unsigned short ApiC::GetFilePermission(const std::wstring &file) {
struct _stat64 file_stat;
int result = _wstat64(file.c_str(), &file_stat);
if (result != 0) {
std::wcerr << L"Unable to change file permission: " << _wcserror(errno)
<< std::endl;
return 0;
}
return file_stat.st_mode & PERMISSION_MASK;
}
int ApiC::SetFilePermission(const std::wstring &path, int permission) {
int ret = _wchmod(path.c_str(), permission);
if (ret != 0) {
std::wcerr << L"Unable to change file permission: " << _wcserror(errno)
<< std::endl;
}
return ret;
}
int ApiC::RemoveFile(const std::wstring &path) {
int ret = _wremove(path.c_str());
if (ret != 0) {
std::wcerr << L"The file cannot be deleted: " << _wcserror(errno)
<< std::endl;
}
return ret;
}
bool ApiC::DirectoryExists(const std::wstring &dir) {
struct _stat64 file_stat;
int result = _wstat64(dir.c_str(), &file_stat);
if (result != 0) {
if (errno != ENOENT) {
std::wcerr << L"Unexpected error in _wstat. Errno: " << _wcserror(errno)
<< std::endl;
}
return false;
}
return (file_stat.st_mode & S_IFDIR) != 0;
}
long long ApiC::GetFreeSpaceT(const std::wstring &dir) {
LARGE_INTEGER free_bytes_available, total_number_of_bytes,
total_number_of_free_bytes;
LPCWSTR drive = dir.c_str();
BOOL result =
GetDiskFreeSpaceExW(drive, (PULARGE_INTEGER)&free_bytes_available,
(PULARGE_INTEGER)&total_number_of_bytes,
(PULARGE_INTEGER)&total_number_of_free_bytes);
if (!result) {
std::wcerr << L"Unable to get file system statistics: " << GetLastError()
<< std::endl;
return -1;
}
return total_number_of_free_bytes.QuadPart;
}
#endif // !_WIN32
| 27.47191 | 80 | 0.628937 | [
"vector"
] |
b7923278e6cc142d9aa78a6cae26100bdc0b9466 | 12,241 | hxx | C++ | src/USRPCtrl.hxx | kb1vc/SoDaRadio | 0a41fa3d795b1c93795ad62ad17bf2de5f60a752 | [
"BSD-2-Clause"
] | 14 | 2017-10-27T16:01:05.000Z | 2021-03-16T08:12:42.000Z | src/USRPCtrl.hxx | dd0vs/SoDaRadio | 0a41fa3d795b1c93795ad62ad17bf2de5f60a752 | [
"BSD-2-Clause"
] | 11 | 2017-09-16T03:13:11.000Z | 2020-12-11T09:11:35.000Z | src/USRPCtrl.hxx | dd0vs/SoDaRadio | 0a41fa3d795b1c93795ad62ad17bf2de5f60a752 | [
"BSD-2-Clause"
] | 6 | 2017-09-13T12:47:43.000Z | 2020-12-02T20:54:25.000Z | /*
Copyright (c) 2012, Matthew H. Reilly (kb1vc)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
///
/// @file USRPCtrl.hxx
/// @brief Thread class that owns the USRP control channel and functions
///
///
/// @author M. H. Reilly (kb1vc)
/// @date July 2013
///
#ifndef USRPCTRL_HDR
#define USRPCTRL_HDR
#include "SoDaBase.hxx"
#include "SoDaThread.hxx"
#include "MultiMBox.hxx"
#include "Command.hxx"
#include "Params.hxx"
#include "TRControl.hxx"
#include "PropTree.hxx"
#include <uhd/version.hpp>
#if UHD_VERSION < 3110000
# include <uhd/utils/msg.hpp>
# include <uhd/utils/thread_priority.hpp>
#else
# include <uhd/utils/thread.hpp>
#endif
#include <uhd/utils/safe_main.hpp>
#include <uhd/usrp/multi_usrp.hpp>
#include <uhd/usrp/dboard_base.hpp>
#include <uhd/types/tune_request.hpp>
#include <uhd/types/tune_result.hpp>
namespace SoDa {
/// @class USRPCtrl
///
/// Though libuhd is designed to be re-entrant, there are some indications
/// that all control functions (set_freq, gain, and other operations)
/// should originate from a single thread. USRPCtrl does that.
///
/// USRPCtrl listens on the Command Stream message channel for
/// requests from other components (including the SoDa::UI listener)
/// and dumps status and completion reports back onto
/// the command stream channel.
class USRPCtrl : public SoDa::Thread {
public:
/// Constructor
/// Build a USRPCtrl thread
/// @param params Pointer to a parameter object with all the initial settings
/// and identification for the attached USRP
USRPCtrl(Params * params);
/// start the thread
void run();
/// return a pointer to the multi_usrp object -- used by
/// RX and TX processes to find the associated USRP widget.
/// @return a pointer to the USRP radio object
uhd::usrp::multi_usrp::sptr getUSRP() { return usrp; }
/// implement the subscription method
void subscribeToMailBox(const std::string & mbox_name, BaseMBox * mbox_p);
#if UHD_VERSION < 3110000
/// This is the more permanent message handler used before the elimination of the msg class
static void normal_message_handler(uhd::msg::type_t type, const std::string & msg);
#endif
/// This is a singleton object -- the last (and only, we hope) such object
/// to be created sets a static pointer to itself. This looks pretty gross, but
/// it is necessary to provide context to the error message handlers.
static SoDa::USRPCtrl * singleton_ctrl_obj;
private:
Params * params;
/// The B200 and B210 need some special handling, as they
/// don't have frontend lock indications (as of 3.7.0)
/// and need a special sample rate.
bool is_B2xx;
bool is_B210; ///< the B210 has two tx channels -- use the second for a Transverter LO -- see USRPLO
/// Parse an incoming command and dispatch.
/// @param cmd a command record
void execCommand(Command * cmd);
/// Dispatch an incoming GET command
/// @param cmd a command record
void execGetCommand(Command * cmd);
/// Dispatch an incoming SET command
/// @param cmd a command record
void execSetCommand(Command * cmd);
/// Dispatch an incoming REPort command
/// @param cmd a command record
void execRepCommand(Command * cmd);
/// get the number of seconds since the "Epoch"
/// @return relative time in seconds
double getTime();
/// is the identified (rx or tx) front-end LO locked?
/// If not, set the tuning frequency to "the right thing"
/// @param req the requested frequency (and tuning discipline)
/// @param sel 'r' for RX LO, 't' for TX LO
/// @param cur tuning result, if the LO was locked.
uhd::tune_result_t checkLock(uhd::tune_request_t & req,
char sel,
uhd::tune_result_t & cur);
/**
* report the antennas that are available, send the report on cmd_stream
*/
void reportAntennas();
/**
* report the modulation modes that are implemented, send the report on cmd_stream
*/
void reportModes();
/**
* report the audio filters that are implemented, send the report on cmd_stream
*/
void reportAFFilters();
/**
* Set the antenna choice. Use "ant" if it is in the list
* of alternatives. Otherwise, choose the first alternative.
* @param ant the requested antenna
* @param sel 'r' for RX, 't' for TX
*/
void setAntenna(const std::string & ant, char sel);
/// Set the front-end (LO + DDS) frequency to 'freq'
/// This includes setting the PLL front end synthesizer
/// as well as the FPGA resident digital synthesizer.
/// @param freq target frequency (LO and DDS combined)
/// @param sel 'r' for RX LO, 't' for TX LO
/// @param set_if_freq if TRUE, tell the USRPRX thread to reset
/// its front-end frequency so that it can adjust its own oscillator.
void set1stLOFreq(double freq, char sel, bool set_if_freq = false);
CmdMBox * cmd_stream; ///< command stream channel
unsigned int subid; ///< subscriber ID for this thread's connection to the command channel
// USRP stuff.
uhd::usrp::multi_usrp::sptr usrp; ///< to which USRP unit is this connected?
uhd::usrp::dboard_iface::sptr dboard; ///< the daughterboard we're controlling
// need this for TX/RX enable.
SoDa::PropTree * tx_fe_subtree; ///< property tree from daughtercard module
// need this for TX/RX enable.
SoDa::PropTree * rx_fe_subtree; ///< property tree from daughtercard module
// what controls and widgets do we have for the two front-ends?
bool tx_fe_has_enable; ///< can we access tx_fe_subtree/enabled ?
bool rx_fe_has_enable; ///< can we access rx_fe_subtree/enabled ?
bool tx_has_lo_locked_sensor; ///< does the tx frond end have an lo_locked sensor?
bool rx_has_lo_locked_sensor; ///< does the rx frond end have an lo_locked sensor?
// Capability Flags --
bool supports_tx_gpio; ///< does this unit support GPIO signals? (B2xx does not as of 3.7.0)
// parallel IO to turn on RX ena and TX ena
// specific to WBX right now.
/// Initialize the GPIO control registers to set the
/// direction and enables for the TX/RX relay output and sense input
void initControlGPIO();
/// get the state of the TXEna bit
/// @return true if the TX relay is activated.
bool getTXEna();
/// get the state of the TX relay confirm bit
/// @return true if the TX relay sense input is asserted
bool getTXRelayOn();
/// turn TX on/off
/// @param val true to enable the transmitter, false otherwise.
void setTXEna(bool val);
/// set TX enable property on front-end module -- not present in all
/// daughtercards...
/// @param val true to enable transmitter front end, false otherwise.
void setTXFrontEndEnable(bool val);
/// set the transverter LO frequency and power
/// This code does not work for libUHD after 3.7 -- it may not work for the older versions either.;(
void setTransverterLOFreqPower(double freq, double power);
void enableTransverterLO();
void disableTransverterLO();
/// we use TX_IO bit 12 to turn on the TX relay
/// we use TX_IO bit 11 to monitor the TX relay
static const unsigned int TX_RELAY_CTL; ///< mask for RELAY control bit
static const unsigned int TX_RELAY_MON; ///< mask for RELAY sense bit
uhd::tune_result_t last_rx_tune_result; ///< RX tune result -- actual LO and DSP freq
uhd::tune_result_t last_tx_tune_result; ///< TX tune result
uhd::tune_result_t saved_rx_tune_result; ///< previous RX tune result -- used for transverter LO "calibration" function
double first_gettime; ///< timestamps are relative to the first timestamp.
// gain settings
double rx_rf_gain; ///< rf gain for RX front end amp/attenuator
double tx_rf_gain; ///< rf gain for final TX amp
uhd::gain_range_t rx_rf_gain_range; ///< property of the device -- what is the min/maximum RX gain setting?
uhd::gain_range_t tx_rf_gain_range; ///< property of the device -- what is the min/maximum TX gain setting?
uhd::freq_range_t rx_rf_freq_range; ///< property of the device -- what is the min/maximum RX frequency?
uhd::freq_range_t tx_rf_freq_range; ///< property of the device -- what is the min/maximum TX frequency?
// state of the box
bool tx_on; ///< if true, we are transmitting.
double last_rx_req_freq; ///< remember the last setting -- useful for "calibration check"
// we horse the TX tuning around when we switch to RX
// to move the transmit birdie out of band.
double tx_freq; ///< remember current tx freq
double tx_freq_rxmode_offset; ///< when in RX mode, move tx off frequency to put the tx birdie out of band, when in TX mode, this is 0
static const double rxmode_offset; ///< tx offset when in RX mode
double tx_samp_rate; ///< sample rate to USRP TX chain.
std::string tx_ant; ///< TX antenna choice (usually has to be TX or TX/RX1?
std::string motherboard_name; ///< The model name of the USRP unit
// transverter local oscillator support.
bool tvrt_lo_capable; ///< if true, this unit can implement a local transverter oscillator.
bool tvrt_lo_mode; ///< if true, set the transmit frequency, with some knowledge of the tvrt LO.
double tvrt_lo_gain; ///< output power for the second transmit channel (used for transverter LO)
double tvrt_lo_freq; ///< the frequency of the second transmit channel oscillator
double tvrt_lo_fe_freq; ///< the frequency of the second transmit channel front-end oscillator
// enables verbose messages
bool debug_mode; ///< print stuff when we are in debug mode
// integer tuning mode is helped by a map of LO capabilities.
/// @brief applyTargetFreqCorrection adjusts the requested frequency,
/// if necessary, to avoid a birdie caused by a multiple of the step
/// size within the passband. It will also adjust the stepsize.
/// @param target_freq -- target tuning frequency
/// @param avoid_freq -- the frequency that we must avoid by at least 1MHz
/// @param tune_req -- tune request record.
void applyTargetFreqCorrection(double target_freq,
double avoid_freq,
uhd::tune_request_t * tune_req);
/// @brief Test for support for integer-N synthesis
/// @param force_int_N force LO tuning to use integer-N synthesis
/// @param force_frac_N force LO tuning to use fractional-N synthesis
void testIntNMode(bool force_int_N, bool force_frac_N);
bool supports_IntN_Mode; ///< if true, this unit can tune the front-end LO
///< in integer-N mode (as opposed to fractional-N)
///< to improve rejection of spurious signals and
///< drop the noise floor a bit.
/// external control widget for TR switching and other things.
SoDa::TRControl * tr_control;
};
}
#endif
| 41.077181 | 138 | 0.698554 | [
"object",
"model"
] |
b79889221fffb3be00209b09fb7a6104e1a50479 | 14,547 | cpp | C++ | src/poly.cpp | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | null | null | null | src/poly.cpp | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | 3 | 2019-09-10T03:50:40.000Z | 2019-09-23T04:20:14.000Z | src/poly.cpp | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | 1 | 2021-10-02T14:16:28.000Z | 2021-10-02T14:16:28.000Z | // Copyright (c) 1997 Bryan Aamot
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <math.h>
#include <string.h>
#include "stdafx.h"
#include "dle-xp.h"
#include "dlcDoc.h"
#include "mineview.h"
#include "define.h"
#include "types.h"
#include "global.h"
#include "poly.h"
#include "cfile.h"
/*
extern HPEN hPenRed, hPenDkRed, hPenGreen, hPenDkGreen, hPenBlue, hPenCyan, hPenDkCyan,
hPenMagenta, hPenYellow, hPenDkYellow, hPenOrange, hPenGold, hPenGray,
hPenLtGray;
extern HRGN hrgnBackground, hrgnLowerBar, hrgnTopBar, hrgnAll;
*/
//-----------------------------------------------------------------------
// CONSTANTS
//-----------------------------------------------------------------------
#define OP_EOF 0 /* eof */
#define OP_DEFPOINTS 1 /* defpoints (not used) */
#define OP_FLATPOLY 2 /* flat-shaded polygon */
#define OP_TMAPPOLY 3 /* texture-mapped polygon */
#define OP_SORTNORM 4 /* sort by normal */
#define OP_RODBM 5 /* rod bitmap (not used) */
#define OP_SUBCALL 6 /* call a subobject */
#define OP_DEFP_START 7 /* defpoints with start */
#define OP_GLOW 8 /* m_info.glow value for next poly */
#define MAX_INTERP_COLORS 100
#define MAX_POINTS_PER_POLY 25
//-----------------------------------------------------------------------
// MACROS
//-----------------------------------------------------------------------
#define W(p) (*((short *) (p)))
#define WP(p) ((short *) (p))
#define VP(p) ((CFixVector*) (p))
#define calcNormal(a, b)
#define glNormal3fv(a)
#define glColor3ub(a, b, c)
#define glBegin(a)
#define glVertex3i(x, y, z)
#define glEnd()
#define glTexCoord2fv(a)
#define UINTW int
//-----------------------------------------------------------------------
// local prototypes
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// globals
//-----------------------------------------------------------------------
static CGameObject* renderObject;
static tModelRenderData modelRenderData;
static CVertex renderOffset;
static short glow_num = -1;
static CDoubleVector normal; // Storage for calculated surface normal
static tModelRenderPoly* faceP;
static int pt, pt0, n_points;
static int lastObjectType = -1;
static int lastObjectId = -1;
static APOINT poly_xy [MAX_POLYMODEL_POINTS];
CPolyModel* renderModel;
//-----------------------------------------------------------------------
// int MultiplyFix ()
//-----------------------------------------------------------------------
int MultiplyFix (int a, int b) {
return (int) ((double (a) * double (b))/F1_0);
}
//-----------------------------------------------------------------------
// DrawModel ()
//-----------------------------------------------------------------------
void CMineView::DrawModel ()
{
if (renderModel)
renderModel->Draw (&m_view, m_pDC);
}
//-----------------------------------------------------------------------
// set_model_points ()
//
// Rotates, translates, then sets screen points (xy) for 3d model points
//-----------------------------------------------------------------------
void CPolyModel::SetModelPoints (int start, int end)
{
CVertex pt;
for (int i = start; i < end; i++) {
//int x0 = modelRenderData.points[i].v.x;
//int y0 = modelRenderData.points[i].v.y;
//int z0 = modelRenderData.points[i].v.z;
// rotate point using Objects () rotation matrix
pt = renderObject->m_location.orient * modelRenderData.points [i];
// set point to be in world coordinates
pt += renderObject->m_location.pos;
// now that points are relative to set screen xy points (poly_xy)
m_view->Project (pt, poly_xy [i]);
}
}
//-----------------------------------------------------------------------
// draw_poly
//
// Action - Draws a polygon if it is facing the outward.
// Used global device context handle set by SetupModel ()
//-----------------------------------------------------------------------
void tModelRenderPoly::Draw (CViewMatrix* view, CDC* pDC)
{
if (view->CheckNormal (renderObject, offset, normal)) {
int i, j;
POINT aPoints [MAX_POLYMODEL_POLY_POINTS];
for (i = 0; i < n_verts; i++) {
j = verts [i];
aPoints [i].x = poly_xy [j].x;
aPoints [i].y = poly_xy [j].y;
}
pDC->Polygon (aPoints, n_verts);
}
}
//-----------------------------------------------------------------------
//
// Calls the CGameObject interpreter to render an CGameObject.
// The CGameObject renderer is really a seperate pipeline. returns true if drew
//
//-----------------------------------------------------------------------
void CPolyModel::Render (byte *p)
{
while (W (p) != OP_EOF) {
switch (W (p)) {
// Point Definitions with Start Offset:
// 2 ushort n_points number of points
// 4 ushort start_point starting point
// 6 ushort unknown
// 8 CFixVector pts[n_points] x, y, z data
case OP_DEFP_START: {
pt0 = W (p+4);
n_points = W (p+2);
modelRenderData.n_points += n_points;
assert (W (p+6)==0);
assert (modelRenderData.n_points < MAX_POLYMODEL_POINTS);
assert (pt0+n_points < MAX_POLYMODEL_POINTS);
for (pt = 0;pt < n_points; pt++)
modelRenderData.points [pt+pt0] = VP (p+8)[pt] + renderOffset;
SetModelPoints (pt0, pt0+n_points);
p += W (p+2)*sizeof (CFixVector) + 8;
break;
}
// Flat Shaded Polygon:
// 2 ushort n_verts
// 4 CFixVector vector1
// 16 CFixVector vector2
// 28 ushort color
// 30 ushort verts[n_verts]
case OP_FLATPOLY: {
faceP = &modelRenderData.polys[modelRenderData.n_polys];
faceP->n_verts = W (p+2);
faceP->offset = *VP (p+4);
faceP->normal = *VP (p+16);
for (pt = 0; pt < faceP->n_verts; pt++)
faceP->verts[pt] = WP (p+30)[pt];
faceP->Draw (m_view, m_pDC);
p += 30 + ((faceP->n_verts&~1)+1)*2;
break;
}
// Texture Mapped Polygon:
// 2 ushort n_verts
// 4 CFixVector vector1
// 16 CFixVector vector2
// 28 ushort nBaseTex
// 30 ushort verts[n_verts]
// -- UVL uvls[n_verts]
case OP_TMAPPOLY: {
faceP = &modelRenderData.polys[modelRenderData.n_polys];
faceP->n_verts = W (p+2);
assert (faceP->n_verts>=MIN_POLYMODEL_POLY_POINTS);
assert (faceP->n_verts<=MAX_POLYMODEL_POLY_POINTS);
assert (modelRenderData.n_polys < MAX_POLYMODEL_POLYS);
faceP->offset = *VP (p+4);
faceP->normal = *VP (p+16);
faceP->color = -1;
faceP->nBaseTex = W (p+28);
faceP->glow_num = glow_num;
for (pt = 0; pt < faceP->n_verts; pt++)
faceP->verts[pt] = WP (p+30)[pt];
p += 30 + ((faceP->n_verts&~1)+1)*2;
faceP->Draw (m_view, m_pDC);
p += faceP->n_verts * 12;
break;
}
// Sort by Normal
// 2 ushort unknown
// 4 CFixVector Front Model normal
// 16 CFixVector Back Model normal
// 28 ushort Front Model Offset
// 30 ushort Back Model Offset
case OP_SORTNORM: {
/* = W (p+2); */
/* = W (p+4); */
/* = W (p+16); */
if (m_view->CheckNormal (renderObject, *VP (p+4), *VP (p+16))) {
Render (p + W (p+28));
Render (p + W (p+30));
}
else {
Render (p + W (p+30));
Render (p + W (p+28));
}
p += 32;
break;
}
// Call a Sub Object
// 2 ushort n_anims
// 4 CFixVector offset
// 16 ushort model offset
case OP_SUBCALL: {
renderOffset += *VP (p+4);
Render (p + W (p+16));
renderOffset -= *VP (p+4);
p += 20;
break;
}
// Glow Number for Next Poly
// 2 UINTW Glow_Value
case OP_GLOW: {
glow_num = W (p+2);
p += 4;
break;
}
default:
assert (0);
}
}
return;
}
//-----------------------------------------------------------------------
// ReadModelData ();
//-----------------------------------------------------------------------
#define FREAD(b) fread (&b, sizeof (b), 1, file)
int CPolyModel::Read (CFileManager& fp, bool bRenderData)
{
if (bRenderData) {
Release ();
if (!(m_info.renderData = new byte [m_info.dataSize]))
return 0;
return fp.Read (m_info.renderData, m_info.dataSize, 1) == 1;
}
else {
m_info.nModels = fp.ReadInt32 ();
m_info.dataSize = fp.ReadInt32 ();
fp.ReadInt32 ();
m_info.renderData = null;
for (int i = 0; i < MAX_SUBMODELS; i++)
m_info.subModels [i].ptr = fp.ReadInt32 ();
for (int i = 0; i < MAX_SUBMODELS; i++)
fp.Read (m_info.subModels [i].offset);
for (int i = 0; i < MAX_SUBMODELS; i++)
fp.Read (m_info.subModels [i].norm);
for (int i = 0; i < MAX_SUBMODELS; i++)
fp.Read (m_info.subModels [i].pnt);
for (int i = 0; i < MAX_SUBMODELS; i++)
m_info.subModels [i].rad = fp.ReadInt32 ();
for (int i = 0; i < MAX_SUBMODELS; i++)
m_info.subModels [i].parent = (byte) fp.ReadSByte ();
for (int i = 0; i < MAX_SUBMODELS; i++)
fp.Read (m_info.subModels [i].vMin);
for (int i = 0; i < MAX_SUBMODELS; i++)
fp.Read (m_info.subModels [i].vMax);
fp.Read (m_info.vMin);
fp.Read (m_info.vMax);
m_info.rad = fp.ReadInt32 ();
m_info.textureCount = fp.ReadByte ();
m_info.firstTexture = fp.ReadUInt16 ();
m_info.simplerModel = fp.ReadByte ();
}
return 1;
}
//-----------------------------------------------------------------------
int CMineView::ReadModelData (char* filename, char *szSubFile, bool bCustom)
{
CFileManager fp;
if (fp.Open (filename, "rb"))
return 1;
uint id;
uint i, n;
if (bCustom) {
struct level_header level;
char data[3];
long position;
fp.Read (data, 3, 1); // verify signature "DHF"
if (data[0] != 'D' || data[1] != 'H' || data[2] != 'F') {
fp.Close ();
return 1;
}
position = 3;
while (!fp.EoF ()) {
fp.Seek (position, SEEK_SET);
if ((fp.Read (&level, sizeof (struct level_header), 1) != 1) ||
(level.size > 10000000L || level.size < 0)) {
fp.Close ();
return 1;
}
if (!strcmp (level.name, szSubFile)) {
id = fp.ReadInt32 (); // read id
if (id != 0x5848414DL) {
fp.Close ();
return 1;
}
fp.ReadUInt16 (); // read version
n = fp.ReadInt16 (); // n_weapon_types
fp.Seek (n * sizeof (WEAPON_INFO), SEEK_CUR); // weapon_info
n = fp.ReadInt16 (); // n_robot_types
for (i = 0; i < n; i++)
theMine->RobotInfo (N_ROBOT_TYPES_D2 + i)->Read (fp);
n = fp.ReadInt16 (); // n_robot_joints
fp.Seek (n * sizeof (JOINTPOS), SEEK_CUR); // robot_joints
break;
}
position += sizeof (struct level_header) + level.size;
}
n = fp.ReadInt16 (); // n_curModels
assert (n <= MAX_POLYGON_MODELS);
for (i = 0; i < n; i++)
m_polyModels [N_POLYGON_MODELS_D2 + i].Read (fp);
for (i = 0; i < n; i++)
m_polyModels [N_POLYGON_MODELS_D2 + i].Read (fp, true);
}
else {
id = fp.ReadInt32 (); // read id
if (id != 0x214d4148L) {
fp.Close ();
return 1;
}
fp.ReadInt16 (); // read version
n = fp.ReadInt16 (); // n_tmap_info
fp.Seek (n * sizeof (ushort), SEEK_CUR); // bitmap_indicies
fp.Seek (n * sizeof (TMAP_INFO), SEEK_CUR); // tmap_info
n = fp.ReadInt16 (); // n_sounds
fp.Seek (n * sizeof (byte), SEEK_CUR); // sounds
fp.Seek (n * sizeof (byte), SEEK_CUR); // alt_sounds
n = fp.ReadInt16 (); // n_vclips
fp.Seek (n * sizeof (VCLIP), SEEK_CUR); // video clips
n = fp.ReadInt16 (); // n_eclips
fp.Seek (n * sizeof (ECLIP), SEEK_CUR); // effect clips
n = fp.ReadInt16 (); // n_wclips
fp.Seek (n * sizeof (WCLIP), SEEK_CUR); // weapon clips
n = fp.Tell ();
n = fp.ReadInt16 (); // n_robots
for (i = 0; i < n; i++)
theMine->RobotInfo (i)->Read (fp);
n = fp.ReadInt16 (); // n_robot_joints
fp.Seek (n * sizeof (JOINTPOS), SEEK_CUR); // robot joints
n = fp.ReadInt16 (); // n_weapon
fp.Seek (n * sizeof (WEAPON_INFO), SEEK_CUR); // weapon info
n = fp.ReadInt16 (); // n_powerups
fp.Seek (n * sizeof (POWERUP_TYPE_INFO), SEEK_CUR); // powerup info
n = fp.ReadInt16 (); // n_curModels
assert (n <= MAX_POLYGON_MODELS);
for (i = 0; i < n; i++)
m_polyModels [i].Read (fp);
for (i = 0; i < n; i++)
m_polyModels [i].Read (fp, true);
}
fp.Close ();
return 0;
}
//-----------------------------------------------------------------------
CPolyModel* CMineView::RenderModel (CGameObject* objP)
{
if ((theMine == null))
return null;
uint nModel;
switch (objP->m_info.type) {
case OBJ_PLAYER:
case OBJ_COOP:
nModel = D2_PLAYER_CLIP_NUMBER;
break;
case OBJ_WEAPON:
nModel = MINE_CLIP_NUMBER;
break;
case OBJ_CNTRLCEN:
switch (objP->m_info.id) {
case 1: nModel = 95; break;
case 2: nModel = 97; break;
case 3: nModel = 99; break;
case 4: nModel = 101; break;
case 5: nModel = 103; break;
case 6: nModel = 105; break;
default: nModel = 97; break; // level 1's reactor
}
break;
case OBJ_ROBOT:
nModel = theMine->RobotInfo ((objP->m_info.id >= N_ROBOT_TYPES_D2) ? objP->m_info.id /*- N_ROBOT_TYPES_D2*/ : objP->m_info.id)->m_info.nModel;
break;
default:
return null;
}
return m_polyModels + nModel;
}
//-----------------------------------------------------------------------
// SetupModel ()
//
// Action - sets the global handle used when drawing polygon models
//-----------------------------------------------------------------------
int CMineView::SetupModel (CGameObject *objP)
{
renderOffset.Clear ();
modelRenderData.n_points = 0;
glow_num = -1;
if (null == (renderModel = RenderModel (renderObject = objP)))
return 1;
if (renderModel->m_info.renderData)
return 0;
char filename[256];
strcpy_s (filename, sizeof (filename), descentPath [1]);
char *slash = strrchr (filename, '\\');
if (slash)
*(slash+1) = '\0';
else
filename[0] = '\0';
bool bCustom = (objP->m_info.type == OBJ_ROBOT) && (objP->m_info.id >= N_ROBOT_TYPES_D2);
if (bCustom) {
char *psz = strstr (filename, "data");
if (psz)
*psz = '\0';
}
strcat_s (filename, sizeof (filename), bCustom ? "missions\\d2x.hog" : "descent2.ham");
if (ReadModelData (filename, bCustom ? "d2x.ham" : "", bCustom))
renderModel = null;
return renderModel == null;
}
//-----------------------------------------------------------------------
| 30.625263 | 144 | 0.526707 | [
"render",
"object",
"model",
"3d"
] |
b7a1ab9a54f84d635d5a380173fcd770b6059796 | 3,887 | cc | C++ | src/solvers/test/test_MGCMFD.cc | baklanovp/libdetran | 820efab9d03ae425ccefb9520bdb6c086fdbf939 | [
"MIT"
] | 4 | 2015-03-07T16:20:23.000Z | 2020-02-10T13:40:16.000Z | src/solvers/test/test_MGCMFD.cc | baklanovp/libdetran | 820efab9d03ae425ccefb9520bdb6c086fdbf939 | [
"MIT"
] | 3 | 2018-02-27T21:24:22.000Z | 2020-12-16T00:56:44.000Z | src/solvers/test/test_MGCMFD.cc | baklanovp/libdetran | 820efab9d03ae425ccefb9520bdb6c086fdbf939 | [
"MIT"
] | 9 | 2015-03-07T16:20:26.000Z | 2022-01-29T00:14:23.000Z | //----------------------------------*-C++-*-----------------------------------//
/**
* @file test_MGSolverGS.cc
* @brief Test of MGSolverGS
* @note Copyright(C) 2012-2013 Jeremy Roberts
*/
//----------------------------------------------------------------------------//
// LIST OF TEST FUNCTIONS
#define TEST_LIST \
FUNC(test_MGCMFD)
#include "TestDriver.hh"
#include "solvers/FixedSourceManager.hh"
#include "solvers/test/fixedsource_fixture.hh"
#include "solvers/mg/MGSolverGS.hh"
#include "solvers/wg/WGSolverSI.hh"
#include "transport/CurrentTally.hh"
#include "transport/CoarseMesh.hh"
#include "transport/Homogenize.hh"
#include "solvers/mg/CMFDLossOperator.hh"
using namespace detran_test;
using namespace detran;
using namespace detran_utilities;
using namespace detran_geometry;
using namespace std;
using std::cout;
using std::endl;
#define COUT(c) std::cout << c << std::endl;
int main(int argc, char *argv[])
{
RUN(argc, argv);
}
//----------------------------------------------------------------------------//
// TEST DEFINITIONS
//----------------------------------------------------------------------------//
typedef FixedSourceManager<_1D> Manager;
typedef Manager::SP_manager SP_manager;
void set_data(InputDB::SP_input db)
{
db->put<std::string>("outer_solver", "GS");
db->put<int>("inner_max_iters", 1);
db->put<double>("inner_tolerance", 1.0e-10);
db->put<int>("outer_max_iters", 0);
db->put<double>("outer_tolerance", 1.0e-14);
db->put<std::string>("bc_west", "vacuum");
db->put<std::string>("bc_east", "vacuum");
}
int test_MGCMFD(int argc, char *argv[])
{
callow_initialize(argc, argv);
{
int ng = 7;
FixedSourceData data = get_fixedsource_data(1, ng, 10, 5);
set_data(data.input);
data.input->put<std::string>("bc_west", "vacuum");
data.input->put<std::string>("bc_east", "vacuum");
data.input->put<int>("quad_number_polar_octant", 8);
//data.material->set_sigma_s(0, 0, 0, 0.99);
data.material->compute_diff_coef();
data.material->compute_sigma_a();
// Build manager and extract the solvers
SP_manager manager(new Manager(data.input, data.material, data.mesh, true));
manager->setup();
manager->set_source(data.source);
manager->set_solver();
typedef MGSolverGS<_1D> GS;
typedef WGSolverSI<_1D> SI;
GS &mgs = *(dynamic_cast<GS* >(&(*manager->solver())));
SI &wgs = *(dynamic_cast<SI* >(&(*mgs.wg_solver())));
// Build the coarse mesh and the current tally and set the sweeper
CoarseMesh::SP_coarsemesh coarse(new CoarseMesh(data.mesh, 2));
Mesh::SP_mesh cmesh = coarse->get_coarse_mesh();
typedef CurrentTally<_1D> Tally;
Tally::SP_tally tally(new Tally(coarse, manager->quadrature(), ng));
// Perform one multigroup sweep
mgs.solve();
//tally->display();
mgs.sweeper()->set_tally(tally);
mgs.sweep();
tally->display();
for (int i = 0; i < manager->state()->phi(0).size(); ++i)
{
COUT(manager->state()->phi(0)[i])
}
// Homogenize
Homogenize H(data.material, Homogenize::PHI_D);
SP_material cmat = H.homogenize(mgs.state(), mgs.mesh(), "COARSEMESH");
vec2_dbl phi = H.coarse_mesh_flux();
cmat->display();
for (int i = 0; i < phi[0].size(); ++i)
{
printf("%16.12f \n", phi[1][i]);
}
// Coarse mesh diffusion
CMFDLossOperator<_1D> A(data.input,
cmat,
cmesh,
tally,
true,
false);
A.construct(phi);
A.print_matlab("cmfd.out");
}
callow_finalize();
return 0;
}
//----------------------------------------------------------------------------//
// end of test_MGSolverGS.cc
//----------------------------------------------------------------------------//
| 30.849206 | 80 | 0.553898 | [
"mesh"
] |
b7ab027bc81f6ed375d65ceddcc59cb4f48f082f | 2,333 | cpp | C++ | code/deps/osrm/unit_tests/library/match.cpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | null | null | null | code/deps/osrm/unit_tests/library/match.cpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | null | null | null | code/deps/osrm/unit_tests/library/match.cpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | 1 | 2021-11-24T14:24:44.000Z | 2021-11-24T14:24:44.000Z | #include <boost/test/test_case_template.hpp>
#include <boost/test/unit_test.hpp>
#include "coordinates.hpp"
#include "fixture.hpp"
#include "waypoint_check.hpp"
#include "osrm/match_parameters.hpp"
#include "osrm/coordinate.hpp"
#include "osrm/engine_config.hpp"
#include "osrm/json_container.hpp"
#include "osrm/osrm.hpp"
#include "osrm/status.hpp"
BOOST_AUTO_TEST_SUITE(match)
BOOST_AUTO_TEST_CASE(test_match)
{
using namespace osrm;
auto osrm = getOSRM(OSRM_TEST_DATA_DIR "/ch/monaco.osrm");
MatchParameters params;
params.coordinates.push_back(get_dummy_location());
params.coordinates.push_back(get_dummy_location());
params.coordinates.push_back(get_dummy_location());
json::Object result;
const auto rc = osrm.Match(params, result);
BOOST_CHECK(rc == Status::Ok || rc == Status::Error);
const auto code = result.values.at("code").get<json::String>().value;
BOOST_CHECK_EQUAL(code, "Ok");
const auto &tracepoints = result.values.at("tracepoints").get<json::Array>().values;
BOOST_CHECK_EQUAL(tracepoints.size(), params.coordinates.size());
const auto &matchings = result.values.at("matchings").get<json::Array>().values;
const auto &number_of_matchings = matchings.size();
for (const auto &waypoint : tracepoints)
{
if (waypoint.is<mapbox::util::recursive_wrapper<util::json::Object>>())
{
BOOST_CHECK(waypoint_check(waypoint));
const auto &waypoint_object = waypoint.get<json::Object>();
const auto matchings_index =
waypoint_object.values.at("matchings_index").get<json::Number>().value;
const auto waypoint_index =
waypoint_object.values.at("waypoint_index").get<json::Number>().value;
const auto &route_legs = matchings[matchings_index]
.get<json::Object>()
.values.at("legs")
.get<json::Array>()
.values;
BOOST_CHECK_LT(waypoint_index, route_legs.size() + 1);
BOOST_CHECK_LT(matchings_index, number_of_matchings);
}
else
{
BOOST_CHECK(waypoint.is<json::Null>());
}
}
}
BOOST_AUTO_TEST_SUITE_END()
| 34.308824 | 88 | 0.630519 | [
"object"
] |
b7ace1cedfa2f8fadfbcbd877b8afe8d18c6e2d5 | 4,560 | hpp | C++ | modules/core/src/Aquila/core/Algorithm.hpp | dtmoodie/Acquilla | b395b7d1338221369f9b0b46c7abc20f7bc5e827 | [
"MIT"
] | null | null | null | modules/core/src/Aquila/core/Algorithm.hpp | dtmoodie/Acquilla | b395b7d1338221369f9b0b46c7abc20f7bc5e827 | [
"MIT"
] | null | null | null | modules/core/src/Aquila/core/Algorithm.hpp | dtmoodie/Acquilla | b395b7d1338221369f9b0b46c7abc20f7bc5e827 | [
"MIT"
] | null | null | null | #pragma once
#include "Aquila/core/detail/Export.hpp"
#include "IAlgorithm.hpp"
#include <MetaObject/object/MetaObject.hpp>
#include <RuntimeObjectSystem/shared_ptr.hpp>
#include <boost/circular_buffer.hpp>
#include <boost/fiber/recursive_mutex.hpp>
#include <boost/fiber/recursive_timed_mutex.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <queue>
#define STRINGIFY_(X) #X
#define STRINGIFY(X) STRINGIFY_(X)
#define LOG_ALGO(LEVEL, ...) m_logger->LEVEL(__FILE__ ":" STRINGIFY(__LINE__) " " __VA_ARGS__)
namespace aq
{
class AQUILA_EXPORTS Algorithm : virtual public IAlgorithm
{
public:
Algorithm();
bool process() override;
int setupParamServer(const std::shared_ptr<mo::IParamServer>& mgr) override;
int setupSignals(const std::shared_ptr<mo::RelayManager>& mgr) override;
void setEnabled(bool value) override;
bool getEnabled() const override;
virtual mo::OptionalTime getTimestamp();
void setSyncInput(const std::string& name) override;
void setSyncMethod(SyncMethod method) override;
void postSerializeInit() override;
void Init(bool first_init) override;
mo::ParamVec_t getComponentParams(const std::string& filter = "") override;
mo::ConstParamVec_t getComponentParams(const std::string& filter = "") const override;
mo::ConstParamVec_t getParams(const std::string& filter = "") const override;
mo::ParamVec_t getParams(const std::string& filter = "") override;
const mo::IControlParam* getParam(const std::string& name) const override;
mo::IControlParam* getParam(const std::string& name) override;
const mo::IPublisher* getOutput(const std::string& name) const override;
mo::IPublisher* getOutput(const std::string& name) override;
IMetaObject::ConstPublisherVec_t getOutputs(const std::string& name_filter = "") const override;
IMetaObject::ConstPublisherVec_t getOutputs(const mo::TypeInfo& type_filter,
const std::string& name_filter = "") const override;
IMetaObject::PublisherVec_t getOutputs(const std::string& name_filter = "") override;
IMetaObject::PublisherVec_t getOutputs(const mo::TypeInfo& type_filter,
const std::string& name_filter = "") override;
void setStream(const mo::IAsyncStreamPtr_t& ctx) override;
std::vector<rcc::weak_ptr<IAlgorithm>> getComponents() const override;
void addComponent(const rcc::weak_ptr<IAlgorithm>& component) override;
void Serialize(ISimpleSerializer* pSerializer) override;
void setLogger(const std::shared_ptr<spdlog::logger>& logger) override;
protected:
void clearModifiedInputs();
void clearModifiedControlParams();
InputState checkInputs() override;
InputState syncTimestamp(const mo::Time& ts, const std::vector<mo::ISubscriber*>& inputs);
InputState syncFrameNumber(size_t fn, const std::vector<mo::ISubscriber*>& inputs);
bool checkModified(const std::vector<mo::ISubscriber*>& inputs) const;
bool checkModifiedControlParams() const;
void removeTimestampFromBuffer(const mo::Time& ts);
void removeFrameNumberFromBuffer(size_t fn);
mo::OptionalTime findDirectTimestamp(bool& buffered, const std::vector<mo::ISubscriber*>& inputs);
mo::OptionalTime findBufferedTimestamp();
void onParamUpdate(const mo::IParam&, mo::Header, mo::UpdateFlags, mo::IAsyncStream&) override;
std::shared_ptr<spdlog::logger> m_logger;
struct SyncData
{
SyncData(const boost::optional<mo::Time>& ts_, mo::FrameNumber fn);
bool operator==(const SyncData& other);
bool operator!=(const SyncData& other);
boost::optional<mo::Time> ts;
mo::FrameNumber fn;
};
private:
mo::FrameNumber m_fn;
mo::OptionalTime m_ts;
mo::OptionalTime m_last_ts;
mo::ISubscriber* m_sync_input = nullptr;
IAlgorithm::SyncMethod m_sync_method = IAlgorithm::SyncMethod::kEVERY;
std::queue<mo::Time> m_ts_processing_queue;
std::queue<size_t> m_fn_processing_queue;
mo::Mutex_t m_mtx;
std::map<const mo::ISubscriber*, boost::circular_buffer<SyncData>> m_buffer_timing_data;
std::vector<rcc::weak_ptr<IAlgorithm>> m_algorithm_components;
bool m_enabled = true;
};
} // namespace aq
| 40 | 106 | 0.675439 | [
"object",
"vector"
] |
b7b1e549bcb009caab3e6306e5e1a369dfaeb16e | 19,088 | cpp | C++ | Chimera/Source/GeneralImaging/PictureControl.cpp | zzpwahaha/Chimera-Control-Trim | df1bbf6bea0b87b8c7c9a99dce213fdc249118f2 | [
"MIT"
] | null | null | null | Chimera/Source/GeneralImaging/PictureControl.cpp | zzpwahaha/Chimera-Control-Trim | df1bbf6bea0b87b8c7c9a99dce213fdc249118f2 | [
"MIT"
] | null | null | null | Chimera/Source/GeneralImaging/PictureControl.cpp | zzpwahaha/Chimera-Control-Trim | df1bbf6bea0b87b8c7c9a99dce213fdc249118f2 | [
"MIT"
] | null | null | null | // created by Mark O. Brown
#include "stdafx.h"
#include "PictureControl.h"
#include <algorithm>
#include <numeric>
#include <boost/lexical_cast.hpp>
#include <qlayout.h>
PictureControl::PictureControl(bool histogramOption, Qt::TransformationMode mode)
: histOption(histogramOption), /*QWidget(), */transformationMode(mode)
, slider(Qt::Vertical, RangeSlider::DoubleHandles)
{
active = true;
if ( histOption ){
horData.resize ( 1 );
vertData.resize ( 1 );
updatePlotData ( );
}
repaint ();
}
void PictureControl::updatePlotData ( ){
if ( !histOption ){
return;
}
horData[ 0 ].resize ( mostRecentImage_m.getCols ( ) );
vertData[ 0 ].resize ( mostRecentImage_m.getRows ( ) );
unsigned count = 0;
std::vector<long> dataRow;
for ( auto& data : horData[ 0 ] ){
data.x = count;
// integrate the column
double p = 0.0;
for ( auto row : range ( mostRecentImage_m.getRows ( ) ) ){
p += mostRecentImage_m ( row, count );
}
count++;
dataRow.push_back ( p );
}
count = 0;
auto avg = std::accumulate ( dataRow.begin ( ), dataRow.end ( ), 0.0 ) / dataRow.size ( );
for ( auto& data : horData[ 0 ] ){
data.y = dataRow[ count++ ] - avg;
}
count = 0;
std::vector<long> dataCol;
for ( auto& data : vertData[ 0 ] ){
data.x = count;
// integrate the row
double p = 0.0;
for ( auto col : range ( mostRecentImage_m.getCols ( ) ) ){
p += mostRecentImage_m ( count, col );
}
count++;
dataCol.push_back ( p );
}
count = 0;
auto avgCol = std::accumulate ( dataCol.begin ( ), dataCol.end ( ), 0.0 ) / dataCol.size ( );
for ( auto& data : vertData[ 0 ] ){
data.y = dataCol[ count++ ] - avgCol;
}
}
/*
* initialize all controls associated with single picture.
*/
void PictureControl::initialize(std::string name, int width, int height, IChimeraQtWindow* parent, int picScaleFactorIn){
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
picScaleFactor = picScaleFactorIn;
if ( width < 100 ){
thrower ( "Pictures must be greater than 100 in width because this is the size of the max/min"
"controls." );
}
if ( height < 100 ){
thrower ( "Pictures must be greater than 100 in height because this is the minimum height "
"of the max/min controls." );
}
QHBoxLayout* layout1 = new QHBoxLayout(this);
layout1->setContentsMargins(0, 0, 0, 0);
coordinatesText = new QLabel("Coordinates: ", this);
coordinatesDisp = new QLabel("", this);
valueText = new QLabel("; Value: ", this);
valueDisp = new QLabel("", this);
layout1->addWidget(new QLabel(qstr(name),this));
layout1->addWidget(coordinatesText);
layout1->addWidget(coordinatesDisp);
layout1->addWidget(valueText);
layout1->addWidget(valueDisp);
layout1->addStretch();
maxWidth = width;
maxHeight = height;
QHBoxLayout* layout2 = new QHBoxLayout(this);
layout2->setContentsMargins(0, 0, 0, 0);
pic.setStyle(plotStyle::DensityPlotWithHisto);
pic.init(parent,"");
pic.plot->setMinimumSize(400, 350);
pictureObject = new ImageLabel (parent);
//connect (pictureObject, &ImageLabel::mouseReleased, [this](QMouseEvent* event) {handleMouse (event); });
std::vector<unsigned char> data (20000);
for (auto& pt : data){
pt = rand () % 255;
}
slider.setRange(0, 4096);
slider.setMaximumWidth(80);
slider.setMaxLength(800);
parent->connect (&slider, &RangeSliderIntg::smlValueChanged, [this]() {redrawImage (); });
parent->connect (&slider, &RangeSliderIntg::lrgValueChanged, [this]() {redrawImage (); });
layout2->addWidget(pic.plot, 1);
layout2->addWidget(&slider, 0);
connect(pic.plot, &QCustomPlot::mouseMove, [this](QMouseEvent* event) {
handleMouse(event); });
layout->addLayout(layout1);
layout->addLayout(layout2);
layout->addStretch();
}
bool PictureControl::isActive(){
return active;
}
void PictureControl::setSliderPositions(unsigned min, unsigned max){
slider.upperSpinBox()->setValue(max);
slider.lowerSpinBox()->setValue(min);
//sliderMin.setValue ( min );
//sliderMax.setValue ( max );
}
/*
* Used during initialization & when used when transitioning between 1 and >1 pictures per repetition.
* Sets the unscaled background area and the scaled area.
*/
void PictureControl::setPictureArea( QPoint loc, int width, int height ){
//// this is important for the control to know where it should draw controls.
//auto& sBA = scaledBackgroundArea;
//auto& px = loc.rx (), & py = loc.ry ();
//unscaledBackgroundArea = { px, py, px + width, py + height };
//// reserve some area for the texts.
//unscaledBackgroundArea.setRight (unscaledBackgroundArea.right () - 100);
//sBA = unscaledBackgroundArea;
///*
//sBA.left *= width;
//sBA.right *= width;
//sBA.top *= height;
//sBA.bottom *= height;*/
//if ( horGraph ){
// //horGraph->setControlLocation ( { scaledBackgroundArea.left, scaledBackgroundArea.bottom },
// // scaledBackgroundArea.right - scaledBackgroundArea.left, 65 );
//}
//if ( vertGraph ){
// //vertGraph->setControlLocation ( { scaledBackgroundArea.left - 65, scaledBackgroundArea.bottom },
// // 65, scaledBackgroundArea.bottom - scaledBackgroundArea.top );
//}
//double widthPicScale;
//double heightPicScale;
//auto& uIP = unofficialImageParameters;
//double w_to_h_ratio = double (uIP.width ()) / uIP.height ();
//double sba_w = sBA.right () - sBA.left ();
//double sba_h = sBA.bottom () - sBA.top ();
//if (w_to_h_ratio > sba_w/sba_h){
// widthPicScale = 1;
// heightPicScale = (1.0/ w_to_h_ratio) * (sba_w / sba_h);
//}
//else{
// heightPicScale = 1;
// widthPicScale = w_to_h_ratio / (sba_w / sba_h);
//}
//unsigned long picWidth = unsigned long( (sBA.right () - sBA.left())*widthPicScale );
//unsigned long picHeight = (sBA.bottom() - sBA.top())*heightPicScale;
//QPoint mid = { (sBA.left () + sBA.right ()) / 2, (sBA.top () + sBA.bottom ()) / 2 };
//pictureArea.setLeft(mid.x() - picWidth / 2);
//pictureArea.setRight(mid.x() + picWidth / 2);
//pictureArea.setTop(mid.y() - picHeight / 2);
//pictureArea.setBottom(mid.y() + picHeight / 2);
//
//if (pictureObject){
// pictureObject->setGeometry (px, py, width, height);
// pictureObject->raise ();
//}
}
/* used when transitioning between single and multiple pictures. It sets it based on the background size, so make
* sure to change the background size before using this.
* ********/
void PictureControl::setSliderControlLocs (QPoint pos, int height){
//sliderMin.reposition ( pos, height);
//pos.rx() += 25;
//sliderMax.reposition ( pos, height );
}
/* used when transitioning between single and multiple pictures. It sets it based on the background size, so make
* sure to change the background size before using this.
* ********/
/*
* change the colormap used for a given picture.
*/
void PictureControl::updatePalette( QVector<QRgb> palette ){
imagePalette = palette;
}
/*
* called when the user changes either the min or max edit.
*/
void PictureControl::handleEditChange( int id ){
//if ( id == sliderMax.getEditId() ){
// sliderMax.handleEdit ( );
//}
//if ( id == sliderMin.getEditId() ){
// sliderMin.handleEdit ( );
//}
}
std::pair<unsigned, unsigned> PictureControl::getSliderLocations(){
return { slider.getSilderSmlVal(), slider.getSilderLrgVal() };
}
/*
* Recalculate the grid of pixels, which needs to be done e.g. when changing number of pictures or re-sizing the
* picture. Does not draw the grid.
*/
void PictureControl::recalculateGrid(imageParameters newParameters){
// not strictly necessary.
grid.clear();
// find the maximum dimension.
unofficialImageParameters = newParameters;
double widthPicScale;
double heightPicScale;
/*if (unofficialImageParameters.width ()> unofficialImageParameters.height())
{
widthPicScale = 1;
heightPicScale = double(unofficialImageParameters.height()) / unofficialImageParameters.width();
}
else
{
heightPicScale = 1;
widthPicScale = double(unofficialImageParameters.width()) / unofficialImageParameters.height();
}*/
auto& uIP = unofficialImageParameters;
double w_to_h_ratio = double (uIP.width ()) / uIP.height ();
auto& sBA = scaledBackgroundArea;
double sba_w = sBA.right () - sBA.left ();
double sba_h = sBA.bottom () - sBA.top ();
if (w_to_h_ratio > sba_w / sba_h){
widthPicScale = 1;
heightPicScale = (1.0 / w_to_h_ratio) * (sba_w / sba_h);
}
else{
heightPicScale = 1;
widthPicScale = w_to_h_ratio / (sba_w / sba_h);
}
long width = long((scaledBackgroundArea.right () - scaledBackgroundArea.left ())*widthPicScale);
long height = long((scaledBackgroundArea.bottom () - scaledBackgroundArea.top ())*heightPicScale);
QPoint mid = { (scaledBackgroundArea.left () + scaledBackgroundArea.right ()) / 2,
(scaledBackgroundArea.top () + scaledBackgroundArea.bottom ()) / 2 };
pictureArea.setLeft (mid.x () - width / 2);
pictureArea.setRight (mid.x () + width / 2);
pictureArea.setTop (mid.y () - height / 2);
pictureArea.setBottom (mid.y () + height / 2);
grid.resize(newParameters.width());
for (unsigned colInc = 0; colInc < grid.size(); colInc++){
grid[colInc].resize(newParameters.height());
for (unsigned rowInc = 0; rowInc < grid[colInc].size(); rowInc++){
// for all 4 pictures...
grid[colInc][rowInc].setLeft(int(pictureArea.left()
+ (double)(colInc+1) * (pictureArea.right () - pictureArea.left ())
/ (double)grid.size( ) + 2));
grid[colInc][rowInc].setRight(int(pictureArea.left()
+ (double)(colInc + 2) * (pictureArea.right () - pictureArea.left ()) / (double)grid.size() + 2));
grid[colInc][rowInc].setTop(int(pictureArea.top ()
+ (double)(rowInc)* (pictureArea.bottom () - pictureArea.top ()) / (double)grid[colInc].size()));
grid[colInc][rowInc].setBottom(int(pictureArea.top()
+ (double)(rowInc + 1)* (pictureArea.bottom () - pictureArea.top ()) / (double)grid[colInc].size()));
}
}
}
/*
* sets the state of the picture and changes visibility of controls depending on that state.
*/
void PictureControl::setActive( bool activeState )
{
if (!coordinatesText || !coordinatesDisp) {
return;
}
active = activeState;
if (!active){
this->hide();
slider.hide();
coordinatesText->hide();
coordinatesDisp->hide();
valueText->hide();
valueDisp->hide();
}
else{
this->show();
slider.show();
coordinatesText->show();
coordinatesDisp->show();
valueText->show();
valueDisp->show();
}
}
/*
* redraws the background and image.
*/
void PictureControl::redrawImage(){
if ( active && mostRecentImage_m.size ( ) != 0 ){
drawBitmap (mostRecentImage_m, mostRecentAutoscaleInfo, mostRecentSpecialMinSetting,
mostRecentSpecialMaxSetting, mostRecentGrids, mostRecentPicNum, true);
}
}
void PictureControl::resetStorage(){
mostRecentImage_m = Matrix<long>(0,0);
}
void PictureControl::setSoftwareAccumulationOption ( softwareAccumulationOption opt ){
saOption = opt;
accumPicData.clear ( );
accumNum = 0;
}
/*
Version of this from the Basler camera control Code. I will consolidate these shortly.
*/
void PictureControl::drawBitmap ( const Matrix<long>& picData, std::tuple<bool, int, int> autoScaleInfo,
bool specialMin, bool specialMax, std::vector<atomGrid> grids, unsigned pictureNumber,
bool includingAnalysisMarkers ){
mostRecentImage_m = picData;
mostRecentPicNum = pictureNumber;
mostRecentGrids = grids;
auto minColor = slider.getSilderSmlVal( );
auto maxColor = slider.getSilderLrgVal( );
mostRecentAutoscaleInfo = autoScaleInfo;
int pixelsAreaWidth = pictureArea.right () - pictureArea.left () + 1;
int pixelsAreaHeight = pictureArea.bottom () - pictureArea.top () + 1;
int dataWidth = grid.size ( );
// first element containst whether autoscaling or not.
//long colorRange;
//if ( std::get<0> ( autoScaleInfo ) ){
// // third element contains max, second contains min.
// colorRange = std::get<2> ( autoScaleInfo ) - std::get<1> ( autoScaleInfo );
// minColor = std::get<1> ( autoScaleInfo );
//}
//else{
// colorRange = maxColor - minColor;
// minColor = minColor;
// //colorRange = sliderMax.getValue ( ) - sliderMin.getValue ( );
// //minColor = sliderMin.getValue ( );
//}
// assumes non-zero size...
if ( grid.size ( ) == 0 ){
thrower ( "Tried to draw bitmap without setting grid size!" );
}
int dataHeight = grid[ 0 ].size ( );
int totalGridSize = dataWidth * dataHeight;
if ( picData.size ( ) != totalGridSize ){
thrower ( "Picture data didn't match grid size!" );
}
int width = picData.getCols();
int height = picData.getRows();
std::vector<plotDataVec> ddvec(height);
for (size_t idx = 0; idx < height; idx++)
{
ddvec[idx].reserve(width);
for (size_t idd = 0; idd < width; idd++)
{
ddvec[idx].push_back(dataPoint{ 0,double(picData(idx,idd)),0 }); // x,y,err
}
}
pic.setData(ddvec);
//float yscale = ( 256.0f ) / (float) colorRange;
//std::vector<uchar> dataArray2 ( dataWidth * dataHeight, 255 );
//int iTemp;
//double dTemp = 1;
//const int picPaletteSize = 256;
//for (int heightInc = 0; heightInc < dataHeight; heightInc++){
// for (int widthInc = 0; widthInc < dataWidth; widthInc++){
// dTemp = ceil (yscale * double(picData (heightInc, widthInc) - minColor));
// if (dTemp <= 0) {
// // raise value to zero which is the floor of values this parameter can take.
// iTemp = 1;
// }
// else if (dTemp >= picPaletteSize - 1) {
// // round to maximum value.
// iTemp = picPaletteSize - 2;
// }
// else{
// // no rounding or flooring to min or max needed.
// iTemp = (int)dTemp;
// }
// // store the value.
// dataArray2[widthInc + heightInc * dataWidth] = (unsigned char)iTemp;
// }
//}
//int sf = picScaleFactor;
//QImage img (sf * dataWidth, sf * dataHeight, QImage::Format_Indexed8);
//img.setColorTable (imagePalette);
//img.fill (0);
//for (auto rowInc : range(dataHeight)){
// std::vector<uchar> singleRow (sf * dataWidth);
// for (auto val : range (dataWidth)){
// for (auto rep : range (sf)) {
// singleRow[sf * val + rep] = dataArray2[rowInc * dataWidth + val];
// }
// }
// for (auto repRow : range (sf)){
// memcpy (img.scanLine (rowInc * sf + repRow), singleRow.data(), img.bytesPerLine ());
// }
//}
// need to convert to an rgb format in order to draw on top. drawing on top using qpainter isn't supported with the
// indexed format.
//img = img.convertToFormat (QImage::Format_RGB888);
//QPainter painter;
//painter.begin (&img);
//drawDongles (painter, grids, pictureNumber, includingAnalysisMarkers);
//painter.end ();
//// seems like this doesn't *quite* work for some reason, hence the extra number here to adjust
//if (img.width () / img.height () > (pictureObject->width () / pictureObject->height ())-0.1) {
// pictureObject->setPixmap (QPixmap::fromImage (img).scaledToWidth (pictureObject->width (), transformationMode));
//}
//else {
// pictureObject->setPixmap (QPixmap::fromImage (img).scaledToHeight (pictureObject->height (), transformationMode));
//}
// //update this with the new picture.
//setHoverValue ( );
}
void PictureControl::setHoverValue( ){
int loc = (grid.size( ) - 1 - selectedLocation.column) * grid.size( ) + selectedLocation.row;
if ( loc >= mostRecentImage_m.size( ) ) {
return;
}
valueDisp->setText( cstr( mostRecentImage_m.data[loc] ) );
}
void PictureControl::handleMouse (QMouseEvent* event){
auto vec = pic.handleMousePosOnCMap(event);
coordinatesDisp->setText("( " + qstr(int(vec[0])) + " , " + qstr(int(vec[1])) + " )");
valueDisp->setText(qstr(int(vec[2])));
}
/*
* draw the grid which outlines where each pixel is. Especially needs to be done when selecting pixels and no picture
* is displayed.
*/
void PictureControl::drawGrid(QPainter& painter){
if (!active){
return;
}
if (grid.size() != 0){
// hard set to 5000. Could easily change this to be able to see finer grids. Tested before and 5000 seems
// reasonable.
if (grid.size() * grid.front().size() > 5000){
return;
}
}
// draw rectangles indicating where the pixels are.
for (unsigned columnInc = 0; columnInc < grid.size(); columnInc++){
for (unsigned rowInc = 0; rowInc < grid[columnInc].size(); rowInc++){
unsigned pixelRow = picScaleFactor * grid[columnInc][rowInc].top();
unsigned pixelColumn = picScaleFactor * grid[columnInc][rowInc].left();
QRect rect = QRect (QPoint (pixelColumn, pixelRow),
QPoint (pixelColumn + picScaleFactor - 2, pixelRow + picScaleFactor - 2));
painter.drawRect (rect);
}
}
}
/*
* draws the circle which denotes the selected pixel that the user wants to know the counts for.
*/
void PictureControl::drawCircle(coordinate selectedLocation, QPainter& painter){
if (grid.size() == 0){
// this hasn't been set yet, presumably this got called by the camera window as the camera window
// was drawing itself before the control was initialized.
return;
}
if (!active){
// don't draw anything if the window isn't active.
return;
}
QRect smallRect( selectedLocation.column * picScaleFactor, selectedLocation.row * picScaleFactor,
picScaleFactor-1, picScaleFactor-1 );
painter.drawEllipse (smallRect);
}
void PictureControl::drawPicNum( unsigned picNum, QPainter& painter ){
QFont font = painter.font ();
// I think this is the font height in pixels on the pixmap basically.
font.setPointSize (20);
painter.setFont (font);
painter.setPen (Qt::white);
painter.drawText (QPoint ( int(picScaleFactor)/5, picScaleFactor), cstr (picNum));
}
void PictureControl::drawAnalysisMarkers( std::vector<atomGrid> gridInfo, QPainter& painter ){
if ( !active ){
return;
}
painter.setPen (Qt::white);
//std::vector<COLORREF> colors = { RGB( 100, 100, 100 ), RGB( 0, 100, 0 ), RGB( 0, 0, 100), RGB( 100, 0, 0 ) };
unsigned gridCount = 0;
for ( auto atomGrid : gridInfo ){
if ( atomGrid.topLeftCorner == coordinate( 0, 0 ) ){
// atom grid is empty, not to be used.
unsigned count = 1;
}
else {
// use the atom grid.
unsigned count = 1;
for ( auto columnInc : range( atomGrid.width ) ){
for ( auto rowInc : range( atomGrid.height ) ){
unsigned pixelRow = picScaleFactor*(atomGrid.topLeftCorner.row + rowInc * atomGrid.pixelSpacing);
unsigned pixelColumn = picScaleFactor * (atomGrid.topLeftCorner.column
+ columnInc * atomGrid.pixelSpacing);
QRect rect = QRect (QPoint(pixelColumn, pixelRow),
QPoint (pixelColumn+picScaleFactor-2, pixelRow + picScaleFactor - 2));
painter.drawRect (rect);
painter.drawText (rect, Qt::AlignCenter, cstr(count++));
}
}
}
gridCount++;
}
}
void PictureControl::drawDongles (QPainter& painter, std::vector<atomGrid> grids, unsigned pictureNumber,
bool includingAnalysisMarkers){
drawPicNum (pictureNumber, painter);
if (includingAnalysisMarkers) {
drawAnalysisMarkers ( grids, painter );
}
painter.setPen (Qt::red);
drawCircle (selectedLocation, painter);
}
void PictureControl::setTransformationMode (Qt::TransformationMode mode) {
transformationMode = mode;
}
void PictureControl::setSliderSize(int size)
{
slider.setMaxLength(size);
}
| 33.370629 | 121 | 0.678803 | [
"vector"
] |
5d9d96a37015e65f1c036c88bad97b08d4d1ac84 | 895 | cpp | C++ | Fizzy/Code/Game/Main_Win32.cpp | cugone/Fizzy | 6311533642d6feec2488011371027b13a8dfd96a | [
"MIT"
] | null | null | null | Fizzy/Code/Game/Main_Win32.cpp | cugone/Fizzy | 6311533642d6feec2488011371027b13a8dfd96a | [
"MIT"
] | null | null | null | Fizzy/Code/Game/Main_Win32.cpp | cugone/Fizzy | 6311533642d6feec2488011371027b13a8dfd96a | [
"MIT"
] | null | null | null |
#include "Engine/Core/EngineBase.hpp"
#include "Engine/Core/StringUtils.hpp"
#include "Engine/Core/Win.hpp"
#include "Game/Game.hpp"
#include "Game/GameConfig.hpp"
#include <sstream>
#include <memory>
#include <vector>
#pragma warning(push)
#pragma warning(disable: 28251) // No annotations for int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) {
UNUSED(hInstance);
UNUSED(hPrevInstance);
UNUSED(nCmdShow);
auto cmdStr = StringUtils::ConvertUnicodeToMultiByte(pCmdLine);
Engine<Game>::Initialize(g_title_str, cmdStr);
Engine<Game>::Run();
Engine<Game>::Shutdown();
}
#pragma warning(pop)
| 28.870968 | 151 | 0.729609 | [
"vector"
] |
5d9d99ba6eafb70990633b8d8e4ab9529946ae66 | 20,283 | cpp | C++ | src/python/py_main.cpp | adbmd/tomotopy | 0ef8c6f3afecf9b610d39defe39e6c50e293682a | [
"MIT"
] | 1 | 2020-09-22T14:30:19.000Z | 2020-09-22T14:30:19.000Z | src/python/py_main.cpp | adbmd/tomotopy | 0ef8c6f3afecf9b610d39defe39e6c50e293682a | [
"MIT"
] | null | null | null | src/python/py_main.cpp | adbmd/tomotopy | 0ef8c6f3afecf9b610d39defe39e6c50e293682a | [
"MIT"
] | null | null | null | #define MAIN_MODULE
#include "module.h"
#include "label.h"
#define TM_DMR
#define TM_GDMR
#define TM_HDP
#define TM_MGLDA
#define TM_PA
#define TM_HPA
#define TM_CT
#define TM_SLDA
#define TM_HLDA
#define TM_LLDA
#define TM_PLDA
#define TM_DT
using namespace std;
PyObject* gModule;
void char2Byte(const string& str, vector<uint32_t>& startPos, vector<uint16_t>& length)
{
if (str.empty()) return;
vector<size_t> charPos;
auto it = str.begin(), end = str.end();
for (; it != end; )
{
charPos.emplace_back(it - str.begin());
uint8_t c = *it;
if ((c & 0xF8) == 0xF0)
{
it += 4;
}
else if ((c & 0xF0) == 0xE0)
{
it += 3;
}
else if ((c & 0xE0) == 0xC0)
{
it += 2;
}
else if ((c & 0x80))
{
throw std::runtime_error{ "utf-8 decoding error" };
}
else it += 1;
}
charPos.emplace_back(str.size());
for (size_t i = 0; i < startPos.size(); ++i)
{
size_t s = startPos[i], e = (size_t)startPos[i] + length[i];
startPos[i] = charPos[s];
length[i] = charPos[e] - charPos[s];
}
}
void TopicModelObject::dealloc(TopicModelObject* self)
{
DEBUG_LOG("TopicModelObject Dealloc " << self);
if (self->inst)
{
delete self->inst;
}
Py_XDECREF(self->initParams);
Py_TYPE(self)->tp_free((PyObject*)self);
}
void CorpusObject::dealloc(CorpusObject* self)
{
DEBUG_LOG("CorpusObject Dealloc " << self->parentModel->ob_base.ob_type << ", " << self->parentModel->ob_base.ob_refcnt);
Py_XDECREF(self->parentModel);
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject * DocumentObject::repr(DocumentObject * self)
{
string ret = "<tomotopy.Document with words=\"";
for (size_t i = 0; i < self->doc->words.size(); ++i)
{
auto w = self->doc->wOrder.empty() ? self->doc->words[i] : self->doc->words[self->doc->wOrder[i]];
ret += self->parentModel->inst->getVocabDict().toWord(w);
ret.push_back(' ');
}
ret.pop_back();
ret += "\">";
return py::buildPyValue(ret);
}
void DocumentObject::dealloc(DocumentObject* self)
{
DEBUG_LOG("DocumentObject Dealloc " << self->parentModel->ob_base.ob_type << ", " << self->parentModel->ob_base.ob_refcnt);
Py_XDECREF(self->parentModel);
if (self->owner)
{
delete self->doc;
}
Py_TYPE(self)->tp_free((PyObject*)self);
}
void DictionaryObject::dealloc(DictionaryObject* self)
{
Py_XDECREF(self->parentModel);
Py_TYPE(self)->tp_free((PyObject*)self);
}
Py_ssize_t DictionaryObject::len(DictionaryObject* self)
{
try
{
if (!self->dict) throw runtime_error{ "dict is null" };
return self->vocabSize;
}
catch (const bad_exception&)
{
return -1;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return -1;
}
}
PyObject* DictionaryObject::getitem(DictionaryObject* self, Py_ssize_t key)
{
try
{
if (!self->dict) throw runtime_error{ "inst is null" };
if (key >= self->vocabSize)
{
PyErr_SetString(PyExc_IndexError, "");
throw bad_exception{};
}
return py::buildPyValue(self->dict->toWord(key));
}
catch (const bad_exception&)
{
return nullptr;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return nullptr;
}
}
PyObject* DictionaryObject::repr(DictionaryObject* self)
{
py::UniqueObj args = Py_BuildValue("(O)", self);
py::UniqueObj l = PyObject_CallObject((PyObject*)&PyList_Type, args);
PyObject* r = PyObject_Repr(l);
return r;
}
int DictionaryObject::init(DictionaryObject *self, PyObject *args, PyObject *kwargs)
{
PyObject* argParent;
const tomoto::Dictionary* dict;
size_t vocabSize = 0;
static const char* kwlist[] = { "f", "g", "v", nullptr };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "On|n", (char**)kwlist,
&argParent, &dict, &vocabSize)) return -1;
try
{
self->parentModel = (TopicModelObject*)argParent;
Py_INCREF(argParent);
self->dict = dict;
if (!vocabSize) vocabSize = dict->size();
self->vocabSize = vocabSize;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return -1;
}
return 0;
}
static PySequenceMethods Dictionary_seq_methods = {
(lenfunc)DictionaryObject::len,
nullptr,
nullptr,
(ssizeargfunc)DictionaryObject::getitem,
};
PyTypeObject Dictionary_type = {
PyVarObject_HEAD_INIT(nullptr, 0)
"tomotopy.Dictionary", /* tp_name */
sizeof(DictionaryObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)DictionaryObject::dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc)DictionaryObject::repr, /* tp_repr */
0, /* tp_as_number */
&Dictionary_seq_methods, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"`list`-like Dictionary interface for vocabularies", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PySeqIter_New, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DictionaryObject::init, /* tp_init */
PyType_GenericAlloc,
PyType_GenericNew,
};
static PyObject* Document_getTopics(DocumentObject* self, PyObject* args, PyObject *kwargs)
{
size_t topN = 10;
static const char* kwlist[] = { "top_n", nullptr };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|n", (char**)kwlist, &topN)) return nullptr;
try
{
if (!self->parentModel->inst) throw runtime_error{ "inst is null" };
if (!self->parentModel->isPrepared) throw runtime_error{ "train() should be called first for calculating the topic distribution" };
return py::buildPyValue(self->parentModel->inst->getTopicsByDocSorted(self->doc, topN));
}
catch (const bad_exception&)
{
return nullptr;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return nullptr;
}
}
static PyObject* Document_getTopicDist(DocumentObject* self)
{
try
{
if (!self->parentModel->inst) throw runtime_error{ "inst is null" };
if (!self->parentModel->isPrepared) throw runtime_error{ "train() should be called first for calculating the topic distribution" };
return py::buildPyValue(self->parentModel->inst->getTopicsByDoc(self->doc));
}
catch (const bad_exception&)
{
return nullptr;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return nullptr;
}
}
static PyObject* Document_getWords(DocumentObject* self, PyObject* args, PyObject *kwargs)
{
size_t topN = 10;
static const char* kwlist[] = { "top_n", nullptr };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|n", (char**)kwlist, &topN)) return nullptr;
try
{
if (!self->parentModel->inst) throw runtime_error{ "inst is null" };
return py::buildPyValue(self->parentModel->inst->getWordsByDocSorted(self->doc, topN));
}
catch (const bad_exception&)
{
return nullptr;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return nullptr;
}
}
static PyMethodDef Document_methods[] =
{
{ "get_topics", (PyCFunction)Document_getTopics, METH_VARARGS | METH_KEYWORDS, Document_get_topics__doc__ },
{ "get_topic_dist", (PyCFunction)Document_getTopicDist, METH_NOARGS, Document_get_topic_dist__doc__ },
#ifdef TM_PA
{ "get_sub_topics", (PyCFunction)Document_getSubTopics, METH_VARARGS | METH_KEYWORDS, Document_get_sub_topics__doc__ },
{ "get_sub_topic_dist", (PyCFunction)Document_getSubTopicDist, METH_NOARGS, Document_get_sub_topic_dist__doc__ },
#endif
{ "get_words", (PyCFunction)Document_getWords, METH_VARARGS | METH_KEYWORDS, Document_get_words__doc__ },
{ "get_count_vector", (PyCFunction)Document_getCountVector, METH_NOARGS, Document_get_count_vector__doc__ },
{ nullptr }
};
static int Document_init(DocumentObject *self, PyObject *args, PyObject *kwargs)
{
PyObject* argParent;
size_t docId, owner = 0;
static const char* kwlist[] = { "f", "g", "h", nullptr };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Onn", (char**)kwlist, &argParent, &docId, &owner)) return -1;
try
{
self->parentModel = (TopicModelObject*)argParent;
if (owner)
{
self->doc = (tomoto::DocumentBase*)docId;
self->owner = true;
}
else
{
self->doc = self->parentModel->inst->getDoc(docId);
self->owner = false;
}
Py_INCREF(argParent);
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return -1;
}
return 0;
}
static PyObject* Document_words(DocumentObject* self, void* closure)
{
try
{
if (!self->doc) throw runtime_error{ "doc is null!" };
return buildPyValueReorder(self->doc->words, self->doc->wOrder);
}
catch (const bad_exception&)
{
return nullptr;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return nullptr;
}
}
static PyObject* Document_weight(DocumentObject* self, void* closure)
{
try
{
if (!self->doc) throw runtime_error{ "doc is null!" };
return py::buildPyValue(self->doc->weight);
}
catch (const bad_exception&)
{
return nullptr;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return nullptr;
}
}
static PyObject* Document_Z(DocumentObject* self, void* closure)
{
PyObject* ret;
try
{
if (!self->doc) throw runtime_error{ "doc is null!" };
#ifdef TM_HLDA
ret = Document_HLDA_Z(self, closure);
if (ret) return ret;
#endif
#ifdef TM_HDP
ret = Document_HDP_Z(self, closure);
if(ret) return ret;
#endif
ret = Document_LDA_Z(self, closure);
if(ret) return ret;
throw runtime_error{ "doc doesn't has `topics` field!" };
}
catch (const bad_exception&)
{
return nullptr;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return nullptr;
}
}
static PyObject* Document_metadata(DocumentObject* self, void* closure)
{
PyObject* ret;
try
{
if (!self->doc) throw runtime_error{ "doc is null!" };
#ifdef TM_GDMR
ret = Document_GDMR_metadata(self, closure);
if (ret) return ret;
#endif
#ifdef TM_DMR
ret = Document_DMR_metadata(self, closure);
if (ret) return ret;
#endif
throw runtime_error{ "doc doesn't has `metadata` field!" };
}
catch (const bad_exception&)
{
return nullptr;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return nullptr;
}
}
static PyGetSetDef Document_getseters[] = {
{ (char*)"words", (getter)Document_words, nullptr, Document_words__doc__, nullptr },
{ (char*)"weight", (getter)Document_weight, nullptr, Document_weight__doc__, nullptr },
{ (char*)"topics", (getter)Document_Z, nullptr, Document_topics__doc__, nullptr },
#ifdef TM_DMR
{ (char*)"metadata", (getter)Document_metadata, nullptr, Document_metadata__doc__, nullptr },
#endif
#ifdef TM_PA
{ (char*)"subtopics", (getter)Document_Z2, nullptr, Document_subtopics__doc__, nullptr },
#endif
#ifdef TM_MGLDA
{ (char*)"windows", (getter)Document_windows, nullptr, Document_windows__doc__, nullptr },
#endif
#ifdef TM_HLDA
{ (char*)"path", (getter)Document_path, nullptr, Document_path__doc__, nullptr },
#endif
#ifdef TM_CT
{ (char*)"beta", (getter)Document_beta, nullptr, Document_beta__doc__, nullptr },
#endif
#ifdef TM_SLDA
{ (char*)"vars", (getter)Document_y, nullptr, Document_vars__doc__, nullptr },
#endif
#ifdef TM_LLDA
{ (char*)"labels", (getter)Document_labels, nullptr, Document_labels__doc__, nullptr },
#endif
#ifdef TM_DT
{ (char*)"eta", (getter)Document_eta, nullptr, Document_eta__doc__, nullptr },
{ (char*)"timepoint", (getter)Document_timepoint, nullptr, Document_timepoint__doc__, nullptr },
#endif
{ nullptr },
};
PyTypeObject Document_type = {
PyVarObject_HEAD_INIT(nullptr, 0)
"tomotopy.Document", /* tp_name */
sizeof(DocumentObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)DocumentObject::dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc)DocumentObject::repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
Document___init____doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Document_methods, /* tp_methods */
0, /* tp_members */
Document_getseters, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)Document_init, /* tp_init */
PyType_GenericAlloc,
PyType_GenericNew,
};
static Py_ssize_t Corpus_len(CorpusObject* self)
{
try
{
if (!self->parentModel->inst) throw runtime_error{ "inst is null" };
return self->parentModel->inst->getNumDocs();
}
catch (const bad_exception&)
{
return -1;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return -1;
}
}
static PyObject* Corpus_getitem(CorpusObject* self, Py_ssize_t key)
{
try
{
if (!self->parentModel->inst) throw runtime_error{ "inst is null" };
if (key >= self->parentModel->inst->getNumDocs())
{
PyErr_SetString(PyExc_IndexError, "");
throw bad_exception{};
}
py::UniqueObj args = Py_BuildValue("(Onn)", self->parentModel, key, 0);
return PyObject_CallObject((PyObject*)&Document_type, args);
}
catch (const bad_exception&)
{
return nullptr;
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return nullptr;
}
}
static int Corpus_init(CorpusObject *self, PyObject *args, PyObject *kwargs)
{
PyObject* argParent;
static const char* kwlist[] = { "f", nullptr };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O", (char**)kwlist, &argParent)) return -1;
try
{
self->parentModel = (TopicModelObject*)argParent;
Py_INCREF(argParent);
}
catch (const exception& e)
{
PyErr_SetString(PyExc_Exception, e.what());
return -1;
}
return 0;
}
static PySequenceMethods Corpus_seq_methods = {
(lenfunc)Corpus_len,
nullptr,
nullptr,
(ssizeargfunc)Corpus_getitem,
};
PyTypeObject Corpus_type = {
PyVarObject_HEAD_INIT(nullptr, 0)
"tomotopy._Corpus", /* tp_name */
sizeof(CorpusObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)CorpusObject::dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
&Corpus_seq_methods, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PySeqIter_New, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)Corpus_init, /* tp_init */
PyType_GenericAlloc,
PyType_GenericNew,
};
PyMODINIT_FUNC MODULE_NAME()
{
import_array();
static PyModuleDef mod =
{
PyModuleDef_HEAD_INIT,
"tomotopy",
"Tomoto Module for Python",
-1,
nullptr,
};
gModule = PyModule_Create(&mod);
if (!gModule) return nullptr;
if (PyType_Ready(&Document_type) < 0) return nullptr;
Py_INCREF(&Document_type);
PyModule_AddObject(gModule, "Document", (PyObject*)&Document_type);
if (PyType_Ready(&Corpus_type) < 0) return nullptr;
Py_INCREF(&Corpus_type);
PyModule_AddObject(gModule, "_Corpus", (PyObject*)&Corpus_type);
if (PyType_Ready(&Dictionary_type) < 0) return nullptr;
Py_INCREF(&Dictionary_type);
PyModule_AddObject(gModule, "Dictionary", (PyObject*)&Dictionary_type);
if (PyType_Ready(&LDA_type) < 0) return nullptr;
Py_INCREF(&LDA_type);
PyModule_AddObject(gModule, "LDAModel", (PyObject*)&LDA_type);
#ifdef TM_DMR
if (PyType_Ready(&DMR_type) < 0) return nullptr;
Py_INCREF(&DMR_type);
PyModule_AddObject(gModule, "DMRModel", (PyObject*)&DMR_type);
#endif
#ifdef TM_HDP
if (PyType_Ready(&HDP_type) < 0) return nullptr;
Py_INCREF(&HDP_type);
PyModule_AddObject(gModule, "HDPModel", (PyObject*)&HDP_type);
#endif
#ifdef TM_MGLDA
if (PyType_Ready(&MGLDA_type) < 0) return nullptr;
Py_INCREF(&MGLDA_type);
PyModule_AddObject(gModule, "MGLDAModel", (PyObject*)&MGLDA_type);
#endif
#ifdef TM_PA
if (PyType_Ready(&PA_type) < 0) return nullptr;
Py_INCREF(&PA_type);
PyModule_AddObject(gModule, "PAModel", (PyObject*)&PA_type);
#endif
#ifdef TM_HPA
if (PyType_Ready(&HPA_type) < 0) return nullptr;
Py_INCREF(&HPA_type);
PyModule_AddObject(gModule, "HPAModel", (PyObject*)&HPA_type);
#endif
#ifdef TM_HLDA
if (PyType_Ready(&HLDA_type) < 0) return nullptr;
Py_INCREF(&HLDA_type);
PyModule_AddObject(gModule, "HLDAModel", (PyObject*)&HLDA_type);
#endif
#ifdef TM_CT
if (PyType_Ready(&CT_type) < 0) return nullptr;
Py_INCREF(&CT_type);
PyModule_AddObject(gModule, "CTModel", (PyObject*)&CT_type);
#endif
#ifdef TM_SLDA
if (PyType_Ready(&SLDA_type) < 0) return nullptr;
Py_INCREF(&SLDA_type);
PyModule_AddObject(gModule, "SLDAModel", (PyObject*)&SLDA_type);
#endif
#ifdef TM_LLDA
if (PyType_Ready(&LLDA_type) < 0) return nullptr;
Py_INCREF(&LLDA_type);
PyModule_AddObject(gModule, "LLDAModel", (PyObject*)&LLDA_type);
#endif
#ifdef TM_PLDA
if (PyType_Ready(&PLDA_type) < 0) return nullptr;
Py_INCREF(&PLDA_type);
PyModule_AddObject(gModule, "PLDAModel", (PyObject*)&PLDA_type);
#endif
#ifdef TM_DT
if (PyType_Ready(&DT_type) < 0) return nullptr;
Py_INCREF(&DT_type);
PyModule_AddObject(gModule, "DTModel", (PyObject*)&DT_type);
#endif
#ifdef TM_GDMR
if (PyType_Ready(&GDMR_type) < 0) return nullptr;
Py_INCREF(&GDMR_type);
PyModule_AddObject(gModule, "GDMRModel", (PyObject*)&GDMR_type);
#endif
#ifdef __AVX2__
PyModule_AddStringConstant(gModule, "isa", "avx2");
#elif defined(__AVX__)
PyModule_AddStringConstant(gModule, "isa", "avx");
#elif defined(__SSE2__) || defined(__x86_64__) || defined(_WIN64)
PyModule_AddStringConstant(gModule, "isa", "sse2");
#else
PyModule_AddStringConstant(gModule, "isa", "none");
#endif
PyObject* sModule = makeLabelModule();
if (!sModule) return nullptr;
Py_INCREF(sModule);
PyModule_AddObject(gModule, "label", sModule);
return gModule;
}
| 28.249304 | 133 | 0.628556 | [
"vector"
] |
5d9ea131fd99d6a08cf2c372f589a08291d9b153 | 5,864 | hpp | C++ | escos/src/mmitss/SignalControl/mmitssSignalControl.hpp | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | escos/src/mmitss/SignalControl/mmitssSignalControl.hpp | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | escos/src/mmitss/SignalControl/mmitssSignalControl.hpp | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <array>
#include <cstdint>
#include <future>
#include <string>
#include <vector>
#include "ConnectedVehicle.h"
#include "Schedule.h"
#include "Config.h"
#include "Mib.h"
#include "Signal.h"
#include "COP_DUAL_RING.h"
#include "siekdbus.hpp"
#include "udpReceiver.hpp"
namespace WaveApp
{
namespace Mmitss
{
class MmitssSignalControlApp;
class MmitssSignalControl
{
public:
using ScheduleList = std::vector<Schedule>;
using ConnectedVehicleList = std::vector<ConnectedVehicle>;
MmitssSignalControl(MmitssSignalControlApp& parent);
virtual ~MmitssSignalControl() = default;
MmitssSignalControl(const MmitssSignalControl&) = delete;
MmitssSignalControl& operator=(const MmitssSignalControl&) = delete;
virtual bool onStartup();
virtual void onShutdown();
virtual void onExit();
void tick();
bool mmitssInit();
private:
static constexpr const uint32_t DEFAULT_TIMER_DELAY_MS = 500;
bool loadMmitssConfig();
void onTimer(siekdbus::timerid_t id);
void requestTrajectory();
void resetArrivalTableInDb();
void storeArrivalTableInDb();
void Construct_eventlist();
void Pack_Event_List(uint8_t* tmp_event_data, int& size);
void onCriticalPointsReceive(const void* data, size_t len);
void onTrajectoryReceive(const void* data, size_t len);
void Find_Passed_Phase_In_Same_Barrier();
int ConflictCall();
void UnpackTrajData1(const char* ablob);
int CheckConflict();
void ModifyCurPhase();
void Complete_Barrier();
// Config
bool ReadSignalParameters();
bool get_lane_no();
MmitssSignalControlApp& m_parent;
uint32_t m_timerInterval{DEFAULT_TIMER_DELAY_MS};
siekdbus::timerid_t m_timerId{0};
siekdbus::TimerConn m_timerConn;
UdpReceiver m_criticalPointsReceiver;
UdpReceiver m_trajectoryReceiver;
std::string m_testSystemAddr;
// MMITSS members
ConnectedVehicleList m_trackedVeh;
ConnectedVehicleList m_vehListEachPhase;
ScheduleList m_eventListR1;
ScheduleList m_eventListR2;
// occupancy value of the detector at stop bar (using as the system detector)
std::vector<int> m_occupancy;
// Parameters for trajectory control
// maximum planning time horizon * number of phases
std::array<std::array<int, 8>, 131> m_arrivalTable;
// previous phases of the two rings, either one ring advanced,
// the previous_phases need to be updated,used to calculate passed phases. [1-8]
int m_previousPhase[2]{};
// passed phase in the same ring, [0-7];
int m_passedPhase[2]{};
// if no vehicle arrives for a phase, then this phase can be skipped.
int m_skipPhase[8]{};
// timer to hold the phase;
int m_holdTimer{0};
// this is the time point (at the time point left turn green turns to yellow)
// to check the ped signal state;
// only applies to leading left turn, when ped button is pushed when left turn is on
int m_check_TimePoint{99999};
// current time
int m_currentTime{0};
// the optimal signal plan of 3 barriers generated by DUAL RING COP
std::array<std::array<int, 4>, 2> m_optSigPlan;
// the optimal signal sequence of 3 barriers generated by DUAL RING COP
std::array<std::array<int, 4>, 2> m_optSigSeq;
// Parameters for EVLS
float m_penetrationRate{1.0};
float m_dsrcRange{300};
// value would be {1,3,4}
int m_phaseNum{};
int m_phaseSeq[8]{};
std::array<int, 8> m_minGreen;
std::array<int, 8> m_maxGreen;
std::array<int, 8> m_yellow;
std::array<int, 8> m_red;
std::array<int, 8> m_pedWalk;
std::array<int, 8> m_pedClr;
// Whether there is a ped call or ped phase is on
// 0: on call and all phase is off 1: yes
int m_pedStatus{};
//[0]: ped status, [1]: ped call in integer number;
// int m_pedInfo[2] {};
// Which ped phase need to be considered in the COP, 1:yes, 0: no;
// int m_pedPhaseConsidered[8] {};
// 0 if left turn phases have queuing vehicle <10; 1 if else
// This flag is used to prevent queue spill back from left turn bay.
int m_queueWarningP1{};
int m_queueWarningP5{};
int m_initPhase[2]{};
int m_currPhase[2]{};
double m_InitTime[2]{};
double m_grnElapse[2]{};
// Red elapse time of each phase
std::array<double, 8> m_redElapseTime;
// Type of objective function that used in COP; 0= total delay 1=average vehicle delay
int m_delayType{};
// This is the number of lanes of each phase, this determines discharging rate
std::array<int, 8> m_laneNo;
// int rolling_horizon; //every 7 seconds, solve COP
int m_beginTime{};
int m_controlTimer{};
// used to switch between solving COP and control the signal
int m_controlFlag{};
// Whether there is a vehicle coming from the conflict phase
int m_conflictFlag{};
// Record current red elapse time information
// Notes: since COP always runs at the beginning of the green time
// (2 phases), actually we should calculate the duration of previous
// red phase for the queue length estimation for the 2 phases just
// turned red, the red duration time could be 0 (or in actually
// calculation they are very small)
// for other four phases, just in the middle of red duration
double m_redStartTime[8]{};
int m_previousSignalColor[8]{};
std::string m_rsuId;
RsuConfig m_cfg;
Phase m_phases;
MmitssMib m_mib;
bool m_started{false};
std::future<bool> m_delayedInit;
CopDualRing m_cop;
// for requesting trajectory data
int m_sockfd{-1};
struct sockaddr_in m_recvAddr;
uint32_t m_reqCount{0};
uint32_t m_lastAckCount{0};
friend CopDualRing;
};
} // namespace Mmitss
} // namespace WaveApp
| 30.071795 | 90 | 0.688438 | [
"vector"
] |
5da14d083305bb964f4c8b06e0ac0045a2f05e7d | 2,422 | cpp | C++ | EuclideanAlgorithmCalculator/EuclideanAlgorithmCalculator.cpp | EdwinTrejo/CMPE691 | 10af51e4ff49ae19e5cefcf4b20cacc33373209b | [
"MIT"
] | null | null | null | EuclideanAlgorithmCalculator/EuclideanAlgorithmCalculator.cpp | EdwinTrejo/CMPE691 | 10af51e4ff49ae19e5cefcf4b20cacc33373209b | [
"MIT"
] | null | null | null | EuclideanAlgorithmCalculator/EuclideanAlgorithmCalculator.cpp | EdwinTrejo/CMPE691 | 10af51e4ff49ae19e5cefcf4b20cacc33373209b | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <vector>
#include <cstdio>
using namespace std;
int checkInputInt(int& getNum);
int findGcd(int& bigNum, int& smallNum);
unsigned int smallNumberVectorSize, bigNumberVectorSize;
int bigNumber, smallNumber, nextSmall, modGet, gcd;
vector<int> smallNumberVector;
vector<int> bigNumberVector;
//TODO thought process, create a loop that will go until nextSmall is zero 0.
//to fill up the vectors and then sequentially display the variables inside the vectors.
//check for correct input and correct big number small number input.
//check for 0 input to avoid runtime errors.
int main() {
cout << "This is a program that tries to calculate the Greatest Common Divisor\n";
cout << "(GCD) for two numbers. It uses the Eucledian Algorithm.\n";
//ask for input
cout << "Big Number: \n";
cin >> bigNumber;
bigNumber = checkInputInt(bigNumber);
cout << "Small Number: \n";
cin >> smallNumber;
smallNumber = checkInputInt(smallNumber);
//add to vector
smallNumberVector.push_back(smallNumber);
bigNumberVector.push_back(bigNumber);
//execution
gcd = findGcd(bigNumber, smallNumber);
//result
cout << "GCD: " << gcd << endl;
getchar();
return 0;
}
int checkInputInt(int& getNum) {
int holdNum = getNum;
if (holdNum < 0)
holdNum = holdNum * -1;
return holdNum;
}
int findGcd(int& bigNum, int& smallNum) {
//calculate test
bigNumber = bigNum;
smallNum = smallNumber;
do {
if (smallNumber == 0)
break;
modGet = bigNumber / smallNumber;
nextSmall = bigNumber - (smallNumber * modGet);
bigNumber = smallNumber;
smallNumber = nextSmall;
smallNumberVector.push_back(smallNumber);
bigNumberVector.push_back(bigNumber);
} while (smallNumber >= 0);
//a loop to display the output of the vectors
for (bigNumberVectorSize = 0; bigNumberVectorSize < bigNumberVector.size(); bigNumberVectorSize++) {
cout << "Big Number: " << bigNumberVector[bigNumberVectorSize] << endl;
}
for (smallNumberVectorSize = 0; smallNumberVectorSize < smallNumberVector.size(); smallNumberVectorSize++) {
cout << "Small Number: " << smallNumberVector[smallNumberVectorSize] << endl;
}
bigNumberVectorSize = bigNumberVector.size() - 1;
return bigNumberVector[bigNumberVectorSize];
}
| 29.180723 | 112 | 0.681255 | [
"vector"
] |
5da89cf745e0bf917afb46fb6f6041beeeb61d7f | 1,481 | cc | C++ | solutions/cses/range-queries/1647.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 4 | 2020-11-07T14:38:02.000Z | 2022-01-03T19:02:36.000Z | solutions/cses/range-queries/1647.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 1 | 2019-04-17T06:55:14.000Z | 2019-04-17T06:55:14.000Z | solutions/cses/range-queries/1647.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <climits>
#include <cmath>
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
typedef long long ll;
typedef long double ld;
void build(vector<int> &a, vector<int> &t, int v, int tl, int tr) {
if (tl == tr) {
t[v] = a[tl];
} else {
int tm = tl + (tr - tl) / 2;
build(a, t, v * 2, tl, tm);
build(a, t, v * 2 + 1, tm + 1, tr);
t[v] = min(t[v * 2], t[v * 2 + 1]);
}
}
int query(vector<int> &t, int v, int tl, int tr, int l, int r) {
if (l > r) {
return 1e9 + 1;
}
if (tl == l && tr == r) {
return t[v];
}
int tm = tl + (tr - tl) / 2;
return min(query(t, v * 2, tl, tm, l, min(tm, r)),
query(t, v * 2 + 1, tm + 1, tr, max(l, tm + 1), r));
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
// Range minimum queries on a static array
// Use a standard segment tree
// We can use something like a sparse table here as well,
// but I haven't learnt that. :D
int n, q;
cin >> n >> q;
vector<int> x(n);
for (int &i : x) cin >> i;
vector<int> t(n * 4);
build(x, t, 1, 0, n - 1);
while (q--) {
int a, b;
cin >> a >> b;
cout << query(t, 1, 0, n - 1, a - 1, b - 1) << '\n';
}
}
| 21.157143 | 67 | 0.546928 | [
"vector"
] |
5daa6f4ea5423f44dba16be6b7d4737386289acb | 2,486 | cpp | C++ | practical_2/bullet.cpp | 40330977/Games_Engineering_1 | 3a01f8fb31707cdabe657a7900992b8624ec38b7 | [
"MIT"
] | null | null | null | practical_2/bullet.cpp | 40330977/Games_Engineering_1 | 3a01f8fb31707cdabe657a7900992b8624ec38b7 | [
"MIT"
] | null | null | null | practical_2/bullet.cpp | 40330977/Games_Engineering_1 | 3a01f8fb31707cdabe657a7900992b8624ec38b7 | [
"MIT"
] | null | null | null | //bullet.cpp
#include "bullet.h"
#include "game.h"
#include "Ship.h"
#include <iostream>
using namespace sf;
using namespace std;
Bullet::Bullet() :Sprite() {
setTexture(spritesheet);
//setTextureRect(sf::IntRect(0, 0, 32, 32));
setOrigin(16, 16);
//setPosition(sf::Vector2f(-64.0f,-64.0f));
setPosition(sf::Vector2f(200.0f, 200.0f));
};
unsigned char Bullet::bulletPointer = 0;
Bullet Bullet::bullets[256];
//Create definition for the constructor
//...
/*Bullet::Bullet(const sf::Vector2f &pos, const bool mode) : Sprite()
{
//setPosition(pos);
//_mode = mode;
}*/
void Bullet::_Update(const float & dt)
{//git status
/*auto p = getPosition();
if(p.y > -16.0f && p.y < (gameHeight+16.0f)){
move(0, dt * 200.0f * (_mode ? 1.0f : -1.0f));
}*/
if (getPosition().y < -32 || getPosition().y > gameHeight + 32) {
//off screen - do nothing
return;
}
else {
move(0, dt * 200.0f * (_mode ? 1.0f : -1.0f));
const FloatRect boundingBox = getGlobalBounds();
for (auto s : ships) {
if (!_mode && s == player) {
//player bulelts don't collide with player
continue;
}
if (_mode && s != player) {
//invader bullets don't collide with other invaders
continue;
}
if (!s->is_exploded() &&
s->getGlobalBounds().intersects(boundingBox)) {
//Explode the ship
s->Explode();
//warp bullet off-screen
setPosition(-100, -100);
return;
}
}
}
}
//void Render(sf::RenderWindow &window);
void Bullet::Update(const float &dt) {
/*if (Keyboard::isKeyPressed(Keyboard::D)) {
_mode = false;
Fire(player->getPosition(), _mode);
}*/
//Bullet b = bullets[bulletPointer];
for ( auto &b : bullets) {
//Bullet b = bullets[bulletpointer];
//bullets->move(0, dt * 200.0f * (b->_mode ? 1.0f : -1.0f));
b._Update(dt);
}
}
void Bullet::Render(sf::RenderWindow & window)
{
for ( auto &b : bullets) {
//Bullet b = bullets[bulletPointer];
window.draw(b);
//cout << "render" << endl;
}
}
//
void Bullet::Fire(const sf::Vector2f & pos, const bool mode)
{
Bullet* b1 = &bullets[++bulletPointer];
b1->setPosition(pos);
b1->_mode = mode;
//b1->setPosition(sf::Vector2f(500.0f, 500.0f));
//if (mode == false) {
//b1._mode = mode;
//b1.setTexture(spritesheet);
b1->setTextureRect(sf::IntRect(64, 32, 32, 32));
cout << "fire" << endl;
//b1.setTextureRect(IntRect(160, 32, 32, 32));
//b1.Update(dt);
//}
}
void Ship::Explode() {
setTextureRect(IntRect(128, 32, 32, 32));
_exploded = true;
}
| 20.716667 | 69 | 0.61786 | [
"render"
] |
5dba5e1801a7e938fda10431bb3b298e89719222 | 4,537 | cpp | C++ | src/route/replication_response_handler.cpp | audreyccheng/anna | f9a39207e9b6519f850a5be381b0be26aeac281d | [
"Apache-2.0"
] | 2 | 2021-03-17T21:39:58.000Z | 2022-01-12T18:36:47.000Z | src/route/replication_response_handler.cpp | audreyccheng/anna | f9a39207e9b6519f850a5be381b0be26aeac281d | [
"Apache-2.0"
] | 3 | 2021-06-02T02:39:40.000Z | 2021-06-23T01:58:14.000Z | src/route/replication_response_handler.cpp | audreyccheng/anna | f9a39207e9b6519f850a5be381b0be26aeac281d | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 U.C. Berkeley RISE Lab
//
// 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 "route/routing_handlers.hpp"
void replication_response_handler(
logger log, string &serialized, SocketCache &pushers, RoutingThread &rt,
GlobalRingMap &global_hash_rings, LocalRingMap &local_hash_rings,
map<Key, KeyReplication> &key_replication_map,
map<Key, vector<pair<Address, string>>> &pending_requests, unsigned &seed) {
TxnResponse response;
response.ParseFromString(serialized);
// we assume tuple 0 because there should only be one tuple responding to a
// replication factor request
TxnKeyTuple tuple = response.tuples(0);
Key key = get_key_from_metadata(tuple.key());
Tier key_tier = get_tier_from_anna_tier(response.tier());
AnnaError error = tuple.error();
if (error == AnnaError::NO_ERROR) {
// LWWValue lww_value;
// lww_value.ParseFromString(tuple.payload());
ReplicationFactor rep_data;
rep_data.ParseFromString(tuple.payload());
for (const auto &global : rep_data.global()) {
key_replication_map[key].global_replication_[global.tier()] =
global.value();
}
for (const auto &local : rep_data.local()) {
key_replication_map[key].local_replication_[local.tier()] = local.value();
}
} else if (error == AnnaError::KEY_DNE) {
// this means that the receiving thread was responsible for the metadata
// but didn't have any values stored -- we use the default rep factor
init_tier_replication(key_replication_map, key, key_tier);
} else if (error == AnnaError::WRONG_THREAD) {
// this means that the node that received the rep factor request was not
// responsible for that metadata
auto respond_address = rt.replication_response_connect_address();
kHashRingUtil->issue_replication_factor_request(
respond_address, response.type(), response.txn_id(), key, key_tier, global_hash_rings[key_tier],
local_hash_rings[key_tier], pushers, seed, log);
return;
} else {
log->error("Unexpected error type {} in replication factor response.",
error);
return;
}
log->info("Routing replication factor response received for key {}", key);
// process pending key address requests
if (pending_requests.find(key) != pending_requests.end()) {
bool succeed;
ServerThreadList threads = {};
// for (const Tier &tier : kAllTiers) {
// // Only txn tier should serve txn requests and vice versa for storage tiers
// if (txn_tier && tier != Tier::TXN ||
// !txn_tier && tier == Tier::TXN) {
// continue;
// }
threads = kHashRingUtil->get_responsible_threads(
rt.replication_response_connect_address(), response.type(),
response.txn_id(), key, false,
global_hash_rings, local_hash_rings, key_replication_map, pushers,
{key_tier}, succeed, seed, log);
// if (threads.size() > 0) {
// break;
// }
if (!succeed || threads.size() == 0) { // TOD(@accheng): needed?
log->error("Missing replication factor for key {}.", key);
return;
}
// }
for (const auto &pending_key_req : pending_requests[key]) {
KeyAddressResponse key_res;
key_res.set_response_id(pending_key_req.second);
auto *tp = key_res.add_addresses();
tp->set_key(key);
// TODO(@accheng): should just be 1 thread? separate method for primary thread?
for (const ServerThread &thread : threads) {
// send transaction or storage request handler addresses
if (key_tier == Tier::TXN) {
tp->add_ips(thread.txn_request_connect_address());
} else {
tp->add_ips(thread.storage_request_connect_address());
}
// TODO(@accheng): would we ever want the logging handler?
}
string serialized;
key_res.SerializeToString(&serialized);
kZmqUtil->send_string(serialized, &pushers[pending_key_req.first]);
}
pending_requests.erase(key);
}
}
| 38.12605 | 102 | 0.678863 | [
"vector"
] |
5dc13c32c41833e25deb51bab42677b97baf040d | 13,151 | cpp | C++ | FalcasEngine/Source Code/ComponentTransform2D.cpp | Falcas-Games/Falcas-Engine | a16316a246b7e7cf88b7362e0af9e9709085cc26 | [
"MIT"
] | null | null | null | FalcasEngine/Source Code/ComponentTransform2D.cpp | Falcas-Games/Falcas-Engine | a16316a246b7e7cf88b7362e0af9e9709085cc26 | [
"MIT"
] | null | null | null | FalcasEngine/Source Code/ComponentTransform2D.cpp | Falcas-Games/Falcas-Engine | a16316a246b7e7cf88b7362e0af9e9709085cc26 | [
"MIT"
] | null | null | null | #include "ComponentTransform2D.h"
#include "ComponentTransform.h"
#include "External Libraries/ImGui/imgui.h"
#include "External Libraries/MathGeoLib/include/Math/float3x3.h"
#include "Application.h"
#include "ModuleSceneIntro.h"
#include "ModuleRenderer3D.h"
#include "GameObject.h"
#include "ModuleWindow.h"
#include "ComponentCamera.h"
#include "ComponentUI.h"
#define M_PI 3.14159265358979323846f
ComponentTransform2D::ComponentTransform2D(GameObject* owner, float2 position, Quat rotation, float2 size) :Component(Component_Type::Transform2D, owner, "Transform2D"), position(position),
size(size), z_depth(10), z_depth_with_layers(10)
{
relative_size.x = App->window->width / size.x;
relative_size.y = App->window->height / size.y;
relative_position.x = App->window->width / position.x;
relative_position.y = App->window->height / position.y;
this->rotation = QuaternionToEuler(rotation);
SetMatrices();
float* camera_view_matrix = App->renderer3D->camera->GetViewMatrix();
}
ComponentTransform2D::~ComponentTransform2D()
{
}
void ComponentTransform2D::Update()
{
if (App->renderer3D->resized) {
size.x = App->window->width / relative_size.x;
size.y = App->window->height / relative_size.y;
position.x = App->window->width / relative_position.x;
position.y = App->window->height / relative_position.y;
needed_to_update = true;
}
if (UpdateMatrixBillboard() && !needed_to_update)
return;
needed_to_update = true;
SetMatrices();
}
float2 ComponentTransform2D::GetPosition()const
{
return position;
}
float3 ComponentTransform2D::GetRotation()const
{
return rotation;
}
float2 ComponentTransform2D::GetSize()const
{
return size;
}
float4x4 ComponentTransform2D::GetGlobalMatrix() const
{
return global_matrix;
}
float4x4 ComponentTransform2D::GetGlobalMatrixTransposed() const
{
return global_matrix_transposed;
}
bool ComponentTransform2D::SaveComponent(JsonObj& obj)
{
float3 pos = { position.x,position.y,z_depth };
obj.AddFloat3("Position", pos);
obj.AddQuat("Rotation", EulerToQuaternion(rotation));
float3 siz = { size.x,size.y,0 };
obj.AddFloat3("Size", siz);
float3 pivot = { pivot_position.x,pivot_position.y,0 };
obj.AddFloat3("Pivot", pivot);
return true;
}
void ComponentTransform2D::SetTransformation(float3 pos, Quat rot, float2 size, float3 pivot)
{
position = { pos.x,pos.y };
z_depth = pos.z;
rotation = QuaternionToEuler(rot);
this->size = size;
pivot_position={ pivot.x,pivot.y };
relative_size.x = App->window->width / size.x;
relative_size.y = App->window->height / size.y;
relative_position.x = App->window->width / position.x;
relative_position.y = App->window->height / position.y;
needed_to_update = true;
}
void ComponentTransform2D::SetPivot(float3 pivot)
{
pivot_position = { pivot.x,pivot.y };
}
void ComponentTransform2D::SetPosition(float2 pos)
{
position = pos;
relative_position.x = App->window->width / position.x;
relative_position.y = App->window->height / position.y;
needed_to_update = true;
}
void ComponentTransform2D::SetRotation(Quat rot)
{
rotation = QuaternionToEuler(rot);
needed_to_update = true;
}
void ComponentTransform2D::SetRotation(float3 rot)
{
rotation = rot;
needed_to_update = true;
}
void ComponentTransform2D::SetSize(float2 size)
{
this->size = size;
relative_size.x = App->window->width / size.x;
relative_size.y = App->window->height / size.y;
needed_to_update = true;
}
void ComponentTransform2D::UpdateZ()
{
if (owner->components.size() > 1) {
z_depth_with_layers = z_depth * ((ComponentUI*)owner->components[1])->layer_of_ui + z_depth;
}
else {
z_depth_with_layers = z_depth;
}
}
bool ComponentTransform2D::UpdateMatrixBillboard()
{
ComponentTransform* trans = (ComponentTransform*)App->renderer3D->camera->owner->GetComponent(Component_Type::Transform);
Quat rot = trans->GetRotation();
float3 pos = trans->GetPosition();
float4x4 matrix_billboard_last_frame = matrix_billboard;
matrix_billboard = matrix_billboard.FromTRS(pos, rot, { 1,1,1 });
return matrix_billboard.Equals(matrix_billboard_last_frame);
}
void ComponentTransform2D::SetMatrices()
{
float3 pivot_world = { pivot_position.x + position.x, pivot_position.y + position.y, 0 };
float3 rotation_in_gradians = rotation * DEGTORAD;
Quat rotate = Quat::identity * Quat::identity.RotateZ(rotation_in_gradians.z);
matrix_pivot = matrix_pivot.FromTRS(pivot_world, rotate, { 1,1,1 });
local_matrix = local_matrix.FromTRS({ -pivot_position.x,-pivot_position.y,z_depth_with_layers }, Quat::identity, { size.x,size.y,1 } );
if (owner->parent != nullptr) {
if (owner->parent->IsUI()) {
ComponentTransform2D* parent_trans = (ComponentTransform2D*)owner->parent->GetComponent(Component_Type::Transform2D);
matrix_parent = parent_trans->GetGlobalMatrix();
matrix_parent = parent_trans->matrix_billboard.Inverted() * matrix_parent;
}
else {
ComponentTransform* parent_trans = (ComponentTransform*)owner->parent->GetComponent(Component_Type::Transform);
matrix_parent = parent_trans->GetGlobalMatrix();
}
}
else matrix_parent = float4x4::identity;
global_matrix = matrix_billboard * matrix_parent * matrix_pivot * local_matrix;
global_matrix_transposed = global_matrix.Transposed();
}
void ComponentTransform2D::SetMatricesWithNewParent(float4x4 parent_global_matrix)
{
UpdateMatrixBillboard();
float4x4 local_matrix_with_rotation = parent_global_matrix.Inverted() * matrix_billboard.Inverted() * global_matrix;
float3 pos, s;
Quat rot;
local_matrix_with_rotation.Decompose(pos, rot, s);
rotation = QuaternionToEuler(rot);
local_matrix = matrix_pivot.Inverted() * local_matrix_with_rotation;
local_matrix.Decompose(pos, rot, s);
position = { pos.x,pos.y };
z_depth = pos.z;
if (owner->components.size() > 1) {
z_depth_with_layers = z_depth * ((ComponentUI*)owner->components[1])->layer_of_ui + z_depth;
}
else {
z_depth_with_layers = z_depth;
}
size = { s.x,s.y };
relative_size.x = App->window->width / size.x;
relative_size.y = App->window->height / size.y;
relative_position.x = App->window->width / position.x;
relative_position.y = App->window->height / position.y;
needed_to_update = true;
needed_to_update_only_children = true;
}
float3 ComponentTransform2D::QuaternionToEuler(Quat q)
{
float3 rotation_euler = q.ToEulerXYZ();
rotation_euler *= RADTODEG;
return rotation_euler;
}
Quat ComponentTransform2D::EulerToQuaternion(float3 eu)
{
eu *= DEGTORAD;
Quat q = Quat::FromEulerXYZ(eu.x, eu.y, eu.z);
return q;
}
Quat ComponentTransform2D::LookAt(const float3& point)
{
float3 vector = {position.x, position.x, 0};
vector = point - vector;
float3x3 matrix = float3x3::LookAt(float3::unitZ, vector.Normalized(), float3::unitY, float3::unitY);
return matrix.ToQuat();
}
float2 ComponentTransform2D::CalculateMovement(float4x4 matrix, float2 goal)
{
float2 movement;
movement.y = (matrix[0][0] * (goal.y - matrix[1][3]) - matrix[1][0] * (goal.x - matrix[0][3])) / (matrix[1][1] * matrix[0][0] - matrix[0][1] * matrix[1][0]);
movement.x = (goal.x - matrix[0][1] * movement.y - matrix[0][3]) / matrix[0][0];
float second_option= (goal.y - matrix[1][1] * movement.y - matrix[1][3]) / matrix[1][0];
if (movement.x != goal.x && ((second_option - goal.x<0 && second_option - goal.x> movement.x) || (second_option - goal.x > 0 && second_option - goal.x < movement.x))) {
movement.x = second_option;
}
return movement;
}
void ComponentTransform2D::Inspector()
{
float null = 0;
int null_int = 0;
ImGui::PushID(name.c_str());
ImGui::Separator();
ImGui::Columns(4, "", false);
ImGui::AlignTextToFramePadding();
ImGui::Text("Position");
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("X");
ImGui::SameLine();
ImGui::PushItemWidth(50);
if (ImGui::DragFloat("##0", (active && owner->active) ? &position.x : &null, 0.01f) && (active && owner->active)) {
relative_position.x = App->window->width / position.x;
relative_position.y = App->window->height / position.y;
needed_to_update = true;
}
ImGui::PopItemWidth();
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("Y");
ImGui::SameLine();
ImGui::PushItemWidth(50);
if (ImGui::DragFloat("##1", (active && owner->active) ? &position.y : &null, 0.01f) && (active && owner->active)) {
relative_position.x = App->window->width / position.x;
relative_position.y = App->window->height / position.y;
needed_to_update = true;
}
ImGui::PopItemWidth();
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("Z");
ImGui::SameLine();
ImGui::PushItemWidth(50);
if (ImGui::DragFloat("##2", (active && owner->active) ? &z_depth : &null, 0.01f) && (active && owner->active)) {
UpdateZ();
needed_to_update = true;
}
ImGui::PopItemWidth();
ImGui::Columns(2, "", false);
ImGui::AlignTextToFramePadding();
ImGui::Text("Rotation");
ImGui::SameLine();
ImGui::PushItemWidth(50);
if (ImGui::DragFloat("##5", (active && owner->active) ? &rotation.z : &null, 0.01f) && (active && owner->active))
needed_to_update = true;
ImGui::PopItemWidth();
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("Layer");
ImGui::SameLine();
ImGui::PushItemWidth(50);
if (ImGui::DragInt("##6", (active && owner->active && owner->components.size() > 1) ? &((ComponentUI*)owner->components[1])->layer_of_ui : &null_int, 0.01,-1, 10) && (active && owner->active)) {
UpdateZ();
needed_to_update = true;
}
ImGui::PopItemWidth();
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("Final Z: %.2f",z_depth_with_layers);
ImGui::Columns(3, "", false);
ImGui::AlignTextToFramePadding();
ImGui::Text("Size");
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("X");
ImGui::SameLine();
ImGui::PushItemWidth(50);
if (ImGui::DragFloat("##7", (active && owner->active) ? &size.x : &null, 0.01f) && (active && owner->active)) {
relative_size.x = App->window->width / size.x;
relative_size.y = App->window->height / size.y;
needed_to_update = true;
}
ImGui::PopItemWidth();
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("Y");
ImGui::SameLine();
ImGui::PushItemWidth(50);
if (ImGui::DragFloat("##8", (active && owner->active) ? &size.y : &null, 0.01f) && (active && owner->active)) {
relative_size.x = App->window->width / size.x;
relative_size.y = App->window->height / size.y;
needed_to_update = true;
}
ImGui::PopItemWidth();
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("Pivot pos");
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("X");
ImGui::SameLine();
ImGui::PushItemWidth(50);
if (ImGui::DragFloat("##9", (active && owner->active) ? &pivot_position.x : &null, 0.01f) && (active && owner->active))
needed_to_update = true;
ImGui::PopItemWidth();
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("Y");
ImGui::SameLine();
ImGui::PushItemWidth(50);
if (ImGui::DragFloat("##10", (active && owner->active) ? &pivot_position.y : &null, 0.01f) && (active && owner->active))
needed_to_update = true;
ImGui::PopItemWidth();
ImGui::Columns(1, "", false);
ImGui::Separator();
ImGui::Text("Controls:");
ImGui::Dummy({0,10});
ImGui::Columns(5, "", false);
ImGui::AlignTextToFramePadding();
ImGui::NextColumn();
ImGui::Dummy({0,40});
if (ImGui::Button("Left", { 50,20 }));
if(ImGui::IsItemActive()) {
SetPosition({ position.x -= 10,position.y });
}
ImGui::NextColumn();
ImGui::Button("Up", { 50,20 });
if (ImGui::IsItemActive()) {
SetPosition({ position.x,position.y+=10 });
}
ImGui::Dummy({0,60});
ImGui::Button("Down", { 50,20 });
if (ImGui::IsItemActive()) {
SetPosition({ position.x,position.y -= 10 });
}
ImGui::NextColumn();
ImGui::Dummy({0,40});
ImGui::Button("Right", { 50,20 });
if (ImGui::IsItemActive()) {
SetPosition({ position.x += 10,position.y });
}
ImGui::Columns(1, "", false);
ImGui::Separator();
ImGui::PopID();
}
void ComponentTransform2D::GetTrianglePoints(float2& min_p, float2& max_p, float2& third_p, float2& third_p_second_tri)
{
float scene_x, scene_y, scene_width, scene_height;
App->scene_intro->GetSceneDimensions(scene_x, scene_y, scene_width, scene_height);
Quat q = q.RotateZ(-rotation.z*DEGTORAD);
for (int i = 0; i < 4; i++) {
float2 point;
if (i == 0) {
point = min_p;
}
else if (i == 1) {
point = max_p;
}
else if(i==2) {
point = third_p;
}
else {
point = third_p_second_tri;
}
point.x *= size.x;
point.y *= size.y;
point.x -= pivot_position.x;
point.y += pivot_position.y;
//ROTATE
float3 point3 = { point.x,point.y,0 };
point3 = q * point3;
point = { point3.x,point3.y };
point.x += pivot_position.x;
point.y -= pivot_position.y;
point.x += position.x;
point.y -= position.y;
point.x += scene_width / 2;
point.y += scene_height / 2;
if (i == 0) {
min_p = point;
}
else if (i == 1) {
max_p = point;
}
else if (i == 2) {
third_p = point;
}
else {
third_p_second_tri = point;
}
}
}
float ComponentTransform2D::GetDepth()
{
return z_depth;
}
| 26.567677 | 195 | 0.696069 | [
"vector",
"transform"
] |
5dc2aebb045decee5f5cae306ebba29e14c632e2 | 1,516 | hh | C++ | cc/legend.hh | skepner/signature-page | 5005e798687ef25dfcbd9356ada27b1909291392 | [
"MIT"
] | null | null | null | cc/legend.hh | skepner/signature-page | 5005e798687ef25dfcbd9356ada27b1909291392 | [
"MIT"
] | null | null | null | cc/legend.hh | skepner/signature-page | 5005e798687ef25dfcbd9356ada27b1909291392 | [
"MIT"
] | null | null | null | #pragma once
#include "acmacs-base/settings-v1.hh"
#include "acmacs-draw/surface.hh"
// ----------------------------------------------------------------------
class LegendSettings : public acmacs::settings::v1::object
{
public:
using acmacs::settings::v1::object::object;
acmacs::settings::v1::field<acmacs::Offset> offset{this, "offset", {-30, 950}}; // in enclosing surface
acmacs::settings::v1::field<double> width{this, "width", 100}; // in enclosing surface scale
acmacs::settings::v1::field<acmacs::TextStyle> title_style{this, "title_style", acmacs::TextStyle{"sans_serif"}};
acmacs::settings::v1::field<double> title_size{this, "title_size", 10};
acmacs::settings::v1::field<acmacs::TextStyle> text_style{this, "text_style", acmacs::TextStyle{"monospace"}};
acmacs::settings::v1::field<double> text_size{this, "text_size", 10};
acmacs::settings::v1::field<double> interline{this, "interline", 1.5};
}; // class LegendSettings
// ----------------------------------------------------------------------
class Legend
{
public:
inline Legend() {}
virtual inline ~Legend() = default;
virtual void draw(acmacs::surface::Surface& aSurface, const LegendSettings& aSettings) const = 0;
virtual acmacs::Size size() const = 0;
}; // class Legend
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 37.9 | 117 | 0.569261 | [
"object"
] |
5dc48ca4382deab29fdb69e94efd0ff4559fe33a | 3,870 | cpp | C++ | src/graph/InsertVertexExecutor.cpp | 0xflotus/nebula | 10faa87c83f66b62e0db493f958492afe8b569c8 | [
"Apache-2.0"
] | 1 | 2019-05-24T02:41:17.000Z | 2019-05-24T02:41:17.000Z | src/graph/InsertVertexExecutor.cpp | steppenwolfyuetong/vgraph | b0d817fd151758d5ef788b2a26bc3e48a3fa4e18 | [
"Apache-2.0"
] | null | null | null | src/graph/InsertVertexExecutor.cpp | steppenwolfyuetong/vgraph | b0d817fd151758d5ef788b2a26bc3e48a3fa4e18 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2018 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "base/Base.h"
#include "graph/InsertVertexExecutor.h"
#include "storage/client/StorageClient.h"
#include "dataman/RowWriter.h"
namespace nebula {
namespace graph {
InsertVertexExecutor::InsertVertexExecutor(Sentence *sentence,
ExecutionContext *ectx) : Executor(ectx) {
sentence_ = static_cast<InsertVertexSentence*>(sentence);
}
Status InsertVertexExecutor::prepare() {
auto status = checkIfGraphSpaceChosen();
if (!status.ok()) {
return status;
}
// TODO(dutor) To support multi-tag insertion
auto tagItems = sentence_->tagItems();
if (tagItems.size() > 1) {
return Status::Error("Multi-tag not supported yet");
}
auto *tagName = tagItems[0]->tagName();
properties_ = tagItems[0]->properties();
rows_ = sentence_->rows();
// TODO(dutor) To check whether the number of props and values matches.
if (rows_.empty()) {
return Status::Error("VALUES cannot be empty");
}
overwritable_ = sentence_->overwritable();
auto spaceId = ectx()->rctx()->session()->space();
tagId_ = ectx()->schemaManager()->toTagID(spaceId, *tagName);
schema_ = ectx()->schemaManager()->getTagSchema(spaceId, tagId_);
if (schema_ == nullptr) {
return Status::Error("No schema found for `%s'", tagName->c_str());
}
return Status::OK();
}
void InsertVertexExecutor::execute() {
using storage::cpp2::Vertex;
using storage::cpp2::Tag;
std::vector<Vertex> vertices(rows_.size());
for (auto i = 0u; i < rows_.size(); i++) {
auto *row = rows_[i];
auto id = row->id();
auto expressions = row->values();
std::vector<VariantType> values;
values.reserve(expressions.size());
for (auto *expr : expressions) {
values.emplace_back(expr->eval());
}
auto &vertex = vertices[i];
std::vector<Tag> tags(1);
auto &tag = tags[0];
RowWriter writer(schema_);
for (auto &value : values) {
switch (value.which()) {
case 0:
writer << boost::get<int64_t>(value);
break;
case 1:
writer << boost::get<double>(value);
break;
case 2:
writer << boost::get<bool>(value);
break;
case 3:
writer << boost::get<std::string>(value);
break;
default:
LOG(FATAL) << "Unknown value type: " << static_cast<uint32_t>(value.which());
}
}
tag.set_tag_id(tagId_);
tag.set_props(writer.encode());
vertex.set_id(id);
vertex.set_tags(std::move(tags));
}
auto space = ectx()->rctx()->session()->space();
auto future = ectx()->storage()->addVertices(space, std::move(vertices), overwritable_);
auto *runner = ectx()->rctx()->runner();
auto cb = [this] (auto &&resp) {
// For insertion, we regard partial success as failure.
auto completeness = resp.completeness();
if (completeness != 100) {
DCHECK(onError_);
onError_(Status::Error("Internal Error"));
return;
}
DCHECK(onFinish_);
onFinish_();
};
auto error = [this] (auto &&e) {
LOG(ERROR) << "Exception caught: " << e.what();
DCHECK(onError_);
onError_(Status::Error("Internal error"));
return;
};
std::move(future).via(runner).thenValue(cb).thenError(error);
}
} // namespace graph
} // namespace nebula
| 30.234375 | 97 | 0.562791 | [
"vector"
] |
5dc880c296a91ab4d6452f8e1c4cab3e6c427419 | 5,824 | cc | C++ | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-nativetask/src/main/native/src/lib/NativeTask.cc | bzhaoopenstack/hadoop | 24080666e5e2214d4a362c889cd9aa617be5de81 | [
"Apache-2.0"
] | 14,425 | 2015-01-01T15:34:43.000Z | 2022-03-31T15:28:37.000Z | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-nativetask/src/main/native/src/lib/NativeTask.cc | bzhaoopenstack/hadoop | 24080666e5e2214d4a362c889cd9aa617be5de81 | [
"Apache-2.0"
] | 3,805 | 2015-03-20T15:58:53.000Z | 2022-03-31T23:58:37.000Z | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-nativetask/src/main/native/src/lib/NativeTask.cc | bzhaoopenstack/hadoop | 24080666e5e2214d4a362c889cd9aa617be5de81 | [
"Apache-2.0"
] | 9,521 | 2015-01-01T19:12:52.000Z | 2022-03-31T03:07:51.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __CYGWIN__
#include <execinfo.h>
#endif
#include "lib/commons.h"
#include "util/StringUtil.h"
#include "NativeTask.h"
#include "lib/NativeObjectFactory.h"
namespace NativeTask {
//////////////////////////////////////////////////////////////////
// NativeObjectType methods
//////////////////////////////////////////////////////////////////
const string NativeObjectTypeToString(NativeObjectType type) {
switch (type) {
case BatchHandlerType:
return string("BatchHandlerType");
default:
return string("UnknownObjectType");
}
}
NativeObjectType NativeObjectTypeFromString(const string type) {
if (type == "BatchHandlerType") {
return BatchHandlerType;
}
return UnknownObjectType;
}
HadoopException::HadoopException(const string & what) {
// remove long path prefix
size_t n = 0;
if (what[0] == '/') {
size_t p = what.find(':');
if (p != what.npos) {
while (true) {
size_t np = what.find('/', n + 1);
if (np == what.npos || np >= p) {
break;
}
n = np;
}
}
}
_reason.append(what.c_str() + n, what.length() - n);
void *array[64];
size_t size;
#ifndef __CYGWIN__
size = backtrace(array, 64);
char ** traces = backtrace_symbols(array, size);
for (size_t i = 0; i < size; i++) {
_reason.append("\n\t");
_reason.append(traces[i]);
}
#endif
}
///////////////////////////////////////////////////////////
void Config::load(const string & path) {
FILE * fin = fopen(path.c_str(), "r");
if (NULL == fin) {
THROW_EXCEPTION(IOException, "file not found or can not open for read");
}
char buff[256];
while (fgets(buff, 256, fin) != NULL) {
if (buff[0] == '#') {
continue;
}
std::string key = buff;
if (key[key.length() - 1] == '\n') {
size_t br = key.find('=');
if (br != key.npos) {
set(key.substr(0, br), StringUtil::Trim(key.substr(br + 1)));
}
}
}
fclose(fin);
}
void Config::set(const string & key, const string & value) {
_configs[key] = value;
}
void Config::setInt(const string & name, int64_t value) {
_configs[name] = StringUtil::ToString(value);
}
void Config::setBool(const string & name, bool value) {
_configs[name] = StringUtil::ToString(value);
}
void Config::parse(int32_t argc, const char ** argv) {
for (int32_t i = 0; i < argc; i++) {
const char * equ = strchr(argv[i], '=');
if (NULL == equ) {
LOG("[NativeTask] config argument not recognized: %s", argv[i]);
continue;
}
if (argv[i][0] == '-') {
LOG("[NativeTask] config argument with '-' prefix ignored: %s", argv[i]);
continue;
}
string key(argv[i], equ - argv[i]);
string value(equ + 1, strlen(equ + 1));
map<string, string>::iterator itr = _configs.find(key);
if (itr == _configs.end()) {
_configs[key] = value;
} else {
itr->second.append(",");
itr->second.append(value);
}
}
}
const char * Config::get(const string & name) {
map<string, string>::iterator itr = _configs.find(name);
if (itr == _configs.end()) {
return NULL;
} else {
return itr->second.c_str();
}
}
string Config::get(const string & name, const string & defaultValue) {
map<string, string>::iterator itr = _configs.find(name);
if (itr == _configs.end()) {
return defaultValue;
} else {
return itr->second;
}
}
int64_t Config::getInt(const string & name, int64_t defaultValue) {
map<string, string>::iterator itr = _configs.find(name);
if (itr == _configs.end()) {
return defaultValue;
} else {
return StringUtil::toInt(itr->second);
}
}
bool Config::getBool(const string & name, bool defaultValue) {
map<string, string>::iterator itr = _configs.find(name);
if (itr == _configs.end()) {
return defaultValue;
} else {
return StringUtil::toBool(itr->second);
}
}
float Config::getFloat(const string & name, float defaultValue) {
map<string, string>::iterator itr = _configs.find(name);
if (itr == _configs.end()) {
return defaultValue;
} else {
return StringUtil::toFloat(itr->second);
}
}
void Config::getStrings(const string & name, vector<string> & dest) {
map<string, string>::iterator itr = _configs.find(name);
if (itr != _configs.end()) {
StringUtil::Split(itr->second, ",", dest, true);
}
}
void Config::getInts(const string & name, vector<int64_t> & dest) {
vector<string> sdest;
getStrings(name, sdest);
for (size_t i = 0; i < sdest.size(); i++) {
dest.push_back(StringUtil::toInt(sdest[i]));
}
}
void Config::getFloats(const string & name, vector<float> & dest) {
vector<string> sdest;
getStrings(name, sdest);
for (size_t i = 0; i < sdest.size(); i++) {
dest.push_back(StringUtil::toFloat(sdest[i]));
}
}
///////////////////////////////////////////////////////////
Counter * ProcessorBase::getCounter(const string & group, const string & name) {
return NULL;
}
///////////////////////////////////////////////////////////
} // namespace NativeTask
| 27.471698 | 80 | 0.603709 | [
"vector"
] |
5dcb5a906649e1d2890b78e4091a76a96c09bc6a | 56,339 | cpp | C++ | src/OFFSET.cpp | khodarahmi/OFFSET | 25fb6babaaf5498658c57a14e668844b08311aa1 | [
"Apache-2.0"
] | 3 | 2016-04-05T13:19:53.000Z | 2021-12-07T01:21:27.000Z | src/OFFSET.cpp | khodarahmi/OFFSET | 25fb6babaaf5498658c57a14e668844b08311aa1 | [
"Apache-2.0"
] | null | null | null | src/OFFSET.cpp | khodarahmi/OFFSET | 25fb6babaaf5498658c57a14e668844b08311aa1 | [
"Apache-2.0"
] | 2 | 2016-04-05T13:19:57.000Z | 2021-12-07T01:21:48.000Z | #include "OFFSET.h"
class GCUtil
{
public:
static OF_VOID sort(OF_UINT list[][2], OF_BOOL ascending)
{
OF_BOOL changed = OF_TRUE;
for(OF_BYTE i=0;changed && i<OF_HW_DATAPAGE_COUNT;i++)
{
changed = OF_FALSE;
for(OF_BYTE j=0;j<OF_HW_DATAPAGE_COUNT-1;j++)
{
if((ascending && list[j][1] > list[j+1][1]) || (!ascending && list[j][1] < list[j+1][1]))
{
OF_UINT temp = list[j][0];
list[j][0] = list[j+1][0];
list[j+1][0] = temp;
temp = list[j][1];
list[j][1] = list[j+1][1];
list[j+1][1] = temp;
changed = OF_TRUE;
}
}
}
}
static OF_BOOL areCoSector(DeviceInterface* di, OF_BYTE pageIndex1, OF_BYTE pageIndex2)
{
return pageIndex1 == pageIndex2 || getPageSectorIndex(di, pageIndex1) == getPageSectorIndex(di, pageIndex2);
}
static OF_UINT getPageSectorIndex(DeviceInterface* di, OF_UINT pageIndex)
{
OF_UINT pageOffset = (pageIndex + OF_HW_FIRST_DATAPAGE_OFFSET)*OF_HW_PAGE_SIZE;
for (OF_UINT offset = 0, i = 0; offset < OF_CONST_TOTAL_SIZE; i++)
{
OF_UINT sectorSize = di->getSectorSize(i);
if (offset >= pageOffset && offset < pageOffset + sectorSize)
{
return i;
}
offset += sectorSize;
}
return -1;
}
static OF_UINT countSectorValidPages(DeviceInterface* di, OF_BYTE sectorIndex, OF_UINT minValid[][2])
{
OF_UINT validCount = 0;
for(OF_BYTE i=0;i<OF_HW_DATAPAGE_COUNT;i++)
{
if(getPageSectorIndex(di, minValid[i][0]) == sectorIndex)
{
validCount += minValid[i][1];
}
}
return validCount;
}
static OF_UINT countSectorInvalidPages(DeviceInterface* di, OF_BYTE sectorIndex, OF_UINT minValid[][2], OF_UINT maxFree[][2])
{
OF_UINT invalidCount = OF_SEGMENT_MAX_COUNT_PER_PAGE - countSectorValidPages(di, sectorIndex, minValid);
for(OF_BYTE i=0;i<OF_HW_DATAPAGE_COUNT;i++)
{
if(getPageSectorIndex(di, maxFree[i][0]) == sectorIndex)
{
invalidCount -= maxFree[i][1];
}
}
return invalidCount;
}
static OF_UINT countInvalid(OF_BYTE i, OF_UINT minValid[][2], OF_UINT maxFree[][2])
{
OF_UINT invalidCount = OF_SEGMENT_MAX_COUNT_PER_PAGE - minValid[i][1];
for(OF_BYTE k=0;k<OF_HW_DATAPAGE_COUNT;k++)
{
if(maxFree[k][0] == minValid[i][0])
{
invalidCount -= maxFree[k][1];
break;
}
}
return invalidCount;
}
static OF_BOOL doesGCLead2FormatPage(DeviceInterface* di, OF_BYTE i, OF_UINT minValid[][2], OF_UINT maxFree[][2])
{
OF_UINT availOutOfSectorFree = 0;
for(OF_BYTE j=0;j<OF_HW_DATAPAGE_COUNT;j++)
{
if(!GCUtil::areCoSector(di, (OF_BYTE) minValid[i][0], (OF_BYTE) maxFree[j][0]))
{
availOutOfSectorFree += maxFree[j][1];
if(availOutOfSectorFree >= minValid[i][1])
{
return OF_TRUE;
}
}
}
return OF_FALSE;
}
};
OFFSET::OFFSET(DeviceInterface* di, OF_BOOL autoFormat)
{
this->di = di;
this->lastGeneratedObjectHandle = 0;
this->freeSegmentsCount = 0;
this->disableGC = this->isTotalFormatting = OF_FALSE;
this->oHandles = (OF_UINT_PTR) di->malloc(OBJECT_HANDLE_LIST_GROW_SIZE*sizeof(OF_UINT));
this->oHandlesCount = OBJECT_HANDLE_LIST_GROW_SIZE;
di->memset(this->oHandles, -1, OBJECT_HANDLE_LIST_GROW_SIZE*sizeof(OF_UINT));
if(autoFormat)
{
/*#if OF_CACHE_L1
for(OF_UINT i=0;i<OF_SEGMENT_MAX_COUNT;i++)
{
setSegmentStatus(i, SEGMENT_STATUS_INVALID, 1);
}
#endif*/
format();
}
initialize();
}
OFFSET::~OFFSET()
{
if (oHandles)
{
di->free(oHandles);
}
if(!this->di)
{
delete this->di;
}
}
OF_VOID OFFSET::initialize()
{
di->disableIRQ();//disable all interrupts
//repairing power failure inconsistencies & setting lastGeneratedObjectHandle
lastGeneratedObjectHandle = 0;
freeSegmentsCount = 0;
OF_UINT buf;
OF_BYTE segCount = getMinimizedSegmentCount(0, OF_FALSE);
OF_BYTE headerBuf[SIZEOF_VI+SIZEOF_OH+SIZEOF_AT+SIZEOF_SF+SIZEOF_SN], dBuf[8];
for(OF_UINT i=0;i<OF_SEGMENT_MAX_COUNT;i+=segCount)
{
segCount = getMinimizedSegmentCount(i, OF_FALSE);
di->seekg(OF_CONST_DATABASE_ADDRESS+i*OF_SEGMENT_MIN_SIZE, OF_TRUE);
di->read(headerBuf, sizeof(headerBuf));//reading segment header info
if((unsigned char)headerBuf[0] == OF_CONST_FREE_QWORD_VALUE)
{//valid segment
buf = *(OF_UINT_PTR)(headerBuf+SIZEOF_VI);
if(buf != OF_CONST_FREE_HWORD_VALUE)
{//non-free segment
if(!_segNum(headerBuf+SIZEOF_VI+SIZEOF_OH+SIZEOF_AT+SIZEOF_SF))
{
addOHandle((OF_OBJECT_HANDLE)(buf | OF_NORMAL_OBJECT_HANDLE_MASK));
}
if(buf > lastGeneratedObjectHandle)
{
lastGeneratedObjectHandle = buf;
}
#if OF_CACHE_L1
setSegmentStatus(i, _segNum(headerBuf+SIZEOF_VI+SIZEOF_OH+SIZEOF_AT+SIZEOF_SF) ? SEGMENT_STATUS_VALID : SEGMENT_STATUS_VALID_FAS, segCount
#if OF_CACHE_L3
, _segNum(headerBuf+SIZEOF_VI+SIZEOF_OH+SIZEOF_AT+SIZEOF_SF)
#if OF_CACHE_L4
, buf, *(OF_ATTRIBUTE_TYPE*)(headerBuf+SIZEOF_VI+SIZEOF_OH)
#endif
#endif
);
#endif
}
else
{//free segment
#if OF_CACHE_L1
setSegmentStatus(i, SEGMENT_STATUS_FREE, segCount);
#endif
freeSegmentsCount++;
}
}
#if OF_CACHE_L1
else
{//invalid segment
setSegmentStatus(i, SEGMENT_STATUS_INVALID, segCount);
}
#endif
}
if (di->readMetaData(OFMID_FORMATTING_PAGE, &buf, sizeof(buf)) == sizeof(buf) && buf != (OF_UINT)-1)
{//continue intruppted (failed) page formating
formatPage(buf>>8, buf & 0x00FF);
endFormattingPage();
}
buf = 0xFFFF;
if (di->readMetaData(OFMID_DELETING_OBJECT_ATTR_0, dBuf, sizeof(dBuf)) == sizeof(dBuf) && di->memcmp(dBuf, &buf, sizeof(buf)))
{//continue intruppted (failed) object or object attribute deleting
OF_UINT oHandle = *(OF_UINT_PTR)dBuf;
OF_ATTRIBUTE_TYPE attrType = *(OF_ATTRIBUTE_TYPE*)(dBuf+sizeof(OF_UINT));
OF_BYTE oldSegFlags = *(OF_BYTE_PTR)(dBuf+sizeof(OF_UINT)+sizeof(OF_ATTRIBUTE_TYPE)), segLen;
OF_UINT itr = 0, cntItr = 0;
while(OF_TRUE)
{
segLen = iterateOnSegments(&itr, &cntItr, (OF_UINT)-1, oHandle, attrType, OF_TRUE, OF_TRUE);
if(!segLen)
{
break;
}
di->read(dBuf, SIZEOF_OH + SIZEOF_AT + SIZEOF_SF);
if(*(OF_UINT_PTR)dBuf == oHandle && (attrType == (OF_ATTRIBUTE_TYPE)OF_CONST_FREE_WORD_VALUE || attrType == *(OF_ATTRIBUTE_TYPE*)(dBuf+SIZEOF_OH)) && (oldSegFlags == (OF_BYTE)OF_CONST_FREE_QWORD_VALUE || (oldSegFlags & SEGMENT_FLAG_MASK_TRANSMIT_COUNTER) == ((*(OF_BYTE_PTR)(dBuf+SIZEOF_OH+SIZEOF_AT)) & SEGMENT_FLAG_MASK_TRANSMIT_COUNTER)))
{//invalidate segment
di->seekp(-1 * (int)SIZEOF_VI);
buf = 0;
di->write((OF_BYTE_PTR)&buf, SIZEOF_VI);
#if OF_CACHE_L1
setSegmentStatusItr(itr, SEGMENT_STATUS_INVALID, segLen);
#endif
}
}
}
gc();
}
OF_BOOL OFFSET::format(OF_BOOL formatMetaPages)
{
OF_ULONG buf = (OF_ULONG)-1;
di->writeMetaData(OFMID_FLAGS_0, &buf, sizeof(buf));
isTotalFormatting = OF_TRUE;
di->disableIRQ();//disable all interrupts
freeSegmentsCount = 0;
#if OF_HW_METAPAGE_COUNT
if(formatMetaPages)
{
for(OF_BYTE i=0;i<OF_HW_METAPAGE_COUNT;i++)
{
formatPage(i, OF_FALSE, OF_TRUE);
}
}
#endif
for(OF_BYTE i=0;i<OF_HW_DATAPAGE_COUNT;i++)
{
formatPage(i, OF_TRUE, OF_TRUE);
}
di->flush();
di->enableIRQ();//enable interrupts
lastGeneratedObjectHandle = 0;
isTotalFormatting = OF_FALSE;
return freeSegmentsCount == OF_SEGMENT_MAX_COUNT;
}
OF_BOOL OFFSET::formatPage(OF_UINT pageIndex, OF_BOOL isDataPage, OF_BOOL forceFormat)
{
OF_UINT sectorIndex = GCUtil::getPageSectorIndex(di, pageIndex);
if (!di->canFormatSector(sectorIndex, forceFormat))
{//now allowed to format sector
return OF_FALSE;
}
di->disableIRQ();
beginFormattingPage(pageIndex, isDataPage);
di->formatSector(sectorIndex);
OF_UINT pageGranularityFactor = di->getSectorSize(sectorIndex) / OF_HW_PAGE_SIZE;
endFormattingPage();
di->enableIRQ();
#if OF_CACHE_L1
#if OF_CACHE_L2
#if OF_CACHE_L3
#if OF_CACHE_L4
di->memset(segStatusCache + pageIndex*OF_SEGMENT_MAX_COUNT_PER_PAGE * 2, 0x03, OF_SEGMENT_MAX_COUNT_PER_PAGE * 2 * pageGranularityFactor);
#else
di->memset(segStatusCache + pageIndex*OF_SEGMENT_MAX_COUNT_PER_PAGE, 0x03, OF_SEGMENT_MAX_COUNT_PER_PAGE*pageGranularityFactor);
#endif
#else
di->memset(segStatusCache + pageIndex*OF_SEGMENT_MAX_COUNT_PER_PAGE/2, 0x33, (OF_SEGMENT_MAX_COUNT_PER_PAGE/2)*pageGranularityFactor);
#endif
#else
di->memset(segStatusCache + pageIndex*OF_SEGMENT_MAX_COUNT_PER_PAGE/4, 0xFF, (OF_SEGMENT_MAX_COUNT_PER_PAGE/4)*pageGranularityFactor);
#endif
#endif
freeSegmentsCount += OF_SEGMENT_MAX_COUNT_PER_PAGE*pageGranularityFactor;
return OF_TRUE;
}
OF_BOOL OFFSET::writeSegment(ObjectSegment* os, OF_BYTE usedContentLen, OF_BOOL doGC)
{
OF_BYTE srcSegLen = _getSegmentSize(os->segmentFlags);
for(OF_BYTE retries=0;retries<2;retries++)
{
if(retries && doGC)
{
gc();
}
OF_UINT itr = 0, cntItr = 0;
if(iterateOnSegments(&itr, &cntItr, (OF_UINT)-1, (OF_UINT)-1, (OF_ATTRIBUTE_TYPE)-1, OF_TRUE, OF_FALSE, OF_TRUE, srcSegLen))
{
OF_BYTE buf[sizeof(ObjectSegment)];
di->memcpy(buf, &os->objectHandler, SIZEOF_OH);
di->memcpy(buf + SIZEOF_OH, &os->attrType, SIZEOF_AT);
di->memcpy(buf + SIZEOF_OH + SIZEOF_AT, &os->segmentFlags, SIZEOF_SF);
di->memcpy(buf + SIZEOF_OH + SIZEOF_AT + SIZEOF_SF, &os->segmentNumber, SIZEOF_SN);
di->memcpy(buf + SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN, os->content, usedContentLen);
di->write(buf, SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN + usedContentLen);
#if OF_CACHE_L1
setSegmentStatusItr(itr, os->segmentNumber ? SEGMENT_STATUS_VALID : SEGMENT_STATUS_VALID_FAS, srcSegLen
#if OF_CACHE_L3
, os->segmentNumber
#if OF_CACHE_L4
, os->objectHandler, os->attrType
#endif
#endif
);
#endif
freeSegmentsCount -= (srcSegLen/OF_OBJECT_SEGMENT_MIN_SIZE);
return OF_TRUE;
}
}
return OF_FALSE;//no free space
}
OF_ULONG OFFSET::getTotalMemory()
{
return (((OF_ULONG)OF_SEGMENT_AVG_COUNT)*((OF_ULONG)OF_OBJECT_SEGMENT_CONTENT_AVG_SIZE));
}
OF_ULONG OFFSET::getFreeMemory(OF_BOOL doGC)
{
if(doGC)
{
gc();
}
return (freeSegmentsCount / 2)*((OF_ULONG)OF_OBJECT_SEGMENT_CONTENT_AVG_SIZE);
}
OF_BOOL OFFSET::canAllocateMemory(OF_ULONG requiredMemory, OF_ULONG attrCount)
{
if(getFreeMemory(OF_FALSE) < requiredMemory + sizeof(OF_ULONG)*attrCount)
{
return getFreeMemory(OF_TRUE) >= requiredMemory + sizeof(OF_ULONG)*attrCount;
}
return OF_TRUE;
}
OF_VOID OFFSET::gc()
{
if(disableGC)
{
return;
}
di->disableIRQ();//disable all interrupts
//gc algorithm:
//step 1: calculate number of valid & free segments each page
//step 2: create two priority lists according to number of valid & free segments: minValid & maxFree
//step 3: while possible, move segments from pages with min valid segments to pages with max free segments
//step 4: if possible, format non-free pages with no valid segment
//begin step 1
OF_UINT minValid[OF_HW_DATAPAGE_COUNT][2];
OF_UINT maxFree[OF_HW_DATAPAGE_COUNT][2];
OF_UINT itr = 0, cntItr = 0;
#if !OF_CACHE_L1
OF_UINT buf = 0, buf2 = 0;
#endif
OF_BYTE segLen;
OF_UINT totalInvalidSegmentsCount = 0, totalFreeSegmentsCount = 0;
for(OF_BYTE i=0;i<OF_HW_DATAPAGE_COUNT;i++)
{
minValid[i][0] = maxFree[i][0] = i;
minValid[i][1] = maxFree[i][1] = 0;
}
while(OF_TRUE)
{
segLen = iterateOnSegments(&itr, &cntItr);
if(!segLen)
{
break;
}
OF_BYTE pageNum = _getItrPageNum(itr);
#if OF_CACHE_L1
switch(getSegmentStatusItr(itr, segLen))
{
case SEGMENT_STATUS_VALID:
case SEGMENT_STATUS_VALID_FAS:
minValid[pageNum][1] += segLen/OF_SEGMENT_MIN_SIZE;
break;
case SEGMENT_STATUS_FREE:
maxFree[pageNum][1]++;
totalFreeSegmentsCount++;
break;
case SEGMENT_STATUS_INVALID:
totalInvalidSegmentsCount++;
}
#else
di->seekg(-1*(int)SIZEOF_VI);
di->read((char*)&buf, SIZEOF_VI);
di->read((char*)&buf2, SIZEOF_OH);
if((unsigned char)buf == OF_CONST_FREE_QWORD_VALUE && buf2 == OF_CONST_FREE_HWORD_VALUE)
{//free segment
maxFree[pageNum][1]++;
}
else if((unsigned char)buf == OF_CONST_FREE_QWORD_VALUE)
{//valid non-free segment
minValid[pageNum][1] += segLen/OF_SEGMENT_MIN_SIZE;
}
else
{//invalid segment
totalInvalidSegmentsCount++;
}
#endif
}
//end step 1
if (totalInvalidSegmentsCount < OF_SEGMENT_MAX_COUNT_PER_PAGE && totalFreeSegmentsCount > OF_SEGMENT_MAX_COUNT_PER_PAGE)
{//at least OF_SEGMENT_MAX_COUNT_PER_PAGE invalid segments must be exists for doing GC
di->flush();
di->enableIRQ();//enable interrupts
return;
}
//begin step 2
GCUtil::sort(minValid, OF_TRUE);
GCUtil::sort(maxFree, OF_FALSE);
//end step 2
//begin step 3
OF_UINT movedSegments = 0;
do
{
movedSegments = 0;
for(OF_BYTE i=0;i<OF_HW_DATAPAGE_COUNT;i++)
{
OF_UINT cntInvalid = GCUtil::countInvalid(i, minValid, maxFree);
if(cntInvalid < OF_SEGMENT_MAX_COUNT_PER_PAGE/3 || !GCUtil::doesGCLead2FormatPage(di, i, minValid, maxFree))
{
continue;
}
for(OF_BYTE j=0;minValid[i][1] && maxFree[j][1] && j<OF_HW_DATAPAGE_COUNT;j++)
{
if(!GCUtil::areCoSector(di, (OF_BYTE) minValid[i][0], (OF_BYTE) maxFree[j][0]))
{
OF_UINT srcInvalid = cntInvalid;
OF_BYTE k=0;
for(;k<OF_HW_DATAPAGE_COUNT;k++)
{
if(minValid[k][0] == maxFree[j][0])
{
break;
}
}
transferPage(minValid[i][0], maxFree[j][0], &minValid[i][1], &srcInvalid, &minValid[k][1], &maxFree[j][1]);
movedSegments += (srcInvalid-cntInvalid);
}
}
if(movedSegments)
{
GCUtil::sort(minValid, OF_TRUE);
GCUtil::sort(maxFree, OF_FALSE);
break;
}
}
}while(movedSegments);
//end step 3
//begin step 4
for(OF_BYTE i=0,j=OF_HW_FIRST_DATAPAGE_OFFSET;i<OF_HW_DATAPAGE_COUNT;j++)
{
OF_UINT sectorIndex = GCUtil::getPageSectorIndex(di, i);
OF_UINT sectorPagesCount = di->getSectorSize(sectorIndex)/OF_HW_PAGE_SIZE;
if (di->canFormatSector(sectorIndex, OF_TRUE) && !GCUtil::countSectorValidPages(di, i, minValid) && GCUtil::countSectorInvalidPages(di, i, minValid, maxFree) > 0/*OF_SEGMENT_MAX_COUNT_PER_PAGE*(1.0/sectorPagesCount)*/)
{
formatPage(i, OF_TRUE, OF_TRUE);
}
i += sectorPagesCount;
}
//end step 4
di->flush();
di->enableIRQ();//enable interrupts
}
OF_VOID OFFSET::transferPage(OF_UINT srcPageIndex, OF_UINT dstPageIndex, OF_UINT_PTR srcValidCount, OF_UINT_PTR srcInvalidCount, OF_UINT_PTR dstValidCount, OF_UINT_PTR dstFreeCount)
{
OF_BYTE cBuf[OF_OBJECT_SEGMENT_MAX_SIZE-SIZEOF_VI];
OF_BYTE srcSegLen, dstSegLen = 0;
OF_UINT srcItr = srcPageIndex, srcCntItr = 0, dstItr = dstPageIndex, dstCntItr = 0;
OF_ULONG mark;
while(OF_TRUE)
{//iterate on valid source page segments
srcSegLen = iterateOnSegments(&srcItr, &srcCntItr, (OF_UINT)-1, (OF_UINT)-1, (OF_ATTRIBUTE_TYPE)-1, OF_TRUE, OF_TRUE);
if(!srcSegLen || _getItrPageNum(srcItr) != srcPageIndex)
{//end of source page segments
break;
}
di->markg(&mark);
if(dstSegLen > srcSegLen)
{
dstItr = dstPageIndex;
dstCntItr = 0;
}
while(OF_TRUE)
{//iterate on free destination page segments with len srcSegLen
dstSegLen = iterateOnSegments(&dstItr, &dstCntItr, (OF_UINT)-1, (OF_UINT)-1, (OF_ATTRIBUTE_TYPE)-1, OF_TRUE, OF_FALSE, OF_TRUE, srcSegLen);
if(!dstSegLen || _getItrPageNum(dstItr) != dstPageIndex)
{//end of destination page segments
break;
}
//reading src segment
di->restoreg(mark);
di->read(cBuf, srcSegLen-SIZEOF_VI);//reading src segment (header & content)
cBuf[SIZEOF_OH+SIZEOF_AT] = (cBuf[SIZEOF_OH+SIZEOF_AT] & ~SEGMENT_FLAG_MASK_TRANSMIT_COUNTER) | (((cBuf[SIZEOF_OH+SIZEOF_AT] & SEGMENT_FLAG_MASK_TRANSMIT_COUNTER)+1)%4);//modifying segmentFlags
di->write(cBuf, srcSegLen - SIZEOF_VI);//transferring segment
#if OF_CACHE_L1
setSegmentStatusItr(dstItr, _segNum(cBuf+SIZEOF_OH+SIZEOF_AT+SIZEOF_SF) ? SEGMENT_STATUS_VALID : SEGMENT_STATUS_VALID_FAS, dstSegLen
#if OF_CACHE_L3
, _segNum(cBuf+SIZEOF_OH+SIZEOF_AT+SIZEOF_SF)
#if OF_CACHE_L4
, *(OF_UINT_PTR)cBuf, *(OF_ATTRIBUTE_TYPE*)(cBuf+SIZEOF_OH)
#endif
#endif
);
#endif
mark -= SIZEOF_VI;
di->restorep(mark);
mark = 0;
di->write((OF_BYTE_PTR)&mark, SIZEOF_VI);//invalidate src segment
#if OF_CACHE_L1
setSegmentStatusItr(srcItr, SEGMENT_STATUS_INVALID, srcSegLen);
#endif
mark = srcSegLen/OF_SEGMENT_MIN_SIZE;
*srcValidCount -= (OF_BYTE) mark;
*srcInvalidCount += (OF_BYTE) mark;
*dstValidCount += (OF_BYTE) mark;
*dstFreeCount -= (OF_BYTE) mark;
freeSegmentsCount -= (OF_BYTE) mark;
if(!*srcValidCount || !*dstFreeCount)
{
return;
}
break;
}
}
}
////////////////////
OF_BOOL OFFSET::iterateOnObjects(OF_ULONG_PTR itr, OF_OBJECT_HANDLE_PTR phObj, OF_BOOL bypassLogin, OF_BOOL onlyPrivateObjects, OF_BOOL onlyPublicObjects)
{
OF_UINT iPos = (OF_UINT) (*itr);
*phObj = OF_INVALID_OBJECT_HANDLE;
for(;iPos<oHandlesCount;iPos++)
{
if(oHandles[iPos] != (OF_UINT) -1)
{
#ifdef OF_METADATA_OBJECT_HANDLE
if((oHandles[iPos] & ~OF_NORMAL_OBJECT_HANDLE_MASK) == OF_METADATA_OBJECT_HANDLE)
{
continue;//could not iterate on metadata object
}
#endif
if(!objectExists(oHandles[iPos] | OF_NORMAL_OBJECT_HANDLE_MASK, OF_TRUE))
{
destroyObject(oHandles[iPos] | OF_NORMAL_OBJECT_HANDLE_MASK, OF_TRUE);
continue;
}
OF_BOOL isPrivateObj = isPrivateObject((OF_ULONG)(oHandles[iPos] | OF_NORMAL_OBJECT_HANDLE_MASK));
if(!bypassLogin && !this->di->isAuthenticated() && isPrivateObj)
{
continue;//could not return handle of private object before login
}
if((onlyPublicObjects && isPrivateObj) || (onlyPrivateObjects && !isPrivateObj))
{
continue;
}
*itr = iPos+1;
*phObj = oHandles[iPos];
break;
}
}
return *phObj != OF_INVALID_OBJECT_HANDLE;
}
OF_BOOL OFFSET::objectExists(OF_OBJECT_HANDLE hObj, OF_BOOL bypassLogin)
{
OF_ULONG itr = 0;
OF_UINT attItr = (OF_UINT) -1;
OF_ATTRIBUTE_TYPE attrType;
return iterateOnObjectAttributes(hObj, &itr, &attItr, &attrType, bypassLogin) != 0;
}
OF_ULONG OFFSET::getObjectSize(OF_OBJECT_HANDLE hObj)
{
return getObjectSegmentCount(hObj) * OF_SEGMENT_MIN_SIZE;
}
OF_ULONG OFFSET::getPureObjectSize(OF_OBJECT_HANDLE hObj)
{
OF_ULONG objectSize = 0, itr = 0;
OF_UINT attItr = (OF_UINT) -1;
OF_BYTE cBuf[SIZEOF_SF + SIZEOF_SN + sizeof(OF_UINT)];
while(iterateOnObjectAttributes(hObj, &itr, &attItr, (OF_ATTRIBUTE_TYPE*)cBuf))
{
di->seekg(-1 * (int)(SIZEOF_SF + SIZEOF_SN));
di->read(cBuf, SIZEOF_SF + SIZEOF_SN + sizeof(OF_UINT));
objectSize += (_getSegmentSize(cBuf[0]) < OF_SEGMENT_MAX_SIZE ? *(OF_BYTE_PTR)(cBuf+SIZEOF_SF+SIZEOF_SN) : *(OF_UINT_PTR)(cBuf+SIZEOF_SF+SIZEOF_SN)) + sizeof(OF_ATTRIBUTE_TYPE) + sizeof(OF_ULONG);
}
return objectSize > 0 ? objectSize + sizeof(OF_OBJECT_HANDLE) : 0;
}
OF_UINT OFFSET::getObjectSegmentCount(OF_OBJECT_HANDLE hObj)
{
OF_UINT segmentCount = 0, segmentSize;
OF_ATTRIBUTE_TYPE attrType;
OF_ULONG itr = 0, itr2 = 0;
OF_UINT attItr = (OF_UINT)-1;
while(iterateOnObjectAttributes(hObj, &itr, &attItr, &attrType))
{
itr2 &= 0xFFFF0000;
while(OF_TRUE)
{
segmentSize = iterateOnObjectAttributeSegments(hObj, attrType, &itr2);
if(!segmentSize)
{
break;
}
segmentCount += (segmentSize/OF_OBJECT_SEGMENT_MIN_SIZE);
}
}
return segmentCount;
}
OF_UINT OFFSET::getObjectAttributeCount(OF_OBJECT_HANDLE hObj)
{
OF_UINT attrCount = 0;
OF_ULONG itr = 0;
OF_UINT attItr = (OF_UINT)-1;
while(iterateOnObjectAttributes(hObj, &itr, &attItr))
{
attrCount++;
}
return attrCount;
}
OF_RV OFFSET::setObjectAttribute(OF_OBJECT_HANDLE_PTR phObj, OF_ATTRIBUTE_TYPE attrType, OF_VOID_PTR pAttrValue, OF_ULONG ulAttrValueLen, OF_BOOL isObjectPrivate, OF_BOOL isAttrSensitive)
{
if(isTotalFormatting)
{
return OFR_FUNCTION_FAILED;
}
OF_RV rv = validateObjectAttributeValue(attrType, pAttrValue, &ulAttrValueLen);
if (rv != OFR_OK)
{
return rv;
}
OF_ULONG freeMem = getFreeMemory(OF_FALSE);
if(freeMem < 5*ulAttrValueLen)
{
freeMem = getFreeMemory(OF_TRUE);
}
if(freeMem < ulAttrValueLen + sizeof(OF_ULONG))
{
return OFR_DEVICE_MEMORY;//can't allocate memory for storing this attribute
}
OF_BYTE oldSegmentFlag = 0, newSegmentFlag = 0, segLen, oldSegLen = 0;
OF_ULONG oldMark, itr = 0, oldItr;
if(*phObj != OF_INVALID_OBJECT_HANDLE)
{//existing object
OF_UINT attItr = (OF_UINT)-1;
#ifdef OF_STORE_METADATA_IN_FS
if(*phObj != OF_METADATA_OBJECT_HANDLE)
#endif
if(!iterateOnObjectAttributes(*phObj, &itr, &attItr))
{//object handle invalid or object can't be seen because of it's privacy level
return OFR_OBJECT_HANDLE_INVALID;
}
oldItr = 0;
//check if attribute already exists & must invalidate its segments or not
oldSegLen = iterateOnObjectAttributeSegments(*phObj, attrType, &oldItr);
if(oldSegLen)
{
di->markp(&oldMark);
OF_BYTE cBuf[SIZEOF_SF + SIZEOF_SN];
di->seekg(-1 * (int)sizeof(cBuf));//seeking before segmentFlags
di->read(cBuf, sizeof(cBuf));//reading segmentFlags & segmentNumber
oldSegmentFlag = cBuf[0];
newSegmentFlag = ((oldSegmentFlag & SEGMENT_FLAG_MASK_TRANSMIT_COUNTER)+1) % 4;
}
}
else
{//new object
if(isObjectPrivate && !di->isAuthenticated())
{//user not logged in & so can't create private object
return OFR_NOT_AUTHENTICATED;
}
if(!allocateNewObjectHandle(phObj))
{//could not allocate new handle for this object
return OFR_DEVICE_ERROR;
}
}
ObjectSegment os;
os.attrType = attrType;
os.objectHandler = (OF_UINT) (*phObj & ~OF_NORMAL_OBJECT_HANDLE_MASK);
os.segmentNumber = 0;
os.segmentFlags = newSegmentFlag | (isAttrSensitive ? SEGMENT_FLAG_MASK_ENCRYPTED : 0);
if(isObjectPrivate)
{
os.segmentFlags |= SEGMENT_FLAG_MASK_PRIVATE;
}
else
{
os.segmentFlags &= ~SEGMENT_FLAG_MASK_PRIVATE;
}
OF_ULONG readedLen = 0, remainedLen = ulAttrValueLen, len2Read;
OF_BYTE offset = 0, segContentLen, maxAllowedSegmentSize = OF_OBJECT_SEGMENT_MAX_SIZE;
OF_BOOL doGC = OF_TRUE;
if(ulAttrValueLen > 0)
{
OF_ULONG ulAttrEncryptedValueLen = ulAttrValueLen;
OF_BYTE_PTR pAttrEncryptedValue = (OF_BYTE_PTR) pAttrValue;
OF_ULONG ulCryptBlockLen = 0;
OF_VOID_PTR cryptCtx = isAttrSensitive ? di->getFSCryptContext(&ulCryptBlockLen, OF_TRUE) : NULL_PTR;
if (isAttrSensitive && cryptCtx != NULL_PTR && ulCryptBlockLen)
{//encryption sensitive attribute content
ulAttrEncryptedValueLen += ulCryptBlockLen - ulAttrValueLen%ulCryptBlockLen;
remainedLen = ulAttrEncryptedValueLen;
pAttrEncryptedValue = (OF_BYTE_PTR)di->malloc(ulAttrEncryptedValueLen);
for (OF_ULONG i = 0; i<ulAttrEncryptedValueLen; i += ulCryptBlockLen)
{
di->memcpy(pAttrEncryptedValue + i, ((OF_BYTE_PTR)pAttrValue) + i, min(ulCryptBlockLen, ulAttrValueLen - i));
di->doFSCrypt(cryptCtx, pAttrEncryptedValue + i, pAttrEncryptedValue + i);
}
di->freeFSCryptContext(cryptCtx);
}
while(readedLen < ulAttrEncryptedValueLen)
{//segmentation object attribute & write the segments to flash
os.segmentFlags &= ~(/*SEGMENT_FLAG_MASK_TRANSMIT_COUNTER |*/ SEGMENT_FLAG_MASK_LAST_ATTR);
if(maxAllowedSegmentSize == OF_OBJECT_SEGMENT_MIN_SIZE || remainedLen <= OF_OBJECT_SEGMENT_CONTENT_MIN_SIZE - (os.segmentNumber ? 0 : sizeof(OF_BYTE)))
{
//os.segmentFlags |= SEGMENT_FLAG_MASK_LEN_MIN;//sf[2-3] = 00b
segContentLen = OF_OBJECT_SEGMENT_CONTENT_MIN_SIZE;
}
else if(maxAllowedSegmentSize == OF_OBJECT_SEGMENT_AVG_SIZE || remainedLen <= OF_OBJECT_SEGMENT_CONTENT_AVG_SIZE - (os.segmentNumber ? 0 : sizeof(OF_BYTE)))
{
os.segmentFlags |= SEGMENT_FLAG_MASK_LEN_AVG;//sf[2-3] = 01b
segContentLen = OF_OBJECT_SEGMENT_CONTENT_AVG_SIZE;
}
else// if(remainedLen >= OF_OBJECT_SEGMENT_CONTENT_AVG_SIZE)
{
os.segmentFlags |= SEGMENT_FLAG_MASK_LEN_MAX;//sf[2-3] = 10b
segContentLen = OF_OBJECT_SEGMENT_CONTENT_MAX_SIZE;
}
if(!os.segmentNumber)
{//first segment
offset = (os.segmentFlags & SEGMENT_FLAG_MASK_LEN_MAX) ? sizeof(OF_UINT) : sizeof(OF_BYTE);
di->memcpy(os.content, &ulAttrValueLen, offset);
}
len2Read = min(remainedLen, (OF_BYTE)(segContentLen - offset));
di->memcpy(os.content + offset, pAttrEncryptedValue + readedLen, len2Read);
if(remainedLen == len2Read)
{
os.segmentFlags |= SEGMENT_FLAG_MASK_LAST_ATTR;
}
if(writeSegment(&os, (OF_BYTE)(len2Read+offset), doGC))
{
readedLen += len2Read;
remainedLen -= len2Read;
os.segmentNumber++;
offset = 0;
}
else
{
if(maxAllowedSegmentSize == OF_OBJECT_SEGMENT_MIN_SIZE)
{
if(os.segmentNumber)
{//invalidate written object attribute segments
OF_UINT buf = 0;
itr = 0;
while(OF_TRUE)
{
segLen = iterateOnObjectAttributeSegments(*phObj, attrType, &itr);
if(!segLen)
{
break;
}
di->seekp(-1 * OF_OBJECT_SEGMENT_HEADER_SIZE);//seeking before validatorIndicator
di->write((OF_BYTE_PTR)&buf, SIZEOF_VI);//invalidate segment
#if OF_CACHE_L1
setSegmentStatusItr((itr>>16) & 0x0000FFFF, SEGMENT_STATUS_INVALID, segLen);
#endif
}
}
//Some error occured while writing to device memory
rv = OFR_DEVICE_MEMORY;
break;
}
doGC = OF_FALSE;
maxAllowedSegmentSize -= OF_OBJECT_SEGMENT_MIN_SIZE;
}
}
if(pAttrEncryptedValue != (OF_BYTE_PTR) pAttrValue)
{
di->free(pAttrEncryptedValue);
}
if(rv != OFR_OK)
{
return rv;
}
}
else//if(!ulAttrValueLen)
{
os.segmentFlags |= SEGMENT_FLAG_MASK_LAST_ATTR;
di->memcpy(os.content, &ulAttrValueLen, sizeof(OF_ULONG));
if(!writeSegment(&os, sizeof(OF_ULONG)))
{
//Some error occured while writing to device memory
return OFR_DEVICE_MEMORY;
}
}
OF_BOOL beginDeleting = OF_FALSE;
if((oldSegmentFlag & SEGMENT_FLAG_MASK_TRANSMIT_COUNTER) != (newSegmentFlag & SEGMENT_FLAG_MASK_TRANSMIT_COUNTER))
{//invalidate old attribute segments
#ifdef OF_METADATA_OBJECT_HANDLE
if(*phObj != OF_METADATA_OBJECT_HANDLE)
#endif
beginDeleting = beginDeletingObjectAttribute(*phObj, attrType, oldSegmentFlag);
OF_BYTE cBuf[SIZEOF_SF + SIZEOF_SN];
di->memset(cBuf, 0, sizeof(cBuf));
oldMark -= OF_OBJECT_SEGMENT_HEADER_SIZE;
di->restorep(oldMark);//seeking before old segment validatorIndicator
di->write(cBuf, SIZEOF_VI);//invalidate old segment
#if OF_CACHE_L1
setSegmentStatusItr((oldItr>>16) & 0x0000FFFF, SEGMENT_STATUS_INVALID, oldSegLen);
#endif
if(!(oldSegmentFlag & SEGMENT_FLAG_MASK_LAST_ATTR))
{//not last segment
OF_UINT itr = 0, cntItr = 0, segNum = 0, buf;
OF_UINT tmp = (OF_UINT) (*phObj & ~OF_NORMAL_OBJECT_HANDLE_MASK);
OF_ATTRIBUTE_TYPE aBuf;
while(OF_TRUE)
{
segLen = iterateOnSegments(&itr, &cntItr, segNum, (OF_UINT)((*phObj) & ~OF_NORMAL_OBJECT_HANDLE_MASK), attrType, OF_TRUE, OF_TRUE);
if(!segLen)
{
break;
}
di->read((OF_BYTE_PTR)&buf, SIZEOF_OH);//reading objectHandler
if(buf == tmp)
{
di->read((OF_BYTE_PTR)&aBuf, SIZEOF_AT);
if(aBuf == attrType)
{
di->read(cBuf, SIZEOF_SF + SIZEOF_SN);//reading segmentFlags & segmentNumber
if((cBuf[0] & SEGMENT_FLAG_MASK_TRANSMIT_COUNTER) != (newSegmentFlag & SEGMENT_FLAG_MASK_TRANSMIT_COUNTER))//== oldSegmentFlag)
{
di->seekp(-1 * (int)SIZEOF_VI);//seeging before validatorIndicator
OF_UINT buf = 0;
di->write((OF_BYTE_PTR)&buf, SIZEOF_VI);//writing validatorIndicator to invalidate segment
#if OF_CACHE_L1
setSegmentStatusItr(itr, SEGMENT_STATUS_INVALID, segLen);
#endif
if(cBuf[0] & SEGMENT_FLAG_MASK_LAST_ATTR)
{
break;
}
segNum++;
}
}
}
}
}
#ifdef OF_METADATA_OBJECT_HANDLE
if(*phObj != OF_METADATA_OBJECT_HANDLE)
#endif
if(beginDeleting)
{
endDeletingObjectAttribute();
}
}
di->flush();
return OFR_OK;
}
OF_RV OFFSET::getObjectAttribute(OF_OBJECT_HANDLE hObj, OF_ATTRIBUTE_TYPE attrType, OF_ULONG_PTR pulAttrValueLen, OF_VOID_PTR pAttrValue)
{
if (isTotalFormatting)
{
return OFR_DEVICE_BUSY;
}
OF_ULONG itr = 0;
OF_BYTE segLen = iterateOnObjectAttributeSegments(hObj, attrType, &itr);
if (!segLen)
{
return OFR_OBJECT_HANDLE_INVALID;//object or object attribute not found
}
if (!di->isAuthenticated() && isPrivateObject(hObj))
{
return OFR_OBJECT_HANDLE_INVALID;//object is private & could not be readed before login
}
OF_BYTE cBuf[SIZEOF_SF + SIZEOF_SN];
di->read(cBuf, sizeof(OF_UINT));//reading attribute len
OF_ULONG valueLen = cBuf[0];//setting attribute len
if (segLen >= OF_OBJECT_SEGMENT_MAX_SIZE)
{
valueLen |= ((OF_UINT)cBuf[1]) << 8;
}
if (pulAttrValueLen == NULL_PTR)
{
return OFR_FUNCTION_INVALID_PARAM;
}
if (pAttrValue != NULL_PTR && *pulAttrValueLen < valueLen)
{//small buffer
return OFR_SMALL_BUFFER;
}
*pulAttrValueLen = valueLen;
if (pAttrValue != NULL_PTR)
{
if (!valueLen)
{
return OFR_OK;
}
OF_BYTE_PTR pEncryptedAttrValue = (OF_BYTE_PTR)pAttrValue;
OF_BYTE offset = segLen < OF_OBJECT_SEGMENT_MAX_SIZE ? sizeof(OF_BYTE) : sizeof(OF_UINT);
OF_ULONG readedLen = offset % 2, len2Read, remainedLen = valueLen;
if (readedLen && remainedLen)
{
di->memcpy(pAttrValue, cBuf + 1, 1);
remainedLen--;
}
di->seekg(-1 * (int)(SIZEOF_SF + SIZEOF_SN + sizeof(OF_UINT)));
di->read(cBuf, SIZEOF_SF + SIZEOF_SN);//reading attribute len
OF_BOOL isAttrSensitive = cBuf[0] & SEGMENT_FLAG_MASK_ENCRYPTED;
di->seekg(sizeof(OF_UINT));//seeking attribute len
OF_ULONG ulCryptBlockLen = 0, encryptedValueLen = valueLen;
OF_VOID_PTR cryptCtx = isAttrSensitive ? di->getFSCryptContext(&ulCryptBlockLen, OF_FALSE) : NULL_PTR;
if (isAttrSensitive && cryptCtx != NULL_PTR && ulCryptBlockLen)
{
encryptedValueLen += ulCryptBlockLen - valueLen%ulCryptBlockLen;
pEncryptedAttrValue = (OF_BYTE_PTR)di->malloc(encryptedValueLen);
remainedLen = encryptedValueLen;
if (readedLen)
{
di->memcpy(pEncryptedAttrValue, pAttrValue, readedLen);
remainedLen -= readedLen;
}
}
while (remainedLen)
{
len2Read = min(remainedLen, (OF_BYTE)(segLen - OF_OBJECT_SEGMENT_HEADER_SIZE - offset));
di->read(pEncryptedAttrValue + readedLen, len2Read);
readedLen += len2Read;
remainedLen -= len2Read;
if (remainedLen)
{
segLen = iterateOnObjectAttributeSegments(hObj, attrType, &itr);
if (!segLen)
{
return OFR_FUNCTION_FAILED;//could not read object value completely
}
}
offset = 0;
}
if (pEncryptedAttrValue != (OF_BYTE_PTR)pAttrValue)
{
for (OF_ULONG i = 0; i<encryptedValueLen; i += ulCryptBlockLen)
{
di->doFSCrypt(cryptCtx, pEncryptedAttrValue + i, pEncryptedAttrValue + i);
di->memcpy(((OF_BYTE_PTR)pAttrValue) + i, pEncryptedAttrValue + i, min(ulCryptBlockLen, valueLen - i));
}
}
if (cryptCtx != NULL_PTR)
{
di->freeFSCryptContext(cryptCtx);
}
if (pEncryptedAttrValue != (OF_BYTE_PTR)pAttrValue)
{
di->free(pEncryptedAttrValue);
}
}
return OFR_OK;
}
OF_RV OFFSET::deleteObjectAttribute(OF_OBJECT_HANDLE hObj, OF_ATTRIBUTE_TYPE attrType)
{
if (isTotalFormatting)
{
return OFR_DEVICE_BUSY;
}
OF_ULONG itr = 0;
OF_BYTE segLen = iterateOnObjectAttributeSegments(hObj, attrType, &itr);
if (!segLen)
{
return OFR_OBJECT_HANDLE_INVALID;//object or object attribute not found
}
if (!di->isAuthenticated() && isPrivateObject(hObj))
{
return OFR_OBJECT_HANDLE_INVALID;//object is private & could not be readed before login
}
OF_ULONG buf = 0;
do
{
di->seekp(-1 * OF_OBJECT_SEGMENT_HEADER_SIZE);//seek before validationIndicator
di->write((OF_BYTE_PTR)&buf, SIZEOF_VI);//invalidate segment
#if OF_CACHE_L1
setSegmentStatusItr((itr >> 16) & 0x0000FFFF, SEGMENT_STATUS_INVALID, segLen);
#endif
} while (segLen = iterateOnObjectAttributeSegments(hObj, attrType, &itr));
di->flush();
return OFR_OK;
}
OF_RV OFFSET::duplicateObject(OF_OBJECT_HANDLE hObj, OF_OBJECT_HANDLE_PTR phNewObj, OF_BYTE_PTR pNewTemplateStream)
{
OF_BOOL ok = OF_TRUE, isObjectPrivate = isPrivateObject(hObj);
OF_BYTE srcSegLen;
OF_UINT copiedObjectSegmentCount = 0;
OF_ULONG itr = 0, itr2 = 0, iItr, mark;
OF_UINT attItr = (OF_UINT)-1, hNewObj = OF_INVALID_OBJECT_HANDLE/*(OF_UINT) (*phNewObj & ~OF_NORMAL_OBJECT_HANDLE_MASK)*/, itr3 = 0, cntItr;
OF_ATTRIBUTE_TYPE attrType;
OF_ATTRIBUTE attr;
OF_BYTE cBuf[OF_OBJECT_SEGMENT_CONTENT_MAX_SIZE + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN];
while(ok && iterateOnObjectAttributes(hObj, &itr, &attItr, &attrType))
{
//ckecking for new template attributes
if(pNewTemplateStream != NULL_PTR)
{
iItr = 0;
OF_BOOL ignoreOldAttr = OF_FALSE;
while(iterateOnObjectTemplateStreamAtrributes(&attr, pNewTemplateStream, &iItr))
{
if(attr.type == attrType)
{
OF_RV rv = setObjectAttribute(phNewObj, attr.type, attr.pValue, attr.ulValueLen, isObjectPrivate);
if(rv != OFR_OK)
{
if(copiedObjectSegmentCount)
{
destroyObject(*phNewObj);
*phNewObj = NULL_PTR;
}
return rv;//Error copying new object attributes
}
copiedObjectSegmentCount++;
ignoreOldAttr = OF_TRUE;
break;
}
}
if(ignoreOldAttr)
{
continue;
}
}
if(!copiedObjectSegmentCount && !allocateNewObjectHandle(phNewObj))
{
return OFR_DEVICE_ERROR;//could not allocate new object handle
}
itr2 &= 0xFFFF0000;
while(ok)
{
srcSegLen = iterateOnObjectAttributeSegments(hObj, attrType, &itr2);
if(!srcSegLen)
{
break;
}
cntItr = 0;
di->markg(&mark);
if (iterateOnSegments(&itr3, &cntItr, (OF_UINT)-1, (OF_UINT)-1, (OF_ATTRIBUTE_TYPE)-1, OF_TRUE, OF_FALSE, OF_TRUE, srcSegLen))
{
mark -= SIZEOF_AT+SIZEOF_SF+SIZEOF_SN;
di->restoreg(mark);//seek after objectHandle
di->read(cBuf, srcSegLen - SIZEOF_VI - SIZEOF_OH);//reading source attributeType, segmentFlags, segmentNumber & content
if(hNewObj == 0xFFFF)
{
hNewObj = (OF_UINT) (*phNewObj & ~OF_NORMAL_OBJECT_HANDLE_MASK);
}
if(isObjectPrivate)
{
cBuf[SIZEOF_AT] |= SEGMENT_FLAG_MASK_PRIVATE;
}
else
{
cBuf[SIZEOF_AT] &= ~SEGMENT_FLAG_MASK_PRIVATE;
}
di->write((OF_BYTE_PTR)&hNewObj, SIZEOF_OH);//replacing new objectHandler
di->write(cBuf, srcSegLen - SIZEOF_VI - SIZEOF_OH);//duplicating attributeType, segmentFlags, segmentNumber & content
#if OF_CACHE_L1
setSegmentStatusItr(itr3, _segNum(cBuf+SIZEOF_AT+SIZEOF_SF) ? SEGMENT_STATUS_VALID : SEGMENT_STATUS_VALID_FAS, srcSegLen
#if OF_CACHE_L3
, _segNum(cBuf+SIZEOF_AT+SIZEOF_SF)
#if OF_CACHE_L4
, hNewObj, attrType
#endif
#endif
);
#endif
copiedObjectSegmentCount++;
}
else
{
ok = OF_FALSE;
break;
}
}
}
if(ok)
{
if(copiedObjectSegmentCount > 0)
{
return OFR_OK;
}
deleteOHandle(*phNewObj);
*phNewObj = OF_INVALID_OBJECT_HANDLE;
return OFR_OBJECT_HANDLE_INVALID;
}
if(copiedObjectSegmentCount > 0)
{
destroyObject(*phNewObj);
*phNewObj = OF_INVALID_OBJECT_HANDLE;
}
return OFR_DEVICE_ERROR;
}
OF_RV OFFSET::destroyObject(OF_OBJECT_HANDLE hObj, OF_BOOL bypassLogin)
{
OF_BOOL success = OF_FALSE;
OF_ULONG itr = 0, itr2 = 0;
OF_UINT attItr = (OF_UINT) -1;
OF_ATTRIBUTE_TYPE attrType;
OF_BYTE segLen;
OF_BOOL beginDeleting = beginDeletingObjectAttribute(hObj);
while(iterateOnObjectAttributes(hObj, &itr, &attItr, &attrType, bypassLogin))
{
itr2 &= 0xFFFF0000;
while(OF_TRUE)
{
segLen = iterateOnObjectAttributeSegments(hObj, attrType, &itr2);
if(!segLen)
{
break;
}
di->seekp(-1 * OF_OBJECT_SEGMENT_HEADER_SIZE);//seek before validationIndicator
OF_UINT buf = 0;
di->write((OF_BYTE_PTR)&buf, SIZEOF_VI);//invalidate segment
#if OF_CACHE_L1
setSegmentStatusItr((itr2>>16) & 0x0000FFFF, SEGMENT_STATUS_INVALID, segLen);
#endif
}
success = OF_TRUE;
}
if(success)
{
deleteOHandle(hObj);
di->flush();
}
if(beginDeleting)
{
endDeletingObjectAttribute();
}
return success ? OFR_OK : OFR_OBJECT_HANDLE_INVALID;
}
OF_BOOL OFFSET::freeObjectSegment(ObjectSegment* os)
{
OF_UINT itr = 0;
OF_BYTE cBuf[SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN], segLen;
while(OF_TRUE)
{
segLen = iterateOnSegments(&itr, NULL_PTR, os->segmentNumber, os->objectHandler, os->attrType, OF_TRUE, OF_TRUE);
if(!segLen)
{
break;
}
di->read(cBuf, SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN);//reading objectHandle, attributeType, segmentFlags & segmentNumber
if(*((OF_UINT_PTR)cBuf) == os->objectHandler && *((OF_ATTRIBUTE_TYPE*)(cBuf+SIZEOF_OH)) == os->attrType && _segNum(cBuf+SIZEOF_OH+SIZEOF_AT+SIZEOF_SF) == os->segmentNumber)
{//matched object info
di->seekp(-1 * (int)SIZEOF_VI);//seeking before validationIndicator
di->memset(cBuf, 0, SIZEOF_VI);
di->write(cBuf, SIZEOF_VI);//invalidate validationIndicator
#if OF_CACHE_L1
setSegmentStatusItr(itr, SEGMENT_STATUS_INVALID, segLen);
#endif
return OF_TRUE;
}
}
return OF_FALSE;
}
OF_BYTE OFFSET::iterateOnSegments(OF_UINT_PTR itr, OF_UINT_PTR cntItr, OF_OBJECT_HANDLE segmentNumber, OF_UINT oHandle, OF_ATTRIBUTE_TYPE attrType, OF_BOOL onlyValidSegments, OF_BOOL onlyNonFreeSegments, OF_BOOL onlyFreeSegments, OF_BYTE requiredSize, OF_BOOL onlyPrivateSegments, OF_BOOL onlyPublicSegments)
{
OF_UINT i = _getItrPageNum(*itr);//pageNum
OF_UINT j = _getItrSegNumInPage(*itr);//segmentNumInPage
OF_BYTE msCount, tmp;
while(cntItr == NULL_PTR || *cntItr < OF_SEGMENT_MAX_COUNT)
{//while iteration not completed
if(j >= OF_SEGMENT_MAX_COUNT_PER_PAGE)
{//goto next page
j = 0;
i++;
}
if(i >= OF_HW_DATAPAGE_COUNT)
{//invalid iterator
if(cntItr == NULL_PTR)
{//iterate only to the end of memory
return 0;
}
i = 0;
}
OF_ULONG iBase = OF_CONST_DATABASE_ADDRESS + i*OF_HW_PAGE_SIZE;
//seeking at the begining of segment
di->seekg(iBase + j*OF_SEGMENT_MIN_SIZE, OF_TRUE);
di->seekp(iBase + j*OF_SEGMENT_MIN_SIZE, OF_TRUE);
msCount = 1;
_setItrPageNum(*itr, i);
_setItrSegNumInPage(*itr, ++j);
(*cntItr)++;
#if OF_CACHE_L1
OF_BOOL cnt = OF_TRUE, nextSeg = OF_TRUE;
OF_UINT sgIndex = i*OF_SEGMENT_MAX_COUNT_PER_PAGE+j-1;
OF_BYTE status = getSegmentStatus(sgIndex);
switch(status)
{
case SEGMENT_STATUS_INVALID:
cnt = !onlyValidSegments;
break;
case SEGMENT_STATUS_VALID:
case SEGMENT_STATUS_VALID_FAS:
cnt = !onlyFreeSegments;
break;
case SEGMENT_STATUS_FREE:
cnt = !onlyNonFreeSegments;
nextSeg = OF_FALSE;
break;
}
if(nextSeg)
{
tmp = getMinimizedSegmentCount(sgIndex)-1;
if(tmp)
{
j += tmp;
_setItrSegNumInPage(*itr, j);
(*cntItr) += tmp;
if(status == SEGMENT_STATUS_VALID || status == SEGMENT_STATUS_VALID_FAS)
{
msCount += tmp;
}
}
}
#if OF_CACHE_L2
#if OF_CACHE_L3
if(cnt && onlyNonFreeSegments && onlyValidSegments)
{
if(segmentNumber != 0xFFFF && getSegmentNumModulus(sgIndex) != (segmentNumber%16))
{
continue;
}
#if OF_CACHE_L4
if ((oHandle != OF_INVALID_OBJECT_HANDLE && getObjHandleModulus(sgIndex) != (oHandle % 16)) || (attrType != OF_INVALID_ATTRIBUTE_TYPE && getObjAttrTypeModulus(sgIndex) != (attrType % 16)))
{
continue;
}
#endif
}
#endif
#endif
if(!cnt)
{
continue;
}
if(onlyPublicSegments || onlyPrivateSegments)
{
OF_BYTE cBuf[SIZEOF_SF + SIZEOF_SN];
di->seekp(SIZEOF_VI);//seeking validationIndicator
di->seekg(SIZEOF_VI + SIZEOF_OH + SIZEOF_AT);
di->read(cBuf, SIZEOF_SF + SIZEOF_SN);//reading segmentFlag & segmentNumber
if (!onlyFreeSegments && segmentNumber != OF_INVALID_SEGMENT_NUMBDER && ((_segNum(cBuf + SIZEOF_SF)) % 16) != (segmentNumber % 16))
{
continue;
}
if((onlyPrivateSegments && (cBuf[0] & SEGMENT_FLAG_MASK_PRIVATE)) || (onlyPublicSegments && !(cBuf[0] & SEGMENT_FLAG_MASK_PRIVATE)))
{
di->seekg(-1 * (int)(SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN));//seeking before objectHandle
return msCount * OF_SEGMENT_MIN_SIZE;
}
}
else
{
di->seekp(SIZEOF_VI);//seeking validationIndicator
di->seekg(SIZEOF_VI);//seeking validationIndicator
#else
OF_UINT buf;
if(onlyValidSegments)
{
di->read((char*)&buf, SIZEOF_VI);//reading validationIndicator
if((unsigned char)buf != OF_CONST_FREE_QWORD_VALUE)
{//invalid segment
tmp = getMinimizedSegmentCount(i*OF_SEGMENT_MAX_COUNT_PER_PAGE+j-1)-1;
if(tmp)
{
j += tmp;
_setItrSegNumInPage(*itr, j);
(*cntItr) += tmp;
}
continue;
}
}
else
{
di->seekg(SIZEOF_VI);//seeking validationIndicator
}
di->read((char*)&buf, SIZEOF_OH);//reading objectHandle
if(buf != OF_CONST_FREE_HWORD_VALUE)
{//non-free segment
tmp = getMinimizedSegmentCount(i*OF_SEGMENT_MAX_COUNT_PER_PAGE+j-1)-1;
if(tmp)
{
j += tmp;
_setItrSegNumInPage(*itr, j);
(*cntItr) += tmp;
msCount += tmp;
}
}
if((onlyFreeSegments && buf != OF_CONST_FREE_HWORD_VALUE) || (onlyNonFreeSegments && buf == OF_CONST_FREE_HWORD_VALUE))
{//free or non-free??? this is the question!
continue;
}
if(onlyPublicSegments || onlyPrivateSegments)
{
unsigned char cBuf[SIZEOF_SF+SIZEOF_SN];
di->seekg(SIZEOF_AT);//seeking attributeType
di->read((char*)cBuf, SIZEOF_SF + SIZEOF_SN);//reading segmentFlag & segmentNumber
if((onlyPrivateSegments && (cBuf[0] & SEGMENT_FLAG_MASK_PRIVATE)) || (onlyPublicSegments && !(cBuf[0] & SEGMENT_FLAG_MASK_PRIVATE)))
{
di->seekg(-1 * (int)(SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN));//seeking before objectHandle
di->seekp(SIZEOF_VI);//seeking validationIndicator
return msCount * OF_SEGMENT_MIN_SIZE;
}
}
else
{
di->seekg(-1 * (int)SIZEOF_OH);//seeking before objectHandle
di->seekp(SIZEOF_VI);//seeking validationIndicator
#endif
if(!onlyNonFreeSegments)
{
OF_BYTE n = (requiredSize/OF_SEGMENT_MIN_SIZE);
if(onlyFreeSegments && msCount < n)
{//calculate number of sequential free segments
#if !OF_CACHE_L1
unsigned char cBuf[SIZEOF_VI+SIZEOF_OH];
#endif
while(*cntItr < OF_SEGMENT_MAX_COUNT)
{
OF_UINT iPos = i*OF_SEGMENT_MAX_COUNT_PER_PAGE;
while(msCount < n && j <= OF_SEGMENT_MAX_COUNT_PER_PAGE-n+msCount && *cntItr < OF_SEGMENT_MAX_COUNT)
{
#if OF_CACHE_L1
if(getSegmentStatus(iPos+j) != SEGMENT_STATUS_FREE)
{
msCount = getMinimizedSegmentCount(iPos+j);
(*cntItr) += msCount;
j += msCount;
msCount = 0;
continue;
}
#else
di->seekg(iBase + j*OF_SEGMENT_MIN_SIZE, OF_TRUE);
di->read((char*)cBuf, SIZEOF_VI + SIZEOF_OH);
OF_ULONG _freeW = OF_CONST_FREE_WORD_VALUE;
if(memcmp(cBuf, &_freeW, SIZEOF_VI+SIZEOF_OH))
{//invalid or non-free segment
msCount = getMinimizedSegmentCount(iPos+j);
(*cntItr) += msCount;
j += msCount;
msCount = 0;
continue;
}
#endif
(*cntItr)++;
j++;
msCount++;
}
if(msCount == n)
{
di->seekg(iBase + (j - n)*OF_SEGMENT_MIN_SIZE + SIZEOF_VI, OF_TRUE);
di->seekp(iBase + (j - n)*OF_SEGMENT_MIN_SIZE + SIZEOF_VI, OF_TRUE);
break;
}
msCount = 0;
(*cntItr) += (OF_SEGMENT_MAX_COUNT_PER_PAGE-j);
j = 0;
if(++i == OF_HW_DATAPAGE_COUNT)
{
i = 0;
}
iBase = OF_CONST_DATABASE_ADDRESS + i*OF_HW_PAGE_SIZE;
}
_setItrPageNum(*itr, i);
_setItrSegNumInPage(*itr, j);
}
return msCount < n ? 0 : msCount * OF_SEGMENT_MIN_SIZE;
}
return msCount * OF_SEGMENT_MIN_SIZE;
}
}
return 0;
}
OF_BYTE OFFSET::iterateOnObjectAttributeSegments(OF_OBJECT_HANDLE hObj, OF_ATTRIBUTE_TYPE attrType, OF_ULONG_PTR itr)
{
OF_BYTE segmentFlags = (OF_BYTE) (*itr & 0x000000FF);
if(SIZEOF_SN == 1 && (segmentFlags & SEGMENT_FLAG_MASK_LAST_ATTR))
{
return 0;
}
OF_BYTE segLen;
OF_UINT segmentNumber = (OF_UINT) (((*itr)>>(8*(2-SIZEOF_SN))) & (SIZEOF_SN==1?0x000000FF:0x0000FFFF));
OF_UINT itr2 = (OF_UINT) ((*itr)>>16 & 0x0000FFFF), cntItr = 0;
OF_UINT oHandle = (OF_UINT) (hObj & ~OF_NORMAL_OBJECT_HANDLE_MASK);
OF_BOOL found = OF_FALSE;
OF_BYTE cBuf[SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN];
while(OF_TRUE)
{
segLen = iterateOnSegments(&itr2, &cntItr, segmentNumber, (OF_UINT)(hObj & ~OF_NORMAL_OBJECT_HANDLE_MASK), attrType, OF_TRUE, OF_TRUE);
if(!segLen)
{
break;
}
#if OF_CACHE_L1
#if OF_CACHE_L2
if(!segmentNumber && getSegmentStatusItr(itr2, segLen) != SEGMENT_STATUS_VALID_FAS)
{
continue;
}
#endif
#endif
di->read(cBuf, SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN);//reading objectHandle, attributeType, segmentFlag & segmentNumber
if(oHandle == *(OF_UINT_PTR)cBuf && *(OF_ATTRIBUTE_TYPE*)(cBuf+SIZEOF_OH) == attrType && _segNum(cBuf+SIZEOF_OH+SIZEOF_AT+SIZEOF_SF) == segmentNumber)
{//matched valid object handle & segment number
found = OF_TRUE;
segmentFlags = cBuf[SIZEOF_OH+SIZEOF_AT];
segmentNumber++;
di->seekp(SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN);//seeking to content
break;
}
}
*itr = itr2;
*itr <<= 8*SIZEOF_SN;
*itr |= segmentNumber;
if(SIZEOF_SN == 1)
{
*itr <<= 8;
*itr |= segmentFlags;
}
return found ? segLen : 0;
}
OF_BOOL OFFSET::iterateOnObjectTemplateStreamAtrributes(OF_ATTRIBUTE_PTR pAttr, const OF_BYTE_PTR pStreamValue, OF_ULONG_PTR itr)
{
if (pStreamValue == NULL_PTR || itr == NULL_PTR || ((*itr) & 0x0000FFFF) == *(OF_ULONG_PTR)pStreamValue /*|| ((*itr) & 0x0000FFFF) == 0xFFFF*/)
{
return OF_FALSE;
}
OF_ULONG cursor = ((*itr) >> 16) & 0x0000FFFF;
if (!cursor)
{
cursor = 2 * sizeof(OF_ULONG);
}
OF_BOOL incValues = *(OF_BOOL*)(pStreamValue + sizeof(OF_ULONG));
pAttr->type = *(OF_ATTRIBUTE_TYPE*)(pStreamValue + cursor);
cursor += sizeof(OF_ATTRIBUTE_TYPE);
pAttr->ulValueLen = *(OF_ULONG_PTR)(pStreamValue + cursor);
cursor += sizeof(OF_ULONG);
if ((incValues /*|| ((pAttr->type & CKF_ARRAY_ATTRIBUTE) && pAttr->type != CKA_ALLOWED_MECHANISMS)*/) && pAttr->ulValueLen && pAttr->ulValueLen != (OF_ULONG)-1)
{
pAttr->pValue = pStreamValue + cursor;
cursor += pAttr->ulValueLen;
}
else
{
pAttr->pValue = NULL_PTR;
}
*itr = (cursor << 16) | (++(*itr) & 0x0000FFFF);
return OF_TRUE;
}
OF_BOOL OFFSET::iterateOnObjectAttributes(OF_OBJECT_HANDLE hObj, OF_ULONG_PTR itr, OF_UINT_PTR attItr, OF_ATTRIBUTE_TYPE* pAttrType, OF_BOOL bypassLogin)
{
if(!bypassLogin && !di->isAuthenticated() && isPrivateObject(hObj))
{
return OF_FALSE;//could not return attributes of private object before login
}
OF_BYTE cBuf[SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN];
//OF_BYTE segmentNumber = (OF_BYTE) (*itr & 0x000000FF);
//OF_BYTE segmentFlags = (OF_BYTE) ((*itr)>>8 & 0x000000FF);
OF_UINT itr2 = (OF_UINT) ((*itr)>>16 & 0x0000FFFF), cntItr = 0;
OF_UINT oHandle = (OF_UINT) (hObj & ~OF_NORMAL_OBJECT_HANDLE_MASK);
OF_BOOL found = OF_FALSE;
OF_BYTE segLen;
while(OF_TRUE)
{
segLen = iterateOnSegments(&itr2, &cntItr, 0, (OF_UINT)(hObj & ~OF_NORMAL_OBJECT_HANDLE_MASK), (OF_ATTRIBUTE_TYPE)-1, OF_TRUE, OF_TRUE);
if(!segLen)
{
break;
}
#if OF_CACHE_L1
#if OF_CACHE_L2
if(getSegmentStatusItr(itr2, segLen) != SEGMENT_STATUS_VALID_FAS)
{
continue;
}
#endif
#endif
if(*attItr == itr2)
{
break;
}
di->read(cBuf, SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN);//reading objectHandle, attributeType, segmentFlag & segmentNumber
if(oHandle == *(OF_UINT_PTR)cBuf && _segNum(cBuf+SIZEOF_OH+SIZEOF_AT+SIZEOF_SF) == 0)
{//matched valid object handle & this is first segment of an object attribute
found = OF_TRUE;
//segmentNumber++;
if(pAttrType != NULL_PTR)
{
*pAttrType = *(OF_ATTRIBUTE_TYPE*)(cBuf+SIZEOF_OH);
}
di->seekp(SIZEOF_OH + SIZEOF_AT + SIZEOF_SF + SIZEOF_SN);//seeking to content
if(*attItr == 0xFFFF)//*attItr == -1
{
*attItr = itr2;
}
break;
}
}
*itr = ((OF_ULONG)itr2)<<16;
//*itr |= segmentNumber;
return found;
}
OF_BOOL OFFSET::beginDeletingObjectAttribute(OF_OBJECT_HANDLE hObj, OF_ATTRIBUTE_TYPE attrType, OF_BYTE flags)
{
OF_BYTE buf[2*sizeof(OF_UINT)+sizeof(OF_ATTRIBUTE_TYPE)];
hObj &= ~OF_NORMAL_OBJECT_HANDLE_MASK;
di->memcpy(buf, &hObj, sizeof(OF_UINT));
di->memcpy(buf + sizeof(OF_UINT), &attrType, sizeof(OF_ATTRIBUTE_TYPE));
di->memcpy(buf + sizeof(OF_UINT)+sizeof(OF_ATTRIBUTE_TYPE), &flags, sizeof(OF_BYTE));
return di->writeMetaData(OFMID_DELETING_OBJECT_ATTR_0, buf, sizeof(buf)) == sizeof(buf);
}
OF_VOID OFFSET::endDeletingObjectAttribute()
{
OF_UINT buf = 0xFFFF;
di->writeMetaData(OFMID_DELETING_OBJECT_ATTR_0, &buf, sizeof(buf));
}
OF_BOOL OFFSET::beginFormattingPage(OF_UINT pageIndex, OF_UINT isDataPage)
{
if(!isTotalFormatting)
{
OF_UINT buf = (((uint16_t)pageIndex)<<8) | isDataPage;
return di->writeMetaData(OFMID_FORMATTING_PAGE, &buf, sizeof(buf)) == sizeof(buf);
}
return OF_TRUE;
}
OF_VOID OFFSET::endFormattingPage()
{
if(!isTotalFormatting)
{
OF_UINT buf = (OF_UINT)-1;
di->writeMetaData(OFMID_FORMATTING_PAGE, &buf, sizeof(buf));
}
}
OF_BOOL OFFSET::allocateNewObjectHandle(OF_OBJECT_HANDLE_PTR phObj)
{
//begin critical section
for(OF_ULONG i=1; i < 0xFFFE; i++)
{
if(lastGeneratedObjectHandle == 0xFFFE)
{
lastGeneratedObjectHandle = 0;
}
if(!this->objectExists(OF_NORMAL_OBJECT_HANDLE_MASK+1+lastGeneratedObjectHandle, OF_TRUE))
{
addOHandle(*phObj = OF_NORMAL_OBJECT_HANDLE_MASK+1+lastGeneratedObjectHandle++);
return OF_TRUE;
}
lastGeneratedObjectHandle++;
}
//end critical section
*phObj = OF_INVALID_OBJECT_HANDLE;
return OF_FALSE;
}
OF_BOOL OFFSET::isPrivateObject(OF_OBJECT_HANDLE hObj)
{
OF_BYTE flags = 0;
OF_ULONG itr = 0, _markp, _markg;
OF_UINT attItr = (OF_UINT)-1;
di->markp(&_markp);
di->markg(&_markg);
if (iterateOnObjectAttributes(hObj, &itr, &attItr, NULL_PTR, OF_TRUE))
{
di->seekg(-1 * (int)(SIZEOF_SF + SIZEOF_SN));
di->read(&flags, SIZEOF_SF);//reading segment flags
}
di->restorep(_markp);
di->restoreg(_markg);
return (flags & SEGMENT_FLAG_MASK_PRIVATE) ? OF_TRUE : OF_FALSE;
}
OF_BYTE OFFSET::getMinimizedSegmentCount(OF_UINT segmentGlobalIndex, OF_BOOL useCache)
{
#if OF_CACHE_L1
if(useCache)
{
#if OF_CACHE_L2
return getSegmentCount(segmentGlobalIndex);
#else
if(getSegmentStatus(segmentGlobalIndex) == SEGMENT_STATUS_FREE)
{
return 1;
}
#endif
}
#endif
OF_UINT buf;
OF_ULONG mark;
di->markg(&mark);
di->seekg(OF_CONST_DATABASE_ADDRESS + segmentGlobalIndex*OF_SEGMENT_MIN_SIZE + SIZEOF_VI, OF_TRUE);
di->read((OF_BYTE_PTR)&buf, SIZEOF_OH);
if(buf == OF_CONST_FREE_HWORD_VALUE)
{//free segment
di->restoreg(mark);
return 1;
}
di->seekg(SIZEOF_AT);
di->read((OF_BYTE_PTR)&buf, SIZEOF_SF);//+SIZEOF_SN);
di->restoreg(mark);
return _getSegmentCount(buf);
}
#if OF_CACHE_L1
OF_BYTE OFFSET::getSegmentStatus(OF_UINT segmentGlobalIndex)
{
#if OF_CACHE_L2
#if OF_CACHE_L3
#if OF_CACHE_L4
return (segStatusCache[2*segmentGlobalIndex] & 0x03);
#else
return (segStatusCache[segmentGlobalIndex] & 0x03);
#endif
#else
return (segStatusCache[segmentGlobalIndex/2] & (0x03 << ((segmentGlobalIndex%2)*4))) >> ((segmentGlobalIndex%2)*4);
#endif
#else
return (segStatusCache[segmentGlobalIndex/4] & (0x03 << ((segmentGlobalIndex%4)*2))) >> ((segmentGlobalIndex%4)*2);
#endif
}
OF_VOID OFFSET::setSegmentStatus(OF_UINT segmentGlobalIndex, OF_BYTE status, OF_BYTE segCount
#if OF_CACHE_L3
, OF_UINT segNum
#if OF_CACHE_L4
, OF_UINT oHandle, OF_ATTRIBUTE_TYPE attrType
#endif
#endif
)
{
#if OF_CACHE_L2
OF_BYTE newStatus = status;
//specifying segment length type
switch(segCount)
{
case 1://1x16-byte segment
break;
case 2://2x16-byte segments
newStatus |= SEGMENT_FLAG_MASK_LEN_AVG;
break;
//case 4:
default://4x16-byte segments
newStatus |= SEGMENT_FLAG_MASK_LEN_MAX;
}
#else
if(status == SEGMENT_STATUS_VALID_FAS)
{
status = SEGMENT_STATUS_VALID;
}
#endif
while(segCount--)
{
#if OF_CACHE_L2
#if OF_CACHE_L3
#if OF_CACHE_L4
segStatusCache[2*segmentGlobalIndex] = (newStatus | ((segNum%16)<<4));
segStatusCache[2*segmentGlobalIndex+1] = ((attrType%16) | ((oHandle%16)<<4));
#else
segStatusCache[segmentGlobalIndex] = (newStatus | ((segNum%16)<<4));
#endif
#else
segStatusCache[segmentGlobalIndex/2] = (segStatusCache[segmentGlobalIndex/2] & ~(0x0F<<((segmentGlobalIndex%2)*4))) | (newStatus<<((segmentGlobalIndex%2)*4));
#endif
/*if(segCount)
{
newStatus &= 0x03;
}*/
#else
segStatusCache[segmentGlobalIndex/4] = (segStatusCache[segmentGlobalIndex/4] & ~(0x03<<((segmentGlobalIndex%4)*2))) | (status<<((segmentGlobalIndex%4)*2));
#endif
segmentGlobalIndex++;
}
}
OF_BYTE OFFSET::getSegmentStatusItr(OF_UINT itr, OF_BYTE segLen)
{
OF_BYTE pageIndex = _getItrPageNum(itr);
OF_UINT segmentIndex = _getItrSegNumInPage(itr);
segLen /= OF_SEGMENT_MIN_SIZE;
//if(segLen <= segmentIndex)
//assume all continues segments are in a single page
return getSegmentStatus(pageIndex*OF_SEGMENT_MAX_COUNT_PER_PAGE+segmentIndex-segLen);
}
OF_VOID OFFSET::setSegmentStatusItr(OF_UINT itr, OF_BYTE status, OF_BYTE segLen
#if OF_CACHE_L3
, OF_UINT segNum
#if OF_CACHE_L4
, OF_UINT oHandle, OF_ATTRIBUTE_TYPE attrType
#endif
#endif
)
{
OF_BYTE pageIndex = _getItrPageNum(itr);
OF_UINT segmentIndex = _getItrSegNumInPage(itr);
segLen /= OF_SEGMENT_MIN_SIZE;
if(segLen <= segmentIndex)
{
setSegmentStatus(pageIndex*OF_SEGMENT_MAX_COUNT_PER_PAGE+segmentIndex-segLen, status, segLen
#if OF_CACHE_L3
, segNum
#if OF_CACHE_L4
, oHandle, attrType
#endif
#endif
);
}
}
#if OF_CACHE_L2
OF_BYTE OFFSET::getSegmentCount(OF_UINT segmentGlobalIndex)
{
#if OF_CACHE_L3
#if OF_CACHE_L4
return _getSegmentCount(segStatusCache[segmentGlobalIndex*2]/* & 0x0F*/);
#else
return _getSegmentCount(segStatusCache[segmentGlobalIndex]/* & 0x0F*/);
#endif
#else
return _getSegmentCount((segStatusCache[segmentGlobalIndex/2]) >> ((segmentGlobalIndex%2)*4));
#endif
}
#if OF_CACHE_L3
OF_BYTE OFFSET::getSegmentNumModulus(OF_UINT segmentGlobalIndex)
{
#if OF_CACHE_L4
return (segStatusCache[segmentGlobalIndex*2]>>4)%16;
#else
return (segStatusCache[segmentGlobalIndex]>>4)%16;
#endif
}
#if OF_CACHE_L4
OF_BYTE OFFSET::getObjHandleModulus(OF_UINT segmentGlobalIndex)
{
return (segStatusCache[segmentGlobalIndex*2+1]>>4)%16;
}
OF_BYTE OFFSET::getObjAttrTypeModulus(OF_UINT segmentGlobalIndex)
{
return (segStatusCache[segmentGlobalIndex*2+1] & 0x0F)%16;
}
#endif
#endif
#endif
#endif
OF_BOOL OFFSET::addOHandle(OF_OBJECT_HANDLE hObject)
{
OF_UINT oHandle = (OF_UINT)(hObject & ~OF_NORMAL_OBJECT_HANDLE_MASK);
for(OF_UINT i=0;i<oHandlesCount;i++)
{
if(oHandles[i] == oHandle)
{//object handle already exists
return OF_FALSE;
}
}
for(OF_UINT i=0;i<oHandlesCount;i++)
{
if(oHandles[i] == (OF_UINT)-1)
{
oHandles[i] = oHandle;
return OF_TRUE;
}
}
OF_UINT_PTR temp = (OF_UINT_PTR)di->realloc(oHandles, (oHandlesCount + OBJECT_HANDLE_LIST_GROW_SIZE)*sizeof(OF_UINT));
if(!temp)
{
return OF_FALSE;
}
oHandles = temp;
oHandles[oHandlesCount++] = oHandle;
for(OF_UINT i=1;i<OBJECT_HANDLE_LIST_GROW_SIZE;i++)
{
oHandles[oHandlesCount++] = (OF_UINT)-1;
}
return OF_TRUE;
}
OF_BOOL OFFSET::deleteOHandle(OF_OBJECT_HANDLE hObject)
{
OF_UINT oHandle = (OF_UINT)(hObject & ~OF_NORMAL_OBJECT_HANDLE_MASK), freeOHandleCount = 0;
OF_BOOL res = OF_FALSE;
for(OF_UINT i=0;i<oHandlesCount;i++)
{
if(oHandles[i] == oHandle)
{
oHandles[i] = (OF_UINT)-1;
res = OF_TRUE;
}
if(oHandles[i] == (OF_UINT)-1)
{
freeOHandleCount++;
}
}
if(freeOHandleCount > 10*OBJECT_HANDLE_LIST_GROW_SIZE)
{
OF_UINT newOhandleCount = oHandlesCount - (freeOHandleCount-(freeOHandleCount%OBJECT_HANDLE_LIST_GROW_SIZE)) + OBJECT_HANDLE_LIST_GROW_SIZE;
OF_UINT_PTR newOHandles = (OF_UINT_PTR) di->malloc(newOhandleCount*sizeof(OF_UINT)/*, OF_FALSE*/);
if(newOHandles)
{
OF_UINT j=0;
for(OF_UINT i=0;i<oHandlesCount;i++)
{
if(oHandles[i] != (OF_UINT)-1)
{
newOHandles[j++] = oHandles[i];
}
}
for(;j<newOhandleCount;j++)
{
newOHandles[j] = (OF_UINT)-1;
}
di->free(oHandles);
oHandles = newOHandles;
oHandlesCount = newOhandleCount;
}
}
return res;
}
OF_RV OFFSET::validateObjectAttributeValue(OF_ATTRIBUTE_TYPE attrType, OF_VOID_PTR pAttrValue, OF_ULONG_PTR pulAttrValueLen)
{
if (attrType == OF_INVALID_ATTRIBUTE_TYPE || pulAttrValueLen == NULL_PTR || (pAttrValue == NULL_PTR && *pulAttrValueLen > 0) || *pulAttrValueLen > OF_OBJECT_MAX_ALLOWED_ATTRIBUTE_SIZE)
{
return OFR_FUNCTION_INVALID_PARAM;
}
return OFR_OK;
}
| 28.141359 | 344 | 0.710804 | [
"object"
] |
5dd2d9a81c1ccfed5b2739a4b3537d0da9b87f09 | 9,421 | hpp | C++ | plugins/ThrustFilePlugin/src/base/forcemodel/FileThrust.hpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | plugins/ThrustFilePlugin/src/base/forcemodel/FileThrust.hpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | plugins/ThrustFilePlugin/src/base/forcemodel/FileThrust.hpp | IncompleteWorlds/GMAT_2020 | 624de54d00f43831a4d46b46703e069d5c8c92ff | [
"Apache-2.0"
] | null | null | null | //------------------------------------------------------------------------------
// FileThrust
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2020 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under the FDSS II
// contract, Task Order 08
//
// Author: Darrel J. Conway, Thinking Systems, Inc.
// Created: Jan 13, 2016
/**
*
*/
//------------------------------------------------------------------------------
#ifndef FileThrust_hpp
#define FileThrust_hpp
#include "ThrustFileDefs.hpp"
#include "PhysicalModel.hpp"
#include "ThrustSegment.hpp"
#include "LinearInterpolator.hpp"
#include "NotAKnotInterpolator.hpp"
/**
* Physical model used to apply derivative data from a thrust history file
*/
class FileThrust: public PhysicalModel
{
public:
FileThrust(const std::string &name = "");
virtual ~FileThrust();
FileThrust(const FileThrust& ft);
FileThrust& operator=(const FileThrust& ft);
bool operator==(const FileThrust& ft) const;
virtual GmatBase* Clone() const;
virtual void Clear(const UnsignedInt
type = Gmat::UNKNOWN_OBJECT);
virtual Integer GetParameterID(const std::string &str) const;
virtual bool IsParameterReadOnly(const Integer id) const;
virtual bool IsParameterReadOnly(const std::string &label) const;
virtual Real GetRealParameter(const Integer id) const;
virtual Real SetRealParameter(const Integer id,
const Real value);
virtual const ObjectTypeArray&
GetRefObjectTypeArray();
virtual bool SetRefObjectName(const UnsignedInt type,
const std::string &name);
virtual const StringArray&
GetRefObjectNameArray(const UnsignedInt type);
virtual bool SetRefObject(GmatBase *obj,
const UnsignedInt type,
const std::string &name = "");
virtual bool SetRefObject(GmatBase *obj,
const UnsignedInt type,
const std::string &name, const Integer index);
virtual bool RenameRefObject(const UnsignedInt type,
const std::string &oldName,
const std::string &newName);
virtual GmatBase* GetRefObject(const UnsignedInt type,
const std::string &name);
virtual GmatBase* GetRefObject(const UnsignedInt type,
const std::string &name,
const Integer index);
virtual bool IsTransient();
virtual bool DepletesMass();
virtual void SetSegmentList(std::vector<ThrustSegment>* segs);
const std::vector<ThrustSegment> GetAllThrustSegments(); // Thrust Scale Factor Solve For
virtual void SetPropList(ObjectArray *soList);
virtual bool Initialize();
virtual bool GetDerivatives(Real * state, Real dt, Integer order,
const Integer id = -1);
virtual Rvector6 GetDerivativesForSpacecraft(Spacecraft *sc);
// Methods used by the ODEModel to set the state indexes, etc
virtual bool SupportsDerivative(Gmat::StateElementId id);
virtual bool SetStart(Gmat::StateElementId id, Integer index,
Integer quantity, Integer sizeOfType);
virtual StringArray GetSolveForList();
virtual void SetStmIndex(Integer id, Integer paramID);
// Methods we may need in the future are commented out
// virtual Integer GetEstimationParameterID(const std::string ¶m);
// virtual std::string GetParameterNameForEstimationParameter(const std::string &parmName);
// virtual std::string GetParameterNameFromEstimationParameter(const std::string &parmName);
// virtual Integer SetEstimationParameter(const std::string ¶m);
virtual bool IsEstimationParameterValid(const Integer id);
// virtual Integer GetEstimationParameterSize(const Integer id);
// virtual Real* GetEstimationParameterValue(const Integer id);
// Covariance handling code
virtual Integer HasParameterCovariances(Integer parameterId);
virtual Rmatrix* GetParameterCovariances(Integer parameterId = -1);
virtual Covariance* GetCovariance();
virtual bool SetPrecisionTimeFlag(bool onOff);
// Methods for getting stop epochs for force models
virtual Real GetForceMaxStep(bool forward = true);
virtual Real GetForceMaxStep(Real theEpoch, bool forward = true);
virtual Real GetForceMaxStep(const GmatTime& theEpochGT, bool forward = true);
DEFAULT_TO_NO_CLONES
protected:
// Pieces needed for bookkeeping
/// Names of the spacecraft accessed by this force
StringArray spacecraftNames;
/// Propagated objects used in the ODEModel
ObjectArray spacecraft;
/// Indexes (in the spacecraft vector) for the Spacecraft used by this force
std::vector<Integer> scIndices;
/// Number of spacecraft in the state vector that use CartesianState
Integer satCount;
/// Start index for the Cartesian state
Integer cartIndex;
/// Flag indicating if the Cartesian state should be populated
bool fillCartesian;
/// Flag to toggle thrust vs accel
bool dataIsThrust;
/// Flag used to warn once that then go silent if mass flow is missing tank
bool massFlowWarningNeeded;
/// Names of the segments accessed by this force
StringArray segmentNames;
/// The segment data from the thrust history file
std::vector<ThrustSegment> *segments;
/// Start index for the dm/dt data
Integer mDotIndex;
/// Flag indicating if any thrusters are set to deplete mass
bool depleteMass;
/// Name of the tank that is supplying fuel (just 1 for now)
std::string activeTankName;
/// List of coordinate systems used in the segments
StringArray csNames;
/// Current coordinate system, used when coversion is needed
CoordinateSystem *coordSystem;
/// 5 raw data elements: 3 thrust/accel components, mdot, interpolation method
Real dataBlock[7];
/// dataSet is (up to) 5 dataBlock sets, with the last element set to time
Real dataSet[5][5];
/// Linear interpolator object (currently not used
LinearInterpolator *liner;
/// Not a knot interpolator, used for spline interpolation
NotAKnotInterpolator *spliner;
/// Flag used to mark when the "too few points" warning has been written
bool warnTooFewPoints;
/// Indices into the profile data that is loaded into the interpolator
Integer interpolatorData[5];
/// Last used index pair
Integer indexPair[2];
// Thrust Scale Factor Solve For data
/// Spacecraft thrust scale factor
Real thrustSF;
/// Starting value for the Spacecraft thrust scale factor
Real thrustSFinitial;
/// Initial value of thrust scale factor
std::vector<Real> tsfInitial;
/// Flag indicating if ThrustSF is being estimated
bool estimatingTSF;
/// ID for the tsfEpsilon parameter
Integer tsfEpsilonID;
/// Row/Column for the TSF entries in the A-matrix and STM
Integer tsfEpsilonRow;
/// Current value(s) of tsf
//std::vector<Real> tsfEpsilon;
Rvector3 Accelerate(GmatEpoch &theEpoch, Real mass);
Rvector3 Accelerate(GmatTime &theEpoch, Real mass);
void ComputeAccelerationMassFlow(const GmatEpoch segEpoch, const GmatEpoch atEpoch, Real burnData[4]);
void ComputeAccelerationMassFlow(const GmatTime &segEpoch, const GmatTime &atEpoch, Real burnData[4]);
Integer GetSegmentData(Integer atIndex, Real offset);
void Interpolate(Integer atIndex, Integer profileIndex, Real offset);
void LinearInterpolate(Integer atIndex, Integer profileIndex, Real offset);
void SplineInterpolate(Integer atIndex, Integer profileIndex, Real offset);
void ConvertDirectionToInertial(Real *dir, Real *dirInertial, Real epoch);
void ConvertDirectionToInertial(Real *dir, Real *dirInertial, const GmatTime &epochGT);
// Methods for checking if an epoch is in an interval, when direction matters
virtual bool InSegmentInterval(GmatEpoch begin, GmatEpoch end, GmatEpoch epoch);
virtual bool InSegmentInterval(const GmatTime& begin, const GmatTime& end, const GmatTime& epoch);
};
#endif /* FileThrust_hpp */
| 45.512077 | 112 | 0.615858 | [
"object",
"vector",
"model"
] |
5dd3f3c0c930175469d1b63c0cb5e65e7f447094 | 3,778 | cpp | C++ | platforms/linux/src/Transport/Socket/Socket.cpp | iotile/baBLE-linux | faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db | [
"MIT"
] | 13 | 2018-07-04T16:35:37.000Z | 2021-03-03T10:41:07.000Z | platforms/linux/src/Transport/Socket/Socket.cpp | iotile/baBLE | faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db | [
"MIT"
] | 11 | 2018-06-01T20:32:32.000Z | 2019-01-21T17:03:47.000Z | platforms/linux/src/Transport/Socket/Socket.cpp | iotile/baBLE-linux | faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db | [
"MIT"
] | null | null | null | #include <unistd.h>
#include "Socket.hpp"
#include "Exceptions/BaBLEException.hpp"
using namespace std;
Socket::Socket(sa_family_t domain, int type, int protocol): Socket() {
m_domain = domain;
m_socket = ::socket(m_domain, type, protocol);
if (m_socket < 0) {
throw Exceptions::BaBLEException(
BaBLE::StatusCode::SocketError,
"Error while creating the socket: " + string(strerror(errno))
);
}
m_open = true;
}
Socket::Socket() {
m_domain = {};
m_socket = -1;
m_open = false;
m_binded = false;
m_option_set = false;
m_connected = false;
}
void Socket::bind(uint16_t device, uint16_t channel){
struct sockaddr_hci addr {
m_domain,
device,
channel
};
int result = ::bind(m_socket, (struct sockaddr*) &addr, sizeof(addr));
if (result != 0) {
throw Exceptions::BaBLEException(
BaBLE::StatusCode::SocketError,
"Error while binding the socket: " + string(strerror(errno))
);
}
m_binded = true;
}
void Socket::bind(const array<uint8_t, 6>& address, uint8_t address_type, uint16_t channel){
bdaddr_t bdaddr{};
copy(address.begin(), address.end(), begin(bdaddr.b));
struct sockaddr_l2 addr{
m_domain,
0,
bdaddr,
channel,
address_type
};
int result = ::bind(m_socket, (struct sockaddr*)&addr, sizeof(addr));
if (result != 0) {
throw Exceptions::BaBLEException(
BaBLE::StatusCode::SocketError,
"Error while binding the socket: " + string(strerror(errno))
);
}
m_binded = true;
}
void Socket::write(const vector<uint8_t>& data){
ssize_t result = ::write(m_socket, data.data(), data.size());
if (result < 0) {
throw Exceptions::BaBLEException(
BaBLE::StatusCode::SocketError,
"Error occured while sending the packet: " + string(strerror(errno))
);
}
}
ssize_t Socket::read(vector<uint8_t>& data, bool peek) {
int flags = 0;
if (peek) {
flags |= MSG_PEEK;
}
ssize_t result = ::recv(m_socket, data.data(), data.size(), flags);
if (result != data.size()) {
throw Exceptions::BaBLEException(
BaBLE::StatusCode::SocketError,
"Error while reading the socket: " + string(strerror(errno))
);
}
}
void Socket::set_option(int level, int name, const void *val, socklen_t len) {
int result = ::setsockopt(m_socket, level, name, val, len);
if (result != 0) {
throw Exceptions::BaBLEException(
BaBLE::StatusCode::SocketError,
"Error while setting options on the socket: " + string(strerror(errno))
);
}
m_option_set = true;
}
void Socket::ioctl(uint64_t request, void* param) {
int result = ::ioctl(m_socket, request, param);
if (result != 0) {
throw Exceptions::BaBLEException(
BaBLE::StatusCode::SocketError,
"Error while sending ioctl request: " + string(strerror(errno))
);
}
}
void Socket::connect(const array<uint8_t, 6>& address, uint8_t address_type, uint16_t channel) {
bdaddr_t bdaddr{};
copy(address.begin(), address.end(), begin(bdaddr.b));
struct sockaddr_l2 addr{
m_domain,
0,
bdaddr,
channel,
address_type
};
int result = ::connect(m_socket, (struct sockaddr *)&addr, sizeof(addr));
if (result != 0) {
throw Exceptions::BaBLEException(
BaBLE::StatusCode::SocketError,
"Error while connecting the socket: " + string(strerror(errno))
);
}
m_connected = true;
}
void Socket::close() {
if (m_open) {
int result = ::close(m_socket);
if (result != 0) {
throw Exceptions::BaBLEException(
BaBLE::StatusCode::SocketError,
"Error while closing the socket: " + string(strerror(errno))
);
}
m_open = false;
}
}
int Socket::get_raw() {
return m_socket;
}
| 24.532468 | 96 | 0.635257 | [
"vector"
] |
5de4b603542e928f3c65d772cf4511e7fdcacff5 | 1,783 | cpp | C++ | src/1752_check.cpp | guitargeek/leetcode | 7d587774d3f922020b5ba3ca2d533b2686891fed | [
"MIT"
] | null | null | null | src/1752_check.cpp | guitargeek/leetcode | 7d587774d3f922020b5ba3ca2d533b2686891fed | [
"MIT"
] | null | null | null | src/1752_check.cpp | guitargeek/leetcode | 7d587774d3f922020b5ba3ca2d533b2686891fed | [
"MIT"
] | null | null | null | /**
1752. Check if Array Is Sorted and Rotated
Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.
There may be duplicates in the original array.
Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.
Example 1:
```
Input: nums = [3,4,5,1,2]
Output: true
Explanation: [1,2,3,4,5] is the original sorted array.
You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].
```
Example 2:
```
Input: nums = [2,1,3,4]
Output: false
Explanation: There is no sorted array once rotated that can make nums.
```
Example 3:
```
Input: nums = [1,2,3]
Output: true
Explanation: [1,2,3] is the original sorted array.
You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.
```
Example 4:
```
Input: nums = [1,1,1]
Output: true
Explanation: [1,1,1] is the original sorted array.
You can rotate any number of positions to make nums.
```
Example 5:
```
Input: nums = [2,1]
Output: true
Explanation: [1,2] is the original sorted array.
You can rotate the array by x = 5 positions to begin on the element of value 2: [2,1].
```
Constraints:
* 1 <= nums.length <= 100
* 1 <= nums[i] <= 100
*/
#include "leet.h"
namespace leet {
bool check(std::vector<int>& nums) {
if (nums.size() < 2)
return true;
int c = 0;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i - 1] > nums[i])
c++;
if (c == 2)
return false;
}
return c == 0 || nums.back() <= nums.front();
}
} // namespace leet
| 21.22619 | 173 | 0.619742 | [
"vector"
] |
5de5c1756fcc8dbe767220bdb0749b6385e0c495 | 18,050 | cc | C++ | epid/common/math/unittests/bignum-test.cc | TinkerBoard-Android/external-epid-sdk | 7d6a6b63582f241b4ae4248bab416277ed659968 | [
"Apache-2.0"
] | 1 | 2019-04-15T16:27:54.000Z | 2019-04-15T16:27:54.000Z | epid/common/math/unittests/bignum-test.cc | TinkerBoard-Android/external-epid-sdk | 7d6a6b63582f241b4ae4248bab416277ed659968 | [
"Apache-2.0"
] | null | null | null | epid/common/math/unittests/bignum-test.cc | TinkerBoard-Android/external-epid-sdk | 7d6a6b63582f241b4ae4248bab416277ed659968 | [
"Apache-2.0"
] | null | null | null | /*############################################################################
# Copyright 2016-2017 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
############################################################################*/
/*!
* \file
* \brief BigNum unit tests.
*/
#include "epid/common-testhelper/epid_gtest-testhelper.h"
#include "gtest/gtest.h"
#include "epid/common-testhelper/bignum_wrapper-testhelper.h"
#include "epid/common-testhelper/errors-testhelper.h"
extern "C" {
#include "epid/common/math/bignum.h"
}
namespace {
// Use Test Fixture for SetUp and TearDown
class BigNumTest : public ::testing::Test {
public:
static const BigNumStr str_0;
static const BigNumStr str_1;
static const BigNumStr str_2;
static const BigNumStr str_big;
static const BigNumStr str_2big;
static const BigNumStr str_large_m1;
static const BigNumStr str_large;
static const BigNumStr str_large_p1;
static const BigNumStr str_32byte_high_bit_set;
static const BigNumStr str_32byte_high;
static const std::vector<unsigned char> vec_33byte_low;
virtual void SetUp() {}
virtual void TearDown() {}
::testing::AssertionResult CompareBigNumStr(const BigNumStr* expected,
const BigNumStr* actual);
::testing::AssertionResult CompareBigNum(const BigNum* expected,
const BigNum* actual);
};
const BigNumStr BigNumTest::str_0{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
const BigNumStr BigNumTest::str_1{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
const BigNumStr BigNumTest::str_2{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02};
const BigNumStr BigNumTest::str_big{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
const BigNumStr BigNumTest::str_2big{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
const BigNumStr BigNumTest::str_large_m1{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xF0, 0xCD, 0x46, 0xE5, 0xF2,
0x5E, 0xEE, 0x71, 0xA4, 0x9E, 0x0C, 0xDC, 0x65, 0xFB, 0x12, 0x99,
0x92, 0x1A, 0xF6, 0x2D, 0x53, 0x6C, 0xD1, 0x0B, 0x50, 0x0C};
/// Intel(R) EPID 2.0 parameter p
const BigNumStr BigNumTest::str_large{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xF0, 0xCD, 0x46, 0xE5, 0xF2,
0x5E, 0xEE, 0x71, 0xA4, 0x9E, 0x0C, 0xDC, 0x65, 0xFB, 0x12, 0x99,
0x92, 0x1A, 0xF6, 0x2D, 0x53, 0x6C, 0xD1, 0x0B, 0x50, 0x0D};
const BigNumStr BigNumTest::str_large_p1{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xF0, 0xCD, 0x46, 0xE5, 0xF2,
0x5E, 0xEE, 0x71, 0xA4, 0x9E, 0x0C, 0xDC, 0x65, 0xFB, 0x12, 0x99,
0x92, 0x1A, 0xF6, 0x2D, 0x53, 0x6C, 0xD1, 0x0B, 0x50, 0x0E};
const BigNumStr BigNumTest::str_32byte_high{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
const BigNumStr BigNumTest::str_32byte_high_bit_set{
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
const std::vector<unsigned char> BigNumTest::vec_33byte_low{
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
::testing::AssertionResult BigNumTest::CompareBigNumStr(
const BigNumStr* expected, const BigNumStr* actual) {
int size = sizeof(BigNumStr);
unsigned char* expected_str = (unsigned char*)expected;
unsigned char* actual_str = (unsigned char*)actual;
for (int i = 0; i < size; ++i) {
if (expected_str[i] != actual_str[i]) {
return ::testing::AssertionFailure()
<< "Mismatch at " << i << " : Expected " << std::hex
<< expected_str[i] << " Found " << std::hex << actual_str[i];
}
}
return ::testing::AssertionSuccess();
}
::testing::AssertionResult BigNumTest::CompareBigNum(const BigNum* expected_bn,
const BigNum* actual_bn) {
size_t size = 0;
std::vector<unsigned char> expected_str;
std::vector<unsigned char> actual_str;
// Use an extra huge size so we have plenty of room to check
// overflow tests. This assumes no tests try to create a number
// bigger than 64 bytes.
size = sizeof(BigNumStr) * 2;
expected_str.resize(size, 0);
actual_str.resize(size, 0);
THROW_ON_EPIDERR(WriteBigNum(expected_bn, size, &expected_str[0]));
THROW_ON_EPIDERR(WriteBigNum(actual_bn, size, &actual_str[0]));
for (size_t i = 0; i < size; ++i) {
if (expected_str[i] != actual_str[i]) {
return ::testing::AssertionFailure() << "Numbers do not match";
}
}
return ::testing::AssertionSuccess();
}
///////////////////////////////////////////////////////////////////////
// Create / Destroy
TEST_F(BigNumTest, NewCanCreate256BitBigNum) {
BigNum* bn = nullptr;
EXPECT_EQ(kEpidNoErr, NewBigNum(32, &bn));
DeleteBigNum(&bn);
}
TEST_F(BigNumTest, NewFailsGivenNullPointer) {
EXPECT_EQ(kEpidBadArgErr, NewBigNum(sizeof(BigNumStr), NULL));
}
TEST_F(BigNumTest, NewFailsGivenSizeZero) {
BigNum* bn = nullptr;
EXPECT_EQ(kEpidBadArgErr, NewBigNum(0, &bn));
DeleteBigNum(&bn);
}
TEST_F(BigNumTest, DeleteBigNumNullsPointer) {
BigNum* bn = nullptr;
THROW_ON_EPIDERR(NewBigNum(sizeof(BigNumStr), &bn));
DeleteBigNum(&bn);
EXPECT_EQ(nullptr, bn);
}
TEST_F(BigNumTest, DeleteWorksGivenNullPointer) {
BigNum* bn = nullptr;
DeleteBigNum(nullptr);
EXPECT_EQ(nullptr, bn);
}
///////////////////////////////////////////////////////////////////////
// Serialization
TEST_F(BigNumTest, ReadFailsGivenNullPtr) {
BigNum* bn = nullptr;
THROW_ON_EPIDERR(NewBigNum(sizeof(BigNumStr), &bn));
EXPECT_EQ(kEpidBadArgErr, ReadBigNum(NULL, sizeof(BigNumStr), bn));
EXPECT_EQ(kEpidBadArgErr,
ReadBigNum(&this->str_large, sizeof(BigNumStr), NULL));
DeleteBigNum(&bn);
}
TEST_F(BigNumTest, ReadFailsGivenInvalidBufferSize) {
BigNumObj bn(32);
EXPECT_EQ(kEpidBadArgErr, ReadBigNum(&this->str_0, 0, bn));
EXPECT_EQ(kEpidBadArgErr,
ReadBigNum(&this->str_0, std::numeric_limits<size_t>::max(), bn));
#if (SIZE_MAX >= 0x100000001) // When size_t value allowed to be 0x100000001
EXPECT_EQ(kEpidBadArgErr, ReadBigNum(&this->str_0, 0x100000001, bn));
#endif
}
TEST_F(BigNumTest, ReadFailsGivenTooBigBuffer) {
BigNum* bn = nullptr;
THROW_ON_EPIDERR(NewBigNum(sizeof(BigNumStr), &bn));
EXPECT_NE(kEpidNoErr, ReadBigNum(&this->vec_33byte_low[0],
this->vec_33byte_low.size(), bn));
DeleteBigNum(&bn);
}
TEST_F(BigNumTest, WriteFailsGivenNullPtr) {
BigNum* bn = nullptr;
BigNumStr str = {0};
THROW_ON_EPIDERR(NewBigNum(sizeof(BigNumStr), &bn));
EXPECT_EQ(kEpidBadArgErr, WriteBigNum(NULL, sizeof(str), &str));
EXPECT_EQ(kEpidBadArgErr, WriteBigNum(bn, 0, NULL));
DeleteBigNum(&bn);
}
TEST_F(BigNumTest, WriteFailsGivenTooSmallBuffer) {
BigNumStr str;
BigNumObj bn(this->vec_33byte_low);
EXPECT_NE(kEpidNoErr, WriteBigNum(bn, sizeof(str), &str));
}
TEST_F(BigNumTest, ReadCanDeSerializeBigNumStrZero) {
BigNumObj bn_ref;
BigNumObj bn;
EXPECT_EQ(kEpidNoErr, ReadBigNum(&this->str_0, sizeof(this->str_0), bn));
// No way to check this yet
}
TEST_F(BigNumTest, ReadCanDeSerializeBigNum) {
BigNumObj bn;
EXPECT_EQ(kEpidNoErr,
ReadBigNum(&this->str_large, sizeof(this->str_large), bn));
// No way to check this yet
}
TEST_F(BigNumTest, WriteCanSerializeBigNumZero) {
BigNumObj bn; // defaults to 0
BigNumStr str;
EXPECT_EQ(kEpidNoErr, WriteBigNum(bn, sizeof(str), &str));
EXPECT_TRUE(CompareBigNumStr(&str, &this->str_0));
}
TEST_F(BigNumTest, DeSerializeFollowedBySerializeHasSameValue) {
BigNumStr str;
BigNumObj bn;
EXPECT_EQ(kEpidNoErr,
ReadBigNum(&this->str_large, sizeof(this->str_large), bn));
EXPECT_EQ(kEpidNoErr, WriteBigNum(bn, sizeof(str), &str));
EXPECT_TRUE(CompareBigNumStr(&this->str_large, &str));
}
///////////////////////////////////////////////////////////////////////
// Addition
TEST_F(BigNumTest, AddBadArgumentsFail) {
BigNumObj bn;
EXPECT_NE(kEpidNoErr, BigNumAdd(nullptr, nullptr, nullptr));
EXPECT_NE(kEpidNoErr, BigNumAdd(bn, nullptr, nullptr));
EXPECT_NE(kEpidNoErr, BigNumAdd(nullptr, bn, nullptr));
EXPECT_NE(kEpidNoErr, BigNumAdd(nullptr, nullptr, bn));
EXPECT_NE(kEpidNoErr, BigNumAdd(bn, bn, nullptr));
EXPECT_NE(kEpidNoErr, BigNumAdd(nullptr, bn, bn));
EXPECT_NE(kEpidNoErr, BigNumAdd(bn, nullptr, bn));
}
TEST_F(BigNumTest, AddZeroIsIdentity) {
BigNumObj bn;
BigNumObj bn_0(this->str_0);
BigNumObj bn_large(this->str_large);
EXPECT_EQ(kEpidNoErr, BigNumAdd(bn_large, bn_0, bn));
EXPECT_TRUE(CompareBigNum(bn, bn_large));
}
TEST_F(BigNumTest, AddOneIncrements) {
BigNumObj bn;
BigNumObj bn_1(this->str_1);
BigNumObj bn_large(this->str_large);
BigNumObj bn_large_p1(this->str_large_p1);
EXPECT_EQ(kEpidNoErr, BigNumAdd(bn_large, bn_1, bn));
EXPECT_TRUE(CompareBigNum(bn, bn_large_p1));
}
TEST_F(BigNumTest, AddOneTo32ByteInTo32BytesFails) {
BigNumObj bn(32);
BigNumObj bn_1(this->str_1);
BigNumObj bn_32high(this->str_32byte_high);
EXPECT_NE(kEpidNoErr, BigNumAdd(bn_32high, bn_1, bn));
}
TEST_F(BigNumTest, AddOneTo32ByteInTo33BytesIncrements) {
BigNumObj bn(33);
BigNumObj bn_1(this->str_1);
BigNumObj bn_32high(this->str_32byte_high);
BigNumObj bn_33low(this->vec_33byte_low);
EXPECT_EQ(kEpidNoErr, BigNumAdd(bn_32high, bn_1, bn));
EXPECT_TRUE(CompareBigNum(bn, bn_33low));
}
///////////////////////////////////////////////////////////////////////
// Subtraction
TEST_F(BigNumTest, SubBadArgumentsFail) {
BigNumObj bn;
EXPECT_NE(kEpidNoErr, BigNumSub(nullptr, nullptr, nullptr));
EXPECT_NE(kEpidNoErr, BigNumSub(bn, nullptr, nullptr));
EXPECT_NE(kEpidNoErr, BigNumSub(nullptr, bn, nullptr));
EXPECT_NE(kEpidNoErr, BigNumSub(nullptr, nullptr, bn));
EXPECT_NE(kEpidNoErr, BigNumSub(bn, bn, nullptr));
EXPECT_NE(kEpidNoErr, BigNumSub(nullptr, bn, bn));
EXPECT_NE(kEpidNoErr, BigNumSub(bn, nullptr, bn));
}
TEST_F(BigNumTest, SubOneFromZeroFails) {
BigNumObj bn;
BigNumObj bn_0(this->str_0);
BigNumObj bn_1(this->str_1);
EXPECT_EQ(kEpidUnderflowErr, BigNumSub(bn_0, bn_1, bn));
}
TEST_F(BigNumTest, SubZeroIsIdentity) {
BigNumObj bn;
BigNumObj bn_0(this->str_0);
BigNumObj bn_large(this->str_large);
EXPECT_EQ(kEpidNoErr, BigNumSub(bn_large, bn_0, bn));
EXPECT_TRUE(CompareBigNum(bn, bn_large));
}
TEST_F(BigNumTest, SubOneDecrements) {
BigNumObj bn;
BigNumObj bn_1(this->str_1);
BigNumObj bn_large(this->str_large);
BigNumObj bn_large_m1(this->str_large_m1);
EXPECT_EQ(kEpidNoErr, BigNumSub(bn_large, bn_1, bn));
EXPECT_TRUE(CompareBigNum(bn, bn_large_m1));
}
///////////////////////////////////////////////////////////////////////
// Multiplication
TEST_F(BigNumTest, MulBadArgumentsFail) {
BigNumObj bn;
EXPECT_NE(kEpidNoErr, BigNumMul(nullptr, nullptr, nullptr));
EXPECT_NE(kEpidNoErr, BigNumMul(bn, nullptr, nullptr));
EXPECT_NE(kEpidNoErr, BigNumMul(nullptr, bn, nullptr));
EXPECT_NE(kEpidNoErr, BigNumMul(nullptr, nullptr, bn));
EXPECT_NE(kEpidNoErr, BigNumMul(bn, bn, nullptr));
EXPECT_NE(kEpidNoErr, BigNumMul(nullptr, bn, bn));
EXPECT_NE(kEpidNoErr, BigNumMul(bn, nullptr, bn));
}
TEST_F(BigNumTest, MulOneIsIdentity) {
BigNumObj bn;
BigNumObj bn_1(this->str_1);
BigNumObj bn_large(this->str_large);
EXPECT_EQ(kEpidNoErr, BigNumMul(bn_large, bn_1, bn));
EXPECT_TRUE(CompareBigNum(bn, bn_large));
}
TEST_F(BigNumTest, MulTwoIsDouble) {
BigNumObj bn;
BigNumObj bn_2(this->str_2);
BigNumObj bn_big(this->str_big);
BigNumObj bn_2big(this->str_2big);
EXPECT_EQ(kEpidNoErr, BigNumMul(bn_big, bn_2, bn));
EXPECT_TRUE(CompareBigNum(bn, bn_2big));
}
TEST_F(BigNumTest, MulZeroIsZero) {
BigNumObj bn;
BigNumObj bn_0(this->str_0);
BigNumObj bn_large(this->str_large);
EXPECT_EQ(kEpidNoErr, BigNumMul(bn_large, bn_0, bn));
EXPECT_TRUE(CompareBigNum(bn, bn_0));
}
TEST_F(BigNumTest, MulReportsErrorGivenOverflow) {
BigNumObj bn(32);
BigNumObj bn_2(this->str_2);
BigNumObj bn_high_bit_set(this->str_32byte_high_bit_set);
EXPECT_EQ(kEpidBadArgErr, BigNumMul(bn_high_bit_set, bn_2, bn));
}
TEST_F(BigNumTest, MulWorksWith264BitValue) {
BigNumObj bn(33);
BigNumObj bn_2(this->str_2);
BigNumObj bn_high_bit_set(this->str_32byte_high_bit_set);
BigNumObj bn_33low(this->vec_33byte_low);
EXPECT_EQ(kEpidNoErr, BigNumMul(bn_high_bit_set, bn_2, bn));
EXPECT_TRUE(CompareBigNum(bn, bn_33low));
}
///////////////////////////////////////////////////////////////////////
// Division
TEST_F(BigNumTest, DivFailsGivenNullPointer) {
BigNumObj a, b, q, r;
EXPECT_EQ(kEpidBadArgErr, BigNumDiv(nullptr, b, q, r));
EXPECT_EQ(kEpidBadArgErr, BigNumDiv(a, nullptr, q, r));
EXPECT_EQ(kEpidBadArgErr, BigNumDiv(a, b, nullptr, r));
EXPECT_EQ(kEpidBadArgErr, BigNumDiv(a, b, q, nullptr));
}
TEST_F(BigNumTest, DivFailsGivenDivByZero) {
BigNumObj a;
BigNumObj zero(this->str_0);
BigNumObj q, r;
EXPECT_EQ(kEpidBadArgErr, BigNumDiv(a, zero, q, r));
}
TEST_F(BigNumTest, DivToOneKeepsOriginal) {
BigNumObj a(this->str_large);
BigNumObj zero(this->str_0);
BigNumObj one(this->str_1);
BigNumObj q, r;
EXPECT_EQ(kEpidNoErr, BigNumDiv(a, one, q, r));
EXPECT_TRUE(CompareBigNum(a, q));
EXPECT_TRUE(CompareBigNum(zero, r));
}
TEST_F(BigNumTest, DivToItselfIsIdentity) {
BigNumObj a(this->str_large);
BigNumObj zero(this->str_0);
BigNumObj one(this->str_1);
BigNumObj q, r;
EXPECT_EQ(kEpidNoErr, BigNumDiv(a, a, q, r));
EXPECT_TRUE(CompareBigNum(one, q));
EXPECT_TRUE(CompareBigNum(zero, r));
}
TEST_F(BigNumTest, DivOneByTwoIsZero) {
BigNumObj zero(this->str_0);
BigNumObj one(this->str_1);
BigNumObj two(this->str_2);
BigNumObj q, r;
EXPECT_EQ(kEpidNoErr, BigNumDiv(one, two, q, r));
EXPECT_TRUE(CompareBigNum(zero, q));
EXPECT_TRUE(CompareBigNum(one, r));
}
///////////////////////////////////////////////////////////////////////
// IsEven
TEST_F(BigNumTest, IsEvenFailsGivenNullPointer) {
BigNumObj zero(this->str_0);
bool r;
EXPECT_EQ(kEpidBadArgErr, BigNumIsEven(nullptr, &r));
EXPECT_EQ(kEpidBadArgErr, BigNumIsEven(zero, nullptr));
}
TEST_F(BigNumTest, IsEvenPassesEvenNumbers) {
BigNumObj zero(this->str_0);
BigNumObj two(this->str_2);
BigNumObj big(this->str_big);
bool r;
EXPECT_EQ(kEpidNoErr, BigNumMul(big, two, big));
EXPECT_EQ(kEpidNoErr, BigNumIsEven(zero, &r));
EXPECT_EQ(kEpidNoErr, BigNumIsEven(two, &r));
EXPECT_EQ(kEpidNoErr, BigNumIsEven(big, &r));
}
TEST_F(BigNumTest, IsEvenFailsOddNumbers) {
BigNumObj zero(this->str_0);
BigNumObj one(this->str_1);
BigNumObj two(this->str_2);
BigNumObj big(this->str_big);
bool r;
EXPECT_EQ(kEpidNoErr, BigNumMul(big, two, big));
EXPECT_EQ(kEpidNoErr, BigNumAdd(big, one, big));
EXPECT_EQ(kEpidNoErr, BigNumIsEven(one, &r));
EXPECT_EQ(kEpidNoErr, BigNumIsEven(big, &r));
}
///////////////////////////////////////////////////////////////////////
// IsZero
TEST_F(BigNumTest, IsZeroFailsGivenNullPointer) {
BigNumObj zero(this->str_0);
bool r;
EXPECT_EQ(kEpidBadArgErr, BigNumIsZero(nullptr, &r));
EXPECT_EQ(kEpidBadArgErr, BigNumIsZero(zero, nullptr));
}
TEST_F(BigNumTest, IsZeroPassesZero) {
BigNumObj zero(this->str_0);
bool r;
EXPECT_EQ(kEpidNoErr, BigNumIsZero(zero, &r));
}
TEST_F(BigNumTest, IsZeroFailsNonZero) {
BigNumObj one(this->str_1);
BigNumObj two(this->str_2);
BigNumObj big(this->str_big);
bool r;
EXPECT_EQ(kEpidNoErr, BigNumIsZero(one, &r));
EXPECT_EQ(kEpidNoErr, BigNumIsZero(two, &r));
EXPECT_EQ(kEpidNoErr, BigNumIsZero(big, &r));
}
///////////////////////////////////////////////////////////////////////
// Pow2N
TEST_F(BigNumTest, Pow2NFailsGivenNullPointer) {
EXPECT_EQ(kEpidBadArgErr, BigNumPow2N(1, nullptr));
}
TEST_F(BigNumTest, Pow2NZeroGivesOne) {
BigNumObj r;
BigNumObj one(this->str_1);
EXPECT_EQ(kEpidNoErr, BigNumPow2N(0, r));
EXPECT_TRUE(CompareBigNum(one, r));
}
TEST_F(BigNumTest, Pow2NOneGivesTwo) {
BigNumObj r;
BigNumObj two(this->str_2);
EXPECT_EQ(kEpidNoErr, BigNumPow2N(1, r));
EXPECT_TRUE(CompareBigNum(two, r));
}
TEST_F(BigNumTest, Pow2NGivesPow2n) {
unsigned int n = 2;
BigNumObj r;
BigNumObj two(this->str_2);
BigNumObj expect;
EXPECT_EQ(kEpidNoErr, BigNumMul(two, two, expect));
for (n = 2; n < 4; n++) {
EXPECT_EQ(kEpidNoErr, BigNumPow2N(n, r));
EXPECT_TRUE(CompareBigNum(expect, r));
EXPECT_EQ(kEpidNoErr, BigNumMul(expect, two, expect));
n++;
}
}
} // namespace
| 33.738318 | 80 | 0.681551 | [
"vector"
] |
5de64b2f967c6a3ecb96722e549459825d4818d4 | 70,478 | cpp | C++ | project/retinaFindings.cpp | janmacek/retinaDiseaseClasifier | 034e255f8f770aa9cb6b3c12688aedb60118da8d | [
"MIT"
] | null | null | null | project/retinaFindings.cpp | janmacek/retinaDiseaseClasifier | 034e255f8f770aa9cb6b3c12688aedb60118da8d | [
"MIT"
] | null | null | null | project/retinaFindings.cpp | janmacek/retinaDiseaseClasifier | 034e255f8f770aa9cb6b3c12688aedb60118da8d | [
"MIT"
] | 2 | 2019-05-31T06:13:56.000Z | 2020-01-21T08:19:05.000Z | //
// Created by janko on 8.5.2016.
//
#include <iostream>
#include <iomanip>
#include <fstream>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/ml/ml.hpp>
#include <cv.hpp>
#include <sys/stat.h>
#include<iostream>
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include <getopt.h>
#include "retinaFindings.h"
/* @brief Creates structuring element in shape of hexagon where object image points are set to 255 and others are set to 0.
* @param size is the length of one hexagon edge
* @return matrix of hexagonal element
*/
cv::Mat getHexagonalStructuringElement(int size) {
cv::Mat elem; elem = cv::Mat::zeros(size * 2 - 1, size * 3 - 2, CV_8UC1);
int oneCount = size, zeroCount = size - 1;
for(int row = 0; row < elem.rows; row++) {
uchar *imagePtr = elem.ptr(row);
for (int j = 0; j < elem.cols; ++j) {
if(j >= zeroCount && j < zeroCount + oneCount){
*imagePtr = 255;
} else {
*imagePtr = 0;
}
*imagePtr++;
}
if(row < size - 1){
zeroCount--;
oneCount+=2;
} else {
zeroCount++;
oneCount-=2;
}
}
return elem;
}
/* @brief Executes reconstruction of image by morfological operation while image before and after operation are not same.
* @param mask of skipped image points, its non-zero elements indicate which matrix elements need to be processed
* @param toReconstruct is matrix which is going to be processed
* @param structureElem is matrix element by which morfological operation is computed
* @param type of morfological operation: 0 = dilatation, other = erosion)
* @return reconstructed image
*/
cv::Mat morfologicalReconstruction(cv::Mat mask, cv::Mat toReconstruct, cv::Mat structureElem, int type) {
cv::Mat m0, m1 = toReconstruct.clone(), ne;
do {
m0 = m1.clone();
if(type == 0){
dilate(m0, m1, structureElem);
cv::min(m1, mask, m1);
} else {
erode(m0, m1, structureElem);
cv::max(m1, mask, m1);
}
cv::min(m1, mask, m1);
cv::compare(m1, m0, ne, cv::CMP_NE);
} while(cv::countNonZero(ne) != 0);
return m1;
}
/* @brief Filters contours by their area.
*/
void removeSmallAreaContours(std::vector<std::vector<cv::Point>> *contours, double minArea){
for(int i = 0; i < contours->size(); i++ ) {
if(cv::contourArea(contours->at(i)) < minArea){
contours->erase(contours->begin() + i--);
}
}
}
/* @brief Computes ratio of loaded image and images used to test functions.
* @param original are dimensions of loaded image
* @param pattern are default dimensions of test image
* @return double value of ratio
*/
double computeRatio(cv::Size original, cv::Size pattern = {480, 640}) {
return ((double)(original.height / pattern.height) + (double)(original.width / pattern.width)) / 2.0;
}
/* @brief Finds retina image background mask by local variance of image or by contours of image
* @param image to be processed
* @param method - allowed values are BG_MASK_BY_CONTOURS = 0, BG_MASK_BY_LOCAL_VARIANCE = 1
* @param reduction is optional parameter, define reduction of dimensions of foreground image
* @param ratio is optional parameter, if not specified, new is computed by image parameter
* @return matrix with same size as original image, zero element are background elements
*/
cv::Mat getBackgroundMask(cv::Mat image, int method, int reduction) {
if(method != BG_MASK_BY_CONTOURS && method != BG_MASK_BY_LOCAL_VARIANCE) {
throw std::invalid_argument("Invalid 'method' property value. Enabled only BG_MASK_BY_CONTOURS = 0, BG_MASK_BY_LOCAL_VARIANCE = 1.");
}
if(image.channels() == 3){
cvtColor(image, image, cv::COLOR_BGR2GRAY );
}
cv::Mat computedImage;
if( method == BG_MASK_BY_LOCAL_VARIANCE ) {
// compute variance of image
image.convertTo(image, CV_32F);
cv::Mat mu;
blur(image, mu, cv::Size(10, 10));
cv::Mat mu2;
blur(image.mul(image), mu2, cv::Size(10, 10));
cv::subtract(mu2, mu.mul(mu), image);
cv::sqrt(image, image);
cv::Mat thresh;
threshold(image, thresh, 10, 255, cv::THRESH_BINARY);
thresh.convertTo(computedImage, CV_8UC1);
} else if( method == BG_MASK_BY_CONTOURS){
// apply canny edge detector
cv::Mat canny;
Canny(image, canny, 20, 60);
// find the contours
std::vector<std::vector<cv::Point>> contours;
cv::findContours(canny, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
// draw contours to image, thickness depends on image size
cv::Mat result; result = cv::Mat::zeros(image.rows, image.cols, CV_8UC3);
for( size_t i = 0; i< contours.size(); i++ ) {
cv::drawContours( result, contours, (int)i, cv::Scalar(255,255,255), 10, 8);
}
cvtColor(result, computedImage, cv::COLOR_BGR2GRAY );
}
// find the largest contour of image, largest is object of retina
std::vector<std::vector<cv::Point>> contours;
cv::findContours(computedImage, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
int largestArea = 0;
int largestContourIndex = 0;
for( int i = 0; i< contours.size(); i++ ) {
//Find the area of contour
double areaIndex = contourArea(contours[i], false);
if(areaIndex > largestArea) {
largestArea = areaIndex;
largestContourIndex =i;
}
}
// fill contour and return it as black / white image
cv::Mat mask(image.rows, image.cols, CV_8UC1, cv::Scalar(0, 0, 0));
cv::drawContours(mask, contours, largestContourIndex, cv::Scalar(255, 255, 255), CV_FILLED, 8);
cv::Rect retinaRect = boundingRect(cv::Mat(contours[largestContourIndex]));
double ratio = computeRatio(retinaRect.size(), {660, 660});
cv::drawContours(mask, contours, largestContourIndex, cv::Scalar(0, 0, 0), (MASK_CONTOURS_LINE_THICKNESS + reduction) * ratio , 8);
return mask;
}
/* @brief Compute correction of shades at image.
* @param image to be processed
* @param ratio is optional parameter, if not specified, new is computed by image parameter
* @return matrix of shade corrected image
*/
cv::Mat shadeCorrection(cv::Mat image, double ratio) {
cv::Mat structure_elem;
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image.clone(), 0, 10);
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> retinaContour;
findContours(backgroundMask.clone(), retinaContour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Rect retinaRect = boundingRect(cv::Mat(retinaContour[0]));
ratio = computeRatio(retinaRect.size(), {660, 660});
}
if(image.channels() > 1) {
cv::cvtColor(image, image, CV_BGR2GRAY);
}
int maxStructureSize = 15 * ratio, structureSize = 1;
while(structureSize < maxStructureSize){
structure_elem = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(structureSize, structureSize));
//morphological opening
morphologyEx(image, image, cv::MORPH_OPEN, structure_elem);
//morphological closing
morphologyEx(image, image, cv::MORPH_CLOSE, structure_elem);
//double structure size
structureSize *= 2;
}
return image;
}
/* @brief Computes standard local variation of matrix of input image.
* @param image to be processed
* @param mask of skipped image points, its non-zero elements indicate which matrix elements need to be processed
* @param kernelSize define size of structuring element used for computing
* @param max contains coordinates of point with the highest value of local variation
* @return matrix of image local variation
*/
cv::Mat localVariation(cv::Mat image, cv::Mat mask, int kernelSize, cv::Point *max = nullptr) {
// convert input image to grayscale
if(mask.channels() == 3) {
cvtColor(mask, mask, CV_BGR2GRAY );
}
// make borders to input image and image mask, to handle out of image dimension values when processing
cv::Mat imageBorder;
copyMakeBorder(image, imageBorder, KERNEL_BRANCH_SIZE, KERNEL_BRANCH_SIZE, KERNEL_BRANCH_SIZE, KERNEL_BRANCH_SIZE, cv::BORDER_REFLECT);
cv::Mat maskBorder;
copyMakeBorder(mask, maskBorder, KERNEL_BRANCH_SIZE, KERNEL_BRANCH_SIZE, KERNEL_BRANCH_SIZE, KERNEL_BRANCH_SIZE, cv::BORDER_CONSTANT, 0);
// prepare matrix for result of local variation
cv::Mat localVariationImage;
localVariationImage = cv::Mat::ones(image.rows, image.cols, CV_8UC1);
double maxValue = 0;
// for each point of each row is local variation computed
for(int row = 0; row < (localVariationImage).rows; row++) {
// get lines of matrices
uchar *imagePtr = (localVariationImage).ptr(row);
uchar *maskPtr = (mask).ptr(row);
for (int col = 0; col < (localVariationImage).cols; col++) {
// if this point has non-zero value in mask
if(*maskPtr != 0){
// get kernel with actual point in the middle and predefined edge size
cv::Mat imageKernel = imageBorder(cv::Rect(col, row, kernelSize, kernelSize));
cv::Mat maskKernel = maskBorder(cv::Rect(col, row, kernelSize, kernelSize));
// get mean of kernel
cv::Scalar kernelMeanScalar, kernelStdDevScalar;
meanStdDev(imageKernel, kernelMeanScalar, kernelStdDevScalar);
// convert kernel to one channel image
cv::Mat imageKernelOneChannel;
imageKernel.convertTo(imageKernelOneChannel, CV_8UC1);
// subtract mean value of all elements in kernel matrix
subtract(imageKernelOneChannel, cv::Scalar(kernelMeanScalar[0]), imageKernelOneChannel);
// exponentiate all values in kernel matrix
pow(imageKernelOneChannel, 2, imageKernelOneChannel);
// remove/reset all masked values in kernel matrix
cv::Mat maskedImageKernel;
imageKernelOneChannel.copyTo(maskedImageKernel, maskKernel);
// compute local variation of pixel
double finalValue = (sum(maskedImageKernel)[0])/(pow(kernelSize, 2)-1.0);
*imagePtr = finalValue;
// recompute max value position
if(max != nullptr && maxValue < finalValue) {
*max = { col, row };
maxValue = finalValue;
}
}
*maskPtr++;
*imagePtr++;
}
}
return localVariationImage;
}
/* @brief Finds optic disc center by standard local variation.
* @param image to be processed
* @param subImageSize define size of sub-image, which is used for improving center position of optic disc by distance tranformation
* @param ratio is optional parameter, if not specified, new is computed by image parameter
* @return point which points to optic disc center
*/
cv::Point getOpticDiscCenter(cv::Mat image, int subImageSize, double ratio) {
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image.clone(), 0, 10);
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> retinaContour;
findContours(backgroundMask.clone(), retinaContour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Rect retinaRect = boundingRect(cv::Mat(retinaContour[0]));
ratio = computeRatio(retinaRect.size(), {660, 660});
}
// kernel width is computed as center point plus branch size twice, each side = left and right / top and bottom
int kernelSize = KERNEL_BRANCH_SIZE * 2 + 1;
// for localization of optic disc is the best option luminance channel
cv::Mat yuvImage, yuvChannels[3];
cvtColor(image, yuvImage, CV_BGR2YUV);
split(yuvImage, yuvChannels);
cv::Mat luminanceChannel = yuvChannels[0];
// remove small background variations by applying shade-correction operator
cv::Mat shadeCorrectedImage = shadeCorrection(luminanceChannel, ratio);
// get pixel with maximum value of local variation
cv::Point maxLocalVariationPosition;
cv::cvtColor(backgroundMask, backgroundMask, CV_GRAY2BGR);
localVariation(shadeCorrectedImage, backgroundMask, kernelSize, &maxLocalVariationPosition);
// cut out sub-image with optic disc centroid by local variation in its center
cv::Mat opticDiscSubImage = image(cv::Rect(maxLocalVariationPosition.x - (0.5 * subImageSize), maxLocalVariationPosition.y - (0.5 * subImageSize), subImageSize, subImageSize));
cv::cvtColor(opticDiscSubImage, opticDiscSubImage, CV_BGR2GRAY);
// compute 80% threshold of gray color optic disc sub-image
double min, max;
minMaxLoc(opticDiscSubImage, &min, &max);
threshold(opticDiscSubImage, opticDiscSubImage, max * 0.8, 255, cv::THRESH_BINARY );
// find biggest object of threshold sub-image
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours( opticDiscSubImage, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
int largestArea =0;
int largestContourIndex =0;
for( int i = 0; i< contours.size(); i++ ) {
// find the area of contour
double areaIndex = contourArea(contours[i], false);
if(areaIndex > largestArea) {
largestArea = areaIndex;
largestContourIndex = i;
}
}
// draw the biggest object using previously computed contour index
cv::Mat biggestTresholdParticle(opticDiscSubImage.rows, opticDiscSubImage.cols, CV_8UC1, cv::Scalar::all(0));
cv::drawContours(biggestTresholdParticle, contours, largestContourIndex, cv::Scalar(255,255,255), CV_FILLED, 8, hierarchy );
// find real optic disc center as max of largest object in distance transformation of threshold image
cv::Mat distanceImage;
cv::distanceTransform(biggestTresholdParticle, distanceImage, CV_DIST_L2, 3);
//normalize(distanceImage, distanceImage, 0, 1., cv::NORM_MINMAX);
cv::Point min_loc, max_loc;
minMaxLoc(distanceImage, &min, &max, &min_loc, &max_loc);
// normalize max point sub-image coordinates to coordinates of entire image
return {max_loc.x + maxLocalVariationPosition.x, max_loc.y + maxLocalVariationPosition.y};
}
/* @brief Finds optic disc contours by watershed transformation.
* @param image to be processed
* @param ratio is optional parameter, if not specified, new is computed by image parameter
* @return vector of contours ( vector of points ) of optic disc
*/
std::vector<std::vector<cv::Point>> getOpticDiscContours(cv::Mat image, double ratio) {
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image.clone(), 0, 10);
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> retinaContour;
findContours(backgroundMask.clone(), retinaContour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Rect retinaRect = boundingRect(cv::Mat(retinaContour[0]));
ratio = computeRatio(retinaRect.size(), {660, 660});
}
// sub-image where optic disc can be find is triple size of optic disc size based on literature, because center find by us can be on the border of optic disc
int subImageSize = (DEFAULT_OPTIC_DISC_SIZE * ratio) * 3;
cv::Point opticDiscCenter = getOpticDiscCenter(image, subImageSize, ratio);
cv::Mat opticDiscSubImage = image(cv::Rect(opticDiscCenter.x - subImageSize, opticDiscCenter.y - subImageSize, subImageSize, subImageSize));
// red channel is the best of channels to find contours of optic disc
std::vector<cv::Mat> bgrChannel;
split(opticDiscSubImage, bgrChannel);
cv::Mat redChannel = (bgrChannel[2]);
cv::normalize(redChannel, redChannel, 0, 255, cv::NORM_MINMAX);
// fill the vessels, applying a simple closing
cv::Mat structureElem = getHexagonalStructuringElement(S1 * ratio);
cv::Mat closedRedChannel;
morphologyEx(redChannel, closedRedChannel, cv::MORPH_CLOSE, structureElem);
// in order to remove large peaks, we open with a large structuring element
structureElem = getHexagonalStructuringElement(S2 * ratio);
cv::Mat openRedChannel;
morphologyEx(closedRedChannel, openRedChannel, cv::MORPH_OPEN, structureElem);
// compute morfological reconstruction of closed red channel by opened red channel;
cv::Mat morfRedChannel = morfologicalReconstruction(closedRedChannel, openRedChannel, structureElem, 0);
// create markers image to prevent over-segmentation in watershed transformation
cv::Mat markers(morfRedChannel.size(),CV_8U,cv::Scalar(-1));
cv::circle(markers, cv::Point(morfRedChannel.rows/2, morfRedChannel.cols/2), redChannel.rows/2, cv::Scalar::all(1), 1);
cv::circle(markers, cv::Point(morfRedChannel.rows/2, morfRedChannel.cols/2), 1, cv::Scalar::all(2), 1);
markers.convertTo(markers, CV_32S);
// to find contours, process watershed transformation and threshold of its result
cvtColor(morfRedChannel, morfRedChannel, CV_GRAY2RGB);
cv::watershed(morfRedChannel, markers);
cv::Mat mask;
convertScaleAbs(markers, mask, 1, 0);
threshold(mask, mask, 1, 255, cv::THRESH_BINARY);
double top = opticDiscCenter.x - subImageSize;
double left = opticDiscCenter.y - subImageSize;
copyMakeBorder(mask, mask, left, image.cols - left, top, image.rows - top,0);
// find the contours
std::vector<std::vector<cv::Point>> contours;
findContours(mask, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
return contours;
}
/* @brief Creates mask of optic disc.
* @param image to be processed
* @param reduction is optional parameter, define reduction of dimensions of foreground image
* @param ratio is optional parameter, if not specified, new is computed by image parameter
* @return matrix with same size as original image, zero element are optic disc elements
*/
cv::Mat getOpticDiscMask(cv::Mat image, int reduction, double ratio) {
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image.clone(), 0, 10);
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> retinaContour;
findContours(backgroundMask.clone(), retinaContour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Rect retinaRect = boundingRect(cv::Mat(retinaContour[0]));
ratio = computeRatio(retinaRect.size(), {660, 660});
}
std::vector<std::vector<cv::Point>> contours = getOpticDiscContours(image, ratio);
cv::Mat mask(image.rows, image.cols, CV_8UC1, cv::Scalar(255, 255, 255));
for(size_t i = 0; i< contours.size(); i++ ) {
drawContours(mask, contours, (int)i, cv::Scalar(0, 0, 0), (2 + reduction) * ratio, 1);
}
bitwise_not(mask, mask);
floodFill(mask, cv::Point(5, 5), CV_RGB(255, 255, 255));
return mask;
}
/* @brief Computes histogram equalization of intensity channel.
* @param image to be processed
* @return image with equalized intensity
*/
cv::Mat equalizeIntensity(cv::Mat image) {
cv::Mat ycrcbImage;
cvtColor(image, ycrcbImage, CV_BGR2YCrCb);
std::vector<cv::Mat> ycrcbChannels;
split(ycrcbImage, ycrcbChannels);
equalizeHist(ycrcbChannels[0], ycrcbChannels[0]);
cv::Mat result;
merge(ycrcbChannels, ycrcbImage);
cvtColor(ycrcbImage, result, CV_YCrCb2BGR);
return result;
}
/* @brief Computes adaptive histogram equalization of color image.
* @param image to be processed
* @param clipLimit is threshold for contrast limiting
* @param tileGridSize is size of grid for histogram equalization
*/
cv::Mat clahe(cv::Mat image, double clipLimit, cv::Size tileGridSize) {
cv::Mat lab_image;
cv::cvtColor(image, lab_image, CV_BGR2Lab);
// Extract the L channel
std::vector<cv::Mat> lab_planes(3);
// now we have the L image in lab_planes[0]
cv::split(lab_image, lab_planes);
// apply the CLAHE algorithm to the L channel
cv::Ptr<cv::CLAHE> clahe = cv::createCLAHE(clipLimit, tileGridSize);
cv::Mat dst;
clahe->apply(lab_planes[0], dst);
// Merge the the color planes back into an Lab image
dst.copyTo(lab_planes[0]);
cv::merge(lab_planes, lab_image);
// convert back to BGR color color
cv::Mat image_clahe;
cv::cvtColor(lab_image, image_clahe, CV_Lab2BGR);
return image_clahe;
}
/* @brief Generates Gabor filter imaginary coefficients.
* @param ksize is size of the filter returned
* @param sigma is tandard deviation of the gaussian envelope
* @param theta is orientation of the normal to the parallel stripes of a Gabor function
* @param lambda is wavelength of the sinusoidal factor
* @param gamma is spatial aspect ratio
* @param psi is phase offset
* @param ktype is type of filter coefficients. It can be CV_32F or CV_64F
* @return generated matrix of gabor kernel
*/
cv::Mat getGaborKernelImaginary(cv::Size ksize, double sigma, double theta, double lambda, double gamma, double psi, int ktype) {
double sigma_x = sigma;
double sigma_y = sigma/gamma;
int nstds = 3;
int xmin, xmax, ymin, ymax;
double c = cos(theta), s = sin(theta);
if( ksize.width > 0 ) {
xmax = ksize.width / 2;
} else {
xmax = cvRound(std::max(fabs(nstds * sigma_x * c), fabs(nstds * sigma_y * s)));
}
if( ksize.height > 0 ) {
ymax = ksize.height/2;
} else {
ymax = cvRound(std::max(fabs(nstds * sigma_x * s), fabs(nstds * sigma_y * c)));
}
xmin = -xmax;
ymin = -ymax;
CV_Assert( ktype == CV_32F || ktype == CV_64F );
cv::Mat kernel(ymax - ymin + 1, xmax - xmin + 1, ktype);
double scale = 1;
double ex = -0.5/(sigma_x*sigma_x);
double ey = -0.5/(sigma_y*sigma_y);
double cscale = CV_PI*2/lambda;
for( int y = ymin; y <= ymax; y++ ) {
for (int x = xmin; x <= xmax; x++) {
double xr = x * c + y * s;
double yr = -x * s + y * c;
double v = scale * std::exp(ex * xr * xr + ey * yr * yr) * (cos(cscale * xr + psi));
if (ktype == CV_32F)
kernel.at<float>(ymax - y, xmax - x) = (float) v;
else
kernel.at<double>(ymax - y, xmax - x) = v;
}
}
return kernel;
}
/* @brief Finds exudates contours in retina image.
* @param image to be processed
* @param opticDiscMask is mask of pixels where is optic disc, if it is empty ( all elemets of matrix are zeros), new one is computed in image
* @param ratio is optional parameter, if not specified, new is computed by image parameter
* @return vector of contours ( vector of points ) of exudates
*/
std::vector<std::vector<cv::Point>> getExudatesContours(cv::Mat image, cv::Mat opticDiscMask, double ratio) {
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image.clone(), 0, 10);
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> retinaContour;
findContours(backgroundMask.clone(), retinaContour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Rect retinaRect = boundingRect(cv::Mat(retinaContour[0]));
ratio = computeRatio(retinaRect.size(), {660, 660});
}
if(opticDiscMask.empty()){
cv::Mat structureElem = cv::getStructuringElement(CV_SHAPE_RECT, cv::Size(10 * ratio, 10 * ratio));
opticDiscMask = getOpticDiscMask(image, 0, ratio);
erode(opticDiscMask, opticDiscMask, structureElem);
}
// exudates appear most contrasted in green channel
std::vector<cv::Mat> bgrChannel;
split(image, bgrChannel);
cv::Mat greenChannel = bgrChannel[1];
// eliminate the vessels by a morfological closing, S1 is maximal width of blood vessel
cv::Mat structureElem = getStructuringElement(CV_SHAPE_RECT, cv::Size(S1 * ratio, S1 * ratio)), morfGreenChannel;
morphologyEx(greenChannel, morfGreenChannel, cv::MORPH_CLOSE, structureElem);
// calculate the local variation for each pixel
int kernelSize = KERNEL_BRANCH_SIZE * 2 + 1;
cv::Mat localVariationImage = localVariation(morfGreenChannel, backgroundMask, kernelSize);
normalize(localVariationImage, localVariationImage, 0, 255, cv::NORM_MINMAX, CV_8UC1);
// thresholding local varion image to extract candidate region, A1 is chosen in a very tolerant manner
int A1 = 10;
threshold(localVariationImage, localVariationImage, A1, 255, cv::THRESH_BINARY );
// fill inner areas of candidate regions
cv::Mat filled; filled = localVariationImage.clone();
floodFill(filled, cv::Point(0, 0), 255);
bitwise_not(filled, filled);
bitwise_or(filled, localVariationImage, filled);
// merge mask of optic disc and background mask
cv::Mat mask; mask = cv::Mat::ones(image.rows, image.cols, CV_8UC1);
bitwise_and(opticDiscMask, backgroundMask, mask);
// remove the candidate region that results from the optic disc or are in background
cv::Mat candidateRegions; candidateRegions = cv::Mat::ones(image.rows, image.cols, CV_8UC1);
filled.copyTo(candidateRegions, mask);
// set all the candidate regions to 0 in the original image
cv::Mat e6; e6 = cv::Mat::ones(image.rows, image.cols, CV_8UC1);
bitwise_not(candidateRegions,candidateRegions);
greenChannel.copyTo(e6, candidateRegions);
// calculate the morphological reconstruction by dilation
cv::Mat e7 = morfologicalReconstruction(greenChannel, e6, structureElem, 0);
// apply a simple threshold operation to the difference between the original image and the reconstructed image
cv::Mat efin;
subtract(greenChannel, e7, efin);
int A2 = 5;
threshold( efin, efin, A2, 255, cv::THRESH_BINARY );
// find the contours in final image
std::vector<std::vector<cv::Point>> contours;
findContours(efin, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
removeSmallAreaContours(&contours, ratio * MIN_FINDING_AREA);
return contours;
}
/* @brief Finds contours of drusen in image of retina.
* @param image to be processed
* @param ratio is optional parameter, if not specified, new is computed by image parameter
* @return vector of contours ( vector of points ) of drusen
*/
std::vector<std::vector<cv::Point>> getDrusenContours(cv::Mat image, double ratio) {
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image.clone(), 0, 10);
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> retinaContour;
findContours(backgroundMask.clone(), retinaContour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Rect retinaRect = boundingRect(cv::Mat(retinaContour[0]));
ratio = computeRatio(retinaRect.size(), {660, 660});
}
// suppress dark regions by application of morphological closing
cv::Mat structureElem = cv::getStructuringElement(CV_SHAPE_ELLIPSE, cv::Size(35, 35));
cv::Mat preprocessedImage;
morphologyEx(image, preprocessedImage, cv::MORPH_CLOSE, structureElem);
//improve the contrast by adaptive histogram equalization
preprocessedImage = clahe(preprocessedImage, 1, {20, 20});
cv::cvtColor(preprocessedImage, preprocessedImage, CV_BGR2GRAY);
// merge responses of chosen gabor filters
cv::Mat responses;
responses = cv::Mat::zeros(image.rows, image.cols, CV_32F);
for (int j = 0; j < GABOR_FILTER_BANK.size(); ++j) {
for (int i = 0; i < 360; i += 45) {
// create gabor kernel and get response of filter
auto gaborKernel = getGaborKernelImaginary(
cv::Size(GABOR_FILTER_BANK[j][5], GABOR_FILTER_BANK[j][5]),
GABOR_FILTER_BANK[j][0],
GABOR_FILTER_BANK[j][1] + i / 180. * M_PI,
GABOR_FILTER_BANK[j][2],
GABOR_FILTER_BANK[j][3],
GABOR_FILTER_BANK[j][4]);
cv::Mat filterResponse;
cv::filter2D(preprocessedImage, filterResponse, CV_32F, gaborKernel);
// get maximum of filter response by applying adaptive threshold
filterResponse.convertTo(filterResponse, CV_8UC1, 1.0 / 255.0);
adaptiveThreshold(filterResponse, filterResponse, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY,
31, 0);
// join result to other responses
filterResponse.convertTo(filterResponse, CV_32F);
responses += filterResponse;
}
}
cv::normalize(responses, responses, 0, 255, cv::NORM_MINMAX);
responses.convertTo(responses, CV_8U);
// get candidate regions as dilated maximum of responses of gabor filter
cv::Mat candidateRegions(image.size(), CV_8UC1, cv::Scalar(255));
threshold(responses, candidateRegions, 50, 255, cv::THRESH_BINARY);
structureElem = cv::getStructuringElement(CV_SHAPE_ELLIPSE, cv::Size(20, 20));
dilate(candidateRegions, candidateRegions, structureElem);
// from candidate regions are removed regions of optic disc and regions outside of retina (in background)
cv::Mat trueCandidateRegions(image.rows, image.cols, CV_8UC1, cv::Scalar(0, 0, 0));
cv::Mat opticDiscMask = getOpticDiscMask(image, 5, ratio);
cv::Mat mask;
cv::bitwise_and(opticDiscMask, backgroundMask, mask);
candidateRegions.copyTo(trueCandidateRegions, mask);
// to find contours fill candidate regions in original image by black color and thet compute morfological reconstruction
cv::Mat imageWithCandidateDeleted(image.size(), CV_8UC3, cv::Scalar(0,0,0));
imageWithCandidateDeleted = cv::Mat::ones(image.size(), CV_8UC1);
cv::bitwise_not(trueCandidateRegions, trueCandidateRegions);
image.copyTo(imageWithCandidateDeleted, trueCandidateRegions);
cv::Mat imageGray;
cvtColor(image, imageGray, cv::COLOR_BGR2GRAY);
cvtColor(imageWithCandidateDeleted, imageWithCandidateDeleted, cv::COLOR_BGR2GRAY);
cv::Mat reconstructed = morfologicalReconstruction(imageGray, imageWithCandidateDeleted, structureElem, 0);
// get difference of original and reconstructed image, use threshold filter to get true druse regions and find contours of these regions
cv::Mat drusen;
subtract(imageGray, reconstructed, drusen);
int A2 = 5;
threshold(drusen, drusen, A2, 255, cv::THRESH_BINARY);
std::vector<std::vector<cv::Point>> contours;
findContours(drusen, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
removeSmallAreaContours(&contours, ratio * MIN_FINDING_AREA);
return contours;
}
/* @brief Computes entropy of image by histogram equalization.
* @param image to be processed
* @param histMax is maximum value of histogram
* @param mask of skipped image points, its non-zero elements indicate which matrix elements need to be processed
* @return entropy of image
*/
float computeEntropy(cv::Mat image, int histMax, cv::Mat mask) {
// calculate relative occurrence of different symbols within given input sequence using histogram
float range[] = { 0, 256 } ;
const float* histRange = { range };
bool uniform = true; bool accumulate = false;
cv::Mat hist;
// compute the histograms
calcHist(&image, 1, 0, mask, hist, 1, &histMax, &histRange, uniform, accumulate );
int cnt = 0;
float entropy = 0;
// total size of all symbols in an image
float total_size = image.size().height * image.size().width;
for(int i=0; i < histMax; i++) {
// the number of times a symbol has occurred
float sym_occur = hist.at<float>(0, i);
// log of zero goes to infinity
if(sym_occur > 0) {
cnt++;
entropy += (sym_occur/total_size)*(log2(total_size/sym_occur));
}
}
return entropy;
}
/* @brief Finds index of contour in which the point is.
* @param contours is pointer to array of elements contours
* @param dimensions are width and height of image from which contours are
* @param position is point in image, if out of contours
* @return index of contour in array of all contoursor -1 if point is not in any of them
*/
int inContours(std::vector<std::vector<cv::Point>> *contours, cv::Size dimensions, cv::Point position) {
for (int i = 0; i < (*contours).size(); ++i) {
cv::Mat druseImage(dimensions, CV_8UC1, cv::Scalar(0));
drawContours( druseImage, (*contours), i, cv::Scalar(255, 255, 255), CV_FILLED, 8);
if((int) druseImage.at<uchar>(position.x, position.y) == 255){
return i;
}
}
return -1;
}
/* @brief Handles user inputs while learning process is active.
* @param event is type of event, i.e. EVENT_LBUTTONDOWN, EVENT_RBUTTONDOWN ...
* @param x position in image
* @param y position in image
* @param data is pointer to structure which contain parameters of function, must be of CallBackParams type
*/
void classificationCallBackFunc(int event, int x, int y, int, void *data) {
// selection of true positive findings
if ( event == cv::EVENT_LBUTTONDOWN || event == cv::EVENT_RBUTTONDOWN ) {
CallBackParams *params = (CallBackParams *) data;
auto contourIndex = inContours(&(*params).contours, (*params).image.size(), {y, x});
// if any contour was selected
if(contourIndex > -1) {
// add or remove clicked contour to array
std::vector<int>::iterator positiveIt = std::find((*params).positive.begin(), (*params).positive.end(), contourIndex);
std::vector<int>::iterator negativeIt = std::find((*params).negative.begin(), (*params).negative.end(), contourIndex);
if(positiveIt != (*params).positive.end() && event == cv::EVENT_LBUTTONDOWN) {
(*params).positive.erase(positiveIt);
} else if(negativeIt != (*params).negative.end() && event == cv::EVENT_RBUTTONDOWN) {
(*params).negative.erase(negativeIt);
} else if(positiveIt != (*params).positive.end() && event == cv::EVENT_RBUTTONDOWN) {
(*params).positive.erase(positiveIt);
(*params).negative.push_back(contourIndex);
} else if(negativeIt != (*params).negative.end() && event == cv::EVENT_LBUTTONDOWN) {
(*params).negative.erase(negativeIt);
(*params).positive.push_back(contourIndex);
} else if(event == cv::EVENT_LBUTTONDOWN) {
(*params).positive.push_back(contourIndex);
} else {
(*params).negative.push_back(contourIndex);
}
// highlight selected contours in image
cv::Mat image, filter((*params).image.size(), CV_8UC3, cv::Scalar(0, 0, 0));
(*params).image.copyTo(image);
for (int i = 0; i < (*params).positive.size(); ++i) {
drawContours(image, (*params).contours, (*params).positive[i], cv::Scalar(53, 232, 61), 1, 8);
drawContours(filter, (*params).contours, (*params).positive[i], cv::Scalar(-50, 50, -50), CV_FILLED, 8);
}
for (int i = 0; i < (*params).negative.size(); ++i) {
drawContours(image, (*params).contours, (*params).negative[i], cv::Scalar(66, 41, 255), 2, 8);
drawContours(filter, (*params).contours, (*params).negative[i], cv::Scalar(-50, -50, 50), CV_FILLED, 8);
}
cv::add(image, filter, image);
cv::imshow((*params).windowName, image);
cv::waitKey(1);
}
}
}
/* @brief Computes features of bright object in image (druse or exudate)
* @param contours is pointer to array of elements contours
* @param image, in which contours were found
* @param index of contour in array
* @return [area, compactness, average boundary intensity, maximum value of boundary intensity,
* mean hue, mean saturation, mean intensity, mean gradient magnitude, energy, entropy, ratio]
*/
std::vector<double> getBrightObjectFeature(std::vector<std::vector<cv::Point>> contours, cv::Mat *image, int index, double ratio) {
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image->clone(), 0, 10);
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> retinaContour;
findContours(backgroundMask.clone(), retinaContour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Rect retinaRect = boundingRect(cv::Mat(retinaContour[0]));
ratio = computeRatio(retinaRect.size(), {660, 660});
}
// because of energy computing we image with all contours filled
cv::Mat contoursMask(image->size(), CV_8UC1, cv::Scalar(0, 0, 0));
for (int i = 0; i < contours.size(); i++) {
drawContours(contoursMask, contours, i, cv::Scalar(255, 255, 255), CV_FILLED, 8);
}
cv::Mat elementMask, elementContoursMask, elementImage, elementContoursImage;
elementMask = cv::Mat::zeros(image->size(), CV_8UC1);
elementContoursMask = cv::Mat::zeros(image->size(), CV_8UC1);
elementImage = cv::Mat::zeros(image->size(), CV_8UC1);
elementContoursImage = cv::Mat::zeros(image->size(), CV_8UC1);
// compute sum of all pixels in element
cv::drawContours(elementMask, contours, index, cv::Scalar(255), CV_FILLED, 8);
image->copyTo(elementImage, elementMask);
double area = cv::sum(elementImage)[0];
// compute compactness of element
double compactness = pow(cv::arcLength(contours[index], true), 2) / ( 4 * CV_PI * area );
//compute average boundary intensity
drawContours(elementContoursMask, contours, index, cv::Scalar(255), 1, 8);
cv::Mat intensity;
cv::cvtColor(*image, intensity, CV_BGR2GRAY);
intensity.copyTo(elementContoursImage, elementContoursMask);
double avgBoundaryIntensity = cv::mean(elementImage)[0];
// compute maximum and minimum boundary intensity
double maxBoundaryIntensity, minBoundaryIntensity;
cv::minMaxLoc(elementContoursImage, &minBoundaryIntensity, &maxBoundaryIntensity);
// compute mean hue, saturation and intensity of element
cv::Mat druseHSV, druseIntensity, druseHSVChannels[3];
cv::cvtColor(elementImage, druseHSV, CV_BGR2HSV);
cv::split(druseHSV, druseHSVChannels);
intensity.copyTo(druseIntensity, elementMask);
double meanHue = cv::mean(druseHSVChannels[0], elementMask)[0];
double meanSaturation = cv::mean(druseHSVChannels[0], elementMask)[0];
double meanIntensity = cv::mean(druseIntensity, elementMask)[0];
// compute mean gradient magnitude
cv::Mat grad_x, grad_y, abs_grad_x, abs_grad_y, grad;
// gradient X & Y
Sobel(druseIntensity, grad_x, CV_16S, 1, 0, 3, 1, 0, cv::BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
Sobel(druseIntensity, grad_y, CV_16S, 0, 1, 3, 1, 0, cv::BORDER_DEFAULT);
convertScaleAbs(grad_y, abs_grad_y);
addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
double meanGradientMagnitude = cv::mean(grad, elementMask)[0];
// compute energy of candidate region
double energy = cv::sum(druseIntensity)[0] / cv::sum(contoursMask)[0];
// compute entropy = measure of randomness
int histMax = 256;
double entropy = computeEntropy(intensity, histMax, elementMask);
return { area, compactness, avgBoundaryIntensity, maxBoundaryIntensity, meanHue,
meanSaturation, meanIntensity, meanGradientMagnitude, energy, entropy, ratio};
}
/* @brief Computes first eccentricity of ellipse.
* @param rectangle which describes ellipse
* @return double value of eccentricity
*/
double getEccentricity(cv::RotatedRect rectangle) {
if(rectangle.size.height > rectangle.size.width) {
return (double) (std::sqrt((std::pow(rectangle.size.height, 2) - std::pow(rectangle.size.width, 2))) / (rectangle.size.height));
} else {
return (double) (std::sqrt((std::pow(rectangle.size.width, 2) - std::pow(rectangle.size.height, 2))) / (rectangle.size.width));
}
}
/* @brief Finds ellipse, which describes macula in retina.
* @param image to be processed
* @param ratio is optional parameter, if not specified, new is computed by image parameter
* @return rotated rectangle which describe macula ellipse or zero-sized rectangle if no macula is found
*/
cv::RotatedRect getMaculaEllipse(cv::Mat image, double ratio) {
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image.clone(), 0, 10);
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> retinaContour;
findContours(backgroundMask.clone(), retinaContour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Rect retinaRect = boundingRect(cv::Mat(retinaContour[0]));
ratio = computeRatio(retinaRect.size(), {660, 660});
}
// macula appears most contrasted in red channel
std::vector<cv::Mat> bgrChannel;
split(image, bgrChannel);
cv::Mat redChannel = bgrChannel[2];
// remove noise details by applying blur filter
int size = ((int) (30 * ratio) | 1);
cv::blur(redChannel, redChannel, {size, size});
// do multilevel thresholding, macula appears most between value 100 - 230
std::vector<cv::RotatedRect> minEllipse;
for (int k = 100; k < 230; ++k) {
cv::Mat threshold_output;
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
// detect edges using Threshold
threshold(redChannel, threshold_output, k, 255, cv::THRESH_BINARY);
// to exclude ellipses of whole retina,flood fill background
cv::floodFill(threshold_output, {0, 0}, 255);
// find contours
findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
// for each contour find rotated rectangles and ellipses
for (int i = 0; i < contours.size(); i++) {
if (contours[i].size() > 5) {
cv::RotatedRect elem = fitEllipse(cv::Mat(contours[i]));
// check if they are ellipses and not circles by eccentricity value
if (getEccentricity(elem) > MAX_MACULA_ECCENTRICITY) {
minEllipse.push_back(elem);
}
}
}
}
if (minEllipse.size() > 0) {
// collect ellipse to group with similar centroid
std::vector<cv::Point2f> centers = {minEllipse[0].center};
std::vector<int> belong(minEllipse.size(), 0);
int iteration = 0;
bool change;
do {
change = false;
for (int i = 0; i < minEllipse.size(); i++) {
// search for the nearest group
int best = belong[i];
double bestDistance = cv::norm(minEllipse[i].center - centers[best]);
for (int j = 0; j < centers.size(); ++j) {
auto dist = cv::norm(minEllipse[i].center - centers[j]);
if (dist < bestDistance) {
bestDistance = dist;
best = j;
change = true;
}
}
// if is centroid of nearest group still too far away, create new group with this poin
if (cv::norm(minEllipse[i].center - centers[best]) > (ratio * MAX_CLUSTERING_DISTANCE)) {
centers.push_back(minEllipse[i].center);
belong[i] = centers.size() - 1;
} else {
belong[i] = best;
}
}
// get members of each group
std::vector<std::vector<cv::Point2f>> members(belong.size());
for (int l = 0; l < belong.size(); ++l) {
members[belong[l]].push_back(minEllipse[l].center);
}
// for each group re-calculate its centroid
for (int k = 0; k < centers.size(); ++k) {
centers[k] = {0, 0};
for (int i = 0; i < members[k].size(); i++) {
centers[k] += members[k][i];
}
centers[k].x /= members[k].size();
centers[k].y /= members[k].size();
}
} while (change && iteration++ < MAX_CLUSTERING_ITERATIONS);
// get ellipses of each final group and the most numerous group
std::vector<std::vector<cv::RotatedRect>> members(belong.size());
int max = 0;
for (int l = 0; l < belong.size(); ++l) {
members[belong[l]].push_back(minEllipse[l]);
if (members[belong[l]].size() > members[max].size()) {
max = belong[l];
}
}
// find the largest ellipse in the most numerous group
int largest = 0;
for (int i = 0; i < members[max].size(); i++) {
if (members[max][i].size.area() > members[max][largest].size.area()) { largest = i; }
}
return members[max][largest];
} else {
return cv::RotatedRect();
}
}
/* @brief Creates mask of macula.
* @param image to be processed
* @param reduction is optional parameter, define reduction of dimensions of foreground image
* @param ratio is optional parameter, if not specified, new is computed by image parameter
* @return matrix with same size as original image, zero element are macula elements
*/
cv::Mat getMaculaMask(cv::Mat image, int reduction, double ratio) {
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image.clone(), 0, 10);
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> retinaContour;
findContours(backgroundMask.clone(), retinaContour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Rect retinaRect = boundingRect(cv::Mat(retinaContour[0]));
ratio = computeRatio(retinaRect.size(), {660, 660});
}
cv::RotatedRect macula = getMaculaEllipse(image, ratio);
cv::Mat mask(image.rows, image.cols, CV_8UC1, cv::Scalar(255, 255, 255));
cv::ellipse( mask, macula, cv::Scalar(0, 0, 0), CV_FILLED, 8 );
if(reduction > 0) {
cv::ellipse( mask, macula, cv::Scalar(0, 0, 0), reduction, 8 );
}
return mask;
}
/* @brief Creates mask of blood vessels in retina image. Gabor filter is used.
* @param image to be processed
* @param opticDiscMask is mask in which zero elements are optic disc elements, if empty == cv::Mat(), new is computed by image
* @param ratio is optional parameter, if not specified, new is computed by image
* @return matrix with same size as original image, zero element are blood vessels elements
*/
cv::Mat getBloodVesselsMask(cv::Mat image, cv::Mat opticDiscMask, double ratio) {
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image.clone(), 0, 10);
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> retinaContour;
findContours(backgroundMask.clone(), retinaContour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Rect retinaRect = boundingRect(cv::Mat(retinaContour[0]));
ratio = computeRatio(retinaRect.size(), {660, 660});
}
// blood vessels appears most contrasted in inverted green channel
std::vector<cv::Mat> bgrChannel;
split(image, bgrChannel);
cv::Mat greenChannel = bgrChannel[1];
cv::subtract(cv::Scalar::all(255), greenChannel, greenChannel);
cv::Mat structureElem = getStructuringElement(CV_SHAPE_ELLIPSE, cv::Size(15 * ratio, 15 * ratio)), morfGreenChannel;
morphologyEx(greenChannel, greenChannel, cv::MORPH_CLOSE, structureElem);
cv::Mat greenChannel32F;
greenChannel32F = cv::Mat::zeros(greenChannel.rows, greenChannel.cols, CV_32FC1);
greenChannel.convertTo(greenChannel32F, CV_32F, 1.0 / 255, 0);
cv::Mat gaborFilterResponse;
gaborFilterResponse = cv::Mat::zeros(image.rows, image.cols, CV_8UC1);
// rotate gabor kernel to find vessels in all angles
for (int i = 0; i < 180; i += 30) {
//ratio = 1;
// compute width and height of kernel, i.e.: "|" shape is smaller width and bigger height and for "__" vice versa
int size = 17 * ratio, kernelWidth = size, kernelHeight = size;
double divisor = 30 / ratio;
if(i <= 90){
kernelHeight -= i / divisor;
kernelWidth -= 3 * ratio - (i / divisor);
} else {
kernelWidth -= (i % 90) / divisor;
kernelHeight -= 3 * ratio - ((i % 90) / divisor);
}
cv::Mat kernel = cv::getGaborKernel({kernelWidth, kernelHeight}, 4.5 * ratio, i / 180. * M_PI, 9.9 * ratio, 1.3, CV_PI * 2);
cv::Mat response;
// proceed 2D filter of image by generated gabor kernel
cv::filter2D(greenChannel32F, response, CV_32F, kernel);
response.convertTo(response, CV_8U, 255);
// add actual gabor filter result to total
addWeighted( gaborFilterResponse, 0.5, response, 0.5, 0.0, gaborFilterResponse);
}
cv::Mat gaborThresh;
threshold(gaborFilterResponse, gaborThresh, 5, 255, cv::THRESH_BINARY_INV);
// find center of optic disc
if(opticDiscMask.empty()){
opticDiscMask = getOpticDiscMask(image, 5, ratio);
}
cv::Mat mask, vessels;
bitwise_and(gaborThresh, opticDiscMask, mask);
cv::Mat distanceMask;
bitwise_not(mask, distanceMask);
distanceTransform(distanceMask, distanceMask, CV_DIST_L2, 3);
double min, max;
cv::Point min_loc, max_loc;
cv::minMaxLoc(distanceMask, &min, &max, &min_loc, &max_loc);
normalize(mask, vessels, 0, 50, cv::NORM_MINMAX);
// use just those lines / objects, which goes from the optic disc
floodFill(vessels, max_loc, 255);
threshold(vessels, vessels, 254, 255, cv::THRESH_BINARY_INV);
bitwise_or(gaborThresh, vessels, vessels);
// remove optic disc from mask
bitwise_and(vessels, backgroundMask, vessels);
return vessels;
}
/* @brief Finds contours of blood vessels in retina image. Local variation and morfological reconstruction are used.
* @param image to be processed
* @param ratio is optional parameter, if not specified, new is computed by image
* @return vector of contours ( vector of points ) of hemorrhages
*/
std::vector<std::vector<cv::Point>> getHemorrhagesContours(cv::Mat image, double ratio) {
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image.clone(), 0, 10);
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> retinaContour;
findContours(backgroundMask.clone(), retinaContour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Rect retinaRect = boundingRect(cv::Mat(retinaContour[0]));
ratio = computeRatio(retinaRect.size(), {660, 660});
}
// hemorrhages appears most contrasted in inverted green channel
std::vector<cv::Mat> bgrChannel;
split(image, bgrChannel);
cv::Mat greenChannel = bgrChannel[1];
// make background color value as mean color of retina
int meanColor = mean(greenChannel, backgroundMask)[0];
bitwise_not(backgroundMask, backgroundMask);
cv::Mat background = cv::Mat(greenChannel.size(), CV_8UC1, meanColor);
background.copyTo(greenChannel, backgroundMask);
// smooth optic disc and other bright lesions
cv::Mat structureElem = getStructuringElement(CV_SHAPE_ELLIPSE, cv::Size(S1 * ratio, S1 * ratio)), morfGreenChannel;
morphologyEx(greenChannel, morfGreenChannel, cv::MORPH_OPEN, structureElem);
// contrast enhancement to improve the contrast of lesions for easy detection using
cv::Ptr<cv::CLAHE> clahe = cv::createCLAHE(1, cv::Size(8 * ratio, 8 * ratio));
clahe->apply(morfGreenChannel, morfGreenChannel);
// invert image
bitwise_not(backgroundMask, backgroundMask);
cv::subtract(cv::Scalar::all(255), morfGreenChannel, morfGreenChannel);
// thresholding local variation image to extract candidate region, A1 is chosen in a very tolerant manner
cv::Mat localVariationImage = localVariation(morfGreenChannel, backgroundMask, 6 * ratio);
normalize(localVariationImage, localVariationImage, 0, 255, cv::NORM_MINMAX, CV_8UC1);
int A1 = 30;
threshold(localVariationImage, localVariationImage, A1, 255, cv::THRESH_BINARY );
// remove vessels from candidate regions
cv::Mat vesselsMask = getBloodVesselsMask(image, cv::Mat(), ratio);
structureElem = getStructuringElement(CV_SHAPE_ELLIPSE, cv::Size(4 * ratio, 4 * ratio));
erode(vesselsMask, vesselsMask, structureElem);
cv::Mat candidates; candidates = cv::Mat::zeros(vesselsMask.size(), CV_8UC1);
localVariationImage.copyTo(candidates, vesselsMask);
// create mask of candidate regions where all contours are filled
std::vector<std::vector<cv::Point>> contours;
findContours(candidates, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
candidates = cv::Mat::zeros(image.rows, image.cols, CV_8UC3);
for( size_t i = 0; i< contours.size(); i++ ) {
drawContours( candidates, contours, (int)i, cv::Scalar(255,255,255), CV_FILLED, 0);
}
cvtColor(candidates, candidates, cv::COLOR_BGR2GRAY );
// remove noise and enlarge candidate regions in mask
erode(candidates, candidates, getStructuringElement(CV_SHAPE_ELLIPSE, cv::Size(5 * ratio, 5 * ratio)));
dilate(candidates, candidates, getStructuringElement(CV_SHAPE_ELLIPSE, cv::Size(6 * ratio, 6 * ratio)));
// set all the candidate regions to 0 in the original image
cv::Mat candidatesMask; candidatesMask = cv::Mat::ones(image.rows, image.cols, CV_8UC1);
cv::bitwise_not(candidates, candidates);
cv::subtract(cv::Scalar::all(255), greenChannel, greenChannel);
greenChannel.copyTo(candidatesMask, candidates);
// calculate the morphological reconstruction by dilation
cv::Mat reconstructedCandidates = morfologicalReconstruction(greenChannel, candidatesMask, structureElem, 0);
// apply a threshold operation to the difference between the original image and the reconstructed image
cv::Mat hemorrhages;
subtract(greenChannel, reconstructedCandidates, hemorrhages);
int A2 = 5;
threshold(hemorrhages, hemorrhages, A2, 255, cv::THRESH_BINARY );
findContours(hemorrhages, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
removeSmallAreaContours(&contours, ratio * MIN_FINDING_AREA);
return contours;
}
/* @brief Computes features of hemorrhage contour
* @param contours is pointer to array of contours of hemorrhages
* @param image, in which contours were found
* @param index of contour in array
* @return [area, eccentricity, perimeter, compactness, aspect ratio,
* mean of candidate green channel, standart deviation of candidate green channel,
* mean of candidate contrast enhancement green channel, standart deviation of candidate contrast enhancement green channel,
* mean gradient magnitude, mean gradient of neighbor pixels,
* mean hue, mean saturation, mean value,
* standart deviation of hue, standart deviation of saturation, standart deviation of value,
* entropy, energy, ratio]
*/
std::vector<double> getHemorrhageFeature(std::vector<std::vector<cv::Point>> contours, cv::Mat *image, int index, double ratio) {
// get background mask and rect which describes contour of hemorrhage
cv::Mat backgroundMask = getBackgroundMask(image->clone(), 0, 10);
cv::Rect hemorrhageRect = boundingRect(cv::Mat(contours[0]));
if (ratio == std::numeric_limits<double>::infinity()) {
std::vector<std::vector<cv::Point>> contours;
findContours(backgroundMask.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
ratio = computeRatio(hemorrhageRect.size(), {660, 660});
}
// get green channel of image
std::vector<cv::Mat> bgrChannel;
split(*image, bgrChannel);
cv::Mat greenChannel = bgrChannel[1];
// make mean color value of retina as background color value and process contrast enhancement
int retinaMeanColor = mean(greenChannel, backgroundMask)[0];
cv::Mat contrastEnhancementGreenChannel = cv::Mat(greenChannel.size(), CV_8UC1, retinaMeanColor);
greenChannel.copyTo(contrastEnhancementGreenChannel, backgroundMask);
cv::Ptr<cv::CLAHE> clahe = cv::createCLAHE(1, cv::Size(8 * ratio, 8 * ratio));
clahe->apply(contrastEnhancementGreenChannel, contrastEnhancementGreenChannel);
// intensity of image is simple grey color image
cv::Mat intensity;
cv::cvtColor(*image, intensity, CV_BGR2GRAY);
// because of energy computing we image with all contours filled
cv::Mat contoursMask(image->size(), CV_8UC1, cv::Scalar(0, 0, 0));
for (int i = 0; i < contours.size(); i++) {
drawContours(contoursMask, contours, i, cv::Scalar(255, 255, 255), CV_FILLED, 8);
}
cv::Mat elementMask, elementContoursMask, elementImage, elementContoursImage;
elementMask = cv::Mat::zeros(image->size(), CV_8UC1);
elementContoursMask = cv::Mat::zeros(image->size(), CV_8UC1);
elementImage = cv::Mat::zeros(image->size(), CV_8UC1);
// compute sum of all pixels in element
cv::drawContours(elementMask, contours, index, cv::Scalar(255), CV_FILLED, 8);
contrastEnhancementGreenChannel.copyTo(elementImage, elementMask);
double area = cv::sum(elementImage)[0];
// compute ratio of the distance between foci of ellipse and its major axis length
cv::RotatedRect contourRect = fitEllipse(cv::Mat(contours[index]));
double eccentricity = getEccentricity(contourRect);
// compute perimeter of contour
double perimeter = cv::arcLength(contours[index], true);
// compute compactness of element
double compactness = pow(perimeter, 2) / ( 4 * CV_PI * area);
// compute ratio of major axis length to minor axis length
double aspectRatio = contourRect.size.width / contourRect.size.height;
// mean and standard deviation value of all green channel pixels within the candidate region
cv::Scalar hemorrhageMean, hemorrhageStdDev;
cv::Mat hemorrhageGreenChannel;
greenChannel.copyTo(hemorrhageGreenChannel, elementMask);
meanStdDev(hemorrhageGreenChannel, hemorrhageMean, hemorrhageStdDev, backgroundMask);
// mean and standard deviation value of all green channel pixels within the candidate region
cv::Scalar hemorrhageCEMean, hemorrhageCEStdDev;
cv::Mat hemorrhageCEGreenChannel;
contrastEnhancementGreenChannel.copyTo(hemorrhageCEGreenChannel, elementMask);
meanStdDev(hemorrhageCEGreenChannel, hemorrhageCEMean, hemorrhageCEStdDev, backgroundMask);
// compute mean gradient magnitude of boundary pixels
cv::Mat grad_x, grad_y, abs_grad_x, abs_grad_y, grad;
cv::Mat druseIntensity;
intensity.copyTo(druseIntensity, elementMask);
// gradient X & Y
Sobel(druseIntensity, grad_x, CV_16S, 1, 0, 3, 1, 0, cv::BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
Sobel(druseIntensity, grad_y, CV_16S, 0, 1, 3, 1, 0, cv::BORDER_DEFAULT);
convertScaleAbs(grad_y, abs_grad_y);
addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
double meanGradientMagnitude = cv::mean(grad, elementContoursMask)[0];
// compute mean gradient magnitude of neighbor pixels in a square region outside the hemorrhage region
cv::Mat squareRegionMask; squareRegionMask = cv::Mat::zeros(contrastEnhancementGreenChannel.size(), CV_8UC1);
cv::rectangle(squareRegionMask, {hemorrhageRect.x, hemorrhageRect.y}, {hemorrhageRect.x + hemorrhageRect.width, hemorrhageRect.y + hemorrhageRect.height}, 255, CV_FILLED);
cv::bitwise_xor(squareRegionMask, elementMask, squareRegionMask);
intensity.copyTo(druseIntensity, squareRegionMask);
// gradient X & Y
Sobel(druseIntensity, grad_x, CV_16S, 1, 0, 3, 1, 0, cv::BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
Sobel(druseIntensity, grad_y, CV_16S, 0, 1, 3, 1, 0, cv::BORDER_DEFAULT);
convertScaleAbs(grad_y, abs_grad_y);
addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
double meanGradientNeighbourMagnitude = cv::mean(grad, elementContoursMask)[0];
// compute mean and standart deviation of hue, saturation and value of element
cv::Mat druseHSV, druseHSVChannels[3];
cv::cvtColor(elementImage, druseHSV, CV_BGR2HSV);
cv::split(druseHSV, druseHSVChannels);
cv::Scalar meanHue, stdDevHue, meanSaturation, stdDevSaturation, meanValue, stdDevValue;
meanStdDev(hemorrhageCEGreenChannel, meanHue, stdDevHue, backgroundMask);
meanStdDev(hemorrhageCEGreenChannel, meanSaturation, stdDevSaturation, backgroundMask);
meanStdDev(hemorrhageCEGreenChannel, meanValue, stdDevValue, backgroundMask);
// compute entropy, in other words measure of randomness
int histMax = 256;
double entropy = computeEntropy(intensity, histMax, elementMask);
// compute energy of candidate region in image
double energy = cv::sum(druseIntensity)[0] / cv::sum(contoursMask)[0];
return { area, eccentricity, perimeter, compactness, aspectRatio, hemorrhageMean[0], hemorrhageStdDev[0],
hemorrhageCEMean[0], hemorrhageCEStdDev[0], meanGradientMagnitude, meanGradientNeighbourMagnitude,
meanHue[0], meanSaturation[0], meanValue[0], stdDevHue[0], stdDevSaturation[0], stdDevValue[0], entropy, energy, ratio };
}
/* @brief Checks if file already exists.
* @param fileName is path to file
* @return if exists true otherwise false
*/
bool fileExist(std::string fileName) {
std::ifstream infile(fileName);
return infile.good();
}
/* @brief Computes features of selected contours from image and save it to file.
* @param output is path to file
* @param image, in which objects for selection are found
* @param type of object, allowed values are LEARN_DRUSE = 0, LEARN_EXUDATE = 1, LEARN_HEMORRHAGE = 2
*/
void appendDatabase(cv::Mat image, int type, std::string output) {
std::vector<std::vector<cv::Point>> contours;
if(type == LEARN_DRUSE) {
contours = getDrusenContours(image);
output += "/druse.csv";
} else if(type == LEARN_EXUDATE) {
contours = getExudatesContours(image);
output += "/exudate.csv";
} else if(type == LEARN_HEMORRHAGE) {
contours = getHemorrhagesContours(image);
output += "/hemorrhage.csv";
} else {
throw std::invalid_argument("Invalid 'method' property value. Enabled only LEARN_DRUSE = 0, LEARN_EXUDATE = 1, LEARN_HEMORRHAGE = 2.");
}
std::cout << "Extraction of contours completed ... " << std::endl;
// show image and set listener for selecting contours area
std::string windowTitle = "Select true findings ( TRUE POSITIVE - right mouse button, FALSE POSITIVE - left mouse button, CONTINUE - press any key ) ...";
cv::namedWindow(windowTitle, cv::WINDOW_NORMAL );
cv::resizeWindow(windowTitle, 500,500);
cv::moveWindow(windowTitle, 200,200);
for (int j = 0; j < contours.size(); ++j) {
drawContours( image, contours, j, cv::Scalar(255, 255, 255), 1, 8);
}
cv::imshow(windowTitle, image);
CallBackParams params = {contours, image, windowTitle};
cv::setMouseCallback(windowTitle, classificationCallBackFunc, ¶ms);
cv::waitKey(0);
cv::destroyWindow(windowTitle);
cv::waitKey(1);
// save features of selected elements to file
std::ofstream file;
if(fileExist(output)) {
file.open(output, std::fstream::app);
} else {
// if file doesn't exist, create it and insert header
file.open(output, std::fstream::app);
if(type == LEARN_EXUDATE || type == LEARN_DRUSE) {
file << DB_FILE_HEADER_1 << std::endl;
} else if(type == LEARN_HEMORRHAGE) {
file << DB_FILE_HEADER_2 << std::endl;
}
}
if(!file) {
std::cerr << "Could not open file [ " << output << " ]." << std::endl;
return;
} else {
std::cout << "Saving features of selected object to file [ " << output << " ] ..." << std::endl;
}
// write true positive object features to file, value in first column is 1
for (std::vector<int>::const_iterator i = params.positive.begin(); i != params.positive.end(); ++i) {
std::vector<double> features = {};
if(type == LEARN_EXUDATE || type == LEARN_DRUSE) {
features = getBrightObjectFeature(contours, &image, *i);
} else if(type == LEARN_HEMORRHAGE) {
features = getHemorrhageFeature(contours, &image, *i);
}
file << "1, ";
for (int j = 0; j < features.size(); ++j) {
file << std::setprecision(8) << features[j];
if( j < features.size() - 1) {
file << ", ";
} else {
file << "\n";
}
}
}
// write false positive object features to file, value in first column is -1
for (std::vector<int>::const_iterator i = params.negative.begin(); i != params.negative.end(); ++i) {
std::vector<double> features = {};
if(type == LEARN_EXUDATE || type == LEARN_DRUSE) {
features = getBrightObjectFeature(contours, &image, *i);
} else if(type == LEARN_HEMORRHAGE) {
features = getHemorrhageFeature(contours, &image, *i);
}
file << "-1, ";
for (int j = 0; j < features.size(); ++j) {
file << std::setprecision(8) << features[j];
if( j < features.size() - 1) {
file << ", ";
} else {
file << "\n";
}
}
}
file.close();
std::cout << "Features were successfully saved." << std::endl;
}
/* @brief Splits string of float values separated by delimiter.
* @param s is string to be splited
* @param delimiter is substring in string which logically splits values
* @param values is empty vector and will be filled by splitted float values
*/
void split(const std::string &s, char delimiter, std::vector<float> &values) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delimiter)) {
values.push_back(std::stof(item));
}
}
/* @brief Converts vector of float values to matrix.
* @param vec is input vector
* @return matrix of converted values
*/
cv::Mat convert(std::vector<std::vector<float>> vec) {
cv::Mat mat(vec.size(), vec.at(0).size(), CV_32FC1);
for(int i=0; i<mat.rows; ++i) {
for (int j = 0; j < mat.cols; ++j) {
mat.at<float>(i, j) = vec.at(i).at(j);
}
}
return mat;
}
/* @brief Trains bayes classifier by input data and save generated model to file.
* @param input is system path to file in which is stored local database of retina findings and their classification as true/false positive
* @param output is system path to folder where statistical model will be saved as XML / YAML file
* @param type of object, allowed values are LEARN_DRUSE = 0, LEARN_EXUDATE = 1, LEARN_HEMORRHAGE = 2
*/
void trainClassifier(std::string input, std::string output, int type) {
std::ifstream dataStream(input);
// get training data out of file
std::vector<std::vector<float>> trainData;
std::vector<float> labels;
if (dataStream.is_open())
{
std::string line;
// skip first line = header line
getline(dataStream, line);
// parse data from file to data array and labels array
while (getline(dataStream, line)) {
std::vector<float> parsedLine;
split(line, ',', parsedLine);
labels.push_back(parsedLine.front());
parsedLine.erase(parsedLine.begin());
trainData.push_back(parsedLine);
}
dataStream.close();
} else {
std::cerr << "Unable to open data file [" + input + "].";
return;
}
if(!fileExist(output)) {
std::cerr << "Output folder [ " + output + " ] does not exist.";
return;
}
if(type == LEARN_DRUSE) {
output += "/druse.xml";
} else if(type == LEARN_EXUDATE) {
output += "/exudate.xml";
} else if(type == LEARN_HEMORRHAGE) {
output += "/hemorrhage.xml";
} else {
throw std::invalid_argument("Invalid 'method' property value. Enabled only LEARN_DRUSE = 0, LEARN_EXUDATE = 1, LEARN_HEMORRHAGE = 2.");
}
if(!trainData.empty()) {
// train bayesclassifier and save it to file
cv::Mat trainingMat = convert(trainData);
float labelsArray[labels.size()];
std::copy(labels.begin(), labels.end(), labelsArray);
cv::Mat labelsMat(1, trainingMat.rows, CV_32SC1, labelsArray);
cv::Ptr<cv::ml::NormalBayesClassifier> bayes = cv::ml::NormalBayesClassifier::create();
bayes->train(trainingMat, cv::ml::ROW_SAMPLE, labelsMat);
bayes->save(output);
} else {
std::cerr << "There are no data in file [" + input + "]. Stopping ...";
return;
}
} | 44.465615 | 180 | 0.659284 | [
"object",
"shape",
"vector",
"model"
] |
5df1dfff93f83787d0a10c401328c79055789ea1 | 5,283 | cpp | C++ | modules/bio_mapred/flatten_seqset.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 16 | 2021-07-14T23:32:31.000Z | 2022-03-24T16:25:15.000Z | modules/bio_mapred/flatten_seqset.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 9 | 2021-07-20T20:39:47.000Z | 2021-09-16T20:57:59.000Z | modules/bio_mapred/flatten_seqset.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 9 | 2021-07-15T19:38:35.000Z | 2022-01-31T19:24:56.000Z | #include <atomic>
#include <iostream>
#include <thread>
#include <boost/format.hpp>
#include "modules/bio_base/seqset.h"
#include "modules/bio_format/dna_io.h"
#include "modules/bio_mapred/flatten_seqset.h"
#include "modules/io/file_io.h"
#include "modules/io/mmap_buffer.h"
#include "modules/io/utils.h"
#include "modules/mapred/temp_file.h"
flatten_seqset::flatten_seqset(std::vector<std::string> seqset_files, int num_threads, int max_read_size)
: m_seqset_files(std::move(seqset_files))
, m_num_threads(num_threads)
, m_max_read_size(max_read_size)
{
if (num_threads < 4) {
throw io_exception(boost::format(
"flatten_seqset requires a minimum of 4 threads, you"
" requested %1%") % num_threads);
}
if (! is_power_of_2(num_threads)) {
throw io_exception(boost::format(
"flatten_seqset requires a number of threads that is a power of two, you"
" requested %1%") % num_threads);
}
}
std::multimap<int, std::shared_ptr<scoped_temp_file>> flatten_seqset::operator() ()
{
SPLOG("flatten_seqset::operator()> Beginning flattening...");
std::multimap<int, std::shared_ptr<scoped_temp_file>> temp_files_map;
std::vector<std::future<void>> are_threads_done;
for (const auto& seqset_path : m_seqset_files) {
SPLOG("Opening seqset \"%s\".", seqset_path.c_str());
std::cout << seqset_path.c_str() << std::endl;
print_progress(0.0);
seqset_file the_seqset_file(seqset_path);
const seqset& the_seqset = the_seqset_file.get_seqset();
SPLOG("Main: First shared = %u, context = %u", the_seqset.entry_shared(0), the_seqset.entry_size(0));
the_seqset.populate_pop_front_cache();
SPLOG("seqset \"%s\" opened and cache populated.", seqset_path.c_str());
m_cur_progress = 0;
size_t total_progress = the_seqset.size();
for (int i = 0; i < m_num_threads; i++) {
are_threads_done.emplace_back(
std::async(std::launch::async,
[this, i, &temp_files_map, &the_seqset]() { this->flatten_partition(i, temp_files_map, the_seqset); }
)
);
}
// Print progress in a separate thread.
auto progress = std::async(std::launch::async,
[&](){
while(m_cur_progress < total_progress) {
print_progress(float(m_cur_progress) / float(total_progress));
usleep(400000);
}
}
);
for (int i = 0; i < m_num_threads; i++) {
are_threads_done[i].get();
}
// Exit the progress thread
m_cur_progress = total_progress;
progress.get();
are_threads_done.clear();
print_progress(1.0);
std::cout << std::endl;
}
SPLOG("flatten_seqset::operator()> Done flattening.");
return temp_files_map;
}
void flatten_seqset::flatten_partition(int partition, temp_file_map_t& temp_file_map, const seqset& the_seqset) const
{
auto temp_file_ptr = std::make_shared<scoped_temp_file>();
SPLOG("Partition %d: Flattening seqset to temp file \"%s\"."
, partition, temp_file_ptr->path().c_str());
dna_sequence start_sequence = find_partition_sequence(partition, m_num_threads);
seqset_range start_context = the_seqset.find(start_sequence);
uint64_t start = start_context.begin();
uint64_t end = the_seqset.size();
if (partition != (m_num_threads - 1)) {
dna_sequence end_sequence = find_partition_sequence(partition + 1, m_num_threads);
seqset_range end_context = the_seqset.find(end_sequence);
end = end_context.begin();
}
SPLOG("Partition %d: start = %lu, end = %lu", partition, start, end);
file_writer temp_file_writer(temp_file_ptr->path());
SPLOG("Partition %d entry count: %lu", partition, end - start);
dna_writer seq_writer(temp_file_writer);
for(uint64_t i = start; i < end; i++) {
// atomic progress tracker
m_cur_progress++;
dna_sequence the_seq {the_seqset.ctx_entry(i).sequence()};
if (m_max_read_size > -1 && the_seq.size() > size_t(m_max_read_size)) {
the_seq = the_seq.subseq(0, m_max_read_size);
}
seq_writer.write(the_seq);
if (((i - start) % 10000000) == 0) {
SPLOG("Partition %d: Wrote %lu sequences to flat file", partition, i - start);
}
}
SPLOG("Partition %d: Done writing.", partition);
{{
std::unique_lock<std::mutex> map_lock(m_temp_file_map_mutex);
temp_file_map.emplace(partition, temp_file_ptr);
}}
SPLOG("Partition %d: Finished flattening.", partition);
}
// Partition DNA space, so map partition and total partition to dna sequence.
// This function takes advantage of the correspondence between base 4 arithmetic
// and DNA sequences. If the number of threads, and thus the number of partitions
// is a power of 4, then each partition is simply the corresponding integer, i.e.
// a kmer_t. If it's not a power of 4 (but still a power of 2 as asserted), we
// need to stretch the partitions by a factor of two.
dna_sequence flatten_seqset::find_partition_sequence(int partition, int thread_count)
{
int total_partitions = thread_count;
kmer_t partition_kmer = partition;
if (! is_power_of_4(total_partitions)) {
partition_kmer *= 2;
total_partitions *= 2;
}
int partition_seq_length = 0;
while (total_partitions >>= 2) {
partition_seq_length++;
}
return dna_sequence(partition_kmer, partition_seq_length);
}
bool flatten_seqset::is_power_of_2(int n)
{
if (n <= 0) return false;
return ! (n & (n - 1));
}
bool flatten_seqset::is_power_of_4(int n)
{
if (! is_power_of_2(n)) return false;
return n & 0x55555555;
}
| 32.018182 | 117 | 0.719667 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.