blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
31c6900616f3d2198c2670812a291da5bdf866a6 | 784fe5d235530804b0a2408f03d71c944720224a | /src/cosma/environment_variables.cpp | 3914d6bb5fc20588ebf591a32ddf3d5c29b8ccfb | [
"BSD-3-Clause"
] | permissive | pouya-haghi/COSMA | af8ed3f2f5a696c66411ba72548eb245afed7763 | 782d5d7c1e52adb800688dc8286c06fbcd13374d | refs/heads/master | 2022-11-10T02:25:06.901451 | 2020-06-23T01:31:39 | 2020-06-23T01:31:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,730 | cpp | #include <cosma/environment_variables.hpp>
#include <algorithm>
bool cosma::env_var_defined(const char* var_name) {
char* var = getenv (var_name);
return var != nullptr;
}
bool cosma::get_bool_env_var(std::string name, bool default_value) {
char* var;
var = getenv(name.c_str());
bool value = default_value;
if (var != nullptr) {
std::string s(var);
std::transform(s.begin(), s.end(), s.begin(),
[&](char c) {
return std::toupper(c);
}
);
value = (s == "ON");
}
return value;
}
int cosma::get_int_env_var(std::string name, int default_value) {
char* var;
var = getenv(name.c_str());
int value = default_value;
if (var != nullptr)
value = std::atoi(var);
return value;
}
int cosma::gpu_streams() {
return get_int_env_var(env_var_names::gpu_n_streams,
env_var_defaults::gpu_n_streams);
}
int cosma::gpu_max_tile_m() {
return get_int_env_var(env_var_names::gpu_tile_m,
env_var_defaults::gpu_tile_m);
}
int cosma::gpu_max_tile_n() {
return get_int_env_var(env_var_names::gpu_tile_n,
env_var_defaults::gpu_tile_n);
}
int cosma::gpu_max_tile_k() {
return get_int_env_var(env_var_names::gpu_tile_k,
env_var_defaults::gpu_tile_k);
}
bool cosma::get_adapt_strategy() {
return get_bool_env_var(env_var_names::adapt_strategy,
env_var_defaults::adapt_strategy);
}
bool cosma::get_overlap_comm_and_comp() {
return get_bool_env_var(env_var_names::overlap,
env_var_defaults::overlap);
}
bool cosma::get_memory_pinning() {
return get_bool_env_var(env_var_names::memory_pinning_enabled,
env_var_defaults::memory_pinning_enabled);
}
// reads the memory limit in MB per rank
// and converts the limit to #elements that each rank is allowed to use
template <typename T>
long long cosma::get_cpu_max_memory() {
char* var;
var = getenv(env_var_names::cpu_max_memory.c_str());
long long value = env_var_defaults::cpu_max_memory;
long long megabytes = env_var_defaults::cpu_max_memory;
if (var != nullptr) {
megabytes = std::atoll(var);
// from megabytes to #elements
value = megabytes * 1024LL * 1024LL / sizeof(T);
}
return value;
}
// template instantiation of get_cpu_max_memory()
template long long cosma::get_cpu_max_memory<float>();
template long long cosma::get_cpu_max_memory<double>();
template long long cosma::get_cpu_max_memory<std::complex<float>>();
template long long cosma::get_cpu_max_memory<std::complex<double>>();
| [
"marko.kabic@cscs.ch"
] | marko.kabic@cscs.ch |
e23f6743247d49224f31e68c197052458565dc19 | c8b7fea80cb77a20dba889d7c3b90fd192c878a4 | /modules/objfmts/win32/SxData.h | 2b1acf34671720f35557da42530bdf39a0a4d9d4 | [] | no_license | PeterJohnson/yasm-nextgen | b870244740f0507dbdd02bd99aa2f0ebd3731726 | de173dcbd49575f1714f2f16347dbb59bc38a9f4 | refs/heads/master | 2020-04-08T20:37:38.333729 | 2011-06-22T05:52:28 | 2011-06-22T05:52:28 | 1,501,974 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,761 | h | #ifndef YASM_SXDATA_H
#define YASM_SXDATA_H
//
// Bytecode for Win32 .sxdata sections
//
// Copyright (C) 2002-2008 Peter Johnson
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the 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.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND OTHER CONTRIBUTORS ``AS IS''
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR OTHER CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include "yasmx/Config/export.h"
#include "yasmx/SymbolRef.h"
namespace yasm
{
class BytecodeContainer;
class SourceLocation;
namespace objfmt
{
YASM_STD_EXPORT
void AppendSxData(BytecodeContainer& container,
SymbolRef sym,
SourceLocation source);
}} // namespace yasm::objfmt
#endif
| [
"peter@tortall.net"
] | peter@tortall.net |
827d8d42dcdc1dd3b6f1b559b8b349a83585bb7f | feb207f41689d5fca13f013a9072125de96b8b44 | /mwnet_mt/net/EventLoopThread.h | 841526c3d809120e8086947e0fcba7c5b6d20bb1 | [] | no_license | cocoj521/libmwnet | d4bc1f13aa07eff31e33b6d46fd312fc83fa9d8e | 27201f76d6c7a81155b264a59a70f3b7ddcefa72 | refs/heads/master | 2023-08-16T21:28:37.202454 | 2023-08-16T08:17:02 | 2023-08-16T08:17:02 | 163,558,652 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 937 | h | // Use of this source code is governed by a BSD-style license
// that can be found in the License file.
// This is a public header file, it must only include public header files.
#ifndef MWNET_MT_NET_EVENTLOOPTHREAD_H
#define MWNET_MT_NET_EVENTLOOPTHREAD_H
#include <mwnet_mt/base/Condition.h>
#include <mwnet_mt/base/Mutex.h>
#include <mwnet_mt/base/Thread.h>
namespace mwnet_mt
{
namespace net
{
class EventLoop;
class EventLoopThread : noncopyable
{
public:
typedef std::function<void(EventLoop*)> ThreadInitCallback;
EventLoopThread(const ThreadInitCallback& cb = ThreadInitCallback(),
const string& name = string());
~EventLoopThread();
EventLoop* startLoop();
EventLoop* getloop();
private:
void threadFunc();
EventLoop* loop_;
bool exiting_;
Thread thread_;
MutexLock mutex_;
Condition cond_;
ThreadInitCallback callback_;
};
}
}
#endif // MWNET_MT_NET_EVENTLOOPTHREAD_H
| [
"cocoj521@163.com"
] | cocoj521@163.com |
dd60a7dba792cdda90e740060b5f5e4b3bb6891d | 87965f0299a1d0b44d3ca7bd162d158a12e193fb | /cpp/x03/func.hpp | b1dd6e6a6b226d34218d7d06cb4da7034cb85f8a | [] | no_license | vitaliiboiko360/cpp_core | bbe2023fd62eef65b14ac4c5b451fa557ca302e9 | a4da028ea3c40892ebefb79b6d0641a667f20f20 | refs/heads/master | 2021-06-09T14:03:21.564144 | 2021-04-25T18:06:06 | 2021-04-25T18:06:06 | 167,162,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | hpp | #include <iostream>
#include <memory>
class MyClass
{
int m_number;
public:
MyClass();
MyClass(int number);
~MyClass();
};
MyClass::MyClass()
{
std::cout<<"MyClass()\n";
}
MyClass::MyClass(int number)
: m_number(number)
{
std::cout<<"MyClass( number= "<<number<<" )\n";
}
MyClass::~MyClass()
{
std::cout<<"~MyClass()\n";
}
std::unique_ptr<MyClass> CreateMyClass(int n)
{
if(n > 0)
return std::make_unique<MyClass>(n);
return {};
} | [
"vukelan@gmail.com"
] | vukelan@gmail.com |
e1ffc0db48b0c7eeae59c910abc103015dee1cec | 64c32421152c671859044ca6f0ff142cb43ddaf2 | /Davide_codes/Pedina.cc | 61a90dffb54c06c4a68acd249f5a8d72981f3faa | [] | no_license | francescobrivio/Dama | f1fdffe9eeb708e43908cb35e757eaeaa38d10f0 | 765ef251002ad26fde4d429102a8a3e3384f1269 | refs/heads/master | 2021-01-01T19:08:47.914907 | 2017-09-30T16:27:09 | 2017-09-30T16:27:09 | 98,522,882 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,989 | cc | #include "Pedina.h"
#include "include/cppinclude.h"
Pedina::Pedina()
{
Board* board = new Board();
srand (time(NULL));
_x = rand() % Nslot + 1;
_y = rand() % Nslot + 1;
_color = 1;
_board = board;
}
Pedina::Pedina(const std::string color, int x, int y, Board* board):
_x (x),
_y (y),
_color (color),
_board (board)
{
}
Pedina::Pedina(const Pedina& origin):
_x (origin.getX()),
_y (origin.getY()),
_color (origin.getColor()),
_board (origin.getBoard())
{
}
Pedina& Pedina::operator= (const Pedina& origin)
{
if (&origin == this) return *this;
this->Pedina::operator=(origin);
this->setX(origin.getX());
this->setY(origin.getY());
this->setColor(origin.getColor());
this->setBoard(origin.getBoard());
return *this;
}
Pedina::~Pedina()
{
}
void Pedina::setX(int x)
{
_x = x;
}
void Pedina::setY(int y)
{
_y = y;
}
int Pedina::getX() const
{
return _x;
}
int Pedina::getY() const
{
return _y;
}
void Pedina::setColor(std::string color)
{
_color = color;
}
std::string Pedina::getColor() const
{
return _color;
}
void Pedina::setBoard(Board* board)
{
_board = board;
}
Board* Pedina::getBoard() const
{
return _board;
}
void Pedina::Move(int x, int y)
{
this->setX(x);
this->setY(y);
}
Moves Pedina::Check()
{
int new_x[Nmoves_pedina], new_y = 0;
char isfree[Nmoves_pedina];
Moves moves;
Position newPos;
std::string status = "";
new_y = this->getY() + 1;
new_x[0] = this->getX() - 1;
new_x[1] = this->getX() + 1;
for(int i=0; i<Nmoves_pedina; i++)
{
isfree[i] = this->getBoard()->getStatus(new_x[i], new_y);
if(isfree[i] == ' ') status = "free";
else if (tolower(isfree[i]) == 'w') status = "ally";
else if (tolower(isfree[i]) == 'b') status = "enemy";
else status = "error";
newPos = std::pair<int, int>(new_x[i], new_y);
moves.push_back(std::pair<Position, std::string>(newPos, status));
}
return moves;
}
| [
"davide.fazzini@cern.ch"
] | davide.fazzini@cern.ch |
c02396d193e1dae0ba8bc935ec804798e05cbdd1 | bda9c698b94a787a43e235c262f5d8635bb021bb | /cnn/basicOps.cpp | 39a31f90e6e9e7d6b979eb76716e1437682587a4 | [] | no_license | yangcyself/CS385cpp | 2e94c28732cb9e14d2e9833ab00608d68dbf9524 | f1219f924e05a5cc549ef0f375d12da107dc506b | refs/heads/master | 2022-01-04T19:38:18.013603 | 2019-06-18T15:54:30 | 2019-06-18T15:54:30 | 192,167,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,372 | cpp |
#include <cnn/basicOps.h>
// #include <stdio.h>
#include <iostream>
namespace convnn
{
void null_deleter(Operator *){}
/**
* The forward function for Conv operators
* if the operator is in train mode, it caches the a and b
* to make it convinence to calculate the gradient.
* ** Thus, the backward of one loss should be called right after the loss is derived **
*/
Tensor
Conv::forward()
{
if(trainmod){
ca = a->forward();
cb = b->forward();
// std::cout<<"CONV forward ca empty "<<ca.is_empty()<<std::endl;
return ca.conv(cb,pad,0,stride);
}else{
return a->forward().conv( b->forward(),pad,0,stride );
}
}
/**
* dout/da can be calculate as another conv
* out conv flip(b) pad_: kh-1-pad(h) , kw-1-pad(w)
* kernel has to transpose inC and outC
* use dilation to deal with forward stride(change it back to the shape before stride)
*
* dout/db can also be calculate as conv similar to above
* however, the kernels to gradient should be flip (Not flip the input feature)
* The output tensor should be transpose into outC * N*H*W
* and the input tensor should be transpose into inC * H*W*N
* Then the conv result is outC * inC*H*W, transposeto outC * H*W*inC
*
*/
void
Conv::backward(const Tensor& in)
{
assert(trainmod);
assert(!ca.is_empty() && !cb.is_empty());
int dpad = cb.height()-1-pad;
Tensor tpkernel = cb.kernelTranspose(); //transposed kernel
Tensor fpkernel = tpkernel.kernelFlip(); //fliped kernel
assert(cb.height()==cb.width()); //for the time being, only support padding the same of H and W
Tensor da = in.conv(fpkernel,dpad);
a->backward(da);
Tensor kout = in.kernelize();
Tensor tpout = kout.transposefromNHWC();
Tensor kin = ca.kernelize();
// std::cout<<"kin: \n";
// kin.print();
// std::cout<<std::endl;
// std::cout<<"tpout: \n";
// tpout.print();
// std::cout<<std::endl;
Tensor tdb = tpout.conv(kin, dpad);
Tensor ktdb = tdb.transposetoNHWC();
Tensor db = ktdb.kernelFlip();
// std::cout<<"db: \n";
// db.print();
// std::cout<<std::endl;
b->backward(db);
}
void
Conv::train(){
trainmod = true;
a->train();b->train();
}
void
Conv::test(){
trainmod = false;
a->test();b->test();
ca.set_empty(); cb.set_empty();
}
}//namespace convnn | [
"13520183356@139.com"
] | 13520183356@139.com |
3763c8b5ffa7d116fe4376884af88b97976bd176 | 7e1962ff4f2e23c29e4fb7b9fb1e7b7174380a4e | /graph.cpp | af139b3a0f2fef1f6fa58fde9197cda54c17d86b | [] | no_license | severly/HexBoard | dc497ac6ec0c4562e4469f45a0864e1170613b1e | 0fe16e233f8ce8855a9c3a201cf2bddb0f32052c | refs/heads/master | 2016-09-05T20:28:56.904728 | 2014-09-14T09:33:25 | 2014-09-14T09:33:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,153 | cpp | /*
* graph.cpp
* All functions related to the Graph class defined in graph.c
*
*/
#include "graph.h"
#include "node.h"
#include "hex_ai.h"
using namespace std;
/*
* Constructor: build a graph of n+2 by n+2 nodes. Each node has a player (corresponding to player 1 or
* player 2) and a list of all nodes it is connected to (max 6).
* The two extra rows and columns are used to check for a win condition.
*/
graph::graph(int num) : order(num+2), size(num) {
// Make the vector big enough to fit every node.
nodes.resize(order);
// Create an order*order 2D array of nodes
for(int i=0; i < order; i++){
for(int j=0; j<order; j++){
// Create node with i,j coordinates and push back into vector.
node tmp(i,j);
nodes[i].push_back(tmp);
}
}
// Attach each node to it's respective neighbors
generate_neighbors();
}
graph::graph(const graph &g){
size = g.size;
order = g.order;
user = g.user;
bp = NULL;
nodes.resize(order);
// Create an order*order 2D array of nodes
for(int i=0; i < order; i++){
for(int j=0; j<order; j++){
// Create node with i,j coordinates and push back into vector.
node tmp(i,j);
tmp.set_player1(g.nodes[i][j].get_player());
nodes[i].push_back(tmp);
}
}
// Create new references
generate_neighbors();
// for(int i=0; i < order; i++){
// cout << "list " << i << ": ";
// for(int j=0; j<order; j++){
// cout << nodes[i][j].neighbors.size() << " ";
// }
// cout <<"\n";
// }
}
/*
* Create neighbor list of each node. Figuring out how to identify
* the adjacent nodes was the hardest part. I did this by picking certain
* representative nodes (such as 0,0; 10, 10; 0,10; 10,0; 5,5) and writing down
* the indices of every node they are connected to. I turned this into an algorithm
* which is created below.
*/
void graph::generate_neighbors(){
for(int i=0; i<order; i++){
for(int j=0; j<order; j++){
if(i+1 < order){
nodes[i][j].add_neighbor(&nodes[i+1][j]);
if(j-1 >= 0) nodes[i][j].add_neighbor(&nodes[i+1][j-1]);
}
if(i-1 >= 0){
nodes[i][j].add_neighbor(&nodes[i-1][j]);
if(j+1 < order) nodes[i][j].add_neighbor(&nodes[i-1][j+1]);
}
if(j+1 < order) nodes[i][j].add_neighbor(&nodes[i][j+1]);
if(j-1 >= 0) nodes[i][j].add_neighbor(&nodes[i][j-1]);
}
}
// Set the special edge nodes for win checking.
for(int i=0; i<order; i++){
nodes[0][i].set_player(PX);
nodes[order-1][i].set_player(PX);
nodes[i][0].set_player(PO);
nodes[i][order-1].set_player(PO);
}
}
void graph::release(){
// Insert code
}
/*
* Functions in class graph
*
*
*/
bool graph::place(bool which, int x, int y){
// Check for valid move and if spot is available
if(!is_valid(x, y)) return 0;
// Set the player of the node associated with x,y
nodes[x+1][y+1].set_player(which);
// Put piece into ascii board and print board
if(bp != NULL){
(*bp).place_piece(which, x, y);
print_board();
}
return 1;
}
// Check if indices are in bounds and if spot is taken
bool graph::is_valid(int x, int y){
if(x < 0 || x >= size || y < 0 || y >= size) return false;
if(!nodes[x+1][y+1].is_empty()) return false;
return true;
}
// Print ASCII version of board
void graph::print_board(){
if(bp == NULL) return;
(*bp).print();
}
// Mostly for debugging:
// Print out each node, it's associated player, and all adjacent nodes
void graph::print(){
cout << endl;
for(int i=0; i<order; i++){
for(int j=0; j<order; j++){
cout << "Node: " << nodes[i][j] << "List: ";
// Use print_list function associated with each node.
nodes[i][j].print_list();
cout << endl;
}
}
}
// Start game, figure out if player wants to go first and if they want to use pie rule
void graph::start_game(){
int which(-1);
string input;
// Figure out whether player goes first or second
while(which!=0 && which !=1){
cout << "Would you like to go first (0) or second (1)?\n>";
getline(cin, input);
sscanf(input.c_str(), "%d", &which);
}
user = (bool) which; // Set player for the rest of the game
// If user wants to go second, let computer go first and implement pie rule
pair<int, int> move;
if(user){
move = ai_move();
char ans(0);
cout << "Would you like to use the pie rule? (y/n)";
while(ans != 'y' && ans!='n'){
getline(cin, input);
sscanf(input.c_str(), "%c", &ans);
}
if(ans == 'y'){
pie_rule(move);
ai_move();
}
}
}
bool graph::pie_rule(pair<int, int> move){
int x(move.first), y(move.second);
// Check that the move is within bounds
if(x < 0 || x >= size || y < 0 || y >= size) return false;
// Set the player of the node associated with x,y
nodes[x+1][y+1].set_player(user);
(*bp).place_piece(user, x, y);
print_board();
return 1;
}
// Functions for the respective players' moves.
bool graph::user_move(int x, int y){
if(!place(user, x, y)){
cout << "Graph: Invalid move.\n";
return 0;
}
return 1;
}
void graph::rand_user(){
pair<int, int> move(-1, -1);
while(!place(user, move.first, move.second)){
move.first=rand() %size; move.second = rand() %size;
}
}
pair<int, int> graph::ai_move(){
pair<int, int> move;
move = hex_ai::get_move(*this);
if(!place(!user, move.first, move.second)){
cout << "Cannot place computer's move";
}else cout << "Computer's move: " << move.first << ", " << move.second << endl;
return move;
}
pair<int, int> graph::rand_ai(){
pair<int, int> move(-1, -1);
while(!place(!user, move.first, move.second)){
move.first=rand() % size; move.second = rand() %size;
}
return move;
}
// Used to simplify indexing in find_win(bool)
node graph::at(pair<int, int> index){
if(index.first > order || index.second > order){
cout << "Out of bounds: (" << index.first << ", " << index.second << ")\n";
node tmp;
return tmp;
}
return nodes[index.first][index.second];
}
// Essentially a DFS algorithm to find destination node.
bool graph::find_win(bool which){
pair<int, int> src, dest;
player p;
// Based on the input, set function up to look for x win or o win.
if(!which){
src.first = 1; src.second=0;
dest.first = order-2; dest.second = order-1;
p=PO;
}else{
src.first = 0; src.second=1;
dest.first = order-1; dest.second = order-2;
p=PX;
}
int curr_sz(1), old_sz(0);
pair<int, int> curr;
// Initialize vector of visited vertices as well as a boolean array
// to easily discern whether a vertex has been visited or not.
vector< pair<int, int> > visited(order*order);
bool been_there[order][order];
// Initialize been_there to false, since we haven't visited any nodes.
for(int i; i < order; i++){
for(int j; j < order; j++) been_there[i][j] = false;
}
// Add source vertex to visited list and set boolean value to true
visited[0] = src;
been_there[src.first][src.second] = true;
node *tmp;
for(int j=0; j!=order*order; j++){
// We have explored all connections of this node and have not found the destination. Let's bail.
if(curr_sz == old_sz) return 0;
old_sz = curr_sz;
// Walk through the list of visited nodes and search each of their adjacency
// lists for the destination node.
for(int i=0; i < curr_sz; i++){
curr = visited[i];
// Walk through adjacent nodes of the current node
for(int l = 0; l < this->at(curr).neighbors.size(); l++){
tmp = this->at(curr).neighbors[l];
// Is this node the right player?
if((*tmp).get_player() == p){
// Has it been visited?
if (been_there[(*tmp).getx()][(*tmp).gety()] == false){
// DO WE HAVE A MATCH?!
if((*tmp).get_position() == dest){
return 1; // WOOOOO! We have a winner!
// If it's not a win scenario, push back this node so we can look at it's
// adjacent nodes later.
}else{
visited[curr_sz] = (*tmp).get_position();
curr_sz++;
been_there[(*tmp).getx()][(*tmp).gety()] = true;
}
}
}
}
}
}
return 0;
}
| [
"sevpalmer@gmail.com"
] | sevpalmer@gmail.com |
c7afb361416ac04e18f89dd30e06c2c4738a46cf | 9ad856f7581cadfb98fd1216b9d696293b12fe49 | /Project/SceneLoader/Scenes/Scene_01/Controller/StartButton/StartButton.hpp | 06992ac5797f76ff70fde36fc47ed6cdc6292a3b | [] | no_license | Hanawaro/Turing-machine | 0c9ac024bdebecdafa111b16513493dd0e11da68 | a3db03c105476a1dcc39a4ad80d2574bee4b725e | refs/heads/master | 2022-07-09T10:11:40.846568 | 2020-05-18T21:04:37 | 2020-05-18T21:04:37 | 264,501,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | hpp | #ifndef StartButton_hpp
#define StartButton_hpp
#include "../../Status/Status.hpp"
class StartButton {
public:
StartButton(SDL_Renderer* l_Renderer);
~StartButton(void);
void draw(void);
void touch(void);
void active(void);
void set(void);
void disable(void);
void clear(void);
void deepClear(void);
public:
const int width = 50;
const int height = 50;
const int x1 = 25;
const int y1 = 25;
const int x2 = x1 + width;
const int y2 = y1 + height;
private:
const std::string m_Path = "Source/Sprite/Start/";
SDL_Renderer* m_Renderer = nullptr;
enum class Locale {
Up,
Down,
Touch
};
Locale m_Locale = Locale::Up;
Button m_Texture;
};
#endif
| [
"hanawaro3@gmail.com"
] | hanawaro3@gmail.com |
8b31a0535c7fe9abf7ef7473932facd180853064 | 8f82a46e54200f130c6421d09570e5861c900236 | /OpenGameCamera/sdk.hpp | 834eacaff6e9acc281f91662390dfc59d32e8d74 | [
"LicenseRef-scancode-free-unknown",
"MIT"
] | permissive | GalaxyEham/OpenGameCamera | 8bb6ddbc8280e73bb3b3113bd44d7fb142da6dc5 | deeddd8cb43b8786f1ffffa6b46f4c1e432665b9 | refs/heads/master | 2020-09-28T11:44:07.964783 | 2019-12-09T02:58:49 | 2019-12-09T02:58:49 | 226,771,912 | 1 | 0 | MIT | 2019-12-09T02:56:03 | 2019-12-09T02:56:02 | null | UTF-8 | C++ | false | false | 2,299 | hpp | #pragma once
#include "SigScan/StaticOffsets.h"
#include "BasicTypes.hpp"
// reverse engineered game classes
class GameRenderer;
class RenderView;
class UISettings;
class GameTimeSettings;
class CameraObject;
class GameRenderSettings;
class GlobalPostProcessSettings;
class InputSettings;
class GameRenderer {
public:
char pad_0000[1304]; //0x0000
class GameRenderSettings* gameRenderSettings; //0x0510
char pad_0520[24]; //0x0520
class RenderView* renderView; //0x0538
char pad_0540[4872]; //0x0540
// static method to return the default instance
static GameRenderer* GetInstance(void) {
return *(GameRenderer**)StaticOffsets::Get_OFFSET_GAMERENDERER();
}
};
class GameRenderSettings {
public:
char pad[0x5c];
float forceFov;
};
class GlobalPostProcessSettings {
public:
char pad_0000[196]; //0x0000
int32_t forceDofEnable; //0x00C4
float forceDofBlurFactor; //0x00C8
char pad_00CC[4]; //0x00CC
float forceDofFocusDistance; //0x00D0
char pad_00D4[20]; //0x00D4
float forceSpriteDofNearStart; //0x00E8
float forceSpriteDofNearEnd; //0x00EC
float forceSpriteDofFarStart; //0x00F0
float forceSpriteDofFarEnd; //0x00F4
float forceSpriteDofBlurMax; //0x00F8
char pad_00FC[313]; //0x00FC
bool spriteDofEnable; //0x0235
char pad_0236[1]; //0x0236
bool enableForeground; //0x0237
char pad_0238[2]; //0x0238
bool spriteDofHalfResolutionEnable; //0x023A
};
// RenderView structure, where we can read the camera transform
class RenderView {
public:
Matrix4x4 transform;
};
class UISettings {
public:
char pad_000[0x44];
bool drawEnable;
// static method to return the default instance, from an offset of GameTimeSettings's pointer
static UISettings* GetInstance(void) {
return *(UISettings**)(StaticOffsets::Get_OFFSET_GAMETIMESETTINGS() + 0x10);
}
};
// used for freezing time
class GameTimeSettings {
public:
char pad[0x38];
float timeScale;
static GameTimeSettings* GetInstance() {
return *(GameTimeSettings**)StaticOffsets::Get_OFFSET_GAMETIMESETTINGS();
}
};
// our CameraObject that needs to be used for the camera hook
class CameraObject {
public:
Matrix4x4 cameraTransform;
};
class InputSettings {
public:
char pad[0x94];
float mouseSensitivityPower;
static InputSettings* GetInstance() {
return *(InputSettings**)OFFSET_INPUTSETTINGS;
}
}; | [
"cnpearson42@gmail.com"
] | cnpearson42@gmail.com |
51cc5f981142ad46f0ede166f955d4430e9f5d3d | db8a05784fc53493e9afe2ac66ec7fc4601ba858 | /dms-enterprise/src/model/ListUserPermissionsResult.cc | dbb1fcf3c140d024d3d18afc77cd55de0ddc2440 | [
"Apache-2.0"
] | permissive | netangel2050/aliyun-openapi-cpp-sdk | 31cf70c28c13508e977c729c62ee9366c0b7ceda | a4f63bc75f217010dab18ef0f5d9cdc6ea92e80e | refs/heads/master | 2023-02-02T22:56:39.269293 | 2020-12-21T02:59:31 | 2020-12-21T02:59:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,901 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/dms-enterprise/model/ListUserPermissionsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Dms_enterprise;
using namespace AlibabaCloud::Dms_enterprise::Model;
ListUserPermissionsResult::ListUserPermissionsResult() :
ServiceResult()
{}
ListUserPermissionsResult::ListUserPermissionsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListUserPermissionsResult::~ListUserPermissionsResult()
{}
void ListUserPermissionsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allUserPermissionsNode = value["UserPermissions"]["UserPermission"];
for (auto valueUserPermissionsUserPermission : allUserPermissionsNode)
{
UserPermission userPermissionsObject;
if(!valueUserPermissionsUserPermission["UserId"].isNull())
userPermissionsObject.userId = valueUserPermissionsUserPermission["UserId"].asString();
if(!valueUserPermissionsUserPermission["UserNickName"].isNull())
userPermissionsObject.userNickName = valueUserPermissionsUserPermission["UserNickName"].asString();
if(!valueUserPermissionsUserPermission["DsType"].isNull())
userPermissionsObject.dsType = valueUserPermissionsUserPermission["DsType"].asString();
if(!valueUserPermissionsUserPermission["DbId"].isNull())
userPermissionsObject.dbId = valueUserPermissionsUserPermission["DbId"].asString();
if(!valueUserPermissionsUserPermission["Logic"].isNull())
userPermissionsObject.logic = valueUserPermissionsUserPermission["Logic"].asString() == "true";
if(!valueUserPermissionsUserPermission["SchemaName"].isNull())
userPermissionsObject.schemaName = valueUserPermissionsUserPermission["SchemaName"].asString();
if(!valueUserPermissionsUserPermission["SearchName"].isNull())
userPermissionsObject.searchName = valueUserPermissionsUserPermission["SearchName"].asString();
if(!valueUserPermissionsUserPermission["InstanceId"].isNull())
userPermissionsObject.instanceId = valueUserPermissionsUserPermission["InstanceId"].asString();
if(!valueUserPermissionsUserPermission["EnvType"].isNull())
userPermissionsObject.envType = valueUserPermissionsUserPermission["EnvType"].asString();
if(!valueUserPermissionsUserPermission["Alias"].isNull())
userPermissionsObject.alias = valueUserPermissionsUserPermission["Alias"].asString();
if(!valueUserPermissionsUserPermission["DbType"].isNull())
userPermissionsObject.dbType = valueUserPermissionsUserPermission["DbType"].asString();
if(!valueUserPermissionsUserPermission["TableName"].isNull())
userPermissionsObject.tableName = valueUserPermissionsUserPermission["TableName"].asString();
if(!valueUserPermissionsUserPermission["TableId"].isNull())
userPermissionsObject.tableId = valueUserPermissionsUserPermission["TableId"].asString();
if(!valueUserPermissionsUserPermission["ColumnName"].isNull())
userPermissionsObject.columnName = valueUserPermissionsUserPermission["ColumnName"].asString();
auto allPermDetailsNode = allUserPermissionsNode["PermDetails"]["PermDetail"];
for (auto allUserPermissionsNodePermDetailsPermDetail : allPermDetailsNode)
{
UserPermission::PermDetail permDetailsObject;
if(!allUserPermissionsNodePermDetailsPermDetail["PermType"].isNull())
permDetailsObject.permType = allUserPermissionsNodePermDetailsPermDetail["PermType"].asString();
if(!allUserPermissionsNodePermDetailsPermDetail["ExpireDate"].isNull())
permDetailsObject.expireDate = allUserPermissionsNodePermDetailsPermDetail["ExpireDate"].asString();
if(!allUserPermissionsNodePermDetailsPermDetail["CreateDate"].isNull())
permDetailsObject.createDate = allUserPermissionsNodePermDetailsPermDetail["CreateDate"].asString();
if(!allUserPermissionsNodePermDetailsPermDetail["OriginFrom"].isNull())
permDetailsObject.originFrom = allUserPermissionsNodePermDetailsPermDetail["OriginFrom"].asString();
if(!allUserPermissionsNodePermDetailsPermDetail["UserAccessId"].isNull())
permDetailsObject.userAccessId = allUserPermissionsNodePermDetailsPermDetail["UserAccessId"].asString();
if(!allUserPermissionsNodePermDetailsPermDetail["ExtraData"].isNull())
permDetailsObject.extraData = allUserPermissionsNodePermDetailsPermDetail["ExtraData"].asString();
userPermissionsObject.permDetails.push_back(permDetailsObject);
}
userPermissions_.push_back(userPermissionsObject);
}
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["ErrorMessage"].isNull())
errorMessage_ = value["ErrorMessage"].asString();
if(!value["ErrorCode"].isNull())
errorCode_ = value["ErrorCode"].asString();
if(!value["TotalCount"].isNull())
totalCount_ = std::stol(value["TotalCount"].asString());
}
long ListUserPermissionsResult::getTotalCount()const
{
return totalCount_;
}
std::string ListUserPermissionsResult::getErrorCode()const
{
return errorCode_;
}
std::vector<ListUserPermissionsResult::UserPermission> ListUserPermissionsResult::getUserPermissions()const
{
return userPermissions_;
}
std::string ListUserPermissionsResult::getErrorMessage()const
{
return errorMessage_;
}
bool ListUserPermissionsResult::getSuccess()const
{
return success_;
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
c362c4a57ca79418b0f211d11a2e464833d4be1e | fb8e55204362d0d0a6c3829760de63abb5fcff2c | /Tutorial 11/LoadingTileMapsUsingVectors/main.cpp | c8b636040677c264fe2a694c0bc1c6f69093c819 | [] | no_license | igorternyuk/SFML2Tutorials | 1ab30c301379291ed44239a0f38ae33392e349a2 | 82679a55fa79d4ac87249afbf596e18fa7507ddd | refs/heads/master | 2021-01-21T16:44:24.140547 | 2017-05-23T14:40:22 | 2017-05-23T14:40:22 | 91,902,487 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,988 | cpp | #include <SFML/Graphics.hpp>
#include <vector>
#include <string>
#include <cmath>
#include <ctime>
#include <stdlib.h>
#include <cctype>
#include <iostream>
#include <fstream>
int main()
{
sf::Vector2i size(600, 600);
sf::RenderWindow window(sf::VideoMode(size.x, size.y), "Loading maps", sf::Style::Default);
window.setPosition(sf::Vector2i(100, 100));
sf::Texture tileTexture;
sf::Sprite tiles;
//Загрузка карты
std::ifstream openFile("map.txt");
std::vector<std::vector<sf::Vector2i>> map;
std::vector<sf::Vector2i> temp;
if(openFile.is_open())
{
std::string tileLocation;
openFile >> tileLocation;
if(!tileTexture.loadFromFile(tileLocation))
{
std::cout << "Could not load image file" << std::endl;
}
tiles.setTexture(tileTexture);
while(!openFile.eof())
{
std::string str;
openFile >> str;
char x = str[0];
char y = str[2];
if(!isdigit(x) || !isdigit(y))
temp.push_back(sf::Vector2i(-1, -1));
else
temp.push_back(sf::Vector2i(x - '0', y - '0'));
std::cout << "temp.size() = " << temp.size() << std::endl;
if(openFile.peek() == '\n')
{
std::cout << "Закидаем строку в матрицу" <<std::endl;
map.push_back(temp);
temp.clear();
}
}
map.push_back(temp);
}
////////////
std::cout << "Печатаем нашу карту" << std::endl;
for(int i = 0; i < int(map.size()); ++i)
{
for(int j = 0; j < int(map[i].size()); ++j)
{
std::cout << "(" << map[i][j].x << "," << map[i][j].y << ") ";
}
std::cout << std::endl;
}
std::cout << "map.size() = " << map.size() << std::endl;
while(window.isOpen())
{
sf::Event event;
while(window.pollEvent(event))
{
switch(event.type)
{
case sf::Event::Closed :
window.close();
break;
case sf::Event::KeyPressed :
if(event.key.code == sf::Keyboard::Escape)
window.close();
break;
default :
break;
}
}
window.clear(sf::Color(0, 200, 230));
for(int i = 0; i < int(map.size()); ++i)
{
for(int j = 0; j < int(map[i].size()); ++j)
{
if(map[i][j].x != -1 && map[i][j].y != -1)
{
tiles.setPosition(j * 32, i * 32);
tiles.setTextureRect(sf::IntRect(map[i][j].x * 32, map[i][j].y * 32, 32, 32));
window.draw(tiles);
}
}
}
window.draw(tiles);
window.display();
}
return 0;
}
| [
"xmonad100@gmail.com"
] | xmonad100@gmail.com |
37d105c771f813dab6fd07ebc7ef10a4e66e5d72 | abe2c978f240a5508f6ec842c9e7a6ab50d4f205 | /QWorkNew/plugins/db/dbproviders/OracleRdbProvider/engine/RdbSqlLinkFinder.cpp | 6aad2345798b511281c9b666b330b43b51b932bc | [] | no_license | kai66673/QWorkNew | 48cdb76edafc36468a9b89a1509db8511f890a42 | de485ae2fff0fa2d0c5274a5c51712896d98c311 | refs/heads/master | 2021-08-26T00:33:25.273835 | 2021-08-25T18:13:13 | 2021-08-25T18:13:13 | 98,813,428 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,712 | cpp | #include "RdbSqlLinkFinder.h"
#include "RdbSqlScope.h"
#include "SqlToken.h"
namespace RDB {
static Core::ILink *createSubobjectLink( Database::DbConnection *connection,
const QString &objectName,
const QString &subobjectName,
unsigned objectType,
unsigned objectSubtype,
int begin, int end )
{
if ( connection ) {
if ( QList<Database::IDbCatalogItem *> *objects = connection->schemaObjectObjects( "", objectName, objectType, objectSubtype ) ) {
for (int i = 0; i < objects->size(); i++) {
Database::IDbCatalogItem *object = objects->at(i);
if ( !subobjectName.compare(object->name(), Qt::CaseInsensitive) ) {
return new Sql::DetailsLink(begin, end, connection, object);
}
}
}
}
return 0;
}
static void printAliasesToTablesMap( const QMap<QString, NameAST *> &m )
{
QMap<QString, NameAST *>::const_iterator it = m.constBegin();
while ( it != m.constEnd() ) {
qDebug() << " -" << it.key() << it.value()->name->chars();
++it;
}
}
namespace { // Anonimous namespace
class ColumnFinder: protected ASTVisitor
{
private:
struct TableColumns {
QList<NameAST *> columns;
void insert( NameAST *columnNameAst ) {
QString columnName(columnNameAst->name->chars());
columnName = columnName.toUpper();
foreach ( NameAST *c, columns ) {
if ( !columnName.compare(c->name->chars(), Qt::CaseInsensitive) )
return;
}
columns << columnNameAst;
}
NameAST *find( const QString &columnName ) const {
foreach ( NameAST *c, columns ) {
if ( !columnName.compare(c->name->chars(), Qt::CaseInsensitive) )
return c;
}
return 0;
}
};
public:
ColumnFinder( Sql::TranslationUnit *unit, Database::DbConnection *connection )
: ASTVisitor(unit)
, m_translationUnit(unit)
, m_connection(connection)
, m_currentColumns(0)
{ }
virtual ~ColumnFinder() {
qDeleteAll(m_tableColumns.values());
}
Core::ILink *operator () ( TranslationUnitAST *ast, StatementAST *currentStatemenAst, int begin, int end,
const QList<NameAST *> &tableNames, const QString &columnName ) {
m_begin = begin;
m_end = end;
bool currentStatemenNotProceded = true;
for ( StatementListAST *iter = ast->statement_list; iter && currentStatemenNotProceded; iter = iter->next ) {
if ( StatementAST *statement = iter->value ) {
if ( statement == currentStatemenAst )
currentStatemenNotProceded = false;
if ( statement->asCreateTableStatement() || statement->asCreateViewStatement() || statement->asAlterTableStatement() ) {
m_currentColumns = 0;
statement->accept(this);
}
}
}
foreach ( NameAST *tableNameAst, tableNames ) {
if ( Core::ILink *link = linkForTableColumn(tableNameAst, columnName) )
return link;
}
return 0;
}
protected:
virtual bool visit( CreateTableStatementAST *ast ) {
if ( ast && ast->schemaTableName && ast->schemaTableName->tableName ) {
QString tableName(ast->schemaTableName->tableName->name->chars());
tableName = tableName.toUpper();
m_currentColumns = new TableColumns();
m_currenActionIsAdd = true;
m_tableColumns[tableName] = m_currentColumns;
}
return true;
}
virtual bool visit( CreateViewStatementAST *ast ) {
if ( ast && ast->schemaViewName && ast->schemaViewName->tableName ) {
QString tableName(ast->schemaViewName->tableName->name->chars());
tableName = tableName.toUpper();
m_currentColumns = new TableColumns();
m_currenActionIsAdd = true;
m_tableColumns[tableName] = m_currentColumns;
}
return true;
}
virtual bool visit( ExprResultColumnAST *ast ) {
if ( ast && ast->expr && m_currenActionIsAdd && m_currentColumns ) {
if ( ColumnAliasAST *aliasAst = ast->columnAlias ) {
m_currentColumns->insert(aliasAst);
} else if ( ColumnExpressionAST *colExpr = ast->expr->asColumnExpression() ) {
if ( colExpr->column )
m_currentColumns->insert(colExpr->column);
}
}
return false;
}
virtual bool visit( ColumnDefinitionAST *ast ) {
if ( ast && m_currenActionIsAdd && m_currentColumns ) {
if ( ColumnNameAST *columnNameAst = ast->columnName ) {
m_currentColumns->insert(columnNameAst);
}
}
return false;
}
virtual bool visit( AlterTableStatementAST *ast ) {
if ( ast && ast->schemaTableName && ast->schemaTableName->tableName ) {
QString tableName(ast->schemaTableName->tableName->name->chars());
tableName = tableName.toUpper();
QMap<QString, TableColumns *>::iterator it = m_tableColumns.find(tableName);
if ( it == m_tableColumns.end() ) {
m_currentColumns = new TableColumns();
m_tableColumns[tableName] = m_currentColumns;
}
else {
m_currentColumns = *it;
}
return true;
}
return false;
}
virtual bool visit( AlterTableDropClauseAST *ast ) {
if ( ast ) {
m_currenActionIsAdd = false;
}
return true;
}
virtual bool visit( AlterTableAddColumnClauseAST *ast ) {
if ( ast ) {
m_currenActionIsAdd = true;
}
return true;
}
virtual bool visit( ColumnNameAST *ast ) {
if ( ast && m_currentColumns && m_currenActionIsAdd ) {
m_currentColumns->insert(ast);
}
return false;
}
private:
Core::ILink *createTextTargetLinkForToken( unsigned token )
{
unsigned line;
unsigned column;
m_translationUnit->getTokenStartPosition(token, &line, &column);
if ( !line )
column++;
return new Core::TextTargetLink(m_begin, m_end, "", line, column - 1);
}
Core::ILink *linkForTableColumn( NameAST *tableAst, const QString &columnName ) {
QString tableName(tableAst->name->chars());
tableName = tableName.toUpper();
if ( Core::ILink *link = createSubobjectLink( m_connection,
tableName,
columnName,
Sql::Constants::DbSchemaObjectType::C_TABLE,
Sql::Constants::DbSchemaObjectSubtype::C_TABLE_COLUMN,
m_begin, m_end ) )
return link;
if ( Core::ILink *link = createSubobjectLink( m_connection,
tableName,
columnName,
Sql::Constants::DbSchemaObjectType::C_VIEW,
Sql::Constants::DbSchemaObjectSubtype::C_VIEW_COLUMN,
m_begin, m_end ) )
return link;
QMap<QString, TableColumns *>::iterator it = m_tableColumns.find(tableName);
if ( it != m_tableColumns.end() ) {
TableColumns *tableColumns = *it;
if ( NameAST *linkAst = tableColumns->find(columnName) ) {
return createTextTargetLinkForToken(linkAst->name_token);
}
}
return 0;
}
Sql::TranslationUnit *m_translationUnit;
Database::DbConnection *m_connection;
int m_begin;
int m_end;
QMap<QString, TableColumns *> m_tableColumns;
TableColumns *m_currentColumns;
bool m_currenActionIsAdd;
};
} // Anonimous namespace
SqlLinkFinder::SqlLinkFinder( Sql::TranslationUnit *unit )
: ASTVisitor(unit)
, m_translationUnit(unit)
, m_ast(0)
, m_currentStatemenAst(0)
, m_linkTokenIndex(-1)
, m_begin(-1)
, m_end(-1)
, m_link(0)
{
}
Core::ILink *SqlLinkFinder::findLinkAt( TranslationUnitAST *ast, int position )
{
m_position = (unsigned) position;
m_ast = ast;
for (unsigned i = 1; i < m_translationUnit->tokenCount() - 1; i++) {
if ( m_translationUnit->getTokenOffset(i) >= m_position ) {
const Sql::Token &tk = m_translationUnit->tokenAt(i - 1);
if ( tk.begin() <= m_position && tk.end() >= m_position ) {
if ( !tk.isIdentifier() )
return 0;
m_linkTokenIndex = i - 1;
m_begin = tk.begin();
m_end = tk.end();
m_linkText = QString(tk.identifier->chars()).toUpper();
return findLinkInternal(ast);
}
return 0;
}
}
return 0;
}
bool SqlLinkFinder::visit( SelectCoreAST *ast )
{
if ( ast ) {
if ( ast->joinSource )
ast->joinSource->accept(this);
if ( ast->columnList )
accept(ast->columnList);
if ( ast->whereExpr )
ast->whereExpr->accept(this);
if ( ast->groupBy )
ast->groupBy->accept(this);
}
return false;
}
bool SqlLinkFinder::visit( FkReferencesClauseAST *ast )
{
if ( ast && ast->refSchemaTableName && ast->refSchemaTableName->tableName && ast->ref_col_list &&
m_linkTokenIndex >= ast->ref_col_list->firstToken() && m_linkTokenIndex <= ast->ref_col_list->lastToken() ) {
m_tableAliasesToNames.clear();
m_tableAliasesToNames[QString(ast->refSchemaTableName->tableName->name->chars()).toUpper()] = ast->refSchemaTableName->tableName;
return true;
}
return false;
}
bool SqlLinkFinder::visit( TableNameAST *ast )
{
if ( !m_link && ast && m_linkTokenIndex == ast->name_token ) {
m_link = findSchemaObjectLink(Sql::Constants::DbSchemaObjectType::C_TABLE);
if ( !m_link ) {
m_link = findSchemaObjectLink(Sql::Constants::DbSchemaObjectType::C_VIEW);
if ( !m_link )
m_link = findCreateTableLink(QString(ast->name->chars()));
}
}
return false;
}
bool SqlLinkFinder::visit( ColumnNameAST *ast )
{
if ( !m_link && ast && m_linkTokenIndex == ast->name_token ) {
if ( ast->tableOfColumn ) {
QString aliasName = QString(ast->tableOfColumn->name->chars()).toUpper();
QMap<QString, NameAST *>::iterator it = m_tableAliasesToNames.find(aliasName);
if ( it != m_tableAliasesToNames.end() ) {
ColumnFinder finder(m_translationUnit, m_connection);
m_link = finder( m_ast, m_currentStatemenAst, m_begin, m_end, QList<NameAST *>() << (*it), m_linkText );
}
}
else {
ColumnFinder finder(m_translationUnit, m_connection);
m_link = finder( m_ast, m_currentStatemenAst, m_begin, m_end, m_tableAliasesToNames.values(), m_linkText );
}
}
return true;
}
bool SqlLinkFinder::visit( StarResultColumnAST *ast )
{
if ( ast && ast->schemaTableName && ast->schemaTableName->tableName && m_linkTokenIndex == ast->schemaTableName->tableName->name_token ) {
QMap<QString, NameAST *>::iterator it = m_tableAliasesToNames.find(m_linkText);
if ( it != m_tableAliasesToNames.end() ) {
m_link = createTextTargetLinkForToken((*it)->name_token);
}
}
return false;
}
bool SqlLinkFinder::visit( SchemaTableNameAST *ast )
{
if ( ast && ast->tableName ) {
m_tableAliasesToNames[QString(ast->tableName->name->chars()).toUpper()] = ast->tableName;
}
return true;
}
bool SqlLinkFinder::visit( TableAliasAST *ast )
{
if ( ast ) {
if ( ast->schemaTableName && ast->schemaTableName->tableName ) {
m_tableAliasesToNames[QString(ast->name->chars()).toUpper()] = ast->schemaTableName->tableName;
}
if ( !m_link && m_linkTokenIndex == ast->name_token ) {
QMap<QString, NameAST *>::iterator it = m_tableAliasesToNames.find(m_linkText);
if ( it != m_tableAliasesToNames.end() ) {
m_link = createTextTargetLinkForToken((*it)->name_token);
}
}
}
return true;
}
bool SqlLinkFinder::visit( IndexNameAST *ast )
{
if ( !m_link && ast && m_linkTokenIndex == ast->name_token ) {
m_link = findSchemaObjectLink(Sql::Constants::DbSchemaObjectType::C_INDEX);
if ( !m_link )
m_link = findCreateIndexLink(QString(ast->name->chars()));
}
return false;
}
bool SqlLinkFinder::visit( TriggerNameAST *ast )
{
if ( !m_link && ast && m_linkTokenIndex == ast->name_token ) {
m_link = findSchemaObjectLink(Sql::Constants::DbSchemaObjectType::C_TRIGGER);
if ( !m_link )
m_link = findCreateTriggerLink(QString(ast->name->chars()));
}
return false;
}
bool SqlLinkFinder::visit( ConstraintNameAST *ast )
{
if ( !m_link && ast && m_linkTokenIndex == ast->name_token ) {
m_link = findSchemaObjectLink(Sql::Constants::DbSchemaObjectType::C_CONSTRAINT);
if ( !m_link )
m_link = findCreateConstraintLink(QString(ast->name->chars()));
}
return false;
}
Core::ILink *SqlLinkFinder::findLinkInternal( TranslationUnitAST *ast )
{
for ( StatementListAST *iter = ast->statement_list; iter; iter = iter->next ) {
StatementAST *statement = iter->value;
if ( statement ) {
if ( m_linkTokenIndex <= statement->lastToken() ) {
if ( m_linkTokenIndex >= statement->firstToken() )
return findLinkInStatement(statement);
return 0;
}
}
}
return 0;
}
Core::ILink *SqlLinkFinder::findLinkInStatement( StatementAST *ast )
{
m_currentStatemenAst = ast;
if ( ast->asBlockStatement() || ast->asCreateModuleStatement() || ast->asCreateRoutineStatement() ) {
const Sql::Token &tk = m_translationUnit->tokenAt(m_linkTokenIndex - 1);
if ( tk.kind() == Sql::T_COLON ) {
SqlIdentifiersVisitor identsVisitor(m_translationUnit, ast, m_linkTokenIndex);
ast->accept(&identsVisitor);
if ( unsigned linkTokenIndex = identsVisitor.linkTokenIndex(m_linkText) ) {
return createTextTargetLinkForToken(linkTokenIndex);
}
}
else {
if ( BlockStatementAST *blockAst = ast->asBlockStatement() ) {
return findLinkInBlockStatement(blockAst);
} else if ( CreateRoutineStatementAST *routineAst = ast->asCreateRoutineStatement() ) {
if ( routineAst->routine && routineAst->routine->block )
return findLinkInBlockStatement(routineAst->routine->block);
}
if ( CreateModuleStatementAST *moduleAst = ast->asCreateModuleStatement() ) {
for ( RoutineListAST *iter = moduleAst->routine_list; iter; iter = iter->next ) {
RoutineAST *routine = iter->value;
if ( !routine )
continue;
if ( m_linkTokenIndex >= routine->firstToken() ) {
if ( m_linkTokenIndex <= routine->lastToken() ) {
if ( routine->block )
return findLinkInBlockStatement(routine->block);
}
break;
}
}
}
}
return 0;
}
return findLinkInSingleStatement(ast);
}
Core::ILink *SqlLinkFinder::findLinkInBlockStatement( BlockStatementAST *ast )
{
if ( ast && m_linkTokenIndex >= ast->firstToken() && m_linkTokenIndex <= ast->lastToken() && ast->entry_list ) {
for (BlockStatementEntryListAST *iter = ast->entry_list; iter; iter = iter->next) {
BlockStatementEntryAST *statement = iter->value;
if ( statement && m_linkTokenIndex >= statement->firstToken() && m_linkTokenIndex <= statement->lastToken() ) {
return findLinkInSingleStatement(statement);
}
}
}
return 0;
}
Core::ILink *SqlLinkFinder::findLinkInSingleStatement( AST *ast )
{
if ( m_provider = Sql::DbMetadataProvider::getInstance() ) {
if ( m_connection = m_provider->connection() ) {
ast->accept(this);
return m_link;
}
}
return 0;
}
Sql::DetailsLink *SqlLinkFinder::findSchemaObjectLink( unsigned objectType )
{
if ( QList<Database::IDbCatalogItem *> *objects = m_connection->schemaObjects("", objectType) ) {
for (int i = 0; i < objects->size(); i++) {
Database::IDbCatalogItem *object = objects->at(i);
if ( !m_linkText.compare(object->name(), Qt::CaseInsensitive) ) {
return new Sql::DetailsLink(m_begin, m_end, m_connection, object);
}
}
}
return 0;
}
Core::ILink *SqlLinkFinder::findCreateTableLink( const QString &tableName )
{
if ( m_ast ) {
bool currentAstNotProceded = true;
for ( StatementListAST *iter = m_ast->statement_list; iter && currentAstNotProceded; iter = iter->next ) {
if ( StatementAST *statement = iter->value ) {
if ( m_currentStatemenAst == statement )
currentAstNotProceded = false;
if ( CreateTableStatementAST *createTableAst = statement->asCreateTableStatement() ) {
if ( createTableAst->schemaTableName && createTableAst->schemaTableName->tableName ) {
TableNameAST *tableNameAst = createTableAst->schemaTableName->tableName;
if ( !tableName.compare(tableNameAst->name->chars(), Qt::CaseInsensitive) ) {
return createTextTargetLinkForToken(tableNameAst->name_token);
}
}
} else if ( CreateViewStatementAST *createViewAst = statement->asCreateViewStatement() ) {
if ( createViewAst->schemaViewName && createViewAst->schemaViewName->tableName ) {
TableNameAST *tableNameAst = createViewAst->schemaViewName->tableName;
if ( !tableName.compare(tableNameAst->name->chars(), Qt::CaseInsensitive) ) {
return createTextTargetLinkForToken(tableNameAst->name_token);
}
}
}
}
}
}
return 0;
}
Core::ILink *SqlLinkFinder::findCreateIndexLink( const QString &indexName )
{
if ( m_ast ) {
bool currentAstNotProceded = true;
for ( StatementListAST *iter = m_ast->statement_list; iter && currentAstNotProceded; iter = iter->next ) {
if ( StatementAST *statement = iter->value ) {
if ( m_currentStatemenAst == statement )
currentAstNotProceded = false;
if ( CreateIndexStatementAST *createIndexAst = statement->asCreateIndexStatement() ) {
if ( createIndexAst->schemaIndexName && createIndexAst->schemaIndexName->indexName ) {
IndexNameAST *indexNameAst = createIndexAst->schemaIndexName->indexName;
if ( !indexName.compare(indexNameAst->name->chars(), Qt::CaseInsensitive) ) {
return createTextTargetLinkForToken(indexNameAst->name_token);
}
}
}
}
}
}
return 0;
}
Core::ILink *SqlLinkFinder::findCreateTriggerLink( const QString &triggerName )
{
if ( m_ast ) {
bool currentAstNotProceded = true;
for ( StatementListAST *iter = m_ast->statement_list; iter && currentAstNotProceded; iter = iter->next ) {
if ( StatementAST *statement = iter->value ) {
if ( m_currentStatemenAst == statement )
currentAstNotProceded = false;
if ( CreateTriggerStatementAST *createTriggerAst = statement->asCreateTriggerStatement() ) {
if ( createTriggerAst->schemaTriggerName && createTriggerAst->schemaTriggerName->triggerName ) {
TriggerNameAST *triggerNameAst = createTriggerAst->schemaTriggerName->triggerName;
if ( !triggerName.compare(triggerNameAst->name->chars(), Qt::CaseInsensitive) ) {
return createTextTargetLinkForToken(triggerNameAst->name_token);
}
}
}
}
}
}
return 0;
}
Core::ILink *SqlLinkFinder::findCreateConstraintLink( const QString &constraintName )
{
if ( m_ast ) {
bool currentAstNotProceded = true;
for ( StatementListAST *iter = m_ast->statement_list; iter && currentAstNotProceded; iter = iter->next ) {
if ( StatementAST *statement = iter->value ) {
if ( m_currentStatemenAst == statement )
currentAstNotProceded = false;
if ( CreateTableStatementAST *createTableAst = statement->asCreateTableStatement() ) {
if ( createTableAst->tableClause ) {
if ( CreateTableDirectClauseAST *createClause = createTableAst->tableClause->asCreateTableDirectClause() ) {
for ( TableConstraintListAST *iter = createClause->constraintList; iter; iter = iter->next ) {
if ( TableConstraintAST *constraint = iter->value ) {
if ( ConstraintNameAST *constraintNameAst = constraint->constraintName ) {
if ( !constraintName.compare(constraintNameAst->name->chars()) ) {
return createTextTargetLinkForToken(constraintNameAst->name_token);
}
}
}
}
for ( ColumnDefinitionListAST *it = createClause->column_def_list; it; it = it->next ) {
if ( ColumnDefinitionAST *columnDefAst = it->value ) {
for ( ColumnConstraintListAST *itc = columnDefAst->constraintList; itc; itc = itc->next ) {
if ( ColumnConstraintAST *colConstrainAst = itc->value ) {
if ( ConstraintNameAST *constraintNameAst = colConstrainAst->constraintName ) {
if ( !constraintName.compare(constraintNameAst->name->chars()) ) {
return createTextTargetLinkForToken(constraintNameAst->name_token);
}
}
}
}
}
}
}
}
} else if ( AlterTableStatementAST *alterTableAst = statement->asAlterTableStatement() ) {
if ( alterTableAst->alterTableClause ) {
if ( AlterTableAddConstraintClauseAST *addClause = alterTableAst->alterTableClause->asAlterTableAddConstraintClause() ) {
if ( TableConstraintAST *constraint = addClause->constraint ) {
if ( ConstraintNameAST *constraintNameAst = constraint->constraintName ) {
if ( !constraintName.compare(constraintNameAst->name->chars()) ) {
return createTextTargetLinkForToken(constraintNameAst->name_token);
}
}
}
}
}
}
}
}
}
return 0;
}
/// TODO: To Static Method
Core::ILink *SqlLinkFinder::createTextTargetLinkForToken( unsigned token )
{
unsigned line;
unsigned column;
m_translationUnit->getTokenStartPosition(token, &line, &column);
if ( !line )
column++;
return new Core::TextTargetLink(m_begin, m_end, "", line, column - 1);
}
} // namespace RDB
| [
"kudryavtsev@teleformis.ru"
] | kudryavtsev@teleformis.ru |
e8c90458c219f0d87f28b3143540285276978960 | 7bc616ba82a2917a842e4ffb333b87c87c364230 | /src/shared/World/Vehicle.h | 0aa5cc35d30b99363b5a199aa6eb41b42024eb6e | [] | no_license | fathat/game-src | af96ef99abc00e41b2e11086f859ee28872f4a87 | a8cc8238a463067d2259ab0b1dff1cd947e27aa5 | refs/heads/master | 2021-01-10T21:00:57.293722 | 2012-02-18T20:59:49 | 2012-02-18T20:59:49 | 3,480,646 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,058 | h | // I N C L U D E S //////////////////////////////
#include "..\Physics\Construction.h"
// C L A S S E S ////////////////////////////////
struct Wheel
{
float Radius;
Vector3D Location;
};
class Vehicle4Wheeled : public Construction
{
protected:
bool AllWheelSteering;
MeshHandle ChassisMesh;
MeshHandle WheelMesh;
MeshManager* pMM;
Wheel WheelList[4];
float ChassisWidth, ChassisHeight, ChassisLength;
float ChassisX, ChassisY, ChassisZ;
float ChassisMass;
Real FrontWheelZOffset;
Real BackWheelZOffset;
Real WheelXOffset;
Real WheelYOffset;
float SteeringAngle;
float SteeringForce;
float MaxSpeed;
Real PedalForce; //between -100 and 100, 100 being gas to the floor
//-100 being brake mashed
Real CurrentSpeed; //HMMMMMM
Real RPM;
int Gear;
bool ClutchDepressed;
bool HandBrake;
LPD3DXMESH d3dxWheelMesh;
//Center of gravity
float CenterX, CenterY, CenterZ;
public:
Vehicle4Wheeled();
std::string GetTypeString();
bool Construct( char* descriptionFile, DynamicsSolver* solver, Screen3D& Screen,MeshManager& MM, Position& Location, ICollisionHandler* collisionHandler=NULL );
void OnTurn( Real Force, Real Angle );
void OnAccelerate( Real pedalForce, Real SideForce=0, Real UpForce=0 );
bool CheckForParticleCollision ( Vector3D& p1, Vector3D& p2, CollisionInfo* c, MeshManager* MM );
void Update( Real FrameTime, WorldManager* SM );
void GetMatrix( Matrix* M );
void Draw(Screen3D& Screen);
//custom functions (not derived from anything)
Real GetRPM() { return RPM; }
Real GetCurrentSpeed() { return CurrentSpeed; }
void SetClutch( bool c ) { ClutchDepressed = c; }
bool GetClutchDepressed() { return ClutchDepressed; }
void SetGear( int g );
int GetGear() { return Gear; }
Real GetGearTorque( int g, Real rpm );
Real GetGearTopSpeed(int g );
Real GetRPMForGear( int g, Real torque );
void SetHandBrake( bool h ) { HandBrake = h; }
bool GetHandBrake() { return HandBrake; }
}; | [
"ian.overgard@gmail.com"
] | ian.overgard@gmail.com |
99e80c2e7d02e0a8385e422551e87edb295e46fa | f414ee90b1b72f357f1b7c53560252c2f7b91c4a | /Workshop 7/Workshop 7/iProduct.cpp | 1b8ac6f18fd75e771d6722c49fca9ead8ec2639c | [] | no_license | jkjCook/OOP345 | 97344a4e4cf831f0c15c997c5de61a9373e4c9b8 | 380e39e260374a865999a7c1d80882f27384f31a | refs/heads/master | 2021-03-27T18:59:44.426258 | 2017-09-06T21:12:48 | 2017-09-06T21:12:48 | 95,379,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,089 | cpp | #include "iProduct.h"
using namespace std;
namespace w7 {
std::ostream& operator<<(std::ostream& os, const iProduct& prod) {
prod.display(os);
return os;
}
iProduct* readProduct(std::ifstream& file) {
iProduct* prod;
if (file.is_open()) {
string line;
getline(file, line);
if (line.find('H') != string::npos) {
prod = new TaxableProduct(stoi(line.substr(0, line.find(' '))), stod(line.substr(line.find(' '), line.find(' '))), 'H');
}
else if (line.find('P') != string::npos) {
prod = new TaxableProduct(stoi(line.substr(0, line.find(' '))), stod(line.substr(line.find(' '), line.find(' '))), 'P');
}
else {
prod = new Product(stoi(line.substr(0, line.find(' '))), stod(line.substr(line.find(' '), 256)));
}
}
return prod;
}
TaxableProduct::TaxableProduct(int num, double price, char status){
this->status(status);
this->price(price);
this->prodNum(num);
}
Product::Product(int num, double price) {
this->prodNum(num);
this->price(price);
}
double Product::getCharge()const {
return m_price;
}
void Product::display(std::ostream& os)const {
os << setw(10) << m_prodNum << " " << fixed << setw(10) << setprecision(2) << m_price;
}
int Product::getProdNum() {
return m_prodNum;
}
void Product::prodNum(int num) {
m_prodNum = num;
}
void Product::price(double price) {
m_price = price;
}
double TaxableProduct::getCharge() {
double total = 0;
if (this->getStatus() == 'H')
total = Product::getCharge() * 1.13;
if (this->getStatus() == 'P')
total = Product::getCharge() * 1.08;
return total;
}
void TaxableProduct::display(std::ostream& os)const {
this->Product::display(os);
os << " " << (m_status == 'H' ? "HST" : "PST");
}
char TaxableProduct::getStatus() {
return m_status;
}
void TaxableProduct::status(char c) {
m_status = c;
}
}
| [
"jkjcook@gmail.com"
] | jkjcook@gmail.com |
6d5a0321f2fcc81ce639bca09322174889d1b52e | bc3f4007a299ecf68d2846ad63b3bd7e6fcaf035 | /Server/KFContrib/KFZConfig/KFFootConfig.hpp | d042e676831aeb627535bd80a5e09b45417eb6fe | [
"Apache-2.0"
] | permissive | maosher/Fighter | 5901e71d4a22a5941a5132b58d44af5b889477b1 | 4587516099f1ff3d31e1acbf571dbe53c485ad67 | refs/heads/master | 2022-12-04T03:01:29.914772 | 2020-08-18T07:58:04 | 2020-08-18T07:58:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 736 | hpp | #ifndef __KF_FOOT_CONFIG_H__
#define __KF_FOOT_CONFIG_H__
#include "KFrame.h"
#include "KFZConfig/KFConfig.h"
namespace KFrame
{
class KFFootSetting : public KFIntSetting
{
public:
// 名字
std::string _name;
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class KFFootConfig : public KFConfigT< KFFootSetting >, public KFInstance< KFFootConfig >
{
public:
KFFootConfig()
{
_file_name = "foot";
}
protected:
// 读取配资
void ReadSetting( KFNode& xmlnode, KFFootSetting* kfsetting );
};
}
#endif | [
"lori227@qq.com"
] | lori227@qq.com |
5fcb5c9fa335ca3550657ea189a791a0c2a06d42 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_2464487_1/C++/Erik/A.cpp | 3757205901960ecf074eb0626a8af3b768d9a6b5 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 667 | cpp | #include <cstdio>
#include <cmath>
#include <iostream>
#include <inttypes.h>
using namespace std;
int main() {
int T;
cin >> T;
uint64_t r,t;
for (int t_ = 0; t_ < T; t_++) {
cin >> r >> t;
uint64_t min, max;
min = 0;
max = (1LLU<<32)-1;
uint64_t n;
while (min < max) {
if ((max+min)%2 == 0)
n = (max+min)/2;
else
n = (max+min)/2+1;
// cout << min << " " << max << " " << n << endl;
uint64_t val = 2*n*n+n*(2*r-1);
if (val > t) {
max = n-1;
} else {
min = n;
}
}
cout << "Case #" << t_+1 << ": " << (int)min;
cout << endl;
}
return 0;
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
b89ff4bbddb977bc3371a3d4bd719f73965014ed | c3296be0b81624bed5a169ee769d660fceaad3e0 | /framework/core/net/entropy_calibrator.h | 4fd343f1ba9c063d8f96ecd3619551cfa1528fad | [
"Apache-2.0"
] | permissive | pangge/Anakin | f994bb15ba07f75d1bd0a0092e7ffbd7b3bf4633 | f327267d1ee2038d92d8c704ec9f1a03cb800fc8 | refs/heads/master | 2021-07-11T02:14:44.606691 | 2018-11-18T05:38:17 | 2018-11-18T05:38:17 | 133,911,283 | 0 | 0 | Apache-2.0 | 2018-09-08T07:35:49 | 2018-05-18T06:15:03 | C++ | UTF-8 | C++ | false | false | 2,917 | h |
/* Copyright (c) 2018 Anakin Authors, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ANAKIN_ENTROPY_CALIBRATOR_H
#define ANAKIN_ENTROPY_CALIBRATOR_H
#include "framework/core/net/calibrator.h"
namespace anakin {
/**
* \brief Net class used for execution of graph and it is thread safety.
*/
template<typename Ttype>
class EntropyCalibrator: public Calibrator<Ttype> {
public:
EntropyCalibrator(BatchStream<Ttype>* stream,
int batch_size,
std::string calibrator_file,
Net<Ttype, Precision::FP32, OpRunType::SYNC>* net,
int bin_num):
Calibrator<Ttype>(stream, batch_size, calibrator_file, net),
_bin_num(bin_num) {}
~EntropyCalibrator() {
for (auto tensor : _in_vec) {
delete tensor;
tensor = nullptr;
}
}
virtual void init_statistics(int tensor_num);
virtual int get_batch_data(std::vector<Tensor4dPtr<Ttype>> inputs);
virtual void reset_data_stream();
//virtual int get_batch_size() {return _batch_size;}
virtual void read_calibrator();
virtual void write_calibrator();
virtual void generate_calibrator_table();
virtual CalibrationAlgoType get_algorithm() {return ENTROPY;}
private:
void get_ref_q(std::vector<int>& ref_p, std::vector<float>& ref_q);
void expand_to_q(std::vector<int>& ref_p, std::vector<float>& ref_q, std::vector<float>& q);
float get_kl_divergence(std::vector<int>&ref_p, std::vector<float>& q);
void get_histgrams(std::vector<Tensor4dPtr<Ttype>> in_vec,
std::vector<OperatorFunc<Ttype, Precision::FP32 >> exec_funcs);
void get_max_values(std::vector<Tensor4dPtr<Ttype>> in_vec,
std::vector<OperatorFunc<Ttype, Precision::FP32 >> exec_funcs);
void get_kl_threshold(std::vector<std::string>& tensor_name_list);
float max_data(Tensor4dPtr<Ttype> tensor, int tensor_id);
void histgram(Tensor4dPtr<Ttype> tensor, int tensor_id);
int get_bin_num() {return _bin_num;}
std::vector<float>& max_vec() {return _max_vec;}
std::vector<std::vector<int>>& hist_vecs() {return _hist_vecs;}
protected:
std::vector<Tensor4dPtr<X86>> _in_vec;
std::map<std::string, float> _scale_map;
std::vector<float> _max_vec;
std::vector<std::vector<int>> _hist_vecs;
int _bin_num;
};
}
#endif
| [
"939136265@qq.com"
] | 939136265@qq.com |
b31f9b6c2e8590ef447457fc46eaae3a6dfbd011 | b39cf89298cb52758300cb41936d3ab0c67465c4 | /include/mesh/mesh.h | 3b5b2014feea1cba3c75de43a3cc18fd444d649e | [] | no_license | EricDDK/OpenGLLearning | 4e64adc474d88d8fb3a89380622413b5105ace3f | 0336764ed4e56e23b743b15d97c4a0ffd1618675 | refs/heads/master | 2020-03-30T03:56:06.776502 | 2019-07-11T06:50:57 | 2019-07-11T06:50:57 | 150,715,821 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,924 | h | #ifndef MESH_H
#define MESH_H
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "shader/shader.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb/stb_image.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <string>
#include <vector>
using namespace std;
struct Vertex {
glm::vec3 Position;
glm::vec3 Normal;
glm::vec2 TexCoords;
glm::vec3 Tangent;
glm::vec3 Bitangent;
};
struct Texture {
unsigned int id;
string type;
string path;
};
class Mesh {
public:
/* 网格数据 */
vector<Vertex> vertices;
vector<unsigned int> indices;
vector<Texture> textures;
/* 函数 */
Mesh(vector<Vertex> vertices, vector<unsigned int> indices, vector<Texture> textures)
{
this->vertices = vertices;
this->indices = indices;
this->textures = textures;
setupMesh();
}
void Draw(Shader shader)
{
// bind appropriate textures
unsigned int diffuseNr = 1;
unsigned int specularNr = 1;
unsigned int normalNr = 1;
unsigned int heightNr = 1;
for (unsigned int i = 0; i < textures.size(); i++)
{
glActiveTexture(GL_TEXTURE0 + i); // active proper texture unit before binding
// retrieve texture number (the N in diffuse_textureN)
string number;
string name = textures[i].type;
if (name == "texture_diffuse")
number = std::to_string(diffuseNr++);
else if (name == "texture_specular")
number = std::to_string(specularNr++); // transfer unsigned int to stream
else if (name == "texture_normal")
number = std::to_string(normalNr++); // transfer unsigned int to stream
else if (name == "texture_height")
number = std::to_string(heightNr++); // transfer unsigned int to stream
// now set the sampler to the correct texture unit
glUniform1i(glGetUniformLocation(shader.ID, (name + number).c_str()), i);
// and finally bind the texture
glBindTexture(GL_TEXTURE_2D, textures[i].id);
}
// draw mesh
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// always good practice to set everything back to defaults once configured.
glActiveTexture(GL_TEXTURE0);
}
/* 渲染数据 */
unsigned int VAO, VBO, EBO;
private:
/* 函数 */
void setupMesh()
{
// create buffers/arrays
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
// load data into vertex buffers
glBindBuffer(GL_ARRAY_BUFFER, VBO);
// A great thing about structs is that their memory layout is sequential for all its items.
// The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which
// again translates to 3/2 floats which translates to a byte array.
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);
// set the vertex attribute pointers
// vertex Positions
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
// vertex normals
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal));
// vertex texture coords
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));
// vertex tangent
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent));
// vertex bitangent
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent));
glBindVertexArray(0);
}
};
#endif
| [
"dekai.ding@shen021.com"
] | dekai.ding@shen021.com |
b9f6d0dee506f6324aaeb0fdb468fcb047353699 | dcac89e0f9ddcd37f6fc5a909a2784e6089a2758 | /N96FY.h | 712eb54366dbc258dc056d149e0dc6f7e35eae09 | [
"MIT"
] | permissive | tstoegi/esp8266_Anemometer_N96FY | c6938163bb049833c3fdc8db6fcc4cdbfdf86b70 | 11a4d8127100a6c8357933c7c1ea77c1a523b251 | refs/heads/master | 2022-01-13T00:33:10.640025 | 2019-05-18T09:33:06 | 2019-05-18T09:33:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,939 | h | #ifndef N96FY_h
#define N96FY_h
#include <Arduino.h>
/* Arduino N96FY Anemometer Library
* For anemometers based on reed switch technic - usually with 2 wires (for GND,VCC)
* See: https://blogskyeweather.wordpress.com/2016/10/07/anemometer-improvement/
* https://hackaday.io/project/12397-modular-weather-station/log/40644-analog-sensors-ultraviolet-light-wind-and-rain
*
* For this reed swith based sensor I found the following information:
* "A wind speed of 1.492 MPH (2,4 km/h) causes the switch to close once per second."
* I assume "close" means turnaround.
*
* We count the number of turnarounds within a dedicated period (e.g. 10 seconds) and
* just multiply with with the speed factor (e.g.KMH_Factor 2.401)
*
* The implementaion is using 2 interrupts, so you can just use one single instance of this class.
* - A timer interrupt for a dedicated call every second
* - A hardware interrupt to track the changes on the signal (reed switch open/closing)
*
* The current implementation is ESP8266 ONLY!
* Connect one cable to GND and the other to D2(
*
* TODO Add support for other MCUs
*
* (C) 2019 Tobias Stöger (@tstoegi)
*
*/
#define KMH_Factor 2.401 //One turnaround in Km/h
#define MPH_Factor 1.492 //One turnaround in MPH
#define AVERAGE_PERIOD_IN_SECONDS 10 // Calculate the average speed within the last n-Seconds
// Setup the ESP internal timer to 1 second
#define INTERVAL_US 80000000L // 80MHz == 1sec
#define INTERRUPT_PIN D2
class N96FY
{
public:
N96FY (bool useInternalPulldown = true);
void begin();
float speedInKMH();
float speedInMPH();
private:
void startTimer();
float calcNumberOfClosingsInOneSecond(void);
static void ISR_sensor();
static void ISR_everySecond();
bool _useInternalPulldown;
static int counter;
static int values[AVERAGE_PERIOD_IN_SECONDS];
static int seconds;
};
#endif
| [
"tobias@more.io"
] | tobias@more.io |
15483b10940ceae8f0026bc67863e8770677df63 | 2adc0703940010c76fde2148d813f60d3453d7a7 | /Linked List/Linked_list_1.cpp | 9a777912c14cb99b724f29b596f02b9cc57d4047 | [] | no_license | Sensrdt/Geeks-For-Geeks-Solution | 063b62d17b3136480bfecb554297e7b8926aa9bd | 20971dd1c352077b993938f890bacaf63f65e392 | refs/heads/master | 2022-09-01T23:57:30.034548 | 2022-07-31T10:10:40 | 2022-07-31T10:10:40 | 198,783,774 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 574 | cpp | #include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node *next;
};
struct Node* head = NULL;
void insert(int new_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = head;
head = new_node;
}
void display()
{
struct Node* ptr;
ptr = head;
while(ptr != NULL)
{
cout<<ptr->data<<" ";
ptr = ptr->next;
}
}
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The linked list is: ";
display();
return 0;
}
| [
"stsdutta2@gmail.com"
] | stsdutta2@gmail.com |
5efead8e1ba39424537e09b2ba5dfc166727e7d1 | e6f954132aaae3b2cf2c07ae57e017da5428364a | /bcomp/lib/wb/src/wb_c_basesensor.cpp | ad0fc571b658075bd6459849fbfa85c48941729e | [] | no_license | connectthefuture/proview | ec4d0254e8178b686ac34db12f47975434ef0b46 | 116e419a60a8b24733e4b11d6c9b8600145fe4c1 | refs/heads/master | 2021-01-20T04:18:20.679652 | 2017-04-18T10:33:24 | 2017-04-18T10:33:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,768 | cpp | /*
* Proview Open Source Process Control.
* Copyright (C) 2005-2017 SSAB EMEA AB.
*
* This file is part of Proview.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Proview. If not, see <http://www.gnu.org/licenses/>
*
* Linking Proview statically or dynamically with other modules is
* making a combined work based on Proview. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* In addition, as a special exception, the copyright holders of
* Proview give you permission to, from the build function in the
* Proview Configurator, combine Proview with modules generated by the
* Proview PLC Editor to a PLC program, regardless of the license
* terms of these modules. You may copy and distribute the resulting
* combined work under the terms of your choice, provided that every
* copy of the combined work is accompanied by a complete copy of
* the source code of Proview (the version used to produce the
* combined work), being distributed under the terms of the GNU
* General Public License plus this exception.
**/
/* wb_c_basesensor.cpp -- work bench methods of the BaseSensor class */
#include <stdio.h>
#include <string.h>
#include "wb_pwrs.h"
#include "wb_pwrb_msg.h"
#include "pwr_basecomponentclasses.h"
#include "wb_ldh.h"
#include "wb_wsx.h"
#include "wb_session.h"
//
// Syntax check.
//
static pwr_tStatus SyntaxCheck( ldh_tSesContext Session,
pwr_tAttrRef Object,
int *ErrorCount,
int *WarningCount)
{
pwr_tStatus sts;
pwr_tCid plcconnect_class[] = { pwr_cClass_BaseSensorFo, 0};
pwr_tCid simconnect_class[] = { pwr_cClass_BaseSensorSim, 0};
if ( Object.Offset == 0) {
sts = wsx_CheckXAttrRef( Session, Object, "PlcConnect", "PlcConnect", plcconnect_class,
0, ErrorCount, WarningCount);
if ( EVEN(sts)) return sts;
sts = wsx_CheckXAttrRef( Session, Object, "SimConnect", "PlcConnect", simconnect_class,
1, ErrorCount, WarningCount);
if ( EVEN(sts)) return sts;
}
return PWRB__SUCCESS;
}
//
// Every method to be exported to the workbench should be registred here.
//
pwr_dExport pwr_BindMethods(BaseSensor) = {
pwr_BindMethod(SyntaxCheck),
pwr_NullMethod
};
| [
"claes.sjofors@proview.se"
] | claes.sjofors@proview.se |
ae1b09e2f38beda4e42424fd986a25ba14a70e36 | adefd0b14bd643729bff9dc299c42b40dc7d81f8 | /BGFX/entry/entry.cpp | 69c0f5e122c96dbcdfa96b94c6841c5e63253218 | [] | no_license | hustztz/Ambergris | 3eff5ca4ca69e7f37ca19821a6ce197e0858a704 | 6057ac5c120a38ff4ec10a6e5baa2b8b41dddc57 | refs/heads/master | 2021-04-26T07:27:59.333765 | 2018-04-08T09:45:44 | 2018-04-08T09:45:44 | 121,361,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,282 | cpp | /*
* Copyright 2011-2018 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
*/
#include <bx/bx.h>
#include <bx/file.h>
#include <bx/sort.h>
#include <bgfx/bgfx.h>
#include <time.h>
#if BX_PLATFORM_EMSCRIPTEN
# include <emscripten.h>
#endif // BX_PLATFORM_EMSCRIPTEN
#include "entry_p.h"
#include "cmd.h"
#include "input.h"
extern "C" int32_t _main_(int32_t _argc, char** _argv);
namespace entry
{
static uint32_t s_debug = BGFX_DEBUG_NONE;
static uint32_t s_reset = BGFX_RESET_NONE;
static uint32_t s_width = ENTRY_DEFAULT_WIDTH;
static uint32_t s_height = ENTRY_DEFAULT_HEIGHT;
static bool s_exit = false;
static bx::FileReaderI* s_fileReader = NULL;
static bx::FileWriterI* s_fileWriter = NULL;
extern bx::AllocatorI* getDefaultAllocator();
bx::AllocatorI* g_allocator = getDefaultAllocator();
typedef bx::StringT<&g_allocator> String;
static String s_currentDir;
class FileReader : public bx::FileReader
{
typedef bx::FileReader super;
public:
virtual bool open(const bx::FilePath& _filePath, bx::Error* _err) override
{
String filePath(s_currentDir);
filePath.append(_filePath.get() );
return super::open(filePath.getPtr(), _err);
}
};
class FileWriter : public bx::FileWriter
{
typedef bx::FileWriter super;
public:
virtual bool open(const bx::FilePath& _filePath, bool _append, bx::Error* _err) override
{
String filePath(s_currentDir);
filePath.append(_filePath.get() );
return super::open(filePath.getPtr(), _append, _err);
}
};
void setCurrentDir(const char* _dir)
{
s_currentDir.set(_dir);
}
#if ENTRY_CONFIG_IMPLEMENT_DEFAULT_ALLOCATOR
bx::AllocatorI* getDefaultAllocator()
{
BX_PRAGMA_DIAGNOSTIC_PUSH();
BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4459); // warning C4459: declaration of 's_allocator' hides global declaration
BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wshadow");
static bx::DefaultAllocator s_allocator;
return &s_allocator;
BX_PRAGMA_DIAGNOSTIC_POP();
}
#endif // ENTRY_CONFIG_IMPLEMENT_DEFAULT_ALLOCATOR
static const char* s_keyName[] =
{
"None",
"Esc",
"Return",
"Tab",
"Space",
"Backspace",
"Up",
"Down",
"Left",
"Right",
"Insert",
"Delete",
"Home",
"End",
"PageUp",
"PageDown",
"Print",
"Plus",
"Minus",
"LeftBracket",
"RightBracket",
"Semicolon",
"Quote",
"Comma",
"Period",
"Slash",
"Backslash",
"Tilde",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"NumPad0",
"NumPad1",
"NumPad2",
"NumPad3",
"NumPad4",
"NumPad5",
"NumPad6",
"NumPad7",
"NumPad8",
"NumPad9",
"Key0",
"Key1",
"Key2",
"Key3",
"Key4",
"Key5",
"Key6",
"Key7",
"Key8",
"Key9",
"KeyA",
"KeyB",
"KeyC",
"KeyD",
"KeyE",
"KeyF",
"KeyG",
"KeyH",
"KeyI",
"KeyJ",
"KeyK",
"KeyL",
"KeyM",
"KeyN",
"KeyO",
"KeyP",
"KeyQ",
"KeyR",
"KeyS",
"KeyT",
"KeyU",
"KeyV",
"KeyW",
"KeyX",
"KeyY",
"KeyZ",
"GamepadA",
"GamepadB",
"GamepadX",
"GamepadY",
"GamepadThumbL",
"GamepadThumbR",
"GamepadShoulderL",
"GamepadShoulderR",
"GamepadUp",
"GamepadDown",
"GamepadLeft",
"GamepadRight",
"GamepadBack",
"GamepadStart",
"GamepadGuide",
};
BX_STATIC_ASSERT(Key::Count == BX_COUNTOF(s_keyName) );
const char* getName(Key::Enum _key)
{
BX_CHECK(_key < Key::Count, "Invalid key %d.", _key);
return s_keyName[_key];
}
char keyToAscii(Key::Enum _key, uint8_t _modifiers)
{
const bool isAscii = (Key::Key0 <= _key && _key <= Key::KeyZ)
|| (Key::Esc <= _key && _key <= Key::Minus);
if (!isAscii)
{
return '\0';
}
const bool isNumber = (Key::Key0 <= _key && _key <= Key::Key9);
if (isNumber)
{
return '0' + char(_key - Key::Key0);
}
const bool isChar = (Key::KeyA <= _key && _key <= Key::KeyZ);
if (isChar)
{
enum { ShiftMask = Modifier::LeftShift|Modifier::RightShift };
const bool shift = !!(_modifiers&ShiftMask);
return (shift ? 'A' : 'a') + char(_key - Key::KeyA);
}
switch (_key)
{
case Key::Esc: return 0x1b;
case Key::Return: return '\n';
case Key::Tab: return '\t';
case Key::Space: return ' ';
case Key::Backspace: return 0x08;
case Key::Plus: return '+';
case Key::Minus: return '-';
default: break;
}
return '\0';
}
bool setOrToggle(uint32_t& _flags, const char* _name, uint32_t _bit, int _first, int _argc, char const* const* _argv)
{
if (0 == bx::strCmp(_argv[_first], _name) )
{
int arg = _first+1;
if (_argc > arg)
{
_flags &= ~_bit;
bool set = false;
bx::fromString(&set, _argv[arg]);
_flags |= set ? _bit : 0;
}
else
{
_flags ^= _bit;
}
return true;
}
return false;
}
int cmdMouseLock(CmdContext* /*_context*/, void* /*_userData*/, int _argc, char const* const* _argv)
{
if (1 < _argc)
{
bool set = false;
if (2 < _argc)
{
bx::fromString(&set, _argv[1]);
inputSetMouseLock(set);
}
else
{
inputSetMouseLock(!inputIsMouseLocked() );
}
return bx::kExitSuccess;
}
return bx::kExitFailure;
}
int cmdGraphics(CmdContext* /*_context*/, void* /*_userData*/, int _argc, char const* const* _argv)
{
if (_argc > 1)
{
if (setOrToggle(s_reset, "vsync", BGFX_RESET_VSYNC, 1, _argc, _argv)
|| setOrToggle(s_reset, "maxaniso", BGFX_RESET_MAXANISOTROPY, 1, _argc, _argv)
|| setOrToggle(s_reset, "hmd", BGFX_RESET_HMD, 1, _argc, _argv)
|| setOrToggle(s_reset, "hmddbg", BGFX_RESET_HMD_DEBUG, 1, _argc, _argv)
|| setOrToggle(s_reset, "hmdrecenter", BGFX_RESET_HMD_RECENTER, 1, _argc, _argv)
|| setOrToggle(s_reset, "msaa", BGFX_RESET_MSAA_X16, 1, _argc, _argv)
|| setOrToggle(s_reset, "flush", BGFX_RESET_FLUSH_AFTER_RENDER, 1, _argc, _argv)
|| setOrToggle(s_reset, "flip", BGFX_RESET_FLIP_AFTER_RENDER, 1, _argc, _argv)
|| setOrToggle(s_reset, "hidpi", BGFX_RESET_HIDPI, 1, _argc, _argv)
|| setOrToggle(s_reset, "depthclamp", BGFX_RESET_DEPTH_CLAMP, 1, _argc, _argv)
)
{
return bx::kExitSuccess;
}
else if (setOrToggle(s_debug, "stats", BGFX_DEBUG_STATS, 1, _argc, _argv)
|| setOrToggle(s_debug, "ifh", BGFX_DEBUG_IFH, 1, _argc, _argv)
|| setOrToggle(s_debug, "text", BGFX_DEBUG_TEXT, 1, _argc, _argv)
|| setOrToggle(s_debug, "wireframe", BGFX_DEBUG_WIREFRAME, 1, _argc, _argv)
|| setOrToggle(s_debug, "profiler", BGFX_DEBUG_PROFILER, 1, _argc, _argv)
)
{
bgfx::setDebug(s_debug);
return bx::kExitSuccess;
}
else if (0 == bx::strCmp(_argv[1], "screenshot") )
{
bgfx::FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
if (_argc > 2)
{
bgfx::requestScreenShot(fbh, _argv[2]);
}
else
{
time_t tt;
time(&tt);
char filePath[256];
bx::snprintf(filePath, sizeof(filePath), "temp/screenshot-%d", tt);
bgfx::requestScreenShot(fbh, filePath);
}
return bx::kExitSuccess;
}
else if (0 == bx::strCmp(_argv[1], "fullscreen") )
{
WindowHandle window = { 0 };
toggleFullscreen(window);
return bx::kExitSuccess;
}
}
return bx::kExitFailure;
}
int cmdExit(CmdContext* /*_context*/, void* /*_userData*/, int /*_argc*/, char const* const* /*_argv*/)
{
s_exit = true;
return bx::kExitSuccess;
}
static const InputBinding s_bindings[] =
{
{ entry::Key::KeyQ, entry::Modifier::LeftCtrl, 1, NULL, "exit" },
{ entry::Key::KeyQ, entry::Modifier::RightCtrl, 1, NULL, "exit" },
{ entry::Key::KeyF, entry::Modifier::LeftCtrl, 1, NULL, "graphics fullscreen" },
{ entry::Key::KeyF, entry::Modifier::RightCtrl, 1, NULL, "graphics fullscreen" },
{ entry::Key::Return, entry::Modifier::RightAlt, 1, NULL, "graphics fullscreen" },
{ entry::Key::F1, entry::Modifier::None, 1, NULL, "graphics stats" },
{ entry::Key::F1, entry::Modifier::LeftCtrl, 1, NULL, "graphics ifh" },
{ entry::Key::GamepadStart, entry::Modifier::None, 1, NULL, "graphics stats" },
{ entry::Key::F1, entry::Modifier::LeftShift, 1, NULL, "graphics stats 0\ngraphics text 0" },
{ entry::Key::F3, entry::Modifier::None, 1, NULL, "graphics wireframe" },
{ entry::Key::F4, entry::Modifier::None, 1, NULL, "graphics hmd" },
{ entry::Key::F4, entry::Modifier::LeftShift, 1, NULL, "graphics hmdrecenter" },
{ entry::Key::F4, entry::Modifier::LeftCtrl, 1, NULL, "graphics hmddbg" },
{ entry::Key::F6, entry::Modifier::None, 1, NULL, "graphics profiler" },
{ entry::Key::F7, entry::Modifier::None, 1, NULL, "graphics vsync" },
{ entry::Key::F8, entry::Modifier::None, 1, NULL, "graphics msaa" },
{ entry::Key::F9, entry::Modifier::None, 1, NULL, "graphics flush" },
{ entry::Key::F10, entry::Modifier::None, 1, NULL, "graphics hidpi" },
{ entry::Key::Print, entry::Modifier::None, 1, NULL, "graphics screenshot" },
{ entry::Key::KeyP, entry::Modifier::LeftCtrl, 1, NULL, "graphics screenshot" },
INPUT_BINDING_END
};
#if BX_PLATFORM_EMSCRIPTEN
static AppI* s_app;
static void updateApp()
{
s_app->update();
}
#endif // BX_PLATFORM_EMSCRIPTEN
static AppI* s_currentApp = NULL;
static AppI* s_apps = NULL;
static uint32_t s_numApps = 0;
static char s_restartArgs[1024] = { '\0' };
static AppI* getCurrentApp(AppI* _set = NULL)
{
if (NULL != _set)
{
s_currentApp = _set;
}
else if (NULL == s_currentApp)
{
s_currentApp = getFirstApp();
}
return s_currentApp;
}
static AppI* getNextWrap(AppI* _app)
{
AppI* next = _app->getNext();
if (NULL != next)
{
return next;
}
return getFirstApp();
}
int cmdApp(CmdContext* /*_context*/, void* /*_userData*/, int _argc, char const* const* _argv)
{
if (0 == bx::strCmp(_argv[1], "restart") )
{
if (2 == _argc)
{
bx::strCopy(s_restartArgs, BX_COUNTOF(s_restartArgs), getCurrentApp()->getName() );
return bx::kExitSuccess;
}
if (0 == bx::strCmp(_argv[2], "next") )
{
AppI* next = getNextWrap(getCurrentApp() );
bx::strCopy(s_restartArgs, BX_COUNTOF(s_restartArgs), next->getName() );
return bx::kExitSuccess;
}
else if (0 == bx::strCmp(_argv[2], "prev") )
{
AppI* prev = getCurrentApp();
for (AppI* app = getNextWrap(prev); app != getCurrentApp(); app = getNextWrap(app) )
{
prev = app;
}
bx::strCopy(s_restartArgs, BX_COUNTOF(s_restartArgs), prev->getName() );
return bx::kExitSuccess;
}
for (AppI* app = getFirstApp(); NULL != app; app = app->getNext() )
{
if (0 == bx::strCmp(_argv[2], app->getName() ) )
{
bx::strCopy(s_restartArgs, BX_COUNTOF(s_restartArgs), app->getName() );
return bx::kExitSuccess;
}
}
}
return bx::kExitFailure;
}
AppI::AppI(const char* _name, const char* _description)
{
m_name = _name;
m_description = _description;
m_next = s_apps;
s_apps = this;
s_numApps++;
}
AppI::~AppI()
{
for (AppI* prev = NULL, *app = s_apps, *next = app->getNext()
; NULL != app
; prev = app, app = next, next = app->getNext() )
{
if (app == this)
{
if (NULL != prev)
{
prev->m_next = next;
}
else
{
s_apps = next;
}
--s_numApps;
break;
}
}
}
const char* AppI::getName() const
{
return m_name;
}
const char* AppI::getDescription() const
{
return m_description;
}
AppI* AppI::getNext()
{
return m_next;
}
AppI* getFirstApp()
{
return s_apps;
}
uint32_t getNumApps()
{
return s_numApps;
}
int runApp(AppI* _app, int _argc, const char* const* _argv)
{
_app->init(_argc, _argv, s_width, s_height);
bgfx::frame();
WindowHandle defaultWindow = { 0 };
setWindowSize(defaultWindow, s_width, s_height);
#if BX_PLATFORM_EMSCRIPTEN
s_app = _app;
emscripten_set_main_loop(&updateApp, -1, 1);
#else
while (_app->update() )
{
if (0 != bx::strLen(s_restartArgs) )
{
break;
}
}
#endif // BX_PLATFORM_EMSCRIPTEN
return _app->shutdown();
}
static int32_t sortApp(const void* _lhs, const void* _rhs)
{
const AppI* lhs = *(const AppI**)_lhs;
const AppI* rhs = *(const AppI**)_rhs;
return bx::strCmpI(lhs->getName(), rhs->getName() );
}
static void sortApps()
{
if (2 > s_numApps)
{
return;
}
AppI** apps = (AppI**)BX_ALLOC(g_allocator, s_numApps*sizeof(AppI*) );
uint32_t ii = 0;
for (AppI* app = getFirstApp(); NULL != app; app = app->getNext() )
{
apps[ii++] = app;
}
bx::quickSort(apps, s_numApps, sizeof(AppI*), sortApp);
s_apps = apps[0];
for (ii = 1; ii < s_numApps; ++ii)
{
AppI* app = apps[ii-1];
app->m_next = apps[ii];
}
apps[s_numApps-1]->m_next = NULL;
BX_FREE(g_allocator, apps);
}
int main(int _argc, const char* const* _argv)
{
//DBG(BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME);
s_fileReader = BX_NEW(g_allocator, FileReader);
s_fileWriter = BX_NEW(g_allocator, FileWriter);
cmdInit();
cmdAdd("mouselock", cmdMouseLock);
cmdAdd("graphics", cmdGraphics );
cmdAdd("exit", cmdExit );
cmdAdd("app", cmdApp );
inputInit();
inputAddBindings("bindings", s_bindings);
entry::WindowHandle defaultWindow = { 0 };
bx::FilePath fp(_argv[0]);
char title[bx::kMaxFilePath];
bx::strCopy(title, BX_COUNTOF(title), fp.getBaseName() );
entry::setWindowTitle(defaultWindow, title);
setWindowSize(defaultWindow, ENTRY_DEFAULT_WIDTH, ENTRY_DEFAULT_HEIGHT);
sortApps();
const char* find = "";
if (1 < _argc)
{
find = _argv[_argc-1];
}
restart:
AppI* selected = NULL;
for (AppI* app = getFirstApp(); NULL != app; app = app->getNext() )
{
if (NULL == selected
&& bx::strFindI(app->getName(), find) )
{
selected = app;
}
#if 0
DBG("%c %s, %s"
, app == selected ? '>' : ' '
, app->getName()
, app->getDescription()
);
#endif // 0
}
int32_t result = bx::kExitSuccess;
s_restartArgs[0] = '\0';
if (0 == s_numApps)
{
result = ::_main_(_argc, (char**)_argv);
}
else
{
result = runApp(getCurrentApp(selected), _argc, _argv);
}
if (0 != bx::strLen(s_restartArgs) )
{
find = s_restartArgs;
goto restart;
}
inputRemoveBindings("bindings");
inputShutdown();
cmdShutdown();
BX_DELETE(g_allocator, s_fileReader);
s_fileReader = NULL;
BX_DELETE(g_allocator, s_fileWriter);
s_fileWriter = NULL;
return result;
}
WindowState s_window[ENTRY_CONFIG_MAX_WINDOWS];
bool processEvents(uint32_t& _width, uint32_t& _height, uint32_t& _debug, uint32_t& _reset, MouseState* _mouse)
{
s_debug = _debug;
s_reset = _reset;
WindowHandle handle = { UINT16_MAX };
bool mouseLock = inputIsMouseLocked();
const Event* ev;
do
{
struct SE { const Event* m_ev; SE() : m_ev(poll() ) {} ~SE() { if (NULL != m_ev) { release(m_ev); } } } scopeEvent;
ev = scopeEvent.m_ev;
if (NULL != ev)
{
switch (ev->m_type)
{
case Event::Axis:
{
const AxisEvent* axis = static_cast<const AxisEvent*>(ev);
inputSetGamepadAxis(axis->m_gamepad, axis->m_axis, axis->m_value);
}
break;
case Event::Char:
{
const CharEvent* chev = static_cast<const CharEvent*>(ev);
inputChar(chev->m_len, chev->m_char);
}
break;
case Event::Exit:
return true;
case Event::Gamepad:
{
// const GamepadEvent* gev = static_cast<const GamepadEvent*>(ev);
// DBG("gamepad %d, %d", gev->m_gamepad.idx, gev->m_connected);
}
break;
case Event::Mouse:
{
const MouseEvent* mouse = static_cast<const MouseEvent*>(ev);
handle = mouse->m_handle;
inputSetMousePos(mouse->m_mx, mouse->m_my, mouse->m_mz);
if (!mouse->m_move)
{
inputSetMouseButtonState(mouse->m_button, mouse->m_down);
}
if (NULL != _mouse
&& !mouseLock)
{
_mouse->m_mx = mouse->m_mx;
_mouse->m_my = mouse->m_my;
_mouse->m_mz = mouse->m_mz;
if (!mouse->m_move)
{
_mouse->m_buttons[mouse->m_button] = mouse->m_down;
}
_mouse->m_click = mouse->m_down;
}
}
break;
case Event::Key:
{
const KeyEvent* key = static_cast<const KeyEvent*>(ev);
handle = key->m_handle;
inputSetKeyState(key->m_key, key->m_modifiers, key->m_down);
}
break;
case Event::Size:
{
const SizeEvent* size = static_cast<const SizeEvent*>(ev);
WindowState& win = s_window[0];
win.m_handle = size->m_handle;
win.m_width = size->m_width;
win.m_height = size->m_height;
handle = size->m_handle;
_width = size->m_width;
_height = size->m_height;
_reset = !s_reset; // force reset
}
break;
case Event::Window:
break;
case Event::Suspend:
break;
case Event::DropFile:
{
const DropFileEvent* drop = static_cast<const DropFileEvent*>(ev);
DBG("%s", drop->m_filePath.get() );
}
break;
default:
break;
}
}
inputProcess();
} while (NULL != ev);
if (handle.idx == 0
&& _reset != s_reset)
{
_reset = s_reset;
bgfx::reset(_width, _height, _reset);
inputSetMouseResolution(uint16_t(_width), uint16_t(_height) );
}
_debug = s_debug;
s_width = _width;
s_height = _height;
return s_exit;
}
bool processWindowEvents(WindowState& _state, uint32_t& _debug, uint32_t& _reset)
{
s_debug = _debug;
s_reset = _reset;
WindowHandle handle = { UINT16_MAX };
bool mouseLock = inputIsMouseLocked();
bool clearDropFile = true;
const Event* ev;
do
{
struct SE
{
SE(WindowHandle _handle)
: m_ev(poll(_handle) )
{
}
~SE()
{
if (NULL != m_ev)
{
release(m_ev);
}
}
const Event* m_ev;
} scopeEvent(handle);
ev = scopeEvent.m_ev;
if (NULL != ev)
{
handle = ev->m_handle;
WindowState& win = s_window[handle.idx];
switch (ev->m_type)
{
case Event::Axis:
{
const AxisEvent* axis = static_cast<const AxisEvent*>(ev);
inputSetGamepadAxis(axis->m_gamepad, axis->m_axis, axis->m_value);
}
break;
case Event::Char:
{
const CharEvent* chev = static_cast<const CharEvent*>(ev);
win.m_handle = chev->m_handle;
inputChar(chev->m_len, chev->m_char);
}
break;
case Event::Exit:
return true;
case Event::Gamepad:
{
const GamepadEvent* gev = static_cast<const GamepadEvent*>(ev);
DBG("gamepad %d, %d", gev->m_gamepad.idx, gev->m_connected);
}
break;
case Event::Mouse:
{
const MouseEvent* mouse = static_cast<const MouseEvent*>(ev);
win.m_handle = mouse->m_handle;
if (mouse->m_move)
{
inputSetMousePos(mouse->m_mx, mouse->m_my, mouse->m_mz);
}
else
{
inputSetMouseButtonState(mouse->m_button, mouse->m_down);
}
if (!mouseLock)
{
if (mouse->m_move)
{
win.m_mouse.m_mx = mouse->m_mx;
win.m_mouse.m_my = mouse->m_my;
win.m_mouse.m_mz = mouse->m_mz;
}
else
{
win.m_mouse.m_buttons[mouse->m_button] = mouse->m_down;
}
}
}
break;
case Event::Key:
{
const KeyEvent* key = static_cast<const KeyEvent*>(ev);
win.m_handle = key->m_handle;
inputSetKeyState(key->m_key, key->m_modifiers, key->m_down);
}
break;
case Event::Size:
{
const SizeEvent* size = static_cast<const SizeEvent*>(ev);
win.m_handle = size->m_handle;
win.m_width = size->m_width;
win.m_height = size->m_height;
_reset = win.m_handle.idx == 0
? !s_reset
: _reset
; // force reset
}
break;
case Event::Window:
{
const WindowEvent* window = static_cast<const WindowEvent*>(ev);
win.m_handle = window->m_handle;
win.m_nwh = window->m_nwh;
ev = NULL;
}
break;
case Event::Suspend:
break;
case Event::DropFile:
{
const DropFileEvent* drop = static_cast<const DropFileEvent*>(ev);
win.m_dropFile = drop->m_filePath;
clearDropFile = false;
}
break;
default:
break;
}
}
inputProcess();
} while (NULL != ev);
if (isValid(handle) )
{
WindowState& win = s_window[handle.idx];
if (clearDropFile)
{
win.m_dropFile.clear();
}
_state = win;
if (handle.idx == 0)
{
inputSetMouseResolution(uint16_t(win.m_width), uint16_t(win.m_height) );
}
}
if (_reset != s_reset)
{
_reset = s_reset;
bgfx::reset(s_window[0].m_width, s_window[0].m_height, _reset);
inputSetMouseResolution(uint16_t(s_window[0].m_width), uint16_t(s_window[0].m_height) );
}
_debug = s_debug;
return s_exit;
}
bx::FileReaderI* getFileReader()
{
return s_fileReader;
}
bx::FileWriterI* getFileWriter()
{
return s_fileWriter;
}
bx::AllocatorI* getAllocator()
{
if (NULL == g_allocator)
{
g_allocator = getDefaultAllocator();
}
return g_allocator;
}
void* TinyStlAllocator::static_allocate(size_t _bytes)
{
return BX_ALLOC(getAllocator(), _bytes);
}
void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
{
if (NULL != _ptr)
{
BX_FREE(getAllocator(), _ptr);
}
}
} // namespace entry
extern "C" bool entry_process_events(uint32_t* _width, uint32_t* _height, uint32_t* _debug, uint32_t* _reset)
{
return entry::processEvents(*_width, *_height, *_debug, *_reset, NULL);
}
| [
"ztz_mai@163.com"
] | ztz_mai@163.com |
82178ba4873850619fa68a8b79c15e531f3e355c | b0a5d32a808b98b8877b67844b3435203d60fc1d | /interface/RecoTrack.h | ec30fae1df54c983b2e3619f738bb26a68d964ee | [] | no_license | chayanit/analysis-tools | aab5edfccab6751280f31e46213d985417fa2b1c | 8c4c746bf133f20f66e07b43010d62f0eaafeece | refs/heads/develop | 2021-07-11T01:48:49.185025 | 2020-04-30T12:33:12 | 2020-04-30T12:33:12 | 135,294,327 | 1 | 0 | null | 2020-06-09T11:41:59 | 2018-05-29T12:41:51 | C++ | UTF-8 | C++ | false | false | 3,962 | h | #ifndef Analysis_Tools_RecoTrack_h
#define Analysis_Tools_RecoTrack_h 1
// -*- C++ -*-
//
// Package: Analysis/Tools
// Class: RecoTrack
//
/**\class xxx RecoTrack.cc Analysis/Tools/src/RecoTrack.cc
Description: [one line class summary]
Implementation:
[Notes on implementation]
*/
//
// Original Author: Roberval Walsh Bastos Rangel
// Created: Fri, 25 May 2018 16:00:00 GMT
//
//
// system include files
#include <memory>
//
// user include files
#include "Analysis/Tools/interface/Candidate.h"
//
// class declaration
//
namespace analysis {
namespace tools {
/// track quality
enum TrackQuality {
undefQuality = -1,
loose = 0,
tight = 1,
highPurity = 2,
confirmed = 3, // means found by more than one iteration
goodIterative = 4, // meaningless
looseSetWithPV = 5,
highPuritySetWithPV = 6,
discarded = 7, // because a better track found. kept in the collection for reference....
qualitySize = 8
};
class RecoTrack : public Candidate {
public:
/// default constructor
RecoTrack();
/// constructor from 3-momentum information
RecoTrack(const float & px, const float & py, const float & pz, const float & q);
/// destructor
~RecoTrack();
// Gets
float chi2() const;
float ndof() const;
float d0() const;
float dxy() const;
int numberOfLostMuonHits() const;
int numberOfBadMuonHits() const;
int numberOfValidMuonHits() const;
int numberOfValidTrackerHits() const;
int numberOfValidStripTECHits() const;
int numberOfValidStripTIBHits() const;
int numberOfValidStripTIDHits() const;
int numberOfValidStripTOBHits() const;
int muonStationsWithValidHits() const;
int muonStationsWithBadHits() const;
int innermostMuonStationWithValidHits() const;
int outermostMuonStationWithValidHits() const;
bool quality(const TrackQuality & trkqual);
// Sets
void chi2(const float &);
void ndof(const float &);
void d0(const float &);
void dxy(const float &);
void numberOfLostMuonHits(const int &);
void numberOfBadMuonHits(const int &);
void numberOfValidMuonHits(const int &);
void numberOfValidTrackerHits(const int &);
void numberOfValidStripTECHits(const int &);
void numberOfValidStripTIBHits(const int &);
void numberOfValidStripTIDHits(const int &);
void numberOfValidStripTOBHits(const int &);
void muonStationsWithValidHits(const int &);
void muonStationsWithBadHits(const int &);
void innermostMuonStationWithValidHits(const int &);
void outermostMuonStationWithValidHits(const int &);
void quality(const TrackQuality & , const bool &);
protected:
// ----------member data ---------------------------
float chi2_;
float ndof_;
float d0_;
float dxy_;
int nLostMuHits_;
int nBadMuHits_;
int nValMuHits_;
int nValTrackerHits_;
int nValStripTECHits_;
int nValStripTIBHits_;
int nValStripTIDHits_;
int nValStripTOBHits_;
int muStationsWithValHits_;
int muStationsWithBadHits_;
int inMuStationWithValHits_;
int outMuStationWithValHits_;
std::map<TrackQuality,bool> qual_;
private:
// ----------member data ---------------------------
};
}
}
#endif // Analysis_Tools_RecoTrack_h
| [
"roberval.walsh@gmail.com"
] | roberval.walsh@gmail.com |
c4738384dcb450244277a9c5d7649271a7380b81 | 69a99d6c06071bbac21a5a2fb7aeffbd4f4edfe7 | /OrganicGLWinLib/TerrainLightingComputeGearT1.h | d94869c4ffa8779f98e42e4b43323c2d22214c97 | [] | no_license | bigans01/OrganicGLWinLib | 66e9034cee14c0b8e9debd0babc46c9ec36ebbea | 01dafe917155dfe09eb559e889af852dc0b0a442 | refs/heads/master | 2023-07-21T14:37:43.022619 | 2023-07-17T23:13:20 | 2023-07-17T23:13:20 | 156,916,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,174 | h | #pragma once
#ifndef TERRAINLIGHTINGCOMPUTEGEAR_T1
#define TERRAINLIGHTINGCOMPUTEGEAR_T1
#include "Gear.h"
#include "OrganicGLWinUtils.h"
class TerrainLightingComputeGearT1 : public Gear
{
public:
// defined virtual functions (from MachineShader base class)
void initializeMachineShader(int in_width, int in_height, GLuint in_programID, GLFWwindow* in_windowRef, ShaderMachineBase* in_shaderMachineBasePtr);
void render();
void passGLuintValue(std::string in_identifier, GLuint in_gluInt);
void executeGearFunction(std::string in_identifier);
void printData();
void interpretMessage(Message in_message);
private:
//GLuint terrainBufferID = 0; // the primary terrain buffer
//GLuint terrainSwapID = 0; // the swap terrain buffer;
// shader uniforms
GLuint mvpHandle;
GLuint textureUniform;
GLuint worldPosUniform;
GLuint atlasWidthUniform;
GLuint atlasTileWidthUniform;
GLuint globalAmbienceMultiplierUniform;
// shader uniform values
//glm::mat4 mv;
// deferred specific functions
GLuint deferredFBO = 0;
GLuint terrainVaoID = 0;
// terrain vao set up
void setupTerrainVAO();
void writeToGBuffers();
void setMatrices();
};
#endif | [
"bigans01@gmail.com"
] | bigans01@gmail.com |
d8b148ac46c014139a3e31ab0ff9682e7599e61b | 8ae13c7d1ff0b89a4a3654bb90f36d122ca234e5 | /FINISHED/C++/Unit01/printStar.cpp | eb82df6a7be111decce1f47c318dc4bb5558ea5b | [] | no_license | ssh352/AllTheSourceCodes | a6f393bcb8bfa26215a0359d14f5f4e3176b9536 | e6862c73add301b9a2dccc8ece1cf9c758ead850 | refs/heads/master | 2020-03-30T13:07:11.424829 | 2015-12-15T01:37:06 | 2015-12-15T01:37:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 620 | cpp | /*
+----------------------------------------------------------
*
* @authors: 风之凌殇 <1054073896@qq.com>
* @FILE NAME: printStar.cpp
* @version: v1.0
* @Time: 2015-08-08 20:15:25
* @Description:
*
+----------------------------------------------------------
*/
#include <iostream>
using namespace std;
int main() {
freopen("test.in", "r", stdin);
freopen("test.out", "w", stdout);
int count;
cin >> count;
while (count--) {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
cout << "*";
}
cout << endl;
}
}
printf("\n");
system("pause");
return 0;
}
| [
"1054073896@qq.com"
] | 1054073896@qq.com |
dc5617d76b33b1b5c073669ff42cc92de0577e15 | 9f25ac38773b5ccdc0247c9d43948d50e60ab97a | /chrome/browser/ui/ash/holding_space/holding_space_downloads_delegate.h | b23ea756a7005368675af28480754a98159339c4 | [
"BSD-3-Clause"
] | permissive | liang0/chromium | e206553170eab7b4ac643ef7edc8cc57d4c74342 | 7a028876adcc46c7f7079f894a810ea1f511c3a7 | refs/heads/main | 2023-03-25T05:49:21.688462 | 2021-04-28T06:07:52 | 2021-04-28T06:07:52 | 362,370,889 | 1 | 0 | BSD-3-Clause | 2021-04-28T07:04:42 | 2021-04-28T07:04:41 | null | UTF-8 | C++ | false | false | 3,112 | h | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_ASH_HOLDING_SPACE_HOLDING_SPACE_DOWNLOADS_DELEGATE_H_
#define CHROME_BROWSER_UI_ASH_HOLDING_SPACE_HOLDING_SPACE_DOWNLOADS_DELEGATE_H_
#include "base/callback.h"
#include "base/scoped_observer.h"
#include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service_delegate.h"
#include "components/download/public/common/download_item.h"
#include "content/public/browser/download_manager.h"
namespace base {
class FilePath;
} // namespace base
namespace ash {
// A delegate of `HoldingSpaceKeyedService` tasked with monitoring the status of
// of downloads and notifying a callback on download completion.
class HoldingSpaceDownloadsDelegate : public HoldingSpaceKeyedServiceDelegate,
public content::DownloadManager::Observer,
public download::DownloadItem::Observer {
public:
// Callback to be invoked when a download is completed. Note that this
// callback will only be invoked after holding space persistence is restored.
using ItemDownloadedCallback =
base::RepeatingCallback<void(const base::FilePath&)>;
HoldingSpaceDownloadsDelegate(
Profile* profile,
HoldingSpaceModel* model,
ItemDownloadedCallback item_downloaded_callback);
HoldingSpaceDownloadsDelegate(const HoldingSpaceDownloadsDelegate&) = delete;
HoldingSpaceDownloadsDelegate& operator=(
const HoldingSpaceDownloadsDelegate&) = delete;
~HoldingSpaceDownloadsDelegate() override;
// Sets the `content::DownloadManager` to be used for testing.
// NOTE: This method must be called prior to delegate initialization.
static void SetDownloadManagerForTesting(
content::DownloadManager* download_manager);
private:
// HoldingSpaceKeyedServiceDelegate:
void Init() override;
void OnPersistenceRestored() override;
// content::DownloadManager::Observer:
void OnManagerInitialized() override;
void ManagerGoingDown(content::DownloadManager* manager) override;
void OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) override;
// download::DownloadItem::Observer:
void OnDownloadUpdated(download::DownloadItem* item) override;
// Invoked when the specified `file_path` has completed downloading.
void OnDownloadCompleted(const base::FilePath& file_path);
// Removes all observers.
void RemoveObservers();
// Callback to invoke when a download is completed.
ItemDownloadedCallback item_downloaded_callback_;
ScopedObserver<content::DownloadManager, content::DownloadManager::Observer>
download_manager_observer_{this};
ScopedObserver<download::DownloadItem, download::DownloadItem::Observer>
download_item_observer_{this};
base::WeakPtrFactory<HoldingSpaceDownloadsDelegate> weak_factory_{this};
};
} // namespace ash
#endif // CHROME_BROWSER_UI_ASH_HOLDING_SPACE_HOLDING_SPACE_DOWNLOADS_DELEGATE_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
d6dd59df4f72e35d3146945125a70f488fe6b834 | b03d75374042769b292c3b2b784110deba45c90d | /Chapter12/4/stack.h | 984c81bf4aba0ba26abd5021522c1ff2b33696ed | [] | no_license | blacktomato/Cpp-Primer-Plus | e2ce08e9d8fc8d8cb2d42bdb42d9b45cfd446df7 | 92bb8681fb2ff6d1e13d8025afe6568da37619e2 | refs/heads/master | 2022-04-24T01:02:35.360514 | 2020-04-19T16:57:54 | 2020-04-19T16:57:54 | 256,462,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 950 | h | #ifndef STACK_H
#define STACK_H
// stack.h -- class declaration for the stack ADT
typedef unsigned long Item;
class Stack{
public:
Stack(); // creates stack with n elements
Stack(int n = MAX); // creates stack with n elements
Stack(const Stack &st);
~Stack();
bool isempty() const;
bool isfull() const;
// push() returns false if stack already is full, true otherwise
bool push(const Item &item); // add item to stack
// pop() returns false if stack already is empty, true otherwise
bool pop(Item &item); // pop top into item
Stack &operator=(const Stack &st);
void show();
private:
enum { MAX = 10 }; // constant specific to class
Item *pitems; // holds stack items
int size; // number of elements in stack
int top; // index for top stack item
};
#endif | [
"b02901001@ntu.edu.tw"
] | b02901001@ntu.edu.tw |
21e4f4febaa9e2c66011757e6f4ce9d4e5c40bfc | 726e2ffb23caadf9b144499ad04b3f8df421c1cc | /include/xml/Node.hpp | 3964d81485488950795543be0d22b06b1adf9e81 | [
"MIT"
] | permissive | spacechase0/XML-Parser | 93e7f5d2d8110f6e165a60660edd7c896825b464 | 0a6c63a27c174bbef1c11cc72d5de960c78f5c56 | refs/heads/master | 2016-09-06T19:47:50.147494 | 2015-03-07T16:43:25 | 2015-03-07T16:43:25 | 2,389,165 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,010 | hpp | #ifndef XML_NODE_HPP
#define XML_NODE_HPP
#include <xml/Attribute.hpp>
#include <memory>
#include <string>
#include <vector>
namespace xml
{
class Node
{
public:
// Typedefs
typedef std::shared_ptr< Node > NodePointer;
typedef std::vector< Attribute > AttributeContainer;
typedef std::vector< NodePointer > NodeContainer;
// Constructors and assignment operator
Node();
Node( const Node& other );
Node( const std::string& theName, bool theSelfClosing = false );
Node( const std::string& theName, const std::vector< Attribute >& theAttributes, bool isSelfClosing = false );
Node( const std::string& theName, const std::vector< Attribute >& theAttributes, const NodeContainer& theChildren );
Node& operator = ( const Node& other );
void setSelfClosing( bool theSelfClosing );
bool isSelfClosing() const;
void setCharacterData( bool theCharData );
static bool isValidCharacterData( const std::string& theText );
bool isCharacterData() const;
void setTextNode( bool theTextNode );
bool isTextNode() const;
void setText( const std::string theText );
std::string getText() const;
void setName( const std::string& theName );
static bool isNameValid( const std::string& theName );
std::string getName() const;
void setAttributes( const std::vector< Attribute >& theAttributes );
const std::vector< Attribute >& getAttributes() const;
void setChildren( const std::vector< std::shared_ptr< Node > >& theChildren );
const std::vector< std::shared_ptr< Node > >& getChildren() const;
std::string getString() const;
private:
enum Flag
{
None = 0,
SelfClosing = 1,
CharacterData = 2,
TextNode = 3
};
std::string name;
std::vector< Attribute > attributes;
std::vector< std::shared_ptr< Node > > children;
Flag flag;
std::string text;
static Attribute dummyAttribute;
static Node dummyNode;
};
}
#endif // XML_NODE_HPP
| [
"chasew@silkweaver.com"
] | chasew@silkweaver.com |
aa505b3dca461f3363dd3ef4215a95cf210d0736 | b3d780ddae3b5455b85a1f8e292d024383067cf6 | /projekat/weapons.hpp | af892d784196ca803f5230b102c660d6ccdd7ae1 | [] | no_license | fdsmudj/Projekat | 4f08a58f2ae74b2f03789d788e57a4d8d0957233 | 9adb90e0e63b517aa57dd8ac40c18c3c11e54fe2 | refs/heads/master | 2022-09-22T04:25:47.323657 | 2020-05-25T12:19:37 | 2020-05-25T12:19:37 | 257,953,513 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | hpp | #ifndef WEAPONS_HPP_INCLUDED
#define WEAPONS_HPP_INCLUDED
enum clas {heavy=1, light=2, energy=3, shells=4};
class Weapons
{
protected:
clas c;
int damage;
bool reload;
int numOfBullets;
double reloadTime;
public:
Weapons(clas c1, int damage1, bool reload1, int numOfBullets1, double reloadTime1)
{
c=c1;
damage=damage1;
reload=reload1;
numOfBullets=numOfBullets1;
reloadTime=reloadTime1;
}
virtual void ispisPolja()
{
cout<<"Ispis polja"<<endl<<endl;
cout<<c<<", "<<damage<<", "<<reload<<", "<<numOfBullets<<", "<<reloadTime;
}
};
#endif // WEAPONS_HPP_INCLUDED
| [
"63963638+fdsmudj@users.noreply.github.com"
] | 63963638+fdsmudj@users.noreply.github.com |
80aa2563b8a1f946597990896174db06ea763d8f | cf0ca99d2db32d391adb332862f38cb86c1e4bf0 | /subsetsum/subsetsum.cpp | 580f4ddf561bbc38bf8e5022ac7dc59d6d05b07e | [] | no_license | Ankurrana/Codechef | b213b4355f3c4f2bfa475b65a98c7a03e2e88664 | 088e4a23f00be0a368c4928c45bd8fb507188b04 | refs/heads/master | 2020-04-26T23:29:34.212998 | 2015-01-14T14:51:38 | 2015-01-14T14:51:38 | 19,064,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | cpp | #include "bits/stdc++.h"
#include "string"
using namespace std;
#define iterate(n) for(i=0;i<n;i++)
#define Diterate(i,s,e) for(lld (i) = s ; (i)<=e ; i++)
#define getw getchar_unlocked
#define get(a) geta(&a)
#define p(a) printf("%lld\n",(lld)(a))
#define d(str,a) cout << str << " = " << a << endl
#define dv(str,a,n) iterate(n) { cout << str << "[" << i << "] = " << a[i] << endl; }
template < typename T >
inline void geta(T *a){
T n=0,s=1;
char p=getw();
if(p=='-') s=-1;
while((p<'0'||p>'9')&&p!=EOF&&p!='-') p=getw();
if(p=='-') s=-1,p=getw();
while(p>='0'&&p<='9') { n = (n<< 3) + (n<< 1) + (p - '0'); p=getw(); }
*a = n*s;
}
#define MAXINDEX 10
#define MAX_SUM 100
int dp[100][1000]; // first index then the sum
int a[100];
int main(){
int n = 4,i,sum,k=0;
a[0] = 2;
a[1] = 3;
a[2] = 7;
a[3] = 8;
bool dp[100][1000] = {false};
iterate(n) dp[i][0] = true;
dp[0][a[0]] = true;
iterate(n) k += a[i];
for(i=1;i<n;i++){
for(sum = 1;sum <= k;sum++){
dp[i][sum] = dp[i-1][sum];
if(sum>=a[i])
dp[i][sum] = max(dp[i][sum], dp[i-1][sum-a[i]]);
}
}
cout << dp[3][6];
return 0;
}
| [
"ankurofficial@hotmail.com"
] | ankurofficial@hotmail.com |
ce4c65af0d412b292a7993885dcd4872886c838b | 04e09e2a3956eef0b18abdf9c45c180cdebc2500 | /Classes/Native/mscorlib_System_Comparison_1_gen4092414351.h | ebb8cdbd60c215357ac6c174913587dada5b7005 | [] | no_license | alexeymax/BetPalzIOSPlugin | fbab11036598d151bd57fd83bf171cb4f77b6032 | 6f1c544a8dd06e6b6ce6d1c5346f73924158bf89 | refs/heads/master | 2021-01-11T22:59:38.673084 | 2017-01-10T12:44:05 | 2017-01-10T12:44:25 | 78,532,028 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// BetpalzUnity.Core.Services.Facebook.Model.FacebookFriend
struct FacebookFriend_t2830675500;
// System.IAsyncResult
struct IAsyncResult_t1999651008;
// System.AsyncCallback
struct AsyncCallback_t163412349;
// System.Object
struct Il2CppObject;
#include "mscorlib_System_MulticastDelegate3201952435.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Comparison`1<BetpalzUnity.Core.Services.Facebook.Model.FacebookFriend>
struct Comparison_1_t4092414351 : public MulticastDelegate_t3201952435
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"mkulik@briskmobile.com"
] | mkulik@briskmobile.com |
9b8558a743f615bee8939c552d9b1cf77f7e294b | b5fa65fb13af238c1fb5cf504b94bb68890f2f28 | /Game.cpp | 253b35d03ca32144875a50930822d72ef2695568 | [] | no_license | DomWilliams0/snake-sfml | eb02ea4671a60829e149ca4609efe60b1bd12b7e | b7d9a15a01e00bfa7e6f93b60f9545ac6c4f28f2 | refs/heads/master | 2020-04-18T09:42:20.414508 | 2016-08-29T17:16:48 | 2016-08-29T17:16:48 | 66,863,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,094 | cpp | #include <SFML/Graphics.hpp>
#include <iostream>
#include <memory>
#include <stack>
#include "Game.hpp"
#include "World.hpp"
#include "Snake.hpp"
#include "Spawner.hpp"
#include "Logger.hpp"
#include "screens/Screen.hpp"
#include "screens/GameScreen.hpp"
#include "screens/MenuScreen.hpp"
#include "screens/PauseScreen.hpp"
#include "screens/GameOverScreen.hpp"
using sf::Vector2f;
using sf::Color;
using sf::RenderWindow;
Game::Game(const Vector2f &screenSize) :
window(sf::VideoMode(screenSize.x, screenSize.y), "Snake", sf::Style::Default, sf::ContextSettings(0, 0, 4)), paused(false), backgroundColor(sf::Color(20, 20, 22))
{
// set frame rate
window.setFramerateLimit(600);
// create logger
Logger::createLogger(std::cout, Logger::Level::DEBUG);
// load fonts
if (mainFont.loadFromFile("res/font.ttf"))
Logger::logInfo("Font loaded successfully");
// load menu
switchScreen(Screen::MENU);
}
Game::~Game()
{
// destruct all screenss
/*for (int i = 0; i < screens.size(); i++)
switchScreen(Screen::NONE);*/
}
void Game::run()
{
sf::Clock clock;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
else
current->handleInput(event);
}
float delta(clock.restart().asSeconds());
if (!paused)
current->tick(delta);
window.clear();
current->render(window);
// todo: temporary
//sf::Vertex halfLine[] = { sf::Vertex(sf::Vector2f(getWindowSize().x / 2, 0)), sf::Vertex(sf::Vector2f(getWindowSize().x / 2, getWindowSize().y)) };
//window.draw(halfLine, 2, sf::Lines);
// todo: temporary
window.display();
}
}
void Game::switchScreen(Screen::ScreenType newScreenType)
{
// destruct current
if (newScreenType == Screen::ScreenType::NONE)
{
delete current;
screens.pop();
current = screens.top();
}
// push new screen onto stack
else
{
Screen *newScreen(createFromScreenType(newScreenType));
if (!newScreen) return;
bool shouldDestruct = (current && current->type != Screen::GAME && newScreenType != Screen::PAUSE);
if (shouldDestruct)
{
screens.pop();
delete current;
}
current = newScreen;
screens.push(newScreen);
}
window.setMouseCursorVisible(current->showMouse);
}
Screen* Game::createFromScreenType(Screen::ScreenType type)
{
switch (type)
{
case Screen::GAME: return new GameScreen(this);
break;
case Screen::MENU: return new MenuScreen(this);
break;
case Screen::PAUSE: return new PauseScreen(this);
break;
case Screen::OPTIONS: Logger::logInfo("No options for now!");
return NULL;
break;
case Screen::GAMEOVER: return new GameOverScreen(this, current);
break;
}
}
void Game::end()
{
window.close();
Logger::logDebug("Game ended through game.end()");
}
int main()
{
std::srand(time(NULL));
// todo random rule changes, like avoid yellows, get reds, you can now go through walls etc
Game game(Vector2f(640, 640));
game.run();
}
| [
"me@domwillia.ms"
] | me@domwillia.ms |
347f22a8438caf2587cee09aa64d00a5470f44fb | b15f60413b8fd808994ef68eba92dd1151a7124d | /Template/TextureManager.cpp | 6c1ca3b26f5abca2524c51b77b2cdc7c2c1fc257 | [] | no_license | woonhak-kong/GAME3001-M2021-Assignment4 | 050b391175958b3cb3d1fabfab8d36a15530f89a | 97b3263e1a87ebe21ec6347f1a8abd2ce751360d | refs/heads/master | 2023-07-09T12:29:56.888668 | 2021-08-12T12:10:16 | 2021-08-12T12:10:16 | 394,242,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,615 | cpp | #include "TextureManager.h"
#include <SDL_image.h>
#include "Game.h"
#include <utility>
#include <fstream>
#include <sstream>
#include "Frame.h"
#include <iterator>
TextureManager::TextureManager()
= default;
TextureManager::~TextureManager()
= default;
inline bool TextureManager::m_textureExists(const std::string & id)
{
return m_textureMap.find(id) != m_textureMap.end();
}
bool TextureManager::m_spriteSheetExists(const std::string & sprite_sheet_name)
{
return m_spriteSheetMap.find(sprite_sheet_name) != m_spriteSheetMap.end();
}
bool TextureManager::m_animationExists(const std::string animationId, const std::string& id)
{
if (m_pAnimations.find(animationId) != m_pAnimations.end())
{
return m_pAnimations.find(animationId)->second.find(id) != m_pAnimations.find(animationId)->second.end();
}
return false;
}
bool TextureManager::load(const std::string & file_name, const std::string & id)
{
if (m_textureExists(id))
{
return true;
}
auto surface = IMG_Load(file_name.c_str());
std::cout << SDL_GetError();
if (surface == nullptr)
{
return false;
}
auto pTexture = SDL_CreateTextureFromSurface(m_pRenderer, surface);
SDL_FreeSurface(surface);
// everything went ok, add the texture to our list
if (pTexture != nullptr)
{
m_textureMap[id] = pTexture;
return true;
}
return false;
}
bool TextureManager::loadSpriteSheet(
const std::string & data_file_name,
const std::string & texture_file_name,
const std::string & sprite_sheet_name)
{
std::string inputLine;
std::fstream dataFile; // create file stream object
std::string delimeter = " ";
// open the text data file
dataFile.open(data_file_name, std::ios::in);
// create a new spritesheet object and allocate memory for it
auto spriteSheet = new SpriteSheet(sprite_sheet_name);
// if the file successfully opened
if (dataFile)
{
// read one line at a time
while (std::getline(dataFile, inputLine))
{
Frame frame;
size_t linePosition = 0;
std::vector<std::string> tokens;
for (auto i = 0; i < 5; ++i)
{
linePosition = inputLine.find(delimeter);
tokens.push_back(inputLine.substr(0, linePosition));
inputLine.erase(0, linePosition + 1);
}
frame.name = tokens[0];
frame.x = std::stoi(tokens[1]);
frame.y = std::stoi(tokens[2]);
frame.w = std::stoi(tokens[3]);
frame.h = std::stoi(tokens[4]);
// add the new frame to the spritesheet
spriteSheet->addFrame(frame);
}
}
else
{
std::cout << "error opening file" << std::endl;
return false;
}
dataFile.close();
// load the sprite texture and store it in the textureMap
load(texture_file_name, sprite_sheet_name);
// get a pointer to the Texture and store it in the new spritesheet object
spriteSheet->setTexture(getTexture(sprite_sheet_name));
// store the new spritesheet in the spriteSheetMap
m_spriteSheetMap[sprite_sheet_name] = spriteSheet;
// cleanup
spriteSheet = nullptr;
return true;
}
void TextureManager::draw(const std::string& id, const int x, const int y, const double angle, const int alpha, const bool centered, const SDL_RendererFlip flip)
{
SDL_Rect srcRect;
SDL_Rect destRect;
srcRect.x = 0;
srcRect.y = 0;
int textureWidth, textureHeight;
SDL_QueryTexture(m_textureMap[id], nullptr, nullptr, &textureWidth, &textureHeight);
srcRect.w = destRect.w = textureWidth;
srcRect.h = destRect.h = textureHeight;
if (centered) {
const int xOffset = textureWidth * 0.5;
const int yOffset = textureHeight * 0.5;
destRect.x = x - xOffset;
destRect.y = y - yOffset;
}
else {
destRect.x = x;
destRect.y = y;
}
//destRect.x = x;
//destRect.y = y;
SDL_SetTextureAlphaMod(m_textureMap[id], alpha);
SDL_RenderCopyEx(m_pRenderer, m_textureMap[id], &srcRect, &destRect, angle, nullptr, flip);
}
void TextureManager::draw(const std::string& id, int x, int y, int destW, int destH, double angle, int alpha, const bool centered, SDL_RendererFlip flip)
{
SDL_Rect srcRect;
SDL_Rect destRect;
srcRect.x = 0;
srcRect.y = 0;
int textureWidth, textureHeight;
SDL_QueryTexture(m_textureMap[id], nullptr, nullptr, &textureWidth, &textureHeight);
srcRect.w = textureWidth;
srcRect.h = textureHeight;
destRect.w = destW;
destRect.h = destH;
if (centered) {
const int xOffset = destRect.w * 0.5;
const int yOffset = destRect.h * 0.5;
destRect.x = x - xOffset;
destRect.y = y - yOffset;
}
else {
destRect.x = x;
destRect.y = y;
}
//destRect.x = x;
//destRect.y = y;
SDL_SetTextureAlphaMod(m_textureMap[id], alpha);
SDL_RenderCopyEx(m_pRenderer, m_textureMap[id], &srcRect, &destRect, angle, nullptr, flip);
}
void TextureManager::drawFrame(const std::string & id, const int x, const int y, const int frame_width,
const int frame_height, int& current_row,
int& current_frame, int frame_number, int row_number,
float speed_factor, const double angle,
const int alpha, const SDL_RendererFlip flip)
{
animateFrames(frame_width, frame_height, frame_number, row_number, speed_factor, current_frame, current_row);
SDL_Rect srcRect;
SDL_Rect destRect;
srcRect.x = 0;
srcRect.y = 0;
// frame_height size
const auto textureWidth = frame_width;
const auto textureHeight = frame_height;
// starting point of the where we are looking
srcRect.x = textureWidth * current_frame;
srcRect.y = textureHeight * current_row;
srcRect.w = textureWidth;
srcRect.h = textureHeight;
destRect.w = textureWidth;
destRect.h = textureHeight;
//if (centered) {
// const int xOffset = textureWidth * 0.5;
// const int yOffset = textureHeight * 0.5;
// destRect.x = x - xOffset;
// destRect.y = y - yOffset;
//}
//else {
// destRect.x = x;
// destRect.y = y;
//}
destRect.x = x;
destRect.y = y;
SDL_SetTextureAlphaMod(m_textureMap[id], alpha);
SDL_RenderCopyEx(m_pRenderer, m_textureMap[id], &srcRect, &destRect, angle, nullptr, flip);
}
void TextureManager::animateFrames(int frame_width, int frame_height, const int frame_number, const int row_number, const float speed_factor, int& current_frame, int& current_row)
{
const auto totalFrames = frame_number * row_number;
const int animationRate = round(totalFrames / 2 / speed_factor);
if (frame_number > 1)
{
if (TheGame::Instance().getFrames() % animationRate == 0)
{
current_frame++;
if (current_frame > frame_number - 1)
{
current_frame = 0;
current_row++;
}
if (current_row > row_number - 1)
{
current_row = 0;
}
}
}
}
void TextureManager::playAnimation(
const std::string & sprite_sheet_name, Animation & animation,
int x, int y, float speed_factor,
double angle, int alpha, SDL_RendererFlip flip)
{
const auto totalFrames = animation.frames.size();
const int animationRate = round(totalFrames / 2 / speed_factor);
if (totalFrames > 1)
{
if (TheGame::Instance().getFrames() % animationRate == 0)
{
animation.current_frame++;
if (animation.current_frame > totalFrames - 1)
{
animation.current_frame = 0;
}
}
}
SDL_Rect srcRect;
SDL_Rect destRect;
srcRect.x = 0;
srcRect.y = 0;
// frame_height size
const auto textureWidth = animation.frames[animation.current_frame].w;
const auto textureHeight = animation.frames[animation.current_frame].h;
// starting point of the where we are looking
srcRect.x = animation.frames[animation.current_frame].x;
srcRect.y = animation.frames[animation.current_frame].y;
srcRect.w = animation.frames[animation.current_frame].w;
srcRect.h = animation.frames[animation.current_frame].h;
destRect.w = textureWidth;
destRect.h = textureHeight;
//if (centered) {
// const int xOffset = textureWidth * 0.5;
// const int yOffset = textureHeight * 0.5;
// destRect.x = x - xOffset;
// destRect.y = y - yOffset;
//}
//else {
// destRect.x = x;
// destRect.y = y;
//}
destRect.x = x;
destRect.y = y;
SDL_SetTextureAlphaMod(m_textureMap[sprite_sheet_name], alpha);
SDL_RenderCopyEx(m_pRenderer, m_textureMap[sprite_sheet_name], &srcRect, &destRect, angle, nullptr, flip);
}
void TextureManager::playAnimation(Animation& animation, int x, int y, int destW, int destH, float speed_factor, double angle, int alpha,
SDL_RendererFlip flip, bool loop /* = true */, std::function<void(CallbackType)> callback /* = nullptr */, int callbackOrder /* = -1*/, bool center /*= false */)
{
const int totalFrames = animation.frames.size();
const int animationRate = round(totalFrames / 2 / speed_factor);
if (totalFrames > 1)
{
if (TheGame::Instance().getFrames() % animationRate == 0)
{
animation.current_frame++;
if(animation.current_frame == totalFrames - 1)
{
if (callback != nullptr)
{
callback(CallbackType::ANIMATION_END);
}
}
if (animation.current_frame > totalFrames - 1)
{
if (loop)
{
animation.current_frame = 0;
}
else
{
animation.current_frame = totalFrames - 1;
}
}
if ( callbackOrder > totalFrames - 1)
{
std::cout << "Error - callbackOrder is lager than totalFrames!!!" << std::endl;
}
else if (callback != nullptr && callbackOrder == animation.current_frame)
{
callback(CallbackType::ATTACK_BOX);
}
}
}
int textureWidth, textureHeight;
SDL_Rect srcRect;
SDL_Rect destRect;
//destRect.x = x;
//destRect.y = y;
// frame_height size
//const auto textureWidth = animation.frames[animation.current_frame].w;
//const auto textureHeight = animation.frames[animation.current_frame].h;
// starting point of the where we are looking
srcRect.x = animation.frames[animation.current_frame].x;
srcRect.y = animation.frames[animation.current_frame].y;
srcRect.w = animation.frames[animation.current_frame].w;
srcRect.h = animation.frames[animation.current_frame].h;
if (center) {
const int xOffset = destW * 0.5;
const int yOffset = destH * 0.5;
destRect.x = x - xOffset;
destRect.y = y - yOffset;
}
else {
destRect.x = x;
destRect.y = y;
}
destRect.w = destW;
destRect.h = destH;
SDL_SetTextureAlphaMod(m_textureMap[animation.frames[animation.current_frame].name], alpha);
SDL_RenderCopyEx(m_pRenderer, m_textureMap[animation.frames[animation.current_frame].name], &srcRect, &destRect, angle, nullptr, flip);
}
void TextureManager::drawText(const std::string & id, const int x, const int y, const double angle, const int alpha, bool centered, const SDL_RendererFlip flip)
{
SDL_Rect srcRect;
SDL_Rect destRect;
srcRect.x = 0;
srcRect.y = 0;
int textureWidth, textureHeight;
SDL_QueryTexture(m_textureMap[id], nullptr, nullptr, &textureWidth, &textureHeight);
srcRect.w = destRect.w = textureWidth;
srcRect.h = destRect.h = textureHeight;
if (centered) {
const int xOffset = textureWidth * 0.5;
const int yOffset = textureHeight * 0.5;
destRect.x = x - xOffset;
destRect.y = y - yOffset;
}
else {
destRect.x = x;
destRect.y = y;
}
//destRect.x = x;
//destRect.y = y;
SDL_SetTextureAlphaMod(m_textureMap[id], alpha);
SDL_RenderCopyEx(m_pRenderer, m_textureMap[id], &srcRect, &destRect, angle, nullptr, flip);
}
void TextureManager::drawTile(const std::string& id, int margin, int spacing, int x, int y, int width, int height,
int currentRow, int currentFrame)
{
SDL_Rect srcRect;
SDL_Rect destRect;
srcRect.x = margin + (spacing + width) * currentFrame;
srcRect.y = margin + (spacing + height) * currentRow;
srcRect.w = destRect.w = width;
srcRect.h = destRect.h = height;
destRect.x = x;
destRect.y = y;
SDL_RenderCopyEx(m_pRenderer, m_textureMap[id], &srcRect, &destRect, 0, nullptr, SDL_FLIP_NONE);
}
void TextureManager::drawRect(int x, int y, int w, int h, const SDL_Color color)
{
SDL_Rect rect = { x, y, w, h };
SDL_SetRenderDrawColor(m_pRenderer, color.r, color.g, color.b, color.a);
SDL_RenderDrawRect(m_pRenderer, &rect);
SDL_SetRenderDrawColor(m_pRenderer, 255,255,255,255);
}
void TextureManager::drawFillRect(int x, int y, int w, int h, const SDL_Color color)
{
SDL_Rect rect = { x, y, w, h };
SDL_SetRenderDrawColor(m_pRenderer, color.r, color.g, color.b, color.a);
SDL_RenderFillRect(m_pRenderer, &rect);
SDL_SetRenderDrawColor(m_pRenderer, 255, 255, 255, 255);
}
glm::vec2 TextureManager::getTextureSize(const std::string & id)
{
int width, height;
SDL_QueryTexture(m_textureMap[id], nullptr, nullptr, &width, &height);
glm::vec2 size;
size.x = width;
size.y = height;
return size;
}
void TextureManager::setAlpha(const std::string & id, const Uint8 new_alpha)
{
auto pTexture = m_textureMap[id];
SDL_SetTextureAlphaMod(pTexture, new_alpha);
pTexture = nullptr;
}
void TextureManager::setAnimation(std::string id, const Animation& animation)
{
if (!m_animationExists(id, animation.name))
{
m_pAnimations[id][animation.name] = animation;
}
}
std::unordered_map<std::string, Animation> TextureManager::getAnimation(const std::string& id)
{
return m_pAnimations[id];
}
void TextureManager::setRenderer(SDL_Renderer* renderer)
{
m_pRenderer = renderer;
}
SDL_Renderer* TextureManager::getRenderer() const
{
return m_pRenderer;
}
void TextureManager::setColour(const std::string & id, const Uint8 red, const Uint8 green, const Uint8 blue)
{
auto pTexture = m_textureMap[id];
SDL_SetTextureColorMod(pTexture, red, green, blue);
pTexture = nullptr;
}
bool TextureManager::addTexture(const std::string & id, SDL_Texture* texture)
{
if (m_textureExists(id))
{
return true;
}
m_textureMap[id] = texture;
return true;
}
SDL_Texture* TextureManager::getTexture(const std::string & id)
{
return m_textureMap[id];
}
void TextureManager::removeTexture(const std::string & id)
{
SDL_DestroyTexture(m_textureMap[id]);
m_textureMap[id] = nullptr;
m_textureMap.erase(id);
}
int TextureManager::getTextureMapSize() const
{
return m_textureMap.size();
}
void TextureManager::clean()
{
for (auto iter = m_textureMap.begin(); iter != m_textureMap.end(); iter++)
{
SDL_DestroyTexture(iter->second);
iter->second = nullptr;
}
m_textureMap.clear();
std::cout << "TextureMap Cleared, TextureMap Size: " << m_textureMap.size() << std::endl;
m_spriteSheetMap.clear();
std::cout << "Existing SpriteSheets Cleared" << std::endl;
}
void TextureManager::displayTextureMap()
{
std::cout << "------------ Displaying Texture Map -----------" << std::endl;
std::cout << "Texture Map size: " << m_textureMap.size() << std::endl;
auto it = m_textureMap.begin();
while (it != m_textureMap.end())
{
std::cout << it->first << std::endl;
++it;
}
}
SpriteSheet* TextureManager::getSpriteSheet(const std::string & name)
{
return m_spriteSheetMap[name];
}
| [
"woonhak.kong@georgebrown.ca"
] | woonhak.kong@georgebrown.ca |
c4059f1932e9bf24ccf9afca46509da1975b75c8 | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /contest/1542571619.cpp | b1e426d845546aa2f4b6b23fa5c2564c41885fba | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 433 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int h,m,s,t1,t2,z;
cin>>h>>m>>s>>t1>>t2;
h=h*60*60+m*60 + s;
m=(m*60+s)*12;
s=s*12*60;
t1=t1*60*60;
t2=t2*60*60;
if (t1>t2)
{
z=t1;
t1=t2;
t2=z;
}
if (((h<=t2 && h>=t1) && (m<=t2 && m>=t1) && (s<=t2 && s>=t1))
||((h<t1 || h>t2) && (m<t1 || m>t2) && (s<t1 || s>t2)))cout<<"YES"<<endl;
else cout<<"NO"<<endl;
} | [
"harshitagar1907@gmail.com"
] | harshitagar1907@gmail.com |
cf6b74b78317bb4761e142c555b6833e8fea69b2 | f22f1c9b9f0265295be7cb83433fcba66b620776 | /xml/jaxp/src/main/include/jcpp/xml/internal/parser/JInputEntity.h | 31d9d423b8abd964a96e0ff8dcae46a1793c3528 | [] | no_license | egelor/jcpp-1 | 63c72c3257b52b37a952344a62fa43882247ba6e | 9b5a180b00890d375d2e8a13b74ab5039ac4388c | refs/heads/master | 2021-05-09T03:46:22.585245 | 2015-08-07T16:04:20 | 2015-08-07T16:04:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,830 | h | #ifndef JCPP_XML_INTERNAL_PARSER_JINPUT_ENTITY_H
#define JCPP_XML_INTERNAL_PARSER_JINPUT_ENTITY_H
#include "jcpp/lang/JInterface.h"
#include "jcpp/lang/JClass.h"
#include "jcpp/io/JReader.h"
#include "jcpp/lang/JStringBuffer.h"
#include "jcpp/lang/JPrimitiveCharArray.h"
#include "jcpp/lang/JPrimitiveObjectArray.h"
#include "org/xml/sax/JLocator.h"
#include "org/xml/sax/JInputSource.h"
#include "org/xml/sax/JErrorHandler.h"
#include "org/xml/sax/JContentHandler.h"
#include "jcpp/xml/internal/parser/JElementValidator.h"
using namespace org::xml::sax;
using namespace jcpp::io;
namespace jcpp{
namespace xml{
namespace internal{
namespace parser{
// @Class(canonicalName="javax.xml.internal.parser.InputEntity", simpleName="InputEntity");
class JCPP_EXPORT JInputEntity : public JObject, public JLocator{
protected:
jint start;
jint finish;
JPrimitiveCharArray* buf;
jint lineNumber;
jbool returnedFirstHalf;
jbool maybeInCRLF;
JString* name;
JInputEntity* next;
JInputSource* input;
JReader* reader;
jbool isClosed;
JErrorHandler* errHandler;
JStringBuffer* rememberedText;
jint startRemember;
jbool isPE;
static jint BUFFER_SIZE ;
public:
JInputEntity();
static JClass* getClazz();
static JInputEntity* getInputEntity(JErrorHandler* h);
virtual jbool isInternal();
virtual jbool isDocument();
virtual jbool isParameterEntity();
virtual JString* getName();
virtual void init(JInputSource* in, JString* name, JInputEntity* stack,jbool isPE);
virtual void init(JPrimitiveCharArray* b, JString* name,JInputEntity* stack, jbool isPE);
virtual void checkRecursion(JInputEntity* stack);
virtual JInputEntity* pop();
virtual jbool isEOF();
virtual JString* getEncoding();
virtual jchar getNameChar();
virtual jchar getc();
virtual jbool peekc(jchar c);
virtual void ungetc();
virtual jbool maybeWhitespace();
virtual jbool parsedContent(JContentHandler* contentHandler,JElementValidator* validator);
virtual void unparsedContent(JContentHandler* contentHandler,JElementValidator* validator,jbool ignorableWhitespace,JString* whitespaceInvalidMessage);
virtual jbool checkSurrogatePair(jint offset);
virtual jbool ignorableWhitespace(JContentHandler* handler);
virtual jbool peek(JString* next, JPrimitiveCharArray* chars);
virtual jbool isXmlDeclOrTextDeclPrefix();
virtual void startRemembering();
virtual JString* rememberText();
virtual JLocator* getLocator();
virtual JString* getPublicId();
virtual JString* getSystemId();
virtual jint getLineNumber();
virtual jint getColumnNumber();
virtual void fillbuf();
virtual void close();
virtual void fatal(JString* messageId);
virtual ~JInputEntity();
};
}
}
}
}
#endif
| [
"mimi4930"
] | mimi4930 |
b28913c6edbaddaa923fa8a4e3f60ccec8d89199 | 0d82341497beb87d62abf0ebacabbe10a2f41465 | /UninstallMonitor/jni/Monitor.cc | 0f9b7162c39b7799110f58295e045e169dde143f | [] | no_license | imwhite/UninstallMonitor | 6f92fd5ea65d62afb68b54da18af2e726dee61f8 | 4443ff7d311a956e724414248c5fde65f26626ba | refs/heads/master | 2021-01-10T09:44:17.837924 | 2018-03-26T09:13:58 | 2018-03-26T09:13:58 | 54,689,320 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,043 | cc | /*
* Monitor.cc
*
* Created on: 2016-3-15
* Author: white
*/
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <jni.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <android/log.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <sys/prctl.h>
#include <Utils.h>
/* 宏定义begin */
//清0宏
#define MEM_ZERO(pDest, destSize) memset(pDest, 0, destSize)
/* LOG宏定义 */
#define LOG_TAG "Monitor"
#define LOG_D(fmt, args...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, fmt, ##args)
#define LOG_E(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, fmt, ##args)
/** 调用java路径 */
#define NAME_JAVA_CLASS "com/uninstall/monitor/JNIHelper"
#define NAME_JAVA_METHOD "openUrl"
/**
* c层打开url
* 扩展:可以执行其他shell命令,am(即activity manager),可以打开某程序、服务,broadcast intent,等等
*/
void doOpenUrlByNative(char* activity, char* action,
char* action_data, char* userSerial) {
if (userSerial == NULL || strcmp(userSerial, "null") == 0) {
// 执行命令am start -a android.intent.action.VIEW -d $(url)
execlp("am", "am", "start", "-a", "android.intent.action.VIEW", "-d",
action_data, (char *) NULL);
}
else {
if (activity == NULL || strcmp(activity, "null") == 0) {
execlp("am", "am", "start", "--user", userSerial, "-a", action, "-d", action_data, (char *) NULL);
}
else {
if (action == NULL || strcmp(action, "null") == 0) {
if (action_data == NULL || strcmp(action_data, "null") == 0) {
execlp("am", "am", "start", "--user",
userSerial, "-n",
activity,
(char *) NULL);
} else {
execlp("am", "am", "start", "--user",
userSerial, "-n",
activity, "-d",
action_data,
(char *) NULL);
}
} else {
if (action_data == NULL || strcmp(action_data, "null") == 0) {
execlp("am", "am", "start", "--user",
userSerial, "-n",
activity, "-a",
action,
(char *) NULL);
} else {
execlp("am", "am", "start", "--user",
userSerial, "-n",
activity, "-a",
action, "-d",
action_data,
(char *) NULL);
}
}
}
}
}
char* doStartAndOpenUrl(char* targetDir, char* activity, char* action, char* url, char* userSerial) {
LOG_D("start------------------");
//fork子进程,这时候会有两个进程执行下面的代码,返回的pid对于父进程是子进程的id,对于子进程id=0
pid_t pid = fork();
char showpid[10];
sprintf(showpid, "%d", pid);
LOG_D("fork pid=%d", pid);
if (pid < 0) {
LOG_E("fork failed !!!");
}
// 第一个子进程执行
else if (pid == 0) {
LOG_D("child process execute");
// 第一个子进程再fork第二个子进程,第二个使对应父进程是init(1)
pid_t pid = fork();
sprintf(showpid, "%d", pid);
// 第一个子进程执行
if(pid != 0){
char showpid[10];
sprintf(showpid, "%d", pid);
LOG_D("child process fork pid=%d", pid);
exit(1);
}
// 第二个子进程执行
// 进程重命名
prctl(PR_SET_NAME, "uninstall_monitor", NULL, NULL, NULL);
// 初始化文件监听
int fileDescriptor = inotify_init();
if (fileDescriptor < 0) {
LOG_E("inotify_init failed !!");
exit(1);
}
const char* targetDirPath = targetDir;
LOG_D("target file %s", targetDirPath);
// 子进程注册"/data/data/{package}"目录监听器
int watchDescriptor;
watchDescriptor = inotify_add_watch(fileDescriptor, targetDirPath, IN_DELETE);
if (watchDescriptor < 0) {
LOG_D("inotify_add_watch failed !!!");
exit(1);
}
//分配缓存,以便读取event,缓存大小=一个struct inotify_event的大小,这样一次处理一个event
void *p_buf = malloc(sizeof(struct inotify_event));
if (p_buf == NULL) {
LOG_D("malloc failed !!!");
exit(1);
}
// 开始监听
LOG_D("start monitor...");
size_t readBytes = read(fileDescriptor, p_buf, sizeof(struct inotify_event));
LOG_D("receive result:");
// 文件操作有event:文件还在,覆盖安装
FILE *p_appDir = fopen(targetDir, "r");
if (p_appDir != NULL) {
LOG_D("reinstall");
exit(1);
}
// 文件操作有event:文件不在已经卸载了,释放
free(p_buf);
inotify_rm_watch(fileDescriptor, IN_DELETE);
LOG_D("uninstalled");
// 打开url
// 方式2:c层
LOG_D("open url(c)");
doOpenUrlByNative(activity, action, url, userSerial);
}
// 父进程执行
else {
//父进程直接退出,使子进程被init进程领养,以避免子进程僵死
LOG_D("parent process execute");
}
LOG_D("end------------------");
return showpid;
}
///**
// * java层打开url
// */
//jboolean doOpenUrlByJava(JNIEnv* env, jstring url) {
// jclass clas = env->FindClass(NAME_JAVA_CLASS);
// LOG_D("class %p ", clas);
// jmethodID methodID = env->GetStaticMethodID(clas, NAME_JAVA_METHOD, "(Ljava/lang/String;)Z");
// LOG_D("methodID %p ", methodID);
// if (methodID == NULL) {
// LOG_E("methodID == NULL");
// return JNI_FALSE;
// }
// jboolean isOpen = env->CallStaticBooleanMethod(clas, methodID, url);
//// LOG_D("CallStaticBooleanMethod ", isOpen?"true":"false");
// return isOpen;
//}
//
//
//string jstring_to_string(JNIEnv *env, const jstring in) {
// jboolean iscopy = JNI_FALSE;
// const char *c_str = env->GetStringUTFChars(in, &iscopy);
//
// string result;
// if (c_str != NULL) {
// result = string(c_str, strlen(c_str));
// }
//
// return result;
//}
| [
"im_white@qq.com"
] | im_white@qq.com |
889dd773583555195dc355e38c177f7348d70d20 | 6500bc4f1dd87c8c87cdf67ec7e96a8f4a749190 | /uva-problem/12543.cpp | a5a272ccbb2bae4b88a98586f38395851c67db9b | [] | no_license | MamunOrRashid/code_snippets | 4130bb72b885dc361393ff52fb101f93716912f2 | ef5bad40a93350bcb4d195dd0fd64c377a23051b | refs/heads/master | 2023-01-23T23:35:09.510436 | 2020-12-03T06:23:55 | 2020-12-03T06:23:55 | 284,689,299 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,377 | cpp | /**#include <bits/stdc++.h>
using namespace std;
int main()
{
string name,temp;
int maxi=0;
while(cin>>name){
if(name=="E-N-D") break;
int len=name.size(),cnt=0;
for(int i=0;i<len;i++){
if(isalpha(name[i]) || name[i]=='-')cnt++;
}
if(cnt>maxi){
temp=name;
maxi=cnt;
}
}
int len=temp.size();
for(int i=0;i<len;i++){
if(isalpha(temp[i]) || temp[i]=='-'){
if(temp[i]>='A' && temp[i]<='Z')printf("%c",tolower(temp[i]));
else printf("%c",temp[i]);
}
}
cout<<endl;
// cout<<strlwr(temp)<<endl;
return 0;
}*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
string name,temp;
int maxi=0;
while(cin>>name){
if(name=="E-N-D") break;
int len=name.size(),cnt=0;
for(int i=0;i<len;i++){
if(isalpha(name[i]) || name[i]=='-')cnt++;
}
if(cnt>maxi){
temp=name;
maxi=cnt;
}
}
int len=temp.size();
for(int i=0;i<len;i++){
if(isalpha(temp[i]) || temp[i]=='-'){
if(temp[i]>='A' && temp[i]<='Z')temp[i]=temp[i]-'A'+'a';
}
}
cout<<temp<<endl;
// cout<<strlwr(temp)<<endl;
return 0;
}
| [
"mdmamun8811@gmail.com"
] | mdmamun8811@gmail.com |
9b172b30c55a6cab1f6131d5891c17ba1a6c55b3 | 49fc5b8f53a1703581ea0b0a59d740f4986b5141 | /examples/19_OptimizeDeferredShading/OptimizeDeferredShading.cpp | 494fca77badf7ea7a62c41228a5427657fb22ebc | [
"MIT"
] | permissive | Guangehhhh/VulkanDemos | cbeccf361cdcc16095cf1c0d5d4e0dfe7f15dc5c | d3b9cc113aa3657689a0e7828892fb754f73361f | refs/heads/master | 2020-08-12T01:58:20.796733 | 2019-10-07T07:07:03 | 2019-10-07T07:07:03 | 214,666,856 | 1 | 0 | MIT | 2019-10-12T15:06:56 | 2019-10-12T15:06:56 | null | UTF-8 | C++ | false | false | 28,154 | cpp | #include "Common/Common.h"
#include "Common/Log.h"
#include "Demo/DVKCommon.h"
#include "Math/Vector4.h"
#include "Math/Matrix4x4.h"
#include "Loader/ImageLoader.h"
#include <vector>
#define NUM_LIGHTS 64
class OptimizeDeferredShading : public DemoBase
{
public:
OptimizeDeferredShading(int32 width, int32 height, const char* title, const std::vector<std::string>& cmdLine)
: DemoBase(width, height, title, cmdLine)
{
}
virtual ~OptimizeDeferredShading()
{
}
virtual bool PreInit() override
{
return true;
}
virtual bool Init() override
{
DemoBase::Setup();
DemoBase::Prepare();
LoadAssets();
CreateGUI();
CreateUniformBuffers();
CreateDescriptorSet();
CreatePipelines();
SetupCommandBuffers();
m_Ready = true;
return true;
}
virtual void Exist() override
{
DemoBase::Release();
DestroyAssets();
DestroyGUI();
DestroyPipelines();
DestroyUniformBuffers();
DestroyAttachments();
}
virtual void Loop(float time, float delta) override
{
if (!m_Ready) {
return;
}
Draw(time, delta);
}
protected:
void CreateFrameBuffers() override
{
DestroyFrameBuffers();
int32 fwidth = GetVulkanRHI()->GetSwapChain()->GetWidth();
int32 fheight = GetVulkanRHI()->GetSwapChain()->GetHeight();
VkDevice device = GetVulkanRHI()->GetDevice()->GetInstanceHandle();
VkImageView attachments[4];
VkFramebufferCreateInfo frameBufferCreateInfo;
ZeroVulkanStruct(frameBufferCreateInfo, VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
frameBufferCreateInfo.renderPass = m_RenderPass;
frameBufferCreateInfo.attachmentCount = 4;
frameBufferCreateInfo.pAttachments = attachments;
frameBufferCreateInfo.width = fwidth;
frameBufferCreateInfo.height = fheight;
frameBufferCreateInfo.layers = 1;
const std::vector<VkImageView>& backbufferViews = GetVulkanRHI()->GetBackbufferViews();
m_FrameBuffers.resize(backbufferViews.size());
for (uint32 i = 0; i < m_FrameBuffers.size(); ++i) {
attachments[0] = backbufferViews[i];
attachments[1] = m_AttachsColor[i]->imageView;
attachments[2] = m_AttachsNormal[i]->imageView;
attachments[3] = m_AttachsDepth[i]->imageView;
VERIFYVULKANRESULT(vkCreateFramebuffer(device, &frameBufferCreateInfo, VULKAN_CPU_ALLOCATOR, &m_FrameBuffers[i]));
}
}
void CreateDepthStencil() override
{
}
void DestoryDepthStencil() override
{
}
void DestroyAttachments()
{
for (int32 i = 0; i < m_AttachsDepth.size(); ++i)
{
vk_demo::DVKTexture* texture = m_AttachsDepth[i];
delete texture;
}
m_AttachsDepth.clear();
for (int32 i = 0; i < m_AttachsColor.size(); ++i)
{
vk_demo::DVKTexture* texture = m_AttachsColor[i];
delete texture;
}
m_AttachsColor.clear();
for (int32 i = 0; i < m_AttachsNormal.size(); ++i)
{
vk_demo::DVKTexture* texture = m_AttachsNormal[i];
delete texture;
}
m_AttachsNormal.clear();
}
void CreateAttachments()
{
auto swapChain = GetVulkanRHI()->GetSwapChain();
int32 fwidth = swapChain->GetWidth();
int32 fheight = swapChain->GetHeight();
int32 numBuffer = swapChain->GetBackBufferCount();
m_AttachsColor.resize(numBuffer);
m_AttachsNormal.resize(numBuffer);
m_AttachsDepth.resize(numBuffer);
for (int32 i = 0; i < m_AttachsColor.size(); ++i)
{
m_AttachsColor[i] = vk_demo::DVKTexture::CreateAttachment(
m_VulkanDevice,
PixelFormatToVkFormat(GetVulkanRHI()->GetPixelFormat(), false),
VK_IMAGE_ASPECT_COLOR_BIT,
fwidth, fheight,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT
);
}
for (int32 i = 0; i < m_AttachsNormal.size(); ++i)
{
m_AttachsNormal[i] = vk_demo::DVKTexture::CreateAttachment(
m_VulkanDevice,
VK_FORMAT_R8G8B8A8_UNORM,
VK_IMAGE_ASPECT_COLOR_BIT,
fwidth, fheight,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT
);
}
for (int32 i = 0; i < m_AttachsDepth.size(); ++i)
{
m_AttachsDepth[i] = vk_demo::DVKTexture::CreateAttachment(
m_VulkanDevice,
PixelFormatToVkFormat(m_DepthFormat, false),
VK_IMAGE_ASPECT_DEPTH_BIT,
fwidth, fheight,
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT
);
}
}
void CreateRenderPass() override
{
DestoryRenderPass();
DestroyAttachments();
CreateAttachments();
VkDevice device = GetVulkanRHI()->GetDevice()->GetInstanceHandle();
PixelFormat pixelFormat = GetVulkanRHI()->GetPixelFormat();
std::vector<VkAttachmentDescription> attachments(4);
// swap chain attachment
attachments[0].format = PixelFormatToVkFormat(pixelFormat, false);
attachments[0].samples = m_SampleCount;
attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
// color attachment
attachments[1].format = PixelFormatToVkFormat(pixelFormat, false);
attachments[1].samples = m_SampleCount;
attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[1].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
// normal attachment
attachments[2].format = VK_FORMAT_R8G8B8A8_UNORM;
attachments[2].samples = m_SampleCount;
attachments[2].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[2].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[2].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[2].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[2].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[2].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
// depth stencil attachment
attachments[3].format = PixelFormatToVkFormat(m_DepthFormat, false);
attachments[3].samples = m_SampleCount;
attachments[3].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[3].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[3].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[3].stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[3].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[3].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference colorReferences[2];
colorReferences[0].attachment = 1;
colorReferences[0].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
colorReferences[1].attachment = 2;
colorReferences[1].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference swapReference = { };
swapReference.attachment = 0;
swapReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depthReference = { };
depthReference.attachment = 3;
depthReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference inputReferences[3];
inputReferences[0].attachment = 1;
inputReferences[0].layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
inputReferences[1].attachment = 2;
inputReferences[1].layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
inputReferences[2].attachment = 3;
inputReferences[2].layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
std::vector<VkSubpassDescription> subpassDescriptions(2);
subpassDescriptions[0].pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassDescriptions[0].colorAttachmentCount = 2;
subpassDescriptions[0].pColorAttachments = colorReferences;
subpassDescriptions[0].pDepthStencilAttachment = &depthReference;
subpassDescriptions[1].pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpassDescriptions[1].colorAttachmentCount = 1;
subpassDescriptions[1].pColorAttachments = &swapReference;
subpassDescriptions[1].inputAttachmentCount = 3;
subpassDescriptions[1].pInputAttachments = inputReferences;
std::vector<VkSubpassDependency> dependencies(3);
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
dependencies[1].srcSubpass = 0;
dependencies[1].dstSubpass = 1;
dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
dependencies[2].srcSubpass = 1;
dependencies[2].dstSubpass = VK_SUBPASS_EXTERNAL;
dependencies[2].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[2].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[2].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[2].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[2].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
VkRenderPassCreateInfo renderPassInfo;
ZeroVulkanStruct(renderPassInfo, VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO);
renderPassInfo.attachmentCount = attachments.size();
renderPassInfo.pAttachments = attachments.data();
renderPassInfo.subpassCount = subpassDescriptions.size();
renderPassInfo.pSubpasses = subpassDescriptions.data();
renderPassInfo.dependencyCount = dependencies.size();
renderPassInfo.pDependencies = dependencies.data();
VERIFYVULKANRESULT(vkCreateRenderPass(device, &renderPassInfo, VULKAN_CPU_ALLOCATOR, &m_RenderPass));
}
void DestroyFrameBuffers() override
{
VkDevice device = GetVulkanRHI()->GetDevice()->GetInstanceHandle();
for (int32 i = 0; i < m_FrameBuffers.size(); ++i) {
vkDestroyFramebuffer(device, m_FrameBuffers[i], VULKAN_CPU_ALLOCATOR);
}
m_FrameBuffers.clear();
}
void DestoryRenderPass() override
{
VkDevice device = GetVulkanRHI()->GetDevice()->GetInstanceHandle();
if (m_RenderPass != VK_NULL_HANDLE) {
vkDestroyRenderPass(device, m_RenderPass, VULKAN_CPU_ALLOCATOR);
m_RenderPass = VK_NULL_HANDLE;
}
}
private:
struct ModelBlock
{
Matrix4x4 model;
};
struct ViewProjectionBlock
{
Matrix4x4 view;
Matrix4x4 projection;
};
struct AttachmentParamBlock
{
float attachmentIndex;
float zNear;
float zFar;
float one;
float xMaxFar;
float yMaxFar;
Vector2 padding;
Matrix4x4 invView;
};
struct PointLight
{
Vector4 position;
Vector3 color;
float radius;
};
struct LightSpawnBlock
{
Vector3 position[NUM_LIGHTS];
Vector3 direction[NUM_LIGHTS];
float speed[NUM_LIGHTS];
};
struct LightDataBlock
{
PointLight lights[NUM_LIGHTS];
};
void Draw(float time, float delta)
{
int32 bufferIndex = DemoBase::AcquireBackbufferIndex();
UpdateUI(time, delta);
UpdateUniform(time, delta);
DemoBase::Present(bufferIndex);
}
void UpdateUniform(float time, float delta)
{
m_VertFragParam.yMaxFar = m_VertFragParam.zFar * MMath::Tan(MMath::DegreesToRadians(75.0f) / 2);
m_VertFragParam.xMaxFar = m_VertFragParam.yMaxFar * (float)GetWidth() / (float)GetHeight();
m_ParamBuffer->CopyFrom(&m_VertFragParam, sizeof(AttachmentParamBlock));
m_ViewProjData.projection.Perspective(MMath::DegreesToRadians(75.0f), (float)GetWidth(), (float)GetHeight(), m_VertFragParam.zNear, m_VertFragParam.zFar);
m_ViewProjBuffer->CopyFrom(&m_ViewProjData, sizeof(ViewProjectionBlock));
for (int32 i = 0; i < NUM_LIGHTS; ++i)
{
float bias = MMath::Sin(time * m_LightInfos.speed[i]) / 5.0f;
m_LightDatas.lights[i].position.x = m_LightInfos.position[i].x + bias * m_LightInfos.direction[i].x * 500.0f;
m_LightDatas.lights[i].position.y = m_LightInfos.position[i].y + bias * m_LightInfos.direction[i].y * 500.0f;
m_LightDatas.lights[i].position.z = m_LightInfos.position[i].z + bias * m_LightInfos.direction[i].z * 500.0f;
}
m_LightParamBuffer->CopyFrom(&m_LightDatas, sizeof(LightDataBlock));
}
void UpdateUI(float time, float delta)
{
m_GUI->StartFrame();
{
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(ImVec2(0, 0), ImGuiSetCond_FirstUseEver);
ImGui::Begin("OptimizeDeferredShading", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove);
int32 index = m_VertFragParam.attachmentIndex;
ImGui::SliderInt("Index", &index, 0, 3);
m_VertFragParam.attachmentIndex = index;
if (ImGui::Button("Random"))
{
vk_demo::DVKBoundingBox bounds = m_Model->rootNode->GetBounds();
for (int32 i = 0; i < NUM_LIGHTS; ++i)
{
m_LightDatas.lights[i].position.x = MMath::RandRange(bounds.min.x, bounds.max.x);
m_LightDatas.lights[i].position.y = MMath::RandRange(bounds.min.y, bounds.max.y);
m_LightDatas.lights[i].position.z = MMath::RandRange(bounds.min.z, bounds.max.z);
m_LightDatas.lights[i].color.x = MMath::RandRange(0.0f, 1.0f);
m_LightDatas.lights[i].color.y = MMath::RandRange(0.0f, 1.0f);
m_LightDatas.lights[i].color.z = MMath::RandRange(0.0f, 1.0f);
m_LightDatas.lights[i].radius = MMath::RandRange(50.0f, 200.0f);
m_LightInfos.position[i] = m_LightDatas.lights[i].position;
m_LightInfos.direction[i] = m_LightInfos.position[i];
m_LightInfos.direction[i].Normalize();
m_LightInfos.speed[i] = 1.0f + MMath::RandRange(0.0f, 5.0f);
}
}
ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
m_GUI->EndFrame();
if (m_GUI->Update()) {
SetupCommandBuffers();
}
}
void LoadAssets()
{
m_Shader0 = vk_demo::DVKShader::Create(
m_VulkanDevice,
"assets/shaders/19_OptimizeDeferredShading/obj.vert.spv",
"assets/shaders/19_OptimizeDeferredShading/obj.frag.spv"
);
m_Shader1 = vk_demo::DVKShader::Create(
m_VulkanDevice,
"assets/shaders/19_OptimizeDeferredShading/quad.vert.spv",
"assets/shaders/19_OptimizeDeferredShading/quad.frag.spv"
);
vk_demo::DVKCommandBuffer* cmdBuffer = vk_demo::DVKCommandBuffer::Create(m_VulkanDevice, m_CommandPool);
// scene model
m_Model = vk_demo::DVKModel::LoadFromFile(
"assets/models/Room/miniHouse_FBX.FBX",
m_VulkanDevice,
cmdBuffer,
m_Shader0->perVertexAttributes
);
// quad model
std::vector<float> vertices = {
-1.0f, 1.0f, 0.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f, 1.0f
};
std::vector<uint16> indices = {
0, 1, 2, 0, 2, 3
};
m_Quad = vk_demo::DVKModel::Create(
m_VulkanDevice,
cmdBuffer,
vertices,
indices,
m_Shader1->perVertexAttributes
);
delete cmdBuffer;
}
void DestroyAssets()
{
delete m_Model;
delete m_Quad;
delete m_Shader0;
delete m_Shader1;
}
void SetupCommandBuffers()
{
VkCommandBufferBeginInfo cmdBeginInfo;
ZeroVulkanStruct(cmdBeginInfo, VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO);
VkClearValue clearValues[4];
clearValues[0].color = { { 0.2f, 0.2f, 0.2f, 0.0f } };
clearValues[1].color = { { 0.0f, 0.0f, 0.0f, 1.0f } };
clearValues[2].color = { { 0.2f, 0.2f, 0.2f, 0.0f } };
clearValues[3].depthStencil = { 1.0f, 0 };
VkRenderPassBeginInfo renderPassBeginInfo;
ZeroVulkanStruct(renderPassBeginInfo, VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO);
renderPassBeginInfo.renderPass = m_RenderPass;
renderPassBeginInfo.clearValueCount = 4;
renderPassBeginInfo.pClearValues = clearValues;
renderPassBeginInfo.renderArea.offset.x = 0;
renderPassBeginInfo.renderArea.offset.y = 0;
renderPassBeginInfo.renderArea.extent.width = m_FrameWidth;
renderPassBeginInfo.renderArea.extent.height = m_FrameHeight;
VkViewport viewport = {};
viewport.x = 0;
viewport.y = m_FrameHeight;
viewport.width = m_FrameWidth;
viewport.height = -(float)m_FrameHeight; // flip y axis
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor = {};
scissor.extent.width = m_FrameWidth;
scissor.extent.height = m_FrameHeight;
scissor.offset.x = 0;
scissor.offset.y = 0;
uint32 alignment = m_VulkanDevice->GetLimits().minUniformBufferOffsetAlignment;
uint32 modelAlign = Align(sizeof(ModelBlock), alignment);
for (int32 i = 0; i < m_CommandBuffers.size(); ++i)
{
renderPassBeginInfo.framebuffer = m_FrameBuffers[i];
VERIFYVULKANRESULT(vkBeginCommandBuffer(m_CommandBuffers[i], &cmdBeginInfo));
vkCmdBeginRenderPass(m_CommandBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdSetViewport(m_CommandBuffers[i], 0, 1, &viewport);
vkCmdSetScissor(m_CommandBuffers[i], 0, 1, &scissor);
// pass0
{
vkCmdBindPipeline(m_CommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_Pipeline0->pipeline);
for (int32 meshIndex = 0; meshIndex < m_Model->meshes.size(); ++meshIndex) {
uint32 offset = meshIndex * modelAlign;
vkCmdBindDescriptorSets(m_CommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_Pipeline0->pipelineLayout, 0, m_DescriptorSet0->descriptorSets.size(), m_DescriptorSet0->descriptorSets.data(), 1, &offset);
m_Model->meshes[meshIndex]->BindDrawCmd(m_CommandBuffers[i]);
}
}
vkCmdNextSubpass(m_CommandBuffers[i], VK_SUBPASS_CONTENTS_INLINE);
// pass1
{
vkCmdBindPipeline(m_CommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_Pipeline1->pipeline);
vkCmdBindDescriptorSets(m_CommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_Pipeline1->pipelineLayout, 0, m_DescriptorSets[i]->descriptorSets.size(), m_DescriptorSets[i]->descriptorSets.data(), 0, nullptr);
for (int32 meshIndex = 0; meshIndex < m_Quad->meshes.size(); ++meshIndex) {
m_Quad->meshes[meshIndex]->BindDrawCmd(m_CommandBuffers[i]);
}
}
m_GUI->BindDrawCmd(m_CommandBuffers[i], m_RenderPass, 1);
vkCmdEndRenderPass(m_CommandBuffers[i]);
VERIFYVULKANRESULT(vkEndCommandBuffer(m_CommandBuffers[i]));
}
}
void CreateDescriptorSet()
{
m_DescriptorSet0 = m_Shader0->AllocateDescriptorSet();
m_DescriptorSet0->WriteBuffer("uboViewProj", m_ViewProjBuffer);
m_DescriptorSet0->WriteBuffer("uboModel", m_ModelBuffer);
m_DescriptorSets.resize(m_AttachsColor.size());
for (int32 i = 0; i < m_DescriptorSets.size(); ++i)
{
m_DescriptorSets[i] = m_Shader1->AllocateDescriptorSet();
m_DescriptorSets[i]->WriteImage("inputColor", m_AttachsColor[i]);
m_DescriptorSets[i]->WriteImage("inputNormal", m_AttachsNormal[i]);
m_DescriptorSets[i]->WriteImage("inputDepth", m_AttachsDepth[i]);
m_DescriptorSets[i]->WriteBuffer("paramData", m_ParamBuffer);
m_DescriptorSets[i]->WriteBuffer("lightDatas", m_LightParamBuffer);
}
}
void CreatePipelines()
{
vk_demo::DVKGfxPipelineInfo pipelineInfo0;
pipelineInfo0.shader = m_Shader0;
pipelineInfo0.colorAttachmentCount = 2;
m_Pipeline0 = vk_demo::DVKGfxPipeline::Create(
m_VulkanDevice,
m_PipelineCache,
pipelineInfo0,
{
m_Model->GetInputBinding()
},
m_Model->GetInputAttributes(),
m_Shader0->pipelineLayout,
m_RenderPass
);
vk_demo::DVKGfxPipelineInfo pipelineInfo1;
pipelineInfo1.depthStencilState.depthTestEnable = VK_FALSE;
pipelineInfo1.depthStencilState.depthWriteEnable = VK_FALSE;
pipelineInfo1.depthStencilState.stencilTestEnable = VK_FALSE;
pipelineInfo1.shader = m_Shader1;
pipelineInfo1.subpass = 1;
m_Pipeline1 = vk_demo::DVKGfxPipeline::Create(
m_VulkanDevice,
m_PipelineCache,
pipelineInfo1,
{
m_Quad->GetInputBinding()
},
m_Quad->GetInputAttributes(),
m_Shader1->pipelineLayout,
m_RenderPass
);
}
void DestroyPipelines()
{
delete m_Pipeline0;
delete m_Pipeline1;
delete m_DescriptorSet0;
for (int32 i = 0; i < m_DescriptorSets.size(); ++i)
{
vk_demo::DVKDescriptorSet* descriptorSet = m_DescriptorSets[i];
delete descriptorSet;
}
m_DescriptorSets.clear();
}
void CreateUniformBuffers()
{
vk_demo::DVKBoundingBox bounds = m_Model->rootNode->GetBounds();
Vector3 boundSize = bounds.max - bounds.min;
Vector3 boundCenter = bounds.min + boundSize * 0.5f;
// param
m_VertFragParam.attachmentIndex = 0;
m_VertFragParam.zNear = 300.0f;
m_VertFragParam.zFar = 1500.0f;
m_VertFragParam.one = 1.0f;
m_VertFragParam.yMaxFar = m_VertFragParam.zFar * MMath::Tan(MMath::DegreesToRadians(75.0f) / 2);
m_VertFragParam.xMaxFar = m_VertFragParam.yMaxFar * (float)GetWidth() / (float)GetHeight();
// view projection buffer
m_ViewProjData.view.SetIdentity();
m_ViewProjData.view.SetOrigin(Vector3(boundCenter.x, boundCenter.y, boundCenter.z - boundSize.Size()));
m_ViewProjData.view.AppendRotation(30, Vector3::RightVector);
m_ViewProjData.view.SetInverse();
m_VertFragParam.invView = m_ViewProjData.view;
m_VertFragParam.invView.SetInverse();
m_ViewProjData.projection.SetIdentity();
m_ViewProjData.projection.Perspective(MMath::DegreesToRadians(75.0f), (float)GetWidth(), (float)GetHeight(), m_VertFragParam.zNear, m_VertFragParam.zFar);
m_ViewProjBuffer = vk_demo::DVKBuffer::CreateBuffer(
m_VulkanDevice,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(ViewProjectionBlock),
&(m_ViewProjData)
);
m_ViewProjBuffer->Map();
// dynamic
uint32 alignment = m_VulkanDevice->GetLimits().minUniformBufferOffsetAlignment;
uint32 modelAlign = Align(sizeof(ModelBlock), alignment);
m_ModelDatas.resize(modelAlign * m_Model->meshes.size());
for (int32 i = 0; i < m_Model->meshes.size(); ++i)
{
ModelBlock* modelBlock = (ModelBlock*)(m_ModelDatas.data() + modelAlign * i);
modelBlock->model = m_Model->meshes[i]->linkNode->GetGlobalMatrix();
}
m_ModelBuffer = vk_demo::DVKBuffer::CreateBuffer(
m_VulkanDevice,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
m_ModelDatas.size(),
m_ModelDatas.data()
);
m_ModelBuffer->Map();
// param buffer
m_ParamBuffer = vk_demo::DVKBuffer::CreateBuffer(
m_VulkanDevice,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(AttachmentParamBlock),
&(m_VertFragParam)
);
m_ParamBuffer->Map();
// light datas
for (int32 i = 0; i < NUM_LIGHTS; ++i)
{
m_LightDatas.lights[i].position.x = MMath::RandRange(bounds.min.x, bounds.max.x);
m_LightDatas.lights[i].position.y = MMath::RandRange(bounds.min.y, bounds.max.y);
m_LightDatas.lights[i].position.z = MMath::RandRange(bounds.min.z, bounds.max.z);
m_LightDatas.lights[i].position.w = 1.0f;
m_LightDatas.lights[i].color.x = MMath::RandRange(0.0f, 1.0f);
m_LightDatas.lights[i].color.y = MMath::RandRange(0.0f, 1.0f);
m_LightDatas.lights[i].color.z = MMath::RandRange(0.0f, 1.0f);
m_LightDatas.lights[i].radius = MMath::RandRange(50.0f, 200.0f);
m_LightInfos.position[i] = m_LightDatas.lights[i].position;
m_LightInfos.direction[i] = m_LightInfos.position[i];
m_LightInfos.direction[i].Normalize();
m_LightInfos.speed[i] = 1.0f + MMath::RandRange(0.0f, 5.0f);
}
m_LightParamBuffer = vk_demo::DVKBuffer::CreateBuffer(
m_VulkanDevice,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
sizeof(LightDataBlock),
&(m_LightDatas)
);
m_LightParamBuffer->Map();
{
// fast reconstruct position from eye linear depth
Matrix4x4 modelViewProj;
modelViewProj.Append(m_ViewProjData.view);
modelViewProj.Append(m_ViewProjData.projection);
// real world position
Vector4 realPos(10, 20, 30, 1.0f);
// view space position
Vector4 posView = m_ViewProjData.view.TransformPosition(realPos);
// projection space position
Vector4 posProj = modelViewProj.TransformVector4(realPos);
// none linear depth
float depth = posProj.z / posProj.w;
// linear depth
float zc0 = 1.0 - m_VertFragParam.zFar / m_VertFragParam.zNear;
float zc1 = m_VertFragParam.zFar / m_VertFragParam.zNear;
float depth01 = 1.0 / (zc0 * depth + zc1);
MLOG("LinearDepth:%f,%f", posProj.w / m_VertFragParam.zFar, depth01);
// ndc space
float u = posProj.x / posProj.w;
float v = posProj.y / posProj.w;
// view space ray
Vector3 viewRay = Vector3(m_VertFragParam.xMaxFar * u, m_VertFragParam.yMaxFar * v, m_VertFragParam.zFar);
Vector3 viewPos = viewRay * depth01;
MLOG("posView:(%f,%f,%f) - (%f,%f,%f)", posView.x, posView.y, posView.z, viewPos.x, viewPos.y, viewPos.z);
}
}
void DestroyUniformBuffers()
{
m_ViewProjBuffer->UnMap();
delete m_ViewProjBuffer;
m_ViewProjBuffer = nullptr;
m_ModelBuffer->UnMap();
delete m_ModelBuffer;
m_ModelBuffer = nullptr;
m_ParamBuffer->UnMap();
delete m_ParamBuffer;
m_ParamBuffer = nullptr;
m_LightParamBuffer->UnMap();
delete m_LightParamBuffer;
m_LightParamBuffer = nullptr;
}
void CreateGUI()
{
m_GUI = new ImageGUIContext();
m_GUI->Init("assets/fonts/Ubuntu-Regular.ttf");
}
void DestroyGUI()
{
m_GUI->Destroy();
delete m_GUI;
}
private:
typedef std::vector<vk_demo::DVKDescriptorSet*> DVKDescriptorSetArray;
typedef std::vector<vk_demo::DVKTexture*> DVKTextureArray;
bool m_Ready = false;
std::vector<uint8> m_ModelDatas;
vk_demo::DVKBuffer* m_ModelBuffer = nullptr;
vk_demo::DVKBuffer* m_ViewProjBuffer = nullptr;
ViewProjectionBlock m_ViewProjData;
AttachmentParamBlock m_VertFragParam;
vk_demo::DVKBuffer* m_ParamBuffer = nullptr;
vk_demo::DVKBuffer* m_LightParamBuffer = nullptr;
LightDataBlock m_LightDatas;
LightSpawnBlock m_LightInfos;
vk_demo::DVKModel* m_Model = nullptr;
vk_demo::DVKModel* m_Quad = nullptr;
vk_demo::DVKGfxPipeline* m_Pipeline0 = nullptr;
vk_demo::DVKShader* m_Shader0 = nullptr;
vk_demo::DVKDescriptorSet* m_DescriptorSet0 = nullptr;
vk_demo::DVKGfxPipeline* m_Pipeline1 = nullptr;
vk_demo::DVKShader* m_Shader1 = nullptr;
DVKDescriptorSetArray m_DescriptorSets;
DVKTextureArray m_AttachsDepth;
DVKTextureArray m_AttachsColor;
DVKTextureArray m_AttachsNormal;
ImageGUIContext* m_GUI = nullptr;
};
std::shared_ptr<AppModuleBase> CreateAppMode(const std::vector<std::string>& cmdLine)
{
return std::make_shared<OptimizeDeferredShading>(1400, 900, "OptimizeDeferredShading", cmdLine);
}
| [
"chenbo150928@gmail.com"
] | chenbo150928@gmail.com |
7bfa87243dba3f47ef97788b62d9b7f645735534 | 28dba754ddf8211d754dd4a6b0704bbedb2bd373 | /Topcoder/MaxDiffBetweenCards.cpp | 3ff988ddd2aaafc852416e64771e1a8a2b77cdd6 | [] | no_license | zjsxzy/algo | 599354679bd72ef20c724bb50b42fce65ceab76f | a84494969952f981bfdc38003f7269e5c80a142e | refs/heads/master | 2023-08-31T17:00:53.393421 | 2023-08-19T14:20:31 | 2023-08-19T14:20:31 | 10,140,040 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,801 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
class MaxDiffBetweenCards {
public:
long long solve(int N) {
if (N == 1) return 0;
string a = "";
for (int i = 0; i < N / 2; i++) a += '9';
a += '1';
if (N & 1) for (int i = 0; i < N / 2; i++) a += '0';
else for (int i = 0; i < N / 2 - 1; i++) a += '0';
string b = "1";
if (N & 1) for (int i = 0; i < N / 2; i++) b += '0';
else for (int i = 0; i < N / 2 - 1; i++) b += '0';
for (int i = 0; i < N / 2; i++) b += '9';
return stoll(a) - stoll(b);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 1; long long Arg1 = 0LL; verify_case(0, Arg1, solve(Arg0)); }
void test_case_1() { int Arg0 = 2; long long Arg1 = 72LL; verify_case(1, Arg1, solve(Arg0)); }
void test_case_2() { int Arg0 = 4; long long Arg1 = 8811LL; verify_case(2, Arg1, solve(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
MaxDiffBetweenCards ___test;
___test.run_test(-1);
return 0;
}
// END CUT HERE
| [
"zjsxzy@gmail.com"
] | zjsxzy@gmail.com |
3beaad7cdd6f8790f38816f35a87e9f68ede3fd0 | 9c3d0b8813ac5fd543991042a1361f920e8e0c5e | /common/base/read_file.h | 879396842fa7451640dd95ea1a79ef3fc29bdee2 | [] | no_license | shiningstarpxx/marvel | 5ee4a8f4707a254a24d5d77f6b77b0cda68ef663 | 0285451700588b608b640de50e732a2e3f8fbd8d | refs/heads/master | 2021-07-11T05:30:44.639957 | 2021-03-12T02:35:45 | 2021-03-12T02:35:45 | 56,899,287 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 893 | h | // Copyright (c) 2016, Tencent
// Filename: read_file.h
// Description:
// Created: 07/27/2016 17:39:58
// Author: michaelpei (Pei Xingxin), michaelpei@tencent.com
#ifndef COMMON_BASE_READ_FILE_H_
#define COMMON_BASE_READ_FILE_H_
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
void LoadFileToMatrix(
const std::string& file_name,
uint32_t demision,
std::vector<std::vector<uint32_t> >* matrix) {
std::ifstream in(file_name);
std::string line;
while (getline(in, line)) {
std::vector<uint32_t> tmp(demision, 0);
uint32_t index = 0;
uint32_t number;
std::stringstream ss(line);
while (ss >> number) {
tmp[index++] = number;
}
matrix->push_back(tmp);
}
in.close();
return;
}
void LoadFileToVector(
const std::string& file_name,
std::vector<uint32_t>* matrix);
#endif // COMMON_BASE_READ_FILE_H_
| [
"xingxinpei@gmail.com"
] | xingxinpei@gmail.com |
2bd313aa23ee76692e3c94b836889557f2b5cd62 | 4a3134ced92b1e6f6440ac67b69449302bf32f5c | /DSA/Arrays/MergeTwoSortedArrays/solution.cpp | ee183d64588a05fff8d3856219e7ca77d1c305ac | [] | no_license | Arihant416/Dsa-cp | 4454f2d1f6b16e94d33bd1d8760fe0ac27354715 | cdfea5ccb8040fc22588a7a7e22616f1d1d411f6 | refs/heads/master | 2023-03-23T16:23:33.692728 | 2021-03-07T05:52:49 | 2021-03-07T05:52:49 | 326,686,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | cpp | /*
Author : Arihant Jain
github:https://github.com/Arihant416
linkedin : https://www.linkedin.com/in/arihant416
*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ull unsigned ll
#define PB push_back
#define MP make_pair
#define flash ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr)
#define vi vector<int>
#define vl vector<ll>
#define vll vector<ull>
#define mpi map<int, int>
#define mpl map<ll, ll>
#define mpll map<ull, ull>
#define pi pair<int, int>
#define pl pair<ll, ll>
#define all(a) begin(a), end(a)
#define maxEl(a) *max_element(all(a))
#define minEl(a) *min_element(all(a))
#define uimap unordered_map<int, int>
#define ulmap unordered_map<ll, ll>
#define mppii map<pi, int>
int nextGap(int currentGap)
{
if (currentGap <= 1)
return 0;
return currentGap / 2 + (currentGap % 2);
}
void merge(int A[], int B[], int sizeA, int sizeB)
{
int i, j, currentGap = sizeA + sizeB;
for (currentGap = nextGap(currentGap); currentGap > 0; currentGap = nextGap(currentGap))
{
for (i = 0; i + currentGap < sizeA; i++)
{
if (A[i] > A[i + currentGap])
{
swap(A[i], A[i + currentGap]);
}
}
for (j = currentGap > sizeA ? currentGap - sizeA : 0; i < sizeA && j < sizeB; i++, j++)
{
if (A[i] > B[j])
swap(A[i], B[j]);
}
if (j < sizeB)
{
for (j = 0; j + currentGap < sizeB; j++)
{
if (B[j] > B[j + currentGap])
{
swap(B[j], B[currentGap]);
}
}
}
}
}
int32_t main()
{
flash;
int sizeA, sizeB;
cin >> sizeA >> sizeB;
int A[sizeA], B[sizeB];
for (int i = 0; i < sizeA; i++)
{
cin >> A[i];
}
for (int i = 0; i < sizeB; i++)
{
cin >> B[i];
}
merge(A, B, sizeA, sizeB);
for (int i = 0; i < sizeA; i++)
{
cout << A[i] << " ";
}
for (int i = 0; i < sizeB; i++)
{
cout << B[i] << " ";
}
return 0;
} | [
"arihantjain416@gmail.com"
] | arihantjain416@gmail.com |
45fd34b47d54e67ddc2a313ec49040828a074956 | 91db922ced8fb4899e4fc5ad20179f07d738a99f | /yorukatsu/48/CountBalls.cpp | ea9a38ae7332ebdc414938db8e370aabf48728d0 | [] | no_license | hntk03/atcoder | d1bb795b9b9db2a689353eedcf6b9211d923b21b | cd024e1b6911765ef9239a72c2e25147922fa460 | refs/heads/master | 2022-10-08T05:35:24.339333 | 2022-10-02T03:12:55 | 2022-10-02T03:12:55 | 162,792,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
//container util
#define SORT(c) sort((c).begin(),(c).end())
#define all(a) (a).begin(), (a).end()
//repetition
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
//print
#define pv(val) cerr << #val << '=' << (val) << endl
const int INF = 1e9;
int main(void){
ll N, A, B; cin >> N >> A >> B;
ll ans = N/(A+B)*A + min(N%(A+B), A);
cout << ans << endl;
return 0;
}
| [
"hntk03@gmail.com"
] | hntk03@gmail.com |
53d8ba39c83a2d3b0ed4c3c0e9d7d327cd387fdf | 22212b6400346c5ec3f5927703ad912566d3474f | /src/Plugins/JSONPlugin/JSONSettingPrototypeGenerator.cpp | 13f6d2f6e4255423f0f509b33eb07ae94b186e94 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | irov/Mengine | 673a9f35ab10ac93d42301bc34514a852c0f150d | 8118e4a4a066ffba82bda1f668c1e7a528b6b717 | refs/heads/master | 2023-09-04T03:19:23.686213 | 2023-09-03T16:05:24 | 2023-09-03T16:05:24 | 41,422,567 | 46 | 17 | MIT | 2022-09-26T18:41:33 | 2015-08-26T11:44:35 | C++ | UTF-8 | C++ | false | false | 1,597 | cpp | #include "JSONSettingPrototypeGenerator.h"
#include "Kernel/FactoryPool.h"
#include "Kernel/AssertionMemoryPanic.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
JSONSettingPrototypeGenerator::JSONSettingPrototypeGenerator()
{
}
//////////////////////////////////////////////////////////////////////////
JSONSettingPrototypeGenerator::~JSONSettingPrototypeGenerator()
{
}
//////////////////////////////////////////////////////////////////////////
FactoryInterfacePtr JSONSettingPrototypeGenerator::_initializeFactory()
{
FactoryInterfacePtr factory = Helper::makeFactoryPool<JSONSetting, 128>( MENGINE_DOCUMENT_FACTORABLE );
return factory;
}
//////////////////////////////////////////////////////////////////////////
void JSONSettingPrototypeGenerator::_finalizeFactory()
{
//Empty
}
//////////////////////////////////////////////////////////////////////////
FactorablePointer JSONSettingPrototypeGenerator::generate( const DocumentInterfacePtr & _doc )
{
const FactoryInterfacePtr & factory = this->getPrototypeFactory();
TypePtr setting = factory->createObject( _doc );
MENGINE_ASSERTION_MEMORY_PANIC( setting, "can't generate category '%s' prototype '%s' doc '%s'"
, this->getCategory().c_str()
, this->getPrototype().c_str()
, MENGINE_DOCUMENT_STR( _doc )
);
return setting;
}
//////////////////////////////////////////////////////////////////////////
} | [
"irov13@mail.ru"
] | irov13@mail.ru |
7df5a071f0e34ebcc9da6ad11f9e1748f1b35f49 | 61dbffaee1fe90f597f7a73eb7cba5c1152bb98a | /VR_Room/Intermediate/Build/Win64/VR_Room/Development/Engine/SharedPCH.Engine.ShadowErrors.cpp | 272169adfa8d4f194dd93e9504d4dceec051b320 | [] | no_license | AtaSuid/VR_Room | 5e8a6b39985f6811ce5d8b73b1ca85a57b02553b | 8eb976dfd399d28ef88fe3d64a91320ced4d3d22 | refs/heads/master | 2022-11-19T05:00:56.601537 | 2020-06-28T23:56:55 | 2020-06-28T23:56:55 | 260,785,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 137 | cpp | #include "Q:/ghost/Documents/GitHub/VR_Room/VR_Room/Intermediate/Build/Win64/VR_Room/Development/Engine/SharedPCH.Engine.ShadowErrors.h"
| [
"53719354+AtaSuid@users.noreply.github.com"
] | 53719354+AtaSuid@users.noreply.github.com |
d304231a10f67f85485d343cf40ac43453f768f3 | 1e905e3b5db000bfa8a7ffb668af0257d0fee624 | /Raytracer/src/Raytracer/BVH.h | c2c3a0a43f3d03c37d8b27295a04bdfe9e9e1bcf | [] | no_license | agarzonp/Raytracer | db08e6a31a62d4f73c1e9eea623b5a8ddea51e5d | b0ada8b37a40494b233510733b87f337fc56c3da | refs/heads/master | 2021-01-20T09:57:14.636395 | 2017-08-18T17:07:09 | 2017-08-18T17:07:09 | 90,310,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,590 | h | #ifndef BVH_H
#define BVH_H
#include <cassert>
#include "../Geom3D/Geom3D.h"
class BVH : public Geom3D::Shape
{
// pointer to children
std::shared_ptr<Geom3D::Shape> left;
std::shared_ptr<Geom3D::Shape> right;
// is leaf node
bool isLastInBVH = false;
#if PROFILE_HIT_TEST
// tracks the number of hit test done
std::atomic<uint64_t> hitTestCount = 0;
#endif
public:
// build
void Build(std::vector<std::shared_ptr<Geom3D::Shape>>& shapes)
{
// order shapes
std::sort(shapes.begin(), shapes.end(), BVH::SortFunc);
// Recursively Build BVH
RecursivelyBuildBVH(shapes);
}
// calculate AABB
void CalculateAABB()
{
// the bounding box tha contains left and right AABB
auto& leftMin = left->GetAABB().Min();
auto& rightMin = right->GetAABB().Min();
aabb.Min() = glm::vec3(std::fminf(leftMin.x, rightMin.x), std::fminf(leftMin.y, rightMin.y), std::fminf(leftMin.z, rightMin.z));
auto& leftMax = left->GetAABB().Max();
auto& rightMax = right->GetAABB().Max();
aabb.Max() = glm::vec3(std::fmaxf(leftMax.x, rightMax.x), std::fmaxf(leftMax.y, rightMax.y), std::fmaxf(leftMax.z, rightMax.z));
}
// Raycast
bool Raycast(const Geom3D::Ray& ray, float minDistance, float maxDistance, Geom3D::RaycastHit& raycastHit) override
{
#if PROFILE_HIT_TEST
hitTestCount++; // count hit test for current BVH
#endif
// Raycast with children if we only intersect current aabb
float tMin = 0.0f;
float tMax = 0.0f;
if (!aabb.Intersect(ray, tMin, tMax))
{
// No intersection so no need to check children
return false;
}
// Left Raycast
Geom3D::RaycastHit leftRaycastHit;
bool hitLeft = left->Raycast(ray, minDistance, maxDistance, leftRaycastHit);
// Right Raycast
Geom3D::RaycastHit rightRaycastHit;
bool hitRight = right->Raycast(ray, minDistance, maxDistance, rightRaycastHit);
#if PROFILE_HIT_TEST
if (isLastInBVH)
{
// count hit test for leaf children
hitTestCount += 2;
}
#endif
if (hitLeft && hitRight)
{
// return the closest hit
raycastHit = leftRaycastHit.hitDistance < rightRaycastHit.hitDistance ? leftRaycastHit : rightRaycastHit;
return true;
}
if (hitLeft)
{
// return left
raycastHit = leftRaycastHit;
return true;
}
if (hitRight)
{
// return right
raycastHit = rightRaycastHit;
return true;
}
return false;
}
#if PROFILE_HIT_TEST
// Hit test count
void ResetHitTestCount()
{
hitTestCount = 0;
if (!isLastInBVH)
{
auto leftBHV = static_cast<BVH*>(&*left);
leftBHV->ResetHitTestCount();
auto rightBVH = static_cast<BVH*>(&*right);
rightBVH->ResetHitTestCount();
}
}
uint64_t GetHitTestCount()
{
if (isLastInBVH)
{
return hitTestCount;
}
auto leftBHV = static_cast<BVH*>(&*left);
hitTestCount += leftBHV->GetHitTestCount();
auto rightBVH = static_cast<BVH*>(&*right);
hitTestCount += rightBVH->GetHitTestCount();
return hitTestCount;
}
#endif
private:
// Build BVH
void RecursivelyBuildBVH(std::vector<std::shared_ptr<Geom3D::Shape>>& shapes)
{
// Set children
SetChildren(shapes);
// Calculate AABB
CalculateAABB();
}
// Set children
void SetChildren(std::vector<std::shared_ptr<Geom3D::Shape>>& shapes)
{
switch (shapes.size())
{
case 0:
assert(false);
break;
case 1:
// make both point to single shape
left = right = shapes[0];
// flag as the last BV in the hierarchy
isLastInBVH = true;
break;
case 2:
// make the left to point to the first and right to the second
left = shapes[0];
right = shapes[1];
// flag as the last BV in the hierarchy
isLastInBVH = true;
break;
default:
{
// recursively construct a new BVH that holds half of the shapes
unsigned halfShapes = shapes.size() / 2;
std::vector<std::shared_ptr<Geom3D::Shape>> leftShapes;
for (unsigned i = 0; i < halfShapes; i++)
{
leftShapes.emplace_back(shapes[i]);
}
auto& newLeftBHV = std::make_shared<BVH>();
newLeftBHV->Build(leftShapes);
left = newLeftBHV;
std::vector<std::shared_ptr<Geom3D::Shape>> rightShapes;
for (unsigned i = halfShapes; i < shapes.size(); i++)
{
rightShapes.emplace_back(shapes[i]);
}
auto& newRightBHV = std::make_shared<BVH>();
newRightBHV->Build(rightShapes);
right = newRightBHV;
break;
}
}
}
// Shapes Sort function according to AABB min position in X
static bool SortFunc(std::shared_ptr<Geom3D::Shape>& shapeA, std::shared_ptr<Geom3D::Shape>& shapeB)
{
return shapeA->GetAABB().Min().x < shapeB->GetAABB().Min().x;
}
};
#endif // !BVH_H
| [
"agarzonp@gmail.com"
] | agarzonp@gmail.com |
107f9e71ab866cadd1efaa59cbff98b5bf2a489e | 802e3586a5e5b279d713f974e56fc473607b582b | /length_of_longest_subsequence.cpp | a9c4b1b95ee71a78c142ae0d54e22bb80be44a6e | [] | no_license | shresthh/interview-bit-solutions | 66bab43c7a59ab8d715102886c7f9d9c76809161 | 2aa9636ae1ccd3b3f6386dfc9dc07b19423a1c64 | refs/heads/master | 2022-12-02T04:17:17.857375 | 2020-08-15T04:21:55 | 2020-08-15T04:21:55 | 269,831,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 624 | cpp | int Solution::longestSubsequenceLength(const vector<int> &A) {
int n = A.size();
if(n==0){
return 0;
}
vector<int> inc(n,1);
for (int i = 0;i<n;i++){
for(int j=0;j<i;j++){
if(A[j]<A[i]){
inc[i] = max(inc[i], inc[j]+1);
}
}
}
vector<int> dec(n,1);
for (int i = n-1;i>=0;i--){
for(int j = n-1;j>=i;j--){
if(A[j]<A[i]){
dec[i] = max(dec[i], dec[j]+1);
}
}
}
int ans = 0;
for(int i = 0;i<n;i++){
ans = max(ans, (inc[i]+dec[i]-1));
}
return ans;
}
| [
"sumuandmishra@gmail.com"
] | sumuandmishra@gmail.com |
b202261aa050b10641e3848d874b4f28c3d7f6ce | d092b8eb1abe2e5f1940986b708ab140f3818093 | /lab_11/poem.cpp | aca252ad70e14368ed78f3438a309ff203658e1a | [] | no_license | MichelleLucero/CS133 | d8b05f77ee317ea5ae1cb3a94c1d871eebc72473 | 1fc7f4662fd4a88c275fd5c2eb56be868e1a35c8 | refs/heads/master | 2021-09-14T19:43:25.411275 | 2018-05-18T07:54:41 | 2018-05-18T07:54:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 346 | cpp | #include <iostream>
using namespace std;
string * createAPoemDynamically() {
string *p = new string;
*p = "Roses are red, violets are blue";
return p;
}
int main() {
while(true) {
string *p;
p = createAPoemDynamically();
// assume that the poem p is not needed at this point
delete p;
}
} | [
"michelle.lucero07@myhunter.cuny.edu"
] | michelle.lucero07@myhunter.cuny.edu |
b810a0be662150df03f24cc565ee75cf46b28f6f | 9e2dbb3f8205f8bd0b3b5d79261182e9fb4c32c4 | /C codes/november2011/exer_p184_1.cpp | 9442f7345481320efa53fef2b35b5c4cc1883193 | [] | no_license | melody40/monorepo | 87129f934066cd1e162d578f8e4950e12b0fa54d | fc5b7c8da70534e69d55770adebf308fd41c02b7 | refs/heads/master | 2022-12-22T22:49:01.277092 | 2020-09-21T17:20:43 | 2020-09-21T18:35:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cpp | #include <stdio.h>
#include <string.h>
int main (void)
{
int i;
char str[100];
char *p = "stop";
//char bigstr[100];
while ( strcmp(p,str) )
{
gets (str);
//strcat (str,"\n");
//strcat( bigstr,str );
}
//printf (bigstr);
scanf ("%d",&i);
return 0;
}
| [
"torshobuet@gmail.com"
] | torshobuet@gmail.com |
201c9323260bfbca26b48e7436e972f5ea174e64 | a3ed36263839b2c50f39773f6c8c0b8780b0ee30 | /85. Maximal Rectangle.cpp | ad8e462b7e1dce4a47c8ac9a2e69b08e9cfae9bb | [] | no_license | ysyncby/Leetcode | 52c0556f509a4dc157527c160c595d4cb72899ce | 775836d0d91eb08d376220796b09b401199bbcd6 | refs/heads/master | 2021-05-27T02:40:05.682917 | 2019-10-31T03:02:05 | 2019-10-31T03:02:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 877 | cpp | // 第一个solution,效率低。 复杂度为O(mmn)
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int m = matrix.size();
if(m==0)
return 0;
int n = matrix[0].size();
int res = 0;
if(n==0)
return 0;
vector<vector<int>> v(m,vector<int>(n,0));
for(int i=0;i<m;++i){
int count = 0;
for(int j=0;j<n;++j){
if(matrix[i][j]=='0')
count = 0;
else{
v[i][j] = ++count;
int min_len = v[i][j];
for(int k=i;k>=0&&min_len!=0;--k){
min_len = min(v[k][j],min_len);
res = max(res, min_len*(i-k+1));
}
}
}
}
return res;
}
}; | [
"879090429@qq.com"
] | 879090429@qq.com |
5e6ef7cbdd2484faf223edd9403f84fe0f0f7348 | 050c8a810d34fe125aecae582f9adfd0625356c6 | /equality/main.cpp | d693b264b3495912053090c5b3f7972abe216855 | [] | no_license | georgerapeanu/c-sources | adff7a268121ae8c314e846726267109ba1c62e6 | af95d3ce726325dcd18b3d94fe99969006b8e138 | refs/heads/master | 2022-12-24T22:57:39.526205 | 2022-12-21T16:05:01 | 2022-12-21T16:05:01 | 144,864,608 | 11 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | cpp | #include <map>
#include <iostream>
using namespace std;
int val,nr,N,K;
map<int,int> M;
int main() {
cin>>N>>K;
for(int i=1;i<=N;i++){cin>>val;M[val]++;}
while(M.rbegin()->first-M.begin()->first>K)
{
int m=min(M.rbegin()->second,M.begin()->second);
int b=M.rbegin()->first;
int a=M.begin()->first;
M[a+1]+=m;
M[b-1]+=m;
M[a]-=m;
M[b]-=m;
nr+=m;
if(!M[a])M.erase(M.find(a));
if(!M[b])M.erase(M.find(b));
}
cout<<nr;
return 0;
}
| [
"alexandrurapeanu@yahoo.com"
] | alexandrurapeanu@yahoo.com |
bd9ee677245c70520dc31002221aee2136e9f2e1 | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_Carno_AIController_BP_functions.cpp | e2936bd3a7572b97d9abed9c47c5cab686047d9a | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,507 | cpp | // ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Carno_AIController_BP_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function Carno_AIController_BP.Carno_AIController_BP_C.UserConstructionScript
// ()
void ACarno_AIController_BP_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function Carno_AIController_BP.Carno_AIController_BP_C.UserConstructionScript");
ACarno_AIController_BP_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Carno_AIController_BP.Carno_AIController_BP_C.ExecuteUbergraph_Carno_AIController_BP
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void ACarno_AIController_BP_C::ExecuteUbergraph_Carno_AIController_BP(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function Carno_AIController_BP.Carno_AIController_BP_C.ExecuteUbergraph_Carno_AIController_BP");
ACarno_AIController_BP_C_ExecuteUbergraph_Carno_AIController_BP_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
28ebb18d9bdab7d5e9227020a2dbbc8e8df63ac6 | 724c0ee36c0e6262f143d965f2e5f894a31cbb16 | /c,c++/code_148a.cpp | 6ec8057df50b2667a3e95e4bac7241b390b5d11d | [] | no_license | amit-mittal/Programming-Questions-Practice | bf5fe47ba1b074960ad33eb2e525baaf99a85336 | 899995ff49cdf1ef77cc9327feb2fbed7b5c94fe | refs/heads/master | 2021-09-04T15:27:52.569111 | 2018-01-19T21:03:31 | 2018-01-19T21:03:31 | 117,618,138 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cpp | #include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int a[5],i,j,b[100005]={0},p,count=0;
for(i=0;i<5;++i)
{
scanf("%d",&a[i]);
}
for(i=0;i<4;++i)
{
p=a[i];j=1;
while(p<=a[4])
{
b[p]=1;
p+=a[i];
}
}
// cout<<"hi"<<endl;
i=1;
while(i<=a[4])
{
// cout<<i<<endl;
if(b[i]==1)
{
// cout<<i<<endl;
count++;
//cout<<"yay";
}
++i;
// cout<<i<<endl<<a[4]<<endl;
}
cout<<count<<endl;
return 0;
}
| [
"Administrator@Amit-Laptop.fareast.corp.microsoft.com"
] | Administrator@Amit-Laptop.fareast.corp.microsoft.com |
5e0f438f08b65c7cb8d4a3cb6bbe53f9b3c48067 | 6231c877a9f347af0f052f13240e7d8ff221677b | /source/bumpmapshaderclass.cpp | f618b58391717740c0f8e4f1b426e75cab16ae6d | [] | no_license | cozlind/GPUMarchingCubes | 674e2fc9e8939f6a2fa42d9d80ec52a2ad491b4c | 08c107c5c686992c3d14ee9ecd7c98b5cf260582 | refs/heads/master | 2020-05-21T14:32:18.170344 | 2017-03-11T05:04:49 | 2017-03-11T05:04:49 | 84,625,053 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,954 | cpp | ////////////////////////////////////////////////////////////////////////////////
// Filename: bumpmapshaderclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "bumpmapshaderclass.h"
BumpMapShaderClass::BumpMapShaderClass()
{
m_vertexShader = 0;
m_pixelShader = 0;
m_layout = 0;
m_matrixBuffer = 0;
m_sampleState = 0;
m_lightBuffer = 0;
}
BumpMapShaderClass::BumpMapShaderClass(const BumpMapShaderClass& other)
{
}
BumpMapShaderClass::~BumpMapShaderClass()
{
}
bool BumpMapShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
bool result;
// Initialize the vertex and pixel shaders.
result = InitializeShader(device, hwnd, L"./source/bumpmap.vs", L"./source/bumpmap.ps");
if(!result)
{
return false;
}
return true;
}
void BumpMapShaderClass::Shutdown()
{
// Shutdown the vertex and pixel shaders as well as the related objects.
ShutdownShader();
return;
}
bool BumpMapShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix,
D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView* colorTexture, ID3D11ShaderResourceView* normalMapTexture,
D3DXVECTOR3 lightDirection, D3DXVECTOR4 diffuseColor)
{
bool result;
// Set the shader parameters that it will use for rendering.
result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, colorTexture, normalMapTexture,
lightDirection, diffuseColor);
if(!result)
{
return false;
}
// Now render the prepared buffers with the shader.
RenderShader(deviceContext, indexCount);
return true;
}
bool BumpMapShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
HRESULT result;
ID3D10Blob* errorMessage;
ID3D10Blob* vertexShaderBuffer;
ID3D10Blob* pixelShaderBuffer;
D3D11_INPUT_ELEMENT_DESC polygonLayout[5];
unsigned int numElements;
D3D11_BUFFER_DESC matrixBufferDesc;
D3D11_SAMPLER_DESC samplerDesc;
D3D11_BUFFER_DESC lightBufferDesc;
// Initialize the pointers this function will use to null.
errorMessage = 0;
vertexShaderBuffer = 0;
pixelShaderBuffer = 0;
// Compile the vertex shader code.
result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "BumpMapVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS,
0, NULL, &vertexShaderBuffer, &errorMessage, NULL);
if(FAILED(result))
{
// If the shader failed to compile it should have writen something to the error message.
if(errorMessage)
{
OutputShaderErrorMessage(errorMessage, hwnd, vsFilename);
}
// If there was nothing in the error message then it simply could not find the shader file itself.
else
{
MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK);
}
return false;
}
// Compile the pixel shader code.
result = D3DX11CompileFromFile(psFilename, NULL, NULL, "BumpMapPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS,
0, NULL, &pixelShaderBuffer, &errorMessage, NULL);
if(FAILED(result))
{
// If the shader failed to compile it should have writen something to the error message.
if(errorMessage)
{
OutputShaderErrorMessage(errorMessage, hwnd, psFilename);
}
// If there was nothing in the error message then it simply could not find the file itself.
else
{
MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK);
}
return false;
}
// Create the vertex shader from the buffer.
result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL,
&m_vertexShader);
if(FAILED(result))
{
return false;
}
// Create the vertex shader from the buffer.
result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL,
&m_pixelShader);
if(FAILED(result))
{
return false;
}
// Create the vertex input layout description.
// This setup needs to match the VertexType stucture in the ModelClass and in the shader.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
polygonLayout[1].SemanticName = "TEXCOORD";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
polygonLayout[1].InputSlot = 0;
polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[1].InstanceDataStepRate = 0;
polygonLayout[2].SemanticName = "NORMAL";
polygonLayout[2].SemanticIndex = 0;
polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[2].InputSlot = 0;
polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[2].InstanceDataStepRate = 0;
polygonLayout[3].SemanticName = "TANGENT";
polygonLayout[3].SemanticIndex = 0;
polygonLayout[3].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[3].InputSlot = 0;
polygonLayout[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[3].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[3].InstanceDataStepRate = 0;
polygonLayout[4].SemanticName = "BINORMAL";
polygonLayout[4].SemanticIndex = 0;
polygonLayout[4].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[4].InputSlot = 0;
polygonLayout[4].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[4].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[4].InstanceDataStepRate = 0;
// Get a count of the elements in the layout.
numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
// Create the vertex input layout.
result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(),
vertexShaderBuffer->GetBufferSize(), &m_layout);
if(FAILED(result))
{
return false;
}
// Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
vertexShaderBuffer->Release();
vertexShaderBuffer = 0;
pixelShaderBuffer->Release();
pixelShaderBuffer = 0;
// Setup the description of the matrix dynamic constant buffer that is in the vertex shader.
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
// Create the matrix constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer);
if(FAILED(result))
{
return false;
}
// Create a texture sampler state description.
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
// Create the texture sampler state.
result = device->CreateSamplerState(&samplerDesc, &m_sampleState);
if(FAILED(result))
{
return false;
}
// Setup the description of the light dynamic constant buffer that is in the pixel shader.
lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightBufferDesc.ByteWidth = sizeof(LightBufferType);
lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightBufferDesc.MiscFlags = 0;
lightBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = device->CreateBuffer(&lightBufferDesc, NULL, &m_lightBuffer);
if(FAILED(result))
{
return false;
}
return true;
}
void BumpMapShaderClass::ShutdownShader()
{
// Release the light constant buffer.
if(m_lightBuffer)
{
m_lightBuffer->Release();
m_lightBuffer = 0;
}
// Release the sampler state.
if(m_sampleState)
{
m_sampleState->Release();
m_sampleState = 0;
}
// Release the matrix constant buffer.
if(m_matrixBuffer)
{
m_matrixBuffer->Release();
m_matrixBuffer = 0;
}
// Release the layout.
if(m_layout)
{
m_layout->Release();
m_layout = 0;
}
// Release the pixel shader.
if(m_pixelShader)
{
m_pixelShader->Release();
m_pixelShader = 0;
}
// Release the vertex shader.
if(m_vertexShader)
{
m_vertexShader->Release();
m_vertexShader = 0;
}
return;
}
void BumpMapShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename)
{
char* compileErrors;
unsigned long bufferSize, i;
ofstream fout;
// Get a pointer to the error message text buffer.
compileErrors = (char*)(errorMessage->GetBufferPointer());
// Get the length of the message.
bufferSize = errorMessage->GetBufferSize();
// Open a file to write the error message to.
fout.open("shader-error.txt");
// Write out the error message.
for(i=0; i<bufferSize; i++)
{
fout << compileErrors[i];
}
// Close the file.
fout.close();
// Release the error message.
errorMessage->Release();
errorMessage = 0;
// Pop a message up on the screen to notify the user to check the text file for compile errors.
MessageBox(hwnd, L"Error compiling shader. Check shader-error.txt for message.", shaderFilename, MB_OK);
return;
}
bool BumpMapShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix,
D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix,
ID3D11ShaderResourceView* colorTexture, ID3D11ShaderResourceView* normalMapTexture,
D3DXVECTOR3 lightDirection, D3DXVECTOR4 diffuseColor)
{
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
MatrixBufferType* dataPtr;
unsigned int bufferNumber;
LightBufferType* dataPtr2;
// Transpose the matrices to prepare them for the shader.
D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);
// Lock the matrix constant buffer so it can be written to.
result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if(FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr = (MatrixBufferType*)mappedResource.pData;
// Copy the matrices into the constant buffer.
dataPtr->world = worldMatrix;
dataPtr->view = viewMatrix;
dataPtr->projection = projectionMatrix;
// Unlock the matrix constant buffer.
deviceContext->Unmap(m_matrixBuffer, 0);
// Set the position of the matrix constant buffer in the vertex shader.
bufferNumber = 0;
// Now set the matrix constant buffer in the vertex shader with the updated values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);
// Set shader texture resources in the pixel shader.
deviceContext->PSSetShaderResources(0, 1, &colorTexture);
deviceContext->PSSetShaderResources(1, 1, &normalMapTexture);
// Lock the light constant buffer so it can be written to.
result = deviceContext->Map(m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if(FAILED(result))
{
return false;
}
// Get a pointer to the data in the constant buffer.
dataPtr2 = (LightBufferType*)mappedResource.pData;
// Copy the lighting variables into the constant buffer.
dataPtr2->diffuseColor = diffuseColor;
dataPtr2->lightDirection = lightDirection;
// Unlock the constant buffer.
deviceContext->Unmap(m_lightBuffer, 0);
// Set the position of the light constant buffer in the pixel shader.
bufferNumber = 0;
// Finally set the light constant buffer in the pixel shader with the updated values.
deviceContext->PSSetConstantBuffers(bufferNumber, 1, &m_lightBuffer);
return true;
}
void BumpMapShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
{
// Set the vertex input layout.
deviceContext->IASetInputLayout(m_layout);
// Set the vertex and pixel shaders that will be used to render this triangle.
deviceContext->VSSetShader(m_vertexShader, NULL, 0);
deviceContext->PSSetShader(m_pixelShader, NULL, 0);
// Set the sampler state in the pixel shader.
deviceContext->PSSetSamplers(0, 1, &m_sampleState);
// Render the triangles.
deviceContext->DrawIndexed(indexCount, 0, 0);
return;
} | [
"cozlind@live.com"
] | cozlind@live.com |
36c895ebe06e0f27e661353c11b5fa5624b28319 | 974ceae2f770eded62de64a7f7c440e680ffc8c4 | /TextureViewer.h | 5f7a3a15d39f703b38af39d2f1c1569e2f94bfdc | [] | no_license | schinma/OpenGLPrograming | 98d3278e86d643d0c1aeba9bcfad6da166ef6278 | 240e3109d518fbe0ef0e991500bac8d0d3bf1635 | refs/heads/master | 2020-04-28T21:28:12.541075 | 2019-04-21T02:41:23 | 2019-04-21T02:41:23 | 175,577,859 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 886 | h |
#define GLM_ENABLE_EXPERIMENTAL
#ifndef CTEXTUREVIEWER_H
#define CTEXTUREVIEWER_H
#include <iostream>
#include <map>
#include <vector>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Loader.h"
/*
* Simple class, which will render texture on screen
*/
class TextureViewer
{
private:
GLuint texture;
//VBO - don't need EBO, i'll use glDrawArrays()
GLuint VBO;
//VAO - needed for glDrawArrays()
GLuint VAO;
ShaderProgram * s;
//Default shaders
std::string vs;
std::string fs;
bool depth;
void setUpShaders();
public:
TextureViewer();
TextureViewer(GLuint tex, std::string vs, std::string fs);
void draw();
//Setters
void setTexture(GLuint tex);
void setDepthOnly(bool depth);
//Getters
GLuint getTexture();
~TextureViewer();
};
#endif
| [
"marie.schindler@epitech.eu"
] | marie.schindler@epitech.eu |
5ada1006a6d226969e9384df1c89007513b25809 | 2be1c65560f4c4bed67e89739966e48ad49be0d4 | /Libs/AliTools/Make_Folders.h | 0c30e40a75c66d1658a419e7523c2029eae89de9 | [] | no_license | dr-aheydari/Prions-diffus-Rxn | 9c5ff3994cf4b7117138333ca32aaeeb66a5b0c2 | 597c87410c74d5d9511a75466914eab2eabfe03c | refs/heads/master | 2021-06-30T07:22:09.542578 | 2020-12-28T22:29:37 | 2020-12-28T22:29:37 | 207,172,131 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 826 | h | // this will be the header file
// creates folders automatically + textfiles for mass conservations
#ifndef MAKE_FOLDER
#define MAKE_FOLDER
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <sys/uio.h>
#include </Users/aliheydari/stdc++.h>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include<unistd.h>
using namespace std;
void MakeFolder(char hole, char DiffRXN,char DiffOnly,double D_psi, double D_zeta, double gamma_AtoB, double gamma_BtoA, int max_level, int min_level, double tOrder,
string* txtPathA,string* txtPathB,string* daughterPathA,string* daughterPathB,string* motherPathB,string* motherPathA,char* FolderPath,
char initCond, string FullPath,string* Return_FolderPAth);
#endif //MAKE_FOLDER
| [
"aheydari@ucmerced.edu"
] | aheydari@ucmerced.edu |
fb3dbf664eb12801d113458be23a95f6ea38d0a8 | c953d39db64c169dff9b059963af3cf2b9cd725b | /C++/053_Maximum Subarray.cpp | 7523b435854c48f50422a8e6274b43b72b0a97b8 | [] | no_license | ailyanlu1/leetcode-4 | 9eece989a288ce2c278a8b1291e7a4a9202dfb41 | 74c2c950a04f4d0d27639ee2deda869fd7e78734 | refs/heads/master | 2020-03-23T06:25:58.312108 | 2015-09-29T02:51:23 | 2015-09-29T02:51:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | cpp | class Solution {
public:
int maxSubArray(int A[], int n) {
if (n == 0)
return 0;
int res = A[0], sum = A[0];
for (int i = 1; i < n; i++) {
sum = sum < 0 ? 0 : sum;
sum += A[i];
res = max(res, sum);
}
return res;
}
}; | [
"gky2010@bupt.edu.cn"
] | gky2010@bupt.edu.cn |
b5b8afcc546e484190c5505da7c5b65d97a93bfd | f3f0ee4c2cb3d9cfd23c48a40f0fc96e51f8ed5c | /MainFrame4.8.6/SatelliteFrame.h | a84192ae2b3c45a21aa67ac111b5d19c6ee9476d | [] | no_license | cr19891215/VR-SV | 88b959ce55f68b90321ca264d4a36dd236fd2331 | b34cdf4fac6695ce98d06ef74dfcdff2468bd12c | refs/heads/master | 2021-12-29T09:49:40.612250 | 2017-04-06T10:01:49 | 2017-04-06T10:01:49 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 308 | h | #pragma once
#include <QWidget>
#include "ui_SatelliteFrame.h"
class CSatelliteFrame : public QWidget
{
Q_OBJECT
public:
CSatelliteFrame(QWidget* parent = NULL);
~CSatelliteFrame(void);
protected slots:
// ´´½¨µ¯µÀµ¼µ¯
void CreateSatellite(void);
private:
Ui::SatelliteFrame ui;
};
| [
"1405590994@qq.com"
] | 1405590994@qq.com |
25517cc870b3a22b2ff731d908731266e2be21ed | 737a0c2b00621b69c806f151a4a7c9ca5ef23793 | /src/io/archivehandler.cpp | 92471ccb622c6b2d71e26f13568bfd843d819380 | [] | no_license | ABI-Software/capclient | 525219a5d1695f2a60c0a711e1298ef160169ec0 | a4a8fa5a4200a5c6da372d42f6e2961bef14f1d3 | refs/heads/master | 2020-03-18T10:54:53.636926 | 2012-10-12T00:45:35 | 2012-10-12T00:45:35 | 134,640,147 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,893 | cpp |
#include "archivehandler.h"
#include "utils/misc.h"
#include "logmsg.h"
#include "utils/debug.h"
#include <wx/zipstrm.h>
#include <wx/wfstream.h>
#include <wx/mstream.h>
#include <wx/txtstrm.h>
namespace cap
{
class Archive
{
public:
Archive(const std::string& archiveName)
: filename_(archiveName)
{}
virtual ~Archive() {}
virtual int GetTotalEntries() = 0;
virtual ArchiveEntries GetEntries() { return ArchiveEntries(); }
virtual ArchiveEntry GetEntry(const std::string & /* name */) { return ArchiveEntry(); }
protected:
std::string filename_;
};
class ZipArchive : public Archive
{
wxFFileInputStream stream_;
public:
explicit ZipArchive(const std::string& archiveName)
: Archive(archiveName)
, stream_(archiveName.c_str())
{
}
int GetTotalEntries();
ArchiveEntries GetEntries();
ArchiveEntry GetEntry(const std::string &name);
ArchiveEntry ReadEntry(wxZipEntry *entry, wxZipInputStream &zip);
};
int ZipArchive::GetTotalEntries()
{
wxZipInputStream zip(stream_);
return zip.GetTotalEntries();
}
ArchiveEntry ZipArchive::ReadEntry(wxZipEntry* entry, wxZipInputStream& zip)
{
ArchiveEntry ae(entry->GetName().c_str());
if (!entry->IsDir())
{
unsigned long int buf_size = entry->GetSize();
unsigned char *buf = (unsigned char *)malloc(buf_size*(sizeof(unsigned char)));
zip.Read(buf, buf_size);
ae.SetBuffer(buf, buf_size);
}
return ae;
}
ArchiveEntry ZipArchive::GetEntry(const std::string &name)
{
ArchiveEntry got;
wxString internalName = wxZipEntry::GetInternalName(name.c_str());
wxZipInputStream zip(stream_);
wxZipEntry *zipEntry = zip.GetNextEntry();
while (zipEntry != 0 && zipEntry->GetInternalName() != internalName)
{
delete zipEntry;
zipEntry = zip.GetNextEntry();
}
if (zipEntry != 0)
{
got = ReadEntry(zipEntry, zip);
}
return got;
}
ArchiveEntries ZipArchive::GetEntries()
{
ArchiveEntries entries;
wxZipInputStream zip(stream_);
wxZipEntry *entry = zip.GetNextEntry();
while (entry != 0)
{
ArchiveEntry ae = ReadEntry(entry, zip);
entries.push_back(ae);
delete entry;
entry = zip.GetNextEntry();
}
return entries;
}
ArchiveHandler::ArchiveHandler()
{
}
ArchiveHandler::~ArchiveHandler()
{
if (archive_)
delete archive_;
}
void ArchiveHandler::SetArchive(const std::string& archiveName)
{
// Employ complex detection scheme here
if (EndsWith(archiveName, ".zip"))
archive_ = new ZipArchive(archiveName);
else
LOG_MSG(LOGWARNING) << "Did not detect archive type for archive : " << archiveName;
}
int ArchiveHandler::GetTotalEntries()
{
if (archive_)
return archive_->GetTotalEntries();
return 0;
}
ArchiveEntries ArchiveHandler::GetEntries()
{
if (archive_)
return archive_->GetEntries();
return ArchiveEntries();
}
ArchiveEntry ArchiveHandler::GetEntry(const std::string &name)
{
if (archive_)
return archive_->GetEntry(name);
return ArchiveEntry();
}
}
| [
"h.sorby@auckland.ac.nz"
] | h.sorby@auckland.ac.nz |
a75fa347991e8fa590e6349e0d1b8447eb3604eb | 7e840c18856256a17a6691da86920025e0e91fda | /JD1052(AC).cpp | e972444f25729cbaa2661f74547f7eb1862014f7 | [] | no_license | stevencoding/jobduoj | 4cb981abf20b793f27fdd52ce1c7fe5907c31d2c | 097fe66ed1321767cf8f8eed5087deb126650e77 | refs/heads/master | 2020-02-26T14:21:40.874783 | 2015-04-27T18:45:57 | 2015-04-27T18:45:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | cpp | #include <cstdio>
using namespace std;
int main()
{
const int MAXN = 205;
int a[MAXN];
int n;
int i;
int x;
while (scanf("%d", &n) == 1) {
for (i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
scanf("%d", &x);
for (i = 0; i < n; ++i) {
if (a[i] == x) {
break;
}
}
printf("%d\n", (i < n ? i : -1));
}
return 0;
} | [
"zhuli19901106@gmail.com"
] | zhuli19901106@gmail.com |
65384a84a816f4723fe0245972b179f474fc92ef | 911729e019762ed93b14f49d19c1b7d817c29af6 | /include/toolv568alg/isp.h | 2f93702cbaa072eb7aa125ad1c74989441a7e4ca | [] | no_license | JackBro/DragonVer1.0 | 59590809df749540f70b904f83c4093890031fbb | 31b3a97f2aa4a66d2ee518b8e6ae4245755009b1 | refs/heads/master | 2020-06-19T21:02:17.248852 | 2014-05-08T02:19:33 | 2014-05-08T02:19:33 | 74,833,772 | 0 | 1 | null | 2016-11-26T15:29:10 | 2016-11-26T15:29:10 | null | UTF-8 | C++ | false | false | 8,646 | h | #ifndef _CMODEL_ISP_ALG_H_
#define _CMODEL_ISP_ALG_H_
#ifndef _WINDLL
#define TOOLV568ALG_DLL
#endif
#ifndef TOOLV568ALG_DLL
#define TOOLV568ALG_DLL __declspec(dllimport)
#endif
//
// use "COM" conception later to modify cmodel
//
enum ISPCONTROLenum
{
TESTBAR = BIT0,
BLACKLEVEL = BIT1,
LENSFALLOFF = BIT2,
DPDDPC = BIT3,
DIGITALGAIN = BIT4,
CFAEXTRACT = BIT5,
COLORCORRECT = BIT6,
GAMMACORRECT = BIT7,
EDGEENHANCE = BIT8
};
static inline int InverseBit(int x)
{
return x ? 0 : 1;
}
//=============== class CIspModule =================
class TOOLV568ALG_DLL CIspModule : public CBaseObject
{
public:
CIspModule(int width, int height, int unit);
int Process(char *src, char *dst);
protected:
//virtual int Read(char *buf, int len);
//virtual int Write(char *buf, int len);
public:
void SetIspCtrl(int ctrl);
int GetIspCtrl(void);
void SetBGLine(int bgline);
int GetBGLine(void);
void SetGpixel(int gpixel);
int GetGpixel(void);
void SetIspModuleEn(int flag, int en);
private:
int ispctrl;
int bgline;
int gpixel;
int m_width;
int m_height;
int m_unit;
};
//=============== class CIspTestBar =================
class TOOLV568ALG_DLL CIspTestBar : public CBaseObject
{
public:
CIspTestBar();
public:
virtual int Read(char *buf, int len);
virtual int Write(char *buf, int len);
};
//=============== class CIspBlackLevel =================
class TOOLV568ALG_DLL CIspBlackLevel : public CBaseObject
{
public:
CIspBlackLevel(int width, int height, int unit);
public:
int Process(char *src, char *dst);
protected:
virtual int Read(char *buf, int len); //len = width
virtual int Write(char *buf, int len); //len = width
public:
void SetROffset(int roffset);
void SetG1Offset(int g1offset);
void SetG2Offset(int g2offset);
void SetBOffset(int boffset);
int GetROffset(void);
int GetG1Offset(void);
int GetG2Offset(void);
int GetBOffset(void);
void SetBGLine(int bgline);
int GetBGLine(void);
void SetGpixel(int gpixel);
int GetGpixel(void);
private:
CLineBayerBuf m_Linebuf;
int m_width;
int m_height;
int m_unit;
int m_rOffset;
int m_g1Offset;
int m_g2Offset;
int m_bOffset;
int m_bgline;
int m_gpixel;
};
//=============== class CIspLensFallOff ================
class TOOLV568ALG_DLL CIspLensFallOff : public CBaseObject
{
public:
CIspLensFallOff(int width, int height, int unit);
public:
int Process(char *src, char *dst);
protected:
virtual int Read(char *buf, int len);
virtual int Write(char *buf, int len);
int GetLensX(void);
int GetLensY(void);
int GetLensFocus(void);
void SetLensX(int x);
void SetLensY(int y);
void SetLensFocus(int f);
private:
CLineBayerBuf m_Linebuf;
int m_lensCx; //0-11bit
int m_lensCy; //0-11bit
int m_lensFocus; //0-12bit
int m_unit;
int m_line;
int m_width;
int m_height;
};
//============== class CIspDpdDpc ========================
#define LAST3X3LINES BIT6
class TOOLV568ALG_DLL CIspDpdDpc : public CBaseObject
{
public:
CIspDpdDpc(int width, int height, int unit);
int Process(char *src, char *dst);
protected:
virtual int Read(char *buf, int len);
virtual int Write(char *buf, int len);
int DpdProcess(char *buf, int len);
int GetDpdNoise(int *p, int gpixel);
int GetNoiseValue(int p, int gpixel);
void LastLinePro(void);
void LoopLinebuf(void);
public:
void SetBGLine(int bgline);
int GetBGLine(void);
void SetGpixel(int gpixel);
int GetGpixel(void);
void SetDpdThd(int thd);
int GetDpdThd(void);
void SetNoiseTable(int *val);
int* GetNoiseTable(void);
private:
int m_width;
int m_height;
int m_line;
int m_unit;
int m_pos;
int m_bgline;
int m_gpixel;
int m_dpdthd;
int m_noisetable[17];
CLineBayerBuf m_Linebuf[5];
CLineBayerBuf *m_pLinebuf[5];
};
//============== class CIspDigitalGain ========================
class TOOLV568ALG_DLL CIspDigitalGain : public CBaseObject
{
public:
CIspDigitalGain(int width, int height, int unit);
public:
int Process(char *src, char *dst);
protected:
virtual int Read(char *buf, int len);
virtual int Write(char *buf, int len);
public:
void SetBGLine(int bgline);
int GetBGLine(void);
void SetGpixel(int gpixel);
int GetGpixel(void);
void SetGlobalGain(int gain);
int GetGlobalGain(void);
void SetRGain(int gain);
int GetRGain(void);
void SetGGain(int gain);
int GetGGain(void);
void SetBGain(int gain);
int GetBGain(void);
void SetGlobalEn(int val);
void SetRgbEn(int val);
void SetGainStep(int step);
int GetGainStep(void);
private:
CLineBayerBuf m_Linebuf;
int m_line;
int m_unit;
int m_width;
int m_height;
int m_bgline;
int m_gpixel;
int m_globalEn;
int m_rgbEn;
int m_globalGain;
int m_gainStep;
int m_rGain;
int m_gGain;
int m_bGain;
};
//============== class CIspCfaExtract ========================
#define LAST5X5LINES BIT6
class TOOLV568ALG_DLL CIspCfaExtract : public CBaseObject
{
public:
CIspCfaExtract(int width, int height, int mode, int unit = 1);
int Process(char *src, char *dst);
public:
virtual void SetSize(int width, int height, int unit = 1);
virtual void SetOrder(int order);
void SetMode(int mode);
int GetMode(void);
void SetFemm(int femm);
int GetFemm(void);
void SetFemp(int femp);
int GetFemp(void);
void SetFemmin(int femmin);
int GetFemmin(void);
void SetFemmax(int femmax);
int GetFemmax(void);
void SetFemx1(int femx1);
int GetFemx1(void);
void SetFemx2(int femx2);
int GetFemx2(void);
protected:
virtual int Read(char *buf, int len);
virtual int Write(char *buf, int len);
virtual void Clear(void);
virtual void GetFirstGblock(void);
virtual void GetNextGblock(void);
virtual void LastLinePro(void);
virtual void LoopLinebuf(void);
virtual int Interpolate(char *buf, int len);
virtual int GetGpixel(int col, int row);
virtual int GetRfromBG(int pos);
virtual int GetRfromGR(int pos);
virtual int GetRfromGB(int pos);
virtual int GetEdge(void);
private:
int m_mode; //1:edge or 0:interpolate
//interpolate
CLineBayerBuf *m_pLinebuf[9];
CLineBayerBuf m_Linebuf[9];
int m_Gblock[5][5];
int *m_pGblock[5];
int m_line, m_pos;
int m_unit, m_width, m_height;
int m_Gfirst, m_GBline;
//edge extract
int m_femm, m_femp, m_femmin, m_femmax, m_femx1, m_femx2;
};
//============== class CIspColorCorrect ========================
class TOOLV568ALG_DLL CIspColorCorrect : public CBaseObject
{
public:
CIspColorCorrect(int width, int height, int unit);
int Process(char *src, char *dst);
protected:
virtual int Read(char *buf, int len);
virtual int Write(char *buf, int len);
public:
void SetColorMatrix(int *p);
void SetColorOffset(int *p);
private:
int m_colormatrix[3][3];
int m_offset[3];
int m_width, m_height, m_unit;
int m_r, m_g, m_b;
};
//============== class CIspGammaCorrect ========================
class TOOLV568ALG_DLL CIspGammaCorrect : public CBaseObject
{
public:
CIspGammaCorrect(int width, int height, int unit, int enable = 1);
int Process(char *src, char *dst);
protected:
virtual int Read(char *buf, int len);
virtual int Write(char *buf, int len);
void GammaCorrect(char *buf);
int GetGammaValue(int val, int rgb);
public:
void SetRGamma(int *p);
int* GetRGamma(void);
void SetGGamma(int *p);
int* GetGGamma(void);
void SetBGamma(int *p);
int* GetBGamma(void);
private:
int m_rgamma[17];
int m_ggamma[17];
int m_bgamma[17];
int m_unit;
int m_width;
int m_height;
int m_r;
int m_g;
int m_b;
int m_enable; //1: enable gamma 0:disable gamma,just cut lower 2 bit
};
//============== class CIspColorConvert ========================
class TOOLV568ALG_DLL CIspColorConvert : public CBaseObject
{
public:
CIspColorConvert(int width, int height);
int Process(char *src, char *dst);
protected:
virtual int Read(char *buf, int len);
virtual int Write(char *buf, int len);
private:
int m_width;
int m_height;
int m_r[2], m_g[2], m_b[2];
};
//============== class CIspEdgeEnhance ========================
class TOOLV568ALG_DLL CIspEdgeEnhance : public CBaseObject
{
public:
CIspEdgeEnhance(int width, int height);
int Process(char *src, char *edge, char *dst);
protected:
virtual int Read(char *buf, int len);
virtual int Write(char *buf, char *edge, int len);
private:
int m_width;
int m_height;
int m_y;
int m_uv;
int m_edge;
};
#endif
| [
"ranger.su@gmail.com"
] | ranger.su@gmail.com |
b6ee4e8cec023a39a04954051c25182ce140886f | cc43a5f5954cf17b46d08ae449ff16d5e063264f | /xybot.ino | 4fd0f1c0cbc722356548cba451c7eef20cc1ff0e | [] | no_license | RolandJuno/xybot | 553c3c89440cef5055815e74925f6a7ae5f16d95 | e0d7f7b7cd7acd8ad809268f7edd0a2a6a0d31a2 | refs/heads/master | 2016-09-12T22:49:52.888179 | 2016-04-19T23:49:30 | 2016-04-19T23:49:30 | 56,639,503 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,908 | ino | // https://github.com/Makeblock-official/mDrawBot/blob/master/firmwares/xybot/xybot.ino
// Feb 29, 2016
// Needs these libraries:
// https://github.com/Makeblock-official/Makeblock-Libraries
#include <MeOrion.h>
#include <EEPROM.h>
#include <SoftwareSerial.h>
#include <Wire.h>
// data stored in eeprom
static union{
struct{
char name[8];
unsigned char motoADir;
unsigned char motoBDir;
unsigned char motorSwitch;
int height;
int width;
int speed;
int penUpPos;
int penDownPos;
}data;
char buf[64];
}roboSetup;
// arduino only handle A,B step mapping
float curSpd,tarSpd; // speed profile
float curX,curY,curZ;
float tarX,tarY,tarZ; // target xyz position
// step value
int tarA,tarB,posA,posB; // target stepper position
int8_t motorAfw,motorAbk;
int8_t motorBfw,motorBbk;
MePort stpA(PORT_1);
MePort stpB(PORT_2);
MePort ylimit(PORT_3);
int ylimit_pin1 = ylimit.pin1(); //limit 2
int ylimit_pin2 = ylimit.pin2(); //limit 1
MePort xlimit(PORT_6);
int xlimit_pin1 = xlimit.pin1(); //limit 4
int xlimit_pin2 = xlimit.pin2(); //limit 3
long last_time;
MeDCMotor laser(M2);
MePort servoPort(PORT_7);
int servopin = servoPort.pin2();
Servo servoPen;
int penState = 0; // 0 for up, 1 for down (draw)
/************** motor movements ******************/
void stepperMoveA(int dir) {
//Serial.print('A');Serial.println(dir);
if (dir>0) {
stpA.dWrite1(LOW);
} else {
stpA.dWrite1(HIGH);
}
stpA.dWrite2(HIGH);
stpA.dWrite2(LOW);
}
void stepperMoveB(int dir) {
//Serial.print('B');Serial.println(dir);
if(dir>0) {
stpB.dWrite1(LOW);
} else {
stpB.dWrite1(HIGH);
}
stpB.dWrite2(HIGH);
stpB.dWrite2(LOW);
}
/************** calculate movements ******************/
//#define STEPDELAY_MIN 200 // micro second
//#define STEPDELAY_MAX 1000
long stepAuxDelay=0;
int stepdelay_min=200;
int stepdelay_max=200;
#define ACCELERATION 2 // mm/s^2 don't get inertia exceed motor could handle
#define SEGMENT_DISTANCE 10 // 1 mm for each segment
int SPEED_STEP=0;
void doMove() {
// Move faster
if (penState == 0) {
stepdelay_min = 25;
stepdelay_max = 500; // was 20*10
SPEED_STEP=1; // ramp speed up/down
}
// Plot/engrave slower
if (penState == 1) {
stepdelay_min = (100-roboSetup.data.speed)*75; // was 150*10
stepdelay_max = (100-roboSetup.data.speed)*75;
SPEED_STEP=0; // constant speed
}
long mDelay=stepdelay_max;
long temp_delay;
int speedDiff = -SPEED_STEP;
int dA,dB,maxD;
float stepA,stepB,cntA=0,cntB=0;
int d;
dA = tarA - posA;
dB = tarB - posB;
maxD = max(abs(dA),abs(dB));
stepA = (float)abs(dA)/(float)maxD;
stepB = (float)abs(dB)/(float)maxD;
//Serial.print("tarA:");
//Serial.print(tarA);
//Serial.print(" ,tarB:");
//Serial.println(tarB);
//Serial.printf("move: max:%d da:%d db:%d\n",maxD,dA,dB);
//Serial.print(stepA);Serial.print(' ');Serial.println(stepB);
for(int i=0; (posA!=tarA)||(posB!=tarB); i++){ // Robbo1 2015/6/8 Changed - change loop terminate test to test for moving not finished rather than a preset amount of moves
//Serial.printf("step %d A:%d B;%d tar:%d %d\n",i,posA,posB,tarA,tarB);
// move A
if (posA!=tarA) {
cntA+=stepA;
if (cntA>=1) {
d = dA>0?motorAfw:motorAbk;
posA+=(dA>0?1:-1);
stepperMoveA(d);
cntA-=1;
}
}
// move B
if (posB!=tarB) {
cntB+=stepB;
if (cntB>=1) {
d = dB>0?motorBfw:motorBbk;
posB+=(dB>0?1:-1);
stepperMoveB(d);
cntB-=1;
}
}
mDelay=constrain(mDelay+speedDiff,stepdelay_min,stepdelay_max);
temp_delay = mDelay + stepAuxDelay;
if (millis() - last_time > 400) {
//Serial.print("posA:");
//Serial.print(posA);
//Serial.print(" ,posB:");
//Serial.println(posB);
last_time = millis();
if(true == process_serial()) {
return;
}
}
if (temp_delay > stepdelay_max) {
temp_delay = stepAuxDelay;
delay(temp_delay/1000);
delayMicroseconds(temp_delay%1000);
} else {
delayMicroseconds(temp_delay);
}
if((maxD-i)<((stepdelay_max-stepdelay_min)/SPEED_STEP)){
speedDiff=SPEED_STEP;
}
}
//Serial.printf("finally %d A:%d B;%d\n",maxD,posA,posB);
posA = tarA;
posB = tarB;
}
/******** mapping xy position to steps ******/
#define STEPS_PER_CIRCLE 3200.0f
#define WIDTH 380
#define HEIGHT 310
#define DIAMETER 11 // the diameter of stepper wheel
//#define STEPS_PER_MM (STEPS_PER_CIRCLE/PI/DIAMETER)
#define STEPS_PER_MM 87.58 // the same as 3d printer
void prepareMove() {
float dx = tarX - curX;
float dy = tarY - curY;
float distance = sqrt(dx*dx+dy*dy);
//Serial.print("distance=");Serial.println(distance);
if (distance < 0.001)
return;
tarA = tarX*STEPS_PER_MM;
tarB = tarY*STEPS_PER_MM;
//Serial.print("tarL:");Serial.print(tarL);Serial.print(' ');Serial.print("tarR:");Serial.println(tarR);
//Serial.print("curL:");Serial.print(curL);Serial.print(' ');Serial.print("curR:");Serial.println(curR);
//Serial.printf("tar Pos %ld %ld\r\n",tarA,tarB);
doMove();
curX = tarX;
curY = tarY;
}
void goHome() {
// stop on either endstop touches
while(digitalRead(ylimit_pin2)==1 && digitalRead(ylimit_pin1)==1){
stepperMoveB(motorBbk);
//delayMicroseconds(stepdelay_min);
delayMicroseconds(200);
}
while(digitalRead(xlimit_pin2)==1 && digitalRead(xlimit_pin1)==1){
stepperMoveA(motorAbk);
//delayMicroseconds(stepdelay_min);
delayMicroseconds(200);
}
// Serial.println("goHome!");
posA = 0;
posB = 0;
curX = 0;
curY = 0;
tarX = 0;
tarY = 0;
tarA = 0;
tarB = 0;
}
void initPosition() {
curX=0; curY=0;
posA = 0;posB = 0;
}
/************** calculate movements ******************/
void parseCordinate(char * cmd) {
char * tmp;
char * str;
str = strtok_r(cmd, " ", &tmp);
tarX = curX;
tarY = curY;
while(str!=NULL){
str = strtok_r(0, " ", &tmp);
if(str[0]=='X'){
tarX = atof(str+1);
}else if(str[0]=='Y'){
tarY = atof(str+1);
}else if(str[0]=='Z'){
tarZ = atof(str+1);
}else if(str[0]=='F'){
float speed = atof(str+1);
tarSpd = speed/60; // mm/min -> mm/s
}else if(str[0]=='A'){
stepAuxDelay = atol(str+1);
}
}
// Serial.print("tarX:");
// Serial.print(tarX);
// Serial.print(", tarY:");
// Serial.print(tarY);
// Serial.print(", stepAuxDelay:");
// Serial.println(stepAuxDelay);
prepareMove();
}
void echoRobotSetup() {
Serial.print("M10 XY ");
Serial.print(roboSetup.data.width);Serial.print(' ');
Serial.print(roboSetup.data.height);Serial.print(' ');
Serial.print(curX);Serial.print(' ');
Serial.print(curY);Serial.print(' ');
Serial.print("A");Serial.print((int)roboSetup.data.motoADir);
Serial.print(" B");Serial.print((int)roboSetup.data.motoBDir);
Serial.print(" H");Serial.print((int)roboSetup.data.motorSwitch);
Serial.print(" S");Serial.print((int)roboSetup.data.speed);
Serial.print(" U");Serial.print((int)roboSetup.data.penUpPos);
Serial.print(" D");Serial.println((int)roboSetup.data.penDownPos);
}
void echoEndStop()
{
Serial.print("M11 ");
Serial.print(digitalRead(ylimit_pin2)); Serial.print(" ");
Serial.print(digitalRead(ylimit_pin1)); Serial.print(" ");
Serial.print(digitalRead(xlimit_pin2)); Serial.print(" ");
Serial.println(digitalRead(xlimit_pin1));
}
void syncRobotSetup()
{
int i;
for(i=0;i<64;i++){
EEPROM.write(i,roboSetup.buf[i]);
}
}
void parseRobotSetup(char * cmd)
{
char * tmp;
char * str;
str = strtok_r(cmd, " ", &tmp);
while(str!=NULL){
str = strtok_r(0, " ", &tmp);
if(str[0]=='A'){
roboSetup.data.motoADir = atoi(str+1);
}else if(str[0]=='B'){
roboSetup.data.motoBDir = atoi(str+1);
}else if(str[0]=='H'){
roboSetup.data.height = atoi(str+1);
}else if(str[0]=='W'){
roboSetup.data.width = atoi(str+1);
}else if(str[0]=='S'){
roboSetup.data.speed = atoi(str+1);
}
}
syncRobotSetup();
}
void parseAuxDelay(char * cmd)
{
char * tmp;
strtok_r(cmd, " ", &tmp);
stepAuxDelay = atol(tmp);
}
void parseLaserPower(char * cmd)
{
char * tmp;
strtok_r(cmd, " ", &tmp);
int pwm = atoi(tmp);
laser.run(pwm);
if (pwm) {
penState = 1;
} else {
penState = 0;
}
}
void parsePen(char * cmd)
{
char * tmp;
strtok_r(cmd, " ", &tmp);
int pos = atoi(tmp);
servoPen.write(pos);
// If pen pos doesn't match stored up/down settings, penState
// is not changed and remains what it was previously.
// If you change the up/down settings, save before continuing.
if (pos == roboSetup.data.penUpPos) {
penState = 0;
}
if (pos == roboSetup.data.penDownPos) {
penState = 1;
}
}
void parsePenPosSetup(char * cmd)
{
char * tmp;
char * str;
str = strtok_r(cmd, " ", &tmp);
while(str!=NULL){
str = strtok_r(0, " ", &tmp);
if(str[0]=='U'){
roboSetup.data.penUpPos = atoi(str+1);
penState = 0;
}else if(str[0]=='D'){
roboSetup.data.penDownPos = atoi(str+1);
penState = 1;
}
}
//Serial.printf("M2 U:%d D:%d\r\n",roboSetup.data.penUpPos,roboSetup.data.penDownPos);
syncRobotSetup();
}
void parseMcode(char * cmd)
{
int code;
code = atoi(cmd);
switch(code){
case 1:
parsePen(cmd);
break;
case 2: // set pen position
parsePenPosSetup(cmd);
break;
case 3:
parseAuxDelay(cmd);
break;
case 4:
parseLaserPower(cmd);
break;
case 5:
parseRobotSetup(cmd);
break;
case 10:
echoRobotSetup();
break;
case 11:
echoEndStop();
break;
}
}
void parseGcode(char * cmd)
{
int code;
code = atoi(cmd);
switch(code){
case 0:
case 1: // xyz move
parseCordinate(cmd);
break;
case 28: // home
stepAuxDelay = 0;
tarX=0; tarY=0;
servoPen.write(roboSetup.data.penUpPos);
laser.run(0);
goHome();
break;
}
}
void parseCmd(char * cmd)
{
if(cmd[0]=='G'){ // gcode
parseGcode(cmd+1);
}else if(cmd[0]=='M'){ // mcode
parseMcode(cmd+1);
}else if(cmd[0]=='P'){
Serial.print("POS X");Serial.print(curX);Serial.print(" Y");Serial.println(curY);
}
Serial.println("OK");
}
// local data
void initRobotSetup()
{
int i;
//Serial.println("read eeprom");
for(i=0;i<64;i++){
roboSetup.buf[i] = EEPROM.read(i);
//Serial.print(roboSetup.buf[i],16);Serial.print(' ');
}
//Serial.println();
if(strncmp(roboSetup.data.name,"XY4",3)!=0){
Serial.println("set to default setup");
// set to default setup
memset(roboSetup.buf,0,64);
memcpy(roboSetup.data.name,"XY4",3);
// default connection move inversely
roboSetup.data.motoADir = 0;
roboSetup.data.motoBDir = 0;
roboSetup.data.width = WIDTH;
roboSetup.data.height = HEIGHT;
roboSetup.data.motorSwitch = 0;
roboSetup.data.speed = 80;
roboSetup.data.penUpPos = 160;
roboSetup.data.penDownPos = 90;
syncRobotSetup();
}
// init motor direction
// yzj, match to standard connection of xy
// A = x, B = y
if(roboSetup.data.motoADir==0){
motorAfw=-1;motorAbk=1;
}else{
motorAfw=1;motorAbk=-1;
}
if(roboSetup.data.motoBDir==0){
motorBfw=-1;motorBbk=1;
}else{
motorBfw=1;motorBbk=-1;
}
int spd = 100 - roboSetup.data.speed;
//stepdelay_min = spd*10;
//stepdelay_max = spd*10;
}
/************** arduino ******************/
void setup() {
pinMode(ylimit_pin1,INPUT_PULLUP);
pinMode(ylimit_pin2,INPUT_PULLUP);
pinMode(xlimit_pin1,INPUT_PULLUP);
pinMode(xlimit_pin2,INPUT_PULLUP);
Serial.begin(115200);
initRobotSetup();
initPosition();
servoPen.attach(servopin);
delay(100);
servoPen.write(roboSetup.data.penUpPos);
laser.run(0);
}
char buf[64];
int8_t bufindex;
boolean process_serial(void)
{
boolean result = false;
memset(buf,0,64);
bufindex = 0;
while(Serial.available()){
char c = Serial.read();
buf[bufindex++]=c;
if(c=='\n'){
buf[bufindex]='\0';
parseCmd(buf);
result = true;
memset(buf,0,64);
bufindex = 0;
}
if(bufindex>=64){
bufindex=0;
}
}
return result;
}
void loop() {
if(Serial.available()){
char c = Serial.read();
buf[bufindex++]=c;
if(c=='\n'){
buf[bufindex]='\0'; // Robbo1 2015/6/8 Add - Null terminate the string - Essential for first use of 'buf' and good programming practice
parseCmd(buf);
memset(buf,0,64);
bufindex = 0;
}
if(bufindex>=64){
bufindex=0;
}
}
// Serial.print(digitalRead(xlimit_pin1));Serial.print(' ');
// Serial.print(digitalRead(xlimit_pin2));Serial.print(' ');
// Serial.print(digitalRead(ylimit_pin1));Serial.print(' ');
// Serial.print(digitalRead(ylimit_pin2));Serial.println();
}
| [
"rickards@Matisste.home"
] | rickards@Matisste.home |
e8b2861e8ecd0563e84fee4cf1c4b246e5cc4e15 | 381d826b5755eed326c0002ff9836559195eba28 | /URI PROBS/1070.cpp | 07d06a848d5225d014e17063968c0ca14e08518e | [] | no_license | tanvieer/ProblemSolving | 79b491ee9dbfab5989efe0cbd4b206729ddc872b | a538b4e67cc7dd110650d88bc7439eade7e16210 | refs/heads/master | 2021-01-23T04:30:15.539121 | 2017-03-28T15:33:27 | 2017-03-28T15:33:27 | 86,206,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 162 | cpp | #include <iostream>
using namespace std;
int main(){
int n,i;
cin>>n;
if (n%2== 0)
n++;
for (i=0;i<=5;i++,n+=2)
cout<<n<<endl;
}
| [
"tanvieer@gmail.com"
] | tanvieer@gmail.com |
830e884307a2910825e11106b18914f3607dfa4a | 498de85c7a914e7ca26f2045a32a3cb16bb80063 | /DribbbleViewer/Pods/Realm/include/realm/array.hpp | 826e9173c9fa5a98ed7151e32cc452e7b000e203 | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0",
"LicenseRef-scancode-commercial-license",
"MIT"
] | permissive | mendesbarreto/IOS | 986217d8a5526b7991fda0931d3323c9f21c2dec | e215e528b94ccd4a2bc3de6c1ade814fa4f76b21 | refs/heads/master | 2023-01-09T06:01:16.930586 | 2016-03-06T01:06:56 | 2016-03-06T01:06:56 | 48,437,824 | 1 | 0 | MIT | 2022-12-27T00:34:22 | 2015-12-22T14:56:18 | C++ | UTF-8 | C++ | false | false | 143,470 | hpp | /*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
/*
Searching: The main finding function is:
template<class cond, Action action, size_t bitwidth, class Callback>
void find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState *state, Callback callback) const
cond: One of Equal, NotEqual, Greater, etc. classes
Action: One of act_ReturnFirst, act_FindAll, act_Max, act_CallbackIdx, etc, constants
Callback: Optional function to call for each search result. Will be called if action == act_CallbackIdx
find() will call find_action_pattern() or find_action() that again calls match() for each search result which optionally calls callback():
find() -> find_action() -------> bool match() -> bool callback()
| ^
+-> find_action_pattern()----+
If callback() returns false, find() will exit, otherwise it will keep searching remaining items in array.
*/
#ifndef REALM_ARRAY_HPP
#define REALM_ARRAY_HPP
#include <cmath>
#include <cstdlib> // size_t
#include <algorithm>
#include <utility>
#include <vector>
#include <ostream>
#include <stdint.h> // unint8_t etc
#include <realm/util/meta.hpp>
#include <realm/util/assert.hpp>
#include <realm/util/file_mapper.hpp>
#include <realm/utilities.hpp>
#include <realm/alloc.hpp>
#include <realm/string_data.hpp>
#include <realm/query_conditions.hpp>
#include <realm/column_fwd.hpp>
/*
MMX: mmintrin.h
SSE: xmmintrin.h
SSE2: emmintrin.h
SSE3: pmmintrin.h
SSSE3: tmmintrin.h
SSE4A: ammintrin.h
SSE4.1: smmintrin.h
SSE4.2: nmmintrin.h
*/
#ifdef REALM_COMPILER_SSE
# include <emmintrin.h> // SSE2
# include <realm/realm_nmmintrin.h> // SSE42
#endif
namespace realm {
enum Action {act_ReturnFirst, act_Sum, act_Max, act_Min, act_Count, act_FindAll, act_CallIdx, act_CallbackIdx,
act_CallbackVal, act_CallbackNone, act_CallbackBoth, act_Average};
template<class T>
inline T no0(T v) { return v == 0 ? 1 : v; }
/// Special index value. It has various meanings depending on
/// context. It is returned by some search functions to indicate 'not
/// found'. It is similar in function to std::string::npos.
const size_t npos = size_t(-1);
// Maximum number of bytes that the payload of an array can be
const size_t max_array_payload = 0x00ffffffL;
/// Alias for realm::npos.
const size_t not_found = npos;
/* wid == 16/32 likely when accessing offsets in B tree */
#define REALM_TEMPEX(fun, wid, arg) \
if (wid == 16) {fun<16> arg;} \
else if (wid == 32) {fun<32> arg;} \
else if (wid == 0) {fun<0> arg;} \
else if (wid == 1) {fun<1> arg;} \
else if (wid == 2) {fun<2> arg;} \
else if (wid == 4) {fun<4> arg;} \
else if (wid == 8) {fun<8> arg;} \
else if (wid == 64) {fun<64> arg;} \
else {REALM_ASSERT_DEBUG(false); fun<0> arg;}
#define REALM_TEMPEX2(fun, targ, wid, arg) \
if (wid == 16) {fun<targ, 16> arg;} \
else if (wid == 32) {fun<targ, 32> arg;} \
else if (wid == 0) {fun<targ, 0> arg;} \
else if (wid == 1) {fun<targ, 1> arg;} \
else if (wid == 2) {fun<targ, 2> arg;} \
else if (wid == 4) {fun<targ, 4> arg;} \
else if (wid == 8) {fun<targ, 8> arg;} \
else if (wid == 64) {fun<targ, 64> arg;} \
else {REALM_ASSERT_DEBUG(false); fun<targ, 0> arg;}
#define REALM_TEMPEX3(fun, targ1, targ2, wid, arg) \
if (wid == 16) {fun<targ1, targ2, 16> arg;} \
else if (wid == 32) {fun<targ1, targ2, 32> arg;} \
else if (wid == 0) {fun<targ1, targ2, 0> arg;} \
else if (wid == 1) {fun<targ1, targ2, 1> arg;} \
else if (wid == 2) {fun<targ1, targ2, 2> arg;} \
else if (wid == 4) {fun<targ1, targ2, 4> arg;} \
else if (wid == 8) {fun<targ1, targ2, 8> arg;} \
else if (wid == 64) {fun<targ1, targ2, 64> arg;} \
else {REALM_ASSERT_DEBUG(false); fun<targ1, targ2, 0> arg;}
#define REALM_TEMPEX4(fun, targ1, targ2, wid, targ3, arg) \
if (wid == 16) {fun<targ1, targ2, 16, targ3> arg;} \
else if (wid == 32) {fun<targ1, targ2, 32, targ3> arg;} \
else if (wid == 0) {fun<targ1, targ2, 0, targ3> arg;} \
else if (wid == 1) {fun<targ1, targ2, 1, targ3> arg;} \
else if (wid == 2) {fun<targ1, targ2, 2, targ3> arg;} \
else if (wid == 4) {fun<targ1, targ2, 4, targ3> arg;} \
else if (wid == 8) {fun<targ1, targ2, 8, targ3> arg;} \
else if (wid == 64) {fun<targ1, targ2, 64, targ3> arg;} \
else {REALM_ASSERT_DEBUG(false); fun<targ1, targ2, 0, targ3> arg;}
#define REALM_TEMPEX5(fun, targ1, targ2, targ3, targ4, wid, arg) \
if (wid == 16) {fun<targ1, targ2, targ3, targ4, 16> arg;} \
else if (wid == 32) {fun<targ1, targ2, targ3, targ4, 32> arg;} \
else if (wid == 0) {fun<targ1, targ2, targ3, targ4, 0> arg;} \
else if (wid == 1) {fun<targ1, targ2, targ3, targ4, 1> arg;} \
else if (wid == 2) {fun<targ1, targ2, targ3, targ4, 2> arg;} \
else if (wid == 4) {fun<targ1, targ2, targ3, targ4, 4> arg;} \
else if (wid == 8) {fun<targ1, targ2, targ3, targ4, 8> arg;} \
else if (wid == 64) {fun<targ1, targ2, targ3, targ4, 64> arg;} \
else {REALM_ASSERT_DEBUG(false); fun<targ1, targ2, targ3, targ4, 0> arg;}
// Pre-definitions
class Array;
class StringColumn;
class GroupWriter;
template<class T>
class QueryState;
namespace _impl { class ArrayWriterBase; }
#ifdef REALM_DEBUG
class MemStats {
public:
MemStats():
allocated(0),
used(0),
array_count(0)
{
}
size_t allocated;
size_t used;
size_t array_count;
};
#endif
class ArrayParent
{
public:
virtual ~ArrayParent() noexcept {}
protected:
virtual void update_child_ref(size_t child_ndx, ref_type new_ref) = 0;
virtual ref_type get_child_ref(size_t child_ndx) const noexcept = 0;
#ifdef REALM_DEBUG
// Used only by Array::to_dot().
virtual std::pair<ref_type, size_t> get_to_dot_parent(size_t ndx_in_parent) const = 0;
#endif
friend class Array;
};
/// Provides access to individual array nodes of the database.
///
/// This class serves purely as an accessor, it assumes no ownership of the
/// referenced memory.
///
/// An array accessor can be in one of two states: attached or unattached. It is
/// in the attached state if, and only if is_attached() returns true. Most
/// non-static member functions of this class have undefined behaviour if the
/// accessor is in the unattached state. The exceptions are: is_attached(),
/// detach(), create(), init_from_ref(), init_from_mem(), init_from_parent(),
/// has_parent(), get_parent(), set_parent(), get_ndx_in_parent(),
/// set_ndx_in_parent(), adjust_ndx_in_parent(), and get_ref_from_parent().
///
/// An array accessor contains information about the parent of the referenced
/// array node. This 'reverse' reference is not explicitely present in the
/// underlying node hierarchy, but it is needed when modifying an array. A
/// modification may lead to relocation of the underlying array node, and the
/// parent must be updated accordingly. Since this applies recursivly all the
/// way to the root node, it is essential that the entire chain of parent
/// accessors is constructed and propperly maintained when a particular array is
/// modified.
///
/// The parent reference (`pointer to parent`, `index in parent`) is updated
/// independently from the state of attachment to an underlying node. In
/// particular, the parent reference remains valid and is unannfected by changes
/// in attachment. These two aspects of the state of the accessor is updated
/// independently, and it is entirely the responsibility of the caller to update
/// them such that they are consistent with the underlying node hierarchy before
/// calling any method that modifies the underlying array node.
///
/// FIXME: This class currently has fragments of ownership, in particular the
/// constructors that allocate underlying memory. On the other hand, the
/// destructor never frees the memory. This is a disastrous situation, because
/// it so easily becomes an obscure source of leaks. There are three options for
/// a fix of which the third is most attractive but hardest to implement: (1)
/// Remove all traces of ownership semantics, that is, remove the constructors
/// that allocate memory, but keep the trivial copy constructor. For this to
/// work, it is important that the constness of the accessor has nothing to do
/// with the constness of the underlying memory, otherwise constness can be
/// violated simply by copying the accessor. (2) Disallov copying but associate
/// the constness of the accessor with the constness of the underlying
/// memory. (3) Provide full ownership semantics like is done for Table
/// accessors, and provide a proper copy constructor that really produces a copy
/// of the array. For this to work, the class should assume ownership if, and
/// only if there is no parent. A copy produced by a copy constructor will not
/// have a parent. Even if the original was part of a database, the copy will be
/// free-standing, that is, not be part of any database. For intra, or inter
/// database copying, one would have to also specify the target allocator.
class Array: public ArrayParent {
public:
// void state_init(int action, QueryState *state);
// bool match(int action, size_t index, int64_t value, QueryState *state);
/// Create an array accessor in the unattached state.
explicit Array(Allocator&) noexcept;
// Fastest way to instantiate an array, if you just want to utilize its
// methods
struct no_prealloc_tag {};
explicit Array(no_prealloc_tag) noexcept;
~Array() noexcept override {}
enum Type {
type_Normal,
/// This array is the main array of an innner node of a B+-tree as used
/// in table columns.
type_InnerBptreeNode,
/// This array may contain refs to subarrays. An element whose least
/// significant bit is zero, is a ref pointing to a subarray. An element
/// whose least significant bit is one, is just a value. It is the
/// responsibility of the application to ensure that non-ref values have
/// their least significant bit set. This will generally be done by
/// shifting the desired vlue to the left by one bit position, and then
/// setting the vacated bit to one.
type_HasRefs
};
/// Create a new integer array of the specified type and size, and filled
/// with the specified value, and attach this accessor to it. This does not
/// modify the parent reference information of this accessor.
///
/// Note that the caller assumes ownership of the allocated underlying
/// node. It is not owned by the accessor.
void create(Type, bool context_flag = false, size_t size = 0, int_fast64_t value = 0);
/// Reinitialize this array accessor to point to the specified new
/// underlying memory. This does not modify the parent reference information
/// of this accessor.
void init_from_ref(ref_type) noexcept;
/// Same as init_from_ref(ref_type) but avoid the mapping of 'ref' to memory
/// pointer.
void init_from_mem(MemRef) noexcept;
/// Same as `init_from_ref(get_ref_from_parent())`.
void init_from_parent() noexcept;
/// Update the parents reference to this child. This requires, of course,
/// that the parent information stored in this child is up to date. If the
/// parent pointer is set to null, this function has no effect.
void update_parent();
/// Called in the context of Group::commit() to ensure that attached
/// accessors stay valid across a commit. Please note that this works only
/// for non-transactional commits. Accessors obtained during a transaction
/// are always detached when the transaction ends.
///
/// Returns true if, and only if the array has changed. If the array has not
/// changed, then its children are guaranteed to also not have changed.
bool update_from_parent(size_t old_baseline) noexcept;
/// Change the type of an already attached array node.
///
/// The effect of calling this function on an unattached accessor is
/// undefined.
void set_type(Type);
/// Construct a complete copy of this array (including its subarrays) using
/// the specified target allocator and return just the reference to the
/// underlying memory.
MemRef clone_deep(Allocator& target_alloc) const;
void move_assign(Array&) noexcept; // Move semantics for assignment
/// Construct an empty integer array of the specified type, and return just
/// the reference to the underlying memory.
static MemRef create_empty_array(Type, bool context_flag, Allocator&);
/// Construct an integer array of the specified type and size, and return
/// just the reference to the underlying memory. All elements will be
/// initialized to the specified value.
static MemRef create_array(Type, bool context_flag, size_t size,
int_fast64_t value, Allocator&);
/// Construct a shallow copy of the specified slice of this array using the
/// specified target allocator. Subarrays will **not** be cloned. See
/// slice_and_clone_children() for an alternative.
MemRef slice(size_t offset, size_t size, Allocator& target_alloc) const;
/// Construct a deep copy of the specified slice of this array using the
/// specified target allocator. Subarrays will be cloned.
MemRef slice_and_clone_children(size_t offset, size_t size,
Allocator& target_alloc) const;
// Parent tracking
bool has_parent() const noexcept;
ArrayParent* get_parent() const noexcept;
/// Setting a new parent affects ownership of the attached array node, if
/// any. If a non-null parent is specified, and there was no parent
/// originally, then the caller passes ownership to the parent, and vice
/// versa. This assumes, of course, that the change in parentship reflects a
/// corresponding change in the list of children in the affected parents.
void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept;
size_t get_ndx_in_parent() const noexcept;
void set_ndx_in_parent(size_t) noexcept;
void adjust_ndx_in_parent(int diff) noexcept;
/// Get the ref of this array as known to the parent. The caller must ensure
/// that the parent information ('pointer to parent' and 'index in parent')
/// is correct before calling this function.
ref_type get_ref_from_parent() const noexcept;
bool is_attached() const noexcept;
/// Detach from the underlying array node. This method has no effect if the
/// accessor is currently unattached (idempotency).
void detach() noexcept;
size_t size() const noexcept;
bool is_empty() const noexcept;
Type get_type() const noexcept;
static void add_to_column(IntegerColumn* column, int64_t value);
void insert(size_t ndx, int_fast64_t value);
void add(int_fast64_t value);
/// This function is guaranteed to not throw if the current width is
/// sufficient for the specified value (e.g. if you have called
/// ensure_minimum_width(value)) and get_alloc().is_read_only(get_ref())
/// returns false (noexcept:array-set). Note that for a value of zero, the
/// first criterion is trivially satisfied.
void set(size_t ndx, int64_t value);
void set_as_ref(size_t ndx, ref_type ref);
template<size_t w>
void set(size_t ndx, int64_t value);
int64_t get(size_t ndx) const noexcept;
template<size_t w>
int64_t get(size_t ndx) const noexcept;
void get_chunk(size_t ndx, int64_t res[8]) const noexcept;
template<size_t w>
void get_chunk(size_t ndx, int64_t res[8]) const noexcept;
ref_type get_as_ref(size_t ndx) const noexcept;
int64_t front() const noexcept;
int64_t back() const noexcept;
/// Remove the element at the specified index, and move elements at higher
/// indexes to the next lower index.
///
/// This function does **not** destroy removed subarrays. That is, if the
/// erased element is a 'ref' pointing to a subarray, then that subarray
/// will not be destroyed automatically.
///
/// This function guarantees that no exceptions will be thrown if
/// get_alloc().is_read_only(get_ref()) would return false before the
/// call. This is automatically guaranteed if the array is used in a
/// non-transactional context, or if the array has already been successfully
/// modified within the current write transaction.
void erase(size_t ndx);
/// Same as erase(size_t), but remove all elements in the specified
/// range.
///
/// Please note that this function does **not** destroy removed subarrays.
///
/// This function guarantees that no exceptions will be thrown if
/// get_alloc().is_read_only(get_ref()) would return false before the call.
void erase(size_t begin, size_t end);
/// Reduce the size of this array to the specified number of elements. It is
/// an error to specify a size that is greater than the current size of this
/// array. The effect of doing so is undefined. This is just a shorthand for
/// calling the ranged erase() function with appropriate arguments.
///
/// Please note that this function does **not** destroy removed
/// subarrays. See clear_and_destroy_children() for an alternative.
///
/// This function guarantees that no exceptions will be thrown if
/// get_alloc().is_read_only(get_ref()) would return false before the call.
void truncate(size_t size);
/// Reduce the size of this array to the specified number of elements. It is
/// an error to specify a size that is greater than the current size of this
/// array. The effect of doing so is undefined. Subarrays will be destroyed
/// recursively, as if by a call to `destroy_deep(subarray_ref, alloc)`.
///
/// This function is guaranteed not to throw if
/// get_alloc().is_read_only(get_ref()) returns false.
void truncate_and_destroy_children(size_t size);
/// Remove every element from this array. This is just a shorthand for
/// calling truncate(0).
///
/// Please note that this function does **not** destroy removed
/// subarrays. See clear_and_destroy_children() for an alternative.
///
/// This function guarantees that no exceptions will be thrown if
/// get_alloc().is_read_only(get_ref()) would return false before the call.
void clear();
/// Remove every element in this array. Subarrays will be destroyed
/// recursively, as if by a call to `destroy_deep(subarray_ref,
/// alloc)`. This is just a shorthand for calling
/// truncate_and_destroy_children(0).
///
/// This function guarantees that no exceptions will be thrown if
/// get_alloc().is_read_only(get_ref()) would return false before the call.
void clear_and_destroy_children();
/// If neccessary, expand the representation so that it can store the
/// specified value.
void ensure_minimum_width(int_fast64_t value);
typedef StringData (*StringGetter)(void*, size_t, char*); // Pre-declare getter function from string index
size_t index_string_find_first(StringData value, ColumnBase* column) const;
void index_string_find_all(IntegerColumn& result, StringData value, ColumnBase* column) const;
size_t index_string_count(StringData value, ColumnBase* column) const;
FindRes index_string_find_all_no_copy(StringData value, size_t& res_ref, ColumnBase* column) const;
/// This one may change the represenation of the array, so be carefull if
/// you call it after ensure_minimum_width().
void set_all_to_zero();
/// Add \a diff to the element at the specified index.
void adjust(size_t ndx, int_fast64_t diff);
/// Add \a diff to all the elements in the specified index range.
void adjust(size_t begin, size_t end, int_fast64_t diff);
/// Add signed \a diff to all elements that are greater than, or equal to \a
/// limit.
void adjust_ge(int_fast64_t limit, int_fast64_t diff);
//@{
/// These are similar in spirit to std::move() and std::move_backward from
/// <algorithm>. \a dest_begin must not be in the range [`begin`,`end`), and
/// \a dest_end must not be in the range (`begin`,`end`].
///
/// These functions are guaranteed to not throw if
/// `get_alloc().is_read_only(get_ref())` returns false.
void move(size_t begin, size_t end, size_t dest_begin);
void move_backward(size_t begin, size_t end, size_t dest_end);
//@}
/// move_rotate moves one element from \a from to be located at index \a to,
/// shifting all elements inbetween by one.
///
/// If \a from is larger than \a to, the elements inbetween are shifted down.
/// If \a to is larger than \a from, the elements inbetween are shifted up.
///
/// This function is guaranteed to not throw if
/// `get_alloc().is_read_only(get_ref())` returns false.
void move_rotate(size_t from, size_t to, size_t num_elems = 1);
//@{
/// Find the lower/upper bound of the specified value in a sequence of
/// integers which must already be sorted ascendingly.
///
/// For an integer value '`v`', lower_bound_int(v) returns the index '`l`'
/// of the first element such that `get(l) ≥ v`, and upper_bound_int(v)
/// returns the index '`u`' of the first element such that `get(u) >
/// v`. In both cases, if no such element is found, the returned value is
/// the number of elements in the array.
///
/// 3 3 3 4 4 4 5 6 7 9 9 9
/// ^ ^ ^ ^ ^
/// | | | | |
/// | | | | -- Lower and upper bound of 15
/// | | | |
/// | | | -- Lower and upper bound of 8
/// | | |
/// | | -- Upper bound of 4
/// | |
/// | -- Lower bound of 4
/// |
/// -- Lower and upper bound of 1
///
/// These functions are similar to std::lower_bound() and
/// std::upper_bound().
///
/// We currently use binary search. See for example
/// http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary.
///
/// FIXME: It may be worth considering if overall efficiency can be improved
/// by doing a linear search for short sequences.
size_t lower_bound_int(int64_t value) const noexcept;
size_t upper_bound_int(int64_t value) const noexcept;
//@}
/// \brief Search the \c Array for a value greater or equal than \a target,
/// starting the search at the \a start index. If \a indirection is
/// provided, use it as a look-up table to iterate over the \c Array.
///
/// If \a indirection is not provided, then the \c Array must be sorted in
/// ascending order. If \a indirection is provided, then its values should
/// point to indices in this \c Array in such a way that iteration happens
/// in ascending order.
///
/// Behaviour is undefined if:
/// - a value in \a indirection is out of bounds for this \c Array;
/// - \a indirection does not contain at least as many elements as this \c
/// Array;
/// - sorting conditions are not respected;
/// - \a start is greater than the number of elements in this \c Array or
/// \a indirection (if provided).
///
/// \param target the smallest value to search for
/// \param start the offset at which to start searching in the array
/// \param indirection an \c Array containing valid indices of values in
/// this \c Array, sorted in ascending order
/// \return the index of the value if found, or realm::not_found otherwise
size_t find_gte(const int64_t target, size_t start, Array const* indirection) const;
void preset(int64_t min, int64_t max, size_t count);
void preset(size_t bitwidth, size_t count);
int64_t sum(size_t start = 0, size_t end = size_t(-1)) const;
size_t count(int64_t value) const noexcept;
bool maximum(int64_t& result, size_t start = 0, size_t end = size_t(-1),
size_t* return_ndx = nullptr) const;
bool minimum(int64_t& result, size_t start = 0, size_t end = size_t(-1),
size_t* return_ndx = nullptr) const;
/// This information is guaranteed to be cached in the array accessor.
bool is_inner_bptree_node() const noexcept;
/// Returns true if type is either type_HasRefs or type_InnerColumnNode.
///
/// This information is guaranteed to be cached in the array accessor.
bool has_refs() const noexcept;
/// This information is guaranteed to be cached in the array accessor.
///
/// Columns and indexes can use the context bit to differentiate leaf types.
bool get_context_flag() const noexcept;
void set_context_flag(bool) noexcept;
ref_type get_ref() const noexcept;
MemRef get_mem() const noexcept;
/// Destroy only the array that this accessor is attached to, not the
/// children of that array. See non-static destroy_deep() for an
/// alternative. If this accessor is already in the detached state, this
/// function has no effect (idempotency).
void destroy() noexcept;
/// Recursively destroy children (as if calling
/// clear_and_destroy_children()), then put this accessor into the detached
/// state (as if calling detach()), then free the allocated memory. If this
/// accessor is already in the detached state, this function has no effect
/// (idempotency).
void destroy_deep() noexcept;
/// Shorthand for `destroy(MemRef(ref, alloc), alloc)`.
static void destroy(ref_type ref, Allocator& alloc) noexcept;
/// Destroy only the specified array node, not its children. See also
/// destroy_deep(MemRef, Allocator&).
static void destroy(MemRef, Allocator&) noexcept;
/// Shorthand for `destroy_deep(MemRef(ref, alloc), alloc)`.
static void destroy_deep(ref_type ref, Allocator& alloc) noexcept;
/// Destroy the specified array node and all of its children, recursively.
///
/// This is done by freeing the specified array node after calling
/// destroy_deep() for every contained 'ref' element.
static void destroy_deep(MemRef, Allocator&) noexcept;
Allocator& get_alloc() const noexcept { return m_alloc; }
// Serialization
/// Returns the ref (position in the target stream) of the written copy of
/// this array, or the ref of the original array if \a only_if_modified is
/// true, and this array is unmodified (Alloc::is_read_only()).
///
/// The number of bytes that will be written by a non-recursive invocation
/// of this function is exactly the number returned by get_byte_size().
///
/// \param deep If true, recursively write out subarrays, but still subject
/// to \a only_if_modified.
ref_type write(_impl::ArrayWriterBase&, bool deep, bool only_if_modified) const;
/// Same as non-static write() with `deep` set to true. This is for the
/// cases where you do not already have an array accessor available.
static ref_type write(ref_type, Allocator&, _impl::ArrayWriterBase&, bool only_if_modified);
// Main finding function - used for find_first, find_all, sum, max, min, etc.
bool find(int cond, Action action, int64_t value, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state, bool nullable_array = false, bool find_null = false) const;
// Templated find function to avoid conversion to and from integer represenation of condition
template <class cond>
bool find(Action action, int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t> *state, bool nullable_array = false, bool find_null = false) const {
if (action == act_ReturnFirst) {
REALM_TEMPEX3(return find, cond, act_ReturnFirst, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null))
}
else if (action == act_Sum) {
REALM_TEMPEX3(return find, cond, act_Sum, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null))
}
else if (action == act_Min) {
REALM_TEMPEX3(return find, cond, act_Min, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null))
}
else if (action == act_Max) {
REALM_TEMPEX3(return find, cond, act_Max, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null))
}
else if (action == act_Count) {
REALM_TEMPEX3(return find, cond, act_Count, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null))
}
else if (action == act_FindAll) {
REALM_TEMPEX3(return find, cond, act_FindAll, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null))
}
else if (action == act_CallbackIdx) {
REALM_TEMPEX3(return find, cond, act_CallbackIdx, m_width, (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null))
}
REALM_ASSERT_DEBUG(false);
return false;
}
/*
bool find(int cond, Action action, null, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state) const;
*/
template<class cond, Action action, size_t bitwidth, class Callback>
bool find(int64_t value, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state, Callback callback, bool nullable_array = false, bool find_null = false) const;
// This is the one installed into the m_vtable->finder slots.
template<class cond, Action action, size_t bitwidth>
bool find(int64_t value, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state) const;
template<class cond, Action action, class Callback>
bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state,
Callback callback, bool nullable_array = false, bool find_null = false) const;
/*
template<class cond, Action action, class Callback>
bool find(null, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state, Callback callback) const;
*/
// Optimized implementation for release mode
template<class cond, Action action, size_t bitwidth, class Callback>
bool find_optimized(int64_t value, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state, Callback callback, bool nullable_array = false, bool find_null = false) const;
// Called for each search result
template<Action action, class Callback>
bool find_action(size_t index, util::Optional<int64_t> value,
QueryState<int64_t>* state, Callback callback) const;
template<Action action, class Callback>
bool find_action_pattern(size_t index, uint64_t pattern,
QueryState<int64_t>* state, Callback callback) const;
// Wrappers for backwards compatibility and for simple use without
// setting up state initialization etc
template<class cond>
size_t find_first(int64_t value, size_t start = 0,
size_t end = size_t(-1)) const;
void find_all(IntegerColumn* result, int64_t value, size_t col_offset = 0,
size_t begin = 0, size_t end = size_t(-1)) const;
size_t find_first(int64_t value, size_t begin = 0,
size_t end = size_t(-1)) const;
// Non-SSE find for the four functions Equal/NotEqual/Less/Greater
template<class cond, Action action, size_t bitwidth, class Callback>
bool compare(int64_t value, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state, Callback callback) const;
// Non-SSE find for Equal/NotEqual
template<bool eq, Action action, size_t width, class Callback>
inline bool compare_equality(int64_t value, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state, Callback callback) const;
// Non-SSE find for Less/Greater
template<bool gt, Action action, size_t bitwidth, class Callback>
bool compare_relation(int64_t value, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state, Callback callback) const;
template<class cond, Action action, size_t foreign_width, class Callback, size_t width>
bool compare_leafs_4(const Array* foreign, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state, Callback callback) const;
template<class cond, Action action, class Callback, size_t bitwidth, size_t foreign_bitwidth>
bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state, Callback callback) const;
template<class cond, Action action, class Callback>
bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state, Callback callback) const;
template<class cond, Action action, size_t width, class Callback>
bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex,
QueryState<int64_t>* state, Callback callback) const;
// SSE find for the four functions Equal/NotEqual/Less/Greater
#ifdef REALM_COMPILER_SSE
template<class cond, Action action, size_t width, class Callback>
bool find_sse(int64_t value, __m128i *data, size_t items, QueryState<int64_t>* state,
size_t baseindex, Callback callback) const;
template<class cond, Action action, size_t width, class Callback>
REALM_FORCEINLINE bool find_sse_intern(__m128i* action_data, __m128i* data, size_t items,
QueryState<int64_t>* state, size_t baseindex,
Callback callback) const;
#endif
template<size_t width>
inline bool test_zero(uint64_t value) const; // Tests value for 0-elements
template<bool eq, size_t width>
size_t find_zero(uint64_t v) const; // Finds position of 0/non-zero element
template<size_t width, bool zero>
uint64_t cascade(uint64_t a) const; // Sets lowermost bits of zero or non-zero elements
template<bool gt, size_t width>
int64_t find_gtlt_magic(int64_t v) const; // Compute magic constant needed for searching for value 'v' using bit hacks
template<size_t width>
inline int64_t lower_bits() const; // Return chunk with lower bit set in each element
size_t first_set_bit(unsigned int v) const;
size_t first_set_bit64(int64_t v) const;
template<size_t w>
int64_t get_universal(const char* const data, const size_t ndx) const;
// Find value greater/less in 64-bit chunk - only works for positive values
template<bool gt, Action action, size_t width, class Callback>
bool find_gtlt_fast(uint64_t chunk, uint64_t magic, QueryState<int64_t>* state, size_t baseindex,
Callback callback) const;
// Find value greater/less in 64-bit chunk - no constraints
template<bool gt, Action action, size_t width, class Callback>
bool find_gtlt(int64_t v, uint64_t chunk, QueryState<int64_t>* state, size_t baseindex,
Callback callback) const;
/// Get the number of elements in the B+-tree rooted at this array
/// node. The root must not be a leaf.
///
/// Please avoid using this function (consider it deprecated). It
/// will have to be removed if we choose to get rid of the last
/// element of the main array of an inner B+-tree node that stores
/// the total number of elements in the subtree. The motivation
/// for removing it, is that it will significantly improve the
/// efficiency when inserting after, and erasing the last element.
size_t get_bptree_size() const noexcept;
/// The root must not be a leaf.
static size_t get_bptree_size_from_header(const char* root_header) noexcept;
/// Find the leaf node corresponding to the specified element
/// index index. The specified element index must refer to an
/// element that exists in the tree. This function must be called
/// on an inner B+-tree node, never a leaf. Note that according to
/// invar:bptree-nonempty-inner and invar:bptree-nonempty-leaf, an
/// inner B+-tree node can never be empty.
///
/// This function is not obliged to instantiate intermediate array
/// accessors. For this reason, this function cannot be used for
/// operations that modify the tree, as that requires an unbroken
/// chain of parent array accessors between the root and the
/// leaf. Thus, despite the fact that the returned MemRef object
/// appears to allow modification of the referenced memory, the
/// caller must handle the memory reference as if it was
/// const-qualified.
///
/// \return (`leaf_header`, `ndx_in_leaf`) where `leaf_header`
/// points to the the header of the located leaf, and
/// `ndx_in_leaf` is the local index within that leaf
/// corresponding to the specified element index.
std::pair<MemRef, size_t> get_bptree_leaf(size_t elem_ndx) const noexcept;
class NodeInfo;
class VisitHandler;
/// Visit leaves of the B+-tree rooted at this inner node,
/// starting with the leaf that contains the element at the
/// specified element index start offset, and ending when the
/// handler returns false. The specified element index offset must
/// refer to an element that exists in the tree. This function
/// must be called on an inner B+-tree node, never a leaf. Note
/// that according to invar:bptree-nonempty-inner and
/// invar:bptree-nonempty-leaf, an inner B+-tree node can never be
/// empty.
///
/// \param elems_in_tree The total number of element in the tree.
///
/// \return True if, and only if the handler has returned true for
/// all visited leafs.
bool visit_bptree_leaves(size_t elem_ndx_offset, size_t elems_in_tree,
VisitHandler&);
class UpdateHandler;
/// Call the handler for every leaf. This function must be called
/// on an inner B+-tree node, never a leaf.
void update_bptree_leaves(UpdateHandler&);
/// Call the handler for the leaf that contains the element at the
/// specified index. This function must be called on an inner
/// B+-tree node, never a leaf.
void update_bptree_elem(size_t elem_ndx, UpdateHandler&);
class EraseHandler;
/// Erase the element at the specified index in the B+-tree with
/// the specified root. When erasing the last element, you must
/// pass npos in place of the index. This function must be called
/// with a root that is an inner B+-tree node, never a leaf.
///
/// This function is guaranteed to succeed (not throw) if the
/// specified element was inserted during the current transaction,
/// and no other modifying operation has been carried out since
/// then (noexcept:bptree-erase-alt).
///
/// FIXME: ExceptionSafety: The exception guarantee explained
/// above is not as powerfull as we would like it to be. Here is
/// what we would like: This function is guaranteed to succeed
/// (not throw) if the specified element was inserted during the
/// current transaction (noexcept:bptree-erase). This must be true
/// even if the element is modified after insertion, and/or if
/// other elements are inserted or erased around it. There are two
/// aspects of the current design that stand in the way of this
/// guarantee: (A) The fact that the node accessor, that is cached
/// in the column accessor, has to be reallocated/reinstantiated
/// when the root switches between being a leaf and an inner
/// node. This problem would go away if we always cached the last
/// used leaf accessor in the column accessor instead. (B) The
/// fact that replacing one child ref with another can fail,
/// because it may require reallocation of memory to expand the
/// bit-width. This can be fixed in two ways: Either have the
/// inner B+-tree nodes always have a bit-width of 64, or allow
/// the root node to be discarded and the column ref to be set to
/// zero in Table::m_columns.
static void erase_bptree_elem(Array* root, size_t elem_ndx, EraseHandler&);
struct TreeInsertBase {
size_t m_split_offset;
size_t m_split_size;
};
template<class TreeTraits>
struct TreeInsert: TreeInsertBase {
typename TreeTraits::value_type m_value;
bool m_nullable;
};
/// Same as bptree_insert() but insert after the last element.
template<class TreeTraits>
ref_type bptree_append(TreeInsert<TreeTraits>& state);
/// Insert an element into the B+-subtree rooted at this array
/// node. The element is inserted before the specified element
/// index. This function must be called on an inner B+-tree node,
/// never a leaf. If this inner node had to be split, this
/// function returns the `ref` of the new sibling.
template<class TreeTraits>
ref_type bptree_insert(size_t elem_ndx, TreeInsert<TreeTraits>& state);
ref_type bptree_leaf_insert(size_t ndx, int64_t, TreeInsertBase& state);
/// Get the specified element without the cost of constructing an
/// array instance. If an array instance is already available, or
/// you need to get multiple values, then this method will be
/// slower.
static int_fast64_t get(const char* header, size_t ndx) noexcept;
/// Like get(const char*, size_t) but gets two consecutive
/// elements.
static std::pair<int64_t, int64_t> get_two(const char* header,
size_t ndx) noexcept;
static void get_three(const char* data, size_t ndx, ref_type& v0, ref_type& v1, ref_type& v2) noexcept;
/// The meaning of 'width' depends on the context in which this
/// array is used.
size_t get_width() const noexcept { return m_width; }
static char* get_data_from_header(char*) noexcept;
static char* get_header_from_data(char*) noexcept;
static const char* get_data_from_header(const char*) noexcept;
enum WidthType {
wtype_Bits = 0,
wtype_Multiply = 1,
wtype_Ignore = 2
};
static bool get_is_inner_bptree_node_from_header(const char*) noexcept;
static bool get_hasrefs_from_header(const char*) noexcept;
static bool get_context_flag_from_header(const char*) noexcept;
static WidthType get_wtype_from_header(const char*) noexcept;
static size_t get_width_from_header(const char*) noexcept;
static size_t get_size_from_header(const char*) noexcept;
static Type get_type_from_header(const char*) noexcept;
/// Get the number of bytes currently in use by this array. This
/// includes the array header, but it does not include allocated
/// bytes corresponding to excess capacity. The result is
/// guaranteed to be a multiple of 8 (i.e., 64-bit aligned).
///
/// This number is exactly the number of bytes that will be
/// written by a non-recursive invocation of write().
size_t get_byte_size() const noexcept;
/// Get the maximum number of bytes that can be written by a
/// non-recursive invocation of write() on an array with the
/// specified number of elements, that is, the maximum value that
/// can be returned by get_byte_size().
static size_t get_max_byte_size(size_t num_elems) noexcept;
/// FIXME: Belongs in IntegerArray
static size_t calc_aligned_byte_size(size_t size, int width);
#ifdef REALM_DEBUG
void print() const;
void verify() const;
typedef size_t (*LeafVerifier)(MemRef, Allocator&);
void verify_bptree(LeafVerifier) const;
class MemUsageHandler {
public:
virtual void handle(ref_type ref, size_t allocated, size_t used) = 0;
};
void report_memory_usage(MemUsageHandler&) const;
void stats(MemStats& stats) const;
typedef void (*LeafDumper)(MemRef, Allocator&, std::ostream&, int level);
void dump_bptree_structure(std::ostream&, int level, LeafDumper) const;
void to_dot(std::ostream&, StringData title = StringData()) const;
class ToDotHandler {
public:
virtual void to_dot(MemRef leaf_mem, ArrayParent*, size_t ndx_in_parent,
std::ostream&) = 0;
~ToDotHandler() {}
};
void bptree_to_dot(std::ostream&, ToDotHandler&) const;
void to_dot_parent_edge(std::ostream&) const;
#endif
static const int header_size = 8; // Number of bytes used by header
// The encryption layer relies on headers always fitting within a single page.
static_assert(header_size == 8, "Header must always fit in entirely on a page");
private:
Array& operator=(const Array&); // not allowed
protected:
typedef bool(*CallbackDummy)(int64_t);
/// Insert a new child after original. If the parent has to be
/// split, this function returns the `ref` of the new parent node.
ref_type insert_bptree_child(Array& offsets, size_t orig_child_ndx,
ref_type new_sibling_ref, TreeInsertBase& state);
void ensure_bptree_offsets(Array& offsets);
void create_bptree_offsets(Array& offsets, int_fast64_t first_value);
bool do_erase_bptree_elem(size_t elem_ndx, EraseHandler&);
template<IndexMethod method, class T>
size_t index_string(StringData value, IntegerColumn& result, ref_type& result_ref,
ColumnBase* column) const;
protected:
// void add_positive_local(int64_t value);
// Includes array header. Not necessarily 8-byte aligned.
virtual size_t calc_byte_len(size_t size, size_t width) const;
virtual size_t calc_item_count(size_t bytes, size_t width) const noexcept;
virtual WidthType GetWidthType() const { return wtype_Bits; }
bool get_is_inner_bptree_node_from_header() const noexcept;
bool get_hasrefs_from_header() const noexcept;
bool get_context_flag_from_header() const noexcept;
WidthType get_wtype_from_header() const noexcept;
size_t get_width_from_header() const noexcept;
size_t get_size_from_header() const noexcept;
// Undefined behavior if m_alloc.is_read_only(m_ref) returns true
size_t get_capacity_from_header() const noexcept;
void set_header_is_inner_bptree_node(bool value) noexcept;
void set_header_hasrefs(bool value) noexcept;
void set_header_context_flag(bool value) noexcept;
void set_header_wtype(WidthType value) noexcept;
void set_header_width(int value) noexcept;
void set_header_size(size_t value) noexcept;
void set_header_capacity(size_t value) noexcept;
static void set_header_is_inner_bptree_node(bool value, char* header) noexcept;
static void set_header_hasrefs(bool value, char* header) noexcept;
static void set_header_context_flag(bool value, char* header) noexcept;
static void set_header_wtype(WidthType value, char* header) noexcept;
static void set_header_width(int value, char* header) noexcept;
static void set_header_size(size_t value, char* header) noexcept;
static void set_header_capacity(size_t value, char* header) noexcept;
static void init_header(char* header, bool is_inner_bptree_node, bool has_refs,
bool context_flag, WidthType width_type, int width,
size_t size, size_t capacity) noexcept;
// This returns the minimum value ("lower bound") of the representable values
// for the given bit width. Valid widths are 0, 1, 2, 4, 8, 16, 32, and 64.
template<size_t width>
static int_fast64_t lbound_for_width() noexcept;
static int_fast64_t lbound_for_width(size_t width) noexcept;
// This returns the maximum value ("inclusive upper bound") of the representable values
// for the given bit width. Valid widths are 0, 1, 2, 4, 8, 16, 32, and 64.
template<size_t width>
static int_fast64_t ubound_for_width() noexcept;
static int_fast64_t ubound_for_width(size_t width) noexcept;
template<size_t width>
void set_width() noexcept;
void set_width(size_t) noexcept;
void alloc(size_t count, size_t width);
void copy_on_write();
private:
template<size_t w>
int64_t sum(size_t start, size_t end) const;
template<bool max, size_t w>
bool minmax(int64_t& result, size_t start, size_t end, size_t* return_ndx) const;
template<size_t w>
size_t find_gte(const int64_t target, size_t start, Array const* indirection) const;
protected:
/// The total size in bytes (including the header) of a new empty
/// array. Must be a multiple of 8 (i.e., 64-bit aligned).
static const size_t initial_capacity = 128;
/// It is an error to specify a non-zero value unless the width
/// type is wtype_Bits. It is also an error to specify a non-zero
/// size if the width type is wtype_Ignore.
static MemRef create(Type, bool context_flag, WidthType, size_t size,
int_fast64_t value, Allocator&);
static MemRef clone(MemRef header, Allocator& alloc, Allocator& target_alloc);
/// Get the address of the header of this array.
char* get_header() noexcept;
/// Same as get_byte_size().
static size_t get_byte_size_from_header(const char*) noexcept;
// Undefined behavior if array is in immutable memory
static size_t get_capacity_from_header(const char*) noexcept;
// Overriding method in ArrayParent
void update_child_ref(size_t, ref_type) override;
// Overriding method in ArrayParent
ref_type get_child_ref(size_t) const noexcept override;
void destroy_children(size_t offset = 0) noexcept;
#ifdef REALM_DEBUG
std::pair<ref_type, size_t>
get_to_dot_parent(size_t ndx_in_parent) const override;
#endif
protected:
// Getters and Setters for adaptive-packed arrays
typedef int64_t (Array::*Getter)(size_t) const; // Note: getters must not throw
typedef void (Array::*Setter)(size_t, int64_t);
typedef bool (Array::*Finder)(int64_t, size_t, size_t, size_t, QueryState<int64_t>*) const;
typedef void (Array::*ChunkGetter)(size_t, int64_t res[8]) const; // Note: getters must not throw
struct VTable {
Getter getter;
ChunkGetter chunk_getter;
Setter setter;
Finder finder[cond_VTABLE_FINDER_COUNT]; // one for each active function pointer
};
template<size_t w>
struct VTableForWidth;
protected:
/// Takes a 64-bit value and returns the minimum number of bits needed
/// to fit the value. For alignment this is rounded up to nearest
/// log2. Posssible results {0, 1, 2, 4, 8, 16, 32, 64}
static size_t bit_width(int64_t value);
#ifdef REALM_DEBUG
void report_memory_usage_2(MemUsageHandler&) const;
#endif
private:
Getter m_getter = nullptr; // cached to avoid indirection
const VTable* m_vtable = nullptr;
public:
// FIXME: Should not be public
char* m_data = nullptr; // Points to first byte after header
protected:
int64_t m_lbound; // min number that can be stored with current m_width
int64_t m_ubound; // max number that can be stored with current m_width
size_t m_size = 0; // Number of elements currently stored.
size_t m_capacity = 0; // Number of elements that fit inside the allocated memory.
Allocator& m_alloc;
private:
size_t m_ref;
ArrayParent* m_parent = nullptr;
size_t m_ndx_in_parent = 0; // Ignored if m_parent is null.
protected:
uint_least8_t m_width = 0; // Size of an element (meaning depend on type of array).
bool m_is_inner_bptree_node; // This array is an inner node of B+-tree.
bool m_has_refs; // Elements whose first bit is zero are refs to subarrays.
bool m_context_flag; // Meaning depends on context.
private:
ref_type do_write_shallow(_impl::ArrayWriterBase&) const;
ref_type do_write_deep(_impl::ArrayWriterBase&, bool only_if_modified) const;
friend class SlabAlloc;
friend class GroupWriter;
friend class StringColumn;
};
class Array::NodeInfo {
public:
MemRef m_mem;
Array* m_parent;
size_t m_ndx_in_parent;
size_t m_offset, m_size;
};
class Array::VisitHandler {
public:
virtual bool visit(const NodeInfo& leaf_info) = 0;
virtual ~VisitHandler() noexcept {}
};
class Array::UpdateHandler {
public:
virtual void update(MemRef, ArrayParent*, size_t leaf_ndx_in_parent,
size_t elem_ndx_in_leaf) = 0;
virtual ~UpdateHandler() noexcept {}
};
class Array::EraseHandler {
public:
/// If the specified leaf has more than one element, this function
/// must erase the specified element from the leaf and return
/// false. Otherwise, when the leaf has a single element, this
/// function must return true without modifying the leaf. If \a
/// elem_ndx_in_leaf is `npos`, it refers to the last element in
/// the leaf. The implementation of this function must be
/// exception safe. This function is guaranteed to be called at
/// most once during each execution of Array::erase_bptree_elem(),
/// and *exactly* once during each *successful* execution of
/// Array::erase_bptree_elem().
virtual bool erase_leaf_elem(MemRef, ArrayParent*,
size_t leaf_ndx_in_parent,
size_t elem_ndx_in_leaf) = 0;
virtual void destroy_leaf(MemRef leaf_mem) noexcept = 0;
/// Must replace the current root with the specified leaf. The
/// implementation of this function must not destroy the
/// underlying root node, or any of its children, as that will be
/// done by Array::erase_bptree_elem(). The implementation of this
/// function must be exception safe.
virtual void replace_root_by_leaf(MemRef leaf_mem) = 0;
/// Same as replace_root_by_leaf(), but must replace the root with
/// an empty leaf. Also, if this function is called during an
/// execution of Array::erase_bptree_elem(), it is guaranteed that
/// it will be preceeded by a call to erase_leaf_elem().
virtual void replace_root_by_empty_leaf() = 0;
virtual ~EraseHandler() noexcept {}
};
// Implementation:
class QueryStateBase { virtual void dyncast(){} };
template<>
class QueryState<int64_t>: public QueryStateBase {
public:
int64_t m_state;
size_t m_match_count;
size_t m_limit;
size_t m_minmax_index; // used only for min/max, to save index of current min/max value
template<Action action>
bool uses_val()
{
if (action == act_Max || action == act_Min || action == act_Sum)
return true;
else
return false;
}
void init(Action action, IntegerColumn* akku, size_t limit)
{
m_match_count = 0;
m_limit = limit;
m_minmax_index = not_found;
if (action == act_Max)
m_state = -0x7fffffffffffffffLL - 1LL;
else if (action == act_Min)
m_state = 0x7fffffffffffffffLL;
else if (action == act_ReturnFirst)
m_state = not_found;
else if (action == act_Sum)
m_state = 0;
else if (action == act_Count)
m_state = 0;
else if (action == act_FindAll)
m_state = reinterpret_cast<int64_t>(akku);
else if (action == act_CallbackIdx) {
}
else {
REALM_ASSERT_DEBUG(false);
}
}
template<Action action, bool pattern>
inline bool match(size_t index, uint64_t indexpattern, int64_t value)
{
if (pattern) {
if (action == act_Count) {
// If we are close to 'limit' argument in query, we cannot count-up a complete chunk. Count up single
// elements instead
if (m_match_count + 64 >= m_limit)
return false;
m_state += fast_popcount64(indexpattern);
m_match_count = size_t(m_state);
return true;
}
// Other aggregates cannot (yet) use bit pattern for anything. Make Array-finder call with pattern = false instead
return false;
}
++m_match_count;
if (action == act_Max) {
if (value > m_state) {
m_state = value;
m_minmax_index = index;
}
}
else if (action == act_Min) {
if (value < m_state) {
m_state = value;
m_minmax_index = index;
}
}
else if (action == act_Sum)
m_state += value;
else if (action == act_Count) {
m_state++;
m_match_count = size_t(m_state);
}
else if (action == act_FindAll) {
Array::add_to_column(reinterpret_cast<IntegerColumn*>(m_state), index);
}
else if (action == act_ReturnFirst) {
m_state = index;
return false;
}
else {
REALM_ASSERT_DEBUG(false);
}
return (m_limit > m_match_count);
}
template<Action action, bool pattern>
inline bool match(size_t index, uint64_t indexpattern, util::Optional<int64_t> value)
{
// FIXME: This is a temporary hack for nullable integers.
if (value) {
return match<action, pattern>(index, indexpattern, *value);
}
// If value is null, the only sensible actions are count, find_all, and return first.
// Max, min, and sum should all have no effect.
if (action == act_Count) {
m_state++;
m_match_count = size_t(m_state);
}
else if (action == act_FindAll) {
Array::add_to_column(reinterpret_cast<IntegerColumn*>(m_state), index);
}
else if (action == act_ReturnFirst) {
m_match_count++;
m_state = index;
return false;
}
return m_limit > m_match_count;
}
};
// Used only for Basic-types: currently float and double
template<class R>
class QueryState : public QueryStateBase {
public:
R m_state;
size_t m_match_count;
size_t m_limit;
size_t m_minmax_index; // used only for min/max, to save index of current min/max value
template<Action action>
bool uses_val()
{
return (action == act_Max || action == act_Min || action == act_Sum || action == act_Count);
}
void init(Action action, Array*, size_t limit)
{
REALM_ASSERT((std::is_same<R, float>::value ||
std::is_same<R, double>::value));
m_match_count = 0;
m_limit = limit;
m_minmax_index = not_found;
if (action == act_Max)
m_state = -std::numeric_limits<R>::infinity();
else if (action == act_Min)
m_state = std::numeric_limits<R>::infinity();
else if (action == act_Sum)
m_state = 0.0;
else {
REALM_ASSERT_DEBUG(false);
}
}
template<Action action, bool pattern, typename resulttype>
inline bool match(size_t index, uint64_t /*indexpattern*/, resulttype value)
{
if (pattern)
return false;
static_assert(action == act_Sum || action == act_Max || action == act_Min || action == act_Count,
"Search action not supported");
if (action == act_Count) {
++m_match_count;
}
else if (!null::is_null_float(value)) {
++m_match_count;
if (action == act_Max) {
if (value > m_state) {
m_state = value;
m_minmax_index = index;
}
}
else if (action == act_Min) {
if (value < m_state) {
m_state = value;
m_minmax_index = index;
}
}
else if (action == act_Sum)
m_state += value;
else {
REALM_ASSERT_DEBUG(false);
}
}
return (m_limit > m_match_count);
}
};
inline Array::Array(Allocator& alloc) noexcept:
m_alloc(alloc)
{
}
// Fastest way to instantiate an Array. For use with GetDirect() that only fills out m_width, m_data
// and a few other basic things needed for read-only access. Or for use if you just want a way to call
// some methods written in Array.*
inline Array::Array(no_prealloc_tag) noexcept:
m_alloc(*static_cast<Allocator*>(0))
{
}
inline void Array::create(Type type, bool context_flag, size_t size, int_fast64_t value)
{
MemRef mem = create_array(type, context_flag, size, value, m_alloc); // Throws
init_from_mem(mem);
}
inline void Array::init_from_ref(ref_type ref) noexcept
{
REALM_ASSERT_DEBUG(ref);
char* header = m_alloc.translate(ref);
init_from_mem(MemRef(header, ref));
}
inline void Array::init_from_parent() noexcept
{
ref_type ref = get_ref_from_parent();
init_from_ref(ref);
}
inline Array::Type Array::get_type() const noexcept
{
if (m_is_inner_bptree_node) {
REALM_ASSERT_DEBUG(m_has_refs);
return type_InnerBptreeNode;
}
if (m_has_refs)
return type_HasRefs;
return type_Normal;
}
inline void Array::get_chunk(size_t ndx, int64_t res[8]) const noexcept
{
REALM_ASSERT_DEBUG(ndx < m_size);
(this->*(m_vtable->chunk_getter))(ndx, res);
}
inline int64_t Array::get(size_t ndx) const noexcept
{
REALM_ASSERT_DEBUG(is_attached());
REALM_ASSERT_DEBUG(ndx < m_size);
return (this->*m_getter)(ndx);
// Two ideas that are not efficient but may be worth looking into again:
/*
// Assume correct width is found early in REALM_TEMPEX, which is the case for B tree offsets that
// are probably either 2^16 long. Turns out to be 25% faster if found immediately, but 50-300% slower
// if found later
REALM_TEMPEX(return get, (ndx));
*/
/*
// Slightly slower in both of the if-cases. Also needs an matchcount m_size check too, to avoid
// reading beyond array.
if (m_width >= 8 && m_size > ndx + 7)
return get<64>(ndx >> m_shift) & m_widthmask;
else
return (this->*(m_vtable->getter))(ndx);
*/
}
inline int64_t Array::front() const noexcept
{
return get(0);
}
inline int64_t Array::back() const noexcept
{
return get(m_size - 1);
}
inline ref_type Array::get_as_ref(size_t ndx) const noexcept
{
REALM_ASSERT_DEBUG(is_attached());
REALM_ASSERT_DEBUG(m_has_refs);
int64_t v = get(ndx);
return to_ref(v);
}
inline bool Array::is_inner_bptree_node() const noexcept
{
return m_is_inner_bptree_node;
}
inline bool Array::has_refs() const noexcept
{
return m_has_refs;
}
inline bool Array::get_context_flag() const noexcept
{
return m_context_flag;
}
inline void Array::set_context_flag(bool value) noexcept
{
m_context_flag = value;
set_header_context_flag(value);
}
inline ref_type Array::get_ref() const noexcept
{
return m_ref;
}
inline MemRef Array::get_mem() const noexcept
{
return MemRef(get_header_from_data(m_data), m_ref);
}
inline void Array::destroy() noexcept
{
if (!is_attached())
return;
char* header = get_header_from_data(m_data);
m_alloc.free_(m_ref, header);
m_data = nullptr;
}
inline void Array::destroy_deep() noexcept
{
if (!is_attached())
return;
if (m_has_refs)
destroy_children();
char* header = get_header_from_data(m_data);
m_alloc.free_(m_ref, header);
m_data = nullptr;
}
inline ref_type Array::write(_impl::ArrayWriterBase& out, bool deep, bool only_if_modified) const
{
REALM_ASSERT(is_attached());
if (only_if_modified && m_alloc.is_read_only(m_ref))
return m_ref;
if (!deep || !m_has_refs)
return do_write_shallow(out); // Throws
return do_write_deep(out, only_if_modified); // Throws
}
inline ref_type Array::write(ref_type ref, Allocator& alloc, _impl::ArrayWriterBase& out,
bool only_if_modified)
{
if (only_if_modified && alloc.is_read_only(ref))
return ref;
Array array(alloc);
array.init_from_ref(ref);
if (!array.m_has_refs)
return array.do_write_shallow(out); // Throws
return array.do_write_deep(out, only_if_modified); // Throws
}
inline void Array::add(int_fast64_t value)
{
insert(m_size, value);
}
inline void Array::erase(size_t ndx)
{
// This can throw, but only if array is currently in read-only
// memory.
move(ndx+1, size(), ndx);
// Update size (also in header)
--m_size;
set_header_size(m_size);
}
inline void Array::erase(size_t begin, size_t end)
{
if (begin != end) {
// This can throw, but only if array is currently in read-only memory.
move(end, size(), begin); // Throws
// Update size (also in header)
m_size -= end - begin;
set_header_size(m_size);
}
}
inline void Array::clear()
{
truncate(0); // Throws
}
inline void Array::clear_and_destroy_children()
{
truncate_and_destroy_children(0);
}
inline void Array::destroy(ref_type ref, Allocator& alloc) noexcept
{
destroy(MemRef(ref, alloc), alloc);
}
inline void Array::destroy(MemRef mem, Allocator& alloc) noexcept
{
alloc.free_(mem);
}
inline void Array::destroy_deep(ref_type ref, Allocator& alloc) noexcept
{
destroy_deep(MemRef(ref, alloc), alloc);
}
inline void Array::destroy_deep(MemRef mem, Allocator& alloc) noexcept
{
if (!get_hasrefs_from_header(mem.m_addr)) {
alloc.free_(mem);
return;
}
Array array(alloc);
array.init_from_mem(mem);
array.destroy_deep();
}
inline void Array::adjust(size_t ndx, int_fast64_t diff)
{
// FIXME: Should be optimized
REALM_ASSERT_3(ndx, <=, m_size);
int_fast64_t v = get(ndx);
set(ndx, int64_t(v + diff)); // Throws
}
inline void Array::adjust(size_t begin, size_t end, int_fast64_t diff)
{
// FIXME: Should be optimized
for (size_t i = begin; i != end; ++i)
adjust(i, diff); // Throws
}
inline void Array::adjust_ge(int_fast64_t limit, int_fast64_t diff)
{
size_t n = size();
for (size_t i = 0; i != n; ++i) {
int_fast64_t v = get(i);
if (v >= limit)
set(i, int64_t(v + diff)); // Throws
}
}
//-------------------------------------------------
inline bool Array::get_is_inner_bptree_node_from_header(const char* header) noexcept
{
typedef unsigned char uchar;
const uchar* h = reinterpret_cast<const uchar*>(header);
return (int(h[4]) & 0x80) != 0;
}
inline bool Array::get_hasrefs_from_header(const char* header) noexcept
{
typedef unsigned char uchar;
const uchar* h = reinterpret_cast<const uchar*>(header);
return (int(h[4]) & 0x40) != 0;
}
inline bool Array::get_context_flag_from_header(const char* header) noexcept
{
typedef unsigned char uchar;
const uchar* h = reinterpret_cast<const uchar*>(header);
return (int(h[4]) & 0x20) != 0;
}
inline Array::WidthType Array::get_wtype_from_header(const char* header) noexcept
{
typedef unsigned char uchar;
const uchar* h = reinterpret_cast<const uchar*>(header);
return WidthType((int(h[4]) & 0x18) >> 3);
}
inline size_t Array::get_width_from_header(const char* header) noexcept
{
typedef unsigned char uchar;
const uchar* h = reinterpret_cast<const uchar*>(header);
return size_t((1 << (int(h[4]) & 0x07)) >> 1);
}
inline size_t Array::get_size_from_header(const char* header) noexcept
{
typedef unsigned char uchar;
const uchar* h = reinterpret_cast<const uchar*>(header);
return (size_t(h[5]) << 16) + (size_t(h[6]) << 8) + h[7];
}
inline size_t Array::get_capacity_from_header(const char* header) noexcept
{
typedef unsigned char uchar;
const uchar* h = reinterpret_cast<const uchar*>(header);
return (size_t(h[0]) << 16) + (size_t(h[1]) << 8) + h[2];
}
inline char* Array::get_data_from_header(char* header) noexcept
{
return header + header_size;
}
inline char* Array::get_header_from_data(char* data) noexcept
{
return data - header_size;
}
inline const char* Array::get_data_from_header(const char* header) noexcept
{
return get_data_from_header(const_cast<char*>(header));
}
inline bool Array::get_is_inner_bptree_node_from_header() const noexcept
{
return get_is_inner_bptree_node_from_header(get_header_from_data(m_data));
}
inline bool Array::get_hasrefs_from_header() const noexcept
{
return get_hasrefs_from_header(get_header_from_data(m_data));
}
inline bool Array::get_context_flag_from_header() const noexcept
{
return get_context_flag_from_header(get_header_from_data(m_data));
}
inline Array::WidthType Array::get_wtype_from_header() const noexcept
{
return get_wtype_from_header(get_header_from_data(m_data));
}
inline size_t Array::get_width_from_header() const noexcept
{
return get_width_from_header(get_header_from_data(m_data));
}
inline size_t Array::get_size_from_header() const noexcept
{
return get_size_from_header(get_header_from_data(m_data));
}
inline size_t Array::get_capacity_from_header() const noexcept
{
return get_capacity_from_header(get_header_from_data(m_data));
}
inline void Array::set_header_is_inner_bptree_node(bool value, char* header) noexcept
{
typedef unsigned char uchar;
uchar* h = reinterpret_cast<uchar*>(header);
h[4] = uchar((int(h[4]) & ~0x80) | int(value) << 7);
}
inline void Array::set_header_hasrefs(bool value, char* header) noexcept
{
typedef unsigned char uchar;
uchar* h = reinterpret_cast<uchar*>(header);
h[4] = uchar((int(h[4]) & ~0x40) | int(value) << 6);
}
inline void Array::set_header_context_flag(bool value, char* header) noexcept
{
typedef unsigned char uchar;
uchar* h = reinterpret_cast<uchar*>(header);
h[4] = uchar((int(h[4]) & ~0x20) | int(value) << 5);
}
inline void Array::set_header_wtype(WidthType value, char* header) noexcept
{
// Indicates how to calculate size in bytes based on width
// 0: bits (width/8) * size
// 1: multiply width * size
// 2: ignore 1 * size
typedef unsigned char uchar;
uchar* h = reinterpret_cast<uchar*>(header);
h[4] = uchar((int(h[4]) & ~0x18) | int(value) << 3);
}
inline void Array::set_header_width(int value, char* header) noexcept
{
// Pack width in 3 bits (log2)
int w = 0;
while (value) {
++w;
value >>= 1;
}
REALM_ASSERT_3(w, <, 8);
typedef unsigned char uchar;
uchar* h = reinterpret_cast<uchar*>(header);
h[4] = uchar((int(h[4]) & ~0x7) | w);
}
inline void Array::set_header_size(size_t value, char* header) noexcept
{
REALM_ASSERT_3(value, <=, max_array_payload);
typedef unsigned char uchar;
uchar* h = reinterpret_cast<uchar*>(header);
h[5] = uchar((value >> 16) & 0x000000FF);
h[6] = uchar((value >> 8) & 0x000000FF);
h[7] = uchar( value & 0x000000FF);
}
// Note: There is a copy of this function is test_alloc.cpp
inline void Array::set_header_capacity(size_t value, char* header) noexcept
{
REALM_ASSERT_3(value, <=, max_array_payload);
typedef unsigned char uchar;
uchar* h = reinterpret_cast<uchar*>(header);
h[0] = uchar((value >> 16) & 0x000000FF);
h[1] = uchar((value >> 8) & 0x000000FF);
h[2] = uchar( value & 0x000000FF);
}
inline void Array::set_header_is_inner_bptree_node(bool value) noexcept
{
set_header_is_inner_bptree_node(value, get_header_from_data(m_data));
}
inline void Array::set_header_hasrefs(bool value) noexcept
{
set_header_hasrefs(value, get_header_from_data(m_data));
}
inline void Array::set_header_context_flag(bool value) noexcept
{
set_header_context_flag(value, get_header_from_data(m_data));
}
inline void Array::set_header_wtype(WidthType value) noexcept
{
set_header_wtype(value, get_header_from_data(m_data));
}
inline void Array::set_header_width(int value) noexcept
{
set_header_width(value, get_header_from_data(m_data));
}
inline void Array::set_header_size(size_t value) noexcept
{
set_header_size(value, get_header_from_data(m_data));
}
inline void Array::set_header_capacity(size_t value) noexcept
{
set_header_capacity(value, get_header_from_data(m_data));
}
inline Array::Type Array::get_type_from_header(const char* header) noexcept
{
if (get_is_inner_bptree_node_from_header(header))
return type_InnerBptreeNode;
if (get_hasrefs_from_header(header))
return type_HasRefs;
return type_Normal;
}
inline char* Array::get_header() noexcept
{
return get_header_from_data(m_data);
}
inline size_t Array::get_byte_size() const noexcept
{
size_t num_bytes = 0;
const char* header = get_header_from_data(m_data);
switch (get_wtype_from_header(header)) {
case wtype_Bits: {
// FIXME: The following arithmetic could overflow, that
// is, even though both the total number of elements and
// the total number of bytes can be represented in
// uint_fast64_t, the total number of bits may not
// fit. Note that "num_bytes = width < 8 ? size / (8 /
// width) : size * (width / 8)" would be guaranteed to
// never overflow, but it potentially involves two slow
// divisions.
uint_fast64_t num_bits = uint_fast64_t(m_size) * m_width;
num_bytes = size_t(num_bits / 8);
if (num_bits & 0x7)
++num_bytes;
goto found;
}
case wtype_Multiply: {
num_bytes = m_size * m_width;
goto found;
}
case wtype_Ignore:
num_bytes = m_size;
goto found;
}
REALM_ASSERT_DEBUG(false);
found:
// Ensure 8-byte alignment
size_t rest = (~num_bytes & 0x7) + 1;
if (rest < 8)
num_bytes += rest;
num_bytes += header_size;
REALM_ASSERT_7(m_alloc.is_read_only(m_ref), ==, true, ||,
num_bytes, <=, get_capacity_from_header(header));
return num_bytes;
}
inline size_t Array::get_byte_size_from_header(const char* header) noexcept
{
size_t num_bytes = 0;
size_t size = get_size_from_header(header);
switch (get_wtype_from_header(header)) {
case wtype_Bits: {
size_t width = get_width_from_header(header);
size_t num_bits = (size * width); // FIXME: Prone to overflow
num_bytes = num_bits / 8;
if (num_bits & 0x7)
++num_bytes;
goto found;
}
case wtype_Multiply: {
size_t width = get_width_from_header(header);
num_bytes = size * width;
goto found;
}
case wtype_Ignore:
num_bytes = size;
goto found;
}
REALM_ASSERT_DEBUG(false);
found:
// Ensure 8-byte alignment
size_t rest = (~num_bytes & 0x7) + 1;
if (rest < 8)
num_bytes += rest;
num_bytes += header_size;
return num_bytes;
}
inline void Array::init_header(char* header, bool is_inner_bptree_node, bool has_refs,
bool context_flag, WidthType width_type, int width,
size_t size, size_t capacity) noexcept
{
// Note: Since the header layout contains unallocated bit and/or
// bytes, it is important that we put the entire header into a
// well defined state initially.
std::fill(header, header + header_size, 0);
set_header_is_inner_bptree_node(is_inner_bptree_node, header);
set_header_hasrefs(has_refs, header);
set_header_context_flag(context_flag, header);
set_header_wtype(width_type, header);
set_header_width(width, header);
set_header_size(size, header);
set_header_capacity(capacity, header);
}
//-------------------------------------------------
inline MemRef Array::clone_deep(Allocator& target_alloc) const
{
char* header = get_header_from_data(m_data);
return clone(MemRef(header, m_ref), m_alloc, target_alloc); // Throws
}
inline void Array::move_assign(Array& a) noexcept
{
REALM_ASSERT_3(&get_alloc(), ==, &a.get_alloc());
// FIXME: Be carefull with the old parent info here. Should it be
// copied?
// FIXME: It will likely be a lot better for the optimizer if we
// did a member-wise copy, rather than recreating the state from
// the referenced data. This is important because TableView efficiency, for
// example, relies on long chains of moves to be optimized away
// completely. This change should be a 'no-brainer'.
destroy_deep();
init_from_ref(a.get_ref());
a.detach();
}
inline MemRef Array::create_empty_array(Type type, bool context_flag, Allocator& alloc)
{
size_t size = 0;
int_fast64_t value = 0;
return create_array(type, context_flag, size, value, alloc); // Throws
}
inline MemRef Array::create_array(Type type, bool context_flag, size_t size, int_fast64_t value,
Allocator& alloc)
{
return create(type, context_flag, wtype_Bits, size, value, alloc); // Throws
}
inline bool Array::has_parent() const noexcept
{
return m_parent != nullptr;
}
inline ArrayParent* Array::get_parent() const noexcept
{
return m_parent;
}
inline void Array::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept
{
m_parent = parent;
m_ndx_in_parent = ndx_in_parent;
}
inline size_t Array::get_ndx_in_parent() const noexcept
{
return m_ndx_in_parent;
}
inline void Array::set_ndx_in_parent(size_t ndx) noexcept
{
m_ndx_in_parent = ndx;
}
inline void Array::adjust_ndx_in_parent(int diff) noexcept
{
// Note that `diff` is promoted to an unsigned type, and that
// C++03 still guarantees the expected result regardless of the
// sizes of `int` and `decltype(m_ndx_in_parent)`.
m_ndx_in_parent += diff;
}
inline ref_type Array::get_ref_from_parent() const noexcept
{
ref_type ref = m_parent->get_child_ref(m_ndx_in_parent);
return ref;
}
inline bool Array::is_attached() const noexcept
{
return m_data != nullptr;
}
inline void Array::detach() noexcept
{
m_data = nullptr;
}
inline size_t Array::size() const noexcept
{
REALM_ASSERT_DEBUG(is_attached());
return m_size;
}
inline bool Array::is_empty() const noexcept
{
return size() == 0;
}
inline size_t Array::get_max_byte_size(size_t num_elems) noexcept
{
int max_bytes_per_elem = 8;
return header_size + num_elems * max_bytes_per_elem; // FIXME: Prone to overflow
}
inline void Array::update_parent()
{
if (m_parent)
m_parent->update_child_ref(m_ndx_in_parent, m_ref);
}
inline void Array::update_child_ref(size_t child_ndx, ref_type new_ref)
{
set(child_ndx, new_ref);
}
inline ref_type Array::get_child_ref(size_t child_ndx) const noexcept
{
return get_as_ref(child_ndx);
}
inline size_t Array::get_bptree_size() const noexcept
{
REALM_ASSERT_DEBUG(is_inner_bptree_node());
int_fast64_t v = back();
return size_t(v / 2); // v = 1 + 2*total_elems_in_tree
}
inline size_t Array::get_bptree_size_from_header(const char* root_header) noexcept
{
REALM_ASSERT_DEBUG(get_is_inner_bptree_node_from_header(root_header));
size_t root_size = get_size_from_header(root_header);
int_fast64_t v = get(root_header, root_size-1);
return size_t(v / 2); // v = 1 + 2*total_elems_in_tree
}
inline void Array::ensure_bptree_offsets(Array& offsets)
{
int_fast64_t first_value = get(0);
if (first_value % 2 == 0) {
offsets.init_from_ref(to_ref(first_value));
}
else {
create_bptree_offsets(offsets, first_value); // Throws
}
offsets.set_parent(this, 0);
}
template<class TreeTraits>
ref_type Array::bptree_append(TreeInsert<TreeTraits>& state)
{
// FIXME: Consider exception safety. Especially, how can the split
// be carried out in an exception safe manner?
//
// Can split be done as a separate preparation step, such that if
// the actual insert fails, the split will still have occured.
//
// Unfortunately, it requires a rather significant rearrangement
// of the insertion flow. Instead of returning the sibling ref
// from insert functions, the leaf-insert functions must instead
// call the special bptree_insert() function on the parent, which
// will then cascade the split towards the root as required.
//
// At each level where a split is required (starting at the leaf):
//
// 1. Create the new sibling.
//
// 2. Copy relevant entries over such that new sibling is in
// its final state.
//
// 3. Call Array::bptree_insert() on parent with sibling ref.
//
// 4. Rearrange entries in original sibling and truncate as
// required (must not throw).
//
// What about the 'offsets' array? It will always be
// present. Consider this carefully.
REALM_ASSERT_DEBUG(size() >= 1 + 1 + 1); // At least one child
ArrayParent& childs_parent = *this;
size_t child_ref_ndx = size() - 2;
ref_type child_ref = get_as_ref(child_ref_ndx), new_sibling_ref;
char* child_header = static_cast<char*>(m_alloc.translate(child_ref));
bool child_is_leaf = !get_is_inner_bptree_node_from_header(child_header);
if (child_is_leaf) {
size_t elem_ndx_in_child = npos; // Append
new_sibling_ref =
TreeTraits::leaf_insert(MemRef(child_header, child_ref), childs_parent,
child_ref_ndx, m_alloc, elem_ndx_in_child, state); // Throws
}
else {
Array child(m_alloc);
child.init_from_mem(MemRef(child_header, child_ref));
child.set_parent(&childs_parent, child_ref_ndx);
new_sibling_ref = child.bptree_append(state); // Throws
}
if (REALM_LIKELY(!new_sibling_ref)) {
// +2 because stored value is 1 + 2*total_elems_in_subtree
adjust(size()-1, +2); // Throws
return 0; // Child was not split, so parent was not split either
}
Array offsets(m_alloc);
int_fast64_t first_value = get(0);
if (first_value % 2 == 0) {
// Offsets array is present (general form)
offsets.init_from_ref(to_ref(first_value));
offsets.set_parent(this, 0);
}
size_t child_ndx = child_ref_ndx - 1;
return insert_bptree_child(offsets, child_ndx, new_sibling_ref, state); // Throws
}
template<class TreeTraits>
ref_type Array::bptree_insert(size_t elem_ndx, TreeInsert<TreeTraits>& state)
{
REALM_ASSERT_3(size(), >=, 1 + 1 + 1); // At least one child
// Conversion to general form if in compact form. Since this
// conversion will occur from root to leaf, it will maintain
// invar:bptree-node-form.
Array offsets(m_alloc);
ensure_bptree_offsets(offsets); // Throws
size_t child_ndx, elem_ndx_in_child;
if (elem_ndx == 0) {
// Optimization for prepend
child_ndx = 0;
elem_ndx_in_child = 0;
}
else {
// There is a choice to be made when the element is to be
// inserted between two subtrees. It can either be appended to
// the first subtree, or it can be prepended to the second
// one. We currently always append to the first subtree. It is
// essentially a matter of using the lower vs. the upper bound
// when searching through the offsets array.
child_ndx = offsets.lower_bound_int(elem_ndx);
REALM_ASSERT_3(child_ndx, <, size() - 2);
size_t elem_ndx_offset = child_ndx == 0 ? 0 : to_size_t(offsets.get(child_ndx-1));
elem_ndx_in_child = elem_ndx - elem_ndx_offset;
}
ArrayParent& childs_parent = *this;
size_t child_ref_ndx = child_ndx + 1;
ref_type child_ref = get_as_ref(child_ref_ndx), new_sibling_ref;
char* child_header = static_cast<char*>(m_alloc.translate(child_ref));
bool child_is_leaf = !get_is_inner_bptree_node_from_header(child_header);
if (child_is_leaf) {
REALM_ASSERT_3(elem_ndx_in_child, <=, REALM_MAX_BPNODE_SIZE);
new_sibling_ref =
TreeTraits::leaf_insert(MemRef(child_header, child_ref), childs_parent,
child_ref_ndx, m_alloc, elem_ndx_in_child, state); // Throws
}
else {
Array child(m_alloc);
child.init_from_mem(MemRef(child_header, child_ref));
child.set_parent(&childs_parent, child_ref_ndx);
new_sibling_ref = child.bptree_insert(elem_ndx_in_child, state); // Throws
}
if (REALM_LIKELY(!new_sibling_ref)) {
// +2 because stored value is 1 + 2*total_elems_in_subtree
adjust(size()-1, +2); // Throws
offsets.adjust(child_ndx, offsets.size(), +1);
return 0; // Child was not split, so parent was not split either
}
return insert_bptree_child(offsets, child_ndx, new_sibling_ref, state); // Throws
}
//*************************************************************************************
// Finding code *
//*************************************************************************************
template<size_t w>
int64_t Array::get(size_t ndx) const noexcept
{
return get_universal<w>(m_data, ndx);
}
template<size_t w>
int64_t Array::get_universal(const char* data, size_t ndx) const
{
if (w == 0) {
return 0;
}
else if (w == 1) {
size_t offset = ndx >> 3;
return (data[offset] >> (ndx & 7)) & 0x01;
}
else if (w == 2) {
size_t offset = ndx >> 2;
return (data[offset] >> ((ndx & 3) << 1)) & 0x03;
}
else if (w == 4) {
size_t offset = ndx >> 1;
return (data[offset] >> ((ndx & 1) << 2)) & 0x0F;
}
else if (w == 8) {
return *reinterpret_cast<const signed char*>(data + ndx);
}
else if (w == 16) {
size_t offset = ndx * 2;
return *reinterpret_cast<const int16_t*>(data + offset);
}
else if (w == 32) {
size_t offset = ndx * 4;
return *reinterpret_cast<const int32_t*>(data + offset);
}
else if (w == 64) {
size_t offset = ndx * 8;
return *reinterpret_cast<const int64_t*>(data + offset);
}
else {
REALM_ASSERT_DEBUG(false);
return int64_t(-1);
}
}
/*
find() (calls find_optimized()) will call match() for each search result.
If pattern == true:
'indexpattern' contains a 64-bit chunk of elements, each of 'width' bits in size where each element indicates a match if its lower bit is set, otherwise
it indicates a non-match. 'index' tells the database row index of the first element. You must return true if you chose to 'consume' the chunk or false
if not. If not, then Array-finder will afterwards call match() successive times with pattern == false.
If pattern == false:
'index' tells the row index of a single match and 'value' tells its value. Return false to make Array-finder break its search or return true to let it continue until
'end' or 'limit'.
Array-finder decides itself if - and when - it wants to pass you an indexpattern. It depends on array bit width, match frequency, and wether the arithemetic and
computations for the given search criteria makes it feasible to construct such a pattern.
*/
// These wrapper functions only exist to enable a possibility to make the compiler see that 'value' and/or 'index' are unused, such that caller's
// computation of these values will not be made. Only works if find_action() and find_action_pattern() rewritten as macros. Note: This problem has been fixed in
// next upcoming array.hpp version
template<Action action, class Callback>
bool Array::find_action(size_t index, util::Optional<int64_t> value, QueryState<int64_t>* state, Callback callback) const
{
if (action == act_CallbackIdx)
return callback(index);
else
return state->match<action, false>(index, 0, value);
}
template<Action action, class Callback>
bool Array::find_action_pattern(size_t index, uint64_t pattern, QueryState<int64_t>* state, Callback callback) const
{
static_cast<void>(callback);
if (action == act_CallbackIdx) {
// Possible future optimization: call callback(index) like in above find_action(), in a loop for each bit set in 'pattern'
return false;
}
return state->match<action, true>(index, pattern, 0);
}
template<size_t width, bool zero>
uint64_t Array::cascade(uint64_t a) const
{
// Takes a chunk of values as argument and sets the least significant bit for each
// element which is zero or non-zero, depending on the template parameter.
// Example for zero=true:
// width == 4 and a = 0x5fd07a107610f610
// will return: 0x0001000100010001
// static values needed for fast population count
const uint64_t m1 = 0x5555555555555555ULL;
if (width == 1) {
return zero ? ~a : a;
}
else if (width == 2) {
// Masks to avoid spillover between segments in cascades
const uint64_t c1 = ~0ULL/0x3 * 0x1;
a |= (a >> 1) & c1; // cascade ones in non-zeroed segments
a &= m1; // isolate single bit in each segment
if (zero)
a ^= m1; // reverse isolated bits if checking for zeroed segments
return a;
}
else if (width == 4) {
const uint64_t m = ~0ULL/0xF * 0x1;
// Masks to avoid spillover between segments in cascades
const uint64_t c1 = ~0ULL/0xF * 0x7;
const uint64_t c2 = ~0ULL/0xF * 0x3;
a |= (a >> 1) & c1; // cascade ones in non-zeroed segments
a |= (a >> 2) & c2;
a &= m; // isolate single bit in each segment
if (zero)
a ^= m; // reverse isolated bits if checking for zeroed segments
return a;
}
else if (width == 8) {
const uint64_t m = ~0ULL/0xFF * 0x1;
// Masks to avoid spillover between segments in cascades
const uint64_t c1 = ~0ULL/0xFF * 0x7F;
const uint64_t c2 = ~0ULL/0xFF * 0x3F;
const uint64_t c3 = ~0ULL/0xFF * 0x0F;
a |= (a >> 1) & c1; // cascade ones in non-zeroed segments
a |= (a >> 2) & c2;
a |= (a >> 4) & c3;
a &= m; // isolate single bit in each segment
if (zero)
a ^= m; // reverse isolated bits if checking for zeroed segments
return a;
}
else if (width == 16) {
const uint64_t m = ~0ULL/0xFFFF * 0x1;
// Masks to avoid spillover between segments in cascades
const uint64_t c1 = ~0ULL/0xFFFF * 0x7FFF;
const uint64_t c2 = ~0ULL/0xFFFF * 0x3FFF;
const uint64_t c3 = ~0ULL/0xFFFF * 0x0FFF;
const uint64_t c4 = ~0ULL/0xFFFF * 0x00FF;
a |= (a >> 1) & c1; // cascade ones in non-zeroed segments
a |= (a >> 2) & c2;
a |= (a >> 4) & c3;
a |= (a >> 8) & c4;
a &= m; // isolate single bit in each segment
if (zero)
a ^= m; // reverse isolated bits if checking for zeroed segments
return a;
}
else if (width == 32) {
const uint64_t m = ~0ULL/0xFFFFFFFF * 0x1;
// Masks to avoid spillover between segments in cascades
const uint64_t c1 = ~0ULL/0xFFFFFFFF * 0x7FFFFFFF;
const uint64_t c2 = ~0ULL/0xFFFFFFFF * 0x3FFFFFFF;
const uint64_t c3 = ~0ULL/0xFFFFFFFF * 0x0FFFFFFF;
const uint64_t c4 = ~0ULL/0xFFFFFFFF * 0x00FFFFFF;
const uint64_t c5 = ~0ULL/0xFFFFFFFF * 0x0000FFFF;
a |= (a >> 1) & c1; // cascade ones in non-zeroed segments
a |= (a >> 2) & c2;
a |= (a >> 4) & c3;
a |= (a >> 8) & c4;
a |= (a >> 16) & c5;
a &= m; // isolate single bit in each segment
if (zero)
a ^= m; // reverse isolated bits if checking for zeroed segments
return a;
}
else if (width == 64) {
return (a == 0) == zero;
}
else {
REALM_ASSERT_DEBUG(false);
return uint64_t(-1);
}
}
// This is the main finding function for Array. Other finding functions are just wrappers around this one.
// Search for 'value' using condition cond (Equal, NotEqual, Less, etc) and call find_action() or find_action_pattern()
// for each match. Break and return if find_action() returns false or 'end' is reached.
// If nullable_array is set, then find_optimized() will treat the array is being nullable, i.e. it will skip the
// first entry and compare correctly against null, etc.
//
// If find_null is set, it means that we search for a null. In that case, `value` is ignored. If find_null is set,
// then nullable_array must be set too.
template<class cond, Action action, size_t bitwidth, class Callback>
bool Array::find_optimized(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback, bool nullable_array, bool find_null) const
{
REALM_ASSERT(!(find_null && !nullable_array));
REALM_ASSERT_DEBUG(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end);
size_t start2 = start;
cond c;
if (end == npos)
end = nullable_array ? size() - 1 : size();
if (nullable_array) {
// We were called by find() of a nullable array. So skip first entry, take nulls in count, etc, etc. Fixme:
// Huge speed optimizations are possible here! This is a very simple generic method.
for (; start2 < end; start2++) {
int64_t v = get<bitwidth>(start2 + 1);
if (c(v, value, v == get(0), find_null)) {
util::Optional<int64_t> v2(v == get(0) ? util::none : util::make_optional(v));
if (!find_action<action, Callback>(start2 + baseindex, v2, state, callback))
return false; // tell caller to stop aggregating/search
}
}
return true; // tell caller to continue aggregating/search (on next array leafs)
}
// Test first few items with no initial time overhead
if (start2 > 0) {
if (m_size > start2 && c(get<bitwidth>(start2), value) && start2 < end) {
if (!find_action<action, Callback>(start2 + baseindex, get<bitwidth>(start2), state, callback))
return false;
}
++start2;
if (m_size > start2 && c(get<bitwidth>(start2), value) && start2 < end) {
if (!find_action<action, Callback>(start2 + baseindex, get<bitwidth>(start2), state, callback))
return false;
}
++start2;
if (m_size > start2 && c(get<bitwidth>(start2), value) && start2 < end) {
if (!find_action<action, Callback>(start2 + baseindex, get<bitwidth>(start2), state, callback))
return false;
}
++start2;
if (m_size > start2 && c(get<bitwidth>(start2), value) && start2 < end) {
if (!find_action<action, Callback>(start2 + baseindex, get<bitwidth>(start2), state, callback))
return false;
}
++start2;
}
if (!(m_size > start2 && start2 < end))
return true;
if (end == size_t(-1))
end = m_size;
// Return immediately if no items in array can match (such as if cond == Greater && value == 100 && m_ubound == 15)
if (!c.can_match(value, m_lbound, m_ubound))
return true;
// optimization if all items are guaranteed to match (such as cond == NotEqual && value == 100 && m_ubound == 15)
if (c.will_match(value, m_lbound, m_ubound)) {
size_t end2;
if (action == act_CallbackIdx)
end2 = end;
else {
REALM_ASSERT_DEBUG(state->m_match_count < state->m_limit);
size_t process = state->m_limit - state->m_match_count;
end2 = end - start2 > process ? start2 + process : end;
}
if (action == act_Sum || action == act_Max || action == act_Min) {
int64_t res;
size_t res_ndx = 0;
if (action == act_Sum)
res = Array::sum(start2, end2);
if (action == act_Max)
Array::maximum(res, start2, end2, &res_ndx);
if (action == act_Min)
Array::minimum(res, start2, end2, &res_ndx);
find_action<action, Callback>(res_ndx + baseindex, res, state, callback);
// find_action will increment match count by 1, so we need to `-1` from the number of elements that
// we performed the fast Array methods on.
state->m_match_count += end2 - start2 - 1;
}
else if (action == act_Count) {
state->m_state += end2 - start2;
}
else {
for (; start2 < end2; start2++)
if (!find_action<action, Callback>(start2 + baseindex, get<bitwidth>(start2), state, callback))
return false;
}
return true;
}
// finder cannot handle this bitwidth
REALM_ASSERT_3(m_width, !=, 0);
#if defined(REALM_COMPILER_SSE)
// Only use SSE if payload is at least one SSE chunk (128 bits) in size. Also note taht SSE doesn't support
// Less-than comparison for 64-bit values.
if ((!(std::is_same<cond, Less>::value && m_width == 64)) && end - start2 >= sizeof(__m128i) && m_width >= 8 &&
(sseavx<42>() || (sseavx<30>() && std::is_same<cond, Equal>::value && m_width < 64))) {
// find_sse() must start2 at 16-byte boundary, so search area before that using compare_equality()
__m128i* const a = reinterpret_cast<__m128i*>(round_up(m_data + start2 * bitwidth / 8, sizeof (__m128i)));
__m128i* const b = reinterpret_cast<__m128i*>(round_down(m_data + end * bitwidth / 8, sizeof (__m128i)));
if (!compare<cond, action, bitwidth, Callback>(value, start2, (reinterpret_cast<char*>(a) - m_data) * 8 / no0(bitwidth), baseindex, state, callback))
return false;
// Search aligned area with SSE
if (b > a) {
if (sseavx<42>()) {
if (!find_sse<cond, action, bitwidth, Callback>(value, a, b - a, state, baseindex + ((reinterpret_cast<char*>(a) - m_data) * 8 / no0(bitwidth)), callback))
return false;
}
else if (sseavx<30>()) {
if (!find_sse<Equal, action, bitwidth, Callback>(value, a, b - a, state, baseindex + ((reinterpret_cast<char*>(a) - m_data) * 8 / no0(bitwidth)), callback))
return false;
}
}
// Search remainder with compare_equality()
if (!compare<cond, action, bitwidth, Callback>(value, (reinterpret_cast<char*>(b) - m_data) * 8 / no0(bitwidth), end, baseindex, state, callback))
return false;
return true;
}
else {
return compare<cond, action, bitwidth, Callback>(value, start2, end, baseindex, state, callback);
}
#else
return compare<cond, action, bitwidth, Callback>(value, start2, end, baseindex, state, callback);
#endif
}
template<size_t width>
inline int64_t Array::lower_bits() const
{
if (width == 1)
return 0xFFFFFFFFFFFFFFFFULL;
else if (width == 2)
return 0x5555555555555555ULL;
else if (width == 4)
return 0x1111111111111111ULL;
else if (width == 8)
return 0x0101010101010101ULL;
else if (width == 16)
return 0x0001000100010001ULL;
else if (width == 32)
return 0x0000000100000001ULL;
else if (width == 64)
return 0x0000000000000001ULL;
else {
REALM_ASSERT_DEBUG(false);
return int64_t(-1);
}
}
// Tests if any chunk in 'value' is 0
template<size_t width>
inline bool Array::test_zero(uint64_t value) const
{
uint64_t hasZeroByte;
uint64_t lower = lower_bits<width>();
uint64_t upper = lower_bits<width>() * 1ULL << (width == 0 ? 0 : (width - 1ULL));
hasZeroByte = (value - lower) & ~value & upper;
return hasZeroByte != 0;
}
// Finds first zero (if eq == true) or non-zero (if eq == false) element in v and returns its position.
// IMPORTANT: This function assumes that at least 1 item matches (test this with test_zero() or other means first)!
template<bool eq, size_t width>
size_t Array::find_zero(uint64_t v) const
{
size_t start = 0;
uint64_t hasZeroByte;
// Warning free way of computing (1ULL << width) - 1
uint64_t mask = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - 1ULL));
if (eq == (((v >> (width * start)) & mask) == 0)) {
return 0;
}
// Bisection optimization, speeds up small bitwidths with high match frequency. More partions than 2 do NOT pay
// off because the work done by test_zero() is wasted for the cases where the value exists in first half, but
// useful if it exists in last half. Sweet spot turns out to be the widths and partitions below.
if (width <= 8) {
hasZeroByte = test_zero<width>(v | 0xffffffff00000000ULL);
if (eq ? !hasZeroByte : (v & 0x00000000ffffffffULL) == 0) {
// 00?? -> increasing
start += 64 / no0(width) / 2;
if (width <= 4) {
hasZeroByte = test_zero<width>(v | 0xffff000000000000ULL);
if (eq ? !hasZeroByte : (v & 0x0000ffffffffffffULL) == 0) {
// 000?
start += 64 / no0(width) / 4;
}
}
}
else {
if (width <= 4) {
// ??00
hasZeroByte = test_zero<width>(v | 0xffffffffffff0000ULL);
if (eq ? !hasZeroByte : (v & 0x000000000000ffffULL) == 0) {
// 0?00
start += 64 / no0(width) / 4;
}
}
}
}
while (eq == (((v >> (width * start)) & mask) != 0)) {
// You must only call find_zero() if you are sure that at least 1 item matches
REALM_ASSERT_3(start, <=, 8 * sizeof(v));
start++;
}
return start;
}
// Generate a magic constant used for later bithacks
template<bool gt, size_t width>
int64_t Array::find_gtlt_magic(int64_t v) const
{
uint64_t mask1 = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); // Warning free way of computing (1ULL << width) - 1
uint64_t mask2 = mask1 >> 1;
uint64_t magic = gt ? (~0ULL / no0(mask1) * (mask2 - v)) : (~0ULL / no0(mask1) * v);
return magic;
}
template<bool gt, Action action, size_t width, class Callback>
bool Array::find_gtlt_fast(uint64_t chunk, uint64_t magic, QueryState<int64_t>* state, size_t baseindex, Callback callback) const
{
// Tests if a a chunk of values contains values that are greater (if gt == true) or less (if gt == false) than v.
// Fast, but limited to work when all values in the chunk are positive.
uint64_t mask1 = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); // Warning free way of computing (1ULL << width) - 1
uint64_t mask2 = mask1 >> 1;
uint64_t m = gt ? (((chunk + magic) | chunk) & ~0ULL / no0(mask1) * (mask2 + 1)) : ((chunk - magic) & ~chunk&~0ULL/no0(mask1)*(mask2+1));
size_t p = 0;
while (m) {
if (find_action_pattern<action, Callback>(baseindex, m >> (no0(width) - 1), state, callback))
break; // consumed, so do not call find_action()
size_t t = first_set_bit64(m) / no0(width);
p += t;
if (!find_action<action, Callback>(p + baseindex, (chunk >> (p * width)) & mask1, state, callback))
return false;
if ((t + 1) * width == 64)
m = 0;
else
m >>= (t + 1) * width;
p++;
}
return true;
}
template<bool gt, Action action, size_t width, class Callback>
bool Array::find_gtlt(int64_t v, uint64_t chunk, QueryState<int64_t>* state, size_t baseindex, Callback callback) const
{
// Find items in 'chunk' that are greater (if gt == true) or smaller (if gt == false) than 'v'. Fixme, __forceinline can make it crash in vS2010 - find out why
if (width == 1) {
for (size_t t = 0; t < 64; t++) {
if (gt ? static_cast<int64_t>(chunk & 0x1) > v : static_cast<int64_t>(chunk & 0x1) < v) {if (!find_action<action, Callback>( t + baseindex, static_cast<int64_t>(chunk & 0x1), state, callback)) return false;} chunk >>= 1;
}
}
else if (width == 2) {
// Alot (50% +) faster than loop/compiler-unrolled loop
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 1 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 2 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 3 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 4 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 5 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 6 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 7 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 8 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 9 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 10 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 11 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 12 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 13 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 14 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 15 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 16 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 17 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 18 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 19 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 20 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 21 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 22 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 23 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 24 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 25 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 26 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 27 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 28 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 29 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 30 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
if (gt ? static_cast<int64_t>(chunk & 0x3) > v : static_cast<int64_t>(chunk & 0x3) < v) {if (!find_action<action, Callback>( 31 + baseindex, static_cast<int64_t>(chunk & 0x3), state, callback)) return false;} chunk >>= 2;
}
else if (width == 4) {
// 128 ms:
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 1 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 2 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 3 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 4 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 5 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 6 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 7 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 8 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 9 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 10 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 11 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 12 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 13 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 14 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
if (gt ? static_cast<int64_t>(chunk & 0xf) > v : static_cast<int64_t>(chunk & 0xf) < v) {if (!find_action<action, Callback>( 15 + baseindex, static_cast<int64_t>(chunk & 0xf), state, callback)) return false;} chunk >>= 4;
// 187 ms:
// if (gt ? static_cast<int64_t>(chunk >> 0*4) & 0xf > v : static_cast<int64_t>(chunk >> 0*4) & 0xf < v) return 0;
}
else if (width == 8) {
// 88 ms:
if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8;
if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 1 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8;
if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 2 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8;
if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 3 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8;
if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 4 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8;
if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 5 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8;
if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 6 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8;
if (gt ? static_cast<int8_t>(chunk) > v : static_cast<int8_t>(chunk) < v) {if (!find_action<action, Callback>( 7 + baseindex, static_cast<int8_t>(chunk), state, callback)) return false;} chunk >>= 8;
//97 ms ms:
// if (gt ? static_cast<int8_t>(chunk >> 0*8) > v : static_cast<int8_t>(chunk >> 0*8) < v) return 0;
}
else if (width == 16) {
if (gt ? static_cast<short int>(chunk >> 0*16) > v : static_cast<short int>(chunk >> 0*16) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<short int>(chunk >> 0*16), state, callback)) return false;};
if (gt ? static_cast<short int>(chunk >> 1*16) > v : static_cast<short int>(chunk >> 1*16) < v) {if (!find_action<action, Callback>( 1 + baseindex, static_cast<short int>(chunk >> 1*16), state, callback)) return false;};
if (gt ? static_cast<short int>(chunk >> 2*16) > v : static_cast<short int>(chunk >> 2*16) < v) {if (!find_action<action, Callback>( 2 + baseindex, static_cast<short int>(chunk >> 2*16), state, callback)) return false;};
if (gt ? static_cast<short int>(chunk >> 3*16) > v : static_cast<short int>(chunk >> 3*16) < v) {if (!find_action<action, Callback>( 3 + baseindex, static_cast<short int>(chunk >> 3*16), state, callback)) return false;};
/*
// Faster but disabled due to bug in VC2010 compiler (fixed in 2012 toolchain) where last 'if' is errorneously optimized away
if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {if (!state->add_positive_local(0 + baseindex); else return 0;} chunk >>= 16;
if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {if (!state->add_positive_local(1 + baseindex); else return 1;} chunk >>= 16;
if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {if (!state->add_positive_local(2 + baseindex); else return 2;} chunk >>= 16;
if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {if (!state->add_positive_local(3 + baseindex); else return 3;} chunk >>= 16;
// Following illustrates it:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
size_t bug(int64_t v, uint64_t chunk)
{
bool gt = true;
if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {return 0;} chunk >>= 16;
if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {return 1;} chunk >>= 16;
if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {return 2;} chunk >>= 16;
if (gt ? static_cast<short int>chunk > v : static_cast<short int>chunk < v) {return 3;} chunk >>= 16;
return -1;
}
int main(int argc, char const *const argv[])
{
int64_t v;
FIXME: We cannot use rand() as it is not thread-safe.
if (rand()*rand() == 3) {
v = rand()*rand()*rand()*rand()*rand();
printf("Change '3' to something else and run test again\n");
}
else {
v = 0x2222000000000000ULL;
}
size_t idx;
idx = bug(200, v);
if (idx != 3)
printf("Compiler failed: idx == %d (expected idx == 3)\n", idx);
v = 0x2222000000000000ULL;
idx = bug(200, v);
if (idx == 3)
printf("Touching v made it work\n", idx);
}
*/
}
else if (width == 32) {
if (gt ? static_cast<int>(chunk) > v : static_cast<int>(chunk) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<int>(chunk), state, callback)) return false;} chunk >>= 32;
if (gt ? static_cast<int>(chunk) > v : static_cast<int>(chunk) < v) {if (!find_action<action, Callback>( 1 + baseindex, static_cast<int>(chunk), state, callback)) return false;} chunk >>= 32;
}
else if (width == 64) {
if (gt ? static_cast<int64_t>(v) > v : static_cast<int64_t>(v) < v) {if (!find_action<action, Callback>( 0 + baseindex, static_cast<int64_t>(v), state, callback)) return false;};
}
return true;
}
template<bool eq, Action action, size_t width, class Callback>
inline bool Array::compare_equality(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const
{
// Find items in this Array that are equal (eq == true) or different (eq = false) from 'value'
REALM_ASSERT_DEBUG(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end);
size_t ee = round_up(start, 64 / no0(width));
ee = ee > end ? end : ee;
for (; start < ee; ++start)
if (eq ? (get<width>(start) == value) : (get<width>(start) != value)) {
if (!find_action<action, Callback>(start + baseindex, get<width>(start), state, callback))
return false;
}
if (start >= end)
return true;
if (width != 32 && width != 64) {
const int64_t* p = reinterpret_cast<const int64_t*>(m_data + (start * width / 8));
const int64_t* const e = reinterpret_cast<int64_t*>(m_data + (end * width / 8)) - 1;
const uint64_t mask = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); // Warning free way of computing (1ULL << width) - 1
const uint64_t valuemask = ~0ULL / no0(mask) * (value & mask); // the "== ? :" is to avoid division by 0 compiler error
while (p < e) {
uint64_t chunk = *p;
uint64_t v2 = chunk ^ valuemask;
start = (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(width);
size_t a = 0;
while (eq ? test_zero<width>(v2) : v2) {
if (find_action_pattern<action, Callback>(start + baseindex, cascade<width, eq>(v2), state, callback))
break; // consumed
size_t t = find_zero<eq, width>(v2);
a += t;
if (a >= 64 / no0(width))
break;
if (!find_action<action, Callback>(a + start + baseindex, get<width>(start + t), state, callback))
return false;
v2 >>= (t + 1) * width;
a += 1;
}
++p;
}
// Loop ended because we are near end or end of array. No need to optimize search in remainder in this case because end of array means that
// lots of search work has taken place prior to ending here. So time spent searching remainder is relatively tiny
start = (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(width);
}
while (start < end) {
if (eq ? get<width>(start) == value : get<width>(start) != value) {
if (!find_action<action, Callback>( start + baseindex, get<width>(start), state, callback))
return false;
}
++start;
}
return true;
}
// There exists a couple of find() functions that take more or less template arguments. Always call the one that
// takes as most as possible to get best performance.
// This is the one installed into the m_vtable->finder slots.
template<class cond, Action action, size_t bitwidth>
bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state) const
{
return find<cond, action, bitwidth>(value, start, end, baseindex, state, CallbackDummy());
}
template<class cond, Action action, class Callback>
bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state,
Callback callback, bool nullable_array, bool find_null) const
{
REALM_TEMPEX4(return find, cond, action, m_width, Callback, (value, start, end, baseindex, state, callback, nullable_array, find_null));
}
template<class cond, Action action, size_t bitwidth, class Callback>
bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state,
Callback callback, bool nullable_array, bool find_null) const
{
return find_optimized<cond, action, bitwidth, Callback>(value, start, end, baseindex, state, callback, nullable_array, find_null);
}
#ifdef REALM_COMPILER_SSE
// 'items' is the number of 16-byte SSE chunks. Returns index of packed element relative to first integer of first chunk
template<class cond, Action action, size_t width, class Callback>
bool Array::find_sse(int64_t value, __m128i *data, size_t items, QueryState<int64_t>* state, size_t baseindex,
Callback callback) const
{
__m128i search = {0};
// FIXME: Lasse, should these casts not be to int8_t, int16_t, int32_t respecitvely?
if (width == 8)
search = _mm_set1_epi8(static_cast<char>(value)); // FIXME: Lasse, Should this not be a cast to 'signed char'?
else if (width == 16)
search = _mm_set1_epi16(static_cast<short int>(value));
else if (width == 32)
search = _mm_set1_epi32(static_cast<int>(value));
else if (width == 64) {
if (std::is_same<cond, Less>::value)
REALM_ASSERT(false);
else
search = _mm_set_epi64x(value, value);
}
return find_sse_intern<cond, action, width, Callback>(data, &search, items, state, baseindex, callback);
}
// Compares packed action_data with packed data (equal, less, etc) and performs aggregate action (max, min, sum,
// find_all, etc) on value inside action_data for first match, if any
template<class cond, Action action, size_t width, class Callback>
REALM_FORCEINLINE bool Array::find_sse_intern(__m128i* action_data, __m128i* data, size_t items,
QueryState<int64_t>* state, size_t baseindex, Callback callback) const
{
size_t i = 0;
__m128i compare = {0};
unsigned int resmask;
// Search loop. Unrolling it has been tested to NOT increase performance (apparently mem bound)
for (i = 0; i < items; ++i) {
// equal / not-equal
if (std::is_same<cond, Equal>::value || std::is_same<cond, NotEqual>::value) {
if (width == 8)
compare = _mm_cmpeq_epi8(action_data[i], *data);
if (width == 16)
compare = _mm_cmpeq_epi16(action_data[i], *data);
if (width == 32)
compare = _mm_cmpeq_epi32(action_data[i], *data);
if (width == 64) {
compare = _mm_cmpeq_epi64(action_data[i], *data); // SSE 4.2 only
}
}
// greater
else if (std::is_same<cond, Greater>::value) {
if (width == 8)
compare = _mm_cmpgt_epi8(action_data[i], *data);
if (width == 16)
compare = _mm_cmpgt_epi16(action_data[i], *data);
if (width == 32)
compare = _mm_cmpgt_epi32(action_data[i], *data);
if (width == 64)
compare = _mm_cmpgt_epi64(action_data[i], *data);
}
// less
else if (std::is_same<cond, Less>::value) {
if (width == 8)
compare = _mm_cmplt_epi8(action_data[i], *data);
else if (width == 16)
compare = _mm_cmplt_epi16(action_data[i], *data);
else if (width == 32)
compare = _mm_cmplt_epi32(action_data[i], *data);
else
REALM_ASSERT(false);
}
resmask = _mm_movemask_epi8(compare);
if (std::is_same<cond, NotEqual>::value)
resmask = ~resmask & 0x0000ffff;
// if (resmask != 0)
// printf("resmask=%d\n", resmask);
size_t s = i * sizeof (__m128i) * 8 / no0(width);
while (resmask != 0) {
uint64_t upper = lower_bits<width / 8>() << (no0(width / 8) - 1);
uint64_t pattern = resmask & upper; // fixme, bits at wrong offsets. Only OK because we only use them in 'count' aggregate
if (find_action_pattern<action, Callback>(s + baseindex, pattern, state, callback))
break;
size_t idx = first_set_bit(resmask) * 8 / no0(width);
s += idx;
if (!find_action<action, Callback>( s + baseindex, get_universal<width>(reinterpret_cast<char*>(action_data), s), state, callback))
return false;
resmask >>= (idx + 1) * no0(width) / 8;
++s;
}
}
return true;
}
#endif //REALM_COMPILER_SSE
template<class cond, Action action, class Callback>
bool Array::compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state,
Callback callback) const
{
cond c;
REALM_ASSERT_3(start, <=, end);
if (start == end)
return true;
int64_t v;
// We can compare first element without checking for out-of-range
v = get(start);
if (c(v, foreign->get(start))) {
if (!find_action<action, Callback>(start + baseindex, v, state, callback))
return false;
}
start++;
if (start + 3 < end) {
v = get(start);
if (c(v, foreign->get(start)))
if (!find_action<action, Callback>(start + baseindex, v, state, callback))
return false;
v = get(start + 1);
if (c(v, foreign->get(start + 1)))
if (!find_action<action, Callback>(start + 1 + baseindex, v, state, callback))
return false;
v = get(start + 2);
if (c(v, foreign->get(start + 2)))
if (!find_action<action, Callback>(start + 2 + baseindex, v, state, callback))
return false;
start += 3;
}
else if (start == end) {
return true;
}
bool r;
REALM_TEMPEX4(r = compare_leafs, cond, action, m_width, Callback, (foreign, start, end, baseindex, state, callback))
return r;
}
template<class cond, Action action, size_t width, class Callback>
bool Array::compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state, Callback callback) const
{
size_t fw = foreign->m_width;
bool r;
REALM_TEMPEX5(r = compare_leafs_4, cond, action, width, Callback, fw, (foreign, start, end, baseindex, state, callback))
return r;
}
template<class cond, Action action, size_t width, class Callback, size_t foreign_width>
bool Array::compare_leafs_4(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state,
Callback callback) const
{
cond c;
char* foreign_m_data = foreign->m_data;
if (width == 0 && foreign_width == 0) {
if (c(0, 0)) {
while (start < end) {
if (!find_action<action, Callback>(start + baseindex, 0, state, callback))
return false;
start++;
}
}
else {
return true;
}
}
#if defined(REALM_COMPILER_SSE)
if (sseavx<42>() && width == foreign_width && (width == 8 || width == 16 || width == 32)) {
// We can only use SSE if both bitwidths are equal and above 8 bits and all values are signed
while (start < end && (((reinterpret_cast<size_t>(m_data) & 0xf) * 8 + start * width) % (128) != 0)) {
int64_t v = get_universal<width>(m_data, start);
int64_t fv = get_universal<foreign_width>(foreign_m_data, start);
if (c(v, fv)) {
if (!find_action<action, Callback>(start + baseindex, v, state, callback))
return false;
}
start++;
}
if (start == end)
return true;
size_t sse_items = (end - start) * width / 128;
size_t sse_end = start + sse_items * 128 / no0(width);
while (start < sse_end) {
__m128i* a = reinterpret_cast<__m128i*>(m_data + start * width / 8);
__m128i* b = reinterpret_cast<__m128i*>(foreign_m_data + start * width / 8);
bool continue_search = find_sse_intern<cond, action, width, Callback>(a, b, 1, state, baseindex + start, callback);
if (!continue_search)
return false;
start += 128 / no0(width);
}
}
#endif
#if 0 // this method turned out to be 33% slower than a naive loop. Find out why
// index from which both arrays are 64-bit aligned
size_t a = round_up(start, 8 * sizeof (int64_t) / (width < foreign_width ? width : foreign_width));
while (start < end && start < a) {
int64_t v = get_universal<width>(m_data, start);
int64_t fv = get_universal<foreign_width>(foreign_m_data, start);
if (v == fv)
r++;
start++;
}
if (start >= end)
return r;
uint64_t chunk;
uint64_t fchunk;
size_t unroll_outer = (foreign_width > width ? foreign_width : width) / (foreign_width < width ? foreign_width : width);
size_t unroll_inner = 64 / (foreign_width > width ? foreign_width : width);
while (start + unroll_outer * unroll_inner < end) {
// fetch new most narrow chunk
if (foreign_width <= width)
fchunk = *reinterpret_cast<int64_t*>(foreign_m_data + start * foreign_width / 8);
else
chunk = *reinterpret_cast<int64_t*>(m_data + start * width / 8);
for (size_t uo = 0; uo < unroll_outer; uo++) {
// fetch new widest chunk
if (foreign_width > width)
fchunk = *reinterpret_cast<int64_t*>(foreign_m_data + start * foreign_width / 8);
else
chunk = *reinterpret_cast<int64_t*>(m_data + start * width / 8);
size_t newstart = start + unroll_inner;
while (start < newstart) {
// Isolate first value from chunk
int64_t v = (chunk << (64 - width)) >> (64 - width);
int64_t fv = (fchunk << (64 - foreign_width)) >> (64 - foreign_width);
chunk >>= width;
fchunk >>= foreign_width;
// Sign extend if required
v = (width <= 4) ? v : (width == 8) ? int8_t(v) : (width == 16) ? int16_t(v) : (width == 32) ? int32_t(v) : int64_t(v);
fv = (foreign_width <= 4) ? fv : (foreign_width == 8) ? int8_t(fv) : (foreign_width == 16) ? int16_t(fv) : (foreign_width == 32) ? int32_t(fv) : int64_t(fv);
if (v == fv)
r++;
start++;
}
}
}
#endif
/*
// Unrolling helped less than 2% (non-frequent matches). Todo, investigate further
while (start + 1 < end) {
int64_t v = get_universal<width>(m_data, start);
int64_t v2 = get_universal<width>(m_data, start + 1);
int64_t fv = get_universal<foreign_width>(foreign_m_data, start);
int64_t fv2 = get_universal<foreign_width>(foreign_m_data, start + 1);
if (c(v, fv)) {
if (!find_action<action, Callback>(start + baseindex, v, state, callback))
return false;
}
if (c(v2, fv2)) {
if (!find_action<action, Callback>(start + 1 + baseindex, v2, state, callback))
return false;
}
start += 2;
}
*/
while (start < end) {
int64_t v = get_universal<width>(m_data, start);
int64_t fv = get_universal<foreign_width>(foreign_m_data, start);
if (c(v, fv)) {
if (!find_action<action, Callback>(start + baseindex, v, state, callback))
return false;
}
start++;
}
return true;
}
template<class cond, Action action, size_t bitwidth, class Callback>
bool Array::compare(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state,
Callback callback) const
{
bool ret = false;
if (std::is_same<cond, Equal>::value)
ret = compare_equality<true, action, bitwidth, Callback>(value, start, end, baseindex, state, callback);
else if (std::is_same<cond, NotEqual>::value)
ret = compare_equality<false, action, bitwidth, Callback>(value, start, end, baseindex, state, callback);
else if (std::is_same<cond, Greater>::value)
ret = compare_relation<true, action, bitwidth, Callback>(value, start, end, baseindex, state, callback);
else if (std::is_same<cond, Less>::value)
ret = compare_relation<false, action, bitwidth, Callback>(value, start, end, baseindex, state, callback);
else
REALM_ASSERT_DEBUG(false);
return ret;
}
template<bool gt, Action action, size_t bitwidth, class Callback>
bool Array::compare_relation(int64_t value, size_t start, size_t end, size_t baseindex, QueryState<int64_t>* state,
Callback callback) const
{
REALM_ASSERT(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end);
uint64_t mask = (bitwidth == 64 ? ~0ULL : ((1ULL << (bitwidth == 64 ? 0 : bitwidth)) - 1ULL)); // Warning free way of computing (1ULL << width) - 1
size_t ee = round_up(start, 64 / no0(bitwidth));
ee = ee > end ? end : ee;
for (; start < ee; start++) {
if (gt ? (get<bitwidth>(start) > value) : (get<bitwidth>(start) < value)) {
if (!find_action<action, Callback>(start + baseindex, get<bitwidth>(start), state, callback))
return false;
}
}
if (start >= end)
return true; // none found, continue (return true) regardless what find_action() would have returned on match
const int64_t* p = reinterpret_cast<const int64_t*>(m_data + (start * bitwidth / 8));
const int64_t* const e = reinterpret_cast<int64_t*>(m_data + (end * bitwidth / 8)) - 1;
// Matches are rare enough to setup fast linear search for remaining items. We use
// bit hacks from http://graphics.stanford.edu/~seander/bithacks.html#HasLessInWord
if (bitwidth == 1 || bitwidth == 2 || bitwidth == 4 || bitwidth == 8 || bitwidth == 16) {
uint64_t magic = find_gtlt_magic<gt, bitwidth>(value);
// Bit hacks only work if searched item has its most significant bit clear for 'greater than' or
// 'item <= 1 << bitwidth' for 'less than'
if (value != int64_t((magic & mask)) && value >= 0 && bitwidth >= 2 && value <= static_cast<int64_t>((mask >> 1) - (gt ? 1 : 0))) {
// 15 ms
while (p < e) {
uint64_t upper = lower_bits<bitwidth>() << (no0(bitwidth) - 1);
const int64_t v = *p;
size_t idx;
// Bit hacks only works if all items in chunk have their most significant bit clear. Test this:
upper = upper & v;
if (!upper) {
idx = find_gtlt_fast<gt, action, bitwidth, Callback>(v, magic, state, (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, callback);
}
else
idx = find_gtlt<gt, action, bitwidth, Callback>(value, v, state, (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, callback);
if (!idx)
return false;
++p;
}
}
else {
// 24 ms
while (p < e) {
int64_t v = *p;
if (!find_gtlt<gt, action, bitwidth, Callback>(value, v, state, (p - reinterpret_cast<int64_t*>(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, callback))
return false;
++p;
}
}
start = (p - reinterpret_cast<int64_t *>(m_data)) * 8 * 8 / no0(bitwidth);
}
// matchcount logic in SIMD no longer pays off for 32/64 bit ints because we have just 4/2 elements
// Test unaligned end and/or values of width > 16 manually
while (start < end) {
if (gt ? get<bitwidth>(start) > value : get<bitwidth>(start) < value) {
if (!find_action<action, Callback>( start + baseindex, get<bitwidth>(start), state, callback))
return false;
}
++start;
}
return true;
}
template<class cond>
size_t Array::find_first(int64_t value, size_t start, size_t end) const
{
REALM_ASSERT(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end);
QueryState<int64_t> state;
state.init(act_ReturnFirst, nullptr, 1); // todo, would be nice to avoid this in order to speed up find_first loops
Finder finder = m_vtable->finder[cond::condition];
(this->*finder)(value, start, end, 0, &state);
return static_cast<size_t>(state.m_state);
}
//*************************************************************************************
// Finding code ends *
//*************************************************************************************
} // namespace realm
#endif // REALM_ARRAY_HPP
| [
"mendes-barreto@live.com"
] | mendes-barreto@live.com |
5ee45b96fd25be305fe7364d4f8a2fccbee075b4 | c1ff870879152fba2b54eddfb7591ec322eb3061 | /plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/deps/v8/src/compiler/ppc/instruction-scheduler-ppc.cc | 2b491f1b803fcfb80867caa5ee70feab6159b379 | [
"ISC",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"Artistic-2.0",
"NAIST-2003",
"MIT",
"BSD-3-Clause",
"Zlib",
"NTP",
"LicenseRef-scancode-openssl",
"ICU",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-unknown-license-reference",
"bzip2-1.0.6",
"SunPro",
"LicenseRef-sca... | permissive | MTASZTAKI/ApertusVR | 1a9809fb7af81c3cd7fb732ed481ebe4ce66fefa | 424ec5515ae08780542f33cc4841a8f9a96337b3 | refs/heads/0.9 | 2022-12-11T20:03:42.926813 | 2019-10-11T09:29:45 | 2019-10-11T09:29:45 | 73,708,854 | 188 | 55 | MIT | 2022-12-11T08:53:21 | 2016-11-14T13:48:00 | C++ | UTF-8 | C++ | false | false | 4,027 | cc | // Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/instruction-scheduler.h"
namespace v8 {
namespace internal {
namespace compiler {
bool InstructionScheduler::SchedulerSupported() { return true; }
int InstructionScheduler::GetTargetInstructionFlags(
const Instruction* instr) const {
switch (instr->arch_opcode()) {
case kPPC_And:
case kPPC_AndComplement:
case kPPC_Or:
case kPPC_OrComplement:
case kPPC_Xor:
case kPPC_ShiftLeft32:
case kPPC_ShiftLeft64:
case kPPC_ShiftLeftPair:
case kPPC_ShiftRight32:
case kPPC_ShiftRight64:
case kPPC_ShiftRightPair:
case kPPC_ShiftRightAlg32:
case kPPC_ShiftRightAlg64:
case kPPC_ShiftRightAlgPair:
case kPPC_RotRight32:
case kPPC_RotRight64:
case kPPC_Not:
case kPPC_RotLeftAndMask32:
case kPPC_RotLeftAndClear64:
case kPPC_RotLeftAndClearLeft64:
case kPPC_RotLeftAndClearRight64:
case kPPC_Add32:
case kPPC_Add64:
case kPPC_AddWithOverflow32:
case kPPC_AddPair:
case kPPC_AddDouble:
case kPPC_Sub:
case kPPC_SubWithOverflow32:
case kPPC_SubPair:
case kPPC_SubDouble:
case kPPC_Mul32:
case kPPC_Mul32WithHigh32:
case kPPC_Mul64:
case kPPC_MulHigh32:
case kPPC_MulHighU32:
case kPPC_MulPair:
case kPPC_MulDouble:
case kPPC_Div32:
case kPPC_Div64:
case kPPC_DivU32:
case kPPC_DivU64:
case kPPC_DivDouble:
case kPPC_Mod32:
case kPPC_Mod64:
case kPPC_ModU32:
case kPPC_ModU64:
case kPPC_ModDouble:
case kPPC_Neg:
case kPPC_NegDouble:
case kPPC_SqrtDouble:
case kPPC_FloorDouble:
case kPPC_CeilDouble:
case kPPC_TruncateDouble:
case kPPC_RoundDouble:
case kPPC_MaxDouble:
case kPPC_MinDouble:
case kPPC_AbsDouble:
case kPPC_Cntlz32:
case kPPC_Cntlz64:
case kPPC_Popcnt32:
case kPPC_Popcnt64:
case kPPC_Cmp32:
case kPPC_Cmp64:
case kPPC_CmpDouble:
case kPPC_Tst32:
case kPPC_Tst64:
case kPPC_ExtendSignWord8:
case kPPC_ExtendSignWord16:
case kPPC_ExtendSignWord32:
case kPPC_Uint32ToUint64:
case kPPC_Int64ToInt32:
case kPPC_Int64ToFloat32:
case kPPC_Int64ToDouble:
case kPPC_Uint64ToFloat32:
case kPPC_Uint64ToDouble:
case kPPC_Int32ToFloat32:
case kPPC_Int32ToDouble:
case kPPC_Uint32ToFloat32:
case kPPC_Uint32ToDouble:
case kPPC_Float32ToDouble:
case kPPC_Float64SilenceNaN:
case kPPC_DoubleToInt32:
case kPPC_DoubleToUint32:
case kPPC_DoubleToInt64:
case kPPC_DoubleToUint64:
case kPPC_DoubleToFloat32:
case kPPC_DoubleExtractLowWord32:
case kPPC_DoubleExtractHighWord32:
case kPPC_DoubleInsertLowWord32:
case kPPC_DoubleInsertHighWord32:
case kPPC_DoubleConstruct:
case kPPC_BitcastInt32ToFloat32:
case kPPC_BitcastFloat32ToInt32:
case kPPC_BitcastInt64ToDouble:
case kPPC_BitcastDoubleToInt64:
return kNoOpcodeFlags;
case kPPC_LoadWordS8:
case kPPC_LoadWordU8:
case kPPC_LoadWordS16:
case kPPC_LoadWordU16:
case kPPC_LoadWordS32:
case kPPC_LoadWordU32:
case kPPC_LoadWord64:
case kPPC_LoadFloat32:
case kPPC_LoadDouble:
return kIsLoadOperation;
case kPPC_StoreWord8:
case kPPC_StoreWord16:
case kPPC_StoreWord32:
case kPPC_StoreWord64:
case kPPC_StoreFloat32:
case kPPC_StoreDouble:
case kPPC_Push:
case kPPC_PushFrame:
case kPPC_StoreToStackSlot:
return kHasSideEffect;
#define CASE(Name) case k##Name:
COMMON_ARCH_OPCODE_LIST(CASE)
#undef CASE
// Already covered in architecture independent code.
UNREACHABLE();
}
UNREACHABLE();
}
int InstructionScheduler::GetInstructionLatency(const Instruction* instr) {
// TODO(all): Add instruction cost modeling.
return 1;
}
} // namespace compiler
} // namespace internal
} // namespace v8
| [
"peter.kovacs@sztaki.mta.hu"
] | peter.kovacs@sztaki.mta.hu |
2efb8bac6709a25fc33e56cd4427d59ccbd9cd76 | d90bb820a517727f4d3f1972f235d7bbbec2a187 | /cpp/vision/opencv_utils.cpp | a4ca355976b210904b79d2f216a8a1ccd6d8e369 | [] | no_license | umariqb/Multi-Person-Pose-Estimation-using-LJPA-ECCVW-2016 | bf83edce518d0d59ac54ee57d4014062655c9d68 | 9fde830e974b5c5453b77c3a07bbc8a8df3ae9d7 | refs/heads/master | 2021-09-23T09:49:01.864657 | 2018-09-21T08:52:15 | 2018-09-21T08:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,871 | cpp | /*
* opencvutils.cpp
*
* Created on: Apr 30, 2013
* Author: mdantone
*/
#include "opencv_utils.hpp"
#include "geometry_utils.hpp"
#include <glog/logging.h>
using namespace cv;
namespace vision {
namespace opencv_utils {
void rect_to_string(Rect rect, string s = "" ) {
LOG(INFO) << s << rect.x << " " << rect.y << " " << rect.width << " " << rect.height;
}
Mat extract_roi(const Mat img, const Rect roi) {
Mat roi_img;
Rect inter = ::vision::geometry_utils::intersect(Rect(0,0, img.cols, img.rows), roi );
// roi is within the matrix
if( inter.width == roi.width && inter.height == roi.height) {
roi_img = img(roi).clone();
}else{
roi_img = Mat(roi.height, roi.width, img.type(), Scalar(0) );
cv::Mat min(1,1,CV_8UC1, cv::Scalar::all(0));
cv::Mat max(1,1,CV_8UC1, cv::Scalar::all(255));
cv::theRNG().fill(roi_img, cv::RNG::UNIFORM, min, max);
Rect inter_roi = Rect(0,0,inter.width,inter.height);
Rect inter_img = Rect(roi.x,roi.y,inter.width,inter.height);
if(inter.width != roi.width ) {
if(roi.x < 0) {
inter_roi.x = abs(roi.x);
inter_img.x = 0;
}else{
inter_img.x = roi.x;
}
}
if(inter.height != roi.height ) {
if(roi.y < 0) {
inter_roi.y = abs(roi.y);
inter_img.y = 0;
}else{
inter_img.y = roi.y;
}
}
roi_img(inter_roi).setTo(Scalar(0));
add( roi_img(inter_roi), img(inter_img), roi_img(inter_roi) );
}
return roi_img;
}
bool check_uniqueness( const std::vector<cv::Rect> rects, const cv::Rect rect ) {
for(int i=0; i < rects.size(); i++) {
if( (rect.x == rects[i].x) && (rect.y == rects[i].y) &&
(rect.width == rects[i].width) && (rect.height == rects[i].height)) {
return false;
}
}
return true;
}
} /* namespace opencv_utils */
} /* namespace vision */
| [
"uiqbal@iai.uni-bonn.de"
] | uiqbal@iai.uni-bonn.de |
7c20510c293a405d2942f847bd5690b36e34ec61 | 89485890afeeacdae996de966b8b13ba0c1bbc9a | /zwplayer/zwvideothread.h | 5b3fdab80e3c7e61dafdfd67da4c1e3d9a9108bc | [] | no_license | weinkym/src_miao | b7c8a35a80e5928470bea07d5eb7e36d54966da9 | 0759c1f819c15c8bb2172fe2558fcb728a186ff8 | refs/heads/master | 2021-08-07T17:55:52.239541 | 2021-06-17T03:38:44 | 2021-06-17T03:38:44 | 64,458,033 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,607 | h | #ifndef ZWVIDEOTHREAD_H
#define ZWVIDEOTHREAD_H
#include <QThread>
#include <QImage>
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include <libavutil/time.h>
#include "libavutil/pixfmt.h"
#include "libswscale/swscale.h"
#include "libswresample/swresample.h"
#include <SDL.h>
#include <SDL_audio.h>
#include <SDL_types.h>
#include <SDL_name.h>
#include <SDL_main.h>
#include <SDL_config.h>
}
//#include "videoplayer/videoplayer_showvideowidget.h"
typedef struct PacketQueue {
AVPacketList *first_pkt, *last_pkt;
int nb_packets;
int size;
SDL_mutex *mutex;
SDL_cond *cond;
} PacketQueue;
#define VIDEO_PICTURE_QUEUE_SIZE 1
#define AVCODEC_MAX_AUDIO_FRAME_SIZE 192000 // 1 second of 48khz 32bit audio
#define MAX_AUDIO_SIZE (25 * 16 * 1024)
#define MAX_VIDEO_SIZE (25 * 256 * 1024)
class ZWVideoThread; //前置声明
typedef struct VideoState {
AVFormatContext *ic;
int videoStream, audioStream;
AVFrame *audio_frame;// 解码音频过程中的使用缓存
PacketQueue audioq;
AVStream *audio_st; //音频流
unsigned int audio_buf_size;
unsigned int audio_buf_index;
AVPacket audio_pkt;
uint8_t *audio_pkt_data;
int audio_pkt_size;
uint8_t *audio_buf;
DECLARE_ALIGNED(16,uint8_t,audio_buf2) [AVCODEC_MAX_AUDIO_FRAME_SIZE * 4];
enum AVSampleFormat audio_src_fmt;
enum AVSampleFormat audio_tgt_fmt;
int audio_src_channels;
int audio_tgt_channels;
int64_t audio_src_channel_layout;
int64_t audio_tgt_channel_layout;
int audio_src_freq;
int audio_tgt_freq;
struct SwrContext *swr_ctx; //用于解码后的音频格式转换
int audio_hw_buf_size;
double audio_clock; ///音频时钟
double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame
AVStream *video_st;
PacketQueue videoq;
/// 跳转相关的变量
int seek_req; //跳转标志
int64_t seek_pos; //跳转的位置 -- 微秒
int seek_flag_audio;//跳转标志 -- 用于音频线程中
int seek_flag_video;//跳转标志 -- 用于视频线程中
double seek_time; //跳转的时间(秒) 值和seek_pos是一样的
///播放控制相关
bool isPause; //暂停标志
bool quit; //停止
bool readFinished; //文件读取完毕
bool readThreadFinished;
bool videoThreadFinished;
SDL_Thread *video_tid; //视频线程id
SDL_AudioDeviceID audioID;
ZWVideoThread *player; //记录下这个类的指针 主要用于在线程里面调用激发信号的函数
} VideoState;
class ZWVideoThread : public QThread
{
Q_OBJECT
public:
enum PlayerState
{
Playing,
Pause,
Stop
};
ZWVideoThread(QObject *parent = Q_NULLPTR);
~ZWVideoThread();
void pause();
void play();
bool stop(bool isWait = false); //参数表示是否等待所有的线程执行完毕再返回
void disPlayVideo(QImage img);
protected:
void run();
signals:
void sigErrorHappened(int type,const QString &errorString);
void sigImageChanged(const QImage &image);
void sig_GetOneFrame(QImage); //没获取到一帧图像 就发送此信号
void sig_StateChanged(ZWVideoThread::PlayerState state);
void sig_TotalTimeChanged(qint64 uSec); //获取到视频时长的时候激发此信号
protected:
bool m_pause;
QString m_filePath;
PlayerState mPlayerState; //播放状态
VideoState mVideoState;
};
#endif // ZWVIDEOTHREAD_H
| [
"weinkym@qq.com"
] | weinkym@qq.com |
9c973ee9e8c28ec021d755152f83ff285727931c | 1f77f63fc4bcf538fc892f6a5ba54058367ed0e5 | /src/csaltTester/src/TestOptCtrl/src/pointpath/RauAutomaticaPointObject.cpp | f015191399808302d99d8af20ccadd0e6e47a8f1 | [
"Apache-2.0"
] | permissive | ChristopherRabotin/GMAT | 5f8211051b620562947443796fa85c80aed5a7cf | 829b7c2c3c7ea73d759c338e7051f92f4f2f6f43 | refs/heads/GMAT-2020a | 2022-05-21T07:01:48.435641 | 2022-05-09T17:28:07 | 2022-05-09T17:28:07 | 84,392,259 | 24 | 10 | Apache-2.0 | 2022-05-11T03:48:44 | 2017-03-09T03:09:20 | C++ | UTF-8 | C++ | false | false | 3,754 | cpp | //$Id$
//------------------------------------------------------------------------------
// RauAutomaticaPointObject
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2020 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Author: Jeremy Knittel
// Created: 2016.11.03
//
/**
* Developed based on RauAutomaticaPointObject.m
*/
//------------------------------------------------------------------------------
#include "RauAutomaticaPointObject.hpp"
#include "MessageInterface.hpp"
//#define DEBUG_RauAutomatica_POINT
//------------------------------------------------------------------------------
// static data
//------------------------------------------------------------------------------
// none
//------------------------------------------------------------------------------
// public methods
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// default constructor
//------------------------------------------------------------------------------
RauAutomaticaPointObject::RauAutomaticaPointObject() :
UserPointFunction()
{
}
//------------------------------------------------------------------------------
// copy constructor
//------------------------------------------------------------------------------
RauAutomaticaPointObject::RauAutomaticaPointObject(const RauAutomaticaPointObject ©) :
UserPointFunction(copy)
{
}
//------------------------------------------------------------------------------
// operator=
//------------------------------------------------------------------------------
RauAutomaticaPointObject& RauAutomaticaPointObject::operator=(const RauAutomaticaPointObject ©)
{
if (© == this)
return *this;
UserPointFunction::operator=(copy);
return *this;
}
//------------------------------------------------------------------------------
// destructor
//------------------------------------------------------------------------------
RauAutomaticaPointObject::~RauAutomaticaPointObject()
{
}
//------------------------------------------------------------------------------
// void EvaluateFunctions()
//-----------------------------------------------------------------------------
void RauAutomaticaPointObject::EvaluateFunctions()
{
// Extract parameter data
Rvector stateInit = GetInitialStateVector(0);
Rvector stateFinal = GetFinalStateVector(0);
Real tInit = GetInitialTime(0);
Real tFinal = GetFinalTime(0);
Rvector costVec(stateFinal.GetSize());
for (int idx = 0; idx < stateFinal.GetSize(); ++idx)
{
costVec(idx) = -stateFinal(idx);
}
SetFunctions(COST, costVec);
Rvector algF(3);
algF(0) = tInit;
algF(1) = tFinal;
algF(2) = stateInit(0);
SetFunctions(ALGEBRAIC, algF);
Rvector lower(3, 0.0, 2.0, 1.0);
Rvector upper(3, 0.0, 2.0, 1.0);
SetFunctionBounds(ALGEBRAIC, LOWER, lower);
SetFunctionBounds(ALGEBRAIC, UPPER, upper);
}
//------------------------------------------------------------------------------
// void EvaluateJacobians()
//-----------------------------------------------------------------------------
void RauAutomaticaPointObject::EvaluateJacobians()
{
// Currently does nothing
}
//------------------------------------------------------------------------------
// protected methods
//------------------------------------------------------------------------------
// none
| [
"christopher.rabotin@gmail.com"
] | christopher.rabotin@gmail.com |
4025edd66e84f1535a6c04f35dbb9b6f064c76ae | e3929acbdc012951b2b1994d7d9d58187404d6f6 | /LeetCode/P141.cpp | 399521e46f6d4f55b8570e9cf6b21c8a6b8e0278 | [] | no_license | LuJianBuPing/LeetCode | a8bc08ab001577e814c628e3566265ef98172429 | 2f58a4efe644dcc0043dbacb9816aff759570afb | refs/heads/master | 2021-03-12T23:22:15.551914 | 2015-07-13T14:16:12 | 2015-07-13T14:16:12 | 32,003,541 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 311 | cpp | #include "LeetCode.h"
class Solution {
public:
bool hasCycle(ListNode *head) {
auto fast = head, slow = head;
while (fast != NULL)
{
if (fast->next != NULL)
fast = fast->next->next;
else
return false;
slow = slow->next;
if (fast == slow)
return true;
}
return false;
}
}; | [
"star.fang1990@live.com"
] | star.fang1990@live.com |
3d6599d3653997b197e0d3e4cc52bee22beadf2d | 028f5a7dc0cfb8c0d3e31cce2f17afd21d3ec5c5 | /homework/Bufitem.h | 3d757c61df2b856516b2027a1795dd248c2c0fcc | [] | no_license | bso112/TextRPG | 1e3df700fb68a94cd93c33f0fca16faae0f27556 | 3a30b8316a7b65ba125d2e7d0d293f5a56c281ad | refs/heads/master | 2023-01-03T18:11:11.491127 | 2020-02-07T15:33:34 | 2020-02-07T15:33:34 | 236,193,445 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 469 | h | #pragma once
#include "stdafx.h"
class CBufItem
{
public:
int id = 0;
char GFX_PATH[GFX_PATH_LENGTH];
char name[ITEM_NAME_LENGTH];
//버프 항목
int attackBuf;
int maxHealthBuf;
int levelBuf;
int expBuf;
//아이템의 속성
ELEMENT element;
//소모성 아이템인가?
bool isConsumable;
char description[DESCRIPTION_LENGTH];
//드롭 확률
float dropChance;
//가격
int price;
public:
CBufItem();
~CBufItem();
void PrintGemInfo() const;
};
| [
"bso11246@gmail.com"
] | bso11246@gmail.com |
4225b1ab742167499ed39642a48b052b666cc5fb | 2b7b3d8cc34ba14b2ef563d53bbb5cf8b267739e | /build/ALBuild/PODOLAN/moc_RBTCPClient.cpp | cfbc9605ef8abfde306698432d920b2a27ee14c6 | [] | no_license | YuuuJin/PODO_hubo2 | 5527e6c8719eabe92cc1158af5d9f3b21a26fa9a | 0487b1555be36a494bbbdf413e39c4a3739a88b3 | refs/heads/master | 2021-05-29T03:11:00.293226 | 2020-04-09T07:38:29 | 2020-04-09T07:38:29 | 254,301,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,823 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'RBTCPClient.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../src/ALPrograms/PODOLAN/LAN/RBTCPClient.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'RBTCPClient.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.8.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_RBTCPClient_t {
QByteArrayData data[5];
char stringdata0[63];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_RBTCPClient_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_RBTCPClient_t qt_meta_stringdata_RBTCPClient = {
{
QT_MOC_LITERAL(0, 0, 11), // "RBTCPClient"
QT_MOC_LITERAL(1, 12, 17), // "RBClientConnected"
QT_MOC_LITERAL(2, 30, 0), // ""
QT_MOC_LITERAL(3, 31, 20), // "RBClientDisconnected"
QT_MOC_LITERAL(4, 52, 10) // "RBReadData"
},
"RBTCPClient\0RBClientConnected\0\0"
"RBClientDisconnected\0RBReadData"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_RBTCPClient[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 29, 2, 0x08 /* Private */,
3, 0, 30, 2, 0x08 /* Private */,
4, 0, 31, 2, 0x09 /* Protected */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void RBTCPClient::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
RBTCPClient *_t = static_cast<RBTCPClient *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->RBClientConnected(); break;
case 1: _t->RBClientDisconnected(); break;
case 2: _t->RBReadData(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject RBTCPClient::staticMetaObject = {
{ &QTcpSocket::staticMetaObject, qt_meta_stringdata_RBTCPClient.data,
qt_meta_data_RBTCPClient, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *RBTCPClient::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *RBTCPClient::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_RBTCPClient.stringdata0))
return static_cast<void*>(const_cast< RBTCPClient*>(this));
return QTcpSocket::qt_metacast(_clname);
}
int RBTCPClient::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QTcpSocket::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 3)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 3;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"blike4@kaist.ac.kr"
] | blike4@kaist.ac.kr |
51fa5f6826b20e32c6c16e820d0fb6e4896dd629 | 9b78ff9c71b8dac8da77c2ad85ae96a3192d81e0 | /WorkThread.h | 1a68a5c4ee8074ffad2243e4e9885e42a9e6e730 | [] | no_license | xingskycn/FloorServer | 5064cb3bb7a7c782dc4fa86993a841c7c49cff72 | c761a580466990bc38d3094d96acac53ed0af45f | refs/heads/master | 2021-01-15T03:45:40.626021 | 2014-08-17T10:52:17 | 2014-08-17T10:52:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,321 | h | /*
* File: WorkThread.h
* Author: chu
*
* Created on 2013年3月9日, 下午4:56
*/
#ifndef WORKTHREAD_H
#define WORKTHREAD_H
#include "common.h"
#include "TaskQueue.h"
//#include "Contacts.h"
#include "Message.h"
#include "Runable.h"
class Worker : public Runable
{
private:
TaskQueue* m_TaskQueue;
char m_buf[SOCK_RECV_BUF];
//ContactsManager* m_ContactsManager;
public:
Worker(TaskQueue* task_queue) : Runable(), m_TaskQueue(task_queue)
{
memset(m_buf, 0, SOCK_RECV_BUF);
//m_ContactsManager = ContactsManager::GetInstance();
}
void Run()
{
LOG(LOG_LEVEL_NODE, "Worker::Run().");
int _fd = -1;
while ( !m_bExit )
{
//_fd = m_TaskQueue->Pop(); //will block if no task
if ((_fd = m_TaskQueue->Pop_Timed()) == -1)
{
continue;
}
LOG(LOG_LEVEL_DEBUG, "[fd: " << _fd << "] start to read.");
//recv data.
int _ret = -1;
int _read_bytes = 0;
int _decrypted_len = 0;
std::string _str;
size_t _sent;
char* _p = m_buf;
memset(m_buf, 0, SOCK_RECV_BUF);
while ( true )
{
_ret = recv(_fd, _p, SOCK_RECV_BUF - _read_bytes, 0);
if (_ret < 0)
{
if (errno == EAGAIN)//no data to read on socket when nonblock. read finished.
{
break;
}
else
{
LOG(LOG_LEVEL_ERROR, "[fd:" << _fd << "] recv() error, returned :" << _ret << ". error: " << strerror(errno));
goto close_socket;
}
}
else if (_ret == 0)//peer point socket is closed
{
LOG(LOG_LEVEL_NODE, "[fd:" << _fd << "] peer closed.");
goto close_socket;
}
else
{
_read_bytes += _ret;
_p = m_buf + _ret;
if (_read_bytes >= SOCK_RECV_BUF)
{
LOG(LOG_LEVEL_WARN, "[fd:" << _fd << "] read " << _read_bytes << " bytes, reach max buffer length. discard.");
goto close_socket;
}
}
}
if (_read_bytes > 0)//have read something
{
LOG(LOG_LEVEL_DEBUG, "[fd:" << _fd << "] read " << _read_bytes << " bytes from fd:" << _fd << ". MSG:" << m_buf);
}
//*********************************************************************************************
//Below is bussiness code.
//*********************************************************************************************
//decode http header
/*
if (m_ContactsManager->Process(m_buf, _str) == true)
{
//LOG_DEBUG("rep:" << _str);
_sent = send(_fd, _str.c_str(), _str.length(), 0);
if (_sent < _str.length())
{
LOG(LOG_LEVEL_WARN, "[fd:" << _fd << "] send response failed, error:" << strerror(errno) << ". response:" << _str << ". _sent:" << _sent << ", size:" << _str.length());
}
else
{
LOG(LOG_LEVEL_INFO, "[fd:" << _fd << "] send ok.");
}
}
*/
//*********************************************************************************************
//Bussiness code finished.
//*********************************************************************************************
//continue;
close_socket:
close(_fd);
LOG(LOG_LEVEL_NODE, "[fd:" << _fd << "] socket closed.");
}
LOG(LOG_LEVEL_NODE, "Worker::Run() exited!");
}
};
typedef boost::shared_ptr<Worker> WorkerPtr;
typedef boost::shared_ptr<boost::thread> ThreadPtr;
class ThreadPool
{
private:
typedef struct _thread
{
_thread(WorkerPtr handle, ThreadPtr object) :
m_handle(handle), m_object(object) { }
WorkerPtr m_handle;
ThreadPtr m_object;
} WorkThread;
std::vector<WorkThread> m_WorkThreads;
public:
ThreadPool(int thread_num, TaskQueue* task_queue)
{
for (int i = 0; i < thread_num; i++)
{
WorkerPtr _worker(new Worker(task_queue));
ThreadPtr _threadObj(new boost::thread(boost::bind(&Worker::Run, _worker.get())));
WorkThread _thread(_worker, _threadObj);
m_WorkThreads.push_back(_thread);
}
}
~ThreadPool() { }
void StopAll()
{
LOG(LOG_LEVEL_NODE, "ThreadPool::StopAll()");
BOOST_FOREACH(std::vector<WorkThread>::value_type& i, m_WorkThreads)
{
i.m_handle->Stop();
}
BOOST_FOREACH(std::vector<WorkThread>::value_type& i, m_WorkThreads)
{
i.m_object->join();
}
LOG(LOG_LEVEL_NODE, "ThreadPool::StopAll() ok.");
}
};
typedef boost::shared_ptr<ThreadPool> ThreadPoolPtr;
#endif /* WORKTHREAD_H */
| [
"gisrzf@163.com"
] | gisrzf@163.com |
b5fe9d6c962e7a0759bbce638b95b15425f598dc | 1d757454ff3655b90949ec7478e8e741d154c8cf | /spoj/mirror_galdr.cpp | b016952dc02e14227ae5a3d66ffd20a19fd40e8f | [] | no_license | manoj9april/cp-solutions | 193b588e0f4690719fe292ac404a8c1f592b8c78 | 41141298600c1e7b9ccb6e26174f797744ed6ac1 | refs/heads/master | 2021-07-12T17:52:21.578577 | 2021-06-20T16:23:05 | 2021-06-20T16:23:05 | 249,103,555 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int t; cin>>t;
while(t--){
string s; cin>>s;
int len = s.length();
bool palin=true;
for(int i=0,j=len-1; i<j; i++,j--){
if(s[i]!=s[j]){
palin=false;
break;
}
}
cout<<(palin?"YES":"NO")<<endl;
}
} | [
"manoj9april@gmail.com"
] | manoj9april@gmail.com |
9948fb5d890261a23ffbaab00cee1a8580a9ea1e | 06cbf451b4f45e92c052ae0c06e4fe033f102ec4 | /CommandBasedExperimantation/CommandBasedRobot/src/OI.cpp | af7521e7e1dc3bad5526d90689169cfbd35e169d | [] | no_license | edwanvi/CommandBasedExperimantation | 799c1c2c50ebeab7793fd5e328ecd995e42f9e01 | 2559fb05d1e44ba326f810db4c1764fa26011afb | refs/heads/master | 2022-05-12T09:43:14.038655 | 2016-02-14T17:39:34 | 2016-02-14T17:39:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,705 | cpp | #include "OI.h"
#include "RobotMap.h"
#include "Commands/Rollers/Set_Roller.h"
#include "Commands/Rollers/Double_Power_Rollers.h"
#include "Commands/Lifting.h"
#include "Commands/Rollers/Solenoid_Roller_Set.h"
#include "Commands/Container_Holder.h"
#include "Commands/HackSlashLiftSensor.h"
#include "Commands/ResetEncoders.h"
#include "Commands/Autonomous/Autonomous_Move.h"
#include "Commands/Drive/Cut_Power.h"
//Drive/ Folder
#include "Commands/Autonomous/Turn.h"
#include "Commands/Drive/ShiftGear.h"
#include "Subsystems/DriveTrain.h"
#include "Commands/ChangeSpeed.h"
#include "Commands/Clipperset.h"
#include "Commands/Container_Holder.h"
#include "Subsystems/Lift.h"
//
OI::OI() {
// Process operator interface input here.
controller = new Joystick(FIRST_CONTROLLER);
controller_2 = new Joystick(SECOND_CONTROLLER);
/**
* XBOX 360 Axes:
* 1: Left Y Axis
* 2: Left Trigger
* 3: Right Trigger
* 5: Right Y Axis
*/
rollerMode = 1;
buttonA = new JoystickButton(controller, 1);
buttonB = new JoystickButton(controller, 2);
buttonX = new JoystickButton(controller, 3);
buttonY = new JoystickButton(controller, 4);
buttonLB = new JoystickButton(controller, 5);
buttonRB = new JoystickButton(controller, 6);
buttonStart = new JoystickButton(controller, 8);
buttonSelect = new JoystickButton(controller, 7);
buttonA_2 = new JoystickButton(controller_2, 2);//2 // xbox or whats
buttonB_2 = new JoystickButton(controller_2, 3);
buttonX_2 = new JoystickButton(controller_2, 1);
buttonY_2 = new JoystickButton(controller_2, 4);
buttonLB_2 = new JoystickButton(controller_2, 5);
buttonRB_2 = new JoystickButton(controller_2, 6);
buttonStart_2 = new JoystickButton(controller_2, 8);
buttonSelect_2 = new JoystickButton(controller_2, 7);
//open
buttonA->WhenPressed(new Solenoid_Roller_Set(false));
//close
buttonY->WhenPressed(new Solenoid_Roller_Set(true));
//gear down
buttonX->WhenPressed(new ShiftGear(true));
//gear up
buttonB->WhenPressed(new ShiftGear(false));
buttonStart->WhenPressed(new Double_Power_Rollers());
buttonSelect->WhenPressed(new Cut_Power());
//buttonStart_2->WhenActive(new ResetEncoders());
buttonStart_2->WhileHeld(new ResetEncoders());
//buttonStart_2->WhenReleased(new )
buttonY_2->WhenPressed(new ChangeSpeed(true));
buttonA_2->WhenPressed(new ChangeSpeed(false));
buttonX_2->WhenPressed(new Clipperset(true));
buttonB_2->WhenPressed(new Clipperset(false));
buttonLB_2->WhenPressed(new Container_Holder(true));
buttonRB_2->WhenPressed(new Container_Holder(false));
buttonStart_2->WhenPressed(new HackSlashLiftSensor());
}
float OI::GetLeftJoystick() {
return 1 * controller->GetRawAxis(1);
}
float OI::GetRightJoystick() {
return -1 * controller->GetRawAxis(5);
}
float OI::GetLeftJoystick_2(){
return -1 * controller_2->GetRawAxis(1);
}
float OI::GetRightJoystick_2(){
return -1 * controller_2->GetRawAxis(5);
}
float OI::GetLeftTrigger() {
return controller->GetRawAxis(2);
}
float OI::GetRightTrigger() {
return controller->GetRawAxis(3);
}
int OI::GetDPad_2() {
return controller_2->GetPOV();
}
int OI::GetDPad() {
return controller->GetPOV();
}
float OI::GetLeftTrigger_2() {
return controller_2->GetRawAxis(2);
}
float OI::GetRightTrigger_2() {
return controller_2->GetRawAxis(3);
}
float OI::GetLeftBumper() {
return controller->GetRawButton(5);
}
float OI::GetRightBumper() {
return controller->GetRawButton(6);
}
int OI::Auto(){
//true for auto, false for teleop
return rollerMode;
}
void OI::SetAuto(int _mode){
rollerMode = _mode;
}
| [
"tkdberger@gmail.com"
] | tkdberger@gmail.com |
a8011f7998afcc739cbec02ae61d48f8881ee3b0 | d46b63a660a8b5c53236fb3d6eb359147c0d6168 | /src/SystemStatusIndicator.h | 51767a02c302ee41ff9dbe6ea74e8d8094ce9ed0 | [] | no_license | gniemann/ambrose | 63cc33bde22e6d212f17f4c4f0ef9639a30f0104 | 58834d889b36309028acb9d6eae0f73c5853a51c | refs/heads/master | 2020-05-18T01:49:54.827663 | 2019-07-11T17:31:42 | 2019-07-11T17:31:42 | 184,099,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,661 | h | //
// Created by Greg Niemann on 2019-03-01.
//
#ifndef BUILD_MONITOR_SYSTEMSTATUSINDICATOR_H
#define BUILD_MONITOR_SYSTEMSTATUSINDICATOR_H
#include <Adafruit_MCP23008.h>
enum class SystemStatus {
off,
idle,
transmitting,
connecting,
notConnected,
failed,
resetPressed,
resetPressedLong,
};
template <uint8_t redPin, uint8_t greenPin, uint8_t bluePin>
class SystemStatusIndicator: Manager {
public:
SystemStatusIndicator(Adafruit_MCP23008 &mcp);
void setStatus(SystemStatus newStatus);
void run() override;
private:
void display();
Adafruit_MCP23008 &mcp;
SystemStatus status;
LEDPtr led;
};
template<uint8_t redPin, uint8_t greenPin, uint8_t bluePin>
SystemStatusIndicator<redPin, greenPin, bluePin>::SystemStatusIndicator(Adafruit_MCP23008 &mcp): mcp(mcp) {
mcp.begin();
mcp.pinMode(redPin, OUTPUT);
mcp.pinMode(greenPin, OUTPUT);
mcp.pinMode(bluePin, OUTPUT);
setStatus(SystemStatus::off);
}
template<uint8_t redPin, uint8_t greenPin, uint8_t bluePin>
void SystemStatusIndicator<redPin, greenPin, bluePin>::setStatus(SystemStatus newStatus) {
if (newStatus == status && led != nullptr) {
return;
}
status = newStatus;
switch (status) {
case SystemStatus::off:
led = LEDPtr(new LED(OFF));
break;
case SystemStatus::idle:
led = LEDPtr(new LED(GREEN));
break;
case SystemStatus::transmitting:
led = LEDPtr(new LED(BLUE));
break;
case SystemStatus::connecting:
led = LEDPtr(new BlinkingLED(GREEN, 2, 2));
break;
case SystemStatus::notConnected:
led = LEDPtr(new BlinkingLED(RED, 2, 2));
break;
case SystemStatus::failed:
led = LEDPtr(new LED(RED));
break;
case SystemStatus::resetPressed:
led = LEDPtr(new BlinkingLED(RED, 2, 2));
break;
case SystemStatus::resetPressedLong:
led = LEDPtr(new BlinkingLED(RED, 1, 1));
break;
}
display();
}
template<uint8_t redPin, uint8_t greenPin, uint8_t bluePin>
void SystemStatusIndicator<redPin, greenPin, bluePin>::run() {
led->step();
display();
}
template<uint8_t redPin, uint8_t greenPin, uint8_t bluePin>
void SystemStatusIndicator<redPin, greenPin, bluePin>::display() {
Color col = led->getColor();
mcp.digitalWrite(redPin, col.red == 0 ? HIGH : LOW);
mcp.digitalWrite(greenPin, col.green == 0 ? HIGH : LOW);
mcp.digitalWrite(bluePin, col.blue == 0 ? HIGH : LOW);
}
#endif //BUILD_MONITOR_SYSTEMSTATUSINDICATOR_H
| [
"greg.niemann@willowtreeapps.com"
] | greg.niemann@willowtreeapps.com |
dced57a791c8d5a11f05e3354e792f3f7979b26c | d2e19429bfeb2a7fb7696005432ff443ecd861ed | /n-home.ino | 382023b1ff8451e9cfcce1b73e9d85294d454050 | [] | no_license | CarrionMysh/n-home | ba54af247a41a4d1a4f8e2d2371fb7f5f5cb42dd | e3e1309489eef6d022cd916a2226516d2edbbc7d | refs/heads/master | 2021-06-11T02:56:02.939597 | 2021-04-21T15:56:47 | 2021-04-21T15:56:47 | 136,664,419 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,114 | ino | #include <FastCRC_tables.h>
#include <FastCRC.h>
#include <FastCRC_cpu.h>
#include <SoftwareSerial.h>
//для передачи в линию используется хардварный serial
#define pin_tr 4 //пин transmission enable для max485
#define led_pin 13 //светодиод активности *debag
#define tx_ready_delay 20 //задержка для max485 (буфер? вообщем, неопределенность буфераmax485)
#define tx_pc 5 //serial pc alfa
#define rx_pc 6 //serial pc alfa
#define value_data 10 //размер пакета
//#define ask '!'
//#define response '&'
#define heartbit '*'
#define self_id 01 //свой id
FastCRC8 CRC8;
SoftwareSerial pc(rx_pc, tx_pc); //инициализация Serial для получения команд с компа, для альфы
const char ask='!';
const char response= '*';
char data[value_data];
char* id_m[] = {"02", "03", "04", "05"}; //массив с id устройств, 01 - master
byte nn = 4; //количество id
char* com_m[2][9] =
{
{"01", "02", "03", "04", "05", "06", "07", "08", "09"},
{"01", "02", "03", "04", "05", "06", "07", "08", "09"}
};
char inputSerial [value_data] = "";
byte count; //указатель длины строки с pc.serial
boolean stringComplete = false;
boolean message_pc = true;
//коды ошибок:
//0 - ok
//1 - header
//2 - id
//20 - unknow
void setup() {
Serial.begin(9600, SERIAL_8E1);
pc.begin(9600);
pinMode(led_pin, OUTPUT); //пин светодиода
pinMode(pin_tr, OUTPUT); //пин передачи
digitalWrite(led_pin, LOW);
digitalWrite(pin_tr, LOW);
pc.println(F("Serial ok"));
}
void loop() {
pc_input();
if (stringComplete == true) {
transmite_com();
pc.println("send ok?");
}
}
void transmite_com() {
char data_tx[value_data];
char subbuf[count];
byte crc;
data_tx[value_data] = subbuf[count]; //формируем исходящий пакет
crc = CRC8.smbus(data_tx, sizeof(data_tx));
data_tx[value_data] = '>' + crc + data_tx[value_data] + '<'; //добавляем символ начала пакета+crc к пакету
stringComplete = false; //обнуляем флаг введеной с консоли команды
tx_up();
Serial.print(inputSerial); //отправляем слэйвам команды введеную с консоли
tx_down();
}
void tx_up() {
digitalWrite(pin_tr, HIGH);
digitalWrite(led_pin, HIGH);
}
void tx_down() {
delay(tx_ready_delay);
digitalWrite(pin_tr, LOW);
digitalWrite(led_pin, LOW);
}
void pc_input() { //читалка с soft_serial
char inChar;
count = 0;
pc.println(F("input ID and command in format idcommand (example: !0201)"));
// if (message_pc) { //если флаг message_pc=true, тогда отображать текстовую приглашалку, чтобы не спамило в консоль
// pc.println(F("input ID and command in format idcommand (example: !0201)"));
// message_pc = false;
// }
while (true) {
if (pc.available()) {
count++;
inChar = pc.read();
if (inChar == 13) {
stringComplete = true; //ввод с pcSerial был и закончен.
message_pc = false;
inputSerial[count] = '\0';
//debug
pc.print(" count: ");pc.println(count);
//debug
if (verify_string() != 0) { //если проверка не прошла - вызов по рекурсии pc_input()
message_pc = true;
pc_input();
}
break;
}
inputSerial [count] = inChar;
}
}
}
byte verify_string() { //верификация ввода команды с Serial_pc
boolean flag = false;
//проверка заголовка
if (inputSerial[1] != ask) {
pc.print("Wrong header = ");pc.println(byte(inputSerial[1]));
return (1);
}
//проверка id
for (byte i = 1; i <= nn; i++) { //перебор id
char* sub[3];
sub[3] = inputSerial[2] + inputSerial[3]+'\0';
pc.print("inputSerial[2]");pc.println(inputSerial[2]);
pc.print("inputSerial[3]");pc.println(inputSerial[3]);
pc.print("check id, sub[2] = ");pc.println(sub[2]);
if (sub[2] != id_m[i]) flag = false;
}
if (flag == false) { //если в 1..2 байтах не встретился id из доступных
pc.println("Wrong id");
return (2);
}
return (0);
//секция команды не проверяется, если что не так - слэйв вернет unknow command, конец пакета '%' так же не проверяем, т.к. вручную его вводить не будем
}
| [
"hivework10@gmail.com"
] | hivework10@gmail.com |
a0c6ba4f49a7111ece05ecf25f1dc10691461aa7 | ba612716fe47a0d7373365fee7d877f0b7c1fd62 | /21_c++_tutorials/04_ascii_table/ascii_table.cpp | e95ded840f2063e0850d192fe3973340d19828fd | [] | no_license | haibianshifeng/6_thevisualroom | 181d736c72cdcc250a83d9e3955fdff7d90b35c5 | b1eadee0f68b51fe8c99b81ea949dcc43d12f2f5 | refs/heads/master | 2020-07-06T11:12:51.597768 | 2019-03-03T22:16:34 | 2019-03-03T22:16:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 478 | cpp | /*
File name: ascii_table.cpp
Date: 9 Dec 2016
Author: Andrew Roberts
*/
// cin, cout:
#include <iostream>
// standard namespaces:
using namespace std;
// main function:
int main()
{
// declare temperature
char character;
// loop between 0 and 127
for(int num = 0; num < 128; num++)
{
// set the number equal to the character:
character = num;
// output the number and character:
cout << num << " : " << character << endl;
}
// return integer:
return 0;
}
| [
"en9apr@hotmail.co.uk"
] | en9apr@hotmail.co.uk |
0706e26e5981bff81e8dffacc0faf9da2625cea2 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /net/reporting/reporting_header_parser.h | 2e167f2ccdef3f7e7d6b184a367ef43df104a5e0 | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 916 | h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_REPORTING_REPORTING_HEADER_PARSER_H_
#define NET_REPORTING_REPORTING_HEADER_PARSER_H_
#include <memory>
#include "base/macros.h"
#include "net/base/net_export.h"
#include "url/gurl.h"
namespace base {
class Value;
} // namespace base
namespace net {
class NetworkIsolationKey;
class ReportingContext;
class NET_EXPORT ReportingHeaderParser {
public:
static void ParseHeader(ReportingContext* context,
const NetworkIsolationKey& network_isolation_key,
const GURL& url,
std::unique_ptr<base::Value> value);
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(ReportingHeaderParser);
};
} // namespace net
#endif // NET_REPORTING_REPORTING_HEADER_PARSER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b2d0fc7ed15b21431b8520ac467b728d90c21d9f | 71ce57c3ac7d39ba12b8473849c00a23c1c338ac | /src/gwen/src/Controls/CheckBox.cpp | 5baaa66991e70b29ba3a59105a1bff50792ba43d | [] | no_license | ReccaStudio/DeferredRenderer | f6a5e5ffbb36ffc79dedc295ad1ab0202251abd0 | d896de09052c5880b99737e51360641d05fe84b7 | refs/heads/master | 2020-04-07T16:35:13.954276 | 2013-12-11T23:44:42 | 2013-12-11T23:44:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 819 | cpp | /*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#include "Gwen/Controls/CheckBox.h"
using namespace Gwen;
using namespace Gwen::Controls;
GWEN_CONTROL_CONSTRUCTOR( CheckBox )
{
SetSize( 13, 13 );
m_bChecked = true;
Toggle();
}
void CheckBox::Render( Skin::Base* skin )
{
skin->DrawCheckBox( this, m_bChecked, IsDepressed() );
}
void CheckBox::OnPress()
{
if ( IsChecked() && !AllowUncheck() )
return;
Toggle();
}
void CheckBox::OnCheckStatusChanged()
{
if ( IsChecked() )
{
onChecked.Call( this );
}
else
{
onUnChecked.Call( this );
}
onCheckChanged.Call( this );
}
void CheckBox::SetChecked( bool bChecked )
{
if ( m_bChecked == bChecked ) return;
m_bChecked = bChecked;
OnCheckStatusChanged();
} | [
"geoff@vonture.net"
] | geoff@vonture.net |
737c2f5f74b3f5c4e4675c47658bcab6f13d978b | 02e27b1637c3eacedb20f831350f4cd08d38ed22 | /brain/brain.x86.assembler_v1.hpp | 11cf58fb21d077e568b431205323333dc38cadff | [] | no_license | MaulingMonkey/brain3 | eee827e127bd87e0fe68f5b29be1a6ffbb003d92 | 886df572581a87dad05b57afce25a23e370f7212 | refs/heads/master | 2016-09-10T00:10:27.101600 | 2008-08-25T02:52:42 | 2008-08-25T02:52:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,253 | hpp | #ifndef IG_BRAIN_X86_ASSEMBLER
#define IG_BRAIN_X86_ASSEMBLER
#include "brain.x86.registers.hpp"
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/cstdint.hpp>
#include <vector>
namespace brain {
namespace x86 {
class assembler {
public:
typedef boost::uint8_t byte;
typedef boost::uint16_t word;
typedef boost::uint32_t dword;
//typedef boost::uint64_t qword;
std::vector<byte> code;
void clear() { code.resize(0); }
void emit( byte b1 ) { code.push_back(b1); }
void emit( byte b1, byte b2 ) { emit(b1); emit(b2); }
void emit( byte b1, byte b2, byte b3 ) { emit(b1,b2); emit(b3); }
void emit( byte b1, byte b2, byte b3, byte b4 ) { emit(b1,b2,b3); emit(b4); }
private:
// +----------------------+--------+--------+-----+--------------+-----------+
// | Instruction Prefixes | Opcode | ModR/M | SIB | Displacement | Immediate |
// +----------------------+--------+--------+-----+--------------+-----------+
// up to 4 1-byte prefix 1-3byte 0-1byte 0-1b 0, 1, 2, or 4 0, 1, 2, or 4
// Opcodes ib, iw, and id
void ib( byte value ) { emit(value); }
void iw( word value ) { emit((value>>0)&0xFF,(value>>8)&0xFF); } // little endian
void id( dword value ) { emit((value>>0)&0xFF,(value>>8)&0xFF,(value>>16)&0xFF,(value>>24)&0xFF); }
bool legal_disp8( int value ) { return (-128 <= value && value <= +127); }
void disp8 ( int value ) { assert(legal_disp8(value)); emit( (value>=0)?(value):(0x100+value) ); }
void disp32( int value ) { unsigned uvalue = (value>=0) ? (value) : (0xFFFFFFFFu+value+1); id(uvalue); }
void disp_8_or_32( int value ) { if (legal_disp8(value)) disp8(value); else disp32(value); }
// Opcode /r
void _r_r_rm( r8 r, r8 rm ) { ModR_M(3,r.value,rm.value); }
void _r_r_rm( r8 r, r16 rm ) { ModR_M(3,r.value,rm.value); }
void _r_r_rm( r8 r, r32 rm ) { ModR_M(3,r.value,rm.value); }
void _r_r_rm( r16 r, r8 rm ) { ModR_M(3,r.value,rm.value); }
void _r_r_rm( r16 r, r16 rm ) { ModR_M(3,r.value,rm.value); }
void _r_r_rm( r16 r, r32 rm ) { ModR_M(3,r.value,rm.value); }
void _r_r_rm( r32 r, r8 rm ) { ModR_M(3,r.value,rm.value); }
void _r_r_rm( r32 r, r16 rm ) { ModR_M(3,r.value,rm.value); }
void _r_r_rm( r32 r, r32 rm ) { ModR_M(3,r.value,rm.value); }
void _r_rm_r( r8 rm, r8 r ) { ModR_M(3,r.value,rm.value); }
void _r_rm_r( r8 rm, r16 r ) { ModR_M(3,r.value,rm.value); }
void _r_rm_r( r8 rm, r32 r ) { ModR_M(3,r.value,rm.value); }
void _r_rm_r( r16 rm, r8 r ) { ModR_M(3,r.value,rm.value); }
void _r_rm_r( r16 rm, r16 r ) { ModR_M(3,r.value,rm.value); }
void _r_rm_r( r16 rm, r32 r ) { ModR_M(3,r.value,rm.value); }
void _r_rm_r( r32 rm, r8 r ) { ModR_M(3,r.value,rm.value); }
void _r_rm_r( r32 rm, r16 r ) { ModR_M(3,r.value,rm.value); }
void _r_rm_r( r32 rm, r32 r ) { ModR_M(3,r.value,rm.value); }
// needs to assert 16 bit addressing
// needs to assert [si], [di], or [bx], the only valid registers
// see Table 2-1.
void _r_r_rm( r16 r, const r16*rm ) {} // ModR_M(0,r.value,rm->value); }
void _r_rm_r( const r16*rm, r16 r ) {} // ModR_M(0,r.value,rm->value); }
void _r_r_rm( r16 r, disp_expr<r16> rm ) {}
void _r_rm_r( disp_expr<r16> rm, r16 r ) {}
// These need to assert 32 bit addressing:
// see Table 2-2.
void _r_r_rm( r32 r, const r32* rm ) { if (*rm==esp) { ModR_M(0,r.value,4); SIB(0,4,4); } else if (*rm==ebp) { ModR_M(1,r.value,ebp.value); disp8(0); } else { ModR_M(0,r.value,rm->value); } }
void _r_rm_r( const r32* rm, r32 r ) { if (*rm==esp) { ModR_M(0,r.value,4); SIB(0,4,4); } else if (*rm==ebp) { ModR_M(1,r.value,ebp.value); disp8(0); } else { ModR_M(0,r.value,rm->value); } }
void _r_r_rm( r32 r, disp_expr<r32> rm ) { const bool d8 = legal_disp8(rm.disp); ModR_M(d8?1:2,r.value,rm.reg.value); if (rm.reg==esp) SIB(0,4,esp); disp_8_or_32(rm.disp); }
void _r_rm_r( disp_expr<r32> rm, r32 r ) { const bool d8 = legal_disp8(rm.disp); ModR_M(d8?1:2,r.value,rm.reg.value); if (rm.reg==esp) SIB(0,4,esp); disp_8_or_32(rm.disp); }
// Opcodes /0../7 -- doesn't use the Mod field according to 3.1.1.1 of the instruction set reference
void _N( byte N, byte value ) { ModR_M(0,N,value); }
void _N( byte N, r8 reg ) { ModR_M(3,N,reg.value); }
void _N( byte N, r16 reg ) { ModR_M(3,N,reg.value); }
void _N( byte N, r32 reg ) { ModR_M(3,N,reg.value); }
//void _N( byte N, const r16* reg ) { ModR_M(0,N,reg->value); }
//void _N( byte N, const r32* reg ) { ModR_M(0,N,reg->value); }
template < typename T > void _0(T value) { _N(0,value); }
template < typename T > void _1(T value) { _N(1,value); }
template < typename T > void _2(T value) { _N(2,value); }
template < typename T > void _3(T value) { _N(3,value); }
template < typename T > void _4(T value) { _N(4,value); }
template < typename T > void _5(T value) { _N(5,value); }
template < typename T > void _6(T value) { _N(6,value); }
template < typename T > void _7(T value) { _N(7,value); }
// r8, r16, r32, r64 = registers
//imm8, imm16, imm32, imm64 = immediate <bits> length value
//r/m8, r/m16, r/m32, r/m64 = register refering to an address of a value of <bits> length
////////////////////////////////////////////////////////
// bits: 7 6 5 3 2 0 //
// +-----+------------+-----+ //
// ModR/M byte format: | Mod | Reg/Opcode | R/M | //
// +-----+------------+-----+ //
void ModR_M( byte mod, byte reg_or_opcode, byte r_m ) {
assert( 0 <= mod && mod <= 3 );
assert( 0 <= reg_or_opcode && reg_or_opcode <= 7 );
assert( 0 <= r_m && r_m <= 7 );
emit( (mod<<6) + (reg_or_opcode<<3) + (r_m<<0) );
}
////////////////////////////////////////////////////////
// SIB format:
// 7 6 5 3 2 0
// +-------+-------+------+
// | Scale | Index | Base |
// +-------+-------+------+
void SIB( byte scale, byte index, byte base ) {
assert( 0 <= scale && scale <= 3 );
assert( 0 <= index && index <= 7 );
assert( 0 <= base && base <= 7 );
emit( (scale<<6) + (index<<3) + (base<<0) );
}
void SIB( byte scale, byte index, r32 base ) { assert( base != ebp ); SIB(scale,index,base.value); }
void SIB( byte scale, r32 index, byte base ) { assert( index != esp ); SIB(scale,index.value,base); }
void SIB( byte scale, r32 index, r32 base ) { assert( base != ebp && index != esp ); SIB(scale,index.value,base.value); }
// See table 2-1. on page 38 of the instruction set reference
// __asm xor eax,ecx; // C1
// __asm xor ecx,eax; // C8
public:
void hlt() { code.push_back(0xF4); }
void nop() { code.push_back(0x90); }
/*-------------------------------------------------------------------------------------------------------------*/
#define OP_RM_N( n, name, preamble, argparity, arg ) \
assembler& name( r ## argparity arg ) { emit(BOOST_PP_SEQ_ENUM(preamble)); _N(n,arg.value); return *this; } \
assembler& name( r ## argparity arg ) { emit(BOOST_PP_SEQ_ENUM(preamble)); _N(n,arg.value); return *this; } \
assembler& name( r ## argparity arg ) { emit(BOOST_PP_SEQ_ENUM(preamble)); _N(n,arg.value); return *this; } \
/*-------------------------------------------------------------------------------------------------------------*/
#define OP_RM_0( name, preamble, argparity, arg ) OP_RM_N( 0, name, preamble, argparity, arg )
#define OP_RM_1( name, preamble, argparity, arg ) OP_RM_N( 1, name, preamble, argparity, arg )
#define OP_RM_2( name, preamble, argparity, arg ) OP_RM_N( 2, name, preamble, argparity, arg )
#define OP_RM_3( name, preamble, argparity, arg ) OP_RM_N( 3, name, preamble, argparity, arg )
#define OP_RM_4( name, preamble, argparity, arg ) OP_RM_N( 4, name, preamble, argparity, arg )
#define OP_RM_5( name, preamble, argparity, arg ) OP_RM_N( 5, name, preamble, argparity, arg )
#define OP_RM_6( name, preamble, argparity, arg ) OP_RM_N( 6, name, preamble, argparity, arg )
#define OP_RM_7( name, preamble, argparity, arg ) OP_RM_N( 7, name, preamble, argparity, arg )
/*---------------------------------------------------------------------------------------------------------------------------------------------------*/
#define OP_R_RM( name, preamble, arg1parity, arg2parity, arg1, arg2 ) \
assembler& name( r ## arg1parity arg1, r ## arg2parity arg2 ) { emit(BOOST_PP_SEQ_ENUM(preamble)); _r_r_rm(arg1,arg2); return *this; } \
assembler& name( r ## arg1parity arg1, const r ## arg2parity *arg2 ) { emit(BOOST_PP_SEQ_ENUM(preamble)); _r_r_rm(arg1,arg2); return *this; } \
assembler& name( r ## arg1parity arg1, disp_expr<r ## arg2parity> arg2 ) { emit(BOOST_PP_SEQ_ENUM(preamble)); _r_r_rm(arg1,arg2); return *this; } \
/*---------------------------------------------------------------------------------------------------------------------------------------------------*/
#define OP_RM_R( name, preamble, arg1parity, arg2parity, arg1, arg2 ) \
assembler& name( r ## arg1parity arg1, r ## arg2parity arg2 ) { emit(BOOST_PP_SEQ_ENUM(preamble)); _r_rm_r(arg1,arg2); return *this; } \
assembler& name( const r ## arg1parity *arg1, r ## arg2parity arg2 ) { emit(BOOST_PP_SEQ_ENUM(preamble)); _r_rm_r(arg1,arg2); return *this; } \
assembler& name( disp_expr<r ## arg1parity> arg1, r ## arg2parity arg2 ) { emit(BOOST_PP_SEQ_ENUM(preamble)); _r_rm_r(arg1,arg2); return *this; } \
/*--------------------------------------------------------------------------------------------------------------------------------------------------------*/
#define OP_R_RM_AND_RM_R( name, rm_r_preamble, r_rm_preamble, arg1parity, arg2parity, arg1, arg2 ) \
assembler& name( r ## arg1parity arg1, r ## arg2parity arg2 ) { emit(BOOST_PP_SEQ_ENUM(rm_r_preamble)); _r_rm_r(arg1,arg2); return *this; } \
assembler& name( const r ## arg1parity *arg1, r ## arg2parity arg2 ) { emit(BOOST_PP_SEQ_ENUM(rm_r_preamble)); _r_rm_r(arg1,arg2); return *this; } \
assembler& name( disp_expr<r ## arg1parity> arg1, r ## arg2parity arg2 ) { emit(BOOST_PP_SEQ_ENUM(rm_r_preamble)); _r_rm_r(arg1,arg2); return *this; } \
assembler& name( r ## arg1parity arg1, const r ## arg2parity *arg2 ) { emit(BOOST_PP_SEQ_ENUM(r_rm_preamble)); _r_r_rm(arg1,arg2); return *this; } \
assembler& name( r ## arg1parity arg1, disp_expr<r ## arg2parity> arg2 ) { emit(BOOST_PP_SEQ_ENUM(r_rm_preamble)); _r_r_rm(arg1,arg2); return *this; } \
/*--------------------------------------------------------------------------------------------------------------------------------------------------------*/
#define ARITH_OP( name, imm_base, imm_mod, r_base ) \
assembler& name( r8 dest, byte value ) { emit(imm_base+0); imm_mod(dest.value); ib(value); return *this; } \
assembler& name( r16 dest, word value ) { emit(imm_base+1); imm_mod(dest.value); iw(value); return *this; } \
assembler& name( r32 dest, dword value ) { emit(imm_base+1); imm_mod(dest.value); id(value); return *this; } \
assembler& name( r8 dest, r8 src ) { emit(r_base+0); _r_rm_r(dest,src); return *this; } \
OP_R_RM_AND_RM_R( name, (r_base+1), (r_base+3), 16, 16, dest, value ) \
OP_R_RM_AND_RM_R( name, (r_base+1), (r_base+3), 32, 32, dest, value ) \
/*--------------------------------------------------------------------------------------------------------------*/
ARITH_OP( adc, 0x80, _2, 0x10 ) // add with carry
ARITH_OP( add, 0x80, _2, 0x00 ) // add
ARITH_OP( and, 0x80, _4, 0x20 ) // logical and
// assembler& call( rel16 ) { emit(0xE8); cw; }
// assembler& call( rel32 ) { emit(0xE8); cd; }
// assembler& call( r16 address ) { emit(0xFF); _2(address.value); return *this; } r/m16
// assembler& call( r32 address ) { emit(0xFF); _2(address.value); return *this; } r/m32
// assembler& call( r64 address ) { emit(0xFF); _2(address.value); return *this; } r/m64
assembler& clc() { emit(0xF8); return *this; } // Clear Carry Flag
assembler& cld() { emit(0xFC); return *this; } // Clear Direction Flag
assembler& cli() { emit(0xFA); return *this; } // Clear Interrupt Flag
assembler& clts() { emit(0x0F,0x06); return *this; } // Clear Task-Switched Flag in CR0 -- requires privilege level 0!!!
assembler& cmc() { emit(0xF5); return *this; } // Complement Carry Flag
// CMOVcc -- Conditional Move
/*-------------------------------------------------------------------------------------------------------------------------------------------------------------*/
#define CMOV_OP( z, unused, postfix_code ) \
OP_R_RM( BOOST_PP_CAT(cmov,BOOST_PP_TUPLE_ELEM(2,0,postfix_code)) , (0x0F)(BOOST_PP_CAT(0x,BOOST_PP_TUPLE_ELEM(2,1,postfix_code))) , 16 , 16 , dest , src ) \
OP_R_RM( BOOST_PP_CAT(cmov,BOOST_PP_TUPLE_ELEM(2,0,postfix_code)) , (0x0F)(BOOST_PP_CAT(0x,BOOST_PP_TUPLE_ELEM(2,1,postfix_code))) , 32 , 32 , dest , src ) \
/*-------------------------------------------------------------------------------------------------------------------------------------------------------------*/
BOOST_PP_SEQ_FOR_EACH( CMOV_OP, ~, \
((a ,47)) ((ae,43)) ((b ,42)) ((be ,46)) ((c ,42)) ((e ,44)) ((g ,4F)) ((ge,4D)) \
((l ,4C)) ((le,4E)) ((na ,46)) ((nae,42)) ((nb ,43)) ((nbe,47)) \
((nc,43)) ((ng,4E)) ((nge,4C)) ((nl ,4D)) ((nle,4F)) ((no ,41)) ((np,4B)) \
((ns,49)) ((nz,45)) ((o ,40)) ((p ,4A)) ((pe ,4A)) ((po ,4B)) ((s ,48)) ((z ,44)) \
)
#undef CMOV_OP
ARITH_OP( cmp, 0x80, _7, 0x38 ) // compare
assembler& cpuid() { emit( 0x0F, 0xA2 ); return *this; }
OP_R_RM( crc32, (0xF2)(0x0F)(0x38)(0xF0), 32, 8, dest, src )
OP_R_RM( crc32, (0xF2)(0x0F)(0x38)(0xF1), 32, 16, dest, src )
OP_R_RM( crc32, (0xF2)(0x0F)(0x38)(0xF1), 32, 32, dest, src )
OP_RM_1( dec, (0xFE), 8, target )
OP_RM_1( dec, (0xFF), 16, target )
OP_RM_1( dec, (0xFF), 32, target )
assembler& ret_near() { emit(0xC3); return *this; }
assembler& ret_far () { emit(0xCB); return *this; }
assembler& ret_near( word n_bytes_pop ) { emit(0xC2); iw(n_bytes_pop); return *this; }
assembler& ret_far ( word n_bytes_pop ) { emit(0xCA); iw(n_bytes_pop); return *this; }
assembler& ret() { ret_near(); return *this; }
assembler& ret( word n_bytes_pop ) { ret_near(n_bytes_pop); return *this; }
assembler& xor( r8 dest, r8 src ) { emit(0x32); _r_r_rm(dest,src); return *this; }
assembler& xor( r16 dest, r16 src ) { emit(0x33); _r_r_rm(dest,src); return *this; }
assembler& xor( r32 dest, r32 src ) { emit(0x33); _r_r_rm(dest,src); return *this; }
};
}
}
#endif //ndef IG_BRAIN_X86_ASSEMBLER
| [
"nobody@nowhere"
] | nobody@nowhere |
00590f9e334580915bd151c59d71f966b60d5fbd | c380f0e026123d42ca00ec1f4a174b059d471acf | /Poker Hands/Cards.cpp | 68f21f8d22cce3947a0a3010ffb9dc083e5c40ae | [] | no_license | Bryanvo/Assorted-Projects | 9160ddf1393dbb01d6c0e7d5309bafe8256cb04c | 2c930c7c1777d6051773ca7aec135b1977303d0d | refs/heads/master | 2021-09-02T07:08:55.486039 | 2017-12-31T08:58:18 | 2017-12-31T08:58:18 | 115,781,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,622 | cpp | // ITP 365 Spring 2016
// HW5 Vector and Poker Hands
// Name: Bryan Vo
// Email: bryanvo@usc.edu
// Platform: Windows
//
// Cards.cpp
// Implements Cards and Poker Hand functionality
#include "Cards.h"
#include <random>
#include <algorithm>
#include <string>
#include <iostream>
// Function: Constructor
// Purpose: Draws 5 cards from the supplied deck, and sorts them
// by rank
// Input: Takes in a ITPVector of cards for the deck
// Returns: Nothing
PokerHand::PokerHand(ITPVector<Card>& deck)
{
// TODO: Implement
for (int i = 0; i < 5; i++)
{
//Draws 5 cards and stores them in the mHand member variable
mHand.insert_back(deck.get_back());
deck.remove_back();
}
// Sort the hand
std::sort(&mHand[0], &mHand[0] + mHand.size());
}
// Function: getBestPokerHand
// Purpose: Returns a string describing the poker hand this PokerHand
// contains
// Input: None
// Returns: The name of the best poker hand
std::string PokerHand::getBestPokerHand() const
{
// TODO: Implement
std::string retVal;
if (hasFlush() == true && hasStraight() == true)
{
retVal = "You have a straight flush";
return retVal;
}
else if (hasFourOfAKind() == true)
{
retVal = "You have a four of a kind";
return retVal;
}
else if (hasFullHouse() == true)
{
retVal = "You have a full house";
return retVal;
}
else if (hasFlush() == true)
{
retVal = "You have a flush";
return retVal;
}
else if (hasStraight() == true)
{
retVal = "You have a straight";
return retVal;
}
else if (hasThreeOfAKind() == true)
{
retVal = "You have a three of a kind";
return retVal;
}
else if (hasTwoPairs() == true)
{
retVal = "You have a two pairs";
return retVal;
}
else if (hasPair() == true)
{
retVal = "You have a pair";
return retVal;
}
else
{
return "high card"; // FIX RETURN VALUE
}
}
// Function: hasStraight
// Purpose: Determines if the hand has a straight
// Input: None
// Returns: true if there's a straight
bool PokerHand::hasStraight() const
{
bool retVal = false;
// TODO: Implement
if (mHand[0].mRank == (mHand[1].mRank - 1) &&
mHand[1].mRank == (mHand[2].mRank - 1) &&
mHand[2].mRank == (mHand[3].mRank - 1) &&
mHand[3].mRank == (mHand[4].mRank - 1))
{
retVal = true;
}
return retVal;
}
// Function: hasFlush
// Purpose: Determines if the hand has a flush
// Input: None
// Returns: true if there's a flush
bool PokerHand::hasFlush() const
{
bool retVal = false;
// TODO: Implement
if (mHand[0].mSuit == mHand[1].mSuit &&
mHand[1].mSuit == mHand[2].mSuit &&
mHand[2].mSuit == mHand[3].mSuit &&
mHand[3].mSuit == mHand[4].mSuit)
{
retVal = true;
}
return retVal;
}
// Function: hasFourOfAKind
// Purpose: Determines if the hand has a 4 of a kind
// Input: None
// Returns: true if there's a 4 of a kind
bool PokerHand::hasFourOfAKind() const
{
// Since it's sorted, there are only two possibilities:
// x x x x y
// or
// x y y y y
bool retVal = false;
if (mHand[0].mRank == mHand[1].mRank &&
mHand[1].mRank == mHand[2].mRank &&
mHand[2].mRank == mHand[3].mRank)
{
retVal = true;
}
if (mHand[1].mRank == mHand[2].mRank &&
mHand[2].mRank == mHand[3].mRank &&
mHand[3].mRank == mHand[4].mRank)
{
retVal = true;
}
return retVal;
}
// Function: hasFullHouse
// Purpose: Determines if the hand has a full house
// Input: None
// Returns: true if there's a full house
bool PokerHand::hasFullHouse() const
{
// Since it's sorted, there are only two possibilities:
// x x x y y
// or
// x x y y y
bool retVal = false;
// TODO: Implement
if (mHand[0].mRank == mHand[1].mRank &&
mHand[1].mRank == mHand[2].mRank &&
mHand[3].mRank == mHand[4].mRank)
{
retVal = true;
}
if (mHand[0].mRank == mHand[1].mRank &&
mHand[2].mRank == mHand[3].mRank &&
mHand[3].mRank == mHand[4].mRank)
{
retVal = true;
}
return retVal;
}
// Function: hasThreeOfAKind
// Purpose: Determines if the hand has a three of a kind
// Input: None
// Returns: true if there's a three of a kind
bool PokerHand::hasThreeOfAKind() const
{
// There are three possibilities:
// x x x y z
// x y y y z
// x y z z z
bool retVal = false;
// TODO: Implement
if (mHand[0].mRank == mHand[1].mRank &&
mHand[1].mRank == mHand[2].mRank &&
mHand[3].mRank != mHand[4].mRank)
{
retVal = true;
}
if (mHand[0].mRank != mHand[4].mRank &&
mHand[1].mRank == mHand[2].mRank &&
mHand[2].mRank == mHand[3].mRank)
{
retVal = true;
}
if (mHand[0].mRank != mHand[1].mRank &&
mHand[2].mRank == mHand[3].mRank &&
mHand[3].mRank == mHand[4].mRank)
{
retVal = true;
}
return retVal;
}
// Function: hasTwoPairs
// Purpose: Determines if the hand has two pairs
// Input: None
// Returns: true if there's two pairs
bool PokerHand::hasTwoPairs() const
{
// There are three possibilities:
// x x y y z
// x y y z z
// x x y z z
bool retVal = false;
// TODO: Implement
if (mHand[0].mRank == mHand[1].mRank &&
mHand[1].mRank != mHand[2].mRank &&
mHand[2].mRank == mHand[3].mRank &&
mHand[3].mRank != mHand[4].mRank &&
mHand[0].mRank != mHand[4].mRank)
{
retVal = true;
}
if (mHand[1].mRank != mHand[2].mRank &&
mHand[1].mRank == mHand[0].mRank &&
mHand[2].mRank != mHand[0].mRank &&
mHand[3].mRank == mHand[1].mRank &&
mHand[4].mRank != mHand[0].mRank)
{
retVal = true;
}
if (mHand[0].mRank == mHand[1].mRank &&
mHand[1].mRank != mHand[2].mRank &&
mHand[2].mRank != mHand[3].mRank &&
mHand[3].mRank == mHand[4].mRank &&
mHand[0].mRank != mHand[4].mRank
)
{
retVal = true;
}
return retVal;
}
// Function: hasPair
// Purpose: Determines if there's a pair
// Input: None
// Returns: true if there's a pair
bool PokerHand::hasPair() const
{
// There's a pair if any neighbors are equal to each other
bool retVal = false;
if (mHand[0].mRank == mHand[1].mRank &&
mHand[2].mRank != mHand[1].mRank &&
mHand[2].mRank != mHand[3].mRank &&
mHand[3].mRank != mHand[4].mRank)
{
retVal = true;
}
if (mHand[1].mRank == mHand[2].mRank &&
mHand[1].mRank != mHand[0].mRank &&
mHand[2].mRank != mHand[0].mRank &&
mHand[3].mRank != mHand[1].mRank &&
mHand[4].mRank != mHand[0].mRank)
{
retVal = true;
}
if (mHand[2].mRank == mHand[3].mRank &&
mHand[0].mRank != mHand[1].mRank &&
mHand[1].mRank != mHand[2].mRank &&
mHand[3].mRank != mHand[4].mRank &&
mHand[0].mRank != mHand[4].mRank)
{
retVal = true;
}
if (mHand[0].mRank != mHand[1].mRank &&
mHand[1].mRank != mHand[2].mRank &&
mHand[2].mRank != mHand[3].mRank &&
mHand[3].mRank == mHand[4].mRank &&
mHand[0].mRank != mHand[4].mRank)
{
retVal = true;
}
return retVal;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// NOTE: Do not edit code below this line!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Function: createDeck
// Purpose: Given an empty ITPVector of Cards, inserts a
// standard 52 card deck and shuffles it
// Input: An ITPVector of Cards (by reference)
// Returns: nothing
void createDeck(ITPVector<Card>& deck)
{
for (int i = 0; i < 4; i++)
{
Suit suit = Suit(i);
for (int value = 2; value <= 14; value++)
{
deck.insert_back(Card(value, suit));
}
}
// Shuffle the deck
std::shuffle(&deck[0], &deck[0] + deck.size(), std::random_device());
}
// Function: << operator for Card
// Purpose: Outputs the name and suit of the card
// Input: ostream and card
// Returns: ostream, with card data output to it
std::ostream& operator<<(std::ostream& os, const Card& card)
{
// Output value
if (card.mRank < 11) // Number card
{
os << card.mRank;
}
else // Face card
{
switch (card.mRank)
{
case 11:
os << "Jack";
break;
case 12:
os << "Queen";
break;
case 13:
os << "King";
break;
case 14:
os << "Ace";
break;
default:
os << "Invalid";
break;
}
}
// Output suit
os << " of ";
switch (card.mSuit)
{
case CLUBS:
os << "Clubs";
break;
case DIAMONDS:
os << "Diamonds";
break;
case HEARTS:
os << "Hearts";
break;
case SPADES:
os << "Spades";
break;
default:
os << "Invalid";
break;
}
return os;
}
// Function: < comparison operator for Card
// Purpose: Compares the value of the left and right card
// Input: Two cards to compare
// Returns: true if left < right
bool operator<(const Card& left, const Card& right)
{
// If their values are the same, compare the suits
if (left.mRank == right.mRank)
{
return left.mSuit < right.mSuit;
}
else
{
return left.mRank < right.mRank;
}
}
// Function: << operator
// Purpose: Prints out the hand
std::ostream& operator<<(std::ostream& os, const PokerHand& hand)
{
os << hand.mHand;
return os;
}
| [
"bryanvo@Bryans-MacBook-Pro.local"
] | bryanvo@Bryans-MacBook-Pro.local |
28d5fba33a5b749255b05d585b8c302874a1302e | a53f8d2859477f837c81f943c81ceed56cf37238 | /RTL/Component/CLODAuthor/NormalMap.cpp | 2d9d930aec3063428fe251b65acc0c8f4298236b | [
"Apache-2.0"
] | permissive | ClinicalGraphics/u3d | ffd062630cde8c27a0792370c158966d51182d4d | a2dc4bf9ead5400939f698d5834b7c5d43dbf42a | refs/heads/master | 2023-04-13T17:25:55.126360 | 2023-03-30T07:34:12 | 2023-03-31T18:20:43 | 61,121,064 | 11 | 5 | Apache-2.0 | 2023-09-01T04:23:31 | 2016-06-14T12:29:13 | C++ | UTF-8 | C++ | false | false | 6,071 | cpp | //***************************************************************************
//
// Copyright (c) 1999 - 2006 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//***************************************************************************
#include <float.h>
#include "NormalMap.h"
NormalMap::NormalMap(int n)
{
// Figure out "reasonable" dimensions for the hash table:
// Empirically I found the following technique to yield only about ~8% empty cells
// for n between 1000 and 100,000. Lower bound will by a 3x5 hashtable
hashWidth = (int) (sqrt( (float)n) / 2.0f);
hashHeight = (int) (hashWidth / 2.0f);
if ((hashWidth < 5) || (hashHeight < 3))
{
hashWidth = 5;
hashHeight = 3;
}
numCells = hashWidth * hashHeight;
numNormals = n;
hashTable = new IntList[numCells];
polarNormals = new PolarCoord[numNormals];
}
NormalMap::~NormalMap()
{
// Loop over all of the cells in the hash table and free the lists:
delete []hashTable;
delete []polarNormals;
}
void NormalMap::vectorToPolar(IV3D *normal, float *phi, float *theta)
{
// Convert normals into polar co-ordinates:
// In general: phi = acos (z/(sqrt(x^2 + y^2 + z^2))) and
// theta = atan(y/x). Since this is an normalized vector, we don't need to
// do the square root...it's always 1. Thus:
if (normal->z > 1.0f)
{
*phi = 0.0f;
}
else if (normal->z < -1.0f)
{
*phi = 0.0f;
}
else
{
*phi = acosf(normal->z);
}
*theta = atan2f(normal->x, normal->y);
}
void NormalMap::insertNormals (IV3D *normals)
{
BOOL duplicateNormal;
U32 index;
U32 actualNumNormals = numNormals;
for (unsigned long n = 0; n < numNormals; n++)
{
int row, col;
vectorToPolar (&normals[n], &polarNormals[n].phi, &polarNormals[n].theta);
polarToRowColumn (polarNormals[n].phi, polarNormals[n].theta, &row, &col);
int hashIndex = hash (row, col);
IntList *list = &hashTable[hashIndex];
// avoid putting duplicate normals in the hash table, it really slows things down.
duplicateNormal = FALSE;
if( list->GetFirst() )
do
{
index = list->GetCurrentData();
if(normals[n].x == normals[index].x &&
normals[n].y == normals[index].y &&
normals[n].z == normals[index].z)
duplicateNormal = TRUE;
} while (!duplicateNormal && list->GetNext());
if(!duplicateNormal)
list->Push(n);
else
actualNumNormals--;
}
}
void NormalMap::nearest (IV3D *normal, unsigned long *index, float *distance)
{
float phi, theta;
int row, col; // , initialRow, initialCol;
vectorToPolar (normal, &phi, &theta);
polarToRowColumn (phi, theta, &row, &col);
// initialRow = row;
// initialCol = col;
// Find neighboring cells:
int left = col - 1;
int right = col + 1;
int up = row - 1;
int down = row + 1;
float closestDistance = FLT_MAX; // Infinity
float testDistance;
unsigned long closest = 0;
int emptyNeighbors = TRUE;
int r,c;
for (r = up; r <= down; r++)
{
// Determine row:
row = r;
if (row < 0)
row += hashHeight;
row = row % hashHeight;
for (c = left; c <= right; c++)
{
// Determine col:
col = c;
if (col < 0)
col += hashWidth;
col = col % hashWidth;
// Grab a cell indexed by row,col:
unsigned long hashIndex = hash (row, col);
IntList *list = &hashTable[hashIndex];
// Compare against each normal in this cell:
if (list->GetFirst())
{
do
{
unsigned long current = list->GetCurrentData();
PolarCoord *pc = &polarNormals[current];
testDistance = polarDistanceSquared (phi, theta, pc->phi, pc->theta);
if (testDistance < closestDistance)
{
closestDistance = testDistance;
closest = current;
emptyNeighbors = FALSE;
}
} while(list->GetNext());
}//if list->GetFirst
}//for c
}//for r
if (!emptyNeighbors)
{
*index = closest;
*distance = closestDistance;
return;
}
// Otherwise...we'll search through all of the normals. This could be less
// drastic and we could try more local searches first...I'll try to implement this later.
// It won't be too much of an issue if you choose good hash dimensions which nicely
// distribute the normals.
for (unsigned long n = 0; n < numNormals; n++)
{
PolarCoord *pc = &polarNormals[n];
testDistance = polarDistanceSquared (phi, theta, pc->phi, pc->theta);
if (testDistance < closestDistance)
{
closestDistance = testDistance;
closest = n;
}
}//for
*index = closest;
*distance = closestDistance;
}
void NormalMap::searchCell( float phi, float theta, int row, int col,
float* closestDistance, unsigned long* closestIndex )
{
float testDistance;
// fix up row and col numbers that are beyond range
if (row < 0) row += hashHeight;
row = row % hashHeight;
if (col < 0) col += hashWidth;
col = col % hashWidth;
// Grab a cell indexed by row,col:
unsigned long hashIndex = hash (row, col);
IntList *list = &hashTable[hashIndex];
// Compare against each normal in this cell:
if (list->GetFirst())
{
do
{
unsigned long current = list->GetCurrentData();
PolarCoord *pc = &polarNormals[current];
testDistance = polarDistanceSquared (phi, theta, pc->phi, pc->theta);
if (testDistance < *closestDistance)
{
*closestDistance = testDistance;
*closestIndex = current;
}
} while(list->GetNext());
}//if list->GetFirst
}
unsigned long NormalMap::hash (IV3D *normal)
{
float phi, theta;
int row, col;
vectorToPolar (normal, &phi, &theta);
polarToRowColumn (phi, theta, &row, &col);
unsigned long index = hash(row, col);
return index;
}
| [
"ningfei.li@gmail.com"
] | ningfei.li@gmail.com |
629bd52866c3ee4d8e28b75c62dc281c039db289 | 26df574c68ca8a470bd3a4b5fa145bfa73cd85b2 | /Source/Private/OnlineSessionInfoHive.h | ce45db2c9d8aec970d0ef3a088ff6a7ef4bf6bf1 | [] | no_license | hach-que/HiveMP-UnrealEngine4-SDK-Archived | 43717ee8b350a1cacc24a7638123a03c706e773a | d5cf4a50f9ac2ffce09c7a4596d23246bb678f62 | refs/heads/master | 2021-01-01T04:28:00.056639 | 2017-09-29T15:51:11 | 2017-09-29T15:51:11 | 97,178,781 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,332 | h | // Copyright 2017 Redpoint Games. MIT Licensed.
#pragma once
#include "CoreMinimal.h"
#include "UObject/CoreOnline.h"
#include "OnlineSubsystemTypes.h"
#include "IPAddress.h"
class FOnlineSessionInfoHive : public FOnlineSessionInfo
{
protected:
/** Hidden on purpose */
FOnlineSessionInfoHive(const FOnlineSessionInfoHive& Src)
{
}
/** Hidden on purpose */
FOnlineSessionInfoHive& operator=(const FOnlineSessionInfoHive& Src)
{
return *this;
}
PACKAGE_SCOPE:
/** Constructor for game lobbies */
FOnlineSessionInfoHive(const FUniqueNetIdString& InLobbyId) :
LobbyId(InLobbyId) {}
/** The Hive lobby ID */
FUniqueNetIdString LobbyId;
public:
virtual ~FOnlineSessionInfoHive() {}
/**
* Comparison operator
*/
bool operator==(const FOnlineSessionInfoHive& Other) const
{
return false;
}
virtual int32 GetSize() const override
{
return sizeof(uint64) +
sizeof(FString);
}
virtual bool IsValid() const override
{
return true;
}
virtual const uint8* GetBytes() const override
{
return NULL;
}
virtual FString ToString() const override
{
return LobbyId.ToString();
}
virtual FString ToDebugString() const override
{
return FString::Printf(TEXT("LobbyId: %s"), *LobbyId.ToString());
}
virtual const FUniqueNetId& GetSessionId() const override
{
return LobbyId;
}
}; | [
"jrhodes@redpointgames.com.au"
] | jrhodes@redpointgames.com.au |
a94a1c3040df290ea3c6ef114ec40df1154777d7 | f86a1f6890562ad5c01921c4c8b1aa2e90838e35 | /src/grid_ecs.hpp | 36b4efb9f02511aa693cb712508bfc80b09fe7f5 | [] | no_license | tomc1998/grid_scriptable | f85951bb190743edc061f5e62fceaef5e2e33091 | cd51a75d68a84487121efb3a4d1e650d84620dba | refs/heads/master | 2020-04-22T13:21:03.254119 | 2019-02-12T23:09:25 | 2019-02-12T23:09:25 | 170,405,795 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,552 | hpp | /** Contains code to tie the grid to the ecs. The grid is partially split this
way to work around forward declarations. */
#pragma once
/** Step the moving entities */
void grid_step(grid& g, entt::DefaultRegistry& r) {
for (unsigned ii = 0; ii < g.moving_list.size(); ++ii) {
// Find the (world) position we SHOULD be at
auto &e = *g.moving_list[ii];
float world_x = grid_to_world(e.x);
float world_y = grid_to_world(e.y);
// Lookup the entity's position
auto& pos = r.get<cpos>(e.e);
// Move the entity at the given transition speed.
// TODO We're assuming that we're moving in one of the cardinal
// directions, and therefore are using the manhattan distance rather than
// the euclidean distance. This needs to be changed if we want movement in
// more than 4 directions.
float dis = std::abs(world_x - pos.vec.x) + std::abs(world_y - pos.vec.y);
if (dis < e.transition_speed) {
// Stop moving this entity
pos.vec.x = world_x;
pos.vec.y = world_y;
e.is_moving = false;
g.moving_list.erase(g.moving_list.begin() + ii);
ii --;
} else {
// Step
pos.vec.x += e.transition_speed * (world_x - pos.vec.x) / dis;
pos.vec.y += e.transition_speed * (world_y - pos.vec.y) / dis;
}
}
}
/** Snap all the entities to the grid. */
void grid_snap(const grid& g, entt::DefaultRegistry& r) {
for (const auto &e : g.entity_list) {
auto& pos = r.get<cpos>(e.e);
pos.vec.x = grid_to_world(e.x);
pos.vec.y = grid_to_world(e.y);
}
}
| [
"thomascheng1998@googlemail.com"
] | thomascheng1998@googlemail.com |
99118a4e2c8b0e90c1b70e5cbb7ba5487a3dfdd1 | 2458d6d18521117124c1ba39cc8b4b8287d745cf | /cocos2d-x-2.2/cocos2dx/label_nodes/CCLabelBMFont.cpp | ec298dd849d0bcb4ce3c1a4b27127d1383efd667 | [
"MIT"
] | permissive | zhuzhonghua/XUI | a9d9fde0258ddde235fdd2aa52145b97b91e0ffc | 4cfd3e8c4d15f8cba4b918da3719aacdcf6009ce | refs/heads/master | 2020-06-26T09:21:06.810301 | 2014-01-07T03:03:22 | 2014-01-07T03:03:22 | 15,630,631 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 37,853 | cpp | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
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.
Use any of these editors to generate BMFonts:
http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
http://www.angelcode.com/products/bmfont/ (Free, Windows only)
****************************************************************************/
#include "CCLabelBMFont.h"
#include "cocoa/CCString.h"
#include "platform/platform.h"
#include "cocoa/CCDictionary.h"
#include "CCConfiguration.h"
#include "draw_nodes/CCDrawingPrimitives.h"
#include "sprite_nodes/CCSprite.h"
#include "support/CCPointExtension.h"
#include "platform/CCFileUtils.h"
#include "CCDirector.h"
#include "textures/CCTextureCache.h"
#include "support/ccUTF8.h"
using namespace std;
NS_CC_BEGIN
// The return value needs to be deleted by CC_SAFE_DELETE_ARRAY.
static unsigned short* copyUTF16StringN(unsigned short* str)
{
int length = str ? cc_wcslen(str) : 0;
unsigned short* ret = new unsigned short[length+1];
for (int i = 0; i < length; ++i) {
ret[i] = str[i];
}
ret[length] = 0;
return ret;
}
//
//FNTConfig Cache - free functions
//
static CCDictionary* s_pConfigurations = NULL;
CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile)
{
CCBMFontConfiguration* pRet = NULL;
if( s_pConfigurations == NULL )
{
s_pConfigurations = new CCDictionary();
}
pRet = (CCBMFontConfiguration*)s_pConfigurations->objectForKey(fntFile);
if( pRet == NULL )
{
pRet = CCBMFontConfiguration::create(fntFile);
if (pRet)
{
s_pConfigurations->setObject(pRet, fntFile);
}
}
return pRet;
}
void FNTConfigRemoveCache( void )
{
if (s_pConfigurations)
{
s_pConfigurations->removeAllObjects();
CC_SAFE_RELEASE_NULL(s_pConfigurations);
}
}
//
//BitmapFontConfiguration
//
CCBMFontConfiguration * CCBMFontConfiguration::create(const char *FNTfile)
{
CCBMFontConfiguration * pRet = new CCBMFontConfiguration();
if (pRet->initWithFNTfile(FNTfile))
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool CCBMFontConfiguration::initWithFNTfile(const char *FNTfile)
{
m_pKerningDictionary = NULL;
m_pFontDefDictionary = NULL;
m_pCharacterSet = this->parseConfigFile(FNTfile);
if (! m_pCharacterSet)
{
return false;
}
return true;
}
std::set<unsigned int>* CCBMFontConfiguration::getCharacterSet() const
{
return m_pCharacterSet;
}
CCBMFontConfiguration::CCBMFontConfiguration()
: m_pFontDefDictionary(NULL)
, m_nCommonHeight(0)
, m_pKerningDictionary(NULL)
, m_pCharacterSet(NULL)
{
}
CCBMFontConfiguration::~CCBMFontConfiguration()
{
CCLOGINFO( "cocos2d: deallocing CCBMFontConfiguration" );
this->purgeFontDefDictionary();
this->purgeKerningDictionary();
m_sAtlasName.clear();
CC_SAFE_DELETE(m_pCharacterSet);
}
const char* CCBMFontConfiguration::description(void)
{
return CCString::createWithFormat(
"<CCBMFontConfiguration = " CC_FORMAT_PRINTF_SIZE_T " | Glphys:%d Kernings:%d | Image = %s>",
(size_t)this,
HASH_COUNT(m_pFontDefDictionary),
HASH_COUNT(m_pKerningDictionary),
m_sAtlasName.c_str()
)->getCString();
}
void CCBMFontConfiguration::purgeKerningDictionary()
{
tCCKerningHashElement *current;
while(m_pKerningDictionary)
{
current = m_pKerningDictionary;
HASH_DEL(m_pKerningDictionary,current);
free(current);
}
}
void CCBMFontConfiguration::purgeFontDefDictionary()
{
tCCFontDefHashElement *current, *tmp;
HASH_ITER(hh, m_pFontDefDictionary, current, tmp) {
HASH_DEL(m_pFontDefDictionary, current);
free(current);
}
}
std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const char *controlFile)
{
std::string fullpath = CCFileUtils::sharedFileUtils()->fullPathForFilename(controlFile);
CCString *contents = CCString::createWithContentsOfFile(fullpath.c_str());
CCAssert(contents, "CCBMFontConfiguration::parseConfigFile | Open file error.");
set<unsigned int> *validCharsString = new set<unsigned int>();
if (!contents)
{
CCLOG("cocos2d: Error parsing FNTfile %s", controlFile);
return NULL;
}
// parse spacing / padding
std::string line;
std::string strLeft = contents->getCString();
while (strLeft.length() > 0)
{
int pos = strLeft.find('\n');
if (pos != (int)std::string::npos)
{
// the data is more than a line.get one line
line = strLeft.substr(0, pos);
strLeft = strLeft.substr(pos + 1);
}
else
{
// get the left data
line = strLeft;
strLeft.erase();
}
if(line.substr(0,strlen("info face")) == "info face")
{
// XXX: info parsing is incomplete
// Not needed for the Hiero editors, but needed for the AngelCode editor
// [self parseInfoArguments:line];
this->parseInfoArguments(line);
}
// Check to see if the start of the line is something we are interested in
else if(line.substr(0,strlen("common lineHeight")) == "common lineHeight")
{
this->parseCommonArguments(line);
}
else if(line.substr(0,strlen("page id")) == "page id")
{
this->parseImageFileName(line, controlFile);
}
else if(line.substr(0,strlen("chars c")) == "chars c")
{
// Ignore this line
}
else if(line.substr(0,strlen("char")) == "char")
{
// Parse the current line and create a new CharDef
tCCFontDefHashElement* element = (tCCFontDefHashElement*)malloc( sizeof(*element) );
this->parseCharacterDefinition(line, &element->fontDef);
element->key = element->fontDef.charID;
HASH_ADD_INT(m_pFontDefDictionary, key, element);
validCharsString->insert(element->fontDef.charID);
}
// else if(line.substr(0,strlen("kernings count")) == "kernings count")
// {
// this->parseKerningCapacity(line);
// }
else if(line.substr(0,strlen("kerning first")) == "kerning first")
{
this->parseKerningEntry(line);
}
}
return validCharsString;
}
void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fntFile)
{
//////////////////////////////////////////////////////////////////////////
// line to parse:
// page id=0 file="bitmapFontTest.png"
//////////////////////////////////////////////////////////////////////////
// page ID. Sanity check
int index = line.find('=')+1;
int index2 = line.find(' ', index);
std::string value = line.substr(index, index2-index);
CCAssert(atoi(value.c_str()) == 0, "LabelBMFont file could not be found");
// file
index = line.find('"')+1;
index2 = line.find('"', index);
value = line.substr(index, index2-index);
m_sAtlasName = CCFileUtils::sharedFileUtils()->fullPathFromRelativeFile(value.c_str(), fntFile);
}
void CCBMFontConfiguration::parseInfoArguments(std::string line)
{
//////////////////////////////////////////////////////////////////////////
// possible lines to parse:
// info face="Script" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,4,3,2 spacing=0,0 outline=0
// info face="Cracked" size=36 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1
//////////////////////////////////////////////////////////////////////////
// padding
int index = line.find("padding=");
int index2 = line.find(' ', index);
std::string value = line.substr(index, index2-index);
sscanf(value.c_str(), "padding=%d,%d,%d,%d", &m_tPadding.top, &m_tPadding.right, &m_tPadding.bottom, &m_tPadding.left);
CCLOG("cocos2d: padding: %d,%d,%d,%d", m_tPadding.left, m_tPadding.top, m_tPadding.right, m_tPadding.bottom);
}
void CCBMFontConfiguration::parseCommonArguments(std::string line)
{
//////////////////////////////////////////////////////////////////////////
// line to parse:
// common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0
//////////////////////////////////////////////////////////////////////////
// Height
int index = line.find("lineHeight=");
int index2 = line.find(' ', index);
std::string value = line.substr(index, index2-index);
sscanf(value.c_str(), "lineHeight=%d", &m_nCommonHeight);
// scaleW. sanity check
index = line.find("scaleW=") + strlen("scaleW=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported");
// scaleH. sanity check
index = line.find("scaleH=") + strlen("scaleH=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported");
// pages. sanity check
index = line.find("pages=") + strlen("pages=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
CCAssert(atoi(value.c_str()) == 1, "CCBitfontAtlas: only supports 1 page");
// packed (ignore) What does this mean ??
}
void CCBMFontConfiguration::parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition)
{
//////////////////////////////////////////////////////////////////////////
// line to parse:
// char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=44 xadvance=14 page=0 chnl=0
//////////////////////////////////////////////////////////////////////////
// Character ID
int index = line.find("id=");
int index2 = line.find(' ', index);
std::string value = line.substr(index, index2-index);
sscanf(value.c_str(), "id=%u", &characterDefinition->charID);
// Character x
index = line.find("x=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
sscanf(value.c_str(), "x=%f", &characterDefinition->rect.origin.x);
// Character y
index = line.find("y=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
sscanf(value.c_str(), "y=%f", &characterDefinition->rect.origin.y);
// Character width
index = line.find("width=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
sscanf(value.c_str(), "width=%f", &characterDefinition->rect.size.width);
// Character height
index = line.find("height=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
sscanf(value.c_str(), "height=%f", &characterDefinition->rect.size.height);
// Character xoffset
index = line.find("xoffset=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
sscanf(value.c_str(), "xoffset=%hd", &characterDefinition->xOffset);
// Character yoffset
index = line.find("yoffset=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
sscanf(value.c_str(), "yoffset=%hd", &characterDefinition->yOffset);
// Character xadvance
index = line.find("xadvance=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
sscanf(value.c_str(), "xadvance=%hd", &characterDefinition->xAdvance);
}
void CCBMFontConfiguration::parseKerningEntry(std::string line)
{
//////////////////////////////////////////////////////////////////////////
// line to parse:
// kerning first=121 second=44 amount=-7
//////////////////////////////////////////////////////////////////////////
// first
int first;
int index = line.find("first=");
int index2 = line.find(' ', index);
std::string value = line.substr(index, index2-index);
sscanf(value.c_str(), "first=%d", &first);
// second
int second;
index = line.find("second=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
sscanf(value.c_str(), "second=%d", &second);
// amount
int amount;
index = line.find("amount=");
index2 = line.find(' ', index);
value = line.substr(index, index2-index);
sscanf(value.c_str(), "amount=%d", &amount);
tCCKerningHashElement *element = (tCCKerningHashElement *)calloc( sizeof( *element ), 1 );
element->amount = amount;
element->key = (first<<16) | (second&0xffff);
HASH_ADD_INT(m_pKerningDictionary,key, element);
}
//
//CCLabelBMFont
//
//LabelBMFont - Purge Cache
void CCLabelBMFont::purgeCachedData()
{
FNTConfigRemoveCache();
}
CCLabelBMFont * CCLabelBMFont::create()
{
CCLabelBMFont * pRet = new CCLabelBMFont();
if (pRet && pRet->init())
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
CCLabelBMFont * CCLabelBMFont::create(const char *str, const char *fntFile, float width, CCTextAlignment alignment)
{
return CCLabelBMFont::create(str, fntFile, width, alignment, CCPointZero);
}
CCLabelBMFont * CCLabelBMFont::create(const char *str, const char *fntFile, float width)
{
return CCLabelBMFont::create(str, fntFile, width, kCCTextAlignmentLeft, CCPointZero);
}
CCLabelBMFont * CCLabelBMFont::create(const char *str, const char *fntFile)
{
return CCLabelBMFont::create(str, fntFile, kCCLabelAutomaticWidth, kCCTextAlignmentLeft, CCPointZero);
}
//LabelBMFont - Creation & Init
CCLabelBMFont *CCLabelBMFont::create(const char *str, const char *fntFile, float width/* = kCCLabelAutomaticWidth*/, CCTextAlignment alignment/* = kCCTextAlignmentLeft*/, CCPoint imageOffset/* = CCPointZero*/)
{
CCLabelBMFont *pRet = new CCLabelBMFont();
if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset))
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool CCLabelBMFont::init()
{
return initWithString(NULL, NULL, kCCLabelAutomaticWidth, kCCTextAlignmentLeft, CCPointZero);
}
bool CCLabelBMFont::initWithString(const char *theString, const char *fntFile, float width/* = kCCLabelAutomaticWidth*/, CCTextAlignment alignment/* = kCCTextAlignmentLeft*/, CCPoint imageOffset/* = CCPointZero*/)
{
CCAssert(!m_pConfiguration, "re-init is no longer supported");
CCAssert( (theString && fntFile) || (theString==NULL && fntFile==NULL), "Invalid params for CCLabelBMFont");
CCTexture2D *texture = NULL;
if (fntFile)
{
CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile);
if (!newConf)
{
CCLOG("cocos2d: WARNING. CCLabelBMFont: Impossible to create font. Please check file: '%s'", fntFile);
release();
return false;
}
newConf->retain();
CC_SAFE_RELEASE(m_pConfiguration);
m_pConfiguration = newConf;
m_sFntFile = fntFile;
texture = CCTextureCache::sharedTextureCache()->addImage(m_pConfiguration->getAtlasName());
}
else
{
texture = new CCTexture2D();
texture->autorelease();
}
if (theString == NULL)
{
theString = "";
}
if (CCSpriteBatchNode::initWithTexture(texture, strlen(theString)))
{
m_fWidth = width;
m_pAlignment = alignment;
m_cDisplayedOpacity = m_cRealOpacity = 255;
m_tDisplayedColor = m_tRealColor = ccWHITE;
m_bCascadeOpacityEnabled = true;
m_bCascadeColorEnabled = true;
m_obContentSize = CCSizeZero;
m_bIsOpacityModifyRGB = m_pobTextureAtlas->getTexture()->hasPremultipliedAlpha();
m_obAnchorPoint = ccp(0.5f, 0.5f);
m_tImageOffset = imageOffset;
m_pReusedChar = new CCSprite();
m_pReusedChar->initWithTexture(m_pobTextureAtlas->getTexture(), CCRectMake(0, 0, 0, 0), false);
m_pReusedChar->setBatchNode(this);
this->setString(theString, true);
return true;
}
return false;
}
CCLabelBMFont::CCLabelBMFont()
: m_sString(NULL)
, m_sInitialString(NULL)
, m_pAlignment(kCCTextAlignmentCenter)
, m_fWidth(-1.0f)
, m_pConfiguration(NULL)
, m_bLineBreakWithoutSpaces(false)
, m_tImageOffset(CCPointZero)
, m_pReusedChar(NULL)
, m_cDisplayedOpacity(255)
, m_cRealOpacity(255)
, m_tDisplayedColor(ccWHITE)
, m_tRealColor(ccWHITE)
, m_bCascadeColorEnabled(true)
, m_bCascadeOpacityEnabled(true)
, m_bIsOpacityModifyRGB(false)
{
}
CCLabelBMFont::~CCLabelBMFont()
{
CC_SAFE_RELEASE(m_pReusedChar);
CC_SAFE_DELETE_ARRAY(m_sString);
CC_SAFE_DELETE_ARRAY(m_sInitialString);
CC_SAFE_RELEASE(m_pConfiguration);
}
// LabelBMFont - Atlas generation
int CCLabelBMFont::kerningAmountForFirst(unsigned short first, unsigned short second)
{
int ret = 0;
unsigned int key = (first<<16) | (second & 0xffff);
if( m_pConfiguration->m_pKerningDictionary ) {
tCCKerningHashElement *element = NULL;
HASH_FIND_INT(m_pConfiguration->m_pKerningDictionary, &key, element);
if(element)
ret = element->amount;
}
return ret;
}
void CCLabelBMFont::createFontChars()
{
int nextFontPositionX = 0;
int nextFontPositionY = 0;
unsigned short prev = -1;
int kerningAmount = 0;
CCSize tmpSize = CCSizeZero;
int longestLine = 0;
unsigned int totalHeight = 0;
unsigned int quantityOfLines = 1;
unsigned int stringLen = m_sString ? cc_wcslen(m_sString) : 0;
if (stringLen == 0)
{
return;
}
set<unsigned int> *charSet = m_pConfiguration->getCharacterSet();
for (unsigned int i = 0; i < stringLen - 1; ++i)
{
unsigned short c = m_sString[i];
if (c == '\n')
{
quantityOfLines++;
}
}
totalHeight = m_pConfiguration->m_nCommonHeight * quantityOfLines;
nextFontPositionY = 0-(m_pConfiguration->m_nCommonHeight - m_pConfiguration->m_nCommonHeight * quantityOfLines);
CCRect rect;
ccBMFontDef fontDef;
for (unsigned int i= 0; i < stringLen; i++)
{
unsigned short c = m_sString[i];
if (c == '\n')
{
nextFontPositionX = 0;
nextFontPositionY -= m_pConfiguration->m_nCommonHeight;
continue;
}
if (charSet->find(c) == charSet->end())
{
CCLOGWARN("cocos2d::CCLabelBMFont: Attempted to use character not defined in this bitmap: %d", c);
continue;
}
kerningAmount = this->kerningAmountForFirst(prev, c);
tCCFontDefHashElement *element = NULL;
// unichar is a short, and an int is needed on HASH_FIND_INT
unsigned int key = c;
HASH_FIND_INT(m_pConfiguration->m_pFontDefDictionary, &key, element);
if (! element)
{
CCLOGWARN("cocos2d::CCLabelBMFont: characer not found %d", c);
continue;
}
fontDef = element->fontDef;
rect = fontDef.rect;
rect = CC_RECT_PIXELS_TO_POINTS(rect);
rect.origin.x += m_tImageOffset.x;
rect.origin.y += m_tImageOffset.y;
CCSprite *fontChar;
bool hasSprite = true;
fontChar = (CCSprite*)(this->getChildByTag(i));
if(fontChar )
{
// Reusing previous Sprite
fontChar->setVisible(true);
}
else
{
// New Sprite ? Set correct color, opacity, etc...
if( 0 )
{
/* WIP: Doesn't support many features yet.
But this code is super fast. It doesn't create any sprite.
Ideal for big labels.
*/
fontChar = m_pReusedChar;
fontChar->setBatchNode(NULL);
hasSprite = false;
}
else
{
fontChar = new CCSprite();
fontChar->initWithTexture(m_pobTextureAtlas->getTexture(), rect);
addChild(fontChar, i, i);
fontChar->release();
}
// Apply label properties
fontChar->setOpacityModifyRGB(m_bIsOpacityModifyRGB);
// Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
fontChar->updateDisplayedColor(m_tDisplayedColor);
fontChar->updateDisplayedOpacity(m_cDisplayedOpacity);
}
// updating previous sprite
fontChar->setTextureRect(rect, false, rect.size);
// See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
int yOffset = m_pConfiguration->m_nCommonHeight - fontDef.yOffset;
CCPoint fontPos = ccp( (float)nextFontPositionX + fontDef.xOffset + fontDef.rect.size.width*0.5f + kerningAmount,
(float)nextFontPositionY + yOffset - rect.size.height*0.5f * CC_CONTENT_SCALE_FACTOR() );
fontChar->setPosition(CC_POINT_PIXELS_TO_POINTS(fontPos));
// update kerning
nextFontPositionX += fontDef.xAdvance + kerningAmount;
prev = c;
if (longestLine < nextFontPositionX)
{
longestLine = nextFontPositionX;
}
if (! hasSprite)
{
updateQuadFromSprite(fontChar, i);
}
}
// If the last character processed has an xAdvance which is less that the width of the characters image, then we need
// to adjust the width of the string to take this into account, or the character will overlap the end of the bounding
// box
if (fontDef.xAdvance < fontDef.rect.size.width)
{
tmpSize.width = longestLine + fontDef.rect.size.width - fontDef.xAdvance;
}
else
{
tmpSize.width = longestLine;
}
tmpSize.height = totalHeight;
this->setContentSize(CC_SIZE_PIXELS_TO_POINTS(tmpSize));
}
//LabelBMFont - CCLabelProtocol protocol
void CCLabelBMFont::setString(const char *newString)
{
this->setString(newString, true);
}
void CCLabelBMFont::setString(const char *newString, bool needUpdateLabel)
{
if (newString == NULL) {
newString = "";
}
if (needUpdateLabel) {
m_sInitialStringUTF8 = newString;
}
unsigned short* utf16String = cc_utf8_to_utf16(newString);
setString(utf16String, needUpdateLabel);
CC_SAFE_DELETE_ARRAY(utf16String);
}
void CCLabelBMFont::setString(unsigned short *newString, bool needUpdateLabel)
{
if (!needUpdateLabel)
{
unsigned short* tmp = m_sString;
m_sString = copyUTF16StringN(newString);
CC_SAFE_DELETE_ARRAY(tmp);
}
else
{
unsigned short* tmp = m_sInitialString;
m_sInitialString = copyUTF16StringN(newString);
CC_SAFE_DELETE_ARRAY(tmp);
}
if (m_pChildren && m_pChildren->count() != 0)
{
CCObject* child;
CCARRAY_FOREACH(m_pChildren, child)
{
CCNode* pNode = (CCNode*) child;
if (pNode)
{
pNode->setVisible(false);
}
}
}
this->createFontChars();
if (needUpdateLabel) {
updateLabel();
}
}
const char* CCLabelBMFont::getString(void)
{
return m_sInitialStringUTF8.c_str();
}
void CCLabelBMFont::setCString(const char *label)
{
setString(label);
}
//LabelBMFont - CCRGBAProtocol protocol
const ccColor3B& CCLabelBMFont::getColor()
{
return m_tRealColor;
}
const ccColor3B& CCLabelBMFont::getDisplayedColor()
{
return m_tDisplayedColor;
}
void CCLabelBMFont::setColor(const ccColor3B& color)
{
m_tDisplayedColor = m_tRealColor = color;
if( m_bCascadeColorEnabled ) {
ccColor3B parentColor = ccWHITE;
CCRGBAProtocol* pParent = dynamic_cast<CCRGBAProtocol*>(m_pParent);
if (pParent && pParent->isCascadeColorEnabled())
{
parentColor = pParent->getDisplayedColor();
}
this->updateDisplayedColor(parentColor);
}
}
GLubyte CCLabelBMFont::getOpacity(void)
{
return m_cRealOpacity;
}
GLubyte CCLabelBMFont::getDisplayedOpacity(void)
{
return m_cDisplayedOpacity;
}
/** Override synthesized setOpacity to recurse items */
void CCLabelBMFont::setOpacity(GLubyte opacity)
{
m_cDisplayedOpacity = m_cRealOpacity = opacity;
if( m_bCascadeOpacityEnabled ) {
GLubyte parentOpacity = 255;
CCRGBAProtocol* pParent = dynamic_cast<CCRGBAProtocol*>(m_pParent);
if (pParent && pParent->isCascadeOpacityEnabled())
{
parentOpacity = pParent->getDisplayedOpacity();
}
this->updateDisplayedOpacity(parentOpacity);
}
}
void CCLabelBMFont::setOpacityModifyRGB(bool var)
{
m_bIsOpacityModifyRGB = var;
if (m_pChildren && m_pChildren->count() != 0)
{
CCObject* child;
CCARRAY_FOREACH(m_pChildren, child)
{
CCNode* pNode = (CCNode*) child;
if (pNode)
{
CCRGBAProtocol *pRGBAProtocol = dynamic_cast<CCRGBAProtocol*>(pNode);
if (pRGBAProtocol)
{
pRGBAProtocol->setOpacityModifyRGB(m_bIsOpacityModifyRGB);
}
}
}
}
}
bool CCLabelBMFont::isOpacityModifyRGB()
{
return m_bIsOpacityModifyRGB;
}
void CCLabelBMFont::updateDisplayedOpacity(GLubyte parentOpacity)
{
m_cDisplayedOpacity = m_cRealOpacity * parentOpacity/255.0;
CCObject* pObj;
CCARRAY_FOREACH(m_pChildren, pObj)
{
CCSprite *item = (CCSprite*)pObj;
item->updateDisplayedOpacity(m_cDisplayedOpacity);
}
}
void CCLabelBMFont::updateDisplayedColor(const ccColor3B& parentColor)
{
m_tDisplayedColor.r = m_tRealColor.r * parentColor.r/255.0;
m_tDisplayedColor.g = m_tRealColor.g * parentColor.g/255.0;
m_tDisplayedColor.b = m_tRealColor.b * parentColor.b/255.0;
CCObject* pObj;
CCARRAY_FOREACH(m_pChildren, pObj)
{
CCSprite *item = (CCSprite*)pObj;
item->updateDisplayedColor(m_tDisplayedColor);
}
}
bool CCLabelBMFont::isCascadeColorEnabled()
{
return false;
}
void CCLabelBMFont::setCascadeColorEnabled(bool cascadeColorEnabled)
{
m_bCascadeColorEnabled = cascadeColorEnabled;
}
bool CCLabelBMFont::isCascadeOpacityEnabled()
{
return false;
}
void CCLabelBMFont::setCascadeOpacityEnabled(bool cascadeOpacityEnabled)
{
m_bCascadeOpacityEnabled = cascadeOpacityEnabled;
}
// LabelBMFont - AnchorPoint
void CCLabelBMFont::setAnchorPoint(const CCPoint& point)
{
if( ! point.equals(m_obAnchorPoint))
{
CCSpriteBatchNode::setAnchorPoint(point);
updateLabel();
}
}
// LabelBMFont - Alignment
void CCLabelBMFont::updateLabel()
{
this->setString(m_sInitialString, false);
if (m_fWidth > 0)
{
// Step 1: Make multiline
vector<unsigned short> str_whole = cc_utf16_vec_from_utf16_str(m_sString);
unsigned int stringLength = str_whole.size();
vector<unsigned short> multiline_string;
multiline_string.reserve( stringLength );
vector<unsigned short> last_word;
last_word.reserve( stringLength );
unsigned int line = 1, i = 0;
bool start_line = false, start_word = false;
float startOfLine = -1, startOfWord = -1;
int skip = 0;
CCArray* children = getChildren();
for (unsigned int j = 0; j < children->count(); j++)
{
CCSprite* characterSprite;
unsigned int justSkipped = 0;
while (!(characterSprite = (CCSprite*)this->getChildByTag(j + skip + justSkipped)))
{
justSkipped++;
}
skip += justSkipped;
if (!characterSprite->isVisible())
continue;
if (i >= stringLength)
break;
unsigned short character = str_whole[i];
if (!start_word)
{
startOfWord = getLetterPosXLeft( characterSprite );
start_word = true;
}
if (!start_line)
{
startOfLine = startOfWord;
start_line = true;
}
// Newline.
if (character == '\n')
{
cc_utf8_trim_ws(&last_word);
last_word.push_back('\n');
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear();
start_word = false;
start_line = false;
startOfWord = -1;
startOfLine = -1;
i+=justSkipped;
line++;
if (i >= stringLength)
break;
character = str_whole[i];
if (!startOfWord)
{
startOfWord = getLetterPosXLeft( characterSprite );
start_word = true;
}
if (!startOfLine)
{
startOfLine = startOfWord;
start_line = true;
}
}
// Whitespace.
if (isspace_unicode(character))
{
last_word.push_back(character);
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear();
start_word = false;
startOfWord = -1;
i++;
continue;
}
// Out of bounds.
if ( getLetterPosXRight( characterSprite ) - startOfLine > m_fWidth )
{
if (!m_bLineBreakWithoutSpaces)
{
last_word.push_back(character);
int found = cc_utf8_find_last_not_char(multiline_string, ' ');
if (found != -1)
cc_utf8_trim_ws(&multiline_string);
else
multiline_string.clear();
if (multiline_string.size() > 0)
multiline_string.push_back('\n');
line++;
start_line = false;
startOfLine = -1;
i++;
}
else
{
cc_utf8_trim_ws(&last_word);
last_word.push_back('\n');
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear();
start_word = false;
start_line = false;
startOfWord = -1;
startOfLine = -1;
line++;
if (i >= stringLength)
break;
if (!startOfWord)
{
startOfWord = getLetterPosXLeft( characterSprite );
start_word = true;
}
if (!startOfLine)
{
startOfLine = startOfWord;
start_line = true;
}
j--;
}
continue;
}
else
{
// Character is normal.
last_word.push_back(character);
i++;
continue;
}
}
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
int size = multiline_string.size();
unsigned short* str_new = new unsigned short[size + 1];
for (int i = 0; i < size; ++i)
{
str_new[i] = multiline_string[i];
}
str_new[size] = '\0';
this->setString(str_new, false);
CC_SAFE_DELETE_ARRAY(str_new);
}
// Step 2: Make alignment
if (m_pAlignment != kCCTextAlignmentLeft)
{
int i = 0;
int lineNumber = 0;
int str_len = cc_wcslen(m_sString);
vector<unsigned short> last_line;
for (int ctr = 0; ctr <= str_len; ++ctr)
{
if (m_sString[ctr] == '\n' || m_sString[ctr] == 0)
{
float lineWidth = 0.0f;
unsigned int line_length = last_line.size();
// if last line is empty we must just increase lineNumber and work with next line
if (line_length == 0)
{
lineNumber++;
continue;
}
int index = i + line_length - 1 + lineNumber;
if (index < 0) continue;
CCSprite* lastChar = (CCSprite*)getChildByTag(index);
if ( lastChar == NULL )
continue;
lineWidth = lastChar->getPosition().x + lastChar->getContentSize().width/2.0f;
float shift = 0;
switch (m_pAlignment)
{
case kCCTextAlignmentCenter:
shift = getContentSize().width/2.0f - lineWidth/2.0f;
break;
case kCCTextAlignmentRight:
shift = getContentSize().width - lineWidth;
break;
default:
break;
}
if (shift != 0)
{
for (unsigned j = 0; j < line_length; j++)
{
index = i + j + lineNumber;
if (index < 0) continue;
CCSprite* characterSprite = (CCSprite*)getChildByTag(index);
characterSprite->setPosition(ccpAdd(characterSprite->getPosition(), ccp(shift, 0.0f)));
}
}
i += line_length;
lineNumber++;
last_line.clear();
continue;
}
last_line.push_back(m_sString[ctr]);
}
}
}
// LabelBMFont - Alignment
void CCLabelBMFont::setAlignment(CCTextAlignment alignment)
{
this->m_pAlignment = alignment;
updateLabel();
}
void CCLabelBMFont::setWidth(float width)
{
this->m_fWidth = width;
updateLabel();
}
void CCLabelBMFont::setLineBreakWithoutSpace( bool breakWithoutSpace )
{
m_bLineBreakWithoutSpaces = breakWithoutSpace;
updateLabel();
}
void CCLabelBMFont::setScale(float scale)
{
CCSpriteBatchNode::setScale(scale);
updateLabel();
}
void CCLabelBMFont::setScaleX(float scaleX)
{
CCSpriteBatchNode::setScaleX(scaleX);
updateLabel();
}
void CCLabelBMFont::setScaleY(float scaleY)
{
CCSpriteBatchNode::setScaleY(scaleY);
updateLabel();
}
float CCLabelBMFont::getLetterPosXLeft( CCSprite* sp )
{
return sp->getPosition().x * m_fScaleX - (sp->getContentSize().width * m_fScaleX * sp->getAnchorPoint().x);
}
float CCLabelBMFont::getLetterPosXRight( CCSprite* sp )
{
return sp->getPosition().x * m_fScaleX + (sp->getContentSize().width * m_fScaleX * sp->getAnchorPoint().x);
}
// LabelBMFont - FntFile
void CCLabelBMFont::setFntFile(const char* fntFile)
{
if (fntFile != NULL && strcmp(fntFile, m_sFntFile.c_str()) != 0 )
{
CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile);
CCAssert( newConf, "CCLabelBMFont: Impossible to create font. Please check file");
m_sFntFile = fntFile;
CC_SAFE_RETAIN(newConf);
CC_SAFE_RELEASE(m_pConfiguration);
m_pConfiguration = newConf;
this->setTexture(CCTextureCache::sharedTextureCache()->addImage(m_pConfiguration->getAtlasName()));
this->createFontChars();
}
}
const char* CCLabelBMFont::getFntFile()
{
return m_sFntFile.c_str();
}
CCBMFontConfiguration* CCLabelBMFont::getConfiguration() const
{
return m_pConfiguration;
}
//LabelBMFont - Debug draw
#if CC_LABELBMFONT_DEBUG_DRAW
void CCLabelBMFont::draw()
{
CCSpriteBatchNode::draw();
const CCSize& s = this->getContentSize();
CCPoint vertices[4]={
ccp(0,0),ccp(s.width,0),
ccp(s.width,s.height),ccp(0,s.height),
};
ccDrawPoly(vertices, 4, true);
}
#endif // CC_LABELBMFONT_DEBUG_DRAW
NS_CC_END
| [
"secondsquare@gmail.com"
] | secondsquare@gmail.com |
15ee4885f54b4d299e34ca2591f01f9e3a5ae957 | 305e09a8d2635800d354b1f1f54e1576e4273fee | /Libs/DATASCOPE/DATASCOPE.cpp | 990c280aa203389b20bf665d5a6f07575afe74cf | [] | no_license | c2j/MecanumCar_Arduino | 737ed186624f38034dc7aba4bef06769a84341aa | ec3854c8dabda9b83c700af502d4bf0f6440f566 | refs/heads/master | 2020-07-30T05:26:28.996212 | 2019-09-22T09:15:24 | 2019-09-22T09:15:24 | 210,102,106 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,327 | cpp |
#include"DATASCOPE.h"
#include"Arduino.h"
unsigned char DataScope_OutPut_Buffer[42] = {0}; //串口发送缓冲区
DATASCOPE::DATASCOPE()
{
}
void DATASCOPE::Float2Byte(float *target,unsigned char *buf,unsigned char beg)
{
unsigned char *point;
point = (unsigned char*)target; //得到float的地址
buf[beg] = point[0];
buf[beg+1] = point[1];
buf[beg+2] = point[2];
buf[beg+3] = point[3];
}
void DATASCOPE::DataScope_Get_Channel_Data(float Data,unsigned char Channel)
{
if ( (Channel > 10) || (Channel == 0) ) return; //通道个数大于10或等于0,直接跳出,不执行函数
else
{
switch (Channel)
{
case 1: Float2Byte(&Data,DataScope_OutPut_Buffer,1); break;
case 2: Float2Byte(&Data,DataScope_OutPut_Buffer,5); break;
case 3: Float2Byte(&Data,DataScope_OutPut_Buffer,9); break;
case 4: Float2Byte(&Data,DataScope_OutPut_Buffer,13); break;
case 5: Float2Byte(&Data,DataScope_OutPut_Buffer,17); break;
case 6: Float2Byte(&Data,DataScope_OutPut_Buffer,21); break;
case 7: Float2Byte(&Data,DataScope_OutPut_Buffer,25); break;
case 8: Float2Byte(&Data,DataScope_OutPut_Buffer,29); break;
case 9: Float2Byte(&Data,DataScope_OutPut_Buffer,33); break;
case 10: Float2Byte(&Data,DataScope_OutPut_Buffer,37); break;
}
}
}
unsigned char DATASCOPE::DataScope_Data_Generate(unsigned char Channel_Number)
{
if ( (Channel_Number > 10) || (Channel_Number == 0) ) { return 0; } //通道个数大于10或等于0,直接跳出,不执行函数
else
{
DataScope_OutPut_Buffer[0] = '$'; //帧头
switch(Channel_Number)
{
case 1: DataScope_OutPut_Buffer[5] = 5; return 6;
case 2: DataScope_OutPut_Buffer[9] = 9; return 10;
case 3: DataScope_OutPut_Buffer[13] = 13; return 14;
case 4: DataScope_OutPut_Buffer[17] = 17; return 18;
case 5: DataScope_OutPut_Buffer[21] = 21; return 22;
case 6: DataScope_OutPut_Buffer[25] = 25; return 26;
case 7: DataScope_OutPut_Buffer[29] = 29; return 30;
case 8: DataScope_OutPut_Buffer[33] = 33; return 34;
case 9: DataScope_OutPut_Buffer[37] = 37; return 38;
case 10: DataScope_OutPut_Buffer[41] = 41; return 42;
}
}
return 0;
}
| [
"chenjj.yz@gmail.com"
] | chenjj.yz@gmail.com |
4ef165184794507ad6ddf7e06b6871f489ee22a9 | b73da634aa065480862abcaf59b80c73364eb5f8 | /pluginonf/step/onf_stepcreateplotmanagerfromfile.h | 43a51a3a2dfcd345cd6dbe7a5a8f6de07c860201 | [] | no_license | computree/computree-plugin-onf | 066f4c0003d34f291b0e1e17f3f88be9aa96d39b | 925b37ee9a324fb6a4f0cfaaed02920a36842ec6 | refs/heads/master | 2020-12-30T13:47:14.266251 | 2017-03-27T14:06:27 | 2017-03-27T14:06:27 | 91,260,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,953 | h | /****************************************************************************
Copyright (C) 2010-2012 the Office National des Forêts (ONF), France
All rights reserved.
Contact : alexandre.piboule@onf.fr
Developers : Alexandre PIBOULE (ONF)
This file is part of PluginONF library.
PluginONF is free library: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PluginONF is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with PluginONF. If not, see <http://www.gnu.org/licenses/lgpl.html>.
*****************************************************************************/
#ifndef ONF_STEPCREATEPLOTMANAGERFROMFILE_H
#define ONF_STEPCREATEPLOTMANAGERFROMFILE_H
#include "ct_step/abstract/ct_abstractstep.h"
class ONF_StepCreatePlotManagerFromFile: public CT_AbstractStep
{
Q_OBJECT
public:
/*! \brief Step constructor
*
* Create a new instance of the step
*
* \param dataInit Step parameters object
*/
ONF_StepCreatePlotManagerFromFile(CT_StepInitializeData &dataInit);
/*! \brief Step description
*
* Return a description of the step function
*/
QString getStepDescription() const;
/*! \brief Step detailled description
*
* Return a detailled description of the step function
*/
QString getStepDetailledDescription() const;
/*! \brief Step URL
*
* Return a URL of a wiki for this step
*/
QString getStepURL() const;
/*! \brief Step copy
*
* Step copy, used when a step is added by step contextual menu
*/
CT_VirtualAbstractStep* createNewInstance(CT_StepInitializeData &dataInit);
protected:
/*! \brief Input results specification
*
* Specification of input results models needed by the step (IN)
*/
void createInResultModelListProtected();
/*! \brief Parameters DialogBox
*
* DialogBox asking for step parameters
*/
void createPostConfigurationDialog();
/*! \brief Output results specification
*
* Specification of output results models created by the step (OUT)
*/
void createOutResultModelListProtected();
/*! \brief Algorithm of the step
*
* Step computation, using input results, and creating output results
*/
void compute();
private:
// Step parameters
QStringList _fileName;
};
#endif // ONF_STEPCREATEPLOTMANAGERFROMFILE_H
| [
"alexandre.piboule@onf.fr"
] | alexandre.piboule@onf.fr |
3f997913547fb1ec4ef91eb568d2cebaf36bd3b0 | cfa3070448f81ee6b028d98374b245186e6999e9 | /include/StatisticalDistributionsLib/ChiSquared.h | 240ccf0d4a3bc3f06ea76d1664d1fb3fc3e36b1a | [] | no_license | yaesoubilab/StatisticalDistributionsLib | 8c619bcfe8464471a05710fec753ffca53bca692 | ccd9962aadffb02defd0a853f4c849a63df53f8c | refs/heads/master | 2022-01-27T04:28:40.527884 | 2019-04-29T19:39:48 | 2019-04-29T19:39:48 | 88,905,422 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 266 | h | #pragma once
#include "Gamma.h"
namespace StatisticalDistributions {
class ChiSquared : public Gamma {
public:
// This needs no explanation, I hope.
inline ChiSquared(long double dof = 1) {
init(dof);
}
void init(long double = 1);
};
}
| [
"eyjmfc@gmail.com"
] | eyjmfc@gmail.com |
733a8d05bde64f7e3c9d0f22932d3c7e22ddd431 | 8fad12bca03f32f141b70cafbc4a3516812c1541 | /Angel.cpp | 6c30e7cfdc11002fbf57ec783e7391d1a3bb17a5 | [] | no_license | CommanderMoo/Supernatural-Experience | 88e4e624f333576eb15b05d665dab2fba89b1f73 | bfebb1f110968dd59e66d427452dfe52943ded0f | refs/heads/master | 2022-04-19T23:46:42.241452 | 2020-04-20T06:26:15 | 2020-04-20T06:26:15 | 257,190,967 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | cpp | #include "Angel.h"
#include <iostream>
Angel::Angel()
{
setName("");
}
Angel::Angel(string userName)
{
cin >> userName;
}
void Angel::setName(string userName)
{
}
string Angel::getName()
{
return string();
}
| [
"RUSPICKN@uat.edu"
] | RUSPICKN@uat.edu |
e08c04155242f8976dbd867cc4faf4b3c078d559 | 26ef7f7b92e9df07a7e1f13e8dd4337f7fb46198 | /Oop_Assignment/Task3.cpp | 12ad5dd5c1c2894a04395a6f7df10175e8c0a9f8 | [] | no_license | yousaf2018/2nd_semester_Oop | 7ce3ca429fc202ef1b285aeb5533886dd75483d2 | 118359efe0a48735af7414565015604e848983c6 | refs/heads/master | 2020-05-13T22:18:06.400896 | 2019-05-01T17:12:43 | 2019-05-01T17:12:43 | 181,667,234 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,052 | cpp | #include <iostream>
using namespace std;
class Date
{
private:
int day;
int month;
int year;
public:
void initialize_values();
void set_values();
void display_values();
void Validity();
Date operator+(Date a);
};
Date Date::operator+(Date a)
{
Date b;
int total_days_1;
int total_days_2;
total_days_1=day+month*30+year*365;
total_days_2=a.day+a.month*30+a.year*365;
if(total_days_1>total_days_2){
cout << "First input was older\n";
}
else
{
cout << "Second input was older\n";
}
}
void Date::initialize_values()
{
int day=0;
int month=0;
int year=0;
}
void Date::set_values()
{
cout << "Enter day\n";
cin >> day;
cout << "Enter month like 1 to 12\n";
cin >> month;
cout << "Enter years like 1800 to 2019\n";
cin >> year;
}
void Date::Validity()
{
if(year<1800||year>2019)
{
cout << "Year is not valid enter from 1800 to 2019\n";
set_values();
}
else if(month<1||month>12)
{
cout << "Month in not valid so enter it from 1 to 12\n";
set_values();
}
else if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
{
if(day>31||day<1)
{
cout << "Enter valid days because this month is 31\n";
set_values();
}
}
else if(month==2)
{
if(day<1||day>28)
{
cout << "Enter valid days this month is 28 or 29 in case Leap year\n";
set_values();
}
}
else if(month==4||month==6||month==9||month==11)
{
if(day<1||day>30)
{
cout << "Enter valid days this month is 30\n";
set_values();
}
}
}
void Date::display_values()
{
cout << "************************************\n";
cout << "Date:" << day << "/" << month << "/" << year <<endl;
cout << "************************************\n";
}
int main()
{
Date object1,object2,object3;
object1.initialize_values();
object1.set_values();
object1.Validity();
object1.display_values();
object2.initialize_values();
object2.set_values();
object2.Validity();
object2.display_values();
object3=object1+object2;
return(0);
}
| [
"mahmoodyousaf975974@gmail.com"
] | mahmoodyousaf975974@gmail.com |
4127538c5bae089e775ab15fbb1514e74a35e531 | 13b79d1b559ddbce2b7be0c5566b44747b2e9c2c | /core/KFile.cpp | 7bab730000426cce43a6c8c4093284d8a5468854 | [] | no_license | kazikikaziki/misc | 604a4a38d4388d4a2ec4a0eb30b4f04cefa46b3d | 7329b8cbd656e0a9eb6a174963931f79d1da3ba1 | refs/heads/master | 2020-06-12T04:40:41.409996 | 2019-07-24T15:33:33 | 2019-07-24T15:33:33 | 194,196,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,350 | cpp | #include "KFile.h"
#include "KPath.h"
#if 1
#include "KLog.h"
#include "KStd.h"
#define FILEASSERT(expr) Log_assert(expr)
#define FILELOG(fmt, ...) Log_verbosef(fmt, ##__VA_ARGS__)
#define FILEOPEN_U8(f, m) K_fopen_u8(f, m)
#else
#include <assert.h>
#define FILEASSERT(expr) assert(expr)
#define FILELOG(fmt, ...) printf(fmt, ##__VA_ARGS__), putchar('\n')
#define FILEOPEN_U8(f, m) fopen(f, m)
#endif
namespace mo {
namespace {
class CNativeOutput: public FileOutputCallback {
Path name_;
FILE *cb_;
bool auto_close_;
public:
CNativeOutput(FILE *fp, const Path &name, bool auto_close) {
cb_ = fp;
name_ = name;
auto_close_ = auto_close;
}
virtual ~CNativeOutput() override {
if (auto_close_) fclose(cb_);
}
virtual int on_file_tell() const override {
return (int)ftell(cb_);
}
virtual void on_file_seek(int pos) override {
fseek(cb_, pos, SEEK_SET);
}
virtual int on_file_write(const void *buf, int bytes) override {
int ret = bytes;
if (buf) {
ret = (int)fwrite(buf, 1, bytes, cb_);
} else {
fseek(cb_, bytes, SEEK_CUR);
}
fflush(cb_);
return ret;
}
};
class CNativeInput: public FileInputCallback {
FILE *cb_;
int size_;
bool auto_close_;
public:
CNativeInput(FILE *fp, bool auto_close) {
FILEASSERT(fp);
cb_ = fp;
auto_close_ = auto_close;
int init = ftell(fp);
fseek(fp, 0, SEEK_SET);
int head = ftell(fp);
fseek(fp, 0, SEEK_END);
int tail = ftell(fp);
fseek(fp, init, SEEK_SET);
FILEASSERT(tail >= head);
size_ = tail - head;
}
virtual ~CNativeInput() override {
if (auto_close_) fclose(cb_);
}
virtual int on_file_size() const override {
return size_;
}
virtual int on_file_read(void *buf, int bytes) override {
if (buf) {
return (int)fread(buf, 1, bytes, cb_);
} else {
fseek(cb_, bytes, SEEK_CUR);
return bytes;
}
}
virtual int on_file_seek(int bytes) override {
fseek(cb_, bytes, SEEK_SET);
return ftell(cb_);
}
virtual int on_file_tell() const override {
return (int)ftell(cb_);
}
};
class CStaticMemoryInput: public FileInputCallback {
uint8_t *buf_;
int size_;
int pos_;
public:
CStaticMemoryInput(const void *data, int size) {
// data == NULL はダメ
// size == 0 は OK
FILEASSERT(data);
pos_ = 0;
buf_ = (uint8_t *)data;
size_ = size;
}
virtual int on_file_size() const override {
return size_;
}
virtual int on_file_read(void *buf, int bytes) override {
int len = bytes;
if (size_ < pos_ + len) {
len = size_ - pos_;
}
if (len > 0) {
if (buf) memcpy(buf, buf_ + pos_, len);
pos_ += len;
return len;
}
return 0;
}
virtual int on_file_seek(int new_pos) override {
if (new_pos < 0) {
pos_ = 0;
} else if (new_pos >= size_) {
pos_ = size_;
} else {
pos_ = new_pos;
}
return pos_;
}
virtual int on_file_tell() const override {
FILEASSERT(0 <= pos_ && pos_ <= size_);
return pos_;
}
};
class CMemoryInput: public FileInputCallback {
CStaticMemoryInput *static_reader_;
std::string buf_;
public:
CMemoryInput(const void *data, int size) {
static_reader_ = NULL;
if (size > 0) {
buf_.resize(size);
buf_.assign((const char*)data, size);
static_reader_ = new CStaticMemoryInput(buf_.data(), size);
} else {
static_reader_ = new CStaticMemoryInput(NULL, 0);
}
}
virtual ~CMemoryInput() {
delete static_reader_;
}
virtual int on_file_size() const override {
return static_reader_->on_file_size();
}
virtual int on_file_read(void *buf, int bytes) override {
return static_reader_->on_file_read(buf, bytes);
}
virtual int on_file_seek(int new_pos) override {
return static_reader_->on_file_seek(new_pos);
}
virtual int on_file_tell() const override {
return static_reader_->on_file_tell();
}
};
class CMemoryOutput: public FileOutputCallback {
public:
std::string *buf_;
int start_;
int pos_;
explicit CMemoryOutput(std::string *buf) {
FILEASSERT(buf);
buf_ = buf;
start_ = buf_->size();
pos_ = 0;
}
virtual int on_file_write(const void *buf, int bytes) override {
FILEASSERT(bytes >= 0);
size_t cur = start_ + pos_;
if (cur + bytes > buf_->size()) {
buf_->resize(cur + bytes);
}
memcpy((void *)(buf_->c_str() + cur), buf, bytes);
pos_ += bytes;
return bytes;
}
virtual int on_file_tell() const override {
return pos_;
}
virtual void on_file_seek(int pos) override {
if (pos >= 0) {
pos_ = pos;
} else {
pos_ = 0;
}
}
};
} // private
#pragma region FileOutput
FileOutput::FileOutput() {
cb_ = NULL;
}
FileOutput::FileOutput(const FileOutput &other) {
cb_ = other.cb_;
}
FileOutput::FileOutput(const Path &filename, bool append) {
cb_ = NULL;
open(Path(filename));
}
FileOutput::~FileOutput() {
close();
}
bool FileOutput::open(FileOutputCallback *cb) {
close();
if (cb) {
cb_ = std::shared_ptr<FileOutputCallback>(cb);
return true;
}
return false;
}
bool FileOutput::open(std::string &output) {
close();
cb_ = std::make_shared<CMemoryOutput>(&output);
return true;
}
bool FileOutput::open(const Path &filename, bool append) {
close();
FILE *fp = FILEOPEN_U8(filename.u8(), append ? "ab" : "wb");
if (fp) {
cb_ = std::make_shared<CNativeOutput>(fp, filename, true);
FILELOG("FileOutput::open %s", filename.u8());
return true;
}
FILELOG("FileOutput::open %s [FAIELD!!]", filename.u8());
return false;
}
void FileOutput::close() {
cb_ = NULL;
}
bool FileOutput::isOpen() const {
return !empty();
}
bool FileOutput::empty() const {
return cb_ == NULL;
}
FileOutput & FileOutput::operator = (const FileOutput &other) {
cb_ = other.cb_;
return *this;
}
int FileOutput::tell() const {
return cb_ ? cb_->on_file_tell() : 0;
}
void FileOutput::write(const void *data, int size) {
if (cb_) cb_->on_file_write(data, size);
}
void FileOutput::write(const std::string &bin) {
write(bin.data(), bin.size());
}
void FileOutput::writeUint8(uint8_t value) {
write(&value, sizeof(value));
}
void FileOutput::writeUint16(uint16_t value) {
write(&value, sizeof(value));
}
void FileOutput::writeUint32(uint32_t value) {
write(&value, sizeof(value));
}
#pragma endregion // FileOutput
#pragma region FileInput
FileInput::FileInput() {
cb_ = NULL;
eof_ = false;
}
FileInput::FileInput(const FileInput &other) {
cb_ = other.cb_;
eof_ = other.eof_;
}
FileInput::FileInput(const Path &filename) {
cb_ = NULL;
eof_ = false;
open(filename);
}
FileInput::~FileInput() {
close();
}
bool FileInput::open(FileInputCallback *cb) {
close();
//
if (cb) {
cb_ = std::shared_ptr<FileInputCallback>(cb);
eof_ = false;
return true;
}
return false;
}
bool FileInput::open(const void *data, int size, bool copy) {
close();
//
if (data && size > 0) {
if (copy) {
cb_ = std::make_shared<CMemoryInput>(data, size);
} else {
cb_ = std::make_shared<CStaticMemoryInput>(data, size);
}
eof_ = false;
return true;
}
return false;
}
bool FileInput::open(const Path &filename) {
close();
//
FILE *fp = FILEOPEN_U8(filename.u8(), "rb");
if (fp) {
cb_ = std::make_shared<CNativeInput>(fp, true);
eof_ = feof(fp);
FILELOG("FileInput::open %s", filename.u8());
return true;
}
FILELOG("FileInput::open %s [FAIELD!!]", filename.u8());
return false;
}
FileInput & FileInput::operator = (const FileInput &other) {
cb_ = other.cb_;
eof_ = other.eof_;
return *this;
}
bool FileInput::empty() const {
return cb_ == NULL;
}
bool FileInput::isOpen() const {
return !empty();
}
void FileInput::close() {
cb_ = NULL;
eof_ = true;
}
int FileInput::size() const {
return cb_ ? cb_->on_file_size() : 0;
}
int FileInput::tell() const {
return cb_ ? cb_->on_file_tell() : 0;
}
void FileInput::seek(int pos) {
if (cb_) {
cb_->on_file_seek(pos);
}
}
int FileInput::read(void *data, int size) {
int rsize = 0;
if (cb_) {
rsize = cb_->on_file_read(data, size);
eof_ = rsize < size;
}
return rsize;
}
uint8_t FileInput::readUint8() {
const int size = 1;
uint8_t val = 0;
if (read(&val, size) == size) {
return val;
}
return 0;
}
uint16_t FileInput::readUint16() {
const int size = 2;
uint16_t val = 0;
if (read(&val, size) == size) {
return val;
}
return 0;
}
uint32_t FileInput::readUint32() {
const int size = 4;
uint32_t val = 0;
if (read(&val, size) == size) {
return val;
}
return 0;
}
std::string FileInput::readBin(int size) {
std::string bin(size, '\0');
int sz = read((void*)bin.data(), bin.size());
bin.resize(sz);
return bin;
}
std::string FileInput::readBin() {
std::string bin;
if (cb_) {
int restsize = size() - tell();
if (restsize > 0) {
bin.resize(restsize);
int readsize = read(&bin[0], bin.size());
if (readsize < (int)bin.size()) {
bin.resize(readsize);
}
}
}
return bin;
}
#pragma endregion // FileInput
void Test_file() {
FileInput file;
FILEASSERT(file.empty());
FILEASSERT(!file.isOpen());
FileOutput o;
o.open("~test.bin");
FILEASSERT(o.isOpen());
o.writeUint32(0xAABBCCDD);
FileOutput o2 = o;
FILEASSERT(o2.isOpen());
o2.close();
FileInput i;
i.open("~test.bin");
FILEASSERT(i.tell() == 0);
FILEASSERT(i.readUint32() == 0xAABBCCDD);
FILEASSERT(i.tell() == 4);
i.seek(0);
FILEASSERT(i.tell() == 0);
FILEASSERT(i.readUint32() == 0xAABBCCDD);
FILEASSERT(i.tell() == 4);
i.seek(0);
i.seek(i.tell() + 2);
FILEASSERT(i.readUint8() == 0xBB);
FILEASSERT(i.readUint8() == 0xAA);
}
} // namespace
| [
"doveilbagno@gmail.com"
] | doveilbagno@gmail.com |
1ff26ea957d1947f63f82f1f24101f898a19a4ad | a4c45cc2ce9fc90e0ba27f647136b3a69ce0bf09 | /problems/water-and-jug-problem/SOLUTION.cpp | 86f8980f57ae48184b5124c250ea884fef0639b1 | [] | no_license | AhJo53589/leetcode-cn | fd8cb65a2d86f25d2e32553f6b32dbfc9cb7bae7 | 7acba71548c41e276003682833e04b8fab8bc8f8 | refs/heads/master | 2023-01-29T19:35:13.816866 | 2023-01-15T03:21:37 | 2023-01-15T03:21:37 | 182,630,154 | 268 | 47 | null | null | null | null | UTF-8 | C++ | false | false | 867 | cpp | //#include <numeric> // c++ 17
//////////////////////////////////////////////////////////////////////////
class Solution {
public:
bool canMeasureWater(int x, int y, int z) {
if (x + y < z) return false;
if (x == 0 || y == 0) return z == 0 || x + y == z;
return z % gcd(x, y) == 0;
}
};
//////////////////////////////////////////////////////////////////////////
bool _solution_run(int x, int y, int z)
{
//int caseNo = -1;
//static int caseCnt = 0;
//if (caseNo != -1 && caseCnt++ != caseNo) return {};
Solution sln;
return sln.canMeasureWater(x, y, z);
}
//#define USE_SOLUTION_CUSTOM
//string _solution_custom(TestCases &tc)
//{
// return {};
//}
//////////////////////////////////////////////////////////////////////////
//#define USE_GET_TEST_CASES_IN_CPP
//vector<string> _get_test_cases_string()
//{
// return {};
//}
| [
"ahjo_bb@hotmail.com"
] | ahjo_bb@hotmail.com |
a543ec536980c6010d948418362badd7c56bdf41 | 8fda0131adae63e21a825c1bdc4fd6b110fcaa10 | /srctree/src/splineMath.cpp | f38fca91da13a54fd9b58037baf8852c7dbf4090 | [] | no_license | vsnchips/skeleton-animation-editor | fa3b37f000498162dc45139ed06762837a92d167 | 1f1a1a935e5a4ed389337a271a5b369f604b88cf | refs/heads/master | 2020-04-07T04:54:59.229915 | 2018-11-18T12:05:43 | 2018-11-18T12:05:43 | 158,077,019 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | cpp | #pragma once
#include "splineMath.hpp"
using namespace glm;
using namespace std;
typedef std::vector<glm::quat> quatSpline;
glm::quat qSpline( float t, quatSpline & spline){
//iterative decasteljau
quatSpline temp = spline;
int i = temp.size()-1;
while( i>0){
for (int j = 0; j < i; j++){
temp[j] = slerp( temp[j], temp[j+1], t);
} i--;
}
return temp[0];
}
vec2 splineSamp2D( float t, vector<vec2> spline){
vector<vec2> tempSpline(spline);
int i = tempSpline.size()-1;
while (i>0){
for (int j=0; j<i; j++){
tempSpline[j] = mix( tempSpline[j] , tempSpline[j+1], t);
} i--;
}
return vec2(tempSpline[0]);
}
vec2 catSamp2D ( float t, vector<vec2> & cats){
return catSamp2D (t, cats, 0.25);
}
vec2 catSamp2D ( float t, vector<vec2> & cats, float bend){
vec2 p = vec2(0);
vector<vec2> spline; spline.clear();
if (cats.size()<1) return p;
else if(cats.size()<3) return cats[0];
else if(cats.size()<4) return cats[1];
else{
vec2 a,ta,tb,b;
float seg;
t = modf(t, &seg);
seg = glm::min(float(seg), float (cats.size()-4));
seg = glm::max( seg, 0.f);
//point A
spline.push_back(
cats[seg+1]
);
//tan A
spline.push_back(
cats[seg+1] + bend*(cats[seg+2] - cats[seg])
);
//tan B
spline.push_back(
cats[seg+2] + bend*(cats[seg+1] - cats[seg+3])
);
//point b
spline.push_back( cats[seg+2] );
}
return splineSamp2D(t, spline);
}
| [
"tonupkiwi@gmail.com"
] | tonupkiwi@gmail.com |
d1396ef56e98c80184d0cc808f67591446d80633 | 400f1bc2292b0e1fcb9cdd1825815a564fec6043 | /Array/Array/Array.cpp | d3df9b4a0ad74f04ac05b42eeb94d1afbf784853 | [] | no_license | murnat98/technotrack | 0b342a8b4fc515e0f76eda8e1ce9182788c30621 | dcbadd5be16ae8adaaa4d3097ffbc14715c5d683 | refs/heads/master | 2020-05-21T08:49:37.369043 | 2017-03-06T14:32:08 | 2017-03-06T14:32:08 | 70,189,615 | 0 | 0 | null | 2016-10-23T16:30:23 | 2016-10-06T20:16:48 | C++ | UTF-8 | C++ | false | false | 2,128 | cpp | #include "Array.hpp"
Array::Array()
{
capacity_ = 0;
count_ = 0;
array_ = nullptr;
allocated_ = false;
}
Array::Array(int size)
{
capacity_ = size;
count_ = 0;
array_ = new int[size];
allocated_ = true;
}
Array::Array(Array& array)
{
assert(&array);
capacity_ = array.capacity_;
array_ = new int[capacity_];
allocated_ = true;
count_ = 0;
}
Array::~Array()
{
if (allocated_ == true)
{
delete[] array_;
array_ = nullptr;
allocated_ = false;
count_ = COUNT_POISON;
capacity_ = CAPACITY_POISON;
}
std::cout << "destruktor" << std::endl;
}
bool Array::ok() const
{
if (capacity_ > 0)
{
return count_ < capacity_ &&
allocated_ == true &&
array_ != nullptr;
}
else
{
return !capacity_ &&
!count_ &&
allocated_ == false &&
array_ == nullptr;
}
}
int Array::dump(const std::string varName) const
{
std::string okText;
if (ok())
okText = "ok";
else
{
okText = "ERROR";
assert(this);
assert(array_);
}
std::ofstream dump("array.dump", std::ofstream::app);
dump << "Array \"" << varName << "\" (" << okText << ") [" << &(*this) << "]\n";
dump << "{\n\tarray_[" << capacity_ << "] = [" << array_ << "]\n";
dump << "\t{\n";
for (int i = 0; i < capacity_; i++)
{
if (i < count_)
{
dump << "\t\t*[" << i << "] = " << array_[i] << "\n";
}
else
{
dump << "\t\t[" << i << "] = " << array_[i] << " Poison!\n";
}
}
dump << "\t}\n\tcount_ = " << count_ << "\n";
dump << "\tcapacity_ = " << capacity_ << "\n";
dump << "}\n";
dump.close();
return 0;
}
void Array::resize(int size)
{
if (size > capacity_)
{
array_ = (int *)realloc(array_, sizeof(array_) * size);
capacity_ = size;
allocated_ = true;
}
}
| [
"murnat98@yandex.ru"
] | murnat98@yandex.ru |
6e753b4ad1260adbeacd38f770312cd6c950f6a7 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_repos_function_1260_httpd-2.3.8.cpp | 0bf7dd26833d4040292b71d00c9a6b772a2c5562 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,563 | cpp | static int fixup_redir(request_rec *r)
{
void *dconf = r->per_dir_config;
alias_dir_conf *dirconf =
(alias_dir_conf *) ap_get_module_config(dconf, &alias_module);
char *ret;
int status;
/* It may have changed since last time, so try again */
if ((ret = try_alias_list(r, dirconf->redirects, 1, &status)) != NULL) {
if (ap_is_HTTP_REDIRECT(status)) {
if (ret[0] == '/') {
char *orig_target = ret;
ret = ap_construct_url(r->pool, ret, r);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"incomplete redirection target of '%s' for "
"URI '%s' modified to '%s'",
orig_target, r->uri, ret);
}
if (!ap_is_url(ret)) {
status = HTTP_INTERNAL_SERVER_ERROR;
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
"cannot redirect '%s' to '%s'; "
"target is not a valid absoluteURI or abs_path",
r->uri, ret);
}
else {
/* append requested query only, if the config didn't
* supply its own.
*/
if (r->args && !ap_strchr(ret, '?')) {
ret = apr_pstrcat(r->pool, ret, "?", r->args, NULL);
}
apr_table_setn(r->headers_out, "Location", ret);
}
}
return status;
}
return DECLINED;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
d7197cbd9db3eb4a91fe85cf4af51e36fe425e61 | fd11a396253f166add68b5471ff1aadfd6175c41 | /src/utilities/cli-cpp-config-generator/cli-cpp-config-generator.cpp | f6111a59d78fe5969910cec20501c02f0eec42e6 | [
"MIT"
] | permissive | Tubbz-alt/cli-cpp | 9daae1f2d910ea1691c1f66f0a952de02071e39a | 4f98a09d5cfeffe0d5c330cda3272ae207c511d1 | refs/heads/master | 2021-09-15T12:42:25.029386 | 2018-06-01T17:40:12 | 2018-06-01T17:40:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,348 | cpp | /**
* @file cli-cpp-config-generator.cpp
* @author Marvin Smith
* @date 7/5/2015
*/
// CLI-C++ Libraries
#include <cli_cpp.hpp>
// C++ Standard Libraries
#include <cstdlib>
#include <deque>
#include <iostream>
#include <string>
/**
* @brief Configuration Options
*/
class Options{
public:
/**
* @brief Constructor
*/
Options()
: m_config_pathname_set(false)
{
}
/**
* @brief Get the Configuration Pathname
*/
std::string Get_Config_Pathname()const{
return m_config_pathname;
}
/**
* @brief Set the Configuration Pathname.
*/
void Set_Config_Pathname( const std::string& config_pathname )
{
m_config_pathname_set = true;
m_config_pathname = config_pathname;
}
/**
* @brief Check if the Configuration Path is set.
*/
bool Config_Pathname_Set()const{
return m_config_pathname_set;
}
private:
/// Configuration Pathname.
std::string m_config_pathname;
/// Config Pathname set
bool m_config_pathname_set;
}; // End of Options Class
/**
* @brief Parse the Command-Line
*
* @param[in] argc Number of command arguments.
* @param[in] argv List of command arguments.
*/
Options Parse_Command_Line( int argc, char* argv[] );
/**
* @brief Print the Usage Instructions
*
* @param[in] application_name
*/
void Usage( std::string const& application_name );
/**
* @brief Main Driver
*/
int main( int argc, char* argv[] )
{
// Parse Command-Line
Options options = Parse_Command_Line( argc, argv );
// Grab the configuration pathname
std::string config_pathname = options.Get_Config_Pathname();
// Parse configuration options
CLI::IO::CONFIG::A_CLI_Configuration_File_Parser parser( config_pathname );
// Write the configuration file
parser.Write();
// exit
return 0;
}
/*************************************/
/* Parse the Command-Line */
/*************************************/
Options Parse_Command_Line( int argc, char* argv[] )
{
// Grab the application name
std::string application_name = argv[0];
// Create list
std::deque<std::string> args;
for( int i=1; i<argc; i++ ){
args.push_back(argv[i]);
}
// Output options
Options options;
std::string arg;
// Prune list
while( args.size() > 0 ){
// Get the next argument
arg = args[0];
args.pop_front();
// Check if help requested
if( arg == "-h" ||
arg == "--help" )
{
Usage( application_name );
std::exit(0);
}
// Otherwise, grab the pathname
else{
if( options.Config_Pathname_Set() == true ){
std::cerr << "error: Configuration pathname already set. Unknown argument." << std::endl;
Usage(application_name);
std::exit(1);
}
options.Set_Config_Pathname(arg);
}
}
// Make sure the config pathname was set.
if( options.Config_Pathname_Set() == false ){
std::cerr << "error: No configuration pathname set." << std::endl;
Usage( application_name );
std::exit(1);
}
// Return output
return options;
}
/***************************************/
/* Print Usage Instructions */
/***************************************/
void Usage( const std::string& application_name )
{
// Print the command
std::cout << "usage: " << application_name << " [options] <config-path>" << std::endl;
std::cout << std::endl;
// Print the options
std::cout << "Options:" << std::endl;
std::cout << " -h | --help : Print usage instructions and exit." << std::endl;
std::cout << std::endl;
// Print the remaining options
std::cout << "Required Items: " << std::endl;
std::cout << " config-path : Path to the xml configuration file. If one does not exist," << std::endl;
std::cout << " then it will be created. If it does exist, it will be " << std::endl;
std::cout << " updated with any missing parameters." << std::endl;
std::cout << std::endl;
}
| [
"marvin_smith1@me.com"
] | marvin_smith1@me.com |
d7b59ae5b50d368c01e30aa998d76ec5f8b8a7f0 | c1c1a4de2c3e815dac6f4d5536304e8c8143c023 | /BattleTank/Source/BattleTank/Tank.h | 3f01a2d348e0038a8fb7f153e372ea3919a540f3 | [] | no_license | JVCounsell/UnrealCourse_BattleTank | f1fe60295ff9ed3b39bd0126ce2b0369a60f1326 | 433806996c5f5aa1640b97430bac73d59da2a623 | refs/heads/master | 2021-01-13T14:37:57.553104 | 2017-02-15T17:47:06 | 2017-02-15T17:47:06 | 76,752,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,012 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Pawn.h"
#include "Tank.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FTankDelegate);
UCLASS()
class BATTLETANK_API ATank : public APawn
{
GENERATED_BODY()
public:
virtual float TakeDamage(float DamageAmount, struct FDamageEvent const & DamageEvent, class AController * EventInstigator, AActor * DamageCauser) override;
UFUNCTION(BlueprintPure, Category = "Health")
float GetHealthPercent() const;
UPROPERTY()
FTankDelegate OnDeath;
private:
// Sets default values for this pawn's properties
ATank();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* InputComponent) override;
UPROPERTY(EditDefaultsOnly, Category = "Setup")
int32 StartingHealth = 100;
UPROPERTY(VisibleAnywhere, Category = "Health")
int32 CurrentHealth;
};
| [
"jeremycounsell@gmail.com"
] | jeremycounsell@gmail.com |
0078058a1067b1bfdd842e4e3ab103652d00347a | ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c | /out/release/gen/third_party/blink/renderer/bindings/core/v8/v8_big_uint_64_array.cc | 244a0d8527f01401ebfdf5c754e9acd30c2d2b40 | [
"BSD-3-Clause"
] | permissive | xueqiya/chromium_src | 5d20b4d3a2a0251c063a7fb9952195cda6d29e34 | d4aa7a8f0e07cfaa448fcad8c12b29242a615103 | refs/heads/main | 2022-07-30T03:15:14.818330 | 2021-01-16T16:47:22 | 2021-01-16T16:47:22 | 330,115,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,960 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/interface.cc.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/core/v8/v8_big_uint_64_array.h"
#include <algorithm>
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_array_buffer.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_shared_array_buffer.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h"
#include "third_party/blink/renderer/platform/scheduler/public/cooperative_scheduling_manager.h"
#include "third_party/blink/renderer/platform/wtf/get_ptr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo v8_big_uint_64_array_wrapper_type_info = {
gin::kEmbedderBlink,
nullptr,
nullptr,
"BigUint64Array",
V8ArrayBufferView::GetWrapperTypeInfo(),
WrapperTypeInfo::kWrapperTypeObjectPrototype,
WrapperTypeInfo::kObjectClassId,
WrapperTypeInfo::kNotInheritFromActiveScriptWrappable,
};
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic pop
#endif
// not [ActiveScriptWrappable]
static_assert(
!std::is_base_of<ActiveScriptWrappableBase, DOMBigUint64Array>::value,
"DOMBigUint64Array inherits from ActiveScriptWrappable<>, but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
static_assert(
std::is_same<decltype(&DOMBigUint64Array::HasPendingActivity),
decltype(&ScriptWrappable::HasPendingActivity)>::value,
"DOMBigUint64Array is overriding hasPendingActivity(), but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
DOMBigUint64Array* V8BigUint64Array::ToImpl(v8::Local<v8::Object> object) {
DCHECK(object->IsBigUint64Array());
ScriptWrappable* script_wrappable = ToScriptWrappable(object);
if (script_wrappable)
return script_wrappable->ToImpl<DOMBigUint64Array>();
v8::Local<v8::BigUint64Array> v8_view = object.As<v8::BigUint64Array>();
v8::Local<v8::Object> array_buffer = v8_view->Buffer();
DOMBigUint64Array* typed_array = nullptr;
if (array_buffer->IsArrayBuffer()) {
typed_array = DOMBigUint64Array::Create(
V8ArrayBuffer::ToImpl(array_buffer),
v8_view->ByteOffset(),
v8_view->Length());
} else if (array_buffer->IsSharedArrayBuffer()) {
typed_array = DOMBigUint64Array::Create(
V8SharedArrayBuffer::ToImpl(array_buffer),
v8_view->ByteOffset(),
v8_view->Length());
} else {
NOTREACHED();
}
v8::Local<v8::Object> associated_wrapper =
typed_array->AssociateWithWrapper(
v8::Isolate::GetCurrent(), typed_array->GetWrapperTypeInfo(), object);
DCHECK(associated_wrapper == object);
return typed_array->ToImpl<DOMBigUint64Array>();
}
DOMBigUint64Array* V8BigUint64Array::ToImplWithTypeCheck(
v8::Isolate* isolate, v8::Local<v8::Value> value) {
return value->IsBigUint64Array() ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr;
}
} // namespace blink
| [
"xueqi@zjmedia.net"
] | xueqi@zjmedia.net |
535313faf7af8876952eb3cb61a1a246a18bec90 | 0c31ec352872dea3cb2391d59a4ccba9f4a3ac64 | /Core/Terrain/ChunkColumn.cpp | 14411ee76583f359f200b46d4706dbb1e9247665 | [
"MIT",
"LicenseRef-scancode-khronos"
] | permissive | marci07iq/SpaceCube | 501330ec5a9acdf2f62d371dd796cbe085b243fa | 464bc3fa1090bed273bcaa3257aebeacc4e8d3b0 | refs/heads/master | 2021-07-17T23:08:51.133152 | 2020-05-03T23:02:11 | 2020-05-03T23:02:11 | 133,565,838 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,308 | cpp | #include "WorldLoader.h"
ChunkCol::~ChunkCol() {
for (int i = 0; i < CHUNK_PER_COLUMN; i++) {
if (_chunks[i] != NULL) {
delete _chunks[i];
}
}
for (int i = 0; i < 4; i++) {
if (_neigh[i] != NULL) {
_neigh[i]->bye(static_cast<Directions>(i ^ 1), this);
}
}
_frag->setChunkCol(modulo(_ccx, COLUMN_PER_FRAGMENT), modulo(_ccy, COLUMN_PER_FRAGMENT), NULL);
}
void ChunkCol::get(DataElement* to) {
for (int c = 0; c < CHUNK_PER_COLUMN; c++) {
DataElement* nce = new DataElement();
_chunks[c]->get(nce);
to->addChild(nce);
}
}
void ChunkCol::set(const DataElement* from) {
for(int c = 0; c < CHUNK_PER_COLUMN; c++) {
if (_chunks[c]) {
throw 1;
return;
}
_chunks[c]->set(from->_children[c]);
}
}
void ChunkCol::setChunk(Chunk* c, int cz) {
if (_chunks[cz] != NULL) {
throw 1;
delete _chunks[cz];
}
c->_col = this;
_chunks[cz] = c;
c->_state = Chunk_Loaded;
c->link();
}
void ChunkCol::link() {
int lccx = modulo(_ccx, COLUMN_PER_FRAGMENT);
int lccy = modulo(_ccy, COLUMN_PER_FRAGMENT);
if (0 < lccx) {
ChunkCol* potentialNeigh = _frag->getChunkCol(lccx - 1, lccy);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_PX, this);
_neigh[Dir_MX] = potentialNeigh;
}
} else {
Fragment* neighFragment = _frag->_neigh[Dir_MX];
if (neighFragment != NULL) {
ChunkCol* potentialNeigh = neighFragment->getChunkCol(COLUMN_PER_FRAGMENT - 1, lccy);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_PX, this);
_neigh[Dir_MX] = potentialNeigh;
}
}
}
if (lccx < COLUMN_PER_FRAGMENT - 1) {
ChunkCol* potentialNeigh = _frag->getChunkCol(lccx + 1, lccy);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_MX, this);
_neigh[Dir_PX] = potentialNeigh;
}
} else {
Fragment* neighFragment = _frag->_neigh[Dir_PX];
if (neighFragment != NULL) {
ChunkCol* potentialNeigh = neighFragment->getChunkCol(0, lccy);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_MX, this);
_neigh[Dir_PX] = potentialNeigh;
}
}
}
if (0 < lccy) {
ChunkCol* potentialNeigh = _frag->getChunkCol(lccx, lccy - 1);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_PY, this);
_neigh[Dir_MY] = potentialNeigh;
}
} else {
Fragment* neighFragment = _frag->_neigh[Dir_MY];
if (neighFragment != NULL) {
ChunkCol* potentialNeigh = neighFragment->getChunkCol(lccx, COLUMN_PER_FRAGMENT - 1);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_PY, this);
_neigh[Dir_MY] = potentialNeigh;
}
}
}
if (lccy < COLUMN_PER_FRAGMENT - 1) {
ChunkCol* potentialNeigh = _frag->getChunkCol(lccx, lccy + 1);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_MY, this);
_neigh[Dir_PY] = potentialNeigh;
}
} else {
Fragment* neighFragment = _frag->_neigh[Dir_PY];
if (neighFragment != NULL) {
ChunkCol* potentialNeigh = neighFragment->getChunkCol(lccx, 0);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_MY, this);
_neigh[Dir_PY] = potentialNeigh;
}
}
}
for (int i = 0; i < CHUNK_PER_COLUMN; i++) {
if (_chunks[i] != NULL) {
_chunks[i]->link();
}
}
}
void ChunkCol::hello(Directions fromDir, ChunkCol* fromChunk) {
if(_neigh[fromDir] != fromChunk) {
_neigh[fromDir] = fromChunk;
}
}
void ChunkCol::unlink() {
ChunkCol* potentialNeigh;
potentialNeigh = _neigh[Dir_MX];
if (potentialNeigh != NULL) {
potentialNeigh->bye(Dir_PX, this);
_neigh[Dir_MX] = NULL;
}
potentialNeigh = _neigh[Dir_PX];
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_MX, this);
_neigh[Dir_PX] = NULL;
}
potentialNeigh = _neigh[Dir_MY];
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_PY, this);
_neigh[Dir_MY] = NULL;
}
potentialNeigh = _neigh[Dir_PY];
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_MY, this);
_neigh[Dir_PY] = NULL;
}
for (int i = 0; i < CHUNK_PER_COLUMN; i++) {
if (_chunks[i] != NULL) {
_chunks[i]->unlink();
}
}
}
void ChunkCol::bye(Directions fromDir, ChunkCol* fromChunk) {
_neigh[fromDir] = NULL;
} | [
"marci07iq@outlook.com"
] | marci07iq@outlook.com |
3e62dd54ae82aa90d514f18ae190c5de76006148 | dc2e0d49f99951bc40e323fb92ea4ddd5d9644a0 | /Cecily/Activemq-cpp_3.7.1/activemq-cpp/src/test-benchmarks/decaf/util/StlListBenchmark.h | 8da34df73f5e8380660c6b7e8a6e70930fd42636 | [
"Apache-2.0"
] | permissive | wenyu826/CecilySolution | 8696290d1723fdfe6e41ce63e07c7c25a9295ded | 14c4ba9adbb937d0ae236040b2752e2c7337b048 | refs/heads/master | 2020-07-03T06:26:07.875201 | 2016-11-19T07:04:29 | 2016-11-19T07:04:29 | 74,192,785 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,417 | h | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _DECAF_UTIL_STLLISTBENCHMARK_H_
#define _DECAF_UTIL_STLLISTBENCHMARK_H_
#include <benchmark/BenchmarkBase.h>
#include <decaf/util/StlList.h>
namespace decaf {
namespace util {
class StlListBenchmark :
public benchmark::BenchmarkBase<
decaf::util::StlListBenchmark, StlList<int> > {
private:
StlList<int> intList;
StlList<std::string> stringList;
public:
StlListBenchmark();
virtual ~StlListBenchmark();
virtual void run();
};
}}
#endif /* _DECAF_UTIL_STLLISTBENCHMARK_H_ */
| [
"626955115@qq.com"
] | 626955115@qq.com |
b89066e49830abdd424a65696963de909d11222f | 09e10747213f59689b3ad4218e4b228c1b07b85a | /game/gameserver/Trial.cpp | 96bd3cf438a33eb756b7d2ae35e7b65d532a714b | [] | no_license | imane-jym/gp | d4b75c8f07b8f4c8403a2fab30ad505140b5c6c1 | a531272417395268101f22164e4b15aa344e428d | refs/heads/master | 2021-01-10T09:47:29.835034 | 2017-11-23T12:02:02 | 2017-11-23T12:02:02 | 43,287,478 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,353 | cpp | #include "Trial.h"
#include "DBCtrl.h"
#include "EnumDefines.h"
#include "ErrorMsg.h"
#include "Role.h"
#include "CmdDefine.h"
#include "CardPacket.h"
#include "WorldBoss.h"
CTrial::CTrial()
{
m_dwCurrentdwIndex = 0;
m_pCRole = NULL;
m_dwCurrentTrigger = 0;
}
int CTrial::Init(CRole *pCRole)
{
m_pCRole = pCRole;
std::string temp;
if (!CDBCtrl::GetUserTrialData(temp, pCRole->GetdwAccountId()))
{
IME_ERROR("get trial data fail");
return -1;
}
ByteBuffer by;
by.append(temp.data(), temp.size());
DeSeriliazeDB(by);
// init trial data
if (m_dwCurrentdwIndex == 0)
{
STC_CONF_TRIAL *pConf = CConfTrial::FindOfFirstTrial();
if (pConf == NULL)
{
IME_ERROR("can not find first record in trial");
return -1;
}
m_dwCurrentdwIndex = pConf->dwIndex;
uint32_t now = time(NULL);
STrialData s;
s.ChallengeCnt = 0;
s.FlushTime = now;
s.StartTime = now;
m_mapTrial[m_dwCurrentdwIndex] = s;
}
OnTimer5s();
return 0;
}
void CTrial::OnTimer5s()
{
std::map<uint32_t, STrialData>::iterator it;
uint32_t now = time(NULL);
for (it = m_mapTrial.begin(); it != m_mapTrial.end(); it++)
{
if (!CUtil::IsToday(it->second.FlushTime))
{
it->second.ChallengeCnt = 0;
it->second.FlushTime = now;
}
}
STC_CONF_TRIAL *pFirstConf = CConfTrial::FindOfFirstTrial();
if (pFirstConf == NULL)
{
IME_ERROR("can not find first record in trial");
return;
}
if (m_dwCurrentdwIndex != pFirstConf->dwIndex)
{
STC_CONF_TRIAL *pConf = CConfTrial::Find(m_dwCurrentdwIndex);
if (pConf == NULL)
{
IME_ERROR("can not find current trial index %u in trial csv", m_dwCurrentdwIndex);
return;
}
it = m_mapTrial.find(m_dwCurrentdwIndex);
if (it == m_mapTrial.end())
{
IME_ERROR("can not find current trial index in trial map");
return;
}
if (m_mapTrial.find(pFirstConf->dwIndex) == m_mapTrial.end())
{
IME_ERROR("can not find first trial index %u in trial map", pFirstConf->dwIndex);
return;
}
if (now >= it->second.StartTime + pConf->dwTrieTime)
{
m_dwCurrentdwIndex = pFirstConf->dwIndex;
HandlerDataInfo();
}
}
}
void CTrial::SaveData()
{
ByteBuffer by;
SeriliazeDB(by);
std::string temp;
temp.assign((const char *)by.contents(), by.size());
CDBCtrl::SaveUserTrialData(temp, m_pCRole->GetdwAccountId());
return;
}
void CTrial::SeriliazeDB(ByteBuffer &by)
{
by << m_dwCurrentTrigger;
by << m_dwCurrentdwIndex;
by << (uint32_t) m_mapTrial.size();
std::map<uint32_t, STrialData>::iterator it;
for (it = m_mapTrial.begin(); it != m_mapTrial.end(); it++)
{
by << it->first;
by << it->second.ChallengeCnt;
by << it->second.FlushTime;
by << it->second.StartTime;
}
}
void CTrial::DeSeriliazeDB(ByteBuffer &by)
{
m_mapTrial.clear();
by >> m_dwCurrentTrigger;
by >> m_dwCurrentdwIndex;
uint32_t number;
by >> number;
for (int i = 0; i < number; i++)
{
STrialData s;
uint32_t key;
by >> key;
by >> s.ChallengeCnt;
by >> s.FlushTime;
by >> s.StartTime;
m_mapTrial[key] = s;
}
}
void CTrial::HandlerDataInfo()
{
STC_CONF_TRIAL *pConf = CConfTrial::Find(m_dwCurrentdwIndex);
if (pConf == NULL)
{
IME_ERROR("can not find record index %u in trial csv", m_dwCurrentdwIndex);
return;
}
if (m_mapTrial.find(m_dwCurrentdwIndex) == m_mapTrial.end())
{
IME_ERROR("can not find record index %u in trial map data", m_dwCurrentdwIndex);
return;
}
STC_CONF_ROLE *pConfExp = CConfRole::Find(m_pCRole->GetwLevel());
if (pConfExp == NULL)
{
IME_ERROR("can not find record index %u in role exp csv", m_pCRole->GetwLevel());
return;
}
WorldPacket info(CMD_SC_TRIAL_INFO);
info << m_dwCurrentdwIndex;
int remain = -1;
if (pConf->dwChallengeNumber != 0)
{
remain = pConf->dwChallengeNumber - m_mapTrial[m_dwCurrentdwIndex].ChallengeCnt;
remain = remain < 0 ? 0 : remain;
}
info << remain;
info << pConf->wConsume;
info << m_pCRole->GetdwStamina();
uint32_t roleexpneed, coinneed, cardexpneed;
roleexpneed = pConf->dwRoleExpNeed / 100.0 * pConfExp->dwRoleExp;
coinneed = pConf->dwCoinNeed / 100.0 * pConfExp->dwCoin;
cardexpneed = pConf->dwCardExpNeed / 100.0 *pConfExp->dwCardExp;
info << roleexpneed;
info << coinneed;
info << cardexpneed;
int cd = -1;
if (pConf->dwTrieTime != 0)
{
cd = m_mapTrial[m_dwCurrentdwIndex].StartTime + pConf->dwTrieTime - time(NULL);
if (cd < 0)
cd = 0;
}
info << cd;
info << m_dwCurrentTrigger;
m_pCRole->SendPacket(&info);
}
void CTrial::HandlerTrial(WorldPacket &pkg)
{
IME_CHAR_LOG("action [userid %u trial]", m_pCRole->GetdwAccountId());
STC_CONF_TRIAL *pConf = CConfTrial::Find(m_dwCurrentdwIndex);
if (pConf == NULL)
{
IME_ERROR("can not find record index %u in trial csv", m_dwCurrentdwIndex);
m_pCRole->SendErrorMsg(ERRNO_MSG_CSV_LOAD, CMD_SC_TRIAL_RESULT);
return;
}
std::map<uint32_t, STrialData>::iterator it = m_mapTrial.find(m_dwCurrentdwIndex);
if (it == m_mapTrial.end())
{
IME_ERROR("can not find record index %u in trial map data", m_dwCurrentdwIndex);
m_pCRole->SendErrorMsg(ERRNO_MSG_DATA_ILLEGAL, CMD_SC_TRIAL_RESULT);
return;
}
if (m_pCRole->GetdwStamina() < pConf->wConsume)
{
m_pCRole->SendStaminaNotEnough(CMD_SC_TRIAL_RESULT);
return;
}
if (m_pCRole->GetwLevel() < pConf->wLevelLimit)
{
m_pCRole->SendErrorMsg(ERRNO_MSG_TRIAL_LEVEL, CMD_SC_TRIAL_RESULT);
return;
}
STC_CONF_ROLE *pConfExp = CConfRole::Find(m_pCRole->GetwLevel());
if (pConfExp == NULL)
{
IME_ERROR("can not find record index %u in role exp csv", m_pCRole->GetwLevel());
m_pCRole->SendErrorMsg(ERRNO_MSG_CSV_LOAD, CMD_SC_TRIAL_RESULT);
return;
}
if (pConf->dwChallengeNumber != 0 && m_mapTrial[m_dwCurrentdwIndex].ChallengeCnt >= pConf->dwChallengeNumber)
{
m_pCRole->SendErrorMsg(ERRNO_MSG_TRIAL_CHALLENGE, CMD_SC_TRIAL_RESULT);
return;
}
if (m_pCRole->GetclsCardPacket()->IsFull(1, 0))
{
m_pCRole->SendErrorMsg(ERRNO_MSG_CARD_PACKET_NOT_ENOUGH, CMD_SC_TRIAL_RESULT);
return;
}
std::vector<CCard *> vec;
if (m_pCRole->GetclsCardPacket()->GetEquippCards(vec))
{
IME_ERROR("get card property fail, userid %u", m_pCRole->GetdwAccountId());
m_pCRole->SendErrorMsg(ERRNO_MSG_SYS, CMD_SC_TRIAL_RESULT);
return;
}
std::vector<int> vecpro;
vecpro.push_back(pConf->dwPro);
vecpro.push_back(pConf->wPro1);
vecpro.push_back(pConf->wPro2);
vecpro.push_back(pConf->wPro3);
vecpro.push_back(pConf->wPro4);
vecpro.push_back(pConf->wPro5);
vecpro.push_back(pConf->wPro6);
vecpro.push_back(pConf->wPro7);
vecpro.push_back(pConf->wPro8);
vecpro.push_back(pConf->wPro9);
vecpro.push_back(pConf->wPro10);
vecpro.push_back(pConf->wPro11);
vecpro.push_back(pConf->wPro12);
vecpro.push_back(pConf->wPro13);
vecpro.push_back(pConf->wPro14);
vecpro.push_back(pConf->wPro15);
IME_DEBUG("total pro %u boss pro %u, %u %u %u %u", pConf->wPro, pConf->wPro1, pConf->wPro2, pConf->wPro3, pConf->wPro4, pConf->wPro5, pConf->wPro6, pConf->wPro7, pConf->wPro8);
if (CUtil::RandEither(pConf->wPro, 100))
{
int ret = CUtil::RandFactor(vecpro);
IME_DEBUG("choose %u", ret);
SProduct duct = {0};
if (ret == BOSS_HAPPEN)
{
CFriendBoss *pFb = (CFriendBoss *)(sWorld->GetWorldBoss()->GetData(m_pCRole->GetdwAccountId()));
if (pFb == NULL)
{
IME_ERROR("can not find this user %u friend boss data", m_pCRole->GetdwAccountId());
m_pCRole->SendErrorMsg(ERRNO_MSG_FRIEND_BOSS_NOT_FIND, CMD_SC_TRIAL_RESULT);
return;
}
if (pFb->GetBossId() == 0)
{
pFb->HandlerHappenBoss(m_pCRole, pConf->dwBossId);
m_pCRole->SendObjEffectByHappenBoss();
}
}
else if (ret == NEXT_ENTER)
{
if (pConf->dwNextTrial != 0)
{
m_dwCurrentTrigger = pConf->dwNextTrial;
}
}
else if (ret == HAPPEN_ROLE)
{
m_pCRole->SendObjEffectByHappenRole();
if (m_pCRole->GetUJoinCount() != 0)
{
duct.type = E_OBJ_WORLD_EXP;
duct.para1 = 0;
duct.para2 = GlobalConfig::TrialFriendWorldHistory;
}
}
else
{
switch(ret)
{
case COIN_GET:
duct.type = E_OBJ_COIN;
duct.para1 = 0;
duct.para2 = pConf->dwCoin;
break;
case ROLE_EXP:
duct.type = E_OBJ_ROLE_EXP;
duct.para1 = 0;
duct.para2 = pConf->dwRoleExp;
break;
case CARD_EXP:
duct.type = E_OBJ_CARD_EXP;
duct.para1 = 0;
duct.para2 = pConf->dwCardExp;
break;
case WORLD_EXP:
duct.type = E_OBJ_WORLD_EXP;
duct.para1 = 0;
duct.para2 = pConf->dwWorldExp;
break;
case ITEM_DROP:
duct.type = E_OBJ_COL_SHOP;
duct.para1 = pConf->dwItemCollection;
duct.para2 = 0;
break;
case PIECES_DROP:
duct.type = E_OBJ_COL_ITEM;
duct.para1 = pConf->dwPiecesCollection;
duct.para2 = 0;
break;
case CARD_DROP:
duct.type = E_OBJ_COL_CARD_PLUS;
duct.para1 = pConf->dwCardCollection;
duct.para2 = pConf->wPlusPro;
break;
case ENERGY_RECOVER:
duct.type = E_OBJ_ENERGY;
duct.para1 = 0;
duct.para2 = pConf->dwEnergy;
break;
case LOT_ENERGY_RECOVER:
duct.type = E_OBJ_ENERGY;
duct.para1 = 0;
duct.para2 = pConf->dwLotEnergy;
break;
case STRENGTH_RECOVER:
duct.type = E_OBJ_STRENGTH;
duct.para1 = 0;
duct.para2 = pConf->dwEnergy;
break;
case LOT_STRENGTH_RECOVER:
duct.type = E_OBJ_STRENGTH;
duct.para1 = 0;
duct.para2 = pConf->dwLotEnergy;
break;
case STAMINA_RECOVER:
duct.type = E_OBJ_STAMINA;
duct.para1 = 0;
duct.para2 = pConf->dwStamina;
break;
case LOT_STAMINA_RECOVER:
duct.type = E_OBJ_STAMINA;
duct.para1 = 0;
duct.para2 = pConf->dwLotStamina;
break;
default:
break;
}
}
if (duct.type != 0)
{
CShopEffect::SGiveProduct ObjEffect = {0};
CShopEffect::GiveGameProductSpecial(m_pCRole, duct.type, duct.para1, duct.para2, ObjEffect, SOURCE_TRIAL);
std::vector<CShopEffect::SGiveProduct> vect;
vect.push_back(ObjEffect);
m_pCRole->SendObjEffect(vect);
}
}
m_pCRole->ChangeStamina(-pConf->wConsume);
it->second.ChallengeCnt++;
uint32_t roleexpneed, coinneed, cardexpneed;
roleexpneed = pConf->dwRoleExpNeed / 100.0 * pConfExp->dwRoleExp * pConf->wConsume;
coinneed = pConf->dwCoinNeed / 100.0 * pConfExp->dwCoin * pConf->wConsume;
cardexpneed = pConf->dwCardExpNeed / 100.0 *pConfExp->dwCardExp * pConf->wConsume;
m_pCRole->AddExp(roleexpneed);
m_pCRole->ChangeCoin(coinneed, SOURCE_TRIAL);
for (int i = 0; i < vec.size(); i++)
{
if (m_pCRole->GetwLevel() * STRENGTH_LEVEL_LIMIT_PARA > vec[i]->GetwLevel())
{
vec[i]->AddExp(cardexpneed);
vec[i]->Calculate(true);
}
}
m_pCRole->Calculate(true);
m_pCRole->HandlerInfoOpt();
HandlerDataInfo();
WorldPacket info(CMD_SC_TRIAL_RESULT);
info << (uint16_t) 0;
info << (uint32_t) roleexpneed;
info << (uint32_t) coinneed;
info << (uint32_t) cardexpneed;
m_pCRole->SendPacket(&info);
}
void CTrial::HandlerEnterNext(WorldPacket &pkg)
{
uint8_t isenter;
pkg >> isenter;
IME_CHAR_LOG("action [userid %u enter next trial isenter %u]", m_pCRole->GetdwAccountId(), isenter);
if (m_dwCurrentTrigger == 0)
{
m_pCRole->SendErrorMsg(ERRNO_MSG_TRIAL_NEXT, CMD_SC_TRIAL_NEXT_RESULT);
return;
}
STC_CONF_TRIAL *pConf = CConfTrial::Find(m_dwCurrentTrigger);
if (pConf == NULL)
{
m_pCRole->SendErrorMsg(ERRNO_MSG_CSV_DATA, CMD_SC_TRIAL_NEXT_RESULT);
return;
}
if (m_pCRole->GetwLevel() < pConf->wLevelLimit)
{
m_dwCurrentTrigger = 0;
HandlerDataInfo();
WorldPacket info(CMD_SC_TRIAL_NEXT_RESULT);
info << (uint16_t) ERRNO_MSG_TRIAL_LEVEL;
info << pConf->wLevelLimit;
m_pCRole->SendPacket(&info);
return;
}
if (isenter > 0)
{
m_dwCurrentdwIndex = m_dwCurrentTrigger;
uint32_t now = time(NULL);
if (m_mapTrial.find(m_dwCurrentdwIndex) != m_mapTrial.end())
{
m_mapTrial[m_dwCurrentdwIndex].StartTime = now;
}
else
{
m_mapTrial[m_dwCurrentdwIndex].ChallengeCnt = 0;
m_mapTrial[m_dwCurrentdwIndex].FlushTime = now;
m_mapTrial[m_dwCurrentdwIndex].StartTime = now;
}
}
m_dwCurrentTrigger = 0;
HandlerDataInfo();
WorldPacket info(CMD_SC_TRIAL_NEXT_RESULT);
info << (uint16_t) 0;
m_pCRole->SendPacket(&info);
}
void CTrial::ChangeTrial(uint32_t index)
{
STC_CONF_TRIAL *pConf = CConfTrial::Find(index);
if (pConf == NULL)
{
IME_ERROR("can not find record index %u in trial csv", index);
return;
}
if (m_pCRole->GetwLevel() < pConf->wLevelLimit)
{
IME_ERROR("role level is not enough, level limit %u", pConf->wLevelLimit);
return;
}
uint32_t current = m_dwCurrentdwIndex;
m_dwCurrentdwIndex = index;
uint32_t now = time(NULL);
if (m_mapTrial.find(m_dwCurrentdwIndex) != m_mapTrial.end())
{
if (current != m_dwCurrentdwIndex)
{
m_mapTrial[m_dwCurrentdwIndex].StartTime = now;
}
else
{
m_mapTrial[m_dwCurrentdwIndex].StartTime -= pConf->dwTrieTime;
}
}
else
{
m_mapTrial[m_dwCurrentdwIndex].ChallengeCnt = 0;
m_mapTrial[m_dwCurrentdwIndex].FlushTime = now;
m_mapTrial[m_dwCurrentdwIndex].StartTime = now;
}
HandlerDataInfo();
return;
}
bool CTrial::ValidChangeTrial(uint32_t index)
{
STC_CONF_TRIAL *pConf = CConfTrial::Find(index);
if (pConf == NULL)
{
IME_ERROR("can not find record index %u in trial csv", index);
return false;
}
if (m_pCRole->GetwLevel() < pConf->wLevelLimit)
{
IME_ERROR("role level is not enough, level limit %u", pConf->wLevelLimit);
return false;
}
return true;
}
| [
"imane@imane-virtual-machine.(none)"
] | imane@imane-virtual-machine.(none) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.