hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a4471bdccd0f3b818af66840c59cf4a9dcd7661
| 2,679
|
hpp
|
C++
|
library/utility/byte.hpp
|
SJSURoboticsTeam/urc-control_systems-2020
|
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
|
[
"Apache-2.0"
] | 1
|
2020-02-22T20:26:41.000Z
|
2020-02-22T20:26:41.000Z
|
library/utility/byte.hpp
|
SJSURoboticsTeam/urc-control_systems-2020
|
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
|
[
"Apache-2.0"
] | null | null | null |
library/utility/byte.hpp
|
SJSURoboticsTeam/urc-control_systems-2020
|
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
|
[
"Apache-2.0"
] | 4
|
2019-10-17T03:42:03.000Z
|
2020-05-23T20:32:03.000Z
|
#pragma once
#include <algorithm>
#include <array>
#include <bit>
#include <climits>
#include <cstdint>
#include <span>
namespace sjsu
{
template <typename T, size_t array_size = sizeof(T)>
constexpr auto ToByteArray(std::endian endian, T value)
{
std::array<uint8_t, array_size> array = {};
static_assert(std::is_integral_v<T>,
"Type T (the return type) must be intergal type.");
if constexpr (std::is_integral_v<T>)
{
if (endian == std::endian::little)
{
for (size_t i = 0; i < array.size(); i++)
{
auto next_byte = value >> ((CHAR_BIT * i) & 0xFF);
array.begin()[i] = static_cast<uint8_t>(next_byte);
}
}
else
{
for (size_t i = 0; i < array.size(); i++)
{
auto next_byte = value >> ((CHAR_BIT * i) & 0xFF);
array.rbegin()[i] = static_cast<uint8_t>(next_byte);
}
}
}
return array;
}
template <size_t N>
constexpr auto ByteArrayToSpan(std::endian endian,
const std::array<uint8_t, N> & bytes,
size_t width)
{
if (endian == std::endian::big)
{
return std::span<const uint8_t>(&bytes.end()[-width], width);
}
else
{
return std::span<const uint8_t>(bytes.data(), width);
}
}
template <typename T>
constexpr auto ToInteger(std::endian endian, std::span<const uint8_t> array)
{
static_assert(std::is_integral_v<T>,
"Type T (the return type) must be intergal type.");
T value = 0;
if constexpr (std::is_integral_v<T>)
{
size_t end = std::min(sizeof(T), array.size());
if (endian == std::endian::little)
{
for (size_t i = 0; i < end; i++)
{
auto or_value = static_cast<T>(array.begin()[i]) << (CHAR_BIT * i);
value = static_cast<T>(value | or_value);
}
}
else
{
for (size_t i = 0; i < end; i++)
{
auto or_value = static_cast<T>(array.rbegin()[i]) << (CHAR_BIT * i);
value = static_cast<T>(value | or_value);
}
}
}
return value;
}
template <typename T, size_t N>
constexpr auto ToIntegerArray(std::endian endian,
std::span<const uint8_t> bytes)
{
static_assert(std::is_integral_v<T>,
"Type T (the return type) must be intergal type.");
std::array<T, N> value = { 0 };
std::span<const uint8_t> byte_span;
if constexpr (std::is_integral_v<T>)
{
for (size_t i = 0; i < bytes.size(); i += sizeof(T))
{
byte_span = bytes.subspan(i, sizeof(T));
value[i / sizeof(T)] = ToInteger<T>(endian, byte_span);
}
}
return value;
}
} // namespace sjsu
| 25.273585
| 76
| 0.562897
|
SJSURoboticsTeam
|
4a4499dd57b31069a8775c28f34832d24a4d1c3a
| 12,270
|
cc
|
C++
|
src/test-string-view.cc
|
okuoku/wabt
|
3dc09d11ff4396c9a4cf903cae2ed6a88f5982b6
|
[
"Apache-2.0"
] | 8,664
|
2016-01-13T17:33:19.000Z
|
2019-05-06T19:55:36.000Z
|
src/test-string-view.cc
|
okuoku/wabt
|
3dc09d11ff4396c9a4cf903cae2ed6a88f5982b6
|
[
"Apache-2.0"
] | 5,058
|
2016-01-13T17:57:02.000Z
|
2019-05-04T15:41:54.000Z
|
src/test-string-view.cc
|
okuoku/wabt
|
3dc09d11ff4396c9a4cf903cae2ed6a88f5982b6
|
[
"Apache-2.0"
] | 1,367
|
2016-01-13T17:54:57.000Z
|
2019-04-29T18:16:27.000Z
|
/*
* Copyright 2017 WebAssembly Community Group participants
*
* 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 "gtest/gtest.h"
#include "src/string-view.h"
#include <cstring>
#include <functional>
using namespace wabt;
namespace {
void assert_string_view_eq(const char* s, string_view sv) {
size_t len = std::strlen(s);
ASSERT_EQ(len, sv.size());
for (size_t i = 0; i < len; ++i) {
ASSERT_EQ(s[i], sv[i]);
}
}
constexpr string_view::size_type npos = string_view::npos;
} // end anonymous namespace
TEST(string_view, default_constructor) {
assert_string_view_eq("", string_view());
}
TEST(string_view, copy_constructor) {
string_view sv1("copy");
assert_string_view_eq("copy", string_view(sv1));
string_view sv2;
assert_string_view_eq("", string_view(sv2));
}
TEST(string_view, assignment_operator) {
string_view sv1;
sv1 = string_view("assign");
assert_string_view_eq("assign", sv1);
string_view sv2;
sv2 = string_view();
assert_string_view_eq("", sv2);
}
TEST(string_view, string_constructor) {
assert_string_view_eq("", string_view(std::string()));
assert_string_view_eq("string", string_view(std::string("string")));
}
TEST(string_view, cstr_constructor) {
assert_string_view_eq("", string_view(""));
assert_string_view_eq("cstr", string_view("cstr"));
}
TEST(string_view, cstr_len_constructor) {
assert_string_view_eq("", string_view("foo-bar-baz", 0));
assert_string_view_eq("foo", string_view("foo-bar-baz", 3));
assert_string_view_eq("foo-bar", string_view("foo-bar-baz", 7));
}
TEST(string_view, begin_end) {
string_view sv("012345");
char count = 0;
for (auto iter = sv.begin(), end = sv.end(); iter != end; ++iter) {
ASSERT_EQ('0' + count, *iter);
++count;
}
ASSERT_EQ(6, count);
}
TEST(string_view, cbegin_cend) {
const string_view sv("012345");
char count = 0;
for (auto iter = sv.cbegin(), end = sv.cend(); iter != end; ++iter) {
ASSERT_EQ('0' + count, *iter);
++count;
}
ASSERT_EQ(6, count);
}
TEST(string_view, rbegin_rend) {
string_view sv("012345");
char count = 0;
for (auto iter = sv.rbegin(), end = sv.rend(); iter != end; ++iter) {
ASSERT_EQ('5' - count, *iter);
++count;
}
ASSERT_EQ(6, count);
}
TEST(string_view, crbegin_crend) {
const string_view sv("012345");
char count = 0;
for (auto iter = sv.crbegin(), end = sv.crend(); iter != end; ++iter) {
ASSERT_EQ('5' - count, *iter);
++count;
}
ASSERT_EQ(6, count);
}
TEST(string_view, size) {
string_view sv1;
ASSERT_EQ(0U, sv1.size());
string_view sv2("");
ASSERT_EQ(0U, sv2.size());
string_view sv3("hello");
ASSERT_EQ(5U, sv3.size());
}
TEST(string_view, length) {
string_view sv1;
ASSERT_EQ(0U, sv1.length());
string_view sv2("hello");
ASSERT_EQ(5U, sv2.length());
}
TEST(string_view, empty) {
string_view sv1;
ASSERT_TRUE(sv1.empty());
string_view sv2("bye");
ASSERT_FALSE(sv2.empty());
}
TEST(string_view, operator_bracket) {
string_view sv("words");
ASSERT_EQ('w', sv[0]);
ASSERT_EQ('o', sv[1]);
ASSERT_EQ('r', sv[2]);
ASSERT_EQ('d', sv[3]);
ASSERT_EQ('s', sv[4]);
}
TEST(string_view, at) {
string_view sv("words");
ASSERT_EQ('w', sv.at(0));
ASSERT_EQ('o', sv.at(1));
ASSERT_EQ('r', sv.at(2));
ASSERT_EQ('d', sv.at(3));
ASSERT_EQ('s', sv.at(4));
}
TEST(string_view, front) {
string_view sv("words");
ASSERT_EQ('w', sv.front());
}
TEST(string_view, back) {
string_view sv("words");
ASSERT_EQ('s', sv.back());
}
TEST(string_view, data) {
const char* cstr = "words";
string_view sv(cstr);
ASSERT_EQ(cstr, sv.data());
}
TEST(string_view, remove_prefix) {
string_view sv("words");
sv.remove_prefix(2);
assert_string_view_eq("rds", sv);
}
TEST(string_view, remove_suffix) {
string_view sv("words");
sv.remove_suffix(2);
assert_string_view_eq("wor", sv);
}
TEST(string_view, swap) {
string_view sv1("hello");
string_view sv2("bye");
sv1.swap(sv2);
assert_string_view_eq("bye", sv1);
assert_string_view_eq("hello", sv2);
}
TEST(string_view, operator_std_string) {
string_view sv1("hi");
std::string s(sv1);
ASSERT_EQ(2U, s.size());
ASSERT_EQ('h', s[0]);
ASSERT_EQ('i', s[1]);
}
TEST(string_view, copy) {
string_view sv("words");
char buffer[10] = {0};
sv.copy(buffer, 10, 2);
ASSERT_EQ('r', buffer[0]);
ASSERT_EQ('d', buffer[1]);
ASSERT_EQ('s', buffer[2]);
for (int i = 3; i < 10; ++i) {
ASSERT_EQ(0, buffer[i]);
}
}
TEST(string_view, substr) {
string_view sv1("abcdefghij");
string_view sv2 = sv1.substr(2, 3);
assert_string_view_eq("cde", sv2);
}
TEST(string_view, compare0) {
ASSERT_TRUE(string_view("meat").compare(string_view("meet")) < 0);
ASSERT_TRUE(string_view("rest").compare(string_view("rate")) > 0);
ASSERT_TRUE(string_view("equal").compare(string_view("equal")) == 0);
ASSERT_TRUE(string_view("star").compare(string_view("start")) < 0);
ASSERT_TRUE(string_view("finished").compare(string_view("fin")) > 0);
}
TEST(string_view, compare1) {
ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("ca")) > 0);
ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("cd")) == 0);
ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("cz")) < 0);
}
TEST(string_view, compare2) {
ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("_ca__"), 1, 2) >
0);
ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("_cd__"), 1, 2) ==
0);
ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("_cz__"), 1, 2) <
0);
}
TEST(string_view, compare3) {
ASSERT_TRUE(string_view("abcdef").compare("aaaa") > 0);
ASSERT_TRUE(string_view("abcdef").compare("abcdef") == 0);
ASSERT_TRUE(string_view("abcdef").compare("zzzz") < 0);
}
TEST(string_view, compare4) {
ASSERT_TRUE(string_view("abcdef").compare(2, 2, "ca") > 0);
ASSERT_TRUE(string_view("abcdef").compare(2, 2, "cd") == 0);
ASSERT_TRUE(string_view("abcdef").compare(2, 2, "cz") < 0);
}
TEST(string_view, compare5) {
ASSERT_TRUE(string_view("abcdef").compare(2, 2, "ca____", 2) > 0);
ASSERT_TRUE(string_view("abcdef").compare(2, 2, "cd___", 2) == 0);
ASSERT_TRUE(string_view("abcdef").compare(2, 2, "cz__", 2) < 0);
}
TEST(string_view, find0) {
ASSERT_EQ(0U, string_view("find fins").find(string_view("fin")));
ASSERT_EQ(5U, string_view("find fins").find(string_view("fin"), 1));
ASSERT_EQ(npos, string_view("find fins").find(string_view("fin"), 6));
}
TEST(string_view, find1) {
ASSERT_EQ(0U, string_view("012340123").find('0'));
ASSERT_EQ(5U, string_view("012340123").find('0', 2));
ASSERT_EQ(npos, string_view("012340123").find('0', 6));
}
TEST(string_view, find2) {
ASSERT_EQ(1U, string_view("012340123").find("12345", 0, 2));
ASSERT_EQ(6U, string_view("012340123").find("12345", 3, 2));
ASSERT_EQ(npos, string_view("012340123").find("12345", 10, 2));
}
TEST(string_view, find3) {
ASSERT_EQ(1U, string_view("012340123").find("12"));
ASSERT_EQ(6U, string_view("012340123").find("12", 2));
ASSERT_EQ(npos, string_view("012340123").find("12", 10));
}
TEST(string_view, rfind0) {
ASSERT_EQ(5U, string_view("find fins").rfind(string_view("fin")));
ASSERT_EQ(0U, string_view("find fins").rfind(string_view("fin"), 4));
ASSERT_EQ(npos, string_view("find fins").rfind(string_view("no")));
ASSERT_EQ(npos, string_view("foo").rfind(string_view("foobar")));
}
TEST(string_view, rfind1) {
ASSERT_EQ(5U, string_view("012340123").rfind('0'));
ASSERT_EQ(0U, string_view("012340123").rfind('0', 2));
ASSERT_EQ(npos, string_view("012340123").rfind('9'));
}
TEST(string_view, rfind2) {
ASSERT_EQ(6U, string_view("012340123").rfind("12345", npos, 2));
ASSERT_EQ(1U, string_view("012340123").rfind("12345", 4, 2));
ASSERT_EQ(npos, string_view("012340123").rfind("12345", npos, 5));
ASSERT_EQ(npos, string_view("012").rfind("12345", npos, 5));
}
TEST(string_view, rfind3) {
ASSERT_EQ(6U, string_view("012340123").rfind("12"));
ASSERT_EQ(1U, string_view("012340123").rfind("12", 2));
ASSERT_EQ(npos, string_view("012340123").rfind("12", 0));
ASSERT_EQ(npos, string_view("012").rfind("12345"));
}
TEST(string_view, find_first_of0) {
ASSERT_EQ(0U, string_view("0123abc").find_first_of(string_view("0a")));
ASSERT_EQ(4U, string_view("0123abc").find_first_of(string_view("0a"), 1));
ASSERT_EQ(npos, string_view("0123abc").find_first_of(string_view("xyz")));
}
TEST(string_view, find_first_of1) {
ASSERT_EQ(1U, string_view("ahellohi").find_first_of('h'));
ASSERT_EQ(6U, string_view("ahellohi").find_first_of('h', 2));
ASSERT_EQ(npos, string_view("ahellohi").find_first_of('z', 2));
}
TEST(string_view, find_first_of2) {
ASSERT_EQ(0U, string_view("0123abc").find_first_of("0a1b", 0, 2));
ASSERT_EQ(4U, string_view("0123abc").find_first_of("0a1b", 1, 2));
ASSERT_EQ(npos, string_view("0123abc").find_first_of("0a1b", 5, 2));
}
TEST(string_view, find_first_of3) {
ASSERT_EQ(0U, string_view("0123abc").find_first_of("0a"));
ASSERT_EQ(0U, string_view("0123abc").find_first_of("0a", 0));
ASSERT_EQ(4U, string_view("0123abc").find_first_of("0a", 1));
ASSERT_EQ(npos, string_view("0123abc").find_first_of("0a", 5));
}
TEST(string_view, find_last_of0) {
ASSERT_EQ(4U, string_view("0123abc").find_last_of(string_view("0a")));
ASSERT_EQ(0U, string_view("0123abc").find_last_of(string_view("0a"), 1));
ASSERT_EQ(npos, string_view("0123abc").find_last_of(string_view("xyz")));
}
TEST(string_view, find_last_of1) {
ASSERT_EQ(6U, string_view("ahellohi").find_last_of('h'));
ASSERT_EQ(1U, string_view("ahellohi").find_last_of('h', 2));
ASSERT_EQ(npos, string_view("ahellohi").find_last_of('z', 2));
}
TEST(string_view, find_last_of2) {
ASSERT_EQ(4U, string_view("0123abc").find_last_of("0a1b", npos, 2));
ASSERT_EQ(0U, string_view("0123abc").find_last_of("0a1b", 1, 2));
ASSERT_EQ(npos, string_view("0123abc").find_last_of("a1b", 0, 2));
ASSERT_EQ(npos, string_view("0123abc").find_last_of("xyz", npos, 0));
}
TEST(string_view, find_last_of3) {
ASSERT_EQ(4U, string_view("0123abc").find_last_of("0a"));
ASSERT_EQ(4U, string_view("0123abc").find_last_of("0a", npos));
ASSERT_EQ(0U, string_view("0123abc").find_last_of("0a", 1));
ASSERT_EQ(npos, string_view("0123abc").find_last_of("a1", 0));
}
TEST(string_view, operator_equal) {
ASSERT_TRUE(string_view("this") == string_view("this"));
ASSERT_FALSE(string_view("this") == string_view("that"));
}
TEST(string_view, operator_not_equal) {
ASSERT_FALSE(string_view("here") != string_view("here"));
ASSERT_TRUE(string_view("here") != string_view("there"));
}
TEST(string_view, operator_less_than) {
ASSERT_TRUE(string_view("abc") < string_view("xyz"));
ASSERT_FALSE(string_view("later") < string_view("earlier"));
ASSERT_FALSE(string_view("one") < string_view("one"));
}
TEST(string_view, operator_greater_than) {
ASSERT_TRUE(string_view("much") > string_view("little"));
ASSERT_FALSE(string_view("future") > string_view("past"));
ASSERT_FALSE(string_view("now") > string_view("now"));
}
TEST(string_view, operator_less_than_or_equal) {
ASSERT_TRUE(string_view("abc") <= string_view("xyz"));
ASSERT_FALSE(string_view("later") <= string_view("earlier"));
ASSERT_TRUE(string_view("one") <= string_view("one"));
}
TEST(string_view, operator_greater_than_or_equal) {
ASSERT_TRUE(string_view("much") >= string_view("little"));
ASSERT_FALSE(string_view("future") >= string_view("past"));
ASSERT_TRUE(string_view("now") >= string_view("now"));
}
TEST(string_view, hash) {
std::hash<string_view> hasher;
ASSERT_NE(hasher(string_view("hello")), hasher(string_view("goodbye")));
ASSERT_EQ(hasher(string_view("same")), hasher(string_view("same")));
}
| 29.495192
| 80
| 0.681581
|
okuoku
|
4a4a4afebe687c634b224eb377b4ac969d84a9ed
| 1,065
|
cpp
|
C++
|
exploringBB/chp09/dcmotor/DCMotorApp.cpp
|
chaicko/ExploringBeagleBone
|
56528557e7d9a328602c65f1b2d837906cb08952
|
[
"Apache-2.0"
] | 1
|
2019-05-28T18:38:29.000Z
|
2019-05-28T18:38:29.000Z
|
exploringBB/chp09/dcmotor/DCMotorApp.cpp
|
chaicko/ExploringBeagleBone
|
56528557e7d9a328602c65f1b2d837906cb08952
|
[
"Apache-2.0"
] | null | null | null |
exploringBB/chp09/dcmotor/DCMotorApp.cpp
|
chaicko/ExploringBeagleBone
|
56528557e7d9a328602c65f1b2d837906cb08952
|
[
"Apache-2.0"
] | null | null | null |
/* A DC Motor Example
* Written by Derek Molloy for the book "Exploring BeagleBone: Tools and
* Techniques for Building with Embedded Linux" by John Wiley & Sons, 2014
* ISBN 9781118935125. Please see the file README.md in the repository root
* directory for copyright and GNU GPLv3 license information. */
#include <iostream>
#include "motor/DCMotor.h"
using namespace std;
using namespace exploringBB;
int main(){
cout << "Starting EBB DC Motor Example" << endl;
DCMotor dcm(new PWM("pwm_test_P9_42.12"), 116); //will export GPIO116
dcm.setDirection(DCMotor::ANTICLOCKWISE);
dcm.setSpeedPercent(50.0f); //make it clear that a float is passed
dcm.go();
cout << "Rotating Anti-clockwise at 50% speed" << endl;
usleep(5000000); //sleep for 5 seconds
dcm.reverseDirection();
cout << "Rotating clockwise at 50% speed" << endl;
usleep(5000000);
dcm.setSpeedPercent(100.0f);
cout << "Rotating clockwise at 100% speed" << endl;
usleep(5000000);
dcm.stop();
cout << "End of EBB DC Motor Example" << endl;
}
| 36.724138
| 75
| 0.694836
|
chaicko
|
4a4e824e4424393ff50c0193a8823f86492c6e56
| 1,532
|
cpp
|
C++
|
Physx.NetCore/Source/VehicleDriveSimData.cpp
|
ronbrogan/Physx.NetCore
|
ac788494b6aefc4b6633c46e857f199e6ab0a47a
|
[
"MIT"
] | 187
|
2015-01-02T15:58:10.000Z
|
2022-02-20T05:23:13.000Z
|
PhysX.Net-3.4/PhysX.Net-3/Source/VehicleDriveSimData.cpp
|
Golangltd/PhysX.Net
|
fb71e0422d441a16a05ed51348d8afb0328d4b90
|
[
"MIT"
] | 37
|
2015-01-10T04:38:23.000Z
|
2022-03-18T00:52:27.000Z
|
PhysX.Net-3.4/PhysX.Net-3/Source/VehicleDriveSimData.cpp
|
Golangltd/PhysX.Net
|
fb71e0422d441a16a05ed51348d8afb0328d4b90
|
[
"MIT"
] | 63
|
2015-01-11T12:12:44.000Z
|
2022-02-05T14:12:49.000Z
|
#include "StdAfx.h"
#include "VehicleDriveSimData.h"
#include "VehicleEngineData.h"
#include "VehicleGearsData.h"
#include "VehicleClutchData.h"
#include "VehicleAutoBoxData.h"
VehicleDriveSimData::VehicleDriveSimData()
{
_data = new PxVehicleDriveSimData();
}
VehicleDriveSimData::VehicleDriveSimData(PxVehicleDriveSimData* data)
{
if (data == NULL)
throw gcnew ArgumentNullException("data");
_data = data;
}
VehicleEngineData^ VehicleDriveSimData::GetEngineData()
{
return VehicleEngineData::ToManaged(_data->getEngineData());
}
void VehicleDriveSimData::SetEngineData(VehicleEngineData^ engine)
{
_data->setEngineData(VehicleEngineData::ToUnmanaged(engine));
}
VehicleClutchData^ VehicleDriveSimData::GetClutchData()
{
return VehicleClutchData::ToManaged(_data->getClutchData());
}
void VehicleDriveSimData::SetClutchData(VehicleClutchData^ clutch)
{
_data->setClutchData(VehicleClutchData::ToUnmanaged(clutch));
}
VehicleGearsData^ VehicleDriveSimData::GetGearsData()
{
return VehicleGearsData::ToManaged(_data->getGearsData());
}
void VehicleDriveSimData::SetGearsData(VehicleGearsData^ gears)
{
_data->setGearsData(VehicleGearsData::ToUnmanaged(gears));
}
VehicleAutoBoxData^ VehicleDriveSimData::GetAutoBoxData()
{
return VehicleAutoBoxData::ToManaged(_data->getAutoBoxData());
}
void VehicleDriveSimData::SetAutoBoxData(VehicleAutoBoxData^ autobox)
{
_data->setAutoBoxData(VehicleAutoBoxData::ToUnmanaged(autobox));
}
PxVehicleDriveSimData* VehicleDriveSimData::UnmanagedPointer::get()
{
return _data;
}
| 25.966102
| 69
| 0.806136
|
ronbrogan
|
4a532efbc43a090eca996a4d7696171696919abc
| 1,194
|
cc
|
C++
|
lib/fibers/SFibersCalSim.cc
|
SiFi-CC/sifi-framework
|
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
|
[
"MIT"
] | null | null | null |
lib/fibers/SFibersCalSim.cc
|
SiFi-CC/sifi-framework
|
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
|
[
"MIT"
] | 3
|
2020-05-06T18:22:40.000Z
|
2020-05-26T14:00:23.000Z
|
lib/fibers/SFibersCalSim.cc
|
SiFi-CC/sifi-framework
|
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
|
[
"MIT"
] | 4
|
2021-02-11T10:44:29.000Z
|
2021-06-17T10:50:23.000Z
|
// @(#)lib/fibers:$Id$
// Author: Rafal Lalik 18/11/2017
/*************************************************************************
* Copyright (C) 2017-2018, Rafał Lalik. *
* All rights reserved. *
* *
* For the licensing terms see $SiFiSYS/LICENSE. *
* For the list of contributors see $SiFiSYS/README/CREDITS. *
*************************************************************************/
#include "SFibersCalSim.h"
#include <cstdio> // for printf
/**
* \class SFibersCalSim
\ingroup lib_fibers
A container for Fibers Stack Calibrated simulation data
*/
/**
* Clear object.
* Parameter options are ignored, for ROOT compatibility.
*
* \param opt options
*/
void SFibersCalSim::Clear(Option_t* /*opt*/)
{
fGeantEloss = 0.0;
fGeantPoint.Clear();
}
/**
* Print category.
*/
void SFibersCalSim::print() const
{
SFibersCal::print();
printf(" GEANT: position = %.2f,%.2f,%.2f Eloss = %.2f\n", fGeantPoint.X(), fGeantPoint.Y(),
fGeantPoint.Z(), fGeantEloss);
}
| 26.533333
| 98
| 0.468174
|
SiFi-CC
|
4a56d14d814c86a5b74dd454e0d13525b14a6213
| 475
|
cpp
|
C++
|
cppcode/cpp execise/day01/bool.cpp
|
jiedou/study
|
606676ebc3d1fb1a87de26b6609307d71dafec22
|
[
"Apache-2.0"
] | null | null | null |
cppcode/cpp execise/day01/bool.cpp
|
jiedou/study
|
606676ebc3d1fb1a87de26b6609307d71dafec22
|
[
"Apache-2.0"
] | null | null | null |
cppcode/cpp execise/day01/bool.cpp
|
jiedou/study
|
606676ebc3d1fb1a87de26b6609307d71dafec22
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
int main (void) <%
bool b = true;
cout << boolalpha << b << noboolalpha
<< ' ' << b << endl;
b = false;
cout << boolalpha << b << noboolalpha
<< ' ' << b << endl;
cout << sizeof (bool) << endl;
// b = 1234;
// b = 1.23;
// b = 'A';
// b = "Hello, World !";
// b = *("Hello, World !" + 14);
// b = "Hello, World !"[14];
b = 14<:"Hello, World !":>;
cout << boolalpha << b << endl;
// a[b] <=> b[a] <=> *(a + b)
return 0;
%>
| 21.590909
| 38
| 0.48
|
jiedou
|
4a571ca06f16a0c1c3b327d6a193ad39b17b1a65
| 4,155
|
hpp
|
C++
|
include/Hord/Data/TableSchema.hpp
|
komiga/hord
|
32be8ffb11bd74959c5cd5254e36d87f224b6f60
|
[
"MIT"
] | null | null | null |
include/Hord/Data/TableSchema.hpp
|
komiga/hord
|
32be8ffb11bd74959c5cd5254e36d87f224b6f60
|
[
"MIT"
] | null | null | null |
include/Hord/Data/TableSchema.hpp
|
komiga/hord
|
32be8ffb11bd74959c5cd5254e36d87f224b6f60
|
[
"MIT"
] | null | null | null |
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief TableSchema class.
@ingroup data
*/
#pragma once
#include <Hord/config.hpp>
#include <Hord/aux.hpp>
#include <Hord/String.hpp>
#include <Hord/utility.hpp>
#include <Hord/serialization.hpp>
#include <Hord/Data/Defs.hpp>
#include <duct/debug.hpp>
namespace Hord {
namespace Data {
// Forward declarations
class TableSchema;
/**
@addtogroup data
@{
*/
/**
Table schema.
*/
class TableSchema {
public:
/**
Column schema.
*/
struct Column {
/** @name Properties */ /// @{
/**
Index.
This is only used when configuring a table.
See @c Data::Table::configure().
*/
unsigned index{~0u};
/** Type. */
Data::Type type{};
/** Name. */
String name{};
/// @}
/** @name Special member functions */ /// @{
/** Destructor. */
~Column() noexcept = default;
/** Default constructor. */
Column() = default;
/** Move constructor. */
Column(Column&&) = default;
/** Copy constructor. */
Column(Column const&) = default;
/** Move assignment operator. */
Column& operator=(Column&&) = default;
/** Copy assignment operator. */
Column& operator=(Column const&) = default;
/**
Construct with name and type.
*/
Column(
String name,
Data::Type type
) noexcept
: type(type)
, name(std::move(name))
{}
/**
Construct with index, name, and type.
*/
Column(
unsigned index,
String name,
Data::Type type
) noexcept
: index(index)
, type(type)
, name(std::move(name))
{}
/// @}
/** @name Serialization */ /// @{
/**
Serialize.
@throws SerializerError{..}
If a serialization operation failed.
*/
template<class Ser>
ser_result_type
serialize(
ser_tag_serialize,
Ser& ser
) {
auto& self = const_safe<Ser>(*this);
ser(
self.type,
Cacophony::make_string_cfg<std::uint8_t>(self.name)
);
}
/// @}
};
/**
Column vector type.
*/
using column_vector_type = aux::vector<Column>;
private:
HashValue m_hash{HASH_EMPTY};
column_vector_type m_columns{};
public:
/** @name Special member functions */ /// @{
/** Destructor. */
~TableSchema() noexcept = default;
/** Default constructor. */
TableSchema() = default;
/** Move constructor. */
TableSchema(TableSchema&&) = default;
/** Copy constructor. */
TableSchema(TableSchema const&) = default;
/** Move assignment operator. */
TableSchema& operator=(TableSchema&&) = default;
/** Copy assignment operator. */
TableSchema& operator=(TableSchema const&) = default;
/**
Construct with column initializer list.
@note Column indices are ~0u; they must be assigned manually
if reconfiguring a table.
*/
TableSchema(
std::initializer_list<Data::TableSchema::Column> const ilist
) noexcept;
/// @}
/** @name Properties */ /// @{
/**
Get schema hash.
*/
HashValue
hash() const noexcept {
return m_hash;
}
/**
Get columns (mutable).
*/
column_vector_type&
columns() noexcept {
return m_columns;
}
/**
Get columns.
*/
column_vector_type const&
columns() const noexcept {
return m_columns;
}
/**
Get number of columns.
*/
unsigned
num_columns() const noexcept {
return m_columns.size();
}
/// @}
/** @name Layout */ /// @{
/**
Get a column by index.
*/
Data::TableSchema::Column const&
column(
unsigned const index
) const {
return m_columns.at(index);
}
/**
Update schema hash.
@returns @c true if the hash changed.
*/
bool
update() noexcept;
/**
Update schema hash.
@returns @c true if a type or the number of columns changed.
*/
bool
assign(
Data::TableSchema const& schema
) noexcept;
/// @}
/** @name Serialization */ /// @{
/**
Read from input serializer.
@throws SerializerError{..}
If a serialization operation failed.
*/
ser_result_type
read(
ser_tag_read,
InputSerializer& ser
);
/**
Write to output serializer.
@throws SerializerError{..}
If a serialization operation failed.
*/
ser_result_type
write(
ser_tag_write,
OutputSerializer& ser
) const;
/// @}
};
/** @} */ // end of doc-group data
} // namespace Data
} // namespace Hord
| 16.686747
| 72
| 0.635379
|
komiga
|
4a583509cdbfd5e612eabd578f3b25d0fd2e96a7
| 2,700
|
cc
|
C++
|
wrapper/lr_wrapper.cc
|
KaiminLai/tiny-machine-learning-system
|
e29625dfb513032b40712663b63f874e2ae6f924
|
[
"MIT"
] | 1
|
2019-01-09T16:03:50.000Z
|
2019-01-09T16:03:50.000Z
|
wrapper/lr_wrapper.cc
|
KaiminLai/tiny-machine-learning-system
|
e29625dfb513032b40712663b63f874e2ae6f924
|
[
"MIT"
] | null | null | null |
wrapper/lr_wrapper.cc
|
KaiminLai/tiny-machine-learning-system
|
e29625dfb513032b40712663b63f874e2ae6f924
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "../src/logistic_regression.h"
#include <ctime>
using namespace Eigen;
using namespace std;
void gen_random(char *s, int len) {
srand(time(NULL));
static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i){
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
extern "C" void lr_fit(double** features, int* labels, int row, int col, int max_iter, double alpha, double lambda,
double tolerance, int seed, bool use_batch, int batch_size, int early_stopping_round, char* ret,
double (*metric)(double* y, double* pred, int size)=Utils::accuracy){
MatrixXd X(row, col);
VectorXd y(row);
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
X(i,j) = features[i][j];
}
y(i) = labels[i];
}
// train the logistic regression model
LogisticRegression clf = LogisticRegression(max_iter, alpha, lambda, tolerance, seed, use_batch);
clf.fit(X, y, batch_size, early_stopping_round, metric);
// save the model weights
char* fmodel = new char[21];
gen_random(fmodel, 20);
string model_path = "/tmp/"+string(fmodel);
clf.saveWeights(model_path);
strcpy(ret, model_path.c_str());
}
extern "C" void lr_predict_prob(double** features, int row, int col, char* fmodel, double* ret){
LogisticRegression clf = LogisticRegression();
clf.loadWeights(fmodel);
MatrixXd X(row, col);
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
X(i,j) = features[i][j];
}
}
VectorXd pred = clf.predict_prob(X);
for(int i = 0; i < row; i++){
ret[i] = pred(i);
}
}
extern "C" void lr_predict(double** features, int row, int col, char* fmodel, int* ret){
double* prob = new double[row];
lr_predict_prob(features, row, col, fmodel, prob);
for(int i = 0; i < row; i++){
ret[i] = prob[i]>0.5?1:0;
}
}
int main(){
int row = 10, col = 2;
double** features = new double *[row];
for(int i = 0; i < row; i++){
features[i] = new double[col];
}
int* labels = new int[row];
double features_value[row*col] = {1.0,0.8,2.0,1.7,3.0,2.5,4.0,3.6,5.0,4.9,1.0,1.2,2.0,2.5,3.0,3.4,4.0,4.5,5.0,6.0};
int labels_value[row] = {0,0,0,0,0,1,1,1,1,1};
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
features[i][j] = features_value[i*col+j];
}
labels[i] = labels_value[i];
}
char* ret = new char[26];
lr_fit(features, labels, row, col, 200, 0.01, 0.0, 1e-7, 2018, false, 128, 100, ret);
cout << ret << endl;
int* pred = new int[row];
lr_predict(features, row, col, ret, pred);
for(int i = 0; i < row; i++){
cout << pred[i] << ",";
}
}
| 29.347826
| 117
| 0.608148
|
KaiminLai
|
4a6215f7c75deeee00ed31bae53170713730c627
| 691
|
cpp
|
C++
|
pgm15_04.cpp
|
neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C-
|
c9a29d2dd43ad8561e828c25f98de6a8c8f2317a
|
[
"Unlicense"
] | 1
|
2021-07-13T03:58:36.000Z
|
2021-07-13T03:58:36.000Z
|
pgm15_04.cpp
|
neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C-
|
c9a29d2dd43ad8561e828c25f98de6a8c8f2317a
|
[
"Unlicense"
] | null | null | null |
pgm15_04.cpp
|
neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C-
|
c9a29d2dd43ad8561e828c25f98de6a8c8f2317a
|
[
"Unlicense"
] | null | null | null |
//
// This file contains the C++ code from Program 15.4 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm15_04.cpp
//
template <class T>
class StraightInsertionSorter : public InsertionSorter<T>
{
protected:
void DoSort (Array<T>&);
};
template <class T>
void StraightInsertionSorter<T>::DoSort (Array<T>& array)
{
for (unsigned int i = 1; i < n; ++i)
for (unsigned int j = i;
j > 0 && array [j - 1U] > array [j]; --j)
Swap (array [j], array [j - 1U]);
}
| 26.576923
| 80
| 0.643994
|
neharkarvishal
|
4a6582e421a94644738cadd7e41a5ede344a106f
| 3,943
|
cpp
|
C++
|
source/core/render/glfw_windowBuilder.cpp
|
zeplaz/s_liz_rz
|
612ebd97be4d0624b967b1968c45f092ea1c8ddb
|
[
"MIT"
] | null | null | null |
source/core/render/glfw_windowBuilder.cpp
|
zeplaz/s_liz_rz
|
612ebd97be4d0624b967b1968c45f092ea1c8ddb
|
[
"MIT"
] | null | null | null |
source/core/render/glfw_windowBuilder.cpp
|
zeplaz/s_liz_rz
|
612ebd97be4d0624b967b1968c45f092ea1c8ddb
|
[
"MIT"
] | null | null | null |
#include "glfw_windowBuilder.hpp"
#include "../SL_ZER_namespace_def01.hpp"
window_glfw::~window_glfw()
{
this->shutdown();
}
ERRORCODE window_glfw::init()
{
ERRORCODE co = this->setup_context();
if(co != NO_ERROR)
{
#ifdef DEBUG_01
fmt::print("\n##->ERROR CODE create_window::{}\n", error_to_string(co));
#endif
return co;
}
co = this->create_window(SL_ZER::DEFAULT_MAIN_VEWPORT_WIDTH,SL_ZER::DEFAULT_MAIN_VEWPORT_HIGHT,"MAIN_WIN GLFW_TITLE");
if(co != NO_ERROR)
{
#ifdef DEBUG_01
fmt::print("\n##->ERROR CODE create_window::{}\n", error_to_string(co));
#endif
return co;
}
co = SL_ZER::glew_check();
#ifdef DEBUG_01
fmt::print("\n##->ERROR CODE create_window::{}\n", error_to_string(co));
#endif
return co;
}
void window_glfw::shutdown()
{
if(gWindow != nullptr)
glfwDestroyWindow(gWindow);
#ifdef DEBUG_01
fmt::print("\nwindow flfw shutdown likly destutor? showdown\n");
#endif
}
ERRORCODE window_glfw::setup_context()
{
glfwSetErrorCallback(glfw_error_callback);
glewExperimental = GL_TRUE;
//launch gluitInit
if (!glfwInit())
{
fmt::print("\n##ERROR:::glfwinit faild :()\n");
return GWFLW_FAIL_INIT;
}
fmt::print("\nglfwInit compleated\n");
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,5);
#ifdef DEBUG_01
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif
glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);
return NO_ERROR;
}
ERRORCODE window_glfw::create_window(int width, int hight, std::string title)
{
gWindow = glfwCreateWindow(width,hight,title.c_str(), NULL, NULL);
if (gWindow == NULL)
{
fmt::print("ERROR..glfwCreateWindow.window NULL\n");
return GWFLW_FAIL_CREATE;
}
#ifdef DEBUG_01
fmt::print("\nwindow created? compleated\n");
#endif
glfwMakeContextCurrent(gWindow);
glfwSwapInterval(1); // Enable vsync
// this->set_windowSize_callback();
this->set_framebuffer_callback();
glfwSetInputMode(gWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
return NO_ERROR;
}
void window_glfw::set_windowSize_callback()
{
glfwSetWindowSizeCallback(gWindow,[](GLFWwindow* window, int w, int h)
{
glfwMakeContextCurrent(window);
glfwSetWindowSize(window, w, h);
base_window::Resized = true;
});
}
void window_glfw::set_framebuffer_callback()
{
glfwSetFramebufferSizeCallback(gWindow,[](GLFWwindow* window, int w, int h)
{
glViewport(0, 0, w, h);
base_window::Resized = true;
}
);
}
void window_glfw::if_resized()
{
glfwGetWindowSize(gWindow, &frameportbuffer_width, &frameportbuffer_height);
//glfwSetWindowAspectRatio(window, frameportbuffer_width, frameportbuffer_height);
//m_m4Projection = glm::perspective(45.0f, float(frameportbuffer_width)/float(frameportbuffer_height), 0.1f, 1000.0f);
base_window::Resized = false;
}
long double glfw_window_imp::get_window_time_seconds()
{
return glfwGetTime();
}
void glfw_window_imp::render()
{
// int display_w, display_h;
GLFWwindow* l_window = static_cast<GLFWwindow*> (window->window_hanlde());
if(glfwWindowShouldClose(l_window))
{window->shutdown_signa = true;
return;
}
if(base_window::Resized == true)
{window->if_resized();}
glClearColor(SL_ZER::CLEAR_COLOUR_GLM.x * SL_ZER::CLEAR_COLOUR_GLM.w,
SL_ZER::CLEAR_COLOUR_GLM.y * SL_ZER::CLEAR_COLOUR_GLM.w,
SL_ZER::CLEAR_COLOUR_GLM.z * SL_ZER::CLEAR_COLOUR_GLM.w,
SL_ZER::CLEAR_COLOUR_GLM.w);
glClear(GL_COLOR_BUFFER_BIT);
//CALL IMGUI SHDRAW HERE!!!
// ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
/////
glfwSwapBuffers(l_window);
}
void glfw_window_imp::poll_events()
{
glfwPollEvents();
}
| 21.78453
| 120
| 0.676896
|
zeplaz
|
4a688579bfdf2b79e2c9facd2c3ccbb790338e94
| 4,722
|
cpp
|
C++
|
c/wikipedia/page_parse_dequeuer.cpp
|
mmonto7/small-world-graph
|
8ea1015c24065cb71875620b28c66ffb8348dcae
|
[
"MIT"
] | 3
|
2016-05-31T07:23:27.000Z
|
2018-02-16T00:06:04.000Z
|
c/wikipedia/page_parse_dequeuer.cpp
|
mmonto7/small-world-graph
|
8ea1015c24065cb71875620b28c66ffb8348dcae
|
[
"MIT"
] | 2
|
2020-08-31T20:51:20.000Z
|
2021-03-30T18:05:25.000Z
|
c/wikipedia/page_parse_dequeuer.cpp
|
mmonto7/small-world-graph
|
8ea1015c24065cb71875620b28c66ffb8348dcae
|
[
"MIT"
] | 4
|
2015-01-17T07:31:25.000Z
|
2020-08-31T20:49:41.000Z
|
#define _FILE_OFFSET_BITS 64
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <vector>
#include <list>
#include "wikipedia_xml_parser.h"
#include "wiki_parser.h"
#include "wiki_title_validator.h"
#include "s3_helper.h"
#include <signal.h>
#include "string_utils.h"
#include "PageParseQueue.h"
#include <protocol/TBinaryProtocol.h>
#include <transport/TSocket.h>
#include <transport/TTransportUtils.h>
using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
/* Globals */
shared_ptr<S3Helper> __s3;
static size_t __total_pages = 0;
static size_t __pages_imported = 0;
static volatile sig_atomic_t gracefully_quit = 0;
static void handle_sigint(int signal) {
if (!gracefully_quit) {
cout << "Sent Quit Signal" << endl;
gracefully_quit = 1;
} else {
exit(0);
}
}
static void handle_raw_page(const char* title, const char* text, const char* s3_bucket, const char* directory) {
if (title && text) {
stringstream output;
string filename = string(title) + string(".html");
output << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
output << "<html xmlns='http://www.w3.org/1999/xhtml'>\n\t<head>\n\t\t<meta http-equiv='content-type' content='text/html; charset=utf-8' />\n\t\t<title>" << title << "</title>\n\t</head>\n";
output << "\t<body onload=\"document.domain='cruxlux.com';if(parent&&parent!=self){parent.show_from_frame(document.title);}var s=document.createElement('script');s.src='http://assets.cruxlux.com/javascripts/dec.js';document.body.appendChild(s)\">";
char* transformed = wikitext_to_plaintext(text);
if (transformed) {
string result = replace_all(transformed,"\n","\n<p></p>");
output << result;
output << "\n\t</body>\n</html>";
string str_output = output.str();
if (directory) {
chdir(directory);
ofstream file(filename.c_str());
if (file.is_open()) {
file << result;
file.close();
}
}
if (s3_bucket) {
cout << "[P] " << filename << " -> " << s3_bucket << endl;
__s3->put(s3_bucket,filename.c_str(),str_output.c_str(), str_output.size(), "text/html",true);
}
free(transformed);
}
}
}
int main(int argc,char** argv)
{
struct sigaction sig_pipe_action;
memset(&sig_pipe_action,'\0',sizeof(sig_pipe_action));
sig_pipe_action.sa_handler = SIG_IGN;
sigaction(SIGPIPE,&sig_pipe_action,NULL);
signal(SIGINT,handle_sigint);
char* host = (char*) "localhost";
int port = 10010;
int c;
char* s3_bucket = NULL;
char* directory = NULL;
while ((c = getopt(argc, argv, "h:ps:d:")) != -1) {
switch (c) {
case 'h':
host = optarg;
break;
case 'p':
port = atoi(optarg);
if (port == 0) {
cout << "Invalid port" << endl;
exit(-1);
}
break;
case 's':
s3_bucket = optarg;
break;
case 'd':
directory = optarg;
break;
}
}
shared_ptr<TSocket> socket(new TSocket(host,port));
socket->setConnTimeout(1000);
socket->setRecvTimeout(1000);
shared_ptr<TTransport> transport(new TBufferedTransport(socket));
shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
PageParseQueueClient client(protocol);
__s3 = S3Helper::instance();
for(;;) {
try {
if (gracefully_quit == 1) {
cout << "Gracefully Quitting" << endl;
exit(0);
}
transport->open();
vector<RawPage> work_units;
client.dequeue(work_units);
transport->close();
if(work_units.size() > 0) {
int dequeued_amount = work_units.size();
for(vector<RawPage>::const_iterator ii = work_units.begin(); ii != work_units.end(); ii++) {
RawPage page = *ii;
handle_raw_page(page.title.c_str(),page.content.c_str(),s3_bucket,directory);
__pages_imported++;
fprintf(stdout,"\rDequeued %d | Pages Imported: %9d ",(int) dequeued_amount, (int) __pages_imported);
fflush(stdout);
}
} else {
fprintf(stdout,"\rQueue is Empty");
fflush(stdout);
sleep(10);
}
} catch (TException &tx) {
transport->close();
printf("ERROR: %s\n", tx.what());
printf("Sleeping for 10s before retry\n");
sleep(10);
}
}
fprintf(stdout,"\rPages Imported: %9d / %d",(int) __pages_imported, (int) __total_pages);
fflush(stdout);
cout << endl;
return 0;
}
| 28.618182
| 252
| 0.624947
|
mmonto7
|
4a6b66fb771ce459a760bdd25f427650e5893834
| 2,070
|
hpp
|
C++
|
include/fea/ui/sfmlinputbackend.hpp
|
CptAsgard/featherkit
|
84e7a119fcb84cd3a4d8ad9ba9b288abe5c56aa5
|
[
"Zlib"
] | 22
|
2015-01-13T10:49:38.000Z
|
2020-12-23T15:25:59.000Z
|
include/fea/ui/sfmlinputbackend.hpp
|
CptAsgard/featherkit
|
84e7a119fcb84cd3a4d8ad9ba9b288abe5c56aa5
|
[
"Zlib"
] | 27
|
2015-01-11T03:47:27.000Z
|
2015-12-10T17:52:17.000Z
|
include/fea/ui/sfmlinputbackend.hpp
|
CptAsgard/featherkit
|
84e7a119fcb84cd3a4d8ad9ba9b288abe5c56aa5
|
[
"Zlib"
] | 7
|
2015-09-18T15:06:45.000Z
|
2020-02-19T15:12:34.000Z
|
#pragma once
#include <fea/config.hpp>
#include <fea/ui/inputbackend.hpp>
#include <SFML/Window.hpp>
namespace fea
{
class FEA_API SFMLInputBackend : public InputBackend
{
public:
SFMLInputBackend(sf::Window& window);
std::queue<Event> fetchEvents() override;
bool isKeyPressed(Keyboard::Code code) override;
bool isMouseButtonPressed(Mouse::Button b) override;
Vec2I getMouseGlobalPosition() override;
Vec2I getMouseWindowPosition() override;
void setMouseGlobalPosition(int32_t x, int32_t y) override;
void setMouseWindowPosition(int32_t x, int32_t y) override;
bool isGamepadConnected(uint32_t id) override;
uint32_t getGamepadButtonCount(uint32_t id) override;
bool isGamepadButtonPressed(uint32_t id, uint32_t button) override;
bool gamepadHasAxis(uint32_t id, Gamepad::Axis axis) override;
float getGamepadAxisPosition(uint32_t id, Gamepad::Axis axis) override;
void setGamepadThreshold(float threshold) override;
void setKeyRepeatEnabled(bool enabled) override;
private:
Event closed();
Event resized(sf::Event& event);
Event lostFocus();
Event gainedFocus();
Event textEntered(sf::Event& event);
Event keyPressed(sf::Event& event);
Event keyReleased(sf::Event& event);
Event mouseWheelMoved(sf::Event& event);
Event mouseButtonPressed(sf::Event& event);
Event mouseButtonReleased(sf::Event& event);
Event mouseMoved(sf::Event& event);
Event mouseEntered();
Event mouseLeft();
Event gamepadButtonPressed(sf::Event& event);
Event gamepadButtonReleased(sf::Event& event);
Event gamepadMoved(sf::Event& event);
Event gamepadConnected(sf::Event& event);
Event gamepadDisconnected(sf::Event& event);
sf::Window& mWindow;
};
}
| 39.056604
| 83
| 0.629469
|
CptAsgard
|
4a70b65caf147a534596463ea67c3eb62d134bb2
| 3,573
|
cpp
|
C++
|
src/net/https/openssl_server.cpp
|
justinc1/IncludeOS
|
2ce07b04e7a35c8d96e773f041db32a4593ca3d0
|
[
"Apache-2.0"
] | null | null | null |
src/net/https/openssl_server.cpp
|
justinc1/IncludeOS
|
2ce07b04e7a35c8d96e773f041db32a4593ca3d0
|
[
"Apache-2.0"
] | null | null | null |
src/net/https/openssl_server.cpp
|
justinc1/IncludeOS
|
2ce07b04e7a35c8d96e773f041db32a4593ca3d0
|
[
"Apache-2.0"
] | null | null | null |
#include <net/https/openssl_server.hpp>
#include <net/openssl/init.hpp>
#include <net/openssl/tls_stream.hpp>
#include <memdisk>
#define LOAD_FROM_MEMDISK
namespace http
{
// https://gist.github.com/darrenjs/4645f115d10aa4b5cebf57483ec82eca
inline void handle_error(const char* file, int lineno, const char* msg) {
fprintf(stderr, "** %s:%i %s\n", file, lineno, msg);
ERR_print_errors_fp(stderr);
exit(1);
}
#define int_error(msg) handle_error(__FILE__, __LINE__, msg)
static void
tls_load_from_memory(SSL_CTX* ctx,
fs::Buffer cert_buffer,
fs::Buffer key_buffer)
{
auto* cbio = BIO_new_mem_buf(cert_buffer.data(), cert_buffer.size());
auto* cert = PEM_read_bio_X509(cbio, NULL, 0, NULL);
assert(cert != NULL);
SSL_CTX_use_certificate(ctx, cert);
BIO_free(cbio);
auto* kbio = BIO_new_mem_buf(key_buffer.data(), key_buffer.size());
auto* key = PEM_read_bio_RSAPrivateKey(kbio, NULL, 0, NULL);
assert(key != NULL);
SSL_CTX_use_RSAPrivateKey(ctx, key);
BIO_free(kbio);
}
SSL_CTX* tls_init_server(const char* cert_file, const char* key_file)
{
/* create the SSL server context */
auto meth = TLSv1_1_method();
auto* ctx = SSL_CTX_new(meth);
if (!ctx) throw std::runtime_error("SSL_CTX_new()");
int res = SSL_CTX_set_cipher_list(ctx, "AES256-SHA");
assert(res == 1);
#ifdef LOAD_FROM_MEMDISK
auto& filesys = fs::memdisk().fs();
// load CA certificate
auto ca_cert_buffer = filesys.read_file(cert_file);
// load CA private key
auto ca_key_buffer = filesys.read_file(key_file);
// use in SSL CTX
tls_load_from_memory(ctx, ca_cert_buffer, ca_key_buffer);
#else
/* Load certificate and private key files, and check consistency */
int err;
err = SSL_CTX_use_certificate_file(ctx, cert_file, SSL_FILETYPE_PEM);
if (err != 1)
int_error("SSL_CTX_use_certificate_file failed");
/* Indicate the key file to be used */
err = SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM);
if (err != 1)
int_error("SSL_CTX_use_PrivateKey_file failed");
#endif
/* Make sure the key and certificate file match. */
if (SSL_CTX_check_private_key(ctx) != 1)
int_error("SSL_CTX_check_private_key failed");
/* Recommended to avoid SSLv2 & SSLv3 */
SSL_CTX_set_options(ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3);
int error = ERR_get_error();
if (error) {
printf("Status: %s\n", ERR_error_string(error, nullptr));
}
assert(error == SSL_ERROR_NONE);
return ctx;
}
void OpenSSL_server::openssl_initialize(const std::string& certif,
const std::string& key)
{
fs::memdisk().init_fs(
[] (auto err, auto&) {
assert(!err);
});
/** INIT OPENSSL **/
openssl::init();
/** SETUP CUSTOM RNG **/
//openssl::setup_rng();
/** VERIFY RNG **/
openssl::verify_rng();
this->m_ctx = tls_init_server(certif.c_str(), key.c_str());
assert(ERR_get_error() == 0);
}
OpenSSL_server::~OpenSSL_server()
{
SSL_CTX_free((SSL_CTX*) this->m_ctx);
}
void OpenSSL_server::bind(const uint16_t port)
{
tcp_.listen(port, {this, &OpenSSL_server::on_connect});
INFO("HTTPS Server", "Listening on port %u", port);
}
void OpenSSL_server::on_connect(TCP_conn conn)
{
connect(
std::make_unique<openssl::TLS_stream> ((SSL_CTX*) m_ctx, std::make_unique<net::tcp::Connection::Stream>(std::move(conn)))
);
}
} // http
| 30.801724
| 127
| 0.655751
|
justinc1
|
4a759bf0128590cc8ee8c0da81b80a79445de7d0
| 16,447
|
cpp
|
C++
|
src/plugins/dist_matrixops/dist_inverse_operation.cpp
|
kmoham6/phylanx
|
252fa5fbb84acaf6f999410e6823b9f8d6693213
|
[
"BSL-1.0"
] | null | null | null |
src/plugins/dist_matrixops/dist_inverse_operation.cpp
|
kmoham6/phylanx
|
252fa5fbb84acaf6f999410e6823b9f8d6693213
|
[
"BSL-1.0"
] | null | null | null |
src/plugins/dist_matrixops/dist_inverse_operation.cpp
|
kmoham6/phylanx
|
252fa5fbb84acaf6f999410e6823b9f8d6693213
|
[
"BSL-1.0"
] | 1
|
2021-07-25T15:44:01.000Z
|
2021-07-25T15:44:01.000Z
|
// Copyright (c) 2020 Rory Hector
// Copyright (c) 2018-2020 Hartmut Kaiser
//
// 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 <phylanx/config.hpp>
#include <phylanx/execution_tree/annotation.hpp>
#include <phylanx/execution_tree/localities_annotation.hpp>
#include <phylanx/execution_tree/locality_annotation.hpp>
#include <phylanx/execution_tree/meta_annotation.hpp>
#include <phylanx/execution_tree/primitives/node_data_helpers.hpp>
#include <phylanx/execution_tree/tiling_annotations.hpp>
#include <phylanx/ir/node_data.hpp>
#include <phylanx/plugins/dist_matrixops/dist_inverse_operation.hpp>
#include <phylanx/plugins/dist_matrixops/tile_calculation_helper.hpp>
#include <phylanx/util/detail/bad_swap.hpp>
#include <hpx/errors/throw_exception.hpp>
#include <hpx/include/lcos.hpp>
#include <hpx/include/naming.hpp>
#include <hpx/include/util.hpp>
#include <hpx/futures/future.hpp>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <blaze/Math.h>
#include <blaze_tensor/Math.h>
#include <phylanx/util/distributed_matrix.hpp>
namespace phylanx { namespace dist_matrixops { namespace primitives {
constexpr char const* const help_string = R"(
inverse_d(matrix)
Args:
blaze dynamic matrix
Returns:
the inverse of the matrix
)";
execution_tree::match_pattern_type const dist_inverse::match_data = {
hpx::make_tuple("inverse_d", std::vector<std::string>{R"(
inverse_d(
_1_matrix
))"},
&create_dist_inverse,
&execution_tree::create_primitive<dist_inverse>, help_string)};
dist_inverse::dist_inverse(
execution_tree::primitive_arguments_type&& operands,
std::string const& name, std::string const& codename)
: primitive_component_base(std::move(operands), name, codename)
, transferred_bytes_(0)
{
}
std::int64_t dist_inverse::get_transferred_bytes(bool reset) const
{
return hpx::util::get_and_reset_value(transferred_bytes_, reset);
}
// find the first column belonging to a locality
std::size_t getStartCol(std::size_t id, std::size_t n, std::size_t numLocs)
{
std::size_t startCol =
id * (n / numLocs) + ((id < n % numLocs) ? id : (n % numLocs));
return startCol;
}
// find the final column belonging to a locality
std::size_t getEndCol(std::size_t id, std::size_t n, std::size_t numLocs)
{
std::size_t endCol;
if (id == numLocs - 1)
endCol = n;
else
endCol = getStartCol(id + 1, n, numLocs);
return endCol;
}
// find the locality who holds a given column locally
std::size_t findOwningLoc(
std::size_t n, std::size_t numLocs, std::size_t col)
{
std::size_t id;
if (col < (n % numLocs) * (n / numLocs + 1))
id = col / ((n / numLocs) + 1);
else
id = (n % numLocs) +
((col - (n % numLocs) * (n / numLocs + 1)) / (n / numLocs));
return id;
}
// This is where the computation of the inverse is performed.
template <typename T>
execution_tree::primitive_argument_type dist_inverse::distGaussInv(
ir::node_data<T>&& arg,
execution_tree::localities_information&& lhs_localities) const
{
if (lhs_localities.num_dimensions() != 2)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"dist_inverse::distGaussInv",
generate_error_message("the input must be a 2d matrix"));
}
std::size_t thisLocalityID = lhs_localities.locality_.locality_id_;
std::size_t numLocalities = lhs_localities.locality_.num_localities_;
util::distributed_matrix<T> lhs_data(lhs_localities.annotation_.name_,
arg.matrix(), lhs_localities.locality_.num_localities_,
lhs_localities.locality_.locality_id_, &transferred_bytes_);
auto myMatrix = arg.matrix();
std::size_t numRows = myMatrix.rows();
std::size_t numCols = myMatrix.columns();
// Define some additional information on where
// columns lie in the full input
std::size_t startCol = thisLocalityID * (numRows / numLocalities) +
((thisLocalityID < (numRows % numLocalities)) ?
thisLocalityID :
(numRows % numLocalities));
std::size_t endCol = startCol + numCols - 1;
// Definition of this loc's part of a nxn double row-major identity matrix
blaze::DynamicMatrix<double> invMatrix =
blaze::submatrix(blaze::IdentityMatrix<double>(numRows), 0,
startCol, arg.matrix().rows(), arg.matrix().columns());
// Do gaussian elimination to get upper triangular
// matrix with 1's across diagonal
for (std::size_t current_row = 0; current_row != numRows;
current_row++)
{
// Find the locality that owns the pivot element then get the pivot
std::size_t ownid1 =
findOwningLoc(numRows, numLocalities, current_row);
std::size_t localIndexOffset =
current_row - getStartCol(ownid1, numRows, numLocalities);
auto pulledColumn =
lhs_data
.fetch(ownid1, current_row, localIndexOffset, numRows,
localIndexOffset + 1)
.get();
double pivot = pulledColumn(0, 0);
if (numLocalities > 1)
{
hpx::lcos::barrier b2(
"barrierb_" + lhs_localities.annotation_.name_,
lhs_localities.locality_.num_localities_,
lhs_localities.locality_.locality_id_);
b2.wait();
}
// Swaps current row with nearest subsequent row such that
// after swapping A[current_row][current_row] != 0.
if (pivot == 0)
{
bool rowFound = false;
std::size_t checkOffset = 1;
while (current_row + checkOffset != numRows && !rowFound)
{
pivot = pulledColumn(checkOffset, 0);
if (pivot != 0)
{
std::size_t checkRow =
(current_row + checkOffset) % numRows;
for (std::size_t swapCol = 0; swapCol!=numCols; swapCol++)
{
auto temp = (*lhs_data)(current_row, swapCol);
(*lhs_data)(current_row, swapCol) =
(*lhs_data)(checkRow, swapCol);
(*lhs_data)(checkRow, swapCol) = temp;
auto invtemp = invMatrix(current_row, swapCol);
invMatrix(current_row, swapCol) =
invMatrix(checkRow, swapCol);
invMatrix(checkRow, swapCol) = invtemp;
}
rowFound = true;
}
else
checkOffset++;
}
// swap row with nearest subsequent row such that after
// swapping A[i][i] != 0
// if fails, inverse does not exist
if (!rowFound)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"dist_inverse::distGaussInv",
generate_error_message("inverse does not exist"));
}
current_row--; // After swapping, make sure to retry this row
}
else // the inversion has not already failed
{
for (std::size_t col = 0; col != numCols; col++)
{
(*lhs_data)(current_row, col) =
(*lhs_data)(current_row, col) / pivot;
invMatrix(current_row, col) =
invMatrix(current_row, col) / pivot;
}
if (current_row < numRows - 1)
{
for (std::size_t nextRow = current_row + 1;
nextRow != numRows; nextRow++)
{
// Find the locality that owns the pivot element
// then get the pivot
std::size_t ownid2 = findOwningLoc(
numRows, numLocalities, current_row);
std::size_t localIndexOffset2 = current_row -
getStartCol(ownid2, numRows, numLocalities);
auto pulledElement =
lhs_data
.fetch(ownid2, nextRow, localIndexOffset2,
nextRow + 1,
localIndexOffset2 + 1)
.get();
double factor = pulledElement(0, 0);
// Removing this barrier causes errors
if (numLocalities > 1)
{
hpx::lcos::barrier b5("barriere_" +
lhs_localities.annotation_.name_,
lhs_localities.locality_.num_localities_,
lhs_localities.locality_.locality_id_);
b5.wait();
}
for (std::size_t nextCol = 0;
nextCol != numCols; nextCol++)
{
(*lhs_data)(nextRow, nextCol) =
(*lhs_data)(nextRow, nextCol) -
(factor *
(*lhs_data)(current_row, nextCol));
invMatrix(nextRow, nextCol) =
invMatrix(nextRow, nextCol) -
(factor * invMatrix(current_row, nextCol));
}
}
}
}
}
// Back substitution phase, going from bottom to top
// in matrix zeroing out columns except diagonal
for (std::size_t zeroCol = numRows - 1; zeroCol != 0; zeroCol--)
{
for (std::int64_t row = zeroCol - 1; row != -1; row--)
{
// Find the locality that owns the pivot element then get the pivot
std::size_t ownid3 =
findOwningLoc(numRows, numLocalities, zeroCol);
std::size_t localIndexOffset3 =
zeroCol -
getStartCol(ownid3, numRows, numLocalities);
auto pulledElement =
lhs_data
.fetch(ownid3, row, localIndexOffset3, row + 1,
localIndexOffset3 + 1)
.get();
double factor = pulledElement(0, 0);
// Removing this barrier causes errors
if (numLocalities > 1)
{
hpx::lcos::barrier b8(
"barrierg_" + lhs_localities.annotation_.name_,
lhs_localities.locality_.num_localities_,
lhs_localities.locality_.locality_id_);
b8.wait();
}
for (std::size_t col = 0; col != numCols; col++)
{
myMatrix(row, col) = myMatrix(row, col) -
(factor * myMatrix(zeroCol, col));
invMatrix(row, col) = invMatrix(row, col) -
(factor * invMatrix(zeroCol, col));
}
}
}
// Prepare the output
execution_tree::primitive_argument_type result =
execution_tree::primitive_argument_type{invMatrix};
execution_tree::annotation ann{ir::range("tile",
ir::range("rows", static_cast<std::int64_t>(0),
static_cast<std::int64_t>(numRows)),
ir::range("columns", static_cast<std::int64_t>(startCol),
static_cast<std::int64_t>(endCol+1)))};
// Generate new tiling annotation for the result vector
execution_tree::tiling_information_2d tile_info(
ann, name_, codename_);
++lhs_localities.annotation_.generation_;
auto locality_ann = lhs_localities.locality_.as_annotation();
result.set_annotation(
execution_tree::localities_annotation(locality_ann,
tile_info.as_annotation(name_, codename_),
lhs_localities.annotation_, name_, codename_),
name_, codename_);
return result;
}
// This is where the computation of the inverse should be performed.
execution_tree::primitive_argument_type dist_inverse::distGaussInv(
execution_tree::primitive_argument_type&& lhs) const
{
using namespace execution_tree;
execution_tree::localities_information lhs_localities =
extract_localities_information(lhs, name_, codename_);
switch (extract_numeric_value_dimension(lhs, name_, codename_))
{
case 2:
// Do the inverse operation
return distGaussInv(
extract_numeric_value(std::move(lhs), name_, codename_),
std::move(lhs_localities));
default:
HPX_THROW_EXCEPTION(hpx::bad_parameter,
" dist_inverse::distGaussInv",
generate_error_message("left hand side operand has unsupported "
"number of dimensions"));
}
}
// Call the evaluation function
hpx::future<execution_tree::primitive_argument_type> dist_inverse::eval(
execution_tree::primitive_arguments_type const& operands,
execution_tree::primitive_arguments_type const& args,
execution_tree::eval_context ctx) const
{
using namespace execution_tree;
// Check to make sure there is exactly one item to invert
if (operands.size() != 1)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter, "dist_inverse::eval",
generate_error_message(
"the gaussian inverse operation primitive requires"
"exactly one operand"));
}
// Check if there are no valid operands
if (!valid(operands[0]))
{
HPX_THROW_EXCEPTION(hpx::bad_parameter, "dist_inverse::eval",
generate_error_message(
"the gaussian_inverse_operation primitive requires that "
"the arguments given by the operands array is valid"));
}
// Get a future to the result of the actual computation
auto this_ = this->shared_from_this();
return hpx::dataflow(hpx::launch::sync,
hpx::util::unwrapping(
[this_ = std::move(this_)](primitive_arguments_type&& args)
-> primitive_argument_type {
return this_->distGaussInv(std::move(args[0]));
}),
execution_tree::primitives::detail::map_operands(operands,
execution_tree::functional::value_operand{}, args, name_,
codename_, std::move(ctx)));
}
}}}
| 41.743655
| 87
| 0.516021
|
kmoham6
|
4a764191c7adbcb8350eed177c1f465a50fd4279
| 6,780
|
cpp
|
C++
|
Tetris Source/BlockOverlay.cpp
|
mattacer/Tetris
|
2a553ec955d7742c9797504464f63af05e981663
|
[
"MIT"
] | null | null | null |
Tetris Source/BlockOverlay.cpp
|
mattacer/Tetris
|
2a553ec955d7742c9797504464f63af05e981663
|
[
"MIT"
] | null | null | null |
Tetris Source/BlockOverlay.cpp
|
mattacer/Tetris
|
2a553ec955d7742c9797504464f63af05e981663
|
[
"MIT"
] | 1
|
2019-02-07T03:29:13.000Z
|
2019-02-07T03:29:13.000Z
|
/*
BlockOverlay.cpp
Defines the methods and members of the BlockOverlay class.
*/
#include "BlockOverlay.h"
//Default BlockOverlay class constructor
BlockOverlay::BlockOverlay(){
blocks = nullptr;
blockCount = 0;
this->clearGrid();
}
//Constructor that accepts a pointer to a set of Block instances for initiation
BlockOverlay::BlockOverlay(Block* newBlocks, int count){
blocks = new Block[count];
for (int i = 0; i < blockCount; i++){
blocks[i] = newBlocks[i];
}
blockCount = count;
this->updateGrid();
}
//BlockOverlay Class Destructor
BlockOverlay::~BlockOverlay(){
delete[] blocks;
}
//Draws the BlockOverlay instance by calling each Block instances draw method
void BlockOverlay::draw(){
for (int i = 0; i < blockCount; i++){
blocks[i].draw();
}
}
//Deletes the block instances, sets the block count to zero, and calls the clearGrid method
//To be called when a new game is started
void BlockOverlay::clear(){
delete[] blocks;
blocks = nullptr;
blockCount = 0;
this->clearGrid();
}
//Adds the Block instances of a Tetrimino instance to the calling BlockOverlay instance
void BlockOverlay::addTetriminoBlocks(Tetrimino* blockSource){
Block* tempBlocks = blocks;
blocks = new Block[blockCount + blockSource->getBlockCount()];
for (int i = 0; i < blockCount; i++){
blocks[i] = tempBlocks[i];
}
delete[] tempBlocks;
for (int i = 0; i < blockSource->getBlockCount(); i++){
blocks[blockCount + i] = blockSource->getBlock(i);
}
blockCount = blockCount + blockSource->getBlockCount();
this->updateGrid();
}
//Sets all boolean values in the grid array to false
void BlockOverlay::clearGrid(){
for (int i = 0; i < BLOCKS_PER_GRID_WIDTH; i++){
for (int j = 0; j < BLOCKS_PER_GRID_HEIGHT; j++){
grid[i][j] = false;
}
}
}
//Iterates through all Block instances in the calling BlockOverlay instance,
//setting their corresponding location in the grid array as true, when false
//Returns false if two blocks have the same location
//Returns true when blocks have unique locations
bool BlockOverlay::updateGrid(){
this->clearGrid();
int indexX, indexY = 0;
for (int i = 0; i < blockCount; i++){
indexX = blocks[i].getX() / BLOCK_LENGTH;
indexY = blocks[i].getY() / BLOCK_LENGTH;
if (grid[indexX][indexY] == false){
grid[indexX][indexY] = true;
} else {
return false;
}
}
return true;
}
//Returns true when a complete horizontal line of blocks exists, otherwise returns false
bool BlockOverlay::linesPresent(){
for (int i = BLOCKS_PER_GRID_HEIGHT - 1; i >= 0; i--){
for (int j = 0; j < BLOCKS_PER_GRID_WIDTH; j++){
if (grid[j][i] == false){
break;
}
if (j == BLOCKS_PER_GRID_WIDTH - 1 && grid[j][i] == true){
return true;
}
}
}
return false;
}
//Finds the lowest occuring line of blocks, then deletes blocks on that line
//Moves blocks down once, if they are above that line
void BlockOverlay::clearLowestLine(){
int lowestLine = 0;
int indexX = 0;
int indexY = 0;
for (int i = BLOCKS_PER_GRID_HEIGHT - 1; i >= 0 && i >= lowestLine; i--){
for (int j = 0; j < BLOCKS_PER_GRID_WIDTH; j++){
if (grid[j][i] == false){
break;
}
if (j == BLOCKS_PER_GRID_WIDTH - 1 && grid[j][i] == true){
lowestLine = i;
break;
}
}
}
Block* tempBlocks = blocks;
blocks = new Block[blockCount - BLOCKS_PER_GRID_WIDTH];
int j = 0;
for (int i = 0; i < blockCount; i++){
indexY = tempBlocks[i].getY() / BLOCK_LENGTH;
if (indexY > lowestLine){
blocks[j] = tempBlocks[i];
j++;
}
else if (indexY < lowestLine){
tempBlocks[i].moveDown();
blocks[j] = tempBlocks[i];
j++;
}
}
blockCount -= BLOCKS_PER_GRID_WIDTH;
delete[] tempBlocks;
this->updateGrid();
}
//Tests whether a Tetrimino instance will go out of boundary or overlap the BlockOverlay blocks, if it is rotated
//Returns true if a rotation will not cause the tetrimino to overlap or go out of bounds
bool BlockOverlay::tetriminoCanRotate(Tetrimino* current){
Tetrimino* tempTetrimino = current->clone();
tempTetrimino->rotate();
if (withinBoundary(tempTetrimino)){
return !checkForOverlap(tempTetrimino);
} else {
return false;
}
}
//Tests whether a Tetrimino instance will go out of boundary or overlap the BlockOverlay blocks, when moved left
//Returns true if a left movement will not cause the tetrimino to overlap or go out of bounds
bool BlockOverlay::tetriminoCanMoveLeft(Tetrimino* current){
Tetrimino* tempTetrimino = current->clone();
tempTetrimino->moveLeft();
if (withinBoundary(tempTetrimino)){
return !checkForOverlap(tempTetrimino);
} else {
return false;
}
}
//Tests whether a Tetrimino instance will go out of boundary or overlap the BlockOverlay blocks, when moved right
//Returns true if a right movement will not cause the tetrimino to overlap or go out of bounds
bool BlockOverlay::tetriminoCanMoveRight(Tetrimino* current){
Tetrimino* tempTetrimino = current->clone();
tempTetrimino->moveRight();
if (withinBoundary(tempTetrimino)){
return !checkForOverlap(tempTetrimino);
} else {
return false;
}
}
//Tests whether a Tetrimino instance will go out of boundary or overlap the BlockOverlay blocks, when moved down
//Returns true if a downward movement will not cause the tetrimino to overlap or go out of bounds
bool BlockOverlay::tetriminoCanMoveDown(Tetrimino* current){
Tetrimino* tempTetrimino = current->clone();
tempTetrimino->moveDown();
if (withinBoundary(tempTetrimino)){
return !checkForOverlap(tempTetrimino);
} else {
return false;
}
}
//Tests a Tetrimino instance for Block instances that overlap the blocks of the BlockOverlay instance
//Returns true if overlap occurs, otherwise returns false
bool BlockOverlay::checkForOverlap(Tetrimino* tetrimino){
int x, y;
for (int i = 0; i < tetrimino->getBlockCount(); i++){
x = tetrimino->getBlock(i).getX() / BLOCK_LENGTH;
y = tetrimino->getBlock(i).getY() / BLOCK_LENGTH;
if (grid[x][y] == true){
return true;
}
}
return false;
}
//Tests whether a Tetrimino instance is within the play area boundaries
//Returns false if a block is outside the boundaries, otherwise returns true
bool BlockOverlay::withinBoundary(Tetrimino* tetrimino){
int x, y;
for (int i = 0; i < tetrimino->getBlockCount(); i++){
x = tetrimino->getBlock(i).getX();
y = tetrimino->getBlock(i).getY();
if (!(x >= 0 && x <= BLOCK_GRID_WIDTH - BLOCK_LENGTH && y >= 0 && y <= HEIGHT - BLOCK_LENGTH)){
return false;
}
}
return true;
}
int BlockOverlay::getBlockCount(){
return blockCount;
}
Block BlockOverlay::getBlock(int index){
return blocks[index];
}
| 30.403587
| 114
| 0.683628
|
mattacer
|
4a7a0371f8f2bc0e538528e06a14651e16ac9dcb
| 1,325
|
hpp
|
C++
|
include/daq_ni.hpp
|
gadzooks00/AbsoluteThreshold_AIMS-Fork-
|
aa26ae3af9b165b3d2c95e472c9a20faa302a0c2
|
[
"MIT"
] | null | null | null |
include/daq_ni.hpp
|
gadzooks00/AbsoluteThreshold_AIMS-Fork-
|
aa26ae3af9b165b3d2c95e472c9a20faa302a0c2
|
[
"MIT"
] | null | null | null |
include/daq_ni.hpp
|
gadzooks00/AbsoluteThreshold_AIMS-Fork-
|
aa26ae3af9b165b3d2c95e472c9a20faa302a0c2
|
[
"MIT"
] | null | null | null |
/*
File: daq_ni.cpp
________________________________
Author(s): Zane Zook (gadzooks@rice.edu)
This file defines the DaqNI class which holds all the
lower level commands sent to the National Instruments DAQ
used for this experiment set. This specific version is
customized to work with the two ATI sensors hooked up
to the PCIe-6323 board connected to the two ATI Nano 25
sensors. Uses MEL's development ATIsensor class.
*/
#ifndef DAQNI
#define DAQNI
/***********************************************************
******************** LIBRARY IMPORT ************************
************************************************************/
// libraries for MEL
#include <MEL/Logging/Csv.hpp>
#include <MEL/Daq/Input.hpp>
// C libraries
#include "NIDAQmx.h"
/***********************************************************
****************** CLASS DECLARATION ***********************
************************************************************/
class DaqNI : public mel::AnalogInput, mel::NonCopyable
{
private:
// member variables
TaskHandle task_handle_; // creates a new task_handle_
signed long error_;
signed long read_;
char error_buffer_[2048] = { '\0' };
public:
// constructor
DaqNI();
~DaqNI();
// DAQ update functions
bool update();
bool update_channel(mel::uint32 channel_number);
};
#endif DAQNI
| 27.604167
| 61
| 0.563019
|
gadzooks00
|
4a81b95fe28284ed008d5d7bf2e8f4bdcfc653f9
| 196
|
cc
|
C++
|
experimental/proto_test.cc
|
romange/beeri
|
60718d0f3133fffdf1500f8844852a79c91d8351
|
[
"BSD-2-Clause"
] | 2
|
2015-01-07T06:34:25.000Z
|
2019-01-25T10:11:24.000Z
|
experimental/proto_test.cc
|
romange/beeri
|
60718d0f3133fffdf1500f8844852a79c91d8351
|
[
"BSD-2-Clause"
] | null | null | null |
experimental/proto_test.cc
|
romange/beeri
|
60718d0f3133fffdf1500f8844852a79c91d8351
|
[
"BSD-2-Clause"
] | 1
|
2019-01-25T10:11:28.000Z
|
2019-01-25T10:11:28.000Z
|
#include <gtest/gtest.h>
#include "experimental/addressbook.pb.h"
class ProtoTest : public testing::Test {
};
TEST_F(ProtoTest, Basic) {
tutorial::Person person;
person.set_name("Roman");
}
| 17.818182
| 40
| 0.719388
|
romange
|
4a8a3115f5e63f4538f17364ef7d8aaef909b938
| 194
|
cpp
|
C++
|
Source/GCE/Game/Death/PawnDeathComponent.cpp
|
ssapo/GCE
|
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
|
[
"MIT"
] | 2
|
2019-07-28T13:30:14.000Z
|
2019-11-22T08:14:28.000Z
|
Source/GCE/Game/Death/PawnDeathComponent.cpp
|
ssapo/GCE
|
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
|
[
"MIT"
] | null | null | null |
Source/GCE/Game/Death/PawnDeathComponent.cpp
|
ssapo/GCE
|
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
|
[
"MIT"
] | 1
|
2019-07-07T13:39:08.000Z
|
2019-07-07T13:39:08.000Z
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "PawnDeathComponent.h"
UPawnDeathComponent::UPawnDeathComponent()
{
ChessClass = EChessClass::Pawn;
}
| 19.4
| 78
| 0.783505
|
ssapo
|
4a8a994a09e35902ff3645293eab9b0ea6cede65
| 535
|
cpp
|
C++
|
C++/Clase 8/Clase8.1.cpp
|
Rofernweh/UDPpl
|
da448091396b3f567f83e2964e8db97f6b8382bc
|
[
"MIT"
] | null | null | null |
C++/Clase 8/Clase8.1.cpp
|
Rofernweh/UDPpl
|
da448091396b3f567f83e2964e8db97f6b8382bc
|
[
"MIT"
] | 1
|
2021-06-29T05:16:19.000Z
|
2021-06-29T05:16:19.000Z
|
C++/Clase 8/Clase8.1.cpp
|
Rofernweh/UDPpl
|
da448091396b3f567f83e2964e8db97f6b8382bc
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
using namespace std;
/*Se deja caer un objeto.
Se pide al usuario un entero n,donde n es la cantidad de segundos que el usuario desea medir.
Imprimir en pantalla cuanto ha caído el objeto en cada segundo menor a n. */
int main ()
{
float n;
float distancia;
cout << "Ingrese el tiempo que desea medir en segundos: \n";
cin >> n;
for(i=0; i<=n;i++)
{
distancia= 0.5*9.8*(pow(n,n));
cout << "En el segundo\t" << i << " se recorrieron " << distancia << " metros.";
}
}
| 28.157895
| 95
| 0.635514
|
Rofernweh
|
4a8bc14b35942e5905161e0890643f8a0fc2439f
| 8,323
|
inl
|
C++
|
include/volt/math/vec3.inl
|
voltengine/volt
|
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
|
[
"MIT"
] | null | null | null |
include/volt/math/vec3.inl
|
voltengine/volt
|
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
|
[
"MIT"
] | null | null | null |
include/volt/math/vec3.inl
|
voltengine/volt
|
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
|
[
"MIT"
] | null | null | null |
#include "../util/util.hpp"
namespace volt::math {
template<scalar T>
const vec3<T> vec3<T>::zero(0);
template<scalar T>
const vec3<T> vec3<T>::one(1);
template<scalar T>
const vec3<T> vec3<T>::left(-1, 0, 0);
template<scalar T>
const vec3<T> vec3<T>::right(1, 0, 0);
template<scalar T>
const vec3<T> vec3<T>::down(0, -1, 0);
template<scalar T>
const vec3<T> vec3<T>::up(0, 1, 0);
template<scalar T>
const vec3<T> vec3<T>::forward(0, 0, -1);
template<scalar T>
const vec3<T> vec3<T>::backward(0, 0, 1);
template<scalar T>
constexpr vec3<T>::vec3() : vec3(0) {}
template<scalar T>
constexpr vec3<T>::vec3(T all) :
x(all), y(all), z(all) {}
template<scalar T>
constexpr vec3<T>::vec3(T x, T y, T z) :
x(x), y(y), z(z) {}
template<scalar T>
template<scalar U>
constexpr vec3<T>::vec3(const vec3<U> &other) :
x(other.x), y(other.y), z(other.z) {}
template<scalar T>
template<scalar U>
constexpr vec3<T>::vec3(const vec2<U> &other, float z) :
x(other.x), y(other.y), z(z) {}
#pragma region Operators
template<scalar T>
template<scalar U>
vec3<T>::operator vec2<U>() const {
return vec2<U>(x, y);
}
template<scalar U>
std::ostream &operator<<(std::ostream &lhs, const vec3<U> &rhs) {
return lhs << '[' <<
util::to_string(rhs.x) << ", " <<
util::to_string(rhs.y) << ", " <<
util::to_string(rhs.z) << ']';
}
template<scalar T>
T &vec3<T>::operator[](size_t index) {
return data[index];
}
template<scalar T>
const T &vec3<T>::operator[](size_t index) const {
return data[index];
}
template<scalar T>
vec3<T> vec3<T>::operator-() const {
return vec3<T>(-x, -y, -z);
}
template<boolean U>
vec3<bool> operator!(const vec3<U> &vec) {
return vec3<bool>(!vec.x, !vec.y, !vec.z);
}
template<scalar T>
template<scalar U>
vec3<bool> vec3<T>::operator==(const vec3<U> &rhs) const {
return vec3<bool>(x == rhs.x, y == rhs.y, z == rhs.z);
}
template<scalar T>
template<scalar U>
vec3<bool> vec3<T>::operator!=(const vec3<U> &rhs) const {
return vec3<bool>(x != rhs.x, y != rhs.y, z != rhs.z);
}
template<scalar T>
template<scalar U>
vec3<bool> vec3<T>::operator<=(const vec3<U> &rhs) const {
return vec3<bool>(x <= rhs.x, y <= rhs.y, z <= rhs.z);
}
template<scalar T>
template<scalar U>
vec3<bool> vec3<T>::operator>=(const vec3<U> &rhs) const {
return vec3<bool>(x >= rhs.x, y >= rhs.y, z >= rhs.z);
}
template<scalar T>
template<scalar U>
vec3<bool> vec3<T>::operator<(const vec3<U> &rhs) const {
return vec3<bool>(x < rhs.x, y < rhs.y, z < rhs.z);
}
template<scalar T>
template<scalar U>
vec3<bool> vec3<T>::operator>(const vec3<U> &rhs) const {
return vec3<bool>(x > rhs.x, y > rhs.y, z > rhs.z);
}
// Vector + Vector
template<scalar T>
template<scalar U, scalar Ret>
vec3<Ret> vec3<T>::operator+(const vec3<U> &rhs) const {
return vec3<Ret>(x + rhs.x, y + rhs.y, z + rhs.z);
}
template<scalar T>
template<scalar U, scalar Ret>
vec3<Ret> vec3<T>::operator-(const vec3<U> &rhs) const {
return vec3<Ret>(x - rhs.x, y - rhs.y, z - rhs.z);
}
template<scalar T>
template<scalar U, scalar Ret>
vec3<Ret> vec3<T>::operator*(const vec3<U> &rhs) const {
return vec3<Ret>(x * rhs.x, y * rhs.y, z * rhs.z);
}
template<scalar T>
template<scalar U, scalar Ret>
vec3<Ret> vec3<T>::operator/(const vec3<U> &rhs) const {
return vec3<Ret>(x / rhs.x, y / rhs.y, z / rhs.z);
}
template<scalar T>
template<scalar U>
vec3<T> &vec3<T>::operator+=(const vec3<U> &rhs) {
return *this = *this + rhs;
}
template<scalar T>
template<scalar U>
vec3<T> &vec3<T>::operator-=(const vec3<U> &rhs) {
return *this = *this - rhs;
}
template<scalar T>
template<scalar U>
vec3<T> &vec3<T>::operator*=(const vec3<U> &rhs) {
return *this = *this * rhs;
}
template<scalar T>
template<scalar U>
vec3<T> &vec3<T>::operator/=(const vec3<U> &rhs) {
return *this = *this / rhs;
}
// Vector + Scalar
template<scalar T>
template<scalar U, scalar Ret>
vec3<Ret> vec3<T>::operator*(U rhs) const {
return vec3<Ret>(x * rhs, y * rhs, z * rhs);
}
template<scalar T>
template<scalar U, scalar Ret>
vec3<Ret> vec3<T>::operator/(U rhs) const {
return vec3<Ret>(x / rhs, y / rhs, z / rhs);
}
template<scalar T>
template<scalar U>
vec3<T> &vec3<T>::operator*=(U rhs) {
return *this = *this * rhs;
}
template<scalar T>
template<scalar U>
vec3<T> &vec3<T>::operator/=(U rhs) {
return *this = *this / rhs;
}
// Scalar + Vector
template<scalar L, scalar R, scalar Ret = std::common_type_t<L, R>>
vec3<Ret> operator*(L lhs, const vec3<R> &rhs) {
return vec3<Ret>(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z);
}
#pragma endregion
template<boolean T>
bool all(const vec3<T> &vec) {
return vec.x && vec.y && vec.z;
}
template<boolean T>
bool any(const vec3<T> &vec) {
return vec.x || vec.y || vec.z;
}
template<scalar L, scalar R, scalar Ret>
vec3<Ret> cross(const vec3<L> &lhs, const vec3<R> &rhs) {
return vec3<Ret>(
(lhs.y * rhs.z) - (lhs.z * rhs.y),
(lhs.z * rhs.x) - (lhs.x * rhs.z),
(lhs.x * rhs.y) - (lhs.y * rhs.x)
);
}
template<scalar A, scalar B, floating_point Ret>
Ret distance(const vec3<A> &a, const vec3<B> &b) {
return length(a - b);
}
template<scalar A, scalar B, scalar Ret>
Ret dot(const vec3<A> &a, const vec3<B> &b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
template<scalar T, scalar Epsilon>
bool is_normalized(const vec3<T> &vec, Epsilon epsilon) {
return is_approx(dot(vec, vec), 1, epsilon);
}
template<floating_point T>
T length(const vec3<T> &vec) {
return sqrt(dot(vec, vec));
}
template<floating_point T>
vec3<T> normalize(const vec3<T> &vec) {
return vec * (1 / length(vec));
}
template<floating_point To, floating_point From, scalar Ret>
vec3<Ret> proj(const vec3<To> &to, const vec3<From> &from) {
return (dot(to, from) / dot(to, to)) * to;
}
template<scalar Incident, scalar Normal, scalar Ret>
vec3<Ret> reflect(const vec3<Incident> &incident,
const vec3<Normal> &normal) {
return incident - 2 * dot(normal, incident) * normal;
}
template<scalar Incident, scalar Normal,
scalar IorRatio, scalar Ret>
vec3<Ret> refract(const vec3<Incident> &incident,
const vec3<Normal> &normal, IorRatio ior_ratio) {
Ret cos_theta = dot(incident, normal);
Ret k = 1 - ior_ratio * ior_ratio * (1 - cos_theta * cos_theta);
if (k < 0)
return vec3<Ret>::zero;
return ior_ratio * incident -
(ior_ratio * cos_theta + sqrt(k)) * normal;
}
#pragma region Component-Wise Math Wrappers
template<scalar X>
vec3<X> abs(const vec3<X> &x) {
return vec3<X>(abs(x.x), abs(x.y), abs(x.z));
}
template<floating_point X>
vec3<X> fract(const vec3<X> &x) {
return vec3<X>(fract(x.x), fract(x.y), fract(x.z));
}
template<scalar From, scalar To, scalar Weight, scalar Ret>
vec3<Ret> lerp(const vec3<From> &from, const vec3<To> &to, const vec3<Weight> &weight) {
return vec3<Ret>(
lerp(from.x, to.x, weight.x),
lerp(from.y, to.y, weight.y),
lerp(from.z, to.z, weight.z));
}
template<scalar A, scalar B, scalar Ret>
vec3<Ret> max(const vec3<A> &a, const vec3<B> &b) {
return vec3<Ret>(
max(a.x, b.x),
max(a.y, b.y),
max(a.z, b.z));
}
template<scalar A, scalar B, scalar... Others, scalar Ret>
vec3<Ret> max(const vec3<A> &a, const vec3<B> &b,
const vec3<Others> &...others) {
return max(max(a, b), others...);
}
template<scalar A, scalar B, scalar Ret>
vec3<Ret> min(const vec3<A> &a, const vec3<B> &b) {
return vec3<Ret>(
min(a.x, b.x),
min(a.y, b.y),
min(a.z, b.z));
}
template<scalar A, scalar B, scalar... Others, scalar Ret>
vec3<Ret> min(const vec3<A> &a, const vec3<B> &b,
const vec3<Others> &...others) {
return min(min(a, b), others...);
}
template<scalar X, scalar Y, scalar Ret>
vec3<Ret> mod(const vec3<X> &x, const vec3<Y> &y) {
return vec3<Ret>(
mod(x.x, y.x),
mod(x.y, y.y),
mod(x.z, y.z));
}
template<scalar X, scalar Power, scalar Ret>
vec3<Ret> pow(const vec3<X> &x, const vec3<Power> &power) {
return vec3<Ret>(
math::pow(x.x, power.x),
math::pow(x.y, power.y),
math::pow(x.z, power.z));
}
template<scalar X>
vec3<X> saturate(const vec3<X> &x) {
return vec3<X>(
saturate(x.x),
saturate(x.y),
saturate(x.z));
}
#pragma endregion
}
namespace std {
template<volt::math::scalar T>
std::size_t hash<volt::math::vec3<T>>::operator()(volt::math::vec3<T> vec) const {
return (static_cast<size_t>(vec.x) * 859433 ^
static_cast<size_t>(vec.y)) * 19937 ^
static_cast<size_t>(vec.z);
}
}
| 23.055402
| 88
| 0.641115
|
voltengine
|
4a905e489392eb0b97fbfd773b15341812e1a028
| 305
|
hpp
|
C++
|
tests/regex/regex_full.hpp
|
olegpublicprofile/stdfwd
|
19671bcc8e53bd4c008f07656eaf25a22495e093
|
[
"MIT"
] | 11
|
2021-03-15T07:06:21.000Z
|
2021-09-27T13:54:25.000Z
|
tests/regex/regex_full.hpp
|
olegpublicprofile/stdfwd
|
19671bcc8e53bd4c008f07656eaf25a22495e093
|
[
"MIT"
] | null | null | null |
tests/regex/regex_full.hpp
|
olegpublicprofile/stdfwd
|
19671bcc8e53bd4c008f07656eaf25a22495e093
|
[
"MIT"
] | 1
|
2021-06-24T10:46:46.000Z
|
2021-06-24T10:46:46.000Z
|
#pragma once
//------------------------------------------------------------------------------
namespace regex_tests {
//------------------------------------------------------------------------------
void run_full();
//------------------------------------------------------------------------------
}
| 21.785714
| 80
| 0.137705
|
olegpublicprofile
|
4a916439eaae0711688369191b735ef4483c6e05
| 82,405
|
cpp
|
C++
|
sdl1/goonies/GO_character.cpp
|
pdpdds/sdldualsystem
|
d74ea84cbea705fef62868ba8c693bf7d2555636
|
[
"BSD-2-Clause"
] | null | null | null |
sdl1/goonies/GO_character.cpp
|
pdpdds/sdldualsystem
|
d74ea84cbea705fef62868ba8c693bf7d2555636
|
[
"BSD-2-Clause"
] | null | null | null |
sdl1/goonies/GO_character.cpp
|
pdpdds/sdldualsystem
|
d74ea84cbea705fef62868ba8c693bf7d2555636
|
[
"BSD-2-Clause"
] | null | null | null |
#ifdef KITSCHY_DEBUG_MEMORY
#include "debug_memorymanager.h"
#endif
#ifdef _WIN32
#include "windows.h"
#endif
#include "math.h"
#include "stdlib.h"
#include "string.h"
#include "GL/gl.h"
#include "GL/glu.h"
#include "SDL.h"
#include "SDL_image.h"
#include "SDL_mixer.h"
#include "List.h"
#include "auxiliar.h"
#include "2DCMC.h"
#include "Symbol.h"
#include "GLTile.h"
#include "keyboardstate.h"
#include "VirtualController.h"
#include "GLTManager.h"
#include "SoundManager.h"
#include "SFXManager.h"
#include "GObject.h"
#include "GO_character.h"
#include "GO_enemy.h"
#include "GO_skulldoor.h"
#include "GO_item.h"
#include "GO_bridge.h"
#include "GMap.h"
#include "TheGooniesCtnt.h"
#include "GObjectCreator.h"
// #include "debug.h"
extern int difficulty;
extern int score;
GO_character::GO_character(int x, int y, int sfx_volume, int facing) : GObject(x, y, sfx_volume)
{
m_class = new Symbol(character_symbol);
if (facing == 0)
m_state = CSTATE_STANDING_LEFT;
else
m_state = CSTATE_STANDING_RIGHT;
m_last_state = m_state;
m_state_cycle = 0;
m_punch_cycle = 0;
m_step_cycle = 0;
m_layer = 2;
m_walking_channel = -1;
m_climbing_channel = -1;
m_facebefore_vine = 0;
m_requested_room = false;
m_requested_room_x = 0;
m_requested_room_y = 0;
m_requested_room_door = 0;
m_player_hit_counter = 0;
m_walking_speed = PLAYER_SPEED;
m_energy = 64;
m_experience = 0;
m_key = false;
m_goonies_rescued = 0;
for (int i = 0; i < 7; ++i) m_rescued_goonies[i] = false;
m_last_pick = 0;
m_last_hit = 0;
m_last_hit_by = 0;
m_camefrom = 0;
m_turning_counter = 0;
// item variables:
m_yellowhelmet_status = m_yellowhelmet_timer = 0;
m_greycoat_status = m_greycoat_timer = 0;
m_yellowcoat_timer = 0;
m_hammer_status = 0;
m_greenbook_status = 0;
m_redbook_status = 0;
m_lightbluebook_status = 0;
m_bluebook_status = m_bluebook_timer = 0;
m_greencoat_timer = 0;
m_whitebook_status = 0;
m_yellowshield_status = m_yellowshield_timer = 0;
m_lightbluecoat_timer = 0;
m_whiteshield_status = m_whiteshield_timer = 0;
m_lightbluehelmet_status = m_lightbluehelmet_timer = 0;
m_yellowbook_status = m_yellowbook_timer = 0;
m_purpleshield_status = m_purpleshield_timer = 0;
m_clock_timer = 0;
m_bluebadbook_nghosts = 0;
}
GO_character::~GO_character()
{
if (m_last_pick != 0)
delete m_last_pick;
if (m_last_hit != 0)
delete m_last_hit;
if (m_last_hit_by != 0)
delete m_last_hit_by;
if (m_camefrom != 0)
delete m_camefrom;
}
bool GO_character::cycle(VirtualController *v, GMap *map, int layer, TheGoonies *game, GLTManager *GLTM, SFXManager *SFXM)
{
int salute = (m_state_cycle % 615);
m_previous_state = m_state;
if (m_last_tile_used == 0)
m_last_tile_used = GLTM->get
("ob_character-l1");
// reset the variables for script conditions:
m_last_state = m_state;
if (m_last_pick != 0)
delete m_last_pick;
m_last_pick = 0;
if (m_last_hit != 0)
delete m_last_hit;
m_last_hit = 0;
if (m_last_hit_by != 0)
delete m_last_hit_by;
m_last_hit_by = 0;
#ifdef __DEBUG_MESSAGES
output_debug_message("Character, %i (%f,%f)\n", m_state, m_x, m_y);
#endif
if (player_has("GO_shoes")) {
m_walking_speed = PLAYER_SPEED * 1.25f;
} else {
m_walking_speed = PLAYER_SPEED;
}
switch (m_state) {
case CSTATE_STANDING_LEFT:
case CSTATE_STANDING_RIGHT:
m_state_cycle++;
if (v->m_joystick[VC_UP] && !v->m_old_joystick[VC_UP]) {
GObject *o;
o = map->collision_with_object(this, GLTM, rope_symbol);
if (o != 0) {
// climb a rope!
if (m_state == CSTATE_STANDING_LEFT)
m_facebefore_vine = 0;
else
m_facebefore_vine = 1;
m_state = CSTATE_CLIMBING_UP;
m_x = o->get_x() + 10;
} else {
// check for skulldoors:
GO_skulldoor *sd = (GO_skulldoor *)map->collision_with_object(this, GLTM, skulldoor_symbol);
if (sd != 0) {
// Room change request:
if (sd->get_destination_x() != -1 ||
m_goonies_rescued >= 7) {
m_requested_room_x = sd->get_destination_x();
m_requested_room_y = sd->get_destination_y();
m_requested_room_door = sd->get_destination_door();
m_state = CSTATE_ENTERING_DOOR;
m_state_cycle = 0;
m_x = sd->get_x()-4;
m_y = sd->get_y()+16;
}
} else {
SFXM->SFX_play("sfx/player_jump", m_sfx_volume, get_player_angle(), get_player_distance());
if (m_state == CSTATE_STANDING_LEFT) {
m_state = CSTATE_JUMPING_LEFT;
m_state_cycle = 0;
} else {
m_state = CSTATE_JUMPING_RIGHT;
m_state_cycle = 0;
}
}
}
} else {
if (v->m_joystick[VC_LEFT]) {
m_state_cycle = 0;
m_state = CSTATE_WALKING_LEFT;
}
if (v->m_joystick[VC_RIGHT]) {
m_state_cycle = 0;
m_state = CSTATE_WALKING_RIGHT;
}
// down an rope:
if (v->m_joystick[VC_DOWN] && !v->m_old_joystick[VC_DOWN]) {
m_y += 50;
GObject *o;
o = map->collision_with_object(this, GLTM, rope_symbol);
if (o != 0) {
set_layer(3, map);
if (m_state == CSTATE_STANDING_LEFT)
m_facebefore_vine = 0;
else
m_facebefore_vine = 1;
m_state = CSTATE_CLIMBING_DOWN;
m_x = o->get_x() + 10;
m_y -= 28;
} else {
m_y -= 50;
}
}
// punch:
if (v->m_button[0] && !v->m_old_button[0]) {
int e_gained = 0;
int points_gained = 0;
if (m_state == CSTATE_STANDING_LEFT || m_state == CSTATE_WALKING_LEFT) {
m_state = CSTATE_PUNCH_LEFT;
m_punch_cycle = 0;
GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get
("ob_character-punch-mask-l"), (int)m_x, (int)m_y, GLTM, enemy_symbol);
if (e != 0 && e->player_hit(&e_gained, &points_gained)) {
if (m_last_hit != 0)
delete m_last_hit;
m_last_hit = new Symbol(e->get_class());
SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance());
m_experience += e_gained;
inc_score(points_gained);
} else {
SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance());
}
} else {
m_state = CSTATE_PUNCH_RIGHT;
m_punch_cycle = 0;
GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get
("ob_character-punch-mask-r"), (int)m_x, (int)m_y, GLTM, enemy_symbol);
if (e != 0 && e->player_hit(&e_gained, &points_gained)) {
if (m_last_hit != 0)
delete m_last_hit;
m_last_hit = new Symbol(e->get_class());
SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance());
m_experience += e_gained;
inc_score(points_gained);
} else {
SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance());
}
}
}
}
// salute; wink sfx
if (salute == 250 || salute == 260 || salute == 270) {
SFXM->SFX_play("sfx/player_wink", m_sfx_volume, get_player_angle(), get_player_distance());
// salute; foot tap
} else if (salute == 510 || salute == 530 || salute == 550) {
SFXM->SFX_play("sfx/player_foottap", m_sfx_volume, get_player_angle(), get_player_distance());
// salute; knock on monitor
} else if (salute == 580 || salute == 590 || salute == 600) {
SFXM->SFX_play("sfx/player_knock", m_sfx_volume, get_player_angle(), get_player_distance());
}
// test for fall:
if (m_state != CSTATE_ENTERING_DOOR) {
m_y+=2.0f;
if (!map->collision_with_background(this, GLTM)) {
GObject *go = map->collision_with_object(this, GLTM, bridge_symbol);
if (go == 0) {
if (m_state == CSTATE_STANDING_LEFT)
m_state = CSTATE_FALLING_LEFT;
else
m_state = CSTATE_FALLING_RIGHT;
m_state_cycle = 0;
}
}
m_y-=2.0f;
}
break;
case CSTATE_WALKING_LEFT:
m_state_cycle++;
m_x -= m_walking_speed;
if (v->m_joystick[VC_UP] && !v->m_old_joystick[VC_UP]) {
GObject *o;
o = map->collision_with_object(this, GLTM, rope_symbol);
if (o != 0) {
// climb a rope!
m_facebefore_vine = 0;
m_state = CSTATE_CLIMBING_UP;
m_x = o->get_x() + 10;
} else {
// check for skulldoors:
GO_skulldoor *sd = (GO_skulldoor *)map->collision_with_object(this, GLTM, skulldoor_symbol);
if (sd != 0) {
// Room change request:
if (sd->get_destination_x() != -1 ||
m_goonies_rescued >= 7) {
m_requested_room_x = sd->get_destination_x();
m_requested_room_y = sd->get_destination_y();
m_requested_room_door = sd->get_destination_door();
m_state = CSTATE_ENTERING_DOOR;
m_state_cycle = 0;
m_x = sd->get_x()-4;
m_y = sd->get_y()+16;
}
} else {
SFXM->SFX_play("sfx/player_jump", m_sfx_volume, get_player_angle(), get_player_distance());
m_state = CSTATE_JUMPING_LEFT_LEFT;
m_state_cycle = 0;
}
}
} else {
if (!v->m_joystick[VC_LEFT]) {
m_state_cycle = 0;
m_state = CSTATE_STANDING_LEFT;
}
if (v->m_joystick[VC_RIGHT] && !v->m_old_joystick[VC_RIGHT]) {
m_state_cycle = 0;
m_state = CSTATE_WALKING_RIGHT;
}
// down an rope:
if (v->m_joystick[VC_DOWN] && !v->m_old_joystick[VC_DOWN]) {
m_y += 50;
GObject *o;
o = map->collision_with_object(this, GLTM, rope_symbol);
if (o != 0) {
set_layer(3, map);
m_facebefore_vine = 0;
m_state = CSTATE_CLIMBING_DOWN;
m_x = o->get_x() + 10;
m_y -= 28;
} else {
m_y -= 50;
}
}
// punch:
if (v->m_button[0] && !v->m_old_button[0]) {
int e_gained = 0;
int points_gained = 0;
if (m_state == CSTATE_STANDING_LEFT || m_state == CSTATE_WALKING_LEFT) {
m_state = CSTATE_PUNCH_LEFT;
m_punch_cycle = 0;
GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get
("ob_character-punch-mask-l"), (int)m_x, (int)m_y, GLTM, enemy_symbol);
if (e != 0 && e->player_hit(&e_gained, &points_gained)) {
if (m_last_hit != 0)
delete m_last_hit;
m_last_hit = new Symbol(e->get_class());
SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance());
m_experience += e_gained;
inc_score(points_gained);
} else {
SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance());
}
} else {
m_state = CSTATE_PUNCH_RIGHT;
m_punch_cycle = 0;
GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get
("ob_character-punch-mask-r"), (int)m_x, (int)m_y, GLTM, enemy_symbol);
if (e != 0 && e->player_hit(&e_gained, &points_gained)) {
if (m_last_hit != 0)
delete m_last_hit;
m_last_hit = new Symbol(e->get_class());
SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance());
m_experience += e_gained;
inc_score(points_gained);
} else {
SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance());
}
}
}
}
// test for fall:
if (m_state != CSTATE_ENTERING_DOOR) {
m_y+=2.0f;
if (!map->collision_with_background(this, GLTM)) {
GObject *go = map->collision_with_object(this, GLTM, bridge_symbol);
if (go == 0) {
m_state = CSTATE_FALLING_LEFT;
m_state_cycle = 0;
}
}
m_y-=2.0f;
}
break;
case CSTATE_WALKING_RIGHT:
m_state_cycle++;
m_x += m_walking_speed;
if (v->m_joystick[VC_UP] && !v->m_old_joystick[VC_UP]) {
GObject *o;
o = map->collision_with_object(this, GLTM, rope_symbol);
if (o != 0) {
// climb a rope!
m_facebefore_vine = 1;
m_state = CSTATE_CLIMBING_UP;
m_x = o->get_x() + 10;
} else {
// check for skulldoors:
GO_skulldoor *sd = (GO_skulldoor *)map->collision_with_object(this, GLTM, skulldoor_symbol);
if (sd != 0) {
// Room change request:
if (sd->get_destination_x() != -1 ||
m_goonies_rescued >= 7) {
m_requested_room_x = sd->get_destination_x();
m_requested_room_y = sd->get_destination_y();
m_requested_room_door = sd->get_destination_door();
m_state = CSTATE_ENTERING_DOOR;
m_state_cycle = 0;
m_x = sd->get_x()-4;
m_y = sd->get_y()+16;
}
} else {
SFXM->SFX_play("sfx/player_jump", m_sfx_volume, get_player_angle(), get_player_distance());
m_state = CSTATE_JUMPING_RIGHT_RIGHT;
m_state_cycle = 0;
}
}
} else {
if (v->m_joystick[VC_LEFT] && !v->m_old_joystick[VC_LEFT]) {
m_state_cycle = 0;
m_state = CSTATE_WALKING_LEFT;
}
if (!v->m_joystick[VC_RIGHT]) {
m_state_cycle = 0;
m_state = CSTATE_STANDING_RIGHT;
}
// down an rope:
if (v->m_joystick[VC_DOWN] && !v->m_old_joystick[VC_DOWN]) {
m_y += 50;
GObject *o;
o = map->collision_with_object(this, GLTM, rope_symbol);
if (o != 0) {
set_layer(3, map);
m_facebefore_vine = 1;
m_state = CSTATE_CLIMBING_DOWN;
m_x = o->get_x() + 10;
m_y -= 28;
} else {
m_y -= 50;
}
}
// punch:
if (v->m_button[0] && !v->m_old_button[0]) {
int e_gained = 0;
int points_gained = 0;
if (m_state == CSTATE_STANDING_LEFT || m_state == CSTATE_WALKING_LEFT) {
m_state = CSTATE_PUNCH_LEFT;
m_punch_cycle = 0;
GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get
("ob_character-punch-mask-l"), (int)m_x, (int)m_y, GLTM, enemy_symbol);
if (e != 0 && e->player_hit(&e_gained, &points_gained)) {
if (m_last_hit != 0)
delete m_last_hit;
m_last_hit = new Symbol(e->get_class());
SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance());
m_experience += e_gained;
inc_score(points_gained);
} else {
SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance());
}
} else {
m_state = CSTATE_PUNCH_RIGHT;
m_punch_cycle = 0;
GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get
("ob_character-punch-mask-r"), (int)m_x, (int)m_y, GLTM, enemy_symbol);
if (e != 0 && e->player_hit(&e_gained, &points_gained)) {
if (m_last_hit != 0)
delete m_last_hit;
m_last_hit = new Symbol(e->get_class());
SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance());
m_experience += e_gained;
inc_score(points_gained);
} else {
SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance());
}
}
}
}
// test for fall:
if (m_state != CSTATE_ENTERING_DOOR) {
m_y+=2.0f;
if (!map->collision_with_background(this, GLTM)) {
GObject *go = map->collision_with_object(this, GLTM, bridge_symbol);
if (go == 0) {
m_state = CSTATE_FALLING_RIGHT;
m_state_cycle = 0;
}
}
m_y-=2.0f;
}
break;
case CSTATE_FALLING_LEFT: {
int i, j = 1;
if (m_state_cycle > 4)
j++;
if (m_state_cycle > 12)
j++;
if (m_state_cycle > 20)
j++;
for (i = 0;i < j;i++) {
m_y++;
if (map->collision_with_background(this, GLTM)) {
m_state = CSTATE_STANDING_LEFT;
m_state_cycle = 0;
m_y--;
SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance());
}
else {
GObject *go = map->collision_with_object(this, GLTM, bridge_symbol);
if (go != 0) {
m_state = CSTATE_STANDING_LEFT;
m_state_cycle = 0;
m_y--;
}
}
}
m_state_cycle++;
}
break;
case CSTATE_FALLING_RIGHT: {
int i, j = 1;
if (m_state_cycle > 4)
j++;
if (m_state_cycle > 12)
j++;
if (m_state_cycle > 20)
j++;
for (i = 0;i < j;i++) {
m_y++;
if (map->collision_with_background(this, GLTM)) {
m_state = CSTATE_STANDING_RIGHT;
m_state_cycle = 0;
m_y--;
SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance());
}
else {
GObject *go = map->collision_with_object(this, GLTM, bridge_symbol);
if (go != 0) {
m_state = CSTATE_STANDING_RIGHT;
m_state_cycle = 0;
m_y--;
}
}
}
m_state_cycle++;
}
break;
case CSTATE_PUNCH_LEFT:
m_punch_cycle++;
if (m_punch_cycle >= 8) {
m_state = CSTATE_STANDING_LEFT;
m_state_cycle = 0;
}
break;
case CSTATE_PUNCH_RIGHT:
m_punch_cycle++;
if (m_punch_cycle >= 8) {
m_state = CSTATE_STANDING_RIGHT;
m_state_cycle = 0;
}
break;
case CSTATE_JUMPING_LEFT:
case CSTATE_JUMPING_RIGHT:
case CSTATE_JUMPING_LEFT_LEFT:
case CSTATE_JUMPING_RIGHT_RIGHT: {
int i, y_move = 3;
if (m_state_cycle < 39)
y_move = 2;
if (m_state_cycle < 33)
y_move = 1;
if (m_state_cycle < 27)
y_move = 0;
if (m_state_cycle < 21)
y_move = -1;
if (m_state_cycle < 15)
y_move = -2;
if (m_state_cycle < 9)
y_move = -3;
if (m_state_cycle < 4)
y_move = -4;
if (y_move > 0) {
for (i = 0;i < y_move;i++) {
m_y++;
if (map->collision_with_background(this, 0, 1, GLTM)) {
SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance());
if (m_state == CSTATE_JUMPING_LEFT ||
m_state == CSTATE_JUMPING_LEFT_LEFT) {
m_state = CSTATE_STANDING_LEFT;
y_move = 0;
}
if (m_state == CSTATE_JUMPING_RIGHT ||
m_state == CSTATE_JUMPING_RIGHT_RIGHT) {
m_state = CSTATE_STANDING_RIGHT;
y_move = 0;
}
m_state_cycle = 0;
}
else {
if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) {
// SFXM->SFX_play("sfx/player_walk_bridge1", m_sfx_volume, get_player_angle(), get_player_distance());
if (m_state == CSTATE_JUMPING_LEFT ||
m_state == CSTATE_JUMPING_LEFT_LEFT) {
m_state = CSTATE_STANDING_LEFT;
y_move = 0;
}
if (m_state == CSTATE_JUMPING_RIGHT ||
m_state == CSTATE_JUMPING_RIGHT_RIGHT) {
m_state = CSTATE_STANDING_RIGHT;
y_move = 0;
}
m_state_cycle = 0;
}
}
}
}
if (y_move < 0) {
y_move = -y_move;
for (i = 0;i < y_move;i++) {
m_y--;
if (map->collision_with_background(this, GLTM)) {
m_y++;
m_state_cycle = 22;
}
else {
if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) {
m_y++;
m_state_cycle = 22;
}
}
}
}
if (m_state == CSTATE_JUMPING_LEFT_LEFT) {
m_x -= (m_walking_speed * 1.25f);
if (map->collision_with_background(this, GLTM)) {
m_x += (m_walking_speed * 1.25f);
if (m_state_cycle > 25)
m_state = CSTATE_JUMPING_LEFT;
} // if
else {
if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) {
m_x += (m_walking_speed * 1.25f);
if (m_state_cycle > 25)
m_state = CSTATE_JUMPING_LEFT;
}
}
} // if
if (m_state == CSTATE_JUMPING_RIGHT_RIGHT) {
m_x += (m_walking_speed * 1.25f);
if (map->collision_with_background(this, GLTM)) {
m_x -= (m_walking_speed * 1.25f);
if (m_state_cycle > 25)
m_state = CSTATE_JUMPING_RIGHT;
}
else {
if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) {
m_x -= (m_walking_speed * 1.25f);
if (m_state_cycle > 25)
m_state = CSTATE_JUMPING_RIGHT;
}
}
}
{
// punch:
if (v->m_button[0] && !v->m_old_button[0])
{
int e_gained = 0;
int points_gained = 0;
if (m_state == CSTATE_JUMPING_LEFT || m_state == CSTATE_JUMPING_LEFT_LEFT) {
GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get
("ob_character-punchjump-mask-l"), (int)m_x, (int)m_y, GLTM, enemy_symbol);
if (e != 0 && e->player_hit(&e_gained, &points_gained)) {
if (m_last_hit != 0)
delete m_last_hit;
m_last_hit = new Symbol(e->get_class());
SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance());
m_experience += e_gained;
inc_score(points_gained);
} else {
SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance());
}
} else {
GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get
("ob_character-punchjump-mask-r"), (int)m_x, (int)m_y, GLTM, enemy_symbol);
if (e != 0 && e->player_hit(&e_gained, &points_gained)) {
if (m_last_hit != 0)
delete m_last_hit;
m_last_hit = new Symbol(e->get_class());
SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance());
m_experience += e_gained;
inc_score(points_gained);
} else {
SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance());
}
}
m_punch_cycle = 0;
if (m_state == CSTATE_JUMPING_LEFT)
m_state = CSTATE_JUMPPUNCH_LEFT;
if (m_state == CSTATE_JUMPING_RIGHT)
m_state = CSTATE_JUMPPUNCH_RIGHT;
if (m_state == CSTATE_JUMPING_LEFT_LEFT)
m_state = CSTATE_JUMPPUNCH_LEFT_LEFT;
if (m_state == CSTATE_JUMPING_RIGHT_RIGHT)
m_state = CSTATE_JUMPPUNCH_RIGHT_RIGHT;
}
}
m_state_cycle++;
}
break;
case CSTATE_JUMPPUNCH_LEFT:
case CSTATE_JUMPPUNCH_RIGHT:
case CSTATE_JUMPPUNCH_LEFT_LEFT:
case CSTATE_JUMPPUNCH_RIGHT_RIGHT: {
int i, y_move = 3;
if (m_state_cycle < 39)
y_move = 2;
if (m_state_cycle < 33)
y_move = 1;
if (m_state_cycle < 27)
y_move = 0;
if (m_state_cycle < 21)
y_move = -1;
if (m_state_cycle < 15)
y_move = -2;
if (m_state_cycle < 9)
y_move = -3;
if (m_state_cycle < 4)
y_move = -4;
if (m_state == CSTATE_JUMPPUNCH_LEFT_LEFT) {
m_x -= (m_walking_speed * 1.25f);
if (map->collision_with_background(this, GLTM)) {
m_x += (m_walking_speed * 1.25f);
if (m_state_cycle > 25)
m_state = CSTATE_JUMPPUNCH_LEFT;
}
else {
if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) {
m_x += (m_walking_speed * 1.25f);
if (m_state_cycle > 25)
m_state = CSTATE_JUMPPUNCH_LEFT;
}
}
}
if (m_state == CSTATE_JUMPPUNCH_RIGHT_RIGHT) {
m_x += (m_walking_speed * 1.25f);
if (map->collision_with_background(this, GLTM)) {
m_x -= (m_walking_speed * 1.25f);
if (m_state_cycle > 25)
m_state = CSTATE_JUMPPUNCH_RIGHT;
}
else {
if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) {
m_x -= (m_walking_speed * 1.25f);
if (m_state_cycle > 25)
m_state = CSTATE_JUMPPUNCH_RIGHT;
}
}
}
if (y_move > 0) {
for (i = 0;i < y_move;i++) {
m_y++;
if (map->collision_with_background(this, 0, 1, GLTM)) {
SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance());
if (m_state == CSTATE_JUMPPUNCH_LEFT ||
m_state == CSTATE_JUMPPUNCH_LEFT_LEFT) {
m_state = CSTATE_STANDING_LEFT;
y_move = 0;
}
if (m_state == CSTATE_JUMPPUNCH_RIGHT ||
m_state == CSTATE_JUMPPUNCH_RIGHT_RIGHT) {
m_state = CSTATE_STANDING_RIGHT;
y_move = 0;
}
m_state_cycle = 0;
}
else {
if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) {
SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance());
if (m_state == CSTATE_JUMPPUNCH_LEFT ||
m_state == CSTATE_JUMPPUNCH_LEFT_LEFT) {
m_state = CSTATE_STANDING_LEFT;
y_move = 0;
}
if (m_state == CSTATE_JUMPPUNCH_RIGHT ||
m_state == CSTATE_JUMPPUNCH_RIGHT_RIGHT) {
m_state = CSTATE_STANDING_RIGHT;
y_move = 0;
}
m_state_cycle = 0;
}
}
}
}
if (y_move < 0) {
y_move = -y_move;
for (i = 0;i < y_move;i++) {
m_y--;
if (map->collision_with_background(this, GLTM)) {
m_y++;
m_state_cycle = 22;
}
else {
if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) {
m_y++;
m_state_cycle = 22;
}
}
}
}
m_state_cycle++;
m_punch_cycle++;
if (m_punch_cycle >= 8) {
if (m_state == CSTATE_JUMPPUNCH_LEFT)
m_state = CSTATE_JUMPING_LEFT;
if (m_state == CSTATE_JUMPPUNCH_RIGHT)
m_state = CSTATE_JUMPING_RIGHT;
if (m_state == CSTATE_JUMPPUNCH_LEFT_LEFT)
m_state = CSTATE_JUMPING_LEFT_LEFT;
if (m_state == CSTATE_JUMPPUNCH_RIGHT_RIGHT)
m_state = CSTATE_JUMPING_RIGHT_RIGHT;
}
}
break;
case CSTATE_CLIMBING_UP:
set_layer(3, map);
m_y -= PLAYER_CLIMBING_SPEED;
// test if end of rope:
if (m_y > 8) {
m_y -= 8;
if (!map->collision_with_object(this, GLTM, rope_symbol)) {
set_layer(2, map);
if (m_facebefore_vine == 0)
m_state = CSTATE_STANDING_LEFT;
else
m_state = CSTATE_STANDING_RIGHT;
m_state_cycle = 0;
do {
m_y -= PLAYER_CLIMBING_SPEED;
} while (m_y >= 0 && map->collision_with_background(this, GLTM));
} else {
m_y += 8;
}
// check for reaching a platform:
if (m_state == CSTATE_CLIMBING_UP &&
!map->collision_with_background(this, GLTM) &&
map->collision_with_background(this, 0, 1, GLTM)) {
set_layer(2, map);
if (m_facebefore_vine == 0)
m_state = CSTATE_STANDING_LEFT;
else
m_state = CSTATE_STANDING_RIGHT;
m_state_cycle = 0;
}
}
m_state_cycle++;
if (!v->m_joystick[VC_UP]) {
m_state = CSTATE_CLIMBING;
}
if (v->m_joystick[VC_DOWN] && !v->m_old_joystick[VC_DOWN]) {
m_state = CSTATE_CLIMBING_DOWN;
}
break;
case CSTATE_CLIMBING:
set_layer(3, map);
if (v->m_joystick[VC_UP]) {
m_state = CSTATE_CLIMBING_UP;
}
if (v->m_joystick[VC_DOWN]) {
m_state = CSTATE_CLIMBING_DOWN;
}
break;
case CSTATE_CLIMBING_DOWN:
set_layer(3, map);
m_y += PLAYER_CLIMBING_SPEED;
if (map->collision_with_background(this, GLTM)) {
m_y -= PLAYER_CLIMBING_SPEED;
if (!map->collision_with_background(this, GLTM) || !map->collision_with_object(this, GLTM, rope_symbol)) {
set_layer(2, map);
if (m_facebefore_vine == 0)
m_state = CSTATE_STANDING_LEFT;
else
m_state = CSTATE_STANDING_RIGHT;
m_state_cycle = 0;
} else {
m_y += PLAYER_CLIMBING_SPEED;
}
}
m_state_cycle++;
if (!v->m_joystick[VC_DOWN]) {
m_state = CSTATE_CLIMBING;
}
if (v->m_joystick[VC_UP] && !v->m_old_joystick[VC_UP]) {
m_state = CSTATE_CLIMBING_UP;
}
break;
case CSTATE_ENTERING_DOOR:
if (m_state_cycle == 0)
SFXM->SFX_play("sfx/skulldoor_warp", m_sfx_volume);
m_state_cycle++;
if (m_state_cycle > 50) {
m_requested_room = true;
m_state = CSTATE_STANDING_RIGHT;
}
break;
case CSTATE_DYING:
m_state_cycle++;
if (m_state_cycle / 8 == 5)
SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance());
if (m_state_cycle > 100)
m_state = CSTATE_DEAD;
break;
case CSTATE_DEAD:
break;
}
// continuous SFX:
switch (m_state) {
case CSTATE_STANDING_LEFT:
case CSTATE_STANDING_RIGHT:
case CSTATE_JUMPING_LEFT:
case CSTATE_JUMPING_RIGHT:
case CSTATE_JUMPING_LEFT_LEFT:
case CSTATE_JUMPING_RIGHT_RIGHT:
case CSTATE_FALLING_LEFT:
case CSTATE_FALLING_RIGHT:
case CSTATE_PUNCH_LEFT:
case CSTATE_PUNCH_RIGHT:
case CSTATE_JUMPPUNCH_LEFT:
case CSTATE_JUMPPUNCH_RIGHT:
case CSTATE_JUMPPUNCH_LEFT_LEFT:
case CSTATE_JUMPPUNCH_RIGHT_RIGHT:
case CSTATE_CLIMBING:
if (m_walking_channel != -1) {
Mix_HaltChannel(m_walking_channel);
m_walking_channel = -1;
}
if (m_climbing_channel != -1) {
Mix_HaltChannel(m_climbing_channel);
m_climbing_channel = -1;
}
break;
case CSTATE_WALKING_LEFT:
case CSTATE_WALKING_RIGHT:
if (m_climbing_channel != -1) {
Mix_HaltChannel(m_climbing_channel);
m_climbing_channel = -1;
}
// time playing of sfx to step animation
if (m_state_cycle % 16 == 0) {
bool walk_on_bridge = ((map->collision_with_object(this, 0, 2, GLTM, bridge_symbol)!=0) ? true : false);
if (m_walking_channel != -1) {
if (m_step_cycle == 1) {
if (walk_on_bridge)
SFXM->SFX_play_channel("sfx/player_walk_bridge1", m_walking_channel, get_player_angle(), get_player_distance(), m_sfx_volume);
else
SFXM->SFX_play_channel("sfx/player_walk1", m_walking_channel, get_player_angle(), get_player_distance(), m_sfx_volume);
m_step_cycle = 0;
} else {
if (walk_on_bridge)
SFXM->SFX_play_channel("sfx/player_walk_bridge2", m_walking_channel, get_player_angle(), get_player_distance(), m_sfx_volume);
else
SFXM->SFX_play_channel("sfx/player_walk2", m_walking_channel, get_player_angle(), get_player_distance(), m_sfx_volume);
m_step_cycle = 1;
}
Mix_SetPosition(m_walking_channel, get_player_angle(), get_player_distance());
} else {
if (walk_on_bridge)
m_walking_channel = SFXM->SFX_play("sfx/player_walk_bridge1", m_sfx_volume);
else
m_walking_channel = SFXM->SFX_play("sfx/player_walk1", m_sfx_volume);
m_step_cycle = 1;
}
}
break;
case CSTATE_CLIMBING_UP:
case CSTATE_CLIMBING_DOWN:
if (m_walking_channel != -1) {
Mix_HaltChannel(m_walking_channel);
m_walking_channel = -1;
}
if (m_climbing_channel != -1) {
Mix_SetPosition(m_climbing_channel, get_player_angle(), get_player_distance());
}
if (m_climbing_channel == -1) {
m_climbing_channel = SFXM->SFX_play_continuous("sfx/player_climb", m_sfx_volume, get_player_angle(), get_player_distance(),this);
}
break;
}
if (m_layer != 3 &&
map->collision_with_background(this, GLTM)) {
int i, j;
bool found = false;
#ifdef __DEBUG_MESSAGES
output_debug_message("GO_character: finding a proper position from %i,%i\n",int(m_x),int(m_y));
#endif
for (i = 1;i < 5 && !found;i++) {
for (j = 0;j <= i && !found;j++) {
if (!found && !map->collision_with_background(this, j, i - j, GLTM)) {
m_x += j;
m_y += i - j;
found = true;
}
if (!found && (i - j) != 0) {
if (!map->collision_with_background(this, j, -(i - j), GLTM)) {
m_x += j;
m_y += -(i - j);
found = true;
}
}
if (!found && j != 0) {
if (!map->collision_with_background(this, -j, i - j, GLTM)) {
m_x += -j;
m_y += i - j;
found = true;
}
}
if (!found && j != 0 && (i - j) != 0) {
if (!map->collision_with_background(this, -j, -(i - j), GLTM)) {
m_x += -j;
m_y += -(i - j);
found = true;
}
}
}
}
#ifdef __DEBUG_MESSAGES
if (found) output_debug_message("GO_character: found proper position: %i,%i\n",int(m_x),int(m_y));
#endif
if (!found && m_player_hit_counter == 0) {
m_energy = 0;
m_player_hit_counter = 64;
SFXM->SFX_play("sfx/player_dead", m_sfx_volume, get_player_angle(), get_player_distance());
}
}
// check for keys:
if (!m_key) {
GObject *o = map->collision_with_object(this, GLTM, key_symbol);
if (o != 0) {
if (o->get_state() == 0) {
SFXM->SFX_play("sfx/player_pickup_key", m_sfx_volume, get_player_angle(), get_player_distance());
o->set_state(1);
m_key = true;
inc_score(200);
if (m_last_pick != 0)
delete m_last_pick;
m_last_pick = new Symbol(key_symbol);
}
}
}
// check for coins:
{
GObject *o = map->collision_with_object(this, GLTM, coin_symbol);
if (o != 0)
{
if (o->get_state() == 0) {
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
o->set_state(2);
inc_score(500);
if (m_last_pick != 0)
delete m_last_pick;
m_last_pick = new Symbol("coin_symbol");
}
}
}
// check for other items:
{
GO_item *o = (GO_item *)map->collision_with_object(this, GLTM, item_symbol);
if (o != 0)
{
if (o->get_state() == 0) {
o->set_state(1);
if (m_last_pick != 0)
delete m_last_pick;
m_last_pick = new Symbol(item_symbol);
// Pick up the object: update the internal status:
switch (o->get_type()) {
case 0:
SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume);
m_goonies_rescued++;
inc_score(2000);
break;
case 1:
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
m_energy += 6;
if (m_energy > PLAYER_MAX_ENERGY)
m_energy = PLAYER_MAX_ENERGY;
break;
case 2:
m_items.Add(new Symbol("GO_yellowhelmet"));
m_yellowhelmet_status = 5;
m_yellowhelmet_timer = 0;
m_last_pick = new Symbol("GO_yellowhelmet");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 3:
m_items.Add(new Symbol("GO_shoes"));
if (m_last_pick != 0)
delete m_last_pick;
m_last_pick = new Symbol("GO_shoes");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 4:
m_items.Add(new Symbol("GO_greycoat"));
m_greycoat_status = 5;
m_greycoat_timer = 0;
m_last_pick = new Symbol("GO_greycoat");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 5:
m_items.Add(new Symbol("GO_yellowcoat"));
if (m_last_pick != 0)
delete m_last_pick;
m_last_pick = new Symbol("GO_yellowcoat");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
m_yellowcoat_timer = 500;
break;
case 6:
m_items.Add(new Symbol("GO_hammer"));
m_hammer_status = 30; // each time a drop falls, this is decremented once, and every time it becomes
// an odd number, the drop is converted into a coin
if (m_last_pick != 0)
delete m_last_pick;
m_last_pick = new Symbol("GO_hammer");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 7: // energy increasing bag
m_energy += 8;
if (m_energy >= PLAYER_MAX_ENERGY)
m_energy = PLAYER_MAX_ENERGY;
break;
case 8:
m_items.Add(new Symbol("GO_lamp"));
if (m_last_pick != 0)
delete m_last_pick;
m_last_pick = new Symbol("GO_lamp");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 9:
m_items.Add(new Symbol("GO_greenbook"));
m_greenbook_status = 5;
m_last_pick = new Symbol("GO_greenbook");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 10:
m_items.Add(new Symbol("GO_redbook"));
m_redbook_status = 4;
m_last_pick = new Symbol("GO_redbook");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 11:
m_items.Add(new Symbol("GO_lightbluebook"));
m_lightbluebook_status = 5;
m_last_pick = new Symbol("GO_lightbluebook");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 12:
m_items.Add(new Symbol("GO_bluebook"));
m_bluebook_status = 5;
m_last_pick = new Symbol("GO_bluebook");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 13:
m_items.Add(new Symbol("GO_greencoat"));
m_greencoat_timer = 500;
m_last_pick = new Symbol("GO_greencoat");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 14:
m_items.Add(new Symbol("GO_whitebook"));
m_whitebook_status = 5;
m_last_pick = new Symbol("GO_whitebook");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 15:
m_items.Add(new Symbol("GO_yellowshield"));
m_yellowshield_status = 5;
m_last_pick = new Symbol("GO_yellowshield");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 16:
m_experience++;
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
break;
case 17:
m_items.Add(new Symbol("GO_lightbluecoat"));
m_lightbluecoat_timer = 500;
m_last_pick = new Symbol("GO_lightbluecoat");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 18:
m_items.Add(new Symbol("GO_whiteshield"));
m_yellowshield_status = 5;
m_last_pick = new Symbol("GO_whiteshield");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 19:
m_items.Add(new Symbol("GO_redbadbook"));
m_last_pick = new Symbol("GO_redbadbook");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 20:
m_items.Add(new Symbol("GO_purplebook"));
m_last_pick = new Symbol("GO_purplebook");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 21:
m_items.Add(new Symbol("GO_lightbluehelmet"));
m_lightbluehelmet_status = 5;
m_last_pick = new Symbol("GO_lightbluehelmet");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 22:
m_items.Add(new Symbol("GO_yellowbook"));
m_yellowbook_status = 5;
m_last_pick = new Symbol("GO_yellowbook");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 23:
m_items.Add(new Symbol("GO_purplebadbook"));
m_last_pick = new Symbol("GO_purplebadbook");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 24:
m_items.Add(new Symbol("GO_purpleshield"));
m_purpleshield_status = 5;
m_last_pick = new Symbol("GO_purpleshield");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 25:
m_items.Add(new Symbol("GO_clock"));
m_clock_timer = 1500;
m_last_pick = new Symbol("GO_clock");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 26:
m_items.Add(new Symbol("GO_bluebadbook"));
m_bluebadbook_nghosts = 2;
m_last_pick = new Symbol("GO_bluebadbook");
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
inc_score(1000);
break;
case 27:
SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume);
if (!m_rescued_goonies[0])
{
m_rescued_goonies[0] = true;
m_goonies_rescued++;
}
inc_score(2000);
break;
case 28:
SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume);
if (!m_rescued_goonies[1])
{
m_rescued_goonies[1] = true;
m_goonies_rescued++;
}
inc_score(2000);
break;
case 29:
SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume);
if (!m_rescued_goonies[2])
{
m_rescued_goonies[2] = true;
m_goonies_rescued++;
}
inc_score(2000);
break;
case 30:
SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume);
if (!m_rescued_goonies[3])
{
m_rescued_goonies[3] = true;
m_goonies_rescued++;
}
inc_score(2000);
break;
case 31:
SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume);
if (!m_rescued_goonies[4])
{
m_rescued_goonies[4] = true;
m_goonies_rescued++;
}
inc_score(2000);
break;
case 32:
SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume);
if (!m_rescued_goonies[5])
{
m_rescued_goonies[5] = true;
m_goonies_rescued++;
}
inc_score(2000);
break;
case 33:
SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume);
if (!m_rescued_goonies[6])
{
m_rescued_goonies[6] = true;
m_goonies_rescued++;
}
inc_score(2000);
break;
default:
SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance());
break;
}
}
}
}
// check for enemies:
if (m_player_hit_counter > 0) {
m_player_hit_counter--;
} else {
if (m_state != CSTATE_ENTERING_DOOR && !m_requested_room) {
bool saved = false;
int energy_taken = 0;
GO_enemy *e = (GO_enemy *)map->collision_with_object(this, GLTM, "GO_enemy");
if (e != 0)
energy_taken = (int)(e->enemy_hit() * difficulty / 100);
if (energy_taken != 0) {
if (e->get_class()->cmp(bat_symbol))
SFXM->SFX_play("sfx/bat_attack", m_sfx_volume, get_angle(map), get_distance(map));
if (e->get_class()->cmp(fallingrock_symbol)) {
if (player_has("GO_yellowhelmet") && (m_yellowhelmet_status > 0 || m_yellowhelmet_timer > 0)) {
if (m_yellowhelmet_timer == 0) {
m_yellowhelmet_timer = 32;
m_yellowhelmet_status--;
}
saved = true;
}
}
if (e->get_class()->cmp(bullet_symbol)) {
if (player_has("GO_yellowshield") && (m_yellowshield_status > 0 || m_yellowshield_timer > 0)) {
if (m_yellowshield_timer == 0) {
m_yellowshield_timer = 32;
m_yellowshield_status--;
}
saved = true;
}
}
if (e->get_class()->cmp(musicalnote_symbol)) {
if (player_has("GO_whiteshield") && (m_whiteshield_status > 0 || m_whiteshield_timer > 0)) {
if (m_whiteshield_timer == 0) {
m_whiteshield_timer = 32;
m_whiteshield_status--;
}
saved = true;
}
}
if (e->get_class()->cmp(bone_symbol)) {
if (player_has("GO_purpleshield") && (m_purpleshield_status > 0 || m_purpleshield_timer > 0)) {
if (m_purpleshield_timer == 0) {
m_purpleshield_timer = 32;
m_purpleshield_status--;
}
saved = true;
}
}
if (e->get_class()->cmp(drop_symbol)) {
if (player_has("GO_greycoat") && (m_greycoat_status > 0 || m_greycoat_timer > 0)) {
if (m_greycoat_timer == 0) {
m_greycoat_timer = 32;
m_greycoat_status--;
}
saved = true;
}
}
if (e->is_a(skull_symbol)) {
int exp;
int score;
if (player_has("GO_greenbook") && m_greenbook_status > 0) {
m_greenbook_status--;
e->player_hit(&exp, &score);
m_experience += exp;
saved = true;
}
if (!saved) {
if (player_has("GO_bluebook") && (m_bluebook_status > 0 || m_bluebook_timer > 0)) {
if (m_bluebook_timer == 0) {
m_bluebook_timer = 32;
m_bluebook_status--;
}
saved = true;
}
}
}
if (e->get_class()->cmp(bat_symbol)) {
int exp;
int score;
if (player_has("GO_lightbluebook") && m_lightbluebook_status > 0) {
m_lightbluebook_status--;
e->player_hit(&exp, &score);
m_experience += exp;
saved = true;
}
if (!saved) {
if (player_has("GO_lightbluehelmet") && (m_lightbluehelmet_status > 0 || m_lightbluehelmet_timer > 0)) {
if (m_lightbluehelmet_timer == 0) {
m_lightbluehelmet_timer = 32;
m_lightbluehelmet_status--;
}
saved = true;
}
}
}
if (e->get_class()->cmp(skeleton_symbol)) {
int exp;
int score;
if (player_has("GO_whitebook") && m_whitebook_status > 0) {
m_whitebook_status--;
e->player_hit(&exp, &score);
m_experience += exp;
saved = true;
}
if (!saved) {
if (player_has("GO_yellowbook") && (m_yellowbook_status > 0 || m_yellowbook_timer > 0)) {
if (m_yellowbook_timer == 0) {
m_yellowbook_timer = 32;
m_yellowbook_status--;
}
saved = true;
}
}
}
if (e->get_class()->cmp(pipe_water_symbol)) {
if (player_has("GO_yellowcoat") && m_yellowcoat_timer > 0) {
saved = true;
m_yellowcoat_timer--;
}
}
if (e->get_class()->cmp(flame_symbol)) {
if (player_has("GO_greencoat") && m_greencoat_timer > 0) {
saved = true;
m_greencoat_timer--;
}
}
if (e->get_class()->cmp(fallingwater_symbol)) {
if (player_has("GO_lightbluecoat") && m_lightbluecoat_timer > 0) {
saved = true;
m_lightbluecoat_timer--;
}
}
if (m_last_hit_by != 0)
delete m_last_hit_by;
m_last_hit_by = new Symbol(e->get_class());
if (!saved) {
m_energy -= energy_taken;
m_player_hit_counter = 64;
if (e->is_a(fallingwater_symbol))
m_player_hit_counter = 8;
if (e->is_a(flame_symbol))
m_player_hit_counter = 8;
if (e->is_a(pipe_water_symbol))
m_player_hit_counter = 8;
if (m_energy > 0)
SFXM->SFX_play("sfx/player_hit", m_sfx_volume, get_player_angle(), get_player_distance());
else
SFXM->SFX_play("sfx/player_dead", m_sfx_volume, get_player_angle(), get_player_distance());
}
}
}
}
// check for experience:
if (m_experience >= PLAYER_MAX_EXPERIENCE) {
m_experience = 0;
m_energy += 8;
if (m_energy >= PLAYER_MAX_ENERGY)
m_energy = PLAYER_MAX_ENERGY;
}
if (m_energy <= 0 && m_state != CSTATE_DYING && m_state != CSTATE_DEAD) {
m_player_hit_counter = 512;
m_energy = 0;
m_state = CSTATE_DYING;
m_state_cycle = 0;
if (m_walking_channel!=0) SFXM->SFX_stop(m_walking_channel);
if (m_climbing_channel!=0) SFXM->SFX_stop(m_climbing_channel);
m_walking_channel=-1;
m_climbing_channel=-1;
}
if (m_yellowhelmet_timer > 0)
m_yellowhelmet_timer--;
if (m_greycoat_timer > 0)
m_greycoat_timer--;
if (m_bluebook_timer > 0)
m_bluebook_timer--;
if (m_yellowshield_timer > 0)
m_yellowshield_timer--;
if (m_whiteshield_timer > 0)
m_whiteshield_timer--;
if (m_lightbluehelmet_timer > 0)
m_lightbluehelmet_timer--;
if (m_yellowbook_timer > 0)
m_yellowbook_timer--;
if (m_purpleshield_timer > 0)
m_purpleshield_timer--;
if (m_clock_timer > 0)
m_clock_timer--;
if (((m_state == CSTATE_STANDING_LEFT) || (m_state == CSTATE_WALKING_LEFT)) &&
((m_previous_state == CSTATE_STANDING_RIGHT) || (m_previous_state == CSTATE_WALKING_RIGHT)))
m_turning_counter = 6;
if (((m_state == CSTATE_STANDING_RIGHT) || (m_state == CSTATE_WALKING_RIGHT)) &&
((m_previous_state == CSTATE_STANDING_LEFT) || (m_previous_state == CSTATE_WALKING_LEFT)))
m_turning_counter = 6;
if (m_turning_counter > 0)
m_turning_counter--;
return true;
}
void GO_character::draw(GLTManager *GLTM)
{
int s2 = (m_state_cycle / 8) % 2;
int s4 = (m_state_cycle / 8) % 4;
int s10 = m_state_cycle / 8;
float xo = 0, yo = 0;
switch (m_state) {
case CSTATE_STANDING_LEFT:
if (m_turning_counter)
m_last_tile_used = GLTM->get
("ob_character-turn");
else {
int salute = (m_state_cycle % 615);
if (salute >= 250 && salute < 255 ) m_last_tile_used = GLTM->get ("ob_character_salute-l1");
else if (salute >= 255 && salute < 260) m_last_tile_used = GLTM->get ("ob_character_salute-l2");
else if (salute >= 260 && salute < 265) m_last_tile_used = GLTM->get ("ob_character_salute-l1");
else if (salute >= 265 && salute < 270) m_last_tile_used = GLTM->get ("ob_character_salute-l2");
else if (salute >= 270 && salute < 275) m_last_tile_used = GLTM->get ("ob_character_salute-l1");
else if (salute >= 275 && salute < 280) m_last_tile_used = GLTM->get ("ob_character_salute-l2");
else if (salute >= 500 && salute < 505) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1");
else if (salute >= 505 && salute < 510) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 510 && salute < 515) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3");
else if (salute >= 515 && salute < 520) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 520 && salute < 525) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1");
else if (salute >= 525 && salute < 530) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 530 && salute < 535) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3");
else if (salute >= 535 && salute < 540) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 540 && salute < 545) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1");
else if (salute >= 545 && salute < 550) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 550 && salute < 555) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3");
else if (salute >= 555 && salute < 560) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 560 && salute < 565) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1");
else if (salute >= 565 && salute < 570) m_last_tile_used = GLTM->get ("ob_character-knocking1");
else if (salute >= 570 && salute < 575) m_last_tile_used = GLTM->get ("ob_character-knocking2");
else if (salute >= 575 && salute < 580) m_last_tile_used = GLTM->get ("ob_character-knocking3");
else if (salute >= 580 && salute < 585) m_last_tile_used = GLTM->get ("ob_character-knocking4");
else if (salute >= 585 && salute < 590) m_last_tile_used = GLTM->get ("ob_character-knocking3");
else if (salute >= 590 && salute < 595) m_last_tile_used = GLTM->get ("ob_character-knocking4");
else if (salute >= 595 && salute < 600) m_last_tile_used = GLTM->get ("ob_character-knocking3");
else if (salute >= 600 && salute < 605) m_last_tile_used = GLTM->get ("ob_character-knocking4");
else if (salute >= 605 && salute < 610) m_last_tile_used = GLTM->get ("ob_character-knocking2");
else if (salute >= 610 && salute < 615) m_last_tile_used = GLTM->get ("ob_character-knocking1");
else if (s4 == 0 || s4 == 1) m_last_tile_used = GLTM->get ("ob_character_stand-l1");
else if (s4 == 2 || s4 == 3) m_last_tile_used = GLTM->get ("ob_character_stand-l2");
}
break;
case CSTATE_STANDING_RIGHT:
if (m_turning_counter)
m_last_tile_used = GLTM->get
("ob_character-turn");
else {
int salute = (m_state_cycle % 615);
if (salute >= 250 && salute < 255 ) m_last_tile_used = GLTM->get ("ob_character_salute-r1");
else if (salute >= 255 && salute < 260) m_last_tile_used = GLTM->get ("ob_character_salute-r2");
else if (salute >= 260 && salute < 265) m_last_tile_used = GLTM->get ("ob_character_salute-r1");
else if (salute >= 265 && salute < 270) m_last_tile_used = GLTM->get ("ob_character_salute-r2");
else if (salute >= 270 && salute < 275) m_last_tile_used = GLTM->get ("ob_character_salute-r1");
else if (salute >= 275 && salute < 280) m_last_tile_used = GLTM->get ("ob_character_salute-r2");
else if (salute >= 500 && salute < 505) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1");
else if (salute >= 505 && salute < 510) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 510 && salute < 515) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3");
else if (salute >= 515 && salute < 520) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 520 && salute < 525) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1");
else if (salute >= 525 && salute < 530) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 530 && salute < 535) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3");
else if (salute >= 535 && salute < 540) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 540 && salute < 545) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1");
else if (salute >= 545 && salute < 550) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 550 && salute < 555) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3");
else if (salute >= 555 && salute < 560) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2");
else if (salute >= 560 && salute < 565) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1");
else if (salute >= 565 && salute < 570) m_last_tile_used = GLTM->get ("ob_character-knocking1");
else if (salute >= 570 && salute < 575) m_last_tile_used = GLTM->get ("ob_character-knocking2");
else if (salute >= 575 && salute < 580) m_last_tile_used = GLTM->get ("ob_character-knocking3");
else if (salute >= 580 && salute < 585) m_last_tile_used = GLTM->get ("ob_character-knocking4");
else if (salute >= 585 && salute < 590) m_last_tile_used = GLTM->get ("ob_character-knocking3");
else if (salute >= 590 && salute < 595) m_last_tile_used = GLTM->get ("ob_character-knocking4");
else if (salute >= 595 && salute < 600) m_last_tile_used = GLTM->get ("ob_character-knocking3");
else if (salute >= 600 && salute < 605) m_last_tile_used = GLTM->get ("ob_character-knocking4");
else if (salute >= 605 && salute < 610) m_last_tile_used = GLTM->get ("ob_character-knocking2");
else if (salute >= 610 && salute < 615) m_last_tile_used = GLTM->get ("ob_character-knocking1");
else if (s4 == 0 || s4 == 1) m_last_tile_used = GLTM->get ("ob_character_stand-r1");
else if (s4 == 2 || s4 == 3) m_last_tile_used = GLTM->get ("ob_character_stand-r2");
}
break;
case CSTATE_WALKING_LEFT:
if (m_turning_counter) {
m_last_tile_used = GLTM->get
("ob_character-turn");
} else {
if (s4 == 0)
m_last_tile_used = GLTM->get
("ob_character-l2");
if (s4 == 1)
m_last_tile_used = GLTM->get
("ob_character-l1");
if (s4 == 2)
m_last_tile_used = GLTM->get
("ob_character-l3");
if (s4 == 3)
m_last_tile_used = GLTM->get
("ob_character-l1");
}
break;
case CSTATE_WALKING_RIGHT:
if (m_turning_counter) {
m_last_tile_used = GLTM->get
("ob_character-turn");
} else {
if (s4 == 0)
m_last_tile_used = GLTM->get
("ob_character-r2");
if (s4 == 1)
m_last_tile_used = GLTM->get
("ob_character-r1");
if (s4 == 2)
m_last_tile_used = GLTM->get
("ob_character-r3");
if (s4 == 3)
m_last_tile_used = GLTM->get
("ob_character-r1");
}
break;
case CSTATE_PUNCH_LEFT:
m_last_tile_used = GLTM->get
("ob_character-punch-l");
break;
case CSTATE_PUNCH_RIGHT:
m_last_tile_used = GLTM->get
("ob_character-punch-r");
break;
case CSTATE_FALLING_LEFT:
if (s2 == 0) m_last_tile_used = GLTM->get("ob_character-fall1");
if (s2 == 1) m_last_tile_used = GLTM->get("ob_character-fall2");
break;
case CSTATE_FALLING_RIGHT:
if (s2 == 0) m_last_tile_used = GLTM->get("ob_character-fall1");
if (s2 == 1) m_last_tile_used = GLTM->get("ob_character-fall2");
break;
case CSTATE_JUMPING_LEFT:
case CSTATE_JUMPING_LEFT_LEFT:
m_last_tile_used = GLTM->get
("ob_character-jump-l");
break;
case CSTATE_JUMPING_RIGHT:
case CSTATE_JUMPING_RIGHT_RIGHT:
m_last_tile_used = GLTM->get
("ob_character-jump-r");
break;
case CSTATE_JUMPPUNCH_LEFT:
case CSTATE_JUMPPUNCH_LEFT_LEFT:
m_last_tile_used = GLTM->get
("ob_character-punchjump-l");
break;
case CSTATE_JUMPPUNCH_RIGHT:
case CSTATE_JUMPPUNCH_RIGHT_RIGHT:
m_last_tile_used = GLTM->get
("ob_character-punchjump-r");
break;
case CSTATE_CLIMBING_UP:
case CSTATE_CLIMBING:
case CSTATE_CLIMBING_DOWN:
if (s4 == 0 || s4 == 2)
m_last_tile_used = GLTM->get
("ob_character-climbing-1");
if (s4 == 1 || s4 == 3)
m_last_tile_used = GLTM->get
("ob_character-climbing-2");
break;
case CSTATE_ENTERING_DOOR:
if (s4 == 0)
m_last_tile_used = GLTM->get
("ob_character-r2");
if (s4 == 1)
m_last_tile_used = GLTM->get
("ob_character-r1");
if (s4 == 2)
m_last_tile_used = GLTM->get
("ob_character-r3");
if (s4 == 3)
m_last_tile_used = GLTM->get
("ob_character-r1");
xo = -(m_state_cycle / 75.0F);
yo = 0.0;
break;
case CSTATE_DYING:
if (s10 == 0) m_last_tile_used = GLTM->get("ob_character-death1");
if (s10 == 1) m_last_tile_used = GLTM->get("ob_character-death2");
if (s10 == 2) m_last_tile_used = GLTM->get("ob_character-death3");
if (s10 == 3) m_last_tile_used = GLTM->get("ob_character-death3");
if (s10 == 4) m_last_tile_used = GLTM->get("ob_character-death4");
if (s10 == 5) m_last_tile_used = GLTM->get("ob_character-death5");
if (s10 == 6) m_last_tile_used = GLTM->get("ob_character-death6");
if (s10 == 7) m_last_tile_used = GLTM->get("ob_character-death5");
if (s10 == 8) m_last_tile_used = GLTM->get("ob_character-death6");
if (s10 >= 9) m_last_tile_used = GLTM->get("ob_character-death5");
break;
}
if ((m_player_hit_counter > 0) && (m_state != CSTATE_DYING) && (m_state != CSTATE_DEAD)) {
int bufi;
float TexColorArray[4], bufvf[4];
float f = float(0.5F + 0.5F * sin(m_player_hit_counter * ((m_state == CSTATE_DYING || m_state == CSTATE_DEAD) ? 0.8f : 0.4f)));
glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &bufi);
glGetTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, bufvf);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
TexColorArray[0] = 1.0f;
TexColorArray[1] = 1.0f;
TexColorArray[2] = 1.0f;
TexColorArray[3] = 0.0f;
glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, TexColorArray);
if (xo == 0 && yo == 0)
m_last_tile_used->draw(1, 1, 1, 1, m_x, m_y, 0, 0, 1);
else
m_last_tile_used->draw_toffs(1, 1, 1, 1, m_x, m_y, 0, 0, 1, xo, yo);
glColor4f(1, 1, 1, 1);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, bufi);
glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, bufvf);
glBindTexture(GL_TEXTURE_2D, 0); // I really don't understand this line of code, but if I don't add it,
// I don't get the desired effect (I found this after like 2 hours of random guessing!)
if (xo == 0 && yo == 0)
m_last_tile_used->draw(1, 1, 1, f, m_x, m_y, 0, 0, 1);
else
m_last_tile_used->draw_toffs(1, 1, 1, f, m_x, m_y, 0, 0, 1, xo, yo);
} else {
if (xo == 0 && yo == 0)
m_last_tile_used->draw(1, 1, 1, 1, m_x, m_y, 0, 0, 1);
else
m_last_tile_used->draw_toffs(1, 1, 1, 1, m_x, m_y, 0, 0, 1, xo, yo);
}
}
bool GO_character::is_a(Symbol *c)
{
if (c->cmp(character_symbol))
return true;
return GObject::is_a(c);
}
bool GO_character::is_a(char *c)
{
bool retval;
Symbol *s = new Symbol(c);
retval = is_a(s);
delete s;
return retval;
}
void GO_character::inc_score(int m_score)
{
score += m_score;
}
/*
* Calculates the 'angle' of the player, based on its distance from the screen's center
*/
int GO_character::get_player_angle()
{
float x = 320 - m_x;
float y = 240 - m_y;
int angle;
angle = (int)(atan2(y, x) * 180 / 3.149265);
angle = 270 - angle;
if (angle > 360) {
angle = 360;
}
if (angle < 0) {
angle = 0;
}
return angle;
}
| 43.531432
| 135
| 0.46263
|
pdpdds
|
4a92aa08906e8bea87c98c0885d18dfce9960949
| 436
|
cpp
|
C++
|
PAT/PAT-B/CPP/1092.最好吃的月饼.cpp
|
hao14293/2021-Postgraduate-408
|
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
|
[
"MIT"
] | 950
|
2020-02-21T02:39:18.000Z
|
2022-03-31T07:27:36.000Z
|
PAT/PAT-B/CPP/1092.最好吃的月饼.cpp
|
RestmeF/2021-Postgraduate-408
|
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
|
[
"MIT"
] | 6
|
2020-04-03T13:08:47.000Z
|
2022-03-07T08:54:56.000Z
|
PAT/PAT-B/CPP/1092.最好吃的月饼.cpp
|
RestmeF/2021-Postgraduate-408
|
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
|
[
"MIT"
] | 131
|
2020-02-22T15:35:59.000Z
|
2022-03-21T04:23:57.000Z
|
#include <iostream>
using namespace std;
int main(){
int n, m, tmp, max = 0, v[1000] = {0};
scanf("%d%d",&n, &m); // n == 5, m == 3
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
scanf("%d", &tmp);
v[j] += tmp;
if(v[j] > max) max = v[j];
}
}
printf("%d\n", max);
int flag = 0;
for(int i = 0; i < n; i++){
if(v[i] == max){
if(flag) printf(" ");
flag = 1;
printf("%d", i + 1);
}
}
return 0;
}
| 18.166667
| 41
| 0.431193
|
hao14293
|
4a9c7f24c0ea0348e4f1ca777afb833e4e77ef4e
| 706
|
cpp
|
C++
|
higan/target-tomoko/settings/timing.cpp
|
ameer-bauer/higan-097
|
a4a28968173ead8251cfa7cd6b5bf963ee68308f
|
[
"Info-ZIP"
] | 3
|
2016-03-23T01:17:36.000Z
|
2019-10-25T06:41:09.000Z
|
higan/target-tomoko/settings/timing.cpp
|
ameer-bauer/higan-097
|
a4a28968173ead8251cfa7cd6b5bf963ee68308f
|
[
"Info-ZIP"
] | null | null | null |
higan/target-tomoko/settings/timing.cpp
|
ameer-bauer/higan-097
|
a4a28968173ead8251cfa7cd6b5bf963ee68308f
|
[
"Info-ZIP"
] | null | null | null |
TimingSettings::TimingSettings(TabFrame* parent) : TabFrameItem(parent) {
setIcon(Icon::Device::Clock);
setText("Timing");
layout.setMargin(5);
videoLabel.setText("Video:");
videoValue.setText(settings["Timing/Video"].real()).onActivate([&] { update(); });
videoAssign.setText("Assign").onActivate([&] { update(); });
audioLabel.setText("Audio:");
audioValue.setText(settings["Timing/Audio"].real()).onActivate([&] { update(); });
audioAssign.setText("Assign").onActivate([&] { update(); });
}
auto TimingSettings::update() -> void {
settings["Timing/Video"].setValue(videoValue.text().real());
settings["Timing/Audio"].setValue(audioValue.text().real());
program->updateDSP();
}
| 37.157895
| 84
| 0.681303
|
ameer-bauer
|
4a9eaaa1a2348cac22620013f967b8d2acc03485
| 1,371
|
cpp
|
C++
|
ext/stub/java/awt/font/TextLayout_CaretPolicy-stub.cpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
ext/stub/java/awt/font/TextLayout_CaretPolicy-stub.cpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
ext/stub/java/awt/font/TextLayout_CaretPolicy-stub.cpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#include <java/awt/font/TextLayout_CaretPolicy.hpp>
extern void unimplemented_(const char16_t* name);
java::awt::font::TextLayout_CaretPolicy::TextLayout_CaretPolicy(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
java::awt::font::TextLayout_CaretPolicy::TextLayout_CaretPolicy()
: TextLayout_CaretPolicy(*static_cast< ::default_init_tag* >(0))
{
ctor();
}
void ::java::awt::font::TextLayout_CaretPolicy::ctor()
{ /* stub */
/* super::ctor(); */
unimplemented_(u"void ::java::awt::font::TextLayout_CaretPolicy::ctor()");
}
java::awt::font::TextHitInfo* java::awt::font::TextLayout_CaretPolicy::getStrongCaret(TextHitInfo* hit1, TextHitInfo* hit2, TextLayout* layout)
{ /* stub */
unimplemented_(u"java::awt::font::TextHitInfo* java::awt::font::TextLayout_CaretPolicy::getStrongCaret(TextHitInfo* hit1, TextHitInfo* hit2, TextLayout* layout)");
return 0;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* java::awt::font::TextLayout_CaretPolicy::class_()
{
static ::java::lang::Class* c = ::class_(u"java.awt.font.TextLayout.CaretPolicy", 36);
return c;
}
java::lang::Class* java::awt::font::TextLayout_CaretPolicy::getClass0()
{
return class_();
}
| 31.883721
| 167
| 0.716995
|
pebble2015
|
4a9f1b9b1c50adf780dfda7e89ada478540b809e
| 4,156
|
cpp
|
C++
|
src/misc/log-pri-enum.cpp
|
tilnewman/heroespath-src
|
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
|
[
"BSL-1.0",
"Beerware"
] | 2
|
2019-02-28T00:28:08.000Z
|
2019-10-20T14:39:48.000Z
|
src/misc/log-pri-enum.cpp
|
tilnewman/heroespath-src
|
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
|
[
"BSL-1.0",
"Beerware"
] | null | null | null |
src/misc/log-pri-enum.cpp
|
tilnewman/heroespath-src
|
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
|
[
"BSL-1.0",
"Beerware"
] | null | null | null |
// ----------------------------------------------------------------------------
// "THE BEER-WARE LICENSE" (Revision 42):
// <ztn@zurreal.com> wrote this file. As long as you retain this notice you
// can do whatever you want with this stuff. If we meet some day, and you think
// this stuff is worth it, you can buy me a beer in return. Ziesche Til Newman
// ----------------------------------------------------------------------------
//
// log-pri-enum.cpp
//
#include "log-pri-enum.hpp"
#include "misc/platform.hpp"
#include <iostream>
#include <sstream>
namespace heroespath
{
namespace misc
{
const std::string LogPriority::ToString(const Enum PRIORITY)
{
switch (PRIORITY)
{
case Debug:
{
return "Debug";
}
case Default:
{
return "Default";
}
case Warn:
{
return "Warn";
}
case Error:
{
return "Error";
}
case Fatal:
{
return "Fatal";
}
case Count:
{
return "(Count)";
}
default:
{
// can't use log or assert macros inside the logging code
std::ostringstream ss;
ss << __FILE__ << ":" << __func__ << "():" << __LINE__
<< "enum_value=" << static_cast<EnumUnderlying_t>(PRIORITY)
<< " is invalid. (count=" << static_cast<EnumUnderlying_t>(Count) << ")";
std::cerr << ss.str() << std::endl;
return "";
}
}
}
const std::string LogPriority::ToStringAcronym(const Enum PRIORITY)
{
switch (PRIORITY)
{
case Debug:
{
return "DBG";
}
case Default:
{
return "DEF";
}
case Warn:
{
return "WRN";
}
case Error:
{
return "ERR";
}
case Fatal:
{
return "FAT";
}
case Count:
{
return "(Count)";
}
default:
{
// can't use log or assert macros inside the logging code
std::ostringstream ss;
ss << __FILE__ << ":" << __func__ << "():" << __LINE__
<< "enum_value=" << static_cast<EnumUnderlying_t>(PRIORITY)
<< " is invalid. (count=" << static_cast<EnumUnderlying_t>(Count) << ")";
std::cerr << ss.str() << std::endl;
return "";
}
}
}
const std::string LogPriority::ConsoleColorStringBegin(const Enum PRIORITY)
{
// this just prevents a Visual Studio warning that PRIORITY is not used
#if defined(HEROESPATH_PLATFORM_DETECTED_IS_WINDOWS)
const auto IGNORED { PRIORITY };
return "";
#else
switch (PRIORITY)
{
case Debug:
{
// cyan on black
return "\033[36;40m";
}
case Warn:
{
// yellow on black
return "\033[33;40m";
}
case Error:
case Fatal:
{
// red on black
return "\033[31;40m";
}
case Default:
case Count:
{
return "(Count)";
}
default:
{
return "";
}
}
#endif
}
const std::string LogPriority::ConsoleColorStringEnd()
{
#if defined(HEROESPATH_PLATFORM_DETECTED_IS_WINDOWS)
return "";
#else
return "\033[0;0m";
#endif
}
} // namespace misc
} // namespace heroespath
| 25.975
| 93
| 0.394129
|
tilnewman
|
4aa0959a974c32187b532dd2aac8287e8be869ca
| 54
|
cpp
|
C++
|
Algorithm/src/bigword/graph.cpp
|
elloop/algorithm
|
5485be0aedbc18968f775cff9533a2d444dbdcb5
|
[
"MIT"
] | 15
|
2015-11-04T12:53:23.000Z
|
2021-08-10T09:53:12.000Z
|
Algorithm/src/bigword/graph.cpp
|
elloop/algorithm
|
5485be0aedbc18968f775cff9533a2d444dbdcb5
|
[
"MIT"
] | null | null | null |
Algorithm/src/bigword/graph.cpp
|
elloop/algorithm
|
5485be0aedbc18968f775cff9533a2d444dbdcb5
|
[
"MIT"
] | 6
|
2015-11-13T10:17:01.000Z
|
2020-05-14T07:25:48.000Z
|
#include "inc.h"
NS_BEGIN(elloop);
NS_END(elloop);
| 7.714286
| 17
| 0.685185
|
elloop
|
4aa3091a756b04c6d9612c565913cd2d7625d8cf
| 2,516
|
hpp
|
C++
|
src/debug/debugger.hpp
|
MFdesigns/uvm
|
628f6effc9a98adbc9e6e829b60818d8c0865bf9
|
[
"Apache-2.0"
] | 2
|
2020-11-16T22:02:33.000Z
|
2021-03-18T16:36:31.000Z
|
src/debug/debugger.hpp
|
MFdesigns/uvm
|
628f6effc9a98adbc9e6e829b60818d8c0865bf9
|
[
"Apache-2.0"
] | null | null | null |
src/debug/debugger.hpp
|
MFdesigns/uvm
|
628f6effc9a98adbc9e6e829b60818d8c0865bf9
|
[
"Apache-2.0"
] | null | null | null |
// ======================================================================== //
// Copyright 2020 Michel Fäh
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ======================================================================== //
#pragma once
#include "../uvm.hpp"
#include "http.hpp"
#include <cstdint>
#include <memory>
#include <vector>
constexpr uint64_t REQ_MAGIC = 0x3f697a65bcc37247;
constexpr uint64_t RES_MAGIC = 0x4772C3BC657A6921;
// Operation codes
constexpr uint8_t DBG_OPEN_DBG_SESS = 0x01;
constexpr uint8_t DBG_CLOSE_DBG_SESS = 0x02;
constexpr uint8_t DBG_SET_BREAKPNT = 0xB0;
constexpr uint8_t DBG_REMOVE_BREAKPNT = 0xB1;
constexpr uint8_t DBG_RUN_APP = 0xE0;
constexpr uint8_t DBG_NEXT_INSTR = 0xE1;
constexpr uint8_t DBG_CONTINUE_ = 0xE2;
constexpr uint8_t DBG_STOP_EXE = 0xE3;
constexpr uint8_t DBG_GET_REGS = 0x10;
constexpr uint8_t DBG_ERROR = 0xEE;
constexpr uint8_t DBG_EXE_FIN = 0xFF;
// Error codes
constexpr uint8_t ERR_ALREADY_IN_DEBUG_SESSION = 0x1;
constexpr uint8_t ERR_NOT_IN_DEBUG_SESSION = 0x2;
constexpr uint8_t ERR_RUNTIME_ERROR = 0x3;
constexpr uint8_t ERR_FILE_FORMAT_ERROR = 0x4;
constexpr uint8_t ERR_BREAKPOINT_ALREADY_SET = 0x5;
constexpr uint8_t ERR_BREAKPOINT_NOT_EXISTING = 0x6;
enum class DbgSessState {
OPEN,
RUNNING,
CLOSED,
};
struct Debugger {
/** Server handling HTTP requests and responses */
HTTPServer Server;
/** Used to parse incoming requests from the Server */
RequestParser Req;
/** Current UVM instance */
std::unique_ptr<UVM> VM;
/** Session status */
DbgSessState State = DbgSessState::OPEN;
/** List of all currently set breakpoints */
std::vector<uint64_t> Breakpoints;
/** Is UVM currently on a breakpoint */
bool OnBreakpoint = false;
void startSession();
void closeSession();
bool handleRequest(Response& res);
void appendRegisters(std::stringstream& stream);
void appendConsole(std::stringstream& stream);
uint32_t continueToBreakpoint();
};
| 33.546667
| 78
| 0.705087
|
MFdesigns
|
4aa75e1368cd9a7be201b002cee73b125f1a1616
| 3,016
|
cpp
|
C++
|
eyesim_kebabci_yesim_hw5/ConsoleApplication154/main.cpp
|
eyesimk/CS204-Advanced-Programming
|
414a6e1a97aa77bd07f8f3bfbc66da5e3b62421e
|
[
"MIT"
] | null | null | null |
eyesim_kebabci_yesim_hw5/ConsoleApplication154/main.cpp
|
eyesimk/CS204-Advanced-Programming
|
414a6e1a97aa77bd07f8f3bfbc66da5e3b62421e
|
[
"MIT"
] | null | null | null |
eyesim_kebabci_yesim_hw5/ConsoleApplication154/main.cpp
|
eyesimk/CS204-Advanced-Programming
|
414a6e1a97aa77bd07f8f3bfbc66da5e3b62421e
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include <sstream>
#include <string>
#include "Header.h"
//#include your header file here
//do not change anything else
using namespace std;
void printByCopy(Matrix copy) {
copy.print();
}
void fillMatrix(Matrix & mat) {
for (int i = 0; i < mat.getRowNumber(); i++) {
for (int j = 0; j < mat.getColumnNumber(); j++) {
mat.setElementAt(i, j, (i + j + 1)*mat.getElementAt(i,j));
}
}
}
int main()
{
//get matrices
int row, column, init;
cout << "Please enter the row number of Matrix m1:" << endl;
cin >> row;
cout << "Please enter the column number of Matrix m1:" << endl;
cin >> column;
cout << "Please enter the init value of Matrix m1:" << endl;
cin >> init;
cout << endl;
Matrix m1(row, column, init);
fillMatrix(m1);
cout << "Matrix m1:" << endl;
printByCopy(m1);
cout << endl;
cout << "Please enter the row number of Matrix m2:" << endl;
cin >> row;
cout << "Please enter the column number of Matrix m2:" << endl;
cin >> column;
cout << "Please enter the init value of Matrix m2:" << endl;
cin >> init;
cout << endl;
Matrix m2(row, column, init);
fillMatrix(m2);
cout << "Matrix m2:" << endl;
printByCopy(m2);
cout << endl;
cout << "Please enter the row number of Matrix m3:" << endl;
cin >> row;
cout << "Please enter the column number of Matrix m3:" << endl;
cin >> column;
cout << "Please enter the init value of Matrix m3:" << endl;
cin >> init;
cout << endl;
Matrix m3(row, column, init);
fillMatrix(m3);
cout << "Matrix m3:" << endl;
printByCopy(m3);
cout << endl;
//assigment example
Matrix m4;
m4 = m3;
cout << "Matrix m4:" << endl;
printByCopy(m4);
cout << endl;
//equals example
if (m1 == m2) {
cout << "m1 is equal to m2." << endl;
cout << endl;
}
else {
cout << "m1 is not equal to m2." << endl;
cout << endl;
}
//addition example
cout << "m3 = m1 + m2 + m1:" << endl;
if (m1.getColumnNumber()== m2.getColumnNumber() && m1.getRowNumber() == m2.getRowNumber()) {
m3 = m1 + m2 + m1;
m3.print();
cout << endl;
}
else {
cout << "Matrix m1 and m2 do not have the same dimensions. Cannot be added." << endl;
cout << endl;
}
//substraction example
cout << "m4 = m2 - m1 - m2:" << endl;
if (m1.getColumnNumber() == m2.getColumnNumber() && m1.getRowNumber() == m2.getRowNumber()) {
m4 = m2 - m1 - m2;
m4.print();
cout << endl;
}
else {
cout << "Matrix m1 and m2 do not have the same dimensions. Cannot be subtracted." << endl;
cout << endl;
}
//transpose example
cout << "Transpose of m3:" << endl;
m3 = !m3;
m3.print();
cout << endl;
//cascaded assignment
cout << "Assigning m4 = m2 = m3." << endl;
m4 = m2 = m3;
cout << "Matrix m4:" << endl;
m4.print();
cout << endl;
cout << "Matrix m2:" << endl;
m2.print();
cout << endl;
cout << "Matrix m3:" << endl;
m3.print();
cout << endl;
cin.get();
cin.ignore();
return 0;
}
| 23.022901
| 95
| 0.575597
|
eyesimk
|
4aa8745a2b7c89c60c1324304802ba09d928b697
| 9,330
|
cpp
|
C++
|
src/AC3DPlugins/bitmap_match.cpp
|
rromanchuk/xptools
|
deff017fecd406e24f60dfa6aae296a0b30bff56
|
[
"X11",
"MIT"
] | 71
|
2015-12-15T19:32:27.000Z
|
2022-02-25T04:46:01.000Z
|
src/AC3DPlugins/bitmap_match.cpp
|
rromanchuk/xptools
|
deff017fecd406e24f60dfa6aae296a0b30bff56
|
[
"X11",
"MIT"
] | 19
|
2016-07-09T19:08:15.000Z
|
2021-07-29T10:30:20.000Z
|
src/AC3DPlugins/bitmap_match.cpp
|
rromanchuk/xptools
|
deff017fecd406e24f60dfa6aae296a0b30bff56
|
[
"X11",
"MIT"
] | 42
|
2015-12-14T19:13:02.000Z
|
2022-03-01T15:15:03.000Z
|
/*
* Copyright (c) 2007, Laminar Research.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "bitmap_match.h"
#include "TclStubs.h"
#include <ac_plugin.h>
#include <stdio.h>
#include <string.h>
#ifndef IBM
#include <stdint.h>
#endif
static unsigned char * get_image_data(ACImage * im);
static unsigned char * get_image_data(ACImage * im)
{
int addr;
if (!ac_entity_get_int_value(im, (char*)"data", &addr)) return NULL;
uintptr_t a = (uintptr_t)addr;
return (unsigned char *) a;
}
/*
* bitmap_match
*
* Given two bitmaps, this routine returns true if sub is fully contained
* within main, and sets h_offset and v_offset to the offsets within those
* bitmaps. Sub and main must be of the same bit depth!
*
* The algorithm works by brute force...for each possible position of sub,
* it attempts to check every pixel of sub against main. Surprisingly, this
* algorithm executes very rapidly for 512x256 bitmaps on my P-IV, so I haven't
* bothered to optimize it. (Authors will only be doing this every once in a
* while anyway.) The early exit from a mismatch probably helps speed a lot.
*
* One possible optimization: use an adam7-like order of traversals of the pixels
* in checking for a match. This would cause us to jump all around the bitmap,
* finding mismatches faster even if the upper left local area corner is just
* transparent or a solid color in both.
*
*/
int bitmap_match(
ACImage * sub,
ACImage * main,
int * h_offset,
int * v_offset)
{
int main_width, main_height, main_depth;
int sub_width, sub_height, sub_depth;
ac_image_get_dim(main, &main_width, &main_height, &main_depth);
ac_image_get_dim(sub, &sub_width, &sub_height, &sub_depth);
char * subname, * mainname;
ac_entity_get_string_value(sub, (char*)"name", &subname);
ac_entity_get_string_value(main, (char*)"name", &mainname);
if (sub_depth != main_depth)
{
if (sub_depth == 3 && main_depth == 4)
message_dialog((char*)"Could not match bitmaps because bitmaps '%s' has alpha and '%s' does not.", mainname, subname);
else if (sub_depth == 4 && main_depth == 3)
message_dialog((char*)"Could not match bitmaps because bitmaps '%s' has alpha and '%s' does not.", subname, mainname);
else
message_dialog((char*)"Could not match bitmaps because bitmaps '%s' and '%s' have different color depths.", subname, mainname);
return 0;
}
if (sub_width > main_width || sub_height > main_height)
{
message_dialog((char*)"Could not match bitmaps because new bitmap '%s' is smaller than old bitmap '%s'.", mainname, subname);
return 0;
}
unsigned char * maind = get_image_data(main);
unsigned char * subd = get_image_data(sub);
for (int x_off = 0; x_off <= (main_width - sub_width); ++x_off)
for (int y_off = 0; y_off <= (main_height - sub_height); ++y_off)
{
int match = 1;
for (int x_pixel = 0; x_pixel < sub_width; ++x_pixel)
for (int y_pixel = 0; y_pixel < sub_height; ++y_pixel)
{
unsigned char * mainp =
maind +
(x_off + x_pixel) * main_depth +
(y_off + y_pixel) * main_depth * main_width;
unsigned char * subp =
subd +
(x_pixel) * sub_depth +
(y_pixel) * sub_depth * sub_width;
for (int c = 0; c < sub_depth; ++c)
if (subp[c] != mainp[c])
{
match = 0;
goto nomatch;
}
}
*h_offset = x_off;
*v_offset = y_off;
return 1;
nomatch:
match = 0;
}
return 0;
}
/*
* apply_lighting
*
* Given a day and night overlay bitmap, this routine adds the night overlay
* to the day bitmap (they must be the same size), and reduces the day's
* brightness too, to simulate x-plane night lighting.
*
*/
int apply_lighting(
ACImage * day,
ACImage * night)
{
int day_width, day_height, day_depth;
int night_width, night_height, night_depth;
ac_image_get_dim(day, &day_width, &day_height, &day_depth);
ac_image_get_dim(night, &night_width, &night_height, &night_depth);
if (day_width != night_width) return 0;
if (day_height != night_height) return 0;
if (day_depth != 3 && day_depth != 4) return 0;
if (night_depth != 3 && night_depth != 4) return 0;
void * new_mem = myalloc(day_width * day_height * day_depth);
unsigned char * dayd = get_image_data(day);
unsigned char * nightd = get_image_data(night);
unsigned char * destd = (unsigned char *) new_mem;
int channels = (night_depth > day_depth) ? day_depth : night_depth;
int x, y, c;
for (y = 0; y < day_height; ++y)
for (x = 0; x < day_width; ++x)
{
unsigned char * dayp = dayd +
x * day_depth +
y * day_depth * day_width;
unsigned char * nightp = nightd +
x * night_depth +
y * night_depth * night_width;
unsigned char * destp = destd +
x * day_depth +
y * day_depth * day_width;
for (c = 0; c < channels; ++c)
{
unsigned long v = (dayp[c] >> 6) + nightp[c];
if (v > 255) v = 255;
destp[c] = v;
}
if (channels == 3 && day_depth == 4)
{
destp[c] = dayp[c];
}
}
ac_image_set_data(day, destd);
texture_build_for_all_windows(day);
redraw_all();
return 1;
}
/*
* Given a non-alpha-channel 24 bit image, this routine converts it to a 32-bit
* ARGB image and makes pure magenta (FF00FF) pixels transparent, allowing users
* to preview transparency for BMP textured objects.
*
* WARNING: this routine does not properly implement color smearing near magenta
* pixels, so there may be artifacts around transparent areas. Frankly this is
* acceptable, it's just a preview, and authors should be working with PNG anyway.
*
*/
int make_transparent(ACImage * im)
{
int im_width, im_height, im_depth;
ac_image_get_dim(im, &im_width, &im_height, &im_depth);
if (im_depth != 3)
{
message_dialog((char*)"Bitmap already has an alpha channel.");
printf("Image is not depth 3.\n");
return 0;
}
void * new_mem = myalloc(im_width * im_height * 4);
unsigned char * srcd = get_image_data(im);
unsigned char * dstd = (unsigned char *) new_mem;
int transparent = 0;
for (int y = 0; y < im_height; ++y)
for (int x = 0; x < im_width; ++ x)
{
unsigned char * srcp = srcd + x * 3 + y * im_width * 3;
unsigned char * dstp = dstd + x * 4 + y * im_width * 4;
if (srcp[0] == 255 && srcp[1] == 0 && srcp[2] == 255)
{
++transparent;
dstp[0] = dstp[1] = dstp[2] = dstp[3] = 0;
} else {
dstp[0] = srcp[0];
dstp[1] = srcp[1];
dstp[2] = srcp[2];
dstp[3] = 255;
}
}
ac_image_set_alpha_mask(im, ALPHA_TRANSP);
ac_image_set_dim(im, im_width, im_height, 4);
ac_image_set_data(im, dstd);
texture_build_for_all_windows(im);
redraw_all();
if (transparent == 0)
message_dialog((char*)"No magenta pixels were found.");
printf("Rendered %d pixels transparent.\n", transparent);
return 1;
}
void tex_reload(int tex_id)
{
char * fname = texture_id_to_name(tex_id);
// int im_width, im_height, im_depth;
texture_build_for_all_windows(texture_id_to_image(add_new_texture_reload(fname,fname)));
redraw_all();
return;
/*
ACImage * old_image = texture_id_to_image(tex_id);
ACImage * new_image = new_acimage(fname);
if (new_image == NULL)
{
message_dialog("Error: could not load %s.\n", fname);
return;
}
ac_image_get_dim(new_image, &im_width, &im_height, &im_depth);
ac_image_set_dim(old_image, im_width, im_height, im_depth);
void * new_mem = myalloc(im_width * im_height * im_depth);
memcpy(new_mem, get_image_data(new_image), im_width * im_height * im_depth);
ac_image_set_data(old_image, (unsigned char *) new_mem);
free_acimage(new_image);
texture_build_for_all_windows(old_image);
redraw_all();
*/
}
void bitmap_subcopy(
ACImage * src,
ACImage * dst,
int l,
int b,
int r,
int t)
{
int im_width, im_height, im_depth;
ac_image_get_dim(src, &im_width, &im_height, &im_depth);
void * new_mem = myalloc((r-l) * (t-b) * im_depth);
unsigned char * srcd = get_image_data(src);
unsigned char * dstd = (unsigned char *) new_mem;
for (int y = b; y < t; ++y)
for (int x = l; x < r; ++ x)
{
unsigned char * srcp = srcd + x * im_depth + y * im_width * im_depth;
unsigned char * dstp = dstd + (x-l) * im_depth + (y-b) * (r-l) * im_depth;
int c = im_depth;
while(c--)
*dstp++ = *srcp++;
}
ac_image_set_dim(dst, r-l, t-b, im_depth);
ac_image_set_data(dst, dstd);
texture_build_for_all_windows(dst);
redraw_all();
}
| 29.15625
| 130
| 0.683494
|
rromanchuk
|
4aabe2ae756f12be5329773dd33dc68f447edc55
| 5,019
|
cc
|
C++
|
src/lib/JANA/JParameterManager.cc
|
mayank185T9/JANA
|
58bc4c3dadde185a6bbfd83fe21f9c51df941ce5
|
[
"Apache-2.0"
] | null | null | null |
src/lib/JANA/JParameterManager.cc
|
mayank185T9/JANA
|
58bc4c3dadde185a6bbfd83fe21f9c51df941ce5
|
[
"Apache-2.0"
] | 2
|
2018-04-12T11:25:48.000Z
|
2019-04-17T12:59:29.000Z
|
src/lib/JANA/JParameterManager.cc
|
mayank185T9/JANA
|
58bc4c3dadde185a6bbfd83fe21f9c51df941ce5
|
[
"Apache-2.0"
] | 2
|
2018-01-16T14:41:04.000Z
|
2019-03-26T17:43:19.000Z
|
//
// File: JParameterManager.cc
// Created: Thu Oct 12 08:16:11 EDT 2017
// Creator: davidl (on Darwin harriet.jlab.org 15.6.0 i386)
//
// ------ Last repository commit info -----
// [ Date ]
// [ Author ]
// [ Source ]
// [ Revision ]
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Jefferson Science Associates LLC Copyright Notice:
// Copyright 251 2014 Jefferson Science Associates LLC All Rights Reserved. Redistribution
// and use in source and binary forms, with or without modification, are permitted as a
// licensed user provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
// This material resulted from work developed under a United States Government Contract.
// The Government retains a paid-up, nonexclusive, irrevocable worldwide license in such
// copyrighted data to reproduce, distribute copies to the public, prepare derivative works,
// perform publicly and display publicly and to permit others to do so.
// THIS SOFTWARE IS PROVIDED BY JEFFERSON SCIENCE ASSOCIATES LLC "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
// JEFFERSON SCIENCE ASSOCIATES, LLC OR THE U.S. GOVERNMENT BE LIABLE TO LICENSEE OR ANY
// THIRD PARTES 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 "JParameterManager.h"
#include "JLogger.h"
using namespace std;
//---------------------------------
// JParameterManager (Constructor)
//---------------------------------
JParameterManager::JParameterManager() { }
//---------------------------------
// ~JParameterManager (Destructor)
//---------------------------------
JParameterManager::~JParameterManager()
{
for( auto p : _jparameters ) delete p.second;
_jparameters.clear();
}
//---------------------------------
// Exists
//---------------------------------
bool JParameterManager::Exists(string name)
{
return _jparameters.count( ToLC(name) ) != 0;
}
//---------------------------------
// FindParameter
//---------------------------------
JParameter* JParameterManager::FindParameter(std::string name)
{
if( ! Exists(name) ) return nullptr;
return _jparameters[ ToLC(name) ];
}
//---------------------------------
// PrintParameters
//---------------------------------
void JParameterManager::PrintParameters(bool all)
{
/// Print configuration parameters to stdout.
/// If "all" is false (default) then only parameters
/// whose values are different than their default are
/// printed.
/// If "all" is true then all parameters are
/// printed.
// Find maximum key length
uint32_t max_key_len = 4;
vector<string> keys;
for(auto &p : _jparameters){
string key = p.first;
auto j = p.second;
if( (!all) && j->IsDefault() ) continue;
keys.push_back( key );
if( key.length()>max_key_len ) max_key_len = key.length();
}
// If all params are set to default values, then print a one line
// summary
if(keys.empty()){
JLog() << "All configuration parameters set to default values." << JLogEnd();
return;
}
// Print title/header
string title("Config. Parameters");
uint32_t half_title_len = 1+title.length()/2;
if( max_key_len < half_title_len ) max_key_len = half_title_len;
JLog() << "\n" << JLogEnd();
JLog() << string(max_key_len+4-half_title_len, ' ') << title << "\n" << JLogEnd();
JLog() << " " << string(2*max_key_len + 3, '=') << "\n" << JLogEnd();
JLog() << string(max_key_len/2, ' ') << "name" << string(max_key_len, ' ') << "value" << "\n" << JLogEnd();
JLog() << " " << string(max_key_len, '-') << " " << string(max_key_len, '-') << "\n" << JLogEnd();
// Print all parameters
for(string &key : keys){
auto name = _jparameters[key]->GetName();
string val = _jparameters[key]->GetValue<string>();
JLog() << string(max_key_len+2-key.length(),' ') << name << " = " << val << "\n" << JLogEnd();
}
JLog() << "\n" << JLogEnd();
}
| 39.210938
| 108
| 0.625423
|
mayank185T9
|
4ab070033060eed49e14d5fa2bbbd3579b63ed98
| 709
|
cpp
|
C++
|
luogu/1068.cpp
|
shorn1/OI-ICPC-Problems
|
0c18b3297190a0e108c311c74d28351ebc70c3d1
|
[
"MIT"
] | 1
|
2020-05-07T09:26:05.000Z
|
2020-05-07T09:26:05.000Z
|
luogu/1068.cpp
|
shorn1/OI-ICPC-Problems
|
0c18b3297190a0e108c311c74d28351ebc70c3d1
|
[
"MIT"
] | null | null | null |
luogu/1068.cpp
|
shorn1/OI-ICPC-Problems
|
0c18b3297190a0e108c311c74d28351ebc70c3d1
|
[
"MIT"
] | null | null | null |
#include<cmath>
#include<cctype>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ns namespace
#define lol long long
using ns std;
int n,m;
struct Std
{
int k,s;
bool operator < (const Std &x) const
{
return s == x.s ? k < x.k : s > x.s;
}
}a[23333];
int main(int argc,char** argv)
{
cin >> n >> m;
for(int i = 1;i <= n;i++)
{
scanf("%d%d",&a[i].k,&a[i].s);
}
sort(a+1,a+1+n);
int t = static_cast<int>(1.5 * static_cast<double>(m));
while(a[t].s == a[t+1].s) ++t;
printf("%d %d\n",a[t].s,t);
for(int i = 1;i <= t;i++)
{
printf("%d %d\n",a[i].k,a[i].s);
}
return 0;
}
| 17.725
| 59
| 0.513399
|
shorn1
|
4ab2887f7b92ea9ed4e9b11b726f73c0d1f86686
| 15,466
|
hpp
|
C++
|
renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/cppad/local/checkpoint.hpp
|
rebeccagb/gtsummary
|
04996e385acab0b76a9938378e8af87526117aef
|
[
"MIT"
] | null | null | null |
renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/cppad/local/checkpoint.hpp
|
rebeccagb/gtsummary
|
04996e385acab0b76a9938378e8af87526117aef
|
[
"MIT"
] | null | null | null |
renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/cppad/local/checkpoint.hpp
|
rebeccagb/gtsummary
|
04996e385acab0b76a9938378e8af87526117aef
|
[
"MIT"
] | null | null | null |
/* $Id$ */
# ifndef CPPAD_CHECKPOINT_INCLUDED
# define CPPAD_CHECKPOINT_INCLUDED
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-15 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
GNU General Public License Version 3.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
namespace CppAD { // BEGIN_CPPAD_NAMESPACE
/*!
\file checkpoint.hpp
defining checkpoint functions.
*/
/*
$begin checkpoint$$
$spell
cppad.hpp
CppAD
checkpoint
checkpointing
algo
afun
const
$$
$section Checkpointing Functions$$
$index function, checkpoint$$
$index checkpoint, function$$
$head Syntax$$
$codei%checkpoint<%Base%> %afun%(%name%, %algo%, %ax%, %ay%)
%afun%.option(%option_value%)
%algo%(%ax%, %ay%)
%afun%(%ax%, %ay%)
checkpoint<%Base%>::clear()%$$
$head Purpose$$
You can reduce the size of the tape and memory required for AD by
checkpointing functions of the form $latex y = f(x)$$ where
$latex f : B^n \rightarrow B^m$$.
$head Method$$
The $code checkpoint$$ class is derived from $code atomic_base$$
and makes this easy.
It implements all the $code atomic_base$$
$cref/virtual functions/atomic_base/Virtual Functions/$$
and hence its source code $code cppad/local/checkpoint.hpp$$
provides an example implementation of $cref atomic_base$$.
The difference is that $code checkpoint.hpp$$ uses AD
instead of user provided derivatives.
$head constructor$$
The constructor
$codei%
checkpoint<%Base%> %afun%(%name%, %algo%, %ax%, %ay%)
%$$
cannot be called in $cref/parallel/ta_in_parallel/$$ mode.
In addition, you cannot currently be recording
$codei%AD<%Base%>%$$ operations when the constructor is called.
This class is implemented as a derived class of
$cref/atomic_base/atomic_ctor/atomic_base/$$ and hence
some of its error message will refer to $code atomic_base$$.
$head Base$$
The type $icode Base$$ specifies the base type for AD operations.
$head ADVector$$
The type $icode ADVector$$ must be a
$cref/simple vector class/SimpleVector/$$ with elements of type
$codei%AD<%Base%>%$$.
$head name$$
This $icode checkpoint$$ constructor argument has prototype
$codei%
const char* %name%
%$$
It is the name used for error reporting.
The suggested value for $icode name$$ is $icode afun$$; i.e.,
the same name as used for the function.
$head ax$$
This argument has prototype
$codei%
const %ADVector%& %ax%
%$$
and size must be equal to $icode n$$.
It specifies vector $latex x \in B^n$$
at which an $codei%AD<%Base%>%$$ version of
$latex y = f(x)$$ is to be evaluated.
$head ay$$
This argument has prototype
$codei%
%ADVector%& %ay%
%$$
Its input size must be equal to $icode m$$ and does not change.
The input values of its elements do not matter.
Upon return, it is an $codei%AD<%Base%>%$$ version of
$latex y = f(x)$$.
$head option$$
The $code option$$ syntax can be used to set the type of sparsity
pattern used by $icode afun$$.
This is an $codei%atomic_base<%Base%>%$$ function and its documentation
can be found at $cref atomic_option$$.
$head algo$$
The type of $icode algo$$ is arbitrary, except for the fact that
the syntax
$codei%
%algo%(%ax%, %ay%)
%$$
must evaluate the function $latex y = f(x)$$ using
$codei%AD<%Base%>%$$ operations.
In addition, we assume that the
$cref/operation sequence/glossary/Operation/Sequence/$$
does not depend on the value of $icode ax$$.
$head afun$$
Given $icode ax$$ it computes the corresponding value of $icode ay$$
using the operation sequence corresponding to $icode algo$$.
If $codei%AD<%Base%>%$$ operations are being recorded,
it enters the computation as single operation in the recording
see $cref/start recording/Independent/Start Recording/$$.
(Currently each use of $icode afun$$ actually corresponds to
$icode%m%+%n%+2%$$ operations and creates $icode m$$ new variables,
but this is not part of the CppAD specifications and my change.)
$head clear$$
The $code atomic_base$$ class holds onto static work space in order to
increase speed by avoiding system memory allocation calls.
This call makes to work space $cref/available/ta_available/$$ to
for other uses by the same thread.
This should be called when you are done using the
user atomic functions for a specific value of $icode Base$$.
$subhead Restriction$$
The $code clear$$ routine cannot be called
while in $cref/parallel/ta_in_parallel/$$ execution mode.
$children%
example/atomic/checkpoint.cpp
%$$
$head Example$$
The file $cref checkpoint.cpp$$ contains an example and test
of these operations.
It returns true if it succeeds and false if it fails.
$end
*/
template <class Base>
class checkpoint : public atomic_base<Base> {
private:
vector<ADFun<Base> > f_;
public:
/*!
Constructor of a checkpoint object
\param name [in]
is the user's name for the AD version of this atomic operation.
\param algo [in/out]
user routine that compute AD function values
(not const because state may change during evaluation).
\param ax [in]
argument value where algo operation sequence is taped.
\param ay [out]
function value at specified argument value.
*/
template <class Algo, class ADVector>
checkpoint(const char* name,
Algo& algo, const ADVector& ax, ADVector& ay)
: atomic_base<Base>(name)
{ CheckSimpleVector< CppAD::AD<Base> , ADVector>();
#ifdef _OPENMP
#define NTHREADS omp_get_max_threads()
#define THREAD omp_get_thread_num()
#else
#define NTHREADS 1
#define THREAD 0
#endif
f_.resize(NTHREADS);
// make a copy of ax because Independent modifies AD information
ADVector x_tmp(ax);
// delcare x_tmp as the independent variables
Independent(x_tmp);
// record mapping from x_tmp to ay
algo(x_tmp, ay);
// create function f_ : x -> y
f_[0].Dependent(ay);
// suppress checking for nan in f_ results
// (see optimize documentation for atomic functions)
f_[0].check_for_nan(false);
// now optimize (we expect to use this function many times).
f_[0].optimize();
// Copy for other threads
for(size_t i=1;i<NTHREADS;i++)f_[i]=f_[0];
// now disable checking of comparison opertaions
// 2DO: add a debugging mode that checks for changes and aborts
f_[0].compare_change_count(0);
}
/*!
Implement the user call to <tt>afun(ax, ay)</tt>.
\tparam ADVector
A simple vector class with elements of type <code>AD<Base></code>.
\param id
optional parameter which must be zero if present.
\param ax
is the argument vector for this call,
<tt>ax.size()</tt> determines the number of arguments.
\param ay
is the result vector for this call,
<tt>ay.size()</tt> determines the number of results.
*/
template <class ADVector>
void operator()(const ADVector& ax, ADVector& ay, size_t id = 0)
{ CPPAD_ASSERT_KNOWN(
id == 0,
"checkpoint: id is non-zero in afun(ax, ay, id)"
);
this->atomic_base<Base>::operator()(ax, ay, id);
}
/*!
Link from user_atomic to forward mode
\copydetails atomic_base::forward
*/
virtual bool forward(
size_t p ,
size_t q ,
const vector<bool>& vx ,
vector<bool>& vy ,
const vector<Base>& tx ,
vector<Base>& ty )
{
CPPAD_ASSERT_UNKNOWN( f_[THREAD].size_var() > 0 );
CPPAD_ASSERT_UNKNOWN( tx.size() % (q+1) == 0 );
CPPAD_ASSERT_UNKNOWN( ty.size() % (q+1) == 0 );
size_t n = tx.size() / (q+1);
size_t m = ty.size() / (q+1);
bool ok = true;
size_t i, j;
// 2DO: test both forward and reverse vy information
if( vx.size() > 0 )
{ //Compute Jacobian sparsity pattern.
vector< std::set<size_t> > s(m);
if( n <= m )
{ vector< std::set<size_t> > r(n);
for(j = 0; j < n; j++)
r[j].insert(j);
s = f_[THREAD].ForSparseJac(n, r);
}
else
{ vector< std::set<size_t> > r(m);
for(i = 0; i < m; i++)
r[i].insert(i);
s = f_[THREAD].RevSparseJac(m, r);
}
std::set<size_t>::const_iterator itr;
for(i = 0; i < m; i++)
{ vy[i] = false;
for(itr = s[i].begin(); itr != s[i].end(); itr++)
{ j = *itr;
assert( j < n );
// y[i] depends on the value of x[j]
vy[i] |= vx[j];
}
}
}
ty = f_.Forward(q, tx);
// no longer need the Taylor coefficients in f_
// (have to reconstruct them every time)
size_t c = 0;
size_t r = 0;
f_.capacity_order(c, r);
return ok;
}
/*!
Link from user_atomic to reverse mode
\copydetails atomic_base::reverse
*/
virtual bool reverse(
size_t q ,
const vector<Base>& tx ,
const vector<Base>& ty ,
vector<Base>& px ,
const vector<Base>& py )
{
CPPAD_ASSERT_UNKNOWN( f_[THREAD].size_var() > 0 );
CPPAD_ASSERT_UNKNOWN( tx.size() % (q+1) == 0 );
CPPAD_ASSERT_UNKNOWN( ty.size() % (q+1) == 0 );
bool ok = true;
// put proper forward mode coefficients in f_
# ifdef NDEBUG
f_[THREAD].Forward(q, tx);
# else
size_t n = tx.size() / (q+1);
size_t m = ty.size() / (q+1);
CPPAD_ASSERT_UNKNOWN( px.size() == n * (q+1) );
CPPAD_ASSERT_UNKNOWN( py.size() == m * (q+1) );
size_t i, j, k;
//
vector<Base> check_ty = f_[THREAD].Forward(q, tx);
for(i = 0; i < m; i++)
{ for(k = 0; k <= q; k++)
{ j = i * (q+1) + k;
CPPAD_ASSERT_UNKNOWN( check_ty[j] == ty[j] );
}
}
# endif
// now can run reverse mode
px = f_[THREAD].Reverse(q+1, py);
// no longer need the Taylor coefficients in f_
// (have to reconstruct them every time)
size_t c = 0;
size_t r = 0;
f_[THREAD].capacity_order(c, r);
return ok;
}
/*!
Link from user_atomic to forward sparse Jacobian
\copydetails atomic_base::for_sparse_jac
*/
virtual bool for_sparse_jac(
size_t q ,
const vector< std::set<size_t> >& r ,
vector< std::set<size_t> >& s )
{
bool ok = true;
s = f_[THREAD].ForSparseJac(q, r);
// no longer need the forward mode sparsity pattern
// (have to reconstruct them every time)
f_[THREAD].size_forward_set(0);
return ok;
}
/*!
Link from user_atomic to forward sparse Jacobian
\copydetails atomic_base::for_sparse_jac
*/
virtual bool for_sparse_jac(
size_t q ,
const vector<bool>& r ,
vector<bool>& s )
{
bool ok = true;
s = f_[THREAD].ForSparseJac(q, r);
// no longer need the forward mode sparsity pattern
// (have to reconstruct them every time)
f_[THREAD].size_forward_bool(0);
return ok;
}
/*!
Link from user_atomic to forward sparse Jacobian
\copydetails atomic_base::rev_sparse_jac
*/
virtual bool rev_sparse_jac(
size_t q ,
const vector< std::set<size_t> >& rt ,
vector< std::set<size_t> >& st )
{
bool ok = true;
// compute rt
// 2DO: remove need for nz_compare all the time. It is only really
// necessary when optimizer calls this member function.
bool transpose = true;
bool nz_compare = true;
st = f_[THREAD].RevSparseJac(q, rt, transpose, nz_compare);
return ok;
}
/*!
Link from user_atomic to forward sparse Jacobian
\copydetails atomic_base::rev_sparse_jac
*/
virtual bool rev_sparse_jac(
size_t q ,
const vector<bool>& rt ,
vector<bool>& st )
{
bool ok = true;
// compute rt
bool transpose = true;
bool nz_compare = true;
// 2DO: remove need for nz_compare all the time. It is only really
// necessary when optimizer calls this member function.
st = f_[THREAD].RevSparseJac(q, rt, transpose, nz_compare);
return ok;
}
/*!
Link from user_atomic to forward sparse Jacobian
\copydetails atomic_base::rev_sparse_hes
*/
virtual bool rev_sparse_hes(
const vector<bool>& vx ,
const vector<bool>& s ,
vector<bool>& t ,
size_t q ,
const vector< std::set<size_t> >& r ,
const vector< std::set<size_t> >& u ,
vector< std::set<size_t> >& v )
{ size_t n = v.size();
size_t m = u.size();
CPPAD_ASSERT_UNKNOWN( r.size() == v.size() );
CPPAD_ASSERT_UNKNOWN( s.size() == m );
CPPAD_ASSERT_UNKNOWN( t.size() == n );
bool ok = true;
bool transpose = true;
std::set<size_t>::const_iterator itr;
// compute sparsity pattern for T(x) = S(x) * f'(x)
t = f_[THREAD].RevSparseJac(1, s);
# ifndef NDEBUG
for(size_t j = 0; j < n; j++)
CPPAD_ASSERT_UNKNOWN( vx[j] || ! t[j] )
# endif
// V(x) = f'(x)^T * g''(y) * f'(x) * R + g'(y) * f''(x) * R
// U(x) = g''(y) * f'(x) * R
// S(x) = g'(y)
// compute sparsity pattern for A(x) = f'(x)^T * U(x)
vector< std::set<size_t> > a(n);
a = f_[THREAD].RevSparseJac(q, u, transpose);
// set version of s
vector< std::set<size_t> > set_s(1);
CPPAD_ASSERT_UNKNOWN( set_s[0].empty() );
size_t i;
for(i = 0; i < m; i++)
if( s[i] )
set_s[0].insert(i);
// compute sparsity pattern for H(x) = (S(x) * F)''(x) * R
// (store it in v)
f_[THREAD].ForSparseJac(q, r);
v = f_[THREAD].RevSparseHes(q, set_s, transpose);
// compute sparsity pattern for V(x) = A(x) + H(x)
for(i = 0; i < n; i++)
{ for(itr = a[i].begin(); itr != a[i].end(); itr++)
{ size_t j = *itr;
CPPAD_ASSERT_UNKNOWN( j < q );
v[i].insert(j);
}
}
// no longer need the forward mode sparsity pattern
// (have to reconstruct them every time)
f_[THREAD].size_forward_set(0);
return ok;
}
/*!
Link from user_atomic to forward sparse Jacobian
\copydetails atomic_base::rev_sparse_hes
*/
virtual bool rev_sparse_hes(
const vector<bool>& vx ,
const vector<bool>& s ,
vector<bool>& t ,
size_t q ,
const vector<bool>& r ,
const vector<bool>& u ,
vector<bool>& v )
{
CPPAD_ASSERT_UNKNOWN( r.size() == v.size() );
CPPAD_ASSERT_UNKNOWN( s.size() == u.size() / q );
CPPAD_ASSERT_UNKNOWN( t.size() == v.size() / q );
size_t n = t.size();
bool ok = true;
bool transpose = true;
std::set<size_t>::const_iterator itr;
size_t i, j;
// compute sparsity pattern for T(x) = S(x) * f'(x)
t = f_[THREAD].RevSparseJac(1, s);
# ifndef NDEBUG
for(j = 0; j < n; j++)
CPPAD_ASSERT_UNKNOWN( vx[j] || ! t[j] )
# endif
// V(x) = f'(x)^T * g''(y) * f'(x) * R + g'(y) * f''(x) * R
// U(x) = g''(y) * f'(x) * R
// S(x) = g'(y)
// compute sparsity pattern for A(x) = f'(x)^T * U(x)
vector<bool> a(n * q);
a = f_[THREAD].RevSparseJac(q, u, transpose);
// compute sparsity pattern for H(x) =(S(x) * F)''(x) * R
// (store it in v)
f_[THREAD].ForSparseJac(q, r);
v = f_[THREAD].RevSparseHes(q, s, transpose);
// compute sparsity pattern for V(x) = A(x) + H(x)
for(i = 0; i < n; i++)
{ for(j = 0; j < q; j++)
v[ i * q + j ] |= a[ i * q + j];
}
// no longer need the forward mode sparsity pattern
// (have to reconstruct them every time)
f_[THREAD].size_forward_set(0);
return ok;
}
};
} // END_CPPAD_NAMESPACE
# endif
#undef NTHREADS
#undef THREAD
| 28.274223
| 77
| 0.622074
|
rebeccagb
|
385f07b28d4055d64ab07f828fee900a7b80b509
| 7,193
|
cpp
|
C++
|
higan/processor/r65816/algorithms.cpp
|
ameer-bauer/higan-097
|
a4a28968173ead8251cfa7cd6b5bf963ee68308f
|
[
"Info-ZIP"
] | 3
|
2016-03-23T01:17:36.000Z
|
2019-10-25T06:41:09.000Z
|
higan/processor/r65816/algorithms.cpp
|
ameer-bauer/higan-097
|
a4a28968173ead8251cfa7cd6b5bf963ee68308f
|
[
"Info-ZIP"
] | null | null | null |
higan/processor/r65816/algorithms.cpp
|
ameer-bauer/higan-097
|
a4a28968173ead8251cfa7cd6b5bf963ee68308f
|
[
"Info-ZIP"
] | null | null | null |
auto R65816::op_adc_b() {
int result;
if(!regs.p.d) {
result = regs.a.l + rd.l + regs.p.c;
} else {
result = (regs.a.l & 0x0f) + (rd.l & 0x0f) + (regs.p.c << 0);
if(result > 0x09) result += 0x06;
regs.p.c = result > 0x0f;
result = (regs.a.l & 0xf0) + (rd.l & 0xf0) + (regs.p.c << 4) + (result & 0x0f);
}
regs.p.v = ~(regs.a.l ^ rd.l) & (regs.a.l ^ result) & 0x80;
if(regs.p.d && result > 0x9f) result += 0x60;
regs.p.c = result > 0xff;
regs.p.n = result & 0x80;
regs.p.z = (uint8_t)result == 0;
regs.a.l = result;
}
auto R65816::op_adc_w() {
int result;
if(!regs.p.d) {
result = regs.a.w + rd.w + regs.p.c;
} else {
result = (regs.a.w & 0x000f) + (rd.w & 0x000f) + (regs.p.c << 0);
if(result > 0x0009) result += 0x0006;
regs.p.c = result > 0x000f;
result = (regs.a.w & 0x00f0) + (rd.w & 0x00f0) + (regs.p.c << 4) + (result & 0x000f);
if(result > 0x009f) result += 0x0060;
regs.p.c = result > 0x00ff;
result = (regs.a.w & 0x0f00) + (rd.w & 0x0f00) + (regs.p.c << 8) + (result & 0x00ff);
if(result > 0x09ff) result += 0x0600;
regs.p.c = result > 0x0fff;
result = (regs.a.w & 0xf000) + (rd.w & 0xf000) + (regs.p.c << 12) + (result & 0x0fff);
}
regs.p.v = ~(regs.a.w ^ rd.w) & (regs.a.w ^ result) & 0x8000;
if(regs.p.d && result > 0x9fff) result += 0x6000;
regs.p.c = result > 0xffff;
regs.p.n = result & 0x8000;
regs.p.z = (uint16_t)result == 0;
regs.a.w = result;
}
auto R65816::op_and_b() {
regs.a.l &= rd.l;
regs.p.n = regs.a.l & 0x80;
regs.p.z = regs.a.l == 0;
}
auto R65816::op_and_w() {
regs.a.w &= rd.w;
regs.p.n = regs.a.w & 0x8000;
regs.p.z = regs.a.w == 0;
}
auto R65816::op_bit_b() {
regs.p.n = rd.l & 0x80;
regs.p.v = rd.l & 0x40;
regs.p.z = (rd.l & regs.a.l) == 0;
}
auto R65816::op_bit_w() {
regs.p.n = rd.w & 0x8000;
regs.p.v = rd.w & 0x4000;
regs.p.z = (rd.w & regs.a.w) == 0;
}
auto R65816::op_cmp_b() {
int r = regs.a.l - rd.l;
regs.p.n = r & 0x80;
regs.p.z = (uint8)r == 0;
regs.p.c = r >= 0;
}
auto R65816::op_cmp_w() {
int r = regs.a.w - rd.w;
regs.p.n = r & 0x8000;
regs.p.z = (uint16)r == 0;
regs.p.c = r >= 0;
}
auto R65816::op_cpx_b() {
int r = regs.x.l - rd.l;
regs.p.n = r & 0x80;
regs.p.z = (uint8)r == 0;
regs.p.c = r >= 0;
}
auto R65816::op_cpx_w() {
int r = regs.x.w - rd.w;
regs.p.n = r & 0x8000;
regs.p.z = (uint16)r == 0;
regs.p.c = r >= 0;
}
auto R65816::op_cpy_b() {
int r = regs.y.l - rd.l;
regs.p.n = r & 0x80;
regs.p.z = (uint8)r == 0;
regs.p.c = r >= 0;
}
auto R65816::op_cpy_w() {
int r = regs.y.w - rd.w;
regs.p.n = r & 0x8000;
regs.p.z = (uint16)r == 0;
regs.p.c = r >= 0;
}
auto R65816::op_eor_b() {
regs.a.l ^= rd.l;
regs.p.n = regs.a.l & 0x80;
regs.p.z = regs.a.l == 0;
}
auto R65816::op_eor_w() {
regs.a.w ^= rd.w;
regs.p.n = regs.a.w & 0x8000;
regs.p.z = regs.a.w == 0;
}
auto R65816::op_lda_b() {
regs.a.l = rd.l;
regs.p.n = regs.a.l & 0x80;
regs.p.z = regs.a.l == 0;
}
auto R65816::op_lda_w() {
regs.a.w = rd.w;
regs.p.n = regs.a.w & 0x8000;
regs.p.z = regs.a.w == 0;
}
auto R65816::op_ldx_b() {
regs.x.l = rd.l;
regs.p.n = regs.x.l & 0x80;
regs.p.z = regs.x.l == 0;
}
auto R65816::op_ldx_w() {
regs.x.w = rd.w;
regs.p.n = regs.x.w & 0x8000;
regs.p.z = regs.x.w == 0;
}
auto R65816::op_ldy_b() {
regs.y.l = rd.l;
regs.p.n = regs.y.l & 0x80;
regs.p.z = regs.y.l == 0;
}
auto R65816::op_ldy_w() {
regs.y.w = rd.w;
regs.p.n = regs.y.w & 0x8000;
regs.p.z = regs.y.w == 0;
}
auto R65816::op_ora_b() {
regs.a.l |= rd.l;
regs.p.n = regs.a.l & 0x80;
regs.p.z = regs.a.l == 0;
}
auto R65816::op_ora_w() {
regs.a.w |= rd.w;
regs.p.n = regs.a.w & 0x8000;
regs.p.z = regs.a.w == 0;
}
auto R65816::op_sbc_b() {
int result;
rd.l ^= 0xff;
if(!regs.p.d) {
result = regs.a.l + rd.l + regs.p.c;
} else {
result = (regs.a.l & 0x0f) + (rd.l & 0x0f) + (regs.p.c << 0);
if(result <= 0x0f) result -= 0x06;
regs.p.c = result > 0x0f;
result = (regs.a.l & 0xf0) + (rd.l & 0xf0) + (regs.p.c << 4) + (result & 0x0f);
}
regs.p.v = ~(regs.a.l ^ rd.l) & (regs.a.l ^ result) & 0x80;
if(regs.p.d && result <= 0xff) result -= 0x60;
regs.p.c = result > 0xff;
regs.p.n = result & 0x80;
regs.p.z = (uint8_t)result == 0;
regs.a.l = result;
}
auto R65816::op_sbc_w() {
int result;
rd.w ^= 0xffff;
if(!regs.p.d) {
result = regs.a.w + rd.w + regs.p.c;
} else {
result = (regs.a.w & 0x000f) + (rd.w & 0x000f) + (regs.p.c << 0);
if(result <= 0x000f) result -= 0x0006;
regs.p.c = result > 0x000f;
result = (regs.a.w & 0x00f0) + (rd.w & 0x00f0) + (regs.p.c << 4) + (result & 0x000f);
if(result <= 0x00ff) result -= 0x0060;
regs.p.c = result > 0x00ff;
result = (regs.a.w & 0x0f00) + (rd.w & 0x0f00) + (regs.p.c << 8) + (result & 0x00ff);
if(result <= 0x0fff) result -= 0x0600;
regs.p.c = result > 0x0fff;
result = (regs.a.w & 0xf000) + (rd.w & 0xf000) + (regs.p.c << 12) + (result & 0x0fff);
}
regs.p.v = ~(regs.a.w ^ rd.w) & (regs.a.w ^ result) & 0x8000;
if(regs.p.d && result <= 0xffff) result -= 0x6000;
regs.p.c = result > 0xffff;
regs.p.n = result & 0x8000;
regs.p.z = (uint16_t)result == 0;
regs.a.w = result;
}
auto R65816::op_inc_b() {
rd.l++;
regs.p.n = rd.l & 0x80;
regs.p.z = rd.l == 0;
}
auto R65816::op_inc_w() {
rd.w++;
regs.p.n = rd.w & 0x8000;
regs.p.z = rd.w == 0;
}
auto R65816::op_dec_b() {
rd.l--;
regs.p.n = rd.l & 0x80;
regs.p.z = rd.l == 0;
}
auto R65816::op_dec_w() {
rd.w--;
regs.p.n = rd.w & 0x8000;
regs.p.z = rd.w == 0;
}
auto R65816::op_asl_b() {
regs.p.c = rd.l & 0x80;
rd.l <<= 1;
regs.p.n = rd.l & 0x80;
regs.p.z = rd.l == 0;
}
auto R65816::op_asl_w() {
regs.p.c = rd.w & 0x8000;
rd.w <<= 1;
regs.p.n = rd.w & 0x8000;
regs.p.z = rd.w == 0;
}
auto R65816::op_lsr_b() {
regs.p.c = rd.l & 1;
rd.l >>= 1;
regs.p.n = rd.l & 0x80;
regs.p.z = rd.l == 0;
}
auto R65816::op_lsr_w() {
regs.p.c = rd.w & 1;
rd.w >>= 1;
regs.p.n = rd.w & 0x8000;
regs.p.z = rd.w == 0;
}
auto R65816::op_rol_b() {
unsigned carry = (unsigned)regs.p.c;
regs.p.c = rd.l & 0x80;
rd.l = (rd.l << 1) | carry;
regs.p.n = rd.l & 0x80;
regs.p.z = rd.l == 0;
}
auto R65816::op_rol_w() {
unsigned carry = (unsigned)regs.p.c;
regs.p.c = rd.w & 0x8000;
rd.w = (rd.w << 1) | carry;
regs.p.n = rd.w & 0x8000;
regs.p.z = rd.w == 0;
}
auto R65816::op_ror_b() {
unsigned carry = (unsigned)regs.p.c << 7;
regs.p.c = rd.l & 1;
rd.l = carry | (rd.l >> 1);
regs.p.n = rd.l & 0x80;
regs.p.z = rd.l == 0;
}
auto R65816::op_ror_w() {
unsigned carry = (unsigned)regs.p.c << 15;
regs.p.c = rd.w & 1;
rd.w = carry | (rd.w >> 1);
regs.p.n = rd.w & 0x8000;
regs.p.z = rd.w == 0;
}
auto R65816::op_trb_b() {
regs.p.z = (rd.l & regs.a.l) == 0;
rd.l &= ~regs.a.l;
}
auto R65816::op_trb_w() {
regs.p.z = (rd.w & regs.a.w) == 0;
rd.w &= ~regs.a.w;
}
auto R65816::op_tsb_b() {
regs.p.z = (rd.l & regs.a.l) == 0;
rd.l |= regs.a.l;
}
auto R65816::op_tsb_w() {
regs.p.z = (rd.w & regs.a.w) == 0;
rd.w |= regs.a.w;
}
| 21.929878
| 90
| 0.52134
|
ameer-bauer
|
386126fb790690f52145ca624e7325b54122c022
| 1,165
|
cc
|
C++
|
LIMoSim/map/osm/osmrelationentry.cc
|
inet-framework/LIMoSim
|
d9bdcefe82d41d4c8fd665a268843763fce59363
|
[
"MIT"
] | 7
|
2017-07-17T07:13:03.000Z
|
2021-10-12T08:39:17.000Z
|
LIMoSim/map/osm/osmrelationentry.cc
|
tudo-cni/LIMoSim
|
f0e4c8d964da18dffecea040775f07da3f5a5d46
|
[
"MIT"
] | 1
|
2018-03-08T10:28:01.000Z
|
2018-03-08T10:28:01.000Z
|
LIMoSim/map/osm/osmrelationentry.cc
|
tudo-cni/LIMoSim
|
f0e4c8d964da18dffecea040775f07da3f5a5d46
|
[
"MIT"
] | 7
|
2017-09-13T09:05:20.000Z
|
2022-01-04T17:20:20.000Z
|
#include "osmrelationentry.h"
namespace LIMoSim
{
OSMRelationEntry::OSMRelationEntry(OSMDocument *_parent) :
OSMEntry(_parent)
{
}
OSMRelationEntry OSMRelationEntry::fromXML(DOMElement *_entry, OSMDocument *_parent)
{
OSMRelationEntry entry(_parent);
entry.id = _entry->getAttribute("id").toInt();
for(auto & childNode : _entry->childNodes)
{
DOMElement *child = childNode->toElement();
std::string name = child->tagName;
if(name=="tag")
{
std::string key = child->getAttribute("k").toString();
Variant value = child->getAttribute("v");
if(key=="name")
entry.name = value.toString();
else if(key=="type")
entry.type = value.toString();
}
else if(name=="member")
{
std::string role = child->getAttribute("role").toString();
std::string ref = child->getAttribute("ref").toString();
if(role=="house")
entry.houses.push_back(ref);
else if(role=="street")
entry.streets.push_back(ref);
}
}
return entry;
}
}
| 24.270833
| 84
| 0.561373
|
inet-framework
|
386136b82c05ed902b3695248be600058dc1bc93
| 1,158
|
cpp
|
C++
|
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinCandidateStack.cpp
|
alinous-core/codable-cash
|
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
|
[
"MIT"
] | 6
|
2019-01-06T05:02:39.000Z
|
2020-10-01T11:45:32.000Z
|
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinCandidateStack.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 209
|
2018-05-18T03:07:02.000Z
|
2022-03-26T11:42:41.000Z
|
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinCandidateStack.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 3
|
2019-07-06T09:16:36.000Z
|
2020-10-15T08:23:28.000Z
|
/*
* JoinCandidateStack.cpp
*
* Created on: 2020/09/03
* Author: iizuka
*/
#include "scan_select/scan_planner/scanner/join/JoinCandidateStack.h"
#include "scan_select/scan_planner/scanner/join/AbstractJoinCandidate.h"
namespace codablecash {
JoinCandidateStack::JoinCandidateStack() : markStack(4) {
}
JoinCandidateStack::~JoinCandidateStack() {
this->stack.deleteElements();
}
bool JoinCandidateStack::isEmpty() const noexcept {
if(this->markStack.size() == 0){
return this->stack.isEmpty();
}
int topidx = this->markStack.size() - 1;
int index = this->markStack.get(topidx);
return this->stack.size() == index;
}
void JoinCandidateStack::push(AbstractJoinCandidate* candidate) noexcept {
this->stack.addElement(candidate);
}
AbstractJoinCandidate* JoinCandidateStack::pop() noexcept {
int index = this->stack.size() - 1;
return this->stack.remove(index);
}
void JoinCandidateStack::mark() noexcept {
int index = this->stack.size();
this->markStack.addElement(index);
}
void JoinCandidateStack::unmark() noexcept {
int index = this->markStack.size() - 1;
this->markStack.remove(index);
}
} /* namespace codablecash */
| 22.269231
| 74
| 0.727116
|
alinous-core
|
3863eabddc64fe61568f9771c3b45a7c6f2337ce
| 60
|
cpp
|
C++
|
GameEngine/src/GameEngine/Core/GameObject.cpp
|
josh-teichro/2DTestGame
|
b2cc31ce997ed54a0c07709edc1e5d8c2ccccc65
|
[
"Apache-2.0"
] | null | null | null |
GameEngine/src/GameEngine/Core/GameObject.cpp
|
josh-teichro/2DTestGame
|
b2cc31ce997ed54a0c07709edc1e5d8c2ccccc65
|
[
"Apache-2.0"
] | null | null | null |
GameEngine/src/GameEngine/Core/GameObject.cpp
|
josh-teichro/2DTestGame
|
b2cc31ce997ed54a0c07709edc1e5d8c2ccccc65
|
[
"Apache-2.0"
] | null | null | null |
#include "gepch.h"
#include "GameEngine/Core/GameObject.h"
| 15
| 39
| 0.75
|
josh-teichro
|
386642924995cbf3a723b741343feb29859b85a3
| 795
|
cpp
|
C++
|
tests/tst_Date/src/tst_Date.cpp
|
pet2petteam/PetAPI
|
ee7945d43953b3fcc20216fa51d8ede03f0b0351
|
[
"MIT"
] | null | null | null |
tests/tst_Date/src/tst_Date.cpp
|
pet2petteam/PetAPI
|
ee7945d43953b3fcc20216fa51d8ede03f0b0351
|
[
"MIT"
] | null | null | null |
tests/tst_Date/src/tst_Date.cpp
|
pet2petteam/PetAPI
|
ee7945d43953b3fcc20216fa51d8ede03f0b0351
|
[
"MIT"
] | null | null | null |
#include <QtTest>
#include <QDate>
#include <Container/ByteBuffer.h>
#include <DataStruct/DateTime.h>
using namespace PetAPI;
class tst_Date : public QObject {
Q_OBJECT
public:
tst_Date() = default;
~tst_Date() = default;
private slots:
void tst_currentDate();
void tst_fromToByteBuffer();
};
void tst_Date::tst_currentDate() {
Date date = Date::currentDate();
QDate qdate = QDate::currentDate();
QVERIFY(qdate.year() == date.year);
QVERIFY(qdate.month() == date.month);
QVERIFY(qdate.day() == date.day);
}
void tst_Date::tst_fromToByteBuffer() {
Date date_1 = Date::currentDate();
ByteBuffer dateBuffer = date_1.toByteBuffer();
Date date_2 = Date::fromByteBuffer(dateBuffer);
QVERIFY(date_1 == date_2);
}
QTEST_APPLESS_MAIN(tst_Date)
#include "tst_Date.moc"
| 18.068182
| 48
| 0.713208
|
pet2petteam
|
386c1ea3018e31b0fd351772ca96ac28d05b9a1f
| 589
|
cpp
|
C++
|
src/pkg_deb/prerm.cpp
|
naughtybikergames/pkg
|
9a78380c6cf82c95dec3968a7ed69000b349113d
|
[
"MIT"
] | null | null | null |
src/pkg_deb/prerm.cpp
|
naughtybikergames/pkg
|
9a78380c6cf82c95dec3968a7ed69000b349113d
|
[
"MIT"
] | null | null | null |
src/pkg_deb/prerm.cpp
|
naughtybikergames/pkg
|
9a78380c6cf82c95dec3968a7ed69000b349113d
|
[
"MIT"
] | null | null | null |
#include <pkg/deb/prerm.hpp>
#include <pkg/utils.hpp>
#include <sstream>
using namespace std;
using namespace pkg::deb;
extern char _binary_resources_pkg_deb_prerm_sh_start;
extern char _binary_resources_pkg_deb_prerm_sh_end;
prerm::prerm() {
stringstream ss;
char *p = &_binary_resources_pkg_deb_prerm_sh_start;
while (p != &_binary_resources_pkg_deb_prerm_sh_end)
ss << *p++;
_prerm = get_all_lines(ss);
}
string prerm::to_string() const {
return _prerm;
}
ostream& operator<<(ostream &out, const prerm prerm) {
return out << prerm.to_string();
}
| 20.310345
| 56
| 0.721562
|
naughtybikergames
|
387390a4844ec0b37df0dc6079d78f01f235962e
| 7,175
|
cpp
|
C++
|
Samples/MediaEditing/cpp/Scenario1_TrimAndSaveClip.xaml.cpp
|
dujianxin/Windows-universal-samples
|
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
|
[
"MIT"
] | 2,504
|
2019-05-07T06:56:42.000Z
|
2022-03-31T19:37:59.000Z
|
Samples/MediaEditing/cpp/Scenario1_TrimAndSaveClip.xaml.cpp
|
dujianxin/Windows-universal-samples
|
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
|
[
"MIT"
] | 314
|
2019-05-08T16:56:30.000Z
|
2022-03-21T07:13:45.000Z
|
Samples/MediaEditing/cpp/Scenario1_TrimAndSaveClip.xaml.cpp
|
dujianxin/Windows-universal-samples
|
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
|
[
"MIT"
] | 2,219
|
2019-05-07T00:47:26.000Z
|
2022-03-30T21:12:31.000Z
|
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "Scenario1_TrimAndSaveClip.xaml.h"
using namespace SDKTemplate;
using namespace concurrency;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::Media::Core;
using namespace Windows::Media::Editing;
using namespace Windows::Media::Transcoding;
using namespace Windows::Storage;
using namespace Windows::Storage::Pickers;
using namespace Windows::Storage::Streams;
using namespace Windows::Storage::AccessCache;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
Scenario1_TrimAndSaveClip::Scenario1_TrimAndSaveClip() : rootPage(MainPage::Current)
{
InitializeComponent();
}
void Scenario1_TrimAndSaveClip::OnNavigatedTo(NavigationEventArgs^ e)
{
// Make sure we don't run out of entries in StoreItemAccessList.
// As we don't need to persist this across app sessions/pages, clearing
// every time is sufficient for this sample
storageItemAccessList = StorageApplicationPermissions::FutureAccessList;
storageItemAccessList->Clear();
}
void Scenario1_TrimAndSaveClip::OnNavigatedFrom(NavigationEventArgs^ e)
{
mediaElement->Source = nullptr;
mediaStreamSource = nullptr;
}
void Scenario1_TrimAndSaveClip::ChooseFile_Click(Object^ sender, RoutedEventArgs^ e)
{
// Get file
auto picker = ref new FileOpenPicker();
picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
picker->FileTypeFilter->Append(".mp4");
create_task(picker->PickSingleFileAsync()).then([this](StorageFile^ videoFile)
{
if (videoFile == nullptr)
{
rootPage->NotifyUser("File picking cancelled", NotifyType::ErrorMessage);
return;
}
this->pickedFile = videoFile;
// These files could be picked from a location that we won't have access to later
// (especially if persisting the MediaComposition to disk and loading it later).
// Use the StorageItemAccessList in order to keep access permissions to that
// file for later use. Be aware that this access list needs to be cleared
// periodically or the app will run out of entries.
storageItemAccessList->Add(this->pickedFile);
create_task(this->pickedFile->OpenReadAsync()).then([this](IRandomAccessStreamWithContentType^ videoSource)
{
mediaElement->SetSource(videoSource, this->pickedFile->ContentType);
trimClip->IsEnabled = true;
});
});
}
void Scenario1_TrimAndSaveClip::TrimClip_Click(Object^ sender, RoutedEventArgs^ e)
{
create_task(MediaClip::CreateFromFileAsync(this->pickedFile)).then([this](MediaClip^ clip)
{
// Trim the front and back 25% from the clip
TimeSpan trimFromStart;
trimFromStart.Duration = (long long)(clip->OriginalDuration.Duration * 0.25);
clip->TrimTimeFromStart = trimFromStart;
TimeSpan trimFromEnd;
trimFromEnd.Duration = (long long)(clip->OriginalDuration.Duration * 0.25);
clip->TrimTimeFromEnd = trimFromEnd;
// Create a MediaComposition containing the clip and set it on the MediaElement.
composition = ref new MediaComposition();
composition->Clips->Append(clip);
mediaStreamSource = composition->GeneratePreviewMediaStreamSource((int)mediaElement->ActualWidth, (int)mediaElement->ActualHeight);
mediaElement->SetMediaStreamSource(mediaStreamSource);
rootPage->NotifyUser("Clip trimmed", NotifyType::StatusMessage);
save->IsEnabled = true;
});
}
void Scenario1_TrimAndSaveClip::Save_Click(Object^ sender, RoutedEventArgs^ e)
{
EnableButtons(false);
rootPage->NotifyUser("Requesting file to save to", NotifyType::StatusMessage);
auto picker = ref new FileSavePicker();
picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
auto filter = ref new Platform::Collections::Vector<String^>();
filter->Append(".mp4");
picker->FileTypeChoices->Insert("MP4 files", filter);
picker->SuggestedFileName = "TrimmedClip.mp4";
create_task(picker->PickSaveFileAsync()).then([this](StorageFile^ file)
{
if (file != nullptr)
{
auto saveOperation = composition->RenderToFileAsync(file, MediaTrimmingPreference::Precise);
saveOperation->Progress = ref new AsyncOperationProgressHandler<TranscodeFailureReason, double>([this](
IAsyncOperationWithProgress<TranscodeFailureReason, double>^ info, double value)
{
create_task(this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this,info,value]()
{
rootPage->NotifyUser("Saving file... Progress: " + value.ToString() + "%", NotifyType::StatusMessage);
}))).wait();
});
saveOperation->Completed = ref new AsyncOperationWithProgressCompletedHandler<TranscodeFailureReason, double>([this](
IAsyncOperationWithProgress<TranscodeFailureReason, double>^ info, AsyncStatus status)
{
create_task(this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, info, status]()
{
auto results = info->GetResults();
if (results != TranscodeFailureReason::None || status != AsyncStatus::Completed)
{
rootPage->NotifyUser("Saving was unsuccessful", NotifyType::ErrorMessage);
}
else
{
rootPage->NotifyUser("Trimmed clip saved to file", NotifyType::StatusMessage);
}
EnableButtons(true);
}))).wait();
});
}
else
{
rootPage->NotifyUser("User cancelled the file selection", NotifyType::StatusMessage);
EnableButtons(true);
}
});
}
void Scenario1_TrimAndSaveClip::EnableButtons(bool isEnabled)
{
chooseFile->IsEnabled = isEnabled;
save->IsEnabled = isEnabled;
trimClip->IsEnabled = isEnabled;
}
| 41.715116
| 140
| 0.65547
|
dujianxin
|
38757d249e2171385af67dca661693a08dac9f8c
| 2,184
|
cpp
|
C++
|
_KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/graphics/vulkan/device_object/render_pass.cpp
|
Karamays/karamay_engine
|
858054ea5155d0b690b7cf17d0e6a6266e0b0b9c
|
[
"MIT"
] | null | null | null |
_KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/graphics/vulkan/device_object/render_pass.cpp
|
Karamays/karamay_engine
|
858054ea5155d0b690b7cf17d0e6a6266e0b0b9c
|
[
"MIT"
] | null | null | null |
_KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/graphics/vulkan/device_object/render_pass.cpp
|
Karamays/karamay_engine
|
858054ea5155d0b690b7cf17d0e6a6266e0b0b9c
|
[
"MIT"
] | 1
|
2022-01-29T08:24:14.000Z
|
2022-01-29T08:24:14.000Z
|
#include "render_pass.h"
#include "pooled_object/command_buffer.h"
#include "framebuffer.h"
render_pass::render_pass(device& dev) : device_object(dev)
{
}
render_pass::~render_pass()
{
deallocate();
}
bool render_pass::allocate(const std::vector<VkAttachmentDescription>& attachments, const std::vector<VkSubpassDependency>& dependencies, const std::vector<VkSubpassDescription>& subpasses)
{
VkRenderPassCreateInfo _create_info;
_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
_create_info.flags;
_create_info.attachmentCount = attachments.size();
_create_info.dependencyCount = dependencies.size();
_create_info.subpassCount = subpasses.size();
_create_info.pAttachments = attachments.data();
_create_info.pDependencies = dependencies.data();
_create_info.pSubpasses = subpasses.data();
auto _ret = vkCreateRenderPass(_device.handle(), &_create_info, nullptr, &_handle);
if (_ret != VkResult::VK_SUCCESS)
{
return false;
}
return true;
}
void render_pass::deallocate()
{
if (_handle)
{
vkDestroyRenderPass(_device.handle(), _handle, nullptr);
_handle = nullptr;
}
}
void render_pass::set(const std::function<void(framebuffer*, command_buffer*)>& sequence)
{
command_buffer* _recorder = nullptr;
framebuffer* _rt = nullptr;
_begin(_recorder, _rt, {}, {}, VkSubpassContents::VK_SUBPASS_CONTENTS_INLINE);
sequence(_rt, _recorder);
_end(_recorder);
}
void render_pass::_begin(command_buffer* recorder, framebuffer* render_target, const std::vector<VkClearValue>& clear_values, VkRect2D render_area, VkSubpassContents contents)
{
VkRenderPassBeginInfo _begin_info;
_begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
_begin_info.framebuffer = render_target->handle();
_begin_info.renderPass = _handle;
_begin_info.clearValueCount = clear_values.size();
_begin_info.pClearValues = clear_values.data();
_begin_info.renderArea = render_area;
vkCmdBeginRenderPass(recorder->handle(), &_begin_info, contents);
}
void render_pass::_end(command_buffer* recorder)
{
vkCmdEndRenderPass(recorder->handle());
}
| 31.652174
| 189
| 0.742674
|
Karamays
|
3879171c305c4ec51d069387dc6db8d8ff397276
| 2,514
|
cpp
|
C++
|
Nasko/DatingAgency/agency.cpp
|
slaviborisov/shu.bg
|
1ed9a65fff1512d18a3e4cde90030abb450f0d9f
|
[
"Apache-2.0"
] | null | null | null |
Nasko/DatingAgency/agency.cpp
|
slaviborisov/shu.bg
|
1ed9a65fff1512d18a3e4cde90030abb450f0d9f
|
[
"Apache-2.0"
] | null | null | null |
Nasko/DatingAgency/agency.cpp
|
slaviborisov/shu.bg
|
1ed9a65fff1512d18a3e4cde90030abb450f0d9f
|
[
"Apache-2.0"
] | null | null | null |
#include "agency.h"
#include <iostream>
#include <string>
using namespace std;
CAgency::CAgency()
{
m = NULL;
total_members = 0;
cout<< "Въведете име на агенцията: ";
getline(cin,agency_name);
}
CAgency::CAgency(string _agency_name)
{
m = NULL;
total_members = 0;
agency_name = _agency_name;
}
int CAgency::GetByPersonalID(long long personal_id)
{
for(int i = 0; i < total_members; i++)
if (personal_id == m[i].GetPersonalID()) return i;
return -1;
}
void CAgency::AddPerson()
{
CPerson *p = m;
m = new CPerson[total_members + 1];
for(int i = 0; i < total_members; i++)
m[i] = p[i];
m[total_members].Add();
total_members++;
delete []p;
}
void CAgency::PrintAllMembers()
{
for(int i = 0; i < total_members; i++)
m[i].Print();
}
void CAgency::DeletePerson()
{
long long personal_id;
cout<<"Въведете ЕГН на клиента: ";
cin>>personal_id;
if(GetByPersonalID(personal_id) != -1) {
CPerson *p = m;
m = new CPerson[total_members - 1];
int j, i;
for(j = 0, i = 0; i < total_members; i++)
if(p[i].GetPersonalID() != personal_id)
m[j++] = p[i];
total_members--;
delete []p;
}
else {
cout<<"Не беше намерен клиент по въведеното ЕГН!";
}
}
void CAgency::PrintByPersonalID()
{
long long personal_id;
cout<<"Въведете ЕГН на клиента: ";
cin>>personal_id;
int index = GetByPersonalID(personal_id);
if(index > 0) {
m[index].Print();
}
}
void CAgency::PrintByProfession()
{
string profession;
cout<<"Въведете професия на клиента: ";
cin>>profession;
for(int i = 0; i < total_members; i++)
if (profession == m[i].GetProfession())
m[i].Print();
}
void CAgency::PrintYoungestPerson()
{
int sex;
float weight;
string profession;
cout<<"Въведете пол на клиента (0 - Мъж, 1 - Жена): ";
cin>>sex;
cout<<"Въведете тегло на клиента: ";
cin>>weight;
cout<<"Въведете професия на клиента: ";
cin>>profession;
CPerson person(0, "", 0, sex, 100, weight, profession, "Walk");
for(int i = 0; i < total_members; i++)
if (sex == m[i].GetSex() && weight == m[i].GetWeight() && profession == m[i].GetProfession())
if(m[i] < person) {
person = m[i];
}
if(person.GetPersonalID() > 0) {
cout<<"Най-младия клиент със сходни качества е: \n";
person.Print();
}
else cout<<"Няма намерен клиент със сходни качества! \n";
}
| 20.95
| 98
| 0.585123
|
slaviborisov
|
387b2b0bcfcf0c7dde3e56e2549152b3c1437fe9
| 5,375
|
cpp
|
C++
|
Esami/Laboratorio20160711/vector_graphics.cpp
|
eMDi94/EDM-ingmo
|
2b53194d862dea87a1f95305511c70c155dcc42c
|
[
"MIT"
] | 2
|
2018-08-16T00:34:55.000Z
|
2019-02-10T00:59:05.000Z
|
Esami/Laboratorio20160711/vector_graphics.cpp
|
eMDi94/EDM-ingmo
|
2b53194d862dea87a1f95305511c70c155dcc42c
|
[
"MIT"
] | null | null | null |
Esami/Laboratorio20160711/vector_graphics.cpp
|
eMDi94/EDM-ingmo
|
2b53194d862dea87a1f95305511c70c155dcc42c
|
[
"MIT"
] | null | null | null |
#include "vector_graphics.h"
#include <stdexcept>
#include <string>
#include <iterator>
using namespace std;
using namespace vector_graphics;
////////////////////////////////////////////
/* element_value dummy implementation*/
///////////////////////////////////////////
const value& element_value::value() const {
throw logic_error("Not implemented.");
}
const object& element_value::object() const {
throw logic_error("Not implemented.");
}
const element& element_value::operator[](const std::string& key) const {
throw logic_error("Not implemented.");
}
////////////////////////////////////////////////
/* implementation of different values */
///////////////////////////////////////////////
class vector_null;
template<typename T, type Tag>
class value_: public element_value {
protected:
explicit value_(T&& val): val_(move(val)) {}
vector_graphics::type type() const override {
return Tag;
}
const T val_;
virtual ~value_() = default;
const static element e_null;
};
template<typename T, type Tag>
const element value_<T, Tag>::e_null = element();
class vector_value: public value_<value, type::value> {
protected:
bool is_hidden() const override {
return false;
}
bool contains(const std::string& key) const override {
return false;
}
const vector_graphics::value& value() const override {
return val_;
}
public:
explicit vector_value(vector_graphics::value&& val): value_(move(val)) {}
};
class vector_null: public value_<nullptr_t, type::null> {
protected:
bool is_hidden() const override {
return false;
}
bool contains(const std::string& key) const override {
return false;
}
public:
explicit vector_null() : value_(nullptr) {};
};
class vector_object: public value_<object, type::object> {
protected:
bool is_hidden() const override {
for (const auto& e : val_)
if (e.element_name() == "hidden" && e.type() == type::value)
return e.value() == "true";
return false;
}
size_t _contains(const std::string& key) const {
for (size_t i = 0; i < val_.size(); ++i)
if (val_.at(i).element_name() == key)
return i;
return val_.size();
}
const vector_graphics::object& object() const override {
return val_;
}
bool contains(const std::string& key) const override {
return _contains(key) != val_.size();
}
const element& operator[](const string &key) const override {
const size_t index = _contains(key);
return index == val_.size() ? e_null : val_.at(index);
}
public:
explicit vector_object(vector_graphics::object&& obj): value_(move(obj)) {}
};
/////////////////////////////////////////////////////
/* vector_graphics element*/
/////////////////////////////////////////////////////
element::element(): element_name_(), ptr_(make_unique<vector_null>()) {}
element::element(const std::string& name, vector_graphics::object&& obj):
element_name_(name),
ptr_(make_unique<vector_object>(forward<vector_graphics::object>(obj))) {}
element::element(const std::string& name, vector_graphics::value&& val):
element_name_(name),
ptr_(make_unique<vector_value>(forward<vector_graphics::value>(val))){}
element::element(element&& rhs) noexcept: element_name_(move(rhs.element_name_)), ptr_(move(rhs.ptr_)) {}
element& element::operator=(element&& rhs) noexcept {
swap(element_name_, rhs.element_name_);
swap(ptr_, rhs.ptr_);
return *this;
}
type element::type() const {
return ptr_->type();
}
const value& element::value() const {
return ptr_->value();
}
const object& element::object() const {
return ptr_->object();
}
bool element::is_hidden() const {
return ptr_->is_hidden();
}
const string& element::element_name() const {
return element_name_;
}
bool element::contains(const string& key) const {
return ptr_->contains(key);
}
const element& element::operator[](const string& key) const {
return (*ptr_)[key];
}
////////////////////////////////////////////////
/*Parsing the file*/
////////////////////////////////////////////////
value read_value(istream& is) {
is.unsetf(ios::skipws);
string val;
//Remove the first "
is.get();
char c1 = 0, c2 = 0;
while (true) {
is >> c2;
if (c1 == '"') {
if (c2 == '"') {
val.push_back(c2);
c2 = 0;
}
else
break;
}
else {
if (c2 != '"')
val.push_back(c2);
}
c1 = c2;
if (!is)
throw logic_error("Never ending value.");
}
is.setf(ios::skipws);
return val;
}
object read_object(istream& is) {
object obj;
element e;
while ((e = parse(is)).type() != type::null) {
obj.push_back(move(e));
}
return obj;
}
element vector_graphics::parse(istream& is) {
string id;
is >> id >> ws;
if (!is)
throw logic_error("File ended with an id.");
const char c = is.peek();
switch (c) {
case 'o': {
string obj_;
is >> obj_;
object obj = read_object(is);
return element(id, move(obj));
}
case '"': {
value val = read_value(is);
return element(id, move(val));
}
case 'e': {
string end;
is >> end;
if (end != "end")
throw logic_error("Id obj not followed by an end.");
return element();
}
default:
throw logic_error("Option not recognized.");
}
}
| 22.395833
| 106
| 0.589395
|
eMDi94
|
3882316b002ee690a8114dfe82b252feddd3579e
| 495
|
cpp
|
C++
|
Source/FSD/Private/FirstPersonNiagaraComponent.cpp
|
Dr-Turtle/DRG_ModPresetManager
|
abd7ff98a820969504491a1fe68cf2f9302410dc
|
[
"MIT"
] | 8
|
2021-07-10T20:06:05.000Z
|
2022-03-04T19:03:50.000Z
|
Source/FSD/Private/FirstPersonNiagaraComponent.cpp
|
Dr-Turtle/DRG_ModPresetManager
|
abd7ff98a820969504491a1fe68cf2f9302410dc
|
[
"MIT"
] | 9
|
2022-01-13T20:49:44.000Z
|
2022-03-27T22:56:48.000Z
|
Source/FSD/Private/FirstPersonNiagaraComponent.cpp
|
Dr-Turtle/DRG_ModPresetManager
|
abd7ff98a820969504491a1fe68cf2f9302410dc
|
[
"MIT"
] | 2
|
2021-07-10T20:05:42.000Z
|
2022-03-14T17:05:35.000Z
|
#include "FirstPersonNiagaraComponent.h"
class UNiagaraSystem;
class USceneComponent;
class UNiagaraComponent;
UNiagaraComponent* UFirstPersonNiagaraComponent::SpawnFirstPersonEmitterAttached(UNiagaraSystem* inNiagaraSystem, USceneComponent* AttachToComponent, FName AttachPointName, FVector Location, FRotator Rotation, FVector Scale, TEnumAsByte<EAttachLocation::Type> LocationType, bool inAutoDestroy) {
return NULL;
}
UFirstPersonNiagaraComponent::UFirstPersonNiagaraComponent() {
}
| 35.357143
| 295
| 0.850505
|
Dr-Turtle
|
3882aef1bd1d6034390d8f633c3f77213d12220c
| 1,742
|
cpp
|
C++
|
archive/3/siec_wifi.cpp
|
Aleshkev/algoritmika
|
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
|
[
"MIT"
] | 2
|
2019-05-04T09:37:09.000Z
|
2019-05-22T18:07:28.000Z
|
archive/3/siec_wifi.cpp
|
Aleshkev/algoritmika
|
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
|
[
"MIT"
] | null | null | null |
archive/3/siec_wifi.cpp
|
Aleshkev/algoritmika
|
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
typedef int I;
typedef float F;
I n, k;
F pos[1000000];
bool is_possible(F range) {
I routers_used = 0;
F handled_up_to = -1.0;
for(I i = 0; i < n; ++i) {
if(pos[i] > handled_up_to) {
++routers_used;
if(routers_used > k) {
return false;
}
handled_up_to = pos[i] + range * 2;
}
}
return true;
}
int main()
{
//cout.sync_with_stdio(false);
//cin.tie(0);
I t;
scanf("%i", &t);
//cin >> t;
for(I j = 0; j < t; ++j) {
scanf("%i %i", &k, &n);
//cin >> k >> n;
for(I i = 0; i < n; ++i) {
scanf("%f", &pos[i]);
//cin >> pos[i];
}
sort(pos, pos + n);
if(k == 51202 && n == 91974) {
printf("4.5\n");
//cout << "4.5\n";
continue;
} else if(k == 82560 && n == 98744) {
printf("1.0\n");
//cout << "1.0\n";
continue;
} else if(k == 11801 && n == 96310) {
printf("37.0\n");
//cout << "37.0\n";
continue;
}
//cout << k << "_" << n << '\n'; continue;
/*for(F x = 0.5; x < 1.5; x += 0.1) {
cout << x << ": " << is_possible(x) << endl;
}*/
F lo = 0.0, hi = 1000000.0 / 4.0;
while(hi - lo > 0.05) {
//cout << lo << ":" << hi << '\n';
F mid = (lo + hi) / 2;
if(is_possible(mid)) {
hi = mid;
} else {
lo = mid;
}
}
printf("%.1f\n", lo);
//cout << fixed << setprecision(1) << lo << '\n';
}
return 0;
}
| 21.506173
| 57
| 0.359357
|
Aleshkev
|
38869a6ca5e0a74324d47afaeb7467cfe4b731d8
| 6,283
|
cc
|
C++
|
gram.cc
|
cadencorontzos/statsAndChats
|
aa402ce6215011f8d0ddf39d8426c6edf78705c9
|
[
"Apache-2.0"
] | null | null | null |
gram.cc
|
cadencorontzos/statsAndChats
|
aa402ce6215011f8d0ddf39d8426c6edf78705c9
|
[
"Apache-2.0"
] | null | null | null |
gram.cc
|
cadencorontzos/statsAndChats
|
aa402ce6215011f8d0ddf39d8426c6edf78705c9
|
[
"Apache-2.0"
] | null | null | null |
#include <string>
#include <iostream>
#include "gram.hh"
#include <ctime>
#include <cstdlib>
bool isPrime(int n) {
// Handle the obvious cases, including even ones.
if ((n <= 2) || (n % 2 == 0)) {
return (n == 2);
}
// Try several odd divisors.
int d = 3;
while (d*d <= n) {
if (n % d == 0) {
// It has a divisor. It's not prime.
return false;
}
d += 2;
}
// No divisors. It's prime.
return true;
}
int primeAtLeast(int n) {
if (n <= 2) {
return 2;
}
int p = 3;
while (p < n || !isPrime(p)) {
p += 2;
}
return p;
}
int charToInt(char c) {
if (c >= 'a' && c <= 'z') {
return c - 'a' + 1;
} else if (c == '.') {
return 27;
} else if (c == '!') {
return 28;
} else if (c == '?') {
return 29;
} else if (c == '\'') {
return 30;
} else if (c == ' ') {
return 31;
} else {
return 0;
}
}
int hashValue(std::string key, int modulus) {
int hashValue = 0;
for (char c: key) {
// Horner's method for computing the value.
hashValue = (32*hashValue + charToInt(c)) % modulus;
}
return hashValue;
}
namespace gram {
bucket* buildBuckets(int howMany) {
bucket* bs = new bucket[howMany];
for (int i=0; i<howMany; i++) {
bs[i].first = nullptr;
}
return bs;
}
//rehashed our hashtable to maintain loadfactor
void rehash(dict* D){
//we want to keep track of the old stuff so we can put it into the new buckets
int oldNumBuckets = D->numBuckets;
bucket* oldTable = D->buckets;
//makes the new buckets and updates numBuckets
D->numBuckets = primeAtLeast(2*D->numBuckets);
D->buckets = buildBuckets(D->numBuckets);
//we iterate through the old buckets here
for(int i = 0; i < oldNumBuckets; i++){
gram* oldGram = oldTable[i].first;
//we go through the grams in the old bucket and put them into their new buckets
while(oldGram!=nullptr){
int newIndex = hashValue(oldGram->words,D->numBuckets);
gram* currentFirstGram = D->buckets[newIndex].first;
gram* nextGram = oldGram->next;
//we just insert the oldGram as the first gram of it's new bucket.
if(currentFirstGram==nullptr){
D->buckets[newIndex].first = oldGram;
oldGram->next = nullptr;
}
else{
oldGram->next = D->buckets[newIndex].first;
D->buckets[newIndex].first = oldGram;
}
oldGram = nextGram;
}
}
//reallocates the space from our old buckets
delete [] oldTable;
}
//builds a dict, with all the defaults set
dict* build(int initialSize, int loadFactor) {
srand(time(0));
dict* newD = new dict;
newD->numEntries = 0;
newD->loadFactor = loadFactor;
newD->numBuckets = primeAtLeast(initialSize);
newD->buckets = buildBuckets(newD->numBuckets);
return newD;
}
//gets a random follower of a word
std::string get(dict* D, std::string ws) {
//we find the appropriate bucket, iterate through til we find our word
int hashIndex= hashValue(ws,D->numBuckets);
gram* currentGram = D->buckets[hashIndex].first;
while(currentGram!=nullptr and currentGram->words != ws){
currentGram = currentGram->next;
}
//we pick a follower # "randomly" and iterate to it
int randInt = std::rand() % currentGram->number;
follower* currentFollower = currentGram->followers;
while(currentFollower!=nullptr and randInt!=0){
currentFollower = currentFollower->next;
randInt--;
}
//returns that follower
return currentFollower->word;
}
std::string get(dict* D, std::string w1, std::string w2) {
return get(D,w1+" "+w2);
}
//adds a word gram and it's follower to the hashtable
void add(dict* D, std::string ws, std::string fw) {
//if we are goint to exceed the load factor, we immediately rehash
if((D->numEntries+1)/D->numBuckets > D->loadFactor){
rehash(D);
}
//creates the new entry in case we need to add it
follower* newFollower = new follower{fw,nullptr};
gram* newGram = new gram{ws,1,newFollower,nullptr};
int bucketIndex = hashValue(ws,D->numBuckets);
gram* currentGram = D->buckets[bucketIndex].first;
//if this is our first entry
if(currentGram == nullptr){
D->buckets[bucketIndex].first = newGram;
D->numEntries++;
return;
}
gram* prevGram = currentGram;
bool alreadyInTheDict = false;
//iterates through the entries in the dict, looking for where the new entry goes
// (or if the entry is already there)
while(!alreadyInTheDict and currentGram!=nullptr ){
if(currentGram->words == ws){
alreadyInTheDict = true;
delete newGram;
}else{
prevGram = currentGram;
currentGram = currentGram->next;
}
}
//if the gram is aleady in the dict, we just add the new follower (if needed)
if(alreadyInTheDict){
follower* currentFollower = currentGram->followers;
follower* prevFollower = nullptr;
while(currentFollower!=nullptr){
if(currentFollower->word == fw){
delete newFollower;
return;
}
prevFollower = currentFollower;
currentFollower = currentFollower->next;
}
if(prevFollower == nullptr){
currentGram->followers = newFollower;
currentGram->number++;
return;
}
prevFollower->next = newFollower;
currentGram->number++;
}
else{
//if the gram is not already in there, we just add it
D->numEntries++;
prevGram->next = newGram;
}
}
void add(dict* D, std::string w1, std::string w2, std::string fw) {
add(D,w1+" "+w2,fw);
}
//reallocates space
void destroy(dict *D) {
//goes through all the buckets
for(int i = 0; i< D->numBuckets; i++){
//goes through all the grams in the buckets
gram* currentGram = D->buckets[i].first;
while(currentGram!=nullptr){
gram* toBeDeleted = currentGram;
follower* currentFollower = currentGram->followers;
//deletes all the grams followers
while(currentFollower !=nullptr){
follower* followerToDelete = currentFollower;
currentFollower = currentFollower->next;
delete followerToDelete;
}
//deletes the gram
currentGram = currentGram->next;
delete toBeDeleted;
}
}
//deletes D and its buckets
delete [] D->buckets;
delete D;
}
}
| 24.447471
| 85
| 0.627726
|
cadencorontzos
|
3887ef153a9dc08fddd6f863a5722c7272ac413c
| 727
|
cpp
|
C++
|
source/plants/WilczeJagody.cpp
|
Silentsky0/po-project-species-rivalry
|
c754ebad03877f2af122ba5bb42feaf99b57829f
|
[
"MIT"
] | null | null | null |
source/plants/WilczeJagody.cpp
|
Silentsky0/po-project-species-rivalry
|
c754ebad03877f2af122ba5bb42feaf99b57829f
|
[
"MIT"
] | null | null | null |
source/plants/WilczeJagody.cpp
|
Silentsky0/po-project-species-rivalry
|
c754ebad03877f2af122ba5bb42feaf99b57829f
|
[
"MIT"
] | null | null | null |
#include "WilczeJagody.h"
WilczeJagody::WilczeJagody(int y, int x){
this->x = x;
this->y = y;
this->strength = 99;
this->initiative = 0;
this->age = 0;
this->name = "Wilcze Jagody";
this->is_plant = true;
}
WilczeJagody::~WilczeJagody(){
}
void WilczeJagody::rysowanie() {
std::cout << "J";
}
void WilczeJagody::byc_zjedzonym(Organizm* jedzacy) {
this->swiat->tabela_wydarzen.add_row({ "Wilcze Jagody", jedzacy->get_name(), std::to_string(jedzacy->get_x()), std::to_string(jedzacy->get_y()), "<===>", this->name , std::to_string(this->x), std::to_string(this->y), jedzacy->get_name() + " zjada wilcze jagody i ginie" });
swiat->usun_organizm((Organizm*)jedzacy);
swiat->zmniejszona_liczba_organizmow = true;
}
| 27.961538
| 275
| 0.68088
|
Silentsky0
|
388f35cc27b82c0c1122138fe889e7f073201a93
| 1,273
|
cpp
|
C++
|
tests/WordStatics.cpp
|
chenzhengxi/example
|
07a8436e92ccab8e330d2a77e2cca23b8a540df3
|
[
"MIT"
] | null | null | null |
tests/WordStatics.cpp
|
chenzhengxi/example
|
07a8436e92ccab8e330d2a77e2cca23b8a540df3
|
[
"MIT"
] | null | null | null |
tests/WordStatics.cpp
|
chenzhengxi/example
|
07a8436e92ccab8e330d2a77e2cca23b8a540df3
|
[
"MIT"
] | null | null | null |
#include "WordStatics.h"
#include <map>
#include <vector>
#include <algorithm>
std::string format(const std::pair<std::string, int> &words)
{
return words.first + ":" + std::to_string(words.second);
}
std::map<std::string, int> split(const std::string &words)
{
int pos = 0;
std::map<std::string, int> tmp;
for (int i = 0; i < words.size(); ++i)
{
if (words[i] == ' ')
{
tmp[words.substr(pos, i - pos)]++;
pos = i + 1;
}
}
if (pos < words.size())
{
tmp[words.substr(pos, words.size() - pos)]++;
}
return tmp;
}
bool cmp_by_value(const std::pair<std::string, int> &lhs, const std::pair<std::string, int> &rhs)
{
return lhs.second > rhs.second;
}
std::string WordStatics(const std::string &words)
{
std::map<std::string, int> subword = split(words);
std::vector<std::pair<std::string, int>> vec;
for (std::map<std::string, int>::iterator it = subword.begin(); it != subword.end(); it++)
{
vec.push_back(std::pair<std::string, int>(it->first, it->second));
}
std::sort(vec.begin(), vec.end(), cmp_by_value);
std::string outstr;
for (auto &&value : vec)
{
outstr += (format(value) + "\r\n");
}
return outstr;
}
| 24.018868
| 97
| 0.559309
|
chenzhengxi
|
3892a8f0d51acea61a7896cd00e3973edd0f961c
| 1,087
|
hpp
|
C++
|
src/Nest/Utils/PrintTimer.hpp
|
CristianDragu/sparrow
|
49844c2329ac001c3a0779baae7a2f02743c4494
|
[
"MIT"
] | 80
|
2015-05-05T12:21:50.000Z
|
2022-03-30T18:38:48.000Z
|
src/Nest/Utils/PrintTimer.hpp
|
CristianDragu/sparrow
|
49844c2329ac001c3a0779baae7a2f02743c4494
|
[
"MIT"
] | 51
|
2016-09-09T13:44:50.000Z
|
2021-11-28T07:03:02.000Z
|
src/Nest/Utils/PrintTimer.hpp
|
CristianDragu/sparrow
|
49844c2329ac001c3a0779baae7a2f02743c4494
|
[
"MIT"
] | 8
|
2015-07-28T11:34:15.000Z
|
2020-02-01T21:54:06.000Z
|
#pragma once
#include <chrono>
namespace Nest {
namespace Common {
/// Helper timer that prints the elapsed time at the console
///
/// In order for this to do something, the "enable" constructor parameter must be true; otherwise
/// this has no effect.
class PrintTimer {
chrono::steady_clock::time_point startTime;
const char* format;
public:
PrintTimer(bool enable, const char* startText, const char* fmtEnd = "[%d ms]\n")
: format(enable ? fmtEnd : nullptr) {
if (enable) {
printf("%s", startText);
startTime = chrono::steady_clock::now();
}
}
~PrintTimer() {
if (format) {
auto durMs = chrono::duration_cast<chrono::milliseconds>(
chrono::steady_clock::now() - startTime);
printf(format, durMs);
}
}
PrintTimer(const PrintTimer&) = delete;
PrintTimer(PrintTimer&&) = delete;
const PrintTimer& operator=(const PrintTimer&) = delete;
const PrintTimer& operator=(PrintTimer&&) = delete;
};
} // namespace Common
} // namespace Nest
| 27.871795
| 97
| 0.621895
|
CristianDragu
|
389478d6e2e6cccf44eddfa6e05f82cf47d42367
| 977
|
hpp
|
C++
|
JK_rhythmgame/test/test-aes_utl.hpp
|
ai2playgame/JK_rhythmgame
|
886f565c64612d452897fd37dcc2f10a1d2aa08b
|
[
"Zlib"
] | null | null | null |
JK_rhythmgame/test/test-aes_utl.hpp
|
ai2playgame/JK_rhythmgame
|
886f565c64612d452897fd37dcc2f10a1d2aa08b
|
[
"Zlib"
] | null | null | null |
JK_rhythmgame/test/test-aes_utl.hpp
|
ai2playgame/JK_rhythmgame
|
886f565c64612d452897fd37dcc2f10a1d2aa08b
|
[
"Zlib"
] | null | null | null |
#pragma once
#include <sstream>
#include "test.hpp"
#include "../src/aes/aes-utl.hpp"
#include "../src/aes/include/key.hpp"
namespace jk::test {
DEFINE_TEST(encrypt_decrypt_test_aes_utl) {
enc::aes_utl encoder;
std::stringstream original, out;
original << "test test. this is a test of crypto class!!! i hope this will be success.";
encoder.encrypt(original, out);
std::vector<std::uint8_t> result;
CHECK_NOTHROW(result = encoder.decrypt(out));
original.seekg(0);
for (auto & i : result) {
char buf;
original.read(&buf, 1);
CHECK_EQUAL(buf, i);
}
}
DEFINE_TEST(key_change_crypto_test_aes_utl) {
enc::aes_utl encoder;
enc::aes_utl decoder;
std::stringstream original, out;
original << "test test. this is a test of crypto class!!! i hope this will be success.";
encoder.encrypt(original, out);
std::vector<std::uint8_t> result;
decoder.get_encoder().setKey(enc::makeKey("password"));
CHECK_THROW(decoder.decrypt(out));
}
}
| 25.710526
| 90
| 0.696008
|
ai2playgame
|
3895668c7d4ae6b9ee09ab6be347e171c6b64b44
| 1,242
|
hpp
|
C++
|
Source/AliveLibAE/MusicTrigger.hpp
|
UltraStars3000/alive_reversing
|
41a3bdae97139358d39e95cd6e1a4027341b3a99
|
[
"MIT"
] | null | null | null |
Source/AliveLibAE/MusicTrigger.hpp
|
UltraStars3000/alive_reversing
|
41a3bdae97139358d39e95cd6e1a4027341b3a99
|
[
"MIT"
] | null | null | null |
Source/AliveLibAE/MusicTrigger.hpp
|
UltraStars3000/alive_reversing
|
41a3bdae97139358d39e95cd6e1a4027341b3a99
|
[
"MIT"
] | null | null | null |
#pragma once
#include "FunctionFwd.hpp"
#include "BaseGameObject.hpp"
#include "Path.hpp"
#include "MusicController.hpp"
struct Path_MusicTrigger : public Path_TLV
{
__int16 field_10_type; // TODO: Enum
short field_12_enabled_by; // TODO: Enum
__int16 field_14_timer;
// pad
};
ALIVE_ASSERT_SIZEOF_ALWAYS(Path_MusicTrigger, 0x18);
class MusicTrigger : public BaseGameObject
{
public:
EXPORT BaseGameObject* ctor_47FE40(Path_MusicTrigger* pTlv, DWORD tlvInfo);
EXPORT MusicTrigger* ctor_47FF10(__int16 type, __int16 enabledBy, int /*not_used*/, __int16 delay);
EXPORT void Init_47FFB0(__int16 type, __int16 enabledBy, __int16 delay);
EXPORT BaseGameObject* vdtor_47FEE0(signed int flags);
EXPORT void dtor_4800C0();
EXPORT void vScreenChange_4802A0();
EXPORT void vUpdate_480140();
virtual BaseGameObject* VDestructor(signed int flags) override;
virtual void VUpdate() override;
virtual void VScreenChanged() override;
private:
int field_20_tlvInfo;
__int16 field_24_flags; // TODO: Recover flags
MusicController::MusicTypes field_26_music_type;
int field_28_counter;
PSX_Point field_2C_tl;
PSX_Point field_30_br;
};
ALIVE_ASSERT_SIZEOF(MusicTrigger, 0x34);
| 30.292683
| 103
| 0.759259
|
UltraStars3000
|
389930a5403cc9f11e941d7788a0462019372958
| 7,449
|
hpp
|
C++
|
gripper/robotiq-2f/main/opcua_task.hpp
|
opcua-skills/plug-and-produce
|
5567cd6177f973e97579fbd9d06ebbf23569ccfb
|
[
"Unlicense"
] | 5
|
2020-04-15T03:24:48.000Z
|
2021-11-03T17:39:59.000Z
|
gripper/robotiq-2f/main/opcua_task.hpp
|
opcua-skills/plug-and-produce
|
5567cd6177f973e97579fbd9d06ebbf23569ccfb
|
[
"Unlicense"
] | null | null | null |
gripper/robotiq-2f/main/opcua_task.hpp
|
opcua-skills/plug-and-produce
|
5567cd6177f973e97579fbd9d06ebbf23569ccfb
|
[
"Unlicense"
] | 2
|
2020-07-04T16:01:25.000Z
|
2021-07-05T09:33:55.000Z
|
/*
* This file is subject to the terms and conditions defined in
* file 'LICENSE', which is part of this source code package.
*
* Copyright (c) 2020 fortiss GmbH, Stefan Profanter
* All rights reserved.
*/
#ifndef ROBOTIQ_2FOPCUA_TASK_HPP
#define ROBOTIQ_2FOPCUA_TASK_HPP
#ifdef UA_ENABLE_AMALGAMATION
#include <open62541.h>
#else
#include <open62541/server_config_default.h>
#endif
#include <spdlog/spdlog.h>
#include <common/logging.h>
#include <robotiq_2f_nodeids.h>
#include "namespace_di_generated.h"
#include "di_nodeids.h"
#include "namespace_fortiss_device_generated.h"
#include "namespace_robotiq_2f_generated.h"
#include "GripperOPCUA.h"
#define fortiss_LDS_URI "fortiss.component.mes"
std::shared_ptr<spdlog::logger> logger;
#ifndef LOCAL_SIMULATION
#include <esp_log.h>
#include "TinyPico.h"
static const char *TAG_OPC = "OPC UA";
TinyPICO *tinyPico;
#endif
static bool
createNodesFromNodeset(
const std::shared_ptr<fortiss::opcua::OpcUaServer>& server
) {
LockedServer ls = server->getLocked();
if (namespace_di_generated(ls.get()) != UA_STATUSCODE_GOOD) {
logger->error("Adding the DI namespace failed. Please check previous error output.");
return false;
}
if (namespace_fortiss_device_generated(ls.get()) != UA_STATUSCODE_GOOD) {
logger->error("Adding the fortiss device namespace failed. Please check previous error output.");
return false;
}
if (namespace_robotiq_2f_generated(ls.get()) != UA_STATUSCODE_GOOD) {
logger->error("Adding the Sommer Automatic namespace failed. Please check previous error output.");
return false;
}
return true;
}
static bool run_opcua(
UA_UInt16 port,
volatile bool* running,
bool ignore_poweroff,
std::shared_ptr<spdlog::logger> _logger = nullptr,
std::shared_ptr<spdlog::logger> _loggerServer = nullptr,
std::shared_ptr<spdlog::logger> _loggerClient = nullptr
) {
//The default 64KB of memory for sending and receicing buffer caused problems to many users. With the code below, they are reduced to ~16KB
UA_UInt32 sendBufferSize = 16000; //64 KB was too much for my platform
UA_UInt32 recvBufferSize = 16000; //64 KB was too much for my platform
std::shared_ptr<spdlog::logger> loggerServer;
std::shared_ptr<spdlog::logger> loggerClient;
if (!logger) {
logger = fortiss::log::get("gripper/robotiq2f");
logger->set_level(spdlog::level::level_enum::info);
loggerServer = logger->clone(logger->name() + "-ua");
loggerServer->set_level(spdlog::level::level_enum::err);
loggerClient = logger->clone(logger->name() + "-ua-reg");
loggerClient->set_level(spdlog::level::level_enum::err);
} else {
logger = _logger;
loggerServer = _loggerServer;
loggerClient = _loggerClient;
}
UA_ServerConfig *uaServerConfig = (UA_ServerConfig*) UA_malloc(sizeof(UA_ServerConfig));
if (!uaServerConfig) {
logger->error("Can not create server config");
throw std::runtime_error("Cannot create server config");
}
// ------------- OPC UA initialization -------------------
if (fortiss::opcua::initServerConfig(
loggerServer,
uaServerConfig,
"fortiss.component.gripper.robotiq",
"fortiss - Gripper - Robotiq",
(UA_UInt16) ((int) port),
false,
false,
"",
sendBufferSize,
recvBufferSize,
true) != UA_STATUSCODE_GOOD) {
return false;
}
#ifndef LOCAL_SIMULATION
#ifndef CONFIG_ETHERNET_HELPER_CUSTOM_HOSTNAME
#ifndef ETHERNET_HELPER_STATIC_IP4
#error You need to set a static IP or a custom hostname with menuconfig
#else
UA_String str = UA_STRING(CONFIG_ETHERNET_HELPER_STATIC_IP4_ADDRESS);
#endif
#else
UA_String str = UA_STRING((char*)CONFIG_ETHERNET_HELPER_CUSTOM_HOSTNAME_STR);
#endif
UA_String_clear(&uaServerConfig->customHostname);
UA_String_copy(&str, &uaServerConfig->customHostname);
tcpip_adapter_ip_info_t default_ip;
esp_err_t ret = tcpip_adapter_get_ip_info(tcpip_adapter_if_t::TCPIP_ADAPTER_IF_STA, &default_ip);
if ((ESP_OK == ret) && (default_ip.ip.addr != INADDR_ANY)) {
uaServerConfig->mdnsIpAddressListSize = 1;
uaServerConfig->mdnsIpAddressList = (uint32_t *)UA_malloc(sizeof(uint32_t)*uaServerConfig->mdnsIpAddressListSize);
memcpy(uaServerConfig->mdnsIpAddressList, &default_ip.ip.addr, sizeof(uint32_t));
} else {
ESP_LOGI(TAG_OPC, "Could not get default IP Address!");
}
#endif
std::shared_ptr<fortiss::opcua::OpcUaServer> server = std::make_shared<fortiss::opcua::OpcUaServer>(
logger,
loggerServer,
loggerClient,
"fortiss.component.gripper.robotiq2f.client",
"fortiss - Gripper - Robotiq 2F - Client",
"",
std::string(fortiss_LDS_URI),
uaServerConfig);
if (!createNodesFromNodeset(server)) {
throw std::runtime_error("Creating nodes from nodeset failed");
}
GripperOPCUA gripperOPCUA(logger, server);
if (const UA_StatusCode retval = server->init(
true
) != UA_STATUSCODE_GOOD) {
logger->error("Starting up the server failed with " + std::string(UA_StatusCode_name(retval)));
return false;
}
const fortiss::opcua::powerOffDeviceCallbackData onPowerOffDeviceData = {
.logger = logger,
.onPowerOffDevice = [running, ignore_poweroff](UA_UInt32 delayMs) {
logger->warn("Got PowerOffDevice Method call! Shutting down OPC UA Server.");
if (!ignore_poweroff)
*running = false;
return UA_STATUSCODE_GOOD;
}
};
{
LockedServer ls = server->getLocked();
UA_StatusCode retval = fortiss::opcua::setPowerOffHandler(ls.get(), UA_NODEID_NUMERIC(
fortiss::opcua::UA_Server_getNamespaceIdByName(server, NAMESPACE_URI_ROBOTIQ),
UA_ROBOTIQ_2FID_ROBOTIQ2F), onPowerOffDeviceData);
if (retval != UA_STATUSCODE_GOOD) {
logger->error("Adding PowerOffHandler failed: " + std::string(UA_StatusCode_name(retval)));
return false;
}
}
if (!gripperOPCUA.connect()) {
logger->error("gripperOPCUA connect failed!");
return false;
}
#ifndef LOCAL_SIMULATION
ESP_LOGI(TAG_OPC, "Starting server loop. Free Heap: %d bytes", xPortGetFreeHeapSize());
tinyPico->DotStar_SetPixelColor(0, 255, 0);
#endif
while (*running) {
server->iterate();
#ifndef LOCAL_SIMULATION
try {
gripperOPCUA.step();
} catch( rl::hal::DeviceException &ex) {
ESP_LOGE(TAG_OPC, "DeviceException: %s", ex.what());
tinyPico->DotStar_SetPixelColor(255, 0, 0);
break;
}
ESP_ERROR_CHECK(esp_task_wdt_reset());
#else
gripperOPCUA.step();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
#endif
std::this_thread::yield();
}
// do one last iteration
server->iterate(true);
gripperOPCUA.step();
gripperOPCUA.shutdown();
server.reset();
spdlog::shutdown();
return true;
}
#endif //ROBOTIQ_2FOPCUA_TASK_HPP
| 33.403587
| 143
| 0.653913
|
opcua-skills
|
389d1b5b255d7d1c83460efed92cbceed0de3d3a
| 3,144
|
cpp
|
C++
|
src/osdep/native/nativepluginloader.cpp
|
lawarner/aft
|
fd2b6b97bedd2be3ccb1739b890aeea6aa2f9603
|
[
"Apache-2.0"
] | null | null | null |
src/osdep/native/nativepluginloader.cpp
|
lawarner/aft
|
fd2b6b97bedd2be3ccb1739b890aeea6aa2f9603
|
[
"Apache-2.0"
] | null | null | null |
src/osdep/native/nativepluginloader.cpp
|
lawarner/aft
|
fd2b6b97bedd2be3ccb1739b890aeea6aa2f9603
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2016 Andy Warner
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <dlfcn.h>
#include "base/factory.h"
#include "osdep/platform.h"
using namespace aft::base;
using namespace aft::osdep;
#if __APPLE__
static const char* DEFAULT_PATH = "/opt/local/lib/aft/plugins";
static const char* PATH_SEPARATOR = "/";
static const char* SO_EXT = ".dylib";
#else
static const char* DEFAULT_PATH = "/usr/local/lib/aft/plugins";
static const char* PATH_SEPARATOR = "/";
static const char* SO_EXT = ".so";
#endif
class aft::osdep::NativePluginImpl
{
public:
NativePluginImpl(const std::string& path = DEFAULT_PATH)
: handle_(0)
, factory_(0)
, path_(path)
{ }
void* handle_;
aft::base::BaseFactory* factory_;
//TODO keep array of directories in path instead of just one
std::string path_;
std::string bundleName_;
};
static std::string
makeSoName(const NativePluginImpl& impl)
{
std::string soName = impl.path_ + PATH_SEPARATOR + impl.bundleName_ + SO_EXT;
return soName;
}
NativePluginLoader::NativePluginLoader()
: impl_(*new NativePluginImpl)
{
}
NativePluginLoader::~NativePluginLoader()
{
delete &impl_;
}
BaseFactory*
NativePluginLoader::loadBundle(const std::string& bundleName)
{
impl_.bundleName_ = bundleName;
std::string soName = makeSoName(impl_);
std::cout << "Going to load " << soName << std::endl;
void* handle = dlopen(soName.c_str(), RTLD_LAZY);
if (!handle)
{
std::cout << "Error loading ld: " << dlerror() << std::endl;
return 0;
}
impl_.handle_ = handle;
InitializeFunction initialize = (InitializeFunction)dlsym(handle, "initialize");
if (!initialize)
{
std::cout << "Unable to load initialize() function" << std::endl;
return 0;
}
DeinitializeFunction deinitialize = (DeinitializeFunction)dlsym(handle, "deinitialize");
BaseFactory* factory = initialize();
if (factory)
{
impl_.factory_ = factory;
factory->setDeinit((void *)deinitialize);
}
else
{
std::cout << "Error instatiating plug-in factory" << std::endl;
}
return factory;
}
void NativePluginLoader::setPath(const std::string& path)
{
//TODO expand env variables and tildes
impl_.path_ = path;
}
void NativePluginLoader::unloadBundle()
{
if (impl_.factory_)
{
impl_.factory_->deinit();
delete impl_.factory_;
impl_.factory_ = 0;
}
if (impl_.handle_)
{
dlclose(impl_.handle_);
impl_.handle_ = 0;
}
}
| 24.372093
| 92
| 0.659987
|
lawarner
|
389e8b0b8a1b9929734767e1b62edd0dfa8a1afa
| 1,018
|
cpp
|
C++
|
lib/il2cpp/il2cpp/libmono/icalls/mscorlib/System.Runtime.InteropServices/Marshal.cpp
|
smorey2/GameEstate
|
1349dd68c675ed056210b4238f5b8e7c92857933
|
[
"MIT"
] | null | null | null |
lib/il2cpp/il2cpp/libmono/icalls/mscorlib/System.Runtime.InteropServices/Marshal.cpp
|
smorey2/GameEstate
|
1349dd68c675ed056210b4238f5b8e7c92857933
|
[
"MIT"
] | null | null | null |
lib/il2cpp/il2cpp/libmono/icalls/mscorlib/System.Runtime.InteropServices/Marshal.cpp
|
smorey2/GameEstate
|
1349dd68c675ed056210b4238f5b8e7c92857933
|
[
"MIT"
] | null | null | null |
#include <cstdlib>
#include "Marshal.h"
#include "vm/PlatformInvoke.h"
namespace mono
{
namespace icalls
{
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace InteropServices
{
intptr_t Marshal::GetFunctionPointerForDelegateInternal(MonoDelegate* d)
{
return mono::vm::PlatformInvoke::MarshalDelegate(d);
}
Il2CppDelegate* Marshal::GetDelegateForFunctionPointerInternal(intptr_t ptr, MonoReflectionType* t)
{
MonoClass *delegateType = mono_type_get_class(mono_unity_reflection_type_get_type(t));
if (!mono_class_init(delegateType))
{
mono_set_pending_exception(mono_class_get_exception_for_failure(delegateType));
return NULL;
}
return mono::vm::PlatformInvoke::MarshalFunctionPointerToDelegate(reinterpret_cast<void*>(ptr), delegateType);
}
} /* namespace InteropServices */
} /* namespace Runtime */
} /* namespace System */
} /* namespace mscorlib */
} /* namespace icalls */
} /* namespace mono */
| 26.789474
| 118
| 0.717092
|
smorey2
|
389f1a7880590f6562af72cfaa68f77dd4382e71
| 521
|
hpp
|
C++
|
zen/lexgen/parser.hpp
|
ZenLibraries/ZenLibraries
|
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
|
[
"Apache-2.0"
] | null | null | null |
zen/lexgen/parser.hpp
|
ZenLibraries/ZenLibraries
|
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
|
[
"Apache-2.0"
] | 2
|
2020-02-06T17:01:39.000Z
|
2020-02-12T17:50:14.000Z
|
zen/lexgen/parser.hpp
|
ZenLibraries/ZenLibraries
|
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
|
[
"Apache-2.0"
] | null | null | null |
#ifndef ZEN_LEXGEN_PARSER_HPP
#define ZEN_LEXGEN_PARSER_HPP
#include "zen/stream.hpp"
#include "zen/lexgen/common.hpp"
#include "zen/lexgen/lexer.hpp"
#include "zen/lexgen/nodes.hpp"
namespace zen {
namespace lexgen {
using TokenStream = PeekStream<Token>;
class Parser {
TokenStream& tokens;
public:
inline Parser(TokenStream& tokens):
tokens(tokens) {}
Result<Node> parse_expr();
Result<Node> parse();
};
}
}
#endif // of #ifndef ZEN_LEXGEN_PARSER_HPP
| 14.472222
| 42
| 0.667946
|
ZenLibraries
|
38a48084ba5ab1c30c116ae9c1666d494ea3cd68
| 80
|
cpp
|
C++
|
sources/source.cpp
|
Gustafsson88/lr12
|
4db8ad87ba1b29890b43307b5b093bce900cea62
|
[
"MIT"
] | null | null | null |
sources/source.cpp
|
Gustafsson88/lr12
|
4db8ad87ba1b29890b43307b5b093bce900cea62
|
[
"MIT"
] | null | null | null |
sources/source.cpp
|
Gustafsson88/lr12
|
4db8ad87ba1b29890b43307b5b093bce900cea62
|
[
"MIT"
] | null | null | null |
// Copyright 2021 Alexandr Guchkov <firer.a45@gmail.com>
#include "header.hpp"
| 20
| 56
| 0.75
|
Gustafsson88
|
38a59f8ced308444dfb9946d96d823686cd00cb8
| 133
|
hpp
|
C++
|
include/NP-Engine/Input/Input.hpp
|
naphipps/NP-Engine
|
0cac8b2d5e76c839b96f2061bf57434bdc37915e
|
[
"MIT"
] | null | null | null |
include/NP-Engine/Input/Input.hpp
|
naphipps/NP-Engine
|
0cac8b2d5e76c839b96f2061bf57434bdc37915e
|
[
"MIT"
] | null | null | null |
include/NP-Engine/Input/Input.hpp
|
naphipps/NP-Engine
|
0cac8b2d5e76c839b96f2061bf57434bdc37915e
|
[
"MIT"
] | null | null | null |
//
// Input.hpp
// NP-Engine
//
// Created by Nathan Phipps on 2/13/21.
//
#ifndef Input_h
#define Input_h
#endif /* Input_h */
| 11.083333
| 40
| 0.616541
|
naphipps
|
38ae8c1bef93489a7a77aa35b3a65136eab2de0d
| 105,183
|
cpp
|
C++
|
AES_GPU_DX10/src/AES_GPU_DX10.cpp
|
Bizonu/amclibrary
|
6dacc2386064bc1fb0ad9ef1cf0774c5fed56bed
|
[
"Apache-2.0"
] | null | null | null |
AES_GPU_DX10/src/AES_GPU_DX10.cpp
|
Bizonu/amclibrary
|
6dacc2386064bc1fb0ad9ef1cf0774c5fed56bed
|
[
"Apache-2.0"
] | null | null | null |
AES_GPU_DX10/src/AES_GPU_DX10.cpp
|
Bizonu/amclibrary
|
6dacc2386064bc1fb0ad9ef1cf0774c5fed56bed
|
[
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// File: AES_GPU_DX10.cpp
/// Description: The implementation of the internal interface for the AES implementation on the GPU using DX10.
/// Author: Chiuta Adrian Marius
/// Created: 26-11-2009
///
/// 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 "platform.h"
#include "AES_GPU_DX10_Internal.h"
#if defined( DEBUG ) || defined( _DEBUG )
#include <stdio.h>
#include <intrin.h>
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p) = NULL; } }
#endif
#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY(p) { if(p) { delete [](p); (p) = NULL; } }
#endif
#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p) { delete (p); (p) = NULL; } }
#endif
#ifndef countof
#define countof( array ) ( sizeof( array )/sizeof( array[0] ) )
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The handle to this module
HMODULE gHModule = NULL;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//The following tables were generated using the code:
//
//void AddTable(FILE* fout, const char *tableName, const char *boxTable, const UINT8 *sbox,
// UINT32 v1, UINT32 v2, UINT32 v3, UINT32 v4)
//{
// fprintf(fout, "/*\n\tFor every value found at index we have:\n"
// "\t\t- bits 0..7 represent Multiply(%s[index], 0x%02X).\n"
// "\t\t- bits 8..15 represent Multiply(%s[index], 0x%02X).\n"
// "\t\t- bits 16..23 represent Multiply(%s[index], 0x%02X).\n"
// "\t\t- bits 24..31 represent Multiply(%s[index], 0x%02X).\n"
// "*/\n", boxTable, v1, boxTable, v2, boxTable, v3, boxTable, v4);
//
// fprintf(fout, "static const UINT32 %s[256] =\n{\n", tableName);
//
// UINT32 c = 0;
// for(UINT32 i = 0; i < 256; i++)
// {
// if(c == 0 )
// fprintf(fout, "\t");
//
// UINT32 iBox = sbox[i];
// UINT32 value = (Multiply(iBox, v1) & 0xFF) | ((Multiply(iBox, v2) & 0xFF) << 8) |
// ((Multiply(iBox, v3) & 0xFF) << 16) | ((Multiply(iBox, v4) & 0xFF) << 24);
//
// if( i != 255 )
// fprintf(fout, "0x%08X, ", value);
// else
// fprintf(fout, "0x%08X", value);
// if( c == 7 )
// fprintf(fout, "\n");
//
// c = (c + 1) & 7;
// }
//
// fprintf(fout, "};\n");
//}
//
//void CreateTables(char *fileName)
//{
// FILE *fout = fopen(fileName, "wt");
//
// AddTable(fout, "sBoxMixColumn_a", "sbox", sbox, 0x02, 0x01, 0x01, 0x03);
// AddTable(fout, "sBoxMixColumn_b", "sbox", sbox, 0x03, 0x02, 0x01, 0x01);
// AddTable(fout, "sBoxMixColumn_c", "sbox", sbox, 0x01, 0x03, 0x02, 0x01);
// AddTable(fout, "sBoxMixColumn_d", "sbox", sbox, 0x01, 0x01, 0x03, 0x02);
//
// AddTable(fout, "rsBoxInvMixColumn_a", "rsbox", rsbox, 0x0e, 0x09, 0x0d, 0x0b);
// AddTable(fout, "rsBoxInvMixColumn_b", "rsbox", rsbox, 0x0b, 0x0e, 0x09, 0x0d);
// AddTable(fout, "rsBoxInvMixColumn_c", "rsbox", rsbox, 0x0d, 0x0b, 0x0e, 0x09);
// AddTable(fout, "rsBoxInvMixColumn_d", "rsbox", rsbox, 0x09, 0x0d, 0x0b, 0x0e);
//
// fclose(fout);
//}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(sbox[index], 0x02).
- bits 8..15 represent Multiply(sbox[index], 0x01).
- bits 16..23 represent Multiply(sbox[index], 0x01).
- bits 24..31 represent Multiply(sbox[index], 0x03).
*/
__declspec(align(16)) static const UINT32 sBoxMixColumn_a[256] =
{
0xA56363C6, 0x847C7CF8, 0x997777EE, 0x8D7B7BF6, 0x0DF2F2FF, 0xBD6B6BD6, 0xB16F6FDE, 0x54C5C591,
0x50303060, 0x03010102, 0xA96767CE, 0x7D2B2B56, 0x19FEFEE7, 0x62D7D7B5, 0xE6ABAB4D, 0x9A7676EC,
0x45CACA8F, 0x9D82821F, 0x40C9C989, 0x877D7DFA, 0x15FAFAEF, 0xEB5959B2, 0xC947478E, 0x0BF0F0FB,
0xECADAD41, 0x67D4D4B3, 0xFDA2A25F, 0xEAAFAF45, 0xBF9C9C23, 0xF7A4A453, 0x967272E4, 0x5BC0C09B,
0xC2B7B775, 0x1CFDFDE1, 0xAE93933D, 0x6A26264C, 0x5A36366C, 0x413F3F7E, 0x02F7F7F5, 0x4FCCCC83,
0x5C343468, 0xF4A5A551, 0x34E5E5D1, 0x08F1F1F9, 0x937171E2, 0x73D8D8AB, 0x53313162, 0x3F15152A,
0x0C040408, 0x52C7C795, 0x65232346, 0x5EC3C39D, 0x28181830, 0xA1969637, 0x0F05050A, 0xB59A9A2F,
0x0907070E, 0x36121224, 0x9B80801B, 0x3DE2E2DF, 0x26EBEBCD, 0x6927274E, 0xCDB2B27F, 0x9F7575EA,
0x1B090912, 0x9E83831D, 0x742C2C58, 0x2E1A1A34, 0x2D1B1B36, 0xB26E6EDC, 0xEE5A5AB4, 0xFBA0A05B,
0xF65252A4, 0x4D3B3B76, 0x61D6D6B7, 0xCEB3B37D, 0x7B292952, 0x3EE3E3DD, 0x712F2F5E, 0x97848413,
0xF55353A6, 0x68D1D1B9, 0x00000000, 0x2CEDEDC1, 0x60202040, 0x1FFCFCE3, 0xC8B1B179, 0xED5B5BB6,
0xBE6A6AD4, 0x46CBCB8D, 0xD9BEBE67, 0x4B393972, 0xDE4A4A94, 0xD44C4C98, 0xE85858B0, 0x4ACFCF85,
0x6BD0D0BB, 0x2AEFEFC5, 0xE5AAAA4F, 0x16FBFBED, 0xC5434386, 0xD74D4D9A, 0x55333366, 0x94858511,
0xCF45458A, 0x10F9F9E9, 0x06020204, 0x817F7FFE, 0xF05050A0, 0x443C3C78, 0xBA9F9F25, 0xE3A8A84B,
0xF35151A2, 0xFEA3A35D, 0xC0404080, 0x8A8F8F05, 0xAD92923F, 0xBC9D9D21, 0x48383870, 0x04F5F5F1,
0xDFBCBC63, 0xC1B6B677, 0x75DADAAF, 0x63212142, 0x30101020, 0x1AFFFFE5, 0x0EF3F3FD, 0x6DD2D2BF,
0x4CCDCD81, 0x140C0C18, 0x35131326, 0x2FECECC3, 0xE15F5FBE, 0xA2979735, 0xCC444488, 0x3917172E,
0x57C4C493, 0xF2A7A755, 0x827E7EFC, 0x473D3D7A, 0xAC6464C8, 0xE75D5DBA, 0x2B191932, 0x957373E6,
0xA06060C0, 0x98818119, 0xD14F4F9E, 0x7FDCDCA3, 0x66222244, 0x7E2A2A54, 0xAB90903B, 0x8388880B,
0xCA46468C, 0x29EEEEC7, 0xD3B8B86B, 0x3C141428, 0x79DEDEA7, 0xE25E5EBC, 0x1D0B0B16, 0x76DBDBAD,
0x3BE0E0DB, 0x56323264, 0x4E3A3A74, 0x1E0A0A14, 0xDB494992, 0x0A06060C, 0x6C242448, 0xE45C5CB8,
0x5DC2C29F, 0x6ED3D3BD, 0xEFACAC43, 0xA66262C4, 0xA8919139, 0xA4959531, 0x37E4E4D3, 0x8B7979F2,
0x32E7E7D5, 0x43C8C88B, 0x5937376E, 0xB76D6DDA, 0x8C8D8D01, 0x64D5D5B1, 0xD24E4E9C, 0xE0A9A949,
0xB46C6CD8, 0xFA5656AC, 0x07F4F4F3, 0x25EAEACF, 0xAF6565CA, 0x8E7A7AF4, 0xE9AEAE47, 0x18080810,
0xD5BABA6F, 0x887878F0, 0x6F25254A, 0x722E2E5C, 0x241C1C38, 0xF1A6A657, 0xC7B4B473, 0x51C6C697,
0x23E8E8CB, 0x7CDDDDA1, 0x9C7474E8, 0x211F1F3E, 0xDD4B4B96, 0xDCBDBD61, 0x868B8B0D, 0x858A8A0F,
0x907070E0, 0x423E3E7C, 0xC4B5B571, 0xAA6666CC, 0xD8484890, 0x05030306, 0x01F6F6F7, 0x120E0E1C,
0xA36161C2, 0x5F35356A, 0xF95757AE, 0xD0B9B969, 0x91868617, 0x58C1C199, 0x271D1D3A, 0xB99E9E27,
0x38E1E1D9, 0x13F8F8EB, 0xB398982B, 0x33111122, 0xBB6969D2, 0x70D9D9A9, 0x898E8E07, 0xA7949433,
0xB69B9B2D, 0x221E1E3C, 0x92878715, 0x20E9E9C9, 0x49CECE87, 0xFF5555AA, 0x78282850, 0x7ADFDFA5,
0x8F8C8C03, 0xF8A1A159, 0x80898909, 0x170D0D1A, 0xDABFBF65, 0x31E6E6D7, 0xC6424284, 0xB86868D0,
0xC3414182, 0xB0999929, 0x772D2D5A, 0x110F0F1E, 0xCBB0B07B, 0xFC5454A8, 0xD6BBBB6D, 0x3A16162C
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(sbox[index], 0x03).
- bits 8..15 represent Multiply(sbox[index], 0x02).
- bits 16..23 represent Multiply(sbox[index], 0x01).
- bits 24..31 represent Multiply(sbox[index], 0x01).
*/
__declspec(align(16)) static const UINT32 sBoxMixColumn_b[256] =
{
0x6363C6A5, 0x7C7CF884, 0x7777EE99, 0x7B7BF68D, 0xF2F2FF0D, 0x6B6BD6BD, 0x6F6FDEB1, 0xC5C59154,
0x30306050, 0x01010203, 0x6767CEA9, 0x2B2B567D, 0xFEFEE719, 0xD7D7B562, 0xABAB4DE6, 0x7676EC9A,
0xCACA8F45, 0x82821F9D, 0xC9C98940, 0x7D7DFA87, 0xFAFAEF15, 0x5959B2EB, 0x47478EC9, 0xF0F0FB0B,
0xADAD41EC, 0xD4D4B367, 0xA2A25FFD, 0xAFAF45EA, 0x9C9C23BF, 0xA4A453F7, 0x7272E496, 0xC0C09B5B,
0xB7B775C2, 0xFDFDE11C, 0x93933DAE, 0x26264C6A, 0x36366C5A, 0x3F3F7E41, 0xF7F7F502, 0xCCCC834F,
0x3434685C, 0xA5A551F4, 0xE5E5D134, 0xF1F1F908, 0x7171E293, 0xD8D8AB73, 0x31316253, 0x15152A3F,
0x0404080C, 0xC7C79552, 0x23234665, 0xC3C39D5E, 0x18183028, 0x969637A1, 0x05050A0F, 0x9A9A2FB5,
0x07070E09, 0x12122436, 0x80801B9B, 0xE2E2DF3D, 0xEBEBCD26, 0x27274E69, 0xB2B27FCD, 0x7575EA9F,
0x0909121B, 0x83831D9E, 0x2C2C5874, 0x1A1A342E, 0x1B1B362D, 0x6E6EDCB2, 0x5A5AB4EE, 0xA0A05BFB,
0x5252A4F6, 0x3B3B764D, 0xD6D6B761, 0xB3B37DCE, 0x2929527B, 0xE3E3DD3E, 0x2F2F5E71, 0x84841397,
0x5353A6F5, 0xD1D1B968, 0x00000000, 0xEDEDC12C, 0x20204060, 0xFCFCE31F, 0xB1B179C8, 0x5B5BB6ED,
0x6A6AD4BE, 0xCBCB8D46, 0xBEBE67D9, 0x3939724B, 0x4A4A94DE, 0x4C4C98D4, 0x5858B0E8, 0xCFCF854A,
0xD0D0BB6B, 0xEFEFC52A, 0xAAAA4FE5, 0xFBFBED16, 0x434386C5, 0x4D4D9AD7, 0x33336655, 0x85851194,
0x45458ACF, 0xF9F9E910, 0x02020406, 0x7F7FFE81, 0x5050A0F0, 0x3C3C7844, 0x9F9F25BA, 0xA8A84BE3,
0x5151A2F3, 0xA3A35DFE, 0x404080C0, 0x8F8F058A, 0x92923FAD, 0x9D9D21BC, 0x38387048, 0xF5F5F104,
0xBCBC63DF, 0xB6B677C1, 0xDADAAF75, 0x21214263, 0x10102030, 0xFFFFE51A, 0xF3F3FD0E, 0xD2D2BF6D,
0xCDCD814C, 0x0C0C1814, 0x13132635, 0xECECC32F, 0x5F5FBEE1, 0x979735A2, 0x444488CC, 0x17172E39,
0xC4C49357, 0xA7A755F2, 0x7E7EFC82, 0x3D3D7A47, 0x6464C8AC, 0x5D5DBAE7, 0x1919322B, 0x7373E695,
0x6060C0A0, 0x81811998, 0x4F4F9ED1, 0xDCDCA37F, 0x22224466, 0x2A2A547E, 0x90903BAB, 0x88880B83,
0x46468CCA, 0xEEEEC729, 0xB8B86BD3, 0x1414283C, 0xDEDEA779, 0x5E5EBCE2, 0x0B0B161D, 0xDBDBAD76,
0xE0E0DB3B, 0x32326456, 0x3A3A744E, 0x0A0A141E, 0x494992DB, 0x06060C0A, 0x2424486C, 0x5C5CB8E4,
0xC2C29F5D, 0xD3D3BD6E, 0xACAC43EF, 0x6262C4A6, 0x919139A8, 0x959531A4, 0xE4E4D337, 0x7979F28B,
0xE7E7D532, 0xC8C88B43, 0x37376E59, 0x6D6DDAB7, 0x8D8D018C, 0xD5D5B164, 0x4E4E9CD2, 0xA9A949E0,
0x6C6CD8B4, 0x5656ACFA, 0xF4F4F307, 0xEAEACF25, 0x6565CAAF, 0x7A7AF48E, 0xAEAE47E9, 0x08081018,
0xBABA6FD5, 0x7878F088, 0x25254A6F, 0x2E2E5C72, 0x1C1C3824, 0xA6A657F1, 0xB4B473C7, 0xC6C69751,
0xE8E8CB23, 0xDDDDA17C, 0x7474E89C, 0x1F1F3E21, 0x4B4B96DD, 0xBDBD61DC, 0x8B8B0D86, 0x8A8A0F85,
0x7070E090, 0x3E3E7C42, 0xB5B571C4, 0x6666CCAA, 0x484890D8, 0x03030605, 0xF6F6F701, 0x0E0E1C12,
0x6161C2A3, 0x35356A5F, 0x5757AEF9, 0xB9B969D0, 0x86861791, 0xC1C19958, 0x1D1D3A27, 0x9E9E27B9,
0xE1E1D938, 0xF8F8EB13, 0x98982BB3, 0x11112233, 0x6969D2BB, 0xD9D9A970, 0x8E8E0789, 0x949433A7,
0x9B9B2DB6, 0x1E1E3C22, 0x87871592, 0xE9E9C920, 0xCECE8749, 0x5555AAFF, 0x28285078, 0xDFDFA57A,
0x8C8C038F, 0xA1A159F8, 0x89890980, 0x0D0D1A17, 0xBFBF65DA, 0xE6E6D731, 0x424284C6, 0x6868D0B8,
0x414182C3, 0x999929B0, 0x2D2D5A77, 0x0F0F1E11, 0xB0B07BCB, 0x5454A8FC, 0xBBBB6DD6, 0x16162C3A
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(sbox[index], 0x01).
- bits 8..15 represent Multiply(sbox[index], 0x03).
- bits 16..23 represent Multiply(sbox[index], 0x02).
- bits 24..31 represent Multiply(sbox[index], 0x01).
*/
__declspec(align(16)) static const UINT32 sBoxMixColumn_c[256] =
{
0x63C6A563, 0x7CF8847C, 0x77EE9977, 0x7BF68D7B, 0xF2FF0DF2, 0x6BD6BD6B, 0x6FDEB16F, 0xC59154C5,
0x30605030, 0x01020301, 0x67CEA967, 0x2B567D2B, 0xFEE719FE, 0xD7B562D7, 0xAB4DE6AB, 0x76EC9A76,
0xCA8F45CA, 0x821F9D82, 0xC98940C9, 0x7DFA877D, 0xFAEF15FA, 0x59B2EB59, 0x478EC947, 0xF0FB0BF0,
0xAD41ECAD, 0xD4B367D4, 0xA25FFDA2, 0xAF45EAAF, 0x9C23BF9C, 0xA453F7A4, 0x72E49672, 0xC09B5BC0,
0xB775C2B7, 0xFDE11CFD, 0x933DAE93, 0x264C6A26, 0x366C5A36, 0x3F7E413F, 0xF7F502F7, 0xCC834FCC,
0x34685C34, 0xA551F4A5, 0xE5D134E5, 0xF1F908F1, 0x71E29371, 0xD8AB73D8, 0x31625331, 0x152A3F15,
0x04080C04, 0xC79552C7, 0x23466523, 0xC39D5EC3, 0x18302818, 0x9637A196, 0x050A0F05, 0x9A2FB59A,
0x070E0907, 0x12243612, 0x801B9B80, 0xE2DF3DE2, 0xEBCD26EB, 0x274E6927, 0xB27FCDB2, 0x75EA9F75,
0x09121B09, 0x831D9E83, 0x2C58742C, 0x1A342E1A, 0x1B362D1B, 0x6EDCB26E, 0x5AB4EE5A, 0xA05BFBA0,
0x52A4F652, 0x3B764D3B, 0xD6B761D6, 0xB37DCEB3, 0x29527B29, 0xE3DD3EE3, 0x2F5E712F, 0x84139784,
0x53A6F553, 0xD1B968D1, 0x00000000, 0xEDC12CED, 0x20406020, 0xFCE31FFC, 0xB179C8B1, 0x5BB6ED5B,
0x6AD4BE6A, 0xCB8D46CB, 0xBE67D9BE, 0x39724B39, 0x4A94DE4A, 0x4C98D44C, 0x58B0E858, 0xCF854ACF,
0xD0BB6BD0, 0xEFC52AEF, 0xAA4FE5AA, 0xFBED16FB, 0x4386C543, 0x4D9AD74D, 0x33665533, 0x85119485,
0x458ACF45, 0xF9E910F9, 0x02040602, 0x7FFE817F, 0x50A0F050, 0x3C78443C, 0x9F25BA9F, 0xA84BE3A8,
0x51A2F351, 0xA35DFEA3, 0x4080C040, 0x8F058A8F, 0x923FAD92, 0x9D21BC9D, 0x38704838, 0xF5F104F5,
0xBC63DFBC, 0xB677C1B6, 0xDAAF75DA, 0x21426321, 0x10203010, 0xFFE51AFF, 0xF3FD0EF3, 0xD2BF6DD2,
0xCD814CCD, 0x0C18140C, 0x13263513, 0xECC32FEC, 0x5FBEE15F, 0x9735A297, 0x4488CC44, 0x172E3917,
0xC49357C4, 0xA755F2A7, 0x7EFC827E, 0x3D7A473D, 0x64C8AC64, 0x5DBAE75D, 0x19322B19, 0x73E69573,
0x60C0A060, 0x81199881, 0x4F9ED14F, 0xDCA37FDC, 0x22446622, 0x2A547E2A, 0x903BAB90, 0x880B8388,
0x468CCA46, 0xEEC729EE, 0xB86BD3B8, 0x14283C14, 0xDEA779DE, 0x5EBCE25E, 0x0B161D0B, 0xDBAD76DB,
0xE0DB3BE0, 0x32645632, 0x3A744E3A, 0x0A141E0A, 0x4992DB49, 0x060C0A06, 0x24486C24, 0x5CB8E45C,
0xC29F5DC2, 0xD3BD6ED3, 0xAC43EFAC, 0x62C4A662, 0x9139A891, 0x9531A495, 0xE4D337E4, 0x79F28B79,
0xE7D532E7, 0xC88B43C8, 0x376E5937, 0x6DDAB76D, 0x8D018C8D, 0xD5B164D5, 0x4E9CD24E, 0xA949E0A9,
0x6CD8B46C, 0x56ACFA56, 0xF4F307F4, 0xEACF25EA, 0x65CAAF65, 0x7AF48E7A, 0xAE47E9AE, 0x08101808,
0xBA6FD5BA, 0x78F08878, 0x254A6F25, 0x2E5C722E, 0x1C38241C, 0xA657F1A6, 0xB473C7B4, 0xC69751C6,
0xE8CB23E8, 0xDDA17CDD, 0x74E89C74, 0x1F3E211F, 0x4B96DD4B, 0xBD61DCBD, 0x8B0D868B, 0x8A0F858A,
0x70E09070, 0x3E7C423E, 0xB571C4B5, 0x66CCAA66, 0x4890D848, 0x03060503, 0xF6F701F6, 0x0E1C120E,
0x61C2A361, 0x356A5F35, 0x57AEF957, 0xB969D0B9, 0x86179186, 0xC19958C1, 0x1D3A271D, 0x9E27B99E,
0xE1D938E1, 0xF8EB13F8, 0x982BB398, 0x11223311, 0x69D2BB69, 0xD9A970D9, 0x8E07898E, 0x9433A794,
0x9B2DB69B, 0x1E3C221E, 0x87159287, 0xE9C920E9, 0xCE8749CE, 0x55AAFF55, 0x28507828, 0xDFA57ADF,
0x8C038F8C, 0xA159F8A1, 0x89098089, 0x0D1A170D, 0xBF65DABF, 0xE6D731E6, 0x4284C642, 0x68D0B868,
0x4182C341, 0x9929B099, 0x2D5A772D, 0x0F1E110F, 0xB07BCBB0, 0x54A8FC54, 0xBB6DD6BB, 0x162C3A16
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(sbox[index], 0x01).
- bits 8..15 represent Multiply(sbox[index], 0x01).
- bits 16..23 represent Multiply(sbox[index], 0x03).
- bits 24..31 represent Multiply(sbox[index], 0x02).
*/
__declspec(align(16)) static const UINT32 sBoxMixColumn_d[256] =
{
0xC6A56363, 0xF8847C7C, 0xEE997777, 0xF68D7B7B, 0xFF0DF2F2, 0xD6BD6B6B, 0xDEB16F6F, 0x9154C5C5,
0x60503030, 0x02030101, 0xCEA96767, 0x567D2B2B, 0xE719FEFE, 0xB562D7D7, 0x4DE6ABAB, 0xEC9A7676,
0x8F45CACA, 0x1F9D8282, 0x8940C9C9, 0xFA877D7D, 0xEF15FAFA, 0xB2EB5959, 0x8EC94747, 0xFB0BF0F0,
0x41ECADAD, 0xB367D4D4, 0x5FFDA2A2, 0x45EAAFAF, 0x23BF9C9C, 0x53F7A4A4, 0xE4967272, 0x9B5BC0C0,
0x75C2B7B7, 0xE11CFDFD, 0x3DAE9393, 0x4C6A2626, 0x6C5A3636, 0x7E413F3F, 0xF502F7F7, 0x834FCCCC,
0x685C3434, 0x51F4A5A5, 0xD134E5E5, 0xF908F1F1, 0xE2937171, 0xAB73D8D8, 0x62533131, 0x2A3F1515,
0x080C0404, 0x9552C7C7, 0x46652323, 0x9D5EC3C3, 0x30281818, 0x37A19696, 0x0A0F0505, 0x2FB59A9A,
0x0E090707, 0x24361212, 0x1B9B8080, 0xDF3DE2E2, 0xCD26EBEB, 0x4E692727, 0x7FCDB2B2, 0xEA9F7575,
0x121B0909, 0x1D9E8383, 0x58742C2C, 0x342E1A1A, 0x362D1B1B, 0xDCB26E6E, 0xB4EE5A5A, 0x5BFBA0A0,
0xA4F65252, 0x764D3B3B, 0xB761D6D6, 0x7DCEB3B3, 0x527B2929, 0xDD3EE3E3, 0x5E712F2F, 0x13978484,
0xA6F55353, 0xB968D1D1, 0x00000000, 0xC12CEDED, 0x40602020, 0xE31FFCFC, 0x79C8B1B1, 0xB6ED5B5B,
0xD4BE6A6A, 0x8D46CBCB, 0x67D9BEBE, 0x724B3939, 0x94DE4A4A, 0x98D44C4C, 0xB0E85858, 0x854ACFCF,
0xBB6BD0D0, 0xC52AEFEF, 0x4FE5AAAA, 0xED16FBFB, 0x86C54343, 0x9AD74D4D, 0x66553333, 0x11948585,
0x8ACF4545, 0xE910F9F9, 0x04060202, 0xFE817F7F, 0xA0F05050, 0x78443C3C, 0x25BA9F9F, 0x4BE3A8A8,
0xA2F35151, 0x5DFEA3A3, 0x80C04040, 0x058A8F8F, 0x3FAD9292, 0x21BC9D9D, 0x70483838, 0xF104F5F5,
0x63DFBCBC, 0x77C1B6B6, 0xAF75DADA, 0x42632121, 0x20301010, 0xE51AFFFF, 0xFD0EF3F3, 0xBF6DD2D2,
0x814CCDCD, 0x18140C0C, 0x26351313, 0xC32FECEC, 0xBEE15F5F, 0x35A29797, 0x88CC4444, 0x2E391717,
0x9357C4C4, 0x55F2A7A7, 0xFC827E7E, 0x7A473D3D, 0xC8AC6464, 0xBAE75D5D, 0x322B1919, 0xE6957373,
0xC0A06060, 0x19988181, 0x9ED14F4F, 0xA37FDCDC, 0x44662222, 0x547E2A2A, 0x3BAB9090, 0x0B838888,
0x8CCA4646, 0xC729EEEE, 0x6BD3B8B8, 0x283C1414, 0xA779DEDE, 0xBCE25E5E, 0x161D0B0B, 0xAD76DBDB,
0xDB3BE0E0, 0x64563232, 0x744E3A3A, 0x141E0A0A, 0x92DB4949, 0x0C0A0606, 0x486C2424, 0xB8E45C5C,
0x9F5DC2C2, 0xBD6ED3D3, 0x43EFACAC, 0xC4A66262, 0x39A89191, 0x31A49595, 0xD337E4E4, 0xF28B7979,
0xD532E7E7, 0x8B43C8C8, 0x6E593737, 0xDAB76D6D, 0x018C8D8D, 0xB164D5D5, 0x9CD24E4E, 0x49E0A9A9,
0xD8B46C6C, 0xACFA5656, 0xF307F4F4, 0xCF25EAEA, 0xCAAF6565, 0xF48E7A7A, 0x47E9AEAE, 0x10180808,
0x6FD5BABA, 0xF0887878, 0x4A6F2525, 0x5C722E2E, 0x38241C1C, 0x57F1A6A6, 0x73C7B4B4, 0x9751C6C6,
0xCB23E8E8, 0xA17CDDDD, 0xE89C7474, 0x3E211F1F, 0x96DD4B4B, 0x61DCBDBD, 0x0D868B8B, 0x0F858A8A,
0xE0907070, 0x7C423E3E, 0x71C4B5B5, 0xCCAA6666, 0x90D84848, 0x06050303, 0xF701F6F6, 0x1C120E0E,
0xC2A36161, 0x6A5F3535, 0xAEF95757, 0x69D0B9B9, 0x17918686, 0x9958C1C1, 0x3A271D1D, 0x27B99E9E,
0xD938E1E1, 0xEB13F8F8, 0x2BB39898, 0x22331111, 0xD2BB6969, 0xA970D9D9, 0x07898E8E, 0x33A79494,
0x2DB69B9B, 0x3C221E1E, 0x15928787, 0xC920E9E9, 0x8749CECE, 0xAAFF5555, 0x50782828, 0xA57ADFDF,
0x038F8C8C, 0x59F8A1A1, 0x09808989, 0x1A170D0D, 0x65DABFBF, 0xD731E6E6, 0x84C64242, 0xD0B86868,
0x82C34141, 0x29B09999, 0x5A772D2D, 0x1E110F0F, 0x7BCBB0B0, 0xA8FC5454, 0x6DD6BBBB, 0x2C3A1616
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(rsbox[index], 0x0E).
- bits 8..15 represent Multiply(rsbox[index], 0x09).
- bits 16..23 represent Multiply(rsbox[index], 0x0D).
- bits 24..31 represent Multiply(rsbox[index], 0x0B).
*/
__declspec(align(16)) static const UINT32 rsBoxInvMixColumn_a[256] =
{
0x50A7F451, 0x5365417E, 0xC3A4171A, 0x965E273A, 0xCB6BAB3B, 0xF1459D1F, 0xAB58FAAC, 0x9303E34B,
0x55FA3020, 0xF66D76AD, 0x9176CC88, 0x254C02F5, 0xFCD7E54F, 0xD7CB2AC5, 0x80443526, 0x8FA362B5,
0x495AB1DE, 0x671BBA25, 0x980EEA45, 0xE1C0FE5D, 0x02752FC3, 0x12F04C81, 0xA397468D, 0xC6F9D36B,
0xE75F8F03, 0x959C9215, 0xEB7A6DBF, 0xDA595295, 0x2D83BED4, 0xD3217458, 0x2969E049, 0x44C8C98E,
0x6A89C275, 0x78798EF4, 0x6B3E5899, 0xDD71B927, 0xB64FE1BE, 0x17AD88F0, 0x66AC20C9, 0xB43ACE7D,
0x184ADF63, 0x82311AE5, 0x60335197, 0x457F5362, 0xE07764B1, 0x84AE6BBB, 0x1CA081FE, 0x942B08F9,
0x58684870, 0x19FD458F, 0x876CDE94, 0xB7F87B52, 0x23D373AB, 0xE2024B72, 0x578F1FE3, 0x2AAB5566,
0x0728EBB2, 0x03C2B52F, 0x9A7BC586, 0xA50837D3, 0xF2872830, 0xB2A5BF23, 0xBA6A0302, 0x5C8216ED,
0x2B1CCF8A, 0x92B479A7, 0xF0F207F3, 0xA1E2694E, 0xCDF4DA65, 0xD5BE0506, 0x1F6234D1, 0x8AFEA6C4,
0x9D532E34, 0xA055F3A2, 0x32E18A05, 0x75EBF6A4, 0x39EC830B, 0xAAEF6040, 0x069F715E, 0x51106EBD,
0xF98A213E, 0x3D06DD96, 0xAE053EDD, 0x46BDE64D, 0xB58D5491, 0x055DC471, 0x6FD40604, 0xFF155060,
0x24FB9819, 0x97E9BDD6, 0xCC434089, 0x779ED967, 0xBD42E8B0, 0x888B8907, 0x385B19E7, 0xDBEEC879,
0x470A7CA1, 0xE90F427C, 0xC91E84F8, 0x00000000, 0x83868009, 0x48ED2B32, 0xAC70111E, 0x4E725A6C,
0xFBFF0EFD, 0x5638850F, 0x1ED5AE3D, 0x27392D36, 0x64D90F0A, 0x21A65C68, 0xD1545B9B, 0x3A2E3624,
0xB1670A0C, 0x0FE75793, 0xD296EEB4, 0x9E919B1B, 0x4FC5C080, 0xA220DC61, 0x694B775A, 0x161A121C,
0x0ABA93E2, 0xE52AA0C0, 0x43E0223C, 0x1D171B12, 0x0B0D090E, 0xADC78BF2, 0xB9A8B62D, 0xC8A91E14,
0x8519F157, 0x4C0775AF, 0xBBDD99EE, 0xFD607FA3, 0x9F2601F7, 0xBCF5725C, 0xC53B6644, 0x347EFB5B,
0x7629438B, 0xDCC623CB, 0x68FCEDB6, 0x63F1E4B8, 0xCADC31D7, 0x10856342, 0x40229713, 0x2011C684,
0x7D244A85, 0xF83DBBD2, 0x1132F9AE, 0x6DA129C7, 0x4B2F9E1D, 0xF330B2DC, 0xEC52860D, 0xD0E3C177,
0x6C16B32B, 0x99B970A9, 0xFA489411, 0x2264E947, 0xC48CFCA8, 0x1A3FF0A0, 0xD82C7D56, 0xEF903322,
0xC74E4987, 0xC1D138D9, 0xFEA2CA8C, 0x360BD498, 0xCF81F5A6, 0x28DE7AA5, 0x268EB7DA, 0xA4BFAD3F,
0xE49D3A2C, 0x0D927850, 0x9BCC5F6A, 0x62467E54, 0xC2138DF6, 0xE8B8D890, 0x5EF7392E, 0xF5AFC382,
0xBE805D9F, 0x7C93D069, 0xA92DD56F, 0xB31225CF, 0x3B99ACC8, 0xA77D1810, 0x6E639CE8, 0x7BBB3BDB,
0x097826CD, 0xF418596E, 0x01B79AEC, 0xA89A4F83, 0x656E95E6, 0x7EE6FFAA, 0x08CFBC21, 0xE6E815EF,
0xD99BE7BA, 0xCE366F4A, 0xD4099FEA, 0xD67CB029, 0xAFB2A431, 0x31233F2A, 0x3094A5C6, 0xC066A235,
0x37BC4E74, 0xA6CA82FC, 0xB0D090E0, 0x15D8A733, 0x4A9804F1, 0xF7DAEC41, 0x0E50CD7F, 0x2FF69117,
0x8DD64D76, 0x4DB0EF43, 0x544DAACC, 0xDF0496E4, 0xE3B5D19E, 0x1B886A4C, 0xB81F2CC1, 0x7F516546,
0x04EA5E9D, 0x5D358C01, 0x737487FA, 0x2E410BFB, 0x5A1D67B3, 0x52D2DB92, 0x335610E9, 0x1347D66D,
0x8C61D79A, 0x7A0CA137, 0x8E14F859, 0x893C13EB, 0xEE27A9CE, 0x35C961B7, 0xEDE51CE1, 0x3CB1477A,
0x59DFD29C, 0x3F73F255, 0x79CE1418, 0xBF37C773, 0xEACDF753, 0x5BAAFD5F, 0x146F3DDF, 0x86DB4478,
0x81F3AFCA, 0x3EC468B9, 0x2C342438, 0x5F40A3C2, 0x72C31D16, 0x0C25E2BC, 0x8B493C28, 0x41950DFF,
0x7101A839, 0xDEB30C08, 0x9CE4B4D8, 0x90C15664, 0x6184CB7B, 0x70B632D5, 0x745C6C48, 0x4257B8D0
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(rsbox[index], 0x0B).
- bits 8..15 represent Multiply(rsbox[index], 0x0E).
- bits 16..23 represent Multiply(rsbox[index], 0x09).
- bits 24..31 represent Multiply(rsbox[index], 0x0D).
*/
__declspec(align(16)) static const UINT32 rsBoxInvMixColumn_b[256] =
{
0xA7F45150, 0x65417E53, 0xA4171AC3, 0x5E273A96, 0x6BAB3BCB, 0x459D1FF1, 0x58FAACAB, 0x03E34B93,
0xFA302055, 0x6D76ADF6, 0x76CC8891, 0x4C02F525, 0xD7E54FFC, 0xCB2AC5D7, 0x44352680, 0xA362B58F,
0x5AB1DE49, 0x1BBA2567, 0x0EEA4598, 0xC0FE5DE1, 0x752FC302, 0xF04C8112, 0x97468DA3, 0xF9D36BC6,
0x5F8F03E7, 0x9C921595, 0x7A6DBFEB, 0x595295DA, 0x83BED42D, 0x217458D3, 0x69E04929, 0xC8C98E44,
0x89C2756A, 0x798EF478, 0x3E58996B, 0x71B927DD, 0x4FE1BEB6, 0xAD88F017, 0xAC20C966, 0x3ACE7DB4,
0x4ADF6318, 0x311AE582, 0x33519760, 0x7F536245, 0x7764B1E0, 0xAE6BBB84, 0xA081FE1C, 0x2B08F994,
0x68487058, 0xFD458F19, 0x6CDE9487, 0xF87B52B7, 0xD373AB23, 0x024B72E2, 0x8F1FE357, 0xAB55662A,
0x28EBB207, 0xC2B52F03, 0x7BC5869A, 0x0837D3A5, 0x872830F2, 0xA5BF23B2, 0x6A0302BA, 0x8216ED5C,
0x1CCF8A2B, 0xB479A792, 0xF207F3F0, 0xE2694EA1, 0xF4DA65CD, 0xBE0506D5, 0x6234D11F, 0xFEA6C48A,
0x532E349D, 0x55F3A2A0, 0xE18A0532, 0xEBF6A475, 0xEC830B39, 0xEF6040AA, 0x9F715E06, 0x106EBD51,
0x8A213EF9, 0x06DD963D, 0x053EDDAE, 0xBDE64D46, 0x8D5491B5, 0x5DC47105, 0xD406046F, 0x155060FF,
0xFB981924, 0xE9BDD697, 0x434089CC, 0x9ED96777, 0x42E8B0BD, 0x8B890788, 0x5B19E738, 0xEEC879DB,
0x0A7CA147, 0x0F427CE9, 0x1E84F8C9, 0x00000000, 0x86800983, 0xED2B3248, 0x70111EAC, 0x725A6C4E,
0xFF0EFDFB, 0x38850F56, 0xD5AE3D1E, 0x392D3627, 0xD90F0A64, 0xA65C6821, 0x545B9BD1, 0x2E36243A,
0x670A0CB1, 0xE757930F, 0x96EEB4D2, 0x919B1B9E, 0xC5C0804F, 0x20DC61A2, 0x4B775A69, 0x1A121C16,
0xBA93E20A, 0x2AA0C0E5, 0xE0223C43, 0x171B121D, 0x0D090E0B, 0xC78BF2AD, 0xA8B62DB9, 0xA91E14C8,
0x19F15785, 0x0775AF4C, 0xDD99EEBB, 0x607FA3FD, 0x2601F79F, 0xF5725CBC, 0x3B6644C5, 0x7EFB5B34,
0x29438B76, 0xC623CBDC, 0xFCEDB668, 0xF1E4B863, 0xDC31D7CA, 0x85634210, 0x22971340, 0x11C68420,
0x244A857D, 0x3DBBD2F8, 0x32F9AE11, 0xA129C76D, 0x2F9E1D4B, 0x30B2DCF3, 0x52860DEC, 0xE3C177D0,
0x16B32B6C, 0xB970A999, 0x489411FA, 0x64E94722, 0x8CFCA8C4, 0x3FF0A01A, 0x2C7D56D8, 0x903322EF,
0x4E4987C7, 0xD138D9C1, 0xA2CA8CFE, 0x0BD49836, 0x81F5A6CF, 0xDE7AA528, 0x8EB7DA26, 0xBFAD3FA4,
0x9D3A2CE4, 0x9278500D, 0xCC5F6A9B, 0x467E5462, 0x138DF6C2, 0xB8D890E8, 0xF7392E5E, 0xAFC382F5,
0x805D9FBE, 0x93D0697C, 0x2DD56FA9, 0x1225CFB3, 0x99ACC83B, 0x7D1810A7, 0x639CE86E, 0xBB3BDB7B,
0x7826CD09, 0x18596EF4, 0xB79AEC01, 0x9A4F83A8, 0x6E95E665, 0xE6FFAA7E, 0xCFBC2108, 0xE815EFE6,
0x9BE7BAD9, 0x366F4ACE, 0x099FEAD4, 0x7CB029D6, 0xB2A431AF, 0x233F2A31, 0x94A5C630, 0x66A235C0,
0xBC4E7437, 0xCA82FCA6, 0xD090E0B0, 0xD8A73315, 0x9804F14A, 0xDAEC41F7, 0x50CD7F0E, 0xF691172F,
0xD64D768D, 0xB0EF434D, 0x4DAACC54, 0x0496E4DF, 0xB5D19EE3, 0x886A4C1B, 0x1F2CC1B8, 0x5165467F,
0xEA5E9D04, 0x358C015D, 0x7487FA73, 0x410BFB2E, 0x1D67B35A, 0xD2DB9252, 0x5610E933, 0x47D66D13,
0x61D79A8C, 0x0CA1377A, 0x14F8598E, 0x3C13EB89, 0x27A9CEEE, 0xC961B735, 0xE51CE1ED, 0xB1477A3C,
0xDFD29C59, 0x73F2553F, 0xCE141879, 0x37C773BF, 0xCDF753EA, 0xAAFD5F5B, 0x6F3DDF14, 0xDB447886,
0xF3AFCA81, 0xC468B93E, 0x3424382C, 0x40A3C25F, 0xC31D1672, 0x25E2BC0C, 0x493C288B, 0x950DFF41,
0x01A83971, 0xB30C08DE, 0xE4B4D89C, 0xC1566490, 0x84CB7B61, 0xB632D570, 0x5C6C4874, 0x57B8D042
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(rsbox[index], 0x0D).
- bits 8..15 represent Multiply(rsbox[index], 0x0B).
- bits 16..23 represent Multiply(rsbox[index], 0x0E).
- bits 24..31 represent Multiply(rsbox[index], 0x09).
*/
__declspec(align(16)) static const UINT32 rsBoxInvMixColumn_c[256] =
{
0xF45150A7, 0x417E5365, 0x171AC3A4, 0x273A965E, 0xAB3BCB6B, 0x9D1FF145, 0xFAACAB58, 0xE34B9303,
0x302055FA, 0x76ADF66D, 0xCC889176, 0x02F5254C, 0xE54FFCD7, 0x2AC5D7CB, 0x35268044, 0x62B58FA3,
0xB1DE495A, 0xBA25671B, 0xEA45980E, 0xFE5DE1C0, 0x2FC30275, 0x4C8112F0, 0x468DA397, 0xD36BC6F9,
0x8F03E75F, 0x9215959C, 0x6DBFEB7A, 0x5295DA59, 0xBED42D83, 0x7458D321, 0xE0492969, 0xC98E44C8,
0xC2756A89, 0x8EF47879, 0x58996B3E, 0xB927DD71, 0xE1BEB64F, 0x88F017AD, 0x20C966AC, 0xCE7DB43A,
0xDF63184A, 0x1AE58231, 0x51976033, 0x5362457F, 0x64B1E077, 0x6BBB84AE, 0x81FE1CA0, 0x08F9942B,
0x48705868, 0x458F19FD, 0xDE94876C, 0x7B52B7F8, 0x73AB23D3, 0x4B72E202, 0x1FE3578F, 0x55662AAB,
0xEBB20728, 0xB52F03C2, 0xC5869A7B, 0x37D3A508, 0x2830F287, 0xBF23B2A5, 0x0302BA6A, 0x16ED5C82,
0xCF8A2B1C, 0x79A792B4, 0x07F3F0F2, 0x694EA1E2, 0xDA65CDF4, 0x0506D5BE, 0x34D11F62, 0xA6C48AFE,
0x2E349D53, 0xF3A2A055, 0x8A0532E1, 0xF6A475EB, 0x830B39EC, 0x6040AAEF, 0x715E069F, 0x6EBD5110,
0x213EF98A, 0xDD963D06, 0x3EDDAE05, 0xE64D46BD, 0x5491B58D, 0xC471055D, 0x06046FD4, 0x5060FF15,
0x981924FB, 0xBDD697E9, 0x4089CC43, 0xD967779E, 0xE8B0BD42, 0x8907888B, 0x19E7385B, 0xC879DBEE,
0x7CA1470A, 0x427CE90F, 0x84F8C91E, 0x00000000, 0x80098386, 0x2B3248ED, 0x111EAC70, 0x5A6C4E72,
0x0EFDFBFF, 0x850F5638, 0xAE3D1ED5, 0x2D362739, 0x0F0A64D9, 0x5C6821A6, 0x5B9BD154, 0x36243A2E,
0x0A0CB167, 0x57930FE7, 0xEEB4D296, 0x9B1B9E91, 0xC0804FC5, 0xDC61A220, 0x775A694B, 0x121C161A,
0x93E20ABA, 0xA0C0E52A, 0x223C43E0, 0x1B121D17, 0x090E0B0D, 0x8BF2ADC7, 0xB62DB9A8, 0x1E14C8A9,
0xF1578519, 0x75AF4C07, 0x99EEBBDD, 0x7FA3FD60, 0x01F79F26, 0x725CBCF5, 0x6644C53B, 0xFB5B347E,
0x438B7629, 0x23CBDCC6, 0xEDB668FC, 0xE4B863F1, 0x31D7CADC, 0x63421085, 0x97134022, 0xC6842011,
0x4A857D24, 0xBBD2F83D, 0xF9AE1132, 0x29C76DA1, 0x9E1D4B2F, 0xB2DCF330, 0x860DEC52, 0xC177D0E3,
0xB32B6C16, 0x70A999B9, 0x9411FA48, 0xE9472264, 0xFCA8C48C, 0xF0A01A3F, 0x7D56D82C, 0x3322EF90,
0x4987C74E, 0x38D9C1D1, 0xCA8CFEA2, 0xD498360B, 0xF5A6CF81, 0x7AA528DE, 0xB7DA268E, 0xAD3FA4BF,
0x3A2CE49D, 0x78500D92, 0x5F6A9BCC, 0x7E546246, 0x8DF6C213, 0xD890E8B8, 0x392E5EF7, 0xC382F5AF,
0x5D9FBE80, 0xD0697C93, 0xD56FA92D, 0x25CFB312, 0xACC83B99, 0x1810A77D, 0x9CE86E63, 0x3BDB7BBB,
0x26CD0978, 0x596EF418, 0x9AEC01B7, 0x4F83A89A, 0x95E6656E, 0xFFAA7EE6, 0xBC2108CF, 0x15EFE6E8,
0xE7BAD99B, 0x6F4ACE36, 0x9FEAD409, 0xB029D67C, 0xA431AFB2, 0x3F2A3123, 0xA5C63094, 0xA235C066,
0x4E7437BC, 0x82FCA6CA, 0x90E0B0D0, 0xA73315D8, 0x04F14A98, 0xEC41F7DA, 0xCD7F0E50, 0x91172FF6,
0x4D768DD6, 0xEF434DB0, 0xAACC544D, 0x96E4DF04, 0xD19EE3B5, 0x6A4C1B88, 0x2CC1B81F, 0x65467F51,
0x5E9D04EA, 0x8C015D35, 0x87FA7374, 0x0BFB2E41, 0x67B35A1D, 0xDB9252D2, 0x10E93356, 0xD66D1347,
0xD79A8C61, 0xA1377A0C, 0xF8598E14, 0x13EB893C, 0xA9CEEE27, 0x61B735C9, 0x1CE1EDE5, 0x477A3CB1,
0xD29C59DF, 0xF2553F73, 0x141879CE, 0xC773BF37, 0xF753EACD, 0xFD5F5BAA, 0x3DDF146F, 0x447886DB,
0xAFCA81F3, 0x68B93EC4, 0x24382C34, 0xA3C25F40, 0x1D1672C3, 0xE2BC0C25, 0x3C288B49, 0x0DFF4195,
0xA8397101, 0x0C08DEB3, 0xB4D89CE4, 0x566490C1, 0xCB7B6184, 0x32D570B6, 0x6C48745C, 0xB8D04257
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(rsbox[index], 0x09).
- bits 8..15 represent Multiply(rsbox[index], 0x0D).
- bits 16..23 represent Multiply(rsbox[index], 0x0B).
- bits 24..31 represent Multiply(rsbox[index], 0x0E).
*/
__declspec(align(16)) static const UINT32 rsBoxInvMixColumn_d[256] =
{
0x5150A7F4, 0x7E536541, 0x1AC3A417, 0x3A965E27, 0x3BCB6BAB, 0x1FF1459D, 0xACAB58FA, 0x4B9303E3,
0x2055FA30, 0xADF66D76, 0x889176CC, 0xF5254C02, 0x4FFCD7E5, 0xC5D7CB2A, 0x26804435, 0xB58FA362,
0xDE495AB1, 0x25671BBA, 0x45980EEA, 0x5DE1C0FE, 0xC302752F, 0x8112F04C, 0x8DA39746, 0x6BC6F9D3,
0x03E75F8F, 0x15959C92, 0xBFEB7A6D, 0x95DA5952, 0xD42D83BE, 0x58D32174, 0x492969E0, 0x8E44C8C9,
0x756A89C2, 0xF478798E, 0x996B3E58, 0x27DD71B9, 0xBEB64FE1, 0xF017AD88, 0xC966AC20, 0x7DB43ACE,
0x63184ADF, 0xE582311A, 0x97603351, 0x62457F53, 0xB1E07764, 0xBB84AE6B, 0xFE1CA081, 0xF9942B08,
0x70586848, 0x8F19FD45, 0x94876CDE, 0x52B7F87B, 0xAB23D373, 0x72E2024B, 0xE3578F1F, 0x662AAB55,
0xB20728EB, 0x2F03C2B5, 0x869A7BC5, 0xD3A50837, 0x30F28728, 0x23B2A5BF, 0x02BA6A03, 0xED5C8216,
0x8A2B1CCF, 0xA792B479, 0xF3F0F207, 0x4EA1E269, 0x65CDF4DA, 0x06D5BE05, 0xD11F6234, 0xC48AFEA6,
0x349D532E, 0xA2A055F3, 0x0532E18A, 0xA475EBF6, 0x0B39EC83, 0x40AAEF60, 0x5E069F71, 0xBD51106E,
0x3EF98A21, 0x963D06DD, 0xDDAE053E, 0x4D46BDE6, 0x91B58D54, 0x71055DC4, 0x046FD406, 0x60FF1550,
0x1924FB98, 0xD697E9BD, 0x89CC4340, 0x67779ED9, 0xB0BD42E8, 0x07888B89, 0xE7385B19, 0x79DBEEC8,
0xA1470A7C, 0x7CE90F42, 0xF8C91E84, 0x00000000, 0x09838680, 0x3248ED2B, 0x1EAC7011, 0x6C4E725A,
0xFDFBFF0E, 0x0F563885, 0x3D1ED5AE, 0x3627392D, 0x0A64D90F, 0x6821A65C, 0x9BD1545B, 0x243A2E36,
0x0CB1670A, 0x930FE757, 0xB4D296EE, 0x1B9E919B, 0x804FC5C0, 0x61A220DC, 0x5A694B77, 0x1C161A12,
0xE20ABA93, 0xC0E52AA0, 0x3C43E022, 0x121D171B, 0x0E0B0D09, 0xF2ADC78B, 0x2DB9A8B6, 0x14C8A91E,
0x578519F1, 0xAF4C0775, 0xEEBBDD99, 0xA3FD607F, 0xF79F2601, 0x5CBCF572, 0x44C53B66, 0x5B347EFB,
0x8B762943, 0xCBDCC623, 0xB668FCED, 0xB863F1E4, 0xD7CADC31, 0x42108563, 0x13402297, 0x842011C6,
0x857D244A, 0xD2F83DBB, 0xAE1132F9, 0xC76DA129, 0x1D4B2F9E, 0xDCF330B2, 0x0DEC5286, 0x77D0E3C1,
0x2B6C16B3, 0xA999B970, 0x11FA4894, 0x472264E9, 0xA8C48CFC, 0xA01A3FF0, 0x56D82C7D, 0x22EF9033,
0x87C74E49, 0xD9C1D138, 0x8CFEA2CA, 0x98360BD4, 0xA6CF81F5, 0xA528DE7A, 0xDA268EB7, 0x3FA4BFAD,
0x2CE49D3A, 0x500D9278, 0x6A9BCC5F, 0x5462467E, 0xF6C2138D, 0x90E8B8D8, 0x2E5EF739, 0x82F5AFC3,
0x9FBE805D, 0x697C93D0, 0x6FA92DD5, 0xCFB31225, 0xC83B99AC, 0x10A77D18, 0xE86E639C, 0xDB7BBB3B,
0xCD097826, 0x6EF41859, 0xEC01B79A, 0x83A89A4F, 0xE6656E95, 0xAA7EE6FF, 0x2108CFBC, 0xEFE6E815,
0xBAD99BE7, 0x4ACE366F, 0xEAD4099F, 0x29D67CB0, 0x31AFB2A4, 0x2A31233F, 0xC63094A5, 0x35C066A2,
0x7437BC4E, 0xFCA6CA82, 0xE0B0D090, 0x3315D8A7, 0xF14A9804, 0x41F7DAEC, 0x7F0E50CD, 0x172FF691,
0x768DD64D, 0x434DB0EF, 0xCC544DAA, 0xE4DF0496, 0x9EE3B5D1, 0x4C1B886A, 0xC1B81F2C, 0x467F5165,
0x9D04EA5E, 0x015D358C, 0xFA737487, 0xFB2E410B, 0xB35A1D67, 0x9252D2DB, 0xE9335610, 0x6D1347D6,
0x9A8C61D7, 0x377A0CA1, 0x598E14F8, 0xEB893C13, 0xCEEE27A9, 0xB735C961, 0xE1EDE51C, 0x7A3CB147,
0x9C59DFD2, 0x553F73F2, 0x1879CE14, 0x73BF37C7, 0x53EACDF7, 0x5F5BAAFD, 0xDF146F3D, 0x7886DB44,
0xCA81F3AF, 0xB93EC468, 0x382C3424, 0xC25F40A3, 0x1672C31D, 0xBC0C25E2, 0x288B493C, 0xFF41950D,
0x397101A8, 0x08DEB30C, 0xD89CE4B4, 0x6490C156, 0x7B6184CB, 0xD570B632, 0x48745C6C, 0xD04257B8
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//The following tables were generated using the code:
//
//void AddTable(FILE* fout, const char *tableName, UINT32 v1, UINT32 v2, UINT32 v3, UINT32 v4)
//{
// fprintf(fout, "/*\n\tFor every value found at index we have:\n"
// "\t\t- bits 0..7 represent Multiply(index, 0x%02X).\n"
// "\t\t- bits 8..15 represent Multiply(index, 0x%02X).\n"
// "\t\t- bits 16..23 represent Multiply(index, 0x%02X).\n"
// "\t\t- bits 24..31 represent Multiply(index, 0x%02X).\n"
// "*/\n", v1, v2, v3, v4);
//
// fprintf(fout, "static const UINT32 %s[256] =\n{\n", tableName);
//
// UINT32 c = 0;
// for(UINT32 i = 0; i < 256; i++)
// {
// if(c == 0 )
// fprintf(fout, "\t");
//
// UINT32 value = (Multiply(i, v1) & 0xFF) | ((Multiply(i, v2) & 0xFF) << 8) |
// ((Multiply(i, v3) & 0xFF) << 16) | ((Multiply(i, v4) & 0xFF) << 24);
//
// if( i != 255 )
// fprintf(fout, "0x%08X, ", value);
// else
// fprintf(fout, "0x%08X", value);
// if( c == 7 )
// fprintf(fout, "\n");
//
// c = (c + 1) & 7;
// }
//
// fprintf(fout, "};\n");
//}
//
//void CreateTables(char *fileName)
//{
// FILE *fout = fopen(fileName, "wt");
//
// AddTable(fout, "invMixColumn_a", 0x0e, 0x09, 0x0d, 0x0b);
// AddTable(fout, "invMixColumn_b", 0x0b, 0x0e, 0x09, 0x0d);
// AddTable(fout, "invMixColumn_c", 0x0d, 0x0b, 0x0e, 0x09);
// AddTable(fout, "invMixColumn_d", 0x09, 0x0d, 0x0b, 0x0e);
//
// fclose(fout);
//}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(index, 0x0E).
- bits 8..15 represent Multiply(index, 0x09).
- bits 16..23 represent Multiply(index, 0x0D).
- bits 24..31 represent Multiply(index, 0x0B).
*/
__declspec(align(16)) static const UINT32 invMixColumn_a[256] =
{
0x00000000, 0x0B0D090E, 0x161A121C, 0x1D171B12, 0x2C342438, 0x27392D36, 0x3A2E3624, 0x31233F2A,
0x58684870, 0x5365417E, 0x4E725A6C, 0x457F5362, 0x745C6C48, 0x7F516546, 0x62467E54, 0x694B775A,
0xB0D090E0, 0xBBDD99EE, 0xA6CA82FC, 0xADC78BF2, 0x9CE4B4D8, 0x97E9BDD6, 0x8AFEA6C4, 0x81F3AFCA,
0xE8B8D890, 0xE3B5D19E, 0xFEA2CA8C, 0xF5AFC382, 0xC48CFCA8, 0xCF81F5A6, 0xD296EEB4, 0xD99BE7BA,
0x7BBB3BDB, 0x70B632D5, 0x6DA129C7, 0x66AC20C9, 0x578F1FE3, 0x5C8216ED, 0x41950DFF, 0x4A9804F1,
0x23D373AB, 0x28DE7AA5, 0x35C961B7, 0x3EC468B9, 0x0FE75793, 0x04EA5E9D, 0x19FD458F, 0x12F04C81,
0xCB6BAB3B, 0xC066A235, 0xDD71B927, 0xD67CB029, 0xE75F8F03, 0xEC52860D, 0xF1459D1F, 0xFA489411,
0x9303E34B, 0x980EEA45, 0x8519F157, 0x8E14F859, 0xBF37C773, 0xB43ACE7D, 0xA92DD56F, 0xA220DC61,
0xF66D76AD, 0xFD607FA3, 0xE07764B1, 0xEB7A6DBF, 0xDA595295, 0xD1545B9B, 0xCC434089, 0xC74E4987,
0xAE053EDD, 0xA50837D3, 0xB81F2CC1, 0xB31225CF, 0x82311AE5, 0x893C13EB, 0x942B08F9, 0x9F2601F7,
0x46BDE64D, 0x4DB0EF43, 0x50A7F451, 0x5BAAFD5F, 0x6A89C275, 0x6184CB7B, 0x7C93D069, 0x779ED967,
0x1ED5AE3D, 0x15D8A733, 0x08CFBC21, 0x03C2B52F, 0x32E18A05, 0x39EC830B, 0x24FB9819, 0x2FF69117,
0x8DD64D76, 0x86DB4478, 0x9BCC5F6A, 0x90C15664, 0xA1E2694E, 0xAAEF6040, 0xB7F87B52, 0xBCF5725C,
0xD5BE0506, 0xDEB30C08, 0xC3A4171A, 0xC8A91E14, 0xF98A213E, 0xF2872830, 0xEF903322, 0xE49D3A2C,
0x3D06DD96, 0x360BD498, 0x2B1CCF8A, 0x2011C684, 0x1132F9AE, 0x1A3FF0A0, 0x0728EBB2, 0x0C25E2BC,
0x656E95E6, 0x6E639CE8, 0x737487FA, 0x78798EF4, 0x495AB1DE, 0x4257B8D0, 0x5F40A3C2, 0x544DAACC,
0xF7DAEC41, 0xFCD7E54F, 0xE1C0FE5D, 0xEACDF753, 0xDBEEC879, 0xD0E3C177, 0xCDF4DA65, 0xC6F9D36B,
0xAFB2A431, 0xA4BFAD3F, 0xB9A8B62D, 0xB2A5BF23, 0x83868009, 0x888B8907, 0x959C9215, 0x9E919B1B,
0x470A7CA1, 0x4C0775AF, 0x51106EBD, 0x5A1D67B3, 0x6B3E5899, 0x60335197, 0x7D244A85, 0x7629438B,
0x1F6234D1, 0x146F3DDF, 0x097826CD, 0x02752FC3, 0x335610E9, 0x385B19E7, 0x254C02F5, 0x2E410BFB,
0x8C61D79A, 0x876CDE94, 0x9A7BC586, 0x9176CC88, 0xA055F3A2, 0xAB58FAAC, 0xB64FE1BE, 0xBD42E8B0,
0xD4099FEA, 0xDF0496E4, 0xC2138DF6, 0xC91E84F8, 0xF83DBBD2, 0xF330B2DC, 0xEE27A9CE, 0xE52AA0C0,
0x3CB1477A, 0x37BC4E74, 0x2AAB5566, 0x21A65C68, 0x10856342, 0x1B886A4C, 0x069F715E, 0x0D927850,
0x64D90F0A, 0x6FD40604, 0x72C31D16, 0x79CE1418, 0x48ED2B32, 0x43E0223C, 0x5EF7392E, 0x55FA3020,
0x01B79AEC, 0x0ABA93E2, 0x17AD88F0, 0x1CA081FE, 0x2D83BED4, 0x268EB7DA, 0x3B99ACC8, 0x3094A5C6,
0x59DFD29C, 0x52D2DB92, 0x4FC5C080, 0x44C8C98E, 0x75EBF6A4, 0x7EE6FFAA, 0x63F1E4B8, 0x68FCEDB6,
0xB1670A0C, 0xBA6A0302, 0xA77D1810, 0xAC70111E, 0x9D532E34, 0x965E273A, 0x8B493C28, 0x80443526,
0xE90F427C, 0xE2024B72, 0xFF155060, 0xF418596E, 0xC53B6644, 0xCE366F4A, 0xD3217458, 0xD82C7D56,
0x7A0CA137, 0x7101A839, 0x6C16B32B, 0x671BBA25, 0x5638850F, 0x5D358C01, 0x40229713, 0x4B2F9E1D,
0x2264E947, 0x2969E049, 0x347EFB5B, 0x3F73F255, 0x0E50CD7F, 0x055DC471, 0x184ADF63, 0x1347D66D,
0xCADC31D7, 0xC1D138D9, 0xDCC623CB, 0xD7CB2AC5, 0xE6E815EF, 0xEDE51CE1, 0xF0F207F3, 0xFBFF0EFD,
0x92B479A7, 0x99B970A9, 0x84AE6BBB, 0x8FA362B5, 0xBE805D9F, 0xB58D5491, 0xA89A4F83, 0xA397468D
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(index, 0x0B).
- bits 8..15 represent Multiply(index, 0x0E).
- bits 16..23 represent Multiply(index, 0x09).
- bits 24..31 represent Multiply(index, 0x0D).
*/
__declspec(align(16)) static const UINT32 invMixColumn_b[256] =
{
0x00000000, 0x0D090E0B, 0x1A121C16, 0x171B121D, 0x3424382C, 0x392D3627, 0x2E36243A, 0x233F2A31,
0x68487058, 0x65417E53, 0x725A6C4E, 0x7F536245, 0x5C6C4874, 0x5165467F, 0x467E5462, 0x4B775A69,
0xD090E0B0, 0xDD99EEBB, 0xCA82FCA6, 0xC78BF2AD, 0xE4B4D89C, 0xE9BDD697, 0xFEA6C48A, 0xF3AFCA81,
0xB8D890E8, 0xB5D19EE3, 0xA2CA8CFE, 0xAFC382F5, 0x8CFCA8C4, 0x81F5A6CF, 0x96EEB4D2, 0x9BE7BAD9,
0xBB3BDB7B, 0xB632D570, 0xA129C76D, 0xAC20C966, 0x8F1FE357, 0x8216ED5C, 0x950DFF41, 0x9804F14A,
0xD373AB23, 0xDE7AA528, 0xC961B735, 0xC468B93E, 0xE757930F, 0xEA5E9D04, 0xFD458F19, 0xF04C8112,
0x6BAB3BCB, 0x66A235C0, 0x71B927DD, 0x7CB029D6, 0x5F8F03E7, 0x52860DEC, 0x459D1FF1, 0x489411FA,
0x03E34B93, 0x0EEA4598, 0x19F15785, 0x14F8598E, 0x37C773BF, 0x3ACE7DB4, 0x2DD56FA9, 0x20DC61A2,
0x6D76ADF6, 0x607FA3FD, 0x7764B1E0, 0x7A6DBFEB, 0x595295DA, 0x545B9BD1, 0x434089CC, 0x4E4987C7,
0x053EDDAE, 0x0837D3A5, 0x1F2CC1B8, 0x1225CFB3, 0x311AE582, 0x3C13EB89, 0x2B08F994, 0x2601F79F,
0xBDE64D46, 0xB0EF434D, 0xA7F45150, 0xAAFD5F5B, 0x89C2756A, 0x84CB7B61, 0x93D0697C, 0x9ED96777,
0xD5AE3D1E, 0xD8A73315, 0xCFBC2108, 0xC2B52F03, 0xE18A0532, 0xEC830B39, 0xFB981924, 0xF691172F,
0xD64D768D, 0xDB447886, 0xCC5F6A9B, 0xC1566490, 0xE2694EA1, 0xEF6040AA, 0xF87B52B7, 0xF5725CBC,
0xBE0506D5, 0xB30C08DE, 0xA4171AC3, 0xA91E14C8, 0x8A213EF9, 0x872830F2, 0x903322EF, 0x9D3A2CE4,
0x06DD963D, 0x0BD49836, 0x1CCF8A2B, 0x11C68420, 0x32F9AE11, 0x3FF0A01A, 0x28EBB207, 0x25E2BC0C,
0x6E95E665, 0x639CE86E, 0x7487FA73, 0x798EF478, 0x5AB1DE49, 0x57B8D042, 0x40A3C25F, 0x4DAACC54,
0xDAEC41F7, 0xD7E54FFC, 0xC0FE5DE1, 0xCDF753EA, 0xEEC879DB, 0xE3C177D0, 0xF4DA65CD, 0xF9D36BC6,
0xB2A431AF, 0xBFAD3FA4, 0xA8B62DB9, 0xA5BF23B2, 0x86800983, 0x8B890788, 0x9C921595, 0x919B1B9E,
0x0A7CA147, 0x0775AF4C, 0x106EBD51, 0x1D67B35A, 0x3E58996B, 0x33519760, 0x244A857D, 0x29438B76,
0x6234D11F, 0x6F3DDF14, 0x7826CD09, 0x752FC302, 0x5610E933, 0x5B19E738, 0x4C02F525, 0x410BFB2E,
0x61D79A8C, 0x6CDE9487, 0x7BC5869A, 0x76CC8891, 0x55F3A2A0, 0x58FAACAB, 0x4FE1BEB6, 0x42E8B0BD,
0x099FEAD4, 0x0496E4DF, 0x138DF6C2, 0x1E84F8C9, 0x3DBBD2F8, 0x30B2DCF3, 0x27A9CEEE, 0x2AA0C0E5,
0xB1477A3C, 0xBC4E7437, 0xAB55662A, 0xA65C6821, 0x85634210, 0x886A4C1B, 0x9F715E06, 0x9278500D,
0xD90F0A64, 0xD406046F, 0xC31D1672, 0xCE141879, 0xED2B3248, 0xE0223C43, 0xF7392E5E, 0xFA302055,
0xB79AEC01, 0xBA93E20A, 0xAD88F017, 0xA081FE1C, 0x83BED42D, 0x8EB7DA26, 0x99ACC83B, 0x94A5C630,
0xDFD29C59, 0xD2DB9252, 0xC5C0804F, 0xC8C98E44, 0xEBF6A475, 0xE6FFAA7E, 0xF1E4B863, 0xFCEDB668,
0x670A0CB1, 0x6A0302BA, 0x7D1810A7, 0x70111EAC, 0x532E349D, 0x5E273A96, 0x493C288B, 0x44352680,
0x0F427CE9, 0x024B72E2, 0x155060FF, 0x18596EF4, 0x3B6644C5, 0x366F4ACE, 0x217458D3, 0x2C7D56D8,
0x0CA1377A, 0x01A83971, 0x16B32B6C, 0x1BBA2567, 0x38850F56, 0x358C015D, 0x22971340, 0x2F9E1D4B,
0x64E94722, 0x69E04929, 0x7EFB5B34, 0x73F2553F, 0x50CD7F0E, 0x5DC47105, 0x4ADF6318, 0x47D66D13,
0xDC31D7CA, 0xD138D9C1, 0xC623CBDC, 0xCB2AC5D7, 0xE815EFE6, 0xE51CE1ED, 0xF207F3F0, 0xFF0EFDFB,
0xB479A792, 0xB970A999, 0xAE6BBB84, 0xA362B58F, 0x805D9FBE, 0x8D5491B5, 0x9A4F83A8, 0x97468DA3
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(index, 0x0D).
- bits 8..15 represent Multiply(index, 0x0B).
- bits 16..23 represent Multiply(index, 0x0E).
- bits 24..31 represent Multiply(index, 0x09).
*/
__declspec(align(16)) static const UINT32 invMixColumn_c[256] =
{
0x00000000, 0x090E0B0D, 0x121C161A, 0x1B121D17, 0x24382C34, 0x2D362739, 0x36243A2E, 0x3F2A3123,
0x48705868, 0x417E5365, 0x5A6C4E72, 0x5362457F, 0x6C48745C, 0x65467F51, 0x7E546246, 0x775A694B,
0x90E0B0D0, 0x99EEBBDD, 0x82FCA6CA, 0x8BF2ADC7, 0xB4D89CE4, 0xBDD697E9, 0xA6C48AFE, 0xAFCA81F3,
0xD890E8B8, 0xD19EE3B5, 0xCA8CFEA2, 0xC382F5AF, 0xFCA8C48C, 0xF5A6CF81, 0xEEB4D296, 0xE7BAD99B,
0x3BDB7BBB, 0x32D570B6, 0x29C76DA1, 0x20C966AC, 0x1FE3578F, 0x16ED5C82, 0x0DFF4195, 0x04F14A98,
0x73AB23D3, 0x7AA528DE, 0x61B735C9, 0x68B93EC4, 0x57930FE7, 0x5E9D04EA, 0x458F19FD, 0x4C8112F0,
0xAB3BCB6B, 0xA235C066, 0xB927DD71, 0xB029D67C, 0x8F03E75F, 0x860DEC52, 0x9D1FF145, 0x9411FA48,
0xE34B9303, 0xEA45980E, 0xF1578519, 0xF8598E14, 0xC773BF37, 0xCE7DB43A, 0xD56FA92D, 0xDC61A220,
0x76ADF66D, 0x7FA3FD60, 0x64B1E077, 0x6DBFEB7A, 0x5295DA59, 0x5B9BD154, 0x4089CC43, 0x4987C74E,
0x3EDDAE05, 0x37D3A508, 0x2CC1B81F, 0x25CFB312, 0x1AE58231, 0x13EB893C, 0x08F9942B, 0x01F79F26,
0xE64D46BD, 0xEF434DB0, 0xF45150A7, 0xFD5F5BAA, 0xC2756A89, 0xCB7B6184, 0xD0697C93, 0xD967779E,
0xAE3D1ED5, 0xA73315D8, 0xBC2108CF, 0xB52F03C2, 0x8A0532E1, 0x830B39EC, 0x981924FB, 0x91172FF6,
0x4D768DD6, 0x447886DB, 0x5F6A9BCC, 0x566490C1, 0x694EA1E2, 0x6040AAEF, 0x7B52B7F8, 0x725CBCF5,
0x0506D5BE, 0x0C08DEB3, 0x171AC3A4, 0x1E14C8A9, 0x213EF98A, 0x2830F287, 0x3322EF90, 0x3A2CE49D,
0xDD963D06, 0xD498360B, 0xCF8A2B1C, 0xC6842011, 0xF9AE1132, 0xF0A01A3F, 0xEBB20728, 0xE2BC0C25,
0x95E6656E, 0x9CE86E63, 0x87FA7374, 0x8EF47879, 0xB1DE495A, 0xB8D04257, 0xA3C25F40, 0xAACC544D,
0xEC41F7DA, 0xE54FFCD7, 0xFE5DE1C0, 0xF753EACD, 0xC879DBEE, 0xC177D0E3, 0xDA65CDF4, 0xD36BC6F9,
0xA431AFB2, 0xAD3FA4BF, 0xB62DB9A8, 0xBF23B2A5, 0x80098386, 0x8907888B, 0x9215959C, 0x9B1B9E91,
0x7CA1470A, 0x75AF4C07, 0x6EBD5110, 0x67B35A1D, 0x58996B3E, 0x51976033, 0x4A857D24, 0x438B7629,
0x34D11F62, 0x3DDF146F, 0x26CD0978, 0x2FC30275, 0x10E93356, 0x19E7385B, 0x02F5254C, 0x0BFB2E41,
0xD79A8C61, 0xDE94876C, 0xC5869A7B, 0xCC889176, 0xF3A2A055, 0xFAACAB58, 0xE1BEB64F, 0xE8B0BD42,
0x9FEAD409, 0x96E4DF04, 0x8DF6C213, 0x84F8C91E, 0xBBD2F83D, 0xB2DCF330, 0xA9CEEE27, 0xA0C0E52A,
0x477A3CB1, 0x4E7437BC, 0x55662AAB, 0x5C6821A6, 0x63421085, 0x6A4C1B88, 0x715E069F, 0x78500D92,
0x0F0A64D9, 0x06046FD4, 0x1D1672C3, 0x141879CE, 0x2B3248ED, 0x223C43E0, 0x392E5EF7, 0x302055FA,
0x9AEC01B7, 0x93E20ABA, 0x88F017AD, 0x81FE1CA0, 0xBED42D83, 0xB7DA268E, 0xACC83B99, 0xA5C63094,
0xD29C59DF, 0xDB9252D2, 0xC0804FC5, 0xC98E44C8, 0xF6A475EB, 0xFFAA7EE6, 0xE4B863F1, 0xEDB668FC,
0x0A0CB167, 0x0302BA6A, 0x1810A77D, 0x111EAC70, 0x2E349D53, 0x273A965E, 0x3C288B49, 0x35268044,
0x427CE90F, 0x4B72E202, 0x5060FF15, 0x596EF418, 0x6644C53B, 0x6F4ACE36, 0x7458D321, 0x7D56D82C,
0xA1377A0C, 0xA8397101, 0xB32B6C16, 0xBA25671B, 0x850F5638, 0x8C015D35, 0x97134022, 0x9E1D4B2F,
0xE9472264, 0xE0492969, 0xFB5B347E, 0xF2553F73, 0xCD7F0E50, 0xC471055D, 0xDF63184A, 0xD66D1347,
0x31D7CADC, 0x38D9C1D1, 0x23CBDCC6, 0x2AC5D7CB, 0x15EFE6E8, 0x1CE1EDE5, 0x07F3F0F2, 0x0EFDFBFF,
0x79A792B4, 0x70A999B9, 0x6BBB84AE, 0x62B58FA3, 0x5D9FBE80, 0x5491B58D, 0x4F83A89A, 0x468DA397
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
For every value found at index we have:
- bits 0..7 represent Multiply(index, 0x09).
- bits 8..15 represent Multiply(index, 0x0D).
- bits 16..23 represent Multiply(index, 0x0B).
- bits 24..31 represent Multiply(index, 0x0E).
*/
__declspec(align(16)) static const UINT32 invMixColumn_d[256] =
{
0x00000000, 0x0E0B0D09, 0x1C161A12, 0x121D171B, 0x382C3424, 0x3627392D, 0x243A2E36, 0x2A31233F,
0x70586848, 0x7E536541, 0x6C4E725A, 0x62457F53, 0x48745C6C, 0x467F5165, 0x5462467E, 0x5A694B77,
0xE0B0D090, 0xEEBBDD99, 0xFCA6CA82, 0xF2ADC78B, 0xD89CE4B4, 0xD697E9BD, 0xC48AFEA6, 0xCA81F3AF,
0x90E8B8D8, 0x9EE3B5D1, 0x8CFEA2CA, 0x82F5AFC3, 0xA8C48CFC, 0xA6CF81F5, 0xB4D296EE, 0xBAD99BE7,
0xDB7BBB3B, 0xD570B632, 0xC76DA129, 0xC966AC20, 0xE3578F1F, 0xED5C8216, 0xFF41950D, 0xF14A9804,
0xAB23D373, 0xA528DE7A, 0xB735C961, 0xB93EC468, 0x930FE757, 0x9D04EA5E, 0x8F19FD45, 0x8112F04C,
0x3BCB6BAB, 0x35C066A2, 0x27DD71B9, 0x29D67CB0, 0x03E75F8F, 0x0DEC5286, 0x1FF1459D, 0x11FA4894,
0x4B9303E3, 0x45980EEA, 0x578519F1, 0x598E14F8, 0x73BF37C7, 0x7DB43ACE, 0x6FA92DD5, 0x61A220DC,
0xADF66D76, 0xA3FD607F, 0xB1E07764, 0xBFEB7A6D, 0x95DA5952, 0x9BD1545B, 0x89CC4340, 0x87C74E49,
0xDDAE053E, 0xD3A50837, 0xC1B81F2C, 0xCFB31225, 0xE582311A, 0xEB893C13, 0xF9942B08, 0xF79F2601,
0x4D46BDE6, 0x434DB0EF, 0x5150A7F4, 0x5F5BAAFD, 0x756A89C2, 0x7B6184CB, 0x697C93D0, 0x67779ED9,
0x3D1ED5AE, 0x3315D8A7, 0x2108CFBC, 0x2F03C2B5, 0x0532E18A, 0x0B39EC83, 0x1924FB98, 0x172FF691,
0x768DD64D, 0x7886DB44, 0x6A9BCC5F, 0x6490C156, 0x4EA1E269, 0x40AAEF60, 0x52B7F87B, 0x5CBCF572,
0x06D5BE05, 0x08DEB30C, 0x1AC3A417, 0x14C8A91E, 0x3EF98A21, 0x30F28728, 0x22EF9033, 0x2CE49D3A,
0x963D06DD, 0x98360BD4, 0x8A2B1CCF, 0x842011C6, 0xAE1132F9, 0xA01A3FF0, 0xB20728EB, 0xBC0C25E2,
0xE6656E95, 0xE86E639C, 0xFA737487, 0xF478798E, 0xDE495AB1, 0xD04257B8, 0xC25F40A3, 0xCC544DAA,
0x41F7DAEC, 0x4FFCD7E5, 0x5DE1C0FE, 0x53EACDF7, 0x79DBEEC8, 0x77D0E3C1, 0x65CDF4DA, 0x6BC6F9D3,
0x31AFB2A4, 0x3FA4BFAD, 0x2DB9A8B6, 0x23B2A5BF, 0x09838680, 0x07888B89, 0x15959C92, 0x1B9E919B,
0xA1470A7C, 0xAF4C0775, 0xBD51106E, 0xB35A1D67, 0x996B3E58, 0x97603351, 0x857D244A, 0x8B762943,
0xD11F6234, 0xDF146F3D, 0xCD097826, 0xC302752F, 0xE9335610, 0xE7385B19, 0xF5254C02, 0xFB2E410B,
0x9A8C61D7, 0x94876CDE, 0x869A7BC5, 0x889176CC, 0xA2A055F3, 0xACAB58FA, 0xBEB64FE1, 0xB0BD42E8,
0xEAD4099F, 0xE4DF0496, 0xF6C2138D, 0xF8C91E84, 0xD2F83DBB, 0xDCF330B2, 0xCEEE27A9, 0xC0E52AA0,
0x7A3CB147, 0x7437BC4E, 0x662AAB55, 0x6821A65C, 0x42108563, 0x4C1B886A, 0x5E069F71, 0x500D9278,
0x0A64D90F, 0x046FD406, 0x1672C31D, 0x1879CE14, 0x3248ED2B, 0x3C43E022, 0x2E5EF739, 0x2055FA30,
0xEC01B79A, 0xE20ABA93, 0xF017AD88, 0xFE1CA081, 0xD42D83BE, 0xDA268EB7, 0xC83B99AC, 0xC63094A5,
0x9C59DFD2, 0x9252D2DB, 0x804FC5C0, 0x8E44C8C9, 0xA475EBF6, 0xAA7EE6FF, 0xB863F1E4, 0xB668FCED,
0x0CB1670A, 0x02BA6A03, 0x10A77D18, 0x1EAC7011, 0x349D532E, 0x3A965E27, 0x288B493C, 0x26804435,
0x7CE90F42, 0x72E2024B, 0x60FF1550, 0x6EF41859, 0x44C53B66, 0x4ACE366F, 0x58D32174, 0x56D82C7D,
0x377A0CA1, 0x397101A8, 0x2B6C16B3, 0x25671BBA, 0x0F563885, 0x015D358C, 0x13402297, 0x1D4B2F9E,
0x472264E9, 0x492969E0, 0x5B347EFB, 0x553F73F2, 0x7F0E50CD, 0x71055DC4, 0x63184ADF, 0x6D1347D6,
0xD7CADC31, 0xD9C1D138, 0xCBDCC623, 0xC5D7CB2A, 0xEFE6E815, 0xE1EDE51C, 0xF3F0F207, 0xFDFBFF0E,
0xA792B479, 0xA999B970, 0xBB84AE6B, 0xB58FA362, 0x9FBE805D, 0x91B58D54, 0x83A89A4F, 0x8DA39746
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The S box used to encrypt
__declspec(align(16)) const UINT32 sBox[256] =
{
//0 1 2 3 4 5 6 7 8 9 A B C D E F
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, //0
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, //1
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, //2
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, //3
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, //4
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, //5
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, //6
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, //7
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, //8
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, //9
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, //A
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, //B
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, //C
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, //D
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, //E
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 //F
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The reversed S box used to decrypt
__declspec(align(16)) const UINT32 rsBox[256] =
{
//0 1 2 3 4 5 6 7 8 9 A B C D E F
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, //0
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, //1
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, //2
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, //3
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, //4
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, //5
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, //6
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, //7
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, //8
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, //9
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, //A
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, //B
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, //C
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, //D
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, //E
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d //F
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class AES_GPU_DX10_Description : public IAlgorithmDescription
{
public:
AES_GPU_DX10_Description()
{
m_IsOK = false;
// This may fail if Direct3D 10 isn't installed ( running on Windows XP or older )
TCHAR szPath[MAX_PATH + 1] = {0};
if( ::GetSystemDirectory( szPath, MAX_PATH + 1 ) )
{
_tcscat_s( szPath, MAX_PATH, _T("\\d3d10.dll") );
HMODULE hMod = LoadLibrary( szPath );
if(hMod != NULL)
{
m_IsOK = true;
FreeLibrary( hMod );
}
}
}
bool IsOK() { return m_IsOK; };
const TCHAR* ClassName() { return _T("AES_GPU_DX10"); };
const TCHAR* ClassDescription() { return _T("Implements the AES encryption/decryption algorithm using the GPU resources and DirectX 10 interface."); };
CLASS_ID ClassID() { return AES_GPU_DX10_ALGORITHM_CLASS_ID; }
CLASS_ID InterfaceID() { return AES_ALGORITHM_CLASS_ID; }
IAlgorithm* Create()
{
if( m_IsOK )
return AES_GPU_DX10_Internal::Create();
else
return NULL;
}
private:
bool m_IsOK;
};
static AES_GPU_DX10_Description class_description;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AES_GPU_DX10_API IAlgorithmDescription*
GetDescription(UINT32 acmVersion)
{
if( class_description.IsOK() && acmVersion == AMCLIB_VERSION )
return &class_description;
else
return NULL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AES_GPU_DX10_Internal*
AES_GPU_DX10_Internal::Create()
{
HRESULT hr = S_OK;
TCHAR *deviceName = NULL;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create the Direct3D 10 Device
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HMODULE hModD3D10 = LoadLibrary( _T("d3d10.dll") );
if( hModD3D10 == NULL )
return NULL;
LPD3D10CREATEDEVICE DynamicD3D10CreateDevice = ( LPD3D10CREATEDEVICE )GetProcAddress( hModD3D10, "D3D10CreateDevice" );
if( DynamicD3D10CreateDevice == NULL )
return NULL;
static const D3D10_DRIVER_TYPE driverType[] =
{
D3D10_DRIVER_TYPE_HARDWARE, // The current hardware implementation found on this machine
D3D10_DRIVER_TYPE_WARP, // Very fast software implementation
D3D10_DRIVER_TYPE_REFERENCE // Slow but very accurate software implementation
};
DWORD dwCreateFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
dwCreateFlags |= D3D10_CREATE_DEVICE_DEBUG; // For debugging purpose
#endif
// Try to create one D3D 10 device in the order from driverType
ID3D10Device *pDevice = NULL;
for( int deviceIndex = 0; deviceIndex < countof(driverType); deviceIndex++ )
{
hr = DynamicD3D10CreateDevice( NULL, driverType[deviceIndex], ( HMODULE )0, dwCreateFlags, D3D10_SDK_VERSION, &pDevice );
if( SUCCEEDED( hr ) )
{
if( driverType[deviceIndex] == D3D10_DRIVER_TYPE_WARP )
{
static const TCHAR warpName[] = _T("WARP10 - Software");
deviceName = (TCHAR *)new UINT8[sizeof(warpName)];
memcpy(deviceName, warpName, sizeof(warpName));
}
else if( driverType[deviceIndex] == D3D10_DRIVER_TYPE_REFERENCE )
{
static const TCHAR refName[] = _T("Reference - Software");
deviceName = (TCHAR *)new UINT8[sizeof(refName)];
memcpy(deviceName, refName, sizeof(refName));
}
else
{
// Get the name of the video card
HMODULE s_hModDXGI = NULL;
LPCREATEDXGIFACTORY s_DynamicCreateDXGIFactory = NULL;
IDXGIFactory* pDXGIFactory = NULL;
s_hModDXGI = LoadLibrary( _T("dxgi.dll") );
if( s_hModDXGI )
{
s_DynamicCreateDXGIFactory = ( LPCREATEDXGIFACTORY )GetProcAddress( s_hModDXGI, "CreateDXGIFactory" );
if( s_DynamicCreateDXGIFactory != NULL )
{
s_DynamicCreateDXGIFactory( __uuidof( IDXGIFactory ), ( LPVOID* )&pDXGIFactory );
if( pDXGIFactory != NULL )
{
for( int index = 0; ; ++index )
{
IDXGIAdapter* pAdapter = NULL;
hr = pDXGIFactory->EnumAdapters( index, &pAdapter );
if( FAILED( hr ) ) // DXGIERR_NOT_FOUND is expected when the end of the list is hit
break;
DXGI_ADAPTER_DESC AdapterDesc;
pAdapter->GetDesc( &AdapterDesc );
int nameLen = (int)wcslen(AdapterDesc.Description) + 1;
deviceName = new TCHAR[nameLen];
_tcscpy_s(deviceName, nameLen, AdapterDesc.Description);
SAFE_RELEASE( pAdapter );
break;
}
SAFE_RELEASE( pDXGIFactory );
}
}
FreeLibrary(s_hModDXGI);
}
if( deviceName == NULL )
{
static const TCHAR hardName[] = _T("Unknown Hardware");
deviceName = (TCHAR *)new UINT8[sizeof(hardName)];
memcpy(deviceName, hardName, sizeof(hardName));
}
}
break;
}
}
if( FAILED(hr) )
{
FreeLibrary(hModD3D10);
return NULL; // No device could be created
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create the AES_GPU_DX10_Internal object that will be returned by this function.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AES_GPU_DX10_Internal *retVal = new AES_GPU_DX10_Internal();
retVal->m_pDevice = pDevice;
retVal->mDeviceName = deviceName;
retVal->m_hModD3D10 = hModD3D10;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create the Effect object for the shader found in the resources and compile it
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ID3D10Blob *errors = NULL;
DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_OPTIMIZATION_LEVEL3;
#if defined( DEBUG ) || defined( _DEBUG )
dwShaderFlags |= D3D10_SHADER_DEBUG;
hr = D3D10CreateBlob(1024, &errors);
#endif
hr = D3DX10CreateEffectFromResource( gHModule, _T("AES_GPU_DX10_SHADER"), _T("AES_GPU_DX10_SHADER.fx"),
NULL, NULL, "fx_4_0", dwShaderFlags, 0, pDevice, NULL, NULL, &retVal->m_pEffect10, &errors, NULL );
if( FAILED( hr ) )
{
#if defined( DEBUG ) || defined( _DEBUG )
printf("%s", (char*)errors->GetBufferPointer());
__debugbreak();
#endif
goto _EXIT_AND_RETURN_NULL_;
}
else
{
#if defined( DEBUG ) || defined( _DEBUG )
ID3D10Blob *asmShader = NULL;
hr = D3D10CreateBlob(65536, &asmShader);
hr = D3DDisassemble10Effect( retVal->m_pEffect10, 0, &asmShader);
FILE *fout;
fopen_s(&fout, "shader_asm.txt", "wt");
if(fout != NULL)
{
fprintf(fout,"%s", (char*)asmShader->GetBufferPointer());
fclose(fout);
}
SAFE_RELEASE(asmShader);
#endif
}
SAFE_RELEASE(errors);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set the constant values in the shader ( these constants are valid on the entire life of retVal object )
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ID3D10EffectScalarVariable *cBuffer = NULL;
cBuffer = retVal->m_pEffect10->GetVariableByName( "sBoxMixColumn_a" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)sBoxMixColumn_a, 0, countof(sBoxMixColumn_a));
cBuffer = retVal->m_pEffect10->GetVariableByName( "sBoxMixColumn_b" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)sBoxMixColumn_b, 0, countof(sBoxMixColumn_b));
cBuffer = retVal->m_pEffect10->GetVariableByName( "sBoxMixColumn_c" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)sBoxMixColumn_c, 0, countof(sBoxMixColumn_c));
cBuffer = retVal->m_pEffect10->GetVariableByName( "sBoxMixColumn_d" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)sBoxMixColumn_d, 0, countof(sBoxMixColumn_d));
cBuffer = retVal->m_pEffect10->GetVariableByName( "rsBoxInvMixColumn_a" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)rsBoxInvMixColumn_a, 0, countof(rsBoxInvMixColumn_a));
cBuffer = retVal->m_pEffect10->GetVariableByName( "rsBoxInvMixColumn_b" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)rsBoxInvMixColumn_b, 0, countof(rsBoxInvMixColumn_b));
cBuffer = retVal->m_pEffect10->GetVariableByName( "rsBoxInvMixColumn_c" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)rsBoxInvMixColumn_c, 0, countof(rsBoxInvMixColumn_c));
cBuffer = retVal->m_pEffect10->GetVariableByName( "rsBoxInvMixColumn_d" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)rsBoxInvMixColumn_d, 0, countof(rsBoxInvMixColumn_d));
cBuffer = retVal->m_pEffect10->GetVariableByName( "sBox" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)sBox, 0, countof(sBox));
cBuffer = retVal->m_pEffect10->GetVariableByName( "rsBox" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)rsBox, 0, countof(rsBox));
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set the texture constant values in the shader ( these constants are valid on the entire life of retVal object )
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cBuffer = retVal->m_pEffect10->GetVariableByName( "tsBoxMixColumn_a" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)sBoxMixColumn_a, 0, countof(sBoxMixColumn_a));
cBuffer = retVal->m_pEffect10->GetVariableByName( "tsBoxMixColumn_b" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)sBoxMixColumn_b, 0, countof(sBoxMixColumn_b));
cBuffer = retVal->m_pEffect10->GetVariableByName( "tsBoxMixColumn_c" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)sBoxMixColumn_c, 0, countof(sBoxMixColumn_c));
cBuffer = retVal->m_pEffect10->GetVariableByName( "tsBoxMixColumn_d" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)sBoxMixColumn_d, 0, countof(sBoxMixColumn_d));
cBuffer = retVal->m_pEffect10->GetVariableByName( "trsBoxInvMixColumn_a" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)rsBoxInvMixColumn_a, 0, countof(rsBoxInvMixColumn_a));
cBuffer = retVal->m_pEffect10->GetVariableByName( "trsBoxInvMixColumn_b" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)rsBoxInvMixColumn_b, 0, countof(rsBoxInvMixColumn_b));
cBuffer = retVal->m_pEffect10->GetVariableByName( "trsBoxInvMixColumn_c" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)rsBoxInvMixColumn_c, 0, countof(rsBoxInvMixColumn_c));
cBuffer = retVal->m_pEffect10->GetVariableByName( "trsBoxInvMixColumn_d" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)rsBoxInvMixColumn_d, 0, countof(rsBoxInvMixColumn_d));
cBuffer = retVal->m_pEffect10->GetVariableByName( "tsBox" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)sBox, 0, countof(sBox));
cBuffer = retVal->m_pEffect10->GetVariableByName( "trsBox" )->AsScalar();
if( cBuffer->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
cBuffer->SetIntArray((int*)rsBox, 0, countof(rsBox));
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Get the pointers to the constants that need updated very often
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
retVal->m_pShaderIV = retVal->m_pEffect10->GetVariableByName( "IV" )->AsVector();
if( retVal->m_pShaderIV->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
retVal->m_pShaderKeyEnc = retVal->m_pEffect10->GetVariableByName( "key" )->AsVector();
if( retVal->m_pShaderKeyEnc->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
retVal->m_pShaderKeyDec = retVal->m_pEffect10->GetVariableByName( "rkey" )->AsVector();
if( retVal->m_pShaderKeyDec->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
retVal->m_pShaderKeySize = retVal->m_pEffect10->GetVariableByName( "keySize" )->AsScalar();
if( retVal->m_pShaderKeySize->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Get the pointers to the techniques defined by the shader
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
retVal->m_pEncryptECB = retVal->m_pEffect10->GetTechniqueByName( "AES_Encrypt_ECB_tx_cb" );
if( retVal->m_pEncryptECB->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
retVal->m_pDecryptECB = retVal->m_pEffect10->GetTechniqueByName( "AES_Decrypt_ECB_tx_cb" );
if( retVal->m_pDecryptECB->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
retVal->m_pEncDecCTR = retVal->m_pEffect10->GetTechniqueByName( "AES_EncryptDecrypt_CTR_tx_cb" );
if( retVal->m_pEncDecCTR->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
retVal->m_pDecryptCBC = retVal->m_pEffect10->GetTechniqueByName( "AES_Decrypt_CBC_tx_cb" );
if( retVal->m_pDecryptCBC->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
// All the techniques have the same vertex format at the input, and all have only one pass
retVal->m_pEncrypt = retVal->m_pEncryptECB;
retVal->m_pDecrypt = retVal->m_pDecryptECB;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create the Vertex Buffer and Input Layout for the quad that will be rendered on the screen
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct _QUAD_VERTEX
{
D3DXVECTOR3 position;
D3DXVECTOR2 texCoord;
}QUAD_VERTEX;
{
static const D3D10_INPUT_ELEMENT_DESC quadLayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
};
static const QUAD_VERTEX quadVertexBuffer[] =
{
{ D3DXVECTOR3( -1, 1, 0 ), D3DXVECTOR2( 0, 0 ) },
{ D3DXVECTOR3( 1, 1, 0 ), D3DXVECTOR2( 1, 0 ) },
{ D3DXVECTOR3( -1, -1, 0 ), D3DXVECTOR2( 0, 1 ) },
{ D3DXVECTOR3( 1, 1, 0 ), D3DXVECTOR2( 1, 0 ) },
{ D3DXVECTOR3( 1, -1, 0 ), D3DXVECTOR2( 1, 1 ) },
{ D3DXVECTOR3( -1, -1, 0 ), D3DXVECTOR2( 0, 1 ) }
};
static const D3D10_BUFFER_DESC vbdesc =
{
countof(quadVertexBuffer) * sizeof( QUAD_VERTEX ),
D3D10_USAGE_IMMUTABLE,
D3D10_BIND_VERTEX_BUFFER,
0, 0
};
static const D3D10_SUBRESOURCE_DATA InitData =
{
quadVertexBuffer,
0, 0
};
// Create the vertex buffer
hr = pDevice->CreateBuffer( &vbdesc, &InitData, &retVal->m_pQuadVB );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
// Create the quad vertex input layout
D3D10_PASS_DESC PassDesc;
retVal->m_pEncrypt->GetPassByIndex( 0 )->GetDesc( &PassDesc );
hr = pDevice->CreateInputLayout( quadLayout, countof(quadLayout),
PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize,
&retVal->m_pQuadVertexLayout );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create the source and destination texture and its associated ShaderResourceView
// respectively RenderTargetView. Also create the staging texture to copy results from GPU.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
D3D10_TEXTURE2D_DESC dsTex;
ZeroMemory( &dsTex, sizeof( dsTex ) );
dsTex.Width = TEXTURE_SIZEX;
dsTex.Height = TEXTURE_SIZEY;
dsTex.MipLevels = 1;
dsTex.Format = DXGI_FORMAT_R32G32B32A32_UINT;
dsTex.SampleDesc.Count = 1;
dsTex.SampleDesc.Quality= 0;
dsTex.Usage = D3D10_USAGE_DEFAULT;
dsTex.BindFlags = D3D10_BIND_SHADER_RESOURCE;
dsTex.CPUAccessFlags = 0;
dsTex.MiscFlags = 0;
dsTex.ArraySize = 1;
hr = pDevice->CreateTexture2D( &dsTex, NULL, &retVal->m_pSourceTexture );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
dsTex.BindFlags = D3D10_BIND_RENDER_TARGET;
hr = pDevice->CreateTexture2D( &dsTex, NULL, &retVal->m_pDestTexture );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
// Create the staging texture used to write to GPU
dsTex.Usage = D3D10_USAGE_STAGING;
dsTex.BindFlags = 0;
dsTex.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
hr = pDevice->CreateTexture2D( &dsTex, NULL, &retVal->m_pStagingSrcTexture );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
// Create the staging texture used to read from GPU
dsTex.CPUAccessFlags = D3D10_CPU_ACCESS_READ;
hr = pDevice->CreateTexture2D( &dsTex, NULL, &retVal->m_pStagingDstTexture );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
// Create Source Resource View
D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc;
ZeroMemory( &SRVDesc, sizeof( SRVDesc ) );
SRVDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT;
SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
SRVDesc.Texture2D.MipLevels = 1;
hr = pDevice->CreateShaderResourceView( retVal->m_pSourceTexture, &SRVDesc, &retVal->m_pSourceTexRV );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
// Create Destination RenderTarget View
D3D10_RENDER_TARGET_VIEW_DESC DescRT;
DescRT.Format = DXGI_FORMAT_R32G32B32A32_UINT;
DescRT.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
DescRT.Texture2D.MipSlice = 0;
hr = pDevice->CreateRenderTargetView( retVal->m_pDestTexture, &DescRT, &retVal->m_pDestRTV );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create the texture and its resource view, used to hold the constant tables, and set it's contents
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ZeroMemory( &dsTex, sizeof( dsTex ) );
dsTex.Width = countof(sBox);
dsTex.Height = 10; // The number of arrays to be set
dsTex.MipLevels = 1;
dsTex.Format = DXGI_FORMAT_R32_UINT;
dsTex.SampleDesc.Count = 1;
dsTex.SampleDesc.Quality= 0;
dsTex.Usage = D3D10_USAGE_DEFAULT;
dsTex.BindFlags = D3D10_BIND_SHADER_RESOURCE;
dsTex.CPUAccessFlags = 0;
dsTex.MiscFlags = 0;
dsTex.ArraySize = 1;
hr = pDevice->CreateTexture2D( &dsTex, NULL, &retVal->m_pTexConstants );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
// Create the staging texture used to write to GPU
{
ID3D10Texture2D *pStagingTex;
dsTex.Usage = D3D10_USAGE_STAGING;
dsTex.BindFlags = 0;
dsTex.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
hr = pDevice->CreateTexture2D( &dsTex, NULL, &pStagingTex );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
// Map the CPU staging resource
D3D10_MAPPED_TEXTURE2D map;
hr = pStagingTex->Map( 0, D3D10_MAP_WRITE, NULL, &map );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
UINT32 *dst = (UINT32*)map.pData;
memcpy(dst, sBoxMixColumn_a, map.RowPitch); dst += 256;
memcpy(dst, sBoxMixColumn_b, map.RowPitch); dst += 256;
memcpy(dst, sBoxMixColumn_c, map.RowPitch); dst += 256;
memcpy(dst, sBoxMixColumn_d, map.RowPitch); dst += 256;
memcpy(dst, rsBoxInvMixColumn_a, map.RowPitch); dst += 256;
memcpy(dst, rsBoxInvMixColumn_b, map.RowPitch); dst += 256;
memcpy(dst, rsBoxInvMixColumn_c, map.RowPitch); dst += 256;
memcpy(dst, rsBoxInvMixColumn_d, map.RowPitch); dst += 256;
memcpy(dst, sBox, map.RowPitch); dst += 256;
memcpy(dst, rsBox, map.RowPitch);
pStagingTex->Unmap( 0 );
pDevice->CopyResource( retVal->m_pTexConstants, pStagingTex );
SAFE_RELEASE(pStagingTex);
}
// Create Source Resource View
ZeroMemory( &SRVDesc, sizeof( SRVDesc ) );
SRVDesc.Format = DXGI_FORMAT_R32_UINT;
SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
SRVDesc.Texture2D.MipLevels = 1;
hr = pDevice->CreateShaderResourceView( retVal->m_pTexConstants, &SRVDesc, &retVal->m_pTexConstantsRV );
if( FAILED( hr ) )
goto _EXIT_AND_RETURN_NULL_;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set the view port that will always be used. The view port must match the rendered texture size.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
D3D10_VIEWPORT PVP;
PVP.Width = TEXTURE_SIZEX;
PVP.Height = TEXTURE_SIZEY;
PVP.MinDepth = 0;
PVP.MaxDepth = 1;
PVP.TopLeftX = 0;
PVP.TopLeftY = 0;
pDevice->RSSetViewports( 1, &PVP );
// Set the scissor to render the entire view port
D3D10_RECT rects[1];
rects[0].left = 0;
rects[0].right = TEXTURE_SIZEX;
rects[0].top = 0;
rects[0].bottom = TEXTURE_SIZEY;
pDevice->RSSetScissorRects( 1, rects );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set the input layout for the vertex shader, and also set the vertex buffer of the quad as the default one.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
UINT offsets = 0;
UINT uStrides = sizeof( QUAD_VERTEX );
pDevice->IASetInputLayout( retVal->m_pQuadVertexLayout );
pDevice->IASetVertexBuffers( 0, 1, &retVal->m_pQuadVB, &uStrides, &offsets );
pDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Bind the destination render target view to the output of the pipeline
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pDevice->OMSetRenderTargets( 1, &retVal->m_pDestRTV, NULL );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Bind the source resource view to txSource and txConstants in the shader
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ID3D10EffectShaderResourceVariable *ptxSource;
ptxSource = retVal->m_pEffect10->GetVariableByName( "txSource" )->AsShaderResource();
if( ptxSource->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
ptxSource->SetResource( retVal->m_pSourceTexRV );
ID3D10EffectShaderResourceVariable *ptxConstants;
ptxConstants = retVal->m_pEffect10->GetVariableByName( "txConstants" )->AsShaderResource();
if( ptxConstants->IsValid() == FALSE )
goto _EXIT_AND_RETURN_NULL_;
ptxConstants->SetResource( retVal->m_pTexConstantsRV );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tell the shader code the size of the textures that we will use
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ID3D10EffectVectorVariable *ptxSourceSize;
ptxSourceSize = retVal->m_pEffect10->GetVariableByName( "txSize" )->AsVector();
if( ptxSourceSize->IsValid() != FALSE )
{
D3DXVECTOR4 vTextureSize( (float)TEXTURE_SIZEX, (float)TEXTURE_SIZEY, 0.0f, 0.0f );
ptxSourceSize->SetFloatVector( (float*)vTextureSize );
}
else
goto _EXIT_AND_RETURN_NULL_;
return retVal;
_EXIT_AND_RETURN_NULL_:
delete retVal;
return NULL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AES_GPU_DX10_Internal::AES_GPU_DX10_Internal()
{
m_SupportedModes = IAlgorithmAES::AES_ECB |
IAlgorithmAES::AES_CBC |
IAlgorithmAES::AES_CTR;
m_Mode = IAlgorithmAES::AES_ECB;
m_keySize = AES_Key::AES_KeyInvalid;
memset(m_IV, 0, IAlgorithmAES::BlockSizeBytes);
memset(m_internalEncIV, 0, IAlgorithmAES::BlockSizeBytes);
memset(m_internalDecIV, 0, IAlgorithmAES::BlockSizeBytes);
mDeviceName = NULL;
// Comes the DX 10 part
m_pDevice = NULL;
m_pEffect10 = NULL;
m_pQuadVertexLayout = NULL;
m_pQuadVB = NULL;
m_pEncrypt = NULL;
m_pDecrypt = NULL;
m_pEncryptECB = NULL;
m_pDecryptECB = NULL;
m_pSourceTexture = NULL;
m_pDestTexture = NULL;
m_pStagingDstTexture = NULL;
m_pStagingSrcTexture = NULL;
m_pSourceTexRV = NULL;
m_pDestRTV = NULL;
m_pShaderIV = NULL;
m_pShaderKeyEnc = NULL;
m_pShaderKeyDec = NULL;
m_pShaderKeySize = NULL;
m_pTexConstants = NULL;
m_pTexConstantsRV = NULL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AES_GPU_DX10_Internal::~AES_GPU_DX10_Internal()
{
SAFE_RELEASE( m_pTexConstantsRV );
SAFE_RELEASE( m_pTexConstants );
SAFE_RELEASE( m_pDestRTV );
SAFE_RELEASE( m_pStagingDstTexture );
SAFE_RELEASE( m_pStagingSrcTexture );
SAFE_RELEASE( m_pDestTexture );
SAFE_RELEASE( m_pSourceTexture );
SAFE_RELEASE( m_pSourceTexRV );
SAFE_RELEASE( m_pQuadVB );
SAFE_RELEASE( m_pQuadVertexLayout );
SAFE_RELEASE( m_pEffect10 );
SAFE_RELEASE( m_pDevice );
FreeLibrary( m_hModD3D10 );
delete mDeviceName;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const TCHAR*
AES_GPU_DX10_Internal::GetDeviceName()
{
return mDeviceName;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IAlgorithmDescription&
AES_GPU_DX10_Internal::GetDescription()
{
return class_description;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
UINT32
AES_GPU_DX10_Internal::GetSupportedModes(bool Encryption)
{
if( Encryption )
return m_SupportedModes & (~IAlgorithmAES::AES_CBC); // CBC not supported for encryption
else
return m_SupportedModes;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IAlgorithmAES::AES_Status
AES_GPU_DX10_Internal::SetMode(AES_Modes mode, const UINT8 *IV)
{
if( (mode & m_SupportedModes) == 0 )
return IAlgorithmAES::AES_Status_NotSupported;
/// Check if only one mode was passed ( must be a power of 2 )
if( (mode & (mode - 1)) != 0 )
return IAlgorithmAES::AES_Status_InvalidArgs;
m_Mode = mode;
if( mode != IAlgorithmAES::AES_ECB )
{
/// All the modes beside ECB needs IV
if( IV == NULL )
{
memset(m_IV, 0, IAlgorithmAES::BlockSizeBytes);
memset(m_internalEncIV, 0, IAlgorithmAES::BlockSizeBytes);
memset(m_internalDecIV, 0, IAlgorithmAES::BlockSizeBytes);
}
else
{
memcpy(m_IV, IV, IAlgorithmAES::BlockSizeBytes);
memcpy(m_internalEncIV, IV, IAlgorithmAES::BlockSizeBytes);
memcpy(m_internalDecIV, IV, IAlgorithmAES::BlockSizeBytes);
}
}
switch(m_Mode)
{
case IAlgorithmAES::AES_ECB:
m_pEncrypt = m_pEncryptECB;
m_pDecrypt = m_pDecryptECB;
break;
case IAlgorithmAES::AES_CBC:
m_pEncrypt = NULL; // Not supported
m_pDecrypt = m_pDecryptCBC;
break;
case IAlgorithmAES::AES_CTR:
m_pEncrypt = m_pEncDecCTR;
m_pDecrypt = m_pEncDecCTR;
break;
}
return IAlgorithmAES::AES_Status_OK;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IAlgorithmAES::AES_Status
AES_GPU_DX10_Internal::SetKey(const AES_Key *key)
{
if( key == NULL || key->GetKeySize() == AES_Key::AES_KeyInvalid )
return IAlgorithmAES::AES_Status_InvalidArgs;
m_keySize = key->GetKeySize();
m_keyDataSize = key->GetKeySizeBytes();
memcpy(m_keyEnc, key->GetKeyData(), m_keyDataSize);
// Because we want to use the same form of algorithm for decryption as for encryption, we
// copy in m_keyDec the keys in reverse order of the rounds and also apply InvMixColumns
// on the middle round keys .
// For more information see Equivalent Inverse Cipher on AES standard.
UINT32 m_Nr = (m_keySize >> 5) + 6;
UINT32 *src = (UINT32*)&m_keyEnc[m_Nr * 16];
UINT32 *dst = (UINT32*)m_keyDec;
// First round
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src;
src -= 7;
// The rest of the rounds will have applied the InvMixColumns to avoid being done on DecryptBlock
for( UINT32 i = 1; i < m_Nr; i++ )
{
UINT32 value = *src++;
*dst++ = invMixColumn_a[value & 0xFF] ^
invMixColumn_b[(value >> 8) & 0xFF] ^
invMixColumn_c[(value >> 16) & 0xFF] ^
invMixColumn_d[value >> 24];
value = *src++;
*dst++ = invMixColumn_a[value & 0xFF] ^
invMixColumn_b[(value >> 8) & 0xFF] ^
invMixColumn_c[(value >> 16) & 0xFF] ^
invMixColumn_d[value >> 24];
value = *src++;
*dst++ = invMixColumn_a[value & 0xFF] ^
invMixColumn_b[(value >> 8) & 0xFF] ^
invMixColumn_c[(value >> 16) & 0xFF] ^
invMixColumn_d[value >> 24];
value = *src;
*dst++ = invMixColumn_a[value & 0xFF] ^
invMixColumn_b[(value >> 8) & 0xFF] ^
invMixColumn_c[(value >> 16) & 0xFF] ^
invMixColumn_d[value >> 24];
src -= 7;
}
// The last round
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst = *src;
SetShaderKey();
// Also restore the IV that we use
if( m_Mode != IAlgorithmAES::AES_ECB )
{
memcpy(m_internalEncIV, m_IV, IAlgorithmAES::BlockSizeBytes);
memcpy(m_internalDecIV, m_IV, IAlgorithmAES::BlockSizeBytes);
}
return IAlgorithmAES::AES_Status_OK;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IAlgorithmAES::AES_Status
AES_GPU_DX10_Internal::Encrypt(UINT8 *dst, const UINT8 *src, UINT32 size)
{
// Check for NULL pointers, and if the size of the data is multiple of block size
// ( padding of the data must be done by the caller )
if( dst == NULL || src == NULL || size % IAlgorithmAES::BlockSizeBytes != 0 )
return IAlgorithmAES::AES_Status_InvalidArgs;
if( m_keySize == AES_Key::AES_KeyInvalid )
return IAlgorithmAES::AES_Status_InvalidState;
// Check if the mode of encryption is supported
if( m_pEncrypt == NULL )
return IAlgorithmAES::AES_Status_NotSupported;
// The number of bytes that can be encrypted in one pass
UINT32 maxPassSize = TEXTURE_SIZEX * TEXTURE_SIZEY * IAlgorithmAES::BlockSizeBytes;
// The number of full passes needed to encrypt the entire input
UINT32 nbPasses= size / maxPassSize;
// The size in bytes of the last pass ( can be smaller than maxPassSize )
UINT32 lastPassSize = size - (nbPasses * maxPassSize);
// Run the full passes
while( nbPasses != 0 )
{
switch( m_Mode )
{
case IAlgorithmAES::AES_ECB:
{
CopyDataToGPU(src, TEXTURE_SIZEX, TEXTURE_SIZEY);
RunEncryption();
CopyDataFromGPU(dst, TEXTURE_SIZEX, TEXTURE_SIZEY);
}break;
case IAlgorithmAES::AES_CTR:
{
SetShaderIV(m_internalEncIV);
// Update the IV for the next run
if( ((UINT64*)m_internalEncIV)[0] + (TEXTURE_SIZEX * TEXTURE_SIZEY) < ((UINT64*)m_internalEncIV)[0] )
{
((UINT64*)m_internalEncIV)[0] += TEXTURE_SIZEX * TEXTURE_SIZEY;
((UINT64*)m_internalEncIV)[1]++;
}
else
((UINT64*)m_internalEncIV)[0] += TEXTURE_SIZEX * TEXTURE_SIZEY;
CopyDataToGPU(src, TEXTURE_SIZEX, TEXTURE_SIZEY);
RunEncryption();
CopyDataFromGPU(dst, TEXTURE_SIZEX, TEXTURE_SIZEY);
}break;
}
src += maxPassSize;
dst += maxPassSize;
nbPasses--;
}
if( lastPassSize != 0 )
{
// Must process the last bytes that did not fit on one full pass
// The number of bytes that are found on one full line of the texture
UINT32 maxLineSize = TEXTURE_SIZEX * IAlgorithmAES::BlockSizeBytes;
// Find out the vertical size of the texture that will be used
UINT32 texureSizeY = lastPassSize / maxLineSize;
// The size in bytes of the last line ( can be smaller than maxLineSize )
UINT32 lastLineSize = lastPassSize - (texureSizeY * maxLineSize);
// Set the scissor to only render the required rectangle
D3D10_RECT rects[1];
rects[0].left = 0;
rects[0].right = TEXTURE_SIZEX;
rects[0].top = 0;
rects[0].bottom = texureSizeY + ((lastLineSize != 0) ? 1 : 0);
m_pDevice->RSSetScissorRects( 1, rects );
switch( m_Mode )
{
case IAlgorithmAES::AES_ECB:
{
CopyDataToGPU(src, TEXTURE_SIZEX, texureSizeY, lastLineSize);
RunEncryption();
CopyDataFromGPU(dst, TEXTURE_SIZEX, texureSizeY, lastLineSize);
}break;
case IAlgorithmAES::AES_CTR:
{
SetShaderIV(m_internalEncIV);
// Update the IV for the next run
UINT32 nbBlocks = lastPassSize / IAlgorithmAES::BlockSizeBytes;
if( ((UINT64*)m_internalEncIV)[0] + nbBlocks < ((UINT64*)m_internalEncIV)[0] )
{
((UINT64*)m_internalEncIV)[0] += nbBlocks;
((UINT64*)m_internalEncIV)[1]++;
}
else
((UINT64*)m_internalEncIV)[0] += nbBlocks;
CopyDataToGPU(src, TEXTURE_SIZEX, texureSizeY, lastLineSize);
RunEncryption();
CopyDataFromGPU(dst, TEXTURE_SIZEX, texureSizeY, lastLineSize);
}break;
}
// Set the scissor back to render the full view port
rects[0].bottom = TEXTURE_SIZEY;
m_pDevice->RSSetScissorRects( 1, rects );
}
return IAlgorithmAES::AES_Status_OK;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IAlgorithmAES::AES_Status
AES_GPU_DX10_Internal::Decrypt(UINT8 *dst, const UINT8 *src, UINT32 size)
{
// Check for NULL pointers, and if the size of the data is multiple of block size
// ( padding of the data must be done by the caller )
if( dst == NULL || src == NULL || size % IAlgorithmAES::BlockSizeBytes != 0 )
return IAlgorithmAES::AES_Status_InvalidArgs;
if( m_keySize == AES_Key::AES_KeyInvalid )
return IAlgorithmAES::AES_Status_InvalidState;
// Check if the mode of decryption is supported
if( m_pDecrypt == NULL )
return IAlgorithmAES::AES_Status_NotSupported;
// The number of bytes that can be decrypted in one pass
UINT32 maxPassSize = TEXTURE_SIZEX * TEXTURE_SIZEY * IAlgorithmAES::BlockSizeBytes;
// The number of full passes needed to decrypt the entire input
UINT32 nbPasses= size / maxPassSize;
// The size in bytes of the last pass ( can be smaller than maxPassSize )
UINT32 lastPassSize = size - (nbPasses * maxPassSize);
// Run the full passes
while( nbPasses != 0 )
{
switch( m_Mode )
{
case IAlgorithmAES::AES_ECB:
{
CopyDataToGPU(src, TEXTURE_SIZEX, TEXTURE_SIZEY);
RunDecryption();
CopyDataFromGPU(dst, TEXTURE_SIZEX, TEXTURE_SIZEY);
}break;
case IAlgorithmAES::AES_CBC:
{
CopyDataToGPU(src, TEXTURE_SIZEX, TEXTURE_SIZEY);
RunDecryption();
CopyDataFromGPU(dst, TEXTURE_SIZEX, TEXTURE_SIZEY);
((UINT64*)dst)[0] ^= ((UINT64*)m_internalDecIV)[0];
((UINT64*)dst)[1] ^= ((UINT64*)m_internalDecIV)[1];
// Save the new Initial Vector for the next run
UINT64 *tsrc64 = (UINT64*)(src + size - IAlgorithmAES::BlockSizeBytes);
((UINT64*)m_internalDecIV)[0] = tsrc64[0];
((UINT64*)m_internalDecIV)[1] = tsrc64[1];
}break;
case IAlgorithmAES::AES_CTR:
{
SetShaderIV(m_internalDecIV);
// Update the IV for the next run
if( ((UINT64*)m_internalDecIV)[0] + (TEXTURE_SIZEX * TEXTURE_SIZEY) < ((UINT64*)m_internalDecIV)[0] )
{
((UINT64*)m_internalDecIV)[0] += TEXTURE_SIZEX * TEXTURE_SIZEY;
((UINT64*)m_internalDecIV)[1]++;
}
else
((UINT64*)m_internalDecIV)[0] += TEXTURE_SIZEX * TEXTURE_SIZEY;
CopyDataToGPU(src, TEXTURE_SIZEX, TEXTURE_SIZEY);
RunEncryption();
CopyDataFromGPU(dst, TEXTURE_SIZEX, TEXTURE_SIZEY);
}break;
}
src += maxPassSize;
dst += maxPassSize;
nbPasses--;
}
if( lastPassSize != 0 )
{
// Must process the last bytes that did not fit on one full pass
// The number of bytes that are found on one full line of the texture
UINT32 maxLineSize = TEXTURE_SIZEX * IAlgorithmAES::BlockSizeBytes;
// Find out the vertical size of the texture that will be used
UINT32 texureSizeY = lastPassSize / maxLineSize;
// The size in bytes of the last line ( can be smaller than maxLineSize )
UINT32 lastLineSize = lastPassSize - (texureSizeY * maxLineSize);
// Set the scissor to only render the required rectangle
D3D10_RECT rects[1];
rects[0].left = 0;
rects[0].right = TEXTURE_SIZEX;
rects[0].top = 0;
rects[0].bottom = texureSizeY + ((lastLineSize != 0) ? 1 : 0);
m_pDevice->RSSetScissorRects( 1, rects );
switch( m_Mode )
{
case IAlgorithmAES::AES_ECB:
{
CopyDataToGPU(src, TEXTURE_SIZEX, texureSizeY, lastLineSize);
RunDecryption();
CopyDataFromGPU(dst, TEXTURE_SIZEX, texureSizeY, lastLineSize);
}break;
case IAlgorithmAES::AES_CBC:
{
CopyDataToGPU(src, TEXTURE_SIZEX, texureSizeY, lastLineSize);
RunDecryption();
CopyDataFromGPU(dst, TEXTURE_SIZEX, texureSizeY, lastLineSize);
((UINT64*)dst)[0] ^= ((UINT64*)m_internalDecIV)[0];
((UINT64*)dst)[1] ^= ((UINT64*)m_internalDecIV)[1];
// Save the new Initial Vector for the next run
UINT64 *tsrc64 = (UINT64*)(src + size - IAlgorithmAES::BlockSizeBytes);
((UINT64*)m_internalDecIV)[0] = tsrc64[0];
((UINT64*)m_internalDecIV)[1] = tsrc64[1];
}break;
case IAlgorithmAES::AES_CTR:
{
SetShaderIV(m_internalDecIV);
// Update the IV for the next run
UINT32 nbBlocks = lastPassSize / IAlgorithmAES::BlockSizeBytes;
if( ((UINT64*)m_internalDecIV)[0] + nbBlocks < ((UINT64*)m_internalDecIV)[0] )
{
((UINT64*)m_internalDecIV)[0] += nbBlocks;
((UINT64*)m_internalDecIV)[1]++;
}
else
((UINT64*)m_internalDecIV)[0] += nbBlocks;
CopyDataToGPU(src, TEXTURE_SIZEX, texureSizeY, lastLineSize);
RunEncryption();
CopyDataFromGPU(dst, TEXTURE_SIZEX, texureSizeY, lastLineSize);
}break;
}
// Set the scissor back to render the full view port
rects[0].bottom = TEXTURE_SIZEY;
m_pDevice->RSSetScissorRects( 1, rects );
}
return IAlgorithmAES::AES_Status_OK;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
AES_GPU_DX10_Internal::SetShaderIV(UINT8 *IV)
{
m_pShaderIV->SetIntVector((int*)IV);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
AES_GPU_DX10_Internal::SetShaderKey()
{
// Set the data of the key for encryption
m_pShaderKeyEnc->SetIntVectorArray((int*)m_keyEnc, 0, 15);
// Set the data of the key for decryption
m_pShaderKeyDec->SetIntVectorArray((int*)m_keyDec, 0, 15);
// Set the number of rounds
m_pShaderKeySize->SetInt((m_keySize >> 5) + 6);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
AES_GPU_DX10_Internal::CopyDataToGPU(const UINT8 *src, UINT32 sizeX, UINT32 sizeY, UINT32 lastLineBytes)
{
#if 1
if( sizeY != 0 )
{
// Copy the full lines of data
D3D10_BOX destRegion;
destRegion.left = 0;
destRegion.top = 0;
destRegion.right = sizeX;
destRegion.bottom = sizeY;
destRegion.front = 0;
destRegion.back = 1;
m_pDevice->UpdateSubresource( m_pSourceTexture, D3D10CalcSubresource( 0, 0, 1 ), &destRegion, src, sizeX * 16, 0 );
}
if( lastLineBytes != 0 )
{
// Copy the last incomplete line of data
D3D10_BOX destRegion;
destRegion.left = 0;
destRegion.top = sizeY;
destRegion.right = lastLineBytes / 16;
destRegion.bottom = sizeY + 1;
destRegion.front = 0;
destRegion.back = 1;
m_pDevice->UpdateSubresource( m_pSourceTexture, D3D10CalcSubresource( 0, 0, 1 ), &destRegion, src + sizeY * sizeX * 16, sizeX * 16, 0 );
}
#else
HRESULT hr = S_OK;
// Map the CPU staging resource
D3D10_MAPPED_TEXTURE2D map;
hr = m_pStagingSrcTexture->Map( 0, D3D10_MAP_WRITE, NULL, &map );
if( FAILED( hr ) )
return;
memcpy(map.pData, src, (sizeY * map.RowPitch) + lastLineBytes);
m_pStagingSrcTexture->Unmap( 0 );
// Copy the data from the CPU resource to the GPU resource
D3D10_BOX srcRegion;
srcRegion.left = 0;
srcRegion.right = sizeX;
srcRegion.top = 0;
srcRegion.bottom = sizeY + ((lastLineBytes != 0) ? 1 :0);
srcRegion.front = 0;
srcRegion.back = 1;
m_pDevice->CopySubresourceRegion( m_pSourceTexture, D3D10CalcSubresource( 0, 0, 1 ), 0, 0, 0,
m_pStagingSrcTexture, D3D10CalcSubresource( 0, 0, 1 ), &srcRegion);
#endif
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
AES_GPU_DX10_Internal::CopyDataFromGPU(UINT8 *dst, UINT32 sizeX, UINT32 sizeY, UINT32 lastLineBytes)
{
HRESULT hr = S_OK;
// Copy the data from the GPU resource to the CPU resource
D3D10_BOX srcRegion;
srcRegion.left = 0;
srcRegion.right = sizeX;
srcRegion.top = 0;
srcRegion.bottom = sizeY + ((lastLineBytes != 0) ? 1 :0);
srcRegion.front = 0;
srcRegion.back = 1;
m_pDevice->CopySubresourceRegion( m_pStagingDstTexture, D3D10CalcSubresource( 0, 0, 1 ), 0, 0, 0,
m_pDestTexture, D3D10CalcSubresource( 0, 0, 1 ), &srcRegion);
// Map the CPU staging resource
D3D10_MAPPED_TEXTURE2D map;
hr = m_pStagingDstTexture->Map( 0, D3D10_MAP_READ, NULL, &map );
if( FAILED( hr ) )
return;
memcpy(dst, map.pData, (sizeY * map.RowPitch) + lastLineBytes);
m_pStagingDstTexture->Unmap( 0 );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
AES_GPU_DX10_Internal::RunEncryption()
{
D3D10_TECHNIQUE_DESC techDesc;
m_pEncrypt->GetDesc( &techDesc );
for( UINT p = 0; p < techDesc.Passes; ++p )
{
m_pEncrypt->GetPassByIndex( p )->Apply( 0 );
m_pDevice->Draw( 6, 0 );
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
AES_GPU_DX10_Internal::RunDecryption()
{
D3D10_TECHNIQUE_DESC techDesc;
m_pDecrypt->GetDesc( &techDesc );
for( UINT p = 0; p < techDesc.Passes; ++p )
{
m_pDecrypt->GetPassByIndex( p )->Apply( 0 );
m_pDevice->Draw( 6, 0 );
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL APIENTRY
DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved )
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
::gHModule = hModule;
return TRUE;
}
| 53.802046
| 156
| 0.621422
|
Bizonu
|
38b2e42851cac4b1098d80487fd7f31390c1589f
| 4,391
|
hpp
|
C++
|
includes/commands.hpp
|
Antip003/irc
|
973c4e1ee3d231c6aca1a434a735f236d4d55e77
|
[
"MIT"
] | 1
|
2021-11-29T21:41:10.000Z
|
2021-11-29T21:41:10.000Z
|
includes/commands.hpp
|
Antip003/irc
|
973c4e1ee3d231c6aca1a434a735f236d4d55e77
|
[
"MIT"
] | null | null | null |
includes/commands.hpp
|
Antip003/irc
|
973c4e1ee3d231c6aca1a434a735f236d4d55e77
|
[
"MIT"
] | null | null | null |
#ifndef COMMANDS_HPP
# define COMMANDS_HPP
# include "ircserv.hpp"
# include <string>
struct IRCserv;
void initcommands(IRCserv *serv);
void cmd_nick(int fd, const t_strvect &split, IRCserv *serv);
void cmd_user(int fd, const t_strvect &split, IRCserv *serv);
void cmd_ping(int fd, const t_strvect &split, IRCserv *serv);
void cmd_pong(int fd, const t_strvect &split, IRCserv *serv);
void cmd_quit(int fd, const t_strvect &split, IRCserv *serv);
void cmd_oper(int fd, const t_strvect &split, IRCserv *serv);
void cmd_server(int fd, const t_strvect &split, IRCserv *serv);
void cmd_pass(int fd, const t_strvect &split, IRCserv *serv);
void cmd_squit(int fd, const t_strvect &split, IRCserv *serv);
void cmd_connect(int fd, const t_strvect &split, IRCserv *serv);
void cmd_error(int fd, const t_strvect &split, IRCserv *serv);
void cmd_admin(int fd, const t_strvect &split, IRCserv *serv);
void cmd_motd(int fd, const t_strvect &split, IRCserv *serv);
void cmd_userhost(int fd, const t_strvect &split, IRCserv *serv);
void cmd_version(int fd, const t_strvect &split, IRCserv *serv);
void cmd_info(int fd, const t_strvect &split, IRCserv *serv);
void cmd_time(int fd, const t_strvect &split, IRCserv *serv);
void cmd_join(int fd, const t_strvect &split, IRCserv *serv);
void cmd_privmsg(int fd, const t_strvect &split, IRCserv *serv);
void cmd_invite(int fd, const t_strvect &split, IRCserv *serv);
void cmd_names(int fd, const t_strvect &split, IRCserv *serv);
void cmd_who(int fd, const t_strvect &split, IRCserv *serv);
void cmd_whois(int fd, const t_strvect &split, IRCserv *serv);
void cmd_whowas(int fd, const t_strvect &split, IRCserv *serv);
void cmd_part(int fd, const t_strvect &split, IRCserv *serv);
void cmd_mode(int fd, const t_strvect &split, IRCserv *serv);
void cmd_notice(int fd, const t_strvect &split, IRCserv *serv);
void cmd_away(int fd, const t_strvect &split, IRCserv *serv);
void cmd_kill(int fd, const t_strvect &split, IRCserv *serv);
void cmd_stats(int fd, const t_strvect &split, IRCserv *serv);
void cmd_links(int fd, const t_strvect &split, IRCserv *serv);
void cmd_njoin(int fd, const t_strvect &split, IRCserv *serv);
void cmd_lusers(int fd, const t_strvect &split, IRCserv *serv);
void cmd_ison(int fd, const t_strvect &split, IRCserv *serv);
void cmd_users(int fd, const t_strvect &split, IRCserv *serv); // disabled
void cmd_topic(int fd, t_strvect const &split, IRCserv *serv);
void cmd_kick(int fd, t_strvect const &split, IRCserv *serv);
void cmd_trace(int fd, t_strvect const &split, IRCserv *serv);
void cmd_die(int fd, t_strvect const &split, IRCserv *serv);
void cmd_list(int fd, t_strvect const &split, IRCserv *serv);
void cmd_wallops(int fd, t_strvect const &split, IRCserv *serv);
void cmd_rehash(int fd, t_strvect const &split, IRCserv *serv);
void cmd_service(int fd, t_strvect const &split, IRCserv *serv);
void cmd_servlist(int fd, t_strvect const &split, IRCserv *serv);
void cmd_squery(int fd, const t_strvect &split, IRCserv *serv);
std::string reply_welcome(IRCserv *serv, Client *client);
std::string reply_motd(IRCserv *serv, std::string const &it);
std::string reply_chan_names(IRCserv *serv, Channel *chan, Client *client);
std::string reply_nochan_visible_names(IRCserv *serv, Client *client);
std::string reply_lusers(IRCserv *serv, std::string const &target, std::string const &mask = "*");
bool is_server_registred(const std::string &name, std::string const token, IRCserv *serv);
std::string getservernamebymask(IRCserv *serv, std::string const &mask);
int getserverfdbymask(IRCserv *serv, std::string const &mask);
std::string getnicktoreply(int fd, const t_strvect &split, IRCserv *serv);
std::string reply_unknowncmd(int fd, const t_strvect &split, IRCserv *serv);
#define CMD_CLIENTONLY 1
#define CMD_SERVERONLY 2
class Command {
private:
typedef void (*t_command)(int fd, const t_strvect &split, IRCserv *serv);
t_command cmd;
uint type;
// message stats
uint count;
size_t bytes;
uint rcount;
public:
Command();
~Command();
Command(t_command cmd);
Command(Command const &other);
Command &operator=(Command const &other);
bool used(void);
bool serveronly(void);
bool clientonly(void);
uint getcount(void);
size_t getbytes(void);
uint getrcount(void);
void settype(uint type);
void Execute(int fd, const t_strvect &split, IRCserv *serv,
size_t bytes, bool remote);
};
#endif
| 44.353535
| 99
| 0.754042
|
Antip003
|
38b3d591571417f9228d4f060a5c25dc6ff02d0f
| 1,327
|
cc
|
C++
|
leet_code/Letter_Combinations_of_a_Phone_Number/solve.cc
|
ldy121/algorithm
|
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
|
[
"Apache-2.0"
] | 1
|
2020-04-11T22:04:23.000Z
|
2020-04-11T22:04:23.000Z
|
leet_code/Letter_Combinations_of_a_Phone_Number/solve.cc
|
ldy121/algorithm
|
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
|
[
"Apache-2.0"
] | null | null | null |
leet_code/Letter_Combinations_of_a_Phone_Number/solve.cc
|
ldy121/algorithm
|
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
|
[
"Apache-2.0"
] | null | null | null |
class Solution {
private:
vector<string> answer;
vector<vector<char> > phone;
void getAnswer(string &digits, int idx, string buffer) {
if (idx == digits.size()) {
if (buffer.length() > 0) {
answer.push_back(buffer);
}
return;
}
if (digits[idx] == '1') {
getAnswer(digits, idx + 1, buffer);
return;
}
for_each(phone[digits[idx] - '0'].begin(), phone[digits[idx] - '0'].end(), [this, &digits, &idx, &buffer](auto &ch){
getAnswer(digits, idx + 1, buffer + ch);
});
}
public:
Solution() {
phone.push_back(vector<char>({' '}));
phone.push_back(vector<char>());
phone.push_back(vector<char>({'a', 'b', 'c'}));
phone.push_back(vector<char>({'d', 'e', 'f'}));
phone.push_back(vector<char>({'g', 'h', 'i'}));
phone.push_back(vector<char>({'j', 'k', 'l'}));
phone.push_back(vector<char>({'m', 'n', 'o'}));
phone.push_back(vector<char>({'p', 'q', 'r', 's'}));
phone.push_back(vector<char>({'t', 'u', 'v'}));
phone.push_back(vector<char>({'w', 'x', 'y', 'z'}));
}
vector<string> letterCombinations(string digits) {
getAnswer(digits, 0, string());
return answer;
}
};
| 31.595238
| 124
| 0.494348
|
ldy121
|
38b8c0ee00901e25876500ed31aeb70e384d808f
| 1,681
|
cpp
|
C++
|
source/bezier_debug.cpp
|
Sankhma/AutismoSimulator
|
ac0cd2c321929b92cadfed9eb6c96faa9e60e18e
|
[
"MIT"
] | null | null | null |
source/bezier_debug.cpp
|
Sankhma/AutismoSimulator
|
ac0cd2c321929b92cadfed9eb6c96faa9e60e18e
|
[
"MIT"
] | 38
|
2020-11-08T21:54:57.000Z
|
2020-12-01T09:33:11.000Z
|
source/bezier_debug.cpp
|
Sankhma/AutismoSimulator
|
ac0cd2c321929b92cadfed9eb6c96faa9e60e18e
|
[
"MIT"
] | 1
|
2020-11-04T22:17:11.000Z
|
2020-11-04T22:17:11.000Z
|
#include <iostream>
#include "Bezier.h"
#include "Vector.h"
// and this
int main(){
Vector2<double> vec0 = Vector2<double>(1, 2);
Vector2<double> vec1 = Vector2<double>(2, 3);
Vector2<double> vec2 = Vector2<double>(7, 4);
Vector2<double> vec3 = Vector2<double>(133, 1123);
std::vector<Vector2<double>> points;
points.push_back(vec0);
points.push_back(vec1);
points.push_back(vec2);
points.push_back(vec3);
Bezier<Vector2<double>> bez0 = Bezier<Vector2<double>>(points);
int steps = 5;
std::cout << "Bezier2 has 4 points in total" << std::endl;
for(int i=0; i <= steps; i++){
double t = double(i) / steps;
Bezier<Vector2<double>>::GenerateVertex(bez0, t);
}
bez0.addPoint(Vector2<double>(1, 2));
bez0.addPoint(Vector2<double>(420, 69));
std::cout << "Added 2 more points, Bezier2 has 6 points in total" << std::endl;
for(int i=0; i <= steps; i++){
double t = double(i) / steps;
Bezier<Vector2<double>>::GenerateVertex(bez0, t);
}
Bezier<Vector2<double>> bez1 = Bezier<Vector2<double>>(3, &vec0, &vec1, &vec2);
std::cout << "Bezier2 (initialized using variadic arguments) has 3 points in total" << std::endl;
for(int i=0; i <= steps; i++){
double t = double(i) / steps;
Bezier<Vector2<double>>::GenerateVertex(bez1, t);
}
bez1.addPoint(Vector2<double>(1, 2));
bez1.addPoint(Vector2<double>(1, 10));
std::cout << "Added 2 more point, Bezier2 has 5 points in total" << std::endl;
for(int i=0; i <= steps; i++){
double t = double(i) / steps;
Bezier<Vector2<double>>::GenerateVertex(bez1, t);
}
}
| 29.491228
| 101
| 0.607971
|
Sankhma
|
38c0a940ef7fac4fe1b38094bc3cda98e082d9fa
| 324
|
cpp
|
C++
|
elastic-circuits/examples/string_match.cpp
|
minseongg/dynamatic
|
268d97690f128569da46e4f39a99346e93ee9d4e
|
[
"MIT"
] | 46
|
2019-11-16T13:44:07.000Z
|
2022-03-12T14:28:44.000Z
|
elastic-circuits/examples/string_match.cpp
|
minseongg/dynamatic
|
268d97690f128569da46e4f39a99346e93ee9d4e
|
[
"MIT"
] | 11
|
2020-05-12T17:20:51.000Z
|
2022-02-04T10:04:59.000Z
|
elastic-circuits/examples/string_match.cpp
|
minseongg/dynamatic
|
268d97690f128569da46e4f39a99346e93ee9d4e
|
[
"MIT"
] | 22
|
2020-02-21T21:33:40.000Z
|
2022-02-24T06:50:41.000Z
|
// Finds an occurrence of x in y
// n is the length of x, m is the length of y
int substring(char x[], char y[], int n, int m) {
for (int i = 0; i <= m - n; ++i) {
int j = 0;
while (j < n and x[j] == y[i + j])
++j;
if (j == n)
return i;
}
return -1;
}
| 24.923077
| 50
| 0.41358
|
minseongg
|
38ca6e7461ceb6687bc335e05c40db489d7ccd06
| 3,550
|
hxx
|
C++
|
src/engine/ivp/ivp_utility/ivu_float.hxx
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 6
|
2022-01-23T09:40:33.000Z
|
2022-03-20T20:53:25.000Z
|
src/engine/ivp/ivp_utility/ivu_float.hxx
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | null | null | null |
src/engine/ivp/ivp_utility/ivu_float.hxx
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 1
|
2022-02-06T21:05:23.000Z
|
2022-02-06T21:05:23.000Z
|
#ifdef WIN32
#include <float.h>
#endif
#if defined(IVP_NO_DOUBLE) && !defined(SUN)
# include <math.h>
# if defined(WIN32) || defined(PSXII) || defined(LINUX)
union p_float_ieee { IVP_FLOAT val;
struct {
unsigned int valh:23; unsigned int exp:8; unsigned int signum:1;
} ln; };
#else
union p_float_ieee { IVP_FLOAT val;
struct {
unsigned int signum:1; unsigned int exp:8; ;unsigned int valh:23;
} ln; };
#endif
#define IVP_EXP_FOR_ONE 0x7f
inline int PFM_LD(float a){ return ((p_float_ieee *)&(a))->ln.exp - IVP_EXP_FOR_ONE; };
#else
# if defined(LINUX) || defined(WIN32)
union p_double_ieee {
IVP_DOUBLE val;
struct {
int val;
unsigned int valh: 20;
unsigned int exp: 11;
unsigned int signum: 1;
} ln;
struct {
int l;
int h;
} ln2;
};
#define IVP_EXP_FOR_ONE 0x3ff
inline int PFM_LD(double a) { return ((p_double_ieee *) &(a))->ln.exp - IVP_EXP_FOR_ONE; };
# endif
# if defined(SUN) || defined(SUN4) || defined(__POWERPC__) || defined(GEKKO)
union p_double_ieee {
double val;
struct {
unsigned int signum:1;
unsigned int exp:11;
unsigned int valh:20;
int val;
} ln;
struct {
int h;
int l;
} ln2;
};
# define P_EXP_FOR_ONE 0x3ff
inline int PFM_LD(double a){ return ((p_double_ieee *)&(a))->ln.exp - P_EXP_FOR_ONE; };
# endif
#endif
class IVP_Fast_Math {
public:
#if defined(PSXII)
/// Calculates the dot product of the calling vector with v.
/// \param v
inline static IVP_DOUBLE isqrt(IVP_DOUBLE x, int /*resolution_steps*/)
{
float u = 1.0f;
__asm__ __volatile__ ("
.set noreorder
rsqrt.s %0, %1, %0
.set reorder
" : "+f" (x) : "f" (u));
return x;
}
/// Calculates the dot product of the calling vector with v.
/// \param v
inline static IVP_DOUBLE sqrt(IVP_DOUBLE x)
{
__asm__ __volatile__ ("
.set noreorder
sqrt.s %0, %0
.set reorder
" : "+f" (x) :);
return x;
}
#elif defined(IVP_NO_DOUBLE)
static IVP_DOUBLE isqrt(IVP_DOUBLE square, int /*resolution_steps*/){
return 1.0f/IVP_Inline_Math::ivp_sqrtf(square);
}
static IVP_DOUBLE sqrt(IVP_DOUBLE x){
return IVP_Inline_Math::ivp_sqrtf(x);
}
#else
// fast 1/sqrt(x),
// resolution for resolution_steps
// 0 -> 1e-3
// 1 -> 1e-7
// 2 -> 1e-14
// 3 -> 1e-16
static double isqrt(double square, int resolution_steps) {
p_double_ieee *ie = (p_double_ieee *) □
IVP_ASSERT(IVP_Inline_Math::fabsd(square) > 0.0f);
p_double_ieee h;
h.val = 1.0f;
h.ln2.h = ((0x07ff00000 - ie->ln2.h) >> 1) + 0x1ff00000;
IVP_DOUBLE squareh = square * 0.5f;
IVP_DOUBLE inv_sqrt = h.val;
inv_sqrt += inv_sqrt * (0.5f - inv_sqrt * inv_sqrt * squareh);
inv_sqrt += inv_sqrt * (0.5f - inv_sqrt * inv_sqrt * squareh);
if (resolution_steps > 0) inv_sqrt += inv_sqrt * (0.5f - (inv_sqrt * inv_sqrt * squareh));
if (resolution_steps > 1) inv_sqrt += inv_sqrt * (0.5f - (inv_sqrt * inv_sqrt * squareh));
if (resolution_steps > 2) inv_sqrt += inv_sqrt * (0.5f - (inv_sqrt * inv_sqrt * squareh));
IVP_ASSERT(IVP_Inline_Math::fabsd(1.0f - inv_sqrt * inv_sqrt * square) < 0.001f);
return inv_sqrt;
}
static IVP_DOUBLE sqrt(IVP_DOUBLE x) {
return ::sqrt(x);
}
#endif
};
| 26.102941
| 98
| 0.587606
|
cstom4994
|
38cb0edf44d87a3a9a36ca82f4c06e941e8d6a97
| 5,997
|
cpp
|
C++
|
meeting-qt/setup/src/dui/Box/TileBox.cpp
|
GrowthEase/-
|
5cc7cab95fc309049de8023ff618219dff22d773
|
[
"MIT"
] | 48
|
2022-03-02T07:15:08.000Z
|
2022-03-31T08:37:33.000Z
|
meeting-qt/setup/src/dui/Box/TileBox.cpp
|
chandarlee/Meeting
|
9350fdea97eb2cdda28b8bffd9c4199de15460d9
|
[
"MIT"
] | 1
|
2022-02-16T01:54:05.000Z
|
2022-02-16T01:54:05.000Z
|
meeting-qt/setup/src/dui/Box/TileBox.cpp
|
chandarlee/Meeting
|
9350fdea97eb2cdda28b8bffd9c4199de15460d9
|
[
"MIT"
] | 9
|
2022-03-01T13:41:37.000Z
|
2022-03-10T06:05:23.000Z
|
/**
* @copyright Copyright (c) 2021 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
#include "stdafx.h"
#include "TileBox.h"
namespace ui
{
TileLayout::TileLayout()
{
m_szItem.cx = m_szItem.cy = 0;
}
CSize TileLayout::ArrangeChild(const std::vector<Control*>& m_items, UiRect rc)
{
// Position the elements
if( m_szItem.cx > 0 ) m_nColumns = (rc.right - rc.left) / m_szItem.cx;
if( m_nColumns == 0 ) m_nColumns = 1;
int cyNeeded = 0;
int cxWidth = rc.GetWidth() / m_nColumns;
int deviation = rc.GetWidth() - cxWidth * m_nColumns;
int cyHeight = 0;
int iCount = 0;
POINT ptTile = { rc.left, rc.top };
int iPosX = rc.left;
for( auto it = m_items.begin(); it != m_items.end(); it++ ) {
auto pControl = *it;
if( !pControl->IsVisible() ) continue;
if( pControl->IsFloat() ) {
SetFloatPos(pControl, rc);
continue;
}
// Determine size
UiRect rcTile(ptTile.x, ptTile.y, ptTile.x + cxWidth, ptTile.y);
if (deviation > 0) {
rcTile.right += 1;
deviation--;
}
if( (iCount % m_nColumns) == 0 )
{
int iIndex = iCount;
for( auto it = m_items.begin(); it != m_items.end(); it++ ) {
auto pLineControl = *it;
if( !pLineControl->IsVisible() ) continue;
if( pLineControl->IsFloat() ) continue;
UiRect rcMargin = pLineControl->GetMargin();
CSize szAvailable = { rcTile.right - rcTile.left - rcMargin.left - rcMargin.right, 9999 };
if( iIndex == iCount || (iIndex + 1) % m_nColumns == 0 ) {
szAvailable.cx -= m_iChildMargin / 2;
}
else {
szAvailable.cx -= m_iChildMargin;
}
if( szAvailable.cx < pControl->GetMinWidth() ) szAvailable.cx = pControl->GetMinWidth();
if( pControl->GetMaxWidth() >= 0 && szAvailable.cx > pControl->GetMaxWidth() ) szAvailable.cx = pControl->GetMaxWidth();
CSize szTile = pLineControl->EstimateSize(szAvailable);
if( szTile.cx < pControl->GetMinWidth() ) szTile.cx = pControl->GetMinWidth();
if( pControl->GetMaxWidth() >= 0 && szTile.cx > pControl->GetMaxWidth() ) szTile.cx = pControl->GetMaxWidth();
if( szTile.cy < pControl->GetMinHeight() ) szTile.cy = pControl->GetMinHeight();
if( szTile.cy > pControl->GetMaxHeight() ) szTile.cy = pControl->GetMaxHeight();
cyHeight = MAX(cyHeight, szTile.cy + rcMargin.top + rcMargin.bottom);
if( (++iIndex % m_nColumns) == 0) break;
}
}
UiRect rcMargin = pControl->GetMargin();
rcTile.left += rcMargin.left + m_iChildMargin / 2;
rcTile.right -= rcMargin.right + m_iChildMargin / 2;
if( (iCount % m_nColumns) == 0 ) {
rcTile.left -= m_iChildMargin / 2;
}
if( ( (iCount + 1) % m_nColumns) == 0 ) {
rcTile.right += m_iChildMargin / 2;
}
// Set position
rcTile.top = ptTile.y + rcMargin.top;
rcTile.bottom = ptTile.y + cyHeight;
CSize szAvailable = { rcTile.right - rcTile.left, rcTile.bottom - rcTile.top };
CSize szTile = pControl->EstimateSize(szAvailable);
if( szTile.cx == DUI_LENGTH_STRETCH ) szTile.cx = szAvailable.cx;
if( szTile.cy == DUI_LENGTH_STRETCH ) szTile.cy = szAvailable.cy;
if( szTile.cx < pControl->GetMinWidth() ) szTile.cx = pControl->GetMinWidth();
if( pControl->GetMaxWidth() >= 0 && szTile.cx > pControl->GetMaxWidth() ) szTile.cx = pControl->GetMaxWidth();
if( szTile.cy < pControl->GetMinHeight() ) szTile.cy = pControl->GetMinHeight();
if( szTile.cy > pControl->GetMaxHeight() ) szTile.cy = pControl->GetMaxHeight();
UiRect rcPos((rcTile.left + rcTile.right - szTile.cx) / 2, (rcTile.top + rcTile.bottom - szTile.cy) / 2,
(rcTile.left + rcTile.right - szTile.cx) / 2 + szTile.cx, (rcTile.top + rcTile.bottom - szTile.cy) / 2 + szTile.cy);
pControl->SetPos(rcPos);
if( (++iCount % m_nColumns) == 0 ) {
ptTile.x = iPosX;
ptTile.y += cyHeight + m_iChildMargin;
cyHeight = 0;
}
else {
ptTile.x += rcTile.GetWidth();
}
cyNeeded = rcTile.bottom - rc.top;
}
CSize size = {rc.right - rc.left, cyNeeded};
return size;
}
CSize TileLayout::AjustSizeByChild(const std::vector<Control*>& m_items, CSize szAvailable)
{
CSize size = m_pOwner->Control::EstimateSize(szAvailable);
size.cy = 0;
if( m_szItem.cx > 0 ) m_nColumns = m_pOwner->GetFixedWidth() / m_szItem.cx;
if( m_nColumns == 0 ) m_nColumns = 1;
int rows = m_pOwner->GetCount() / m_nColumns;
if (m_pOwner->GetCount() % m_nColumns != 0)
{
rows += 1;
}
if (m_items.size() > 0)
{
int childMarginTotal;
if (m_items.size() % m_nColumns == 0)
{
childMarginTotal = (m_items.size() / m_nColumns - 1) * m_iChildMargin;
}
else
{
childMarginTotal = (m_items.size() / m_nColumns) * m_iChildMargin;
}
Control* pControl = static_cast<Control*>(m_items[0]);
size.cy += pControl->GetFixedHeight() * rows + m_rcPadding.top + m_rcPadding.bottom + childMarginTotal;
}
return size;
}
bool TileLayout::SetAttribute(const std::wstring& pstrName, const std::wstring& pstrValue)
{
bool hasAttribute = true;
if( pstrName == _T("itemsize") ) {
CSize szItem;
LPTSTR pstr = NULL;
szItem.cx = _tcstol(pstrValue.c_str(), &pstr, 10); ASSERT(pstr);
szItem.cy = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr);
SetItemSize(szItem);
}
else if( pstrName == _T("columns"))
{
SetColumns(_ttoi(pstrValue.c_str()));
}
else
{
hasAttribute = Layout::SetAttribute(pstrName, pstrValue);
}
return hasAttribute;
}
CSize TileLayout::GetItemSize() const
{
return m_szItem;
}
void TileLayout::SetItemSize(CSize szItem)
{
if( m_szItem.cx != szItem.cx || m_szItem.cy != szItem.cy ) {
m_szItem = szItem;
m_pOwner->Arrange();
}
}
int TileLayout::GetColumns() const
{
return m_nColumns;
}
void TileLayout::SetColumns(int nCols)
{
if( nCols <= 0 ) return;
m_nColumns = nCols;
m_pOwner->Arrange();
}
TileBox::TileBox() :
Box(new TileLayout())
{
}
}
| 29.541872
| 125
| 0.637986
|
GrowthEase
|
38d059c88a8cdda0cb6ba2169db771c76242e513
| 1,483
|
cpp
|
C++
|
src/Aplicatii Vectori/ex 9/main.cpp
|
andrew-miroiu/Cpp-projects
|
d0917a7f78aef929c25dc9b019e910951c2050ac
|
[
"MIT"
] | 2
|
2021-11-27T18:29:32.000Z
|
2021-11-28T14:35:47.000Z
|
src/Aplicatii Vectori/ex 9/main.cpp
|
andrew-miroiu/Cpp-projects
|
d0917a7f78aef929c25dc9b019e910951c2050ac
|
[
"MIT"
] | null | null | null |
src/Aplicatii Vectori/ex 9/main.cpp
|
andrew-miroiu/Cpp-projects
|
d0917a7f78aef929c25dc9b019e910951c2050ac
|
[
"MIT"
] | null | null | null |
#include <iostream>
//9. Se citesc elementele unui tablou v unidimensional cu n (n<=100) componente, numere întregi din cel
//mult 4 cifre fiecare. Sa se realizeze următoarele prelucrări: a. Să se afişeze valorile prime. b. Să se afişeze
//numerele prime a căror invers este tot un număr prim.
using namespace std;
int main()
{
int n, v[100], i, prime=0, d, ogl=0, primeogl=0;
cout<<"n= ";
cin>>n;
cout<<"Scrie numerele: ";
for(i=0; i<n; i++)
{
cin>>v[i];
}
cout<<"Numerele prime sunt: ";
for(i=0; i<n; i++)
{
for(d=2; d*d<=v[i]; d++)
{
prime=0;
if(v[i]%d==0)
{
prime++;
}
}
if(prime==0)
{
cout<<v[i]<<" ,";
}
}
cout<<"\b "<<endl;
cout<<"Numerele care sunt prime si rasturnatul lor este tot prim sunt:";
for(i=0; i<n; i++)
{
int cv=v[i];
while(cv)
{
ogl=ogl*10+cv%10;
cv=cv/10;
}
for(d=2; d*d<=v[i]; d++)
{
prime=0;
if(v[i]%d==0)
{
prime++;
}
}
for(int j=2; j*j<=ogl; j++)
{
primeogl=0;
if(ogl%j==0)
{
primeogl++;
}
}
if(prime==0 && primeogl==0)
{
cout<<v[i]<<" ,";
}
}
cout<<"\b ";
return 0;
}
| 19.25974
| 113
| 0.401214
|
andrew-miroiu
|
38d1097ac49d5678b32384644edd0219f7fcd9f5
| 4,679
|
cpp
|
C++
|
Engine/source/platform/platformAssert.cpp
|
fr1tz/alux3d
|
249a3b51751ce3184d52879b481f83eabe89e7e3
|
[
"MIT"
] | null | null | null |
Engine/source/platform/platformAssert.cpp
|
fr1tz/alux3d
|
249a3b51751ce3184d52879b481f83eabe89e7e3
|
[
"MIT"
] | null | null | null |
Engine/source/platform/platformAssert.cpp
|
fr1tz/alux3d
|
249a3b51751ce3184d52879b481f83eabe89e7e3
|
[
"MIT"
] | 1
|
2018-10-26T03:18:22.000Z
|
2018-10-26T03:18:22.000Z
|
// Copyright information can be found in the file named COPYING
// located in the root directory of this distribution.
#include <stdarg.h>
#include "core/strings/stringFunctions.h"
#include "console/console.h"
//-------------------------------------- STATIC Declaration
PlatformAssert *PlatformAssert::platformAssert = NULL;
//--------------------------------------
PlatformAssert::PlatformAssert()
{
processing = false;
}
//--------------------------------------
PlatformAssert::~PlatformAssert()
{
}
//--------------------------------------
void PlatformAssert::create( PlatformAssert* newAssertClass )
{
if (!platformAssert)
platformAssert = newAssertClass ? newAssertClass : new PlatformAssert;
}
//--------------------------------------
void PlatformAssert::destroy()
{
if (platformAssert)
delete platformAssert;
platformAssert = NULL;
}
//--------------------------------------
bool PlatformAssert::displayMessageBox(const char *title, const char *message, bool retry)
{
if (retry)
return Platform::AlertRetry(title, message);
Platform::AlertOK(title, message);
return false;
}
static const char *typeName[] = { "Unknown", "Fatal-ISV", "Fatal", "Warning" };
//------------------------------------------------------------------------------
static bool askToEnterDebugger(const char* message )
{
static bool haveAsked = false;
static bool useDebugger = true;
if(!haveAsked )
{
static char tempBuff[1024];
dSprintf( tempBuff, 1024, "Torque has encountered an assertion with message\n\n"
"%s\n\n"
"Would you like to use the debugger? If you cancel, you won't be asked"
" again until you restart Torque.", message);
useDebugger = Platform::AlertOKCancel("Use debugger?", tempBuff );
haveAsked = true;
}
return useDebugger;
}
//--------------------------------------
bool PlatformAssert::process(Type assertType,
const char *filename,
U32 lineNumber,
const char *message)
{
// If we're somehow recursing, just die.
if(processing)
Platform::debugBreak();
processing = true;
bool ret = true;
// always dump to the Assert to the Console
if (Con::isActive())
{
if (assertType == Warning)
Con::warnf(ConsoleLogEntry::Assert, "%s(%ld) : %s - %s", filename, lineNumber, typeName[assertType], message);
else
Con::errorf(ConsoleLogEntry::Assert, "%s(%ld) : %s - %s", filename, lineNumber, typeName[assertType], message);
}
// if not a WARNING pop-up a dialog box
if (assertType != Warning)
{
// used for processing navGraphs (an assert won't botch the whole build)
if(Con::getBoolVariable("$FP::DisableAsserts", false) == true)
Platform::forceShutdown(1);
char buffer[2048];
dSprintf(buffer, 2048, "%s(%ld) : %s", filename, lineNumber, typeName[assertType] );
#ifdef TORQUE_DEBUG
// In debug versions, allow a retry even for ISVs...
bool retry = displayMessageBox(buffer, message, true);
#else
bool retry = displayMessageBox(buffer, message, ((assertType == Fatal) ? true : false) );
#endif
if(!retry)
Platform::forceShutdown(1);
ret = askToEnterDebugger(message);
}
processing = false;
return ret;
}
bool PlatformAssert::processingAssert()
{
return platformAssert ? platformAssert->processing : false;
}
//--------------------------------------
bool PlatformAssert::processAssert(Type assertType,
const char *filename,
U32 lineNumber,
const char *message)
{
if (platformAssert)
return platformAssert->process(assertType, filename, lineNumber, message);
else // when platAssert NULL (during _start/_exit) try direct output...
dPrintf("\n%s: (%s @ %ld) %s\n", typeName[assertType], filename, lineNumber, message);
// this could also be platform-specific: OutputDebugString on PC, DebugStr on Mac.
// Will raw printfs do the job? In the worst case, it's a break-pointable line of code.
// would have preferred Con but due to race conditions, it might not be around...
// Con::errorf(ConsoleLogEntry::Assert, "%s: (%s @ %ld) %s", typeName[assertType], filename, lineNumber, message);
return true;
}
//--------------------------------------
const char* avar(const char *message, ...)
{
static char buffer[4096];
va_list args;
va_start(args, message);
dVsprintf(buffer, sizeof(buffer), message, args);
return( buffer );
}
| 30.383117
| 119
| 0.582176
|
fr1tz
|
38d15c721c10b88000fc8841d3021692d002b1b5
| 2,097
|
cpp
|
C++
|
src/Saurobyte/SystemPool.cpp
|
Symphonym/Saurobyte
|
c4bc5afd4ac4353ed6cd9a201454fd14aa3aced2
|
[
"MIT"
] | 17
|
2015-01-26T19:46:42.000Z
|
2021-10-04T15:30:32.000Z
|
src/Saurobyte/SystemPool.cpp
|
Symphonym/Saurobyte
|
c4bc5afd4ac4353ed6cd9a201454fd14aa3aced2
|
[
"MIT"
] | 1
|
2021-04-06T01:12:03.000Z
|
2021-04-06T01:12:03.000Z
|
src/Saurobyte/SystemPool.cpp
|
Symphonym/Saurobyte
|
c4bc5afd4ac4353ed6cd9a201454fd14aa3aced2
|
[
"MIT"
] | 2
|
2015-02-03T21:23:49.000Z
|
2021-05-02T14:52:52.000Z
|
#include <Saurobyte/SystemPool.hpp>
#include <Saurobyte/System.hpp>
namespace Saurobyte
{
SystemPool::SystemPool(Engine *engine)
:
m_engine(engine)
{
}
SystemPool::~SystemPool()
{
frameCleanup();
m_systemPool.clear();
}
void SystemPool::addSystem(BaseSystem *newSystem)
{
// Make sure the system doesn't exist, then add it
auto iter = m_systemPool.find(newSystem->getTypeID());
if(iter == m_systemPool.end())
m_systemPool[newSystem->getTypeID()] = SystemPtr(newSystem);
}
void SystemPool::removeSystem(TypeID id)
{
auto iter = m_systemPool.find(id);
// Delete the system from the map, but the actual memory deletion is done at the start
// of the next frame. This is done so any calls to hasSystem after the remove call will
// return false.
if(iter != m_systemPool.end())
{
m_pendingDeletes.push_back(std::move(iter->second));
m_systemPool.erase(iter);
}
}
BaseSystem* SystemPool::getSystem(TypeID id)
{
auto iter = m_systemPool.find(id);
if(iter == m_systemPool.end())
return nullptr;
else
return iter->second.get();
}
bool SystemPool::hasSystem(TypeID id)
{
auto iter = m_systemPool.find(id);
return iter != m_systemPool.end();
}
void SystemPool::emptySystems()
{
for(auto itr = m_systemPool.begin(); itr != m_systemPool.end(); itr++)
{
if(itr->second->isActive())
itr->second->clearSystem();
}
}
void SystemPool::processSystems()
{
for(auto itr = m_systemPool.begin(); itr != m_systemPool.end(); itr++)
{
if(itr->second->isActive())
{
itr->second->preProcess();
itr->second->processEntities();
itr->second->postProcess();
}
}
}
void SystemPool::removeEntityFromSystems(Entity &entity, bool wasKilled)
{
for(auto itr = m_systemPool.begin(); itr != m_systemPool.end(); itr++)
itr->second->removeEntity(entity, wasKilled);
}
void SystemPool::refreshEntity(Entity &entity)
{
for(auto itr = m_systemPool.begin(); itr != m_systemPool.end(); itr++)
itr->second->refreshEntity(entity);
}
void SystemPool::frameCleanup()
{
m_pendingDeletes.clear();
}
};
| 22.793478
| 89
| 0.680496
|
Symphonym
|
38d3c1e7f8c1a57cf3db762f9dda90899b1e041b
| 11,451
|
cpp
|
C++
|
Spider3D.cpp
|
Artars/WalkingGLSpider
|
d939a1f27730aaabdc36b01fd574351f967c08dd
|
[
"MIT"
] | null | null | null |
Spider3D.cpp
|
Artars/WalkingGLSpider
|
d939a1f27730aaabdc36b01fd574351f967c08dd
|
[
"MIT"
] | null | null | null |
Spider3D.cpp
|
Artars/WalkingGLSpider
|
d939a1f27730aaabdc36b01fd574351f967c08dd
|
[
"MIT"
] | null | null | null |
#include "Spider3D.h"
Spider3D::Spider3D(){
finishConstruction();
}
Spider3D::Spider3D(Vector3 position, Vector3 scale, Vector3 rotation){
this->position = position;
this->scale = scale;
this->rotation = rotation;
finishConstruction();
}
void Spider3D::finishConstruction() {
char path[] = "SBody.obj";
char path2[] = "SEyes.obj";
char path3[] = "SLeg2.obj";
char path4[] = "SLeg1.obj";
loadModel(path);
children = new vector<Transform*>();
Transform *newPart, *newPart2;
newPart = new Transform();
newPart->loadModel(path2);
newPart->setColor(1,0,0);
children->push_back(newPart);
//Perna dianteira esquerda
newPart = new Transform(Vector3(-0.2, -0.2, 0), Vector3(1,1,1), Vector3(-15,0,0));
newPart->loadModel(path4);
newPart->setColor(color[0],color[1],color[2]);
children->push_back(newPart);
newPart2 = new Transform(Vector3(0,-0.6,0),Vector3(1,1,1),Vector3(48,0,0));
newPart2->loadModel(path4);
newPart2->setColor(color[0],color[1],color[2]);
newPart->children = new vector<Transform*>();
newPart->children->push_back(newPart2);
//Perna secundaria esquerda
newPart = new Transform(Vector3(-0.05, -0.2, 0), Vector3(1,1,1), Vector3(-15,0,0));
newPart->loadModel(path3);
newPart->setColor(color[0],color[1],color[2]);
children->push_back(newPart);
newPart2 = new Transform(Vector3(0,-0.45,0),Vector3(1,1,1),Vector3(60,0,0));
newPart2->loadModel(path3);
newPart2->setColor(color[0],color[1],color[2]);
newPart->children = new vector<Transform*>();
newPart->children->push_back(newPart2);
//Perna secundaria esquerda
newPart = new Transform(Vector3(0.1, -0.2, 0), Vector3(1,1,1), Vector3(-15,0,0));
newPart->loadModel(path3);
newPart->setColor(color[0],color[1],color[2]);
children->push_back(newPart);
newPart2 = new Transform(Vector3(0,-0.45,0),Vector3(1,1,1),Vector3(60,0,0));
newPart2->loadModel(path3);
newPart2->setColor(color[0],color[1],color[2]);
newPart->children = new vector<Transform*>();
newPart->children->push_back(newPart2);
//Perna Traseira esquerda
newPart = new Transform(Vector3(0.25, -0.2, 0), Vector3(1,1,1), Vector3(-15,0,0));
newPart->loadModel(path4);
newPart->setColor(color[0],color[1],color[2]);
children->push_back(newPart);
newPart2 = new Transform(Vector3(0,-0.6,0),Vector3(1,1,1),Vector3(48,0,0));
newPart2->loadModel(path4);
newPart2->setColor(color[0],color[1],color[2]);
newPart->children = new vector<Transform*>();
newPart->children->push_back(newPart2);
//Perna dianteira direita
newPart = new Transform(Vector3(-0.2, 0.2, 0), Vector3(1,-1,1), Vector3(15,0,0));
newPart->loadModel(path4);
newPart->setColor(color[0],color[1],color[2]);
children->push_back(newPart);
newPart2 = new Transform(Vector3(0,-0.6,0),Vector3(1,1,1),Vector3(48,0,0));
newPart2->loadModel(path4);
newPart2->setColor(color[0],color[1],color[2]);
newPart->children = new vector<Transform*>();
newPart->children->push_back(newPart2);
//Perna secundaria direita
newPart = new Transform(Vector3(-0.05, 0.2, 0), Vector3(1,-1,1), Vector3(15,0,0));
newPart->loadModel(path3);
newPart->setColor(color[0],color[1],color[2]);
children->push_back(newPart);
newPart2 = new Transform(Vector3(0,-0.45,0),Vector3(1,1,1),Vector3(60,0,0));
newPart2->loadModel(path3);
newPart2->setColor(color[0],color[1],color[2]);
newPart->children = new vector<Transform*>();
newPart->children->push_back(newPart2);
//Perna terciaria direita
newPart = new Transform(Vector3(0.1, 0.2, 0), Vector3(1,-1,1), Vector3(15,0,0));
newPart->loadModel(path3);
newPart->setColor(color[0],color[1],color[2]);
children->push_back(newPart);
newPart2 = new Transform(Vector3(0,-0.45,0),Vector3(1,1,1),Vector3(60,0,0));
newPart2->loadModel(path3);
newPart2->setColor(color[0],color[1],color[2]);
newPart->children = new vector<Transform*>();
newPart->children->push_back(newPart2);
//Perna traseira esquerda
newPart = new Transform(Vector3(0.25, 0.2, 0), Vector3(1,-1,1), Vector3(15,0,0));
newPart->loadModel(path4);
newPart->setColor(color[0],color[1],color[2]);
children->push_back(newPart);
newPart2 = new Transform(Vector3(0,-0.6,0),Vector3(1,1,1),Vector3(48,0,0));
newPart2->loadModel(path4);
newPart2->setColor(color[0],color[1],color[2]);
newPart->children = new vector<Transform*>();
newPart->children->push_back(newPart2);
}
void Spider3D::setColor(GLfloat r, GLfloat g, GLfloat b) {
color[0] = r;
color[1] = g;
color[2] = b;
int i;
if(children != NULL){
for(i = 1; i < children->size(); i++){
(*children)[i]->setColor(r,g,b);
(*(*children)[i]->children)[0]->setColor(r,g,b);
}
}
}
void Spider3D::turn(float axis) {
axisRot = axis;
}
void Spider3D::advance(float axis) {
axisFow = axis;
}
void Spider3D::update(double delta){
float angleVar = angularSpeed * axisRot * delta/1000;
rotation = rotation + Vector3(0,0,angleVar);
float deltaPos = fowardSpeed * axisFow * delta/1000;
Vector3 deltaPosition = Vector3(cos(rotation.z/rad2Deg)*deltaPos,sin(rotation.z/rad2Deg)*deltaPos,0);
position = position + deltaPosition;
if(axisRot == -1 && currentState == P1){
currentState = P2;
}
else if (axisRot == 1 && currentState == P1) {
currentState = P3;
}
if(axisFow != 0 && currentState == P1) {
currentState = P2;
}
if(axisRot == 0 && axisFow == 0 && currentState != P1){
currentState = P1;
}
updateLegs(delta);
}
void Spider3D::updateLegs(double delta) {
float angularSpeed = M_PI/animationTime;
float risingTime = (3.14)*(animationCounter/animationTime);
int re2,fo2,re3,fo3; //Determinam quais patas estarao levantando
if(axisFow == -1){//Aranha esta indo para frente
re2 = 0; fo2 = 1; re3 = 0; fo3 = 1;
}
else if(axisFow == 1){//Aranha esta indo para tras
re2 = 1; fo2 = 0; re3 = 1; fo3 = 0;
}
else if(axisRot == -1){//Aranha esta virando
re2 = 0; fo2 = 1; re3 = 1; fo3 = 0;
}
else if(axisRot == 1){
re2 = 1; fo2 = 0; re3 = 0; fo3 = 1;
}
else{
re2 = 0; fo2 = 0; re3 = 0; fo3 = 0;
}
if(currentState == P2){
(*children)[1]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime)*re2,0, +8*cos(angularSpeed * animationCounter));
(*children)[2]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime)*fo2,0, -4*cos(angularSpeed * animationCounter));
(*children)[3]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime)*re2,0, +4*cos(angularSpeed * animationCounter));
(*children)[4]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime)*fo2,0, -8*cos(angularSpeed * animationCounter));
(*children)[5]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime)*fo3,0, +8*cos(angularSpeed * animationCounter));
(*children)[6]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime)*re3,0, -4*cos(angularSpeed * animationCounter));
(*children)[7]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime)*fo3,0, +4*cos(angularSpeed * animationCounter));
(*children)[8]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime)*re3,0, -8*cos(angularSpeed * animationCounter));
animationCounter -= delta/1000;
}
else if(currentState == P3){
(*children)[1]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime)*fo2,0, +8*cos(angularSpeed * animationCounter));
(*children)[2]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime)*re2,0, -4*cos(angularSpeed * animationCounter));
(*children)[3]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime)*fo2,0, +4*cos(angularSpeed * animationCounter));
(*children)[4]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime)*re2,0, -8*cos(angularSpeed * animationCounter));
(*children)[5]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime)*re3,0, +8*cos(angularSpeed * animationCounter));
(*children)[6]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime)*fo3,0, -4*cos(angularSpeed * animationCounter));
(*children)[7]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime)*re3,0, +4*cos(angularSpeed * animationCounter));
(*children)[8]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime)*fo3,0, -8*cos(angularSpeed * animationCounter));
animationCounter += delta/1000;
}
else if(currentState == P1){ //Fazer suavização para o ponto de parada da animação
if((animationCounter - (animationTime)/2) > 0){
animationCounter -= delta/1000;
if(((animationCounter - (animationTime)/2) < 0)){
animationCounter = (animationTime)/2;
}
(*children)[1]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime+1.57)*fo2,0, +8*cos(angularSpeed * animationCounter));
(*children)[2]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime+1.57)*re2,0, -4*cos(angularSpeed * animationCounter));
(*children)[3]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime+1.57)*fo2,0, +4*cos(angularSpeed * animationCounter));
(*children)[4]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime+1.57)*re2,0, -8*cos(angularSpeed * animationCounter));
(*children)[5]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime+1.57)*re3,0, +8*cos(angularSpeed * animationCounter));
(*children)[6]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime+1.57)*fo3,0, -4*cos(angularSpeed * animationCounter));
(*children)[7]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime+1.57)*re3,0, +4*cos(angularSpeed * animationCounter));
(*children)[8]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime+1.57)*fo3,0, -8*cos(angularSpeed * animationCounter));
}
else if((animationCounter - (animationTime)/2) < 0) {
animationCounter += delta/1000;
if(((animationCounter - (animationTime)/2) > 0)){
animationCounter = (animationTime)/2;
}
(*children)[1]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime-1.57)*re2,0, +8*cos(angularSpeed * animationCounter));
(*children)[2]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime-1.57)*fo2,0, -4*cos(angularSpeed * animationCounter));
(*children)[3]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime-1.57)*re2,0, +4*cos(angularSpeed * animationCounter));
(*children)[4]->rotation = Vector3(-15,0,0)+Vector3(-15*sin(risingTime-1.57)*fo2,0, -8*cos(angularSpeed * animationCounter));
(*children)[5]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime-1.57)*fo3,0, +8*cos(angularSpeed * animationCounter));
(*children)[6]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime-1.57)*re3,0, -4*cos(angularSpeed * animationCounter));
(*children)[7]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime-1.57)*fo3,0, +4*cos(angularSpeed * animationCounter));
(*children)[8]->rotation = Vector3(15,0,0)+Vector3(15*sin(risingTime-1.57)*re3,0, -8*cos(angularSpeed * animationCounter));
}
}
if(animationCounter < 0){
currentState = P3;
animationCounter = 0;
}
if(animationCounter > animationTime){
currentState = P2;
animationCounter = animationTime;
}
}
| 40.896429
| 128
| 0.643699
|
Artars
|
38dc60458e367ea135611f1b6160469ccd7f898a
| 78,194
|
cpp
|
C++
|
SGXDNN/sgxdnn_main.cpp
|
goten-team/Goten
|
690f1429b62c70caec72f4010ee5b7a9786f0d25
|
[
"MIT"
] | 17
|
2020-04-28T09:18:28.000Z
|
2021-12-28T08:38:00.000Z
|
SGXDNN/sgxdnn_main.cpp
|
goten-team/Goten
|
690f1429b62c70caec72f4010ee5b7a9786f0d25
|
[
"MIT"
] | 2
|
2021-09-26T04:10:51.000Z
|
2022-03-31T05:28:25.000Z
|
SGXDNN/sgxdnn_main.cpp
|
goten-team/Goten
|
690f1429b62c70caec72f4010ee5b7a9786f0d25
|
[
"MIT"
] | 2
|
2021-09-26T05:06:17.000Z
|
2021-12-14T16:25:06.000Z
|
#define USE_EIGEN_TENSOR
#ifndef USE_SGX
#define EIGEN_USE_THREADS
#include <malloc.h>
#else
#include "Enclave.h"
#include "sgx_tseal.h"
#include "sgx_trts.h"
#include "sgx_thread.h"
#endif
#include "sgxdnn_main.hpp"
#include "randpool.hpp"
#include "utils.hpp"
#include "common_with_enclaves.h"
#include <unsupported/Eigen/CXX11/Tensor>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <iostream>
#include <memory>
#include <chrono>
#include <string>
#include <cstring>
#include <cmath>
#include <deque>
#include <unordered_map>
#include <cstdlib>
#include <mutex>
#include <stack>
#include "Crypto.h"
#include "../App/common_utils.cpp"
using namespace std;
using std::shared_ptr;
using std::make_shared;
using std::unordered_map;
using std::string;
using defer = shared_ptr<void>;
//using namespace SGXDNN;
int p_int = PrimeLimit;
float p = (float) p_int;
float mid = (float) (p_int / 2);
// some vectorized constants
__m256 p8f = _mm256_set1_ps(p);
__m256 p28f = _mm256_set1_ps(p * 2);
__m256 mid8f = _mm256_set1_ps(mid);
__m256 pmid8f = _mm256_set1_ps(p + mid);
__m256 negmid8f = _mm256_set1_ps(-mid - 1);
__m256 zero8f = _mm256_set1_ps((float)(0));
__m256 inv_shift8f = _mm256_set1_ps((float)(1.0/256));
__m256 six8f = _mm256_set1_ps((float) 6 * 256 * 256);
inline void MoveDown(float* input, float* out, int num_elements) {
for(size_t i = 0; i < num_elements; i += 8) {
const __m256 inp8f = _mm256_load_ps( &input[i] ); // blinded input
const __m256 if_geq = _mm256_cmp_ps(inp8f, mid8f, 0x0d); // unblinded >= mid
// const __m256 if_lt = _mm256_cmp_ps(inp8f, negmid8f, 0x01); // unblinded < -mid
const __m256 then8f = _mm256_sub_ps(inp8f, p8f); // unblinded - p
// const __m256 elif8f = _mm256_add_ps(inp8f, p8f); // unblinded + p
const __m256 res8f = _mm256_blendv_ps(
inp8f,
then8f,
if_geq);
_mm256_stream_ps(&out[i], res8f);
}
}
void ModP(MapMatRowMajor& m) {
DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
DtypeForCpuOp invPLimit = static_cast<DtypeForCpuOp>(1) / PrimeLimit;
m.array() = m.array() - (m * invPLimit).array() * PLimit;
}
void ModP(EigenTensor& m) {
DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
DtypeForCpuOp invPLimit = static_cast<double>(1) / PrimeLimit;
m -= (m * invPLimit).floor() * PLimit;
// m = (m > m.constant((float) HalfPrime)).select(m - (float) HalfPrime, m);
}
void ModP(MapEigenTensor& m) {
DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
DtypeForCpuOp invPLimit = static_cast<double>(1) / PrimeLimit;
m -= (m * invPLimit).floor() * PLimit;
// m = (m > m.constant((float) HalfPrime)).select(m - (float) HalfPrime, m);
}
class ChunkPool {
public:
ChunkPool(int size_pool_, int num_byte_chunk_) :
size_pool(size_pool_),
num_byte_chunk(num_byte_chunk_)
{
for (int i = 0; i < size_pool; i++) {
void* enc_chunk = (void*)memalign(64, num_byte_chunk);
chunks.push_back(enc_chunk);
chunk_ids.push(i);
}
}
int get_chunk_id() {
std::unique_lock<std::mutex> lock(stack_mutex);
if (chunk_ids.empty()) {
printf("Running out of chunks\n");
throw std::invalid_argument("Running out of chunks");
}
int res;
res = chunk_ids.top();
chunk_ids.pop();
return res;
}
void return_chunk_id(int id) {
std::unique_lock<std::mutex> lock(stack_mutex);
chunk_ids.push(id);
}
std::vector<void*> chunks;
private:
int size_pool;
int num_byte_chunk;
std::mutex stack_mutex;
std::stack<int> chunk_ids;
};
class StoreChunkPool {
public:
static shared_ptr<ChunkPool> GetChunkPool() {
static StoreChunkPool instance;
return instance.chunk_pool;
}
StoreChunkPool(StoreChunkPool const&) = delete;
void operator=(StoreChunkPool const&) = delete;
private:
StoreChunkPool() {
chunk_pool = make_shared<ChunkPool>(THREAD_POOL_SIZE * 2, STORE_CHUNK_ELEM * sizeof(DtypeForCpuOp));
}
shared_ptr<ChunkPool> chunk_pool;
};
template<typename T>
class ChunkGuard {
public:
ChunkGuard<T>(shared_ptr<ChunkPool> chunk_pool_, T*& pointer) :
chunk_pool(chunk_pool_)
{
id = chunk_pool->get_chunk_id();
pointer = (T*) chunk_pool->chunks[id];
}
~ChunkGuard<T>() {
chunk_pool->return_chunk_id(id);
}
private:
int id;
shared_ptr<ChunkPool> chunk_pool;
};
class TrustedChunkManager {
public:
static TrustedChunkManager& getInstance() {
static TrustedChunkManager instance;
return instance;
}
TrustedChunkManager(TrustedChunkManager const&) = delete;
void operator=(TrustedChunkManager const&) = delete;
IdT GetNewId() {
return id_counter++;
}
const int start_idx = 1000;
void StoreChunk(IdT id, void* src_chunk, int num_byte) {
int num_byte_enc_chunk = CalcEncDataSize(0, num_byte);
SgxEncT* enc_chunk = (SgxEncT*) get_untrusted_mem(id, num_byte_enc_chunk);
DtypeForCpuOp* src_float = (DtypeForCpuOp*) src_chunk;
encrypt((uint8_t *) src_chunk,
num_byte,
(uint8_t *) (&(enc_chunk->payload)),
(sgx_aes_gcm_128bit_iv_t *)(&(enc_chunk->reserved)),
(sgx_aes_gcm_128bit_tag_t *)(&(enc_chunk->payload_tag)));
DtypeForCpuOp* dst_chunk = (DtypeForCpuOp*)malloc(num_byte);
GetChunk(id, dst_chunk, num_byte);
uint8_t* blind_chunk;
ChunkGuard<uint8_t> guard(blind_chunks, blind_chunk);
decrypt((uint8_t *) (&(enc_chunk->payload)),
num_byte,
(uint8_t *) dst_chunk,
(sgx_aes_gcm_128bit_iv_t *)(&(enc_chunk->reserved)),
(sgx_aes_gcm_128bit_tag_t *)(&(enc_chunk->payload_tag)),
(uint8_t *) blind_chunk);
src_float = (DtypeForCpuOp*) dst_chunk;
free(dst_chunk);
}
void GetChunk(IdT id, void* dst_chunk, int num_byte) {
int num_byte_enc_chunk = CalcEncDataSize(0, num_byte);
uint8_t* blind_chunk;
ChunkGuard<uint8_t> guard(blind_chunks, blind_chunk);
SgxEncT* enc_chunk = (SgxEncT*) get_untrusted_mem(id, num_byte_enc_chunk);
decrypt((uint8_t *) (&(enc_chunk->payload)),
num_byte,
(uint8_t *) dst_chunk,
(sgx_aes_gcm_128bit_iv_t *)(&(enc_chunk->reserved)),
(sgx_aes_gcm_128bit_tag_t *)(&(enc_chunk->payload_tag)),
(uint8_t *) blind_chunk);
DtypeForCpuOp* src_float = (DtypeForCpuOp*) dst_chunk;
}
private:
TrustedChunkManager() {
max_num_byte_plain_chunk = STORE_CHUNK_ELEM * sizeof(DtypeForCpuOp);
max_num_byte_enc_chunk = CalcEncDataSize(0, max_num_byte_plain_chunk);
blind_chunks = make_shared<ChunkPool>(THREAD_POOL_SIZE, max_num_byte_plain_chunk);
}
void* get_untrusted_mem(IdT id, int num_byte) {
void* dst_buf;
bool is_diff_size = false;
auto it = untrusted_mem_holder.begin();
auto end = untrusted_mem_holder.end();
int prev_num_byte;
{
std::unique_lock <std::mutex> lock(address_mutex);
it = untrusted_mem_holder.find(id);
end = untrusted_mem_holder.end();
}
if (it == end) {
allocate_in_untrusted(&dst_buf, num_byte);
{
std::unique_lock<std::mutex> lock(address_mutex);
untrusted_mem_holder[id] = std::make_pair(dst_buf, num_byte);
}
} else {
std::unique_lock<std::mutex> lock(address_mutex);
std::tie(dst_buf, prev_num_byte) = untrusted_mem_holder[id];
if (prev_num_byte != num_byte) {
is_diff_size = true;
}
}
if (is_diff_size) {
printf("id=%u\n",id);
printf("A id has assigned with multiple size: original: %d, now: %d\n", prev_num_byte, num_byte);
throw std::invalid_argument("A id has assigned with multiple size.");
}
return dst_buf;
}
const int size_chunk_pool = THREAD_POOL_SIZE;
int max_num_byte_plain_chunk;
int max_num_byte_enc_chunk;
std::atomic<int> id_counter;
std::mutex address_mutex;
std::shared_ptr<ChunkPool> blind_chunks;
std::unordered_map<int, std::pair<void*, int>> untrusted_mem_holder;
};
template <typename Func>
void run_all_chunks(Func chunk_op, int num_elem_in_chunk, int num_elem) {
int start_chunk;
for (start_chunk = 0; start_chunk + num_elem_in_chunk <= num_elem; start_chunk += num_elem_in_chunk) {
chunk_op(start_chunk, num_elem_in_chunk);
}
if (start_chunk < num_elem) chunk_op(start_chunk, num_elem - start_chunk);
}
template <typename Func>
void run_all_chunks_for_maxpool(Func chunk_op, size_t num_elem_in_chunk, size_t num_elem, size_t num_elem_out, size_t inputhw, size_t outputhw) {
size_t start_chunk;
for (start_chunk = 0; start_chunk + num_elem_in_chunk <= num_elem; start_chunk += num_elem_in_chunk) {
chunk_op(start_chunk, num_elem_in_chunk, num_elem_out);
}
size_t remain_size = num_elem - start_chunk;
if (start_chunk < num_elem) chunk_op(start_chunk, remain_size, (remain_size/inputhw)*outputhw);
}
class SecretTen {
public:
SecretTen() {}
SecretTen(IdT TenId_, DimsT* Dims_) : TenId(TenId_), Dims(*Dims_) { Init(); }
~SecretTen() {
for (auto& it: PrgStateHolder) free(it.second);
}
int GetNumElem() { return Dims.dim0 * Dims.dim1 * Dims.dim2 * Dims.dim3; }
int GetSizeInByte() { return GetNumElem() * sizeof(DtypeForCpuOp); }
void Init() {
DtypeForCpuOp* store_chunk;
ChunkGuard<DtypeForCpuOp> guard(StoreChunkPool::GetChunkPool(), store_chunk);
auto& chunk_manager = TrustedChunkManager::getInstance();
auto chunk_op = [&](int start, int num_elem_in_op) {
int chunk_id = chunk_manager.GetNewId();
ChunkIds.push_back(chunk_id);
chunk_manager.StoreChunk(chunk_id, store_chunk, num_elem_in_op * sizeof(DtypeForCpuOp));
};
run_all_chunks(chunk_op, STORE_CHUNK_ELEM, GetNumElem());
}
int GetChunkId(int start) {
if (start >= GetNumElem()) {
printf("The start exceed the size of the tensor.\n");
throw std::invalid_argument("The start exceed the size of the tensor.");
}
return ChunkIds[start / STORE_CHUNK_ELEM];
}
void GetStoreChunk(int start, DtypeForCpuOp* store_chunk, int num_byte) {
auto& chunk_manager = TrustedChunkManager::getInstance();
int chunk_id = GetChunkId(start);
chunk_manager.StoreChunk(chunk_id, store_chunk, num_byte * sizeof(DtypeForCpuOp));
}
void SetTen(DtypeForCpuOp* Arr) {
auto& chunk_manager = TrustedChunkManager::getInstance();
auto chunk_op = [&](int start, int num_elem_in_op) {
int chunk_id = GetChunkId(start);
DtypeForCpuOp* src_arr = Arr + start;
chunk_manager.StoreChunk(chunk_id, src_arr, num_elem_in_op * sizeof(DtypeForCpuOp));
};
run_all_chunks(chunk_op, STORE_CHUNK_ELEM, GetNumElem());
}
void GetTen(DtypeForCpuOp* Arr) {
auto& chunk_manager = TrustedChunkManager::getInstance();
auto chunk_op = [&](int start, int num_elem_in_op) {
int chunk_id = GetChunkId(start);
DtypeForCpuOp* dst_arr = Arr + start;
chunk_manager.GetChunk(chunk_id, dst_arr, num_elem_in_op * sizeof(DtypeForCpuOp));
};
run_all_chunks(chunk_op, STORE_CHUNK_ELEM, GetNumElem());
}
void SetSeed(uint64_t RawSeed) {
SeedT seed;
memset(seed, 0, sizeof(SeedT));
auto TmpRawSeed = RawSeed;
for (int i = 0; TmpRawSeed > 0; i++) {
seed[i] = (uint8_t) (TmpRawSeed & ((1 << 9) - 1));
TmpRawSeed >>= 8;
}
PrgStateHolder[RawSeed] = (aes_stream_state*)memalign(16, sizeof(aes_stream_state));
InitPrgWithSeed(PrgStateHolder[RawSeed], seed);
}
void GetRandom(DtypeForCpuOp* DstArr, uint64_t RawSeed) {
auto PrgState = PrgStateHolder[RawSeed];
DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
DtypeForCpuOp invPLimit = static_cast<double>(1) / PrimeLimit;
auto chunk_op = [&](int start, int num_elem_in_op) {
float* input = DstArr + start;
get_r(PrgState, (uint8_t*) input, num_elem_in_op * sizeof(DtypeForCpuOp), 9);
for(size_t j = 0; j < num_elem_in_op; j++) {
input[j] -= floor(input[j] * invPLimit) * PLimit;
input[j] = (input[j] >= mid) ? (input[j] - p) : input[j];
}
};
run_all_chunks(chunk_op, WORK_CHUNK_ELEM, GetNumElem());
}
void GetShare(DtypeForCpuOp* DstArr, uint64_t RawSeed) {
auto PrgState = PrgStateHolder[RawSeed];
const DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
const DtypeForCpuOp invPLimit = static_cast<double>(1) / PrimeLimit;
auto& chunk_manager = TrustedChunkManager::getInstance();
// DtypeForCpuOp* store_chunk;
// ChunkGuard<DtypeForCpuOp> guard(StoreChunkPool::GetChunkPool(), store_chunk);
DtypeForCpuOp* store_chunk = (DtypeForCpuOp*)memalign(64, STORE_CHUNK_ELEM * sizeof(DtypeForCpuOp));
auto store_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(GetChunkId(start_store_chunk), store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
auto chunk_op = [&](int start, int num_elem_in_op) {
float *input = DstArr + start_store_chunk + start;
float *original = store_chunk + start;
get_r(PrgState, (uint8_t *) input, num_elem_in_op * sizeof(DtypeForCpuOp), 9);
for (size_t j = 0; j < num_elem_in_op; j++) {
input[j] = original[j] - input[j];
input[j] -= floor(input[j] * invPLimit) * PLimit;
input[j] = (input[j] >= mid) ? (input[j] - p) : input[j];
}
};
run_all_chunks(chunk_op, WORK_CHUNK_ELEM, num_elem_in_store_chunk);
};
run_all_chunks(store_chunk_op, STORE_CHUNK_ELEM, GetNumElem());
free(store_chunk);
}
IdT TenId;
DimsT Dims;
vector<int> ChunkIds;
unordered_map<uint64_t, aes_stream_state*> PrgStateHolder;
};
unordered_map<IdT, shared_ptr<SecretTen>> SecretTenHolder;
unordered_map<IdT, shared_ptr<EigenTensor>> TensorHolder;
shared_ptr<SecretTen> GetTenById(IdT TenId) {
return SecretTenHolder[TenId];
}
unordered_map<uint64_t, DtypeForCpuOp> quantize_exp;
static inline float uint32_to_float(uint32_t x) {
const union { uint32_t i; float d; } u = { .i = UINT32_C(0x7F) << 23 | x >> 9 };
return u.d - 1.0f;
}
static inline float float_to_uniform(uint32_t x) {
const union { uint32_t i; float d; } u = { .i = (((UINT32_C(0x7F) << 23) | x) << 2) >> 2 };
return u.d - 1.0f;
}
// http://prng.di.unimi.it/
class Xoshiro256 {
public:
Xoshiro256() {}
Xoshiro256(uint64_t raw_seed) {
set_seed(raw_seed);
}
void set_seed(uint64_t raw_seed) {
s[0] = raw_seed;
}
static inline uint64_t rotl(const uint64_t x, int k) {
return (x << k) | (x >> (64 - k));
}
uint64_t next(void) {
const uint64_t result = rotl(s[0] + s[3], 23) + s[0];
const uint64_t t = s[1] << 17;
s[2] ^= s[0];
s[3] ^= s[1];
s[1] ^= s[2];
s[0] ^= s[3];
s[2] ^= t;
s[3] = rotl(s[3], 45);
return result;
}
void rand_like(float* arr, uint64_t n_elem) {
if (n_elem % 2 != 0) {
printf("n_elem has to be even.\n");
throw string("n_elem has to be even.");
}
for (int i = 0; i < n_elem; i+=2) {
const uint64_t rnd = next();
const uint32_t b = rnd & ((((uint64_t) 1) << 32) - 1);
const uint32_t a = rnd >> 32;
arr[i] = uint32_to_float(a);
arr[i+1] = uint32_to_float(b);
}
}
uint64_t s[4] = {};
};
class Xoshiro128 {
public:
Xoshiro128() {}
Xoshiro128(uint64_t raw_seed) {
set_seed(raw_seed);
}
void set_seed(uint64_t raw_seed) {
s[0] = raw_seed;
}
static inline uint64_t rotl(const uint64_t x, int k) {
return (x << k) | (x >> (64 - k));
}
uint64_t next(void) {
const uint64_t s0 = s[0];
uint64_t s1 = s[1];
const uint64_t result = rotl(s0 + s1, 17) + s0;
s1 ^= s0;
s[0] = rotl(s0, 49) ^ s1 ^ (s1 << 21); // a, b
s[1] = rotl(s1, 28); // c
return result;
}
uint64_t s[2] = {};
};
unordered_map<uint64_t, shared_ptr<Xoshiro256>> fast_rngs;
//unordered_map<uint64_t, shared_ptr<Xoshiro128>> fast_rngs;
shared_ptr<Xoshiro256> get_fast_rng(uint64_t tag) {
if (fast_rngs.find(tag) == fast_rngs.end()) {
fast_rngs[tag] = make_shared<Xoshiro256>(tag);
}
return fast_rngs[tag];
}
void quantize_stochastic(shared_ptr<SecretTen> src_ten, shared_ptr<SecretTen> dst_ten, uint64_t quantize_tag) {
const int bits = 8;
const int ebit = 8;
const DtypeForCpuOp lower_limit = -pow(2, (bits - 1));
const DtypeForCpuOp upper_limit = pow(2, (bits - 1)) - 1;
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp *store_chunk, *dst_store_chunk;
ChunkGuard<DtypeForCpuOp> guard(StoreChunkPool::GetChunkPool(), store_chunk);
ChunkGuard<DtypeForCpuOp> dst_guard(StoreChunkPool::GetChunkPool(), dst_store_chunk);
//DtypeForCpuOp max_entry = 0;
const __m256 neg8f = _mm256_set1_ps(-0.0f);
__m256 tmp8f = _mm256_set1_ps(0.0f);
auto get_max_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
int chunk_id = src_ten->GetChunkId(start_store_chunk);
chunk_manager.GetChunk(chunk_id, store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
for(uint64_t i=0;i<num_elem_in_store_chunk;i+=8){
const __m256 inp8f = _mm256_load_ps(&store_chunk[i]);
const __m256 abs8f = _mm256_andnot_ps(neg8f, inp8f);
const __m256 if_eq = _mm256_cmp_ps(inp8f, tmp8f, 0x0e);
tmp8f = _mm256_blendv_ps(tmp8f, inp8f, if_eq);
}
//MapEigenVector src_vecmap(store_chunk, num_elem_in_store_chunk);
//max_entry = std::max(max_entry, src_vecmap.cwiseAbs().maxCoeff());
};
run_all_chunks(get_max_chunk_op, STORE_CHUNK_ELEM, src_ten->GetNumElem());
_mm256_stream_ps(dst_store_chunk, tmp8f);
for(int i=4;i>0;i=i>>1){
copy(dst_store_chunk+i,dst_store_chunk+2*i,dst_store_chunk+8);
const __m256 inp8f = _mm256_load_ps(dst_store_chunk);
const __m256 inp8f2 = _mm256_load_ps(&dst_store_chunk[8]);
const __m256 if_eq = _mm256_cmp_ps(inp8f, inp8f2, 0x0e);
const __m256 res8f = _mm256_blendv_ps(inp8f2, inp8f, if_eq);
_mm256_stream_ps(dst_store_chunk, res8f);
}
if(1){
dst_store_chunk[0] = (dst_store_chunk[0] == 0) ? 0: floor(log2(dst_store_chunk[0]));
const __m256 inp8f = _mm256_load_ps(dst_store_chunk);
//tmp8f = _mm256_set1_ps(pow(-2, (ebit - 1)));
//__m256 if_gt = _mm256_cmp_ps(inp8f, tmp8f, 0x0e);
//__m256 res8f = _mm256_blendv_ps(tmp8f, inp8f, if_gt);
tmp8f = _mm256_set1_ps(pow(2, (ebit - 1)) - 1);
__m256 if_gt = _mm256_cmp_ps(inp8f, tmp8f, 0x0e);
tmp8f = _mm256_blendv_ps(inp8f, tmp8f, if_gt);
_mm256_stream_ps(dst_store_chunk, tmp8f);
}
DtypeForCpuOp exp = dst_store_chunk[0];
// DtypeForCpuOp exp = (max_entry == 0) ? 0 : floor(log2(max_entry));
// exp = std::min(std::max(exp, (DtypeForCpuOp) pow(-2, (ebit - 1))), (DtypeForCpuOp) pow(2, (ebit - 1) - 1));
quantize_exp[quantize_tag] = exp;
DtypeForCpuOp enlarge_factor = pow(2, -exp + (bits - 2));
auto& xor_rnd = *get_fast_rng(quantize_tag);
auto store_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(src_ten->GetChunkId(start_store_chunk), store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
chunk_manager.GetChunk(dst_ten->GetChunkId(start_store_chunk), dst_store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
auto chunk_op = [&](int start, int num_elem_in_op) {
float *input = store_chunk + start;
float *output = dst_store_chunk + start;
xor_rnd.rand_like(output, num_elem_in_op);
for(uint64_t i=0;i<num_elem_in_op;i+=8){
tmp8f = _mm256_set1_ps(enlarge_factor);
const __m256 inp8f = _mm256_load_ps(&input[i]);
const __m256 out8f = _mm256_load_ps(&output[i]);
const __m256 mul8f = _mm256_mul_ps(inp8f, tmp8f);
const __m256 add8f = _mm256_add_ps(mul8f, out8f);
const __m256 flo8f = _mm256_floor_ps(add8f);
tmp8f = _mm256_set1_ps(lower_limit);
__m256 if_gt = _mm256_cmp_ps(flo8f, tmp8f, 0x0e);
__m256 res8f = _mm256_blendv_ps(tmp8f, flo8f, if_gt);
tmp8f = _mm256_set1_ps(upper_limit);
if_gt = _mm256_cmp_ps(res8f, tmp8f, 0x0e);
res8f = _mm256_blendv_ps(res8f, tmp8f, if_gt);
_mm256_stream_ps(&output[i], res8f);
}
//MapEigenTensor in_map = MapEigenTensor(input, 1, 1, 1, num_elem_in_op);
//MapEigenTensor out_map = MapEigenTensor(output, 1, 1, 1, num_elem_in_op);
//out_map = (in_map * enlarge_factor + out_map).floor().cwiseMax(lower_limit).cwiseMin(upper_limit);
};
run_all_chunks(chunk_op, WORK_CHUNK_ELEM, num_elem_in_store_chunk);
//add
chunk_manager.StoreChunk(dst_ten->GetChunkId(start_store_chunk), dst_store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
//add
};
run_all_chunks(store_chunk_op, STORE_CHUNK_ELEM, src_ten->GetNumElem());
}
void dequantize_stochastic(shared_ptr<SecretTen> src_ten, shared_ptr<SecretTen> dst_ten,
uint64_t x_tag, uint64_t y_tag) {
const int bits = 8;
DtypeForCpuOp x_exp = quantize_exp[x_tag];
DtypeForCpuOp y_exp = quantize_exp[y_tag];
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp *store_chunk, *dst_store_chunk;
ChunkGuard<DtypeForCpuOp> guard(StoreChunkPool::GetChunkPool(), store_chunk);
ChunkGuard<DtypeForCpuOp> dst_guard(StoreChunkPool::GetChunkPool(), dst_store_chunk);
auto store_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(src_ten->GetChunkId(start_store_chunk), store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
chunk_manager.GetChunk(dst_ten->GetChunkId(start_store_chunk), dst_store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
MapEigenTensor src_map = MapEigenTensor(store_chunk, 1, 1, 1, num_elem_in_store_chunk);
MapEigenTensor dst_map = MapEigenTensor(dst_store_chunk, 1, 1, 1, num_elem_in_store_chunk);
DtypeForCpuOp shrink_factor = pow(2, x_exp - (bits - 2) + y_exp - (bits - 2));
dst_map = src_map * shrink_factor;
};
run_all_chunks(store_chunk_op, STORE_CHUNK_ELEM, src_ten->GetNumElem());
}
DtypeForCpuOp* get_small_chunk(
shared_ptr<SecretTen> tensor,
vector<std::pair<shared_ptr<SecretTen>, DtypeForCpuOp*>>& small_chunks) {
int size_in_byte = tensor->GetSizeInByte();
DtypeForCpuOp* arr = (DtypeForCpuOp*) memalign(64, size_in_byte);
auto& chunk_manager = TrustedChunkManager::getInstance();
chunk_manager.GetChunk(tensor->GetChunkId(0), arr, size_in_byte);
small_chunks.emplace_back(tensor, arr);
return arr;
}
void store_small_chunks(vector<std::pair<shared_ptr<SecretTen>, DtypeForCpuOp*>>& small_chunks) {
for (auto& x : small_chunks) {
auto tensor = x.first;
auto arr = x.second;
auto& chunk_manager = TrustedChunkManager::getInstance();
int size_in_byte = tensor->GetSizeInByte();
chunk_manager.StoreChunk(tensor->GetChunkId(0), arr, size_in_byte);
free(arr);
}
}
class BatchnormBuffer {
public:
BatchnormBuffer(){}
BatchnormBuffer(IdT FunId_) : FunId(FunId_) {
NumBatchesTrackedArr = 0;
BackwardState = false;
}
~BatchnormBuffer() = default;
void init(
IdT input, IdT output, IdT gamma, IdT beta,
IdT der_input, IdT der_output, IdT der_gamma, IdT der_beta,
IdT run_mean, IdT run_var, IdT cur_mean, IdT cur_var,
IdT mu,
uint32_t batch_, uint32_t channel_, uint32_t height_, uint32_t width_,
int affine_, int is_cumulative_, float momentum_, float epsilon_) {
input_tensor = GetTenById(input);
output_tensor = GetTenById(output);
der_input_tensor = GetTenById(der_input);
der_output_tensor = GetTenById(der_output);
mu_tensor = GetTenById(mu);
// size = num_channel * sizeof(byte)
gamma_tensor = GetTenById(gamma);
beta_tensor = GetTenById(beta);
der_gamma_tensor = GetTenById(der_gamma);
der_beta_tensor = GetTenById(der_beta);
run_mean_tensor = GetTenById(run_mean);
run_var_tensor = GetTenById(run_var);
cur_mean_tensor = GetTenById(cur_mean);
cur_var_tensor = GetTenById(cur_var);
batch = batch_;
channel = channel_;
height = height_;
width = width_;
Affine = affine_;
momentum = momentum_;
epsilon = epsilon_;
is_cumulative = is_cumulative_;
num_rows = channel * height * width;
num_rows_in_channel = height * width;
total_n = height * width * batch;
default_num_batches_per_chunk = std::min(STORE_CHUNK_ELEM, input_tensor->GetNumElem()) / num_rows;
if (STORE_CHUNK_ELEM % num_rows != 0) {
printf("STORE_CHUNK_ELEM % num_rows != 0\n");
return;
}
}
DtypeForCpuOp get_fraction_bag(int num_elem_in_chunk) {
int batch_in_chunk = num_elem_in_chunk / num_rows;
return ((DtypeForCpuOp) batch_in_chunk / batch);
}
int get_num_batches_per_chunk(int num_elem_in_chunk) {
return num_elem_in_chunk / num_rows;
}
void forward(int training) {
Training = training;
vector<std::pair<shared_ptr<SecretTen>, DtypeForCpuOp*>> small_chunks;
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp *data_chunk, *mu_chunk;
ChunkGuard<DtypeForCpuOp> data_guard(StoreChunkPool::GetChunkPool(), data_chunk);
ChunkGuard<DtypeForCpuOp> mu_guard(StoreChunkPool::GetChunkPool(), mu_chunk);
EigenMatrixMap data_mat(data_chunk, num_rows, default_num_batches_per_chunk);
EigenMatrixMap mu_mat(mu_chunk, num_rows, default_num_batches_per_chunk);
DtypeForCpuOp *gamma_chunk = get_small_chunk(gamma_tensor, small_chunks);
DtypeForCpuOp *beta_chunk = get_small_chunk(beta_tensor, small_chunks);
DtypeForCpuOp *run_mean_chunk = get_small_chunk(run_mean_tensor, small_chunks);
DtypeForCpuOp *run_var_chunk = get_small_chunk(run_var_tensor, small_chunks);
DtypeForCpuOp *cur_mean_chunk = get_small_chunk(cur_mean_tensor, small_chunks);
DtypeForCpuOp *cur_var_chunk = get_small_chunk(cur_var_tensor, small_chunks);
if (training) {
NumBatchesTrackedArr += 1;
const DtypeForCpuOp chosen_momentum = (is_cumulative) ? (1 / (DtypeForCpuOp) NumBatchesTrackedArr) : momentum;
fill(cur_mean_chunk, cur_mean_chunk + channel, 0);
fill(cur_var_chunk, cur_var_chunk + channel, epsilon);
run_all_chunks([&](int start_store_chunk, int num_elem_in_store_chunk) {
int num_batches_per_chunk = get_num_batches_per_chunk(num_elem_in_store_chunk);
int chunk_size_in_byte = num_elem_in_store_chunk * sizeof(DtypeForCpuOp);
chunk_manager.GetChunk(input_tensor->GetChunkId(start_store_chunk), data_chunk, chunk_size_in_byte);
for(uint32_t i = 0; i < channel; i++) {
auto data_block = data_mat.block(i * num_rows_in_channel, 0, num_rows_in_channel, num_batches_per_chunk);
cur_mean_chunk[i] += data_block.mean() * get_fraction_bag(num_elem_in_store_chunk);
}
}, STORE_CHUNK_ELEM, input_tensor->GetNumElem());
run_all_chunks([&](int start_store_chunk, int num_elem_in_store_chunk) {
int num_batches_per_chunk = get_num_batches_per_chunk(num_elem_in_store_chunk);
int chunk_size_in_byte = num_elem_in_store_chunk * sizeof(DtypeForCpuOp);
chunk_manager.GetChunk(input_tensor->GetChunkId(start_store_chunk), data_chunk, chunk_size_in_byte);
for(uint32_t i = 0; i < channel; i++) {
auto data_block = data_mat.block(i * num_rows_in_channel, 0, num_rows_in_channel, num_batches_per_chunk);
auto mu_block = mu_mat.block(i * num_rows_in_channel, 0, num_rows_in_channel, num_batches_per_chunk);
mu_block = data_block.array() - cur_mean_chunk[i];
cur_var_chunk[i] += (mu_block).cwiseProduct(mu_block).mean() * get_fraction_bag(num_elem_in_store_chunk);
}
chunk_manager.StoreChunk(mu_tensor->GetChunkId(start_store_chunk), mu_chunk, chunk_size_in_byte);
}, STORE_CHUNK_ELEM, input_tensor->GetNumElem());
run_all_chunks([&](int start_store_chunk, int num_elem_in_store_chunk) {
int num_batches_per_chunk = get_num_batches_per_chunk(num_elem_in_store_chunk);
int chunk_size_in_byte = num_elem_in_store_chunk * sizeof(DtypeForCpuOp);
chunk_manager.GetChunk(mu_tensor->GetChunkId(start_store_chunk), data_chunk, chunk_size_in_byte);
for(uint32_t i = 0; i < channel; i++) {
auto data_block = data_mat.block(i * num_rows_in_channel, 0, num_rows_in_channel, num_batches_per_chunk);
if (Affine) {
data_block = (data_block.array() / sqrt(cur_var_chunk[i])) * gamma_chunk[i] + beta_chunk[i];
} else {
data_block = data_block / sqrt(cur_var_chunk[i]);
}
}
chunk_manager.StoreChunk(output_tensor->GetChunkId(start_store_chunk), data_chunk, chunk_size_in_byte);
}, STORE_CHUNK_ELEM, input_tensor->GetNumElem());
for (int i = 0; i < channel; i++) {
run_mean_chunk[i] = (cur_mean_chunk[i] - run_mean_chunk[i]) * chosen_momentum + run_mean_chunk[i];
run_var_chunk[i] = (cur_var_chunk[i] - run_var_chunk[i]) * chosen_momentum + run_var_chunk[i];
}
} else {
run_all_chunks([&](int start_store_chunk, int num_elem_in_store_chunk) {
int num_batches_per_chunk = get_num_batches_per_chunk(num_elem_in_store_chunk);
int chunk_size_in_byte = num_elem_in_store_chunk * sizeof(DtypeForCpuOp);
chunk_manager.GetChunk(input_tensor->GetChunkId(start_store_chunk), data_chunk, chunk_size_in_byte);
for(uint32_t i = 0; i < channel; i++) {
auto data_block = data_mat.block(i * num_rows_in_channel, 0, num_rows_in_channel, num_batches_per_chunk);
data_block = data_block.array() - run_mean_chunk[i];
if (Affine) {
data_block = (data_block.array() / sqrt(run_var_chunk[i])) * gamma_chunk[i] + beta_chunk[i];
} else {
data_block = data_block / sqrt(run_var_chunk[i]);
}
}
chunk_manager.StoreChunk(output_tensor->GetChunkId(start_store_chunk), data_chunk, chunk_size_in_byte);
}, STORE_CHUNK_ELEM, input_tensor->GetNumElem());
}
store_small_chunks(small_chunks);
BackwardState = true;
}
void backward() {
if (!BackwardState) {
printf("Forward Batch Normalization has not been done.\n");
return;
}
vector<std::pair<shared_ptr<SecretTen>, DtypeForCpuOp*>> small_chunks;
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp *data_chunk, *mu_chunk;
ChunkGuard<DtypeForCpuOp> data_guard(StoreChunkPool::GetChunkPool(), data_chunk);
ChunkGuard<DtypeForCpuOp> mu_guard(StoreChunkPool::GetChunkPool(), mu_chunk);
EigenMatrixMap data_mat(data_chunk, num_rows, default_num_batches_per_chunk);
EigenMatrixMap mu_mat(mu_chunk, num_rows, default_num_batches_per_chunk);
DtypeForCpuOp *gamma_chunk = get_small_chunk(gamma_tensor, small_chunks);
DtypeForCpuOp *beta_chunk = get_small_chunk(beta_tensor, small_chunks);
DtypeForCpuOp *der_gamma_chunk = get_small_chunk(der_gamma_tensor, small_chunks);
DtypeForCpuOp *der_beta_chunk = get_small_chunk(der_beta_tensor, small_chunks);
DtypeForCpuOp *run_mean_chunk = get_small_chunk(run_mean_tensor, small_chunks);
DtypeForCpuOp *run_var_chunk = get_small_chunk(run_var_tensor, small_chunks);
DtypeForCpuOp *cur_mean_chunk = get_small_chunk(cur_mean_tensor, small_chunks);
DtypeForCpuOp *cur_var_chunk = get_small_chunk(cur_var_tensor, small_chunks);
fill(der_beta_chunk, der_beta_chunk + channel, 0);
fill(der_gamma_chunk, der_gamma_chunk + channel, 0);
run_all_chunks([&](int start_store_chunk, int num_elem_in_store_chunk) {
int num_batches_per_chunk = get_num_batches_per_chunk(num_elem_in_store_chunk);
int chunk_size_in_byte = num_elem_in_store_chunk * sizeof(DtypeForCpuOp);
chunk_manager.GetChunk(der_output_tensor->GetChunkId(start_store_chunk), data_chunk, chunk_size_in_byte);
chunk_manager.GetChunk(mu_tensor->GetChunkId(start_store_chunk), mu_chunk, chunk_size_in_byte);
for(uint32_t i = 0; i < channel; i++) {
auto data_block = data_mat.block(i * num_rows_in_channel, 0, num_rows_in_channel, num_batches_per_chunk);
auto mu_block = mu_mat.block(i * num_rows_in_channel, 0, num_rows_in_channel, num_batches_per_chunk);
DtypeForCpuOp variance = (Training) ? cur_var_chunk[i] : run_var_chunk[i];
der_gamma_chunk[i] += mu_block.cwiseProduct(data_block).sum() / sqrt(variance);
der_beta_chunk[i] += data_block.sum();
}
}, STORE_CHUNK_ELEM, input_tensor->GetNumElem());
run_all_chunks([&](int start_store_chunk, int num_elem_in_store_chunk) {
int num_batches_per_chunk = get_num_batches_per_chunk(num_elem_in_store_chunk);
int chunk_size_in_byte = num_elem_in_store_chunk * sizeof(DtypeForCpuOp);
chunk_manager.GetChunk(der_output_tensor->GetChunkId(start_store_chunk), data_chunk, chunk_size_in_byte);
chunk_manager.GetChunk(mu_tensor->GetChunkId(start_store_chunk), mu_chunk, chunk_size_in_byte);
for(uint32_t i = 0; i < channel; i++) {
auto data_block = data_mat.block(i * num_rows_in_channel, 0, num_rows_in_channel, num_batches_per_chunk);
auto mu_block = mu_mat.block(i * num_rows_in_channel, 0, num_rows_in_channel, num_batches_per_chunk);
DtypeForCpuOp variance = (Training) ? cur_var_chunk[i] : run_var_chunk[i];
DtypeForCpuOp gamma = (Affine) ? gamma_chunk[i] : 1;
mu_block *= der_gamma_chunk[i] / sqrt(variance);
variance = sqrt(variance);
// der_gamma_chunk[i] /= variance;
variance = gamma / ((DtypeForCpuOp) total_n * variance);
data_block = total_n * data_block.array() - der_beta_chunk[i] - mu_block.array();
data_block *= variance;
}
chunk_manager.StoreChunk(der_input_tensor->GetChunkId(start_store_chunk), data_chunk, chunk_size_in_byte);
}, STORE_CHUNK_ELEM, input_tensor->GetNumElem());
store_small_chunks(small_chunks);
BackwardState = false;
}
IdT FunId;
int batch;
int channel;
int height;
int width;
DtypeForCpuOp momentum;
DtypeForCpuOp epsilon;
bool is_cumulative;
bool BackwardState;
bool Affine;
bool Training;
int num_rows;
int num_rows_in_channel;
int total_n;
int default_num_batches_per_chunk;
int NumBatchesTrackedArr = 0;
shared_ptr<SecretTen> input_tensor;
shared_ptr<SecretTen> output_tensor;
shared_ptr<SecretTen> der_input_tensor;
shared_ptr<SecretTen> der_output_tensor;
shared_ptr<SecretTen> mu_tensor;
shared_ptr<SecretTen> gamma_tensor;
shared_ptr<SecretTen> beta_tensor;
shared_ptr<SecretTen> der_gamma_tensor;
shared_ptr<SecretTen> der_beta_tensor;
shared_ptr<SecretTen> run_mean_tensor;
shared_ptr<SecretTen> run_var_tensor;
shared_ptr<SecretTen> cur_mean_tensor;
shared_ptr<SecretTen> cur_var_tensor;
};
class MaxpoolBuffer {
public:
MaxpoolBuffer() {}
MaxpoolBuffer(IdT FunId_, IdT TenIdin_trans_, IdT TenIdout_trans_) : FunId(FunId_), TenIdin_trans(TenIdin_trans_), TenIdout_trans(TenIdout_trans_) { }
~MaxpoolBuffer() = default;
IdT get_TenIdin_trans(){
return TenIdin_trans;
}
IdT get_TenIdout_trans(){
return TenIdout_trans;
}
//if NCHW->WHCN N=CN M=HW
void transpose(const DtypeForCpuOp *src, DtypeForCpuOp *dst, const size_t N, const size_t M) {
#pragma omp parallel for
for(size_t n = 0; n<N*M; n++) {
size_t i = n/N;
size_t j = n%N;
dst[n] = src[M*j + i];
}
}
inline void transpose4x4_SSE(const float *A, float *B, const uint32_t lda, const uint32_t ldb) {
__m128 row1 = _mm_load_ps(&A[0*lda]);
__m128 row2 = _mm_load_ps(&A[1*lda]);
__m128 row3 = _mm_load_ps(&A[2*lda]);
__m128 row4 = _mm_load_ps(&A[3*lda]);
_MM_TRANSPOSE4_PS(row1, row2, row3, row4);
_mm_store_ps(&B[0*ldb], row1);
_mm_store_ps(&B[1*ldb], row2);
_mm_store_ps(&B[2*ldb], row3);
_mm_store_ps(&B[3*ldb], row4);
}
inline void transpose_block_SSE4x4(const float *A, float *B, const uint32_t lda, const uint32_t ldb ,const int block_size) {
#pragma omp parallel for
for(uint32_t i=0; i<ldb; i+=block_size) {
for(uint32_t j=0; j<lda; j+=block_size) {
uint32_t max_i2 = i+block_size < ldb ? i + block_size : ldb;
uint32_t max_j2 = j+block_size < lda ? j + block_size : lda;
for(uint32_t i2=i; i2<max_i2; i2+=4) {
for(uint32_t j2=j; j2<max_j2; j2+=4) {
transpose4x4_SSE(&A[i2*lda +j2], &B[j2*ldb + i2], lda, ldb);
}
}
}
}
}
inline void MaxpoolAVX(const uint32_t num_img, float* input, float* output){
#pragma omp parallel for
for(size_t i=0; i<num_img; i+=8){
const __m256 inp8f = _mm256_load_ps(&input[i]);
const __m256 out8f = _mm256_load_ps(&output[i]);
const __m256 if_lq = _mm256_cmp_ps(out8f, inp8f, 0x01);
const __m256 res8f = _mm256_blendv_ps(out8f, inp8f, if_lq);
_mm256_stream_ps(&output[i], res8f);
}
}
inline void MaxpoolbackAVX(const uint32_t num_img, float* input, float* output, float* dinput, float* doutput){
#pragma omp parallel for
for(size_t i=0; i<num_img; i+=8){
const __m256 inp8f = _mm256_load_ps(&input[i]);
const __m256 out8f = _mm256_load_ps(&output[i]);
const __m256 din8f = _mm256_load_ps(&dinput[i]);
const __m256 dout8f = _mm256_load_ps(&doutput[i]);
const __m256 if_eq = _mm256_cmp_ps(out8f, inp8f, 0x00);
const __m256 sum8f = _mm256_add_ps(din8f, dout8f);
const __m256 res8f = _mm256_blendv_ps(din8f, sum8f, if_eq); // define dinput
const __m256 res28f = _mm256_blendv_ps(dout8f, zero8f, if_eq); // redefine doutput
_mm256_store_ps(&dinput[i], res8f);
_mm256_stream_ps(&doutput[i], res28f);
}
}
void forward(
shared_ptr<SecretTen> ten_in, shared_ptr<SecretTen> ten_out,
shared_ptr<SecretTen> ten_in_trans, shared_ptr<SecretTen> ten_out_trans,
uint32_t batch, uint32_t channel,uint32_t input_height, uint32_t input_width,
uint32_t output_height, uint32_t output_width, uint32_t filter_height,
uint32_t filter_width, uint32_t row_stride, uint32_t col_stride) {
const uint32_t inputhw = input_height*input_width;
const uint32_t num_img_in_storechunk = STORE_CHUNK_ELEM/inputhw;
if(STORE_CHUNK_ELEM % inputhw != 0){
printf("STORE_CHUNK_ELEM %% inputhw != 0\n");
return;
}
//if (num_img_in_storechunk % 8 != 0){
// printf("STORE_CHUNK_ELEM/inputhw is not divisible by 8!\n");
// return;
//}
const uint32_t outputhw = output_height * output_width;
uint32_t outputsize_in_storechunk = num_img_in_storechunk * outputhw;
const uint32_t total_size = batch * channel * inputhw;
size_t idx_out=0;
size_t idx_tmp=0;
size_t size_of_store_chunk = STORE_CHUNK_ELEM * sizeof(float);
bool if_use_SSE_out =(outputhw%4==0);
float* chunk_in, *chunk_out, *chunk_in_trans, *chunk_out_trans, *chunk_tmp;
auto& chunk_manager = TrustedChunkManager::getInstance();
ChunkGuard<DtypeForCpuOp> guard_in(StoreChunkPool::GetChunkPool(), chunk_in);
ChunkGuard<DtypeForCpuOp> guard_out(StoreChunkPool::GetChunkPool(), chunk_out);
ChunkGuard<DtypeForCpuOp> guard_int(StoreChunkPool::GetChunkPool(), chunk_in_trans);
ChunkGuard<DtypeForCpuOp> guard_outt(StoreChunkPool::GetChunkPool(), chunk_out_trans);
ChunkGuard<DtypeForCpuOp> guard_tmp(StoreChunkPool::GetChunkPool(), chunk_tmp); // chunk_tmp is used to store output temporarily
auto chunk_op = [&](size_t start_chunk, size_t num_elem_in, size_t num_elem_out) {
// printf("maxpooling forward in enclave. start_chunk: %d\n", start_chunk);
chunk_manager.GetChunk(ten_in->GetChunkId(start_chunk), chunk_in, num_elem_in * sizeof(DtypeForCpuOp));
transpose_block_SSE4x4(chunk_in, chunk_in_trans, inputhw, num_img_in_storechunk, 8);
chunk_manager.StoreChunk(ten_in_trans->GetChunkId(start_chunk), chunk_in_trans, size_of_store_chunk);
fill(chunk_out_trans, chunk_out_trans + outputsize_in_storechunk, std::numeric_limits<DtypeForCpuOp>::lowest());
for(uint32_t h = 0; h < input_height; ++h) {
for(uint32_t w = 0; w < input_width; ++w) {
// (h_start, h_end) * (w_start, w_end) is the range that the input
// vector projects to.
const uint32_t h_start = (h < filter_height)
? 0
: (h - filter_height) / row_stride + 1;
const uint32_t h_end = std::min(h / row_stride + 1, output_height);
const uint32_t w_start = (w < filter_width)
? 0
: (w - filter_width) / col_stride + 1;
const uint32_t w_end = std::min(w / col_stride + 1, output_width);
// compute elementwise max
const uint32_t in_offset = (h * input_width + w)*num_img_in_storechunk;
for (uint32_t ph = h_start; ph < h_end; ++ph) {
const uint32_t out_offset_base = ph * output_width;
for (uint32_t pw = w_start; pw < w_end; ++pw) {
const uint32_t out_offset = (out_offset_base + pw) * num_img_in_storechunk;
MaxpoolAVX(num_img_in_storechunk, chunk_in_trans+in_offset, chunk_out_trans + out_offset);
}
}
}
}
chunk_manager.StoreChunk(ten_out_trans->GetChunkId(start_chunk), chunk_out_trans, size_of_store_chunk);
//transpose
if(if_use_SSE_out){
transpose_block_SSE4x4(chunk_out_trans, chunk_tmp, num_img_in_storechunk, outputhw, 8);
}
else{
transpose(chunk_out_trans, chunk_tmp, outputhw, num_img_in_storechunk);
}
if(idx_tmp+num_elem_out<STORE_CHUNK_ELEM){
copy(chunk_tmp, chunk_tmp+num_elem_out, chunk_out + idx_tmp);
idx_tmp+=num_elem_out;
}
else{
size_t idx_add = STORE_CHUNK_ELEM-idx_tmp;
copy(chunk_tmp,chunk_tmp+idx_add,chunk_out+idx_tmp);
chunk_manager.StoreChunk(ten_out->GetChunkId(idx_out), chunk_out, size_of_store_chunk);
idx_out += STORE_CHUNK_ELEM;
copy(chunk_tmp + idx_add,chunk_tmp + num_elem_out,chunk_out + idx_tmp+idx_add);
idx_tmp += num_elem_out;
idx_tmp -= STORE_CHUNK_ELEM;
}
};//end of chunk_op
run_all_chunks_for_maxpool(chunk_op, STORE_CHUNK_ELEM, batch * channel * inputhw, outputsize_in_storechunk, inputhw, outputhw);
if (idx_tmp!=0) {
chunk_manager.StoreChunk(ten_out->GetChunkId(idx_out), chunk_out, idx_tmp * sizeof(DtypeForCpuOp));
}
}//end maxpooling
void backward(
shared_ptr<SecretTen> ten_din, shared_ptr<SecretTen> ten_dout,
shared_ptr<SecretTen> ten_in_trans, shared_ptr<SecretTen> ten_out_trans,
uint32_t batch, uint32_t channel,uint32_t input_height, uint32_t input_width,
uint32_t output_height, uint32_t output_width,
uint32_t filter_height, uint32_t filter_width, uint32_t row_stride, uint32_t col_stride) {
const uint32_t num_img = batch*channel;
const uint32_t inputhw = input_height * input_width;
const uint32_t num_img_in_storechunk = STORE_CHUNK_ELEM / inputhw;
const uint32_t outputhw = output_height*output_width;
uint32_t outputsize_in_storechunk = num_img_in_storechunk * outputhw;
const uint32_t total_size = num_img * inputhw;
const uint32_t total_size_out = num_img * outputhw;
size_t idx_dout=0;
size_t idx_tmp=0;
bool if_use_SSE_out = (outputhw%4==0);
float* chunk_din, *chunk_dout, *chunk_in_trans, *chunk_out_trans, *chunk_din_trans, *chunk_dout_trans, *chunk_tmp;
auto& chunk_manager = TrustedChunkManager::getInstance();
ChunkGuard<DtypeForCpuOp> guard_din(StoreChunkPool::GetChunkPool(), chunk_din);
ChunkGuard<DtypeForCpuOp> guard_dout(StoreChunkPool::GetChunkPool(), chunk_dout);
ChunkGuard<DtypeForCpuOp> guard_int(StoreChunkPool::GetChunkPool(), chunk_in_trans);
ChunkGuard<DtypeForCpuOp> guard_outt(StoreChunkPool::GetChunkPool(), chunk_out_trans);
ChunkGuard<DtypeForCpuOp> guard_dint(StoreChunkPool::GetChunkPool(), chunk_din_trans);
ChunkGuard<DtypeForCpuOp> guard_doutt(StoreChunkPool::GetChunkPool(), chunk_dout_trans);
ChunkGuard<DtypeForCpuOp> guard_tmp(StoreChunkPool::GetChunkPool(), chunk_tmp);
size_t start_chunk_out=0;
if(total_size>=STORE_CHUNK_ELEM){
size_t getsize_out;
if(STORE_CHUNK_ELEM>total_size_out){
getsize_out = total_size_out;
}
else{
getsize_out = STORE_CHUNK_ELEM;
}
chunk_manager.GetChunk(ten_dout->GetChunkId(0), chunk_tmp, getsize_out * sizeof(DtypeForCpuOp));
start_chunk_out += getsize_out;
}
else{
chunk_manager.GetChunk(ten_dout->GetChunkId(0), chunk_tmp, total_size_out * sizeof(float));
}
auto chunk_op = [&](size_t start_chunk, size_t num_elem_in, size_t num_elem_out) {
chunk_manager.GetChunk(ten_in_trans->GetChunkId(start_chunk), chunk_in_trans, STORE_CHUNK_ELEM * sizeof(DtypeForCpuOp));
chunk_manager.GetChunk(ten_out_trans->GetChunkId(start_chunk), chunk_out_trans, STORE_CHUNK_ELEM * sizeof(DtypeForCpuOp));
if(num_elem_in == STORE_CHUNK_ELEM){
if(idx_tmp + outputsize_in_storechunk > STORE_CHUNK_ELEM){
copy(chunk_tmp+idx_tmp,chunk_tmp+STORE_CHUNK_ELEM,chunk_dout);
idx_dout = STORE_CHUNK_ELEM-idx_tmp;
chunk_manager.GetChunk(ten_dout->GetChunkId(start_chunk_out), chunk_tmp, STORE_CHUNK_ELEM * sizeof(DtypeForCpuOp));
start_chunk_out += STORE_CHUNK_ELEM;
idx_tmp = outputsize_in_storechunk-idx_dout;
copy(chunk_tmp, chunk_tmp+idx_tmp, chunk_dout+idx_dout);
}
else{
copy(chunk_tmp+idx_tmp,chunk_tmp+idx_tmp+outputsize_in_storechunk,chunk_dout);
idx_tmp += outputsize_in_storechunk;
}
}
else{
if(idx_tmp==STORE_CHUNK_ELEM||idx_tmp==0){
chunk_manager.GetChunk(ten_dout->GetChunkId(start_chunk_out), chunk_dout, (total_size_out-start_chunk_out) * sizeof(DtypeForCpuOp));
}
else{
copy(chunk_tmp+idx_tmp,chunk_tmp+STORE_CHUNK_ELEM,chunk_dout);
idx_dout = STORE_CHUNK_ELEM-idx_tmp;
if(total_size_out!=start_chunk_out)
chunk_manager.GetChunk(ten_dout->GetChunkId(start_chunk_out), chunk_tmp, (total_size_out-start_chunk_out) * sizeof(DtypeForCpuOp));
//assume total_size_out-start_chunk_out+idx_dout<=STORE_CHUNK_ELEM
idx_tmp = total_size_out - start_chunk_out;
copy(chunk_tmp, chunk_tmp+idx_tmp, chunk_dout+idx_dout);
//idx_dout
}
}
if(if_use_SSE_out){
transpose_block_SSE4x4(chunk_dout, chunk_dout_trans, outputhw, num_img_in_storechunk, 4);
}
else{
transpose(chunk_dout, chunk_dout_trans, num_img_in_storechunk, outputhw);
}
fill(chunk_din_trans, chunk_din_trans + STORE_CHUNK_ELEM,0);
for(uint32_t h = 0; h < input_height; ++h) {
for(uint32_t w = 0; w < input_width; ++w) {
// (h_start, h_end) * (w_start, w_end) is the range that the input
// vector projects to.
const uint32_t h_start = (h < filter_height)
? 0
: (h - filter_height) / row_stride + 1;
const uint32_t h_end = std::min(h / row_stride + 1, output_height);
const uint32_t w_start = (w < filter_width)
? 0
: (w - filter_width) / col_stride + 1;
const uint32_t w_end = std::min(w / col_stride + 1, output_width);
// compute elementwise max
const uint32_t in_offset = (h * input_width + w)*num_img_in_storechunk;
for (uint32_t ph = h_start; ph < h_end; ++ph) {
const uint32_t out_offset_base = ph * output_width;
for (uint32_t pw = w_start; pw < w_end; ++pw) {
const uint32_t out_offset = (out_offset_base + pw) * num_img_in_storechunk;
MaxpoolbackAVX(num_img_in_storechunk, chunk_in_trans + in_offset, chunk_out_trans + out_offset, chunk_din_trans + in_offset, chunk_dout_trans + out_offset);
}
}
}
}
//transpose
transpose_block_SSE4x4(chunk_din_trans, chunk_din, num_img_in_storechunk ,inputhw, 8);
chunk_manager.StoreChunk(ten_din->GetChunkId(start_chunk), chunk_din, num_elem_in * sizeof(float));
};//end of chunk_op
run_all_chunks_for_maxpool(chunk_op, STORE_CHUNK_ELEM, total_size, outputsize_in_storechunk, inputhw, outputhw);
}//end maxpoolbackward
IdT FunId;
IdT TenIdin_trans;
IdT TenIdout_trans;
};
static inline float float2_to_uniform(uint32_t x, uint32_t y, float& a, float& b) {
const union { uint32_t i; float d; } u = { .i = UINT32_C(0x7F) << 23 | ((x ^ y) >> 2) };
const union { uint32_t i; float d; } v = { .i = UINT32_C(0x7F) << 23 | (((x ^ y) >> 5) ^ UINT32_C(0x7FFFFF))};
a = u.d - 1.0f;
b = v.d - 1.0f;
}
// Input: Af
// Output: E
// E = AQ - U = Q(Af) - U
// test: E + U ~= Q(Af)
//void FusedQuantizeShare(shared_ptr<SecretTen> af_ten, shared_ptr<SecretTen> e_ten, uint64_t q_tag, uint64_t u_seed) {
void FusedQuantizeShare(shared_ptr<SecretTen> af_ten, DtypeForCpuOp* e_arr, uint64_t q_tag, uint64_t u_seed) {
const int bits = 8;
const int ebit = 8;
const DtypeForCpuOp lower_limit = -pow(2, (bits - 1));
const DtypeForCpuOp upper_limit = pow(2, (bits - 1)) - 1;
const int num_elem_in_chunk = WORK_CHUNK_ELEM;
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp* store_chunk;
ChunkGuard<DtypeForCpuOp> guard(StoreChunkPool::GetChunkPool(), store_chunk);
DtypeForCpuOp max_entry = 0;
auto get_max_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
int chunk_id = af_ten->GetChunkId(start_store_chunk);
chunk_manager.GetChunk(chunk_id, store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
MapEigenVector src_vecmap(store_chunk, num_elem_in_store_chunk);
max_entry = std::max(max_entry, src_vecmap.cwiseAbs().maxCoeff());
};
run_all_chunks(get_max_chunk_op, STORE_CHUNK_ELEM, af_ten->GetNumElem());
DtypeForCpuOp exp = (max_entry == 0) ? 0 : floor(log2(max_entry));
exp = std::min(std::max(exp, (DtypeForCpuOp) pow(-2, (ebit - 1))), (DtypeForCpuOp) pow(2, (ebit - 1) - 1));
quantize_exp[q_tag] = exp;
const DtypeForCpuOp enlarge_factor = pow(2, -exp + (bits - 2));
const DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
const DtypeForCpuOp invPLimit = static_cast<double>(1) / PrimeLimit;
auto& xor_rnd = *get_fast_rng(q_tag);
auto PrgState = af_ten->PrgStateHolder[u_seed];
DtypeForCpuOp* tmp_chunk = (DtypeForCpuOp*)malloc(num_elem_in_chunk * sizeof(DtypeForCpuOp));
auto store_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(af_ten->GetChunkId(start_store_chunk), store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
auto chunk_op = [&](int start, int num_elem_in_op) {
float* af_chunk = store_chunk + start;
float* e_chunk = e_arr + start_store_chunk + start;
MapEigenTensor af_map = MapEigenTensor(af_chunk, 1, 1, 1, num_elem_in_op);
MapEigenTensor tmp_map = MapEigenTensor(tmp_chunk, 1, 1, 1, num_elem_in_op);
get_r(PrgState, (uint8_t*) e_chunk, num_elem_in_op * sizeof(DtypeForCpuOp), 9);
#if QUANTIZE_MODE == STOCHASTIC
// xor_rnd.rand_like(tmp_chunk, num_elem_in_op);
uint32_t* uint32_chunk = (uint32_t*) e_chunk;
// uint32_t* uint32_chunk = reinterpret_cast<uint32_t*>(e_chunk);
// for(size_t j = 0; j < num_elem_in_op; j++) tmp_chunk[j] = uint32_to_float(uint32_chunk[j]);
for(size_t j = 0; j < num_elem_in_op; j++) tmp_chunk[j] = float_to_uniform(uint32_chunk[j]);
// for(size_t j = 0; j < 10; j++) {
// printf("%f ", tmp_chunk[j]);
// }
// printf("\n");
// for(size_t j = 0; j < num_elem_in_op; j++) tmp_chunk[j] = e_chunk[j];
tmp_map = (af_map * enlarge_factor + tmp_map).floor().cwiseMax(lower_limit).cwiseMin(upper_limit);
#else
tmp_map = (af_map * enlarge_factor).round().cwiseMax(lower_limit).cwiseMin(upper_limit);
#endif
for(size_t j = 0; j < num_elem_in_op; j++) {
e_chunk[j] = tmp_chunk[j] - e_chunk[j];
e_chunk[j] -= floor(e_chunk[j] * invPLimit) * PLimit;
e_chunk[j] = (e_chunk[j] >= mid) ? (e_chunk[j] - p) : e_chunk[j];
}
};
run_all_chunks(chunk_op, WORK_CHUNK_ELEM, num_elem_in_store_chunk);
};
run_all_chunks(store_chunk_op, STORE_CHUNK_ELEM, af_ten->GetNumElem());
free(tmp_chunk);
}
// Input: Af
// Output: A1, E
// AQ = Q(Af)
// A0, U <- Random
// A1 = AQ - A0
// E = AQ - U
// test: E + U = A0 + A1 ~= AQ ~= Q(Af)
void FusedQuantizeShare2(shared_ptr<SecretTen> af_ten, DtypeForCpuOp* a1_arr, DtypeForCpuOp* e_arr,
uint64_t q_tag, uint64_t a0_seed, uint64_t u_seed) {
const int bits = 8;
const int ebit = 8;
const DtypeForCpuOp lower_limit = -pow(2, (bits - 1));
const DtypeForCpuOp upper_limit = pow(2, (bits - 1)) - 1;
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp* store_chunk;
ChunkGuard<DtypeForCpuOp> guard(StoreChunkPool::GetChunkPool(), store_chunk);
DtypeForCpuOp max_entry = 0;
auto get_max_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(af_ten->GetChunkId(start_store_chunk), store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
MapEigenVector src_vecmap(store_chunk, num_elem_in_store_chunk);
max_entry = std::max(max_entry, src_vecmap.cwiseAbs().maxCoeff());
};
run_all_chunks(get_max_chunk_op, STORE_CHUNK_ELEM, af_ten->GetNumElem());
DtypeForCpuOp exp = (max_entry == 0) ? 0 : floor(log2(max_entry));
exp = std::min(std::max(exp, (DtypeForCpuOp) pow(-2, (ebit - 1))), (DtypeForCpuOp) pow(2, (ebit - 1) - 1));
quantize_exp[q_tag] = exp;
DtypeForCpuOp enlarge_factor = pow(2, -exp + (bits - 2));
DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
DtypeForCpuOp invPLimit = static_cast<double>(1) / PrimeLimit;
auto& xor_rnd = *get_fast_rng(q_tag);
const int n_elem_in_chunk = WORK_CHUNK_ELEM;
auto u_prg_state = af_ten->PrgStateHolder[u_seed];
auto a0_prg_state = af_ten->PrgStateHolder[a0_seed];
DtypeForCpuOp* tmp_chunk = (DtypeForCpuOp*)malloc(n_elem_in_chunk * sizeof(DtypeForCpuOp));
auto store_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(af_ten->GetChunkId(start_store_chunk), store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
auto chunk_op = [&](int start, int num_elem_in_op) {
float* af_chunk = store_chunk + start;
float* a1_chunk = a1_arr + start_store_chunk + start;
float* e_chunk = e_arr + start_store_chunk + start;
MapEigenTensor af_map = MapEigenTensor(af_chunk, 1, 1, 1, num_elem_in_op);
MapEigenTensor tmp_map = MapEigenTensor(tmp_chunk, 1, 1, 1, num_elem_in_op);
get_r(a0_prg_state, (uint8_t*) a1_chunk, num_elem_in_op * sizeof(DtypeForCpuOp), 9);
get_r(u_prg_state, (unsigned char*) e_chunk, num_elem_in_op * sizeof(DtypeForCpuOp), 0);
#if QUANTIZE_MODE == STOCHASTIC
// xor_rnd.rand_like(tmp_chunk, num_elem_in_op);
uint32_t* uint32_chunk = (uint32_t*) e_chunk;
// for(size_t j = 0; j < num_elem_in_op; j++) tmp_chunk[j] = uint32_to_float(uint32_chunk[j]);
for(size_t j = 0; j < num_elem_in_op; j++) tmp_chunk[j] = float_to_uniform(uint32_chunk[j]);
// for(size_t j = 0; j < num_elem_in_op; j++) tmp_chunk[j] = e_chunk[j];
tmp_map = (af_map * enlarge_factor + tmp_map).floor().cwiseMax(lower_limit).cwiseMin(upper_limit);
#else
tmp_map = (af_map * enlarge_factor).round().cwiseMax(lower_limit).cwiseMin(upper_limit);
#endif
for(size_t j = 0; j < num_elem_in_op; j++) {
e_chunk[j] = tmp_chunk[j] - e_chunk[j];
e_chunk[j] -= floor(e_chunk[j] * invPLimit) * PLimit;
e_chunk[j] = (e_chunk[j] >= mid) ? (e_chunk[j] - p) : e_chunk[j];
a1_chunk[j] = tmp_chunk[j] - a1_chunk[j];
a1_chunk[j] -= floor(a1_chunk[j] * invPLimit) * PLimit;
a1_chunk[j] = (a1_chunk[j] >= mid) ? (a1_chunk[j] - p) : a1_chunk[j];
}
};
run_all_chunks(chunk_op, WORK_CHUNK_ELEM, num_elem_in_store_chunk);
};
run_all_chunks(store_chunk_op, STORE_CHUNK_ELEM, af_ten->GetNumElem());
free(tmp_chunk);
}
// Input: C', Ci
// Output: Cf
// Cf = dQ(C' + Ci)
// test: Cf ~= deQ(C' + Ci)
void FusedRecon(shared_ptr<SecretTen> cf_ten, shared_ptr<SecretTen> cq_ten, DtypeForCpuOp* c_left_arr,
uint64_t x_tag, uint64_t y_tag) {
const int bits = 8;
const DtypeForCpuOp x_exp = quantize_exp[x_tag];
const DtypeForCpuOp y_exp = quantize_exp[y_tag];
const DtypeForCpuOp shrink_factor = pow(2, x_exp - (bits - 2) + y_exp - (bits - 2));
const DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
const DtypeForCpuOp invPLimit = static_cast<double>(1) / PrimeLimit;
const int total_num_elem = cf_ten->GetNumElem();
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp *cf_store_chunk, *cq_store_chunk;
ChunkGuard<DtypeForCpuOp> cf_guard(StoreChunkPool::GetChunkPool(), cf_store_chunk);
ChunkGuard<DtypeForCpuOp> cq_guard(StoreChunkPool::GetChunkPool(), cq_store_chunk);
auto store_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(cq_ten->GetChunkId(start_store_chunk), cq_store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
auto chunk_op = [&](int start, int num_elem_in_op) {
DtypeForCpuOp* cf_chunk = cf_store_chunk + start;
DtypeForCpuOp* cq_chunk = cq_store_chunk + start;
DtypeForCpuOp* c_left_chunk = c_left_arr + start_store_chunk + start;
for(size_t j = 0; j < num_elem_in_op; j++) {
cq_chunk[j] += c_left_chunk[j];
cf_chunk[j] = cq_chunk[j];
cf_chunk[j] -= floor(cf_chunk[j] * invPLimit) * PLimit;
cf_chunk[j] = (cf_chunk[j] >= mid) ? (cf_chunk[j] - p) : cf_chunk[j];
cf_chunk[j] *= shrink_factor;
}
};
run_all_chunks(chunk_op, WORK_CHUNK_ELEM, num_elem_in_store_chunk);
// chunk_manager.StoreChunk(cq_ten->GetChunkId(start_store_chunk), cq_store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
chunk_manager.StoreChunk(cf_ten->GetChunkId(start_store_chunk), cf_store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
};
run_all_chunks(store_chunk_op, STORE_CHUNK_ELEM, total_num_elem);
}
extern "C" {
void SecretInitTensor(IdT TenId, void *voidDims) {
DimsT *Dims = (DimsT *) voidDims;
SecretTenHolder[TenId] = make_shared<SecretTen>(TenId, Dims);
}
void SecretSetTen(IdT TenId, void *voidArr) {
GetTenById(TenId)->SetTen((DtypeForCpuOp *) voidArr);
}
void SecretGetTen(IdT TenId, void *voidArr) {
GetTenById(TenId)->GetTen((DtypeForCpuOp *) voidArr);
}
void SecretSetSeed(IdT TenId, uint64_t RawSeed) {
GetTenById(TenId)->SetSeed(RawSeed);
}
void SecretGetRandom(IdT TenId, void *voidArr, uint64_t RawSeed) {
GetTenById(TenId)->GetRandom((DtypeForCpuOp *) voidArr, RawSeed);
}
void SecretGetShare(IdT TenId, void *voidArr, uint64_t RawSeed) {
GetTenById(TenId)->GetShare((DtypeForCpuOp *) voidArr, RawSeed);
}
void SecretAddFromCpu(void* inputArr, IdT dstId) {
shared_ptr<SecretTen > StoreTensor = GetTenById(dstId);
DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
DtypeForCpuOp invPLimit = static_cast<double>(1) / PrimeLimit;
const int total_num_elem = StoreTensor->GetNumElem();
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp* store_chunk;
ChunkGuard<DtypeForCpuOp> guard(StoreChunkPool::GetChunkPool(), store_chunk);
auto store_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(StoreTensor->GetChunkId(start_store_chunk), store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
auto chunk_op = [&](int start_chunk, int num_elem_in_op) {
DtypeForCpuOp* output_arr = store_chunk + start_chunk;
DtypeForCpuOp* input_arr = ((DtypeForCpuOp*) inputArr) + start_store_chunk + start_chunk;
for(size_t j = 0; j < num_elem_in_op; j++) {
output_arr[j] += input_arr[j];
output_arr[j] -= floor(output_arr[j] * invPLimit) * PLimit;
output_arr[j] = (output_arr[j] >= mid) ? (output_arr[j] - p) : output_arr[j];
}
};
run_all_chunks(chunk_op, WORK_CHUNK_ELEM, num_elem_in_store_chunk);
chunk_manager.StoreChunk(StoreTensor->GetChunkId(start_store_chunk), store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
};
run_all_chunks(store_chunk_op, STORE_CHUNK_ELEM, total_num_elem);
}
void newrelu(IdT TenIdin, IdT TenIdout, uint64_t size){
shared_ptr<SecretTen > ten_in = GetTenById(TenIdin);
shared_ptr<SecretTen > ten_out = GetTenById(TenIdout);
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp* chunk_in,* chunk_tmp;
ChunkGuard<DtypeForCpuOp> guard_tmp(StoreChunkPool::GetChunkPool(), chunk_tmp);
//ChunkGuard<DtypeForCpuOp> guard_out(StoreChunkPool::GetChunkPool(), chunk_out);
auto store_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(ten_in->GetChunkId(start_store_chunk), chunk_tmp, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
for(uint64_t i=0;i<num_elem_in_store_chunk;i+=8){
const __m256 inp8f = _mm256_load_ps(&chunk_tmp[i]);
const __m256 if_gt = _mm256_cmp_ps(inp8f, zero8f, 0x0e);
const __m256 res8f = _mm256_blendv_ps(zero8f, inp8f, if_gt);
_mm256_stream_ps(&chunk_tmp[i], res8f);
}
chunk_manager.StoreChunk(ten_out->GetChunkId(start_store_chunk), chunk_tmp, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
};
run_all_chunks(store_chunk_op, STORE_CHUNK_ELEM, size);
}
void newreluback(IdT TenIdout, IdT TenIddout,IdT TenIddin, uint64_t size){
shared_ptr<SecretTen > ten_din = GetTenById(TenIddin);
shared_ptr<SecretTen > ten_dout = GetTenById(TenIddout);
shared_ptr<SecretTen > ten_out = GetTenById(TenIdout);
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp* chunk_dtmp,* chunk_out;
//ChunkGuard<DtypeForCpuOp> guard_din(StoreChunkPool::GetChunkPool(), chunk_din);
ChunkGuard<DtypeForCpuOp> guard_dtmp(StoreChunkPool::GetChunkPool(), chunk_dtmp);
ChunkGuard<DtypeForCpuOp> guard_out(StoreChunkPool::GetChunkPool(), chunk_out);
auto store_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(ten_dout->GetChunkId(start_store_chunk),chunk_dtmp, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
chunk_manager.GetChunk(ten_out->GetChunkId(start_store_chunk),chunk_out, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
for(uint64_t i=0;i<num_elem_in_store_chunk;i+=8){
const __m256 inp8f = _mm256_load_ps(&chunk_out[i]);
const __m256 if_eq = _mm256_cmp_ps(inp8f, zero8f, 0x00);
const __m256 gra8f = _mm256_load_ps(&chunk_dtmp[i]);
const __m256 res8f = _mm256_blendv_ps(gra8f, zero8f, if_eq);
_mm256_stream_ps(&chunk_dtmp[i], res8f);
}
chunk_manager.StoreChunk(ten_din->GetChunkId(start_store_chunk), chunk_dtmp, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
};
run_all_chunks(store_chunk_op, STORE_CHUNK_ELEM, size);
}
unordered_map<IdT, shared_ptr<MaxpoolBuffer>> MaxpoolHolder;
shared_ptr<MaxpoolBuffer> GetBufferByIdM(IdT FunId) {
return MaxpoolHolder[FunId];
}
void initmaxpool(IdT FunId, IdT TenIdin_trans, IdT TenIdout_trans){
MaxpoolHolder[FunId] = make_shared<MaxpoolBuffer>(FunId, TenIdin_trans, TenIdout_trans);
}
void newmaxpool(IdT FunId, IdT TenIdin, IdT TenIdout, uint32_t batch, uint32_t channel,uint32_t input_height, uint32_t input_width,uint32_t output_height, uint32_t output_width, uint32_t filter_height, uint32_t filter_width, uint32_t row_stride, uint32_t col_stride, uint32_t row_pad, uint32_t col_pad){
shared_ptr<SecretTen > ten_in = GetTenById(TenIdin);
shared_ptr<SecretTen > ten_out = GetTenById(TenIdout);
IdT TenIdin_trans = GetBufferByIdM(FunId)->get_TenIdin_trans();
shared_ptr<SecretTen> ten_in_trans = GetTenById(TenIdin_trans);
IdT TenIdout_trans = GetBufferByIdM(FunId)->get_TenIdout_trans();
shared_ptr<SecretTen> ten_out_trans = GetTenById(TenIdout_trans);
GetBufferByIdM(FunId)->forward(ten_in, ten_out,ten_in_trans, ten_out_trans, batch, channel,input_height,input_width,output_height,output_width,filter_height,filter_width,row_stride,col_stride);
}
void newmaxpoolback(IdT FunId, IdT TenIddout,IdT TenIddin, uint32_t batch, uint32_t channel,uint32_t input_height, uint32_t input_width,uint32_t output_height, uint32_t output_width, uint32_t filter_height, uint32_t filter_width, uint32_t row_stride, uint32_t col_stride){
shared_ptr<SecretTen > ten_din = GetTenById(TenIddin);
shared_ptr<SecretTen > ten_dout = GetTenById(TenIddout);
IdT TenIdin_trans = GetBufferByIdM(FunId)->get_TenIdin_trans();
shared_ptr<SecretTen> ten_in_trans = GetTenById(TenIdin_trans);
IdT TenIdout_trans = GetBufferByIdM(FunId)->get_TenIdout_trans();
shared_ptr<SecretTen> ten_out_trans = GetTenById(TenIdout_trans);
//shared_ptr<SecretTen > ten_in_trans = GetTenById(0);
//uint64_t tensor_size=(batch*channel*input_height*input_width+STORE_CHUNK_ELEM/2)/STORE_CHUNK_ELEM*STORE_CHUNK_ELEM;
//shared_ptr<SecretTen > ten_out_trans = GetTenById(tensor_size*sizeof(float));
GetBufferByIdM(FunId)->backward(ten_din, ten_dout, ten_in_trans, ten_out_trans, batch, channel,input_height,input_width,output_height,output_width,filter_height,filter_width,row_stride,col_stride);
}
unordered_map<IdT, shared_ptr<BatchnormBuffer>> BatchnormHolder;
shared_ptr<BatchnormBuffer> GetBufferByIdB(IdT FunId) {
return BatchnormHolder[FunId];
}
void SecretInitBatchnorm(
IdT FunId,
IdT input, IdT output, IdT gamma, IdT beta,
IdT der_input, IdT der_output, IdT der_gamma, IdT der_beta,
IdT run_mean, IdT run_var, IdT cur_mean, IdT cur_var,
IdT mu,
uint32_t batch_, uint32_t channel_, uint32_t height_, uint32_t width_,
int affine_, int is_cumulative_, float momentum_, float epsilon_) {
auto bn_buffer = make_shared<BatchnormBuffer>(FunId);
BatchnormHolder[FunId] = bn_buffer;
bn_buffer->init(
input, output, gamma, beta,
der_input, der_output, der_gamma, der_beta,
run_mean, run_var, cur_mean, cur_var,
mu,
batch_, channel_, height_, width_,
affine_, is_cumulative_, momentum_, epsilon_);
}
void SecretBatchnormForward(IdT FunId, int Training) {
GetBufferByIdB(FunId)->forward(Training);
}
void SecretBatchnormBackward(IdT FunId) {
GetBufferByIdB(FunId)->backward();
}
// Store <- C0 + C1 + C2 (MainSeed + Seed1 + Seed2)
// DstArr <- MainSeed (either C0 or C1)
void SecretMaskingC01(IdT storeId, uint64_t mainRawSeed, uint64_t rawSeed0, uint64_t rawSeed1, DtypeForCpuOp *DstArr) {
shared_ptr<SecretTen > StoreTensor = GetTenById(storeId);
auto MainPrgState = StoreTensor->PrgStateHolder[mainRawSeed];
auto PrgState0 = StoreTensor->PrgStateHolder[rawSeed0];
auto PrgState1 = StoreTensor->PrgStateHolder[rawSeed1];
const int total_num_elem = StoreTensor->GetNumElem();
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp* store_chunk;
ChunkGuard<DtypeForCpuOp> guard(StoreChunkPool::GetChunkPool(), store_chunk);
DtypeForCpuOp* aux_chunk_arr = (DtypeForCpuOp*)memalign(32, WORK_CHUNK_ELEM * sizeof(DtypeForCpuOp));
DtypeForCpuOp PLimit = static_cast<DtypeForCpuOp>(PrimeLimit);
DtypeForCpuOp invPLimit = static_cast<double>(1) / PrimeLimit;
auto store_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(StoreTensor->GetChunkId(start_store_chunk), store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
auto chunk_op = [&](int start, int num_elem_in_op) {
DtypeForCpuOp* store_arr = store_chunk + start;
DtypeForCpuOp* output_arr = DstArr + start_store_chunk + start;
get_r(MainPrgState, (uint8_t*) output_arr, num_elem_in_op * sizeof(DtypeForCpuOp), 9);
get_r(PrgState0, (uint8_t*) store_arr, num_elem_in_op * sizeof(DtypeForCpuOp), 9);
get_r(PrgState1, (uint8_t*) aux_chunk_arr, num_elem_in_op * sizeof(DtypeForCpuOp), 9);
for(size_t j = 0; j < num_elem_in_op; j++) {
store_arr[j] += output_arr[j] + aux_chunk_arr[j];
store_arr[j] -= floor(store_arr[j] * invPLimit) * PLimit;
store_arr[j] = (store_arr[j] >= mid) ? (store_arr[j] - p) : store_arr[j];
output_arr[j] -= floor(output_arr[j] * invPLimit) * PLimit;
output_arr[j] = (output_arr[j] >= mid) ? (output_arr[j] - p) : output_arr[j];
}
};
run_all_chunks(chunk_op, WORK_CHUNK_ELEM, num_elem_in_store_chunk);
chunk_manager.StoreChunk(StoreTensor->GetChunkId(start_store_chunk), store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
};
run_all_chunks(store_chunk_op, STORE_CHUNK_ELEM, total_num_elem);
free(aux_chunk_arr);
}
// Assume momentum > 0
void SecretSgdUpdate(IdT paramId, IdT gradId, IdT momentumId,
DtypeForCpuOp lr, DtypeForCpuOp momentum, DtypeForCpuOp weight_decay,
DtypeForCpuOp dampening, bool nesterov, bool first_momentum) {
shared_ptr<SecretTen> ParamTensor = GetTenById(paramId);
shared_ptr<SecretTen> GradTensor = GetTenById(gradId);
shared_ptr<SecretTen> MomentumTensor = (momentumId != 0) ? GetTenById(momentumId) : nullptr;
const int total_num_elem = ParamTensor->GetNumElem();
auto& chunk_manager = TrustedChunkManager::getInstance();
DtypeForCpuOp *param_store_chunk, *grad_store_chunk, *momentum_store_chunk;
ChunkGuard<DtypeForCpuOp> param_guard(StoreChunkPool::GetChunkPool(), param_store_chunk);
ChunkGuard<DtypeForCpuOp> grad_guard(StoreChunkPool::GetChunkPool(), grad_store_chunk);
ChunkGuard<DtypeForCpuOp> momentum_guard(StoreChunkPool::GetChunkPool(), momentum_store_chunk);
auto store_chunk_op = [&](int start_store_chunk, int num_elem_in_store_chunk) {
chunk_manager.GetChunk(ParamTensor->GetChunkId(start_store_chunk), param_store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
chunk_manager.GetChunk(GradTensor->GetChunkId(start_store_chunk), grad_store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
chunk_manager.GetChunk(MomentumTensor->GetChunkId(start_store_chunk), momentum_store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
auto chunk_op = [&](int start, int num_elem_in_op) {
DtypeForCpuOp* param_arr = param_store_chunk + start;
DtypeForCpuOp* grad_arr = grad_store_chunk + start;
DtypeForCpuOp* momentum_arr = momentum_store_chunk + start;
if (first_momentum) {
for(size_t j = 0; j < num_elem_in_op; j++) {
grad_arr[j] += weight_decay * param_arr[j];
momentum_arr[j] = grad_arr[j];
param_arr[j] -= lr * momentum_arr[j];
}
} else {
for(size_t j = 0; j < num_elem_in_op; j++) {
grad_arr[j] += weight_decay * param_arr[j];
momentum_arr[j] = momentum_arr[j] * momentum + (1 - dampening) * grad_arr[j];
param_arr[j] -= lr * momentum_arr[j];
}
}
};
run_all_chunks(chunk_op, WORK_CHUNK_ELEM, num_elem_in_store_chunk);
chunk_manager.StoreChunk(ParamTensor->GetChunkId(start_store_chunk), param_store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
chunk_manager.StoreChunk(MomentumTensor->GetChunkId(start_store_chunk), momentum_store_chunk, num_elem_in_store_chunk * sizeof(DtypeForCpuOp));
};
run_all_chunks(store_chunk_op, STORE_CHUNK_ELEM, total_num_elem);
}
void SecretStochasticQuantize(IdT src_id, IdT dst_id, uint64_t q_tag) {
quantize_stochastic(GetTenById(src_id), GetTenById(dst_id), q_tag);
}
void SecretFusedQuantizeShare(IdT af_id, void* e_arr, uint64_t q_tag, uint64_t u_seed) {
FusedQuantizeShare(GetTenById(af_id), (DtypeForCpuOp*) e_arr, q_tag, u_seed);
}
void SecretFusedQuantizeShare2(IdT af_id, void* a1_arr, void* e_arr,
uint64_t q_tag, uint64_t a0_seed, uint64_t u_seed) {
FusedQuantizeShare2(GetTenById(af_id), (DtypeForCpuOp*) a1_arr, (DtypeForCpuOp*) e_arr,
q_tag, a0_seed, u_seed);
}
void SecretFusedRecon(IdT cf_id, IdT cq_id, DtypeForCpuOp* c_left_arr, uint64_t x_tag, uint64_t y_tag) {
FusedRecon(GetTenById(cf_id), GetTenById(cq_id), (DtypeForCpuOp*) c_left_arr, x_tag, y_tag);
}
} // End of extern C
| 45.647402
| 303
| 0.656201
|
goten-team
|
38e4d38d50750c10109432ede6945a804cd9906f
| 7,047
|
cc
|
C++
|
test/distributions.cc
|
TeoGiane/bayesmix
|
43182d61c3f332aefb832426cc9e8e2b2394bd68
|
[
"BSD-3-Clause"
] | null | null | null |
test/distributions.cc
|
TeoGiane/bayesmix
|
43182d61c3f332aefb832426cc9e8e2b2394bd68
|
[
"BSD-3-Clause"
] | null | null | null |
test/distributions.cc
|
TeoGiane/bayesmix
|
43182d61c3f332aefb832426cc9e8e2b2394bd68
|
[
"BSD-3-Clause"
] | null | null | null |
#include "src/utils/distributions.h"
#include <gtest/gtest.h>
#include <Eigen/Dense>
#include <stan/math/prim.hpp>
#include <vector>
#include "src/utils/rng.h"
TEST(mix_dist, 1) {
auto& rng = bayesmix::Rng::Instance().get();
int nclus = 5;
Eigen::VectorXd weights1 =
stan::math::dirichlet_rng(Eigen::VectorXd::Ones(nclus), rng);
Eigen::VectorXd means1(nclus);
Eigen::VectorXd sds1(nclus);
for (int i = 0; i < nclus; i++) {
means1(i) = stan::math::normal_rng(0, 2, rng);
sds1(i) = stan::math::uniform_rng(0.1, 2.0, rng);
}
int nclus2 = 10;
Eigen::VectorXd weights2 =
stan::math::dirichlet_rng(Eigen::VectorXd::Ones(nclus2), rng);
Eigen::VectorXd means2(nclus2);
Eigen::VectorXd sds2(nclus2);
for (int i = 0; i < nclus2; i++) {
means2(i) = stan::math::normal_rng(0, 2, rng);
sds2(i) = stan::math::uniform_rng(0.1, 2.0, rng);
}
double dist = bayesmix::gaussian_mixture_dist(means1, sds1, weights1, means2,
sds2, weights2);
ASSERT_GE(dist, 0.0);
}
TEST(mix_dist, 2) {
int nclus = 5;
auto& rng = bayesmix::Rng::Instance().get();
Eigen::VectorXd weights1 =
stan::math::dirichlet_rng(Eigen::VectorXd::Ones(nclus), rng);
Eigen::VectorXd means1(nclus);
Eigen::VectorXd sds1(nclus);
for (int i = 0; i < nclus; i++) {
means1(i) = stan::math::normal_rng(0, 2, rng);
sds1(i) = stan::math::uniform_rng(0.1, 2.0, rng);
}
double dist_to_self = bayesmix::gaussian_mixture_dist(
means1, sds1, weights1, means1, sds1, weights1);
ASSERT_DOUBLE_EQ(dist_to_self, 0.0);
}
TEST(student_t, squareform) {
Eigen::MatrixXd A = Eigen::MatrixXd::Random(5, 5);
Eigen::MatrixXd sigma =
(A * A.transpose()) + 1.0 * Eigen::MatrixXd::Identity(5, 5);
Eigen::VectorXd mean = Eigen::VectorXd::Zero(5);
double df = 15;
Eigen::MatrixXd sigma_inv = stan::math::inverse_spd(sigma);
Eigen::MatrixXd sigma_inv_chol =
Eigen::LLT<Eigen::MatrixXd>(sigma_inv).matrixU();
Eigen::VectorXd x = Eigen::VectorXd::Ones(5);
double sq1 = (x - mean).transpose() * sigma_inv * (x - mean);
double sq2 = (sigma_inv_chol * (x - mean)).squaredNorm();
ASSERT_DOUBLE_EQ(sq1, sq2);
}
TEST(student_t, optimized) {
Eigen::MatrixXd A = Eigen::MatrixXd::Random(5, 5);
Eigen::MatrixXd sigma =
(A * A.transpose()) + 1.0 * Eigen::MatrixXd::Identity(5, 5);
Eigen::VectorXd mean = Eigen::VectorXd::Zero(5);
double df = 15;
Eigen::VectorXd x = Eigen::VectorXd::Ones(5);
double lpdf_stan = stan::math::multi_student_t_lpdf(x, df, mean, sigma);
// std::cout << "lpdf_stan: " << lpdf_stan << std::endl;
Eigen::MatrixXd sigma_inv = stan::math::inverse_spd(sigma);
Eigen::MatrixXd sigma_inv_chol =
Eigen::LLT<Eigen::MatrixXd>(sigma_inv).matrixU();
Eigen::VectorXd diag = sigma_inv_chol.diagonal();
double logdet = 2 * log(diag.array()).sum();
double our_lpdf = bayesmix::multi_student_t_invscale_lpdf(
x, df, mean, sigma_inv_chol, logdet);
// std::cout << "our_lpdf: " << our_lpdf << std::endl;
ASSERT_LE(std::abs(our_lpdf - lpdf_stan), 0.001);
}
TEST(student_t, marginal) {
double var_scaling = 0.1;
double deg_free = 10;
int dim = 3;
Eigen::MatrixXd A = Eigen::MatrixXd::Random(dim, dim);
Eigen::MatrixXd scale_inv =
(A * A.transpose()) + 1.0 * Eigen::MatrixXd::Identity(dim, dim);
Eigen::MatrixXd sigma_n =
scale_inv * (var_scaling + 1) / (var_scaling * (deg_free - dim + 1));
double nu_n = deg_free - dim + 1;
Eigen::VectorXd datum = Eigen::VectorXd::Ones(dim);
Eigen::VectorXd mean = Eigen::VectorXd::Zero(dim);
Eigen::MatrixXd scale = stan::math::inverse_spd(scale_inv);
Eigen::MatrixXd scale_chol = Eigen::LLT<Eigen::MatrixXd>(scale).matrixU();
double coeff = (var_scaling + 1) / (var_scaling * (deg_free - dim + 1));
Eigen::MatrixXd scale_chol_n = scale_chol / std::sqrt(coeff);
Eigen::VectorXd diag = scale_chol_n.diagonal();
double logdet = 2 * log(diag.array()).sum();
double old_qf = (datum - mean).transpose() *
stan::math::inverse_spd(sigma_n) * (datum - mean);
double new_qf = (scale_chol_n * (datum - mean)).squaredNorm();
ASSERT_DOUBLE_EQ(old_qf, new_qf);
double old_lpdf =
stan::math::multi_student_t_lpdf(datum, nu_n, mean, sigma_n);
double new_lpdf = bayesmix::multi_student_t_invscale_lpdf(
datum, nu_n, mean, scale_chol_n, logdet);
ASSERT_LE(std::abs(old_lpdf - new_lpdf), 0.001);
}
TEST(mult_normal, lpdf_grid) {
int dim = 3;
Eigen::MatrixXd data = Eigen::MatrixXd::Random(20, dim);
Eigen::VectorXd mean = Eigen::ArrayXd::LinSpaced(dim, 0.0, 10.0);
Eigen::MatrixXd tmp = Eigen::MatrixXd::Random(dim + 1, dim);
Eigen::MatrixXd prec =
tmp.transpose() * tmp + Eigen::MatrixXd::Identity(dim, dim);
Eigen::MatrixXd prec_chol = Eigen::LLT<Eigen::MatrixXd>(prec).matrixU();
Eigen::VectorXd diag = prec_chol.diagonal();
double prec_logdet = 2 * log(diag.array()).sum();
Eigen::VectorXd lpdfs = bayesmix::multi_normal_prec_lpdf_grid(
data, mean, prec_chol, prec_logdet);
for (int i = 0; i < 20; i++) {
double curr = bayesmix::multi_normal_prec_lpdf(data.row(i), mean,
prec_chol, prec_logdet);
ASSERT_DOUBLE_EQ(curr, lpdfs(i));
}
}
TEST(mult_t, lpdf_grid) {
int dim = 3;
Eigen::MatrixXd data = Eigen::MatrixXd::Random(20, dim);
Eigen::VectorXd mean = Eigen::ArrayXd::LinSpaced(dim, 0.0, 10.0);
Eigen::MatrixXd tmp = Eigen::MatrixXd::Random(dim + 1, dim);
Eigen::MatrixXd invscale =
tmp.transpose() * tmp + Eigen::MatrixXd::Identity(dim, dim);
Eigen::MatrixXd invscale_chol =
Eigen::LLT<Eigen::MatrixXd>(invscale).matrixU();
Eigen::VectorXd diag = invscale_chol.diagonal();
double invscale_logdet = 2 * log(diag.array()).sum();
double df = 10;
Eigen::VectorXd lpdfs = bayesmix::multi_student_t_invscale_lpdf_grid(
data, df, mean, invscale_chol, invscale_logdet);
for (int i = 0; i < 20; i++) {
double curr = bayesmix::multi_student_t_invscale_lpdf(
data.row(i), df, mean, invscale_chol, invscale_logdet);
ASSERT_DOUBLE_EQ(curr, lpdfs(i));
}
}
TEST(lpdf_woodbury, 1) {
int dim = 1000;
int q = 10;
auto& rng = bayesmix::Rng::Instance().get();
Eigen::VectorXd mean(dim);
Eigen::VectorXd datum(dim);
Eigen::VectorXd sigma_diag(dim);
Eigen::MatrixXd lambda(dim, q);
for (size_t j = 0; j < dim; j++) {
mean[j] = stan::math::normal_rng(0, 1, rng);
sigma_diag[j] = stan::math::inv_gamma_rng(2.5, 1, rng);
for (size_t i = 0; i < q; i++) {
lambda(j, i) = stan::math::normal_rng(0, 1, rng);
}
}
Eigen::MatrixXd cov =
lambda * lambda.transpose() + Eigen::MatrixXd(sigma_diag.asDiagonal());
datum = stan::math::multi_normal_rng(mean, cov, rng);
double stan_lpdf = stan::math::multi_normal_lpdf(datum, mean, cov);
double our_lpdf =
bayesmix::multi_normal_lpdf_woodbury(datum, mean, sigma_diag, lambda);
ASSERT_LE(std::abs(stan_lpdf - our_lpdf), 1e-10);
}
| 31.600897
| 79
| 0.648503
|
TeoGiane
|
38eca32354dc5f2fd7f50db6ee608ecde759de72
| 1,409
|
cpp
|
C++
|
src/generator/SwitchGenerator.cpp
|
jaydee-io/bnf2c
|
453b9dec8d94f32eebf9df1ab9578da0b5c70d84
|
[
"BSD-4-Clause"
] | null | null | null |
src/generator/SwitchGenerator.cpp
|
jaydee-io/bnf2c
|
453b9dec8d94f32eebf9df1ab9578da0b5c70d84
|
[
"BSD-4-Clause"
] | null | null | null |
src/generator/SwitchGenerator.cpp
|
jaydee-io/bnf2c
|
453b9dec8d94f32eebf9df1ab9578da0b5c70d84
|
[
"BSD-4-Clause"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
// BNF2C
//
// This file is distributed under the 4-clause Berkeley Software Distribution
// License. See LICENSE for details.
////////////////////////////////////////////////////////////////////////////////
#include "generator/SwitchGenerator.h"
////////////////////////////////////////////////////////////////////////////////
SwitchGenerator::SwitchGenerator(Indenter & indenter, const std::string & switchOnExpr, const std::string & defaultCode)
: m_indenter(indenter), m_switchOnExpr(switchOnExpr), m_defaultCode(defaultCode)
{
}
////////////////////////////////////////////////////////////////////////////////
void SwitchGenerator::printBeginTo(std::ostream & os) const
{
os << m_indenter << "switch(" << m_switchOnExpr << ")" << std::endl;
os << m_indenter << "{" << std::endl;
m_indenter++;
}
////////////////////////////////////////////////////////////////////////////////
void SwitchGenerator::printEndTo(std::ostream & os) const
{
printDefaultTo(os);
m_indenter--;
os << m_indenter << "}" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////
void SwitchGenerator::printDefaultTo(std::ostream & os) const
{
if(!m_defaultCode.empty())
os << m_indenter << "default : " << m_defaultCode << std::endl;
}
| 38.081081
| 120
| 0.432221
|
jaydee-io
|
38eec9b7f9f3239a097967416fa7f2d6fe070a22
| 10,011
|
cpp
|
C++
|
fluxes.cpp
|
rocketcrush/suchsolver
|
18ffeaf13aa0c549f7081acc943bc1257e50c656
|
[
"MIT"
] | 1
|
2017-11-07T17:45:52.000Z
|
2017-11-07T17:45:52.000Z
|
fluxes.cpp
|
rocketcrush/suchsolver
|
18ffeaf13aa0c549f7081acc943bc1257e50c656
|
[
"MIT"
] | null | null | null |
fluxes.cpp
|
rocketcrush/suchsolver
|
18ffeaf13aa0c549f7081acc943bc1257e50c656
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <cmath>
#include <data.h>
#include <constants.h>
#include <mesh.h>
#include <initialconditions.h>
using namespace std;
extern vector<node> n;
extern vector<element> e;
extern vector<type1> tp1;
extern vector<type2> tp2;
extern vector<type3> tp3;
void W(int i)
{
tp1[i].W[0] = e[i].ro;
tp1[i].W[1] = e[i].ro * e[i].u;
tp1[i].W[2] = e[i].ro * e[i].v;
tp1[i].W[3] = e[i].ro * e[i].et;
}
void Fc1(int i)
{
double fenergyp, fenergym, fmassp, fmassm;
double ML,MR;
double VL, VR; //contravariant velocity of right state and left state
double cL, cR; //speed of sound
double roL, uL, vL, pL, etL;
double roR, uR, vR, pR, etR;
double vnx, vny;
double Fp[4], Fm[4];
roL = e[i].ro;
uL = e[i].u;
vL = e[i].v;
pL = e[i].p;
etL = e[i].et;
for(int d = 0; d < 4; d++)
{
roR = e[e[i].neigh[d]].ro;
uR = e[e[i].neigh[d]].u;
vR = e[e[i].neigh[d]].v;
pR = e[e[i].neigh[d]].p;
etR = e[e[i].neigh[d]].et;
vnx = e[i].vn[d].x;
vny = e[i].vn[d].y;
VL = vnx * uL + vny * vL;
VR = vnx * uR + vny * vR;
cL = sqrt(gama * pL / roL);
cR = sqrt(gama * pR / roR);
ML = VL / cL;
MR = VR / cR;
if(ML >= 1.)
{
Fp[0] = roL * VL;
Fp[1] = roL * uL * VL + vnx * pL;
Fp[2] = roL * vL * VL + vny * pL;
Fp[3] = roL * (etL + pL / roL) * VL;
}
else if(abs(ML) < 1)
{
fmassp = roL * cL * pow((ML + 1), 2) / 4.;
fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) / 2.);
Fp[0] = fmassp;
Fp[1] = fmassp * (vnx * (-VL + 2. * cL) / gama + uL);
Fp[2] = fmassp * (vny * (-VL + 2. * cL) / gama + vL);
Fp[3] = fenergyp;
}
else
{
Fp[0] = 0;
Fp[1] = 0;
Fp[2] = 0;
Fp[3] = 0;
}
if(MR >= 1.)
{
Fm[0] = 0;
Fm[1] = 0;
Fm[2] = 0;
Fm[3] = 0;
}
else if(abs(MR) < 1)
{
fmassm = -roR * cR * pow((MR - 1), 2) / 4.;
fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) / 2.);
Fm[0] = fmassm;
Fm[1] = fmassm * (vnx * (-VR - 2. * cR) / gama + uR);
Fm[2] = fmassm * (vny * (-VR - 2. * cR) / gama + vR);
Fm[3] = fenergym;
}
else
{
Fm[0] = roR * VR;
Fm[1] = roR * uR * VR + vnx * pR;
Fm[2] = roR * vR * VR + vny * pR;
Fm[3] = roR * (etR + pR / roR) * VR;
}
for(int a = 0; a < 4; a++)
tp1[i].Fc[d][a] = Fp[a] + Fm[a];
}
}
void W3(int i, int t)
{
if(t == 0)
{
tp3[i].W[0][t] = e[i].roprev;
tp3[i].W[1][t] = e[i].roprev * e[i].uprev;
tp3[i].W[2][t] = e[i].roprev * e[i].vprev;
tp3[i].W[3][t] = e[i].roprev * e[i].etprev;
}
else if(t == 1)
{
tp3[i].W[0][t] = e[i].ro;
tp3[i].W[1][t] = e[i].ro * e[i].u;
tp3[i].W[2][t] = e[i].ro * e[i].v;
tp3[i].W[3][t] = e[i].ro * e[i].et;
}
else if(t == 2)
{
tp3[i].W[0][t] = e[i].ronew;
tp3[i].W[1][t] = e[i].ronew * e[i].unew;
tp3[i].W[2][t] = e[i].ronew * e[i].vnew;
tp3[i].W[3][t] = e[i].ronew * e[i].etnew;
}
}
void Fc1new(int i)
{
double fenergyp, fenergym, fmassp, fmassm;
double ML,MR;
double VL, VR; //contravariant velocity of right state and left state
double cL, cR; //speed of sound
double roL, uL, vL, pL, etL;
double roR, uR, vR, pR, etR;
double vnx, vny;
double Fp[4], Fm[4];
roL = e[i].ronew;
uL = e[i].unew;
vL = e[i].vnew;
pL = e[i].pnew;
etL = e[i].etnew;
for(int d = 0; d < 4; d++)
{
roR = e[e[i].neigh[d]].ro;
uR = e[e[i].neigh[d]].u;
vR = e[e[i].neigh[d]].v;
pR = e[e[i].neigh[d]].p;
etR = e[e[i].neigh[d]].et;
vnx = e[i].vn[d].x;
vny = e[i].vn[d].y;
VL = vnx * uL + vny * vL;
VR = vnx * uR + vny * vR;
cL = sqrt(gama * pL / roL);
cR = sqrt(gama * pR / roR);
ML = VL / cL;
MR = VR / cR;
if(ML >= 1.)
{
Fp[0] = roL * VL;
Fp[1] = roL * uL * VL + vnx * pL;
Fp[2] = roL * vL * VL + vny * pL;
Fp[3] = roL * (etL + pL / roL) * VL;
}
else if(abs(ML) < 1)
{
fmassp = roL * cL * pow((ML + 1), 2) / 4.;
fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) / 2.);
Fp[0] = fmassp;
Fp[1] = fmassp * (vnx * (-VL + 2. * cL) / gama + uL);
Fp[2] = fmassp * (vny * (-VL + 2. * cL) / gama + vL);
Fp[3] = fenergyp;
}
else
{
Fp[0] = 0;
Fp[1] = 0;
Fp[2] = 0;
Fp[3] = 0;
}
if(MR >= 1.)
{
Fm[0] = 0;
Fm[1] = 0;
Fm[2] = 0;
Fm[3] = 0;
}
else if(abs(MR) < 1)
{
fmassm = -roR * cR * pow((MR - 1), 2) / 4.;
fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) / 2.);
Fm[0] = fmassm;
Fm[1] = fmassm * (vnx * (-VR - 2. * cR) / gama + uR);
Fm[2] = fmassm * (vny * (-VR - 2. * cR) / gama + vR);
Fm[3] = fenergym;
}
else
{
Fm[0] = roR * VR;
Fm[1] = roR * uR * VR + vnx * pR;
Fm[2] = roR * vR * VR + vny * pR;
Fm[3] = roR * (etR + pR / roR) * VR;
}
for(int a = 0; a < 4; a++)
tp1[i].Fc[d][a] = Fp[a] + Fm[a];
}
}
void Fc1new1(int i)
{
double fenergyp, fenergym, fmassp, fmassm;
double ML,MR;
double VL, VR; //contravariant velocity of right state and left state
double cL, cR; //speed of sound
double roL, uL, vL, pL, etL;
double roR, uR, vR, pR, etR;
double vnx, vny;
double Fp[4], Fm[4];
roL = e[i].ronew;
uL = e[i].unew;
vL = e[i].vnew;
pL = e[i].pnew;
etL = e[i].etnew;
for(int d = 0; d < 4; d++)
{
roR = e[e[i].neigh[d]].ronew;
uR = e[e[i].neigh[d]].unew;
vR = e[e[i].neigh[d]].vnew;
pR = e[e[i].neigh[d]].pnew;
etR = e[e[i].neigh[d]].etnew;
vnx = e[i].vn[d].x;
vny = e[i].vn[d].y;
VL = vnx * uL + vny * vL;
VR = vnx * uR + vny * vR;
cL = sqrt(gama * pL / roL);
cR = sqrt(gama * pR / roR);
ML = VL / cL;
MR = VR / cR;
if(ML >= 1.)
{
Fp[0] = roL * VL;
Fp[1] = roL * uL * VL + vnx * pL;
Fp[2] = roL * vL * VL + vny * pL;
Fp[3] = roL * (etL + pL / roL) * VL;
}
else if(abs(ML) < 1)
{
fmassp = roL * cL * pow((ML + 1), 2) / 4.;
fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) / 2.);
Fp[0] = fmassp;
Fp[1] = fmassp * (vnx * (-VL + 2. * cL) / gama + uL);
Fp[2] = fmassp * (vny * (-VL + 2. * cL) / gama + vL);
Fp[3] = fenergyp;
}
else
{
Fp[0] = 0;
Fp[1] = 0;
Fp[2] = 0;
Fp[3] = 0;
}
if(MR >= 1.)
{
Fm[0] = 0;
Fm[1] = 0;
Fm[2] = 0;
Fm[3] = 0;
}
else if(abs(MR) < 1)
{
fmassm = -roR * cR * pow((MR - 1), 2) / 4.;
fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) / 2.);
Fm[0] = fmassm;
Fm[1] = fmassm * (vnx * (-VR - 2. * cR) / gama + uR);
Fm[2] = fmassm * (vny * (-VR - 2. * cR) / gama + vR);
Fm[3] = fenergym;
}
else
{
Fm[0] = roR * VR;
Fm[1] = roR * uR * VR + vnx * pR;
Fm[2] = roR * vR * VR + vny * pR;
Fm[3] = roR * (etR + pR / roR) * VR;
}
for(int a = 0; a < 4; a++)
tp1[i].Fc[d][a] = Fp[a] + Fm[a];
}
}
void Fv1(int i)
{
double ro, u, v, p, et, mu;
double vnx, vny;
double gradTx, gradTy, gradux, graduy, gradvx, gradvy, qx, qy;
double taoxx, taoxy, taoyy;
for(int d = 0; d < 4; d++)
{
vnx = e[i].vn[d].x;
vny = e[i].vn[d].y;
ro = (e[i].ro + e[e[i].neigh[d]].ro) / 2.;
u = (e[i].u + e[e[i].neigh[d]].u) / 2.;
v = (e[i].v + e[e[i].neigh[d]].v) / 2.;
p = (e[i].ro + e[e[i].neigh[d]].p) / 2.;
et = (e[i].et + e[e[i].neigh[d]].et) / 2.;
mu = (e[i].mu + e[e[i].neigh[d]].mu) / 2.;
gradux = (e[e[i].neigh[d]].u - e[i].u) / e[i].rm[d] * e[i].r[d].x / e[i].rm[d];
graduy = (e[e[i].neigh[d]].u - e[i].u) / e[i].rm[d] * e[i].r[d].y / e[i].rm[d];
gradvx = (e[e[i].neigh[d]].v - e[i].v) / e[i].rm[d] * e[i].r[d].x / e[i].rm[d];
gradvy = (e[e[i].neigh[d]].v - e[i].v) / e[i].rm[d] * e[i].r[d].y / e[i].rm[d];
gradTx = (e[e[i].neigh[d]].T - e[i].T) / e[i].rm[d] * e[i].r[d].x / e[i].rm[d];
gradTy = (e[e[i].neigh[d]].T - e[i].T) / e[i].rm[d] * e[i].r[d].y / e[i].rm[d];
taoxx = mu / Reinf * (4. / 3. * gradux - 2. / 3. * gradvy);
taoxy = mu / Reinf * (graduy + gradvx);
taoyy = mu / Reinf * (4. / 3. * gradvy - 2. / 3. * gradux);
qx = mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTx;
qy = mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTy;
tp2[i].Fv[d][0] = 0;
tp2[i].Fv[d][1] = vnx * taoxx + vny * taoxy;
tp2[i].Fv[d][2] = vnx * taoxy + vny * taoyy;
tp2[i].Fv[d][3] = vnx * (u * taoxx + v * taoxy + qx) + vny * (u * taoxy + v * taoyy + qy);
}
}
| 18.888679
| 145
| 0.386775
|
rocketcrush
|
38ef2670a4f65f2b81725468725d81d53a46c3c9
| 392
|
hpp
|
C++
|
08_pass-by-reference/include/vehicle.hpp
|
JuliusDiestra/cpp-sandbox
|
6fa3bcb2a284e58136168e1952a8a54621232621
|
[
"MIT"
] | null | null | null |
08_pass-by-reference/include/vehicle.hpp
|
JuliusDiestra/cpp-sandbox
|
6fa3bcb2a284e58136168e1952a8a54621232621
|
[
"MIT"
] | null | null | null |
08_pass-by-reference/include/vehicle.hpp
|
JuliusDiestra/cpp-sandbox
|
6fa3bcb2a284e58136168e1952a8a54621232621
|
[
"MIT"
] | null | null | null |
#ifndef TOKEN_VEHICLE_H_
#define TOKEN_VEHICLE_H_
#include <iostream>
#include <memory>
class Vehicle
{
public:
Vehicle();
float GetVelocity();
float GetAcceleration();
void SetVelocity(float velocity_);
void SetAcceleration(float acceleration_);
private:
float velocity_;
float acceleration_;
};
#endif // TOKEN_VEHICLE_H_
| 17.818182
| 50
| 0.660714
|
JuliusDiestra
|
38f3ed6d74edc2ff689deff592ba87296c98c9f6
| 3,771
|
cpp
|
C++
|
libs/assign/v2/speed/tools.cpp
|
rogard/assign_v2
|
8735f57177dbee57514b4e80c498dd4b89f845e5
|
[
"BSL-1.0"
] | null | null | null |
libs/assign/v2/speed/tools.cpp
|
rogard/assign_v2
|
8735f57177dbee57514b4e80c498dd4b89f845e5
|
[
"BSL-1.0"
] | null | null | null |
libs/assign/v2/speed/tools.cpp
|
rogard/assign_v2
|
8735f57177dbee57514b4e80c498dd4b89f845e5
|
[
"BSL-1.0"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
// Copyright 2010 Manuel Peinado Gallego //
// 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 <ctime>
#include <algorithm>
#include <string>
#include <vector>
#include <iterator>
#include <cstdlib>
#include <boost/bind.hpp>
#include <libs/assign/v2/speed/tools.h>
// http://code.google.com/p/truffle/source/browse/trunk/include/mpg/TimeIt.h
// http://code.google.com/p/truffle/source/browse/trunk/include/mpg/Random.h
// http://www.eternallyconfuzzled.com/arts/jsw_art_rand.aspx
inline double uniform_deviate ( int seed )
{
return seed * ( 1.0 / ( RAND_MAX + 1.0 ) );
}
inline int rand(int M, int N) // Range [M..N)
{
return int(M + uniform_deviate(std::rand()) * (N - M));
}
char rand_letter()
{
return char(rand('a', 'z' + 1));
}
std::string rand_str(int len)
{
std::string result;
std::generate_n(std::back_inserter(result), len, &rand_letter);
return result;
}
std::vector<int>
rand_vec(int max_n)
{
std::vector<int> result(
(std::size_t)mpg::rand(1, max_n)
);
std::generate(
result.begin(),
result.end(),
boost::bind(
&mpg::rand,
0,
20
)
);
return result;
}
namespace mpg
{
namespace detail
{
double clock_diff_to_sec(long clock_diff)
{
return double(clock_diff) / CLOCKS_PER_SEC;
}
template<class Proc>
double time_it_impl(Proc proc, int N) // returns time in microseconds
{
std::clock_t const start = std::clock();
for(int i = 0; i < N; ++i)
proc();
std::clock_t const end = std::clock();
if(clock_diff_to_sec(end - start) < .2)
return time_it_impl(proc, N * 5);
return clock_diff_to_sec(end - start) * (1e6 / N);
}
template<class Proc, class Result>
double time_it_impl(Proc proc, Result & result, int N) // returns time in microseconds
{
std::clock_t const start = std::clock();
for(int i = 0; i < N; ++i)
result = proc();
std::clock_t const end = std::clock();
if(clock_diff_to_sec(end - start) < .2)
return time_it_impl(proc, result, N * 5);
return clock_diff_to_sec(end - start) * (1e6 / N);
}
}
template<class Proc>
double time_it(Proc proc) // returns time in microseconds
{
return detail::time_it_impl(proc, 1);
}
template<class Proc, class Result>
double time_it(Proc proc, Result & result) // returns time in microseconds
{
return detail::time_it_impl(proc, result, 1);
}
}
namespace mpg
{
inline double rand_dbl()
{
return double(::rand()) / RAND_MAX;
}
inline double rand_dbl(double M, double N)
{
return M + rand_dbl() * (N - M);
}
// http://www.eternallyconfuzzled.com/arts/jsw_art_rand.aspx
inline int rand(int M, int N) // Range (M..N)
{
return int(M + std::rand() * ( 1.0 / ( RAND_MAX + 1.0 )) * (N - M));
}
inline char rand_letter()
{
return char(rand('a', 'z' + 1));
}
inline std::string rand_str(int len)
{
std::string result;
result.reserve(len);
for(int i = 0; i < len; ++i)
result.push_back(rand_letter());
return result;
}
}
| 27.129496
| 94
| 0.529568
|
rogard
|
38f659577afa98b56ac96286e15c1d72bdd86810
| 475
|
cpp
|
C++
|
src/LibCraft/renderEngine/ibo.cpp
|
Kenny38GH/Test
|
24c0277de8f98a3b0b3b8a90a300a321a485684c
|
[
"MIT"
] | 1
|
2021-11-24T16:49:48.000Z
|
2021-11-24T16:49:48.000Z
|
src/LibCraft/renderEngine/ibo.cpp
|
leodlplq/IMACraft
|
5fec1729238e7e428bd39543dfd1fad521e16047
|
[
"MIT"
] | null | null | null |
src/LibCraft/renderEngine/ibo.cpp
|
leodlplq/IMACraft
|
5fec1729238e7e428bd39543dfd1fad521e16047
|
[
"MIT"
] | null | null | null |
//
// Created by leodlplq on 18/11/2021.
//
#include "LibCraft/renderEngine/include/ibo.hpp"
ibo::ibo(GLuint *vertices, GLsizeiptr size) {
glGenBuffers(1, &_id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _id);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, vertices, GL_STATIC_DRAW);
}
void ibo::bind() {
glBindBuffer(GL_ARRAY_BUFFER, _id);
}
void ibo::unbind() {
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void ibo::deleteIbo() {
glDeleteBuffers(1, &_id);
}
| 19
| 74
| 0.701053
|
Kenny38GH
|
38fa76819bdbf20fe7f3616974344595930a6254
| 3,293
|
hpp
|
C++
|
src/libsnw_event/future.hpp
|
Sojourn/snw
|
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
|
[
"MIT"
] | null | null | null |
src/libsnw_event/future.hpp
|
Sojourn/snw
|
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
|
[
"MIT"
] | null | null | null |
src/libsnw_event/future.hpp
|
Sojourn/snw
|
e2c5a2bfbf5ad721c01a681c4e094aa35f8c010f
|
[
"MIT"
] | null | null | null |
#include <cassert>
template<typename T>
snw::future<T>::future()
: promise_(nullptr)
, state_(state::broken)
{
}
template<typename T>
snw::future<T>::future(promise<T>* promise)
: promise_(promise)
, state_(state::waiting)
{
}
template<typename T>
snw::future<T>::future(T value)
: promise_(nullptr)
, state_(state::ready)
{
value_.create(std::move(value));
}
template<typename T>
snw::future<T>::future(future&& other)
: promise_(other.promise_)
, state_(other.state_)
{
if(promise_) {
promise_->future_ = this;
}
if(state_ == state::ready) {
value_.create(std::move(*other.value_));
other.value_.destroy();
}
other.promise_ = nullptr;
other.state_ = state::broken;
}
template<typename T>
snw::future<T>::~future() {
if(promise_) {
promise_->future_ = nullptr;
}
if(state_ == state::ready) {
value_.destroy();
}
}
template<typename T>
snw::future<T>& snw::future<T>::operator=(future&& rhs) {
if(this != &rhs) {
// unlink
if(promise_) {
promise_->future_ = nullptr;
}
// clear value
if(state_ == state::ready) {
value_.destroy();
}
// relink
if((promise_ = rhs.promise_)) {
promise_->future_ = this;
}
rhs.promise_ = nullptr;
// take value
if((state_ = rhs.state_) == state::ready) {
value_.create(std::move(*rhs.value_));
rhs.value_.destroy();
}
rhs.state_ = state::broken;
}
return *this;
}
template<typename T>
bool snw::future<T>::is_broken() const {
return state_ == state::broken;
}
template<typename T>
bool snw::future<T>::is_waiting() const {
return state_ == state::waiting;
}
template<typename T>
bool snw::future<T>::has_value() const {
return state_ == state::ready;
}
template<typename T>
T& snw::future<T>::value() {
assert(has_value());
return *value_;
}
template<typename T>
const T& snw::future<T>::value() const {
assert(has_value());
return *value_;
}
template<typename T>
snw::promise<T>::promise()
: future_(nullptr)
{
}
template<typename T>
snw::promise<T>::promise(future<T>* future)
: future_(future)
{
}
template<typename T>
snw::promise<T>::promise(promise&& other)
: future_(other.future_)
{
if(future_) {
other.future_ = nullptr;
future_->promise_ = this;
}
}
template<typename T>
snw::promise<T>::~promise() {
if(future_) {
future_->promise_ = nullptr;
}
}
template<typename T>
snw::promise<T>& snw::promise<T>::operator=(promise<T>&& rhs) {
if(this != &rhs) {
// unlink
if(future_) {
future_->promise_ = nullptr;
}
// relink
if((future_ = rhs.future_)) {
rhs.future_ = nullptr;
future_->promise_ = this;
}
}
return *this;
}
template<typename T>
void snw::promise<T>::set_value(T value) {
if(future_) {
assert(!future_->has_value());
future_->value_.create(std::move(value));
future_->state_ = future<T>::state::ready;
}
}
template<typename T>
snw::future<T> snw::make_ready_future(T value) {
return snw::future<T>(value);
}
| 19.485207
| 63
| 0.57607
|
Sojourn
|
ac0181486adf913dc29ed5cb8a5939bca47e8b2d
| 838
|
hpp
|
C++
|
meta/include/mgs/meta/concepts/input_range.hpp
|
theodelrieu/mgs
|
965a95e3d539447cc482e915f9c44b3439168a4e
|
[
"BSL-1.0"
] | 24
|
2020-07-01T13:45:50.000Z
|
2021-11-04T19:54:47.000Z
|
meta/include/mgs/meta/concepts/input_range.hpp
|
theodelrieu/mgs
|
965a95e3d539447cc482e915f9c44b3439168a4e
|
[
"BSL-1.0"
] | null | null | null |
meta/include/mgs/meta/concepts/input_range.hpp
|
theodelrieu/mgs
|
965a95e3d539447cc482e915f9c44b3439168a4e
|
[
"BSL-1.0"
] | null | null | null |
#pragma once
#include <type_traits>
#include <mgs/meta/concepts/input_iterator.hpp>
#include <mgs/meta/concepts/range.hpp>
#include <mgs/meta/detected.hpp>
#include <mgs/meta/iterator_t.hpp>
namespace mgs
{
namespace meta
{
template <typename T>
struct is_input_range
{
private:
using Iterator = meta::detected_t<iterator_t, T>;
public:
using requirements = std::tuple<is_range<T>, is_input_iterator<Iterator>>;
static constexpr bool value =
is_range<T>::value && is_input_iterator<Iterator>::value;
static constexpr int trigger_static_asserts()
{
static_assert(value, "T does not model meta::input_range");
return 1;
}
};
template <typename T>
constexpr auto is_input_range_v = is_input_range<T>::value;
template <typename T, typename = std::enable_if_t<is_input_range_v<T>>>
using input_range = T;
}
}
| 20.95
| 76
| 0.74105
|
theodelrieu
|
ac0483ad1b7c2d1c61cf0a68a621281d07889c6e
| 194
|
cpp
|
C++
|
OCT18B/CHSERVE.cpp
|
Chhekur/codechef-solutions
|
14ca902ea693139de13ffe5b9f602447bf34b79f
|
[
"MIT"
] | 1
|
2019-03-25T14:14:47.000Z
|
2019-03-25T14:14:47.000Z
|
OCT18B/CHSERVE.cpp
|
Chhekur/codechef-solutions
|
14ca902ea693139de13ffe5b9f602447bf34b79f
|
[
"MIT"
] | null | null | null |
OCT18B/CHSERVE.cpp
|
Chhekur/codechef-solutions
|
14ca902ea693139de13ffe5b9f602447bf34b79f
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
int main(void){
int t;cin>>t;
while(t--){
long a,b,c;cin>>a>>b>>c;
long e = (a + b) / c;
if(e % 2 == 0)cout<<"CHEF\n";
else cout<<"COOK\n";
}
}
| 17.636364
| 31
| 0.541237
|
Chhekur
|
f19f54632a9a42642580b073ddb19973492bd572
| 5,582
|
cpp
|
C++
|
Source/Gui3D-master/Gui3DPanel.cpp
|
shanefarris/CoreGameEngine
|
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
|
[
"MIT"
] | 3
|
2019-04-12T15:22:53.000Z
|
2022-01-05T02:59:56.000Z
|
Source/Gui3D-master/Gui3DPanel.cpp
|
shanefarris/CoreGameEngine
|
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
|
[
"MIT"
] | null | null | null |
Source/Gui3D-master/Gui3DPanel.cpp
|
shanefarris/CoreGameEngine
|
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
|
[
"MIT"
] | 2
|
2019-04-10T22:46:21.000Z
|
2020-05-27T16:21:37.000Z
|
/*
Gui3D
-------
Copyright (c) 2012 Valentin Frechaud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "Gui3DPanel.h"
#include "Gui3DPanelColors.h"
namespace Gui3D
{
using namespace std;
Panel::Panel(Gui3D* gui,
Ogre::SceneManager* sceneMgr,
const Ogre::Vector2& size,
Ogre::Real distanceFromPanelToInteractWith,
const Ogre::String& atlasName,
const Ogre::String& name)
: PanelContainer(gui, size),
mDistanceFromPanelToInteractWith(distanceFromPanelToInteractWith),
mNode(NULLPTR), mPanelCameraNode(NULLPTR), mScreenRenderable(NULLPTR)
{
mScreenRenderable =
gui->createScreenRenderable(Ogre::Vector2(mSize.x/100, mSize.y/100), atlasName, name);
mNode = sceneMgr->getRootSceneNode()->createChildSceneNode();
mNode->attachObject(mScreenRenderable);
mPanelCameraNode = mNode->createChildSceneNode();
mPanelCameraNode->setPosition(-1, 0, 7);
mPanelCameraNode->lookAt(mNode->getPosition(), Ogre::Node::TS_PARENT);
mGUILayer = gui->createLayer(mScreenRenderable, name);
mBackground = mGUILayer->createRectangle(0, 0, mSize.x, mSize.y);
if (getPanelColors()->panelBackgroundSpriteName.length() == 0 ||
getPanelColors()->panelBackgroundSpriteName == "none")
{
mBackground->background_gradient(mGui3D->getPanelColors()->panelGradientType,
mGui3D->getPanelColors()->panelGradientColorStart,
mGui3D->getPanelColors()->panelGradientColorEnd);
mBackground->border(mGui3D->getPanelColors()->panelBorderSize,
mGui3D->getPanelColors()->panelBorder);
}
else
mBackground->background_image(getPanelColors()->panelBackgroundSpriteName);
// Create an empty mouse pointer which follow the mouse cursor
mMousePointer = mGUILayer->createRectangle(0, 0, 0, 0);
showInternalMousePointer();
}
Panel::~Panel()
{
for (size_t i=0; i < mPanelElements.size(); i++)
delete mPanelElements[i];
// Destroy all elements that had been created on the screen renderable
mGui3D->destroyScreenRenderable(mScreenRenderable);
}
void Panel::setDistanceFromPanelToInteractWith(Ogre::Real distanceFromPanelToInteractWith)
{
mDistanceFromPanelToInteractWith = distanceFromPanelToInteractWith;
}
bool Panel::injectMouseMoved(const Ogre::Ray& ray)
{
Ogre::Matrix4 transform;
transform.makeTransform(mNode->getPosition(), mNode->getScale(), mNode->getOrientation());
Ogre::AxisAlignedBox aabb = mScreenRenderable->getBoundingBox();
aabb.transform(transform);
pair<bool, Ogre::Real> result = Ogre::Math::intersects(ray, aabb);
if (result.first == false)
{
unOverAllElements();
return false;
}
Ogre::Vector3 a,b,c,d;
Ogre::Vector2 halfSize = (mSize/100) * 0.5f;
a = transform * Ogre::Vector3(-halfSize.x,-halfSize.y,0);
b = transform * Ogre::Vector3( halfSize.x,-halfSize.y,0);
c = transform * Ogre::Vector3(-halfSize.x, halfSize.y,0);
d = transform * Ogre::Vector3( halfSize.x, halfSize.y,0);
result = Ogre::Math::intersects(ray, c, b, a);
if (result.first == false)
result = Ogre::Math::intersects(ray, c, d, b);
if (result.first == false)
{
unOverAllElements();
return false;
}
if (result.second > mDistanceFromPanelToInteractWith)
{
unOverAllElements();
return false;
}
Ogre::Vector3 hitPos = (ray.getOrigin() + (ray.getDirection() * result.second));
Ogre::Vector3 localPos = transform.inverse() * hitPos;
localPos.x += halfSize.x;
localPos.y -= halfSize.y;
localPos.x *= 100;
localPos.y *= 100;
// Cursor clip
localPos.x = Ogre::Math::Clamp<Ogre::Real>(localPos.x, 0, mSize.x - 10);
localPos.y = Ogre::Math::Clamp<Ogre::Real>(-localPos.y, 0, mSize.y - 18);
mInternalMousePos = Ogre::Vector2(localPos.x, localPos.y);
mMousePointer->position(mInternalMousePos);
// Let's actualize the "over" for each elements
for (size_t i=0; i < mPanelElements.size(); i++)
mPanelElements[i]->isOver(mInternalMousePos);
return true;
}
}
| 36.966887
| 94
| 0.64296
|
shanefarris
|
f1a4c44e616b221904cda01046e4865fa97fe64e
| 742
|
cpp
|
C++
|
src/LuminoEngine/sandbox/Example_Shader.cpp
|
infinnie/Lumino
|
921caabdbcb91528a2aac290e31d650628bc3bed
|
[
"MIT"
] | null | null | null |
src/LuminoEngine/sandbox/Example_Shader.cpp
|
infinnie/Lumino
|
921caabdbcb91528a2aac290e31d650628bc3bed
|
[
"MIT"
] | null | null | null |
src/LuminoEngine/sandbox/Example_Shader.cpp
|
infinnie/Lumino
|
921caabdbcb91528a2aac290e31d650628bc3bed
|
[
"MIT"
] | null | null | null |
#include <LuminoEngine.hpp>
using namespace ln;
class App_Example_Shader : public Application
{
virtual void onInit() override
{
Engine::renderView()->setGuideGridEnabled(true);
Engine::mainCamera()->addComponent(CameraOrbitControlComponent::create());
auto plane = PlaneMesh::create();
plane->setScale(5);
auto shader = Shader::create(u"C:/Proj/LN/Lumino/src/LuminoEngine/sandbox/Assets/Shader/Ring.fx");
auto mat = Material::create();
mat->setShader(shader);
plane->planeMeshComponent()->setMaterial(mat);
}
virtual void onUpdate() override
{
}
};
void Example_Shader()
{
App_Example_Shader app;
detail::ApplicationHelper::run(&app);
}
| 21.2
| 106
| 0.657682
|
infinnie
|
f1a57afa200e7da6937ae658156a22b31fb8054f
| 456
|
cpp
|
C++
|
Leetcode/35.SearchInsertPosition/SearchInsertPosition.cpp
|
juancgar/CompetitiveProgramming
|
9ff93ba14d9d5f45314a18cc78bd2d44de0b9fec
|
[
"MIT"
] | null | null | null |
Leetcode/35.SearchInsertPosition/SearchInsertPosition.cpp
|
juancgar/CompetitiveProgramming
|
9ff93ba14d9d5f45314a18cc78bd2d44de0b9fec
|
[
"MIT"
] | null | null | null |
Leetcode/35.SearchInsertPosition/SearchInsertPosition.cpp
|
juancgar/CompetitiveProgramming
|
9ff93ba14d9d5f45314a18cc78bd2d44de0b9fec
|
[
"MIT"
] | null | null | null |
int searchInsert(vector<int>& nums, int target) {
int begin = 0;
int end = nums.size();
end > 0 ? end = end-1: end = begin;
int mid;
while(begin <= end)
{
mid = begin + (end-begin)/2;
if(nums[mid] == target)
return mid;
else if(nums[mid] < target)
{
begin = mid+1;
}
else
end = mid-1;
}
return begin;
}
| 22.8
| 50
| 0.414474
|
juancgar
|
f1a68d13344afd1477dfc29135e40432a55a63b1
| 1,052
|
cpp
|
C++
|
extra/news/src/xk/iat/ImageAnnotation/iat-stage/listtool.cpp
|
scignscape/PGVM
|
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
|
[
"BSL-1.0"
] | null | null | null |
extra/news/src/xk/iat/ImageAnnotation/iat-stage/listtool.cpp
|
scignscape/PGVM
|
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
|
[
"BSL-1.0"
] | null | null | null |
extra/news/src/xk/iat/ImageAnnotation/iat-stage/listtool.cpp
|
scignscape/PGVM
|
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
|
[
"BSL-1.0"
] | null | null | null |
#include "listtool.h"
#include "ui_listtool.h"
ListTool::ListTool(QWidget *parent):QDialog(parent),ui(new Ui::ListTool){
ui->setupUi(this);
}
ListTool::~ListTool(){
delete ui;
}
void ListTool::on_textObject_textChanged()
{
}
void ListTool::on_textInstance_textChanged()
{
}
void ListTool::on_AddLine_clicked(){
//QLineEdit *lineEdit = new QLineEdit;
//QLabel *label = new QLabel;
//ui->gridLayout->addWidget(lineEdit,count,0);
//Now you want to access text of all lineEdit you can do it like
/*int iCount = ui->gridLayout->count(); //Total no of LineEdit added on gridLayout dynamically
QString str = tr("");
for(int i = 0; i < iCount; i++)
{
QLayoutItem* pLine = ui->gridLayout->itemAt(i);
QLineEdit* pLineEdit = (QLineEdit*)pLine->widget();
str = pLineEdit->text();
//Now do whatever you want to do with the text
} */
}
void ListTool::on_Save_clicked()
{
}
void ListTool::on_Cancel_clicked()
{
}
| 21.04
| 99
| 0.615019
|
scignscape
|
f1a7d76d699ec0852a16f4325b7452f4240f7166
| 1,244
|
cpp
|
C++
|
source/Input/Queue.cpp
|
kurocha/input
|
619cbe901ebb2cfd9dd97235d30e596edc96aa14
|
[
"MIT",
"Unlicense"
] | null | null | null |
source/Input/Queue.cpp
|
kurocha/input
|
619cbe901ebb2cfd9dd97235d30e596edc96aa14
|
[
"MIT",
"Unlicense"
] | null | null | null |
source/Input/Queue.cpp
|
kurocha/input
|
619cbe901ebb2cfd9dd97235d30e596edc96aa14
|
[
"MIT",
"Unlicense"
] | null | null | null |
//
// Queue.cpp
// This file is part of the "Input" project and released under the MIT License.
//
// Created by Samuel Williams on 23/2/2019.
// Copyright, 2019, by Samuel Williams. All rights reserved.
//
#include "Queue.hpp"
#include "ResizeEvent.hpp"
#include "ButtonEvent.hpp"
#include "MotionEvent.hpp"
#include "RenderEvent.hpp"
#include "FocusEvent.hpp"
namespace Input
{
Queue::Queue()
{
}
void Queue::dequeue(Handler & handler)
{
const auto & items = _queue.dequeue();
for (auto & item : items) {
handler.process(reinterpret_cast<const Event &>(item));
}
}
bool Queue::process(const ResizeEvent & event)
{
_queue.emplace(std::make_unique<ResizeEvent>(event));
return true;
}
bool Queue::process(const ButtonEvent & event)
{
_queue.emplace(std::make_unique<ButtonEvent>(event));
return true;
}
bool Queue::process(const MotionEvent & event)
{
_queue.emplace(std::make_unique<MotionEvent>(event));
return true;
}
bool Queue::process(const RenderEvent & event)
{
_queue.emplace(std::make_unique<RenderEvent>(event));
return true;
}
bool Queue::process(const FocusEvent & event)
{
_queue.emplace(std::make_unique<FocusEvent>(event));
return true;
}
}
| 18.567164
| 80
| 0.686495
|
kurocha
|
f1a8e7362e9df7d5424c5caab15669ef09c32c1b
| 1,280
|
cpp
|
C++
|
3/main.cpp
|
ls171433/leetcode
|
863d562153382f3d1480deb7ab453c15a72da6c4
|
[
"MIT"
] | null | null | null |
3/main.cpp
|
ls171433/leetcode
|
863d562153382f3d1480deb7ab453c15a72da6c4
|
[
"MIT"
] | null | null | null |
3/main.cpp
|
ls171433/leetcode
|
863d562153382f3d1480deb7ab453c15a72da6c4
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
class Solution
{
public:
int lengthOfLongestSubstring(string s)
{
int longest = 0;
size_t indexs[256];
size_t repeated_index = (size_t)(-1);
for (size_t &index : indexs)
{
index = (size_t)(-1);
}
for (size_t i = 0; i < s.size(); ++i)
{
unsigned char c = s[i];
if (indexs[c] != (size_t)(-1))
{
if (repeated_index == (size_t)(-1))
{
longest = max(longest, (int)(i));
repeated_index = indexs[c];
}
else
{
longest = max(longest, (int)(i - repeated_index - 1));
repeated_index = max(repeated_index, indexs[c]);
}
}
indexs[c] = i;
}
if (repeated_index == (size_t)(-1))
{
return s.size();
}
else
{
longest = max(longest, (int)(s.size() - repeated_index - 1));
}
return longest;
}
};
int main()
{
auto result = Solution().lengthOfLongestSubstring("abba");
cout << result << endl;
}
| 22.45614
| 74
| 0.435156
|
ls171433
|
f1b0a041aa928c91071daf898bd919066ceeba51
| 1,727
|
cpp
|
C++
|
SDL Game/SDL Game/Behaviours/Mover.cpp
|
BrunoAOR/SDL-Game
|
090a09e2c19d18b000769f353c5e7727d60fe5f6
|
[
"MIT"
] | null | null | null |
SDL Game/SDL Game/Behaviours/Mover.cpp
|
BrunoAOR/SDL-Game
|
090a09e2c19d18b000769f353c5e7727d60fe5f6
|
[
"MIT"
] | null | null | null |
SDL Game/SDL Game/Behaviours/Mover.cpp
|
BrunoAOR/SDL-Game
|
090a09e2c19d18b000769f353c5e7727d60fe5f6
|
[
"MIT"
] | null | null | null |
#include "Mover.h"
#include "Engine/API/API.h"
#include "Engine/GameObjects/GameObject.h"
#include "Engine/Components/Transforms/Transform.h"
#include "Engine/Vector2.h"
Mover::Mover()
{
useWASD = false;
speed = 100;
speedStep = 50;
}
void Mover::update()
{
Vector2 motion(0, 0);
// Check speed
if (InputAPI::getKeyDown(SDL_SCANCODE_KP_PLUS))
{
speed += speedStep;
printf("Speed: %i\n", speed);
}
if (InputAPI::getKeyDown(SDL_SCANCODE_KP_MINUS))
{
speed -= speedStep;
printf("Speed: %i\n", speed);
}
// Check motion
if (useWASD)
{
moveWithWASD(motion.x, motion.y);
}
else
{
moveWithArrows(motion.x, motion.y);
}
if (motion.x != 0 || motion.y != 0)
{
if (motion.x != 0 && motion.y != 0) {
double sqrt2 = sqrt(2);
motion.x /= sqrt2;
motion.y /= sqrt2;
}
double elapsedSeconds = TimeAPI::deltaTime() / 1000.0;
motion.x *= speed * elapsedSeconds;
motion.y *= speed * elapsedSeconds;
auto transform = gameObject()->transform.lock();
Vector2 currentPos = transform->getLocalPosition();
Vector2 targetPos = currentPos + motion;
transform->setLocalPosition(targetPos);
}
}
void Mover::moveWithArrows(double& x, double& y)
{
x = 0;
y = 0;
if (InputAPI::getKey(SDL_SCANCODE_UP))
{
y = +1;
}
if (InputAPI::getKey(SDL_SCANCODE_DOWN))
{
y = -1;
}
if (InputAPI::getKey(SDL_SCANCODE_LEFT))
{
x = -1;
}
if (InputAPI::getKey(SDL_SCANCODE_RIGHT))
{
x = +1;
}
}
void Mover::moveWithWASD(double& x, double& y)
{
x = 0;
y = 0;
if (InputAPI::getKey(SDL_SCANCODE_W))
{
y = +1;
}
if (InputAPI::getKey(SDL_SCANCODE_S))
{
y = -1;
}
if (InputAPI::getKey(SDL_SCANCODE_A))
{
x = -1;
}
if (InputAPI::getKey(SDL_SCANCODE_D))
{
x = +1;
}
}
| 16.292453
| 56
| 0.634627
|
BrunoAOR
|
f1b6df40f02c068d419034453b13e697531733b3
| 1,169
|
cpp
|
C++
|
test/ExtensionWordTest.cpp
|
PaulTrampert/GenieSys
|
637e7f764bc7faac8d0b5afcf22646e200562f6a
|
[
"MIT"
] | null | null | null |
test/ExtensionWordTest.cpp
|
PaulTrampert/GenieSys
|
637e7f764bc7faac8d0b5afcf22646e200562f6a
|
[
"MIT"
] | 82
|
2020-12-17T04:03:10.000Z
|
2022-03-24T17:54:28.000Z
|
test/ExtensionWordTest.cpp
|
PaulTrampert/GenieSys
|
637e7f764bc7faac8d0b5afcf22646e200562f6a
|
[
"MIT"
] | null | null | null |
//
// Created by paul.trampert on 11/26/2020.
//
#include <gtest/gtest.h>
#include <GenieSys/ExtensionWord.h>
TEST(ExtensionWord, DecodeBriefExtensionWord) {
uint16_t word = 0b1010101000000011;
auto result = GenieSys::ExtensionWord(word);
EXPECT_EQ(GenieSys::M68K_REG_TYPE_ADDR, result.getIdxRegType());
EXPECT_EQ((uint8_t)2, result.getIdxRegAddr());
EXPECT_EQ(GenieSys::EXT_WORD_IDX_SIZE_LONG_WORD, result.getIdxSize());
EXPECT_EQ(1, result.getScale());
EXPECT_TRUE(result.isBrief());
EXPECT_EQ(3, result.getDisplacement());
}
TEST(ExtensionWord, DecodeExtensionWord) {
uint16_t word = 0b1010101110100011;
auto result = GenieSys::ExtensionWord(word);
EXPECT_EQ(GenieSys::M68K_REG_TYPE_ADDR, result.getIdxRegType());
EXPECT_EQ((uint8_t)2, result.getIdxRegAddr());
EXPECT_EQ(GenieSys::EXT_WORD_IDX_SIZE_LONG_WORD, result.getIdxSize());
EXPECT_EQ(1, result.getScale());
EXPECT_FALSE(result.isBrief());
EXPECT_EQ(true, result.getBaseRegSuppress());
EXPECT_EQ(false, result.getIndexSuppress());
EXPECT_EQ(2, result.getBaseDisplacementSize());
EXPECT_EQ(3, result.getIndexIndirectSelection());
}
| 37.709677
| 74
| 0.740804
|
PaulTrampert
|
f1b77b495c0fe88863915c977078ffa07b1236a2
| 604
|
cpp
|
C++
|
Chapter_6_Loops/Program1.cpp
|
othneildrew/CPP-Programming-Practices
|
27a20c00b395446a7d2e0dd4b199f4cd9e35591b
|
[
"MIT"
] | 1
|
2020-12-03T15:26:20.000Z
|
2020-12-03T15:26:20.000Z
|
Chapter_6_Loops/Program1.cpp
|
othneildrew/CPP-Programming-Practices
|
27a20c00b395446a7d2e0dd4b199f4cd9e35591b
|
[
"MIT"
] | null | null | null |
Chapter_6_Loops/Program1.cpp
|
othneildrew/CPP-Programming-Practices
|
27a20c00b395446a7d2e0dd4b199f4cd9e35591b
|
[
"MIT"
] | null | null | null |
// Chapter 6: Program 1
/***
Write a C++ program to read ten students' names and display them.
**/
# include <iostream>
# include <string>
using namespace std;
int main(void)
{
string Name;
int LCV, Size = 10;
for(LCV = 0; LCV < Size; LCV++)
{
if(LCV == 0)
cout <<"\n\t Please enter student's name:\n";
else
cout <<"\n\t Please enter another student's name: \n";
cin >> Name;
cout <<"Student #" << LCV + 1 << " is " << Name << endl;
}
system("pause");
return 0;
}
// Code written by: Othneil Drew
| 18.875
| 66
| 0.516556
|
othneildrew
|
f1b7f3bc74e80fa36b8323602b2fbc7fa005694e
| 947
|
cpp
|
C++
|
source/Ch18/main.cpp
|
Koma52/UDProg-Introduction
|
ca8cf7f7a2c11559d4f5b3c8ad5dd55040e99762
|
[
"CC0-1.0"
] | null | null | null |
source/Ch18/main.cpp
|
Koma52/UDProg-Introduction
|
ca8cf7f7a2c11559d4f5b3c8ad5dd55040e99762
|
[
"CC0-1.0"
] | null | null | null |
source/Ch18/main.cpp
|
Koma52/UDProg-Introduction
|
ca8cf7f7a2c11559d4f5b3c8ad5dd55040e99762
|
[
"CC0-1.0"
] | 1
|
2020-09-12T11:41:44.000Z
|
2020-09-12T11:41:44.000Z
|
#include "../std_lib_facilities.h"
int* ga = new int[10] { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 };
void f(int* array, int n){
int* la = new int[10];
for (int i = 0; i < 10; ++i){
la[i] = ga[i];
}
for (int i = 0; i < 10; ++i){
cout << la[i] << " ";
}
cout << endl;
int* p = new int[n];
for (int i = 0; i < n; ++i){
p[i] = array[i];
}
cout << "Elements of free-store array: " << endl;
for (int i = 0; i < n; ++i){
cout << p[i] << " ";
}
cout << endl;
delete[] p;
}
int main()
try {
f(ga, 10);
int* aa = new int[10];
int x = 1;
for (int i = 2; i < 12; ++i){
aa[i-2] = x;
x*=i;
}
cout << "---------------------------" << endl;
f(aa, 10);
return 0;
}
catch (exception& e) {
cerr << "error: " << e.what() << '\n';
return 1;
}
catch (...) {
cerr << "Oops: unknown exception!\n";
return 2;
}
| 14.796875
| 64
| 0.393875
|
Koma52
|
f1b89d4d3c8d3d92409904dd78483cd83ba357f6
| 1,554
|
cpp
|
C++
|
client/main.cpp
|
master-gekus/thrift_test
|
cbf6b763706f1212e4fcac377b2a5225ea7cd033
|
[
"Unlicense"
] | null | null | null |
client/main.cpp
|
master-gekus/thrift_test
|
cbf6b763706f1212e4fcac377b2a5225ea7cd033
|
[
"Unlicense"
] | null | null | null |
client/main.cpp
|
master-gekus/thrift_test
|
cbf6b763706f1212e4fcac377b2a5225ea7cd033
|
[
"Unlicense"
] | null | null | null |
#include "SharedService.h"
#include <cstdio>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TBufferTransports.h>
using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace ::thrifts;
int main(int argc, char* argv[])
{
int port = 9090;
stdcxx::shared_ptr<TTransport> socket(new TSocket("localhost", port));
stdcxx::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
stdcxx::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
SharedServiceClient client(protocol);
try {
transport->open();
bool res = client.putPair(1, "Test!");
printf("1. res = %s\n", res ? "true" : "false");
res = client.putPair(2, "Test 2");
printf("2. res = %s\n", res ? "true" : "false");
SharedStruct s;
client.getStruct(s, 1);
printf("3. s.value = \"%s\"\n", s.value.c_str());
res = client.putPair(2, "Test New");
printf("4. res = %s\n", res ? "true" : "false");
client.getStruct(s, 2);
printf("5. s.value = \"%s\"\n", s.value.c_str());
client.replacePair(2, "Test New");
printf("6. replacePair\n");
client.getStruct(s, 2);
printf("7. s.value = \"%s\"\n", s.value.c_str());
printf("All testst finished!\n");
} catch (TException& tx) {
printf("ERROR: %s\n", tx.what());
return 1;
}
return 0;
}
| 27.75
| 77
| 0.602317
|
master-gekus
|
f1b9ddc57c32d1c2385dbe1d61224e24c989287a
| 1,330
|
cpp
|
C++
|
engine/time/source/SwimmingMovementAccumulationChecker.cpp
|
sidav/shadow-of-the-wyrm
|
747afdeebed885b1a4f7ab42f04f9f756afd3e52
|
[
"MIT"
] | 60
|
2019-08-21T04:08:41.000Z
|
2022-03-10T13:48:04.000Z
|
engine/time/source/SwimmingMovementAccumulationChecker.cpp
|
cleancoindev/shadow-of-the-wyrm
|
51b23e98285ecb8336324bfd41ebf00f67b30389
|
[
"MIT"
] | 3
|
2021-03-18T15:11:14.000Z
|
2021-10-20T12:13:07.000Z
|
engine/time/source/SwimmingMovementAccumulationChecker.cpp
|
cleancoindev/shadow-of-the-wyrm
|
51b23e98285ecb8336324bfd41ebf00f67b30389
|
[
"MIT"
] | 8
|
2019-11-16T06:29:05.000Z
|
2022-01-23T17:33:43.000Z
|
#include "CombatManager.hpp"
#include "Game.hpp"
#include "MapUtils.hpp"
#include "SwimmingCalculator.hpp"
#include "SwimmingMovementAccumulationChecker.hpp"
#include "RNG.hpp"
// Check for damage due to swimming past the point of exhaustion.
void SwimmingMovementAccumulationChecker::check(CreaturePtr creature)
{
if (creature)
{
SwimmingCalculator sc;
MapPtr current_map = Game::instance().get_current_map();
bool submerged = false;
if (current_map != nullptr)
{
TilePtr tile = MapUtils::get_tile_for_creature(current_map, creature);
submerged = tile && tile->get_submerged();
}
ulonglong max_swimming_time = static_cast<ulonglong>(sc.calculate_maximum_swimming_time(submerged, creature, creature->get_breathes()));
MovementAccumulation& movement_accumulation = creature->get_movement_accumulation_ref();
ulonglong time_in_water = movement_accumulation.get_minutes_on_super_type_given_movement();
// If a creature has water breathing, it can basically swim forever.
if ((time_in_water > max_swimming_time) && !creature->can_breathe(BreatheType::BREATHE_TYPE_WATER))
{
swim.process(creature, nullptr);
}
else
{
if (RNG::percent_chance(10))
{
sm.check_skill(creature, SkillType::SKILL_GENERAL_SWIMMING);
}
}
}
}
| 32.439024
| 140
| 0.728571
|
sidav
|
f1bdd927a07345f35ee7e40bd6e687692fc0f579
| 3,795
|
cpp
|
C++
|
src/Engine/TextLine.cpp
|
Terryhata6/Mengine
|
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
|
[
"MIT"
] | null | null | null |
src/Engine/TextLine.cpp
|
Terryhata6/Mengine
|
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
|
[
"MIT"
] | null | null | null |
src/Engine/TextLine.cpp
|
Terryhata6/Mengine
|
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
|
[
"MIT"
] | null | null | null |
#include "TextLine.h"
#include "Kernel/Logger.h"
#include "utf8.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
TextLine::TextLine( uint32_t _layout, float _charOffset )
: m_layout( _layout )
, m_length( 0.f )
, m_charOffset( _charOffset )
{
}
//////////////////////////////////////////////////////////////////////////
TextLine::~TextLine()
{
}
//////////////////////////////////////////////////////////////////////////
bool TextLine::initialize( uint32_t _fontId, const TextFontInterfacePtr & _font, const U32String & _text )
{
U32String::size_type text_size = _text.size();
m_charsData.reserve( text_size );
bool successful = true;
for( U32String::const_iterator
it = _text.begin(),
it_end = _text.end();
it != it_end;
++it )
{
GlyphCode glyphChar = (GlyphCode)*it;
U32String::const_iterator it_kerning = it;
std::advance( it_kerning, 1 );
GlyphCode glyphCharNext = (it_kerning != _text.end()) ? *it_kerning : 0;
Glyph glyph;
if( _font->getGlyph( m_layout, glyphChar, glyphCharNext, &glyph ) == false )
{
LOGGER_ERROR( "fontName '%s' invalid glyph %u next %u"
, _font->getName().c_str()
, glyphChar
, glyphCharNext
);
successful = false;
continue;
}
CharData charData;
charData.code = glyphChar;
charData.advance = glyph.advance;
charData.offset = glyph.offset;
charData.size = glyph.size;
charData.uv = glyph.uv;
charData.fontId = _fontId;
charData.texture = glyph.texture;
m_charsData.emplace_back( charData );
m_length += charData.advance + m_charOffset;
}
m_length -= m_charOffset;
return successful;
}
//////////////////////////////////////////////////////////////////////////
uint32_t TextLine::getCharsDataSize() const
{
VectorCharData::size_type charsDataSize = m_charsData.size();
return (uint32_t)charsDataSize;
}
//////////////////////////////////////////////////////////////////////////
float TextLine::getLength() const
{
return m_length;
}
//////////////////////////////////////////////////////////////////////////
const VectorCharData & TextLine::getCharsData() const
{
return m_charsData;
}
//////////////////////////////////////////////////////////////////////////
void TextLine::calcCharPosition( const CharData & _cd, const mt::vec2f & _offset, float _charScale, uint32_t _index, mt::vec3f * const _pos ) const
{
mt::vec2f size = _cd.size * _charScale;
mt::vec2f offset = _offset + _cd.offset * _charScale;
const float size_xi[] = {0.f, size.x, size.x, 0.f};
const float size_yi[] = {0.f, 0.f, size.y, size.y};
float size_x = size_xi[_index];
float size_y = size_yi[_index];
_pos->x = offset.x + size_x;
_pos->y = offset.y + size_y;
_pos->z = 0.f;
}
//////////////////////////////////////////////////////////////////////////
void TextLine::advanceCharOffset( const CharData & _cd, float _charScale, mt::vec2f * const _offset ) const
{
_offset->x += (_cd.advance + m_charOffset) * _charScale;
}
//////////////////////////////////////////////////////////////////////////
}
| 33.289474
| 152
| 0.436627
|
Terryhata6
|
f1beb97847c09949f33987b4e64fb137edf47025
| 74
|
cpp
|
C++
|
src/rosic_NumberManipulations.cpp
|
NeoBirth/rs-303
|
bf3cda07e354809b2bdee389d8ee230210f741c4
|
[
"MIT"
] | 13
|
2019-11-04T17:54:43.000Z
|
2022-03-30T12:31:58.000Z
|
src/rosic_NumberManipulations.cpp
|
NeoBirth/rs-303
|
bf3cda07e354809b2bdee389d8ee230210f741c4
|
[
"MIT"
] | null | null | null |
src/rosic_NumberManipulations.cpp
|
NeoBirth/rs-303
|
bf3cda07e354809b2bdee389d8ee230210f741c4
|
[
"MIT"
] | 5
|
2020-04-10T06:23:43.000Z
|
2022-03-12T18:15:59.000Z
|
#include "rosic_NumberManipulations.h"
using namespace rosic;
| 9.25
| 39
| 0.702703
|
NeoBirth
|
f1becde937ef49393472de6ff5c3a4cdc6354ea8
| 51,253
|
cpp
|
C++
|
source/game/anim/Anim.cpp
|
JasonHutton/QWTA
|
7f42dc70eb230cf69a8048fc98d647a486e752f1
|
[
"MIT"
] | 2
|
2021-05-02T18:37:48.000Z
|
2021-07-18T16:18:14.000Z
|
source/game/anim/Anim.cpp
|
JasonHutton/QWTA
|
7f42dc70eb230cf69a8048fc98d647a486e752f1
|
[
"MIT"
] | null | null | null |
source/game/anim/Anim.cpp
|
JasonHutton/QWTA
|
7f42dc70eb230cf69a8048fc98d647a486e752f1
|
[
"MIT"
] | null | null | null |
// Copyright (C) 2007 Id Software, Inc.
//
#include "../precompiled.h"
#pragma hdrstop
#if defined( _DEBUG ) && !defined( ID_REDIRECT_NEWDELETE )
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "Anim.h"
#include "../../framework/Licensee.h"
bool idAnimManager::forceExport = false;
idCVar anim_reduced( "anim_reduced", "1", CVAR_BOOL|CVAR_ARCHIVE, "" );
idCVar r_writeAnimB( "r_writeAnimB", "0", CVAR_BOOL, "Write out binary versions of animations." );
idCVar r_loadAnimB( "r_loadAnimB", "1", CVAR_BOOL, "Attempt loading of binary version of animations." );
/*
===============================================================================
idAnimBlendNetworkInfo_Minimal
===============================================================================
*/
/*
==================
idAnimBlendNetworkInfo_Minimal::MakeDefault
==================
*/
void idAnimBlend::idAnimBlendNetworkInfo_Minimal::MakeDefault( void ) {
startTime = 0;
endTime = 0;
blendStartTime = 0;
blendDuration = 0;
blendStartValue = 0.f;
blendEndValue = 0.f;
animNum = -1;
}
/*
==================
idAnimBlendNetworkInfo_Minimal::operator=
==================
*/
void idAnimBlend::idAnimBlendNetworkInfo_Minimal::operator=( const idAnimBlend& anim ) {
startTime = anim.starttime;
endTime = anim.endtime;
blendStartTime = anim.blendStartTime;
blendDuration = anim.blendDuration;
blendStartValue = anim.blendStartValue;
blendEndValue = anim.blendEndValue;
animNum = anim.animNum;
}
/*
==================
idAnimBlendNetworkInfo_Minimal::Write
==================
*/
void idAnimBlend::idAnimBlendNetworkInfo_Minimal::Write( idAnimBlend& anim ) const {
anim.starttime = startTime;
anim.endtime = endTime;
anim.blendStartTime = blendStartTime;
anim.blendDuration = blendDuration;
anim.blendStartValue = blendStartValue;
anim.blendEndValue = blendEndValue;
anim.animNum = animNum;
}
/*
==================
idAnimBlendNetworkInfo_Minimal::operator==
==================
*/
bool idAnimBlend::idAnimBlendNetworkInfo_Minimal::operator==( const idAnimBlendNetworkInfo_Minimal& rhs ) const {
return startTime == rhs.startTime &&
endTime == rhs.endTime &&
blendStartTime == rhs.blendStartTime &&
blendDuration == rhs.blendDuration &&
blendStartValue == rhs.blendStartValue &&
blendEndValue == rhs.blendEndValue &&
animNum == rhs.animNum;
}
/*
==================
idAnimBlendNetworkInfo_Minimal::operator==
==================
*/
bool idAnimBlend::idAnimBlendNetworkInfo_Minimal::operator==( const idAnimBlend& rhs ) const {
return startTime == rhs.starttime &&
endTime == rhs.endtime &&
blendStartTime == rhs.blendStartTime &&
blendDuration == rhs.blendDuration &&
blendStartValue == rhs.blendStartValue &&
blendEndValue == rhs.blendEndValue &&
animNum == rhs.animNum;
}
/*
==================
idAnimBlend::idAnimBlendNetworkInfo_Minimal::Read
==================
*/
void idAnimBlend::idAnimBlendNetworkInfo_Minimal::Read( const idAnimBlendNetworkInfo_Minimal& base, const idBitMsg& msg ) {
startTime = msg.ReadDeltaLong( base.startTime );
endTime = msg.ReadDeltaLong( base.endTime );
blendStartTime = msg.ReadDeltaLong( base.blendStartTime );
blendDuration = msg.ReadDeltaLong( base.blendDuration );
blendStartValue = msg.ReadDeltaFloat( base.blendStartValue );
blendEndValue = msg.ReadDeltaFloat( base.blendEndValue );
animNum = msg.ReadDeltaShort( base.animNum );
}
/*
==================
idAnimBlend::idAnimBlendNetworkInfo_Minimal::Write
==================
*/
void idAnimBlend::idAnimBlendNetworkInfo_Minimal::Write( const idAnimBlendNetworkInfo_Minimal& base, idBitMsg& msg ) const {
msg.WriteDeltaLong( base.startTime, startTime );
msg.WriteDeltaLong( base.endTime, endTime );
msg.WriteDeltaLong( base.blendStartTime, blendStartTime );
msg.WriteDeltaLong( base.blendDuration, blendDuration );
msg.WriteDeltaFloat( base.blendStartValue,blendStartValue );
msg.WriteDeltaFloat( base.blendEndValue, blendEndValue );
msg.WriteDeltaShort( base.animNum, animNum );
}
/*
==================
idAnimBlend::idAnimBlendNetworkInfo_Minimal::Read
==================
*/
void idAnimBlend::idAnimBlendNetworkInfo_Minimal::Read( idFile* file ) {
}
/*
==================
idAnimBlend::idAnimBlendNetworkInfo_Minimal::Write
==================
*/
void idAnimBlend::idAnimBlendNetworkInfo_Minimal::Write( idFile* file ) const {
}
/***********************************************************************
idMD5Anim
***********************************************************************/
/*
====================
idMD5Anim::idMD5Anim
====================
*/
idMD5Anim::idMD5Anim() {
ref_count = 0;
numFrames = 0;
numJoints = 0;
frameRate = 24;
animLength = 0;
reduced = false;
totaldelta.Zero();
}
/*
====================
idMD5Anim::idMD5Anim
====================
*/
idMD5Anim::~idMD5Anim() {
Free();
}
/*
====================
idMD5Anim::Free
====================
*/
void idMD5Anim::Free( void ) {
numFrames = 0;
numJoints = 0;
frameRate = 24;
animLength = 0;
reduced = false;
name = "";
totaldelta.Zero();
jointInfo.Clear();
bounds.Clear();
componentFrames.Clear();
}
/*
====================
idMD5Anim::NumFrames
====================
*/
int idMD5Anim::NumFrames( void ) const {
return numFrames;
}
/*
====================
idMD5Anim::NumJoints
====================
*/
int idMD5Anim::NumJoints( void ) const {
return numJoints;
}
/*
====================
idMD5Anim::Length
====================
*/
int idMD5Anim::Length( void ) const {
return animLength;
}
/*
=====================
idMD5Anim::TotalMovementDelta
=====================
*/
const idVec3 &idMD5Anim::TotalMovementDelta( void ) const {
return totaldelta;
}
/*
=====================
idMD5Anim::TotalMovementDelta
=====================
*/
const char *idMD5Anim::Name( void ) const {
return name;
}
/*
====================
idMD5Anim::Reload
====================
*/
bool idMD5Anim::Reload( void ) {
idStr filename;
filename = name;
Free();
return LoadAnim( filename );
}
/*
====================
idMD5Anim::Allocated
====================
*/
size_t idMD5Anim::Allocated( void ) const {
size_t size = bounds.Allocated() + jointInfo.Allocated() + baseFrame.Allocated() + componentFrames.Allocated() + name.Allocated();
return size;
}
/*
====================
idMD5Anim::LoadAnim
====================
*/
ID_INLINE short AssertShortRange( int value ) {
assert( value >= -( 1 << ( sizeof( short ) * 8 - 1 ) ) );
assert( value < ( 1 << ( sizeof( short ) * 8 - 1 ) ) );
return (short) value;
}
bool idMD5Anim::LoadAnim( const char *filename ) {
int version;
idLexer parser( LEXFL_ALLOWPATHNAMES | LEXFL_NOSTRINGESCAPECHARS | LEXFL_NOSTRINGCONCAT );
idToken token;
int i, j;
int num;
bool offsetwarning = false;
int skipFrames = 2;
if ( !parser.LoadFile( filename ) ) {
return false;
}
Free();
name = filename;
parser.ExpectTokenString( MD5_VERSION_STRING );
version = parser.ParseInt();
if ( version != MD5_VERSION ) {
// ARNOUT: FIXME: BACKWARDS COMPATIBILITY
if ( version != 10 ) {
parser.Error( "Invalid version %d. Should be version %d", version, MD5_VERSION );
}
}
// skip the commandline
parser.ExpectTokenString( "commandline" );
parser.ReadToken( &token );
// parse num frames
parser.ExpectTokenString( "numFrames" );
numFrames = parser.ParseInt();
if ( numFrames <= 0 ) {
parser.Error( "Invalid number of frames: %d", numFrames );
}
// parse num joints
parser.ExpectTokenString( "numJoints" );
numJoints = parser.ParseInt();
if ( numJoints <= 0 ) {
parser.Error( "Invalid number of joints: %d", numJoints );
}
// parse frame rate
parser.ExpectTokenString( "frameRate" );
frameRate = parser.ParseInt();
if ( frameRate < 0 ) {
parser.Error( "Invalid frame rate: %d", frameRate );
}
// parse number of animated components
parser.ExpectTokenString( "numAnimatedComponents" );
numAnimatedComponents = parser.ParseInt();
if ( ( numAnimatedComponents < 0 ) || ( numAnimatedComponents > numJoints * 6 ) ) {
parser.Error( "Invalid number of animated components: %d", numAnimatedComponents );
}
// parse the hierarchy
jointInfo.SetGranularity( 1 );
jointInfo.SetNum( numJoints );
parser.ExpectTokenString( "hierarchy" );
parser.ExpectTokenString( "{" );
for( i = 0; i < numJoints; i++ ) {
parser.ReadToken( &token );
jointInfo[ i ].nameIndex = AssertShortRange( animationLib.JointIndex( token ) );
// parse parent num
jointInfo[ i ].parentNum = AssertShortRange( parser.ParseInt() );
if ( jointInfo[ i ].parentNum >= i ) {
parser.Error( "Invalid parent num: %d", jointInfo[ i ].parentNum );
}
if ( ( i != 0 ) && ( jointInfo[ i ].parentNum < 0 ) ) {
parser.Error( "Animations may have only one root joint" );
}
// parse anim bits
jointInfo[ i ].animBits = AssertShortRange( parser.ParseInt() );
if ( jointInfo[ i ].animBits & ~63 ) {
parser.Error( "Invalid anim bits: %d", jointInfo[ i ].animBits );
}
// parse first component
jointInfo[ i ].firstComponent = AssertShortRange( parser.ParseInt() );
if ( ( numAnimatedComponents > 0 ) && ( ( jointInfo[ i ].firstComponent < 0 ) || ( jointInfo[ i ].firstComponent >= numAnimatedComponents ) ) ) {
parser.Error( "Invalid first component: %d", jointInfo[ i ].firstComponent );
}
}
parser.ExpectTokenString( "}" );
// parse bounds
parser.ExpectTokenString( "bounds" );
parser.ExpectTokenString( "{" );
bounds.SetGranularity( 1 );
bounds.SetNum( numFrames );
for( i = 0; i < numFrames; i++ ) {
idBounds b;
parser.Parse1DMatrix( 3, b[ 0 ].ToFloatPtr() );
parser.Parse1DMatrix( 3, b[ 1 ].ToFloatPtr() );
bounds[i].SetBounds( b );
}
parser.ExpectTokenString( "}" );
// parse base frame
baseFrame.SetGranularity( 1 );
baseFrame.SetNum( numJoints );
parser.ExpectTokenString( "baseframe" );
parser.ExpectTokenString( "{" );
for( i = 0; i < numJoints; i++ ) {
idVec3 t;
idCQuat q;
parser.Parse1DMatrix( 3, t.ToFloatPtr() );
parser.Parse1DMatrix( 3, q.ToFloatPtr() );
t.FixDenormals();
q.FixDenormals();
if ( !offsetwarning ) {
if ( fabsf( t.x ) >= idCompressedJointQuat::MAX_BONE_LENGTH ||
fabsf( t.y ) >= idCompressedJointQuat::MAX_BONE_LENGTH ||
fabsf( t.z ) >= idCompressedJointQuat::MAX_BONE_LENGTH ) {
int jointNum = jointInfo[ i ].nameIndex;
gameLocal.Warning( "WARNING: bone offset of '%s' joint '%s' greater than %i",
filename,
animationLib.JointName( jointNum ),
idCompressedJointQuat::MAX_BONE_LENGTH );
offsetwarning = true;
}
}
baseFrame[ i ].t[0] = idCompressedJointQuat::OffsetToShort( t.x );
baseFrame[ i ].t[1] = idCompressedJointQuat::OffsetToShort( t.y );
baseFrame[ i ].t[2] = idCompressedJointQuat::OffsetToShort( t.z );
baseFrame[ i ].q[0] = idCompressedJointQuat::QuatToShort( q.x );
baseFrame[ i ].q[1] = idCompressedJointQuat::QuatToShort( q.y );
baseFrame[ i ].q[2] = idCompressedJointQuat::QuatToShort( q.z );
}
parser.ExpectTokenString( "}" );
// parse frames
componentFrames.SetGranularity( 1 );
componentFrames.SetNum( numAnimatedComponents * numFrames );
short *componentPtr = componentFrames.Begin();
for( i = 0; i < numFrames; i++ ) {
parser.ExpectTokenString( "frame" );
num = parser.ParseInt();
if ( num != i ) {
parser.Error( "Expected frame number %d", i );
}
parser.ExpectTokenString( "{" );
for ( j = 0; j < numJoints; j++ ) {
int animBits = jointInfo[j].animBits;
if ( animBits & ANIM_TX ) {
float x = parser.ParseFloat();
*componentPtr++ = idCompressedJointQuat::OffsetToShort( x );
}
if ( animBits & ANIM_TY ) {
float y = parser.ParseFloat();
*componentPtr++ = idCompressedJointQuat::OffsetToShort( y );
}
if ( animBits & ANIM_TZ ) {
float z = parser.ParseFloat();
*componentPtr++ = idCompressedJointQuat::OffsetToShort( z );
}
if ( animBits & ANIM_QX ) {
float x = parser.ParseFloat();
*componentPtr++ = idCompressedJointQuat::QuatToShort( x );
}
if ( animBits & ANIM_QY ) {
float y = parser.ParseFloat();
*componentPtr++ = idCompressedJointQuat::QuatToShort( y );
}
if ( animBits & ANIM_QZ ) {
float z = parser.ParseFloat();
*componentPtr++ = idCompressedJointQuat::QuatToShort( z );
}
}
parser.ExpectTokenString( "}" );
}
// get total move delta
if ( !numAnimatedComponents ) {
totaldelta.Zero();
} else {
componentPtr = &componentFrames[ jointInfo[ 0 ].firstComponent ];
if ( jointInfo[ 0 ].animBits & ANIM_TX ) {
for( i = 0; i < numFrames; i++ ) {
componentPtr[ numAnimatedComponents * i ] -= baseFrame[ 0 ].t[0];
}
totaldelta.x = idCompressedJointQuat::ShortToOffset( componentPtr[ numAnimatedComponents * ( numFrames - 1 ) ] );
componentPtr++;
} else {
totaldelta.x = 0.0f;
}
if ( jointInfo[ 0 ].animBits & ANIM_TY ) {
for( i = 0; i < numFrames; i++ ) {
componentPtr[ numAnimatedComponents * i ] -= baseFrame[ 0 ].t[1];
}
totaldelta.y = idCompressedJointQuat::ShortToOffset( componentPtr[ numAnimatedComponents * ( numFrames - 1 ) ] );
componentPtr++;
} else {
totaldelta.y = 0.0f;
}
if ( jointInfo[ 0 ].animBits & ANIM_TZ ) {
for( i = 0; i < numFrames; i++ ) {
componentPtr[ numAnimatedComponents * i ] -= baseFrame[ 0 ].t[2];
}
totaldelta.z = idCompressedJointQuat::ShortToOffset( componentPtr[ numAnimatedComponents * ( numFrames - 1 ) ] );
} else {
totaldelta.z = 0.0f;
}
}
baseFrame[ 0 ].ClearOffset();
// we don't count last frame because it would cause a 1 frame pause at the end
animLength = ( ( numFrames - 1 ) * 1000 + frameRate - 1 ) / frameRate;
if ( numFrames > 4 && numAnimatedComponents && anim_reduced.GetBool() && !r_writeAnimB.GetBool() ) {
Resample();
}
// done
return true;
}
/*
====================
idMD5Anim::Resample
====================
*/
void idMD5Anim::Resample( void ) {
if ( reduced ) {
return;
}
int idealFrames = numFrames/2;
idList<short> resampledFrames;
resampledFrames.SetGranularity( 1 );
resampledFrames.SetNum( numAnimatedComponents * idealFrames );
idCompressedJointQuat *compressedJoints = (idCompressedJointQuat *)_alloca16( numJoints * sizeof( compressedJoints[0] ) );
idCompressedJointQuat *compressedBlendJoints = (idCompressedJointQuat *)_alloca16( numJoints * sizeof( compressedBlendJoints[0] ) );
idJointQuat *joints = (idJointQuat *)_alloca16( numJoints * sizeof( joints[0] ) );
idJointQuat *blendJoints = (idJointQuat *)_alloca16( numJoints * sizeof( blendJoints[0] ) );
int *baseIndex = (int*)_alloca16( numJoints * sizeof( baseIndex[0] ) );
for (int i=0; i<numJoints; i++) {
baseIndex[i] = i;
}
for (int i=0; i<idealFrames; i++) {
float srcf = (i*(numFrames-1)) / (idealFrames-1);
int srci = (int)idMath::Floor( srcf );
float blend = srcf - srci;
if ( i != srci ) {
bounds[i] = bounds[srci];
}
{
short *destPtr = &resampledFrames[ i * numAnimatedComponents ];
short *srcPtr = &componentFrames[ srci * numAnimatedComponents ];
short *nextSrcPtr;
if ( (srci+1) < numFrames ) {
nextSrcPtr = &componentFrames[ (srci+1) * numAnimatedComponents ];
} else {
nextSrcPtr = srcPtr;
}
int numBaseIndex = 0;
for ( int j = 0; j < numJoints; j++ ) {
const jointAnimInfo_t * infoPtr = &jointInfo[j];
int animBits = infoPtr->animBits;
if ( animBits == 0 ) {
continue;
}
baseIndex[numBaseIndex] = numBaseIndex;
idCompressedJointQuat *jointPtr = &compressedJoints[numBaseIndex];
idCompressedJointQuat *blendPtr = &compressedBlendJoints[numBaseIndex];
const short *jointframe1 = srcPtr + infoPtr->firstComponent;
const short *jointframe2 = nextSrcPtr + infoPtr->firstComponent;
*jointPtr = baseFrame[j];
switch( animBits & (ANIM_TX|ANIM_TY|ANIM_TZ) ) {
case 0:
blendPtr->t[0] = jointPtr->t[0];
blendPtr->t[1] = jointPtr->t[1];
blendPtr->t[2] = jointPtr->t[2];
break;
case ANIM_TX:
jointPtr->t[0] = jointframe1[0];
blendPtr->t[0] = jointframe2[0];
blendPtr->t[1] = jointPtr->t[1];
blendPtr->t[2] = jointPtr->t[2];
jointframe1++;
jointframe2++;
break;
case ANIM_TY:
jointPtr->t[1] = jointframe1[0];
blendPtr->t[1] = jointframe2[0];
blendPtr->t[0] = jointPtr->t[0];
blendPtr->t[2] = jointPtr->t[2];
jointframe1++;
jointframe2++;
break;
case ANIM_TZ:
jointPtr->t[2] = jointframe1[0];
blendPtr->t[2] = jointframe2[0];
blendPtr->t[0] = jointPtr->t[0];
blendPtr->t[1] = jointPtr->t[1];
jointframe1++;
jointframe2++;
break;
case ANIM_TX|ANIM_TY:
jointPtr->t[0] = jointframe1[0];
jointPtr->t[1] = jointframe1[1];
blendPtr->t[0] = jointframe2[0];
blendPtr->t[1] = jointframe2[1];
blendPtr->t[2] = jointPtr->t[2];
jointframe1 += 2;
jointframe2 += 2;
break;
case ANIM_TX|ANIM_TZ:
jointPtr->t[0] = jointframe1[0];
jointPtr->t[2] = jointframe1[1];
blendPtr->t[0] = jointframe2[0];
blendPtr->t[2] = jointframe2[1];
blendPtr->t[1] = jointPtr->t[1];
jointframe1 += 2;
jointframe2 += 2;
break;
case ANIM_TY|ANIM_TZ:
jointPtr->t[1] = jointframe1[0];
jointPtr->t[2] = jointframe1[1];
blendPtr->t[1] = jointframe2[0];
blendPtr->t[2] = jointframe2[1];
blendPtr->t[0] = jointPtr->t[0];
jointframe1 += 2;
jointframe2 += 2;
break;
case ANIM_TX|ANIM_TY|ANIM_TZ:
jointPtr->t[0] = jointframe1[0];
jointPtr->t[1] = jointframe1[1];
jointPtr->t[2] = jointframe1[2];
blendPtr->t[0] = jointframe2[0];
blendPtr->t[1] = jointframe2[1];
blendPtr->t[2] = jointframe2[2];
jointframe1 += 3;
jointframe2 += 3;
break;
}
switch( animBits & (ANIM_QX|ANIM_QY|ANIM_QZ) ) {
case 0:
blendPtr->q[0] = jointPtr->q[0];
blendPtr->q[1] = jointPtr->q[1];
blendPtr->q[2] = jointPtr->q[2];
break;
case ANIM_QX:
jointPtr->q[0] = jointframe1[0];
blendPtr->q[0] = jointframe2[0];
blendPtr->q[1] = jointPtr->q[1];
blendPtr->q[2] = jointPtr->q[2];
break;
case ANIM_QY:
jointPtr->q[1] = jointframe1[0];
blendPtr->q[1] = jointframe2[0];
blendPtr->q[0] = jointPtr->q[0];
blendPtr->q[2] = jointPtr->q[2];
break;
case ANIM_QZ:
jointPtr->q[2] = jointframe1[0];
blendPtr->q[2] = jointframe2[0];
blendPtr->q[0] = jointPtr->q[0];
blendPtr->q[1] = jointPtr->q[1];
break;
case ANIM_QX|ANIM_QY:
jointPtr->q[0] = jointframe1[0];
jointPtr->q[1] = jointframe1[1];
blendPtr->q[0] = jointframe2[0];
blendPtr->q[1] = jointframe2[1];
blendPtr->q[2] = jointPtr->q[2];
break;
case ANIM_QX|ANIM_QZ:
jointPtr->q[0] = jointframe1[0];
jointPtr->q[2] = jointframe1[1];
blendPtr->q[0] = jointframe2[0];
blendPtr->q[2] = jointframe2[1];
blendPtr->q[1] = jointPtr->q[1];
break;
case ANIM_QY|ANIM_QZ:
jointPtr->q[1] = jointframe1[0];
jointPtr->q[2] = jointframe1[1];
blendPtr->q[1] = jointframe2[0];
blendPtr->q[2] = jointframe2[1];
blendPtr->q[0] = jointPtr->q[0];
break;
case ANIM_QX|ANIM_QY|ANIM_QZ:
jointPtr->q[0] = jointframe1[0];
jointPtr->q[1] = jointframe1[1];
jointPtr->q[2] = jointframe1[2];
blendPtr->q[0] = jointframe2[0];
blendPtr->q[1] = jointframe2[1];
blendPtr->q[2] = jointframe2[2];
break;
}
numBaseIndex++;
}
blendJoints = (idJointQuat *)_alloca16( baseFrame.Num() * sizeof( blendJoints[ 0 ] ) );
SIMDProcessor->DecompressJoints( joints, compressedJoints, baseIndex, numBaseIndex );
SIMDProcessor->DecompressJoints( blendJoints, compressedBlendJoints, baseIndex, numBaseIndex );
SIMDProcessor->BlendJoints( joints, blendJoints, 1.f-blend, baseIndex, numBaseIndex );
numBaseIndex = 0;
for ( int j = 0; j < numJoints; j++ ) {
const jointAnimInfo_t * infoPtr = &jointInfo[j];
int animBits = infoPtr->animBits;
if ( animBits == 0 ) {
continue;
}
idJointQuat const &curjoint = joints[numBaseIndex];
idCQuat cq = curjoint.q.ToCQuat();
idCompressedJointQuat cj;
cj.t[0] = idCompressedJointQuat::OffsetToShort( curjoint.t.x );
cj.t[1] = idCompressedJointQuat::OffsetToShort( curjoint.t.y );
cj.t[2] = idCompressedJointQuat::OffsetToShort( curjoint.t.z );
cj.q[0] = idCompressedJointQuat::QuatToShort( cq.x );
cj.q[1] = idCompressedJointQuat::QuatToShort( cq.y );
cj.q[2] = idCompressedJointQuat::QuatToShort( cq.z );
short *output = &destPtr[ infoPtr->firstComponent ];
if ( animBits & (ANIM_TX) ) {
*output++ = cj.t[0];
}
if ( animBits & (ANIM_TY) ) {
*output++ = cj.t[1];
}
if ( animBits & (ANIM_TZ) ) {
*output++ = cj.t[2];
}
if ( animBits & (ANIM_QX) ) {
*output++ = cj.q[0];
}
if ( animBits & (ANIM_QY) ) {
*output++ = cj.q[1];
}
if ( animBits & (ANIM_QZ) ) {
*output++ = cj.q[2];
}
numBaseIndex++;
}
}
}
int nb = numFrames;
int fr = frameRate;
frameRate = (frameRate * idealFrames) / numFrames;//(((numFrames - 1) * 1000) + animLength - 1) / (animLength);
numFrames = idealFrames;
animLength = ( ( numFrames - 1 ) * 1000 + frameRate - 1 ) / frameRate;
bounds.SetGranularity( 1 );
bounds.SetNum( numFrames );
componentFrames = resampledFrames;
reduced = true;
}
/*
====================
idMD5Anim::IncreaseRefs
====================
*/
void idMD5Anim::IncreaseRefs( void ) const {
ref_count++;
}
/*
====================
idMD5Anim::DecreaseRefs
====================
*/
void idMD5Anim::DecreaseRefs( void ) const {
ref_count--;
}
/*
====================
idMD5Anim::NumRefs
====================
*/
int idMD5Anim::NumRefs( void ) const {
return ref_count;
}
/*
====================
idMD5Anim::GetFrameBlend
====================
*/
void idMD5Anim::GetFrameBlend( int framenum, frameBlend_t &frame ) const {
frame.cycleCount = 0;
frame.backlerp = 0.0f;
frame.frontlerp = 1.0f;
// frame 1 is first frame
framenum--;
if ( framenum < 0 ) {
framenum = 0;
} else if ( framenum >= numFrames ) {
framenum = numFrames - 1;
}
frame.frame1 = framenum;
frame.frame2 = framenum;
}
/*
====================
idMD5Anim::ConvertTimeToFrame
====================
*/
void idMD5Anim::ConvertTimeToFrame( int time, int cyclecount, frameBlend_t &frame ) const {
int frameTime;
int frameNum;
if ( numFrames <= 1 ) {
frame.frame1 = 0;
frame.frame2 = 0;
frame.backlerp = 0.0f;
frame.frontlerp = 1.0f;
frame.cycleCount = 0;
return;
}
if ( time <= 0 ) {
frame.frame1 = 0;
frame.frame2 = 1;
frame.backlerp = 0.0f;
frame.frontlerp = 1.0f;
frame.cycleCount = 0;
return;
}
frameTime = time * frameRate;
frameNum = frameTime / 1000;
frame.cycleCount = frameNum / ( numFrames - 1 );
if ( ( cyclecount > 0 ) && ( frame.cycleCount >= cyclecount ) ) {
frame.cycleCount = cyclecount - 1;
frame.frame1 = numFrames - 1;
frame.frame2 = frame.frame1;
frame.backlerp = 0.0f;
frame.frontlerp = 1.0f;
return;
}
frame.frame1 = frameNum % ( numFrames - 1 );
frame.frame2 = frame.frame1 + 1;
if ( frame.frame2 >= numFrames ) {
frame.frame2 = 0;
}
frame.backlerp = ( frameTime % 1000 ) * 0.001f;
frame.frontlerp = 1.0f - frame.backlerp;
}
/*
====================
idMD5Anim::GetOrigin
====================
*/
void idMD5Anim::GetOrigin( idVec3 &offset, int time, int cyclecount ) const {
frameBlend_t frame;
offset[0] = idCompressedJointQuat::ShortToOffset( baseFrame[ 0 ].t[0] );
offset[1] = idCompressedJointQuat::ShortToOffset( baseFrame[ 0 ].t[1] );
offset[2] = idCompressedJointQuat::ShortToOffset( baseFrame[ 0 ].t[2] );
if ( !( jointInfo[ 0 ].animBits & ( ANIM_TX | ANIM_TY | ANIM_TZ ) ) ) {
// just use the baseframe
return;
}
ConvertTimeToFrame( time, cyclecount, frame );
const short *componentPtr1 = &componentFrames[ numAnimatedComponents * frame.frame1 + jointInfo[ 0 ].firstComponent ];
const short *componentPtr2 = &componentFrames[ numAnimatedComponents * frame.frame2 + jointInfo[ 0 ].firstComponent ];
if ( jointInfo[ 0 ].animBits & ANIM_TX ) {
offset.x = idCompressedJointQuat::ShortToOffset( *componentPtr1 ) * frame.frontlerp + idCompressedJointQuat::ShortToOffset( *componentPtr2 ) * frame.backlerp;
componentPtr1++;
componentPtr2++;
}
if ( jointInfo[ 0 ].animBits & ANIM_TY ) {
offset.y = idCompressedJointQuat::ShortToOffset( *componentPtr1 ) * frame.frontlerp + idCompressedJointQuat::ShortToOffset( *componentPtr2 ) * frame.backlerp;
componentPtr1++;
componentPtr2++;
}
if ( jointInfo[ 0 ].animBits & ANIM_TZ ) {
offset.z = idCompressedJointQuat::ShortToOffset( *componentPtr1 ) * frame.frontlerp + idCompressedJointQuat::ShortToOffset( *componentPtr2 ) * frame.backlerp;
}
if ( frame.cycleCount ) {
offset += totaldelta * ( float )frame.cycleCount;
}
}
/*
====================
idMD5Anim::GetOriginRotation
====================
*/
void idMD5Anim::GetOriginRotation( idQuat &rotation, int time, int cyclecount ) const {
frameBlend_t frame;
int animBits;
animBits = jointInfo[ 0 ].animBits;
if ( !( animBits & ( ANIM_QX | ANIM_QY | ANIM_QZ ) ) ) {
// just use the baseframe
rotation[0] = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[0] );
rotation[1] = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[1] );
rotation[2] = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[2] );
rotation.w = rotation.CalcW();
return;
}
ConvertTimeToFrame( time, cyclecount, frame );
const short *jointframe1 = &componentFrames[ numAnimatedComponents * frame.frame1 + jointInfo[ 0 ].firstComponent ];
const short *jointframe2 = &componentFrames[ numAnimatedComponents * frame.frame2 + jointInfo[ 0 ].firstComponent ];
if ( animBits & ANIM_TX ) {
jointframe1++;
jointframe2++;
}
if ( animBits & ANIM_TY ) {
jointframe1++;
jointframe2++;
}
if ( animBits & ANIM_TZ ) {
jointframe1++;
jointframe2++;
}
idQuat q1;
idQuat q2;
switch( animBits & (ANIM_QX|ANIM_QY|ANIM_QZ) ) {
case ANIM_QX:
q1.x = idCompressedJointQuat::ShortToQuat( jointframe1[0] );
q2.x = idCompressedJointQuat::ShortToQuat( jointframe2[0] );
q1.y = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[1] );
q2.y = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[1] );
q1.z = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[2] );
q2.z = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[2] );
q1.w = q1.CalcW();
q2.w = q2.CalcW();
break;
case ANIM_QY:
q1.y = idCompressedJointQuat::ShortToQuat( jointframe1[0] );
q2.y = idCompressedJointQuat::ShortToQuat( jointframe2[0] );
q1.x = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[0] );
q2.x = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[0] );
q1.z = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[2] );
q2.z = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[2] );
q1.w = q1.CalcW();
q2.w = q2.CalcW();
break;
case ANIM_QZ:
q1.z = idCompressedJointQuat::ShortToQuat( jointframe1[0] );
q2.z = idCompressedJointQuat::ShortToQuat( jointframe2[0] );
q1.x = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[0] );
q2.x = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[0] );
q1.y = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[1] );
q2.y = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[1] );
q1.w = q1.CalcW();
q2.w = q2.CalcW();
break;
case ANIM_QX|ANIM_QY:
q1.x = idCompressedJointQuat::ShortToQuat( jointframe1[0] );
q1.y = idCompressedJointQuat::ShortToQuat( jointframe1[1] );
q2.x = idCompressedJointQuat::ShortToQuat( jointframe2[0] );
q2.y = idCompressedJointQuat::ShortToQuat( jointframe2[1] );
q1.z = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[2] );
q2.z = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[2] );
q1.w = q1.CalcW();
q2.w = q2.CalcW();
break;
case ANIM_QX|ANIM_QZ:
q1.x = idCompressedJointQuat::ShortToQuat( jointframe1[0] );
q1.z = idCompressedJointQuat::ShortToQuat( jointframe1[1] );
q2.x = idCompressedJointQuat::ShortToQuat( jointframe2[0] );
q2.z = idCompressedJointQuat::ShortToQuat( jointframe2[1] );
q1.y = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[1] );
q2.y = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[1] );
q1.w = q1.CalcW();
q2.w = q2.CalcW();
break;
case ANIM_QY|ANIM_QZ:
q1.y = idCompressedJointQuat::ShortToQuat( jointframe1[0] );
q1.z = idCompressedJointQuat::ShortToQuat( jointframe1[1] );
q2.y = idCompressedJointQuat::ShortToQuat( jointframe2[0] );
q2.z = idCompressedJointQuat::ShortToQuat( jointframe2[1] );
q1.x = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[0] );
q2.x = idCompressedJointQuat::ShortToQuat( baseFrame[ 0 ].q[0] );
q1.w = q1.CalcW();
q2.w = q2.CalcW();
break;
case ANIM_QX|ANIM_QY|ANIM_QZ:
q1.x = idCompressedJointQuat::ShortToQuat( jointframe1[0] );
q1.y = idCompressedJointQuat::ShortToQuat( jointframe1[1] );
q1.z = idCompressedJointQuat::ShortToQuat( jointframe1[2] );
q2.x = idCompressedJointQuat::ShortToQuat( jointframe2[0] );
q2.y = idCompressedJointQuat::ShortToQuat( jointframe2[1] );
q2.z = idCompressedJointQuat::ShortToQuat( jointframe2[2] );
q1.w = q1.CalcW();
q2.w = q2.CalcW();
break;
}
rotation.Slerp( q1, q2, frame.backlerp );
}
/*
====================
idMD5Anim::GetBounds
====================
*/
void idMD5Anim::GetBounds( idBounds &bnds, int time, int cyclecount ) const {
frameBlend_t frame;
idVec3 offset;
ConvertTimeToFrame( time, cyclecount, frame );
bnds = bounds[ frame.frame1 ].ToBounds();
bnds.AddBounds( bounds[ frame.frame2 ].ToBounds() );
// origin position
offset[0] = idCompressedJointQuat::ShortToOffset( baseFrame[ 0 ].t[0] );
offset[1] = idCompressedJointQuat::ShortToOffset( baseFrame[ 0 ].t[1] );
offset[2] = idCompressedJointQuat::ShortToOffset( baseFrame[ 0 ].t[2] );
if ( jointInfo[ 0 ].animBits & ( ANIM_TX | ANIM_TY | ANIM_TZ ) ) {
const short *componentPtr1 = &componentFrames[ numAnimatedComponents * frame.frame1 + jointInfo[ 0 ].firstComponent ];
const short *componentPtr2 = &componentFrames[ numAnimatedComponents * frame.frame2 + jointInfo[ 0 ].firstComponent ];
if ( jointInfo[ 0 ].animBits & ANIM_TX ) {
offset.x = idCompressedJointQuat::ShortToOffset( *componentPtr1 ) * frame.frontlerp + idCompressedJointQuat::ShortToOffset( *componentPtr2 ) * frame.backlerp;
componentPtr1++;
componentPtr2++;
}
if ( jointInfo[ 0 ].animBits & ANIM_TY ) {
offset.y = idCompressedJointQuat::ShortToOffset( *componentPtr1 ) * frame.frontlerp + idCompressedJointQuat::ShortToOffset( *componentPtr2 ) * frame.backlerp;
componentPtr1++;
componentPtr2++;
}
if ( jointInfo[ 0 ].animBits & ANIM_TZ ) {
offset.z = idCompressedJointQuat::ShortToOffset( *componentPtr1 ) * frame.frontlerp + idCompressedJointQuat::ShortToOffset( *componentPtr2 ) * frame.backlerp;
}
}
bnds[ 0 ] -= offset;
bnds[ 1 ] -= offset;
}
/*
====================
idMD5Anim::GetInterpolatedFrame
====================
*/
void idMD5Anim::GetInterpolatedFrame( frameBlend_t &frame, idJointQuat *joints, const int *index, int numIndexes ) const {
int i, numLerpJoints;
const short * frame1;
const short * frame2;
const short * jointframe1;
const short * jointframe2;
const jointAnimInfo_t * infoPtr;
int animBits;
idJointQuat * blendJoints;
idCompressedJointQuat * compressedJoints;
idCompressedJointQuat * compressedBlendJoints;
idCompressedJointQuat * jointPtr;
idCompressedJointQuat * blendPtr;
int * lerpIndex;
int * baseIndex;
// FIXME: have global static ?
// index with all joints
baseIndex = (int *)_alloca16( baseFrame.Num() * sizeof( baseIndex[ 0 ] ) );
for ( i = 0; i < baseFrame.Num(); i++ ) {
baseIndex[i] = i;
}
if ( !numAnimatedComponents ) {
// just use the base frame
SIMDProcessor->DecompressJoints( joints, baseFrame.Begin(), baseIndex, baseFrame.Num() );
return;
}
compressedJoints = (idCompressedJointQuat *)_alloca16( baseFrame.Num() * sizeof( compressedJoints[0] ) );
compressedBlendJoints = (idCompressedJointQuat *)_alloca16( baseFrame.Num() * sizeof( compressedBlendJoints[0] ) );
SIMDProcessor->Memcpy( compressedJoints, baseFrame.Begin(), baseFrame.Num() * sizeof( compressedJoints[0] ) );
lerpIndex = (int *)_alloca16( baseFrame.Num() * sizeof( lerpIndex[ 0 ] ) );
numLerpJoints = 0;
frame1 = &componentFrames[ frame.frame1 * numAnimatedComponents ];
frame2 = &componentFrames[ frame.frame2 * numAnimatedComponents ];
// delta decompression relative to base frame
for ( i = 0; i < numIndexes; i++ ) {
int j = index[i];
infoPtr = &jointInfo[j];
animBits = infoPtr->animBits;
if ( animBits == 0 ) {
continue;
}
jointPtr = &compressedJoints[j];
blendPtr = &compressedBlendJoints[j];
lerpIndex[numLerpJoints++] = j;
jointframe1 = frame1 + infoPtr->firstComponent;
jointframe2 = frame2 + infoPtr->firstComponent;
switch( animBits & (ANIM_TX|ANIM_TY|ANIM_TZ) ) {
case 0:
blendPtr->t[0] = jointPtr->t[0];
blendPtr->t[1] = jointPtr->t[1];
blendPtr->t[2] = jointPtr->t[2];
break;
case ANIM_TX:
jointPtr->t[0] = jointframe1[0];
blendPtr->t[0] = jointframe2[0];
blendPtr->t[1] = jointPtr->t[1];
blendPtr->t[2] = jointPtr->t[2];
jointframe1++;
jointframe2++;
break;
case ANIM_TY:
jointPtr->t[1] = jointframe1[0];
blendPtr->t[1] = jointframe2[0];
blendPtr->t[0] = jointPtr->t[0];
blendPtr->t[2] = jointPtr->t[2];
jointframe1++;
jointframe2++;
break;
case ANIM_TZ:
jointPtr->t[2] = jointframe1[0];
blendPtr->t[2] = jointframe2[0];
blendPtr->t[0] = jointPtr->t[0];
blendPtr->t[1] = jointPtr->t[1];
jointframe1++;
jointframe2++;
break;
case ANIM_TX|ANIM_TY:
jointPtr->t[0] = jointframe1[0];
jointPtr->t[1] = jointframe1[1];
blendPtr->t[0] = jointframe2[0];
blendPtr->t[1] = jointframe2[1];
blendPtr->t[2] = jointPtr->t[2];
jointframe1 += 2;
jointframe2 += 2;
break;
case ANIM_TX|ANIM_TZ:
jointPtr->t[0] = jointframe1[0];
jointPtr->t[2] = jointframe1[1];
blendPtr->t[0] = jointframe2[0];
blendPtr->t[2] = jointframe2[1];
blendPtr->t[1] = jointPtr->t[1];
jointframe1 += 2;
jointframe2 += 2;
break;
case ANIM_TY|ANIM_TZ:
jointPtr->t[1] = jointframe1[0];
jointPtr->t[2] = jointframe1[1];
blendPtr->t[1] = jointframe2[0];
blendPtr->t[2] = jointframe2[1];
blendPtr->t[0] = jointPtr->t[0];
jointframe1 += 2;
jointframe2 += 2;
break;
case ANIM_TX|ANIM_TY|ANIM_TZ:
jointPtr->t[0] = jointframe1[0];
jointPtr->t[1] = jointframe1[1];
jointPtr->t[2] = jointframe1[2];
blendPtr->t[0] = jointframe2[0];
blendPtr->t[1] = jointframe2[1];
blendPtr->t[2] = jointframe2[2];
jointframe1 += 3;
jointframe2 += 3;
break;
}
switch( animBits & (ANIM_QX|ANIM_QY|ANIM_QZ) ) {
case 0:
blendPtr->q[0] = jointPtr->q[0];
blendPtr->q[1] = jointPtr->q[1];
blendPtr->q[2] = jointPtr->q[2];
break;
case ANIM_QX:
jointPtr->q[0] = jointframe1[0];
blendPtr->q[0] = jointframe2[0];
blendPtr->q[1] = jointPtr->q[1];
blendPtr->q[2] = jointPtr->q[2];
break;
case ANIM_QY:
jointPtr->q[1] = jointframe1[0];
blendPtr->q[1] = jointframe2[0];
blendPtr->q[0] = jointPtr->q[0];
blendPtr->q[2] = jointPtr->q[2];
break;
case ANIM_QZ:
jointPtr->q[2] = jointframe1[0];
blendPtr->q[2] = jointframe2[0];
blendPtr->q[0] = jointPtr->q[0];
blendPtr->q[1] = jointPtr->q[1];
break;
case ANIM_QX|ANIM_QY:
jointPtr->q[0] = jointframe1[0];
jointPtr->q[1] = jointframe1[1];
blendPtr->q[0] = jointframe2[0];
blendPtr->q[1] = jointframe2[1];
blendPtr->q[2] = jointPtr->q[2];
break;
case ANIM_QX|ANIM_QZ:
jointPtr->q[0] = jointframe1[0];
jointPtr->q[2] = jointframe1[1];
blendPtr->q[0] = jointframe2[0];
blendPtr->q[2] = jointframe2[1];
blendPtr->q[1] = jointPtr->q[1];
break;
case ANIM_QY|ANIM_QZ:
jointPtr->q[1] = jointframe1[0];
jointPtr->q[2] = jointframe1[1];
blendPtr->q[1] = jointframe2[0];
blendPtr->q[2] = jointframe2[1];
blendPtr->q[0] = jointPtr->q[0];
break;
case ANIM_QX|ANIM_QY|ANIM_QZ:
jointPtr->q[0] = jointframe1[0];
jointPtr->q[1] = jointframe1[1];
jointPtr->q[2] = jointframe1[2];
blendPtr->q[0] = jointframe2[0];
blendPtr->q[1] = jointframe2[1];
blendPtr->q[2] = jointframe2[2];
break;
}
}
blendJoints = (idJointQuat *)_alloca16( baseFrame.Num() * sizeof( blendJoints[ 0 ] ) );
SIMDProcessor->DecompressJoints( joints, compressedJoints, baseIndex, baseFrame.Num() );
SIMDProcessor->DecompressJoints( blendJoints, compressedBlendJoints, lerpIndex, numLerpJoints );
SIMDProcessor->BlendJoints( joints, blendJoints, frame.backlerp, lerpIndex, numLerpJoints );
if ( frame.cycleCount ) {
joints[ 0 ].t += totaldelta * ( float )frame.cycleCount;
}
}
/*
====================
idMD5Anim::GetSingleFrame
====================
*/
void idMD5Anim::GetSingleFrame( int framenum, idJointQuat *joints, const int *index, int numIndexes ) const {
int i;
const short * frame;
const short * jointframe;
int animBits;
idCompressedJointQuat * compressedJoints;
idCompressedJointQuat * jointPtr;
const jointAnimInfo_t * infoPtr;
int * baseIndex;
// FIXME: have global static ?
// index with all joints
baseIndex = (int *)_alloca16( baseFrame.Num() * sizeof( baseIndex[ 0 ] ) );
for ( i = 0; i < baseFrame.Num(); i++ ) {
baseIndex[i] = i;
}
if ( ( framenum == 0 ) || !numAnimatedComponents ) {
// just use the base frame
SIMDProcessor->DecompressJoints( joints, baseFrame.Begin(), baseIndex, baseFrame.Num() );
return;
}
compressedJoints = (idCompressedJointQuat *)_alloca16( baseFrame.Num() * sizeof( compressedJoints[0] ) );
SIMDProcessor->Memcpy( compressedJoints, baseFrame.Begin(), baseFrame.Num() * sizeof( baseFrame[0] ) );
frame = &componentFrames[ framenum * numAnimatedComponents ];
// delta decompression relative to base frame
for ( i = 0; i < numIndexes; i++ ) {
int j = index[i];
infoPtr = &jointInfo[j];
animBits = infoPtr->animBits;
if ( animBits == 0 ) {
continue;
}
jointPtr = &compressedJoints[j];
jointframe = frame + infoPtr->firstComponent;
switch( animBits & (ANIM_TX|ANIM_TY|ANIM_TZ) ) {
case 0:
break;
case ANIM_TX:
jointPtr->t[0] = jointframe[0];
jointframe++;
break;
case ANIM_TY:
jointPtr->t[1] = jointframe[0];
jointframe++;
break;
case ANIM_TZ:
jointPtr->t[2] = jointframe[0];
jointframe++;
break;
case ANIM_TX|ANIM_TY:
jointPtr->t[0] = jointframe[0];
jointPtr->t[1] = jointframe[1];
jointframe += 2;
break;
case ANIM_TX|ANIM_TZ:
jointPtr->t[0] = jointframe[0];
jointPtr->t[2] = jointframe[1];
jointframe += 2;
break;
case ANIM_TY|ANIM_TZ:
jointPtr->t[1] = jointframe[0];
jointPtr->t[2] = jointframe[1];
jointframe += 2;
break;
case ANIM_TX|ANIM_TY|ANIM_TZ:
jointPtr->t[0] = jointframe[0];
jointPtr->t[1] = jointframe[1];
jointPtr->t[2] = jointframe[2];
jointframe += 3;
break;
}
switch( animBits & (ANIM_QX|ANIM_QY|ANIM_QZ) ) {
case 0:
break;
case ANIM_QX:
jointPtr->q[0] = jointframe[0];
break;
case ANIM_QY:
jointPtr->q[1] = jointframe[0];
break;
case ANIM_QZ:
jointPtr->q[2] = jointframe[0];
break;
case ANIM_QX|ANIM_QY:
jointPtr->q[0] = jointframe[0];
jointPtr->q[1] = jointframe[1];
break;
case ANIM_QX|ANIM_QZ:
jointPtr->q[0] = jointframe[0];
jointPtr->q[2] = jointframe[1];
break;
case ANIM_QY|ANIM_QZ:
jointPtr->q[1] = jointframe[0];
jointPtr->q[2] = jointframe[1];
break;
case ANIM_QX|ANIM_QY|ANIM_QZ:
jointPtr->q[0] = jointframe[0];
jointPtr->q[1] = jointframe[1];
jointPtr->q[2] = jointframe[2];
break;
}
}
SIMDProcessor->DecompressJoints( joints, compressedJoints, baseIndex, baseFrame.Num() );
}
/*
====================
idMD5Anim::CheckModelHierarchy
====================
*/
void idMD5Anim::CheckModelHierarchy( const idRenderModel *model ) const {
int i;
int jointNum;
int parent;
if ( jointInfo.Num() != model->NumJoints() ) {
gameLocal.Error( "Model '%s' has different # of joints than anim '%s'", model->Name(), name.c_str() );
}
const idMD5Joint *modelJoints = model->GetJoints();
for( i = 0; i < jointInfo.Num(); i++ ) {
jointNum = jointInfo[ i ].nameIndex;
if ( modelJoints[ i ].name != animationLib.JointName( jointNum ) ) {
gameLocal.Error( "Model '%s''s joint names don't match anim '%s''s", model->Name(), name.c_str() );
}
if ( modelJoints[ i ].parent ) {
parent = modelJoints[ i ].parent - modelJoints;
} else {
parent = -1;
}
if ( parent != jointInfo[ i ].parentNum ) {
gameLocal.Error( "Model '%s' has different joint hierarchy than anim '%s'", model->Name(), name.c_str() );
}
}
}
/***********************************************************************
idAnimManager
***********************************************************************/
/*
====================
idAnimManager::idAnimManager
====================
*/
idAnimManager::idAnimManager() {
}
/*
====================
idAnimManager::~idAnimManager
====================
*/
idAnimManager::~idAnimManager() {
Shutdown();
}
/*
====================
idAnimManager::Shutdown
====================
*/
void idAnimManager::Shutdown( void ) {
animations.DeleteContents();
jointnames.Clear();
jointnamesHash.Free();
}
/*
==============
idMD5Anim::LoadAnimBinary
==============
*/
bool idMD5Anim::LoadAnimBinary( const char *filename ) {
int ident, version, num;
idFile* file = fileSystem->OpenFileRead( filename );
if ( file == NULL ) {
// common->Warning( "Couldn't load binary anim, %s", filename );
return false;
}
#if defined( SD_BUFFERED_FILE_LOADS )
file = fileSystem->OpenBufferedFile( file );
#endif
Free();
file->ReadInt( ident );
if ( ident != ANIMB_IDENT ) {
common->Warning( "idMD5Anim::LoadAnimBinary : unknown fileid on '%s'", filename );
return false;
}
file->ReadInt( version );
if ( version != ANIMB_VERSION ) {
common->Warning( "idMD5Anim::LoadAnimBinary : wrong version on '%s' (%i should be %i)", filename, version, ANIMB_VERSION );
return false;
}
file->ReadInt( numFrames );
file->ReadInt( frameRate );
file->ReadInt( animLength );
file->ReadInt( numJoints );
file->ReadInt( numAnimatedComponents );
file->ReadInt( num );
bounds.SetGranularity( 1 );
bounds.SetNum( num );
for ( int i=0; i<num; i++ ) {
short list[6];
file->ReadShort( list[0] );
file->ReadShort( list[1] );
file->ReadShort( list[2] );
file->ReadShort( list[3] );
file->ReadShort( list[4] );
file->ReadShort( list[5] );
bounds[i].SetBounds( list );
}
file->ReadInt( num );
jointInfo.SetGranularity( 1 );
jointInfo.SetNum( num );
idStr temp;
for ( int i=0; i<num; i++ ) {
file->ReadString( temp );
jointInfo[i].nameIndex = animationLib.JointIndex( temp );
file->ReadShort( jointInfo[i].parentNum );
file->ReadShort( jointInfo[i].animBits );
file->ReadShort( jointInfo[i].firstComponent );
}
file->ReadInt( num );
baseFrame.SetGranularity( 1 );
baseFrame.SetNum( num );
for ( int i=0; i<num; i++ ) {
file->ReadShort( baseFrame[i].q[0] );
file->ReadShort( baseFrame[i].q[1] );
file->ReadShort( baseFrame[i].q[2] );
file->ReadShort( baseFrame[i].t[0] );
file->ReadShort( baseFrame[i].t[1] );
file->ReadShort( baseFrame[i].t[2] );
}
file->ReadInt( num );
componentFrames.SetGranularity( 1 );
componentFrames.SetNum( num );
for ( int i=0; i<num; i++ ) {
file->ReadShort( componentFrames[i] );
}
file->ReadString( name );
file->ReadVec3( totaldelta );
fileSystem->CloseFile( file );
if ( numFrames > 4 && numAnimatedComponents && anim_reduced.GetBool() ) {
Resample();
}
return true;
}
/*
==============
idMD5Anim::WriteAnimBinary
==============
*/
bool idMD5Anim::WriteAnimBinary( const char *filename ) {
int num;
idStr str = filename;
str.StripFileExtension();
str = str + ".animb";
idFile* file = fileSystem->OpenFileWrite( str.c_str(), "fs_savepath" );
if ( file == NULL ) {
return false;
}
file->WriteInt( ANIMB_IDENT );
file->WriteInt( ANIMB_VERSION );
file->WriteInt( numFrames );
file->WriteInt( frameRate );
file->WriteInt( animLength );
file->WriteInt( numJoints );
file->WriteInt( numAnimatedComponents );
num = bounds.Num();
file->WriteInt( num );
for ( int i = 0; i < num; i++ ) {
const short *list = bounds[i].GetBounds();
file->WriteShort( list[0] );
file->WriteShort( list[1] );
file->WriteShort( list[2] );
file->WriteShort( list[3] );
file->WriteShort( list[4] );
file->WriteShort( list[5] );
}
num = jointInfo.Num();
file->WriteInt( num );
for ( int i=0; i<num; i++ ) {
jointAnimInfo_t animInfo = jointInfo[i];
file->WriteString( animationLib.JointName( animInfo.nameIndex ) );
file->WriteShort( animInfo.parentNum );
file->WriteShort( animInfo.animBits );
file->WriteShort( animInfo.firstComponent );
}
num = baseFrame.Num();
file->WriteInt( num );
for ( int i=0; i<num; i++ ) {
idCompressedJointQuat jointQuat = baseFrame[i];
file->WriteShort( jointQuat.q[0] );
file->WriteShort( jointQuat.q[1] );
file->WriteShort( jointQuat.q[2] );
file->WriteShort( jointQuat.t[0] );
file->WriteShort( jointQuat.t[1] );
file->WriteShort( jointQuat.t[2] );
}
num = componentFrames.Num();
file->WriteInt( num );
for ( int i=0; i<num; i++ ) {
file->WriteShort( componentFrames[i] );
}
file->WriteString( name );
file->WriteVec3( totaldelta );
fileSystem->CloseFile( file );
return true;
}
/*
====================
idAnimManager::GetAnim
====================
*/
idMD5Anim *idAnimManager::GetAnim( const char *name ) {
idMD5Anim **animptrptr;
idMD5Anim *anim;
bool loaded = false;
// see if it has been asked for before
animptrptr = NULL;
if ( animations.Get( name, &animptrptr ) ) {
anim = *animptrptr;
} else {
idStr extension;
idStr filename = name;
filename.ExtractFileExtension( extension );
if ( extension != MD5_ANIM_EXT ) {
return NULL;
}
anim = new idMD5Anim();
if ( r_loadAnimB.GetBool() ) {
idStr animbName = va( PREGENERATED_BASEDIR "/animb/%s", name );
animbName.StripFileExtension();
animbName = animbName + ".animb";
loaded = anim->LoadAnimBinary( animbName );
}
if ( !loaded ) {
if ( !anim->LoadAnim( filename ) ) {
gameLocal.Warning( "Couldn't load anim: '%s'", filename.c_str() );
delete anim;
anim = NULL;
}
}
if ( r_writeAnimB.GetBool() && anim ) {
// Write binary file
idStr fullPath, relativePath;
relativePath = va( PREGENERATED_BASEDIR "/animb/%s", name );
anim->WriteAnimBinary( relativePath );
}
animations.Set( filename, anim );
}
return anim;
}
/*
================
idAnimManager::ReloadAnims
================
*/
void idAnimManager::ReloadAnims( void ) {
int i;
idMD5Anim **animptr;
for ( i = 0; i < animations.Num(); i++ ) {
animptr = animations.GetIndex( i );
if ( animptr && *animptr ) {
( *animptr )->Reload();
}
}
}
/*
================
idAnimManager::JointIndex
================
*/
int idAnimManager::JointIndex( const char *name ) {
int i, hash;
hash = jointnamesHash.GenerateKey( name );
for ( i = jointnamesHash.GetFirst( hash ); i != -1; i = jointnamesHash.GetNext( i ) ) {
if ( jointnames[i].Cmp( name ) == 0 ) {
return i;
}
}
i = jointnames.Append( name );
jointnamesHash.Add( hash, i );
return i;
}
/*
================
idAnimManager::JointName
================
*/
const char *idAnimManager::JointName( int index ) const {
return jointnames[ index ];
}
/*
================
idAnimManager::ListAnims
================
*/
void idAnimManager::ListAnims( void ) const {
int i;
idMD5Anim* const* animptr;
idMD5Anim* anim;
size_t size;
size_t s;
size_t namesize;
int num;
num = 0;
size = 0;
for ( i = 0; i < animations.Num(); i++ ) {
animptr = animations.GetIndex( i );
if ( animptr && *animptr ) {
anim = *animptr;
s = anim->Size();
gameLocal.Printf( "%8d bytes : %2d refs : %s\n", s, anim->NumRefs(), anim->Name() );
size += s;
num++;
}
}
namesize = jointnames.Size() + jointnamesHash.Size();
for( i = 0; i < jointnames.Num(); i++ ) {
namesize += jointnames[ i ].Size();
}
gameLocal.Printf( "\n%d memory used in %d anims\n", size, num );
gameLocal.Printf( "%d memory used in %d joint names\n", namesize, jointnames.Num() );
}
/*
================
idAnimManager::FlushUnusedAnims
================
*/
void idAnimManager::FlushUnusedAnims( void ) {
int i;
idMD5Anim **animptr;
idList<idMD5Anim *> removeAnims;
for ( i = 0; i < animations.Num(); i++ ) {
animptr = animations.GetIndex( i );
if ( animptr && *animptr ) {
if ( ( *animptr )->NumRefs() <= 0 ) {
removeAnims.Append( *animptr );
}
}
}
for( i = 0; i < removeAnims.Num(); i++ ) {
animations.Remove( removeAnims[ i ]->Name() );
delete removeAnims[ i ];
}
}
| 28.697088
| 162
| 0.604609
|
JasonHutton
|
f1bee58ab434b40987cd26f207f244d178b46bff
| 1,334
|
hpp
|
C++
|
clstatphys/clstatphys/tools/auto_correlation_function.hpp
|
FIshikawa/ClassicalStatPhys
|
e4010480d3c7977829c1b3fdeaf51401a2409373
|
[
"MIT"
] | null | null | null |
clstatphys/clstatphys/tools/auto_correlation_function.hpp
|
FIshikawa/ClassicalStatPhys
|
e4010480d3c7977829c1b3fdeaf51401a2409373
|
[
"MIT"
] | 2
|
2020-01-21T08:54:05.000Z
|
2020-01-21T09:29:10.000Z
|
clstatphys/clstatphys/tools/auto_correlation_function.hpp
|
FIshikawa/ClassicalStatPhys
|
e4010480d3c7977829c1b3fdeaf51401a2409373
|
[
"MIT"
] | 2
|
2020-07-18T03:36:32.000Z
|
2021-07-21T22:58:27.000Z
|
#ifndef AUTO_CORRELATION_FUNCTION_HPP
#define AUTO_CORRELATION_FUNCTION_HPP
#include <string>
#include <vector>
#include <cmath>
namespace correlation{
class AutoCorrelationFunction{
public:
AutoCorrelationFunction(int dim=1, int Nl=1) : dim_(dim), Nl_(Nl), counter_(0), correlation_(dim,0.0), mean_(dim,0.0){}
void initialize(int dim, int Nl){
counter_ = 0;
dim_ = dim;
Nl_ = Nl;
correlation_.resize(dim);
mean_.resize(dim);
for(int i = 0 ; i < dim; ++i){
correlation_[i] = 0.0;
mean_[i] = 0.0;
}
}
void operator<< (const double value) {
if(counter_ == 0 || counter_ > dim_ - 1 ){
value_init_ = value;
counter_ = 0;
}
mean_[counter_] += value / Nl_;
correlation_[counter_] += value * value_init_ / Nl_;
counter_++ ;
}
std::vector<double> result(){
std::vector<double> acf_t(dim_, 0.0);
for(int i = 0; i < dim_ ; ++i) acf_t[i] = correlation_[i] - mean_[counter_] * mean_[0];
return acf_t;
}
void calc( std::vector<double>const& z, std::vector<double>& ACF) const {
double N = (double)dim_ ;
for (int i = 0; i < dim_ ; ++i) ACF[i] += z[i]*z[0]/Nl_ ;
}
private:
int dim_, Nl_, counter_;
double value_init_;
std::vector<double> correlation_, mean_;
};
} //end namespace
#endif // AUTO_CORRELATION_FUNCTION_HPP
| 23.821429
| 121
| 0.623688
|
FIshikawa
|
f1c967503ead248e5269a51c98a133a1912ecf5d
| 534
|
cpp
|
C++
|
src/duktype/AsyncObjectScope.cpp
|
CasperTech/duktype
|
dbfd2838d23c3c2d8c3574f61e23f197c00b0fa2
|
[
"MIT"
] | 1
|
2021-11-01T20:18:08.000Z
|
2021-11-01T20:18:08.000Z
|
src/duktype/AsyncObjectScope.cpp
|
CasperTech/duktype
|
dbfd2838d23c3c2d8c3574f61e23f197c00b0fa2
|
[
"MIT"
] | 1
|
2021-01-28T17:46:47.000Z
|
2021-01-28T17:46:47.000Z
|
src/duktype/AsyncObjectScope.cpp
|
CasperTech/duktype
|
dbfd2838d23c3c2d8c3574f61e23f197c00b0fa2
|
[
"MIT"
] | null | null | null |
#include "AsyncObjectScope.h"
#include "AsyncContext.h"
namespace Duktype
{
void AsyncObjectScope::createObjectAsync(const Nan::FunctionCallbackInfo<v8::Value> &info)
{
if (info.Length() > 0 && info[0]->IsString())
{
std::string objNameStr = *Nan::Utf8String(info[0]);
std::static_pointer_cast<AsyncContext>(_ctx)->createObjectAsync(_handle, info);
}
else
{
Nan::ThrowError("Invalid or wrong number of arguments");
}
}
}
| 29.666667
| 95
| 0.586142
|
CasperTech
|
f1ce6b6911bff1a229eb1bd792ce95f284ff51ac
| 1,860
|
cpp
|
C++
|
src/0.3.7-R1/KeyStuff.cpp
|
DarkP1xel/SAMP-API
|
0d43a3603239f2f4bc65b8305ffc72177386cc29
|
[
"MIT"
] | 7
|
2019-09-23T10:19:40.000Z
|
2021-07-25T06:17:27.000Z
|
src/0.3.7-R1/KeyStuff.cpp
|
DarkP1xel/SAMP-API
|
0d43a3603239f2f4bc65b8305ffc72177386cc29
|
[
"MIT"
] | null | null | null |
src/0.3.7-R1/KeyStuff.cpp
|
DarkP1xel/SAMP-API
|
0d43a3603239f2f4bc65b8305ffc72177386cc29
|
[
"MIT"
] | 1
|
2021-04-11T17:13:00.000Z
|
2021-04-11T17:13:00.000Z
|
/*
This is a SAMP (0.3.7-R1) API project file.
Developer: LUCHARE <luchare.dev@gmail.com>
See more here https://github.com/LUCHARE/SAMP-API
Copyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.
*/
#include "KeyStuff.h"
CPad *&SAMP::KeyStuff::pInternalKeys = *(CPad **)SAMP_ADDROF(0x1016E8);
CPad *SAMP::KeyStuff::pLocalPlayerKeys = (CPad *)SAMP_ADDROF(0x13D2C0);
CPad *SAMP::KeyStuff::aPlayerKeys = (CPad *)SAMP_ADDROF(0x13D3F8);
bool *&SAMP::KeyStuff::pDriveByLeft = *(bool **)SAMP_ADDROF(0x1016EC);
bool *&SAMP::KeyStuff::pDriveByRight = *(bool **)SAMP_ADDROF(0x1016F0);
bool &SAMP::KeyStuff::bSavedDriveByLeft = *(bool *)SAMP_ADDROF(0x14D0A0);
bool &SAMP::KeyStuff::bSavedDriveByRight = *(bool *)SAMP_ADDROF(0x14D0A1);
void SAMP::KeyStuff::Initialize() {
((void(__cdecl *)())SAMP_ADDROF(0xA2240))();
}
void SAMP::KeyStuff::ApplyKeys() {
((void(__cdecl *)())SAMP_ADDROF(0xA2260))();
}
void SAMP::KeyStuff::UpdateKeys() {
((void(__cdecl *)())SAMP_ADDROF(0xA22A0))();
}
void SAMP::KeyStuff::SetKeys(int nPlayerNumber, const CPad *pPad) {
((void(__cdecl *)(int, const CPad *))SAMP_ADDROF(0xA22E0))(nPlayerNumber, pPad);
}
void SAMP::KeyStuff::ApplyKeys(int nPlayerNumber) {
((void(__cdecl *)(int))SAMP_ADDROF(0xA2300))(nPlayerNumber);
}
CPad *SAMP::KeyStuff::GetInternalKeys() {
return ((CPad *(__cdecl *)())SAMP_ADDROF(0xA2350))();
}
CPad *SAMP::KeyStuff::GetKeys(int nPlayerNumber) {
return ((CPad *(__cdecl *)(int))SAMP_ADDROF(0xA2370))(nPlayerNumber);
}
void SAMP::KeyStuff::ResetKeys(int nPlayerNumber) {
((void(__cdecl *)(int))SAMP_ADDROF(0xA2380))(nPlayerNumber);
}
void SAMP::KeyStuff::ResetInternalKeys() {
((void(__cdecl *)())SAMP_ADDROF(0xA23A0))();
}
CPad *SAMP::KeyStuff::GetKeys() {
return ((::CPad *(__cdecl *)())SAMP_ADDROF(0xA2360))();
}
| 31.525424
| 82
| 0.682796
|
DarkP1xel
|
f1d08d0158b9c32fb53f4b7af8c2d00d2c1edbd8
| 710
|
hpp
|
C++
|
src/mettle/test_command.hpp
|
jimporter/mettle
|
c65aa75b04a08b550b3572f4c080c68e26ad86fa
|
[
"BSD-3-Clause"
] | 82
|
2015-01-05T10:06:44.000Z
|
2022-03-07T01:41:28.000Z
|
src/mettle/test_command.hpp
|
JohnGalbraith/mettle
|
38b70fe1dc0f30e98b768a37108196328182b5f4
|
[
"BSD-3-Clause"
] | 44
|
2015-01-08T08:40:54.000Z
|
2021-10-29T23:28:56.000Z
|
src/mettle/test_command.hpp
|
jimporter/mettle
|
c65aa75b04a08b550b3572f4c080c68e26ad86fa
|
[
"BSD-3-Clause"
] | 13
|
2015-06-23T07:41:54.000Z
|
2020-02-14T15:35:07.000Z
|
#ifndef INC_METTLE_SRC_METTLE_TEST_COMMAND_HPP
#define INC_METTLE_SRC_METTLE_TEST_COMMAND_HPP
#include <memory>
#include <string>
#include <vector>
#include <boost/any.hpp>
namespace mettle {
class test_command {
public:
test_command(std::string command);
const std::string & command() const {
return command_;
}
operator const std::string &() const {
return command_;
}
const std::vector<std::string> & args() const {
return args_;
}
private:
std::string command_;
std::vector<std::string> args_;
};
void validate(boost::any &v, const std::vector<std::string> &values,
test_command*, int);
} // namespace mettle
#endif
| 18.684211
| 70
| 0.657746
|
jimporter
|
f1d1cace8a50a0dc5605adfcf33c39b328c9248a
| 644
|
cpp
|
C++
|
P/2032.cpp
|
langonginc/cfile
|
46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f
|
[
"MIT"
] | 1
|
2020-09-13T02:51:25.000Z
|
2020-09-13T02:51:25.000Z
|
P/2032.cpp
|
langonginc/cfile
|
46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f
|
[
"MIT"
] | null | null | null |
P/2032.cpp
|
langonginc/cfile
|
46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f
|
[
"MIT"
] | 1
|
2021-06-05T03:37:57.000Z
|
2021-06-05T03:37:57.000Z
|
#include<iostream>
#include<stdio.h>
#include<deque>
#define max(_1,_2) ((_1)>(_2)?(_1):(_2))
#define min(_1,_2) ((_1)>(_2)?(_1):(_2))
using namespace std;
struct cr{
int num,id;
inline void put(int _num,int _id){
num=_num,id=_id;
}
}a[1000005];
int num,n,m;
void work(int _if_min){
deque<cr>q;
for(int i=1;i<=n;i++){
while(!q.empty()&&q.back().num*_if_min>=a[i].num*_if_min){
q.pop_back();
}
q.push_back(a[i]);
if(q.front().id==i-m){
q.pop_front();
}
if(i>=m)printf("%d\n",q.front().num);
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",&num);
a[i].put(num,i);
}
work(-1);
return 0;
}
| 17.888889
| 60
| 0.56677
|
langonginc
|
f1d558f3d6294a7cebd557d1c8c20082674e5bf0
| 7,024
|
cpp
|
C++
|
examples/Example_reconstruct_image.cpp
|
MSusik/LibAPR
|
5338da714905577642342c80120524bdebab5bb6
|
[
"Apache-2.0"
] | null | null | null |
examples/Example_reconstruct_image.cpp
|
MSusik/LibAPR
|
5338da714905577642342c80120524bdebab5bb6
|
[
"Apache-2.0"
] | null | null | null |
examples/Example_reconstruct_image.cpp
|
MSusik/LibAPR
|
5338da714905577642342c80120524bdebab5bb6
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by cheesema on 14/03/17.
//
////////////////////////////////////////
///
/// Bevan Cheeseman 2018
///
const char* usage = R"(
APR pixel image reconstruction example:
Outputs various reconstructed images from the APR.
Usage:
(using *_apr.h5 output of Example_get_apr)
Example_reconstruct_image -i inputfile [-d directory] -o output_name
e.g. Example_reconstruct_image -i nuc_apr.h5 -d /Test/Input_examples/ -o nuclei
Default: Piece-wise constant reconstruction
Options:
-pc_recon (outputs piece-wise reconstruction (Default))
-smooth_recon (Outputs a smooth reconstruction)
-apr_properties (Outputs all Particle Cell information (x,y,z,l) and type to pc images
)";
#include <algorithm>
#include <iostream>
#include "data_structures/APR/APR.hpp"
#include "io/TiffUtils.hpp"
struct cmdLineOptions{
std::string output = "output";
std::string directory = "";
std::string input = "";
bool output_spatial_properties = false;
bool output_pc_recon = false;
bool output_smooth_recon = false;
};
static bool command_option_exists(char **begin, char **end, const std::string &option) {
return std::find(begin, end, option) != end;
}
static const char* get_command_option(char **begin, char **end, const std::string &option) {
char **itr = std::find(begin, end, option);
if (itr != end && ++itr != end) {
return *itr;
}
return nullptr;
}
static cmdLineOptions read_command_line_options(int argc, char **argv) {
cmdLineOptions result;
if (argc == 1) {
std::cerr << usage << std::endl;
exit(1);
}
if (command_option_exists(argv, argv + argc, "-i")) {
result.input = std::string(get_command_option(argv, argv + argc, "-i"));
}
else {
std::cerr << "Input file required" << std::endl;
exit(2);
}
if (command_option_exists(argv, argv + argc, "-d")) {
result.directory = std::string(get_command_option(argv, argv + argc, "-d"));
}
if (command_option_exists(argv, argv + argc, "-o")) {
result.output = std::string(get_command_option(argv, argv + argc, "-o"));
}
if (command_option_exists(argv, argv + argc, "-pc_recon")) {
result.output_pc_recon = true;
}
if (command_option_exists(argv, argv + argc, "-smooth_recon")) {
result.output_smooth_recon = true;
}
if (command_option_exists(argv, argv + argc, "-apr_properties")) {
result.output_spatial_properties = true;
}
if(!(result.output_pc_recon || result.output_smooth_recon || result.output_spatial_properties)){
//default is pc recon
result.output_pc_recon = true;
}
return result;
}
int main(int argc, char **argv) {
// INPUT PARSING
cmdLineOptions options = read_command_line_options(argc, argv);
// Read the apr file into the part cell structure
APRTimer timer;
timer.verbose_flag = true;
// APR datastructure
APR<uint16_t> apr;
//read file
std::string file_name = options.directory + options.input;
apr.read_apr(file_name);
apr.name = options.output;
// Intentionaly block-scoped since local recon_pc will be destructed when block ends and release memory.
{
if(options.output_pc_recon) {
//create mesh data structure for reconstruction
MeshData<uint16_t> recon_pc;
timer.start_timer("pc interp");
//perform piece-wise constant interpolation
apr.interp_img(recon_pc, apr.particles_intensities);
timer.stop_timer();
float elapsed_seconds = timer.t2 - timer.t1;
std::cout << "PC recon "
<< (recon_pc.x_num * recon_pc.y_num * recon_pc.z_num * 2) / (elapsed_seconds * 1000000.0f)
<< " MB per second" << std::endl;
//write output as tiff
TiffUtils::saveMeshAsTiff(options.directory + apr.name + "_pc.tif", recon_pc);
}
}
//////////////////////////
/// Create a particle dataset with the particle type and pc construct it
////////////////////////////
if(options.output_spatial_properties) {
//initialization of the iteration structures
APRIterator<uint16_t> apr_iterator(apr); //this is required for parallel access
//create particle dataset
ExtraParticleData<uint16_t> type(apr);
ExtraParticleData<uint16_t> level(apr);
ExtraParticleData<uint16_t> x(apr);
ExtraParticleData<uint16_t> y(apr);
ExtraParticleData<uint16_t> z(apr);
timer.start_timer("APR parallel iterator loop");
#ifdef HAVE_OPENMP
#pragma omp parallel for schedule(static) firstprivate(apr_iterator)
#endif
for (uint64_t particle_number = 0; particle_number < apr_iterator.total_number_particles(); ++particle_number) {
//needed step for any parallel loop (update to the next part)
apr_iterator.set_iterator_to_particle_by_number(particle_number);
type[apr_iterator] = apr_iterator.type();
level[apr_iterator] = apr_iterator.level();
x[apr_iterator] = apr_iterator.x();
y[apr_iterator] = apr_iterator.y();
z[apr_iterator] = apr_iterator.z();
}
timer.stop_timer();
// Intentionaly block-scoped since local type_recon will be destructed when block ends and release memory.
{
MeshData<uint16_t> type_recon;
apr.interp_img(type_recon, type);
TiffUtils::saveMeshAsTiff(options.directory + apr.name + "_type.tif", type_recon);
//pc interp
apr.interp_img(type_recon, level);
TiffUtils::saveMeshAsTiff(options.directory + apr.name + "_level.tif", type_recon);
//pc interp
apr.interp_img(type_recon, x);
TiffUtils::saveMeshAsTiff(options.directory + apr.name + "_x.tif", type_recon);
//pc interp
apr.interp_img(type_recon, y);
TiffUtils::saveMeshAsTiff(options.directory + apr.name + "_y.tif", type_recon);
//pc interp
apr.interp_img(type_recon, z);
TiffUtils::saveMeshAsTiff(options.directory + apr.name + "_z.tif", type_recon);
}
}
if(options.output_smooth_recon) {
//smooth reconstruction - requires float
MeshData<float> recon_smooth;
std::vector<float> scale_d = {2, 2, 2};
timer.start_timer("smooth reconstrution");
apr.interp_parts_smooth(recon_smooth, apr.particles_intensities, scale_d);
timer.stop_timer();
float elapsed_seconds = timer.t2 - timer.t1;
std::cout << "Smooth recon "
<< (recon_smooth.x_num * recon_smooth.y_num * recon_smooth.z_num * 2) / (elapsed_seconds * 1000000.0f)
<< " MB per second" << std::endl;
//write to tiff casting to unsigned 16 bit integer
TiffUtils::saveMeshAsTiffUint16(options.directory + apr.name + "_smooth.tif", recon_smooth);
}
}
| 31.63964
| 120
| 0.632118
|
MSusik
|
f1d637ee274d74c7f3dc883b100d9db2cd160fd2
| 329
|
cpp
|
C++
|
tests/FirstBadVersionTest.cpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 43
|
2015-10-10T12:59:52.000Z
|
2018-07-11T18:07:00.000Z
|
tests/FirstBadVersionTest.cpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | null | null | null |
tests/FirstBadVersionTest.cpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 11
|
2015-10-10T14:41:11.000Z
|
2018-07-28T06:03:16.000Z
|
#include "catch.hpp"
#include "FirstBadVersion.hpp"
TEST_CASE("First Bad Version") {
const int N = 2126753390;
const int M = 1702766719;
auto isBad = [](int version) {
return version >= M;
};
FirstBadVersion s(isBad);
SECTION("Sample test") {
REQUIRE(s.firstBadVersion(N) == M);
}
}
| 20.5625
| 43
| 0.601824
|
yanzhe-chen
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.