hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7d6a6526026b9c3749bfc1bb1150338f05a1ff78
| 4,073
|
cpp
|
C++
|
command.cpp
|
SAE-Geneve/classylabyrinth-PaulOwO
|
9229d3a5295dbed86892cefc03496c35a1997789
|
[
"MIT"
] | null | null | null |
command.cpp
|
SAE-Geneve/classylabyrinth-PaulOwO
|
9229d3a5295dbed86892cefc03496c35a1997789
|
[
"MIT"
] | null | null | null |
command.cpp
|
SAE-Geneve/classylabyrinth-PaulOwO
|
9229d3a5295dbed86892cefc03496c35a1997789
|
[
"MIT"
] | null | null | null |
#include <vector>
#include "command.h"
#include "character.h"
#include "player.h"
#include <iostream>
#include "world.h"
void Command::North()
{
Player player = world_.GetPlayer();
if (world_.get_tile_at_position(player.GetX(),player.GetY() - 1) != '.')
return;
else
player.SetY(player.GetY() - 1);
world_.SetPlayer(player);
}
void Command::South()
{
Player player = world_.GetPlayer();
if (world_.get_tile_at_position(player.GetX(), player.GetY() + 1) != '.')
return;
else
player.SetY(player.GetY() + 1);
world_.SetPlayer(player);
}
void Command::East()
{
Player player = world_.GetPlayer();
if (world_.get_tile_at_position(player.GetX() + 1, player.GetY()) != '.')
return;
else
player.SetX(player.GetX() + 1);
world_.SetPlayer(player);
}
void Command::West()
{
Player player = world_.GetPlayer();
if (world_.get_tile_at_position(player.GetX() - 1, player.GetY()) != '.')
return;
else
player.SetX(player.GetX() - 1);
world_.SetPlayer(player);
}
/*void Command::Attack(Character1,Character2)
{
Character2.health_points -= std::max(0, Character1.attack - Character2.defence);
set_player(player);
set_enemy(enemy, enemy.x, enemy.y);
}*/
void Command::PlayerAttack()
{
Player player = world_.GetPlayer();
std::vector<Enemy> enemy_vec;
if (world_.get_tile_at_position(player.GetX(), player.GetY() - 1) == 'E')
enemy_vec.push_back(world_.GetEnemy(player.GetX(), player.GetY() - 1));
if (world_.get_tile_at_position(player.GetX(), player.GetY() + 1) == 'E')
enemy_vec.push_back(world_.GetEnemy(player.GetX(), player.GetY() + 1));
if (world_.get_tile_at_position(player.GetX() - 1, player.GetY()) == 'E')
enemy_vec.push_back(world_.GetEnemy(player.GetX() - 1, player.GetY()));
if (world_.get_tile_at_position(player.GetX() + 1, player.GetY()) == 'E')
enemy_vec.push_back(world_.GetEnemy(player.GetX() + 1, player.GetY()));
for (auto& enemy : enemy_vec)
enemy.SetHealthPoints(enemy.GetHealthPoints() - player.GetAttack() + enemy.GetDefence());
}
void Command::EnemyAttack()
{
}
void Command::Tick()
{
Player player = world_.GetPlayer();
player.Regen();
//EnnemyAttack()
}
void Command::ShowState()
{
Player player = world_.GetPlayer();
// Show the maze to the user.
std::cout << "Maze :\n";
for (int i = -1; i < 2; ++i)
{
std::cout << "\t +---+---+---+\n\t";
for (int j = -1; j < 2; ++j)
{
std::cout
<< " | "
<< (char)world_.get_tile_at_position(player.GetX() + j, player.GetY() + i);
}
std::cout << " |\n";
}
std::cout << "\t +---+---+---+\n\n";
std::cout << "Player(" << player.GetX() << ", " << player.GetY() << ") :\n";
std::cout << "\tname : ";
player.PrintName();
std::cout << "\n\thealth points : " << player.GetHealthPoints() << "\n";
std::cout << "\n";
for (int i = -1; i < 2; ++i)
{
for (int j = -1; j < 2; ++j)
{
if ('E' ==
world_.get_tile_at_position(player.GetX() + i, player.GetY() + j))
{
Enemy enemy = world_.GetEnemy(player.GetX() + i, player.GetY() + j);
std::cout
<< "Enemy(" << player.GetX() + i
<< ", " << player.GetY() + j
<< ")\n";
std::cout << "\tname : ";
enemy.PrintName();
std::cout << "\n\thealth points : " << enemy.GetHealthPoints() << "\n";
std::cout << "\n";
}
}
}
}
void Command::ShowHelp()
{
std::cout << "Valid options:\n"
<< "\t[q]uit -> quit the game.\n"
<< "\t[n]orth -> move north.\n"
<< "\t[s]outh -> move south.\n"
<< "\t[e]ast -> move east.\n"
<< "\t[w]est -> move west.\n"
<< "\t[a]ttack -> attack enemy.\n"
<< "\t[h]elp -> show help.\n";
}
char Command::GetCommand()
{
std::cout << "] ";
std::string command_str;
std::getline(std::cin, command_str);
return command_str[0];
}
void Command::ExecuteCommand()
{
switch (GetCommand())
{
case 'q':
std::cout << "Ciao!\n";
exit(0);
case 'n':
return North();
break;
case 's':
return South();
break;
case 'e':
return East();
break;
case 'w':
return West();
break;
case 'a':
return PlayerAttack();
break;
case 'h':
default:
ShowHelp();
break;
}
Tick();
}
| 22.016216
| 91
| 0.599067
|
SAE-Geneve
|
7d6ac821dfb47fe447c915208b6ad81622943da1
| 8,312
|
cpp
|
C++
|
Remove_bad_split_good/llcpImp.cpp
|
awagsta/Data-Structures-and-Algorithms
|
d32dc118ff7392421dd61c0ff8cca0eebb27747a
|
[
"MIT"
] | null | null | null |
Remove_bad_split_good/llcpImp.cpp
|
awagsta/Data-Structures-and-Algorithms
|
d32dc118ff7392421dd61c0ff8cca0eebb27747a
|
[
"MIT"
] | null | null | null |
Remove_bad_split_good/llcpImp.cpp
|
awagsta/Data-Structures-and-Algorithms
|
d32dc118ff7392421dd61c0ff8cca0eebb27747a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cstdlib>
#include "llcpInt.h"
using namespace std;
int FindListLength(Node* headPtr)
{
int length = 0;
while (headPtr != 0)
{
++length;
headPtr = headPtr->link;
}
return length;
}
bool IsSortedUp(Node* headPtr)
{
if (headPtr == 0 || headPtr->link == 0) // empty or 1-node
return true;
while (headPtr->link != 0) // not at last node
{
if (headPtr->link->data < headPtr->data)
return false;
headPtr = headPtr->link;
}
return true;
}
void InsertAsHead(Node*& headPtr, int value)
{
Node *newNodePtr = new Node;
newNodePtr->data = value;
newNodePtr->link = headPtr;
headPtr = newNodePtr;
}
void InsertAsTail(Node*& headPtr, int value)
{
Node *newNodePtr = new Node;
newNodePtr->data = value;
newNodePtr->link = 0;
if (headPtr == 0)
headPtr = newNodePtr;
else
{
Node *cursor = headPtr;
while (cursor->link != 0) // not at last node
cursor = cursor->link;
cursor->link = newNodePtr;
}
}
void InsertSortedUp(Node*& headPtr, int value)
{
Node *precursor = 0,
*cursor = headPtr;
while (cursor != 0 && cursor->data < value)
{
precursor = cursor;
cursor = cursor->link;
}
Node *newNodePtr = new Node;
newNodePtr->data = value;
newNodePtr->link = cursor;
if (cursor == headPtr)
headPtr = newNodePtr;
else
precursor->link = newNodePtr;
///////////////////////////////////////////////////////////
/* using-only-cursor (no precursor) version
Node *newNodePtr = new Node;
newNodePtr->data = value;
//newNodePtr->link = 0;
//if (headPtr == 0)
// headPtr = newNodePtr;
//else if (headPtr->data >= value)
//{
// newNodePtr->link = headPtr;
// headPtr = newNodePtr;
//}
if (headPtr == 0 || headPtr->data >= value)
{
newNodePtr->link = headPtr;
headPtr = newNodePtr;
}
//else if (headPtr->link == 0)
// head->link = newNodePtr;
else
{
Node *cursor = headPtr;
while (cursor->link != 0 && cursor->link->data < value)
cursor = cursor->link;
//if (cursor->link != 0)
// newNodePtr->link = cursor->link;
newNodePtr->link = cursor->link;
cursor->link = newNodePtr;
}
////////////////// commented lines removed //////////////////
Node *newNodePtr = new Node;
newNodePtr->data = value;
if (headPtr == 0 || headPtr->data >= value)
{
newNodePtr->link = headPtr;
headPtr = newNodePtr;
}
else
{
Node *cursor = headPtr;
while (cursor->link != 0 && cursor->link->data < value)
cursor = cursor->link;
newNodePtr->link = cursor->link;
cursor->link = newNodePtr;
}
*/
///////////////////////////////////////////////////////////
}
bool DelFirstTargetNode(Node*& headPtr, int target)
{
Node *precursor = 0,
*cursor = headPtr;
while (cursor != 0 && cursor->data != target)
{
precursor = cursor;
cursor = cursor->link;
}
if (cursor == 0)
{
cout << target << " not found." << endl;
return false;
}
if (cursor == headPtr) //OR precursor == 0
headPtr = headPtr->link;
else
precursor->link = cursor->link;
delete cursor;
return true;
}
bool DelNodeBefore1stMatch(Node*& headPtr, int target)
{
if (headPtr == 0 || headPtr->link == 0 || headPtr->data == target) return false;
Node *cur = headPtr->link, *pre = headPtr, *prepre = 0;
while (cur != 0 && cur->data != target)
{
prepre = pre;
pre = cur;
cur = cur->link;
}
if (cur == 0) return false;
if (cur == headPtr->link)
{
headPtr = cur;
delete pre;
}
else
{
prepre->link = cur;
delete pre;
}
return true;
}
void ShowAll(ostream& outs, Node* headPtr)
{
while (headPtr != 0)
{
outs << headPtr->data << " ";
headPtr = headPtr->link;
}
outs << endl;
}
void FindMinMax(Node* headPtr, int& minValue, int& maxValue)
{
if (headPtr == 0)
{
cerr << "FindMinMax() attempted on empty list" << endl;
cerr << "Minimum and maximum values not set" << endl;
}
else
{
minValue = maxValue = headPtr->data;
while (headPtr->link != 0)
{
headPtr = headPtr->link;
if (headPtr->data < minValue)
minValue = headPtr->data;
else if (headPtr->data > maxValue)
maxValue = headPtr->data;
}
}
}
double FindAverage(Node* headPtr)
{
if (headPtr == 0)
{
cerr << "FindAverage() attempted on empty list" << endl;
cerr << "An arbitrary zero value is returned" << endl;
return 0.0;
}
else
{
int sum = 0,
count = 0;
while (headPtr != 0)
{
++count;
sum += headPtr->data;
headPtr = headPtr->link;
}
return double(sum) / count;
}
}
void ListClear(Node*& headPtr, int noMsg)
{
int count = 0;
Node *cursor = headPtr;
while (headPtr != 0)
{
headPtr = headPtr->link;
delete cursor;
cursor = headPtr;
++count;
}
if (noMsg) return;
clog << "Dynamic memory for " << count << " nodes freed"
<< endl;
}
void RemBadSplitGood(Node*& head1Ptr, Node*& head2Ptr, Node*& head3Ptr)
{
Node * pre = 0;
Node * cursor = head1Ptr;
head2Ptr = 0;
head3Ptr = 0;
Node *h2Current = 0, *h3Current = 0;
while(cursor != 0)
{
if(head1Ptr->data != 6 && !(head1Ptr->data >= 0 && head1Ptr->data <= 9) )
{
head1Ptr = head1Ptr->link;
delete cursor;
cursor = head1Ptr;
}
else if(cursor->data == 6)
{
pre = cursor;
cursor = cursor->link;
}
else if(cursor->data >= 0 && cursor->data <= 5)
{
if(cursor == head1Ptr)
{
Node * temp = cursor;
head1Ptr = head1Ptr->link;
cursor = head1Ptr;
temp->link = 0;
if(head2Ptr == 0)
{
head2Ptr = temp;
h2Current = head2Ptr;
}
else
{
h2Current->link = temp;
h2Current = h2Current->link;
}
}
else // cursor is not the head node
{
pre->link = cursor->link;
Node * temp = cursor;
cursor = cursor->link;
temp->link = 0;
if(head2Ptr == 0)
{
head2Ptr = temp;
h2Current = head2Ptr;
}
else
{
h2Current->link = temp;
h2Current = h2Current->link;
}
}
}
else if(cursor->data >= 7 && cursor->data <= 9)
{
if(cursor == head1Ptr)
{
Node * temp = cursor;
head1Ptr = head1Ptr->link;
cursor = head1Ptr;
temp->link = 0;
if(head3Ptr == 0)
{
head3Ptr = temp;
h3Current = head3Ptr;
}
else
{
h3Current->link = temp;
h3Current = h3Current->link;
}
}
else // cursor is not the head node
{
pre->link = cursor->link;
Node * temp = cursor;
cursor = cursor->link;
temp->link = 0;
if(head3Ptr == 0)
{
head3Ptr = temp;
h3Current = head3Ptr;
}
else
{
h3Current->link = temp;
h3Current = h3Current->link;
}
}
}
else // value not between 0 and 9 inclusive
{
pre->link = cursor->link;
delete cursor;
cursor = cursor->link;
}
}
// if any of the lists are empty, indicate this with a -99 sentinel value
if(head1Ptr == 0)
{
head1Ptr = new Node;
head1Ptr->link = 0;
head1Ptr->data = -99;
}
if(head2Ptr == 0)
{
head2Ptr = new Node;
head2Ptr->link = 0;
head2Ptr->data = -99;
}
if(head3Ptr == 0)
{
head3Ptr = new Node;
head3Ptr->link = 0;
head3Ptr->data = -99;
}
}
| 22.106383
| 83
| 0.490014
|
awagsta
|
7d721de4f52be0839911e50daf631d081fe92375
| 14,349
|
hpp
|
C++
|
core/os/MacOS/src/cogs/os/gui/scroll_bar.hpp
|
cogmine/cogs
|
ef1c369a36a4f811704e0ced0493c3a6f8eca821
|
[
"MIT"
] | 5
|
2019-02-08T15:59:14.000Z
|
2022-01-22T19:12:33.000Z
|
core/os/MacOS/src/cogs/os/gui/scroll_bar.hpp
|
cogmine/cogs
|
ef1c369a36a4f811704e0ced0493c3a6f8eca821
|
[
"MIT"
] | 1
|
2019-12-03T03:11:34.000Z
|
2019-12-03T03:11:34.000Z
|
core/os/MacOS/src/cogs/os/gui/scroll_bar.hpp
|
cogmine/cogs
|
ef1c369a36a4f811704e0ced0493c3a6f8eca821
|
[
"MIT"
] | null | null | null |
//
// Copyright (C) 2000-2020 - Colen M. Garoutte-Carson <colen at cogmine.com>, Cog Mine LLC
//
// Status: Good
#ifndef COGS_HEADER_OS_GUI_SCROLL_BAR
#define COGS_HEADER_OS_GUI_SCROLL_BAR
#include "cogs/sync/transactable.hpp"
#include "cogs/sync/resettable_timer.hpp"
#include "cogs/gui/scroll_bar.hpp"
#include "cogs/math/boolean.hpp"
#include "cogs/mem/rcnew.hpp"
#include "cogs/os/gui/nsview.hpp"
namespace cogs {
namespace os {
class scroll_bar;
};
};
@interface objc_scroll_bar : NSScroller
{
@public
cogs::weak_rcptr<cogs::os::scroll_bar> m_cppScrollBar;
}
-(BOOL)isFlipped;
-(void)scrolled:(id)sender;
-(void)preferredScrollerStyleChanged:(NSNotification*)notification;
+(BOOL)isCompatibleWithOverlayScrollers;
-(void)drawRect:(NSRect)dirtyRect;
-(void)drawKnob;
-(void)defaultDrawKnob;
-(void)drawKnobSlotInRect:(NSRect)slotRect highlight:(BOOL)flag;
-(void)defaultDrawKnobSlotInRect:(NSRect)slotRect highlight:(BOOL)flag;
-(void)fade:(NSTimer*)timer;
@end
namespace cogs {
namespace os {
class scroll_bar : public nsview_pane, public gui::scroll_bar_interface
{
private:
volatile transactable<gui::scroll_bar_state> m_state;
volatile double m_pos = 0;
volatile boolean m_canAutoFade;
volatile boolean m_shouldAutoFade;
gfx::dimension m_dimension;
gfx::range m_currentRange;
gfx::size m_currentDefaultSize;
bool m_isHiddenWhenInactive;
bool m_isHidden = false;
CGFloat m_knobAlpha;
bool m_isKnobSlotVisible;
rcref<resettable_timer> m_fadeDelayTimer;
boolean m_fadeDelayDispatched;
__strong NSTimer* m_fadeTimer = nullptr;
rcptr<task<void> > m_fadeDelayTask;
delegated_dependency_property<gui::scroll_bar_state> m_stateProperty;
delegated_dependency_property<double> m_positionProperty;
delegated_dependency_property<bool> m_canAutoFadeProperty;
delegated_dependency_property<bool> m_shouldAutoFadeProperty;
void set_scroll_bar_state(const gui::scroll_bar_state& newState, double newPos)
{
start_fade_delay();
rcptr<gui::scroll_bar> sb = get_bridge().template static_cast_to<gui::scroll_bar>();
objc_scroll_bar* objcScrollBar = (objc_scroll_bar*)get_NSView();
for (;;)
{
if (newState.m_thumbSize >= newState.m_max)
{
if (!!m_isHiddenWhenInactive)
{
if (!m_isHidden)
{
m_isHidden = true;
sb->hide();
}
break;
}
[objcScrollBar setEnabled: NO];
}
else
{
double maxPos = newState.m_max - newState.m_thumbSize;
double pos = newPos;
if (pos > maxPos)
pos = maxPos;
[objcScrollBar setEnabled: YES] ;
[objcScrollBar setDoubleValue: (pos / maxPos) ];
[objcScrollBar setKnobProportion: (newState.m_thumbSize / newState.m_max) ];
}
if (!!m_isHidden)
{
m_isHidden = false;
sb->show();
}
break;
}
}
// Will execute in main thread
void delay_expired()
{
m_fadeDelayDispatched = false;
objc_scroll_bar* objcScrollBar = (objc_scroll_bar*)get_NSView();
m_fadeTimer = [NSTimer timerWithTimeInterval: 0.05 target: objcScrollBar selector: @selector(fade:) userInfo: nil repeats: YES];
[[NSRunLoop mainRunLoop] addTimer: m_fadeTimer forMode: NSRunLoopCommonModes];
}
void stop_fade(CGFloat knobAlpha = 1.0)
{
if (!!m_fadeTimer)
{
[m_fadeTimer invalidate];
m_fadeTimer = nullptr;
}
if (m_knobAlpha != knobAlpha)
{
m_knobAlpha = knobAlpha;
objc_scroll_bar* objcScrollBar = (objc_scroll_bar*)get_NSView();
[objcScrollBar setNeedsDisplay: YES];
}
}
void start_fade_delay()
{
if (m_isFadeSupressed || !m_shouldAutoFade || !m_canAutoFade)
return;
stop_fade();
if (m_fadeDelayDispatched)
{
if (m_fadeDelayTimer->reschedule(make_measure<seconds>(1)))
return; // Succeeded in postponing the existing timer. All done
// The timer must have already fired.
// We are on the main thread, and delay_expired must be pending after us.
// Cancellation should succeed.
m_fadeDelayTask->cancel();
}
else
{
// The timer was not running. Start it.
m_fadeDelayDispatched = true;
m_fadeDelayTimer->reset(make_measure<seconds>(1));
}
m_fadeDelayTask = m_fadeDelayTimer->dispatch([r{ this_weak_rcptr }]()
{
// move to main thread
rcptr<scroll_bar> r2 = r;
if (!r2)
return signaled();
return r2->get_subsystem()->dispatch([r]()
{
rcptr<scroll_bar> r2 = r;
if (!!r2)
r2->delay_expired();
});
});
}
volatile boolean m_isFadeSupressed;
// Must only be called from main thread.
// m_isFadeSupressed can be read from any thread, but should only be modified in the main thread.
void suppress_fade()
{
if (!m_isFadeSupressed)
{
m_isFadeSupressed = true;
if (m_shouldAutoFade && m_canAutoFade)
stop_fade(1.0);
}
}
// Must only be called from main thread
void unsuppress_fade()
{
if (!!m_isFadeSupressed)
{
m_isFadeSupressed = false;
start_fade_delay();
}
}
public:
explicit scroll_bar(const rcref<volatile nsview_subsystem>& uiSubsystem)
: nsview_pane(uiSubsystem),
m_fadeDelayTimer(rcnew(resettable_timer)),
m_stateProperty(uiSubsystem, [this]()
{
return *(m_state.begin_read());
}, [this](const gui::scroll_bar_state& state)
{
gui::scroll_bar_state newState = state;
gui::scroll_bar_state oldState = newState;
m_state.swap_contents(oldState);
if (newState != oldState)
{
double curPos = cogs::atomic::load(m_pos);
set_scroll_bar_state(newState, curPos);
m_stateProperty.changed();
}
m_stateProperty.set_complete();
}),
m_positionProperty(uiSubsystem, [this]()
{
return cogs::atomic::load(m_pos);
}, [this](double d)
{
double newPos = d;
double oldPos = cogs::atomic::exchange(m_pos, newPos);
if (newPos != oldPos)
{
set_scroll_bar_state(*(m_state.begin_read()), newPos);
m_positionProperty.changed();
}
m_positionProperty.set_complete();
}),
m_canAutoFadeProperty(uiSubsystem, [this]()
{
return m_canAutoFade;
}, [this](bool b)
{
bool oldValue = m_canAutoFade.exchange(b);
if (b != oldValue)
{
if (m_shouldAutoFade)
{
objc_scroll_bar* objcScrollBar = (objc_scroll_bar*)get_NSView();
if (objcScrollBar)
{
if (!b)
{
stop_fade(1.0);
[objcScrollBar setScrollerStyle: NSScrollerStyleLegacy];
[objcScrollBar setNeedsDisplay: YES];
}
else
{
stop_fade(0.0);
[objcScrollBar setScrollerStyle: NSScrollerStyleOverlay];
[objcScrollBar setNeedsDisplay: YES];
}
}
}
m_canAutoFadeProperty.changed();
}
m_canAutoFadeProperty.set_complete();
}),
m_shouldAutoFadeProperty(uiSubsystem, [this]()
{
return m_shouldAutoFade;
}, [this](bool b)
{
bool oldValue = m_shouldAutoFade.exchange(b);
if (b != oldValue)
{
if (m_canAutoFade)
{
objc_scroll_bar* objcScrollBar = (objc_scroll_bar*)get_NSView();
if (objcScrollBar)
{
if (!b)
{
stop_fade(1.0);
[objcScrollBar setScrollerStyle: NSScrollerStyleLegacy];
[objcScrollBar setNeedsDisplay: YES];
}
else
{
stop_fade(0.0);
[objcScrollBar setScrollerStyle: NSScrollerStyleOverlay];
[objcScrollBar setNeedsDisplay: YES];
}
}
}
m_shouldAutoFadeProperty.changed();
}
m_shouldAutoFadeProperty.set_complete();
})
{
}
~scroll_bar()
{
objc_scroll_bar* objcScrollBar = (objc_scroll_bar*)get_NSView();
if (!!objcScrollBar)
objcScrollBar->m_cppScrollBar.release();
}
virtual void installing()
{
rcptr<gui::scroll_bar> sb = get_bridge().template static_cast_to<gui::scroll_bar>();
m_dimension = sb->get_dimension();
m_isHiddenWhenInactive = sb->is_hidden_when_inactive();
// use bogus frame just for the purpose of detecting dimension.
NSRect bogusBounds;
bogusBounds.origin.x = bogusBounds.origin.y = 0;
if (m_dimension == gfx::dimension::horizontal)
{
bogusBounds.size.width = 100;
bogusBounds.size.height = 10;
}
else
{
bogusBounds.size.width = 10;
bogusBounds.size.height = 100;
}
__strong objc_scroll_bar* objcScrollBar = [[objc_scroll_bar alloc] initWithFrame:bogusBounds];
objcScrollBar->m_cppScrollBar = this_rcptr;
bogusBounds.origin.x = bogusBounds.origin.y = 0;
m_isKnobSlotVisible = true;
[objcScrollBar setTarget:objcScrollBar];
[objcScrollBar setAction: @selector(scrolled:)];
NSScrollerStyle preferredStyle = [NSScroller preferredScrollerStyle];
bool canAutoFade = (preferredStyle == NSScrollerStyleOverlay);
bool shouldAutoFade = sb->get_should_auto_fade_property()->get();
m_canAutoFade = canAutoFade;
m_shouldAutoFade = shouldAutoFade;
if (shouldAutoFade && canAutoFade)
{
[objcScrollBar setScrollerStyle: preferredStyle];
m_knobAlpha = 0.0;
}
else
{
[objcScrollBar setScrollerStyle: NSScrollerStyleLegacy];
m_knobAlpha = 1.0;
}
m_stateProperty.bind_from(sb->get_state_property());
m_positionProperty.bind(sb->get_position_property(), false);
m_canAutoFadeProperty.bind_to(get_can_auto_fade_property(sb.dereference()));
m_shouldAutoFadeProperty.bind_from(sb->get_should_auto_fade_property());
[[NSNotificationCenter defaultCenter] addObserver:objcScrollBar selector:@selector(preferredScrollerStyleChanged:) name:NSPreferredScrollerStyleDidChangeNotification object:nil];
install_NSView(objcScrollBar);
nsview_pane::installing();
}
void scrolled()
{
transactable<gui::scroll_bar_state>::read_token rt;
m_state.begin_read(rt);
bool setPosition = true;
double oldPos = cogs::atomic::load(m_pos);
double pos = oldPos;
double max = rt->m_max;
double thumbSize = rt->m_thumbSize;
double maxPos = max;
maxPos -= thumbSize;
objc_scroll_bar* objcScrollBar = (objc_scroll_bar*)get_NSView();
NSScrollerPart part = [objcScrollBar hitPart];
switch (part)
{
case NSScrollerDecrementPage:
if (pos <= thumbSize)
pos = 0;
else
pos -= thumbSize;
break;
case NSScrollerIncrementPage:
pos += thumbSize;
if (pos > maxPos)
pos = maxPos;
break;
//case NSScrollerDecrementLine:
// if (pos > 0)
// --pos;
// break;
//case NSScrollerIncrementLine:
// if (pos < maxPos)
// ++pos;
// break;
case NSScrollerKnob:
case NSScrollerKnobSlot:
{
double curValue = [objcScrollBar doubleValue];
double scaledUp = curValue * maxPos;
pos = (longest)scaledUp;
}
case NSScrollerNoPart:
default:
setPosition = false;
break;
}
if (pos != oldPos)
{
if (!!setPosition)
[objcScrollBar setDoubleValue: (pos/maxPos) ];
// sets are serialized in the UI thread. No need to worry about synchronizing with other writes.
m_positionProperty.set(pos);
}
}
virtual void calculate_range()
{
objc_scroll_bar* objcScrollBar = (objc_scroll_bar*)get_NSView();
m_currentRange.clear();
double scrollBarWidth = (longest)[NSScroller scrollerWidthForControlSize:[objcScrollBar controlSize] scrollerStyle:[objcScrollBar scrollerStyle]];
m_currentRange.get_max(!m_dimension) = scrollBarWidth;
m_currentDefaultSize.set(scrollBarWidth, scrollBarWidth);
}
virtual gfx::range get_range() const { return m_currentRange; }
virtual std::optional<gfx::size> get_default_size() const { return m_currentDefaultSize; }
virtual bool is_focusable() const { return false; }
void set_can_auto_fade(bool b)
{
m_canAutoFadeProperty.set(b);
}
void drawKnob()
{
objc_scroll_bar* objcScrollBar = (objc_scroll_bar*)get_NSView();
NSGraphicsContext* curContext = [NSGraphicsContext currentContext];
CGContextRef context = [curContext CGContext];
CGContextSaveGState(context);
CGContextSetAlpha(context, m_knobAlpha);
[objcScrollBar defaultDrawKnob];
CGContextRestoreGState(context);
}
void drawKnobSlotInRect(const NSRect& slotRect, bool highlightFlag)
{
objc_scroll_bar* objcScrollBar = (objc_scroll_bar*)get_NSView();
NSGraphicsContext* curContext = [NSGraphicsContext currentContext];
CGContextRef context = [curContext CGContext];
CGContextSaveGState(context);
CGContextSetAlpha(context, m_knobAlpha);
[objcScrollBar defaultDrawKnobSlotInRect: slotRect highlight: highlightFlag];
CGContextRestoreGState(context);
}
void fade()
{
objc_scroll_bar* objcScrollBar = (objc_scroll_bar*)get_NSView();
CGFloat alpha = m_knobAlpha - 0.2;
if (alpha > 0) {
m_knobAlpha = alpha;
[objcScrollBar setNeedsDisplay: YES];
}
else
{
[m_fadeTimer invalidate];
m_fadeTimer = nullptr;
}
}
virtual void cursor_entering(const gfx::point& pt)
{
suppress_fade();
nsview_pane::cursor_entering(pt);
}
virtual void cursor_leaving()
{
unsuppress_fade();
nsview_pane::cursor_leaving();
}
};
inline std::pair<rcref<gui::bridgeable_pane>, rcref<gui::scroll_bar_interface> > nsview_subsystem::create_scroll_bar() volatile
{
rcref<scroll_bar> sb = rcnew(scroll_bar)(this_rcref);
return std::make_pair(sb, sb);
}
}
}
#ifdef COGS_OBJECTIVE_C_CODE
@implementation objc_scroll_bar
-(BOOL)isFlipped
{
return YES;
}
-(void)scrolled:(id)sender
{
cogs::rcptr<cogs::os::scroll_bar> cppScrollBar = m_cppScrollBar;
if (!!cppScrollBar)
cppScrollBar->scrolled();
}
-(void)preferredScrollerStyleChanged:(NSNotification*)notification
{
cogs::rcptr<cogs::os::scroll_bar> cppScrollBar = m_cppScrollBar;
if (!!cppScrollBar)
{
NSScrollerStyle scrollerStyle = [NSScroller preferredScrollerStyle];
cppScrollBar->set_can_auto_fade(scrollerStyle == NSScrollerStyleOverlay);
}
}
+(BOOL)isCompatibleWithOverlayScrollers
{
return YES;
}
-(void)drawKnob
{
cogs::rcptr<cogs::os::scroll_bar> cppScrollBar = m_cppScrollBar;
if (!!cppScrollBar)
cppScrollBar->drawKnob();
else
[super drawKnob];
}
-(void)defaultDrawKnob
{
[super drawKnob];
}
-(void)drawKnobSlotInRect:(NSRect)slotRect highlight:(BOOL)flag
{
cogs::rcptr<cogs::os::scroll_bar> cppScrollBar = m_cppScrollBar;
if (!!cppScrollBar)
cppScrollBar->drawKnobSlotInRect(slotRect, flag);
else
[super drawKnobSlotInRect:slotRect highlight:flag];
}
-(void)defaultDrawKnobSlotInRect:(NSRect)slotRect highlight:(BOOL)flag
{
[super drawKnobSlotInRect:slotRect highlight:flag];
}
-(void)drawRect:(NSRect)dirtyRect
{
[super drawRect:dirtyRect];
}
-(void)fade:(NSTimer*)timer
{
cogs::rcptr<cogs::os::scroll_bar> cppScrollBar = m_cppScrollBar;
if (!!cppScrollBar)
cppScrollBar->fade();
}
@end
#endif
#endif
| 24.075503
| 180
| 0.716008
|
cogmine
|
7d7f75355ff8f074d94ef4a92ad36d3fe50d55c9
| 48
|
hpp
|
C++
|
src/boost_preprocessor_list_to_tuple.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_preprocessor_list_to_tuple.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_preprocessor_list_to_tuple.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/preprocessor/list/to_tuple.hpp>
| 24
| 47
| 0.8125
|
miathedev
|
7d7fb8c2d059d53e033a0ebb83481f72df87ebd5
| 57,296
|
cpp
|
C++
|
src/drivers/cosmica.cpp
|
pierrelouys/PSP-MAME4ALL
|
54374b0579b7e2377f015ac155d8f519addfaa1a
|
[
"Unlicense"
] | 1
|
2021-01-25T20:16:33.000Z
|
2021-01-25T20:16:33.000Z
|
src/drivers/cosmica.cpp
|
pierrelouys/PSP-MAME4ALL
|
54374b0579b7e2377f015ac155d8f519addfaa1a
|
[
"Unlicense"
] | 1
|
2021-05-24T20:28:35.000Z
|
2021-05-25T14:44:54.000Z
|
src/drivers/cosmica.cpp
|
PSP-Archive/PSP-MAME4ALL
|
54374b0579b7e2377f015ac155d8f519addfaa1a
|
[
"Unlicense"
] | null | null | null |
/*Se anula todo lo referente a Space Panic y Cosmic Guerrilla*/
/***************************************************************************
Space Panic memory map
0000-3FFF ROM
4000-5BFF Video RAM (Bitmap)
5C00-5FFF RAM
6000-601F Sprite Controller
4 bytes per sprite
byte 1 - 80 = ?
40 = Rotate sprite left/right
3F = Sprite Number (Conversion to my layout via table)
byte 2 - X co-ordinate
byte 3 - Y co-ordinate
byte 4 - 08 = Switch sprite bank
07 = Colour
6800 IN1 - Player controls. See input port setup for mappings
6801 IN2 - Player 2 controls for cocktail mode. See input port setup for mappings.
6802 DSW - Dip switches
6803 IN0 - Coinage and player start
700C-700E Colour Map Selector
(Not Implemented)
7000-700B Various triggers, Sound etc
700F Ditto
7800 80 = Flash Screen?
I/O ports:
read:
write:
***************************************************************************/
#include "driver.h"
#include "vidhrdw/generic.h"
#include "z80/z80.h"
/**************************************************/
/* Cosmic routines */
/**************************************************/
int PixelClock = 0;
extern unsigned char *cosmic_videoram;
void cosmic_videoram_w(int offset,int data);
void cosmic_flipscreen_w(int offset, int data);
int cosmic_vh_start(void);
void cosmic_vh_stop(void);
void cosmic_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
void cosmic_vh_screenrefresh_sprites(struct osd_bitmap *bitmap,int full_refresh);
//static struct MemoryReadAddress readmem[] =
//{
// { 0x4000, 0x5FFF, MRA_RAM },
// { 0x0000, 0x3fff, MRA_ROM },
// { 0x6800, 0x6800, input_port_0_r }, /* IN1 */
// { 0x6801, 0x6801, input_port_1_r }, /* IN2 */
// { 0x6802, 0x6802, input_port_2_r }, /* DSW */
// { 0x6803, 0x6803, input_port_3_r }, /* IN0 */
// { -1 } /* end of table */
//};
static struct DACinterface dac_interface =
{
1,
{ 100 }
};
/* Se anula porque da error
static struct Samplesinterface samples_interface =
{
9, /* 9 channels * /
25 /* volume * /
}; Fin Se anula porque da error*/
/**************************************************/
/* Space Panic specific routines */
/************************************************** /
void panic_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
void panic_colourmap_select(int offset,int data);
int panic_interrupt(void);
static struct MemoryWriteAddress panic_writemem[] =
{
{ 0x4000, 0x43FF, MWA_RAM },
{ 0x4400, 0x5BFF, cosmic_videoram_w, &cosmic_videoram },
{ 0x5C00, 0x5FFF, MWA_RAM },
{ 0x6000, 0x601F, MWA_RAM, &spriteram, &spriteram_size },
{ 0x0000, 0x3fff, MWA_ROM },
{ 0x700C, 0x700E, panic_colourmap_select },
{ -1 } /* end of table * /
};
INPUT_PORTS_START( input_ports )
PORT_START /* IN1 * /
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_START /* IN2 * /
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL )
PORT_START /* DSW * /
PORT_DIPNAME( 0x07, 0x00, "Coin_A", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "1C_1C" )
PORT_DIPSETTING( 0x05, "2C_3C" )
PORT_DIPSETTING( 0x01, "1C_2C" )
PORT_DIPSETTING( 0x02, "1C_3C" )
PORT_DIPSETTING( 0x03, "1C_4C" )
PORT_DIPSETTING( 0x04, "1C_5C" )
/* 0x06 and 0x07 disabled * /
PORT_DIPNAME( 0x08, 0x00, "Cabinet", IP_KEY_NONE)
PORT_DIPSETTING( 0x00, "Upright" )
PORT_DIPSETTING( 0x08, "Cocktail" )
PORT_DIPNAME( 0x10, 0x00, "Bonus_Life", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "3000" )
PORT_DIPSETTING( 0x10, "5000" )
PORT_DIPNAME( 0x20, 0x00, "Lives", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "3" )
PORT_DIPSETTING( 0x20, "4" )
PORT_DIPNAME( 0xc0, 0x40, "Coin_B", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "2C_1C" )
PORT_DIPSETTING( 0x40, "1C_1C" )
PORT_DIPSETTING( 0x80, "1C_2C" )
PORT_DIPSETTING( 0xc0, "1C_3C" )
PORT_START /* IN0 * /
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN2 )
INPUT_PORTS_END
/* Main Sprites * /
static struct GfxLayout panic_spritelayout0 =
{
16,16, /* 16*16 sprites *
48 , /* 64 sprites * /
2, /* 2 bits per pixel * /
{ 4096*8, 0 }, /* the two bitplanes are separated /
{ 0,1,2,3,4,5,6,7,16*8+0,16*8+1,16*8+2,16*8+3,16*8+4,16*8+5,16*8+6,16*8+7 },
{ 15*8, 14*8, 13*8, 12*8, 11*8, 10*8, 9*8, 8*8, 7*8, 6*8, 5*8, 4*8, 3*8, 2*8, 1*8, 0*8 },
32*8 /* every sprite takes 32 consecutive bytes * /
};
/* Man Top * /
static struct GfxLayout panic_spritelayout1 =
{
16,16, /* 16*16 sprites * /
16 , /* 16 sprites * /
2, /* 2 bits per pixel * /
{ 4096*8, 0 }, /* the two bitplanes are separated * /
{ 0,1,2,3,4,5,6,7,16*8+0,16*8+1,16*8+2,16*8+3,16*8+4,16*8+5,16*8+6,16*8+7 },
{ 15*8, 14*8, 13*8, 12*8, 11*8, 10*8, 9*8, 8*8, 7*8, 6*8, 5*8, 4*8, 3*8, 2*8, 1*8, 0*8 },
32*8 /* every sprite takes 32 consecutive bytes * /
};
static struct GfxDecodeInfo panic_gfxdecodeinfo[] =
{
{ 1, 0x0A00, &panic_spritelayout0, 0, 8 }, /* Monsters * /
{ 1, 0x0200, &panic_spritelayout0, 0, 8 }, /* Monsters eating Man * /
{ 1, 0x0800, &panic_spritelayout1, 0, 8 }, /* Man * /
{ -1 } /* end of array * /
};
static struct MachineDriver panic_machine_driver =
{
/* basic machine hardware * /
{
{
CPU_Z80,
2000000, /* 2 Mhz? * /
0,
readmem,panic_writemem,0,0,
panic_interrupt,2
}
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration * /
1, /* single CPU, no need for interleaving * /
0,
/* video hardware * /
32*8, 24*8, { 0*8, 32*8-1, 0*8, 24*8-1 },
panic_gfxdecodeinfo,
16, 8*4,
panic_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY,
0,
cosmic_vh_start,
cosmic_vh_stop,
cosmic_vh_screenrefresh,
/* sound hardware * /
0,0,0,0
};
static int panic_hiload(void)
{
unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region];
/* wait for default to be copied * /
if (RAM[0x40c1] == 0x00 && RAM[0x40c2] == 0x03 && RAM[0x40c3] == 0x04)
{
void *f;
if ((f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,0)) != 0)
{
RAM[0x4004] = 0x01; /* Prevent program resetting high score * /
osd_fread(f,&RAM[0x40C1],5);
osd_fread(f,&RAM[0x5C00],12);
osd_fclose(f);
}
return 1;
}
else return 0; /* we can't load the hi scores yet * /
}
static void panic_hisave(void)
{
void *f;
unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region];
if ((f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,1)) != 0)
{
osd_fwrite(f,&RAM[0x40C1],5);
osd_fwrite(f,&RAM[0x5C00],12);
osd_fclose(f);
}
}
int panic_interrupt(void)
{
static int count=0;
count++;
if (count == 1)
{
return 0x00cf; /* RST 08h * /
}
else
{
count=0;
return 0x00d7; /* RST 10h * /
}
}
ROM_START( panic_rom )
ROM_REGION(0x10000) /* 64k for code * /
ROM_LOAD( "spcpanic.1", 0x0000, 0x0800, 0x405ae6f9 ) /* Code * /
ROM_LOAD( "spcpanic.2", 0x0800, 0x0800, 0xb6a286c5 )
ROM_LOAD( "spcpanic.3", 0x1000, 0x0800, 0x85ae8b2e )
ROM_LOAD( "spcpanic.4", 0x1800, 0x0800, 0xb6d4f52f )
ROM_LOAD( "spcpanic.5", 0x2000, 0x0800, 0x5b80f277 )
ROM_LOAD( "spcpanic.6", 0x2800, 0x0800, 0xb73babf0 )
ROM_LOAD( "spcpanic.7", 0x3000, 0x0800, 0xfc27f4e5 )
ROM_REGION_DISPOSE(0x2000) /* temporary space for graphics (disposed after conversion) * /
ROM_LOAD( "spcpanic.9", 0x0000, 0x0800, 0xeec78b4c )
ROM_LOAD( "spcpanic.10", 0x0800, 0x0800, 0xc9631c2d )
ROM_LOAD( "spcpanic.12", 0x1000, 0x0800, 0xe83423d0 )
ROM_LOAD( "spcpanic.11", 0x1800, 0x0800, 0xacea9df4 )
ROM_REGION(0x0820) /* color PROMs * /
ROM_LOAD( "82s123.sp", 0x0000, 0x0020, 0x35d43d2f )
ROM_LOAD( "spcpanic.8", 0x0020, 0x0800, 0x7da0b321 )
ROM_END
ROM_START( panica_rom )
ROM_REGION(0x10000) /* 64k for code * /
ROM_LOAD( "panica.1", 0x0000, 0x0800, 0x289720ce ) /* Code * /
ROM_LOAD( "spcpanic.2", 0x0800, 0x0800, 0xb6a286c5 )
ROM_LOAD( "spcpanic.3", 0x1000, 0x0800, 0x85ae8b2e )
ROM_LOAD( "spcpanic.4", 0x1800, 0x0800, 0xb6d4f52f )
ROM_LOAD( "spcpanic.5", 0x2000, 0x0800, 0x5b80f277 )
ROM_LOAD( "spcpanic.6", 0x2800, 0x0800, 0xb73babf0 )
ROM_LOAD( "panica.7", 0x3000, 0x0800, 0x3641cb7f )
ROM_REGION_DISPOSE(0x2000) /* temporary space for graphics (disposed after conversion) * /
ROM_LOAD( "spcpanic.9", 0x0000, 0x0800, 0xeec78b4c )
ROM_LOAD( "spcpanic.10", 0x0800, 0x0800, 0xc9631c2d )
ROM_LOAD( "spcpanic.12", 0x1000, 0x0800, 0xe83423d0 )
ROM_LOAD( "spcpanic.11", 0x1800, 0x0800, 0xacea9df4 )
ROM_REGION(0x0820) /* color PROMs * /
ROM_LOAD( "82s123.sp", 0x0000, 0x0020, 0x35d43d2f )
ROM_LOAD( "spcpanic.8", 0x0020, 0x0800, 0x7da0b321 )
ROM_END
ROM_START( panicger_rom )
ROM_REGION(0x10000) /* 64k for code * /
ROM_LOAD( "spacepan.001", 0x0000, 0x0800, 0xa6d9515a ) /* Code * /
ROM_LOAD( "spacepan.002", 0x0800, 0x0800, 0xcfc22663 )
ROM_LOAD( "spacepan.003", 0x1000, 0x0800, 0xe1f36893 )
ROM_LOAD( "spacepan.004", 0x1800, 0x0800, 0x01be297c )
ROM_LOAD( "spacepan.005", 0x2000, 0x0800, 0xe0d54805 )
ROM_LOAD( "spacepan.006", 0x2800, 0x0800, 0xaae1458e )
ROM_LOAD( "spacepan.007", 0x3000, 0x0800, 0x14e46e70 )
ROM_REGION_DISPOSE(0x2000) /* temporary space for graphics (disposed after conversion) * /
ROM_LOAD( "spcpanic.9", 0x0000, 0x0800, 0xeec78b4c )
ROM_LOAD( "spcpanic.10", 0x0800, 0x0800, 0xc9631c2d )
ROM_LOAD( "spcpanic.12", 0x1000, 0x0800, 0xe83423d0 )
ROM_LOAD( "spcpanic.11", 0x1800, 0x0800, 0xacea9df4 )
ROM_REGION(0x0820) /* color PROMs * /
ROM_LOAD( "82s123.sp", 0x0000, 0x0020, 0x35d43d2f )
ROM_LOAD( "spcpanic.8", 0x0020, 0x0800, 0x7da0b321 )
ROM_END
struct GameDriver panic_driver =
{
__FILE__,
0,
"panic",
"Space Panic (set 1)",
"1980",
"Universal",
"Mike Coates (MAME driver)\nMarco Cassili",
0,
&panic_machine_driver,
0,
panic_rom,
0, 0,
0,
0, /* sound_prom * /
input_ports,
PROM_MEMORY_REGION(2), 0, 0,
ORIENTATION_ROTATE_270,
panic_hiload, panic_hisave
};
struct GameDriver panica_driver =
{
__FILE__,
&panic_driver,
"panica",
"Space Panic (set 2)",
"1980",
"Universal",
"Mike Coates (MAME driver)\nMarco Cassili",
0,
&panic_machine_driver,
0,
panica_rom,
0, 0,
0,
0, /* sound_prom * /
input_ports,
PROM_MEMORY_REGION(2), 0, 0,
ORIENTATION_ROTATE_270,
panic_hiload, panic_hisave
};
struct GameDriver panicger_driver =
{
__FILE__,
&panic_driver,
"panicger",
"Space Panic (German)",
"1980",
"Universal (ADP Automaten license)",
"Mike Coates (MAME driver)\nMarco Cassili",
0,
&panic_machine_driver,
0,
panicger_rom,
0, 0,
0,
0, /* sound_prom * /
input_ports,
PROM_MEMORY_REGION(2), 0, 0,
ORIENTATION_ROTATE_270,
panic_hiload, panic_hisave
};
/**************************************************/
/* Cosmic Alien specific routines */
/**************************************************/
void cosmicalien_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
void cosmicalien_colourmap_select(int offset,int data);
int cosmicalien_interrupt(void)
{
PixelClock = (PixelClock + 2) & 63;
if (PixelClock == 0)
{
if (readinputport(3) & 1) /* Left Coin */
return nmi_interrupt();
else
return ignore_interrupt();
}
else
return ignore_interrupt();
}
int cosmicalien_video_address_r(int offset)
{
return PixelClock;
}
static struct MemoryReadAddress cosmicalien_readmem[] =
{
{ 0x4000, 0x5FFF, MRA_RAM },
{ 0x0000, 0x3fff, MRA_ROM },
{ 0x6800, 0x6800, input_port_0_r }, /* IN1 */
{ 0x6801, 0x6801, input_port_1_r }, /* IN2 */
{ 0x6802, 0x6802, input_port_2_r }, /* DSW */
{ 0x6803, 0x6803, cosmicalien_video_address_r },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress cosmicalien_writemem[] =
{
{ 0x4000, 0x43ff, MWA_RAM },
{ 0x4400, 0x5bff, cosmic_videoram_w, &cosmic_videoram},
{ 0x5c00, 0x5fff, MWA_RAM },
{ 0x6000, 0x601f, MWA_RAM ,&spriteram, &spriteram_size },
{ 0x7000, 0x700B, MWA_RAM }, /* Sound Triggers */
{ 0x700C, 0x700C, cosmicalien_colourmap_select },
{ -1 } /* end of table */
};
INPUT_PORTS_START( cosmicalien_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_2WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_2WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_2WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_2WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN2 */
PORT_DIPNAME( 0x01, 0x00, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "Upright" )
PORT_DIPSETTING( 0x01, "Cocktail" )
PORT_DIPNAME( 0x02, 0x02, "Lives", IP_KEY_NONE )
PORT_DIPSETTING( 0x02, "3" )
PORT_DIPSETTING( 0x00, "5" )
PORT_DIPNAME( 0x0c, 0x00, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0x08, "2C_1C" )
PORT_DIPSETTING( 0x00, "1C_1C" )
PORT_DIPSETTING( 0x04, "1C_2C" )
/* 0c gives 1C_1C */
PORT_DIPNAME( 0x30, 0x30, "Bonus_Life", IP_KEY_NONE )
PORT_DIPSETTING( 0x30, "5000" )
PORT_DIPSETTING( 0x20, "10000" )
PORT_DIPSETTING( 0x10, "15000" )
PORT_DIPSETTING( 0x00, "None" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
/* The coin slots are not memory mapped. Coin causes a NMI, */
/* This fake input port is used by the interrupt */
/* handler to be notified of coin insertions. We use IMPULSE to */
/* trigger exactly one interrupt, without having to check when the */
/* user releases the key. */
PORT_START /* FAKE */
PORT_BITX(0x01, IP_ACTIVE_HIGH, IPT_COIN1 | IPF_IMPULSE,
"Coin", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 1 )
INPUT_PORTS_END
static struct GfxLayout cosmicalien_spritelayout16 =
{
16,16, /* 16*16 sprites */
64, /* 64 sprites */
2, /* 2 bits per pixel */
{ 0, 64*16*16 }, /* the two bitplanes are separated */
{ 0,1,2,3,4,5,6,7,16*8+0,16*8+1,16*8+2,16*8+3,16*8+4,16*8+5,16*8+6,16*8+7},
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 },
32*8 /* every sprite takes 32 consecutive bytes */
};
static struct GfxLayout cosmicalien_spritelayout32 =
{
32,32, /* 32*32 sprites */
16, /* 16 sprites */
2, /* 2 bits per pixel */
{ 0, 64*16*16 }, /* the two bitplanes are separated */
{ 0,1,2,3,4,5,6,7,
32*8+0, 32*8+1, 32*8+2, 32*8+3, 32*8+4, 32*8+5, 32*8+6, 32*8+7,
64*8+0, 64*8+1, 64*8+2, 64*8+3, 64*8+4, 64*8+5, 64*8+6, 64*8+7,
96*8+0, 96*8+1, 96*8+2, 96*8+3, 96*8+4, 96*8+5, 96*8+6, 96*8+7 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8, 16*8, 17*8,18*8,19*8,20*8,21*8,22*8,23*8,24*8,25*8,26*8,27*8,28*8,29*8,30*8,31*8 },
128*8 /* every sprite takes 128 consecutive bytes */
};
static struct GfxDecodeInfo cosmicalien_gfxdecodeinfo[] =
{
{ 1, 0x0000, &cosmicalien_spritelayout16, 0, 8 },
{ 1, 0x0000, &cosmicalien_spritelayout32, 0, 8 },
{ -1 } /* end of array */
};
/* HSC 12/02/98 */
static int cosmicalienhiload(void)
{
static int firsttime = 0;
unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region];
/* check if the hi score table has already been initialized */
/* the high score table is intialized to all 0, so first of all */
/* we dirty it, then we wait for it to be cleared again */
if (firsttime == 0)
{
fast_memset(&RAM[0x400e],0xff,4); /* high score */
firsttime = 1;
}
/* check if the hi score table has already been initialized */
if (memcmp(&RAM[0x400e],"\x00\x00\x00",3) == 0 )
{
void *f;
if ((f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,0)) != 0)
{
osd_fread(f,&RAM[0x400e],3);
osd_fclose(f);
}
firsttime = 0;
return 1;
}
else return 0; /* we can't load the hi scores yet */
}
static void cosmicalienhisave(void)
{
void *f;
unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region];
if ((f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,1)) != 0)
{
osd_fwrite(f,&RAM[0x400e],3);
osd_fclose(f);
}
}
static struct MachineDriver cosmicalien_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
1081600,
0,
cosmicalien_readmem,cosmicalien_writemem,0,0,
cosmicalien_interrupt,32
}
},
60, 2500, /* frames per second, vblank duration */
1, /* single CPU, no need for interleaving */
0,
/* video hardware */
32*8, 24*8, { 0*8, 32*8-1, 0*8, 24*8-1 },
cosmicalien_gfxdecodeinfo,
8, 16*4,
cosmicalien_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY,
0,
cosmic_vh_start,
cosmic_vh_stop,
cosmic_vh_screenrefresh_sprites,
/* sound hardware */
0,0,0,0
};
ROM_START( cosmicalien_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "r1", 0x0000, 0x0800, 0x535ee0c5 )
ROM_LOAD( "r2", 0x0800, 0x0800, 0xed3cf8f7 )
ROM_LOAD( "r3", 0x1000, 0x0800, 0x6a111e5e )
ROM_LOAD( "r4", 0x1800, 0x0800, 0xc9b5ca2a )
ROM_LOAD( "r5", 0x2000, 0x0800, 0x43666d68 )
ROM_REGION_DISPOSE(0x1000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "r6", 0x0000, 0x0800, 0x431e866c )
ROM_LOAD( "r7", 0x0800, 0x0800, 0xaa6c6079 )
ROM_REGION(0x0420) /* color PROMs */
ROM_LOAD( "bpr1", 0x0000, 0x0020, 0xdfb60f19 )
ROM_LOAD( "r9", 0x0020, 0x0400, 0xea4ee931 )
ROM_END
struct GameDriver cosmica_driver =
{
__FILE__,
0,
"cosmica",
"Cosmic Alien",
"1980",
"Universal",
"Lee Taylor",
0,
&cosmicalien_machine_driver,
0,
cosmicalien_rom,
0, 0,
0,
0, /* sound_prom */
cosmicalien_input_ports,
PROM_MEMORY_REGION(2), 0, 0,
ORIENTATION_ROTATE_270,
cosmicalienhiload, cosmicalienhisave /* hsc 12/02/98 */
};
/*************************************************************************/
/* Cosmic Guerilla specific routines */
/*************************************************************************/
/* 0000-03FF ROM COSMICG.1 */
/* 0400-07FF ROM COSMICG.2 */
/* 0800-0BFF ROM COSMICG.3 */
/* 0C00-0FFF ROM COSMICG.4 */
/* 1000-13FF ROM COSMICG.5 */
/* 1400-17FF ROM COSMICG.6 */
/* 1800-1BFF ROM COSMICG.7 */
/* 1C00-1FFF ROM COSMICG.8 - Graphics */
/* */
/* 2000-23FF RAM */
/* 2400-3FEF Screen RAM */
/* 3FF0-3FFF CRT Controller registers (3FF0, register, 3FF4 Data) */
/* */
/* CRTC data */
/* ROM COSMICG.9 - Color Prom */
/* */
/* CR Bits (Inputs) */
/* 0000-0003 A9-A13 from CRTC Pixel Clock */
/* 0004-000B Controls */
/* 000C-000F Dip Switches */
/* */
/* CR Bits (Outputs) */
/* 0016-0017 Colourmap Selector */
/************************************************************************* /
void cosmicguerilla_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
void cosmicguerilla_output_w(int offset, int data);
void cosmicguerilla_colourmap_select(int offset,int data);
int cosmicguerilla_read_pixel_clock(int offset);
static struct MemoryReadAddress cosmicguerilla_readmem[] =
{
{ 0x2000, 0x3fff, MRA_RAM},
{ 0x0000, 0x1fff, MRA_ROM},
{ -1 } /* end of table * /
};
static struct MemoryWriteAddress cosmicguerilla_writemem[] =
{
{ 0x2000, 0x23ff, MWA_RAM },
{ 0x2400, 0x3bff, cosmic_videoram_w, &cosmic_videoram },
{ 0x3C00, 0x3fff, MWA_RAM },
{ 0x0000, 0x1fff, MWA_ROM },
{ -1 } /* end of table * /
};
/*static const char *cosmicguerilla_sample_names[] =
{
"*cosmicg",
"cg_m0.wav", /* 8 Different pitches of March Sound * /
"cg_m1.wav",
"cg_m2.wav",
"cg_m3.wav",
"cg_m4.wav",
"cg_m5.wav",
"cg_m6.wav",
"cg_m7.wav",
"cg_att.wav", /* Killer Attack * /
"cg_chnc.wav", /* Bonus Chance * /
"cg_gotb.wav", /* Got Bonus - have not got correct sound for * /
"cg_dest.wav", /* Gun Destroy * /
"cg_gun.wav", /* Gun Shot * /
"cg_gotm.wav", /* Got Monster * /
"cg_ext.wav", /* Coin Extend * /
0 /* end of array * /
};
* /
static struct IOReadPort cosmicguerilla_readport[] =
{
{ 0x00, 0x00, cosmicguerilla_read_pixel_clock },
{ 0x01, 0x01, input_port_1_r },
{ -1 } /* end of table * /
};
static struct IOWritePort cosmicguerilla_writeport[] =
{
{ 0x00, 0x15, cosmicguerilla_output_w },
{ 0x16, 0x17, cosmicguerilla_colourmap_select },
{ -1 } /* end of table * /
};
/***********eliminamos por ahora***************** /
void cosmicguerilla_output_w(int offset, int data)
{/*
static int MarchSelect;
static int GunDieSelect;
static int SoundEnable;
int Count;
/* Sound Enable / Disable * /
if (offset == 12)
{
SoundEnable = data;
if (data == 0)
for(Count=0;Count<9;Count++) sample_stop(Count);
}
if (SoundEnable)
{
switch (offset)
{
/* The schematics show a direct link to the sound amp */
/* as other cosmic series games, but it never seems to */
/* be used for anything. It is implemented for sake of */
/* completness. Maybe it plays a tune if you win ? * /
case 1 : DAC_data_w(0, -data);
break;
/* March Sound * /
case 2 : if (errorlog) fprintf(errorlog,"March = %d\n",MarchSelect);
if (data) sample_start (0, MarchSelect, 0);
break;
case 3 : MarchSelect = (MarchSelect & 0xFE) | data;
break;
case 4 : MarchSelect = (MarchSelect & 0xFD) | (data << 1);
break;
case 5 : MarchSelect = (MarchSelect & 0xFB) | (data << 2);
break;
/* Killer Attack (crawly thing at bottom of screen) * /
case 6 : if (data)
sample_start(1, 8, 1);
else
sample_stop(1);
break;
/* Bonus Chance & Got Bonus * /
case 7 : if (data)
{
sample_stop(4);
sample_start(4, 10, 0);
}
break;
case 8 : if (data)
{
if (!sample_playing(4)) sample_start(4, 9, 1);
}
else
sample_stop(4);
break;
/* Got Ship * /
case 9 : if (data) sample_start(3, 11, 0);
break;
case 11: /* Watchdog * /
break;
/* Got Monster / Gunshot * /
case 13: if (data) sample_start(8, 13-GunDieSelect, 0);
break;
case 14: GunDieSelect = data;
break;
/* Coin Extend (extra base) * /
case 15: if (data) sample_start(5, 14, 0);
break;
}
}
if((errorlog) && (offset != 11))
fprintf(errorlog,"Output %x=%x\n",offset,data);* /
}
/***********************fin eliminacion*********************** /
int cosmicguerilla_read_pixel_clock(int offset)
{
/* The top four address lines from the CRTC are bits 0-3 * /
return (input_port_0_r(0) & 0xf0) | PixelClock;
}
int cosmicguerilla_interrupt(void)
{
/* Increment Pixel Clock * /
PixelClock = (PixelClock + 1) & 15;
/* Insert Coin * /
if ((readinputport(2) & 1) & (PixelClock == 0)) /* Coin * /
{
return 4;
}
else
{
return ignore_interrupt();
}
}
static void cosmicguerilla_decode(void)
{
/* Roms have data pins connected different from normal * /
int Count;
unsigned char Scrambled,Normal;
for(Count=0x1fff;Count>=0;Count--)
{
Scrambled = Machine->memory_region[0][Count];
Normal = (Scrambled >> 3 & 0x11)
| (Scrambled >> 1 & 0x22)
| (Scrambled << 1 & 0x44)
| (Scrambled << 3 & 0x88);
Machine->memory_region[0][Count] = Normal;
}
/* Patch to avoid crash - Seems like duff romcheck routine */
/* I would expect it to be bitrot, but have two romsets */
/* from different sources with the same problem! * /
Machine->memory_region[0][0x1e9e] = 0x04;
Machine->memory_region[0][0x1e9f] = 0xc0;
}
/* These are used for the CR handling - This can be used to */
/* from 1 to 16 bits from any bit offset between 0 and 4096 */
/* Offsets are in BYTES, so bits 0-7 are at offset 0 etc. * /
INPUT_PORTS_START( cosmicguerilla_input_ports )
PORT_START /* 4-7 * /
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_2WAY )
PORT_START /* 8-15 * /
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_2WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_2WAY | IPF_COCKTAIL)
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_2WAY | IPF_COCKTAIL)
PORT_DIPNAME( 0x30, 0x30, "Bonus_Life", IP_KEY_NONE )
PORT_DIPSETTING( 0x10, "1000" )
PORT_DIPSETTING( 0x20, "1500" )
PORT_DIPSETTING( 0x30, "2000" )
PORT_DIPSETTING( 0x00, "None" )
PORT_DIPNAME( 0x40, 0x00, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0x40, "2C_1C" )
PORT_DIPSETTING( 0x00, "1C_1C" )
PORT_DIPNAME( 0x80, 0x00, "Lives", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "3" )
PORT_DIPSETTING( 0x80, "5" )
PORT_START /* Hard wired settings */
/* The coin slots are not memory mapped. Coin causes INT 4 */
/* This fake input port is used by the interrupt handler */
/* to be notified of coin insertions. We use IMPULSE to */
/* trigger exactly one interrupt, without having to check */
/* when the user releases the key. * /
PORT_BITX(0x01, IP_ACTIVE_HIGH, IPT_COIN1 | IPF_IMPULSE,
"Coin", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 1 )
/* This dip switch is not read by the program at any time */
/* but is wired to enable or disable the flip screen output * /
PORT_DIPNAME( 0x02, 0x00, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "Upright" )
PORT_DIPSETTING( 0x02, "Cocktail" )
/* This odd setting is marked as shown on the schematic, */
/* and again, is not read by the program, but wired into */
/* the watchdog circuit. The book says to leave it off * /
PORT_DIPNAME( 0x04, 0x00, "Unused", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "Off" )
PORT_DIPSETTING( 0x04, "On" )
INPUT_PORTS_END
static int cosmicguerillahiload(void)
{
static int firsttime = 0;
unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region];
/* check if the hi score table has already been initialized */
/* the high score table is intialized to all 0, so first of all */
/* we dirty it, then we wait for it to be cleared again * /
if (firsttime == 0)
{
fast_memset(&RAM[0x3c10],0xff,4); /* high score * /
firsttime = 1;
}
/* check if the hi score table has already been initialized * /
if (memcmp(&RAM[0x3c10],"\x00\x00\x00\x00",4) == 0 )
{
void *f;
if ((f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,0)) != 0)
{
osd_fread(f,&RAM[0x3c10],4);
osd_fclose(f);
}
firsttime = 0;
return 1;
}
else return 0; /* we can't load the hi scores yet * /
}
static void cosmicguerillahisave(void)
{
void *f;
unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region];
if ((f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,1)) != 0)
{
osd_fwrite(f,&RAM[0x3c10],4);
osd_fclose(f);
}
}
static struct MachineDriver cosmicguerilla_machine_driver =
{
/* basic machine hardware * /
{
{
CPU_TMS9900,
1228500, /* 9.828 Mhz Crystal * /
0,
cosmicguerilla_readmem,cosmicguerilla_writemem,
cosmicguerilla_readport,cosmicguerilla_writeport,
cosmicguerilla_interrupt,16
}
},
60, 0, /* frames per second, vblank duration * /
1, /* single CPU, no need for interleaving * /
0,
/* video hardware * /
32*8, 24*8, { 0*8, 32*8-1, 0*8, 24*8-1 },
0, /* no gfxdecodeinfo - bitmapped display * /
16,8*4,
cosmicguerilla_vh_convert_color_prom,
VIDEO_TYPE_RASTER,
0,
cosmic_vh_start,
cosmic_vh_stop,
cosmic_vh_screenrefresh,
/* sound hardware * /
0,0,0,0/*,
{
/*{
SOUND_SAMPLES,
&samples_interface
},* /
{
SOUND_DAC,
&dac_interface
}
}* /
};
ROM_START( cosmicguerilla_rom )
ROM_REGION(0x10000) /* 8k for code * /
ROM_LOAD( "cosmicg1.bin", 0x0000, 0x0400, 0xe1b9f894 )
ROM_LOAD( "cosmicg2.bin", 0x0400, 0x0400, 0x35c75346 )
ROM_LOAD( "cosmicg3.bin", 0x0800, 0x0400, 0x82a49b48 )
ROM_LOAD( "cosmicg4.bin", 0x0C00, 0x0400, 0x1c1c934c )
ROM_LOAD( "cosmicg5.bin", 0x1000, 0x0400, 0xb1c00fbf )
ROM_LOAD( "cosmicg6.bin", 0x1400, 0x0400, 0xf03454ce )
ROM_LOAD( "cosmicg7.bin", 0x1800, 0x0400, 0xf33ebae7 )
ROM_LOAD( "cosmicg8.bin", 0x1C00, 0x0400, 0x472e4990 )
ROM_REGION(0x0400) /* Colour Prom * /
ROM_LOAD( "cosmicg9.bin", 0x0000, 0x0400, 0x689c2c96 )
ROM_END
struct GameDriver cosmicg_driver =
{
__FILE__,
0,
"cosmicg",
"Cosmic Guerilla",
"1979",
"Universal",
"Andy Jones\nMike Coates",
0,
&cosmicguerilla_machine_driver,
0,
cosmicguerilla_rom,
cosmicguerilla_decode, 0,
0, /*cosmicguerilla_sample_names,* /
0, /* sound_prom * /
cosmicguerilla_input_ports,
PROM_MEMORY_REGION(1), 0, 0,
ORIENTATION_ROTATE_270,
cosmicguerillahiload, cosmicguerillahisave
};
/***************************************************************************
Magical Spot 2 memory map (preliminary)
0000-2fff ROM
6000-63ff RAM
6400-7fff Video RAM
read:
write:
***************************************************************************/
void magspot2_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
void magspot2_colourmap_w(int offset, int data);
static int magspot2_interrupt(void)
{
/* Coin 1 causes an IRQ, Coin 2 an NMI */
if (input_port_4_r(0) & 0x01)
{
return interrupt();
}
if (input_port_4_r(0) & 0x02)
{
return nmi_interrupt();
}
return ignore_interrupt();
}
static int magspot2_coinage_dip_r(int offset)
{
return (input_port_5_r(0) & (1 << (7 - offset))) ? 0 : 1;
}
static struct MemoryReadAddress magspot2_readmem[] =
{
{ 0x0000, 0x2fff, MRA_ROM },
{ 0x3800, 0x3807, magspot2_coinage_dip_r },
{ 0x5000, 0x5000, input_port_0_r },
{ 0x5001, 0x5001, input_port_1_r },
{ 0x5002, 0x5002, input_port_2_r },
{ 0x5003, 0x5003, input_port_3_r },
{ 0x6000, 0x7fff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress magspot2_writemem[] =
{
{ 0x0000, 0x2fff, MWA_ROM },
{ 0x4000, 0x401f, MWA_RAM, &spriteram, &spriteram_size},
{ 0x4800, 0x4800, DAC_data_w },
{ 0x480D, 0x480D, magspot2_colourmap_w },
{ 0x480F, 0x480F, cosmic_flipscreen_w },
{ 0x6000, 0x63ff, MWA_RAM },
{ 0x6400, 0x7bff, cosmic_videoram_w, &cosmic_videoram, &videoram_size},
{ 0x7c00, 0x7fff, MWA_RAM },
{ -1 } /* end of table */
};
INPUT_PORTS_START( magspot2_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_2WAY )
PORT_BIT( 0x1c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_2WAY )
PORT_DIPNAME( 0xc0, 0x40, "Bonus Game", IP_KEY_NONE )
PORT_DIPSETTING( 0x40, "5000" )
PORT_DIPSETTING( 0x80, "10000" )
PORT_DIPSETTING( 0xc0, "15000" )
PORT_DIPSETTING( 0x00, "None" )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_2WAY | IPF_COCKTAIL )
PORT_BIT( 0x1c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_2WAY | IPF_COCKTAIL )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 */
PORT_DIPNAME( 0x03, 0x01, "Bonus_Life", IP_KEY_NONE )
PORT_DIPSETTING( 0x01, "2000" )
PORT_DIPSETTING( 0x02, "3000" )
PORT_DIPSETTING( 0x03, "5000" )
PORT_DIPSETTING( 0x00, "None" )
PORT_DIPNAME( 0x04, 0x00, "Unknown", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "Off" )
PORT_DIPSETTING( 0x04, "On" )
PORT_DIPNAME( 0x18, 0x08, "Lives", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "2" )
PORT_DIPSETTING( 0x08, "3" )
PORT_DIPSETTING( 0x10, "4" )
PORT_DIPSETTING( 0x18, "5" )
PORT_DIPNAME( 0x20, 0x00, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "Upright" )
PORT_DIPSETTING( 0x20, "Cocktail" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START /* IN3 */
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_VBLANK )
PORT_BIT( 0x3e, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 )
/* Fake port to handle coins */
PORT_START /* IN4 */
PORT_BITX(0x01, IP_ACTIVE_HIGH, IPT_COIN1 | IPF_IMPULSE,
"Coin", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 1 )
PORT_BITX(0x02, IP_ACTIVE_HIGH, IPT_COIN2 | IPF_IMPULSE,
"Coin", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 1 )
/* Fake port to handle coinage dip switches. Each bit goes to 3800-3807 */
PORT_START /* IN5 */
PORT_DIPNAME( 0x0f, 0x00, "Coin_A", IP_KEY_NONE )
PORT_DIPSETTING( 0x0c, "4C_1C" )
PORT_DIPSETTING( 0x08, "3C_1C" )
PORT_DIPSETTING( 0x0d, "4 Coins/2 Credits" )
PORT_DIPSETTING( 0x05, "2C_1C" )
PORT_DIPSETTING( 0x09, "3C_2C" )
PORT_DIPSETTING( 0x0e, "4C_3C" )
PORT_DIPSETTING( 0x0f, "4 Coins/4 Credits" )
PORT_DIPSETTING( 0x0a, "3 Coins/3 Credits" )
PORT_DIPSETTING( 0x06, "2 Coins/2 Credits" )
PORT_DIPSETTING( 0x00, "1C_1C" )
PORT_DIPSETTING( 0x0b, "3C_4C" )
PORT_DIPSETTING( 0x07, "2C_3C" )
PORT_DIPSETTING( 0x01, "1C_2C" )
PORT_DIPSETTING( 0x02, "1C_3C" )
PORT_DIPSETTING( 0x03, "1C_4C" )
PORT_DIPSETTING( 0x04, "1C_5C" )
PORT_DIPNAME( 0xf0, 0x00, "Coin_B", IP_KEY_NONE )
PORT_DIPSETTING( 0xc0, "4C_1C" )
PORT_DIPSETTING( 0x80, "3C_1C" )
PORT_DIPSETTING( 0xd0, "4 Coins/2 Credits" )
PORT_DIPSETTING( 0x50, "2C_1C" )
PORT_DIPSETTING( 0x90, "3C_2C" )
PORT_DIPSETTING( 0xe0, "4C_3C" )
PORT_DIPSETTING( 0xf0, "4 Coins/4 Credits" )
PORT_DIPSETTING( 0xa0, "3 Coins/3 Credits" )
PORT_DIPSETTING( 0x60, "2 Coins/2 Credits" )
PORT_DIPSETTING( 0x00, "1C_1C" )
PORT_DIPSETTING( 0xb0, "3C_4C" )
PORT_DIPSETTING( 0x70, "2C_3C" )
PORT_DIPSETTING( 0x10, "1C_2C" )
PORT_DIPSETTING( 0x20, "1C_3C" )
PORT_DIPSETTING( 0x30, "1C_4C" )
PORT_DIPSETTING( 0x40, "1C_5C" )
INPUT_PORTS_END
static struct MachineDriver magspot2_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
18432000/6, /* 3.072 Mhz ???? */
0,
magspot2_readmem,magspot2_writemem,0,0,
magspot2_interrupt,1
},
},
60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - interleaving is forced when a sound command is written */
0,
/* video hardware */
32*8, 24*8, { 0*8, 32*8-1, 0*8, 24*8-1 },
cosmicalien_gfxdecodeinfo,
16, 16*4,
magspot2_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY,
0,
cosmic_vh_start,
cosmic_vh_stop,
cosmic_vh_screenrefresh_sprites,
/* sound hardware */
0,0,0,0,
{
{
SOUND_DAC,
&dac_interface
}
}
};
ROM_START( magspot2_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "my1", 0x0000, 0x0800, 0xc0085ade )
ROM_LOAD( "my2", 0x0800, 0x0800, 0xd534a68b )
ROM_LOAD( "my3", 0x1000, 0x0800, 0x25513b2a )
ROM_LOAD( "my5", 0x1800, 0x0800, 0x8836bbc4 )
ROM_LOAD( "my4", 0x2000, 0x0800, 0x6a08ab94 )
ROM_LOAD( "my6", 0x2800, 0x0800, 0x77c6d109 )
ROM_REGION_DISPOSE(0x1000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "my7", 0x0000, 0x0800, 0x1ab338d3 )
ROM_LOAD( "my8", 0x0800, 0x0800, 0x9e1d63a2 )
ROM_REGION(0x0420) /* color proms */
ROM_LOAD( "m13", 0x0000, 0x0020, 0x36e2aa2a )
ROM_LOAD( "my9", 0x0020, 0x0400, 0x89f23ebd )
ROM_END
struct GameDriver magspot2_driver =
{
__FILE__,
0,
"magspot2",
"Magical Spot II",
"1980",
"Universal",
"Zsolt Vasvari",
0,
&magspot2_machine_driver,
0,
magspot2_rom,
0, 0,
0,
0, /* sound_prom */
magspot2_input_ports,
PROM_MEMORY_REGION(2), 0, 0,
ORIENTATION_ROTATE_270,
0, 0
};
/***************************************************************************
Devil Zone
***************************************************************************/
void devzone_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
static struct MemoryReadAddress devzone_readmem[] =
{
{ 0x0000, 0x2fff, MRA_ROM },
{ 0x5000, 0x5000, input_port_0_r },
{ 0x5001, 0x5001, input_port_1_r },
{ 0x5002, 0x5002, input_port_2_r },
{ 0x5003, 0x5003, input_port_3_r },
{ 0x6000, 0x6001, MRA_RAM },
{ 0x6002, 0x6002, input_port_5_r },
{ 0x6003, 0x7fff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress devzone_writemem[] =
{
{ 0x0000, 0x2fff, MWA_ROM },
{ 0x4000, 0x401f, MWA_RAM, &spriteram, &spriteram_size},
{ 0x4800, 0x4800, DAC_data_w },
{ 0x480D, 0x480D, magspot2_colourmap_w },
{ 0x480F, 0x480F, cosmic_flipscreen_w },
{ 0x6000, 0x63ff, MWA_RAM },
{ 0x6400, 0x7bff, cosmic_videoram_w, &cosmic_videoram, &videoram_size},
{ 0x7c00, 0x7fff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MachineDriver devzone_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
18432000/6, /* 3.072 Mhz ???? */
0,
devzone_readmem,devzone_writemem,0,0,
magspot2_interrupt,1
},
},
60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - interleaving is forced when a sound command is written */
0,
/* video hardware */
32*8, 24*8, { 0*8, 32*8-1, 0*8, 24*8-1 },
cosmicalien_gfxdecodeinfo,
16, 16*4,
devzone_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY,
0,
cosmic_vh_start,
cosmic_vh_stop,
cosmic_vh_screenrefresh_sprites,
/* sound hardware */
0,0,0,0,
{
{
SOUND_DAC,
&dac_interface
}
}
};
INPUT_PORTS_START( devzone_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_2WAY )
PORT_BIT( 0x1c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_2WAY )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_2WAY | IPF_COCKTAIL )
PORT_BIT( 0x1c, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_2WAY | IPF_COCKTAIL )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 */
PORT_DIPNAME( 0x03, 0x01, "Bonus_Life", IP_KEY_NONE )
PORT_DIPSETTING( 0x01, "4000" )
PORT_DIPSETTING( 0x02, "6000" )
PORT_DIPSETTING( 0x03, "8000" )
PORT_DIPSETTING( 0x00, "None" )
PORT_DIPNAME( 0x0c, 0x0c, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0x0c, "Use Coin A & B" )
PORT_DIPSETTING( 0x04, "2C_1C" )
PORT_DIPSETTING( 0x00, "1C_1C" )
PORT_DIPSETTING( 0x08, "1C_2C" )
PORT_DIPNAME( 0x10, 0x10, "Lives", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "2" )
PORT_DIPSETTING( 0x10, "3" )
PORT_DIPNAME( 0x20, 0x00, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "Upright" )
PORT_DIPSETTING( 0x20, "Cocktail" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START /* IN3 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_VBLANK )
PORT_BIT( 0x3e, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 )
/* Fake port to handle coins */
PORT_START /* IN4 */
PORT_BITX(0x01, IP_ACTIVE_HIGH, IPT_COIN1 | IPF_IMPULSE,
"Coin", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 1 )
PORT_BITX(0x02, IP_ACTIVE_HIGH, IPT_COIN2 | IPF_IMPULSE,
"Coin", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 1 )
PORT_START /* IN5 */
PORT_DIPNAME( 0x0f, 0x00, "Coin_A", IP_KEY_NONE )
PORT_DIPSETTING( 0x0c, "4C_1C" )
PORT_DIPSETTING( 0x08, "3C_1C" )
PORT_DIPSETTING( 0x0d, "4 Coins/2 Credits" )
PORT_DIPSETTING( 0x05, "2C_1C" )
PORT_DIPSETTING( 0x09, "3C_2C" )
PORT_DIPSETTING( 0x0e, "4C_3C" )
PORT_DIPSETTING( 0x0f, "4 Coins/4 Credits" )
PORT_DIPSETTING( 0x0a, "3 Coins/3 Credits" )
PORT_DIPSETTING( 0x06, "2 Coins/2 Credits" )
PORT_DIPSETTING( 0x00, "1C_1C" )
PORT_DIPSETTING( 0x0b, "3C_4C" )
PORT_DIPSETTING( 0x07, "2C_3C" )
PORT_DIPSETTING( 0x01, "1C_2C" )
PORT_DIPSETTING( 0x02, "1C_3C" )
PORT_DIPSETTING( 0x03, "1C_4C" )
PORT_DIPSETTING( 0x04, "1C_5C" )
PORT_DIPNAME( 0xf0, 0x10, "Coin_B", IP_KEY_NONE )
PORT_DIPSETTING( 0xc0, "4C_1C" )
PORT_DIPSETTING( 0x80, "3C_1C" )
PORT_DIPSETTING( 0xd0, "4 Coins/2 Credits" )
PORT_DIPSETTING( 0x50, "2C_1C" )
PORT_DIPSETTING( 0x90, "3C_2C" )
PORT_DIPSETTING( 0xe0, "4C_3C" )
PORT_DIPSETTING( 0xf0, "4 Coins/4 Credits" )
PORT_DIPSETTING( 0xa0, "3 Coins/3 Credits" )
PORT_DIPSETTING( 0x60, "2 Coins/2 Credits" )
PORT_DIPSETTING( 0x00, "1C_1C" )
PORT_DIPSETTING( 0xb0, "3C_4C" )
PORT_DIPSETTING( 0x70, "2C_3C" )
PORT_DIPSETTING( 0x10, "1C_2C" )
PORT_DIPSETTING( 0x20, "1C_3C" )
PORT_DIPSETTING( 0x30, "1C_4C" )
PORT_DIPSETTING( 0x40, "1C_5C" )
INPUT_PORTS_END
ROM_START( devzone_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "dv1.e3", 0x0000, 0x0800, 0xc70faf00 )
ROM_LOAD( "dv2.e4", 0x0800, 0x0800, 0xeacfed61 )
ROM_LOAD( "dv3.e5", 0x1000, 0x0800, 0x7973317e )
ROM_LOAD( "dv5.e7", 0x1800, 0x0800, 0xb71a3989 )
ROM_LOAD( "dv4.e6", 0x2000, 0x0800, 0xa58c5b8c )
ROM_LOAD( "dv6.e8", 0x2800, 0x0800, 0x3930fb67 )
ROM_REGION_DISPOSE(0x1000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "dv7.n1", 0x0000, 0x0800, 0xe7562fcf )
ROM_LOAD( "dv8.n2", 0x0800, 0x0800, 0xda1cbec1 )
ROM_REGION(0x0400) /* color proms */
ROM_LOAD( "dz9.e2", 0x0000, 0x0400, 0x693855b6 )
ROM_END
struct GameDriver devzone_driver =
{
__FILE__,
0,
"devzone",
"Devil Zone",
"1980",
"Universal",
"Zsolt Vasvari\nMike Coates",
GAME_WRONG_COLORS,
&devzone_machine_driver,
0,
devzone_rom,
0, 0,
0,
0, /* sound_prom */
devzone_input_ports,
PROM_MEMORY_REGION(2), 0, 0,
ORIENTATION_ROTATE_270,
0, 0
};
/***************************************************************************
No Mans Land
***************************************************************************/
void nomanland_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
void nomanland_background_w(int offset, int data);
static struct GfxLayout nomanland_treelayout =
{
32,32, /* 16*16 sprites */
4, /* 8 sprites */
2, /* 2 bits per pixel */
{ 0, 8*128*8 }, /* the two bitplanes are separated */
{ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 },
{ 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, 8*32, 9*32, 10*32, 11*32, 12*32, 13*32, 14*32, 15*32,
16*32, 17*32, 18*32, 19*32, 20*32, 21*32, 22*32, 23*32, 24*32, 25*32, 26*32, 27*32, 28*32, 29*32, 30*32, 31*32 },
128*8 /* every sprite takes 128 consecutive bytes */
};
static struct GfxLayout nomanland_waterlayout =
{
16,32, /* 16*32 sprites */
32, /* 16 sprites */
2, /* 2 bits per pixel */
{ 0, 8*128*8 }, /* the two bitplanes are separated */
{ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 },
{ 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, 8*32, 9*32, 10*32, 11*32, 12*32, 13*32, 14*32, 15*32,
16*32, 17*32, 18*32, 19*32, 20*32, 21*32, 22*32, 23*32, 24*32, 25*32, 26*32, 27*32, 28*32, 29*32, 30*32, 31*32 },
32 /* To create a set of sprites 1 pixel displaced */
};
static struct GfxDecodeInfo nomanland_gfxdecodeinfo[] =
{
{ 1, 0x0000, &cosmicalien_spritelayout16, 0, 8 },
{ 1, 0x1000, &nomanland_treelayout, 0, 9 },
{ 1, 0x1200, &nomanland_waterlayout, 0, 10 },
{ -1 } /* end of array */
};
int nomanland_interrupt(void)
{
if (readinputport(4) & 1) /* Left Coin */
return nmi_interrupt();
else
return ignore_interrupt();
}
/* Has 8 way joystick, remap combinations to missing directions */
int nomanland_port_r(int offset)
{
int control;
int fire = input_port_3_r(0);
if (offset)
control = input_port_1_r(0);
else
control = input_port_0_r(0);
/* If firing - stop tank */
if ((fire & 0xc0) == 0) return 0xff;
/* set bit according to 8 way direction */
if ((control & 0x82) == 0 ) return 0xfe; /* Up & Left */
if ((control & 0x0a) == 0 ) return 0xfb; /* Down & Left */
if ((control & 0x28) == 0 ) return 0xef; /* Down & Right */
if ((control & 0xa0) == 0 ) return 0xbf; /* Up & Right */
return control;
}
static struct MemoryReadAddress nomanland_readmem[] =
{
{ 0x0000, 0x2fff, MRA_ROM },
{ 0x3800, 0x3807, magspot2_coinage_dip_r },
{ 0x5000, 0x5001, nomanland_port_r },
{ 0x5002, 0x5002, input_port_2_r },
{ 0x5003, 0x5003, input_port_3_r },
{ 0x6000, 0x7fff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress nomanland2_readmem[] =
{
{ 0x0000, 0x2fff, MRA_ROM },
// { 0x3800, 0x3807, magspot2_coinage_dip_r },
{ 0x5000, 0x5001, nomanland_port_r },
{ 0x5002, 0x5002, input_port_2_r },
{ 0x5003, 0x5003, input_port_3_r },
{ 0x6000, 0x7fff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress nomanland_writemem[] =
{
{ 0x0000, 0x2fff, MWA_ROM },
{ 0x4000, 0x401f, MWA_RAM, &spriteram, &spriteram_size},
{ 0x4807, 0x4807, nomanland_background_w },
{ 0x480A, 0x480A, DAC_data_w },
{ 0x480D, 0x480D, magspot2_colourmap_w },
{ 0x480F, 0x480F, cosmic_flipscreen_w },
{ 0x6000, 0x63ff, MWA_RAM },
{ 0x6400, 0x7bff, cosmic_videoram_w, &cosmic_videoram, &videoram_size},
{ 0x7c00, 0x7fff, MWA_RAM },
{ -1 } /* end of table */
};
ROM_START( nomanland_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "1.bin", 0x0000, 0x0800, 0xba117ba6 )
ROM_LOAD( "2.bin", 0x0800, 0x0800, 0xe5ed654f )
ROM_LOAD( "3.bin", 0x1000, 0x0800, 0x7fc42724 )
ROM_LOAD( "5.bin", 0x1800, 0x0800, 0x9cc2f1d9 )
ROM_LOAD( "4.bin", 0x2000, 0x0800, 0x0e8cd46a )
ROM_LOAD( "6.bin", 0x2800, 0x0800, 0xba472ba5 )
ROM_REGION_DISPOSE(0x1800) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "nml7.n1", 0x0800, 0x0800, 0xd08ed22f )
ROM_LOAD( "nml8.n2", 0x0000, 0x0800, 0x739009b4 )
ROM_LOAD( "nl11.ic7", 0x1000, 0x0400, 0xe717b241 )
ROM_LOAD( "nl10.ic4", 0x1400, 0x0400, 0x5b13f64e )
ROM_REGION(0x0420) /* color proms */
ROM_LOAD( "nml.clr", 0x0000, 0x0020, 0x65e911f9 )
ROM_LOAD( "nl9.e2", 0x0020, 0x0400, 0x9e05f14e )
ROM_END
ROM_START( nomanlandg_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "nml1.e3", 0x0000, 0x0800, 0xe212ed91 )
ROM_LOAD( "nml2.e4", 0x0800, 0x0800, 0xf66ef3d8 )
ROM_LOAD( "nml3.e5", 0x1000, 0x0800, 0xd422fc8a )
ROM_LOAD( "nml5.e7", 0x1800, 0x0800, 0xd58952ac )
ROM_LOAD( "nml4.e6", 0x2000, 0x0800, 0x994c9afb )
ROM_LOAD( "nml6.e8", 0x2800, 0x0800, 0x01ed2d8c )
ROM_REGION_DISPOSE(0x1800) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "nml7.n1", 0x0800, 0x0800, 0xd08ed22f )
ROM_LOAD( "nml8.n2", 0x0000, 0x0800, 0x739009b4 )
ROM_LOAD( "nl11.ic7", 0x1000, 0x0400, 0xe717b241 )
ROM_LOAD( "nl10.ic4", 0x1400, 0x0400, 0x5b13f64e )
ROM_REGION(0x0420) /* color proms */
ROM_LOAD( "nml.clr", 0x0000, 0x0020, 0x65e911f9 )
ROM_LOAD( "nl9.e2", 0x0020, 0x0400, 0x9e05f14e )
ROM_END
static struct MachineDriver nomanland_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
18432000/6, /* 3.072 Mhz ???? */
0,
nomanland_readmem,nomanland_writemem,0,0,
nomanland_interrupt,1
},
},
60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame */
0,
/* video hardware */
32*8, 24*8, { 0*8, 32*8-1, 0*8, 24*8-1 },
nomanland_gfxdecodeinfo,
16, 16*4,
nomanland_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY,
0,
cosmic_vh_start,
cosmic_vh_stop,
cosmic_vh_screenrefresh_sprites,
/* sound hardware */
0,0,0,0,
{
{
SOUND_DAC,
&dac_interface
}
}
};
static struct MachineDriver nomanland2_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
18432000/6, /* 3.072 Mhz ???? */
0,
nomanland2_readmem,nomanland_writemem,0,0,
nomanland_interrupt,1
},
},
60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame */
0,
/* video hardware */
32*8, 24*8, { 0*8, 32*8-1, 0*8, 24*8-1 },
nomanland_gfxdecodeinfo,
16, 16*4,
nomanland_vh_convert_color_prom,
VIDEO_TYPE_RASTER/VIDEO_SUPPORTS_DIRTY,
0,
cosmic_vh_start,
cosmic_vh_stop,
cosmic_vh_screenrefresh_sprites,
/* sound hardware */
0,0,0,0,
{
{
SOUND_DAC,
&dac_interface
}
}
};
INPUT_PORTS_START( nomanland_input_ports )
PORT_START /* Controls - Remapped for game */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x55, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN1 */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x55, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 */
PORT_DIPNAME( 0x03, 0x02, "Bonus_Life", IP_KEY_NONE )
PORT_DIPSETTING( 0x01, "2000" )
PORT_DIPSETTING( 0x02, "3000" )
PORT_DIPSETTING( 0x03, "5000" )
PORT_DIPSETTING( 0x00, "None" )
PORT_DIPNAME( 0x0c, 0x00, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0x04, "2C_1C" )
PORT_DIPSETTING( 0x00, "1C_1C" )
PORT_DIPSETTING( 0x0c, "2 Coins/2 Credits" )
PORT_DIPSETTING( 0x08, "1C_2C" )
PORT_DIPNAME( 0x10, 0x00, "Lives", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "3" )
PORT_DIPSETTING( 0x10, "5" )
PORT_DIPNAME( 0x20, 0x00, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "Upright" )
PORT_DIPSETTING( 0x20, "Cocktail" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START /* IN3 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_VBLANK )
PORT_BIT( 0x3e, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 )
/* Fake port to handle coins */
PORT_START /* IN4 */
PORT_BITX(0x01, IP_ACTIVE_HIGH, IPT_COIN1 | IPF_IMPULSE,
"Coin", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 1 )
#if 0
Although the port is read, the game does not appear to use these
PORT_START /* IN5 */
PORT_DIPNAME( 0xf0, 0x00, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0xc0, "4C_1C" )
PORT_DIPSETTING( 0x80, "3C_1C" )
PORT_DIPSETTING( 0xd0, "4 Coins/2 Credits" )
PORT_DIPSETTING( 0x50, "2C_1C" )
PORT_DIPSETTING( 0x90, "3C_2C" )
PORT_DIPSETTING( 0xe0, "4C_3C" )
PORT_DIPSETTING( 0xf0, "4 Coins/4 Credits" )
PORT_DIPSETTING( 0xa0, "3 Coins/3 Credits" )
PORT_DIPSETTING( 0x60, "2 Coins/2 Credits" )
PORT_DIPSETTING( 0x00, "1C_1C" )
PORT_DIPSETTING( 0xb0, "3C_4C" )
PORT_DIPSETTING( 0x70, "2C_3C" )
PORT_DIPSETTING( 0x10, "1C_2C" )
PORT_DIPSETTING( 0x20, "1C_3C" )
PORT_DIPSETTING( 0x30, "1C_4C" )
PORT_DIPSETTING( 0x40, "1C_5C" )
#endif
INPUT_PORTS_END
INPUT_PORTS_START( nomanland2_input_ports )
PORT_START /* Controls - Remapped for game */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x55, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN1 */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x55, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 */
PORT_DIPNAME( 0x03, 0x02, "Bonus_Life", IP_KEY_NONE )
PORT_DIPSETTING( 0x01, "3000" )
PORT_DIPSETTING( 0x02, "5000" )
PORT_DIPSETTING( 0x03, "8000" )
PORT_DIPSETTING( 0x00, "None" )
PORT_DIPNAME( 0x0c, 0x00, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0x04, "2C_1C" )
PORT_DIPSETTING( 0x00, "1C_1C" )
// PORT_DIPSETTING( 0x0c, "2 Coins/2 Credits" ) Seems to do 1/1 ?
PORT_DIPSETTING( 0x08, "1C_2C" )
PORT_DIPNAME( 0x10, 0x00, "Lives", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "2" )
PORT_DIPSETTING( 0x10, "3" )
PORT_DIPNAME( 0x20, 0x00, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "Upright" )
PORT_DIPSETTING( 0x20, "Cocktail" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START /* IN3 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_VBLANK )
PORT_BIT( 0x3e, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 )
/* Fake port to handle coins */
PORT_START /* IN4 */
PORT_BITX(0x01, IP_ACTIVE_HIGH, IPT_COIN1 | IPF_IMPULSE,
"Coin", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 1 )
INPUT_PORTS_END
struct GameDriver nomnlnd_driver =
{
__FILE__,
0,
"nomnlnd",
"No Man's Land",
"1980?",
"Universal",
"Mike Coates",
GAME_WRONG_COLORS,
&nomanland_machine_driver,
0,
nomanland_rom,
0, 0,
0,
0, /* sound_prom */
nomanland_input_ports,
PROM_MEMORY_REGION(2), 0, 0,
ORIENTATION_ROTATE_270,
0, 0
};
struct GameDriver nomnlndg_driver =
{
__FILE__,
&nomnlnd_driver,
"nomnlndg",
"No Man's Land (Gottlieb)",
"1980?",
"Universal (Gottlieb license)",
"Mike Coates",
GAME_WRONG_COLORS,
&nomanland2_machine_driver,
0,
nomanlandg_rom,
0, 0,
0,
0, /* sound_prom */
nomanland2_input_ports,
PROM_MEMORY_REGION(2), 0, 0,
ORIENTATION_ROTATE_270,
0, 0
};
| 29.352459
| 172
| 0.638823
|
pierrelouys
|
7d80836b17d9e97d4b9005008b5b88c3e3a74a6a
| 572
|
hpp
|
C++
|
include/basic_csv_file_def.hpp
|
MarkusJx/csv
|
35a945c789215ad6e817bd52de7d08c9842920b9
|
[
"MIT"
] | null | null | null |
include/basic_csv_file_def.hpp
|
MarkusJx/csv
|
35a945c789215ad6e817bd52de7d08c9842920b9
|
[
"MIT"
] | null | null | null |
include/basic_csv_file_def.hpp
|
MarkusJx/csv
|
35a945c789215ad6e817bd52de7d08c9842920b9
|
[
"MIT"
] | null | null | null |
#ifndef MARKUSJX_CSV_BASIC_CSV_FILE_DEF_HPP
#define MARKUSJX_CSV_BASIC_CSV_FILE_DEF_HPP
#include "escape_sequence_generator.hpp"
namespace markusjx {
/**
* A csv file
*
* @tparam T the char type of the file
* @tparam Sep the separator to use
* @tparam _escape_generator_ the escape sequence generator to use
*/
template<class T, char Sep = ';', class _escape_generator_ = util::escape_sequence_generator<util::std_basic_string<T>, Sep>>
class basic_csv_file;
} //namespace markusjx
#endif //MARKUSJX_CSV_BASIC_CSV_FILE_DEF_HPP
| 30.105263
| 129
| 0.73951
|
MarkusJx
|
7d809872f30787c25f2ac2006a245718cad63d7a
| 768
|
hpp
|
C++
|
include/dudp/server.hpp
|
swrh/dudp
|
b0159edd90f8cda10c150a7c2b9cf71d5443c7b6
|
[
"BSD-3-Clause"
] | null | null | null |
include/dudp/server.hpp
|
swrh/dudp
|
b0159edd90f8cda10c150a7c2b9cf71d5443c7b6
|
[
"BSD-3-Clause"
] | null | null | null |
include/dudp/server.hpp
|
swrh/dudp
|
b0159edd90f8cda10c150a7c2b9cf71d5443c7b6
|
[
"BSD-3-Clause"
] | null | null | null |
#if !defined(_DUDP_SERVER_HPP_)
#define _DUDP_SERVER_HPP_
#include <array>
#include <memory>
#include <string>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/udp.hpp>
namespace dudp {
class
server
{
private:
boost::asio::ip::udp::socket socket_;
boost::asio::ip::udp::endpoint remote_endpoint_;
std::array<char, 1024> recv_buffer_;
public:
server(boost::asio::io_service &service, uint16_t port);
protected:
void start_receive();
void handle_receive(const boost::system::error_code &error, std::size_t bytes_transferred);
void handle_send(std::shared_ptr<std::string> message, const boost::system::error_code &error, std::size_t bytes_transferred);
};
}
#endif // !defined(_DUDP_SERVER_HPP_)
// vim:set sw=4 ts=4 et:
| 21.942857
| 130
| 0.727865
|
swrh
|
7d80cb5e3304cc76c8bc88c252e07bea5429a27f
| 6,175
|
cpp
|
C++
|
kernel/runtime/dmzRuntimeResourcesObserver.cpp
|
shillcock/dmz
|
02174b45089e12cd7f0840d5259a00403cd1ccff
|
[
"MIT"
] | 2
|
2015-11-05T03:03:40.000Z
|
2016-02-03T21:50:40.000Z
|
kernel/runtime/dmzRuntimeResourcesObserver.cpp
|
dmzgroup/dmz
|
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
|
[
"MIT"
] | null | null | null |
kernel/runtime/dmzRuntimeResourcesObserver.cpp
|
dmzgroup/dmz
|
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
|
[
"MIT"
] | null | null | null |
#include "dmzRuntimeContext.h"
#include "dmzRuntimeContextResources.h"
#include <dmzRuntimeHandle.h>
#include <dmzRuntimeLog.h>
#include <dmzRuntimePluginInfo.h>
#include <dmzRuntimeResourcesObserver.h>
/*!
\file dmzRuntimeResourcesObserver.h
\ingroup Runtime
\brief Contains ResourcesObserver class.
\enum dmz::ResourcesActivateModeEnum
\ingroup Runtime
\brief Resources callback activate mode.
\enum dmz::ResourcesUpdateTypeEnum
\ingroup Runtime
\brief Resources update callback type.
\class dmz::ResourcesObserver
\ingroup Runtime
\brief Observes changes in runtime Resources.
*/
struct dmz::ResourcesObserver::State {
RuntimeHandle *handlePtr;
const Handle ObsHandle;
Log log;
RuntimeContextResources *rc;
UInt32 mask;
UInt32 warnMask;
State (const Handle TheObsHandle, const String &ObsName, RuntimeContext *context) :
handlePtr (
TheObsHandle == 0 ?
new RuntimeHandle (ObsName + ".ResourcesObserver", context) :
0),
ObsHandle (handlePtr ? handlePtr->get_runtime_handle () : TheObsHandle),
log (ObsName + "ResourcesObserver", context),
rc (context ? context->get_resources_context () : 0),
mask (0),
warnMask (0) {
if (rc) { rc->ref (); }
}
~State () {
if (rc) { rc->unref (); rc = 0; }
if (handlePtr) { delete handlePtr; handlePtr = 0; }
}
};
/*!
\brief Constructor.
\param[in] context Pointer to the RuntimeContext.
*/
dmz::ResourcesObserver::ResourcesObserver (RuntimeContext *context) :
__state (*(new State (0, "<Anonymous Resources Observer>", context))) {;}
/*!
\brief Constructor.
\param[in] Info Reference to the PluginInfo.
*/
dmz::ResourcesObserver::ResourcesObserver (const PluginInfo &Info) :
__state (*(new State (Info.get_handle (), Info.get_name (), Info.get_context ()))) {
}
//! Destructor.
dmz::ResourcesObserver::~ResourcesObserver () {
set_resources_observer_callback_mask (ResourcesDumpNone, 0);
delete &__state;
}
//! Returns a mask of active callbacks.
dmz::UInt32
dmz::ResourcesObserver::get_resources_observer_callback_mask () const {
return __state.mask;
}
/*!
\brief Activates dmz::ResourcesObserver::update_resource() callback.
\param[in] Mode Specifies if all currently defined resources should be dumped to observer
upon activation.
\param[in] TheMask A mask specifying which callbacks to activate.
\return Returns a mask of all callbacks that were activated.
*/
dmz::UInt32
dmz::ResourcesObserver::set_resources_observer_callback_mask (
const ResourcesActivateModeEnum Mode,
const UInt32 TheMask) {
if (__state.rc) {
const Boolean Dump = (Mode == ResourcesDumpAll);
const Handle ObsHandle = __state.ObsHandle;
if (ResourcesPathMask & TheMask) {
if ((ResourcesPathMask & __state.mask) == 0) {
if (__state.rc->pathObsTable.store (ObsHandle, this)) {
__state.mask |= ResourcesPathMask;
if (Dump) {
HashTableStringIterator it;
StringContainer *ptr (0);
while (__state.rc->pathTable.get_next (it, ptr)) {
update_resources_path (it.get_hash_key (), ResourcesCreated);
}
}
}
}
}
else if (ResourcesPathMask & __state.mask) {
__state.mask &= ~ResourcesPathMask;
__state.rc->pathObsTable.remove (ObsHandle);
}
if (ResourcesResourceMask & TheMask) {
if ((ResourcesResourceMask & __state.mask) == 0) {
if (__state.rc->rcObsTable.store (ObsHandle, this)) {
__state.mask |= ResourcesResourceMask;
if (Dump) {
HashTableStringIterator it;
Config *ptr (0);
while (__state.rc->rcTable.get_next (it, ptr)) {
update_resource (it.get_hash_key (), ResourcesCreated);
}
}
}
}
}
else if (ResourcesResourceMask & __state.mask) {
__state.mask &= ~ResourcesResourceMask;
__state.rc->rcObsTable.remove (ObsHandle);
}
}
return __state.mask;
}
/*!
\brief Dumps the current Resources to the observer.
\details The dmz::ResourcesObserver::update_resource() Mode parameter will be set to dmz::ResourcesDumped.
*/
void
dmz::ResourcesObserver::dump_current_resources () {
if (__state.rc) {
if (__state.mask & ResourcesPathMask) {
HashTableStringIterator it;
StringContainer *ptr (0);
while (__state.rc->pathTable.get_next (it, ptr)) {
update_resources_path (it.get_hash_key (), ResourcesDumped);
}
}
if (__state.mask & ResourcesResourceMask) {
HashTableStringIterator it;
Config *ptr (0);
while (__state.rc->rcTable.get_next (it, ptr)) {
update_resource (it.get_hash_key (), ResourcesDumped);
}
}
}
}
/*!
\brief Function invoked when runtime Resources paths are create, updated, or removed.
\param[in] Name String containing name of path being updated.
\param[in] Type Type of update.
*/
void
dmz::ResourcesObserver::update_resources_path (
const String &Name,
const ResourcesUpdateTypeEnum Type) {
if ((ResourcesPathMask & __state.warnMask) == 0) {
__state.warnMask |= ResourcesPathMask;
__state.log.warn << "Base dmz::ResourcesObserver::update_resources_path called."
<< " Function should have been overridden?" << endl;
}
}
/*!
\brief Function invoked when runtime Resources are create, updated, or removed.
\param[in] Name String containing name of resource being updated.
\param[in] Type Type of update.
*/
void
dmz::ResourcesObserver::update_resource (
const String &Name,
const ResourcesUpdateTypeEnum Type) {
if ((ResourcesResourceMask & __state.warnMask) == 0) {
__state.warnMask |= ResourcesResourceMask;
__state.log.warn << "Base dmz::ResourcesObserver::update_resource called."
<< " Function should have been overridden?" << endl;
}
}
| 24.311024
| 106
| 0.645506
|
shillcock
|
7d8495bf05507e3aa970d8f074866587ad2ed7d6
| 3,929
|
cpp
|
C++
|
simple_demo/plain_executables/DataSource.cpp
|
cd606/tm_examples
|
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
|
[
"Apache-2.0"
] | 1
|
2020-05-22T08:47:00.000Z
|
2020-05-22T08:47:00.000Z
|
simple_demo/plain_executables/DataSource.cpp
|
cd606/tm_examples
|
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
|
[
"Apache-2.0"
] | null | null | null |
simple_demo/plain_executables/DataSource.cpp
|
cd606/tm_examples
|
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
|
[
"Apache-2.0"
] | null | null | null |
#include <tm_kit/infra/Environments.hpp>
#include <tm_kit/infra/TerminationController.hpp>
#include <tm_kit/infra/RealTimeApp.hpp>
#include <tm_kit/basic/ByteData.hpp>
#include <tm_kit/basic/VoidStruct.hpp>
#include <tm_kit/basic/TrivialBoostLoggingComponent.hpp>
#include <tm_kit/basic/real_time_clock/ClockComponent.hpp>
#include <tm_kit/basic/real_time_clock/ClockImporter.hpp>
#include <tm_kit/transport/BoostUUIDComponent.hpp>
#include <tm_kit/transport/zeromq/ZeroMQComponent.hpp>
#include <tm_kit/transport/zeromq/ZeroMQImporterExporter.hpp>
#include <tm_kit/transport/rabbitmq/RabbitMQComponent.hpp>
#include <tm_kit/transport/rabbitmq/RabbitMQImporterExporter.hpp>
#include <tm_kit/transport/HeartbeatAndAlertComponent.hpp>
#include <tm_kit/transport/MultiTransportBroadcastPublisherManagingUtils.hpp>
#include "simple_demo/data_structures/InputDataStructure.hpp"
#include "simple_demo/external_logic/DataSource.hpp"
#include <iostream>
#include <sstream>
using namespace dev::cd606::tm;
using namespace simple_demo;
using TheEnvironment = infra::Environment<
infra::CheckTimeComponent<false>,
infra::TrivialExitControlComponent,
basic::TrivialBoostLoggingComponent,
basic::real_time_clock::ClockComponent,
transport::BoostUUIDComponent,
transport::zeromq::ZeroMQComponent,
transport::rabbitmq::RabbitMQComponent,
transport::web_socket::WebSocketComponent,
transport::json_rest::JsonRESTComponent,
transport::HeartbeatAndAlertComponent
>;
using M = infra::RealTimeApp<TheEnvironment>;
class DataSourceImporter final : public M::AbstractImporter<InputDataPOCO>, public DataSourceListener {
private:
TheEnvironment *env_;
DataSource source_;
public:
DataSourceImporter() : env_(nullptr), source_() {}
~DataSourceImporter() {}
virtual void start(TheEnvironment *env) override final {
env_ = env;
source_.start(this);
env->sendAlert("simple_demo.data_source.info", infra::LogLevel::Info, "Data source started");
}
virtual void onData(DataFromSource const &data) override final {
publish(M::pureInnerData<InputDataPOCO>(env_, InputDataPOCO {data.value}, false));
}
};
int main(int argc, char **argv) {
TheEnvironment env;
env.transport::json_rest::JsonRESTComponent::setDocRoot(56788, "../simple_demo/plain_executables/datasource_web");
transport::initializeHeartbeatAndAlertComponent
(&env, "simple_demo DataSource", "rabbitmq://127.0.0.1::guest:guest:amq.topic[durable=true]");
env.setStatus("program", transport::HeartbeatMessage::Status::Good);
using R = infra::AppRunner<M>;
R r(&env);
auto addTopic = basic::SerializationActions<M>::template addConstTopic<InputDataPOCO>("input.data");
auto publisherSink = transport::MultiTransportBroadcastPublisherManagingUtils<R>
::oneBroadcastPublisherWithProtocol<basic::proto_interop::Proto, InputDataPOCO>(
r
, "input data publisher"
, "zeromq://localhost:12345"
);
auto publisherSink2 = transport::MultiTransportBroadcastPublisherManagingUtils<R>
::oneBroadcastPublisherWithProtocol<std::void_t, InputDataPOCO>(
r
, "input data publisher 2"
, "websocket://localhost:56789:::/data[ignoreTopic=true]"
);
auto source = M::importer(new DataSourceImporter());
auto toPub = r.execute("addTopic", addTopic
, r.importItem("source", source));
r.connect(
toPub.clone()
, publisherSink
);
r.connect(
toPub.clone()
, publisherSink2
);
transport::attachHeartbeatAndAlertComponent(r, &env, "simple_demo.plain_executables.data_source.heartbeat", std::chrono::seconds(10));
r.finalize();
infra::terminationController(infra::TerminateAtTimePoint {
infra::withtime_utils::parseLocalTodayActualTime(23, 59, 59)
});
return 0;
}
| 36.719626
| 138
| 0.73072
|
cd606
|
7d8ae4ee372c289ebda3efd3bb80874368db22a6
| 1,427
|
cpp
|
C++
|
src/XSRenderer/XSScreenshot.cpp
|
Razish/AIE-pathfinding
|
366e19c7d20c626969e95e4ba9614127ed69e865
|
[
"MIT"
] | 1
|
2015-09-11T06:38:19.000Z
|
2015-09-11T06:38:19.000Z
|
src/XSRenderer/XSScreenshot.cpp
|
Razish/AIE-pathfinding
|
366e19c7d20c626969e95e4ba9614127ed69e865
|
[
"MIT"
] | null | null | null |
src/XSRenderer/XSScreenshot.cpp
|
Razish/AIE-pathfinding
|
366e19c7d20c626969e95e4ba9614127ed69e865
|
[
"MIT"
] | null | null | null |
#include "XSCommon/XSCommon.h"
#include "XSCommon/XSCvar.h"
#include "XSCommon/XSCommand.h"
#include "XSRenderer/XSRenderer.h"
#include "XSRenderer/XSBackend.h"
#include "XSRenderer/XSImagePNG.h"
#include "XSRenderer/XSRenderCommand.h"
namespace XS {
namespace Renderer {
namespace Backend {
static const size_t numScreenshotsPerFrame = 4u;
static const char *GetScreenshotName( void ) {
static char timestamp[numScreenshotsPerFrame][XS_MAX_FILENAME];
time_t rawtime;
time( &rawtime );
static uint32_t index = 0u;
char *p = timestamp[index];
strftime( p, sizeof(timestamp[index]), "%Y-%m-%d_%H-%M-%S.png", localtime( &rawtime ) );
index++;
index &= numScreenshotsPerFrame;
return p;
}
void Cmd_Screenshot( const commandContext_t * const context ) {
const int32_t w = vid_width->GetInt(), h = vid_height->GetInt();
glBindBuffer( GL_PIXEL_PACK_BUFFER, defaultPbo );
glReadPixels( 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, NULL );
GLsync sync = glFenceSync( GL_SYNC_GPU_COMMANDS_COMPLETE, 0 );
RenderCommand cmd( RenderCommand::Type::SCREENSHOT );
cmd.screenshot.name = GetScreenshotName();
cmd.screenshot.width = w;
cmd.screenshot.height = h;
cmd.screenshot.pbo = defaultPbo;
cmd.screenshot.sync = sync;
//TODO: wait until next frame
cmd.Execute();
}
} // namespace Backend
} // namespace Renderer
} // namespace XS
| 27.980392
| 92
| 0.695865
|
Razish
|
7d8d4e079ea50b00869f110d8dab885e825acd21
| 2,787
|
cpp
|
C++
|
engine/gfx/gles2/src/gfx_gles2_shader.cpp
|
aeon-engine/aeon-engine
|
9efcf83985110c36ebf0964bd4f76b261f2f6717
|
[
"MIT"
] | 12
|
2017-02-25T17:14:15.000Z
|
2021-08-02T13:39:18.000Z
|
engine/gfx/gles2/src/gfx_gles2_shader.cpp
|
aeon-engine/aeon-engine
|
9efcf83985110c36ebf0964bd4f76b261f2f6717
|
[
"MIT"
] | 31
|
2017-02-23T06:59:44.000Z
|
2017-05-21T11:49:10.000Z
|
engine/gfx/gles2/src/gfx_gles2_shader.cpp
|
aeon-engine/aeon-engine
|
9efcf83985110c36ebf0964bd4f76b261f2f6717
|
[
"MIT"
] | 5
|
2017-05-02T05:34:53.000Z
|
2020-05-19T06:57:50.000Z
|
/*
* Copyright (c) 2012-2018 Robin Degen
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <aeon/gfx/gles2/gfx_gles2_shader.h>
#include <glm/gtc/type_ptr.hpp>
#include <aeon/gfx/gl_common/check_gl_error.h>
namespace aeon
{
namespace gfx
{
namespace gles2
{
gfx_gles2_shader::gfx_gles2_shader()
: logger_(common::logger::get_singleton(), "Gfx::Gles2::Shader")
, handle_(0)
, projection_matrix_handle_(0)
, model_matrix_handle_(0)
, view_matrix_handle_(0)
{
}
gfx_gles2_shader::~gfx_gles2_shader()
{
AEON_LOG_TRACE(logger_) << "Deleting Program (GL handle: " << handle_ << ")." << std::endl;
glDeleteProgram(handle_);
AEON_CHECK_GL_ERROR();
}
void gfx_gles2_shader::bind() const
{
glUseProgram(handle_);
AEON_CHECK_GL_ERROR();
}
void gfx_gles2_shader::set_projection_matrix(const glm::mat4 &matrix)
{
glUniformMatrix4fv(projection_matrix_handle_, 1, GL_FALSE, glm::value_ptr(matrix));
AEON_CHECK_GL_ERROR();
}
void gfx_gles2_shader::set_model_matrix(const glm::mat4 &matrix)
{
glUniformMatrix4fv(model_matrix_handle_, 1, GL_FALSE, glm::value_ptr(matrix));
AEON_CHECK_GL_ERROR();
}
void gfx_gles2_shader::set_view_matrix(const glm::mat4 &matrix)
{
glUniformMatrix4fv(view_matrix_handle_, 1, GL_FALSE, glm::value_ptr(matrix));
AEON_CHECK_GL_ERROR();
}
auto gfx_gles2_shader::get_sampler_handle_by_name(const std::string &name) const -> GLint
{
auto handle = glGetUniformLocation(handle_, name.c_str());
AEON_CHECK_GL_ERROR();
return handle;
}
void gfx_gles2_shader::bind_sampler(const GLint handle, const int bind_point) const
{
glUniform1i(handle, bind_point);
AEON_CHECK_GL_ERROR();
}
} // namespace gles2
} // namespace gfx
} // namespace aeon
| 29.648936
| 95
| 0.743093
|
aeon-engine
|
7d9ce29c24d2f57029956dc2dc705fa615ac628f
| 422
|
cpp
|
C++
|
C++Now 2017/Mocking Examples/runtime_rtti_name/f.cpp
|
dascandy/presentations
|
7a004ba5e485900a7c81e7a1116b098d24331075
|
[
"Apache-2.0"
] | 2
|
2017-05-18T19:48:51.000Z
|
2017-11-10T16:11:43.000Z
|
C++Now 2017/Mocking Examples/runtime_rtti_name/f.cpp
|
dascandy/presentations
|
7a004ba5e485900a7c81e7a1116b098d24331075
|
[
"Apache-2.0"
] | null | null | null |
C++Now 2017/Mocking Examples/runtime_rtti_name/f.cpp
|
dascandy/presentations
|
7a004ba5e485900a7c81e7a1116b098d24331075
|
[
"Apache-2.0"
] | null | null | null |
#include <typeinfo>
#include <cstdlib>
#include <cstdio>
#include <cstring>
struct T {
virtual ~T() {}
};
struct rttiinfo {
void* type;
const char* name;
void* base;
};
T* f(const char* name) {
static rttiinfo rti;
void** vt = new void*[10];
static T object;
memcpy(&rti, ((void***)&object)[0][-1], sizeof(rttiinfo));
*(void**)&object = &vt[1];
vt[0] = &rti;
rti.name = name;
return &object;
}
| 15.62963
| 60
| 0.594787
|
dascandy
|
7d9dc8e3d47c49f5ce5db516be1ea23172d4c790
| 644
|
cpp
|
C++
|
OOP/Shapes.cpp
|
ApostolAndrew/OOP
|
aff106a8df8960108fa07ed0c36ed64dc8497a9f
|
[
"MIT"
] | null | null | null |
OOP/Shapes.cpp
|
ApostolAndrew/OOP
|
aff106a8df8960108fa07ed0c36ed64dc8497a9f
|
[
"MIT"
] | null | null | null |
OOP/Shapes.cpp
|
ApostolAndrew/OOP
|
aff106a8df8960108fa07ed0c36ed64dc8497a9f
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
class Shape {
protected:
float width, height;
public:
void set(float a, float b) {
width = a;
height = b;
}
};
class Rectangle : public Shape {
public:
float area() {
return width * height;
}
};
class Triangle : public Shape {
public:
float area() {
return (width * height / 2);
}
};
int main() {
Triangle tri;
Rectangle rec;
float tarea, rarea;
tri.set(5,10);
rec.set(7,3);
cout << tri.area() << endl;
cout << rec.area() << endl;
return 0;
}
| 16.947368
| 40
| 0.493789
|
ApostolAndrew
|
7da1d757366a23377316e1c32feed2fc22302b8d
| 4,929
|
cpp
|
C++
|
src/util/tensor_distribution.cpp
|
mdschatz/rote
|
111e965c6365c605f9872ee8302b1170565a3002
|
[
"BSD-3-Clause"
] | null | null | null |
src/util/tensor_distribution.cpp
|
mdschatz/rote
|
111e965c6365c605f9872ee8302b1170565a3002
|
[
"BSD-3-Clause"
] | null | null | null |
src/util/tensor_distribution.cpp
|
mdschatz/rote
|
111e965c6365c605f9872ee8302b1170565a3002
|
[
"BSD-3-Clause"
] | 2
|
2018-07-21T15:39:45.000Z
|
2021-02-09T20:34:50.000Z
|
#include "rote.hpp"
namespace rote{
bool CheckOrder(const Unsigned& outOrder, const Unsigned& inOrder){
if(outOrder != inOrder){
LogicError("Invalid redistribution: Objects being redistributed must be of same order");
}
return true;
}
bool CheckNonDistOutIsPrefix(const TensorDistribution& outDist, const TensorDistribution& inDist){
Unsigned nonDistMode = outDist.size() - 1;
if(!(outDist[nonDistMode] <= inDist[nonDistMode])){
std::stringstream msg;
msg << "Invalid redistribution\n"
<< outDist
<< " <-- "
<< inDist
<< std::endl
<< "Output Non-distributed mode distribution must be prefix"
<< std::endl;
LogicError(msg.str());
}
return true;
}
bool CheckNonDistInIsPrefix(const TensorDistribution& outDist, const TensorDistribution& inDist){
Unsigned nonDistMode = outDist.size() - 1;
if(!(inDist[nonDistMode] <= outDist[nonDistMode])){
std::stringstream msg;
msg << "Invalid redistribution\n"
<< outDist
<< " <-- "
<< inDist
<< std::endl
<< "Input Non-distributed mode distribution must be prefix"
<< std::endl;
LogicError(msg.str());
}
return true;
}
bool CheckSameNonDist(const TensorDistribution& outDist, const TensorDistribution& inDist){
Unsigned nonDistMode = outDist.size() - 1;
if(!outDist[nonDistMode].SameModesAs(inDist[nonDistMode])){
std::stringstream msg;
msg << "Invalid redistribution\n"
<< outDist
<< " <-- "
<< inDist
<< std::endl
<< "Output Non-distributed mode distribution must be same"
<< std::endl;
LogicError(msg.str());
}
return true;
}
bool CheckSameCommModes(const TensorDistribution& outDist, const TensorDistribution& inDist){
TensorDistribution commonPrefix = inDist.GetCommonPrefix(outDist);
TensorDistribution remainderIn = inDist - commonPrefix;
TensorDistribution remainderOut = outDist - commonPrefix;
if(!remainderIn.UsedModes().SameModesAs(remainderOut.UsedModes())){
std::stringstream msg;
msg << "Invalid redistribution\n"
<< outDist
<< " <-- "
<< inDist
<< std::endl
<< "Cannot determine modes communicated over"
<< std::endl;
LogicError(msg.str());
}
return true;
}
bool CheckPartition(const TensorDistribution& outDist, const TensorDistribution& inDist){
Unsigned i;
Unsigned j = 0;
Unsigned objOrder = outDist.size() - 1;
ModeArray sourceModes;
ModeArray sinkModes;
for(i = 0; i < objOrder; i++){
if(inDist[i].size() != outDist[i].size()){
if(inDist[i] <= outDist[i]){
sinkModes.push_back(i);
}
else if(outDist[i] <= inDist[i]){
sourceModes.push_back(i);
}
}else if(inDist[i] != outDist[i]){
std::stringstream msg;
msg << "Invalid redistribution\n"
<< outDist
<< " <-- "
<< inDist
<< std::endl
<< "Cannot form partition"
<< std::endl;
LogicError(msg.str());
}
}
for(i = 0; i < sourceModes.size() && j < sinkModes.size(); i++){
if(sourceModes[i] == sinkModes[j]){
std::stringstream msg;
msg << "Invalid redistribution\n"
<< outDist
<< " <-- "
<< inDist
<< std::endl
<< "Cannot form partition"
<< std::endl;
LogicError(msg.str());
}else if(sourceModes[i] > sinkModes[j]){
i--;
j++;
}else if(sourceModes[i] < sinkModes[j]){
continue;
}
}
return true;
}
bool CheckInIsPrefix(const TensorDistribution& outDist, const TensorDistribution& inDist){
Unsigned objOrder = outDist.size() - 1;
for(Unsigned i = 0; i < objOrder; i++){
if(!(inDist[i] <= outDist[i])){
std::stringstream msg;
msg << "Invalid redistribution:\n"
<< outDist
<< " <-- "
<< inDist
<< std::endl
<< "Input mode-" << i << " mode distribution must be prefix of output mode distribution"
<< std::endl;
LogicError(msg.str());
}
}
return true;
}
bool CheckOutIsPrefix(const TensorDistribution& outDist, const TensorDistribution& inDist){
Unsigned objOrder = outDist.size() - 1;
for(Unsigned i = 0; i < objOrder; i++){
if(!(outDist[i] <= inDist[i])){
std::stringstream msg;
msg << "Invalid redistribution\n"
<< outDist
<< " <-- "
<< inDist
<< std::endl
<< "Output mode-" << i << " mode distribution must be prefix of input mode distribution"
<< std::endl;
LogicError(msg.str());
}
}
return true;
}
bool CheckSameGridViewShape(const ObjShape& outShape, const ObjShape& inShape){
if(AnyElemwiseNotEqual(outShape, inShape)){
std::stringstream msg;
msg << "Invalid redistribution: Mode distributions must correspond to equal logical grid dimensions"
<< std::endl;
LogicError(msg.str());
}
return true;
}
bool CheckIsValidPermutation(const Unsigned& order, const Permutation& perm){
return perm.size() == order;
}
}
| 27.082418
| 102
| 0.623656
|
mdschatz
|
7da344669f21c1cfdaecf5062fbb9717b6904967
| 1,960
|
cc
|
C++
|
test/testnewalloc.cc
|
dch0ph/libcmatrix
|
1f5fae7a398fe2c643252f93371b407dbfb70855
|
[
"MIT"
] | null | null | null |
test/testnewalloc.cc
|
dch0ph/libcmatrix
|
1f5fae7a398fe2c643252f93371b407dbfb70855
|
[
"MIT"
] | null | null | null |
test/testnewalloc.cc
|
dch0ph/libcmatrix
|
1f5fae7a398fe2c643252f93371b407dbfb70855
|
[
"MIT"
] | null | null | null |
#include "cmatrix.h"
#include <iostream>
struct dodgy;
std::ostream& operator<< (std::ostream&, const dodgy&);
static int initcount=0;
static int destroycount=0;
static int copycount=0;
//static int assigncount=0;
struct dodgy {
int val;
explicit dodgy(int valv =1234) : val(valv) {
std::cerr << "Make: " << valv << '\n';
initcount++;
}
dodgy(const dodgy& a) { val=a.val;
std::cerr << "Copy: " << *this << '\n';
copycount++;
}
// dodgy& operator= (const dodgy& a) {
// std::cerr << "Assigned: " << *this << '\n';
// assigncount++;
// val=a.val;
// return *this;
// }
~dodgy() {
//if (val!=1234)
std::cerr << "Uninitialised dodgy: " << *this << '\n';
destroycount++;
}
};
std::ostream& operator<< (std::ostream& ostr, const dodgy& a)
{
return ostr << a.val;
}
using namespace libcmatrix;
template<class T> bool stress(T& obj, int left)
{
typedef typename T::value_type Type;
char junk[]="DEADBEEFDEADBEEFDE"; //mess up stack a bit
try {
T newlist(3,mxflag::normal);
std::cout << newlist << '\n';
//newlist=dodgy(5);
//std::cout << newlist << '\n';
newlist.create(4,Type(99));
newlist.push_back(Type(100));
std::cout << newlist << '\n';
//T newlist2(5,Type(3),mxflag::normal);
//std::cout << newlist2 << '\n';
} catch (MatrixException& exc) {
std::cerr << exc << '\n';
return false;
}
if (--left>0)
stress(obj,--left);
return true;
}
int main()
{
List<dodgy> dlist1;
stress(dlist1,3);
std::cout << "Created: " << initcount << '\n';
std::cout << "Copied: " << copycount << '\n';
std::cout << "Destroyed: " << destroycount << '\n';
// std::cout << "Assigned: " << copycount << '\n';
cmatrix b(4,4);
Matrix<int> x(5,5); //this won't show up
for (size_t j=4;j--;) {
cmatrix a(3,3,4.0);
std::cout << a << '\n';
matrix_traits<complex>::allocator::print(std::cout);
}
return 0;
}
| 21.304348
| 61
| 0.557143
|
dch0ph
|
7da38eb297d73de555fa3171db7348109211039c
| 22,360
|
hpp
|
C++
|
include/flusspferd/class_description.hpp
|
Flusspferd/flusspferd
|
f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5
|
[
"MIT"
] | 7
|
2015-06-08T09:59:36.000Z
|
2021-02-27T18:45:17.000Z
|
include/flusspferd/class_description.hpp
|
Flusspferd/flusspferd
|
f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5
|
[
"MIT"
] | null | null | null |
include/flusspferd/class_description.hpp
|
Flusspferd/flusspferd
|
f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5
|
[
"MIT"
] | 3
|
2016-07-06T20:47:01.000Z
|
2021-06-30T19:09:47.000Z
|
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
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.
*/
#ifndef FLUSSFPERD_CLASS_DESCRIPTION_HPP
#define FLUSSFPERD_CLASS_DESCRIPTION_HPP
#ifndef PREPROC_DEBUG
#include "class.hpp"
#include "native_object_base.hpp"
#include "create/function.hpp"
#endif
#include "detail/limit.hpp"
#include <boost/preprocessor.hpp>
#ifndef IN_DOXYGEN
/* 2-tuple seq */
#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2(x, y) \
((x, y)) \
FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS
#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS(x, y) \
((x, y)) \
FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2
#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS_ELIM
#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2_ELIM
#define FLUSSPFERD_PP_GEN_TUPLE2SEQ(x) \
BOOST_PP_CAT(FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS x, _ELIM)
/* 3-tuple seq */
#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2(x, y, z) \
((x, y, z)) \
FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS
#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS(x, y, z) \
((x, y, z)) \
FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2
#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS_ELIM
#define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2_ELIM
#define FLUSSPFERD_PP_GEN_TUPLE3SEQ(x) \
BOOST_PP_CAT(FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS x, _ELIM)
/* -- */
#define FLUSSPFERD_CD_PARAM_FOLD(s, state, elem) \
BOOST_PP_ARRAY_REPLACE( \
state, \
BOOST_PP_EXPAND( \
BOOST_PP_CAT(FLUSSPFERD_CD_PARAM__, \
BOOST_PP_TUPLE_ELEM(2, 0, elem))), \
BOOST_PP_TUPLE_ELEM(2, 1, elem)) \
/* */
#define FLUSSPFERD_CD_PARAM_INITIAL \
(13, ( \
~cpp_name~, /* name */ \
::flusspferd::native_object_base, /* base class */ \
~constructor_name~, /* constructor name */ \
0, /* constructor arity */ \
true, /* constructible */ \
~full_name~, /* full name */ \
(~, none, ~), /* methods */ \
(~, none, ~), /* constructor methods */ \
(~, none, ~), /* properties */ \
(~, none, ~), /* constructor properties */ \
false, /* custom enumerate */ \
0, /* augment constructor (custom func.)*/\
0 /* augment prototype (custom func.) */ \
)) \
/* */
#define FLUSSPFERD_CD_PARAM__cpp_name 0
#define FLUSSPFERD_CD_PARAM__base 1
#define FLUSSPFERD_CD_PARAM__constructor_name 2
#define FLUSSPFERD_CD_PARAM__constructor_arity 3
#define FLUSSPFERD_CD_PARAM__constructible 4
#define FLUSSPFERD_CD_PARAM__full_name 5
#define FLUSSPFERD_CD_PARAM__methods 6
#define FLUSSPFERD_CD_PARAM__constructor_methods 7
#define FLUSSPFERD_CD_PARAM__properties 8
#define FLUSSPFERD_CD_PARAM__constructor_properties 9
#define FLUSSPFERD_CD_PARAM__custom_enumerate 10
#define FLUSSPFERD_CD_PARAM__augment_constructor 11
#define FLUSSPFERD_CD_PARAM__augment_prototype 12
#define FLUSSPFERD_CD_PARAM(tuple_seq) \
BOOST_PP_SEQ_FOLD_LEFT( \
FLUSSPFERD_CD_PARAM_FOLD, \
FLUSSPFERD_CD_PARAM_INITIAL, \
FLUSSPFERD_PP_GEN_TUPLE2SEQ(tuple_seq) \
) \
/* */
#define FLUSSPFERD_CLASS_DESCRIPTION_A(array) \
BOOST_PP_EXPAND(FLUSSPFERD_CLASS_DESCRIPTION_P BOOST_PP_ARRAY_DATA(array)) \
/* */
#define FLUSSPFERD_CLASS_DESCRIPTION_P( \
p_cpp_name, \
p_base, \
p_constructor_name, \
p_constructor_arity, \
p_constructible, \
p_full_name, \
p_methods, \
p_constructor_methods, \
p_properties, \
p_constructor_properties, \
p_custom_enumerate, \
p_augment_constructor, \
p_augment_prototype \
) \
template<typename Class> \
class BOOST_PP_CAT(p_cpp_name, _base) : public p_base { \
public: \
typedef BOOST_PP_CAT(p_cpp_name, _base) base_type; \
struct class_info : ::flusspferd::class_info { \
typedef boost::mpl::bool_< (p_constructible) > constructible; \
static char const *constructor_name() { \
return (p_constructor_name); \
} \
typedef ::boost::mpl::size_t< (p_constructor_arity) > constructor_arity; \
static char const *full_name() { \
return (p_full_name); \
} \
static ::flusspferd::object create_prototype() { \
::flusspferd::root_object obj(::flusspferd::create<flusspferd::object>( \
::flusspferd::prototype< p_base >() \
)); \
FLUSSPFERD_CD_METHODS(p_methods) \
FLUSSPFERD_CD_PROPERTIES(p_properties) \
BOOST_PP_EXPR_IF( \
p_augment_prototype, \
Class :: augment_prototype(obj);) \
return obj; \
} \
static void augment_constructor(::flusspferd::object &obj) { \
(void)obj; \
FLUSSPFERD_CD_METHODS(p_constructor_methods) \
FLUSSPFERD_CD_PROPERTIES(p_constructor_properties) \
BOOST_PP_EXPR_IF( \
p_augment_constructor, \
Class :: augment_constructor(obj);) \
} \
typedef boost::mpl::bool_< (p_custom_enumerate) > custom_enumerate; \
}; \
BOOST_PP_REPEAT( \
BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT), \
FLUSSPFERD_CD_CTOR_FWD, \
(BOOST_PP_CAT(p_cpp_name, _base), p_base)) \
}; \
class p_cpp_name \
: \
public BOOST_PP_CAT(p_cpp_name, _base) < p_cpp_name > \
/* */
#define FLUSSPFERD_CD_CTOR_FWD(z, n, d) \
BOOST_PP_EXPR_IF(n, template<) \
BOOST_PP_ENUM_PARAMS(n, typename P) \
BOOST_PP_EXPR_IF(n, >) \
BOOST_PP_TUPLE_ELEM(2, 0, d) \
( \
BOOST_PP_ENUM_BINARY_PARAMS(n, P, const &p) \
) \
: \
BOOST_PP_TUPLE_ELEM(2, 1, d) \
( \
BOOST_PP_ENUM_PARAMS(n, p) \
) \
{ } \
/* */
#define FLUSSPFERD_CD_METHODS(p_methods) \
BOOST_PP_SEQ_FOR_EACH( \
FLUSSPFERD_CD_METHOD, \
~, \
FLUSSPFERD_PP_GEN_TUPLE3SEQ(p_methods)) \
/* */
#define FLUSSPFERD_CD_METHOD(r, d, p_method) \
BOOST_PP_CAT( \
FLUSSPFERD_CD_METHOD__, \
BOOST_PP_TUPLE_ELEM(3, 1, p_method) \
) ( \
BOOST_PP_TUPLE_ELEM(3, 0, p_method), \
BOOST_PP_TUPLE_ELEM(3, 2, p_method) \
) \
/* */
#define FLUSSPFERD_CD_METHOD__bind(p_method_name, p_bound) \
::flusspferd::create< ::flusspferd::method>( \
::flusspferd::param::_container = obj, \
::flusspferd::param::_name = (p_method_name), \
::flusspferd::param::_function = & Class :: p_bound); \
/* */
#define FLUSSPFERD_CD_METHOD__bind_static(p_method_name, p_bound) \
::flusspferd::create< ::flusspferd::function>( \
::flusspferd::param::_container = obj, \
::flusspferd::param::_name = (p_method_name), \
::flusspferd::param::_function = & Class :: p_bound); \
/* */
#define FLUSSPFERD_CD_METHOD__alias(p_method_name, p_alias) \
obj.define_property( \
(p_method_name), \
obj.get_property((p_alias)), \
::flusspferd::dont_enumerate); \
/* */
#define FLUSSPFERD_CD_METHOD__function(p_method_name, p_expr) \
::flusspferd::create< ::flusspferd::function>( \
::flusspferd::param::_container = obj, \
::flusspferd::param::_name = (p_method_name), \
::flusspferd::param::_function = BOOST_PP_TUPLE_ELEM(2, 1, p_expr), \
::flusspferd::param::_signature = \
::flusspferd::param::type<BOOST_PP_TUPLE_ELEM(2, 0, p_expr)>()); \
/* */
#define FLUSSPFERD_CD_METHOD__method(p_method_name, p_expr) \
::flusspferd::create< ::flusspferd::method>( \
::flusspferd::param::_container = obj, \
::flusspferd::param::_name = (p_method_name), \
::flusspferd::param::_function = BOOST_PP_TUPLE_ELEM(2, 1, p_expr), \
::flusspferd::param::_signature = \
::flusspferd::param::type<BOOST_PP_TUPLE_ELEM(2, 0, p_expr)>()); \
/* */
#define FLUSSPFERD_CD_METHOD__none(p_method_name, p_param) \
/* */
#define FLUSSPFERD_CD_PROPERTIES(p_properties) \
BOOST_PP_SEQ_FOR_EACH( \
FLUSSPFERD_CD_PROPERTY, \
~, \
FLUSSPFERD_PP_GEN_TUPLE3SEQ(p_properties)) \
/* */
#define FLUSSPFERD_CD_PROPERTY(r, d, p_property) \
BOOST_PP_CAT( \
FLUSSPFERD_CD_PROPERTY__, \
BOOST_PP_TUPLE_ELEM(3, 1, p_property) \
) ( \
BOOST_PP_TUPLE_ELEM(3, 0, p_property), \
BOOST_PP_TUPLE_ELEM(3, 2, p_property) \
) \
/* */
#define FLUSSPFERD_CD_PROPERTY__getter_setter(p_property_name, p_param) \
{ \
flusspferd::root_object getter( \
::flusspferd::create< ::flusspferd::method>( \
"$get_" p_property_name, \
& Class :: \
BOOST_PP_TUPLE_ELEM(2, 0, p_param) \
) \
); \
flusspferd::root_object setter( \
::flusspferd::create< ::flusspferd::method>( \
"$set_" p_property_name, \
& Class :: \
BOOST_PP_TUPLE_ELEM(2, 1, p_param) \
) \
); \
obj.define_property( \
(p_property_name), \
::flusspferd::property_attributes( \
::flusspferd::permanent_shared_property, getter, setter)); \
} \
/* */
#define FLUSSPFERD_CD_PROPERTY__getter_setter_expression(p_property_name, p_expr) \
{ \
::flusspferd::root_object getter(::flusspferd::create< ::flusspferd::method>( \
::flusspferd::param::_name = (p_property_name), \
::flusspferd::param::_function = BOOST_PP_TUPLE_ELEM(4, 1, p_expr), \
::flusspferd::param::_signature = \
::flusspferd::param::type<BOOST_PP_TUPLE_ELEM(4, 0, p_expr)>())); \
::flusspferd::root_object setter(::flusspferd::create< ::flusspferd::method>( \
::flusspferd::param::_name = (p_property_name), \
::flusspferd::param::_function = BOOST_PP_TUPLE_ELEM(4, 3, p_expr), \
::flusspferd::param::_signature = \
::flusspferd::param::type<BOOST_PP_TUPLE_ELEM(4, 2, p_expr)>())); \
obj.define_property( \
(p_property_name), \
::flusspferd::property_attributes( \
::flusspferd::permanent_shared_property, getter, setter)); \
} \
/* */
#define FLUSSPFERD_CD_PROPERTY__getter(p_property_name, p_param) \
{ \
::flusspferd::root_object getter( \
::flusspferd::create< ::flusspferd::method>( \
"$get_" p_property_name, \
& Class :: p_param \
) \
); \
obj.define_property( \
(p_property_name), \
::flusspferd::property_attributes( \
::flusspferd::permanent_shared_property \
| ::flusspferd::read_only_property, \
getter \
) \
); \
} \
/* */
#define FLUSSPFERD_CD_PROPERTY__getter_expression(p_property_name, p_expr) \
{ \
::flusspferd::root_object getter(::flusspferd::create< ::flusspferd::method>( \
::flusspferd::param::_name = (p_property_name), \
::flusspferd::param::_function = BOOST_PP_TUPLE_ELEM(2, 1, p_expr), \
::flusspferd::param::_signature = \
::flusspferd::param::type<BOOST_PP_TUPLE_ELEM(2, 0, p_expr)>())); \
obj.define_property( \
(p_property_name), \
::flusspferd::property_attributes( \
::flusspferd::permanent_shared_property \
| ::flusspferd::read_only_property, \
getter \
) \
); \
} \
/* */
#define FLUSSPFERD_CD_PROPERTY__constant(p_property_name, p_param) \
obj.define_property( \
(p_property_name), \
::flusspferd::value((p_param)), \
::flusspferd::read_only_property | ::flusspferd::permanent_property); \
/* */
#define FLUSSPFERD_CD_PROPERTY__variable(p_property_name, p_param) \
obj.define_property( \
(p_property_name), \
::flusspferd::value((p_param))); \
/* */
#define FLUSSPFERD_CD_PROPERTY__none(p_property_name, p_param) \
/* */
#define FLUSSPFERD_CLASS_DESCRIPTION(p_cpp_name, tuple_seq) \
FLUSSPFERD_CLASS_DESCRIPTION_A( \
FLUSSPFERD_CD_PARAM( \
tuple_seq \
(cpp_name, p_cpp_name) \
) \
) \
/* */
#else // IN_DOXYGEN
/**
* Generate a @ref flusspferd::load_class "loadable" class named @p cpp_name.
*
* Also generates a template class <code>cpp_name<em>_base</em><T></code>.
* This class contains a typedef @c base_type to itself, and it is the direct
* base class of @p cpp_name. This implies that inside @p cpp_name, the
* identifier @p base_type can be used to reference the direct base class,
* especially in constructors.
*
* The class @p base_type has forwarding constructors to its base class (by
* default flusspferd::native_object_base), taking each parameter as a constant
* reference to its type. These forwarding constructors can be used to
* initialize the real (indirect) base class.
*
* Most importantly, @p base_type contains a class @c class_info, with all
* elements set according to the named parameters.
*
* <dl><dt><b>Usage template:</b></dt><dd>
* @code
FLUSSPFERD_CLASS_DESCRIPTION(
cpp_name,
(parameter_name_1, parameter_value_1)
(parameter_name_2, parameter_value_2)
...
)
{
CONTENTS
};
* @endcode
* </dd></dl>
*
* @param cpp_name The name of the generated class.
* @param named_parameters A sequence of named parameters in the form
* <code>(parameter1_name, parameter2_value)
* (parameter2_name, parameter2_value) ...</code>
*
* <dl><dt><b>Named parameters:</b></dt>
* <dd><dl>
* <dt><em>base</em> (optional)</dt>
* <dd><b>{Class}</b> The (indirect) base class. Must be derived from
* flusspferd::native_object_base and contain a valid class_info.
* The class' prototype will be used as the prototype of the generated
* prototype (i.e., @c instanceof works).
* <br>Default: flusspferd::native_object_base.
* </dd>
* <dt><em>constructor_name</em> (required)</dt>
* <dd><b>{String}</b> The name of the constructor inside the container passed
* to flusspferd::load_class.</dd>
* <dt><em>constructor_arity</em> (optional)</dt>
* <dd><b>{Integer}</b> The Javascript constructor's arity.
* <br>Default: @c 0.</dd>
* <dt><em>constructible</em> (optional)</dt>
* <dd><b>{Boolean}</b> Whether the class is constructible from Javascript.
* <br>Default: @c true.</dd>
* <dt><em>full_name</em> (required)</dt>
* <dd><b>{String}</b> The full, identifying name of the class, must be
* system-unique.</dd>
* <dt><em>methods</em> (optional)</dt>
* <dd><b>[3-tuple Sequence]</b> Sequence of automatically generated Javascript
* methods. Of the form <code>(method_name, type, parameter)...</code>,
* where @c method_name is a string.
* <br>Default: <code>(~, none, ~)</code></dd>
* <dt><em>constructor_methods</em> (optional)</dt>
* <dd><b>[3-tuple Sequence]</b> Sequence of automatically generated Javascript
* methods <b>on the constructor</b>. Of the form <code>(method_name, type,
* parameter)...</code>,
* where @c method_name is a string.
* <br>Default: <code>(~, none, ~)</code></dd>
* <dt><em>properties</em> (optional)</dt>
* <dd><b>[3-tuple Sequence]</b> Sequence of automatically generated Javascript
* properties. Of the form <code>(property_name, type, parameter)...</code>,
* where @c property_name is a string.
* <br>Default: <code>(~, none, ~)</code></dd>
* <dt><em>constructor_properties</em> (optional)</dt>
* <dd><b>[3-tuple Sequence]</b> Sequence of automatically generated Javascript
* properties <b>on the constructor</b>. Of the form <code>(property_name,
* type, parameter)...</code>,
* where @c property_name is a string.
* <br>Default: <code>(~, none, ~)</code></dd>
* <dt><em>custom_enumerate</em> (optional)</dt>
* <dd><b>{Boolean}</b> Whether the class overrides the standard enumerate
* hooks. (Enables class_info::custom_enumerate.)
* <br>Default: @c true.</dd>
* <dt><em>augment_constructor</em> (optional)</dt>
* <dd><b>{0,1}</b> If set to 1, @p cpp_name::augment_constructor(ctor) will be
* called with the constructor object as parameter when the Javascript
* constructor is being generated by flusspferd::load_class (or more
* specifically, @c base_type::class_info::augment_constructor).
* <br>Default: 0</dd>
* <dt><em>augment_prototype</em> (optional)</dt>
* <dd><b>{0,1}</b> If set to 1, @p cpp_name::augment_prototype(ctor) will be
* called with the prototype object as parameter when the Javascript
* constructor is being generated by flusspferd::load_class (or more
* specifically, @c base_type::class_info::create_prototype).
* <br>Default: 0</dd>
* </dl></dd></dl>
*
* <dl><dt><b>Method types:</b></dt>
* <dd>The parameters @c methods and @c constructor_methods take sequences with elements of
* the form <code>(method_name, <b>type</b>, parameter)</code>, where @c type is one of
* the identifiers mentioned below.
* <br><br>
* <dl>
* <dt><code>(?, <b>none</b>, ?)</code></dt>
* <dd>Generates no method. Used as a dummy of the form <code>(~, none, ~)</code>
* because empty sequences are not valid.</dd>
* <dt><code>(name, <b>bind</b>, method)</code></dt>
* <dd>Binds the method with name @p name to non-static method @c cpp_name::method.</dd>
* <dt><code>(name, <b>bind_static</b>, method)</code></dt>
* <dd>Binds the method with name @p name to the static method @c cpp_name::method.</dd>
* <dt><code>(name, <b>alias</b>, alias_name)</code></dt>
* <dd>Copies the method @p alias_name into a property with name @p name. The method
* @p alias_name must be already defined @em above this method.</dd>
* <dt><code>(name, <b>function</b>, (signature, expression))</code></dt>
* <dd>Add a function expression (a functor or a Boost.Phoenix expression,
* for example) with a given function signature. The class object will
* @em not be passed.
* @note Use (literally) @p Class instead of the class name in the
* expression.</dd>
* <dt><code>(name, <b>method</b>, (signature, expression))</code></dt>
* <dd>Add a function expression (a functor or a Boost.Phoenix expression,
* for example) with a given function signature. The class object
* @em will be passed.
* @note Use (literally) @p Class instead of the class name in the
* expression!</dd>
* </dl>
* </dd></dl>
*
* <dl><dt><b>Property types:</b></dt>
* <dd>The parameters @c properties and @c constructor_properties take sequences with elements
* of the form <code>(property_name, <b>type</b>, parameter)</code>, where @c type is one
* of the identifiers mentioned below.
* <br><br>
* <dl>
* <dt><code>(?, <b>none</b>, ?)</code></dt>
* <dd>Generates no property. Used as a dummy of the form <code>(~, none, ~)</code>
* because empty sequences are not valid.</dd>
* <dt><code>(name, <b>getter_setter</b>, (getter, setter))</code></dt>
* <dd>Generates a property that is accessed through the accessors (non-static methods)
* @p cpp_name::getter and @p cpp_name::setter.</dd>
* <dt><code>(name, <b>getter</b>, getter)</code></dt>
* <dd>Generates a @em constant property that is accessed through the non-static method
* @p cpp_name::getter.</dd>
* <dt><code>(name, <b>variable</b>, initial_value)</code></dt>
* <dd>Generates a standard property with the initial value @p initial_value.</dd>
* <dt><code>(name, <b>constant</b>, value)</code></dt>
* <dd>Generates a constant property with the value @p value.</dd>
* <dt><code>(name, <b>getter_expression</b>, (signature, expression))</code></dt>
* <dd>Generates a @em constant property that is accessed through a getter
* expression (a functor or a Boost.Phoenix expression, for example)
* with a given function signature. The class object @em will be passed.
* @note Use (literally) @p Class instead of the class name in the
* expression!</dd>
* <dt><code>(name, <b>getter_setter_expression</b>, (getter_signature, getter_expression, setter_signature, setter_expression))</code></dt>
* <dd>Generates a property that is accessed through each a getter and
* setter expression (a functor or a Boost.Phoenix expression, for example)
* with a given function signature. The class object @em will be passed.
* @note Use (literally) @p Class instead of the class name in the
* expression!</dd>
* </dl>
* </dd></dl>
*
* <dl><dt><b>Example:</b></dt>
* <dd>
* @code
FLUSSPFERD_CLASS_DESCRIPTION(
my_class,
(full_name, "MyModule.MyClass")
(constructor_name, "MyClass")
(methods,
("myMethod", bind, my_method)
("anotherName", alias, "myMethod"))
(constructor_methods,
("constructorMethod", bind_static, constructor_method))
(constructor_properties,
("VERSION", constant, "1.0")))
{
double my_method(double parameter) {
return parameter * 2;
}
static double constructor_method(double parameter1, int parameter2) {
return parameter1 + parameter1;
}
};
void some_function() {
flusspferd::load_class<my_class>();
}
@endcode
* </dd></dl>
*
* @see flusspferd::load_class, flusspferd::class_info
*
* @ingroup classes
*/
#define FLUSSPFERD_CLASS_DESCRIPTION(cpp_name, named_parameters) ...
#endif // IN_DOXYGEN
#endif
| 38.222222
| 144
| 0.652326
|
Flusspferd
|
7da444fef18e499bc96280f8f86bf5c177b3b49b
| 831
|
cc
|
C++
|
src/Parser/AST/AtomExprNode.cc
|
stenbror/PythonCoreNative
|
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
|
[
"BSL-1.0"
] | 2
|
2021-06-09T12:58:46.000Z
|
2021-06-09T21:06:43.000Z
|
src/Parser/AST/AtomExprNode.cc
|
JeffTheK/PythonCoreNative
|
a5b4c2a4092e39d9094042e88d272f01ae84993d
|
[
"BSL-1.0"
] | null | null | null |
src/Parser/AST/AtomExprNode.cc
|
JeffTheK/PythonCoreNative
|
a5b4c2a4092e39d9094042e88d272f01ae84993d
|
[
"BSL-1.0"
] | 1
|
2021-05-24T11:18:32.000Z
|
2021-05-24T11:18:32.000Z
|
#include <ast/AtomExprNode.h>
using namespace PythonCoreNative::RunTime::Parser::AST;
using namespace PythonCoreNative::RunTime::Parser;
AtomExprNode::AtomExprNode(
unsigned int start, unsigned int end,
std::shared_ptr<Token> op1,
std::shared_ptr<ExpressionNode> left,
std::shared_ptr<std::vector<std::shared_ptr<ExpressionNode>>> right
) : ExpressionNode(start, end)
{
mOp1 = op1;
mLeft = left;
mRight = right;
}
std::shared_ptr<Token> AtomExprNode::GetOperator()
{
return mOp1;
}
std::shared_ptr<ExpressionNode> AtomExprNode::GetLeft()
{
return mLeft;
}
std::shared_ptr<std::vector<std::shared_ptr<ExpressionNode>>> AtomExprNode::GetRight()
{
return mRight;
}
| 25.181818
| 95
| 0.613718
|
stenbror
|
7daa822af90d6f7d460cf32208aa31ca968062ed
| 1,070
|
cpp
|
C++
|
robot-car/sensors/UltrasonicSensor.cpp
|
TanayB11/intro-to-robotics
|
d1f3c936b80837de189461e492e5d3cae9c164bb
|
[
"MIT"
] | null | null | null |
robot-car/sensors/UltrasonicSensor.cpp
|
TanayB11/intro-to-robotics
|
d1f3c936b80837de189461e492e5d3cae9c164bb
|
[
"MIT"
] | null | null | null |
robot-car/sensors/UltrasonicSensor.cpp
|
TanayB11/intro-to-robotics
|
d1f3c936b80837de189461e492e5d3cae9c164bb
|
[
"MIT"
] | null | null | null |
//Ultrasonic Ranger
#define ECHO A4
#define TRIG A5
#include <Servo.h>
Servo rangerServo;
// function prototypes
void allStop();
void forward();
void back();
void right();
void left();
int findRange(){ //Dist in cm
int range;
digitalWrite(TRIG,LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(20);
digitalWrite(TRIG, LOW);
range = pulseIn(ECHO,HIGH); //Pulse width measure in difference of microseconds
range = range/58;
return(range);
delay(500);
}
void setup(){
Serial.begin(9600);
for (int c=0;c<10;c++){
int servoR = 20;
int servoL = 180;
int servoC = 110;
pinMode(ECHO,INPUT);
pinMode(TRIG, OUTPUT);
rangerServo.attach(3);
rangerServo.write(servoL);
delay(1000);
Serial.println(findRange());
rangerServo.write(servoR);
delay(1000);
Serial.println(findRange());
rangerServo.write(servoC);
delay(1000);
Serial.println(findRange());
}
}
void loop(){
}
| 20.980392
| 83
| 0.598131
|
TanayB11
|
7dad0696f55a0708eae5ebfb16be66a70dfa2d75
| 5,203
|
cpp
|
C++
|
server/server_state_game.cpp
|
cschreib/cobalt
|
11184864008f411875a3321f3fb4493ebc9a79e2
|
[
"MIT"
] | 9
|
2015-12-09T22:25:25.000Z
|
2022-01-12T23:50:56.000Z
|
server/server_state_game.cpp
|
cschreib/cobalt
|
11184864008f411875a3321f3fb4493ebc9a79e2
|
[
"MIT"
] | 6
|
2019-12-28T21:18:16.000Z
|
2020-02-15T21:04:54.000Z
|
server/server_state_game.cpp
|
cschreib/cobalt
|
11184864008f411875a3321f3fb4493ebc9a79e2
|
[
"MIT"
] | null | null | null |
#include "server_state_game.hpp"
#include "server_state_idle.hpp"
#include "server_instance.hpp"
#include <filesystem.hpp>
namespace server {
namespace state {
game::game(server::instance& serv) : base(serv, server::state_id::game, "game"), saving_(false) {
// TODO: add all game components to this container
save_chunks_.push_back(universe_.make_serializer());
}
void game::register_callbacks() {
pool_ << net_.watch_request(
[this](server::netcom::request_t<request::server::game_save>&& req) {
try {
save_to_directory(req.arg.save);
req.answer();
} catch (request::server::game_save::failure& fail) {
// Clear load buffers
for (auto& c : save_chunks_) {
c.clear();
}
req.fail(std::move(fail));
} catch (...) {
// Clear load buffers
for (auto& c : save_chunks_) {
c.clear();
}
out_.error("unexpected exception in game::save_to_directory()");
throw;
}
});
pool_ << net_.watch_request(
[this](server::netcom::request_t<request::server::game_load>&& req) {
try {
load_from_directory(req.arg.save);
req.answer();
} catch (request::server::game_load::failure& fail) {
// Clear load buffers
for (auto& c : save_chunks_) {
c.clear();
}
req.fail(std::move(fail));
} catch (...) {
// Clear load buffers
for (auto& c : save_chunks_) {
c.clear();
}
out_.error("unexpected exception in game::load_from_directory()");
throw;
}
});
pool_ << net_.watch_request(
[this](server::netcom::request_t<request::server::stop_and_idle>&& req) {
serv_.set_state<server::state::idle>();
req.answer();
});
}
void game::set_player_list(std::unique_ptr<server::player_list> plist) {
plist_ = std::move(plist);
}
void game::save_to_directory(const std::string& dir) {
using failure = request::server::game_save::failure;
if (saving_) {
throw failure{failure::reason::already_saving, ""};
}
saving_ = true;
// Block the game and bake all game data into serializable structures
net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>(
message::server::game_save_progress::step::gathering_game_data
));
for (auto& c : save_chunks_) {
c.save_data();
}
// Save to disk in the background
net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>(
message::server::game_save_progress::step::saving_to_disk
));
thread_ = std::thread([this, dir]() {
for (auto& c : save_chunks_) {
c.serialize(dir);
}
// Clear buffers
for (auto& c : save_chunks_) {
c.clear();
}
net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>(
message::server::game_save_progress::step::game_saved
));
saving_ = false;
});
}
void game::load_from_directory(const std::string& dir) {
using failure = request::server::game_load::failure;
// The whole game will be blocked during the operation.
if (saving_) {
throw failure{failure::reason::cannot_load_while_saving, ""};
}
if (!file::exists(dir)) {
throw failure{failure::reason::no_such_saved_game, ""};
}
if (!is_saved_game_directory(dir)) {
throw failure{failure::reason::invalid_saved_game, ""};
}
// NOTE: One might need to clear the game state before
std::uint16_t s = 0;
std::uint16_t nchunk = save_chunks_.size();
for (auto& c : save_chunks_) {
net_.send_message(netcom::all_actor_id, make_packet<message::server::game_load_progress>(
nchunk, s, c.name()
));
c.deserialize(dir);
c.load_data_first_pass();
++s;
}
net_.send_message(netcom::all_actor_id, make_packet<message::server::game_load_progress>(
nchunk, nchunk, "loading_second_pass"
));
// A two pass loading is needed for some components
for (auto& c : save_chunks_) {
c.load_data_second_pass();
}
// Clear buffers
for (auto& c : save_chunks_) {
c.clear();
}
}
bool game::is_saved_game_directory(const std::string& dir) const {
for (auto& c : save_chunks_) {
if (!c.is_valid_directory(dir)) {
return false;
}
}
return true;
}
}
}
| 30.605882
| 101
| 0.528733
|
cschreib
|
7daed8b0134aa1554ac7b67d778c39e89a446fe6
| 7,724
|
cpp
|
C++
|
Source/com/Communicator.cpp
|
goruklu/WPEFramework
|
99fc7dd0732dbdd9c332df7ceccb625436ab7a4e
|
[
"Apache-2.0"
] | null | null | null |
Source/com/Communicator.cpp
|
goruklu/WPEFramework
|
99fc7dd0732dbdd9c332df7ceccb625436ab7a4e
|
[
"Apache-2.0"
] | null | null | null |
Source/com/Communicator.cpp
|
goruklu/WPEFramework
|
99fc7dd0732dbdd9c332df7ceccb625436ab7a4e
|
[
"Apache-2.0"
] | null | null | null |
#include "Communicator.h"
namespace WPEFramework {
namespace RPC {
static Core::ProxyPoolType<RPC::AnnounceMessage> AnnounceMessageFactory(2);
static void LoadProxyStubs(const string& pathName)
{
static std::list<Core::Library> processProxyStubs;
Core::Directory index(pathName.c_str(), _T("*.so"));
while (index.Next() == true) {
// Check if this ProxySTub file is already loaded in this process space..
std::list<Core::Library>::const_iterator loop(processProxyStubs.begin());
while ((loop != processProxyStubs.end()) && (loop->Name() != index.Current())) {
loop++;
}
if (loop == processProxyStubs.end()) {
Core::Library library(index.Current().c_str());
if (library.IsLoaded() == true) {
processProxyStubs.push_back(library);
}
}
}
}
void* Communicator::RemoteProcess::Aquire(const uint32_t waitTime, const string& className, const uint32_t interfaceId, const uint32_t versionId)
{
void* result(nullptr);
if (_channel.IsValid() == true) {
Core::ProxyType<RPC::AnnounceMessage> message(AnnounceMessageFactory.Element());
message->Parameters().Set(className, interfaceId, versionId);
uint32_t feedback = _channel->Invoke(message, waitTime);
if (feedback == Core::ERROR_NONE) {
void* implementation = message->Response().Implementation();
if (implementation != nullptr) {
// From what is returned, we need to create a proxy
ProxyStub::UnknownProxy* instance = RPC::Administrator::Instance().ProxyInstance(_channel, implementation, interfaceId, true, interfaceId, false);
result = (instance != nullptr ? instance->QueryInterface(interfaceId) : nullptr);
}
}
}
return (result);
}
Communicator::Communicator(const Core::NodeId& node, Core::ProxyType<IHandler> handler, const string& proxyStubPath)
: _processMap(*this)
, _ipcServer(node, _processMap, handler, proxyStubPath)
{
if (proxyStubPath.empty() == false) {
RPC::LoadProxyStubs(proxyStubPath);
}
// These are the elements we are expecting to receive over the IPC channels.
_ipcServer.CreateFactory<AnnounceMessage>(1);
_ipcServer.CreateFactory<InvokeMessage>(3);
}
/* virtual */ Communicator::~Communicator()
{
// Make sure any closed channel is cleared before we start validating the end result :-)
_ipcServer.Cleanup();
// All process must be terminated if we end up here :-)
ASSERT(_processMap.Size() == 0);
// Close all communication paths...
_ipcServer.Close(Core::infinite);
_ipcServer.DestroyFactory<InvokeMessage>();
_ipcServer.DestroyFactory<AnnounceMessage>();
TRACE_L1("Clearing Communicator. Active Processes %d", _processMap.Size());
}
void Communicator::RemoteProcess::Terminate()
{
ASSERT(_parent != nullptr);
if (_parent != nullptr) {
_parent->Destroy(Id());
}
}
CommunicatorClient::CommunicatorClient(const Core::NodeId& remoteNode, Core::ProxyType<IHandler> handler)
: Core::IPCChannelClientType<Core::Void, false, true>(remoteNode, CommunicationBufferSize)
, _announceMessage(Core::ProxyType<RPC::AnnounceMessage>::Create())
, _announceEvent(false, true)
, _handler(handler)
, _announcements(*this)
{
CreateFactory<RPC::AnnounceMessage>(1);
CreateFactory<RPC::InvokeMessage>(2);
Register(_handler->InvokeHandler());
Register(_handler->AnnounceHandler());
_handler->AnnounceHandler(&_announcements);
// For now clients do not support announce messages from the server...
// Register(_handler->AnnounceHandler());
}
CommunicatorClient::~CommunicatorClient()
{
BaseClass::Close(Core::infinite);
Unregister(_handler->AnnounceHandler());
Unregister(_handler->InvokeHandler());
_handler->AnnounceHandler(nullptr);
DestroyFactory<RPC::InvokeMessage>();
DestroyFactory<RPC::AnnounceMessage>();
}
uint32_t CommunicatorClient::Open(const uint32_t waitTime)
{
ASSERT(BaseClass::IsOpen() == false);
_announceEvent.ResetEvent();
//do not set announce parameters, we do not know what side will offer the interface
uint32_t result = BaseClass::Open(waitTime);
if ((result == Core::ERROR_NONE) && (_announceEvent.Lock(waitTime) != Core::ERROR_NONE)) {
result = Core::ERROR_OPENING_FAILED;
}
return (result);
}
uint32_t CommunicatorClient::Open(const uint32_t waitTime, const string& className, const uint32_t interfaceId, const uint32_t version)
{
ASSERT(BaseClass::IsOpen() == false);
_announceEvent.ResetEvent();
_announceMessage->Parameters().Set(className, interfaceId, version);
uint32_t result = BaseClass::Open(waitTime);
if ((result == Core::ERROR_NONE) && (_announceEvent.Lock(waitTime) != Core::ERROR_NONE)) {
result = Core::ERROR_OPENING_FAILED;
}
return (result);
}
uint32_t CommunicatorClient::Open(const uint32_t waitTime, const uint32_t interfaceId, void* implementation)
{
ASSERT(BaseClass::IsOpen() == false);
_announceEvent.ResetEvent();
_announceMessage->Parameters().Set(interfaceId, implementation, Data::Init::REQUEST);
uint32_t result = BaseClass::Open(waitTime);
if ((result == Core::ERROR_NONE) && (_announceEvent.Lock(waitTime) != Core::ERROR_NONE)) {
result = Core::ERROR_OPENING_FAILED;
}
return (result);
}
uint32_t CommunicatorClient::Close(const uint32_t waitTime)
{
return (BaseClass::Close(waitTime));
}
/* virtual */ void CommunicatorClient::StateChange()
{
BaseClass::StateChange();
if (BaseClass::Source().IsOpen()) {
TRACE_L1("Invoking the Announce message to the server. %d", __LINE__);
uint32_t result = Invoke<RPC::AnnounceMessage>(_announceMessage, this);
TRACE_L1("Todo Announce message handled. %d", __LINE__);
if (result != Core::ERROR_NONE) {
TRACE_L1("Error during invoke of AnnounceMessage: %d", result);
}
} else {
TRACE_L1("Connection to the server is down (ticket has been raised: WPE-255)");
}
}
/* virtual */ void CommunicatorClient::Dispatch(Core::IIPC& element)
{
// Message delivered and responded on....
RPC::AnnounceMessage* announceMessage = static_cast<RPC::AnnounceMessage*>(&element);
ASSERT(dynamic_cast<RPC::AnnounceMessage*>(&element) != nullptr);
// Is result of an announce message, contains default trace categories in JSON format.
string jsonDefaultCategories(announceMessage->Response().TraceCategories());
if (jsonDefaultCategories.empty() == false) {
Trace::TraceUnit::Instance().SetDefaultCategoriesJson(jsonDefaultCategories);
}
string proxyStubPath(announceMessage->Response().ProxyStubPath());
if (proxyStubPath.empty() == false) {
// Also load the ProxyStubs before we do anything else
RPC::LoadProxyStubs(proxyStubPath);
}
// Set event so WaitForCompletion() can continue.
_announceEvent.SetEvent();
}
}
}
| 35.431193
| 166
| 0.625971
|
goruklu
|
7db01b41db6a230d93d36370ee279da8d2d3771c
| 1,954
|
cc
|
C++
|
src/core/basetypes/MCLog.cc
|
zhanleewo/mailcore2
|
a6c2d0465b25351689a1b4761f191201275f2b52
|
[
"BSD-3-Clause"
] | null | null | null |
src/core/basetypes/MCLog.cc
|
zhanleewo/mailcore2
|
a6c2d0465b25351689a1b4761f191201275f2b52
|
[
"BSD-3-Clause"
] | null | null | null |
src/core/basetypes/MCLog.cc
|
zhanleewo/mailcore2
|
a6c2d0465b25351689a1b4761f191201275f2b52
|
[
"BSD-3-Clause"
] | null | null | null |
#include "MCLog.h"
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <pthread.h>
#include <unistd.h>
static pid_t sPid = -1;
bool mailcore::logEnabled = false;
__attribute__((constructor))
static void initialize() {
sPid = getpid();
}
static void logInternalv(FILE * file,
const char * user, const char * filename, unsigned int line,
int dumpStack, const char * format, va_list argp);
void mailcore::logInternal(const char * user,
const char * filename,
unsigned int line,
int dumpStack,
const char * format, ...)
{
va_list argp;
va_start(argp, format);
logInternalv(stderr, user, filename, line, dumpStack, format, argp);
va_end(argp);
}
static void logInternalv(FILE * file,
const char * user, const char * filename, unsigned int line,
int dumpStack, const char * format, va_list argp)
{
if (!mailcore::logEnabled)
return;
while (1) {
const char * p = filename;
p = strchr(filename, '/');
if (p == NULL) {
break;
}
filename = p + 1;
}
struct timeval tv;
struct tm tm_value;
pthread_t thread_id = pthread_self();
gettimeofday(&tv, NULL);
localtime_r(&tv.tv_sec, &tm_value);
fprintf(file, "%04u-%02u-%02u %02u:%02u:%02u.%03u ", tm_value.tm_year + 1900, tm_value.tm_mon + 1, tm_value.tm_mday, tm_value.tm_hour, tm_value.tm_min, tm_value.tm_sec, (int) (tv.tv_usec / 1000));
#ifdef __MACH__
if (pthread_main_np()) {
#else
if (0) {
#endif
fprintf(file, "[%i:main] %s:%i: ", sPid, filename, line);
}
else {
unsigned long threadValue;
#ifdef _MACH_PORT_T
threadValue = pthread_mach_thread_np(thread_id);
#else
threadValue = (unsigned long) thread_id;
#endif
fprintf(file, "[%i:%lx] %s:%i: ", sPid, threadValue, filename, line);
}
vfprintf(file, format, argp);
fprintf(file, "\n");
}
| 24.425
| 197
| 0.631013
|
zhanleewo
|
7db36b23be968d4b9e78291144751234d7bfb4e8
| 1,945
|
cc
|
C++
|
www/cliqz/patches/patch-mozilla-release_media_webrtc_trunk_webrtc_modules_video__capture_linux_device__info__linux.cc
|
fraggerfox/cliqz-pkgsrc
|
61233b17d4c5bc1edeb571ddbf00fb2308c10c5f
|
[
"BSD-2-Clause"
] | null | null | null |
www/cliqz/patches/patch-mozilla-release_media_webrtc_trunk_webrtc_modules_video__capture_linux_device__info__linux.cc
|
fraggerfox/cliqz-pkgsrc
|
61233b17d4c5bc1edeb571ddbf00fb2308c10c5f
|
[
"BSD-2-Clause"
] | null | null | null |
www/cliqz/patches/patch-mozilla-release_media_webrtc_trunk_webrtc_modules_video__capture_linux_device__info__linux.cc
|
fraggerfox/cliqz-pkgsrc
|
61233b17d4c5bc1edeb571ddbf00fb2308c10c5f
|
[
"BSD-2-Clause"
] | null | null | null |
$NetBSD: patch-mozilla-release_media_webrtc_trunk_webrtc_modules_video__capture_linux_device__info__linux.cc,v 1.1 2020/07/24 07:29:32 fox Exp $
* Fix buiuld under NetBSD.
NetBSD's sys/videoio.h does not have v4l2_capability.device_caps
and video capture does not work for me anyway.
Taken from www/firefox
--- mozilla-release/media/webrtc/trunk/webrtc/modules/video_capture/linux/device_info_linux.cc.orig 2020-06-19 00:11:06.000000000 +0000
+++ mozilla-release/media/webrtc/trunk/webrtc/modules/video_capture/linux/device_info_linux.cc
@@ -207,10 +207,12 @@ uint32_t DeviceInfoLinux::NumberOfDevice
sprintf(device, "/dev/video%d", n);
if ((fd = open(device, O_RDONLY)) != -1) {
// query device capabilities and make sure this is a video capture device
+#if !defined(__NetBSD__)
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0 || !(cap.device_caps & V4L2_CAP_VIDEO_CAPTURE)) {
close(fd);
continue;
}
+#endif
close(fd);
count++;
@@ -241,10 +243,12 @@ int32_t DeviceInfoLinux::GetDeviceName(u
sprintf(device, "/dev/video%d", device_index);
if ((fd = open(device, O_RDONLY)) != -1) {
// query device capabilities and make sure this is a video capture device
+#if !defined(__NetBSD__)
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0 || !(cap.device_caps & V4L2_CAP_VIDEO_CAPTURE)) {
close(fd);
continue;
}
+#endif
if (count == deviceNumber) {
// Found the device
found = true;
@@ -328,9 +332,11 @@ int32_t DeviceInfoLinux::CreateCapabilit
struct v4l2_capability cap;
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) == 0) {
// skip devices without video capture capability
+#if !defined(__NetBSD__)
if (!(cap.device_caps & V4L2_CAP_VIDEO_CAPTURE)) {
continue;
}
+#endif
if (cap.bus_info[0] != 0) {
if (strncmp((const char*)cap.bus_info, (const char*)deviceUniqueIdUTF8,
| 39.693878
| 144
| 0.66838
|
fraggerfox
|
7dbb3900d3bf652de4dde9567004d7685874909b
| 12,103
|
hpp
|
C++
|
search/flrtastar.hpp
|
skiesel/search
|
b9bb14810a85d6a486d603b3d81444c9d0b246b0
|
[
"MIT"
] | 28
|
2015-02-10T04:06:16.000Z
|
2022-03-11T11:51:38.000Z
|
search/flrtastar.hpp
|
skiesel/search
|
b9bb14810a85d6a486d603b3d81444c9d0b246b0
|
[
"MIT"
] | 3
|
2016-11-03T12:03:28.000Z
|
2020-07-13T17:35:40.000Z
|
search/flrtastar.hpp
|
skiesel/search
|
b9bb14810a85d6a486d603b3d81444c9d0b246b0
|
[
"MIT"
] | 9
|
2015-10-22T20:22:45.000Z
|
2020-06-30T20:11:31.000Z
|
// Copyright © 2013 the Search Authors under the MIT license. See AUTHORS for the list of authors.
#pragma once
#include "../search/search.hpp"
#include "../utils/geom2d.hpp"
#include "../utils/pool.hpp"
#include <vector>
template <class D>
class Flrtastar2 : public SearchAlgorithm<D> {
private:
typedef typename D::PackedState PackedState;
typedef typename D::Operators Operators;
typedef typename D::State State;
typedef typename D::Cost Cost;
typedef typename D::Oper Oper;
typedef typename D::Edge Edge;
class Node;
class Nodes;
struct inedge {
inedge(Node *n, double c) : node(n), incost(c) {
}
Node *node;
double incost;
};
struct outedge {
outedge(Node *n, Oper o, Cost rc, Cost c) :
node(n),
op(o),
revcost(rc == Cost(-1) ? geom2d::Infinity : rc),
outcost(c == Cost(-1) ? geom2d::Infinity : c) {
}
Node *node;
Oper op;
double revcost;
double outcost;
};
class Node {
public:
static ClosedEntry<Node, D> &closedentry(Node *n) {
return n->closedent;
}
static PackedState &key(Node *n) {
return n->state;
}
PackedState state;
double gglobal, h, hdef;
bool dead;
bool expd; // was this expanded before?
bool goal;
std::vector<outedge> succs;
std::vector<inedge> preds;
private:
friend class Nodes;
friend class Pool<Node>;
Node() : gglobal(geom2d::Infinity), dead(false), expd(false) {
}
ClosedEntry<Node, D> closedent;
};
class Nodes {
public:
Nodes(unsigned int sz) : tbl(sz) {
pool = new Pool<Node>();
}
~Nodes() {
delete pool;
}
void clear() {
tbl.clear();
delete pool;
pool = new Pool<Node>();
}
Node *get(D &d, State &s) {
Node *n = pool->construct();
d.pack(n->state, s);
unsigned long hash = n->state.hash(&d);
Node *found = tbl.find(n->state, hash);
if (found) {
pool->destruct(n);
return found;
}
n->goal = d.isgoal(s);
n->h = n->hdef = d.h(s);
tbl.add(n, hash);
return n;
}
private:
ClosedList<Node, Node, D> tbl;
Pool<Node> *pool;
};
class AstarNode {
public:
AstarNode() : openind(-1), updated(false) {
}
class Nodes {
public:
static ClosedEntry<AstarNode, D> &closedentry(AstarNode *n) {
return n->nodesent;
}
static PackedState &key(AstarNode *n) {
return n->node->state;
}
};
class Closed {
public:
static ClosedEntry<AstarNode, D> &closedentry(AstarNode *n) {
return n->closedent;
}
static PackedState &key(AstarNode *n) {
return n->node->state;
}
};
class FSort {
public:
static void setind(AstarNode *n, int i) {
n->openind = i;
}
static bool pred(AstarNode *a, AstarNode *b) {
if (geom2d::doubleeq(a->f, b->f))
return a->glocal > b->glocal;
return a->f < b->f;
}
};
class HSort {
public:
static void setind(AstarNode *n, int i) {
n->openind = i;
}
static bool pred(AstarNode *a, AstarNode *b) {
return a->node->h < b->node->h;
}
};
Node *node;
AstarNode *parent;
double glocal, f;
Oper op;
long openind;
bool updated;
private:
ClosedEntry<AstarNode, D> closedent, nodesent;
};
public:
Flrtastar2(int argc, const char *argv[]) :
SearchAlgorithm<D>(argc, argv),
astarClosed(1),
astarNodes(1),
nodes(30000001),
lookahead(0) {
for (int i = 0; i < argc; i++) {
if (i < argc - 1 && strcmp(argv[i], "-lookahead") == 0)
lookahead = strtoul(argv[++i], NULL, 10);
}
if (lookahead < 1)
fatal("Must specify a lookahead ≥1 using -lookahead");
astarPool = new Pool<AstarNode>();
astarNodes.resize(lookahead*3);
astarClosed.resize(lookahead*3);
}
~Flrtastar2() {
delete astarPool;
}
void reset() {
SearchAlgorithm<D>::reset();
nodes.clear();
astarOpen.clear();
astarClosed.clear();
astarNodes.clear();
delete astarPool;
astarPool = new Pool<AstarNode>();
}
void search(D &d, State &s0) {
this->start();
Node *cur = nodes.get(d, s0);
cur->gglobal = 0;
while (!cur->goal && !this->limit()) {
AstarNode *goal = expandLss(d, cur);
if (!goal && !this->limit()) {
gCostLearning(d);
hCostLearning(d);
markDeadRedundant(d);
}
cur = move(cur, goal);
times.push_back(walltime() - this->res.wallstart);
}
this->finish();
if (!cur->goal) {
this->res.ops.clear();
return;
}
// Rebuild the path from the operators.
nodes.clear();
this->res.path.push_back(s0);
for (auto it = this->res.ops.begin(); it != this->res.ops.end(); it++) {
State copy = this->res.path.back();
Edge e(d, copy, *it);
this->res.path.push_back(e.state);
}
std::reverse(this->res.ops.begin(), this->res.ops.end());
std::reverse(this->res.path.begin(), this->res.path.end());
}
virtual void output(FILE *out) {
SearchAlgorithm<D>::output(out);
dfpair(out, "num steps", "%lu", (unsigned long) times.size());
assert (lengths.size() == times.size());
if (times.size() != 0) {
double min = times.front();
double max = times.front();
for (unsigned int i = 1; i < times.size(); i++) {
double dt = times[i] - times[i-1];
if (dt < min)
min = dt;
if (dt > max)
max = dt;
}
dfpair(out, "first emit wall time", "%f", times.front());
dfpair(out, "min step wall time", "%f", min);
dfpair(out, "max step wall time", "%f", max);
dfpair(out, "mean step wall time", "%f", (times.back()-times.front())/times.size());
}
if (lengths.size() != 0) {
unsigned int min = lengths.front();
unsigned int max = lengths.front();
unsigned long sum = 0;
for (auto l : lengths) {
if (l < min)
min = l;
if (l > max)
max = l;
sum += l;
}
dfpair(out, "min step length", "%u", min);
dfpair(out, "max step length", "%u", max);
dfpair(out, "mean step length", "%g", sum / (double) lengths.size());
}
}
private:
// ExpandLss returns the cheapest goal node if one was generated
// and NULL otherwise.
AstarNode *expandLss(D &d, Node *rootNode) {
astarOpen.clear();
for (auto n : astarNodes)
astarPool->destruct(n);
astarNodes.clear();
astarClosed.clear();
AstarNode *a = astarPool->construct();
a->node = rootNode;
a->parent = NULL;
a->op = D::Nop;
a->glocal = 0;
a->f = rootNode->h;
astarOpen.push(a);
astarNodes.add(a);
AstarNode *goal = NULL;
for (unsigned int exp = 0; !astarOpen.empty() && exp < lookahead && !this->limit(); exp++) {
AstarNode *s = *astarOpen.pop();
if (!astarClosed.find(s->node->state))
astarClosed.add(s);
if (s->node->dead)
continue;
AstarNode *g = expandPropagate(d, s, true);
if (g && (!goal || g->glocal < goal->glocal))
goal = g;
if (s->node->goal) {
astarOpen.push(s);
goal = s;
break;
}
}
return goal;
}
// ExpandPropagate returns the cheapest goal node if one is generated
// and NULL otherwise.
AstarNode *expandPropagate(D &d, AstarNode *s, bool doExpand) {
AstarNode *goal = NULL;
if (this->limit())
return NULL;
auto kids = expand(d, s->node);
for (unsigned int i = 0; i < kids.size(); i++) {
auto e = kids[i];
Node *k = e.node;
AstarNode *kid = astarNodes.find(k->state);
if (doExpand && astarNodes.find(s->node->state)) {
if (!kid) {
kid = astarPool->construct();
kid->node = k;
kid->glocal = geom2d::Infinity;
kid->openind = -1;
astarNodes.add(kid);
}
if (kid->glocal > s->glocal + e.outcost) {
if (kid->parent) // !NULL if a dup
this->res.dups++;
kid->parent = s;
kid->glocal = s->glocal + e.outcost;
kid->f = kid->glocal + kid->node->h;
kid->op = e.op;
astarOpen.pushupdate(kid, kid->openind);
}
}
if (k->goal && kid && (!goal || kid->glocal < goal->glocal))
goal = kid;
if (s->node->gglobal + e.outcost < k->gglobal) {
bool wasDead = k->dead;
k->dead = false;
k->gglobal = s->node->gglobal + e.outcost;
// k->h = k->hdef;
bool onClosed = astarClosed.find(k->state);
if (kid && onClosed && wasDead)
expandPropagate(d, kid, true);
else if (kid && (kid->openind >= 0 || onClosed))
expandPropagate(d, kid, false);
}
if (k->gglobal + e.revcost < s->node->gglobal && !k->dead) {
s->node->gglobal = k->gglobal + e.revcost;
// s->node->h = s->node->hdef;
if (i > 0)
i = -1;
}
}
return goal;
}
void gCostLearning(D &d) {
std::vector<AstarNode*> &o = astarOpen.data();
for (unsigned int i = 0; i < o.size(); i++) {
if (!o[i]->node->dead)
expandPropagate(d, o[i], false);
}
}
void hCostLearning(D &d) {
BinHeap<typename AstarNode::HSort, AstarNode*> open;
open.append(astarOpen.data());
unsigned long left = astarClosed.getFill();
while (left > 0 && !open.empty()) {
AstarNode *s = *open.pop();
if (astarClosed.find(s->node->state))
left--;
for (auto e : s->node->preds) {
Node *sprime = e.node;
AstarNode *sp = astarClosed.find(sprime->state);
if (!sp)
continue;
if (!sp->updated || sprime->h > e.incost + s->node->h) {
sprime->h = e.incost + s->node->h;
sp->updated = true;
open.pushupdate(sp, sp->openind);
}
}
}
}
void markDeadRedundant(D &d) {
for (auto n : astarClosed) {
assert(!n->node->goal);
if (n->node->dead) // || n->node->goal)
continue;
n->node->dead = isDead(d, n->node) || isRedundant(d, n->node);
}
for (auto n : astarOpen.data()) {
if (n->node->dead || n->node->goal)
continue;
assert (!std::isinf(n->node->gglobal));
n->node->dead = isDead(d, n->node) || isRedundant(d, n->node);
}
}
bool isDead(D &d, Node *n) {
for (auto succ : expand(d, n)) {
if (succ.node->gglobal >= n->gglobal + succ.outcost)
return false;
}
return true;
}
bool isRedundant(D &d, Node *n) {
for (auto succ : expand(d, n)) {
if (succ.node->dead)
continue;
// The distinct predecessor with minimum f was the earliest
// to be expanded.
Node *distinct = NULL;
double bestc = geom2d::Infinity;
for (auto pred : succ.node->preds) {
if (pred.node->dead)
continue;
double c = pred.node->gglobal + pred.incost;
if (!distinct || c < bestc) {
distinct = pred.node;
bestc = c;
}
assert (distinct == n || !std::isinf(succ.node->gglobal));
}
if (distinct == n)
return false;
}
return true;
}
Node *move(Node *cur, AstarNode *goal) {
AstarNode *best = goal;
if (!best) {
for (auto n : astarOpen.data()) {
if (n->node == cur || n->node->dead)
continue;
if (best == NULL || AstarNode::FSort::pred(n, best))
best = n;
}
}
if (best) {
assert (best->node != cur);
std::vector<Oper> ops;
for (AstarNode *p = best; p->node != cur; p = p->parent) {
assert (p->parent != best); // no cycles
ops.push_back(p->op);
}
this->res.ops.insert(this->res.ops.end(), ops.rbegin(), ops.rend());
lengths.push_back(ops.size());
return best->node;
}
outedge next = cur->succs[0];
for (unsigned int i = 1; i < cur->succs.size(); i++) {
if (cur->succs[i].node->gglobal < next.node->gglobal)
next = cur->succs[i];
}
this->res.ops.push_back(next.op);
lengths.push_back(1);
return next.node;
}
// Expand returns the successor nodes of a state.
std::vector<outedge> expand(D &d, Node *n) {
assert(!n->dead);
if (n->expd)
return n->succs;
State buf, &s = d.unpack(buf, n->state);
this->res.expd++;
Operators ops(d, s);
for (unsigned int i = 0; i < ops.size(); i++) {
this->res.gend++;
Edge e(d, s, ops[i]);
Node *k = nodes.get(d, e.state);
if (std::isinf(k->gglobal))
k->gglobal = n->gglobal + e.cost;
k->preds.emplace_back(n, e.cost);
n->succs.emplace_back(k, ops[i], e.revcost, e.cost);
}
n->expd = true;
return n->succs;
}
BinHeap<typename AstarNode::FSort, AstarNode*> astarOpen;
ClosedList<typename AstarNode::Closed, AstarNode, D> astarClosed;
ClosedList<typename AstarNode::Nodes, AstarNode, D> astarNodes;
Pool<AstarNode> *astarPool;
Nodes nodes;
unsigned int lookahead;
std::vector<double> times;
std::vector<unsigned int> lengths;
};
| 22.207339
| 98
| 0.590102
|
skiesel
|
7dbe445dba5f2fdc6d304dc5747b534460221d13
| 626
|
hpp
|
C++
|
src/shader.hpp
|
qkniep/Simetra
|
734292ff3d48afd83f811501d8da39f5bb0d3623
|
[
"MIT"
] | 2
|
2021-01-07T15:30:36.000Z
|
2021-06-13T21:47:46.000Z
|
src/shader.hpp
|
qkniep/Simetra
|
734292ff3d48afd83f811501d8da39f5bb0d3623
|
[
"MIT"
] | null | null | null |
src/shader.hpp
|
qkniep/Simetra
|
734292ff3d48afd83f811501d8da39f5bb0d3623
|
[
"MIT"
] | null | null | null |
#ifndef SHADER_HPP
#define SHADER_HPP
#include <string>
#include <GLFW/glfw3.h>
class ShaderProgram {
GLuint programID;
public:
bool load(const char* vertexFilePath, const char* fragmentFilePath);
void use();
GLuint getProgramID();
private:
static bool loadShaderFromFile(const GLuint shaderID, const char* filePath);
static bool readShaderCodeFromFile(std::string& shaderCode, const char* filePath);
static bool compileShader(const GLuint shaderID, const std::string& shaderCode);
void linkProgram(const GLuint vertexShaderID, const GLuint fragmentShaderID);
};
#endif // SHADER_HPP
| 24.076923
| 84
| 0.749201
|
qkniep
|
7dc2e2f3b3958394ab573ab39b079a6f0d422ff1
| 16,397
|
cc
|
C++
|
examples/tester/wampcc_tester.cc
|
vai-hhn/wampcc
|
ac206f60028406ea8af4c295e11cbc7de67cf2ad
|
[
"MIT"
] | 70
|
2017-03-09T12:45:30.000Z
|
2021-12-31T20:34:40.000Z
|
examples/tester/wampcc_tester.cc
|
vai-hhn/wampcc
|
ac206f60028406ea8af4c295e11cbc7de67cf2ad
|
[
"MIT"
] | 54
|
2017-04-15T23:02:08.000Z
|
2021-04-13T08:44:25.000Z
|
examples/tester/wampcc_tester.cc
|
vai-hhn/wampcc
|
ac206f60028406ea8af4c295e11cbc7de67cf2ad
|
[
"MIT"
] | 30
|
2017-06-02T14:12:28.000Z
|
2021-12-06T07:28:48.000Z
|
/*
* Copyright (c) 2017 Darren Smith
*
* wampcc is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "wampcc/wampcc.h"
#include "wampcc/utils.h"
#include <algorithm>
#include <sstream>
#include <getopt.h> /* for getopt_long; standard getopt is in unistd.h */
#define LOG(X) \
do { \
auto level = wampcc::logger::eInfo; \
if (logger.wants_level && logger.write && logger.wants_level(level)) { \
std::ostringstream __xx_oss; \
__xx_oss << X; \
logger.write(level, __xx_oss.str(), __FILE__, __LINE__); \
} \
} while (0)
const std::string uri_double = "double";
enum class role { invalid = 0, router, callee, caller, publisher, subscriber };
wampcc::wamp_args const final_item {{"final"},{{"final",1}}};
struct user_options
{
enum class transport {
rawsocket,
websocket,
} session_transport = transport::websocket;
int serialisers = wampcc::all_serialisers;
wampcc::user_optional<std::string> admin_port;
wampcc::user_optional<std::string> port;
wampcc::user_optional<int> count;
role program_role = role::invalid;
std::string realm = "default_realm";
bool debug = false;
bool use_websocket = false;
bool use_ssl = false;
} uopts;
wampcc::logger logger;
class tester
{
private:
std::unique_ptr<wampcc::kernel> m_kernel;
std::shared_ptr<wampcc::wamp_router> m_router;
std::shared_ptr<wampcc::wamp_router> m_admin;
std::shared_ptr<wampcc::wamp_session> m_callee;
std::shared_ptr<wampcc::wamp_session> m_subscriber;
std::vector<wampcc::wamp_args> m_subscription_data;
public:
// control when main thread can exit
std::promise<int> can_exit;
void create_kernel()
{
auto loglevel =
uopts.debug ? wampcc::logger::eDebug : wampcc::logger::eInfo;
logger = wampcc::logger::stream(wampcc::logger::lockable_cout,
wampcc::logger::levels_upto(loglevel));
m_kernel.reset(new wampcc::kernel({}, logger));
}
void create_router()
{
m_router.reset(new wampcc::wamp_router(m_kernel.get()));
logger.write(wampcc::logger::eInfo,
"router listening on " + uopts.port.value(), __FILE__,
__LINE__);
m_router->listen(wampcc::auth_provider::no_auth_required(),
std::atoi(uopts.port.value().c_str()));
}
std::shared_ptr<wampcc::wamp_session> connect_and_logon()
{
std::string host = "127.0.0.1";
std::unique_ptr<wampcc::tcp_socket> sock(
new wampcc::tcp_socket(m_kernel.get()));
auto fut = sock->connect(host, uopts.port.value());
if (fut.wait_for(std::chrono::milliseconds(250)) !=
std::future_status::ready)
throw std::runtime_error("timeout during connect");
if (auto ec = fut.get())
throw std::runtime_error("connect failed: " +
std::to_string(ec.os_value()) + ", " +
ec.message());
auto on_session_state = [this](wampcc::wamp_session&, bool is_open) {
if (!is_open)
try {
this->can_exit.set_value(0);
} catch (...) { /* ignore promise already set error */
}
};
std::shared_ptr<wampcc::wamp_session> session;
switch (uopts.session_transport) {
case user_options::transport::websocket: {
wampcc::websocket_protocol::options proto_opts;
proto_opts.serialisers = uopts.serialisers;
session = wampcc::wamp_session::create<wampcc::websocket_protocol>(
m_kernel.get(), std::move(sock), on_session_state, proto_opts);
break;
}
case user_options::transport::rawsocket: {
wampcc::rawsocket_protocol::options proto_opts;
proto_opts.serialisers = uopts.serialisers;
session = wampcc::wamp_session::create<wampcc::rawsocket_protocol>(
m_kernel.get(), std::move(sock), on_session_state, proto_opts);
break;
}
}
wampcc::client_credentials credentials;
credentials.realm = uopts.realm;
auto logon_fut = session->hello(credentials);
if (logon_fut.wait_for(std::chrono::seconds(5)) !=
std::future_status::ready)
throw std::runtime_error("time-out during wamp session logon");
if (!session->is_open())
throw std::runtime_error("wamp session logon failed");
return session;
}
void create_callee()
{
std::shared_ptr<wampcc::wamp_session> session = connect_and_logon();
wampcc::json_object options;
std::promise<std::tuple<bool, std::string>> promise;
auto on_result = [&](wampcc::wamp_session&, wampcc::registered_info info) {
bool is_good = !info.was_error;
std::string error_uri = info.error_uri;
std::tuple<bool, std::string> result{is_good, error_uri};
promise.set_value(result);
};
auto on_invoke = [](wampcc::wamp_session& ws,
wampcc::invocation_info invoc) {
for (auto& item : invoc.args.args_list)
if (item.is_string())
item = item.as_string() + item.as_string();
ws.yield(invoc.request_id, std::move(invoc.args.args_list));
};
session->provide(uri_double, options, std::move(on_result),
std::move(on_invoke));
auto fut = promise.get_future();
if (fut.wait_for(std::chrono::seconds(1)) != std::future_status::ready)
throw std::runtime_error("timeout during rpc registration");
auto result = fut.get();
if (std::get<0>(result) == false)
throw std::runtime_error("rpc registration failed: " +
std::get<1>(result));
m_callee = std::move(session);
}
void create_caller()
{
if (!uopts.count)
throw std::runtime_error("missing count");
std::shared_ptr<wampcc::wamp_session> session = connect_and_logon();
for (int i = 0; i < uopts.count.value(); i++) {
std::promise<wampcc::result_info> promised_result;
wampcc::wamp_args call_args;
call_args.args_list = {"hello", "world", std::to_string(i)};
session->call(uri_double, {}, call_args, [&](wampcc::wamp_session&, wampcc::result_info r) {
try {
promised_result.set_value(r);
} catch (...) { /* ignore promise already set error */ }
});
auto fut = promised_result.get_future();
if (fut.wait_for(std::chrono::seconds(1)) != std::future_status::ready)
throw std::runtime_error("timeout during call");
auto result = fut.get();
if (result.was_error)
throw std::runtime_error("call error: " + result.error_uri);
// expected value
for (auto& item : call_args.args_list)
if (item.is_string())
item = item.as_string() + item.as_string();
if (call_args != result.args)
throw std::runtime_error("rpc result did not match expected");
}
LOG("rpc result successful, closing session");
if (session->close().wait_for(std::chrono::seconds(1))
!= std::future_status::ready)
throw std::runtime_error("timeout during session close");
}
void create_admin_port()
{
m_admin.reset(new wampcc::wamp_router(m_kernel.get()));
logger.write(wampcc::logger::eInfo,
"admin listening on " + uopts.admin_port.value(), __FILE__,
__LINE__);
std::future<wampcc::uverr> futerr =
m_admin->listen(wampcc::auth_provider::no_auth_required(),
std::atoi(uopts.admin_port.value().c_str()));
if (futerr.wait_for(std::chrono::milliseconds(250)) !=
std::future_status::ready)
throw std::runtime_error("timeout during listen(admin)");
if (auto ec = futerr.get())
throw std::runtime_error("listen failed: " +
std::to_string(ec.os_value()) + ", " +
ec.message());
m_admin->callable("default_realm", "stop",
[this](wampcc::wamp_router&, wampcc::wamp_session&, wampcc::call_info) {
this->can_exit.set_value(0);
});
}
std::vector<wampcc::wamp_args> data_set() const
{
std::vector<wampcc::wamp_args> retval;
retval.reserve(uopts.count.value()+1);
for (int i = 0; i < uopts.count.value(); i++) {
wampcc::wamp_args args;
args.args_list.push_back(wampcc::json_value::make_uint(i));
retval.push_back(std::move(args));
}
retval.push_back(final_item);
return retval;
}
void create_publisher()
{
if (!uopts.count)
throw std::runtime_error("missing count");
{
std::shared_ptr<wampcc::wamp_session> session = connect_and_logon();
std::string uri_numbers_topic = "numbers";
auto data_to_send = data_set();
for (auto& item : data_to_send)
session->publish(uri_numbers_topic, {}, std::move(item));
}
can_exit.set_value(0);
}
void create_subscriber()
{
if (!uopts.count)
throw std::runtime_error("missing count");
auto data_execpt = data_set();
decltype(data_execpt) data_actual;
std::shared_ptr<wampcc::wamp_session> session = connect_and_logon();
std::promise<wampcc::subscribed_info> promised_result;
auto on_subscribed = [&](wampcc::wamp_session&, wampcc::subscribed_info r) {
promised_result.set_value(std::move(r));
};
auto on_event = [this](wampcc::wamp_session&, wampcc::event_info info) {
LOG("subscription event: " << info.args.args_list);
bool is_final = info.args == final_item;
m_subscription_data.push_back(std::move(info.args));
if (is_final) {
auto expect = data_set();
if (m_subscription_data == expect) {
LOG("received expected data set");
can_exit.set_value(0);
}
else {
LOG("received unexpected data set");
can_exit.set_value(1);
}
}
};
std::string uri_numbers_topic = "numbers";
wampcc::json_object options;
wampcc::wamp_args args;
session->subscribe(uri_numbers_topic, options, on_subscribed, on_event);
auto fut = promised_result.get_future();
if (fut.wait_for(std::chrono::seconds(1)) != std::future_status::ready)
throw std::runtime_error("timeout during subscribe");
auto subscribed_result = fut.get();
if (subscribed_result.was_error)
throw std::runtime_error("subscribe error: " +
subscribed_result.error_uri);
m_subscriber = std::move(session);
}
};
void parse_proto(const char* src)
{
for (auto str : wampcc::tokenize(src, ',', false)) {
if (str == "web")
uopts.session_transport = user_options::transport::websocket;
else if (str == "raw")
uopts.session_transport = user_options::transport::rawsocket;
else if (str == "ssl")
uopts.use_ssl = true;
else if (str == "json")
uopts.serialisers = static_cast<int>(wampcc::serialiser_type::json);
else if (str == "msgpack")
uopts.serialisers = static_cast<int>(wampcc::serialiser_type::msgpack);
else
throw std::runtime_error("unknown proto flag");
}
}
#define HELPLN(X, S, T) std::cout << " " << X << S << T << std::endl
void usage()
{
const char* sp1 = "\t";
const char* sp2 = "\t\t";
std::cout << "usage: wampcc_tester [OPTIONS]" << std::endl;
std::cout << "Options:" << std::endl;
HELPLN("--router", sp2, "router role");
HELPLN("--caller", sp2, "caller role");
HELPLN("--callee", sp2, "callee role");
HELPLN("--subscriber", sp2, "subscriber role");
HELPLN("--publisher", sp2, "publisher role");
HELPLN("-a, --admin_port=ARG", sp1, "specify admin port");
HELPLN("-p, --port", sp2, "wamp connection port");
HELPLN("-d, --debug", sp2, "increased logging");
HELPLN("-c, --count=N", sp2, "number of messages to-send / expect-receive");
HELPLN("--proto PROTO_OPTS", sp1,
"comma separated list of options, default 'web,json'");
std::cout << std::endl << "Protocol options:" << std::endl
<< " web - select websocket protocol" << std::endl
<< " raw - select rawsocket protocol" << std::endl
<< " json - support only json serialiser" << std::endl
<< " msgpack - support only msgpack serialiser" << std::endl;
exit(0);
}
static void process_options(int argc, char** argv)
{
/*
struct option
{
const char *name;
int has_arg;
int *flag;
int val;
};
*/
// these enums are used for options that don't have a short version
enum {
OPT_NO_URI_CHECK = 1,
OPT_ARGLIST,
OPT_ARGDICT,
OPT_TIMEOUT,
OPT_PROTO,
OPT_ROUTER,
OPT_CALLEE,
OPT_CALLER,
OPT_PUBLISHER,
OPT_SUBSCRIBER
};
// int digit_optind = 0;
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"router", no_argument, 0, OPT_ROUTER},
{"callee", no_argument, 0, OPT_CALLEE},
{"caller", no_argument, 0, OPT_CALLER},
{"publisher", no_argument, 0, OPT_PUBLISHER},
{"subscriber", no_argument, 0, OPT_SUBSCRIBER},
{"proto", required_argument, 0, OPT_PROTO},
{"admin_port", required_argument, 0, 'a'},
{"port", required_argument, 0, 'p'},
{"debug", no_argument, 0, 'd'},
{"count", required_argument, 0, 'c'},
{NULL, 0, NULL, 0}};
const char* optstr = "hp:a:dc:"; // short opt string
::opterr = 1;
while (true) {
/* "optind" is the index of the next element to be processed in argv. It
is defined in the getopts header, and the system initializes this value
to 1. The caller can reset it to 1 to restart scanning of the same
argv, or when scanning a new argument vector. */
// take a copy to remember value for after return from getopt_long()
// int this_option_optind = ::optind ? ::optind : 1;
int long_index = 0;
int c = getopt_long(argc, argv, optstr, long_options, &long_index);
if (c == -1)
break;
switch (c) {
case OPT_PROTO:
parse_proto(optarg);
break;
case OPT_ROUTER:
uopts.program_role = role::router;
break;
case OPT_CALLER:
uopts.program_role = role::caller;
break;
case OPT_PUBLISHER:
uopts.program_role = role::publisher;
break;
case OPT_SUBSCRIBER:
uopts.program_role = role::subscriber;
break;
case OPT_CALLEE:
uopts.program_role = role::callee;
break;
case 'a':
uopts.admin_port = optarg;
break;
case 'p':
uopts.port = optarg;
break;
case 'd':
uopts.debug = true;
break;
case 'h':
usage();
break;
case 'c':
uopts.count = std::atoi(optarg);
break;
case '?':
exit(1); // invalid option
default: {
std::cout << "unknown option: -" << char(c) << "\n";
exit(1);
}
}
} // while
if (uopts.program_role == role::invalid)
throw std::runtime_error("missing role");
if (!uopts.port)
throw std::runtime_error("missing port");
}
int main_impl(int argc, char** argv)
{
process_options(argc, argv);
tester impl;
impl.create_kernel();
if (uopts.admin_port)
impl.create_admin_port();
switch (uopts.program_role) {
case role::invalid:
throw std::runtime_error("role not specified");
break;
case role::router:
impl.create_router();
break;
case role::callee:
impl.create_callee();
break;
case role::caller:
impl.create_caller();
break;
case role::publisher:
impl.create_publisher();
break;
case role::subscriber:
impl.create_subscriber();
break;
}
/* Suspend main thread */
int result = impl.can_exit.get_future().get();
return result;
}
int main(int argc, char** argv)
{
try {
return main_impl(argc, argv);
} catch (std::exception& e) {
std::cout << "error, " << e.what() << std::endl;
return 1;
}
}
| 30.252768
| 98
| 0.598707
|
vai-hhn
|
7dc9018939e96b62f6b2f0ff121a5a036f7089ce
| 1,375
|
hpp
|
C++
|
include/euclidean2/object/water.hpp
|
Euclidean-Entertainment/Assignment_2
|
04a855f3cec41c9046340b3248d32e5acb94c221
|
[
"BSD-3-Clause"
] | 1
|
2018-05-03T03:57:29.000Z
|
2018-05-03T03:57:29.000Z
|
include/euclidean2/object/water.hpp
|
Euclidean-Entertainment/Assignment_2
|
04a855f3cec41c9046340b3248d32e5acb94c221
|
[
"BSD-3-Clause"
] | 1
|
2018-05-04T14:17:53.000Z
|
2018-05-04T14:17:53.000Z
|
include/euclidean2/object/water.hpp
|
Euclidean-Entertainment/Assignment_2
|
04a855f3cec41c9046340b3248d32e5acb94c221
|
[
"BSD-3-Clause"
] | 2
|
2018-05-03T03:57:32.000Z
|
2018-05-20T12:01:55.000Z
|
/**
*
*/
#ifndef _WATER_HPP_INCLUDED_
#define _WATER_HPP_INCLUDED_
#include "euclidean2/vertex.hpp"
#include "euclidean2/system/material.hpp"
#include "euclidean2/system/texture.hpp"
#include <climits>
#include <vector>
static constexpr int MIN_TESSELATIONS = 16;
static constexpr int MAX_TESSELATIONS = 512;
struct water_t
{
int tesselations = MIN_TESSELATIONS;
vertex3f_t verts[MAX_TESSELATIONS][MAX_TESSELATIONS];
material_t mat;
};
struct ground_t
{
vertex3f_t verts[128][128]; // We don't need too many tesselations for the seafloor
texture_t tex;
material_t mat;
};
/**
* Generate our water using triangle strips
*/
void water_generate(water_t& water);
/**
* Actually draw the quad strip
*/
void water_draw(water_t& water, bool drawNorms);
/**
* Animate our water
*/
void water_animate(water_t& water, float t, int numWaves);
/**
* Draw the seafloor
*/
void water_drawGround(ground_t& ground);
/**
*
*/
static inline void water_increaseTesselations(water_t& water)
{
if(water.tesselations < MAX_TESSELATIONS)
{
water.tesselations *= 2;
water_generate(water);
}
}
/**
*
*/
static inline void water_decreaseTesselations(water_t& water)
{
if(water.tesselations > MIN_TESSELATIONS)
{
water.tesselations /= 2;
water_generate(water);
}
}
#endif
| 17.628205
| 88
| 0.688727
|
Euclidean-Entertainment
|
7dca48bbb88ede97a25fd4a70ba9b8ec9b17992b
| 1,284
|
cpp
|
C++
|
GeeksForGeeks/C Plus Plus/K_largest_elements.cpp
|
ankit-sr/Competitive-Programming
|
3397b313b80a32a47cfe224426a6e9c7cf05dec2
|
[
"MIT"
] | 4
|
2021-06-19T14:15:34.000Z
|
2021-06-21T13:53:53.000Z
|
GeeksForGeeks/C Plus Plus/K_largest_elements.cpp
|
ankit-sr/Competitive-Programming
|
3397b313b80a32a47cfe224426a6e9c7cf05dec2
|
[
"MIT"
] | 2
|
2021-07-02T12:41:06.000Z
|
2021-07-12T09:37:50.000Z
|
GeeksForGeeks/C Plus Plus/K_largest_elements.cpp
|
ankit-sr/Competitive-Programming
|
3397b313b80a32a47cfe224426a6e9c7cf05dec2
|
[
"MIT"
] | 3
|
2021-06-19T15:19:20.000Z
|
2021-07-02T17:24:51.000Z
|
/*
Problem Statement:
-----------------
Given an array Arr of N positive integers, find K largest elements from the array. The output elements should be printed in decreasing order.
Example 1:
---------
Input:
N = 5, K = 2
Arr[] = {12, 5, 787, 1, 23}
Output: 787 23
Explanation: 1st largest element in the array is 787 and second largest is 23.
Example 2:
---------
Input:
N = 7, K = 3
Arr[] = {1, 23, 12, 9, 30, 2, 50}
Output: 50 30 23
Explanation: 3 Largest element in the array are 50, 30 and 23.
Your Task: You don't need to read input or print anything. Your task is to complete the function kLargest() which takes the array of integers arr,
n and k as parameters and returns an array of integers denoting the answer. The array should be in decreasing order.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(K*logK)
*/
// Link --> https://practice.geeksforgeeks.org/problems/k-largest-elements4206/1#
// Code:
class Solution{
public:
vector <int> kLargest(int a[], int n, int k)
{
vector <int> answer;
priority_queue <int> maxHeap;
for(int i=0 ; i<n ; i++)
maxHeap.push(a[i]);
for(int i=0 ; i<k ; i++)
{
answer.push_back(maxHeap.top());
maxHeap.pop();
}
return answer;
}
};
| 24.226415
| 148
| 0.639408
|
ankit-sr
|
7dd0ff3c07426231bb6aeb7e8dde943472e08431
| 2,549
|
cpp
|
C++
|
Engine/GameObject.cpp
|
rakocevicjovan/PCG_and_graphics
|
02c81d5b814f468f1397c6377438cb4a8810e0ac
|
[
"MIT"
] | null | null | null |
Engine/GameObject.cpp
|
rakocevicjovan/PCG_and_graphics
|
02c81d5b814f468f1397c6377438cb4a8810e0ac
|
[
"MIT"
] | 3
|
2021-05-09T20:19:23.000Z
|
2021-08-10T19:00:19.000Z
|
Engine/GameObject.cpp
|
rakocevicjovan/PCG_and_graphics
|
02c81d5b814f468f1397c6377438cb4a8810e0ac
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "GameObject.h"
#include "Renderer.h"
Actor::Actor(Model* model, SMatrix& transform)
: _steerComp(this), _transform(transform), _collider(Collider(BoundingVolumeType::BVT_SPHERE, this, true))
{
_renderables.reserve(model->_meshes.size());
for (MeshNode& meshNode : model->_meshNodeTree)
{
// Work this out
for (auto& meshInMeshNode : meshNode.meshes)
{
_renderables.emplace_back(model->_meshes[meshInMeshNode], meshNode.transform);
}
//_renderables.back()._localTransform = mesh._parentSpaceTransform;
//_renderables.back()._transform = transform * mesh._parentSpaceTransform;
//_renderables.back().mat = mesh._material.get();
_collider.addHull(new SphereHull(_renderables.back()._transform.Translation(), 1.f * transform._11)); //@TODO see what to do about this
}
}
Actor::Actor(const Actor& other)
: _steerComp(other._steerComp), _collider(Collider(other._collider.BVT, this, other._collider.dynamic))
{
_transform = other._transform;
for (Hull* sp : other._collider.getHulls())
_collider.addHull(new SphereHull(sp->getPosition(), sp->getExtent()));
_renderables.reserve(other._renderables.size());
for (const Renderable& r : other._renderables)
_renderables.push_back(r);
}
void Actor::patchMaterial(VertexShader* vs, PixelShader* ps)
{
for (Renderable& r : _renderables)
{
r.mat->setVS(vs);
r.mat->setPS(ps);
}
}
void Actor::propagate()
{
for (Renderable& r : _renderables)
{
r._transform = _transform * r._localTransform;
}
//@TODO consider changing to per-mesh collider... could be cleaner tbh
_collider.updateHullPositions();
}
void Actor::render(const Renderer& renderer) const
{
for (const Renderable& r : _renderables)
renderer.render(r);
}
void Actor::addToRenderQueue(Renderer& renderer, const SVec3& camPos, const SVec3& viewForward)
{
for (Renderable& r : _renderables)
{
r.zDepth = (_transform.Translation() - camPos).Dot(viewForward);
renderer.addToRenderQueue(r);
}
}
void Actor::addRenderable(const Renderable& renderable, float r)
{
_renderables.push_back(renderable);
_collider.addHull(new SphereHull(renderable._localTransform.Translation(), r));
}
/*
void Actor::copyShenanigans(const Actor& other)
{
_collider = other._collider;
_collider.clearHullsNoDelete();
for (Hull* sp : other._collider.getHulls())
_collider.addHull(new SphereHull(sp->getPosition(), sp->getExtent()));
renderables.reserve(other.renderables.size());
for (const Renderable& r : other.renderables)
renderables.push_back(r);
}
*/
| 23.601852
| 138
| 0.731267
|
rakocevicjovan
|
7dd74ce39de9bd43e27097a0fb3026a5959e01d7
| 2,768
|
hpp
|
C++
|
display/GUI.hpp
|
mbellier/FluidSolver
|
c75c95f1725a362703d500c0dd3443df7d710bc3
|
[
"Apache-2.0"
] | 18
|
2015-01-08T00:48:40.000Z
|
2022-01-12T15:04:04.000Z
|
display/GUI.hpp
|
mbellier/FluidSolver
|
c75c95f1725a362703d500c0dd3443df7d710bc3
|
[
"Apache-2.0"
] | null | null | null |
display/GUI.hpp
|
mbellier/FluidSolver
|
c75c95f1725a362703d500c0dd3443df7d710bc3
|
[
"Apache-2.0"
] | 3
|
2015-11-20T02:35:16.000Z
|
2018-03-25T20:14:55.000Z
|
#ifndef GUI_H
#define GUI_H
#include <QtOpenGL>
#include <QGLWidget>
#include <QString>
#include <QList>
#include "Print.hpp"
#include "Dialog.hpp"
#include "../config.hpp"
#include "../solver/FluidSolver2D.hpp"
#include "../solver/FloatMatrix2D.hpp"
#include "LeapMotion.h"
/**
* Class herited from myGLWidget corresponding
* to the window where the fluid is displayed.
*/
class GUI : public QGLWidget
{
Q_OBJECT//Maccro used to define new SLOTS
public:
GUI(QWidget *parent, \
QString name, \
Print *p, \
Config &configurationDatas,
bool drawVelocityField,\
bool enableMouseMove);
~GUI();
void initializeGL();
void resizeGL(int width, int height);
void paintGL();
void keyPressEvent(QKeyEvent *keyEvent);
void mousePressEvent(QMouseEvent *mouseEvent);
void mouseReleaseEvent(QMouseEvent *mouseEvent);
void mouseMoveEvent(QMouseEvent *mouseEvent);
void wheelEvent(QWheelEvent *mouseEvent);
void toggleFullWindow();
void calculateFPS();
void fillSquare(unsigned int sqrWidth, unsigned int sqrHeight, float value, FloatMatrix2D* matrix, bool prev = false);
void addObstacle(float sqrWidth, float sqrHeight);
void resizeMatrix(FloatMatrix2D &out, const FloatMatrix2D &in, int k);
void addPrintMode(Print *p);
FluidSolver *fluid;
public slots:
virtual void timeOutSlot();
void saveConfig();
void loadConfig();
void desPause(){_pause = false;};
private:
QTimer *t_Timer; // used to refresh the window.
bool _pause; // pause the simulation
bool b_Fullscreen; // window fullscreen state
bool _drawVelocityField; // toggle velocity field drawings
float coef; // 'radius' of the cursor
int mouseX; // horizontal position of the mouse
int mouseY; // hertical position of the mouse
int prevMouseX; // previous event horizontal position of the mouse
int prevMouseY; // previous event vertical position of the mouse
bool pressing; // is mouse left button pressed ?
bool emptying; // is mouse right button pressed ?
bool _enableMouseMove; // toggle mouse velocity modifications
Config &configuration;
bool waitingMousePress; // waiting for button pressed?
int firstPosX;
int firstPosY;
Dialog *saveWin;
Dialog *loadWin;
// LeapMotion
Leap::Controller leap;
QList <Leap::Vector> fingers;
// information displayed in the title
float fps;
unsigned int dispMouseX, dispMouseY;
float dispDens, dispVelX, dispVelY;
// Print modes
QList <Print *> _printModes;
unsigned int _currentPrintMode;
// Average matrices
FloatMatrix2D *M1;
FloatMatrix2D *M2;
// Reduction factor
static const int k = 5;
};
#endif // GUI_H
| 26.873786
| 120
| 0.696171
|
mbellier
|
7dd832787c050136d22b59a79eb1f95ac3791afa
| 618
|
cpp
|
C++
|
potd/potd-q25/Queue.cpp
|
taoyuc3/CS225
|
e3a8add28059c63a663ad512885ddf8df86eebd9
|
[
"MIT"
] | null | null | null |
potd/potd-q25/Queue.cpp
|
taoyuc3/CS225
|
e3a8add28059c63a663ad512885ddf8df86eebd9
|
[
"MIT"
] | null | null | null |
potd/potd-q25/Queue.cpp
|
taoyuc3/CS225
|
e3a8add28059c63a663ad512885ddf8df86eebd9
|
[
"MIT"
] | null | null | null |
#include "Queue.h"
// `int size()` - returns the number of elements in the stack (0 if empty)
int Queue::size() const {
return mySize;
}
// `bool isEmpty()` - returns if the list has no elements, else false
bool Queue::isEmpty() const {
return mySize==0 ? true : false;
}
// `void enqueue(int val)` - enqueue an item to the queue in O(1) time
void Queue::enqueue(int value) {
myQueue.push_back(value);
++mySize;
}
// `int dequeue()` - removes an item off the queue and returns the value in O(1) time
int Queue::dequeue() {
int ans = myQueue.front();
myQueue.pop_back();
--mySize;
return ans;
}
| 20.6
| 85
| 0.658576
|
taoyuc3
|
7dd86d15ec8e46a1f3049c99b0c013ece0720fb3
| 8,595
|
cpp
|
C++
|
TI_Sound/SoundManager.cpp
|
edhaker13/team-indecisive
|
290d5f8d905fbf7524bfd685336044477b316fbe
|
[
"CC-BY-3.0"
] | null | null | null |
TI_Sound/SoundManager.cpp
|
edhaker13/team-indecisive
|
290d5f8d905fbf7524bfd685336044477b316fbe
|
[
"CC-BY-3.0"
] | null | null | null |
TI_Sound/SoundManager.cpp
|
edhaker13/team-indecisive
|
290d5f8d905fbf7524bfd685336044477b316fbe
|
[
"CC-BY-3.0"
] | null | null | null |
#include "SoundManager.h"
namespace Indecisive
{
static const std::string _PATH = ".\\/Assets\\/";
bool SoundManager::Initialize(HWND hwnd)
{
// TODO: Too many lines, just return method
bool result;
// Initialize direct sound and the primary sound buffer.
result = InitializeDirectSound(hwnd);
if (!result)
{
return false;
}
return true;
}
bool SoundManager::InitializeDirectSound(HWND hwnd)
{
HRESULT result;
DSBUFFERDESC bufferDesc;
WAVEFORMATEX waveFormat;
// Initialize the direct sound interface pointer for the default sound device.
result = DirectSoundCreate8(NULL, &m_DirectSound, NULL);
if (FAILED(result))
{
return false;
}
// Set the cooperative level to priority so the format of the primary sound buffer can be modified.
result = m_DirectSound->SetCooperativeLevel(hwnd, DSSCL_PRIORITY);
if (FAILED(result))
{
return false;
}
// Setup the primary buffer description.
bufferDesc.dwSize = sizeof(DSBUFFERDESC);
bufferDesc.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRLVOLUME;
bufferDesc.dwBufferBytes = 0;
bufferDesc.dwReserved = 0;
bufferDesc.lpwfxFormat = NULL;
bufferDesc.guid3DAlgorithm = GUID_NULL;
// Get control of the primary sound buffer on the default sound device.
result = m_DirectSound->CreateSoundBuffer(&bufferDesc, &m_primaryBuffer, NULL);
if (FAILED(result))
{
return false;
}
// Setup the format of the primary sound bufffer.
// In this case it is a .WAV file recorded at 44,100 samples per second in 16-bit stereo (cd audio format).
// TODO: Read format??
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nSamplesPerSec = 44100;
waveFormat.wBitsPerSample = 16;
waveFormat.nChannels = 2;
waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
waveFormat.cbSize = 0;
// Set the primary buffer to be the wave format specified.
result = m_primaryBuffer->SetFormat(&waveFormat);
if (FAILED(result))
{
return false;
}
return true;
}
bool SoundManager::CanRead(const std::string& filename) const
{
assert(!filename.empty());
std::string::size_type pos = filename.find_last_of('.');
// No file extension - can't read
if (pos == std::string::npos)
return false;
std::string ext = filename.substr(pos + 1);
return ext.compare("wav") == 0;
}
bool SoundManager::Load(const std::string& filename)
{
int error;
FILE* filePtr = nullptr;
unsigned int count;
WaveHeaderType waveFileHeader;
WAVEFORMATEX waveFormat;
DSBUFFERDESC bufferDesc;
HRESULT result;
IDirectSoundBuffer* tempBuffer = nullptr;
IDirectSoundBuffer8* secondaryBuffer = nullptr;
unsigned char* waveData;
unsigned char *bufferPtr;
unsigned long bufferSize;
// Open the wave file in binary.
error = fopen_s(&filePtr, (_PATH + filename).c_str(), "rb");
if (error != 0)
{
return false;
}
// Read in the wave file header.
count = fread(&waveFileHeader, sizeof(waveFileHeader), 1, filePtr);
if (count != 1)
{
return false;
}
// Check that the chunk ID is the RIFF format.
if ((waveFileHeader.chunkId[0] != 'R') || (waveFileHeader.chunkId[1] != 'I') ||
(waveFileHeader.chunkId[2] != 'F') || (waveFileHeader.chunkId[3] != 'F'))
{
return false;
}
// Check that the file format is the WAVE format.
if ((waveFileHeader.format[0] != 'W') || (waveFileHeader.format[1] != 'A') ||
(waveFileHeader.format[2] != 'V') || (waveFileHeader.format[3] != 'E'))
{
return false;
}
// Check that the sub chunk ID is the fmt format.
if ((waveFileHeader.subChunkId[0] != 'f') || (waveFileHeader.subChunkId[1] != 'm') ||
(waveFileHeader.subChunkId[2] != 't') || (waveFileHeader.subChunkId[3] != ' '))
{
return false;
}
// Check that the audio format is WAVE_FORMAT_PCM.
if (waveFileHeader.audioFormat != WAVE_FORMAT_PCM)
{
return false;
}
// Check that the wave file was recorded in stereo format.
if (waveFileHeader.numChannels != 2)
{
return false;
}
// Check that the wave file was recorded at a sample rate of 44.1 KHz.
if (waveFileHeader.sampleRate != 44100)
{
return false;
}
// Ensure that the wave file was recorded in 16 bit format.
if (waveFileHeader.bitsPerSample != 16)
{
return false;
}
// Check for the data chunk header.
if ((waveFileHeader.dataChunkId[0] != 'd') || (waveFileHeader.dataChunkId[1] != 'a') ||
(waveFileHeader.dataChunkId[2] != 't') || (waveFileHeader.dataChunkId[3] != 'a'))
{
return false;
}
// Set the wave format of secondary buffer that this wave file will be loaded onto.
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nSamplesPerSec = 44100;
waveFormat.wBitsPerSample = 16;
waveFormat.nChannels = 2;
waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
waveFormat.cbSize = 0;
// Set the buffer description of the secondary sound buffer that the wave file will be loaded onto.
bufferDesc.dwSize = sizeof(DSBUFFERDESC);
bufferDesc.dwFlags = DSBCAPS_CTRLVOLUME;
bufferDesc.dwBufferBytes = waveFileHeader.dataSize;
bufferDesc.dwReserved = 0;
bufferDesc.lpwfxFormat = &waveFormat;
bufferDesc.guid3DAlgorithm = GUID_NULL;
// Create a temporary sound buffer with the specific buffer settings.
result = m_DirectSound->CreateSoundBuffer(&bufferDesc, &tempBuffer, NULL);
if (FAILED(result))
{
return false;
}
// Test the buffer format against the direct sound 8 interface and create the secondary buffer.
result = tempBuffer->QueryInterface(IID_IDirectSoundBuffer8, (void**)&secondaryBuffer);
if (FAILED(result))
{
return false;
}
// Release the temporary buffer.
tempBuffer->Release();
tempBuffer = 0;
// TODO: Read file using std::ifstream
// Move to the beginning of the wave data which starts at the end of the data chunk header.
fseek(filePtr, sizeof(WaveHeaderType), SEEK_SET);
// Create a temporary buffer to hold the wave file data.
waveData = new unsigned char[waveFileHeader.dataSize];
if (!waveData)
{
return false;
}
// Read in the wave file data into the newly created buffer.
count = fread(waveData, 1, waveFileHeader.dataSize, filePtr);
if (count != waveFileHeader.dataSize)
{
return false;
}
// Close the file once done reading.
error = fclose(filePtr);
if (error != 0)
{
return false;
}
// Lock the secondary buffer to write wave data into it.
result = (secondaryBuffer)->Lock(0, waveFileHeader.dataSize, (void**)&bufferPtr, (DWORD*)&bufferSize, NULL, 0, 0);
if (FAILED(result))
{
return false;
}
// Copy the wave data into the buffer.
memcpy(bufferPtr, waveData, waveFileHeader.dataSize);
// Unlock the secondary buffer after the data has been written to it.
result = (secondaryBuffer)->Unlock((void*)bufferPtr, bufferSize, NULL, 0);
if (FAILED(result))
{
return false;
}
// Release the wave data since it was copied into the secondary buffer.
delete[] waveData;
waveData = nullptr;
// Add buffer to map
m_Sounds.emplace(filename, secondaryBuffer);
return true;
}
bool SoundManager::Play(const std::string& filename, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags)
{
HRESULT result;
// TODO: use map.find and handle failure
IDirectSoundBuffer8* secondaryBuffer = m_Sounds[filename];
if (secondaryBuffer == nullptr)
{
return false;
}
// Set position at the beginning of the sound buffer.
result = secondaryBuffer->SetCurrentPosition(0);
if (FAILED(result))
{
return false;
}
// Set volume of the buffer to 100%.
result = secondaryBuffer->SetVolume(DSBVOLUME_MAX);
if (FAILED(result))
{
return false;
}
// Play the contents of the secondary sound buffer.
result = secondaryBuffer->Play(dwReserved1, dwPriority, dwFlags);
if (FAILED(result))
{
return false;
}
return true;
}
void SoundManager::Shutdown()
{
// Release the secondary buffer.
for (auto& pair: m_Sounds)
{
if (pair.second) pair.second->Release();
}
// Shutdown the Direct Sound API.
ShutdownDirectSound();
return;
}
void SoundManager::ShutdownDirectSound()
{
// Release the primary sound buffer pointer.
if (m_primaryBuffer)
{
m_primaryBuffer->Release();
m_primaryBuffer = 0;
}
// Release the direct sound interface pointer.
if (m_DirectSound)
{
m_DirectSound->Release();
m_DirectSound = 0;
}
return;
}
}
| 26.204268
| 116
| 0.696684
|
edhaker13
|
7ddaccf6fde9087e21913df4d0594e7c10425772
| 10,466
|
cpp
|
C++
|
tests/instructions.cpp
|
voivoid/SynacorChallenge
|
8d922b290011a3a497b8933c012abc3afa9415d8
|
[
"MIT"
] | null | null | null |
tests/instructions.cpp
|
voivoid/SynacorChallenge
|
8d922b290011a3a497b8933c012abc3afa9415d8
|
[
"MIT"
] | null | null | null |
tests/instructions.cpp
|
voivoid/SynacorChallenge
|
8d922b290011a3a497b8933c012abc3afa9415d8
|
[
"MIT"
] | null | null | null |
#include "boost/test/unit_test.hpp"
#include "synacor/instructions.h"
#include "synacor/io.h"
#include "synacor/memory_storage.h"
#include "synacor/stack.h"
#include "test_utils.h"
#include "boost/scope_exit.hpp"
#include <sstream>
#ifdef _MSC_VER
# pragma warning( disable : 4459 )
#endif
namespace
{
struct InstructionsFixture
{
InstructionsFixture() : io( io_ss, io_ss )
{
memory.store( memory.get_register( 1 ), 42 );
}
template <typename Instruction, typename... Args>
synacor::Address exec( Args... args )
{
synacor::Machine machine{ memory, stack, io };
return Instruction{ args... }.execute( machine, instruction_addr );
}
synacor::Word read_result_reg()
{
return memory.read( result_reg );
}
template <typename Instruction>
auto get_unary_func_test()
{
const auto test = [this]( const synacor::Word from, const synacor::Word expected ) {
const auto next_addr = exec<Instruction>( synacor::Word( result_reg ), from );
BOOST_CHECK_EQUAL( expected, read_result_reg() );
BOOST_CHECK_EQUAL( next_addr, instruction_addr + synacor::Address( 3 ) );
};
return test;
}
template <typename Instruction>
auto get_binary_func_test()
{
const auto test = [this]( const synacor::Word from1, const synacor::Word from2, const synacor::Word expected ) {
const auto next_addr = exec<Instruction>( synacor::Word( result_reg ), from1, from2 );
BOOST_CHECK_EQUAL( expected, read_result_reg() );
BOOST_CHECK_EQUAL( next_addr, instruction_addr + synacor::Address( 4 ) );
};
return test;
}
const synacor::Address instruction_addr = synacor::Address{ 30000 };
std::stringstream io_ss;
synacor::MemoryStorage memory;
synacor::Stack stack;
synacor::IO io;
const synacor::Address result_reg = memory.get_register( 0 );
const synacor::Address reg_with_42_num = memory.get_register( 1 );
};
#define CHECK_IS_NOT_CHANGED( var ) \
BOOST_SCOPE_EXIT( var, this_ ) \
{ \
BOOST_CHECK( var == this_->var ); \
} \
BOOST_SCOPE_EXIT_END
#define CHECK_MEMORY_IS_NOT_CHANGED CHECK_IS_NOT_CHANGED( memory )
#define CHECK_STACK_IS_NOT_CHANGED CHECK_IS_NOT_CHANGED( stack )
} // namespace
using namespace synacor;
BOOST_FIXTURE_TEST_SUITE( synacor_instructions_suite, InstructionsFixture )
// HALT
BOOST_AUTO_TEST_CASE( synacor_instructions_halt )
{
CHECK_STACK_IS_NOT_CHANGED;
CHECK_MEMORY_IS_NOT_CHANGED;
const auto next_addr = exec<synacor::instructions::Halt>();
BOOST_CHECK_EQUAL( Address( 65535 ), next_addr );
}
// SET
BOOST_AUTO_TEST_CASE( synacor_instructions_set )
{
CHECK_STACK_IS_NOT_CHANGED;
const auto test = get_unary_func_test<synacor::instructions::Set>();
test( Word( reg_with_42_num ), 42 );
test( 100, 100 );
}
// PUSH
BOOST_AUTO_TEST_CASE( synacor_instructions_push )
{
CHECK_MEMORY_IS_NOT_CHANGED;
const auto test = [this]( const Word from, const Word expected ) {
const auto next_addr = exec<synacor::instructions::Push>( from );
BOOST_REQUIRE( !stack.is_empty() );
BOOST_CHECK_EQUAL( stack.top(), expected );
BOOST_CHECK_EQUAL( next_addr, instruction_addr + Address( 2 ) );
};
test( Word( reg_with_42_num ), 42 );
test( 100, 100 );
}
// POP
BOOST_AUTO_TEST_CASE( synacor_instructions_pop )
{
BOOST_CHECK( stack.is_empty() );
stack.push( 42 );
const auto next_addr = exec<synacor::instructions::Pop>( Word( result_reg ) );
BOOST_CHECK_EQUAL( 42, read_result_reg() );
BOOST_CHECK( stack.is_empty() );
BOOST_CHECK_EQUAL( next_addr, instruction_addr + Address( 2 ) );
}
// EQ
BOOST_AUTO_TEST_CASE( synacor_instructions_eq )
{
CHECK_STACK_IS_NOT_CHANGED;
const auto test = get_binary_func_test<synacor::instructions::Eq>();
test( Word( reg_with_42_num ), Word( reg_with_42_num ), 1 );
test( Word( reg_with_42_num ), 100, 0 );
test( 100, Word( reg_with_42_num ), 0 );
test( 100, 100, 1 );
}
// GT
BOOST_AUTO_TEST_CASE( synacor_instructions_gt )
{
CHECK_STACK_IS_NOT_CHANGED;
const auto test = get_binary_func_test<synacor::instructions::Gt>();
test( Word( reg_with_42_num ), Word( reg_with_42_num ), 0 );
test( Word( reg_with_42_num ), 10, 1 );
test( 100, Word( reg_with_42_num ), 1 );
test( 100, 100, 0 );
}
// JMP
BOOST_AUTO_TEST_CASE( synacor_instructions_jmp )
{
CHECK_MEMORY_IS_NOT_CHANGED;
CHECK_STACK_IS_NOT_CHANGED;
const auto next_addr = exec<synacor::instructions::Jmp>( Word( 1234 ) );
BOOST_CHECK_EQUAL( next_addr, Address( 1234 ) );
}
// JT
BOOST_AUTO_TEST_CASE( synacor_instructions_jt )
{
CHECK_MEMORY_IS_NOT_CHANGED;
CHECK_STACK_IS_NOT_CHANGED;
const auto test = [this]( const Word from, const Address expected ) {
const auto next_addr = exec<synacor::instructions::Jt>( from, Word( 1234 ) );
BOOST_CHECK_EQUAL( next_addr, expected );
};
test( Word( reg_with_42_num ), Address( 1234 ) );
test( 0, instruction_addr + Address( 3 ) );
}
// JF
BOOST_AUTO_TEST_CASE( synacor_instructions_jf )
{
CHECK_MEMORY_IS_NOT_CHANGED;
CHECK_STACK_IS_NOT_CHANGED;
const auto test = [this]( const Word from, const Address expected ) {
const auto next_addr = exec<synacor::instructions::Jf>( from, Word( 1234 ) );
BOOST_CHECK_EQUAL( next_addr, expected );
};
test( 0, Address( 1234 ) );
test( Word( reg_with_42_num ), instruction_addr + Address( 3 ) );
}
// ADD
BOOST_AUTO_TEST_CASE( synacor_instructions_add )
{
CHECK_STACK_IS_NOT_CHANGED;
const auto test = get_binary_func_test<synacor::instructions::Add>();
test( Word( reg_with_42_num ), Word( reg_with_42_num ), 84 );
test( 100, 200, 300 );
test( 32758, 15, 5 );
}
// MULT
BOOST_AUTO_TEST_CASE( synacor_instructions_mult )
{
CHECK_STACK_IS_NOT_CHANGED;
const auto test = get_binary_func_test<synacor::instructions::Mult>();
test( Word( reg_with_42_num ), Word( reg_with_42_num ), 1764 );
test( 100, 200, 20000 );
test( 32758, 15, 32618 );
}
// MOD
BOOST_AUTO_TEST_CASE( synacor_instructions_mod )
{
CHECK_STACK_IS_NOT_CHANGED;
const auto test = get_binary_func_test<synacor::instructions::Mod>();
test( Word( reg_with_42_num ), Word( reg_with_42_num ), 0 );
test( 100, 200, 100 );
test( 32758, 15, 13 );
}
// AND
BOOST_AUTO_TEST_CASE( synacor_instructions_and )
{
CHECK_STACK_IS_NOT_CHANGED;
const auto test = get_binary_func_test<synacor::instructions::And>();
test( Word( reg_with_42_num ), Word( reg_with_42_num ), 42 );
test( 100, 200, 64 );
test( 32758, 15, 6 );
}
// OR
BOOST_AUTO_TEST_CASE( synacor_instructions_or )
{
CHECK_STACK_IS_NOT_CHANGED;
const auto test = get_binary_func_test<synacor::instructions::Or>();
test( Word( reg_with_42_num ), Word( reg_with_42_num ), 42 );
test( 100, 200, 236 );
test( 32758, 15, 32767 );
}
// NOT
BOOST_AUTO_TEST_CASE( synacor_instructions_not )
{
CHECK_STACK_IS_NOT_CHANGED;
const auto test = get_unary_func_test<synacor::instructions::Not>();
test( Word( reg_with_42_num ), 32725 );
test( 100, 32667 );
test( 0, 32767 );
}
// RMEM
BOOST_AUTO_TEST_CASE( synacor_instructions_rmem )
{
CHECK_STACK_IS_NOT_CHANGED;
memory.store( Address( 30000 ), 123 );
BOOST_CHECK_NE( 123, read_result_reg() );
exec<synacor::instructions::RMem>( Word( result_reg ), Word( 30000 ) );
BOOST_CHECK_EQUAL( 123, read_result_reg() );
memory.store( Address( 42 ), 4242 );
BOOST_CHECK_NE( 4242, read_result_reg() );
exec<synacor::instructions::RMem>( Word( result_reg ), Word( reg_with_42_num ) );
BOOST_CHECK_EQUAL( 4242, read_result_reg() );
}
// WMEM
BOOST_AUTO_TEST_CASE( synacor_instructions_wmem )
{
CHECK_STACK_IS_NOT_CHANGED;
BOOST_CHECK_NE( 42, memory.read( Address( 30000 ) ) );
exec<synacor::instructions::WMem>( Word( 30000 ), Word( reg_with_42_num ) );
BOOST_CHECK_EQUAL( 42, memory.read( Address( 30000 ) ) );
BOOST_CHECK_NE( 12345, memory.read( Address( 42 ) ) );
exec<synacor::instructions::WMem>( Word( reg_with_42_num ), Word( 12345 ) );
BOOST_CHECK_EQUAL( 12345, memory.read( Address( 42 ) ) );
}
// CALL
BOOST_AUTO_TEST_CASE( synacor_instructions_call )
{
CHECK_MEMORY_IS_NOT_CHANGED;
BOOST_CHECK( stack.is_empty() );
BOOST_CHECK( Address( 10000 ) != instruction_addr );
const auto next_addr = exec<synacor::instructions::Call>( Word( 10000 ) );
BOOST_CHECK_EQUAL( next_addr, Address( 10000 ) );
BOOST_CHECK( !stack.is_empty() );
BOOST_CHECK( instruction_addr + Address( 2 ) == Address( Word( stack.pop() ) ) );
}
// RET
BOOST_AUTO_TEST_CASE( synacor_instructions_ret )
{
CHECK_MEMORY_IS_NOT_CHANGED;
CHECK_STACK_IS_NOT_CHANGED;
exec<synacor::instructions::Call>( Word( 10000 ) );
const auto next_addr = exec<synacor::instructions::Ret>();
BOOST_CHECK( instruction_addr + Address( 2 ) == next_addr );
}
// OUT
BOOST_AUTO_TEST_CASE( synacor_instructions_out )
{
CHECK_MEMORY_IS_NOT_CHANGED;
CHECK_STACK_IS_NOT_CHANGED;
const auto test = [this]( const Word from, const char expected ) {
const auto next_addr = exec<synacor::instructions::Out>( from );
BOOST_CHECK_EQUAL( expected, io_ss.get() );
BOOST_CHECK_EQUAL( next_addr, instruction_addr + Address( 2 ) );
};
test( Word( reg_with_42_num ), '*' );
test( 100, 'd' );
}
// IN
BOOST_AUTO_TEST_CASE( synacor_instructions_in )
{
CHECK_STACK_IS_NOT_CHANGED;
const auto test = [this]( const char expected ) {
const auto next_addr = exec<synacor::instructions::In>( Word( result_reg ) );
BOOST_CHECK_EQUAL( expected, read_result_reg() );
BOOST_CHECK_EQUAL( next_addr, instruction_addr + Address( 2 ) );
};
io_ss << "abc";
test( 'a' );
test( 'b' );
test( 'c' );
}
// NOOP
BOOST_AUTO_TEST_CASE( synacor_instructions_noop )
{
CHECK_MEMORY_IS_NOT_CHANGED;
CHECK_STACK_IS_NOT_CHANGED;
const auto next_addr = exec<synacor::instructions::Noop>();
BOOST_CHECK_EQUAL( next_addr, instruction_addr + Address( 1 ) );
}
BOOST_AUTO_TEST_SUITE_END()
| 27.255208
| 140
| 0.671699
|
voivoid
|
7de18477eba6ca4f9c0f4ad6f1f10c37984e82cf
| 619
|
hpp
|
C++
|
src/Omega_h_inertia.hpp
|
joshia5/ayj-omega_h
|
8b65215013df29af066fa076261ba897d64a72c2
|
[
"BSD-2-Clause-FreeBSD"
] | 44
|
2019-01-23T03:37:18.000Z
|
2021-08-24T02:20:29.000Z
|
src/Omega_h_inertia.hpp
|
joshia5/ayj-omega_h
|
8b65215013df29af066fa076261ba897d64a72c2
|
[
"BSD-2-Clause-FreeBSD"
] | 67
|
2019-01-29T15:35:42.000Z
|
2021-08-17T20:42:40.000Z
|
src/Omega_h_inertia.hpp
|
joshia5/ayj-omega_h
|
8b65215013df29af066fa076261ba897d64a72c2
|
[
"BSD-2-Clause-FreeBSD"
] | 29
|
2019-01-14T21:33:32.000Z
|
2021-08-10T11:35:24.000Z
|
#ifndef INERTIA_HPP
#define INERTIA_HPP
#include <vector>
#include "Omega_h_remotes.hpp"
#include "Omega_h_vector.hpp"
namespace Omega_h {
namespace inertia {
struct Rib {
std::vector<Vector<3>> axes;
};
Read<I8> mark_bisection(
CommPtr comm, Reals coords, Reals masses, Real tolerance, Vector<3>& axis);
Read<I8> mark_bisection_given_axis(
CommPtr comm, Reals coords, Reals masses, Real tolerance, Vector<3> axis);
void recursively_bisect(CommPtr comm, Real tolerance, Reals* p_coords,
Reals* p_masses, Remotes* p_owners, Rib* p_hints);
} // namespace inertia
} // end namespace Omega_h
#endif
| 22.107143
| 79
| 0.741519
|
joshia5
|
8fcc4b6fcd37808464600f77f4c3cf0a4a9ddf61
| 347
|
hpp
|
C++
|
examples/06_ssd1306/main/include/i2c.hpp
|
graealex/qemu_esp32
|
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
|
[
"Apache-2.0"
] | 335
|
2016-10-12T06:59:33.000Z
|
2022-03-29T14:26:04.000Z
|
examples/06_ssd1306/main/include/i2c.hpp
|
graealex/qemu_esp32
|
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
|
[
"Apache-2.0"
] | 30
|
2016-10-30T11:23:59.000Z
|
2021-11-12T10:51:20.000Z
|
examples/06_ssd1306/main/include/i2c.hpp
|
graealex/qemu_esp32
|
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
|
[
"Apache-2.0"
] | 48
|
2016-10-30T08:41:13.000Z
|
2022-02-15T22:15:09.000Z
|
#ifndef I2C_H_
#define I2C_H_
#include "driver/gpio.h"
#include "rom/ets_sys.h"
class I2C {
private:
gpio_num_t scl_pin, sda_pin;
public:
I2C(gpio_num_t scl, gpio_num_t sda);
void init(uint8_t scl_pin, uint8_t sda_pin);
bool start(void);
void stop(void);
bool write(uint8_t data);
uint8_t read(void);
void set_ack(bool ack);
};
#endif
| 15.772727
| 45
| 0.729107
|
graealex
|
8fcc7de9d75968f69f738bf5721e91618526caa1
| 797
|
cpp
|
C++
|
codeforce2/463C. Gargari and Bishops.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
codeforce2/463C. Gargari and Bishops.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
codeforce2/463C. Gargari and Bishops.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int const N = 3001;
int n, g[N][N], x, y, xx, yy;
long long dp1[2 * N], dp2[2 * N], sol1 = -1, sol2 = -1;
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j) {
scanf("%d", &g[i][j]);
dp1[i + j] += g[i][j];
dp2[i - j + n] += g[i][j];
}
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j) {
long long v = dp1[i + j] + dp2[i - j + n] - g[i][j];
if((i + j) & 1) {
if(v > sol2) {
sol2 = v;
xx = i;
yy = j;
}
} else {
if(v > sol1) {
sol1 = v;
x = i;
y = j;
}
}
}
printf("%lld\n", sol1 + sol2);
printf("%d %d %d %d\n", x, y, xx, yy);
return 0;
}
| 19.439024
| 58
| 0.350063
|
khaled-farouk
|
8fe3fd9e25449a7cb543fc2fec778b0d6f4729f5
| 5,754
|
cpp
|
C++
|
src/window.cpp
|
den-mentiei/hlsl-toy
|
ac80d90ff9d52abc80ba31c06bd5a048a8c08cde
|
[
"MIT"
] | 4
|
2016-05-28T18:21:55.000Z
|
2020-01-13T01:39:28.000Z
|
src/window.cpp
|
den-mentiei/hlsl-toy
|
ac80d90ff9d52abc80ba31c06bd5a048a8c08cde
|
[
"MIT"
] | null | null | null |
src/window.cpp
|
den-mentiei/hlsl-toy
|
ac80d90ff9d52abc80ba31c06bd5a048a8c08cde
|
[
"MIT"
] | null | null | null |
#include "window.h"
namespace toy {
namespace {
static const wchar_t* WINDOW_CLASS = L"hlsl-toy-class";
} // anonymous namespace
LRESULT WINAPI Window::windows_proc(HWND handle, UINT message, WPARAM wparam, LPARAM lparam) {
Window* window = reinterpret_cast<Window*>(::GetWindowLong(handle, GWL_USERDATA));
if (window == nullptr || window->is_closing()) {
return DefWindowProcW(handle, message, wparam, lparam);
}
switch (message) {
case WM_CLOSE:
window->handle_close();
break;
case WM_KEYDOWN:
window->handle_key_down(static_cast<unsigned>(wparam));
break;
case WM_LBUTTONDOWN:
window->handle_mouse_down(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16), Mouse::B_LEFT);
break;
case WM_RBUTTONDOWN:
window->handle_mouse_down(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16), Mouse::B_RIGHT);
break;
case WM_LBUTTONUP:
window->handle_mouse_up(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16), Mouse::B_LEFT);
break;
case WM_RBUTTONUP:
window->handle_mouse_up(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16), Mouse::B_RIGHT);
break;
case WM_MOUSEMOVE:
window->handle_mouse_move(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16), wparam);
break;
case WM_SIZE:
window->handle_resize(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16));
break;
default:
return DefWindowProcW(handle, message, wparam, lparam);
}
return 0;
}
void Window::register_class(HINSTANCE instance) {
WNDCLASSW window_class;
window_class.style = 0;
window_class.lpfnWndProc = Window::windows_proc;
window_class.cbClsExtra = 0;
window_class.cbWndExtra = 0;
window_class.hInstance = instance;
window_class.hIcon = 0;
window_class.hCursor = ::LoadCursor(nullptr, IDC_ARROW);
window_class.hbrBackground = 0;
window_class.lpszMenuName = 0;
window_class.lpszClassName = WINDOW_CLASS;
::RegisterClassW(&window_class);
}
Window::Window()
: _handle(0)
, _is_closing(false)
, _w(0)
, _h(0)
, _keypress_cb(nullptr)
, _mouse_move_cb(nullptr)
, _mouse_down_cb(nullptr)
, _mouse_up_cb(nullptr)
, _resize_cb(nullptr)
{}
Window::~Window() {
if (_handle) {
close();
}
}
void Window::open(HINSTANCE instance, const wchar_t* title, const unsigned w, const unsigned h) {
RECT desktop_rect;
::GetClientRect(::GetDesktopWindow(), &desktop_rect);
unsigned x = (desktop_rect.right - w) / 2;
unsigned y = (desktop_rect.bottom - h) / 2;
_w = w;
_h = h;
RECT window_rect;
window_rect.left = x;
window_rect.right = window_rect.left + w;
window_rect.top = y;
window_rect.bottom = window_rect.top + h;
::AdjustWindowRect(&window_rect, WS_OVERLAPPEDWINDOW, 0);
_handle = ::CreateWindowW(WINDOW_CLASS, title, WS_OVERLAPPEDWINDOW, window_rect.left, window_rect.top, window_rect.right - window_rect.left, window_rect.bottom - window_rect.top, 0, 0, instance, 0);
::SetWindowLong(_handle, GWL_USERDATA, reinterpret_cast<LONG>(this));
::ShowWindow(_handle, SW_SHOW);
::UpdateWindow(_handle);
}
void Window::close() {
::SetWindowLong(_handle, GWL_USERDATA, 0);
::DestroyWindow(_handle);
_handle = 0;
}
void Window::update() {
MSG message;
while (::PeekMessage(&message, _handle, 0, 0, PM_REMOVE)) {
::TranslateMessage(&message);
::DispatchMessage(&message);
}
}
bool Window::is_closing() const {
return _is_closing;
}
HWND Window::handle() const {
return _handle;
}
void Window::handle_close() {
_is_closing = true;
}
void Window::handle_resize(const unsigned w, const unsigned h) {
_w = w;
_h = h;
if (_resize_cb) {
_resize_cb(w, h, _resize_cb_userdata);
}
}
void Window::handle_key_down(const unsigned key_code) {
if (_keypress_cb) {
_keypress_cb(key_code, _keypress_cb_userdata);
}
}
void Window::handle_mouse_move(const unsigned x, const unsigned y, unsigned state) {
if (_mouse_move_cb) {
Mouse::Button button;
switch (state) {
case MK_LBUTTON:
button = Mouse::B_LEFT;
break;
case MK_RBUTTON:
button = Mouse::B_RIGHT;
break;
default:
button = Mouse::B_NONE;
break;
}
_mouse_move_cb(x, y, button, _mouse_move_cb_userdata);
}
}
void Window::handle_mouse_down(const unsigned x, const unsigned y, Mouse::Button button) {
if (_mouse_down_cb) {
_mouse_down_cb(x, y, button, _mouse_down_cb_userdata);
}
}
void Window::handle_mouse_up(const unsigned x, const unsigned y, Mouse::Button button) {
if (_mouse_up_cb) {
_mouse_up_cb(x, y, button, _mouse_up_cb_userdata);
}
}
unsigned Window::width() const {
return _w;
}
unsigned Window::height() const {
return _h;
}
void Window::set_keypress_callback(KeypressCallback callback, void* userdata) {
_keypress_cb = callback;
_keypress_cb_userdata = userdata;
}
void Window::set_mouse_move_callback(MouseCallback callback, void* userdata) {
_mouse_move_cb = callback;
_mouse_move_cb_userdata = userdata;
}
void Window::set_mouse_down_callback(MouseCallback callback, void* userdata) {
_mouse_down_cb = callback;
_mouse_down_cb_userdata = userdata;
}
void Window::set_mouse_up_callback(MouseCallback callback, void* userdata) {
_mouse_up_cb = callback;
_mouse_up_cb_userdata = userdata;
}
void Window::set_resize_callback(ResizeCallback callback, void* userdata) {
_resize_cb = callback;
_resize_cb_userdata = userdata;
}
std::wstring Window::choose_toy_file_dialog() {
OPENFILENAMEW ofn;
wchar_t buffer[MAX_PATH + 1];
buffer[0] = 0;
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = _handle;
ofn.lpstrFile = buffer;
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFilter = L"HLSL (*.hlsl)\0*.hlsl\0All (*.*)\0*.*\0";
ofn.nFilterIndex = 0;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (TRUE == GetOpenFileNameW(&ofn))
return std::wstring(buffer);
return std::wstring();
}
} // namespace toy
| 24.176471
| 199
| 0.72367
|
den-mentiei
|
8fe5c70f858c945d7d1ac3ac9bc7f43eedde49b2
| 1,070
|
hpp
|
C++
|
ElectruxShorthandInterpretedLanguage/include/ExpressionEvaluator.hpp
|
Electrux/CCPP-Code
|
3c5e5b866cf050c11bced9651b112eb31dd2465d
|
[
"BSD-3-Clause"
] | 6
|
2019-08-29T23:31:17.000Z
|
2021-11-14T20:35:47.000Z
|
ElectruxShorthandInterpretedLanguage/include/ExpressionEvaluator.hpp
|
Electrux/CCPP-Code
|
3c5e5b866cf050c11bced9651b112eb31dd2465d
|
[
"BSD-3-Clause"
] | null | null | null |
ElectruxShorthandInterpretedLanguage/include/ExpressionEvaluator.hpp
|
Electrux/CCPP-Code
|
3c5e5b866cf050c11bced9651b112eb31dd2465d
|
[
"BSD-3-Clause"
] | 1
|
2019-09-01T12:22:58.000Z
|
2019-09-01T12:22:58.000Z
|
#ifndef EXPRESSIONEVALUATOR_HPP
#define EXPRESSIONEVALUATOR_HPP
#include <string>
#include <vector>
#include "Errors.hpp"
#include "DataTypes.hpp"
ErrorTypes EvalExpression( const std::vector< DataType::Data > & dataline, const int & from, const int & to, Variable & result );
ErrorTypes GenPostfix( const std::vector< DataType::Data > & dataline, const int & from, const int & to,
std::vector< DataType::Data > & postfix );
DataType::SymbolType GetOverallDataType( const std::vector< DataType::Data > & postfixexpr );
std::string CalculatePostfixExpression( const std::vector< DataType::Data > & postfixexpr, const DataType::SymbolType & exprtype );
std::string PerformOperation( const DataType::Data & op1, const DataType::Data & op2,
const DataType::Data & op, const DataType::SymbolType & exprtype );
bool SetAllVariableValues( std::vector< DataType::Data > & postfixexpr );
bool IsValidDataType( const DataType::Data & data );
bool IsSymbol( const std::string & data );
int GetPrec( const std::string & symbol );
#endif // EXPRESSIONEVALUATOR_HPP
| 35.666667
| 131
| 0.740187
|
Electrux
|
8fe7ab9117a3eb60248e066eb12b55f75ff67fb9
| 5,536
|
hpp
|
C++
|
include/range/v3/view/reverse.hpp
|
anders-sjogren/range-v3
|
a7583aaf4e446d435867e54d58575d40c0575312
|
[
"MIT"
] | null | null | null |
include/range/v3/view/reverse.hpp
|
anders-sjogren/range-v3
|
a7583aaf4e446d435867e54d58575d40c0575312
|
[
"MIT"
] | null | null | null |
include/range/v3/view/reverse.hpp
|
anders-sjogren/range-v3
|
a7583aaf4e446d435867e54d58575d40c0575312
|
[
"MIT"
] | null | null | null |
/// \file
// Range v3 library
//
// Copyright Eric Niebler 2014
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
//
#ifndef RANGES_V3_VIEW_REVERSE_HPP
#define RANGES_V3_VIEW_REVERSE_HPP
#include <utility>
#include <iterator>
#include <range/v3/range_fwd.hpp>
#include <range/v3/size.hpp>
#include <range/v3/begin_end.hpp>
#include <range/v3/range_traits.hpp>
#include <range/v3/range_adaptor.hpp>
#include <range/v3/utility/meta.hpp>
#include <range/v3/utility/static_const.hpp>
#include <range/v3/view/view.hpp>
namespace ranges
{
inline namespace v3
{
/// \addtogroup group-views
/// @{
template<typename Rng>
struct reverse_view
: range_adaptor<reverse_view<Rng>, Rng>
{
private:
CONCEPT_ASSERT(BidirectionalIterable<Rng>());
CONCEPT_ASSERT(BoundedIterable<Rng>());
friend range_access;
// A rather convoluted implementation to avoid the problem std::reverse_iterator
// has adapting iterators that return references to internal data.
struct adaptor : adaptor_base
{
private:
reverse_view const *rng_;
public:
adaptor() = default;
adaptor(reverse_view const &rng)
: rng_(&rng)
{}
range_iterator_t<Rng> begin(reverse_view const &rng) const
{
auto it = ranges::end(rng.mutable_base());
ranges::advance(it, -1, ranges::begin(rng.mutable_base()));
return it;
}
void next(range_iterator_t<Rng> &it) const
{
if(0 != ranges::advance(it, -1, ranges::begin(rng_->mutable_base())))
it = ranges::end(rng_->mutable_base());
}
void prev(range_iterator_t<Rng> &it) const
{
if(0 != ranges::advance(it, 1, ranges::end(rng_->mutable_base())))
it = ranges::begin(rng_->mutable_base());
}
CONCEPT_REQUIRES(RandomAccessIterable<Rng>())
void advance(range_iterator_t<Rng> &it, range_difference_t<Rng> n) const
{
if(n > 0)
ranges::advance(it, -n + 1), this->next(it);
else if(n < 0)
this->prev(it), ranges::advance(it, -n - 1);
}
CONCEPT_REQUIRES(RandomAccessIterable<Rng>())
range_difference_t<Rng>
distance_to(range_iterator_t<Rng> const &here, range_iterator_t<Rng> const &there,
adaptor const &other_adapt) const
{
RANGES_ASSERT(rng_ == other_adapt.rng_);
if(there == ranges::end(rng_->mutable_base()))
return here == ranges::end(rng_->mutable_base())
? 0 : (here - ranges::begin(rng_->mutable_base())) + 1;
else if(here == ranges::end(rng_->mutable_base()))
return (ranges::begin(rng_->mutable_base()) - there) - 1;
return here - there;
}
};
adaptor begin_adaptor() const
{
return {*this};
}
adaptor end_adaptor() const
{
return {*this};
}
public:
reverse_view() = default;
reverse_view(Rng rng)
: range_adaptor_t<reverse_view>{std::move(rng)}
{}
CONCEPT_REQUIRES(SizedIterable<Rng>())
range_size_t<Rng> size() const
{
return ranges::size(this->base());
}
};
namespace view
{
struct reverse_fn
{
template<typename Rng>
using Concept = meta::and_<
BidirectionalIterable<Rng>,
BoundedIterable<Rng>>;
template<typename Rng, CONCEPT_REQUIRES_(Concept<Rng>())>
reverse_view<all_t<Rng>> operator()(Rng && rng) const
{
return reverse_view<all_t<Rng>>{all(std::forward<Rng>(rng))};
}
#ifndef RANGES_DOXYGEN_INVOKED
// For error reporting
template<typename Rng, CONCEPT_REQUIRES_(!Concept<Rng>())>
void operator()(Rng &&) const
{
CONCEPT_ASSERT_MSG(BidirectionalIterable<Rng>(),
"The object on which view::reverse operates must be a model of the "
"BidirectionalIterable concept.");
CONCEPT_ASSERT_MSG(BoundedIterable<Rng>(),
"To reverse an iterable object, its end iterator must be a model of "
"the BidirectionalIterator concept.");
}
#endif
};
/// \relates reverse_fn
/// \ingroup group-views
namespace
{
constexpr auto&& reverse = static_const<view<reverse_fn>>::value;
}
}
/// @}
}
}
#endif
| 36.183007
| 98
| 0.504697
|
anders-sjogren
|
8fed68e99333ac75a57ea4c403c874ab78103776
| 5,173
|
cc
|
C++
|
neb/test/host.cc
|
centreon-lab/centreon-broker
|
b412470204eedc01422bbfd00bcc306dfb3d2ef5
|
[
"Apache-2.0"
] | 40
|
2015-03-10T07:55:39.000Z
|
2021-06-11T10:13:56.000Z
|
neb/test/host.cc
|
centreon-lab/centreon-broker
|
b412470204eedc01422bbfd00bcc306dfb3d2ef5
|
[
"Apache-2.0"
] | 297
|
2015-04-30T10:02:04.000Z
|
2022-03-09T13:31:54.000Z
|
neb/test/host.cc
|
centreon-lab/centreon-broker
|
b412470204eedc01422bbfd00bcc306dfb3d2ef5
|
[
"Apache-2.0"
] | 29
|
2015-08-03T10:04:15.000Z
|
2021-11-25T12:21:00.000Z
|
/*
* Copyright 2011 - 2019 Centreon (https://www.centreon.com/)
*
* 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.
*
* For more information : contact@centreon.com
*
*/
#include "com/centreon/broker/neb/host.hh"
#include <gtest/gtest.h>
#include <cmath>
#include "randomize.hh"
using namespace com::centreon::broker;
class HostTest : public ::testing::Test {
public:
void SetUp() override {
// Initialization.
randomize_init();
}
void TearDown() override {
// Cleanup.
randomize_cleanup();
}
};
TEST_F(HostTest, Assignment) {
// Object #1.
neb::host h1;
std::vector<randval> randvals1;
randomize(h1, &randvals1);
// Object #2.
neb::host h2;
randomize(h2);
// Assignment.
h2 = h1;
// Reset object #1.
std::vector<randval> randvals2;
randomize(h1, &randvals2);
// Compare objects with expected results.
ASSERT_TRUE(h1 == randvals2);
ASSERT_TRUE(h2 == randvals1);
}
TEST_F(HostTest, CopyConstructor) {
// Object #1.
neb::host h1;
std::vector<randval> randvals1;
randomize(h1, &randvals1);
// Object #2.
neb::host h2(h1);
// Reset object #1.
std::vector<randval> randvals2;
randomize(h1, &randvals2);
// Compare objects with expected results.
ASSERT_TRUE(h1 == randvals2);
ASSERT_TRUE(h2 == randvals1);
}
TEST_F(HostTest, DefaultConstructor) {
// Object.
io::data::broker_id = 0;
neb::host h;
// Check.
ASSERT_EQ(h.source_id, 0u);
ASSERT_EQ(h.destination_id, 0u);
ASSERT_FALSE(h.acknowledged);
ASSERT_EQ(h.acknowledgement_type, 0);
ASSERT_TRUE(h.action_url.empty());
ASSERT_FALSE(h.active_checks_enabled);
ASSERT_TRUE(h.address.empty());
ASSERT_TRUE(h.alias.empty());
ASSERT_TRUE(h.check_command.empty());
ASSERT_FALSE((fabs(h.check_interval) > 0.0001));
ASSERT_FALSE(h.check_freshness);
ASSERT_FALSE(!h.check_period.empty());
ASSERT_FALSE((h.check_type != 0));
ASSERT_FALSE((h.current_check_attempt != 0));
ASSERT_FALSE((h.current_state != 4));
ASSERT_FALSE(h.default_active_checks_enabled);
ASSERT_FALSE(h.default_event_handler_enabled);
ASSERT_FALSE(h.default_flap_detection_enabled);
ASSERT_FALSE(h.default_notifications_enabled);
ASSERT_FALSE(h.default_passive_checks_enabled);
ASSERT_FALSE((h.downtime_depth != 0));
ASSERT_FALSE(!h.enabled);
ASSERT_FALSE(!h.event_handler.empty());
ASSERT_FALSE(h.event_handler_enabled);
ASSERT_FALSE((fabs(h.execution_time) > 0.0001));
ASSERT_FALSE((fabs(h.first_notification_delay) > 0.0001));
ASSERT_FALSE(h.flap_detection_enabled);
ASSERT_FALSE(h.flap_detection_on_down);
ASSERT_FALSE(h.flap_detection_on_unreachable);
ASSERT_FALSE(h.flap_detection_on_up);
ASSERT_FALSE((fabs(h.freshness_threshold) > 0.0001));
ASSERT_FALSE(h.has_been_checked);
ASSERT_FALSE((fabs(h.high_flap_threshold) > 0.0001));
ASSERT_FALSE((h.host_id != 0));
ASSERT_FALSE(!h.host_name.empty());
ASSERT_FALSE(!h.icon_image.empty());
ASSERT_FALSE(!h.icon_image_alt.empty());
ASSERT_FALSE(h.is_flapping);
ASSERT_FALSE((h.last_check != 0));
ASSERT_FALSE((h.last_hard_state != 4));
ASSERT_FALSE((h.last_hard_state_change != 0));
ASSERT_FALSE((h.last_notification != 0));
ASSERT_FALSE((h.last_state_change != 0));
ASSERT_FALSE((h.last_time_down != 0));
ASSERT_FALSE((h.last_time_unreachable != 0));
ASSERT_FALSE((h.last_time_up != 0));
ASSERT_FALSE((h.last_update != 0));
ASSERT_FALSE((fabs(h.latency) > 0.0001));
ASSERT_FALSE((fabs(h.low_flap_threshold) > 0.0001));
ASSERT_FALSE((h.max_check_attempts != 0));
ASSERT_FALSE((h.next_check != 0));
ASSERT_FALSE((h.next_notification != 0));
ASSERT_FALSE(h.no_more_notifications);
ASSERT_FALSE(!h.notes.empty());
ASSERT_FALSE(!h.notes_url.empty());
ASSERT_FALSE((h.notification_number != 0));
ASSERT_FALSE(h.notifications_enabled);
ASSERT_FALSE((fabs(h.notification_interval) > 0.0001));
ASSERT_FALSE(!h.notification_period.empty());
ASSERT_FALSE(h.notify_on_down);
ASSERT_FALSE(h.notify_on_downtime);
ASSERT_FALSE(h.notify_on_flapping);
ASSERT_FALSE(h.notify_on_recovery);
ASSERT_FALSE(h.notify_on_unreachable);
ASSERT_FALSE(h.obsess_over);
ASSERT_FALSE(!h.output.empty());
ASSERT_FALSE(h.passive_checks_enabled);
ASSERT_FALSE((fabs(h.percent_state_change) > 0.0001));
ASSERT_FALSE(!h.perf_data.empty());
ASSERT_FALSE(h.retain_nonstatus_information);
ASSERT_FALSE(h.retain_status_information);
ASSERT_FALSE((fabs(h.retry_interval) > 0.0001));
ASSERT_FALSE(h.should_be_scheduled);
ASSERT_FALSE(h.stalk_on_down);
ASSERT_FALSE(h.stalk_on_unreachable);
ASSERT_FALSE(h.stalk_on_up);
ASSERT_FALSE((h.state_type != 0));
ASSERT_FALSE(!h.statusmap_image.empty());
}
| 31.351515
| 75
| 0.727238
|
centreon-lab
|
8fee5cae86153aa48502aff5223a103558611347
| 14,555
|
cpp
|
C++
|
src/sim/ldpcsim.cpp
|
patrickwillner/libldpc
|
d2ec2d369dd4f4c5cad33caa8e416280d048a89c
|
[
"MIT"
] | 1
|
2021-01-29T17:19:57.000Z
|
2021-01-29T17:19:57.000Z
|
src/sim/ldpcsim.cpp
|
patrickwillner/libldpc
|
d2ec2d369dd4f4c5cad33caa8e416280d048a89c
|
[
"MIT"
] | 2
|
2021-07-16T10:03:40.000Z
|
2021-08-19T21:40:53.000Z
|
src/sim/ldpcsim.cpp
|
patrickwillner/libldpc
|
d2ec2d369dd4f4c5cad33caa8e416280d048a89c
|
[
"MIT"
] | 1
|
2021-07-16T10:40:47.000Z
|
2021-07-16T10:40:47.000Z
|
#include "ldpcsim.h"
#include <omp.h>
namespace ldpc
{
ldpc_sim::ldpc_sim(const std::shared_ptr<ldpc_code> &code,
const decoder_param &decoderParams,
const channel_param &channelParams,
const simulation_param &simulationParams)
: ldpc_sim(code, decoderParams, channelParams, simulationParams, nullptr)
{
}
ldpc_sim::ldpc_sim(const std::shared_ptr<ldpc_code> &code,
const decoder_param &decoderParams,
const channel_param &channelParams,
const simulation_param &simulationParams,
sim_results_t *results)
: mLdpcCode(code),
mDecoderParams(decoderParams),
mChannelParams(channelParams),
mSimulationParams(simulationParams),
mResults(results)
{
try
{
//results may vary with same seed, since some threads are executed more than others
for (u32 i = 0; i < mSimulationParams.threads; ++i)
{
// initialize the correct channel
if (mChannelParams.type == std::string("AWGN"))
{
mChannel.push_back(
std::make_shared<channel_awgn>(
channel_awgn(
mLdpcCode,
mDecoderParams,
mChannelParams.seed + i,
1.
)
)
);
}
else if (mChannelParams.type == std::string("BSC"))
{
mChannel.push_back(
std::make_shared<channel_bsc>(
channel_bsc(
mLdpcCode,
mDecoderParams,
mChannelParams.seed + i,
0.
)
)
);
}
else if (mChannelParams.type == std::string("BEC"))
{
mChannel.push_back(
std::make_shared<channel_bec>(
channel_bec(
mLdpcCode,
mDecoderParams,
mChannelParams.seed + i,
0.
)
)
);
}
else
{
throw std::runtime_error("No channel selected.");
}
}
}
catch (std::exception &e)
{
std::cout << "Error: ldpc_sim::ldpc_sim() " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
}
std::ostream &operator<<(std::ostream &os, const ldpc_sim &sim)
{
os << "== Decoder Parameters\n";
os << sim.mDecoderParams << "\n";
os << "== Channel Parameters\n";
os << sim.mChannelParams << "\n";
os << "== Simulation Parameters\n";
os << sim.mSimulationParams << "\n";
return os;
}
void ldpc_sim::start(bool *stopFlag)
{
u64 frames;
u64 bec = 0;
u64 fec = 0;
u64 iters;
ldpc::vec_double_t xVals;
double val = mChannelParams.xRange[0];
while (val < mChannelParams.xRange[1])
{
xVals.push_back(val);
val += mChannelParams.xRange[2];
}
auto minFec = mSimulationParams.fec;
auto maxFrames = mSimulationParams.maxFrames;
std::string xValType = "SNR";
if (mChannelParams.type == std::string("BSC") || mChannelParams.type == std::string("BEC"))
{
xValType = "EPS";
// reverse the epsilon values, since we should start at the worst
// crossover probability increase to the best
std::reverse(xVals.begin(), xVals.end());
}
std::vector<std::string> printResStr(xVals.size() + 1, std::string());
std::ofstream fp;
char resStr[128];
#ifndef LIB_SHARED
#ifdef LOG_FRAME_TIME
printResStr[0].assign("snr fer ber frames avg_iter frame_time");
#else
printResStr[0].assign("snr fer ber frames avg_iter");
#endif
#endif
std::cout << "=============================" << "===========================================================" << std::endl;
std::cout << " FEC | FRAME | " << xValType << " | BER | FER | AVGITERS | TIME/FRAME \n";
std::cout << "========+================+===" << "======+============+============+===========+==============" << std::endl;
for (u64 i = 0; i < xVals.size(); ++i)
{
bec = 0;
fec = 0;
frames = 0;
iters = 0;
auto timeStart = std::chrono::high_resolution_clock::now();
#pragma omp parallel default(none) \
num_threads(mSimulationParams.threads) \
shared(iters, stopFlag, timeStart, mChannel, fec, xVals, stdout, \
bec, frames, printResStr, fp, resStr, minFec, maxFrames, i)
{
unsigned tid = omp_get_thread_num();
// reconfigure channel to match parameter
mChannel[tid]->set_channel_param(xVals[i]);
do
{
if (!mLdpcCode->G().empty())
{
mChannel[tid]->encode_and_map();
}
// calculate the channel transitions
mChannel[tid]->simulate();
// calculate the corresponding LLRs, depending on the channel
mChannel[tid]->calculate_llrs();
//decode
auto it = mChannel[tid]->decode();
#pragma omp atomic update
iters += it;
if (fec < minFec)
{
#pragma omp atomic update
++frames;
// count the bit errors
int bec_tmp = 0;
for (auto ci : mLdpcCode->bit_pos())
{
bec_tmp += (mChannel[tid]->estimate()[ci] != mChannel[tid]->codeword()[ci]);
}
if (bec_tmp > 0)
{
auto timeNow = std::chrono::high_resolution_clock::now();
auto timeFrame = timeNow - timeStart; //eliminate const time for printing etc
u64 tFrame = static_cast<u64>(std::chrono::duration_cast<std::chrono::microseconds>(timeFrame).count());
tFrame = tFrame / frames;
#pragma omp critical
{
bec += bec_tmp;
++fec;
#ifndef LIB_SHARED
printf("\r %2lu/%2lu | %12lu | %.3f | %.2e | %.2e | %.1e | %.3fms",
fec, minFec, frames, xVals[i],
static_cast<double>(bec) / (frames * mLdpcCode->nc()), //ber
static_cast<double>(fec) / frames, //fer
static_cast<double>(iters) / frames, //avg iters
static_cast<double>(tFrame) * 1e-3); //frame time tFrame
fflush(stdout);
#ifdef LOG_FRAME_TIME
sprintf(resStr, "%lf %.3e %.3e %lu %.3e %.6f",
xVals[i], static_cast<double>(fec) / frames, static_cast<double>(bec) / (frames * mLdpcCode->nc()),
frames, static_cast<double>(iters) / frames, static_cast<double>(tFrame) * 1e-6);
#else
sprintf(resStr, "%lf %.3e %.3e %lu %.3e",
xVals[i], static_cast<double>(fec) / frames, static_cast<double>(bec) / (frames * mLdpcCode->nc()),
frames, static_cast<double>(iters) / frames);
#endif
printResStr[i + 1].assign(resStr);
try
{
fp.open(mSimulationParams.resultFile);
for (const auto &x : printResStr)
{
fp << x << "\n";
}
fp.close();
}
catch (...)
{
printf("Warning: can not open logfile for writing\n");
}
#ifdef LOG_CW
//log_error(frames, xVals[i]);
#endif
#endif
//save to result struct
if (mResults != nullptr)
{
mResults->fer[i] = static_cast<double>(fec) / frames;
mResults->ber[i] = static_cast<double>(bec) / (frames * mLdpcCode->nc());
mResults->avg_iter[i] = static_cast<double>(iters) / frames;
mResults->time[i] = static_cast<double>(tFrame) * 1e-6;
mResults->fec[i] = fec;
mResults->frames[i] = frames;
}
timeStart += std::chrono::high_resolution_clock::now() - timeNow; //dont measure time for printing files
}
}
}
} while (fec < minFec && frames < maxFrames && !*stopFlag); //end while
}
#ifndef LIB_SHARED
printf("\n");
#endif
} //end for
*resStr = 0;
}
/*
void ldpc_sim::print_file_header(const char *binaryFile, const char *codeFile, const char *simFile, const char *mapFile)
{
FILE *fp = fopen(mLogfile, "a+");
fprintf(fp, "%% binary: %s (Version: %s, Built: %s)\n", binaryFile, VERSION, BUILD_DATE);
fprintf(fp, "%% sim file: %s\n", simFile);
fprintf(fp, "%% code file: %s\n", codeFile);
fprintf(fp, "%% mapping file: %s\n", mapFile);
fprintf(fp, "%% result file: %s\n", mLogfile);
fprintf(fp, "%% iter: %lu\n", mBPIter);
fprintf(fp, "%% max frames: %lu\n", mMaxFrames);
fprintf(fp, "%% min fec: %lu\n", mMinFec);
fprintf(fp, "%% BP early terminate: %hu\n", 1);
fprintf(fp, "%% num threads: %d\n", 1);
}
*/
/*
void ldpc_sim::log_error(u64 pFrameNum, double pSNR)
{
char errors_file[MAX_FILENAME_LEN];
snprintf(errors_file, MAX_FILENAME_LEN, "errors_%s", mLogfile.c_str());
FILE *fp = fopen(errors_file, "a+");
if (!fp)
{
printf("can not
open error log file.\n");
exit(EXIT_FAILU
RE);
}
// calculation of syndrome and failed syndrome checks
u64 synd_weight = 0;
for (auto si : mLdpcDecoder->syndrome())
{
synd_weight += si;
}
std::vector<u64> failed_checks_idx(synd_weight);
u64 j = 0;
for (u64 i = 0; i < mLdpcCode->mc(); i++)
{
if (mLdpcDecoder->syndrome()[i] == 1)
{
failed_checks_idx[j++] = i;
}
}
// calculation of failed codeword bits
u64 cw_dis = 0;
for (u64 i = 0; i < mLdpcCode->nc(); i++)
{
#ifdef ENCODE
cw_dis += ((mLdpcDecoder->llr_out()[i] <= 0) != mC[pThreads][i]);
#else
cw_dis += ((mLdpcDecoder->llr_out()[i] <= 0) != 0);
#endif
}
std::vector<u64> x(mN);
std::vector<u64> xhat(mN);
std::vector<u64> chat(mLdpcCode->nc());
for (u64 i = 0; i < mLdpcCode->nc(); ++i)
{
chat[i] = (mLdpcDecoder->llr_out()[i] <= 0);
}
u64 tmp;
//map c to x map_c_to_x(c, x);
for (u64 i = 0; i < mN; i++)
{
tmp = 0;
for (u64 j = 0; j < mBits; j++)
{
tmp += mC[mBitMapper[j][i]] << (mBits - 1 - j);
}
x[i] = mLabelsRev[tmp];
}
//map_c_to_x(chat, xhat);
for (u64 i = 0; i < mN; i++)
{
tmp = 0;
for (u64 j = 0; j < mBits; j++)
{
tmp += chat[mBitMapper[j][i]] << (mBits - 1 - j);
}
xhat[i] = mLabelsRev[tmp];
}
double cw_dis_euc = 0;
for (u64 i = 0; i < mN; i++)
{
#ifdef ENCODE
cw_dis_euc += (mConstellation.X()[x[i]] - mConstellation.X()[xhat[i]]) * (mConstellation.X()[x[i]] - mConstellation.X()[xhat[i]]);
#else
cw_dis_euc += (mConstellation.X()[0] - mConstellation.X()[xhat[i]]) * (mConstellation.X()[0] - mConstellation.X()[xhat[i]]);
#endif
}
std::vector<u64> failed_bits_idx(cw_dis);
j = 0;
for (u64 i = 0; i < mLdpcCode->nc(); i++)
{
#ifdef ENCODE
if (chat[i] != mC[pThreads][i])
{
failed_bits_idx[j++] = i;
}
#else
if (chat[i] != 0)
{
failed_bits_idx[j++] = i;
}
#endif
}
// print results in file
fprintf(fp, "SNR: %.2f -- frame: %lu -- is codeword: %d -- dE(c,chat): %.3f -- dH(c,chat): %lu | ", pSNR, pFrameNum, synd_weight == 0, cw_dis_euc, cw_dis);
for (auto failed_bits_idx_i : failed_bits_idx)
{
fprintf(fp, "%lu ", failed_bits_idx_i);
}
fprintf(fp, " -- ");
fprintf(fp, "synd weight: %lu | ", synd_weight);
for (auto failed_checks_idx_i : failed_checks_idx)
{
fprintf(fp, "%lu ", failed_checks_idx_i);
}
fprintf(fp, "\n");
fclose(fp);
}
*/
} // namespace ldpc
| 35.67402
| 159
| 0.419924
|
patrickwillner
|
8ff1bb73cfc65f29b37e4a2be18d431483970428
| 8,392
|
cpp
|
C++
|
server-client-sample/connectivity/classic/ServerTest.cpp
|
kaiostech/gonk-binder
|
5ab61435a1939f992e4ace372b9c694a65023927
|
[
"FSFAP"
] | null | null | null |
server-client-sample/connectivity/classic/ServerTest.cpp
|
kaiostech/gonk-binder
|
5ab61435a1939f992e4ace372b9c694a65023927
|
[
"FSFAP"
] | null | null | null |
server-client-sample/connectivity/classic/ServerTest.cpp
|
kaiostech/gonk-binder
|
5ab61435a1939f992e4ace372b9c694a65023927
|
[
"FSFAP"
] | 2
|
2020-07-17T01:55:32.000Z
|
2021-08-12T06:12:29.000Z
|
/* (c) 2020 KAI OS TECHNOLOGIES (HONG KONG) LIMITED All rights reserved. This
* file or any portion thereof may not be reproduced or used in any manner
* whatsoever without the express written permission of KAI OS TECHNOLOGIES
* (HONG KONG) LIMITED. KaiOS is the trademark of KAI OS TECHNOLOGIES (HONG
* KONG) LIMITED or its affiliate company and may be registered in some
* jurisdictions. All other trademarks are the property of their respective
* owners.
*/
#include "ServerTest.h"
#include <binder/IInterface.h>
#include <binder/IServiceManager.h>
#include <binder/ProcessState.h>
#define KAIOS_SERVER_DEBUG(args...) \
__android_log_print(ANDROID_LOG_INFO, "KaiOS_AIDL_ConnectivityServer", ##args)
using android::ProcessState;
using android::sp;
using android::binder::Status;
// TODO: REWRITE_BY_YOURSELF_START
#include "b2g/connectivity/BnConnectivity.h"
using b2g::connectivity::CaptivePortalLandingParcel;
using b2g::connectivity::ICaptivePortalLandingListener;
using b2g::connectivity::IConnectivityEventListener;
using b2g::connectivity::ITetheringStatusListener;
using b2g::connectivity::NetworkInfoParcel;
using b2g::connectivity::TetheringStatusParcel;
// Helper function.
void ServerTest::InitNetworkInfo(NetworkInfoParcel& aNetworkInfo) {
aNetworkInfo.name.clear();
aNetworkInfo.netId = 0;
aNetworkInfo.state = IConnectivity::NETWORK_STATE_UNKNOWN;
aNetworkInfo.type = IConnectivity::NETWORK_TYPE_UNKNOWN;
aNetworkInfo.prefixLengths.clear();
aNetworkInfo.ips.clear();
aNetworkInfo.gateways.clear();
aNetworkInfo.dnses.clear();
}
// TODO: REWRITE_BY_YOURSELF_END
ServerTest::ServerTest() {
// TODO: REWRITE_BY_YOURSELF
InitNetworkInfo(mActiveNetworkInfo);
android::defaultServiceManager()->addService(
android::String16(getServiceName()), this);
sp<ProcessState> process(ProcessState::self());
process->startThreadPool();
}
// TODO: REWRITE_BY_YOURSELF_START
Status ServerTest::isAlive(bool* aLive) {
*aLive = true;
return Status::ok();
}
// Network function
Status ServerTest::addEventListener(
const sp<IConnectivityEventListener>& listener) {
std::lock_guard lock(mNetworkEventMutex);
class DeathRecipient : public android::IBinder::DeathRecipient {
public:
DeathRecipient(ServerTest* serverTest,
sp<IConnectivityEventListener> listener)
: mServerTest(serverTest), mListener(std::move(listener)) {}
~DeathRecipient() override = default;
void binderDied(const android::wp<android::IBinder>& /* who */) override {
KAIOS_SERVER_DEBUG("Client is dead, remove listener");
mServerTest->removeEventListener(mListener);
}
private:
ServerTest* mServerTest;
sp<IConnectivityEventListener> mListener;
};
sp<android::IBinder::DeathRecipient> deathRecipient =
new DeathRecipient(this, listener);
android::IInterface::asBinder(listener)->linkToDeath(deathRecipient);
mListenerTestMap.insert({listener, deathRecipient});
return Status::ok();
}
Status ServerTest::removeEventListener(
const sp<IConnectivityEventListener>& listener) {
std::lock_guard lock(mNetworkEventMutex);
mListenerTestMap.erase(listener);
return Status::ok();
}
Status ServerTest::getActiveNetworkInfo(NetworkInfoParcel* aNetworkInfoParcel) {
*aNetworkInfoParcel = mActiveNetworkInfo;
return Status::ok();
}
Status ServerTest::getNetworkInfos(
std::vector<NetworkInfoParcel>* aNetworkInfoParcels) {
*aNetworkInfoParcels = mNetworkInfos;
return Status::ok();
}
void ServerTest::updateActiveNetworkInfo(
NetworkInfoParcel& aNetworkInfoParcel) {
mActiveNetworkInfo = aNetworkInfoParcel;
for (auto& listenerMap : mListenerTestMap) {
listenerMap.first->onActiveNetworkChanged(aNetworkInfoParcel);
}
}
void ServerTest::updateNetworkInfo(NetworkInfoParcel& aNetworkInfoParcel) {
// Update NetworkInfos cache.
bool found = false;
for (uint32_t i = 0; i < mNetworkInfos.size(); i++) {
if (mNetworkInfos[i].type == aNetworkInfoParcel.type &&
mNetworkInfos[i].name == aNetworkInfoParcel.name) {
// Replace by new status.
found = true;
mNetworkInfos[i] = aNetworkInfoParcel;
break;
}
}
if (!found) {
mNetworkInfos.push_back(aNetworkInfoParcel);
}
for (auto& listenerMap : mListenerTestMap) {
listenerMap.first->onNetworkChanged(aNetworkInfoParcel);
}
}
// Tethering function
Status ServerTest::getTetheringStatus(
TetheringStatusParcel* aTetheringStatusParcel) {
*aTetheringStatusParcel = mTetheringStatusParcel;
return Status::ok();
}
Status ServerTest::addTetheringStatusListener(
const sp<ITetheringStatusListener>& listener) {
std::lock_guard lock(mTetheringMutex);
class DeathRecipient : public android::IBinder::DeathRecipient {
public:
DeathRecipient(ServerTest* serverTest,
sp<ITetheringStatusListener> listener)
: mServerTest(serverTest), mListener(std::move(listener)) {}
~DeathRecipient() override = default;
void binderDied(const android::wp<android::IBinder>& /* who */) override {
KAIOS_SERVER_DEBUG("Client is dead, remove tethering listener");
mServerTest->removeTetheringStatusListener(mListener);
}
private:
ServerTest* mServerTest;
sp<ITetheringStatusListener> mListener;
};
sp<android::IBinder::DeathRecipient> deathRecipient =
new DeathRecipient(this, listener);
android::IInterface::asBinder(listener)->linkToDeath(deathRecipient);
mTetheringListenerTestMap.insert({listener, deathRecipient});
return Status::ok();
}
Status ServerTest::removeTetheringStatusListener(
const sp<ITetheringStatusListener>& listener) {
std::lock_guard lock(mTetheringMutex);
mTetheringListenerTestMap.erase(listener);
return Status::ok();
}
void ServerTest::updateTetheringStatus(
TetheringStatusParcel& aTetheringStatusParcel) {
mTetheringStatusParcel = aTetheringStatusParcel;
for (auto& listenerMap : mTetheringListenerTestMap) {
listenerMap.first->onTetheringStatusChanged(aTetheringStatusParcel);
}
}
// Captive portal function
Status ServerTest::getCaptivePortalLandings(
std::vector<CaptivePortalLandingParcel>* aCaptivePortalLandings) {
*aCaptivePortalLandings = mCaptivePortalLandings;
return Status::ok();
}
Status ServerTest::addCaptivePortalLandingListener(
const sp<ICaptivePortalLandingListener>& listener) {
std::lock_guard lock(mCaptivePortalMutex);
class DeathRecipient : public android::IBinder::DeathRecipient {
public:
DeathRecipient(ServerTest* serverTest,
sp<ICaptivePortalLandingListener> listener)
: mServerTest(serverTest), mListener(std::move(listener)) {}
~DeathRecipient() override = default;
void binderDied(const android::wp<android::IBinder>& /* who */) override {
KAIOS_SERVER_DEBUG("Client is dead, remove captive portal listener");
mServerTest->removeCaptivePortalLandingListener(mListener);
}
private:
ServerTest* mServerTest;
sp<ICaptivePortalLandingListener> mListener;
};
sp<android::IBinder::DeathRecipient> deathRecipient =
new DeathRecipient(this, listener);
android::IInterface::asBinder(listener)->linkToDeath(deathRecipient);
mCaptivePortalListenerTestMap.insert({listener, deathRecipient});
return Status::ok();
}
Status ServerTest::removeCaptivePortalLandingListener(
const sp<ICaptivePortalLandingListener>& listener) {
std::lock_guard lock(mCaptivePortalMutex);
mCaptivePortalListenerTestMap.erase(listener);
return Status::ok();
}
void ServerTest::updateCaptivePortal(
CaptivePortalLandingParcel& aCaptivePortalLandingParcel) {
// Update captive portal status.
bool found = false;
for (uint32_t i = 0; i < mCaptivePortalLandings.size(); i++) {
if (mCaptivePortalLandings[i].networkType ==
aCaptivePortalLandingParcel.networkType &&
mCaptivePortalLandings[i].landing ==
aCaptivePortalLandingParcel.landing) {
// Replace by new status.
found = true;
mCaptivePortalLandings[i] = aCaptivePortalLandingParcel;
break;
}
}
if (!found) {
mCaptivePortalLandings.push_back(aCaptivePortalLandingParcel);
}
for (auto& listenerMap : mCaptivePortalListenerTestMap) {
listenerMap.first->onCaptivePortalLandingChanged(
aCaptivePortalLandingParcel);
}
}
// TODO: REWRITE_BY_YOURSELF_END
| 33.03937
| 80
| 0.750119
|
kaiostech
|
8ff25b07f1019afac31fa0b3a7cbac04c3c1114e
| 1,116
|
cpp
|
C++
|
decompiler/level_extractor/extract_common.cpp
|
Hat-Kid/jak-project
|
0e2320ca9584118316313e41e646b179a1083feb
|
[
"ISC"
] | null | null | null |
decompiler/level_extractor/extract_common.cpp
|
Hat-Kid/jak-project
|
0e2320ca9584118316313e41e646b179a1083feb
|
[
"ISC"
] | null | null | null |
decompiler/level_extractor/extract_common.cpp
|
Hat-Kid/jak-project
|
0e2320ca9584118316313e41e646b179a1083feb
|
[
"ISC"
] | null | null | null |
#include <cstddef>
#include "extract_common.h"
u32 clean_up_vertex_indices(std::vector<u32>& idx) {
std::vector<u32> fixed;
u32 num_tris = 0;
bool looking_for_start = true;
size_t i_of_start;
for (size_t i = 0; i < idx.size(); i++) {
if (looking_for_start) {
if (idx[i] != UINT32_MAX) {
looking_for_start = false;
i_of_start = i;
}
} else {
if (idx[i] == UINT32_MAX) {
looking_for_start = true;
size_t num_verts = i - i_of_start;
if (num_verts >= 3) {
if (!fixed.empty()) {
fixed.push_back(UINT32_MAX);
}
fixed.insert(fixed.end(), idx.begin() + i_of_start, idx.begin() + i);
num_tris += (num_verts - 2);
}
}
}
}
if (!looking_for_start) {
size_t num_verts = idx.size() - i_of_start;
if (num_verts >= 3) {
if (!fixed.empty()) {
fixed.push_back(UINT32_MAX);
}
fixed.insert(fixed.end(), idx.begin() + i_of_start, idx.begin() + idx.size());
num_tris += (num_verts - 2);
}
}
idx = std::move(fixed);
return num_tris;
}
| 24.8
| 84
| 0.548387
|
Hat-Kid
|
8ff4c7c05e71629adadc56b321e708fdd532b0a6
| 5,471
|
cpp
|
C++
|
benchmark/BM_sinecrunch.cpp
|
MuAlphaOmegaEpsilon/sinecrunch
|
65d4f6003f60fcaa973ae67e90c9f6a5cc16bce8
|
[
"MIT"
] | 1
|
2019-04-05T19:09:46.000Z
|
2019-04-05T19:09:46.000Z
|
benchmark/BM_sinecrunch.cpp
|
MuAlphaOmegaEpsilon/sinecrunch
|
65d4f6003f60fcaa973ae67e90c9f6a5cc16bce8
|
[
"MIT"
] | null | null | null |
benchmark/BM_sinecrunch.cpp
|
MuAlphaOmegaEpsilon/sinecrunch
|
65d4f6003f60fcaa973ae67e90c9f6a5cc16bce8
|
[
"MIT"
] | null | null | null |
#include <sltbench/Bench.h>
#include <algorithm>
#define _USE_MATH_DEFINES
#include <math.h>
#include <numeric>
// A simple shorthand for single precision floating point.
using floatSP = float;
// A simple shorthand for double precision floating point.
using floatDP = double;
// A simple shorthand for quadruple precision floating point.
using floatQP = long double;
// The total number of samples to take.
// One more is added since the sample at ZERO is also required.
constexpr uint32_t samplesNum = (1 << 15) + 1;
// The amount of space there is between two consecutive samples.
constexpr floatDP samplePeriod = (floatSP) (M_PI * 2.0f / (samplesNum - 1));
// Since the purpose of the benchmark is about measuring sinusoid function
// calls performance, we don't want to deal with angle conversions at
// bench-time: lets have all the angles for every float precision already
// calculated.
static floatSP anglesSP [samplesNum];
static floatDP anglesDP [samplesNum];
static floatQP anglesQP [samplesNum];
// Returns the array of angles of the specified type.
template <typename T> T* getAngles ();
template <> floatSP* getAngles () { return anglesSP; }
template <> floatDP* getAngles () { return anglesDP; }
template <> floatQP* getAngles () { return anglesQP; }
// The ground truth values for a sinusoid.
// These samples are calculated using the highest precision function at
// disposal, which returns a quad precision float.
static floatQP groundTruth [samplesNum];
// A little shorthand to specify both, the BEGIN and END iterators of the
// passed array.
// Since the number of samples is always the same in this whole file, there's
// no need to always specify the same details about array length.
#define RANGE(array) array, array + samplesNum
void initialize ()
{
// Populate the single precision angles array first.
// The single precision array gets populated first since its lowest
// precision one, and there's no precision loss when converting to higher
// precision arrays.
std::iota (RANGE (anglesSP), samplePeriod);
// Copy over the other precision arrays.
// The copy is required instead of doing iota again:
// we don't want to populate the angles arrays at different precision
// levels, we want to have the EXACT same angles just converted to
// different types! That's why we populated anglesSP first.
std::copy (RANGE (anglesSP), anglesDP);
std::copy (RANGE (anglesSP), anglesQP);
// Calculate the ground truth samples.
std::transform (RANGE (anglesQP), groundTruth, sinl);
}
template <typename T> constexpr
floatDP error_abs (const T& val, const floatQP& ref) noexcept
{
return fabs (static_cast <floatDP> (val - static_cast <T> (ref)));
}
template <typename T> constexpr
floatDP error_rel (const T& val, const floatQP& ref) noexcept
{
return fabs (1.0 - static_cast <floatDP> (val / static_cast <T> (ref)));
}
template <typename T, T (*sinusoid)(T)>
static void benchSinusoid ()
{
// const T* angles = getAngles <T> ();
// T result [samplesNum];
// floatDP errors [samplesNum];
// double random = fmod (rand () / 1000.0, 2.0 * M_PI);
// // Main funciton benchmark loop: this is where the execution of the
// // function is actually measured.
// for (const auto _ : state)
// benchmark::DoNotOptimize (result[0] = sinusoid (random));
// std::transform (RANGE (angles), result, sinusoid);
// // Total number of items processed.
// // Google Benchmark will calculate how many items_per_second based on this.
// state.SetItemsProcessed (state.iterations ());
// state.SetBytesProcessed (state.iterations () * sizeof (T));
// state.counters["angle"] = random;
// // Absolute errors calculations
// std::transform (RANGE (result), groundTruth, errors, error_abs <T>);
// state.counters["AErr_avg"] = std::accumulate (RANGE (errors), 0.0L) * samplePeriod;
// state.counters["AErr_max"] = *std::max_element (RANGE (errors));
// state.counters["AErr_min"] = *std::min_element (RANGE (errors));
// // Relative errors calculations
// std::transform (RANGE (result), groundTruth, errors, error_rel <T>);
// state.counters["RE_avg"] = std::accumulate (RANGE (errors), 0.0L) * samplePeriod;
// state.counters["RE_max"] = *std::max_element (RANGE (errors));
// state.counters["RE_min"] = *std::min_element (RANGE (errors));
}
// A little shorthand to mark a function for benchmarking and to rename it.
// Type is at the same time the argument and the return type.
// Function is the sinusoid to test.
// Name defines under which tag the function should appear in the results.
#define BENCH_SINUSOID(type, function, name) \
const auto SIN_ ## type ## _ ## name = benchSinusoid <type, function>; \
SLTBENCH_FUNCTION (SIN_ ## type ## _ ## name)
// Register all the standard functions to benchmark.
BENCH_SINUSOID (floatQP, sinl, compiler)
BENCH_SINUSOID (floatDP, sin, compiler)
BENCH_SINUSOID (floatSP, sinf, compiler)
// Register FastTrigo functions to benchmark.
#include <fasttrigo.h>
BENCH_SINUSOID (floatSP, FT::sin, fasttrigo_fast)
BENCH_SINUSOID (floatSP, FTA::sin, fasttrigo_precise)
// Register sinecrunch functions to benchmark.
#include <sinecrunch.hpp>
BENCH_SINUSOID (floatSP, sinecrunch::sin<1>, sinecrunch)
int main(int argc, char** argv)
{
initialize ();
return sltbench::Main(argc, argv);
}
| 37.993056
| 90
| 0.703528
|
MuAlphaOmegaEpsilon
|
8ff5e8b271e4fde432711382d7adc743646f5149
| 2,514
|
hh
|
C++
|
nox/src/include/timeval.hh
|
ayjazz/OESS
|
deadc504d287febc7cbd7251ddb102bb5c8b1f04
|
[
"Apache-2.0"
] | 28
|
2015-02-04T13:59:25.000Z
|
2021-12-29T03:44:47.000Z
|
nox/src/include/timeval.hh
|
ayjazz/OESS
|
deadc504d287febc7cbd7251ddb102bb5c8b1f04
|
[
"Apache-2.0"
] | 552
|
2015-01-05T18:25:54.000Z
|
2022-03-16T18:51:13.000Z
|
nox/src/include/timeval.hh
|
ayjazz/OESS
|
deadc504d287febc7cbd7251ddb102bb5c8b1f04
|
[
"Apache-2.0"
] | 25
|
2015-02-04T18:48:20.000Z
|
2020-06-18T15:51:05.000Z
|
/* Copyright 2008 (C) Nicira, Inc.
*
* This file is part of NOX.
*
* NOX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NOX 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 NOX. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TIMEVAL_HH
#define TIMEVAL_HH 1
#include <sys/time.h>
long long int time_msec();
struct timeval do_gettimeofday(bool update = false);
::timeval operator+(const ::timeval&, const ::timeval&);
::timeval operator-(const ::timeval&, const ::timeval&);
const ::timeval& operator+=(::timeval&, const ::timeval&);
const ::timeval& operator-=(::timeval&, const ::timeval&);
int timeval_compare(const ::timeval&, const ::timeval&);
double timeval_to_double(const ::timeval&);
double timespec_to_double(const ::timespec&);
static inline timeval make_timeval(unsigned long int tv_sec,
unsigned long int tv_usec)
{
timeval tv;
tv.tv_sec = tv_sec;
tv.tv_usec = tv_usec;
return tv;
}
static inline timespec make_timespec(unsigned long int tv_sec,
unsigned long int tv_nsec)
{
timespec ts;
ts.tv_sec = tv_sec;
ts.tv_nsec = tv_nsec;
return ts;
}
long int timeval_to_ms(const ::timeval&);
::timeval timeval_from_ms(long int ms);
long int timespec_to_ms(const ::timespec&);
::timespec timespec_from_ms(long int ms);
static inline bool operator==(const ::timeval& x, const ::timeval& y)
{
return timeval_compare(x, y) == 0;
}
static inline bool operator!=(const ::timeval& x, const ::timeval& y)
{
return timeval_compare(x, y) != 0;
}
static inline bool operator<(const ::timeval& x, const ::timeval& y)
{
return timeval_compare(x, y) < 0;
}
static inline bool operator>(const ::timeval& x, const ::timeval& y)
{
return timeval_compare(x, y) > 0;
}
static inline bool operator<=(const ::timeval& x, const ::timeval& y)
{
return timeval_compare(x, y) <= 0;
}
static inline bool operator>=(const ::timeval& x, const ::timeval& y)
{
return timeval_compare(x, y) >= 0;
}
#endif /* timeval.hh */
| 28.247191
| 71
| 0.683373
|
ayjazz
|
8ffc731c5d2b12384e2e867f7832b11c629e86a6
| 1,420
|
cpp
|
C++
|
Testing/testCiphers.cpp
|
MPAGS-CPP-2019/mpags-day-5-JamesDownsLab
|
9af7ace33284d06aaf97143211a1646e97f458c8
|
[
"MIT"
] | null | null | null |
Testing/testCiphers.cpp
|
MPAGS-CPP-2019/mpags-day-5-JamesDownsLab
|
9af7ace33284d06aaf97143211a1646e97f458c8
|
[
"MIT"
] | null | null | null |
Testing/testCiphers.cpp
|
MPAGS-CPP-2019/mpags-day-5-JamesDownsLab
|
9af7ace33284d06aaf97143211a1646e97f458c8
|
[
"MIT"
] | null | null | null |
//! Unit Tests for MPAGSCipher CaesarCipher Class
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "Cipher.hpp"
#include "CipherMode.hpp"
#include "CaesarCipher.hpp"
#include "PlayfairCipher.hpp"
#include "VigenereCipher.hpp"
bool testCipher(
const Cipher& cipher,
const CipherMode mode,
const std::string& inputText,
const std::string& outputText){
if (outputText == cipher.applyCipher(inputText, mode)) {
return true;
}
else {
return false;
}
}
TEST_CASE("Caesar Cipher", "[caesar]") {
CaesarCipher cipher {10};
REQUIRE(testCipher(cipher, CipherMode::Encrypt, "HELLOWORLD", "ROVVYGYBVN"));
REQUIRE(testCipher(cipher, CipherMode::Decrypt, "ROVVYGYBVN", "HELLOWORLD"));
}
TEST_CASE("Playfair Cipher", "[playfair]") {
PlayfairCipher cipher {"hello"};
REQUIRE(testCipher(cipher, CipherMode::Encrypt, "BOBISSOMESORTOFJUNIORCOMPLEXXENOPHONEONEZEROTHING", "FHIQXLTLKLTLSUFNPQPKETFENIOLVSWLTFIAFTLAKOWATEQOKPPA"));
REQUIRE(testCipher(cipher, CipherMode::Decrypt, "FHIQXLTLKLTLSUFNPQPKETFENIOLVSWLTFIAFTLAKOWATEQOKPPA", "BOBISXSOMESORTOFIUNIORCOMPLEXQXENOPHONEONEZEROTHINGZ"));
}
TEST_CASE("Vigenere Cipher", "[vigenere]") {
VigenereCipher cipher {"key"};
REQUIRE(testCipher(cipher, CipherMode::Encrypt, "HELLOWORLD", "RIJVSUYVJN"));
REQUIRE(testCipher(cipher, CipherMode::Decrypt, "RIJVSUYVJN", "HELLOWORLD"));
}
| 33.809524
| 165
| 0.725352
|
MPAGS-CPP-2019
|
8904f7bd15a658d3e38bd83e3df7292e443b5f28
| 147
|
cpp
|
C++
|
common/crc32.cpp
|
cschreib/cobalt
|
11184864008f411875a3321f3fb4493ebc9a79e2
|
[
"MIT"
] | 9
|
2015-12-09T22:25:25.000Z
|
2022-01-12T23:50:56.000Z
|
common/crc32.cpp
|
cschreib/cobalt
|
11184864008f411875a3321f3fb4493ebc9a79e2
|
[
"MIT"
] | 6
|
2019-12-28T21:18:16.000Z
|
2020-02-15T21:04:54.000Z
|
common/crc32.cpp
|
cschreib/cobalt
|
11184864008f411875a3321f3fb4493ebc9a79e2
|
[
"MIT"
] | null | null | null |
#include "crc32.hpp"
std::uint32_t get_crc32(const std::string& str) {
return recursive_crc32(0, str.c_str(), 0, str.size(), 0, 0x4C11DB7);
}
| 24.5
| 72
| 0.680272
|
cschreib
|
890b3e947225c14bf71935b487d6202fac00c508
| 884
|
hpp
|
C++
|
code/interface.hpp
|
BrunoFCM/CAL_projeto
|
1b0ebadd350dcbbc7d5ee99d93cb98a377fd8b56
|
[
"MIT"
] | 1
|
2021-01-12T12:33:00.000Z
|
2021-01-12T12:33:00.000Z
|
code/interface.hpp
|
BrunoFCM/CAL_projeto
|
1b0ebadd350dcbbc7d5ee99d93cb98a377fd8b56
|
[
"MIT"
] | null | null | null |
code/interface.hpp
|
BrunoFCM/CAL_projeto
|
1b0ebadd350dcbbc7d5ee99d93cb98a377fd8b56
|
[
"MIT"
] | null | null | null |
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include "Group.hpp"
#include "bus.hpp"
#include "TouristGenerator.hpp"
#include "TouristOrganizer.hpp"
using namespace std;
#define INPUT_FILE "input.txt"
#define NODES_FILE "T03_nodes_X_Y_Fafe.txt"
#define EDGES_FILE "T03_edges_Fafe.txt"
bool loadTourists(vector<Tourist*> &tourists, vector<Bus*> &buses);
void loadMap(Graph &map);
void add_tourist(vector<Tourist*> &tourists);
void add_bus(vector<Bus*> &buses);
void check_tourist(vector<Tourist*> &tourists);
void check_bus(vector<Bus*> &buses);
void get_path(vector<Tourist*> &tourists, vector<Bus*> &buses, Graph &map);
void get_groups(vector<Tourist*> &tourists, vector<Bus*> &buses, Graph &map);
void random_tourist(vector<Tourist*> &tourists);
void app_interface(vector<Tourist*> &tourists, vector<Bus*> &buses, Graph &map);
| 34
| 80
| 0.755656
|
BrunoFCM
|
8913a1fadb946bca918fdf7792263d1e2c83ea9c
| 571
|
cpp
|
C++
|
c3dEngine2/c3dEngine/c3dEngine/core/c3dGlobalTimer.cpp
|
wantnon2/c3dEngine2
|
0c12d077d8f2bac8c12b8f720eccc5a2f3f3a7c1
|
[
"MIT"
] | 27
|
2015-01-11T15:42:21.000Z
|
2021-10-10T06:24:37.000Z
|
c3dEngine2/c3dEngine/c3dEngine/core/c3dGlobalTimer.cpp
|
wantnon2/c3dEngine2
|
0c12d077d8f2bac8c12b8f720eccc5a2f3f3a7c1
|
[
"MIT"
] | null | null | null |
c3dEngine2/c3dEngine/c3dEngine/core/c3dGlobalTimer.cpp
|
wantnon2/c3dEngine2
|
0c12d077d8f2bac8c12b8f720eccc5a2f3f3a7c1
|
[
"MIT"
] | 18
|
2015-01-11T15:42:28.000Z
|
2021-10-10T06:24:38.000Z
|
//
// c3dGlobalTimer.cpp
// HelloOpenGL
//
// Created by wantnon (yang chao) on 12-11-19.
//
//
#include "c3dGlobalTimer.h"
static Cc3dGlobalTimer*s_globalTimer=NULL;
Cc3dGlobalTimer*Cc3dGlobalTimer::sharedGlobalTimer(){
if(s_globalTimer==NULL){
s_globalTimer=new Cc3dGlobalTimer();
}
return s_globalTimer;
}
//--------------------
static Cc3dFrameCounter*s_frameCounter=NULL;
Cc3dFrameCounter*Cc3dFrameCounter::sharedFrameCounter(){
if(s_frameCounter==NULL){
s_frameCounter=new Cc3dFrameCounter();
}
return s_frameCounter;
}
| 21.961538
| 56
| 0.698774
|
wantnon2
|
891d23337829d76802201a034f1fd38f24e9733f
| 16,168
|
cc
|
C++
|
mac/chatkit/cim/pb/CIM.Friend.pb.cc
|
xmcy0011/CoffeeChat-Desktop
|
20b907e95ec8b481dbbb77a3b22587ac108520fb
|
[
"MIT"
] | 1
|
2021-08-05T10:32:24.000Z
|
2021-08-05T10:32:24.000Z
|
mac/chatkit/cim/pb/CIM.Friend.pb.cc
|
xmcy0011/CoffeeChat-Desktop
|
20b907e95ec8b481dbbb77a3b22587ac108520fb
|
[
"MIT"
] | null | null | null |
mac/chatkit/cim/pb/CIM.Friend.pb.cc
|
xmcy0011/CoffeeChat-Desktop
|
20b907e95ec8b481dbbb77a3b22587ac108520fb
|
[
"MIT"
] | null | null | null |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: CIM.Friend.proto
#include "CIM.Friend.pb.h"
#include <algorithm>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
PROTOBUF_PRAGMA_INIT_SEG
namespace CIM {
namespace Friend {
constexpr CIMFriendQueryUserListReq::CIMFriendQueryUserListReq(
::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized)
: user_id_(PROTOBUF_ULONGLONG(0)){}
struct CIMFriendQueryUserListReqDefaultTypeInternal {
constexpr CIMFriendQueryUserListReqDefaultTypeInternal()
: _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {}
~CIMFriendQueryUserListReqDefaultTypeInternal() {}
union {
CIMFriendQueryUserListReq _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT CIMFriendQueryUserListReqDefaultTypeInternal _CIMFriendQueryUserListReq_default_instance_;
constexpr CIMFriendQueryUserListRsp::CIMFriendQueryUserListRsp(
::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized)
: user_info_list_()
, user_id_(PROTOBUF_ULONGLONG(0)){}
struct CIMFriendQueryUserListRspDefaultTypeInternal {
constexpr CIMFriendQueryUserListRspDefaultTypeInternal()
: _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {}
~CIMFriendQueryUserListRspDefaultTypeInternal() {}
union {
CIMFriendQueryUserListRsp _instance;
};
};
PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT CIMFriendQueryUserListRspDefaultTypeInternal _CIMFriendQueryUserListRsp_default_instance_;
} // namespace Friend
} // namespace CIM
namespace CIM {
namespace Friend {
// ===================================================================
class CIMFriendQueryUserListReq::_Internal {
public:
};
CIMFriendQueryUserListReq::CIMFriendQueryUserListReq(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::MessageLite(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:CIM.Friend.CIMFriendQueryUserListReq)
}
CIMFriendQueryUserListReq::CIMFriendQueryUserListReq(const CIMFriendQueryUserListReq& from)
: ::PROTOBUF_NAMESPACE_ID::MessageLite() {
_internal_metadata_.MergeFrom<std::string>(from._internal_metadata_);
user_id_ = from.user_id_;
// @@protoc_insertion_point(copy_constructor:CIM.Friend.CIMFriendQueryUserListReq)
}
void CIMFriendQueryUserListReq::SharedCtor() {
user_id_ = PROTOBUF_ULONGLONG(0);
}
CIMFriendQueryUserListReq::~CIMFriendQueryUserListReq() {
// @@protoc_insertion_point(destructor:CIM.Friend.CIMFriendQueryUserListReq)
SharedDtor();
_internal_metadata_.Delete<std::string>();
}
void CIMFriendQueryUserListReq::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
}
void CIMFriendQueryUserListReq::ArenaDtor(void* object) {
CIMFriendQueryUserListReq* _this = reinterpret_cast< CIMFriendQueryUserListReq* >(object);
(void)_this;
}
void CIMFriendQueryUserListReq::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void CIMFriendQueryUserListReq::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void CIMFriendQueryUserListReq::Clear() {
// @@protoc_insertion_point(message_clear_start:CIM.Friend.CIMFriendQueryUserListReq)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
user_id_ = PROTOBUF_ULONGLONG(0);
_internal_metadata_.Clear<std::string>();
}
const char* CIMFriendQueryUserListReq::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// uint64 user_id = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
user_id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<std::string>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* CIMFriendQueryUserListReq::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:CIM.Friend.CIMFriendQueryUserListReq)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint64 user_id = 1;
if (this->user_id() != 0) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(1, this->_internal_user_id(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(),
static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:CIM.Friend.CIMFriendQueryUserListReq)
return target;
}
size_t CIMFriendQueryUserListReq::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:CIM.Friend.CIMFriendQueryUserListReq)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// uint64 user_id = 1;
if (this->user_id() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size(
this->_internal_user_id());
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size();
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void CIMFriendQueryUserListReq::CheckTypeAndMergeFrom(
const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) {
MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const CIMFriendQueryUserListReq*>(
&from));
}
void CIMFriendQueryUserListReq::MergeFrom(const CIMFriendQueryUserListReq& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:CIM.Friend.CIMFriendQueryUserListReq)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<std::string>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.user_id() != 0) {
_internal_set_user_id(from._internal_user_id());
}
}
void CIMFriendQueryUserListReq::CopyFrom(const CIMFriendQueryUserListReq& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:CIM.Friend.CIMFriendQueryUserListReq)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CIMFriendQueryUserListReq::IsInitialized() const {
return true;
}
void CIMFriendQueryUserListReq::InternalSwap(CIMFriendQueryUserListReq* other) {
using std::swap;
_internal_metadata_.Swap<std::string>(&other->_internal_metadata_);
swap(user_id_, other->user_id_);
}
std::string CIMFriendQueryUserListReq::GetTypeName() const {
return "CIM.Friend.CIMFriendQueryUserListReq";
}
// ===================================================================
class CIMFriendQueryUserListRsp::_Internal {
public:
};
void CIMFriendQueryUserListRsp::clear_user_info_list() {
user_info_list_.Clear();
}
CIMFriendQueryUserListRsp::CIMFriendQueryUserListRsp(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::MessageLite(arena),
user_info_list_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:CIM.Friend.CIMFriendQueryUserListRsp)
}
CIMFriendQueryUserListRsp::CIMFriendQueryUserListRsp(const CIMFriendQueryUserListRsp& from)
: ::PROTOBUF_NAMESPACE_ID::MessageLite(),
user_info_list_(from.user_info_list_) {
_internal_metadata_.MergeFrom<std::string>(from._internal_metadata_);
user_id_ = from.user_id_;
// @@protoc_insertion_point(copy_constructor:CIM.Friend.CIMFriendQueryUserListRsp)
}
void CIMFriendQueryUserListRsp::SharedCtor() {
user_id_ = PROTOBUF_ULONGLONG(0);
}
CIMFriendQueryUserListRsp::~CIMFriendQueryUserListRsp() {
// @@protoc_insertion_point(destructor:CIM.Friend.CIMFriendQueryUserListRsp)
SharedDtor();
_internal_metadata_.Delete<std::string>();
}
void CIMFriendQueryUserListRsp::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
}
void CIMFriendQueryUserListRsp::ArenaDtor(void* object) {
CIMFriendQueryUserListRsp* _this = reinterpret_cast< CIMFriendQueryUserListRsp* >(object);
(void)_this;
}
void CIMFriendQueryUserListRsp::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void CIMFriendQueryUserListRsp::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
void CIMFriendQueryUserListRsp::Clear() {
// @@protoc_insertion_point(message_clear_start:CIM.Friend.CIMFriendQueryUserListRsp)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
user_info_list_.Clear();
user_id_ = PROTOBUF_ULONGLONG(0);
_internal_metadata_.Clear<std::string>();
}
const char* CIMFriendQueryUserListRsp::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// uint64 user_id = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
user_id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// repeated .CIM.Def.CIMUserInfo user_info_list = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr -= 1;
do {
ptr += 1;
ptr = ctx->ParseMessage(_internal_add_user_info_list(), ptr);
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<18>(ptr));
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<std::string>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* CIMFriendQueryUserListRsp::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:CIM.Friend.CIMFriendQueryUserListRsp)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint64 user_id = 1;
if (this->user_id() != 0) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(1, this->_internal_user_id(), target);
}
// repeated .CIM.Def.CIMUserInfo user_info_list = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->_internal_user_info_list_size()); i < n; i++) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(2, this->_internal_user_info_list(i), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(),
static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:CIM.Friend.CIMFriendQueryUserListRsp)
return target;
}
size_t CIMFriendQueryUserListRsp::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:CIM.Friend.CIMFriendQueryUserListRsp)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .CIM.Def.CIMUserInfo user_info_list = 2;
total_size += 1UL * this->_internal_user_info_list_size();
for (const auto& msg : this->user_info_list_) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg);
}
// uint64 user_id = 1;
if (this->user_id() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size(
this->_internal_user_id());
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size();
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void CIMFriendQueryUserListRsp::CheckTypeAndMergeFrom(
const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) {
MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const CIMFriendQueryUserListRsp*>(
&from));
}
void CIMFriendQueryUserListRsp::MergeFrom(const CIMFriendQueryUserListRsp& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:CIM.Friend.CIMFriendQueryUserListRsp)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<std::string>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
user_info_list_.MergeFrom(from.user_info_list_);
if (from.user_id() != 0) {
_internal_set_user_id(from._internal_user_id());
}
}
void CIMFriendQueryUserListRsp::CopyFrom(const CIMFriendQueryUserListRsp& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:CIM.Friend.CIMFriendQueryUserListRsp)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CIMFriendQueryUserListRsp::IsInitialized() const {
return true;
}
void CIMFriendQueryUserListRsp::InternalSwap(CIMFriendQueryUserListRsp* other) {
using std::swap;
_internal_metadata_.Swap<std::string>(&other->_internal_metadata_);
user_info_list_.InternalSwap(&other->user_info_list_);
swap(user_id_, other->user_id_);
}
std::string CIMFriendQueryUserListRsp::GetTypeName() const {
return "CIM.Friend.CIMFriendQueryUserListRsp";
}
// @@protoc_insertion_point(namespace_scope)
} // namespace Friend
} // namespace CIM
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::CIM::Friend::CIMFriendQueryUserListReq* Arena::CreateMaybeMessage< ::CIM::Friend::CIMFriendQueryUserListReq >(Arena* arena) {
return Arena::CreateMessageInternal< ::CIM::Friend::CIMFriendQueryUserListReq >(arena);
}
template<> PROTOBUF_NOINLINE ::CIM::Friend::CIMFriendQueryUserListRsp* Arena::CreateMaybeMessage< ::CIM::Friend::CIMFriendQueryUserListRsp >(Arena* arena) {
return Arena::CreateMessageInternal< ::CIM::Friend::CIMFriendQueryUserListRsp >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 36.662132
| 156
| 0.746598
|
xmcy0011
|
89232393ffcdec7f58dda27e0baea19f45c83444
| 5,658
|
cpp
|
C++
|
dlls/usas.cpp
|
solidi/coldice-remastered
|
e383047320d8cd321d716cdd7cc336231b58bbe1
|
[
"Unlicense"
] | 2
|
2022-01-04T09:37:40.000Z
|
2022-01-12T22:18:54.000Z
|
dlls/usas.cpp
|
solidi/coldice-remastered
|
e383047320d8cd321d716cdd7cc336231b58bbe1
|
[
"Unlicense"
] | null | null | null |
dlls/usas.cpp
|
solidi/coldice-remastered
|
e383047320d8cd321d716cdd7cc336231b58bbe1
|
[
"Unlicense"
] | 1
|
2022-01-06T23:03:05.000Z
|
2022-01-06T23:03:05.000Z
|
/***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "monsters.h"
#include "weapons.h"
#include "nodes.h"
#include "player.h"
#include "gamerules.h"
// special deathmatch shotgun spreads
#define VECTOR_CONE_DM_SHOTGUN Vector( 0.08716, 0.04362, 0.00 )// 10 degrees by 5 degrees
#define VECTOR_CONE_DM_DOUBLESHOTGUN Vector( 0.17365, 0.04362, 0.00 ) // 20 degrees by 5 degrees
enum usas_e {
USAS_AIM = 0,
USAS_LONGIDLE,
USAS_IDLE1,
USAS_LAUNCH,
USAS_RELOAD,
USAS_DEPLOY,
USAS_FIRE1,
USAS_FIRE2,
USAS_FIRE3,
USAS_HOLSTER,
};
#ifdef USAS
LINK_ENTITY_TO_CLASS( weapon_usas, CUsas );
#endif
void CUsas::Spawn( )
{
Precache( );
m_iId = WEAPON_USAS;
SET_MODEL(ENT(pev), "models/w_usas.mdl");
m_iDefaultAmmo = USAS_DEFAULT_GIVE;
FallInit();// get ready to fall
}
void CUsas::Precache( void )
{
PRECACHE_MODEL("models/v_usas.mdl");
PRECACHE_MODEL("models/w_usas.mdl");
PRECACHE_MODEL("models/p_usas.mdl");
m_iShell = PRECACHE_MODEL ("models/w_shotgunshell.mdl");// shotgun shell
PRECACHE_SOUND("items/9mmclip1.wav");
PRECACHE_SOUND ("usas_fire.wav");
PRECACHE_SOUND ("weapons/reload1.wav"); // shotgun reload
PRECACHE_SOUND ("weapons/reload3.wav"); // shotgun reload
PRECACHE_SOUND ("weapons/357_cock1.wav"); // gun empty sound
PRECACHE_SOUND ("weapons/scock1.wav"); // cock gun
m_usSingleFire = PRECACHE_EVENT( 1, "events/usas.sc" );
}
int CUsas::AddToPlayer( CBasePlayer *pPlayer )
{
if ( CBasePlayerWeapon::AddToPlayer( pPlayer ) )
{
MESSAGE_BEGIN( MSG_ONE, gmsgWeapPickup, NULL, pPlayer->pev );
WRITE_BYTE( m_iId );
MESSAGE_END();
return TRUE;
}
return FALSE;
}
int CUsas::GetItemInfo(ItemInfo *p)
{
p->pszName = STRING(pev->classname);
p->pszAmmo1 = "buckshot";
p->iMaxAmmo1 = BUCKSHOT_MAX_CARRY;
p->pszAmmo2 = NULL;
p->iMaxAmmo2 = -1;
p->iMaxClip = USAS_MAX_CLIP;
p->iSlot = 2;
p->iPosition = 3;
p->iFlags = 0;
p->iId = m_iId = WEAPON_USAS;
p->iWeight = USAS_WEIGHT;
p->pszDisplayName = "USAS-12 Auto Shotgun";
return 1;
}
BOOL CUsas::Deploy( )
{
return DefaultDeploy( "models/v_usas.mdl", "models/p_usas.mdl", USAS_DEPLOY, "mp5" );
}
void CUsas::Holster( int skiplocal /* = 0 */ )
{
m_pPlayer->m_flNextAttack = UTIL_WeaponTimeBase() + 0.5;
SendWeaponAnim( USAS_HOLSTER );
}
void CUsas::PrimaryAttack()
{
// don't fire underwater
if (m_pPlayer->pev->waterlevel == 3)
{
PlayEmptySound( );
m_flNextPrimaryAttack = GetNextAttackDelay(0.15);
return;
}
if (m_iClip <= 0)
{
Reload( );
if (m_iClip == 0)
PlayEmptySound( );
return;
}
m_pPlayer->m_iWeaponVolume = LOUD_GUN_VOLUME;
m_pPlayer->m_iWeaponFlash = NORMAL_GUN_FLASH;
m_iClip--;
int flags;
#if defined( CLIENT_WEAPONS )
flags = FEV_NOTHOST;
#else
flags = 0;
#endif
m_pPlayer->pev->effects = (int)(m_pPlayer->pev->effects) | EF_MUZZLEFLASH;
// player "shoot" animation
m_pPlayer->SetAnimation( PLAYER_ATTACK1 );
Vector vecSrc = m_pPlayer->GetGunPosition( );
Vector vecAiming = m_pPlayer->GetAutoaimVector( AUTOAIM_5DEGREES );
Vector vecDir;
#ifdef CLIENT_DLL
if ( bIsMultiplayer() )
#else
if ( g_pGameRules->IsMultiplayer() )
#endif
{
vecDir = m_pPlayer->FireBulletsPlayer( 4, vecSrc, vecAiming, VECTOR_CONE_DM_SHOTGUN, 2048, BULLET_PLAYER_BUCKSHOT, 0, 0, m_pPlayer->pev, m_pPlayer->random_seed );
}
else
{
// regular old, untouched spread.
vecDir = m_pPlayer->FireBulletsPlayer( 6, vecSrc, vecAiming, VECTOR_CONE_10DEGREES, 2048, BULLET_PLAYER_BUCKSHOT, 0, 0, m_pPlayer->pev, m_pPlayer->random_seed );
}
PLAYBACK_EVENT_FULL( flags, m_pPlayer->edict(), m_usSingleFire, 0.0, (float *)&g_vecZero, (float *)&g_vecZero, vecDir.x, vecDir.y, 0, 0, 0, 0 );
if (!m_iClip && m_pPlayer->m_rgAmmo[m_iPrimaryAmmoType] <= 0)
// HEV suit - indicate out of ammo condition
m_pPlayer->SetSuitUpdate("!HEV_AMO0", FALSE, 0);
m_flNextPrimaryAttack = GetNextAttackDelay(0.25);
m_flNextSecondaryAttack = UTIL_WeaponTimeBase() + 0.25;
if (m_iClip != 0)
m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 5.0;
else
m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 0.75;
m_fInSpecialReload = 0;
}
void CUsas::Reload( void )
{
if ( m_pPlayer->ammo_buckshot <= 0 )
return;
DefaultReload( USAS_MAX_CLIP, USAS_RELOAD, 1.5 );
}
void CUsas::WeaponIdle( void )
{
ResetEmptySound( );
m_pPlayer->GetAutoaimVector( AUTOAIM_5DEGREES );
if ( m_flTimeWeaponIdle > UTIL_WeaponTimeBase() )
return;
if ( m_pPlayer->pev->button & IN_IRONSIGHT )
return;
int iAnim;
switch ( RANDOM_LONG( 0, 1 ) )
{
case 0:
iAnim = USAS_LONGIDLE;
break;
default:
case 1:
iAnim = USAS_IDLE1;
break;
}
SendWeaponAnim( iAnim );
m_flTimeWeaponIdle = UTIL_SharedRandomFloat( m_pPlayer->random_seed, 10, 15 ); // how long till we do this again.
}
void CUsas::ProvideDualItem(CBasePlayer *pPlayer, const char *item) {
if (item == NULL) {
return;
}
#ifndef CLIENT_DLL
if (!stricmp(item, "weapon_usas")) {
if (!pPlayer->HasNamedPlayerItem("weapon_dual_usas")) {
pPlayer->GiveNamedItem("weapon_dual_usas");
ALERT(at_aiconsole, "Give weapon_dual_usas!\n");
}
}
#endif
}
void CUsas::SwapDualWeapon( void ) {
m_pPlayer->SelectItem("weapon_dual_usas");
}
| 23.093878
| 164
| 0.711205
|
solidi
|
8929b24024e725fe891a9dc1a28aa566604596e6
| 7,158
|
cpp
|
C++
|
3rdparty/nana/source/system/dataexch.cpp
|
Greentwip/windy
|
4eb8174f952c5b600ff004827a5c85dbfb013091
|
[
"MIT"
] | 1
|
2017-07-13T21:11:55.000Z
|
2017-07-13T21:11:55.000Z
|
3rdparty/nana/source/system/dataexch.cpp
|
Greentwip/Windy
|
4eb8174f952c5b600ff004827a5c85dbfb013091
|
[
"MIT"
] | null | null | null |
3rdparty/nana/source/system/dataexch.cpp
|
Greentwip/Windy
|
4eb8174f952c5b600ff004827a5c85dbfb013091
|
[
"MIT"
] | null | null | null |
/*
* Data Exchanger Implementation
* Copyright(C) 2003-2013 Jinhao(cnjinhao@hotmail.com)
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* @file: nana/system/dataexch.cpp
* @description: An implementation of a data exchange mechanism through Windows Clipboard, X11 Selection.
*/
#include <nana/system/dataexch.hpp>
#include <nana/traits.hpp>
#include <nana/paint/graphics.hpp>
#include <vector>
#include <cassert>
#if defined(NANA_WINDOWS)
#include <windows.h>
#elif defined(NANA_X11)
#include PLATFORM_SPEC_HPP
#include <nana/gui/detail/bedrock.hpp>
#include <nana/gui/detail/basic_window.hpp>
#endif
namespace nana{ namespace system{
//class dataexch
void dataexch::set(const nana::char_t* text)
{
_m_set(std::is_same<char, nana::char_t>::value ? format::text : format::unicode, text, (nana::strlen(text) + 1) * sizeof(nana::char_t));
}
void dataexch::set(const nana::string& text)
{
_m_set(std::is_same<char, nana::char_t>::value ? format::text : format::unicode, text.c_str(), (text.length() + 1) * sizeof(nana::char_t));
}
bool dataexch::set(const nana::paint::graphics& g)
{
#if defined(NANA_WINDOWS)
size sz = g.size();
paint::pixel_buffer pbuffer;
rectangle r;
r.x = 0;
r.y = 0;
r.width = sz.width;
r.height = sz.height;
pbuffer.attach(g.handle(), r);
size_t bytes_per_line = pbuffer.bytes_per_line();
size_t bitmap_bytes = bytes_per_line * r.height;
struct {
BITMAPINFOHEADER bmiHeader;
RGBQUAD bmiColors[256];
} bmi = {0};
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
HDC hDC = ::GetDC(NULL);
if (::GetDIBits(hDC, (HBITMAP)g.pixmap(), 0, 1, NULL, (BITMAPINFO *)&bmi, DIB_RGB_COLORS) == 0) {
assert(false);
::ReleaseDC(NULL, hDC);
return false;
}
if (!::ReleaseDC(NULL, hDC)) {
return false;
}
size_t header_size = sizeof(bmi.bmiHeader);
// Bitmaps are huge, so to avoid unnegligible extra copy, this routine does not use private _m_set method.
HGLOBAL h_gmem = ::GlobalAlloc(GHND | GMEM_SHARE, header_size + bitmap_bytes);
void * gmem = ::GlobalLock(h_gmem);
if (gmem) {
char* p = (char*)gmem;
// Fix BITMAPINFOHEADER obtained from GetDIBits WinAPI
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biHeight = ::abs(bmi.bmiHeader.biHeight);
memcpy(p, &bmi, header_size);
p += header_size;
// many programs do not support bottom-up DIB, so reversing row order is needed.
for (int y=0; y<bmi.bmiHeader.biHeight; ++y) {
memcpy(p, pbuffer.raw_ptr(bmi.bmiHeader.biHeight - 1 - y), bytes_per_line);
p += bytes_per_line;
}
if (::GlobalUnlock(h_gmem) || GetLastError() == NO_ERROR)
if (::OpenClipboard(::GetFocus()))
if (::EmptyClipboard())
if (::SetClipboardData(CF_DIB, h_gmem))
if (::CloseClipboard())
return true;
}
assert(false);
::GlobalFree(h_gmem);
return false;
//#elif defined(NANA_X11)
#else
throw "not implemented yet.";
return false;
#endif
}
void dataexch::get(nana::string& str)
{
std::size_t size;
void* res = _m_get(std::is_same<char, nana::char_t>::value ? format::text : format::unicode, size);
if(res)
{
#if defined(NANA_X11) && defined(NANA_UNICODE)
nana::detail::charset_conv conv("UTF-32", "UTF-8");
const std::string & utf32str = conv.charset(reinterpret_cast<char*>(res), size);
const nana::char_t * utf32ptr = reinterpret_cast<const nana::char_t*>(utf32str.c_str());
str.append(utf32ptr + 1, utf32ptr + utf32str.size() / sizeof(nana::char_t));
#else
str.reserve(size / sizeof(nana::char_t));
str.append(reinterpret_cast<nana::char_t*>(res), reinterpret_cast<nana::char_t*>(res) + size / sizeof(nana::char_t));
nana::string::size_type pos = str.find_last_not_of(nana::char_t(0));
if(pos != str.npos)
str.erase(pos + 1);
#endif
#if defined(NANA_X11)
::XFree(res);
#endif
}
}
//private:
bool dataexch::_m_set(unsigned type, const void* buf, std::size_t size)
{
bool res = false;
#if defined(NANA_WINDOWS)
if(type < format::end && ::OpenClipboard(::GetFocus()))
{
if(::EmptyClipboard())
{
HGLOBAL g = ::GlobalAlloc(GHND | GMEM_SHARE, size);
void * addr = ::GlobalLock(g);
memcpy(addr, buf, size);
::GlobalUnlock(g);
switch(type)
{
case format::text: type = CF_TEXT; break;
case format::unicode: type = CF_UNICODETEXT; break;
case format::pixmap: type = CF_BITMAP; break;
}
HANDLE h = ::SetClipboardData(type, g);
res = (h != NULL);
}
::CloseClipboard();
}
#elif defined(NANA_X11)
auto & spec = ::nana::detail::platform_spec::instance();
native_window_type owner = nullptr;
{
internal_scope_guard lock;
auto wd = detail::bedrock::instance().focus();
if(wd) owner = wd->root;
}
if(owner)
{
Atom atom_type;
switch(type)
{
case format::text: atom_type = XA_STRING; break;
case format::unicode: atom_type = spec.atombase().utf8_string; break;
default:
return false;
}
#if defined(NANA_UNICODE)
//The internal clipboard stores UTF8_STRING, the parameter string should be converted from utf32 to utf8.
nana::detail::charset_conv conv("UTF-8", "UTF-32");
std::string utf8str = conv.charset(reinterpret_cast<const char*>(buf), size);
buf = utf8str.c_str();
size = utf8str.size();
#endif
spec.write_selection(owner, atom_type, buf, size);
return true;
}
#endif
return res;
}
void* dataexch::_m_get(unsigned type, size_t& size)
{
void* res = 0;
#if defined(NANA_WINDOWS)
if(type < format::end && ::OpenClipboard(::GetFocus()))
{
switch(type)
{
case format::text: type = CF_TEXT; break;
case format::unicode: type = CF_UNICODETEXT; break;
case format::pixmap: type = CF_BITMAP; break;
}
HANDLE handle = ::GetClipboardData(type);
if(handle)
{
res = reinterpret_cast<HGLOBAL>(::GlobalLock(handle));
if(res)
size = ::GlobalSize(handle);
}
::CloseClipboard();
}
#elif defined(NANA_X11)
nana::detail::platform_spec & spec = nana::detail::platform_spec::instance();
native_window_type requester = nullptr;
spec.lock_xlib();
{
internal_scope_guard isg;
detail::bedrock::core_window_t * wd = detail::bedrock::instance().focus();
if(wd) requester = wd->root;
}
spec.unlock_xlib();
if(requester)
{
Atom atom;
switch(type)
{
case format::text: atom = XA_STRING; break;
case format::unicode: atom = spec.atombase().utf8_string; break;
default:
return 0;
}
res = spec.request_selection(requester, atom, size);
}
#endif
return res;
}
//end class dataexch
}//end namespace system
}//end namespace nana
| 29.578512
| 142
| 0.627969
|
Greentwip
|
8931bfc0d91a750dc6fcb607316655ab207cc0c3
| 4,497
|
cpp
|
C++
|
assignments/a6-transform/unique.cpp
|
dndinh7/animation-toolkit
|
906b003166f5ea588333e8681448afaf33cb30b3
|
[
"MIT"
] | null | null | null |
assignments/a6-transform/unique.cpp
|
dndinh7/animation-toolkit
|
906b003166f5ea588333e8681448afaf33cb30b3
|
[
"MIT"
] | null | null | null |
assignments/a6-transform/unique.cpp
|
dndinh7/animation-toolkit
|
906b003166f5ea588333e8681448afaf33cb30b3
|
[
"MIT"
] | null | null | null |
#include "atkui/framework.h"
#include "atk/toolkit.h"
#include <deque>
using namespace atk;
using glm::vec3;
class Steve : public atkui::Framework {
public:
Steve() : atkui::Framework(atkui::Perspective) {
background(vec3(0));
cameraPos = vec3(-500, 500, -500);
setCameraEnabled(false);
}
virtual ~Steve() {}
virtual void setup() {
lookAt(cameraPos, vec3(0));
Joint* root = new Joint("Hip");
root->setLocalTranslation(vec3(0, 170.0f, 0));
_steve.addJoint(root);
Joint* neck = new Joint("Neck");
neck->setLocalTranslation(vec3(0, 120.0f, 0));
_steve.addJoint(neck, root);
Joint* head = new Joint("Head");
head->setLocalTranslation(vec3(40.0f*cos(0), 30.0f, 40.0f * sin(0)));
_steve.addJoint(head, neck);
Joint* lLeg = new Joint("LeftLeg");
lLeg->setLocalTranslation(vec3(20.0f, -20.0f, 0));
_steve.addJoint(lLeg, root);
Joint* rLeg = new Joint("RightLeg");
rLeg->setLocalTranslation(vec3(-20.0f, -20.0f, 0));
_steve.addJoint(rLeg, root);
Joint* lFoot = new Joint("LeftFoot");
lFoot->setLocalTranslation(vec3(0, -140.0f, 0));
_steve.addJoint(lFoot, lLeg);
Joint* rFoot = new Joint("RightFoot");
rFoot->setLocalTranslation(vec3(0, -140.0f, 0));
_steve.addJoint(rFoot, rLeg);
Joint* lShoulder = new Joint("LeftShoulder");
lShoulder->setLocalTranslation(vec3(40.0f, 0, 0));
_steve.addJoint(lShoulder, neck);
Joint* rShoulder = new Joint("RightShoulder");
rShoulder->setLocalTranslation(vec3(-40.0f, 0, 0));
_steve.addJoint(rShoulder, neck);
Joint* lArm = new Joint("LeftArm");
lArm->setLocalTranslation(vec3(20.0f, -120.0f, 0));
_steve.addJoint(lArm, lShoulder);
Joint* rArm = new Joint("RightArm");
rArm->setLocalTranslation(vec3(-20.0f, -120.0f, 0));
_steve.addJoint(rArm, rShoulder);
_steve.fk();
}
virtual void scene()
{
setColor(vec3(52.0f/255.0f, 140.0f/255.0f, 49.0f/255.0f));
drawCube(vec3(0), vec3(5000.0f, 0.1f, 5000.0f));
setColor(vec3(1, 215.0f/255.0f, 0));
drawCube(vec3(0), vec3(300.0f, 0.2f, 5000.0f));
setColor(vec3(1));
float theta = 0.45f * sin(3.0f*elapsedTime());
float theta2 = -0.45f * sin(3.0f*elapsedTime());
_steve.getByName("Hip")->setLocalTranslation(_steve.getByName("Hip")->getLocalTranslation() + vec3(0, 0, -25.0f * dt()));
_steve.getByName("Hip")->setLocalRotation(glm::angleAxis(0.60f * sin(3.0f * elapsedTime()), vec3(1, 0, 0)));
_steve.getByName("LeftLeg")->setLocalRotation(glm::angleAxis(0.60f * sin(3.0f * elapsedTime()), vec3(1, 0, 0)));
_steve.getByName("RightLeg")->setLocalRotation(glm::angleAxis(theta2, vec3(1, 0, 0)));
_steve.getByName("LeftShoulder")->setLocalRotation(glm::angleAxis(theta2, vec3(1, 0, 1)));
_steve.getByName("RightShoulder")->setLocalRotation(glm::angleAxis(theta, vec3(1, 0, 1)));
_steve.getByName("Head")->setLocalTranslation(vec3(40.0f * cos(5.0f*elapsedTime()), 30.0f, 40.0f * sin(5.0f*elapsedTime())));
_steve.fk();
for (int i = 0; i < _steve.getNumJoints(); i++) {
Joint* cur_joint = _steve.getByID(i);
if (cur_joint == _steve.getRoot()) {
continue;
}
Joint* parent = cur_joint->getParent();
vec3 globalParentPos = parent->getGlobalTranslation();
vec3 globalPos = cur_joint->getGlobalTranslation();
setColor(vec3(0, 1, 1));
drawEllipsoid(globalParentPos, globalPos, 12.5f);
}
setColor(vec3(1, 1, 0));
drawSphere(_steve.getByName("Head")->getGlobalTranslation(), 50.0f);
setColor(vec3(106.0f / 255.0f, 13.0f / 255.0f, 173.0f / 255.0f));
drawSphere(_steve.getByName("LeftArm")->getGlobalTranslation(), 25.0f);
drawSphere(_steve.getByName("RightArm")->getGlobalTranslation(), 25.0f);
drawSphere(_steve.getByName("LeftFoot")->getGlobalTranslation(), 25.0f);
drawSphere(_steve.getByName("RightFoot")->getGlobalTranslation(), 25.0f);
cameraPos += vec3(0, 0, -22.5f * dt());
lookAt(cameraPos, vec3(0));
}
protected:
Skeleton _steve;
vec3 cameraPos;
};
int main(int argc, char** argv)
{
Steve viewer;
viewer.run();
}
| 34.068182
| 133
| 0.596842
|
dndinh7
|
89325d137a9c5992cf978546431202f269055988
| 9,354
|
cpp
|
C++
|
data/918.cpp
|
TianyiChen/rdcpp-data
|
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
|
[
"MIT"
] | null | null | null |
data/918.cpp
|
TianyiChen/rdcpp-data
|
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
|
[
"MIT"
] | null | null | null |
data/918.cpp
|
TianyiChen/rdcpp-data
|
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
|
[
"MIT"
] | null | null | null |
int PL ,du ,lUu
, h2,
KjY1 ,ez
,Ilu ,l
,uVy8 ,
YaZ ,/*Bv*/ UkM
,
wGDvh, ho
,XNDO ,gb9nx
, HW,
f ,H,KHvs85Q ,
qvf , Pu ,
Vf85E, T ,//H
fjK,
kIb/*kl0*/ , TEE,s2 ,//
rqqN38
,HiA2
,
H4av , j,
Qy
,
/*Q8*/
Tal,bYpV
,
mfW /*Dk*/;void
f_f0
()
{
volatile int sS1s, //Z
Ajs
,lC//fco1
//0iGM
,C9I, /*N1*/bTl9a ; mfW=bTl9a +sS1s +Ajs +
lC +C9I; //
{{{{
{
{}} //YCvk
}{ if ( true)for//V
(int i=1; i<
1 ;++i/*jK*/){ }else return/*6*/ ;
}}if
(true )
{ {if
( true)
{
}else
if
(
true
){ int wArx
;volatile int OLeWL ;wArx =/*GWg*/OLeWL ;
}else{}
}
{{}}}
else//b
{ int djP;volatile int XNtr ,w ;
for (int i=1
;
i<
2;++i
)/*l*/djP=w+XNtr ; }
return ;for(int
i=1
;/*Q*/i< 3 ;++i )
for (int i=1 ;i<
4
;++i )
{ return ;{ {{
} for
(int i=1
/*wYRi*/ ;i< 5 ;++i
) {}
/*g*/} } }
{{
if
(true)
{ }
else { }};
}
}for (int i=1 ;
i<6 ;++i ) {volatile int e, P,
WNb2 ;PL = //qw
WNb2
+
e
+P//i
;//
{{ }{/*7*/{ { }} }}
}{{//h
;
for
(int i=1 ; i< 7;++i)
{/*c*//*J9Rk*/{ }if(
true ){ volatile int E5P ,
zO9;
du
= zO9+E5P
;}
else
return ; } return ;
{
{} } {
} } return
;}{
{ return
//R
;for (int i=1//wA
;
i<8;++i) {{}
for(int i=1
;
i<9 ;++i){
volatile int//PJCz
eIl
;lUu
= eIl
; } } ;{for(int i=1 ;
i<
10;++i)
return/*Y*//*p6Np*/ ;for
(int i=1;/*0*/i< 11 ;++i
)
{} }}for (int
i=1;
i< 12;++i)/*Z*/ for(int
/*q*/
i=1
;//F
i<13
/*tbpn*/;++i
){;
{}/*j5*/}
{
volatile int
bQNiFw , //R
zTc
, Be7 ;
h2 =
/*eDM*/Be7 +
bQNiFw+ zTc;if
(true )
{
}//w
else for
(int
i=1;i< 14 ;++i ){
}
for(int i=1
;
i<15 ;++i ) { }
}{{volatile int PucE ;
return
;KjY1
=PucE;}
; ;//uufc2
{
if(
true) {
}else/*6C*/ {}
}
{if //Bl
(true )
{ {for (int i=1; i<16;++i){}}}else return//V
;}}}
} { //OA
{ return ;
{ volatile int
ist ,x;
{
{{ }
} }if (
true)for(int i=1
;i< 17
;++i/*mu*/)ez=
x+ist;
else ; {
} }
{volatile int IkbrU , UXe, K7Sq
;
{ } {int yzl
;volatile int
zFj,xdetZ;//kZ5
for(int i=1 ; i<
18 ;++i/*0*/)
{ {}}yzl =
xdetZ
+zFj ;}
Ilu =
K7Sq//D
+
IkbrU+
UXe
;}}for (int
i=1 ; i< 19;++i
)
/*ng*/if(true
){{
{
/*dt*/{
} { } }{return
;} } { ;} {{
; }
if
(
true)//
{ //h47
{ /*Lr*/ }/*Z*/{if/*M*/ (
true
){
} else { }} } else{for (int i=1
; i< 20
;++i
)if ( true )for (int /*HsWf*/i=1 ;i</*dxa0*/
21
;++i
)
{}else{ }}/*he*///yD
} }else { {
;
}
for (int
i=1
/*gKd*/
; i<22 ;++i
) if (true
){
return ;/*x16R*/}/*Cz*/else{
int/*8*/ NTyGL0
; volatile int n9 ,lGmgo,
ysA ; NTyGL0 = ysA+//cZW
n9
+ lGmgo ;
; }}return
;}; return
;return ;} void//Zu
f_f1() { {//C3b
for(int
i=1;i<
23 ;++i){
{
int
ytA;volatile int
ADo6GK, kT3D;
ytA = kT3D+
ADo6GK
; if ( true){ {}
}else ;} {int
mQXIf;
volatile int tl
,//kv
T4D ;{ ;
}if (true
) { int enN ;
volatile int c /*xk*/
; if (//bQA
true )enN =
c ;
else{}
return ; }
else for(int i=1; i<24
;++i)mQXIf //5xw
//BN
//W0
=T4D
+tl;}}//
{/*dN*/{ volatile int xRFg,Bn
;/*b*/for (int /*D*///sUB
i=1 ; i<
25
;++i
)if(
true ){volatile int/**/ FJ ,
sb
//N
;
l=
sb+ FJ /*4*/;/*c*/return ;} /*u*/else ; if
(
true)return ; else uVy8
= Bn+xRFg; /*TDP4*/}{ for
(int i=1 ;
i<26;++i
){return ;//h
{}}}/*Qto*/ {
volatile int A
, vKEI ,
Hi, /*C*/hp4,
QQ ;if( true
) {int tDRkG
;volatile int
gZze ,HnH; //X9
if
(
true ) {} else for
(int i=1
; i< 27;++i //C
) tDRkG =
/*b*/ HnH//BQ
+gZze;
}
else
for(int i=1;i<
28;++i) return ; YaZ=QQ//omN
+ A + vKEI+ Hi +hp4;}}
{int rd0Vi
;
volatile int //e2M
I,//DwC8M
j29iq, lm4 , Jd ; for
(int
//a
i=1
;
i<
29;++i){ {
} }{
{
}
}rd0Vi /*t*/=
Jd+I+
j29iq
+lm4;
{
{{}}
{ ;} } } }{volatile int bjG ,Iw ,eG7 /*66K*/
,
kR
,aqj
, Gl, J, fCU5n
,
ATZ, BeUR;if/**/ (true) UkM=
BeUR+ //16v
bjG+Iw//ng
+
eG7 +kR; else{ int LB5
;
volatile int NF ,n4ej,
Y2i , OEl,//07H
F0 ;//L
LB5= /*9*/F0 +NF +n4ej+ Y2i
+
OEl ;{
{}
} return ; } if (true) { volatile int
QjRc,
BL
,IM
; wGDvh=/*6Z*/
IM
+ /*ri5*/QjRc+BL;
{ { return ;} } } else//n
for(int i=1
//dY6
;
i< 30;++i)return/*Hjl*//*7*/ ; { volatile int
oW5W ,e98 , V
, kd;
for(int i=1 ; i<
31
;++i) {int qJV/*s*/ ; volatile int GdnW ,
NR ,o3 ;qJV//r
= o3 +GdnW
+ NR;
for(int i=1 ;i<32 ;++i )
{return ;
{ }{} }{ {} }if/*dJGg*/(
true ){ {//Z
}} else{ ;}} {
volatile int
Zfg
,r
;if(
true //zM
) ho=
r /*OBx*/+ Zfg;
else
{;}}//i
{; { }} for(int i=1//B
;
i< 33 //Dca
;++i
) XNDO
=kd +oW5W/*sGIuV*/
+
e98+V
;} return
;gb9nx= aqj+
Gl+
J+
fCU5n
+ ATZ;/*s8S*/
}//Wml
;;
return //h
//DHq
;} void f_f2(){;/*hYP*/for
(int
i=1 ; i< 34 ;++i) {
{/*tuZ*/volatile int zclz , zjQ9
,MTs;//MNN
{ for (int i=1; i< 35
;++i) { }
}
/*tSM*/
{
{ {if
(//fwW1
true ) {}
else
{} }}}
HW = MTs
+//OKD
zclz+ zjQ9
; }
{ volatile int YRkK74,
Zv ,/*KOz*/Oa,vnax, og ,PJ8 ,
de,
L2;
for (int
i=1//WwA
;
i< 36/*P*/
;++i )f= L2+YRkK74 +
Zv +Oa//
;H = vnax
+ og
+
PJ8 +de ;}
//dOb
{
for(int i=1;i<37 ;++i)for (int i=1;i< 38
;++i) ;return ;
}{ for(int i=1 ;
i< 39
;++i
)
{
int GulC
;//3J
volatile int gCh, A5; GulC
=
A5+ gCh ; for (int i=1 ; i< 40 ;++i
) {/*ava*/{
//OpG
} { } }//F
{ return ; {}{
} } };
{ if(
true)
; else{
int PxN3O; volatile int
k
, Z6w
;{{}
{ }}PxN3O=Z6w + k;
for (int i=1; i<
41
;++i){
} }
//t
{{ } for (int i=1
; i<42
;++i ) {}
} }} }
{;//2jJ
{
volatile int Q,//mt6
Q5wxb,WR;KHvs85Q
= WR
+Q +Q5wxb
;{{{}}{
return ;
}
}return
;}
;
}
{
volatile int
U //3m
, r6
, Gm
,y
,bcml
,ABY/*LH*/
;{
/*b*/return ;{{/*WO*/}/*o*/}for(int i=1//Bnz
;
i</*4*/
43;++i ){volatile int
ed
,
lrf ,CD4YO//WwC
;{
} if ( true
)qvf
= CD4YO+
ed +lrf /*yp*/
;
else return ;}}
{ ; { {
{ {
for
(int i=1;i</*F*/44;++i
) for
(int i=1 ;i<
45
//Z
;++i ) if
(
true){
} else
{/*DJ9*/}
for(int i=1 ;i<46;++i )
return ;}
} }//4s4
}}{//V
return
; for(int i=1 ;
i<
47 ;++i) {for (int
i=1
;i< 48 //h
;++i) { ;}return ; }
} if (true
) {
return
; {{
/**/{ {{ }
} }
}
return ; {{}
} if( /**/true )if( true
){//d
if (true)
return ; else
{ } return ;}
else{ } //Cd
else
//1g
{
/*Dd*/} } }
else Pu =
ABY +
/*xK*//*BXx*/ U+r6
+Gm
+ y
+
bcml ; }{int g3q5W ;
volatile int
UE
,
wDMR, //aXA
Hq4ho
, Dj7Ll ,mXX,cG,
z , sh ,s3MLht,
/*jLag*/CFe,ROe , moUE;{ volatile int czs0
//Qw
,//gXc
TS,
iY1 ,I0e6;
/*6*/ {return
;{//PK
} /*Z1*/{{
; }
return ;
}}{
volatile int X2,UO
,//qIKQ
TBH,
O/*CRE5J*/;
Vf85E = /*x*/O+
X2
+UO
+TBH //
;
} /*b6*/{int
gH ;/**/ volatile int VUcX
, Wr4BB ; {//R
for(int /*y*/i=1 ;i<49;++i )
return ;} { /**/int B ;volatile int FaoFI , YT ;if
( true) for(int
i=1;i< 50;++i
) B
=
YT
+ FaoFI ;else
{{
}} }if(true)
gH = Wr4BB + VUcX;/*vnE*/
else for(int /*i3*/
i=1;i<
51/*s*/ ;++i) ; } /*U3*/T//b1
= I0e6+czs0 + TS
+//
//
iY1/*P*/; }
for(int
i=1
; i< 52;++i) if( true)return ; else
return ;if( true) {{
; return
;} {//Hg
{
}}} else{{{//xowR
return ; }}
if(true ) ;
else{{ volatile int xH3
,wFC;
fjK
= wFC+
xH3 ;;} {volatile int
//p
Kk,
MP; for(int i=1
; i<53;++i
)for(int i=1; i<
54;++i ) kIb //9x
= MP+
Kk ;} {
}}
return ;
{
{}}
}if
(true) TEE= moUE +
UE//y
+ wDMR +Hq4ho /*qBv*/+ Dj7Ll+ mXX+cG/*qF9*/;
//Ar
else
g3q5W= z
+ sh
+ s3MLht
+ CFe+ROe//nf
;
}
return ;}int main(){int JxhC
;//V7
volatile int In1Dv ,
Y546 ,
ZVW , g3uH /*oy8*/, Cr ,lj
//q
;
return 662632231;if( true)
JxhC
= lj
+In1Dv + Y546
+ ZVW+g3uH+Cr ; else{ int
nb/*mUOBV*/;volatile int
Hpk,/**/
mzIn,
Glx
,/*S*/dftb,GYn
,Or, dGv,
Pqr2l //x
, fW,
yYv,vK8I;/**/nb= vK8I
+
Hpk+
mzIn + Glx//eeA
+
dftb;{
int
MzB;volatile int nYtEF
,Aa8,DSHq,
O4fu;//
MzB=
//cE
O4fu
+
nYtEF+Aa8+
DSHq ;{;
{
}}{ {}
return/*2G*/ 1323723358
;
//8dMq
}
}
s2 =GYn+
Or+dGv+Pqr2l
+/*JlU*/
fW +
yYv;}{
return 2146463394; {if( true ) ; else
;{return 266339152 ; }
;{
{ volatile int
CZ
;
{}rqqN38/*WvZ*/= /*2Ao91*/CZ
; {
}
}}
}
if
(
true )
for(int i=1//S
;
i< 55;++i
) { int jYrv ;volatile int
TJ ,CcS
,
CN;jYrv=CN
+ TJ
+CcS//wE
;{
;
}/*4x*/
} else{volatile int
BH,//E
YLqFrR//0
,S ,qD5, Ovl; ;HiA2= Ovl
+BH+ YLqFrR+ S+ qD5 ; return/**/
1448105849; } {{ {} return 192569863; }
return 2145998470 //5QI
; }}
return
167674675
; { {{
return
491830048;
{
}} { return
990171621;for (int i=1 ;i<
56;++i ){
{volatile int
qjTl
;
H4av =
qjTl;} }}
{
for(int
i=1
;i< 57
;++i) ; } {volatile int
J2ji ,eRyE;j = eRyE+
//oO
J2ji;{}
}}if ( true
){
{for(int i=1 ;
i< 58;++i
)
; {
//vw
} } { int
xd
;
volatile int z477,u/*vgb*/,//
rW ;xd =rW
+ z477
+
u; }//3o
if( true)
; //g
else
return
699246214 ;
}else{ {int Tef ; volatile int/**/ C,LZ , lwec ; for(int i=1 ;
i<59 ;++i) Tef = lwec + C+
LZ;}//5dr
{
return
2142480702;}
}{volatile int C1,m8kp ,L8//K
,R ;
{ volatile int NeNjA,
G
,DKfQY , dYtQ; //
for(int
i=1 ;
i<
60;++i
) {volatile int
VbZ;
Qy /**/=VbZ;}Tal //ER
=
dYtQ
+ NeNjA
+
G +DKfQY;}bYpV = /*0*/
R//GCD
+C1+
m8kp +L8;
{
{{{ }{} }} }{ int Pv;volatile int //l
D6
,
CsZ ,
ko7
;for
(int
i=1 ; /*V5*/
i<61 /*r*/;++i) {}{
{{
{
}} { }}{ /*o*/} }Pv=ko7+D6+
CsZ;} //
}
} //BS9
}
| 10.222951
| 65
| 0.455634
|
TianyiChen
|
89330ec7af9f1a8ee0171f1058a3c7aa4bb9bbc8
| 6,949
|
cpp
|
C++
|
src/lib/rtm/LocalServiceAdmin.cpp
|
r-kurose/OpenRTM-aist
|
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
|
[
"RSA-MD"
] | 15
|
2019-01-08T15:34:04.000Z
|
2022-03-01T08:36:17.000Z
|
src/lib/rtm/LocalServiceAdmin.cpp
|
r-kurose/OpenRTM-aist
|
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
|
[
"RSA-MD"
] | 448
|
2018-12-27T03:13:56.000Z
|
2022-03-24T09:57:03.000Z
|
src/lib/rtm/LocalServiceAdmin.cpp
|
r-kurose/OpenRTM-aist
|
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
|
[
"RSA-MD"
] | 31
|
2018-12-26T04:34:22.000Z
|
2021-11-25T04:39:51.000Z
|
// -*- C++ -*-
/*!
* @file LocalServiceAdmin.cpp
* @brief SDO service administration class
* @date $Date$
* @author Noriaki Ando <n-ando@aist.go.jp>
*
* Copyright (C) 2011
* Noriaki Ando
* Intelligent Systems Research Institute,
* National Institute of
* Advanced Industrial Science and Technology (AIST), Japan
* All rights reserved.
*
* $Id: SdoConfiguration.cpp 1971 2010-06-03 08:46:40Z n-ando $
*
*/
#include <coil/UUID.h>
#include <mutex>
#include <coil/stringutil.h>
#include <rtm/RTObject.h>
#include <rtm/CORBA_SeqUtil.h>
#include <rtm/LocalServiceAdmin.h>
#include <rtm/LocalServiceBase.h>
#include <cstring>
#include <algorithm>
#include <memory>
#include <vector>
namespace RTM
{
/*!
* @if jp
* @brief コンストラクタ
* @else
* @brief Constructor
* @endif
*/
LocalServiceAdmin::LocalServiceAdmin()
: rtclog("LocalServiceAdmin")
{
RTC_TRACE(("LocalServiceAdmin::LocalServiceAdmin()"));
}
/*!
* @if jp
* @brief 仮想デストラクタ
* @else
* @brief Virtual destractor
* @endif
*/
LocalServiceAdmin::~LocalServiceAdmin()
{
finalize();
}
/*!
* @if jp
* @brief "all" 文字列探索Functor
* @else
* @brief A functor to search "all"
* @endif
*/
struct find_all
{
bool operator()(const std::string& str)
{
return coil::normalize(str) == "all";
}
};
/*!
* @if jp
*
* @brief LocaServiceAdminの初期化
* @else
* @brief Initialization of LocalServiceAdmin
* @endif
*/
void LocalServiceAdmin::init(coil::Properties& props)
{
RTC_TRACE(("LocalServiceAdmin::init():"));
RTC_DEBUG_STR((props));
coil::vstring svcs(coil::split(props["enabled_services"], ","));
bool all_enable(false);
if (std::find_if(svcs.begin(), svcs.end(), find_all()) != svcs.end())
{
RTC_INFO(("All the local services are enabled."));
all_enable = true;
}
RTM::LocalServiceFactory& factory(RTM::LocalServiceFactory::instance());
coil::vstring ids = factory.getIdentifiers();
RTC_DEBUG(("Available services: %s", coil::flatten(ids).c_str()));
for (auto & id : ids)
{
if (all_enable || isEnabled(id, svcs))
{
if (notExisting(id))
{
LocalServiceBase* service(factory.createObject(id));
RTC_DEBUG(("Service created: %s", id.c_str()));
coil::Properties& prop(props.getNode(id));
service->init(prop);
addLocalService(service);
}
}
}
}
/*!
* @if jp
* @brief LocalserviceAdmin の終了処理
* @else
* @brief Finalization ofLocalServiceAdmin
* @endif
*/
void LocalServiceAdmin::finalize()
{
RTM::LocalServiceFactory& factory(RTM::LocalServiceFactory::instance());
for (auto & service : m_services)
{
service->finalize();
factory.deleteObject(service);
}
m_services.clear();
}
/*!
* @if jp
* @brief LocalServiceProfileListの取得
* @else
* @brief Getting LocalServiceProfileList
* @endif
*/
RTM::LocalServiceProfileList LocalServiceAdmin::getServiceProfiles()
{
RTM::LocalServiceProfileList profs(0);
for (auto & service : m_services)
{
profs.emplace_back(service->getProfile());
}
return profs;
}
/*!
* @if jp
* @brief LocalServiceProfile を取得する
* @else
* @brief Get LocalServiceProfile of an LocalService
* @endif
*/
bool
LocalServiceAdmin::getServiceProfile(const std::string& name,
::RTM::LocalServiceProfile& prof)
{
std::lock_guard<std::mutex> guard(m_services_mutex);
for (auto & service : m_services)
{
if (name == service->getProfile().name)
{
prof = service->getProfile();
return true;
}
}
return false;
}
/*!
* @if jp
* @brief LocalService の Service を取得する
* @else
* @brief Get a pointer of a LocalService
* @endif
*/
RTM::LocalServiceBase* LocalServiceAdmin::getService(const char* id)
{
for (auto & service : m_services)
{
if (service->getProfile().name == id)
{
return service;
}
}
return nullptr;
}
/*!
* @if jp
* @brief SDO service provider をセットする
* @else
* @brief Set a SDO service provider
* @endif
*/
bool
LocalServiceAdmin::addLocalService(::RTM::LocalServiceBase* service)
{
if (service == nullptr)
{
RTC_ERROR(("Invalid argument: addLocalService(service == NULL)"));
return false;
}
RTC_TRACE(("LocalServiceAdmin::addLocalService(%s)",
service->getProfile().name.c_str()));
std::lock_guard<std::mutex> guard(m_services_mutex);
m_services.emplace_back(service);
return true;
}
/*!
* @if jp
* @brief LocalService を削除する
* @else
* @brief Remove a LocalService
* @endif
*/
bool LocalServiceAdmin::removeLocalService(const std::string& name)
{
RTC_TRACE(("removeLocalService(%s)", name.c_str()));
std::lock_guard<std::mutex> guard(m_services_mutex);
std::vector<LocalServiceBase*>::iterator it = m_services.begin();
std::vector<LocalServiceBase*>::iterator it_end = m_services.end();
while (it != it_end)
{
if (name == (*it)->getProfile().name)
{
(*it)->finalize();
LocalServiceFactory&
factory(LocalServiceFactory::instance());
factory.deleteObject(*it);
m_services.erase(it);
RTC_INFO(("SDO service has been deleted: %s", name.c_str()));
return true;
}
++it;
}
RTC_WARN(("Specified SDO service not found: %s", name.c_str()));
return false;
}
//============================================================
// private functions
/*!
* @if jp
* @brief 指定されたIDが有効かどうかチェックする
* @else
* @brief Check if specified ID is enabled
* @endif
*/
bool LocalServiceAdmin::isEnabled(const std::string& id,
const coil::vstring& enabled)
{
bool ret = std::find(enabled.begin(), enabled.end(), id) != enabled.end();
RTC_DEBUG(("Local service %s %s enabled.", id.c_str(),
ret ? "is" : "is not"));
return ret;
}
/*!
* @if jp
* @brief 指定されたIDがすでに存在するかどうかチェックする
* @else
* @brief Check if specified ID is existing
* @endif
*/
bool LocalServiceAdmin::notExisting(const std::string& id)
{
std::lock_guard<std::mutex> guard(m_services_mutex);
for (auto & service : m_services)
{
if (service->getProfile().name == id)
{
RTC_WARN(("Local service %s already exists.", id.c_str()));
return false;
}
}
RTC_DEBUG(("Local service %s does not exist.", id.c_str()));
return true;
}
} // namespace RTM
| 24.044983
| 78
| 0.576054
|
r-kurose
|
8934bc258baa69177a04743b44509d032f0d45cc
| 4,992
|
cpp
|
C++
|
benchmark/runtime/integer/single.cpp
|
danra/scnlib
|
815782badc1b548c21bb151372497e1516bee806
|
[
"Apache-2.0"
] | 556
|
2018-11-17T01:49:32.000Z
|
2022-03-25T09:35:10.000Z
|
benchmark/runtime/integer/single.cpp
|
danra/scnlib
|
815782badc1b548c21bb151372497e1516bee806
|
[
"Apache-2.0"
] | 51
|
2019-05-09T14:36:53.000Z
|
2022-03-19T12:47:12.000Z
|
benchmark/runtime/integer/single.cpp
|
danra/scnlib
|
815782badc1b548c21bb151372497e1516bee806
|
[
"Apache-2.0"
] | 21
|
2019-02-11T19:56:30.000Z
|
2022-03-28T02:52:27.000Z
|
// Copyright 2017 Elias Kosunen
//
// 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
//
// https://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.
//
// This file is a part of scnlib:
// https://github.com/eliaskosunen/scnlib
#include "bench_int.h"
template <typename Int>
static void scan_int_single_scn(benchmark::State& state)
{
auto source = stringified_integers_list<Int>();
auto it = source.begin();
Int i;
for (auto _ : state) {
if (it == source.end()) {
it = source.begin();
}
auto result = scn::scan(*it, "{}", i);
if (!result) {
state.SkipWithError("Benchmark errored");
break;
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * sizeof(Int)));
}
BENCHMARK_TEMPLATE(scan_int_single_scn, int);
BENCHMARK_TEMPLATE(scan_int_single_scn, long long);
BENCHMARK_TEMPLATE(scan_int_single_scn, unsigned);
template <typename Int>
static void scan_int_single_scn_default(benchmark::State& state)
{
auto source = stringified_integers_list<Int>();
auto it = source.begin();
Int i;
for (auto _ : state) {
if (it == source.end()) {
it = source.begin();
}
auto result = scn::scan_default(*it, i);
if (!result) {
state.SkipWithError("Benchmark errored");
break;
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * sizeof(Int)));
}
BENCHMARK_TEMPLATE(scan_int_single_scn_default, int);
BENCHMARK_TEMPLATE(scan_int_single_scn_default, long long);
BENCHMARK_TEMPLATE(scan_int_single_scn_default, unsigned);
template <typename Int>
static void scan_int_single_scn_value(benchmark::State& state)
{
auto source = stringified_integers_list<Int>();
auto it = source.begin();
for (auto _ : state) {
if (it == source.end()) {
it = source.begin();
}
auto result = scn::scan_value<Int>(*it);
if (!result) {
state.SkipWithError("Benchmark errored");
break;
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * sizeof(Int)));
}
BENCHMARK_TEMPLATE(scan_int_single_scn_value, int);
BENCHMARK_TEMPLATE(scan_int_single_scn_value, long long);
BENCHMARK_TEMPLATE(scan_int_single_scn_value, unsigned);
template <typename Int>
static void scan_int_single_scn_parse(benchmark::State& state)
{
auto source = stringified_integers_list<Int>();
auto it = source.begin();
Int i{};
for (auto _ : state) {
if (it == source.end()) {
it = source.begin();
}
auto result = scn::parse_integer<Int>(
scn::string_view{it->data(), it->size()}, i);
if (!result) {
state.SkipWithError("Benchmark errored");
break;
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * sizeof(Int)));
}
BENCHMARK_TEMPLATE(scan_int_single_scn_parse, int);
BENCHMARK_TEMPLATE(scan_int_single_scn_parse, long long);
BENCHMARK_TEMPLATE(scan_int_single_scn_parse, unsigned);
template <typename Int>
static void scan_int_single_sstream(benchmark::State& state)
{
auto source = stringified_integers_list<Int>();
auto it = source.begin();
Int i;
for (auto _ : state) {
if (it == source.end()) {
it = source.begin();
}
std::istringstream iss{*it};
iss >> i;
if (iss.fail()) {
state.SkipWithError("Benchmark errored");
break;
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * sizeof(Int)));
}
BENCHMARK_TEMPLATE(scan_int_single_sstream, int);
BENCHMARK_TEMPLATE(scan_int_single_sstream, long long);
BENCHMARK_TEMPLATE(scan_int_single_sstream, unsigned);
template <typename Int>
static void scan_int_single_scanf(benchmark::State& state)
{
auto source = stringified_integers_list<Int>();
auto it = source.begin();
Int i;
for (auto _ : state) {
if (it == source.end()) {
it = source.begin();
}
auto ret = scanf_integral(it->c_str(), i);
if (ret != 1) {
state.SkipWithError("Benchmark errored");
break;
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * sizeof(Int)));
}
BENCHMARK_TEMPLATE(scan_int_single_scanf, int);
BENCHMARK_TEMPLATE(scan_int_single_scanf, long long);
BENCHMARK_TEMPLATE(scan_int_single_scanf, unsigned);
| 29.538462
| 75
| 0.648037
|
danra
|
8938915a32c234de257ac62cb73ae6bdf20cf121
| 6,216
|
cc
|
C++
|
plugins/taglib/TagParser.cc
|
bsdelf/mous
|
eb59b625d0ba8236f3597ae6015d9215cef922cf
|
[
"BSD-2-Clause"
] | 75
|
2015-04-26T11:22:07.000Z
|
2022-02-12T17:18:37.000Z
|
plugins/taglib/TagParser.cc
|
bsdelf/mous
|
eb59b625d0ba8236f3597ae6015d9215cef922cf
|
[
"BSD-2-Clause"
] | 7
|
2016-05-31T21:56:01.000Z
|
2019-09-15T06:25:28.000Z
|
plugins/taglib/TagParser.cc
|
bsdelf/mous
|
eb59b625d0ba8236f3597ae6015d9215cef922cf
|
[
"BSD-2-Clause"
] | 19
|
2015-09-23T01:50:15.000Z
|
2022-02-12T17:18:41.000Z
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <vector>
#include <map>
#include <taglib/mpegfile.h>
#include <taglib/fileref.h>
#include <taglib/tag.h>
#include <taglib/audioproperties.h>
using namespace TagLib;
#include <scx/Conv.h>
#include <scx/FileHelper.h>
#include <scx/IconvHelper.h>
using namespace scx;
#include <plugin/TagParserProto.h>
using namespace mous;
#include "CoverArt.h"
namespace TagLib {
namespace ID3v2{
class Tag;
}
}
namespace {
struct Self {
std::string file_name;
FileRef* file_ref = nullptr;
Tag* tag = nullptr;
AudioProperties* props = nullptr;
std::map<std::string, CoverFormat(*)(const string&, char**, uint32_t*)> dump_funcs;
std::map<std::string, bool(*)(const string&, CoverFormat, const char*, size_t)> store_funcs;
std::string title;
std::string artist;
std::string album;
std::string comment;
std::string genre;
};
}
static string StringTostd_string(const String& str) {
if (str.isLatin1()) {
return str.to8Bit();
}
string std_str;
const ByteVector& v = str.data(String::UTF16BE);
if (IconvHelper::ConvFromTo("UTF-16BE", "UTF-8", v.data(), v.size(), std_str)) {
return std_str;
} else {
return str.to8Bit();
}
}
static void* Create() {
auto self = new Self();
self->dump_funcs = {
{ "mp3", DumpMp3Cover },
{ "m4a", DumpMp4Cover}
};
self->store_funcs = {
{ "mp3", StoreMp3Cover },
{ "m4a", StoreMp4Cover }
};
return self;
}
static void Destroy(void* ptr) {
Close(ptr);
delete SELF;
}
static ErrorCode Open(void* ptr, const char* path) {
SELF->file_name = path;
SELF->file_ref = new FileRef(path, true);//AudioProperties::);
if (!SELF->file_ref->isNull() && SELF->file_ref->tag()) {
SELF->tag = SELF->file_ref->tag();
SELF->props = SELF->file_ref->audioProperties();
}
return ErrorCode::Ok;
}
static void Close(void* ptr) {
if (SELF->file_ref) {
delete SELF->file_ref;
SELF->file_ref = nullptr;
SELF->tag = nullptr;
SELF->props = nullptr;
}
SELF->file_name.clear();
}
static bool HasTag(void* ptr) {
return SELF->tag;
}
static const char* GetTitle(void* ptr) {
if (!SELF->tag) {
return nullptr;
}
SELF->title = StringTostd_string(SELF->tag->title());
return SELF->title.c_str();
}
static const char* GetArtist(void* ptr)
{
if (!SELF->tag) {
return nullptr;
}
SELF->artist = StringTostd_string(SELF->tag->artist());
return SELF->artist.c_str();
}
static const char* GetAlbum(void* ptr)
{
if (!SELF->tag) {
return nullptr;
}
SELF->album = StringTostd_string(SELF->tag->album());
return SELF->album.c_str();
}
static const char* GetComment(void* ptr) {
if (!SELF->tag) {
return nullptr;
}
SELF->comment = StringTostd_string(SELF->tag->comment());
return SELF->comment.c_str();
}
static const char* GetGenre(void* ptr) {
if (!SELF->tag) {
return nullptr;
}
SELF->genre = StringTostd_string(SELF->tag->genre());
return SELF->genre.c_str();
}
static int32_t GetYear(void* ptr)
{
if (!SELF->tag) {
return -1;
}
return SELF->tag->year();
}
static int32_t GetTrack(void* ptr)
{
if (!SELF->tag) {
return -1;
}
return SELF->tag->track();
}
static bool HasAudioProperties(void* ptr)
{
return SELF->props;
}
static int32_t GetDuration(void* ptr)
{
if (!SELF->props) {
return 0;
}
return SELF->props->length()*1000;
}
static int32_t GetBitRate(void* ptr)
{
if (!SELF->props) {
return 0;
}
return SELF->props->bitrate();
}
static bool CanEdit(void* ptr) {
return true;
}
static bool Save(void* ptr)
{
const string& ext = ToLower(FileHelper::FileSuffix(SELF->file_name));
if (ext == "mp3") {
auto ref = dynamic_cast<TagLib::MPEG::File*>(SELF->file_ref->file());
if (!ref) {
printf("[taglib] bad type\n");
return false;
}
return ref->save(TagLib::MPEG::File::TagTypes::ID3v2, true, 3, true);
} else {
return SELF->file_ref ? SELF->file_ref->save() : false;
}
}
static void SetTitle(void* ptr, const char* title)
{
if (SELF->tag) {
SELF->tag->setTitle(title);
}
}
static void SetArtist(void* ptr, const char* artist)
{
if (SELF->tag) {
SELF->tag->setArtist(artist);
}
}
static void SetAlbum(void* ptr, const char* album)
{
if (SELF->tag) {
SELF->tag->setAlbum(album);
}
}
static void SetComment(void* ptr, const char* comment)
{
if (SELF->tag) {
SELF->tag->setComment(comment);
}
}
static void SetGenre(void* ptr, const char* genre)
{
if (SELF->tag) {
SELF->tag->setGenre(genre);
}
}
static void SetYear(void* ptr, int32_t year)
{
if (SELF->tag) {
SELF->tag->setYear(year);
}
}
static void SetTrack(void* ptr, int32_t track)
{
if (SELF->tag) {
SELF->tag->setTrack(track);
}
}
static CoverFormat DumpCoverArt(void* ptr, char** out, uint32_t* length)
{
if (SELF->file_name.empty()) {
return CoverFormat::None;
}
const string& ext = ToLower(FileHelper::FileSuffix(SELF->file_name));
if (SELF->dump_funcs.find(ext) != SELF->dump_funcs.end()) {
return SELF->dump_funcs[ext](SELF->file_name, out, length);
} else {
return CoverFormat::None;
}
}
static bool StoreCoverArt(void* ptr, CoverFormat fmt, const char* data, size_t length)
{
if (SELF->file_name.empty()) {
return false;
}
const string& ext = ToLower(FileHelper::FileSuffix(SELF->file_name));
if (SELF->store_funcs.find(ext) != SELF->store_funcs.end()) {
return SELF->store_funcs[ext](SELF->file_name, fmt, data, length);
} else {
return false;
}
}
static const BaseOption** GetOptions(void* ptr) {
(void) ptr;
return nullptr;
}
static const char** GetSuffixes(void* ptr) {
static const char* suffixes[] { "*", nullptr };
return suffixes;
}
| 21.583333
| 100
| 0.598456
|
bsdelf
|
89395fc1e297359f3d2e6ca94098c6a453418625
| 932
|
cxx
|
C++
|
state/sw.cxx
|
kydos/dilib-demo
|
de5ded471adb7075d04450371d2e3a88bd57d5c7
|
[
"Apache-2.0"
] | null | null | null |
state/sw.cxx
|
kydos/dilib-demo
|
de5ded471adb7075d04450371d2e3a88bd57d5c7
|
[
"Apache-2.0"
] | null | null | null |
state/sw.cxx
|
kydos/dilib-demo
|
de5ded471adb7075d04450371d2e3a88bd57d5c7
|
[
"Apache-2.0"
] | null | null | null |
#include "util.hxx"
#include <dilib/state.hxx>
#include <random>
#include <chrono>
#include <thread>
int main(int argc, char *argv[]) {
if (argc > 2) {
std::string name = argv[1];
std::string did = argv[2];
std::cout << "StateWriter(" << name << ")" << std::endl;
dilib::StateWriter<dilib::demo::DevicePosition> sw(name);
std::default_random_engine generator;
std::uniform_int_distribution<float> distribution(0,100);
while (true) {
float lon = distribution(generator);
float lat = distribution(generator);
float lev = distribution(generator);
dilib::demo::DevicePosition sample(did, lon ,lat, lev);
sw.write(sample);
std::cout << "(" << did << ", " << lon << ", " << lat << ", " << lev << ")" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
} else {
std::cout << "USAGE:\n\tsw <name> <did>" << std::endl;
}
}
| 26.628571
| 95
| 0.590129
|
kydos
|
893b011b4350afabdf5f407733a8efb9e42337a7
| 4,191
|
cpp
|
C++
|
C++/Semester_2/class_4.cpp
|
Trilonka/MireaAl
|
2d68b6facbeb99cc4040ea206c64e95ea3c1bc92
|
[
"BSD-2-Clause"
] | null | null | null |
C++/Semester_2/class_4.cpp
|
Trilonka/MireaAl
|
2d68b6facbeb99cc4040ea206c64e95ea3c1bc92
|
[
"BSD-2-Clause"
] | null | null | null |
C++/Semester_2/class_4.cpp
|
Trilonka/MireaAl
|
2d68b6facbeb99cc4040ea206c64e95ea3c1bc92
|
[
"BSD-2-Clause"
] | 1
|
2021-12-14T09:35:43.000Z
|
2021-12-14T09:35:43.000Z
|
#include <iostream>
using namespace std;
class BaseString
{
protected:
char *p;
int len;
int capacity;
public:
BaseString(char *ptr)
{
//cout<<"\nBase Constructor 1\n";
len = 0;
for (int i = 0; ptr[i] != '\0'; i++) {
len++;
}
capacity = (len >= 256) ? len << 1 : 256;
p = new char[capacity];
for (int i = 0; i < len; i++) {
p[i] = ptr[i];
}
p[len] = '\0';
}
BaseString(const char *ptr)
{
//cout<<"\nBase Constructor 1\n";
len = 0;
for (int i = 0; ptr[i] != '\0'; i++) {
len++;
}
capacity = (len >= 256) ? len << 1 : 256;
p = new char[capacity];
for (int i = 0; i < len; i++) {
p[i] = ptr[i];
}
p[len] = '\0';
}
BaseString(int Capacity = 256)
{
//cout<<"\nBase Constructor 0\n";
capacity = Capacity;
p = new char[capacity];
len = 0;
}
BaseString(const BaseString &s)
{
//cout<<"\nBase Copy Constructor\n";
len = s.len;
capacity = s.capacity;
p = new char[capacity];
for(int i=0; i<len;i++) {
p[i] = s.p[i];
}
p[len] = '\0';
}
~BaseString()
{
//cout<<"\nBase Destructor\n";
if (p != NULL)
delete[] p;
len = 0;
}
int Length() { return len; }
int Capacity() { return capacity; }
char *get() { return p; }
char &operator[](int i) { return p[i]; }
BaseString &operator=(const BaseString &s)
{
//cout<<"\nBase Operator = \n";
delete[] p;
len = s.len;
capacity = s.capacity;
p = new char[capacity];
for (int i = 0; i < len; i++) {
p[i] = s.p[i];
}
p[len] = '\0';
return *this;
}
BaseString operator+(const BaseString &s)
{
BaseString res;
res.len = len + s.len;
res.capacity = (res.len >= 256) ? res.len << 1 : 256;
for (int i = 0; i < len; i++) {
res.p[i] = p[i];
}
for (int i = len; i < res.len; i++) {
res.p[i] = s.p[i - len];
}
return res;
}
virtual void print()
{
int i = 0;
while (p[i] != '\0') {
cout << p[i++];
}
}
};
class String : public BaseString
{
public:
String(char *ptr) : BaseString(ptr) {}
String(const char *s) : BaseString(s) {}
String(int Capacity = 256) : BaseString(Capacity) {}
String(const String &s)
{
delete[] p;
capacity = s.capacity;
p = new char[capacity];
len = s.len;
for (int i = 0; i < len; i++) {
p[i] = s.p[i];
}
p[len] = '\0';
}
~String() {}
int IndexOf(char c)
{
for (int i = 0; i < len; i++) {
if (p[i] == c) {
return i;
}
}
return -1;
}
int string_to_number()
{
int ans = 0;
char k = 1;
bool isNum = true;
for (int i = len-1; i>=0; i--) {
if(i==0 && p[i]=='-' && isNum) {
return ans *= -1;
}
if (p[i]>='0' && p[i]<='9') {
ans += k*p[i];
k *= 10;
} else {
isNum = false;
break;
}
}
if (!isNum) cout << "It isn't a number, returned 0" << endl;
return isNum ? ans : 0;
}
};
int main()
{
BaseString str1("hi teacher, have you a good day!");
str1.print(); cout << endl;
BaseString str2(" you are the best");
BaseString str3;
str3 = str1 + str2;
str3.print(); cout << endl;
String s1("wow");
String s2(str3.get());
s2.print(); cout << endl;
s1 = s2;
cout << s1.IndexOf('o') << endl;
String num1("4213");
num1.print();
String num2("-3213");
cout << num1.string_to_number() << endl;
cout << num2.string_to_number() << endl;
cout << s1.string_to_number() << endl;
}
| 22.532258
| 68
| 0.409926
|
Trilonka
|
9f1c8ff208d697fa8730f4e81fb0f6340056fcce
| 1,643
|
cc
|
C++
|
squim/image/multi_frame_writer.cc
|
baranov1ch/squim
|
5bde052735e0dac7c87e8f7939d0168e6ee05857
|
[
"Apache-2.0"
] | 2
|
2016-05-06T01:15:49.000Z
|
2016-05-06T01:29:00.000Z
|
squim/image/multi_frame_writer.cc
|
baranov1ch/squim
|
5bde052735e0dac7c87e8f7939d0168e6ee05857
|
[
"Apache-2.0"
] | null | null | null |
squim/image/multi_frame_writer.cc
|
baranov1ch/squim
|
5bde052735e0dac7c87e8f7939d0168e6ee05857
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2015 Alexey Baranov <me@kotiki.cc>. 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 "squim/image/multi_frame_writer.h"
#include "squim/image/image_encoder.h"
namespace image {
MultiFrameWriter::MultiFrameWriter(std::unique_ptr<ImageEncoder> encoder)
: encoder_(std::move(encoder)) {}
MultiFrameWriter::~MultiFrameWriter() {}
Result MultiFrameWriter::Initialize(const ImageInfo* image_info) {
return encoder_->Initialize(image_info);
}
void MultiFrameWriter::SetMetadata(const ImageMetadata* metadata) {
encoder_->SetMetadata(metadata);
}
Result MultiFrameWriter::WriteFrame(ImageFrame* frame) {
return encoder_->EncodeFrame(frame, false);
}
Result MultiFrameWriter::FinishWrite(ImageOptimizationStats* stats) {
auto result = encoder_->EncodeFrame(nullptr, true);
// Normally pending should result in another call to this function but who
// cares, finish writes up-to date does nothing which may suspend IO. If that
// ever happens, add another step.
if (result.error())
return result;
return encoder_->FinishWrite(stats);
}
} // namespace image
| 31
| 79
| 0.752891
|
baranov1ch
|
9f1cf689e23f70318bd72ccc884671d7e91fc583
| 260
|
hpp
|
C++
|
src/algorithms/next_pos_chars.hpp
|
ruolin/vg
|
fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04
|
[
"MIT"
] | 740
|
2016-02-23T02:31:10.000Z
|
2022-03-31T20:51:36.000Z
|
src/algorithms/next_pos_chars.hpp
|
ruolin/vg
|
fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04
|
[
"MIT"
] | 2,455
|
2016-02-24T08:17:45.000Z
|
2022-03-31T20:19:41.000Z
|
src/algorithms/next_pos_chars.hpp
|
ruolin/vg
|
fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04
|
[
"MIT"
] | 169
|
2016-03-03T15:41:33.000Z
|
2022-03-31T04:01:53.000Z
|
#pragma once
#include "../handle.hpp"
#include <vg/vg.pb.h>
#include <functional>
#include "../position.hpp"
namespace vg {
namespace algorithms {
using namespace std;
map<pos_t, char> next_pos_chars(const PathPositionHandleGraph& graph, pos_t pos);
}
}
| 14.444444
| 81
| 0.726923
|
ruolin
|
9f22d3790d88e1ac78e04f0fa1ddd96685262d2f
| 1,357
|
cpp
|
C++
|
src/zone_server.cpp
|
sischkg/nxnsattack
|
c20896e40187bbcacb5c0255ff8f3cc7d0592126
|
[
"MIT"
] | 5
|
2020-05-22T10:01:51.000Z
|
2022-01-01T04:45:14.000Z
|
src/zone_server.cpp
|
sischkg/dns-fuzz-server
|
6f45079014e745537c2f564fdad069974e727da1
|
[
"MIT"
] | 1
|
2020-06-07T14:09:44.000Z
|
2020-06-07T14:09:44.000Z
|
src/zone_server.cpp
|
sischkg/dns-fuzz-server
|
6f45079014e745537c2f564fdad069974e727da1
|
[
"MIT"
] | 2
|
2020-03-10T03:06:20.000Z
|
2021-07-25T15:07:45.000Z
|
#include "auth_server.hpp"
#include <boost/program_options.hpp>
#include <iostream>
#include <fstream>
int main( int argc, char **argv )
{
namespace po = boost::program_options;
std::string bind_address;
uint16_t bind_port;
std::string zone_filename;
std::string apex;
po::options_description desc( "unbound" );
desc.add_options()( "help,h", "print this message" )
( "bind,b", po::value<std::string>( &bind_address )->default_value( "0.0.0.0" ), "bind address" )
( "port,p", po::value<uint16_t>( &bind_port )->default_value( 53 ), "bind port" )
( "file,f", po::value<std::string>( &zone_filename ), "zone filename" )
( "zone,z", po::value<std::string>( &apex), "zone apex" );
po::variables_map vm;
po::store( po::parse_command_line( argc, argv, desc ), vm );
po::notify( vm );
if ( vm.count( "help" ) ) {
std::cerr << desc << "\n";
return 1;
}
try {
dns::DNSServerParameters params;
params.mBindAddress = bind_address;
params.mBindPort = bind_port;
dns::AuthServer server( params );
server.load( apex, zone_filename );
server.start();
}
catch ( std::runtime_error &e ) {
std::cerr << e.what() << std::endl;
}
catch ( std::logic_error &e ) {
std::cerr << e.what() << std::endl;
}
return 0;
}
| 27.693878
| 105
| 0.590273
|
sischkg
|
9f23a340317e03cb15a7ec88a2cc6bb8c32dd96b
| 9,980
|
cpp
|
C++
|
tests/RaZ/Render/Shader.cpp
|
xiaohunqupo/RaZ
|
ad0a1e0f336d8beb20afc73c0a5e6ee8a319a8f1
|
[
"MIT"
] | 1
|
2022-01-26T06:36:54.000Z
|
2022-01-26T06:36:54.000Z
|
tests/RaZ/Render/Shader.cpp
|
xiaohunqupo/RaZ
|
ad0a1e0f336d8beb20afc73c0a5e6ee8a319a8f1
|
[
"MIT"
] | null | null | null |
tests/RaZ/Render/Shader.cpp
|
xiaohunqupo/RaZ
|
ad0a1e0f336d8beb20afc73c0a5e6ee8a319a8f1
|
[
"MIT"
] | null | null | null |
#include "Catch.hpp"
#include "RaZ/Render/Renderer.hpp"
#include "RaZ/Render/Shader.hpp"
namespace {
inline void checkShader(const Raz::Shader& shader, const Raz::FilePath& path = {}) {
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK(shader.isValid());
CHECK(shader.getPath() == path);
shader.compile();
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK(shader.isCompiled());
}
} // namespace
TEST_CASE("Shader validity") {
Raz::Renderer::recoverErrors(); // Flushing errors
{
Raz::VertexShader vertShader;
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK(vertShader.isValid());
vertShader.destroy();
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK_FALSE(vertShader.isValid());
}
// Tessellation shaders are only available in OpenGL 4.0+
if (Raz::Renderer::checkVersion(4, 0)) {
{
Raz::TessellationControlShader tessCtrlShader;
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK(tessCtrlShader.isValid());
tessCtrlShader.destroy();
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK_FALSE(tessCtrlShader.isValid());
}
{
Raz::TessellationEvaluationShader tessEvalShader;
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK(tessEvalShader.isValid());
tessEvalShader.destroy();
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK_FALSE(tessEvalShader.isValid());
}
}
{
Raz::GeometryShader geomShader;
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK(geomShader.isValid());
geomShader.destroy();
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK_FALSE(geomShader.isValid());
}
{
Raz::FragmentShader fragShader;
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK(fragShader.isValid());
fragShader.destroy();
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK_FALSE(fragShader.isValid());
}
// Compute shaders are only available in OpenGL 4.3+
if (Raz::Renderer::checkVersion(4, 3)) {
Raz::ComputeShader compShader;
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK(compShader.isValid());
compShader.destroy();
CHECK_FALSE(Raz::Renderer::hasErrors());
CHECK_FALSE(compShader.isValid());
}
}
TEST_CASE("Shader clone") {
// The content of the shaders does not need to be valid for this test
const Raz::FilePath shaderPath = RAZ_TESTS_ROOT "assets/shaders/basic.comp";
constexpr std::string_view shaderSource = "Shader source test";
static constexpr auto areShadersEqual = [] (const Raz::Shader& shader1, const Raz::Shader& shader2) {
CHECK_FALSE(shader1.getIndex() == shader2.getIndex()); // Both shaders remain two different objects: their indices must be different
CHECK(shader1.getPath() == shader2.getPath());
CHECK(Raz::Renderer::recoverShaderType(shader1.getIndex()) == Raz::Renderer::recoverShaderType(shader2.getIndex()));
CHECK(Raz::Renderer::recoverShaderSource(shader1.getIndex()) == Raz::Renderer::recoverShaderSource(shader2.getIndex()));
};
{
const Raz::VertexShader shaderFromPath(shaderPath);
areShadersEqual(shaderFromPath, shaderFromPath.clone());
const Raz::VertexShader shaderFromSource = Raz::VertexShader::loadFromSource(shaderSource);
areShadersEqual(shaderFromSource, shaderFromSource.clone());
}
// Tessellation shaders are only available in OpenGL 4.0+
if (Raz::Renderer::checkVersion(4, 0)) {
{
const Raz::TessellationControlShader shaderFromPath(shaderPath);
areShadersEqual(shaderFromPath, shaderFromPath.clone());
const Raz::TessellationControlShader shaderFromSource = Raz::TessellationControlShader::loadFromSource(shaderSource);
areShadersEqual(shaderFromSource, shaderFromSource.clone());
}
{
const Raz::TessellationEvaluationShader shaderFromPath(shaderPath);
areShadersEqual(shaderFromPath, shaderFromPath.clone());
const Raz::TessellationEvaluationShader shaderFromSource = Raz::TessellationEvaluationShader::loadFromSource(shaderSource);
areShadersEqual(shaderFromSource, shaderFromSource.clone());
}
}
{
const Raz::GeometryShader shaderFromPath(shaderPath);
areShadersEqual(shaderFromPath, shaderFromPath.clone());
const Raz::GeometryShader shaderFromSource = Raz::GeometryShader::loadFromSource(shaderSource);
areShadersEqual(shaderFromSource, shaderFromSource.clone());
}
{
const Raz::FragmentShader shaderFromPath(shaderPath);
areShadersEqual(shaderFromPath, shaderFromPath.clone());
const Raz::FragmentShader shaderFromSource = Raz::FragmentShader::loadFromSource(shaderSource);
areShadersEqual(shaderFromSource, shaderFromSource.clone());
}
// Compute shaders are only available in OpenGL 4.3+
if (Raz::Renderer::checkVersion(4, 3)) {
const Raz::ComputeShader shaderFromPath(shaderPath);
areShadersEqual(shaderFromPath, shaderFromPath.clone());
const Raz::ComputeShader shaderFromSource = Raz::ComputeShader::loadFromSource(shaderSource);
areShadersEqual(shaderFromSource, shaderFromSource.clone());
}
}
TEST_CASE("Vertex shader from source") {
Raz::Renderer::recoverErrors(); // Flushing errors
const std::string vertSource = R"(
void main() {
gl_Position = vec4(1.0);
}
)";
// The #version tag is automatically added if not present; if it is, nothing is changed to the source
checkShader(Raz::VertexShader::loadFromSource(vertSource));
checkShader(Raz::VertexShader::loadFromSource("#version 330\n" + vertSource));
}
TEST_CASE("Tessellation control shader from source") {
// Tessellation shaders are only available in OpenGL 4.0+
if (!Raz::Renderer::checkVersion(4, 0))
return;
Raz::Renderer::recoverErrors(); // Flushing errors
const std::string tessCtrlSource = R"(
layout(vertices = 3) out;
void main() {
gl_TessLevelOuter[0] = 1.0;
gl_TessLevelOuter[1] = 2.0;
gl_TessLevelOuter[2] = 3.0;
gl_TessLevelOuter[3] = 4.0;
gl_TessLevelInner[0] = 1.0;
gl_TessLevelInner[1] = 2.0;
}
)";
// The #version tag is automatically added if not present; if it is, nothing is changed to the source
checkShader(Raz::TessellationControlShader::loadFromSource(tessCtrlSource));
checkShader(Raz::TessellationControlShader::loadFromSource("#version 400\n" + tessCtrlSource));
}
TEST_CASE("Tessellation evaluation shader from source") {
// Tessellation shaders are only available in OpenGL 4.0+
if (!Raz::Renderer::checkVersion(4, 0))
return;
Raz::Renderer::recoverErrors(); // Flushing errors
const std::string tessEvalSource = R"(
layout(triangles, equal_spacing, ccw) in;
void main() {
gl_Position = vec4(0.0);
}
)";
// The #version tag is automatically added if not present; if it is, nothing is changed to the source
checkShader(Raz::TessellationEvaluationShader::loadFromSource(tessEvalSource));
checkShader(Raz::TessellationEvaluationShader::loadFromSource("#version 400\n" + tessEvalSource));
}
TEST_CASE("Fragment shader from source") {
Raz::Renderer::recoverErrors(); // Flushing errors
const std::string fragSource = R"(
layout(location = 0) out vec4 fragColor;
void main() {
fragColor = vec4(1.0);
}
)";
// The #version tag is automatically added if not present; if it is, nothing is changed to the source
checkShader(Raz::FragmentShader::loadFromSource(fragSource));
checkShader(Raz::FragmentShader::loadFromSource("#version 330\n" + fragSource));
}
TEST_CASE("Compute shader from source") {
// Compute shaders are only available in OpenGL 4.3+
if (!Raz::Renderer::checkVersion(4, 3))
return;
Raz::Renderer::recoverErrors(); // Flushing errors
const std::string compSource = R"(
layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
layout(rgba32f, binding = 0) uniform image2D uniOutput;
void main() {
imageStore(uniOutput, ivec2(0), vec4(0.0));
}
)";
// The #version tag is automatically added if not present; if it is, nothing is changed to the source
checkShader(Raz::ComputeShader::loadFromSource(compSource));
checkShader(Raz::ComputeShader::loadFromSource("#version 430\n" + compSource));
}
TEST_CASE("Vertex shader imported") {
Raz::Renderer::recoverErrors(); // Flushing errors
const Raz::FilePath vertShaderPath = RAZ_TESTS_ROOT "../shaders/common.vert";
const Raz::VertexShader vertShader(vertShaderPath);
checkShader(vertShader, vertShaderPath);
}
TEST_CASE("Tessellation control shader imported") {
// Tessellation shaders are only available in OpenGL 4.0+
if (!Raz::Renderer::checkVersion(4, 0))
return;
Raz::Renderer::recoverErrors(); // Flushing errors
const Raz::FilePath tessCtrlShaderPath = RAZ_TESTS_ROOT "assets/shaders/basic.tesc";
const Raz::TessellationControlShader tessCtrlShader(tessCtrlShaderPath);
checkShader(tessCtrlShader, tessCtrlShaderPath);
}
TEST_CASE("Tessellation evaluation shader imported") {
// Tessellation shaders are only available in OpenGL 4.0+
if (!Raz::Renderer::checkVersion(4, 0))
return;
Raz::Renderer::recoverErrors(); // Flushing errors
const Raz::FilePath tessEvalShaderPath = RAZ_TESTS_ROOT "assets/shaders/basic.tese";
const Raz::TessellationEvaluationShader tessEvalShader(tessEvalShaderPath);
checkShader(tessEvalShader, tessEvalShaderPath);
}
TEST_CASE("Fragment shader imported") {
Raz::Renderer::recoverErrors(); // Flushing errors
const Raz::FilePath fragShaderPath = RAZ_TESTS_ROOT "../shaders/lambert.frag";
const Raz::FragmentShader fragShader(fragShaderPath);
checkShader(fragShader, fragShaderPath);
}
TEST_CASE("Compute shader imported") {
// Compute shaders are only available in OpenGL 4.3+
if (!Raz::Renderer::checkVersion(4, 3))
return;
Raz::Renderer::recoverErrors(); // Flushing errors
const Raz::FilePath compShaderPath = RAZ_TESTS_ROOT "assets/shaders/basic.comp";
const Raz::ComputeShader compShader(compShaderPath);
checkShader(compShader, compShaderPath);
}
| 32.508143
| 136
| 0.71994
|
xiaohunqupo
|
9f267d44ac326c20212e735301699300d0b135e0
| 1,145
|
cpp
|
C++
|
Engine/Renderer/GLES3/src/GLES3RenderTextureManager.cpp
|
LiangYue1981816/AresEngine
|
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
|
[
"BSD-2-Clause"
] | 3
|
2018-12-08T16:32:05.000Z
|
2020-06-02T11:07:15.000Z
|
Engine/Renderer/GLES3/src/GLES3RenderTextureManager.cpp
|
LiangYue1981816/AresEngine
|
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
|
[
"BSD-2-Clause"
] | null | null | null |
Engine/Renderer/GLES3/src/GLES3RenderTextureManager.cpp
|
LiangYue1981816/AresEngine
|
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
|
[
"BSD-2-Clause"
] | 1
|
2019-09-12T00:26:05.000Z
|
2019-09-12T00:26:05.000Z
|
#include "GLES3Renderer.h"
CGLES3RenderTextureManager::CGLES3RenderTextureManager(void)
{
}
CGLES3RenderTextureManager::~CGLES3RenderTextureManager(void)
{
for (const auto& itRenderTexture : m_pRenderTextures) {
delete itRenderTexture.second;
}
}
CGLES3RenderTexture* CGLES3RenderTextureManager::Get(uint32_t name)
{
mutex_autolock autolock(&lock);
{
const auto& itRenderTexture = m_pRenderTextures.find(name);
if (itRenderTexture != m_pRenderTextures.end()) {
return itRenderTexture->second;
}
else {
return nullptr;
}
}
}
CGLES3RenderTexture* CGLES3RenderTextureManager::Create(uint32_t name)
{
mutex_autolock autolock(&lock);
{
if (m_pRenderTextures[name] == nullptr) {
m_pRenderTextures[name] = new CGLES3RenderTexture(this, name);
}
return m_pRenderTextures[name];
}
}
void CGLES3RenderTextureManager::Destroy(CGLES3RenderTexture* pRenderTexture)
{
ASSERT(pRenderTexture);
{
mutex_autolock autolock(&lock);
{
if (m_pRenderTextures.find(pRenderTexture->GetName()) != m_pRenderTextures.end()) {
m_pRenderTextures.erase(pRenderTexture->GetName());
}
}
}
delete pRenderTexture;
}
| 20.446429
| 86
| 0.751092
|
LiangYue1981816
|
9f3987fbb9f0e91edeb0403e6b34be56e630e354
| 3,702
|
cc
|
C++
|
src/usart.cc
|
radishkill/check_system
|
0f5692462ebd40a0d7b7ae2a8462df75b6fec74c
|
[
"Apache-2.0"
] | null | null | null |
src/usart.cc
|
radishkill/check_system
|
0f5692462ebd40a0d7b7ae2a8462df75b6fec74c
|
[
"Apache-2.0"
] | null | null | null |
src/usart.cc
|
radishkill/check_system
|
0f5692462ebd40a0d7b7ae2a8462df75b6fec74c
|
[
"Apache-2.0"
] | null | null | null |
#include "usart.h"
#include "mutils.h"
Usart::Usart()
: fd_(-1), device_name_("") {
}
Usart::Usart(const char* name, int baud_rate, int databits, int stopbits, char parity, int flow_ctrl) {
Open(name, baud_rate, databits, stopbits, parity, flow_ctrl);
}
int Usart::Open(const char* name, int baud_rate, int databits, int stopbits, char parity, int flow_ctrl) {
device_name_ = name;
fd_ = open(device_name_.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
if (fd_ == -1) {
perror("open serialPort fail");
return -1;
}
SetParity(baud_rate, databits, stopbits, parity, flow_ctrl);
return 0;
}
int Usart::SetParity(int baud_rate, int databits, int stopbits, char parity, int flow_ctrl)
{
struct termios options;
if ( tcgetattr( fd_, &options) != 0)
{
return (-1);
}
bzero(&options, sizeof(options));
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~CSIZE;
switch (baud_rate)
{
case 2400:
cfsetispeed(&options, B2400);
cfsetospeed(&options, B2400);
break;
case 4800:
cfsetispeed(&options, B4800);
cfsetospeed(&options, B4800);
break;
case 9600:
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
break;
case 115200:
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
break;
default:
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
break;
}
switch (databits) /*设置数据位数*/
{
case 5:
options.c_cflag |= CS5;
break;
case 6:
options.c_cflag |= CS6;
break;
case 7:
options.c_cflag |= CS7;
break;
case 8:
options.c_cflag |= CS8;
break;
}
/* 设置停止位*/
switch (stopbits)
{
case 1:
options.c_cflag &= ~CSTOPB;
break;
case 2:
options.c_cflag |= CSTOPB;
break;
default:
fprintf(stderr,"Unsupported stop bits\n");
return -1;
}
// 校验码
switch (parity)
{
case '0': /*奇校验*/
options.c_cflag |= PARENB;/*开启奇偶校验*/
options.c_iflag |= (INPCK | ISTRIP);/*INPCK打开输入奇偶校验;ISTRIP去除字符的第八个比特 */
options.c_cflag |= PARODD;/*启用奇校验(默认为偶校验)*/
break;
case 'E':/*偶校验*/
options.c_cflag |= PARENB; /*开启奇偶校验 */
options.c_iflag |= ( INPCK | ISTRIP);/*打开输入奇偶校验并去除字符第八个比特*/
options.c_cflag &= ~PARODD;/*启用偶校验*/
break;
case 'N': /*无奇偶校验*/
options.c_cflag &= ~PARENB;
break;
}
switch (flow_ctrl)
{
case 0:
options.c_cflag &= ~CRTSCTS;
break;
case 1://haidware
// options.c_cflag |= CRTSCTS;
break;
case 2://software
flow_ctrl = 0;
options.c_iflag |= (IXON | IXOFF | IXANY);
break;
default:
fprintf(stderr,"error\n");
break;
}
/*设置最少字符和等待时间,对于接收字符和等待时间没有特别的要求时*/
options.c_cc[VTIME] = 0;/*非规范模式读取时的超时时间;*/
options.c_cc[VMIN] = 0; /*非规范模式读取时的最小字符数*/
tcflush(fd_ ,TCIFLUSH);/*tcflush清空终端未完成的输入/输出请求及数据;TCIFLUSH表示清空正收到的数据,且不读取出来 */
return tcsetattr(fd_, TCSAFLUSH, &options);
}
int Usart::SendData(char* buf, int len) {
std::cout << "send:";
Utils::ShowRawString(buf, len);
std::cout << std::endl;
return write(fd_, buf, len);
}
int Usart::ReadData(char* buf, int len) {
std::cout << "recv:";
int ret = read(fd_, buf, len);
Utils::ShowRawString(buf, ret);
std::cout << std::endl;
return ret;
}
bool Usart::IsOpen() const {
if (fd_ <= 0)
return false;
return true;
}
int Usart::GetFd() const {
return fd_;
}
void Usart::Close() {
close(fd_);
fd_ = -1;
}
| 23.730769
| 106
| 0.573474
|
radishkill
|
9f39f8cf75d908f2fb7704ad6e7097c4e1c0315d
| 960
|
hh
|
C++
|
CommTrackingObjects/smartsoft/src-gen/CommTrackingObjects/CommPersonLostEventResultData.hh
|
canonical-robots/DomainModelsRepositories
|
68b9286d84837e5feb7b200833b158ab9c2922a4
|
[
"BSD-3-Clause"
] | null | null | null |
CommTrackingObjects/smartsoft/src-gen/CommTrackingObjects/CommPersonLostEventResultData.hh
|
canonical-robots/DomainModelsRepositories
|
68b9286d84837e5feb7b200833b158ab9c2922a4
|
[
"BSD-3-Clause"
] | 2
|
2020-08-20T14:49:47.000Z
|
2020-10-07T16:10:07.000Z
|
CommTrackingObjects/smartsoft/src-gen/CommTrackingObjects/CommPersonLostEventResultData.hh
|
canonical-robots/DomainModelsRepositories
|
68b9286d84837e5feb7b200833b158ab9c2922a4
|
[
"BSD-3-Clause"
] | 8
|
2018-06-25T08:41:28.000Z
|
2020-08-13T10:39:30.000Z
|
//--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#ifndef COMMTRACKINGOBJECTS_COMMPERSONLOSTEVENTRESULT_DATA_H_
#define COMMTRACKINGOBJECTS_COMMPERSONLOSTEVENTRESULT_DATA_H_
#include "CommTrackingObjects/enumPersonLostEventTypeData.hh"
namespace CommTrackingObjectsIDL
{
struct CommPersonLostEventResult
{
CommTrackingObjectsIDL::PersonLostEventType state;
};
};
#endif /* COMMTRACKINGOBJECTS_COMMPERSONLOSTEVENTRESULT_DATA_H_ */
| 30.967742
| 76
| 0.676042
|
canonical-robots
|
9f3b907f061965f3de5e1526686d532c2c4cd3f1
| 826
|
cpp
|
C++
|
codeforces/contests/1351/A.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | 18
|
2020-08-27T05:27:50.000Z
|
2022-03-08T02:56:48.000Z
|
codeforces/contests/1351/A.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | null | null | null |
codeforces/contests/1351/A.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | 1
|
2020-10-13T05:23:58.000Z
|
2020-10-13T05:23:58.000Z
|
/*
A. A+B (Trial Problem)
time limit per test1 second
memory limit per test: 256 megabytes
inputstandard input
outputstandard output
You are given two integers 𝑎 and 𝑏. Print 𝑎+𝑏.
Input
The first line contains an integer 𝑡 (1≤𝑡≤104) — the number of test cases in the input. Then 𝑡 test cases follow.
Each test case is given as a line of two integers 𝑎 and 𝑏 (−1000≤𝑎,𝑏≤1000).
Output
Print 𝑡 integers — the required numbers 𝑎+𝑏.
Example
input
4
1 5
314 15
-99 99
123 987
output
6
329
0
1110
*/
#include <bits/stdc++.h>
using namespace std;
#define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL)
int main()
{
FAST_INP;
int t,a,b;
cin >> t;
while(t--){
// take two input values
cin >> a >> b;
// add them together
cout << (a+b) << "\n";
}
return 0;
}
| 17.208333
| 113
| 0.650121
|
wingkwong
|
9f3c5f94ce2e321af0a8047f71a3a051c3091a70
| 68,205
|
cpp
|
C++
|
Yugo/src/Editor/Editor.cpp
|
bd93/Yugo
|
4448083b2968a889d2b8bf1c83d9ba11cb358aaf
|
[
"MIT"
] | null | null | null |
Yugo/src/Editor/Editor.cpp
|
bd93/Yugo
|
4448083b2968a889d2b8bf1c83d9ba11cb358aaf
|
[
"MIT"
] | null | null | null |
Yugo/src/Editor/Editor.cpp
|
bd93/Yugo
|
4448083b2968a889d2b8bf1c83d9ba11cb358aaf
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "Editor.h"
#include "Animation/Components.h"
#include "Animation/Animation.h"
#include "Scripting/Components.h"
#include "Core/Time.h"
#include "Core/ModelImporter.h"
#include "Renderer/SpriteRenderer.h"
//#include "GameUI/Widget.h"
#include <ImGuizmo.h>
#include <windows.h>
#include <commdlg.h>
#include <entt/core/type_info.hpp>
namespace Yugo
{
// Play mode flag
static bool s_PlayMode = false;
// Show/hide Scene in editor
static bool s_RenderScene = true;
// Show/hide in-game UI in editor
static bool s_RenderUI = false;
// Show/hide bounding boxes
static bool s_RenderBoundingBox = false;
// ImGuizmo widget data
static ImGuizmo::OPERATION s_CurrentGizmoOperation(ImGuizmo::TRANSLATE);
static ImGuizmo::MODE s_CurrentGizmoMode(ImGuizmo::WORLD);
static bool s_UseSnap = false;
static float s_Snap[3] = { 1.f, 1.f, 1.f };
static float s_Bounds[] = { -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f };
static float s_BoundsSnap[] = { 0.1f, 0.1f, 0.1f };
static bool s_BoundSizing = false;
static bool s_BoundSizingSnap = false;
Editor::Editor()
: m_MainWindow(uPtrCreate<Window>("Editor", 1200, 800)),
m_GameWindow(uPtrCreate<Window>("Game", 1200, 800)),
m_Scene(sPtrCreate<Scene>()),
m_UserInterface(sPtrCreate<UserInterface>()),
m_ScriptEngine(uPtrCreate<ScriptEngine>()),
m_SelectedSceneEntity(entt::null)
{
m_SceneInfo.SceneName = "Default";
m_SceneInfo.SceneFilePath = "None";
/*
By default initialize width and heigh to main window size.
In the next frame it will be resized to Scene ImGui window in UpdateSceneViewport method.
*/
m_SceneInfo.SceneWidth = m_MainWindow->m_Width;
m_SceneInfo.SceneHeight = m_MainWindow->m_Height;
}
/**
* @brief Method to be called during application OnStart stage.
*
* This method initialize all necessary components.
*/
void Editor::OnStart()
{
m_MainWindow->OnStart();
UserInput::SetGLFWwindow(m_MainWindow->m_GLFWwindow);
// Initialize ImGui
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
ImGuiStyle& style = ImGui::GetStyle();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForOpenGL(m_MainWindow->m_GLFWwindow, true);
ImGui_ImplOpenGL3_Init("#version 330");
// Initially create texture framebuffer with default size (1200 x 800)
CreateFrameBuffer(m_SceneInfo.SceneWidth, m_SceneInfo.SceneHeight);
m_Scene->OnStart();
//m_UserInterface->OnStart();
Dispatcher::Subscribe<MouseButtonPress>(this);
Dispatcher::Subscribe<KeyboardKeyPress>(this);
Dispatcher::Subscribe<ImportAssetEvent>(this);
Dispatcher::Subscribe<MouseScroll>(this);
Dispatcher::Subscribe<WindowResize>(this);
}
/**
* @brief Method to be called during application OnRender stage.
*
* This method renders ImGui widgets.
* Inside Scene window it renders Scene and UI.
*/
void Editor::OnRender()
{
// ImGui rendering initialisation
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGuiWindowFlags window_flags = 0;
window_flags |= ImGuiWindowFlags_MenuBar;
window_flags |= ImGuiWindowFlags_NoDocking;
window_flags |= ImGuiWindowFlags_NoBackground;
window_flags |= ImGuiWindowFlags_NoCollapse;
window_flags |= ImGuiWindowFlags_NoResize;
window_flags |= ImGuiWindowFlags_NoTitleBar;
window_flags |= ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoNavFocus;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus;
// OS specific window viewport
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->Pos);
ImGui::SetNextWindowSize(viewport->Size);
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("Dock Space", NULL, window_flags);
ImGui::PopStyleVar(3);
ImGuiID dockspace_id = ImGui::GetID("MyDockSpace");
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_None);
/*
The order of showing widgets/windows is important!
E.g. ShowImGuizmo method, which is called in ShowSceneWindow method, need to be in front of ShowInspectorWindow.
The reason is because of model matrix update.
Editor's OnUpdate method is called first and thus model matrix is updated with TransformComponent members (Position, Rotation, Scale).
Then in ShowImGuizmo method model matrix is updated if user moves entity with imguizmo widget.
Then in ShowInspectorWindow method model matrix is decomposed to TransformComponent members, so user can manualy change them in Inspector window.
Just right after this model matrix is recomposed (updated) with TransformComponent members.
*/
ShowMenuBar();
ShowSceneWindow();
if (s_RenderScene)
{
ShowHierarchyWindow(m_Scene->m_Registry);
ShowInspectorWindow(m_Scene->m_Registry);
}
else if (s_RenderUI)
{
//ShowHierarchyWindow(m_UserInterface->m_Registry);
//ShowInspectorWindow(m_UserInterface->m_Registry);
}
ShowProjectWindow();
//ImGui::ShowDemoWindow(); // ImGui demo window with all possible widgets/features
// Render Scene in Game window when editor is in play mode
if (s_PlayMode)
{
Window::MakeContextCurrent(m_GameWindow->m_GLFWwindow);
glEnable(GL_DEPTH_TEST);
glClearColor(0.3f, 0.3f, 0.3f, 1.0f); // Color of game window background
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_GameWindow->m_Scene->OnRender(); // Game window scene is a copy of Editor's scene
m_GameWindow->m_UserInterface->OnRender();
//Window::PollEvents(); // temp!
m_GameWindow->SwapBuffers();
glDisable(GL_DEPTH_TEST);
Window::MakeContextCurrent(m_MainWindow->m_GLFWwindow);
if (m_GameWindow->WindowShouldClose())
{
s_PlayMode = false;
m_ScriptEngine->OnStop();
m_GameWindow->OnShutdown();
UserInput::SetGLFWwindow(m_MainWindow->m_GLFWwindow);
m_MainWindow->SetEventCallbacks();
m_GameWindow->RemoveEventCallbacks();
Window::s_CurrentActiveWindowName = m_MainWindow->GetWindowName();
}
}
// Render Scene in editor's Scene window
m_FrameBuffer->Bind();
glEnable(GL_DEPTH_TEST);
glClearColor(0.3f, 0.3f, 0.3f, 1.0f); // Color of framebuffer's texture inside scene imgui window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (s_RenderScene)
{
m_Scene->OnRender();
if (s_RenderBoundingBox)
{
auto& camera = m_Scene->GetCamera();
auto view = m_Scene->m_Registry.view<MeshComponent, BoundBoxComponent, TransformComponent>();
for (auto entity : view)
{
auto& [aabb, transform] = view.get<BoundBoxComponent, TransformComponent>(entity);
MeshRenderer::DrawAABB(aabb, transform, camera, ResourceManager::GetShader("quadShader"));
//for (const auto& subAABB : aabb.SubAABBs)
//{
// MeshRenderer::DrawAABB(subAABB, transform, ResourceManager::GetShader("quadShader"));
//}
}
}
glDisable(GL_DEPTH_TEST);
}
else if (s_RenderUI)
{
//m_UserInterface->OnRender();
}
m_FrameBuffer->BlitMultisampled(m_SceneInfo.SceneWidth, m_SceneInfo.SceneHeight, m_FrameBuffer->GetId(), m_IntermediateFrameBuffer->GetId());
m_FrameBuffer->Unbind();
// Render ImGui
ImGuiIO& io = ImGui::GetIO();
int glfwWindowWidth;
int glfwWindowHeight;
glfwGetWindowSize(m_MainWindow->m_GLFWwindow, &glfwWindowWidth, &glfwWindowHeight);
io.DisplaySize = ImVec2((float)glfwWindowWidth, (float)glfwWindowHeight);
ImGui::Render();
/*
Clear default framebuffer color and depth buffers which are attchaed to it;
This is needed because scene is being rendered on custom framebuffer's attached texture
and ImGUI is being renderd on default framebuffer
*/
glClearColor(0.2f, 0.2f, 0.2f, 1.0f); // Color of ImGui background (Main window)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
GLFWwindow* backup_current_context = glfwGetCurrentContext();
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
glfwMakeContextCurrent(backup_current_context);
}
}
void Editor::OnUpdate(TimeStep ts)
{
if (s_PlayMode)
{
// The order of update is important! If scene is updated first, then script can't execute entity movement
//Window::MakeContextCurrent(m_GameWindow->m_GLFWwindow);
m_ScriptEngine->OnUpdate(ts);
m_GameWindow->m_Scene->OnUpdate(ts);
m_GameWindow->m_UserInterface->OnUpdate(ts);
//Window::MakeContextCurrent(m_MainWindow->m_GLFWwindow);
}
else
{
if (s_RenderScene)
m_Scene->OnUpdate(ts);
else if (s_RenderUI)
m_UserInterface->OnUpdate(ts);
auto view = m_Scene->m_Registry.view<MeshComponent, TransformComponent, AnimationComponent>();
for (auto entity : view)
{
auto& [mesh, animation] = view.get<MeshComponent, AnimationComponent>(entity);
if (animation.IsAnimationRunning)
Animation::RunAnimation(mesh, animation);
}
if (UserInput::IsKeyboardKeyPressed(KEY_LEFT_CONTROL) && UserInput::IsMouseButtonPressed(MOUSE_BUTTON_LEFT) && m_IsSceneWindowHovered)
{
auto view = m_Scene->m_Registry.view<CameraComponent, TransformComponent, EntityTagComponent>();
for (auto entity : view)
{
auto& [camera, transform, tag] = view.get<CameraComponent, TransformComponent, EntityTagComponent>(entity);
if (tag.Name == "Main Camera")
Camera::RotateAroundPivot(transform, camera);
}
}
}
}
void Editor::OnEvent(const Event& event)
{
if (s_PlayMode)
{
//Window::MakeContextCurrent(m_GameWindow->m_GLFWwindow);
m_ScriptEngine->OnEvent(event);
if (event.GetEventType() == EventType::WindowResize)
{
const auto& windowResize = static_cast<const WindowResize&>(event);
int screenWidth = windowResize.GetWidth();
int screenHeight = windowResize.GetHeight();
m_GameWindow->m_UserInterface->m_FramebufferWidth = screenWidth;
m_GameWindow->m_UserInterface->m_FramebufferHeight = screenHeight;
auto& camera = m_GameWindow->m_Scene->GetCamera();
Camera::UpdateProjectionMatrix(camera, screenWidth, screenHeight);
}
//Window::MakeContextCurrent(m_MainWindow->m_GLFWwindow);
}
else
{
// Cast mouse ray, Select entity, reset mouse position offset for camera
if (event.GetEventType() == EventType::MouseButtonPress)
{
const auto& mouseButtonPress = static_cast<const MouseButtonPress&>(event);
if (mouseButtonPress.GetButtonCode() == MOUSE_BUTTON_LEFT)
{
if (!ImGuizmo::IsOver(s_CurrentGizmoOperation) && m_IsSceneWindowHovered)
{
SelectMesh();
Camera::ResetMousePositionOffset(m_Scene->GetCamera());
}
}
}
// Import asset event is invoked when user drag and drop asset to scene imgui window
if (event.GetEventType() == EventType::ImportAsset)
{
auto& camera = m_Scene->GetCamera();
MouseRay::CalculateRayOrigin(camera, m_MouseInfo.MousePosX, m_MouseInfo.MousePosY, m_SceneInfo.SceneWidth, m_SceneInfo.SceneHeight);
const auto& importAssetEvent = static_cast<const ImportAssetEvent&>(event);
const auto& importAssetFilePath = importAssetEvent.GetAssetFilePath();
ImportAsset(importAssetFilePath);
}
// Camera zoom in / zoom out
if (event.GetEventType() == EventType::MouseScroll)
{
if (m_IsSceneWindowHovered)
{
const auto& mouseScroll = static_cast<const MouseScroll&>(event);
auto& camera = m_Scene->GetCamera();
Camera::Scroll(mouseScroll.GetOffsetY(), camera);
}
}
}
}
void Editor::OnShutdown()
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
//m_ScriptEngine->OnShutdown();
m_Scene->OnShutdown();
m_MainWindow->OnShutdown();
Window::TerminateGLFW();
}
void Editor::ShowMenuBar()
{
if (ImGui::BeginMenuBar())
{
static bool saveSuccess = false;
static bool saveError = false;
if (saveSuccess)
{
ImGui::OpenPopup("Success!");
if (ImGui::BeginPopupModal("Success!"))
{
ImGui::Text("This scene has been saved");
ImGui::Separator();
if (ImGui::Button("OK", ImVec2(120, 0))) { saveSuccess = false; ImGui::CloseCurrentPopup(); }
ImGui::EndPopup();
}
}
if (saveError)
{
ImGui::OpenPopup("Error!");
if (ImGui::BeginPopupModal("Error!"))
{
ImGui::Text("First click Save As...");
ImGui::Separator();
if (ImGui::Button("OK", ImVec2(120, 0))) { saveError = false; ImGui::CloseCurrentPopup(); }
ImGui::EndPopup();
}
}
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("New Scene"))
{
m_Scene->m_Registry.clear();
m_SceneInfo.SceneName = "Default";
m_SceneInfo.SceneFilePath = "None";
}
if (ImGui::MenuItem("Load Scene"))
{
std::string filePath;
ShowFileDialogBox("Open", filePath);
m_Scene->LoadScene(filePath);
m_SceneInfo.SceneFilePath = filePath;
std::size_t foundBegin = filePath.find_last_of("\\");
std::size_t foundEnd = filePath.find_last_of(".");
std::string fileName = filePath.substr(foundBegin + 1, foundEnd - foundBegin - 1);
m_SceneInfo.SceneName = fileName;
}
ImGui::Separator();
if (ImGui::MenuItem("Save"))
{
const auto& filePath = m_SceneInfo.SceneFilePath;
if (filePath == "None")
{
saveError = true;
}
else
{
m_Scene->SaveScene(filePath);
saveSuccess = true;
}
}
if (ImGui::MenuItem("Save As..."))
{
std::string filePath;
ShowFileDialogBox("Save As", filePath);
m_Scene->SaveScene(filePath);
m_SceneInfo.SceneFilePath = filePath;
std::size_t foundBegin = filePath.find_last_of("\\");
std::size_t foundEnd = filePath.find_last_of(".");
std::string fileName = filePath.substr(foundBegin + 1, foundEnd - foundBegin - 1);
m_SceneInfo.SceneName = fileName;
}
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::End();
}
void Editor::ShowProjectWindow()
{
using TraverseFun = std::function<void(const std::string&)>;
ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiCond_FirstUseEver);
if (ImGui::Begin("Project"))
{
static std::string currentPath;
// left
ImGui::BeginChild("left pane", ImVec2(250, 0), true);
static size_t selection = 0;
int rootId = 1;
static size_t nodeClicked = 0;
ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen;
if (selection == rootId)
{
nodeFlags |= ImGuiTreeNodeFlags_Selected;
currentPath = FileSystem::GetSolutionFolderPath() + "Main\\src\\Assets";
}
std::string pathToFolder = FileSystem::GetSolutionFolderPath() + "Main\\src\\Assets";
auto folderTreeMap = FileSystem::HashFolderTree(pathToFolder);
bool rootNodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)rootId, nodeFlags, "Assets");
if (ImGui::IsItemClicked())
{
nodeClicked = rootId;
currentPath = pathToFolder;
}
if (ImGui::IsItemClicked(1))
ImGui::OpenPopup(pathToFolder.c_str());
ShowFolderMenuPopup(pathToFolder);
TraverseFun TraverseFolderTree = [&](const std::string& path) {
for (const auto& entry : FileSystem::DirIter(path))
{
if (entry.is_directory())
{
std::string folderName = entry.path().filename().string();
std::string pathToFolder = path + "\\" + folderName;
ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;
if (selection == folderTreeMap[folderName])
nodeFlags |= ImGuiTreeNodeFlags_Selected;
bool nodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)folderTreeMap[folderName], nodeFlags, "%s", folderName.c_str());
if (ImGui::IsItemClicked())
{
nodeClicked = folderTreeMap[folderName];
currentPath = pathToFolder;
}
if (ImGui::IsItemClicked(1))
ImGui::OpenPopup(pathToFolder.c_str());
ShowFolderMenuPopup(pathToFolder);
if (nodeOpen)
{
TraverseFolderTree(pathToFolder);
ImGui::TreePop();
}
}
else
{
std::string fileName = entry.path().filename().string();
std::string pathToFile = path + "\\" + fileName;
ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen;
if (selection == folderTreeMap[fileName])
nodeFlags |= ImGuiTreeNodeFlags_Selected;
ImGui::TreeNodeEx((void*)(intptr_t)folderTreeMap[fileName], nodeFlags, "%s", fileName.c_str());
if (ImGui::IsItemClicked())
{
nodeClicked = folderTreeMap[fileName];
}
if (ImGui::IsItemClicked(1))
{
ImGui::OpenPopup(pathToFile.c_str());
}
if (ImGui::BeginPopup(pathToFile.c_str()))
{
ImGui::Text("Are you sure you want to delete this file?");
if (ImGui::Button("OK"))
{
FileSystem::Delete(pathToFile);
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Cancel"))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
}
}
};
if (rootNodeOpen)
{
ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()); // Increase spacing to differentiate leaves from expanded contents.
TraverseFolderTree(FileSystem::GetSolutionFolderPath() + "Main\\src\\Assets");
if (nodeClicked != 0)
{
selection = nodeClicked;
}
ImGui::PopStyleVar();
ImGui::TreePop();
}
ImGui::EndChild();
ImGui::SameLine();
// right
ImGui::BeginGroup();
ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()));
ImGui::Text(currentPath.c_str());
ImGui::Separator();
if (currentPath != "")
{
if (ImGui::Button("Add Asset"))
{
std::string filePath;
ShowFileDialogBox("Open", filePath);
std::string fileName = FileSystem::FilePath(filePath).filename().string();
FileSystem::CopyFileTo(filePath, currentPath + "\\" + fileName);
}
}
ImGui::Text("Drag and drop asset:");
ImGui::Dummy(ImVec2(0.0f, 10.0f)); // Padding from top line separator
int i = 0;
if (currentPath != "")
{
ImGui::Columns(7);
for (auto& entry : FileSystem::DirIter(currentPath))
{
if (!entry.is_directory())
{
std::string fileName = entry.path().filename().string();
ImGui::PushID(i++);
ImGui::Button(fileName.c_str(), ImVec2(-FLT_MIN, 0.0f));
ImGui::NextColumn();
if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None))
{
ImGui::SetDragDropPayload("Import Asset", (currentPath + "\\" + fileName).c_str(), (currentPath + "\\" + fileName).size() + 1);
ImGui::Text("Drag and drop %s", fileName.c_str());
ImGui::EndDragDropSource();
}
ImGui::PopID();
}
}
}
ImGui::EndChild();
ImGui::EndGroup();
}
ImGui::End();
}
void Editor::ShowInspectorWindow(entt::registry& registry)
{
ImGui::Begin("Inspector");
static int radioOption = 0;
static int pastRadiooption = radioOption;
ImGui::RadioButton("Show Scene", &radioOption, 0);
ImGui::SameLine();
ImGui::RadioButton("Show UI", &radioOption, 1);
if (radioOption == 0)
{
s_RenderScene = true;
s_RenderUI = false;
}
else if (radioOption == 1)
{
s_RenderScene = false;
s_RenderUI = true;
}
if (pastRadiooption != radioOption)
{
m_SelectedSceneEntity = entt::null;
s_CurrentGizmoOperation = ImGuizmo::BOUNDS;
pastRadiooption = radioOption;
}
ImGui::Separator();
const char* components[] = { "MeshComponent", "SpriteComponent", "AnimationComponent", "ScriptComponent" };
static bool toggles[] = { false, false, false, false }; // For toggle widget
if (m_SelectedSceneEntity != entt::null)
{
for (int i = 0; i < IM_ARRAYSIZE(components); i++)
{
toggles[i] = false; // Reset previous state
if (components[i] == "MeshComponent" && registry.has<MeshComponent>(m_SelectedSceneEntity))
toggles[i] = true;
if (components[i] == "SpriteComponent" && registry.has<SpriteComponent>(m_SelectedSceneEntity))
toggles[i] = true;
if (components[i] == "AnimationComponent" && registry.has<AnimationComponent>(m_SelectedSceneEntity))
toggles[i] = true;
if (components[i] == "ScriptComponent" && registry.has<ScriptComponent>(m_SelectedSceneEntity))
toggles[i] = true;
}
// Always show TransformComponent
auto& transform = registry.get<TransformComponent>(m_SelectedSceneEntity);
ImGuizmo::DecomposeMatrixToComponents(glm::value_ptr(transform.ModelMatrix), glm::value_ptr(transform.Position), glm::value_ptr(transform.Rotation), glm::value_ptr(transform.Scale));
ImGui::InputFloat3("Translate", glm::value_ptr(transform.Position));
ImGui::InputFloat3("Rotate", glm::value_ptr(transform.Rotation));
ImGui::InputFloat3("Scale", glm::value_ptr(transform.Scale));
ImGuizmo::RecomposeMatrixFromComponents(glm::value_ptr(transform.Position), glm::value_ptr(transform.Rotation), glm::value_ptr(transform.Scale), glm::value_ptr(transform.ModelMatrix));
ImGui::NewLine();
// Show padding options for UI canvas widget
//if (registry.has<CanvasWidgetComponent>(m_SelectedSceneEntity))
//{
// //auto& relationship = registry.get<RelationshipComponent>(m_SelectedSceneEntity);
// static float padding[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; // left, right, top, bottom
// ImGui::InputFloat4("Padding", padding);
// static int dimensions[2] = { 1, 1 };
// ImGui::InputInt2("Rows x Columns", dimensions);
// static float cellWidgetSize[2] = { 50.0f, 50.0f };
// ImGui::InputFloat2("Cell Widget Size", cellWidgetSize);
// if (ImGui::Button("Create")) // Create canvas matrix widget
// CreateCanvasMatrixWidget(dimensions, padding, cellWidgetSize, m_SelectedSceneEntity);
//}
//// Show text input for widget's text
//if (registry.has<TextWidgetComponent>(m_SelectedSceneEntity))
//{
// static entt::entity previousEntity;
// static char buf[64] = "";
// auto& text = registry.get<TextWidgetComponent>(m_SelectedSceneEntity);
// if (previousEntity != m_SelectedSceneEntity)
// memset(buf, 0, 64 * sizeof(char));
// if (ImGui::InputText("Text", buf, 64))
// text.Text = std::string(buf);
// previousEntity = m_SelectedSceneEntity;
// ImGui::NewLine();
//}
if (ImGui::RadioButton("Local", s_CurrentGizmoMode == ImGuizmo::LOCAL))
s_CurrentGizmoMode = ImGuizmo::LOCAL;
ImGui::SameLine();
if (ImGui::RadioButton("World", s_CurrentGizmoMode == ImGuizmo::WORLD))
s_CurrentGizmoMode = ImGuizmo::WORLD;
ImGui::NewLine();
if (ImGui::IsKeyPressed((int)KEY_S))
s_UseSnap = !s_UseSnap;
ImGui::PushID(0);
ImGui::Checkbox("", &s_UseSnap);
ImGui::PopID();
ImGui::SameLine();
switch (s_CurrentGizmoOperation)
{
case ImGuizmo::TRANSLATE:
ImGui::InputFloat3("Snap", &s_Snap[0]);
break;
case ImGuizmo::ROTATE:
ImGui::InputFloat("Angle Snap", &s_Snap[1]);
break;
case ImGuizmo::SCALE:
ImGui::InputFloat("Scale Snap", &s_Snap[2]);
break;
}
ImGui::Checkbox("Bound Sizing", &s_BoundSizing);
if (s_BoundSizing)
{
ImGui::PushID(1);
ImGui::Checkbox("", &s_BoundSizingSnap);
ImGui::SameLine();
ImGui::InputFloat3("Snap", s_BoundsSnap);
ImGui::PopID();
}
ImGui::Separator();
for (int i = 0; i < IM_ARRAYSIZE(components); ++i)
{
if (toggles[i])
{
if (components[i] == "MeshComponent")
{
ImGui::Checkbox("Show Bounding Box", &s_RenderBoundingBox);
ImGui::Separator();
}
if (components[i] == "AnimationComponent")
{
auto view = registry.view<MeshComponent, AnimationComponent>();
for (auto entity : view)
{
auto& [mesh, animation] = view.get<MeshComponent, AnimationComponent>(entity);
if (entity == m_SelectedSceneEntity)
{
static std::string firstAnimationName = "None"; // Keep track of selected entity's first animation name in order to show it in Combo preview
static std::string currentAnimationName = animation.AnimationNameVec[0];
if (firstAnimationName != animation.AnimationNameVec[0])
{
firstAnimationName = animation.AnimationNameVec[0];
currentAnimationName = firstAnimationName;
}
if (ImGui::BeginCombo("Animation Names", currentAnimationName.c_str())) // The second parameter is the label previewed before opening the combo.
{
for (uint32_t i = 0; i < animation.AnimationNameVec.size(); ++i)
{
bool isSelected = (currentAnimationName == animation.AnimationNameVec[i]);
if (ImGui::Selectable(animation.AnimationNameVec[i].c_str(), isSelected))
currentAnimationName = animation.AnimationNameVec[i];
if (isSelected)
ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo
}
ImGui::EndCombo();
}
if (ImGui::Button("Start Animation"))
{
animation.RunningAnimationName = currentAnimationName;
animation.IsAnimationRunning = true;
animation.AnimationMap[currentAnimationName].AnimationStartingTime = Time::CurrentRealTime();
}
ImGui::SameLine();
if (ImGui::Button("Stop Animation"))
{
animation.IsAnimationRunning = false;
animation.RunningAnimationName = "None";
}
}
}
ImGui::Separator();
}
if (components[i] == "ScriptComponent")
{
static std::string scriptFilePath = "Script: None";
static entt::entity previousEntity = m_SelectedSceneEntity;
if (previousEntity != m_SelectedSceneEntity)
{
if (registry.has<ScriptComponent>(m_SelectedSceneEntity))
{
auto& scriptComponent = registry.get<ScriptComponent>(m_SelectedSceneEntity);
scriptFilePath = scriptComponent.ScriptFilePath;
}
else
{
scriptFilePath = "Script: None";
}
previousEntity = m_SelectedSceneEntity;
}
ImGui::Text(scriptFilePath.c_str());
if (ImGui::Button("Select Script"))
ShowFileDialogBox("Open", scriptFilePath);
ImGui::SameLine();
if (ImGui::Button("Attach Script"))
{
auto& scriptComponent = registry.get<ScriptComponent>(m_SelectedSceneEntity);
auto& entityTagComponent = registry.get<EntityTagComponent>(m_SelectedSceneEntity);
scriptComponent.ScriptFilePath = scriptFilePath;
//Entity entity(m_SelectedSceneEntity, entityTagComponent.Name, m_Scene.get());
//m_ScriptEngine->AttachScript(scriptFilePath, entity);
m_ScriptEngine->AttachScript(scriptFilePath, m_SelectedSceneEntity);
}
ImGui::Separator();
}
if (components[i] == "SpriteComponent")
{
auto view = registry.view<SpriteComponent>();
if (m_SelectedSceneEntity != entt::null)
{
auto& sprite = registry.get<SpriteComponent>(m_SelectedSceneEntity);
auto& texture = sprite.Texture;
ImGui::Text("Texture:");
ImGui::Image((void*)texture.GetId(), ImVec2(80.0f, 80.0f), ImVec2(0, 0), ImVec2(1, 1));
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("Import Asset"))
{
char* payloadData = (char*)payload->Data;
std::string assetFilePath(payloadData);
if (ResourceManager::HasTexture(assetFilePath))
{
texture = ResourceManager::GetTexture(assetFilePath);
}
else
{
ResourceManager::AddTexture(assetFilePath, Texture(assetFilePath));
texture = ResourceManager::GetTexture(assetFilePath);
}
sprite.HasTexture = true;
}
ImGui::EndDragDropTarget();
}
ImGui::Separator();
ImGui::Text("Color:");
static ImVec4 color = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
static ImVec4 ref_color_v(1.0f, 1.0f, 1.0f, 1.0f);
ImGuiColorEditFlags flags =
ImGuiColorEditFlags_AlphaPreview |
ImGuiColorEditFlags_AlphaBar |
ImGuiColorEditFlags_DisplayRGB |
ImGuiColorEditFlags_DisplayHex;
if (ImGui::ColorPicker4("My Color", (float*)&color, flags, &ref_color_v.x))
{
//if (registry.has<TextWidgetComponent>(m_SelectedSceneEntity))
//{
// auto& text = registry.get<TextWidgetComponent>(m_SelectedSceneEntity);
// text.Color = glm::vec4(color.x, color.y, color.z, color.w);
//}
//else
//{
// sprite.Color = glm::vec4(color.x, color.y, color.z, color.w);
//}
}
ImGui::Separator();
}
}
}
}
if (ImGui::Button("Add Component"))
ImGui::OpenPopup("addComponentPopup");
ImGui::SameLine();
if (ImGui::BeginPopup("addComponentPopup"))
{
for (int i = 0; i < IM_ARRAYSIZE(components); i++)
{
if (ImGui::MenuItem(components[i], "", &toggles[i]))
{
if (components[i] == "MeshComponent")
{
if (toggles[i])
{
auto& entityTag = registry.get<EntityTagComponent>(m_SelectedSceneEntity);
auto& [loadedMesh, loadedAnimation] = ModelImporter::LoadMeshFile(entityTag.AssetFilePath);
auto& mesh = registry.emplace<MeshComponent>(m_SelectedSceneEntity, *loadedMesh);
MeshRenderer::Submit(mesh);
}
else
{
registry.remove<MeshComponent>(m_SelectedSceneEntity);
}
}
if (components[i] == "SpriteComponent")
{
if (toggles[i])
{
auto& sprite = registry.emplace<SpriteComponent>(m_SelectedSceneEntity);
SpriteRenderer::Submit(sprite);
}
else
{
registry.remove<SpriteComponent>(m_SelectedSceneEntity);
}
}
if (components[i] == "AnimationComponent")
{
if (toggles[i])
registry.emplace<AnimationComponent>(m_SelectedSceneEntity);
else
registry.remove<AnimationComponent>(m_SelectedSceneEntity);
}
if (components[i] == "ScriptComponent")
{
if (toggles[i])
{
registry.emplace<ScriptComponent>(m_SelectedSceneEntity);
}
else
{
registry.remove<ScriptComponent>(m_SelectedSceneEntity);
}
}
}
}
ImGui::EndPopup();
}
}
ImGui::End();
}
void Editor::ShowHierarchyWindow(entt::registry& registry)
{
if (ImGui::Begin("Hierarchy", NULL))
{
using TraverseFun = std::function<void(entt::entity)>;
static uint32_t selection = 0;
uint32_t rootId = 1;
static uint32_t nodeClicked = 0;
ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen;
if (selection == rootId)
nodeFlags |= ImGuiTreeNodeFlags_Selected;
const char* sceneName;
sceneName = m_SceneInfo.SceneName.c_str();
bool rootNodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)rootId, nodeFlags, sceneName);
if (ImGui::IsItemClicked())
{
nodeClicked = rootId;
m_SelectedSceneEntity = entt::null;
}
if (ImGui::IsItemClicked(1))
ImGui::OpenPopup(std::to_string(rootId).c_str());
ShowHierarchyMenuPopup(entt::null, registry);
auto view = registry.view<RelationshipComponent, EntityTagComponent>();
TraverseFun traverse = [&](entt::entity entity) {
auto& tag = view.get<EntityTagComponent>(entity);
/*
Bug is triggered in the following situation:
If I get relationship by reference, then there shouldn't be any new entity added to the registry.
If it isn't the case, then relationship reference has trash values for parent entity as well as number of children value;
In the line "ShowHierarchyMenuPopup(entity);" a new entity is added, thus registry is changed;
Because of that I return relationship by value (anyway I don't have to modify relationship in this method);
*/
auto relationship = view.get<RelationshipComponent>(entity);
if (relationship.NumOfChildren == 0) // Leaf node
{
ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen;
const char* entityTag;
entityTag = tag.Name.c_str();
uint32_t entityId = rootId + (uint32_t)entity + 1;
if (selection == entityId)
nodeFlags |= ImGuiTreeNodeFlags_Selected;
ImGui::TreeNodeEx((void*)(uintptr_t)entityId, nodeFlags, entityTag);
if (ImGui::IsItemClicked())
{
m_SelectedSceneEntity = entity;
if (s_CurrentGizmoOperation == ImGuizmo::BOUNDS)
s_CurrentGizmoOperation = ImGuizmo::TRANSLATE;
}
if (ImGui::IsItemClicked(1))
ImGui::OpenPopup(std::to_string(entityId).c_str());
ShowHierarchyMenuPopup(entity, registry);
}
else
{
ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen;
uint32_t entityId = rootId + (uint32_t)entity + 1;
if (selection == entityId)
nodeFlags |= ImGuiTreeNodeFlags_Selected;
const char* entityTag;
entityTag = tag.Name.c_str();
bool rootNodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)entityId, nodeFlags, entityTag);
if (ImGui::IsItemClicked())
{
m_SelectedSceneEntity = entity;
if (s_CurrentGizmoOperation == ImGuizmo::BOUNDS)
s_CurrentGizmoOperation = ImGuizmo::TRANSLATE;
}
if (ImGui::IsItemClicked(1))
ImGui::OpenPopup(std::to_string(entityId).c_str());
ShowHierarchyMenuPopup(entity, registry);
if (rootNodeOpen)
{
auto relationship = view.get<RelationshipComponent>(entity);
for (auto child : relationship.Children)
traverse(child);
ImGui::TreePop();
}
}
};
if (rootNodeOpen)
{
ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()); // Increase spacing to differentiate leaves from expanded contents.
auto view = registry.view<RelationshipComponent, EntityTagComponent, TransformComponent>();
for (auto entity : view)
{
auto& relationship = view.get<RelationshipComponent>(entity);
if (relationship.Parent == entt::null) // Recursive traverse only if entity's parent is root node (entt::null)
traverse(entity);
}
// Nodes will be selected either by clicking on it or by clicking on model in scene
if (m_SelectedSceneEntity != entt::null)
nodeClicked = (uint32_t)m_SelectedSceneEntity + 2; // 0 and 1 are already reserved => Id = 0 for entt::null, Id = 1 for root node (scene name)
else
if (nodeClicked != rootId) nodeClicked = 0;
selection = nodeClicked;
ImGui::PopStyleVar();
ImGui::TreePop();
}
}
ImGui::End();
}
void Editor::ShowSceneWindow()
{
ImGui::Begin("Scene", NULL);
m_IsSceneWindowFocused = ImGui::IsWindowFocused();
/*
Keep track of Scene Window's width and height;
If scene window is resized, then Framebuffer (where scene is rendered) needs to be resized too
*/
float sceneWindowWidth = ImGui::GetWindowContentRegionMax().x - ImGui::GetWindowContentRegionMin().x;
float sceneWindowHeight = ImGui::GetWindowContentRegionMax().y - ImGui::GetWindowContentRegionMin().y;
UpdateSceneViewport(sceneWindowWidth, sceneWindowHeight); // Update Framebuffer's size and viewport
// xPadding and yPadding are distances between scene framebuffer texture and scene ImGui window;
float xPadding = (ImGui::GetWindowSize().x - m_SceneInfo.SceneWidth) * 0.5f;
float yPadding = (ImGui::GetWindowSize().y + ImGui::GetItemRectSize().y - m_SceneInfo.SceneHeight) * 0.5f;
ImGui::SetCursorPos(ImVec2(xPadding, yPadding));
//ImGui::Image((void*)m_Texture->GetId(), ImVec2((float)m_SceneInfo.SceneWidth, (float)m_SceneInfo.SceneHeight), ImVec2(0, 1), ImVec2(1, 0));
ImGui::Image((void*)m_IntermediateTexture->GetId(), ImVec2((float)m_SceneInfo.SceneWidth, (float)m_SceneInfo.SceneHeight), ImVec2(0, 1), ImVec2(1, 0)); // temp
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("Import Asset"))
{
char* payloadData = (char*)payload->Data;
std::string strPayloadData(payloadData);
ImportAssetEvent importAssetEvent(strPayloadData);
Dispatcher::Publish(importAssetEvent);
}
ImGui::EndDragDropTarget();
}
float scenePosMinX = ImGui::GetWindowPos().x + xPadding;
float scenePosMinY = ImGui::GetWindowPos().y + yPadding;
float scenePosMaxX = scenePosMinX + m_SceneInfo.SceneWidth;
float scenePosMaxY = scenePosMinY + m_SceneInfo.SceneHeight;
ImVec2 scenePosMin = ImVec2(scenePosMinX, scenePosMinY);
ImVec2 scenePosMax = ImVec2(scenePosMaxX, scenePosMaxY);
// Relative to Scene Framebuffer
m_SceneInfo.ScenePosMin = glm::vec2(scenePosMinX, scenePosMinY);
m_SceneInfo.ScenePosMax = glm::vec2(scenePosMaxX, scenePosMaxY);
// Relative to Scene Framebuffer
m_MouseInfo.MousePosX = ImGui::GetMousePos().x - ImGui::GetWindowPos().x - xPadding;
m_MouseInfo.MousePosY = ImGui::GetMousePos().y - ImGui::GetWindowPos().y - yPadding;
if (ImGui::IsMouseHoveringRect(scenePosMin, scenePosMax))
m_IsSceneWindowHovered = true;
else
m_IsSceneWindowHovered = false;
if (m_SelectedSceneEntity != entt::null)
{
if (s_RenderScene)
{
auto& transform = m_Scene->m_Registry.get<TransformComponent>(m_SelectedSceneEntity);
auto& camera = m_Scene->GetCamera();
ShowImGuizmoWidget(transform, camera.Projection, camera.View);
}
else if (s_RenderUI)
{
//auto& transform = m_UserInterface->m_Registry.get<TransformComponent>(m_SelectedSceneEntity);
//auto& camera = m_UserInterface->GetCamera();
//
//ShowImGuizmoWidget(transform, camera.Projection, glm::mat4(1.0f));
}
}
ImGui::End();
ImGui::Begin("Scene Commands");
if (ImGui::Button("Play Scene"))
{
s_PlayMode = true;
if (m_SelectedSceneEntity != entt::null)
m_SelectedSceneEntity = entt::null;
CreateGameWindow();
m_ScriptEngine->OnStart(m_GameWindow->m_Scene.get(), m_GameWindow->m_UserInterface.get(), m_GameWindow.get());
}
ImGui::SameLine();
if (ImGui::Button("Stop Scene"))
{
s_PlayMode = false;
m_ScriptEngine->OnStop();
m_GameWindow->OnShutdown();
UserInput::SetGLFWwindow(m_MainWindow->m_GLFWwindow);
}
ImGui::End();
}
void Editor::ShowImGuizmoWidget(TransformComponent& transform, const glm::mat4& projectionMatrix, const glm::mat4& viewMatrix)
{
ImGuizmo::BeginFrame();
ImGuizmo::SetOrthographic(true);
if (ImGui::IsKeyDown((int)KEY_LEFT_CONTROL) && ImGui::IsKeyPressed((int)KEY_T))
s_CurrentGizmoOperation = ImGuizmo::TRANSLATE;
if (ImGui::IsKeyDown((int)KEY_LEFT_CONTROL) && ImGui::IsKeyPressed((int)KEY_R))
s_CurrentGizmoOperation = ImGuizmo::ROTATE;
if (ImGui::IsKeyDown((int)KEY_LEFT_CONTROL) && ImGui::IsKeyPressed((int)KEY_Y))
s_CurrentGizmoOperation = ImGuizmo::SCALE;
ImGuizmo::SetDrawlist();
ImGuizmo::SetRect(
m_SceneInfo.ScenePosMin.x,
m_SceneInfo.ScenePosMin.y,
(float)m_SceneInfo.SceneWidth,
(float)m_SceneInfo.SceneHeight
);
ImGuizmo::Manipulate(
glm::value_ptr(viewMatrix),
glm::value_ptr(projectionMatrix),
s_CurrentGizmoOperation,
s_CurrentGizmoMode,
glm::value_ptr(transform.ModelMatrix),
NULL,
s_UseSnap ? &s_Snap[0] : NULL,
s_BoundSizing ? s_Bounds : NULL,
s_BoundSizingSnap ? s_BoundsSnap : NULL
);
// Update delta position and matrix components (position, rotation, scale) after guizmo manipulation
float position[3];
float rotation[3];
float scale[3];
ImGuizmo::DecomposeMatrixToComponents(glm::value_ptr(transform.ModelMatrix), position, rotation, scale);
auto deltaPosition = glm::vec3(position[0] - transform.Position.x, position[1] - transform.Position.y, position[2] - transform.Position.z); // Capture the amount by which this widget has been moved
// Update delta position for all children
if (s_RenderScene)
{
auto view = m_Scene->m_Registry.view<RelationshipComponent, TransformComponent>();
using TraverseFun = std::function<void(entt::entity)>;
TraverseFun traverse = [&](entt::entity entity) {
auto& relationship = view.get<RelationshipComponent>(entity);
for (auto child : relationship.Children)
{
auto& childTransform = view.get<TransformComponent>(child);
//childTransform.DeltaPosition = transform.DeltaPosition;
childTransform.DeltaPosition = deltaPosition;
}
for (auto child : relationship.Children)
{
traverse(child);
}
};
traverse(m_SelectedSceneEntity);
}
else if (s_RenderUI)
{
//auto view = m_UserInterface->m_Registry.view<RelationshipComponent, TransformComponent>();
//using TraverseFun = std::function<void(entt::entity)>;
//TraverseFun traverse = [&](entt::entity entity) {
// auto& relationship = view.get<RelationshipComponent>(entity);
// for (auto child : relationship.Children)
// {
// auto& childTransform = view.get<TransformComponent>(child);
// //childTransform.DeltaPosition = transform.DeltaPosition;
// childTransform.DeltaPosition = deltaPosition;
// }
// for (auto child : relationship.Children)
// {
// traverse(child);
// }
//};
//traverse(m_SelectedSceneEntity);
}
}
void Editor::ShowFileDialogBox(const std::string& option, std::string& fullPath)
{
OPENFILENAMEA ofn; // common dialog box structure
char filePath[260]; // buffer for file path
HWND hwnd; // owner window
HANDLE hf; // file handle
// Initialize OPENFILENAMEA
memset(&ofn, 0, sizeof(ofn));
memset(&hwnd, 0, sizeof(hwnd));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = filePath;
/*
Set lpstrFile[0] to '\0' so that GetOpenFileName does not
use the contents of szFile to initialize itself.
*/
ofn.lpstrFile[0] = '\0';
if (option == "Save As")
{
ofn.nMaxFile = sizeof(filePath);
ofn.lpstrFilter = "*.json\0";
}
ofn.nMaxFile = sizeof(filePath);
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (option == "Save As")
{
// Display the Save As dialog box.
if (GetSaveFileNameA(&ofn))
{
std::string strFilePath(ofn.lpstrFile);
std::string strFileExtension(ofn.lpstrFilter);
//std::string strFileName = FileSystem::FilePath(strFilePath + strFileExtension.substr(1)).filename().string();
fullPath = strFilePath + strFileExtension.substr(1);
}
}
if (option == "Open")
{
// Display the Open file dialog box.
if (GetOpenFileNameA(&ofn))
{
std::string strFilePath(ofn.lpstrFile);
//std::string strFileName = FileSystem::FilePath(strFilePath).filename().string();
fullPath = strFilePath;
}
}
}
void Editor::ShowFolderMenuPopup(const std::string& folderPath)
{
static char newFolderName[32] = "";
std::string menuAction = "";
if (ImGui::BeginPopup(folderPath.c_str()))
{
if (ImGui::MenuItem("New")) { menuAction = "New"; }
if (ImGui::MenuItem("Delete")) { menuAction = "Delete"; }
if (ImGui::MenuItem("Cancel")) { menuAction = "Cancel"; }
ImGui::EndPopup();
}
ImGui::PushID(folderPath.c_str());
if (menuAction == "New") { ImGui::OpenPopup("New"); }
if (menuAction == "Delete") { ImGui::OpenPopup("Delete"); }
if (menuAction == "Cancel") {}
if (ImGui::BeginPopup("New"))
{
ImGui::Text("Enter new folder name:");
ImGui::InputText("##folderName", newFolderName, IM_ARRAYSIZE(newFolderName));
if (ImGui::Button("OK"))
{
FileSystem::CreateNewFolder(folderPath + "\\" + newFolderName);
memset(newFolderName, 0, 32 * sizeof(newFolderName[0]));
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Cancel"))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
if (ImGui::BeginPopup("Delete"))
{
ImGui::Text("Are you sure you want to delete this folder?");
ImGui::MenuItem("***before deleting click arrow to close folder***", NULL, false, false);
if (ImGui::Button("OK"))
{
FileSystem::Delete(folderPath);
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Cancel"))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
ImGui::PopID();
}
void Editor::ShowHierarchyMenuPopup(entt::entity node, entt::registry& registry)
{
std::string stringNodeId;
bool isSceneRootNode = false;
if (node == entt::null)
{
isSceneRootNode = true;
stringNodeId = std::to_string(1);
}
else
{
stringNodeId = std::to_string((uint32_t)node + 2);
}
static char newUiWidgetName[32] = "";
static char newSpriteName[32] = "";
std::string menuAction = "";
if (ImGui::BeginPopup(stringNodeId.c_str()))
{
if (ImGui::BeginMenu("New"))
{
//if (ImGui::MenuItem("Canvas")) CreateWidget("Canvas", node);
//if (ImGui::MenuItem("Button")) CreateWidget("Button", node);
//if (ImGui::MenuItem("Text")) CreateWidget("Text", node);
if (ImGui::MenuItem("Entity"))
{
auto newEntity = m_Scene->CreateEntity();
auto& tag = newEntity.AddComponent<EntityTagComponent>();
tag.Name = "Entity" + std::to_string(static_cast<int>(newEntity.GetEnttEntity()));
auto& transform = newEntity.AddComponent<TransformComponent>();
auto& relationship = newEntity.AddComponent<RelationshipComponent>();
relationship.Parent = entt::null;
}
ImGui::EndMenu();
}
if (!isSceneRootNode && ImGui::MenuItem("Rename")) { menuAction = "Rename"; }
if (!isSceneRootNode && ImGui::MenuItem("Copy")) { menuAction = "Copy"; }
if (!isSceneRootNode && ImGui::MenuItem("Delete")) { menuAction = "Delete"; }
if (ImGui::MenuItem("Cancel")) { menuAction = "Cancel"; }
ImGui::EndPopup();
}
ImGui::PushID(stringNodeId.c_str());
if (menuAction == "Sprite") { ImGui::OpenPopup("Sprite"); }
if (menuAction == "Rename") { ImGui::OpenPopup("Rename"); }
if (menuAction == "Copy") { CreateCopyEntity(node); }
if (menuAction == "Delete") { ImGui::OpenPopup("Delete"); }
if (menuAction == "Cancel") {}
if (ImGui::BeginPopup("Sprite"))
{
ImGui::Text("Enter sprite's name:");
ImGui::InputText("##spriteName", newSpriteName, IM_ARRAYSIZE(newSpriteName));
if (ImGui::Button("OK"))
{
auto newEntity = m_Scene->CreateEntity();
//auto newEntity = m_UserInterface->CreateWidget();
auto& tag = newEntity.AddComponent<EntityTagComponent>();
auto& transform = newEntity.AddComponent<TransformComponent>();
auto& relationship = newEntity.AddComponent<RelationshipComponent>();
auto& sprite = newEntity.AddComponent<SpriteComponent>();
transform.Position = glm::vec3(0.0f, 0.0f, 0.0f);
transform.Rotation = glm::vec3(0.0f, 0.0f, 0.0f);
transform.Scale = glm::vec3(100.0f, 100.0f, 1.0f);
tag.Name = newSpriteName;
relationship.Parent = node;
SpriteRenderer::Submit(sprite);
if (node != entt::null)
{
//auto& parentRelationship = m_Scene->m_Registry.get<RelationshipComponent>(node);
auto& parentRelationship = registry.get<RelationshipComponent>(node);
parentRelationship.Children.push_back(newEntity.GetEnttEntity());
parentRelationship.NumOfChildren++;
}
memset(newSpriteName, 0, 32 * sizeof(newSpriteName[0]));
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Cancel"))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
if (ImGui::BeginPopup("Rename"))
{
ImGui::Text("Enter new name:");
ImGui::InputText("##name", newSpriteName, IM_ARRAYSIZE(newSpriteName));
if (ImGui::Button("OK"))
{
//auto& tag = m_Scene->m_Registry.get<EntityTagComponent>(node);
auto& tag = registry.get<EntityTagComponent>(node);
tag.Name = newSpriteName;
memset(newSpriteName, 0, 32 * sizeof(newSpriteName[0]));
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Cancel"))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
if (ImGui::BeginPopup("Delete"))
{
ImGui::Text("Are you sure you want to delete this game object?");
ImGui::MenuItem("", NULL, false, false);
using TraverseFun = std::function<void(entt::entity)>;
if (ImGui::Button("OK"))
{
// If entity is selected, then unselect it in order to delete it (this way there won't be any bugs)
if (m_SelectedSceneEntity != entt::null)
m_SelectedSceneEntity = entt::null;
TraverseFun Traverse = [&](entt::entity entity) {
//auto relationship = m_Scene->m_Registry.get<RelationshipComponent>(entity);
auto relationship = registry.get<RelationshipComponent>(entity);
for (auto child : relationship.Children)
Traverse(child);
//m_Scene->m_Registry.destroy(entity);
registry.destroy(entity);
if (relationship.Parent != entt::null)
{
//auto& parentRelationship = m_Scene->m_Registry.get<RelationshipComponent>(relationship.Parent);
auto& parentRelationship = registry.get<RelationshipComponent>(relationship.Parent);
uint32_t index = 0;
for (auto child : parentRelationship.Children)
{
if (child == node)
{
parentRelationship.Children.erase(parentRelationship.Children.begin() + index);
parentRelationship.NumOfChildren--;
break;
}
index++;
}
}
};
Traverse(node);
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Cancel"))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
ImGui::PopID();
}
void Editor::CreateWidget(const std::string& name, entt::entity parent)
{
auto newWidget = m_Scene->CreateEntity();
//auto newWidget = m_UserInterface->CreateWidget();
auto& tag = newWidget.AddComponent<EntityTagComponent>();
auto& transform = newWidget.AddComponent<TransformComponent>();
auto& relationship = newWidget.AddComponent<RelationshipComponent>();
auto& sprite = newWidget.AddComponent<SpriteComponent>();
if (name == "Canvas")
//newWidget.AddComponent<CanvasWidgetComponent>();
if (name == "Button")
//newWidget.AddComponent<ButtonWidgetComponent>();
if (name == "Text")
//newWidget.AddComponent<TextWidgetComponent>();
tag.Name = name;
relationship.Parent = parent;
SpriteRenderer::Submit(sprite);
if (parent != entt::null)
{
auto& parentTransform = m_Scene->m_Registry.get<TransformComponent>(parent);
//auto& parentTransform = m_UserInterface->m_Registry.get<TransformComponent>(parent);
transform.Position = parentTransform.Position;
transform.Rotation = parentTransform.Rotation;
if (name == "Text")
transform.Position.x += parentTransform.Scale.x / 2.0f; // Pass center position so text can be rendered at centered position compared to parent widget
auto& parentRelationship = m_Scene->m_Registry.get<RelationshipComponent>(parent);
//auto& parentRelationship = m_UserInterface->m_Registry.get<RelationshipComponent>(parent);
parentRelationship.Children.push_back(newWidget.GetEnttEntity());
parentRelationship.NumOfChildren++;
}
else
{
transform.Position = glm::vec3(0.0f, 0.0f, 0.0f);
transform.Rotation = glm::vec3(0.0f, 0.0f, 0.0f);
}
if (name == "Text")
transform.Scale = glm::vec3(1.0f, 1.0f, 1.0f);
else
transform.Scale = glm::vec3(100.0f, 100.0f, 1.0f);
}
void Editor::CreateCanvasMatrixWidget(int dimensions[2], float padding[4], float cellWidgetSize[2], entt::entity parent)
{
int rows = dimensions[0];
int columns = dimensions[1];
float paddingLeft = padding[0];
float paddingRight = padding[1];
float paddingTop = padding[2];
float paddingBottom = padding[3];
float cellWidgetWidth = cellWidgetSize[0];
float cellWidgetHeight = cellWidgetSize[1];
float widgetWidth = paddingLeft + paddingRight + (columns - 1) * paddingLeft + columns * cellWidgetWidth;
float widgetHeight = paddingTop + paddingBottom + (rows - 1) * paddingTop + rows * cellWidgetHeight;
for (int row = 0; row < rows; ++row)
{
for (int column = 0; column < columns; ++column)
{
// Cell canvas widget is a slot (placeholder) for widgets such as buttons
auto canvas = m_Scene->CreateEntity();
//auto& cellWidgetCanvas = canvas.AddComponent<CanvasWidgetComponent>();
auto& cellWidgetRelationship = canvas.AddComponent<RelationshipComponent>();
auto& cellWidgetSprite = canvas.AddComponent<SpriteComponent>();
auto& cellWidgetTransform = canvas.AddComponent<TransformComponent>();
auto& entityTagComponent = canvas.AddComponent<EntityTagComponent>();
entityTagComponent.Name = "Canvas";
cellWidgetSprite.Color = glm::vec4(0.8f, 0.8f, 0.8f, 0.7f);
SpriteRenderer::Submit(cellWidgetSprite);
auto& transform = m_Scene->m_Registry.get<TransformComponent>(parent);
if (column == 0)
cellWidgetTransform.Position.x = transform.Position.x + paddingLeft;
else
cellWidgetTransform.Position.x = transform.Position.x + (column + 1) * paddingLeft + column * cellWidgetWidth;
if (row == 0)
cellWidgetTransform.Position.y = transform.Position.y - paddingTop;
else
cellWidgetTransform.Position.y = transform.Position.y - (row + 1) * paddingTop - row * cellWidgetHeight;
cellWidgetTransform.Scale.x = cellWidgetWidth;
cellWidgetTransform.Scale.y = cellWidgetHeight;
//cellWidgetRelationship.Parent = m_SelectedSceneEntity;
cellWidgetRelationship.Parent = parent;
auto& relationship = m_Scene->m_Registry.get<RelationshipComponent>(parent);
relationship.Children.push_back(canvas.GetEnttEntity());
relationship.NumOfChildren++;
}
}
auto& transform = m_Scene->m_Registry.get<TransformComponent>(parent);
transform.Scale.x = widgetWidth;
transform.Scale.y = widgetHeight;
ImGui::NewLine();
}
void Editor::CreateCopyEntity(entt::entity node) // Entity can have many children or none
{
using TraverseFun = std::function<void(entt::entity, entt::entity)>;
TraverseFun traverse = [&](entt::entity node, entt::entity copyNode) {
auto nodeRelationship = m_Scene->m_Registry.get<RelationshipComponent>(node); // Get by value because entt library change this component under the hood when new component is added to registry (TODO: Check this weird feature!)
for (auto child : nodeRelationship.Children)
{
auto copyEntity = m_Scene->m_Registry.create();
if (m_Scene->m_Registry.has<EntityTagComponent>(child))
m_Scene->m_Registry.emplace<EntityTagComponent>(copyEntity, m_Scene->m_Registry.get<EntityTagComponent>(child));
if (m_Scene->m_Registry.has<TransformComponent>(child))
m_Scene->m_Registry.emplace<TransformComponent>(copyEntity, m_Scene->m_Registry.get<TransformComponent>(child));
if (m_Scene->m_Registry.has<MeshComponent>(child))
m_Scene->m_Registry.emplace<MeshComponent>(copyEntity, m_Scene->m_Registry.get<MeshComponent>(child));
if (m_Scene->m_Registry.has<BoundBoxComponent>(child))
m_Scene->m_Registry.emplace<BoundBoxComponent>(copyEntity, m_Scene->m_Registry.get<BoundBoxComponent>(child));
if (m_Scene->m_Registry.has<SpriteComponent>(child))
m_Scene->m_Registry.emplace<SpriteComponent>(copyEntity, m_Scene->m_Registry.get<SpriteComponent>(child));
//if (m_Scene->m_Registry.has<CanvasWidgetComponent>(child))
// m_Scene->m_Registry.emplace<CanvasWidgetComponent>(copyEntity, m_Scene->m_Registry.get<CanvasWidgetComponent>(child));
//if (m_Scene->m_Registry.has<ButtonWidgetComponent>(child))
// m_Scene->m_Registry.emplace<ButtonWidgetComponent>(copyEntity, m_Scene->m_Registry.get<ButtonWidgetComponent>(child));
//if (m_Scene->m_Registry.has<TextWidgetComponent>(child))
// m_Scene->m_Registry.emplace<TextWidgetComponent>(copyEntity, m_Scene->m_Registry.get<TextWidgetComponent>(child));
auto& copyRelationship = m_Scene->m_Registry.emplace<RelationshipComponent>(copyEntity);
copyRelationship.Parent = copyNode; // copyNode is the parent of copyEntity
auto& copyParentRelationship = m_Scene->m_Registry.get<RelationshipComponent>(copyNode);
copyParentRelationship.Children.push_back(copyEntity);
copyParentRelationship.NumOfChildren++;
}
int index = 0;
auto& copyNodeRelationship = m_Scene->m_Registry.get<RelationshipComponent>(copyNode);
for (auto child : nodeRelationship.Children)
{
auto copyChild = copyNodeRelationship.Children[index];
traverse(child, copyChild);
index++;
}
};
// Create copy root (starting) node
auto copyNode = m_Scene->m_Registry.create();
auto& relationship = m_Scene->m_Registry.get<RelationshipComponent>(node);
if (relationship.Parent != entt::null) // If node's parent isn't scene root node
{
auto& parentRelationship = m_Scene->m_Registry.get<RelationshipComponent>(relationship.Parent);
parentRelationship.Children.push_back(copyNode); // Push copy node to parent's children
parentRelationship.NumOfChildren++;
}
if (m_Scene->m_Registry.has<EntityTagComponent>(node))
m_Scene->m_Registry.emplace<EntityTagComponent>(copyNode, m_Scene->m_Registry.get<EntityTagComponent>(node));
if (m_Scene->m_Registry.has<TransformComponent>(node))
m_Scene->m_Registry.emplace<TransformComponent>(copyNode, m_Scene->m_Registry.get<TransformComponent>(node));
if (m_Scene->m_Registry.has<MeshComponent>(node))
m_Scene->m_Registry.emplace<MeshComponent>(copyNode, m_Scene->m_Registry.get<MeshComponent>(node));
if (m_Scene->m_Registry.has<BoundBoxComponent>(node))
m_Scene->m_Registry.emplace<BoundBoxComponent>(copyNode, m_Scene->m_Registry.get<BoundBoxComponent>(node));
if (m_Scene->m_Registry.has<SpriteComponent>(node))
m_Scene->m_Registry.emplace<SpriteComponent>(copyNode, m_Scene->m_Registry.get<SpriteComponent>(node));
//if (m_Scene->m_Registry.has<CanvasWidgetComponent>(node))
// m_Scene->m_Registry.emplace<CanvasWidgetComponent>(copyNode, m_Scene->m_Registry.get<CanvasWidgetComponent>(node));
//if (m_Scene->m_Registry.has<ButtonWidgetComponent>(node))
// m_Scene->m_Registry.emplace<ButtonWidgetComponent>(copyNode, m_Scene->m_Registry.get<ButtonWidgetComponent>(node));
//if (m_Scene->m_Registry.has<TextWidgetComponent>(node))
// m_Scene->m_Registry.emplace<TextWidgetComponent>(copyNode, m_Scene->m_Registry.get<TextWidgetComponent>(node));
//auto& copyRelationship = m_Scene->m_Registry.emplace<RelationshipComponent>(copyNode, m_Scene->m_Registry.get<RelationshipComponent>(node));
auto& copyRelationship = m_Scene->m_Registry.emplace<RelationshipComponent>(copyNode);
copyRelationship.Parent = relationship.Parent;
traverse(node, copyNode);
}
/**
* @brief Create second window for "play" mode.
*
* This method creates second window, when user clicks "Play" button.
* This window will render the final look of a game, together with in-game UI.
*/
void Editor::CreateGameWindow()
{
Window::Hint(GLFW_DECORATED, true);
m_GameWindow->CreateGLFWwindow(NULL, m_MainWindow->m_GLFWwindow);
Window::s_CurrentActiveWindowName = m_GameWindow->GetWindowName();
Window::MakeContextCurrent(m_GameWindow->m_GLFWwindow);
m_GameWindow->m_UserInterface->OnStart();
//glfwSetWindowAspectRatio(m_GameWindow->m_GLFWwindow, m_GameWindow->m_Width, m_GameWindow->m_Height);
m_GameWindow->SetEventCallbacks();
m_MainWindow->RemoveEventCallbacks();
UserInput::SetGLFWwindow(m_GameWindow->m_GLFWwindow);
m_GameWindow->ShowWindow();
auto& fromRegistry = m_Scene->m_Registry;
auto& toRegistry = m_GameWindow->m_Scene->m_Registry;
toRegistry.clear();
m_Scene->m_CloneFunctions[entt::type_hash<TransformComponent>::value()] = &Scene::CloneRegistry<TransformComponent>;
m_Scene->m_CloneFunctions[entt::type_hash<RelationshipComponent>::value()] = &Scene::CloneRegistry<RelationshipComponent>;
m_Scene->m_CloneFunctions[entt::type_hash<EntityTagComponent>::value()] = &Scene::CloneRegistry<EntityTagComponent>;
m_Scene->m_CloneFunctions[entt::type_hash<BoundBoxComponent>::value()] = &Scene::CloneRegistry<BoundBoxComponent>;
m_Scene->m_CloneFunctions[entt::type_hash<MeshComponent>::value()] = &Scene::CloneRegistry<MeshComponent>;
m_Scene->m_CloneFunctions[entt::type_hash<SpriteComponent>::value()] = &Scene::CloneRegistry<SpriteComponent>;
m_Scene->m_CloneFunctions[entt::type_hash<AnimationComponent>::value()] = &Scene::CloneRegistry<AnimationComponent>;
m_Scene->m_CloneFunctions[entt::type_hash<CameraComponent>::value()] = &Scene::CloneRegistry<CameraComponent>;
m_Scene->m_CloneFunctions[entt::type_hash<ScriptComponent>::value()] = &Scene::CloneRegistry<ScriptComponent>;
//m_Scene->m_CloneFunctions[entt::type_hash<TextWidgetComponent>::value()] = &Scene::CloneRegistry<TextWidgetComponent>;
//m_Scene->m_CloneFunctions[entt::type_hash<CanvasWidgetComponent>::value()] = &Scene::CloneRegistry<CanvasWidgetComponent>;
//m_Scene->m_CloneFunctions[entt::type_hash<ButtonWidgetComponent>::value()] = &Scene::CloneRegistry<ButtonWidgetComponent>;
// Create entities with same id as entities in m_Scene
fromRegistry.each([&toRegistry](auto entity)
{
auto copyEntity = toRegistry.create(entity);
}
);
// Iterate over all components of m_Editor->m_Scene and copy components to m_GameWindow->m_Scene
m_Scene->m_Registry.visit([this, &fromRegistry, &toRegistry](const auto componentType)
{
m_Scene->m_CloneFunctions[componentType.hash()](fromRegistry, toRegistry);
}
);
auto view = m_GameWindow->m_Scene->GetView<MeshComponent>();
for (auto entity : view)
{
auto& mesh = view.get<MeshComponent>(entity);
MeshRenderer::SubmitCopy(mesh);
}
Window::MakeContextCurrent(m_MainWindow->m_GLFWwindow);
}
/**
* @brief Create a frame buffer.
*
* This method creates frame buffer, which will be used for Scene window in editor.
*/
void Editor::CreateFrameBuffer(int width, int height)
{
m_FrameBuffer = sPtrCreate<FrameBuffer>();
m_IntermediateFrameBuffer = sPtrCreate<FrameBuffer>();
m_RenderBuffer = sPtrCreate<RenderBuffer>();
//m_Texture = sPtrCreate<Texture>(width, height);
m_Texture = sPtrCreate<Texture>(width, height, 4);
m_IntermediateTexture = sPtrCreate<Texture>(width, height);
m_FrameBuffer->Bind();
m_RenderBuffer->Bind();
//m_RenderBuffer->Storage(width, height);
m_RenderBuffer->Storage(width, height, 4);
m_RenderBuffer->Unbind();
m_FrameBuffer->AttachMultisampled(m_Texture->GetId(), FrameBuffer::AttachmentType::TextureBuffer);
m_FrameBuffer->AttachMultisampled(m_RenderBuffer->GetId(), FrameBuffer::AttachmentType::RenderBuffer);
//m_FrameBuffer->Attach(m_Texture->GetId(), FrameBuffer::AttachmentType::TextureBuffer);
//m_FrameBuffer->Attach(m_RenderBuffer->GetId(), FrameBuffer::AttachmentType::RenderBuffer);
m_FrameBuffer->Unbind();
m_IntermediateFrameBuffer->Bind();
m_IntermediateFrameBuffer->Attach(m_IntermediateTexture->GetId(), FrameBuffer::AttachmentType::TextureBuffer);
m_IntermediateFrameBuffer->Unbind();
}
/**
* @brief Bind frame buffer.
*
* Frame buffer is bound before Scene rendering.
*/
void Editor::BindFrameBuffer()
{
m_FrameBuffer->Bind();
}
/**
* @brief Unbind frame buffer.
*
* Frame buffer is unbound after Scene rendering is done.
*/
void Editor::UnbindFrameBuffer()
{
m_FrameBuffer->Unbind();
}
/**
* @brief Import asset in Scene window
*
* Asset is imported on drag'n'drop.
* Asset could be found in Project windo, in editor.
*/
void Editor::ImportAsset(const std::string& importAssetFilePath)
{
auto& [loadedMesh, loadedAnimation] = ModelImporter::LoadMeshFile(importAssetFilePath);
auto meshEntity = m_Scene->CreateEntity();
auto& entityTag = meshEntity.AddComponent<EntityTagComponent>(importAssetFilePath);
auto& mesh = meshEntity.AddComponent<MeshComponent>(*loadedMesh);
auto& transform = meshEntity.AddComponent<TransformComponent>();
auto& relationship = meshEntity.AddComponent<RelationshipComponent>();
relationship.Parent = entt::null;
meshEntity.AddComponent<BoundBoxComponent>(*loadedMesh);
if (loadedMesh->HasAnimation)
auto& animation = meshEntity.AddComponent<AnimationComponent>(*loadedAnimation);
// Check if mouse ray intersects ground plane
if (MouseRay::CheckCollisionWithPlane())
{
// Place asset on the intersection point
const glm::vec3& intersectionPoint = MouseRay::GetIntersectionPoint();
transform.Position = intersectionPoint;
}
else
{
// Place asset on the origin point of world coordinate system
transform.Position = glm::vec3(0.0f, 0.0f, 0.0f);
}
transform.Scale = glm::vec3(10.0f, 10.0f, 10.0f);
MeshRenderer::Submit(mesh);
}
/**
* @brief Select mesh on left click
*
* Mesh is selected when user clicks on it in Scene window.
* Editor will keep track of the selected entity ID, which is of the type entt::entity.
*/
void Editor::SelectMesh()
{
auto& camera = m_Scene->GetCamera();
MouseRay::CalculateRayOrigin(camera, m_MouseInfo.MousePosX, m_MouseInfo.MousePosY, m_SceneInfo.SceneWidth, m_SceneInfo.SceneHeight);
auto view = m_Scene->m_Registry.view<MeshComponent, TransformComponent, BoundBoxComponent>();
bool isAnyMeshSelected = false;
std::pair<entt::entity, int> minIntersectionDistance = std::make_pair(entt::null, -1); // If ray goes through many meshes, then take minimum intersection distance
for (auto entity : view)
{
const auto& [mesh, transform] = view.get<MeshComponent, TransformComponent>(entity);
// Check if mouse ray intersects AABB of a mesh
if (MouseRay::CheckCollisionWithBox(mesh, transform))
{
// Check if mouse ray intersects any mesh triangle
if (MouseRay::CheckCollisionWithMesh(mesh, transform))
{
isAnyMeshSelected = true;
if (minIntersectionDistance.first == entt::null)
{
minIntersectionDistance.first = entity;
minIntersectionDistance.second = (int)MouseRay::GetCollisionDistance();
}
else
{
if (minIntersectionDistance.second > (int)MouseRay::GetCollisionDistance())
{
minIntersectionDistance.first = entity;
minIntersectionDistance.second = (int)MouseRay::GetCollisionDistance();
}
}
}
}
}
if (isAnyMeshSelected)
{
m_SelectedSceneEntity = minIntersectionDistance.first;
s_CurrentGizmoOperation = ImGuizmo::TRANSLATE;
}
else
{
m_SelectedSceneEntity = entt::null;
s_CurrentGizmoOperation = ImGuizmo::BOUNDS;
}
}
/**
* @brief Update Scene texture when Scene window is resized.
*
* This method resizes framebuffer according to Scene window size and it also updates viewport (glViewport function).
*/
void Editor::UpdateSceneViewport(float sceneWindowWidth, float sceneWindowHeight)
{
float ratio = 1.5f;
float x = sceneWindowWidth;
float y = sceneWindowHeight;
if ((x / y) > ratio)
{
x = ratio * y;
}
if ((x / y) < ratio)
{
y = (1 / ratio) * x;
}
//m_Texture->Resize((int)x, (int)y);
m_Texture->ResizeMultisampled((int)x, (int)y, 4);
m_IntermediateTexture->Resize((int)x, (int)y);
m_RenderBuffer->ResizeMultisampled((int)x, (int)y, 4);
//m_RenderBuffer->Resize((int)x, (int)y);
glViewport(0, 0, (int)x, (int)y);
m_SceneInfo.SceneWidth = (int)x;
m_SceneInfo.SceneHeight = (int)y;
}
}
| 34.051423
| 228
| 0.693659
|
bd93
|
9f3d0b3a213a110f9f24124fe4be6b1e84186cb5
| 5,216
|
hpp
|
C++
|
include/indigox/utils/common.hpp
|
allison-group/indigox
|
22657cb3ceb888049cc231e73d18fb2eac099604
|
[
"MIT"
] | 7
|
2019-11-24T15:51:37.000Z
|
2021-10-02T05:18:42.000Z
|
include/indigox/utils/common.hpp
|
allison-group/indigox
|
22657cb3ceb888049cc231e73d18fb2eac099604
|
[
"MIT"
] | 2
|
2018-12-17T00:55:32.000Z
|
2019-10-11T01:47:04.000Z
|
include/indigox/utils/common.hpp
|
allison-group/indigox
|
22657cb3ceb888049cc231e73d18fb2eac099604
|
[
"MIT"
] | 2
|
2019-10-21T01:26:56.000Z
|
2019-12-02T00:00:42.000Z
|
/*! \file common.hpp
*/
#ifndef INDIGOX_UTILS_COMMON_HPP
#define INDIGOX_UTILS_COMMON_HPP
#include <array>
#include <bitset>
#include <algorithm>
#include <iterator>
#include <memory>
#include <string>
#include <type_traits>
// forward definitions of serilisation stuff
namespace cereal {
class access;
class PortableBinaryInputArchive;
class PortableBinaryOutputArchive;
class JSONInputArchive;
class JSONOutputArchive;
template <class T> class construct;
} // namespace cereal
//! utils namespace for useful utility functions
namespace indigox::utils {
enum class Option {
Yes = 1,
No = Yes << 1,
Auto = Yes << 2,
Default = Yes << 3,
All = Yes << 4,
Some = Yes << 5,
None = Yes << 6
};
inline Option operator|(Option l, Option r) {
using under = std::underlying_type<Option>::type;
return static_cast<Option>(static_cast<under>(l) | static_cast<under>(r));
}
inline Option operator&(Option l, Option r) {
using under = std::underlying_type<Option>::type;
return static_cast<Option>(static_cast<under>(l) & static_cast<under>(r));
}
/*! \brief Convert a string to upper case.
* \param s the string to convert.
* \return the uppercase version of s. */
std::string ToUpper(const std::string &s);
/*! \brief Convert a string to lower case.
* \param s the string to convert.
* \return the lower case version of s. */
std::string ToLower(const std::string &s);
/*! \brief Convert a string to lower case with a single leading upper case.
* \details Acts on the string as a whole, ignoring any white space.
* \param s the string the convert.
* \return the lower case version of s with a leading upper case letter. */
std::string ToUpperFirst(const std::string &s);
/*! \brief Generate a random string.
* \details All upper and lower case letters are available.
* \param length the number of characters to generate.
* \param seed the seed for the random number generator. If
* \return the randomly generated string. */
std::string GetRandomString(size_t length, size_t seed = 0);
/*! \brief Check if a given shared_ptr<T> is in a weak_ptr<T> container.
* \details Checks all weak_ptr<T> instances in the iterator range to see
* if the reference the supplied shared_ptr<T>. If the supplied shared_ptr<T>
* is empty, no comparisons are made.
* \tparam T the element_type.
* \tparam __Iter the iterator type.
* \param b,e start and end of the iterator range.
* \param x the shared_ptr<T> instance to search for.
* \return the iterator position of the first found element. */
template <typename T, typename __Iter>
inline __Iter WeakContainsShared(__Iter b, __Iter e, std::shared_ptr<T> x) {
static_assert(
std::is_same<typename std::weak_ptr<T>,
typename std::iterator_traits<__Iter>::value_type>::value,
"__Iter must be iterator over std::weak_ptr<T>.");
if (!x) return e;
return std::find_if(b, e,
[x](std::weak_ptr<T> _x) { return _x.lock() == x; });
}
/*! \brief Check if a shared_ptr is pointing to a null member.
* \details Types must implement a boolean operator which returns true if
* that instance is considered a null instance.
* \tparam T the stored type.
* \param t the shared_ptr<T> to check.
* \return if the shared_ptr references a null instance. */
// template<typename T>
// inline bool IsNull(std::shared_ptr<T> t) {
// return !(t && *t);
// }
} // namespace indigox::utils
#define b_cnt (uint32_t)Settings::BoolCount
#define i_cnt (uint32_t)Settings::IntCount
#define f_cnt (uint32_t)Settings::RealCount
#define p_cnt (uint32_t)param
#define DEFAULT_SETTINGS(...) \
private: \
std::bitset<b_cnt> p_bool; \
std::array<double, f_cnt - b_cnt - 2> p_num; \
\
void ResetSettings() { \
p_bool.reset(); \
p_num.fill(0.); \
} \
\
public: \
bool GetBool(Settings param) { \
if (p_cnt >= b_cnt) throw std::runtime_error("Not a boolean parameter"); \
return p_bool.test(p_cnt); \
} \
void SetBool(Settings param, bool value) { \
if (p_cnt >= b_cnt) throw std::runtime_error("Not a boolean parameter"); \
p_bool[p_cnt] = value; \
} \
int64_t GetInt(Settings param) { \
uint32_t offset = 1 + b_cnt; \
if (p_cnt <= b_cnt || p_cnt >= i_cnt) throw std::runtime_error("Not an integer parameter"); \
return int64_t(p_num[p_cnt - offset]); \
} \
void SetInt(Settings param, int64_t value) { \
uint32_t offset = 1 + b_cnt; \
if (p_cnt <= b_cnt || p_cnt >= i_cnt) throw std::runtime_error("Not an integer parameter"); \
p_num[p_cnt - offset] = double(value); \
} \
double GetReal(Settings param) { \
uint32_t offset = 2 + b_cnt; \
if (p_cnt <= i_cnt || p_cnt >= f_cnt) throw std::runtime_error("Not a real parameter"); \
return p_num[p_cnt - offset]; \
} \
void SetReal(Settings param, double value) { \
uint32_t offset = 2 + b_cnt; \
if (p_cnt <= i_cnt || p_cnt >= f_cnt) throw std::runtime_error("Not a real parameter"); \
p_num[p_cnt - offset] = value; \
} \
void DefaultSettings()
#endif /* INDIGOX_UTILS_COMMON_HPP */
| 34.543046
| 97
| 0.66296
|
allison-group
|
9f3e51b216a6de9ee5f29eb9cd92ae51cb7f783f
| 4,986
|
cpp
|
C++
|
windows/c++/visualstudio/src/InformationManager.cpp
|
afskylia/bachelor-starcraft-bot
|
e9d53345d77f6243f5a2db1781cdfcb7838ebcfd
|
[
"MIT"
] | null | null | null |
windows/c++/visualstudio/src/InformationManager.cpp
|
afskylia/bachelor-starcraft-bot
|
e9d53345d77f6243f5a2db1781cdfcb7838ebcfd
|
[
"MIT"
] | 2
|
2021-06-27T18:57:39.000Z
|
2021-06-27T18:57:52.000Z
|
windows/c++/visualstudio/src/InformationManager.cpp
|
afskylia/bachelor-starcraft-bot
|
e9d53345d77f6243f5a2db1781cdfcb7838ebcfd
|
[
"MIT"
] | null | null | null |
#include "InformationManager.h"
#include "MiraBotMain.h"
#include "Global.h"
using namespace MiraBot;
/// <summary>
/// Here we save important information through the game e.g. enemy race and where they are.
/// </summary>
InformationManager::InformationManager()
{
//// Save positions of all chokepoints in main base
//auto base = BWAPI::Broodwar->self()->getStartLocation();
//const auto area = Global::map().map.GetNearestArea(base);
//for (auto cp : area->ChokePoints())
// base_chokepoints.push_back(BWAPI::Position(cp->Center()));
}
void InformationManager::onFrame()
{
if (m_should_update_ && BWAPI::Broodwar->getFrameCount() % 50 == 0)
{
informationIsUpdated();
m_should_update_ = false;
}
}
/// <summary>
/// Call this when information is updated, e.g. enemy is found
/// </summary>
void InformationManager::informationUpdateShouldHappen()
{
if (!m_should_update_) m_should_update_ = true;
}
/// <summary>
/// information in the manager is send to e.g. strategy manager to update strategy.
/// </summary>
void InformationManager::informationIsUpdated()
{
updateEnemyStrategy();
Global::strategy().informationUpdate();
}
/// <summary>
/// Update Enemy Strategy
/// </summary>
void InformationManager::updateEnemyStrategy()
{
// Do not update if we do not know any enemies.
if (enemy_units.empty()) return;
for (BWAPI::UnitInterface* enemy_unit : enemy_units)
{
bool enemy_is_near_our_base = enemy_unit->getPosition().getApproxDistance(main_base->getPosition()) < 1000;
bool enemy_is_in_own_base = enemy_unit->getPosition().getApproxDistance(BWAPI::Position(enemy_start_location)) <
1000;
// Offensive if leaving base or near our base
if (enemy_is_near_our_base || enemy_is_in_own_base)
{
m_current_enemy_strategy = Enums::offensive;
return;
}
}
m_current_enemy_strategy = Enums::defensive;
}
/// <summary>
/// log the enemy race and starting location
/// </summary>
/// <param name="unit">First enemy unit found</param>
void InformationManager::logEnemyRaceAndStartLocation(BWAPI::Unit unit)
{
// If we did not find the enemy, log it
if (!found_enemy)
{
enemy_race = unit->getType().getRace();
found_enemy = true;
std::cout << "Enemy is " << enemy_race << "\n";
auto& start_locations = BWAPI::Broodwar->getStartLocations();
// Find closest starting location to enemy unit
double shortest_distance = INT_MAX;
for (BWAPI::TilePosition position : start_locations)
{
const auto distance = position.getDistance(unit->getTilePosition());
if (distance < shortest_distance)
{
shortest_distance = distance;
enemy_start_location = position;
}
}
std::cout << "Enemy starting location: " << enemy_start_location << "\n";
Global::map().addCircle(BWAPI::Position(enemy_start_location), "ENEMY START LOCATION");
auto area = Global::map().map.GetNearestArea(enemy_start_location);
enemy_areas.push_back(area);
informationUpdateShouldHappen();
}
}
/// <summary>
/// Keeps track of the enemy units.
/// </summary>
/// <param name="unit">the unit to add or remove</param>
/// <param name="remove_unit">should we remove the unit, default is false</param>
void InformationManager::addOrRemoveEnemyUnit(BWAPI::Unit unit, bool remove_unit)
{
// try find the unit in unit set
auto it = enemy_units.find(unit);
// if not in the unit set, add it, if in the set and should remove then remove it
if (!remove_unit)
{
if (it != enemy_units.end())
{
enemy_units.erase(it);
}
enemy_units.insert(unit);
informationUpdateShouldHappen();
}
else
{
enemy_units.erase(it);
informationUpdateShouldHappen();
}
}
void InformationManager::onUnitShow(BWAPI::Unit unit)
{
// If we find an enemy, we should log the information
if (unit->getPlayer()->isEnemy(BWAPI::Broodwar->self()))
{
// Save all unit bases we find (if it has buildings, we consider it a base)
const auto* area = Global::map().map.GetNearestArea(unit->getTilePosition());
if (unit->getType().isBuilding() && !std::count(enemy_areas.begin(), enemy_areas.end(), area))
{
enemy_areas.push_back(area);
Global::map().addCircle(unit->getPosition(), "ENEMY AREA\n");
}
logEnemyRaceAndStartLocation(unit);
addOrRemoveEnemyUnit(unit);
informationUpdateShouldHappen();
}
}
void InformationManager::onStart()
{
main_base = BWAPI::Broodwar->getClosestUnit(BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation()),
BWAPI::Filter::IsResourceDepot);
informationUpdateShouldHappen();
}
void InformationManager::onUnitDestroy(BWAPI::Unit unit)
{
// If we find an enemy, we should log the information
if (unit->getPlayer()->isEnemy(BWAPI::Broodwar->self()))
{
addOrRemoveEnemyUnit(unit, true);
informationUpdateShouldHappen();
}
}
/// <summary>
/// Gets the strategy from enemy units
/// </summary>
/// <returns>strategy based on units</returns>
Enums::strategy_type InformationManager::getEnemyStrategy()
{
return m_current_enemy_strategy;
}
| 27.854749
| 114
| 0.712796
|
afskylia
|
9f3ef13ff365f2d7b000ee73688fc5072f454092
| 4,165
|
cpp
|
C++
|
Spectre2D/source/FileSystem.cpp
|
DragonGamesStudios/Spectre2D
|
044f73f3516f92fd939349e11e89e4524c84e7fd
|
[
"MIT"
] | null | null | null |
Spectre2D/source/FileSystem.cpp
|
DragonGamesStudios/Spectre2D
|
044f73f3516f92fd939349e11e89e4524c84e7fd
|
[
"MIT"
] | null | null | null |
Spectre2D/source/FileSystem.cpp
|
DragonGamesStudios/Spectre2D
|
044f73f3516f92fd939349e11e89e4524c84e7fd
|
[
"MIT"
] | null | null | null |
#include "..\include\Spectre2D\FileSystem.h"
namespace sp
{
FileSystem::FileSystem(bool appdata)
{
if (appdata)
{
#if defined(_WIN32)
char* appbuff;
size_t len;
_dupenv_s(&appbuff, &len, "APPDATA");
current_path = appbuff;
#elif defined(__linux__)
current_path = "~/.local/";
#endif
}
else
{
current_path = fs::current_path();
}
}
bool FileSystem::create_dir(const std::string& dirname)
{
return fs::create_directory(current_path / dirname);
}
bool FileSystem::delete_dir_recursively(const std::string& dirname)
{
return fs::remove_all(current_path / dirname) > 0;
}
bool FileSystem::enter_dir(const std::string& path)
{
if (exists(path))
{
current_path = get_correct_path(path);
return true;
}
return false;
}
bool FileSystem::enter_dir(const fs::path& path)
{
if (exists(path))
{
current_path = get_correct_path(path);
return true;
}
return false;
}
std::string FileSystem::get_directory() const
{
return current_path.filename().string();
}
fs::path FileSystem::get_current_path() const
{
return current_path;
}
void FileSystem::exit()
{
current_path = current_path.parent_path();
}
void FileSystem::exit_to(const fs::path& dirname)
{
while (
current_path.filename() != dirname && fs::absolute(current_path) != fs::absolute(dirname)
&& !current_path.empty()
)
{
this->exit();
}
}
bool FileSystem::create_dir_if_necessary(const std::string& dirname)
{
if (!exists(dirname))
return create_dir(dirname);
return true;
}
std::ifstream FileSystem::open_file(const std::string& path) const
{
return std::ifstream(current_path / path);
}
std::ifstream FileSystem::open_file(const fs::path& path) const
{
return std::ifstream(current_path / path);
}
std::ofstream FileSystem::open_ofile(const std::string& path) const
{
return std::ofstream(current_path / path);
}
std::ofstream FileSystem::open_ofile(const fs::path& path) const
{
return std::ofstream(current_path / path);
}
bool FileSystem::create_file(const std::string& filename)
{
std::ofstream f(filename);
bool worked = f.is_open();
f.close();
return worked;
}
bool FileSystem::create_file_if_necessary(const std::string& filename)
{
if (!exists(filename))
return create_file(filename);
return true;
}
bool FileSystem::delete_file(const std::string& filename)
{
return fs::remove(filename);
}
bool FileSystem::delete_file(const fs::path& filename)
{
return fs::remove(filename);
}
bool FileSystem::delete_file_if_exists(const std::string& filename)
{
if (exists(filename))
return fs::remove(filename);
return true;
}
bool FileSystem::delete_file_if_exists(const fs::path& filename)
{
if (exists(filename))
return fs::remove(filename);
return true;
}
bool FileSystem::exists(const fs::path& path) const
{
return fs::exists(get_correct_path(path));
}
bool FileSystem::add_path_template(const std::string& temp, const fs::path& target)
{
fs::path correct = target;
if (!correct.is_absolute()) correct = current_path / correct;
size_t s = temp.size();
if (s > 4 && temp[0] == temp[1] && temp[1] == temp[s - 1] && temp[s - 1] == temp[s - 2] && temp[s - 2] == '_')
{
path_templates.insert(std::make_pair(temp, correct));
return true;
}
return false;
}
bool FileSystem::is_template(const std::string& name)
{
size_t s = name.size();
return (s > 4 && name[0] == name[1] && name[1] == name[s - 1] && name[s - 1] == name[s - 2] && name[s - 2] == '_');
}
fs::path FileSystem::get_correct_path(const fs::path& path) const
{
if (path.empty())
return current_path;
if (path.has_root_path())
return path;
std::string root = (*path.begin()).string();
fs::path rest;
for (auto it = ++path.begin(); it != path.end(); it++)
rest /= *it;
if (is_template(root) && path_templates.find(root) != path_templates.end())
return path_templates.at(root) / rest;
return current_path / path;
}
fs::directory_iterator FileSystem::get_files_in_directory(const fs::path& dirname)
{
return fs::directory_iterator(get_correct_path(dirname));
}
}
| 20.218447
| 117
| 0.669148
|
DragonGamesStudios
|
9f46e62c023b9a42a3184aa2e447b9596181f220
| 860
|
cpp
|
C++
|
src/peakIndexInMountainArray.cpp
|
guitargeek/leetcode
|
7d587774d3f922020b5ba3ca2d533b2686891fed
|
[
"MIT"
] | null | null | null |
src/peakIndexInMountainArray.cpp
|
guitargeek/leetcode
|
7d587774d3f922020b5ba3ca2d533b2686891fed
|
[
"MIT"
] | null | null | null |
src/peakIndexInMountainArray.cpp
|
guitargeek/leetcode
|
7d587774d3f922020b5ba3ca2d533b2686891fed
|
[
"MIT"
] | null | null | null |
/**
852. Peak Index in a Mountain Array
Let's call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i such that
A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].
Example 1:
```
Input: [0,1,0]
Output: 1
```
Example 2:
```
Input: [0,2,1,0]
Output: 1
```
Note:
3 <= A.length <= 10000
0 <= A[i] <= 10^6
A is a mountain, as defined above.
*/
#include "leet.h"
namespace leet {
using namespace std;
int peakIndexInMountainArray(vector<int>& A) {
for (int i = 1; i < A.size(); ++i) {
if (A[i] - A[i - 1] < 0)
return i - 1;
}
return -1;
}
} // namespace leet
| 17.2
| 117
| 0.517442
|
guitargeek
|
9f488e046a44a1c69f4910c46d8195b6e47a9356
| 3,286
|
cpp
|
C++
|
src/panels/wx_id_list.cpp
|
KeyWorksRW/wxUiEditor
|
fc58bb37284430fa5901579ae121d4482b588c75
|
[
"Apache-2.0"
] | 7
|
2021-10-22T02:43:12.000Z
|
2022-01-15T10:52:58.000Z
|
src/panels/wx_id_list.cpp
|
KeyWorksRW/wxUiEditor
|
fc58bb37284430fa5901579ae121d4482b588c75
|
[
"Apache-2.0"
] | 288
|
2021-05-16T19:12:04.000Z
|
2022-03-30T13:22:31.000Z
|
src/panels/wx_id_list.cpp
|
KeyWorksRW/wxUiEditor
|
fc58bb37284430fa5901579ae121d4482b588c75
|
[
"Apache-2.0"
] | null | null | null |
/////////////////////////////////////////////////////////////////////////////
// Purpose: wxID_ strings
// Author: Ralph Walden
// Copyright: Copyright (c) 2020 KeyWorks Software (Ralph Walden)
// License: Apache License -- see ../../LICENSE
/////////////////////////////////////////////////////////////////////////////
// This file is designed to be #included into propgrid_panel.cpp, so it doesn't have the normal precompiled header.
// clang-format off
inline const char* list_wx_ids[] = {
"wxID_ABORT",
"wxID_ABOUT",
"wxID_ADD",
"wxID_ANY",
"wxID_APPLY",
"wxID_BACKWARD",
"wxID_BOLD",
"wxID_BOTTOM",
"wxID_CANCEL",
"wxID_CDROM",
"wxID_CLEAR",
"wxID_CLOSE",
"wxID_CLOSE_ALL",
"wxID_CLOSE_FRAME",
"wxID_CONTEXT_HELP",
"wxID_CONVERT",
"wxID_COPY",
"wxID_CUT",
"wxID_DEFAULT",
"wxID_DELETE",
"wxID_DOWN",
"wxID_DUPLICATE",
"wxID_EDIT",
"wxID_EXECUTE",
"wxID_EXIT",
"wxID_FILE",
"wxID_FILE1",
"wxID_FILE2",
"wxID_FILE3",
"wxID_FILE4",
"wxID_FILE5",
"wxID_FILE6",
"wxID_FILE7",
"wxID_FILE8",
"wxID_FILE9",
"wxID_FIND",
"wxID_FIRST",
"wxID_FLOPPY",
"wxID_FORWARD",
"wxID_HARDDISK",
"wxID_HELP",
"wxID_HELP_COMMANDS",
"wxID_HELP_CONTENTS",
"wxID_HELP_CONTEXT",
"wxID_HELP_INDEX",
"wxID_HELP_PROCEDURES",
"wxID_HELP_SEARCH",
"wxID_HOME",
"wxID_ICONIZE_FRAME",
"wxID_IGNORE",
"wxID_INDENT",
"wxID_INDEX",
"wxID_INFO",
"wxID_ITALIC",
"wxID_JUMP_TO",
"wxID_JUSTIFY_CENTER",
"wxID_JUSTIFY_FILL",
"wxID_JUSTIFY_LEFT",
"wxID_JUSTIFY_RIGHT",
"wxID_LAST",
"wxID_MAXIMIZE_FRAME",
"wxID_MDI_WINDOW_ARRANGE_ICONS",
"wxID_MDI_WINDOW_CASCADE",
"wxID_MDI_WINDOW_FIRST",
"wxID_MDI_WINDOW_LAST",
"wxID_MDI_WINDOW_NEXT",
"wxID_MDI_WINDOW_PREV",
"wxID_MDI_WINDOW_TILE_HORZ",
"wxID_MDI_WINDOW_TILE_VERT",
"wxID_MORE",
"wxID_MOVE_FRAME",
"wxID_NETWORK",
"wxID_NEW",
"wxID_NO",
"wxID_NONE",
"wxID_NOTOALL",
"wxID_OK",
"wxID_OPEN",
"wxID_PAGE_SETUP",
"wxID_PASTE",
"wxID_PREFERENCES",
"wxID_PREVIEW",
"wxID_PRINT",
"wxID_PRINT_SETUP",
"wxID_PROPERTIES",
"wxID_REDO",
"wxID_REFRESH",
"wxID_REMOVE",
"wxID_REPLACE",
"wxID_REPLACE_ALL",
"wxID_RESET",
"wxID_RESIZE_FRAME",
"wxID_RESTORE_FRAME",
"wxID_RETRY",
"wxID_REVERT",
"wxID_REVERT_TO_SAVED",
"wxID_SAVE",
"wxID_SAVEAS",
"wxID_SELECTALL",
"wxID_SELECT_COLOR",
"wxID_SELECT_FONT",
"wxID_SEPARATOR",
"wxID_SETUP",
"wxID_SORT_ASCENDING",
"wxID_SORT_DESCENDING",
"wxID_SPELL_CHECK",
"wxID_STATIC",
"wxID_STOP",
"wxID_STRIKETHROUGH",
"wxID_SYSTEM_MENU",
"wxID_TOP",
"wxID_UNDELETE",
"wxID_UNDERLINE",
"wxID_UNDO",
"wxID_UNINDENT",
"wxID_UP",
"wxID_VIEW_DETAILS",
"wxID_VIEW_LARGEICONS",
"wxID_VIEW_LIST",
"wxID_VIEW_SMALLICONS",
"wxID_VIEW_SORTDATE",
"wxID_VIEW_SORTNAME",
"wxID_VIEW_SORTSIZE",
"wxID_VIEW_SORTTYPE",
"wxID_YES",
"wxID_YESTOALL",
"wxID_ZOOM_100",
"wxID_ZOOM_FIT",
"wxID_ZOOM_IN",
"wxID_ZOOM_OUT",
};
// clang-format on
| 22.506849
| 115
| 0.602252
|
KeyWorksRW
|
9f49c7a5b74af2b4895012b19f979731cdb85e87
| 882
|
hpp
|
C++
|
Library/Deps/MessagePack/Include/msgpack/v2/adaptor/nil_decl.hpp
|
rneogns/simpleio
|
20830a2b9b22c31eab23508acd25b275b53103c9
|
[
"MIT"
] | null | null | null |
Library/Deps/MessagePack/Include/msgpack/v2/adaptor/nil_decl.hpp
|
rneogns/simpleio
|
20830a2b9b22c31eab23508acd25b275b53103c9
|
[
"MIT"
] | null | null | null |
Library/Deps/MessagePack/Include/msgpack/v2/adaptor/nil_decl.hpp
|
rneogns/simpleio
|
20830a2b9b22c31eab23508acd25b275b53103c9
|
[
"MIT"
] | null | null | null |
//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2016 FURUHASHI Sadayuki and KONDO Takatoshi
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef MSGPACK_V2_TYPE_NIL_DECL_HPP
#define MSGPACK_V2_TYPE_NIL_DECL_HPP
#include "msgpack/v1/adaptor/nil_decl.hpp"
namespace msgpack {
/// @cond
MSGPACK_API_VERSION_NAMESPACE(v2) {
/// @endcond
namespace type {
using v1::type::nil_t;
#if defined(MSGPACK_USE_LEGACY_NIL)
typedef nil_t nil;
#endif // defined(MSGPACK_USE_LEGACY_NIL)
using v1::type::operator<;
using v1::type::operator==;
} // namespace type
/// @cond
} // MSGPACK_API_VERSION_NAMESPACE(v2)
/// @endcond
} // namespace msgpack
#endif // MSGPACK_V2_TYPE_NIL_DECL_HPP
| 20.511628
| 66
| 0.701814
|
rneogns
|
9f527ae3a9e3cc87fc724c86a3c08884f97f8c7b
| 51
|
cpp
|
C++
|
src/dna_block.cpp
|
dyigitpolat/relaxase
|
bb183197b48ca448afe71cb801c9cdafb8d418a1
|
[
"MIT"
] | 1
|
2020-10-22T11:27:51.000Z
|
2020-10-22T11:27:51.000Z
|
src/dna_block.cpp
|
dyigitpolat/relaxase
|
bb183197b48ca448afe71cb801c9cdafb8d418a1
|
[
"MIT"
] | null | null | null |
src/dna_block.cpp
|
dyigitpolat/relaxase
|
bb183197b48ca448afe71cb801c9cdafb8d418a1
|
[
"MIT"
] | null | null | null |
#include "dna_block.hpp"
DNABlock::DNABlock()
{
}
| 8.5
| 24
| 0.686275
|
dyigitpolat
|
9f542b5f07245ea8acda91d4cbc1761ec9aa5684
| 1,415
|
hpp
|
C++
|
examples_tf2/include/examples_tf2/listener.hpp
|
ROBOTIS-Platform/ros2_examples
|
5b1cfff84c7d6baaaee5239a717475c65f8a7a90
|
[
"Apache-2.0"
] | 10
|
2019-08-13T01:41:34.000Z
|
2021-12-06T14:11:17.000Z
|
examples_tf2/include/examples_tf2/listener.hpp
|
ROBOTIS-Platform/ros2_examples
|
5b1cfff84c7d6baaaee5239a717475c65f8a7a90
|
[
"Apache-2.0"
] | 4
|
2019-09-29T22:53:18.000Z
|
2020-11-08T23:29:17.000Z
|
examples_tf2/include/examples_tf2/listener.hpp
|
ROBOTIS-Platform/ros2_examples
|
5b1cfff84c7d6baaaee5239a717475c65f8a7a90
|
[
"Apache-2.0"
] | 2
|
2020-09-25T13:12:35.000Z
|
2021-12-06T14:11:18.000Z
|
/*******************************************************************************
* Copyright 2019 ROBOTIS CO., LTD.
*
* 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.
*******************************************************************************/
/* Authors: Darby Lim, Pyo */
#ifndef EXAMPLES_TF2_LISTENER_HPP_
#define EXAMPLES_TF2_LISTENER_HPP_
#include <cmath>
#include <string>
#include <geometry_msgs/msg/transform_stamped.hpp>
#include <rclcpp/rclcpp.hpp>
#include <tf2/LinearMath/Transform.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <tf2_ros/transform_listener.h>
#define RAD_TO_DEG 180/M_PI
#define DEG_TO_RAD M_PI/180
namespace robotis
{
class Listener : public rclcpp::Node
{
public:
explicit Listener();
private:
rclcpp::TimerBase::SharedPtr timer_;
tf2_ros::Buffer tf_buffer_;
tf2_ros::TransformListener tf_listener_;
};
} // robotis
#endif // EXAMPLES_TF2_LISTENER_HPP_
| 28.877551
| 80
| 0.681979
|
ROBOTIS-Platform
|
9f5a92cc43c0f35a7101f046a633ed4529fe8c27
| 1,506
|
cpp
|
C++
|
src/lua/script.cpp
|
FiniteReality/SourceLua
|
41ced5fb3c80376cac012c0dab1f9f2f39400e40
|
[
"MIT"
] | 7
|
2017-08-27T08:11:48.000Z
|
2022-03-06T06:20:02.000Z
|
src/lua/script.cpp
|
FiniteReality/SourceLua
|
41ced5fb3c80376cac012c0dab1f9f2f39400e40
|
[
"MIT"
] | 7
|
2017-08-18T14:17:09.000Z
|
2018-04-17T15:26:22.000Z
|
src/lua/script.cpp
|
FiniteReality/SourceLua
|
41ced5fb3c80376cac012c0dab1f9f2f39400e40
|
[
"MIT"
] | 3
|
2017-10-04T03:35:58.000Z
|
2020-11-25T13:48:44.000Z
|
#include <stdexcept>
#include <common/logging.hpp>
#include <lua/error_handler.hpp>
#include <lua/script.hpp>
#include <thread/scheduler.hpp>
namespace SourceLua
{
namespace Lua
{
Script::Script(lua_State* L)
: _L{L}, _name{"=unknown"}
{
if (_L == nullptr)
throw new std::runtime_error("L must not be null");
// Push the table now so that we don't have to re-order the stack
lua_getfield(_L, LUA_REGISTRYINDEX, SOURCELUA_SCRIPT_CACHE_KEY);
_T = lua_newthread(_L);
if (_T == nullptr)
throw new std::runtime_error("Could not initialize Lua thread");
thread_ref = luaL_ref(L, -2);
lua_pop(_L, 1);
}
Script::Script(lua_State* L, const char* name)
: Script(L)
{
_name.replace(1, _name.size(), name);
}
Script::~Script()
{
// Remove the reference to allow GC to occur
lua_getfield(_L, LUA_REGISTRYINDEX, SOURCELUA_SCRIPT_CACHE_KEY);
luaL_unref(_L, -1, thread_ref);
lua_pop(_L, 1);
}
void Script::Run(const char* code)
{
Run(code, strlen(code));
}
void Script::Run(const char* code, size_t length)
{
int err = luaL_loadbufferx(_T, code, length, _name.c_str(), "t");
if (err == LUA_OK)
{
auto task = Threading::CreateDelayedTask(_T, 0);
Threading::Scheduler::EnqueueTask(std::move(task));
}
else
{
Errors::HandleError(_T, err);
}
}
const char* Script::name() const
{
return _name.substr(1).c_str();
}
}
}
// kate: indent-mode cstyle; indent-width 4; replace-tabs on;
| 20.351351
| 72
| 0.64741
|
FiniteReality
|
9f5de0c64add9d5db02e91744023085e65f3f36b
| 1,956
|
cpp
|
C++
|
src/platformspecifics/u32/u32backend.cpp
|
mightybruno/KShare
|
c1124354be9c8bb5c1931e37e19391f0b6c4389f
|
[
"MIT"
] | 16
|
2020-01-22T04:52:46.000Z
|
2022-02-22T09:53:39.000Z
|
src/platformspecifics/u32/u32backend.cpp
|
mightybruno/KShare
|
c1124354be9c8bb5c1931e37e19391f0b6c4389f
|
[
"MIT"
] | 15
|
2020-02-16T01:12:42.000Z
|
2021-05-03T21:51:26.000Z
|
src/platformspecifics/u32/u32backend.cpp
|
mightybruno/KShare
|
c1124354be9c8bb5c1931e37e19391f0b6c4389f
|
[
"MIT"
] | 3
|
2020-04-03T22:20:14.000Z
|
2020-09-23T07:58:09.000Z
|
#include "u32backend.hpp"
#include <Lmcons.h>
#include <QCursor>
#include <QtWin>
#include <windows.h>
std::tuple<QPoint, QPixmap> PlatformBackend::getCursor() {
CURSORINFO cursorInfo;
cursorInfo.cbSize = sizeof(cursorInfo);
if (GetCursorInfo(&cursorInfo)) {
if (cursorInfo.flags == CURSOR_SHOWING) {
ICONINFO info; // It took me 5 hours to get to here
if (GetIconInfo(cursorInfo.hCursor, &info)) {
return std::tuple<QPoint, QPixmap>(QPoint(info.xHotspot, info.yHotspot),
QtWin::fromHBITMAP(info.hbmColor, QtWin::HBitmapAlpha));
} else
return std::tuple<QPoint, QPixmap>(QPoint(0, 0), QPixmap());
} else
return std::tuple<QPoint, QPixmap>(QPoint(0, 0), QPixmap());
} else
return std::tuple<QPoint, QPixmap>(QPoint(0, 0), QPixmap());
}
DWORD PlatformBackend::pid() {
return GetCurrentProcessId();
}
WId PlatformBackend::getActiveWID() {
return (WId)GetForegroundWindow();
}
QString illegal(QStringLiteral("<>:\"/\\|?*"));
QStringList illegalNames({ "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7",
"COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" });
bool PlatformBackend::filenameValid(QString name) {
int periods = 0;
for (QChar c : name) {
if (c == '.') periods++;
if (illegal.contains(c)) return false;
if (c < 32) return false;
}
if (periods == name.length()) return false;
return !illegalNames.contains(name);
}
QString PlatformBackend::getCurrentUser() {
WCHAR username[UNLEN + 1];
DWORD username_len = UNLEN + 1;
QString userName;
if (GetUserName(username, &username_len)) {
userName = QString::fromWCharArray(username, username_len - 1);
}
delete[] username;
return userName;
}
| 33.724138
| 117
| 0.596115
|
mightybruno
|
9f6582ee72bd887fccf911c2093a149b631e3e6d
| 914
|
cpp
|
C++
|
src/ROCInterpolator.cpp
|
timosachsenberg/Fido
|
e46bb879d3405dc7a63ad5c4188f0734a2a7ef82
|
[
"MIT"
] | null | null | null |
src/ROCInterpolator.cpp
|
timosachsenberg/Fido
|
e46bb879d3405dc7a63ad5c4188f0734a2a7ef82
|
[
"MIT"
] | null | null | null |
src/ROCInterpolator.cpp
|
timosachsenberg/Fido
|
e46bb879d3405dc7a63ad5c4188f0734a2a7ef82
|
[
"MIT"
] | null | null | null |
#include "ROCInterpolator.h"
double ROCInterpolator::interpolate(const Array<double> & fps, const Array<double> & tps, double fpVal)
{
bool success = false;
int k;
for (k=0; k<fps.size(); k++)
{
if ( fps[k] > fpVal )
{
success = true;
break;
}
}
if ( ! success )
{
cerr << "Problem: no place to interpolate here (value = " << fpVal << " )" << endl;
exit(1);
}
// k is the first index that passes fpVal
if ( k!= 0 )
return tps[k-1] + (tps[k] - tps[k-1])/(fps[k]-fps[k-1])*(fpVal-fps[k-1]);
else
return tps[0];
}
double ROCInterpolator::interpolateCollection(const Array<Array<double> > & fpCollection, const Array<Array<double> > & tpCollection, double fpVal)
{
double tot = 0.0;
for (int k=0; k<fpCollection.size(); k++)
{
tot += interpolate(fpCollection[k], tpCollection[k], fpVal);
}
return tot / fpCollection.size();
}
| 21.761905
| 147
| 0.592998
|
timosachsenberg
|
9f674ff79f625a217de65b4e7b20161653915228
| 13,236
|
cpp
|
C++
|
src/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.cpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.cpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.cpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
// Generated from /POI/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
#include <org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.hpp>
#include <java/io/ByteArrayOutputStream.hpp>
#include <java/io/EOFException.hpp>
#include <java/io/IOException.hpp>
#include <java/io/InputStream.hpp>
#include <java/lang/ArrayStoreException.hpp>
#include <java/lang/ClassCastException.hpp>
#include <java/lang/Exception.hpp>
#include <java/lang/IllegalStateException.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/String.hpp>
#include <java/lang/Throwable.hpp>
#include <java/security/GeneralSecurityException.hpp>
#include <java/security/Key.hpp>
#include <java/security/MessageDigest.hpp>
#include <java/util/Arrays.hpp>
#include <javax/crypto/Cipher.hpp>
#include <javax/crypto/SecretKey.hpp>
#include <javax/crypto/spec/SecretKeySpec.hpp>
#include <org/apache/poi/EncryptedDocumentException.hpp>
#include <org/apache/poi/poifs/crypt/CipherAlgorithm.hpp>
#include <org/apache/poi/poifs/crypt/CryptoFunctions.hpp>
#include <org/apache/poi/poifs/crypt/Decryptor.hpp>
#include <org/apache/poi/poifs/crypt/EncryptionHeader.hpp>
#include <org/apache/poi/poifs/crypt/EncryptionInfo.hpp>
#include <org/apache/poi/poifs/crypt/EncryptionVerifier.hpp>
#include <org/apache/poi/poifs/crypt/HashAlgorithm.hpp>
#include <org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor_CryptoAPICipherInputStream.hpp>
#include <org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor_StreamDescriptorEntry.hpp>
#include <org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDocumentInputStream.hpp>
#include <org/apache/poi/poifs/filesystem/DirectoryNode.hpp>
#include <org/apache/poi/poifs/filesystem/DocumentInputStream.hpp>
#include <org/apache/poi/poifs/filesystem/DocumentNode.hpp>
#include <org/apache/poi/poifs/filesystem/Entry.hpp>
#include <org/apache/poi/poifs/filesystem/POIFSFileSystem.hpp>
#include <org/apache/poi/util/BoundedInputStream.hpp>
#include <org/apache/poi/util/IOUtils.hpp>
#include <org/apache/poi/util/LittleEndian.hpp>
#include <org/apache/poi/util/LittleEndianInputStream.hpp>
#include <org/apache/poi/util/StringUtil.hpp>
#include <Array.hpp>
#include <ObjectArray.hpp>
#include <SubArray.hpp>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace poi
{
namespace poifs
{
namespace crypt
{
namespace cryptoapi
{
typedef ::SubArray< ::poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor_StreamDescriptorEntry, ::java::lang::ObjectArray > CryptoAPIDecryptor_StreamDescriptorEntryArray;
} // cryptoapi
} // crypt
} // poifs
} // poi
template<typename T, typename U>
static T java_cast(U* u)
{
if(!u) return static_cast<T>(nullptr);
auto t = dynamic_cast<T>(u);
if(!t) throw new ::java::lang::ClassCastException();
return t;
}
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
namespace
{
template<typename F>
struct finally_
{
finally_(F f) : f(f), moved(false) { }
finally_(finally_ &&x) : f(x.f), moved(false) { x.moved = true; }
~finally_() { if(!moved) f(); }
private:
finally_(const finally_&); finally_& operator=(const finally_&);
F f;
bool moved;
};
template<typename F> finally_<F> finally(F f) { return finally_<F>(f); }
}
poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::CryptoAPIDecryptor(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::CryptoAPIDecryptor()
: CryptoAPIDecryptor(*static_cast< ::default_init_tag* >(0))
{
ctor();
}
void poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::init()
{
length = -int64_t(1LL);
chunkSize = -int32_t(1);
}
void poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::ctor()
{
super::ctor();
init();
}
bool poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::verifyPassword(::java::lang::String* password)
{
auto ver = npc(getEncryptionInfo())->getVerifier();
auto skey = generateSecretKey(password, ver);
try {
auto cipher = initCipherForBlock(nullptr, 0, getEncryptionInfo(), skey, ::javax::crypto::Cipher::DECRYPT_MODE);
auto encryptedVerifier = npc(ver)->getEncryptedVerifier();
auto verifier = new ::int8_tArray(npc(encryptedVerifier)->length);
npc(cipher)->update(encryptedVerifier, 0, npc(encryptedVerifier)->length, verifier);
setVerifier(verifier);
auto encryptedVerifierHash = npc(ver)->getEncryptedVerifierHash();
auto verifierHash = npc(cipher)->doFinal(encryptedVerifierHash);
auto hashAlgo = npc(ver)->getHashAlgorithm();
auto hashAlg = ::poi::poifs::crypt::CryptoFunctions::getMessageDigest(hashAlgo);
auto calcVerifierHash = npc(hashAlg)->digest(verifier);
if(::java::util::Arrays::equals(calcVerifierHash, verifierHash)) {
setSecretKey(skey);
return true;
}
} catch (::java::security::GeneralSecurityException* e) {
throw new ::poi::EncryptedDocumentException(static_cast< ::java::lang::Throwable* >(e));
}
return false;
}
javax::crypto::Cipher* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::initCipherForBlock(::javax::crypto::Cipher* cipher, int32_t block) /* throws(GeneralSecurityException) */
{
auto ei = getEncryptionInfo();
auto sk = getSecretKey();
return initCipherForBlock(cipher, block, ei, sk, ::javax::crypto::Cipher::DECRYPT_MODE);
}
javax::crypto::Cipher* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::initCipherForBlock(::javax::crypto::Cipher* cipher, int32_t block, ::poi::poifs::crypt::EncryptionInfo* encryptionInfo, ::javax::crypto::SecretKey* skey, int32_t encryptMode) /* throws(GeneralSecurityException) */
{
clinit();
auto ver = npc(encryptionInfo)->getVerifier();
auto hashAlgo = npc(ver)->getHashAlgorithm();
auto blockKey = new ::int8_tArray(int32_t(4));
::poi::util::LittleEndian::putUInt(blockKey, 0, block);
auto hashAlg = ::poi::poifs::crypt::CryptoFunctions::getMessageDigest(hashAlgo);
npc(hashAlg)->update(npc(skey)->getEncoded());
auto encKey = npc(hashAlg)->digest(blockKey);
auto header = npc(encryptionInfo)->getHeader();
auto keyBits = npc(header)->getKeySize();
encKey = ::poi::poifs::crypt::CryptoFunctions::getBlock0(encKey, keyBits / int32_t(8));
if(keyBits == 40) {
encKey = ::poi::poifs::crypt::CryptoFunctions::getBlock0(encKey, 16);
}
::javax::crypto::SecretKey* key = new ::javax::crypto::spec::SecretKeySpec(encKey, npc(skey)->getAlgorithm());
if(cipher == nullptr) {
cipher = ::poi::poifs::crypt::CryptoFunctions::getCipher(key, npc(header)->getCipherAlgorithm(), nullptr, nullptr, encryptMode);
} else {
npc(cipher)->init_(encryptMode, static_cast< ::java::security::Key* >(key));
}
return cipher;
}
javax::crypto::SecretKey* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::generateSecretKey(::java::lang::String* password, ::poi::poifs::crypt::EncryptionVerifier* ver)
{
clinit();
if(npc(password)->length() > 255) {
password = npc(password)->substring(0, 255);
}
auto hashAlgo = npc(ver)->getHashAlgorithm();
auto hashAlg = ::poi::poifs::crypt::CryptoFunctions::getMessageDigest(hashAlgo);
npc(hashAlg)->update(npc(ver)->getSalt());
auto hash = npc(hashAlg)->digest(::poi::util::StringUtil::getToUnicodeLE(password));
::javax::crypto::SecretKey* skey = new ::javax::crypto::spec::SecretKeySpec(hash, npc(npc(ver)->getCipherAlgorithm())->jceId);
return skey;
}
poi::poifs::crypt::ChunkedCipherInputStream* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::getDataStream(::poi::poifs::filesystem::DirectoryNode* dir) /* throws(IOException, GeneralSecurityException) */
{
throw new ::java::io::IOException(u"not supported"_j);
}
poi::poifs::crypt::ChunkedCipherInputStream* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::getDataStream(::java::io::InputStream* stream, int32_t size, int32_t initialPos) /* throws(IOException, GeneralSecurityException) */
{
return new CryptoAPIDecryptor_CryptoAPICipherInputStream(this, stream, size, initialPos);
}
poi::poifs::filesystem::POIFSFileSystem* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::getSummaryEntries(::poi::poifs::filesystem::DirectoryNode* root, ::java::lang::String* encryptedStream) /* throws(IOException, GeneralSecurityException) */
{
auto es = java_cast< ::poi::poifs::filesystem::DocumentNode* >(npc(root)->getEntry(encryptedStream));
auto dis = npc(root)->createDocumentInputStream(static_cast< ::poi::poifs::filesystem::Entry* >(es));
auto bos = new ::java::io::ByteArrayOutputStream();
::poi::util::IOUtils::copy(dis, bos);
npc(dis)->close();
auto sbis = new CryptoAPIDocumentInputStream(this, npc(bos)->toByteArray_());
auto leis = new ::poi::util::LittleEndianInputStream(sbis);
::poi::poifs::filesystem::POIFSFileSystem* fsOut = nullptr;
{
auto finally0 = finally([&] {
::poi::util::IOUtils::closeQuietly(leis);
::poi::util::IOUtils::closeQuietly(sbis);
});
try {
auto streamDescriptorArrayOffset = static_cast< int32_t >(npc(leis)->readUInt());
npc(leis)->readUInt();
auto skipN = streamDescriptorArrayOffset - int64_t(8LL);
if(npc(sbis)->skip(skipN) < skipN) {
throw new ::java::io::EOFException(u"buffer underrun"_j);
}
npc(sbis)->setBlock(0);
auto encryptedStreamDescriptorCount = static_cast< int32_t >(npc(leis)->readUInt());
auto entries = new CryptoAPIDecryptor_StreamDescriptorEntryArray(encryptedStreamDescriptorCount);
for (auto i = int32_t(0); i < encryptedStreamDescriptorCount; i++) {
auto entry = new CryptoAPIDecryptor_StreamDescriptorEntry();
entries->set(i, entry);
npc(entry)->streamOffset = static_cast< int32_t >(npc(leis)->readUInt());
npc(entry)->streamSize = static_cast< int32_t >(npc(leis)->readUInt());
npc(entry)->block = npc(leis)->readUShort();
auto nameSize = npc(leis)->readUByte();
npc(entry)->flags = npc(leis)->readUByte();
npc(entry)->reserved2 = npc(leis)->readInt();
npc(entry)->streamName = ::poi::util::StringUtil::readUnicodeLE(leis, nameSize);
npc(leis)->readShort();
/* assert((npc(npc(entry)->streamName)->length() == nameSize)) */ ;
}
fsOut = new ::poi::poifs::filesystem::POIFSFileSystem();
for(auto entry : *npc(entries)) {
npc(sbis)->seek(npc(entry)->streamOffset);
npc(sbis)->setBlock(npc(entry)->block);
::java::io::InputStream* is = new ::poi::util::BoundedInputStream(sbis, npc(entry)->streamSize);
npc(fsOut)->createDocument(is, npc(entry)->streamName);
npc(is)->close();
}
} catch (::java::lang::Exception* e) {
::poi::util::IOUtils::closeQuietly(fsOut);
if(dynamic_cast< ::java::security::GeneralSecurityException* >(e) != nullptr) {
throw java_cast< ::java::security::GeneralSecurityException* >(e);
} else if(dynamic_cast< ::java::io::IOException* >(e) != nullptr) {
throw java_cast< ::java::io::IOException* >(e);
} else {
throw new ::java::io::IOException(u"summary entries can't be read"_j, e);
}
}
}
return fsOut;
}
int64_t poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::getLength()
{
if(length == -int64_t(1LL)) {
throw new ::java::lang::IllegalStateException(u"Decryptor.getDataStream() was not called"_j);
}
return length;
}
void poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::setChunkSize(int32_t chunkSize)
{
this->chunkSize = chunkSize;
}
poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::clone() /* throws(CloneNotSupportedException) */
{
return java_cast< CryptoAPIDecryptor* >(super::clone());
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIDecryptor", 55);
return c;
}
java::io::InputStream* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::getDataStream(::poi::poifs::filesystem::NPOIFSFileSystem* fs)
{
return super::getDataStream(fs);
}
java::io::InputStream* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::getDataStream(::poi::poifs::filesystem::OPOIFSFileSystem* fs)
{
return super::getDataStream(fs);
}
java::io::InputStream* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::getDataStream(::poi::poifs::filesystem::POIFSFileSystem* fs)
{
return super::getDataStream(fs);
}
java::lang::Class* poi::poifs::crypt::cryptoapi::CryptoAPIDecryptor::getClass0()
{
return class_();
}
| 43.396721
| 286
| 0.681399
|
pebble2015
|
9f68aa95585aa41d77e0ed106d383dd597cbf049
| 247
|
cpp
|
C++
|
matu379.cpp
|
NewtonVan/Fxxk_Y0u_m47u
|
d303c7f13c074b5462ac8390a9ff94e546099fac
|
[
"MIT"
] | 1
|
2020-09-26T16:47:16.000Z
|
2020-09-26T16:47:16.000Z
|
matu379.cpp
|
NewtonVan/Fxxk_Y0u_m47u
|
d303c7f13c074b5462ac8390a9ff94e546099fac
|
[
"MIT"
] | null | null | null |
matu379.cpp
|
NewtonVan/Fxxk_Y0u_m47u
|
d303c7f13c074b5462ac8390a9ff94e546099fac
|
[
"MIT"
] | 1
|
2020-09-26T16:47:40.000Z
|
2020-09-26T16:47:40.000Z
|
class CNumber
: public CNumberFactory
{
int num;
public:
CNumber(){}
void Add(int number)
{
num+= number;
}
void Sub(int number)
{
num-= number;
}
int GetValue()
{
return num;
}
void SetValue(int number)
{
num= number;
}
};
| 9.88
| 26
| 0.611336
|
NewtonVan
|
9f68f9c4a02e34a149a3938ce62b0ad322608fc9
| 1,526
|
cpp
|
C++
|
libs/numeric/mtl/test/forms_test.cpp
|
lit-uriy/mtl4-mirror
|
37cf7c2847165d3537cbc3400cb5fde6f80e3d8b
|
[
"MTLL"
] | 24
|
2019-03-26T15:25:45.000Z
|
2022-03-26T10:00:45.000Z
|
libs/numeric/mtl/test/forms_test.cpp
|
lit-uriy/mtl4-mirror
|
37cf7c2847165d3537cbc3400cb5fde6f80e3d8b
|
[
"MTLL"
] | 2
|
2020-04-17T12:35:32.000Z
|
2021-03-03T15:46:25.000Z
|
libs/numeric/mtl/test/forms_test.cpp
|
lit-uriy/mtl4-mirror
|
37cf7c2847165d3537cbc3400cb5fde6f80e3d8b
|
[
"MTLL"
] | 10
|
2019-12-01T13:40:30.000Z
|
2022-01-14T08:39:54.000Z
|
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
// 2008 Dresden University of Technology and the Trustees of Indiana University.
// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.
#include <iostream>
#include <cmath>
#include <boost/numeric/mtl/mtl.hpp>
template <typename ResMatrix, typename ArgMatrix>
void test(const ResMatrix&, const ArgMatrix& B)
{
ResMatrix C(B * B);
C+= trans(B) * B;
C+= trans(B) * B * B;
#if 0
std::cout << typeid(typename mtl::traits::category<mtl::mat::mat_mat_times_expr<ArgMatrix, ArgMatrix> >::type).name() << '\n';
std::cout << typeid(typename mtl::traits::category<mtl::mat::rscaled_view<ArgMatrix, double> >::type).name() << '\n';
char c; std::cin >> c;
#endif
C+= B * 3.5 * B * B;
C+= trans(B) * 3.5 * B * B;
C+= 3.5 * ArgMatrix(B * B);
C= 3.5 * ArgMatrix(B * B);
//C+= 3.5 * (B * B);
//C= 3.5 * (B * B);
}
int main(int, char**)
{
using namespace mtl;
typedef mat::parameters<tag::row_major, mtl::index::c_index, mtl::fixed::dimensions<2, 2>, true> fmat_para;
float ma[2][2]= {{2., 3.}, {4., 5.}};
dense2D<float> A_dyn(ma);
dense2D<float, fmat_para> A_stat(ma);
test(A_dyn, A_dyn);
//test(A_dyn, A_stat);
return 0;
}
| 26.77193
| 127
| 0.607471
|
lit-uriy
|
9f69caee1f05d4fe28323644c0d7adb9982389e5
| 33,406
|
cpp
|
C++
|
sources/unittests/HJIPDE_solve/UTest_HJIPDE_solve.cpp
|
mdoshi96/beacls
|
860426ed1336d9539dea195987efcdd8a8276a1c
|
[
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 30
|
2017-12-17T22:57:50.000Z
|
2022-01-30T17:06:34.000Z
|
sources/unittests/HJIPDE_solve/UTest_HJIPDE_solve.cpp
|
codingblazes/beacls
|
6c1d685ee00e3b39d8100c4a170a850682679abc
|
[
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 2
|
2017-03-24T06:18:16.000Z
|
2017-04-04T16:16:06.000Z
|
sources/unittests/HJIPDE_solve/UTest_HJIPDE_solve.cpp
|
codingblazes/beacls
|
6c1d685ee00e3b39d8100c4a170a850682679abc
|
[
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 8
|
2018-07-06T01:47:21.000Z
|
2021-07-23T15:50:34.000Z
|
#define _USE_MATH_DEFINES
#include <levelset/levelset.hpp>
#include <helperOC/helperOC.hpp>
#include <helperOC/DynSys/DynSys/DynSysSchemeData.hpp>
#include <helperOC/DynSys/DubinsCar/DubinsCar.hpp>
#include <helperOC/DynSys/DubinsCarCAvoid/DubinsCarCAvoid.hpp>
#include <helperOC/DynSys/Air3D/Air3D.hpp>
#include <sstream>
#include <iomanip>
#include "UTest_HJIPDE_solve.hpp"
#ifdef _OPENMP
#include <omp.h>
#endif
bool check_and_make_message(
std::string& message,
const std::vector<beacls::FloatVec>& expected_datas,
const std::vector<beacls::FloatVec>& result_datas,
const FLOAT_TYPE small
) {
FLOAT_TYPE min_diff = std::numeric_limits<FLOAT_TYPE>::max();
FLOAT_TYPE max_diff = 0;
FLOAT_TYPE first_diff = 0;
FLOAT_TYPE sum_of_square = 0;
size_t min_diff_t = 0;
size_t max_diff_t = 0;
size_t first_diff_t = 0;
size_t min_diff_index = 0;
size_t max_diff_index = 0;
size_t first_diff_index = 0;
size_t num_of_diffs = 0;
size_t num_of_datas = 0;
bool allSucceed = true;
for (size_t t = 0; t < result_datas.size(); ++t) {
const beacls::FloatVec& expected_data = expected_datas[t];
const beacls::FloatVec& result_data = result_datas[t];
for (size_t index = 0; index < result_data.size(); ++index) {
FLOAT_TYPE expected_result = expected_data[index];
FLOAT_TYPE result = result_data[index];
++num_of_datas;
const FLOAT_TYPE diff = std::abs(expected_result - result);
if (diff > small) {
allSucceed = false;
if (min_diff > diff) {
min_diff = diff;
min_diff_t = t;
min_diff_index = index;
}
if (max_diff < diff) {
max_diff = diff;
max_diff_t = t;
max_diff_index = index;
}
if (first_diff == 0) {
first_diff = diff;
first_diff_t = t;
first_diff_index = index;
}
sum_of_square += diff * diff;
++num_of_diffs;
}
}
}
if (!allSucceed) {
const FLOAT_TYPE rms = std::sqrt(sum_of_square / num_of_datas);
std::stringstream ss;
ss << "Error: # of Diffs = " << num_of_diffs << ", RMS = " << std::setprecision(16) << rms << std::resetiosflags(std::ios_base::floatfield)
<< ", First Diff " << std::setprecision(16) << first_diff << std::resetiosflags(std::ios_base::floatfield) << "@(" << first_diff_t << "," << first_diff_index
<< "), Max Diff " << std::setprecision(16) << max_diff << std::resetiosflags(std::ios_base::floatfield) << "@(" << max_diff_t << "," << max_diff_index
<< "), Min Diff " << std::setprecision(16) << min_diff << std::resetiosflags(std::ios_base::floatfield) << "@(" << min_diff_t << "," << min_diff_index
<< ")" << std::endl;
message.append(ss.str());
}
return allSucceed;
}
bool run_UTest_HJIPDE_solve_minWith(
std::string &message,
const std::vector<std::vector<beacls::FloatVec > >& expected_datas,
helperOC::DynSysSchemeData* schemeData,
beacls::FloatVec& tau,
beacls::FloatVec& data0,
const FLOAT_TYPE small,
const helperOC::ExecParameters& execParameters
) {
/*!< selecting 'zero' computes reachable tube(usually, choose this option)
selecting 'none' computes reachable set
selecting 'data0' computes reachable tube, but only use this if there are
obstacles_ptrs(constraint / avoid sets) in the state space
*/
std::vector<helperOC::HJIPDE::MinWithType> minWiths{helperOC::HJIPDE::MinWithType_None, helperOC::HJIPDE::MinWithType_Zero};
bool result = true;
for (size_t i = 0; i < minWiths.size(); ++i) {
helperOC::HJIPDE_extraArgs extraArgs;
helperOC::HJIPDE_extraOuts extraOuts;
extraArgs.keepLast = false;
extraArgs.execParameters = execParameters;
helperOC::HJIPDE* hjipde = new helperOC::HJIPDE();
beacls::FloatVec stoptau;
std::vector<beacls::FloatVec > datas;
const std::vector<beacls::FloatVec >& expected_datas_i = expected_datas[i];
hjipde->solve(datas, stoptau, extraOuts, data0, tau, schemeData, minWiths[i], extraArgs);
if (datas.empty()) {
std::stringstream ss;
ss << "Error result is empty: " << i << std::endl;
message.append(ss.str());
return false;
}
if (datas.size() != expected_datas_i.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << i << " : " << datas.size() << "!= " << expected_datas_i.size() << std::endl;
message.append(ss.str());
return false;
}
result &= check_and_make_message(
message,
expected_datas_i,
datas,
small
);
if(hjipde) delete hjipde;
}
return result;
}
/*
@brief Test using time-varying targets
*/
bool run_UTest_HJIPDE_solve_tvTarget(
std::string &message,
const std::vector<std::vector<beacls::FloatVec > >& expected_datas,
helperOC::DynSysSchemeData* schemeData,
beacls::FloatVec& tau,
beacls::FloatVec& data0,
const FLOAT_TYPE radius,
const FLOAT_TYPE small,
const helperOC::ExecParameters& execParameters
) {
const levelset::HJI_Grid *g = schemeData->get_grid();
std::vector<beacls::FloatVec> targets(tau.size());
beacls::FloatVec center{ 1.5,1.5,0. };
beacls::IntegerVec pdDims{ 2 }; //!< 2nd diemension is periodic
for (size_t i = 0; i < targets.size(); ++i) {
levelset::BasicShape* shape = new levelset::ShapeCylinder(pdDims, center, ((FLOAT_TYPE)i+1)/tau.size()*radius);
shape->execute(g, targets[i]);
delete shape;
}
helperOC::HJIPDE::MinWithType minWith = helperOC::HJIPDE::MinWithType_None;
bool result = true;
helperOC::HJIPDE_extraArgs extraArgs;
helperOC::HJIPDE_extraOuts extraOuts;
extraArgs.targets = targets;
extraArgs.keepLast = false;
extraArgs.execParameters = execParameters;
helperOC::HJIPDE* hjipde = new helperOC::HJIPDE();
beacls::FloatVec stoptau;
std::vector<beacls::FloatVec > datas;
const std::vector<beacls::FloatVec >& expected_datas_0 = expected_datas[0];
hjipde->solve(datas, stoptau, extraOuts, data0, tau, schemeData, minWith, extraArgs);
if (datas.empty()) {
std::stringstream ss;
ss << "Error result is empty" << std::endl;
message.append(ss.str());
return false;
}
if (datas.size() != expected_datas_0.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << datas.size() << "!= " << expected_datas_0.size() << std::endl;
message.append(ss.str());
return false;
}
result &= check_and_make_message(
message,
expected_datas_0,
datas,
small
);
if (hjipde) delete hjipde;
return result;
}
/*
@brief Test using single obstacle
*/
bool run_UTest_HJIPDE_solve_singleObs(
std::string &message,
const std::vector<std::vector<beacls::FloatVec > >& expected_datas,
helperOC::DynSysSchemeData* schemeData,
beacls::FloatVec& tau,
beacls::FloatVec& data0,
const FLOAT_TYPE radius,
const FLOAT_TYPE small,
const helperOC::ExecParameters& execParameters
) {
const levelset::HJI_Grid *g = schemeData->get_grid();
std::vector<beacls::FloatVec> obstacles(1);
beacls::FloatVec center{ 1.5,1.5,0. };
beacls::IntegerVec pdDims{ 2 }; //!< 2nd diemension is periodic
std::vector<beacls::FloatVec> targets(1);
targets[0] = data0;
levelset::BasicShape* shape = new levelset::ShapeCylinder(pdDims, center, (FLOAT_TYPE)(0.75*radius));
shape->execute(g, obstacles[0]);
delete shape;
helperOC::HJIPDE::MinWithType minWith = helperOC::HJIPDE::MinWithType_None;
bool result = true;
helperOC::HJIPDE_extraArgs extraArgs;
helperOC::HJIPDE_extraOuts extraOuts;
extraArgs.targets = targets;
extraArgs.obstacles = obstacles;
extraArgs.keepLast = false;
extraArgs.execParameters = execParameters;
helperOC::HJIPDE* hjipde = new helperOC::HJIPDE();
beacls::FloatVec stoptau;
std::vector<beacls::FloatVec > datas;
const std::vector<beacls::FloatVec >& expected_datas_0 = expected_datas[0];
hjipde->solve(datas, stoptau, extraOuts, data0, tau, schemeData, minWith, extraArgs);
if (datas.empty()) {
std::stringstream ss;
ss << "Error result is empty" << std::endl;
message.append(ss.str());
return false;
}
if (datas.size() != expected_datas_0.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << datas.size() << "!= " << expected_datas_0.size() << std::endl;
message.append(ss.str());
return false;
}
result &= check_and_make_message(
message,
expected_datas_0,
datas,
small
);
if (hjipde) delete hjipde;
return result;
}
/*
@brief Test using time-varying obstacle
*/
bool run_UTest_HJIPDE_solve_tvObs(
std::string &message,
const std::vector<std::vector<beacls::FloatVec > >& expected_datas,
helperOC::DynSysSchemeData* schemeData,
beacls::FloatVec& tau,
beacls::FloatVec& data0,
const FLOAT_TYPE radius,
const FLOAT_TYPE small,
const helperOC::ExecParameters& execParameters
) {
const levelset::HJI_Grid *g = schemeData->get_grid();
std::vector<beacls::FloatVec> obstacles(tau.size());
beacls::FloatVec center{ 1.5,1.5,0. };
beacls::IntegerVec pdDims{ 2 }; //!< 2nd diemension is periodic
std::vector<beacls::FloatVec> targets(1);
targets[0] = data0;
for (size_t i = 0; i < obstacles.size(); ++i) {
levelset::BasicShape* shape = new levelset::ShapeCylinder(pdDims, center, ((FLOAT_TYPE)i+1) / obstacles.size()*radius);
shape->execute(g, obstacles[i]);
delete shape;
}
helperOC::HJIPDE::MinWithType minWith = helperOC::HJIPDE::MinWithType_None;
bool result = true;
helperOC::HJIPDE_extraArgs extraArgs;
helperOC::HJIPDE_extraOuts extraOuts;
extraArgs.targets = targets;
extraArgs.obstacles = obstacles;
extraArgs.keepLast = false;
extraArgs.execParameters = execParameters;
helperOC::HJIPDE* hjipde = new helperOC::HJIPDE();
beacls::FloatVec stoptau;
std::vector<beacls::FloatVec > datas;
const std::vector<beacls::FloatVec >& expected_datas_0 = expected_datas[0];
hjipde->solve(datas, stoptau, extraOuts, data0, tau, schemeData, minWith, extraArgs);
if (datas.empty()) {
std::stringstream ss;
ss << "Error result is empty" << std::endl;
message.append(ss.str());
return false;
}
if (datas.size() != expected_datas_0.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << datas.size() << "!= " << expected_datas_0.size() << std::endl;
message.append(ss.str());
return false;
}
result &= check_and_make_message(
message,
expected_datas_0,
datas,
small
);
if (hjipde) delete hjipde;
return result;
}
/*
@brief Test using single obstacle but few time steps
*/
bool run_UTest_HJIPDE_solve_obs_stau(
std::string &message,
const std::vector<std::vector<beacls::FloatVec > >& expected_datas,
helperOC::DynSysSchemeData* schemeData,
beacls::FloatVec& data0,
const FLOAT_TYPE radius,
const FLOAT_TYPE small,
const helperOC::ExecParameters& execParameters
) {
const levelset::HJI_Grid *g = schemeData->get_grid();
std::vector<beacls::FloatVec> obstacles(1);
beacls::FloatVec center{ 1.5,1.5,0. };
beacls::IntegerVec pdDims{ 2 }; //!< 2nd diemension is periodic
std::vector<beacls::FloatVec> targets(1);
targets[0] = data0;
levelset::BasicShape* shape = new levelset::ShapeCylinder(pdDims, center, (FLOAT_TYPE)(0.75*radius));
shape->execute(g, obstacles[0]);
delete shape;
FLOAT_TYPE local_tau_bottom = 0.;
FLOAT_TYPE local_tau_top = 2.;
size_t local_tau_num = 5;
beacls::FloatVec local_tau(local_tau_num);
for (size_t i = 0; i < local_tau_num; ++i) {
local_tau[i] = local_tau_bottom + i * (local_tau_top - local_tau_bottom) / (local_tau_num - 1);
}
helperOC::HJIPDE::MinWithType minWith = helperOC::HJIPDE::MinWithType_None;
bool result = true;
helperOC::HJIPDE_extraArgs extraArgs;
helperOC::HJIPDE_extraOuts extraOuts;
extraArgs.targets = targets;
extraArgs.obstacles = obstacles;
extraArgs.keepLast = false;
extraArgs.execParameters = execParameters;
helperOC::HJIPDE* hjipde = new helperOC::HJIPDE();
beacls::FloatVec stoptau;
std::vector<beacls::FloatVec > datas;
const std::vector<beacls::FloatVec >& expected_datas_0 = expected_datas[0];
hjipde->solve(datas, stoptau, extraOuts, data0, local_tau, schemeData, minWith, extraArgs);
if (datas.empty()) {
std::stringstream ss;
ss << "Error result is empty" << std::endl;
message.append(ss.str());
return false;
}
if (datas.size() != expected_datas_0.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << datas.size() << "!= " << expected_datas_0.size() << std::endl;
message.append(ss.str());
return false;
}
result &= check_and_make_message(
message,
expected_datas_0,
datas,
small
);
if (hjipde) delete hjipde;
return result;
}
/*
@brief Test the inclusion of initial state
*/
bool run_UTest_HJIPDE_solve_stopInit(
std::string &message,
const std::vector<std::vector<beacls::FloatVec > >& expected_datas,
helperOC::DynSysSchemeData* schemeData,
beacls::FloatVec& data0,
const FLOAT_TYPE small,
const helperOC::ExecParameters& execParameters
) {
FLOAT_TYPE local_tau_bottom = 0.;
FLOAT_TYPE local_tau_top = 2.;
size_t local_tau_num = 50;
beacls::FloatVec local_tau(local_tau_num);
for (size_t i = 0; i < local_tau_num; ++i) {
local_tau[i] = local_tau_bottom + i * (local_tau_top - local_tau_bottom) / (local_tau_num - 1);
}
helperOC::HJIPDE::MinWithType minWith = helperOC::HJIPDE::MinWithType_None;
bool result = true;
helperOC::HJIPDE_extraArgs extraArgs;
helperOC::HJIPDE_extraOuts extraOuts;
extraArgs.stopInit = beacls::FloatVec{ (FLOAT_TYPE)-1.1, (FLOAT_TYPE)-1.1,(FLOAT_TYPE)0 };
extraArgs.keepLast = false;
extraArgs.execParameters = execParameters;
helperOC::HJIPDE* hjipde = new helperOC::HJIPDE();
beacls::FloatVec stoptau;
std::vector<beacls::FloatVec > datas;
const std::vector<beacls::FloatVec >& expected_datas_0 = expected_datas[0];
hjipde->solve(datas, stoptau, extraOuts, data0, local_tau, schemeData, minWith, extraArgs);
if (datas.empty()) {
std::stringstream ss;
ss << "Error result is empty" << std::endl;
message.append(ss.str());
return false;
}
if (datas.size() != expected_datas_0.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << datas.size() << "!= " << expected_datas_0.size() << std::endl;
message.append(ss.str());
return false;
}
result &= check_and_make_message(
message,
expected_datas_0,
datas,
small
);
if (hjipde) delete hjipde;
return result;
}
/*
@brief Test the inclusion of initial state
*/
bool run_UTest_HJIPDE_solve_stopSetInclude(
std::string &message,
const std::vector<std::vector<beacls::FloatVec > >& expected_datas,
helperOC::DynSysSchemeData* schemeData,
beacls::FloatVec& data0,
const FLOAT_TYPE small,
const helperOC::ExecParameters& execParameters
) {
const levelset::HJI_Grid *g = schemeData->get_grid();
beacls::FloatVec stopSetInclude;
levelset::BasicShape* shape = new levelset::ShapeSphere(beacls::FloatVec{(FLOAT_TYPE)-1.1, (FLOAT_TYPE)1.1, (FLOAT_TYPE)0}, (FLOAT_TYPE)0.5);
shape->execute(g, stopSetInclude);
delete shape;
FLOAT_TYPE local_tau_bottom = 0.;
FLOAT_TYPE local_tau_top = 2.;
size_t local_tau_num = 5;
beacls::FloatVec local_tau(local_tau_num);
for (size_t i = 0; i < local_tau_num; ++i) {
local_tau[i] = local_tau_bottom + i * (local_tau_top - local_tau_bottom) / (local_tau_num - 1);
}
helperOC::HJIPDE::MinWithType minWith = helperOC::HJIPDE::MinWithType_None;
bool result = true;
helperOC::HJIPDE_extraArgs extraArgs;
helperOC::HJIPDE_extraOuts extraOuts;
extraArgs.stopSetInclude = stopSetInclude;
extraArgs.keepLast = false;
extraArgs.execParameters = execParameters;
helperOC::HJIPDE* hjipde = new helperOC::HJIPDE();
beacls::FloatVec stoptau;
std::vector<beacls::FloatVec > datas;
const std::vector<beacls::FloatVec >& expected_datas_0 = expected_datas[0];
hjipde->solve(datas, stoptau, extraOuts, data0, local_tau, schemeData, minWith, extraArgs);
if (datas.empty()) {
std::stringstream ss;
ss << "Error result is empty" << std::endl;
message.append(ss.str());
return false;
}
if (datas.size() != expected_datas_0.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << datas.size() << "!= " << expected_datas_0.size() << std::endl;
message.append(ss.str());
return false;
}
result &= check_and_make_message(
message,
expected_datas_0,
datas,
small
);
if (hjipde) delete hjipde;
return result;
}
/*
@brief Test intersection of some set
*/
bool run_UTest_HJIPDE_solve_stopSetIntersect(
std::string &message,
const std::vector<std::vector<beacls::FloatVec > >& expected_datas,
helperOC::DynSysSchemeData* schemeData,
beacls::FloatVec& data0,
const FLOAT_TYPE small,
const helperOC::ExecParameters& execParameters
) {
const levelset::HJI_Grid *g = schemeData->get_grid();
beacls::FloatVec stopSetIntersect;
levelset::BasicShape* shape = new levelset::ShapeSphere(beacls::FloatVec{-1.25, 1.25, 0}, 0.5);
shape->execute(g, stopSetIntersect);
delete shape;
FLOAT_TYPE local_tau_bottom = 0.;
FLOAT_TYPE local_tau_top = 1.;
size_t local_tau_num = 11;
beacls::FloatVec local_tau(local_tau_num);
for (size_t i = 0; i < local_tau_num; ++i) {
local_tau[i] = local_tau_bottom + i * (local_tau_top - local_tau_bottom) / (local_tau_num - 1);
}
helperOC::HJIPDE::MinWithType minWith = helperOC::HJIPDE::MinWithType_None;
bool result = true;
helperOC::HJIPDE_extraArgs extraArgs;
helperOC::HJIPDE_extraOuts extraOuts;
extraArgs.stopSetIntersect = stopSetIntersect;
extraArgs.keepLast = false;
extraArgs.execParameters = execParameters;
helperOC::HJIPDE* hjipde = new helperOC::HJIPDE();
beacls::FloatVec stoptau;
std::vector<beacls::FloatVec > datas;
const std::vector<beacls::FloatVec >& expected_datas_0 = expected_datas[0];
hjipde->solve(datas, stoptau, extraOuts, data0, local_tau, schemeData, minWith, extraArgs);
if (datas.empty()) {
std::stringstream ss;
ss << "Error result is empty" << std::endl;
message.append(ss.str());
return false;
}
if (datas.size() != expected_datas_0.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << datas.size() << "!= " << expected_datas_0.size() << std::endl;
message.append(ss.str());
return false;
}
result &= check_and_make_message(
message,
expected_datas_0,
datas,
small
);
if (hjipde) delete hjipde;
return result;
}
/*
@brief Test the intermediate plotting
*/
bool run_UTest_HJIPDE_solve_plotData(
std::string &message,
const std::vector<std::vector<beacls::FloatVec > >& expected_datas,
helperOC::DynSysSchemeData* schemeData,
beacls::FloatVec& data0,
const FLOAT_TYPE radius,
const FLOAT_TYPE small,
const helperOC::ExecParameters& execParameters
) {
const levelset::HJI_Grid *g = schemeData->get_grid();
FLOAT_TYPE local_tau_bottom = 0.;
FLOAT_TYPE local_tau_top = 2.;
size_t local_tau_num = 51;
beacls::FloatVec local_tau(local_tau_num);
for (size_t i = 0; i < local_tau_num; ++i) {
local_tau[i] = local_tau_bottom + i * (local_tau_top - local_tau_bottom) / (local_tau_num - 1);
}
std::vector<beacls::FloatVec> obstacles(local_tau.size());
beacls::FloatVec center{ 1.5,1.5,0. };
beacls::IntegerVec pdDims{ 2 }; //!< 2nd diemension is periodic
for (size_t i = 0; i < obstacles.size(); ++i) {
levelset::BasicShape* shape = new levelset::ShapeCylinder(pdDims, center, ((FLOAT_TYPE)i + 1) / obstacles.size()*radius);
shape->execute(g, obstacles[i]);
delete shape;
}
helperOC::HJIPDE::MinWithType minWith = helperOC::HJIPDE::MinWithType_None;
bool result = true;
helperOC::HJIPDE_extraArgs extraArgs;
helperOC::HJIPDE_extraOuts extraOuts;
extraArgs.obstacles = obstacles;
extraArgs.keepLast = false;
extraArgs.execParameters = execParameters;
helperOC::HJIPDE* hjipde = new helperOC::HJIPDE();
beacls::FloatVec stoptau;
std::vector<beacls::FloatVec > datas;
const std::vector<beacls::FloatVec >& expected_datas_0 = expected_datas[0];
hjipde->solve(datas, stoptau, extraOuts, data0, local_tau, schemeData, minWith, extraArgs);
if (datas.empty()) {
std::stringstream ss;
ss << "Error result is empty" << std::endl;
message.append(ss.str());
return false;
}
if (datas.size() != expected_datas_0.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << datas.size() << "!= " << expected_datas_0.size() << std::endl;
message.append(ss.str());
return false;
}
result &= check_and_make_message(
message,
expected_datas_0,
datas,
small
);
if (hjipde) delete hjipde;
return result;
}
/*
@brief Test starting from saved data (where data0 has dimension g.dim + 1)
*/
bool run_UTest_HJIPDE_solve_savedData(
std::string &message,
const std::vector<std::vector<beacls::FloatVec > >& expected_datas,
helperOC::DynSysSchemeData* schemeData,
beacls::FloatVec& tau,
beacls::FloatVec& data0,
const FLOAT_TYPE small,
const helperOC::ExecParameters& execParameters
) {
helperOC::HJIPDE::MinWithType minWith = helperOC::HJIPDE::MinWithType_Zero;
bool result = true;
helperOC::HJIPDE_extraArgs extraArgs;
helperOC::HJIPDE_extraOuts extraOuts;
extraArgs.keepLast = false;
extraArgs.execParameters = execParameters;
helperOC::HJIPDE* hjipde = new helperOC::HJIPDE();
beacls::FloatVec stoptau;
std::vector<beacls::FloatVec > datas1;
const std::vector<beacls::FloatVec >& expected_datas_0 = expected_datas[0];
hjipde->solve(datas1, stoptau, extraOuts, data0, tau, schemeData, minWith, extraArgs);
if (datas1.empty()) {
std::stringstream ss;
ss << "Error result1 is empty" << std::endl;
message.append(ss.str());
return false;
}
if (datas1.size() != expected_datas_0.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << datas1.size() << "!= " << expected_datas_0.size() << std::endl;
message.append(ss.str());
return false;
}
//!< Cut off data 1
FLOAT_TYPE tcutoff = 0.5;
size_t istart = 1;
for (size_t i = 0; i < tau.size(); ++i) {
if (tau[i] > tcutoff) {
istart = i+1;
break;
}
}
extraArgs.istart = istart;
std::vector<beacls::FloatVec > dataSaved(tau.size());
std::copy(datas1.cbegin(), datas1.cbegin() + istart, dataSaved.begin());
std::vector<beacls::FloatVec > datas2;
hjipde->solve(datas2, stoptau, extraOuts, dataSaved, tau, schemeData, minWith, extraArgs);
if (datas2.empty()) {
std::stringstream ss;
ss << "Error result2 is empty" << std::endl;
message.append(ss.str());
return false;
}
if (datas2.size() != expected_datas_0.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << datas2.size() << "!= " << expected_datas_0.size() << std::endl;
message.append(ss.str());
return false;
}
std::string tmp_message;
result &= check_and_make_message(
tmp_message,
expected_datas_0,
datas1,
small
);
if (!tmp_message.empty()) {
message = std::string("Data1: ") + tmp_message;
tmp_message.clear();
}
result &= check_and_make_message(
tmp_message,
expected_datas_0,
datas2,
small
);
if (!tmp_message.empty()) {
message = std::string("Data2: ") + tmp_message;
tmp_message.clear();
}
result &= check_and_make_message(
tmp_message,
datas1,
datas2,
small
);
if (!tmp_message.empty()) {
message = std::string("Data1-Data2: ") + tmp_message;
tmp_message.clear();
}
if (hjipde) delete hjipde;
return result;
}
/*
@brief Test the intermediate plotting
*/
bool run_UTest_HJIPDE_solve_stopConverge(
std::string &message,
const std::vector<std::vector<beacls::FloatVec > >& expected_datas,
const bool isMiddleModel,
const bool isDubinsCarCAvoidModel,
const FLOAT_TYPE small,
const helperOC::ExecParameters& execParameters
) {
// Grid
beacls::IntegerVec Ns;
beacls::FloatVec grid_min;
beacls::FloatVec grid_max;
FLOAT_TYPE captureRadius;
if(!isMiddleModel){
Ns = beacls::IntegerVec{ 41, 41, 41 }; //!< Number of grid points per dimension
grid_min = beacls::FloatVec{ -5, -5, (FLOAT_TYPE)-M_PI }; //!< Lower corner of computation domain
grid_max = beacls::FloatVec{ 5, 5, (FLOAT_TYPE)M_PI }; //!< Upper corner of computation domain
captureRadius = 1;
}else{
Ns = beacls::IntegerVec{ 61, 61, 61 }; //!< Number of grid points per dimension
grid_min = beacls::FloatVec{ -25, -20, 0 }; //!< Lower corner of computation domain
grid_max = beacls::FloatVec{ 25, 20, (FLOAT_TYPE)(2*M_PI) }; //!< Upper corner of computation domain
captureRadius = 5;
}
beacls::IntegerVec pdDims{ 2 }; //!< 2nd diemension is periodic
FLOAT_TYPE va = 5;
FLOAT_TYPE vb = 5;
FLOAT_TYPE uMax = 1;
FLOAT_TYPE dMax = 1;
//!< problem parameters
FLOAT_TYPE speed = 1;
FLOAT_TYPE wMax = 1;
levelset::HJI_Grid* g = helperOC::createGrid(grid_min, grid_max, Ns, pdDims);
levelset::BasicShape* shape;
beacls::FloatVec center{ 0.,0.,0. }; //!< Center coordinate
shape = new levelset::ShapeCylinder(pdDims, center, captureRadius);
beacls::FloatVec data0;
shape->execute(g, data0);
if (shape) delete shape;
helperOC::DynSys* dynSys;
if(isDubinsCarCAvoidModel)
dynSys = new helperOC::DubinsCarCAvoid(beacls::FloatVec{(FLOAT_TYPE)0, (FLOAT_TYPE)0, (FLOAT_TYPE)0}, uMax, dMax, va, vb);
else
dynSys = new helperOC::DubinsCar(beacls::FloatVec{(FLOAT_TYPE)0, (FLOAT_TYPE)0, (FLOAT_TYPE)0}, wMax, speed);
//!< time vector
FLOAT_TYPE t0 = 0;
FLOAT_TYPE tMax = 5;
FLOAT_TYPE dt = (FLOAT_TYPE)0.01;
beacls::FloatVec tau = generateArithmeticSequence<FLOAT_TYPE>(t0, dt, tMax);
helperOC::DynSysSchemeData* schemeData = new helperOC::DynSysSchemeData;
schemeData->set_grid(g); //!< Grid MUST be specified!
//!<Dynamical system parameters
schemeData->dynSys = dynSys;
schemeData->uMode = helperOC::DynSys_UMode_Max;
schemeData->dMode = helperOC::DynSys_DMode_Min;
helperOC::HJIPDE::MinWithType minWith = helperOC::HJIPDE::MinWithType_Zero;
bool result = true;
helperOC::HJIPDE_extraArgs extraArgs;
helperOC::HJIPDE_extraOuts extraOuts;
extraArgs.keepLast = false;
extraArgs.execParameters = execParameters;
extraArgs.stopConverge = true;
extraArgs.convergeThreshold = (FLOAT_TYPE)1e-3;
helperOC::HJIPDE* hjipde = new helperOC::HJIPDE();
beacls::FloatVec stoptau;
std::vector<beacls::FloatVec > datas;
const std::vector<beacls::FloatVec >& expected_datas_0 = expected_datas[0];
hjipde->solve(datas, stoptau, extraOuts, data0, tau, schemeData, minWith, extraArgs);
if (datas.empty()) {
std::stringstream ss;
ss << "Error result is empty" << std::endl;
message.append(ss.str());
return false;
}
if (datas.size() != expected_datas_0.size()) {
std::stringstream ss;
ss << "Error time length of results is different: " << datas.size() << "!= " << expected_datas_0.size() << std::endl;
message.append(ss.str());
return false;
}
result &= check_and_make_message(
message,
expected_datas_0,
datas,
small
);
if (hjipde) delete hjipde;
if (dynSys) delete dynSys;
if (schemeData) delete schemeData;
return result;
}
bool run_UTest_HJIPDE_solve(
std::string &message,
const std::vector<std::string>& expects_filenames,
const HJIPDE_solve_WhatTest whatTest,
const HJIPDE_solve_Shape shapeType,
const beacls::UVecType type,
const FLOAT_TYPE small_diff,
const size_t chunk_size,
const int num_of_threads,
const int num_of_gpus,
const levelset::DelayedDerivMinMax_Type delayedDerivMinMax,
const bool enable_user_defined_dynamics_on_gpu
) {
helperOC::ExecParameters execParameters;
execParameters.useCuda = (type == beacls::UVecType_Cuda) ? true : false;
execParameters.line_length_of_chunk = chunk_size;
execParameters.num_of_threads = num_of_threads;
execParameters.num_of_gpus = num_of_gpus;
execParameters.delayedDerivMinMax = delayedDerivMinMax;
execParameters.enable_user_defined_dynamics_on_gpu = enable_user_defined_dynamics_on_gpu;
const size_t line_length_of_chunk = chunk_size;
const FLOAT_TYPE small = small_diff;
std::vector<std::vector<beacls::FloatVec > > expected_datas(expects_filenames.size());
std::transform(expects_filenames.cbegin(), expects_filenames.cend(), expected_datas.begin(), ([&message](const auto& rhs) {
std::vector<beacls::FloatVec > datas;
beacls::FloatVec data;
beacls::MatFStream* rhs_fs = beacls::openMatFStream(rhs, beacls::MatOpenMode_Read);
beacls::IntegerVec read_Ns;
if (!load_vector(data, std::string("data"), read_Ns, false, rhs_fs)) {
std::stringstream ss;
ss << "Cannot open expected result file: " << rhs.c_str() << std::endl;
message.append(ss.str());
beacls::closeMatFStream(rhs_fs);
return std::vector<beacls::FloatVec >();
}
datas.resize(read_Ns[read_Ns.size() - 1]);
size_t num_of_elements = std::accumulate(read_Ns.cbegin(), read_Ns.cbegin() + read_Ns.size() - 1, (size_t)1, [](const auto& lhs, const auto& rhs) { return lhs * rhs; });
for (size_t t = 0; t < datas.size(); ++t){
datas[t].resize(num_of_elements);
std::copy(data.cbegin() + t*num_of_elements, data.cbegin() + (t + 1)*num_of_elements, datas[t].begin());
}
beacls::closeMatFStream(rhs_fs);
return datas;
}));
if (std::any_of(expected_datas.cbegin(), expected_datas.cend(), [](const auto& rhs) { return rhs.empty(); })) {
return false;
}
// Grid
beacls::FloatVec grid_min{ -5, -5, (FLOAT_TYPE)-M_PI }; //!< Lower corner of computation domain
beacls::FloatVec grid_max{ 5, 5, (FLOAT_TYPE)M_PI }; //!< Upper corner of computation domain
beacls::IntegerVec Ns = beacls::IntegerVec{ 41, 41, 41 }; //!< Number of grid points per dimension
beacls::IntegerVec pdDims{ 2 }; //!< 2nd diemension is periodic
levelset::HJI_Grid* g = helperOC::createGrid(grid_min, grid_max, Ns, pdDims);
// state space dimensions
// target set
levelset::BasicShape* shape;
FLOAT_TYPE radius = 1;
beacls::FloatVec center{ 0.,0.,0.}; //!< Center coordinate
switch (shapeType) {
default:
case HJIPDE_solve_Shape_Invalid:
{
std::stringstream ss;
ss << "Error Invalid Shape type: " << shapeType << std::endl;
message.append(ss.str());
}
return false;
case HJIPDE_solve_Shape_Cylinder:
shape = new levelset::ShapeCylinder(pdDims, center, radius);
break;
case HJIPDE_solve_Shape_Sphere:
shape = new levelset::ShapeSphere(center, radius);
break;
case HJIPDE_solve_Shape_RectangleByCorner:
shape = new levelset::ShapeRectangleByCorner(beacls::FloatVec{-radius, -radius, -radius}, beacls::FloatVec{radius, radius, radius});
break;
case HJIPDE_solve_Shape_RectangleByCenter:
shape = new levelset::ShapeRectangleByCenter(center, beacls::FloatVec{radius,radius,radius});
break;
}
beacls::FloatVec data0;
shape->execute(g, data0);
//!< time vector
FLOAT_TYPE t0 = 0;
FLOAT_TYPE tMax = 2;
FLOAT_TYPE dt = (FLOAT_TYPE)0.025;
beacls::FloatVec tau = generateArithmeticSequence<FLOAT_TYPE>(t0, dt, tMax);
// If intermediate results are not needed, use
// beacls::FloatVec tau = generateArithmeticSequence(t0, tMax, tMax);
//!< problem parameters
FLOAT_TYPE speed = 1;
FLOAT_TYPE wMax = 1;
//!< Pack problem parameters
helperOC::DynSysSchemeData* schemeData = new helperOC::DynSysSchemeData;
schemeData->set_grid(g); //!< Grid MUST be specified!
//!<Dynamical system parameters
helperOC::DubinsCar* dCar = new helperOC::DubinsCar(beacls::FloatVec{(FLOAT_TYPE)0, (FLOAT_TYPE)0, (FLOAT_TYPE)0}, wMax, speed);
schemeData->dynSys = dCar;
bool result = true;
switch (whatTest) {
default:
case HJIPDE_solve_WhatTest_Invalid:
{
std::stringstream ss;
ss << "Error Invalid test type: " << whatTest << std::endl;
message.append(ss.str());
}
result = false;
break;
case HJIPDE_solve_WhatTest_minWith:
result = run_UTest_HJIPDE_solve_minWith(message, expected_datas, schemeData, tau, data0,small, execParameters);
break;
case HJIPDE_solve_WhatTest_tvTargets:
result = run_UTest_HJIPDE_solve_tvTarget(message, expected_datas, schemeData, tau, data0, radius,small, execParameters);
break;
case HJIPDE_solve_WhatTest_singleObs:
result = run_UTest_HJIPDE_solve_singleObs(message, expected_datas, schemeData, tau, data0, radius,small, execParameters);
break;
case HJIPDE_solve_WhatTest_tvObs:
result = run_UTest_HJIPDE_solve_tvObs(message, expected_datas, schemeData, tau, data0, radius,small, execParameters);
break;
case HJIPDE_solve_WhatTest_obs_stau:
result = run_UTest_HJIPDE_solve_obs_stau(message, expected_datas, schemeData, data0, radius,small, execParameters);
break;
case HJIPDE_solve_WhatTest_stopInit:
result = run_UTest_HJIPDE_solve_stopInit(message, expected_datas, schemeData, data0,small, execParameters);
break;
case HJIPDE_solve_WhatTest_stopSetInclude:
result = run_UTest_HJIPDE_solve_stopSetInclude(message, expected_datas, schemeData, data0,small, execParameters);
break;
case HJIPDE_solve_WhatTest_stopSetIntersect:
result = run_UTest_HJIPDE_solve_stopSetIntersect(message, expected_datas, schemeData, data0,small, execParameters);
break;
case HJIPDE_solve_WhatTest_plotData:
result = run_UTest_HJIPDE_solve_plotData(message, expected_datas, schemeData, data0, radius,small, execParameters);
break;
case HJIPDE_solve_WhatTest_savedData:
result = run_UTest_HJIPDE_solve_savedData(message, expected_datas, schemeData, tau, data0,small, execParameters);
break;
case HJIPDE_solve_WhatTest_stopConvergeSmallDubinsCar:
result = run_UTest_HJIPDE_solve_stopConverge(message, expected_datas, false, false,small, execParameters);
break;
case HJIPDE_solve_WhatTest_stopConvergeSmallDubinsCarCAvoid:
result = run_UTest_HJIPDE_solve_stopConverge(message, expected_datas, false, true,small, execParameters);
break;
}
if (dCar) delete dCar;
if (shape) delete shape;
if (schemeData) delete schemeData;
if (g) delete g;
return result;
}
| 32.464529
| 171
| 0.719003
|
mdoshi96
|
9f6e36adaf6b346d9611e7844be006a208a6b40d
| 5,855
|
cpp
|
C++
|
src/MainFrame.cpp
|
senfti/Kacarsonne
|
f2e3cbd7fd80bd1c9a6e41f03544b1e0718c0bd2
|
[
"MIT"
] | 4
|
2020-04-10T19:11:28.000Z
|
2020-05-01T11:25:46.000Z
|
src/MainFrame.cpp
|
senfti/Kacarsonne
|
f2e3cbd7fd80bd1c9a6e41f03544b1e0718c0bd2
|
[
"MIT"
] | 2
|
2020-05-07T17:34:40.000Z
|
2020-06-05T18:53:29.000Z
|
src/MainFrame.cpp
|
senfti/Kacarsonne
|
f2e3cbd7fd80bd1c9a6e41f03544b1e0718c0bd2
|
[
"MIT"
] | 2
|
2020-04-10T19:11:34.000Z
|
2020-12-08T19:12:31.000Z
|
//
// Created by ts on 24.03.20.
//
#include <filesystem>
#include <MainFrame.h>
#include <IdsDialog.h>
#include <PointEntryDialog.h>
#include <PointHistoryWindow.h>
#include <SettingsWindow.h>
#include "main.h"
MainFrame::MainFrame(MyApp* app) : MainFrame_B(nullptr), app_(app), timer_(this){
}
MainFrame::~MainFrame(){
}
void MainFrame::setGame(Game *game, bool restart){
{
std::lock_guard<std::mutex> lock(game->data_lock_);
game_ = game;
if(!game_->connection_->iAmHost())
restart_menu_item_->Enable(false);
table_panel_->setGame(game);
pt_history_wnd_ = new PointHistoryWindow(this, game->players_);
pt_history_wnd_id_ = pt_history_wnd_->GetId();
// pt_history_wnd_->Show();
}
std::lock_guard<std::mutex> lock(game_->data_lock_);
if(restart){
for(auto& pg : players_guis_)
pg->setPoints(0);
}
else{
int i=0;
for(const auto &p : game_->players_){
players_guis_.push_back(new PointGroup(p.name_, p.color_, game_->connection_->player_number_ == i++, this));
info_sizer_->Add(players_guis_.back());
}
if(!players_guis_.empty())
players_guis_[0]->setActive(true, false);
Connect(timer_.GetId(), wxEVT_TIMER, wxTimerEventHandler(MainFrame::OnTimer), NULL, this);
timer_.Start(100);
}
table_panel_->initOffset();
}
void MainFrame::setCurrentPlayer(int player){
for(unsigned i = 0; i < players_guis_.size(); i++){
players_guis_[i]->setActive(player == int(i), game_->current_card_);
}
}
void MainFrame::quit(wxCommandEvent &event){
takeScreenshot("");
Destroy();
}
void MainFrame::next(wxCommandEvent &event){
next();
}
void MainFrame::next(){
if(game_->next()){
next_button_->Enable(game_->isActive());
back_button_->Enable(game_->isActive());
shuffle_button_->Enable(game_->isActive() && game_->current_card_);
std::lock_guard<std::mutex> lock(game_->data_lock_);
setCurrentPlayer(game_->current_player_);
}
}
void MainFrame::back(wxCommandEvent &event){
if(game_->revert()){
next_button_->Enable(game_->isActive());
back_button_->Enable(game_->isActive());
shuffle_button_->Enable(game_->isActive() && game_->current_card_);
table_panel_->Refresh();
table_panel_->Update();
}
}
void MainFrame::shuffle( wxCommandEvent& event ){
if(game_->shuffle()){
table_panel_->Refresh();
table_panel_->Update();
}
}
void MainFrame::restart( wxCommandEvent& event ){
if(game_->connection_->iAmHost()){
takeScreenshot("");
app_->reset(false);
}
}
void MainFrame::newGame( wxCommandEvent& event ){
takeScreenshot("");
app_->reset(true);
}
void MainFrame::help( wxCommandEvent& event ){
HelpDialog_B help_dialog(this);
help_dialog.ShowModal();
}
void MainFrame::showIds( wxCommandEvent& event ){
IdsDialog d(this, game_->connection_);
d.ShowModal();
}
void MainFrame::viewSettings( wxCommandEvent& event ){
SettingsWindow wnd(this, &game_->card_count_);
wnd.ShowModal();
}
void MainFrame::OnTimer(wxTimerEvent &event){
next_button_->Enable(game_->isActive() && !game_->current_card_ && game_->stack_.getLeftCards());
back_button_->Enable(game_->isActive());
shuffle_button_->Enable(game_->isActive() && game_->current_card_ && !game_->played_cards_.empty() && game_->stack_.getLeftCards());
table_panel_->checkFlip();
setCurrentPlayer(game_->current_player_);
if(game_->update_table_){
game_->update_table_ = false;
table_panel_->Refresh();
}
int next_preview = game_->getPreviewCard();
if(next_preview != preview_image_){
if(next_preview >= 0 && next_preview < int(Card::CARD_IMAGES.size())){
wxSize size = preview_bitmap_->GetClientSize();
preview_bitmap_->SetBitmap(wxBitmap(Card::CARD_IMAGES[next_preview].image_.Scale(size.x, size.y)));
}
else{
wxSize size = preview_bitmap_->GetClientSize();
preview_bitmap_->SetBitmap(wxBitmap(wxImage(size)));
}
preview_image_ = next_preview;
}
for(unsigned i = 0; i < players_guis_.size(); i++){
std::lock_guard<std::mutex> lock(game_->data_lock_);
players_guis_[i]->setPoints(game_->players_[i].points_);
players_guis_[i]->setStones(game_->players_[i].getRemainingStones());
if(game_->update_old_pts_)
players_guis_[i]->setOldPoints(game_->players_[i].points_);
if(FindWindowById(pt_history_wnd_id_))
pt_history_wnd_->setPoints(i, game_->players_[i].points_);
}
game_->update_old_pts_ = false;
{
std::lock_guard<std::mutex> lock(game_->data_lock_);
auto flare = game_->flares_.begin();
bool refresh = !game_->flares_.empty();
while(flare != game_->flares_.end()){
if(flare->isTimeout())
flare = game_->flares_.erase(flare);
else
break;
}
if(refresh){
table_panel_->Refresh();
}
}
static unsigned long long last_curr_time = getTime();
if(game_->current_card_)
last_curr_time = getTime();
else if(getTime() - last_curr_time > 3 && !game_->isFirst())
next();
}
void MainFrame::disable(){
timer_.Stop();
}
void MainFrame::takeScreenshot(const std::string& prefix){
if(!std::filesystem::exists("screenshots")){
std::filesystem::create_directory("screenshots");
}
wxScreenDC screen_dc;
wxSize size = GetClientSize();
wxPoint pos = ClientToScreen(wxPoint(0, 0));
wxBitmap screenshot(size.GetWidth(), size.GetHeight(), -1);
wxMemoryDC mem_dc;
mem_dc.SelectObject(screenshot);
mem_dc.Blit(0, 0, size.GetWidth(), size.GetHeight(), &screen_dc, pos.x, pos.y);
mem_dc.SelectObject(wxNullBitmap);
auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::string s(30, '\0');
std::strftime(&s[0], s.size(), "%Y-%m-%d %H-%M-%S", std::localtime(&now));
s = std::string(s.c_str());
screenshot.SaveFile("screenshots/" + prefix + s + ".png", wxBITMAP_TYPE_PNG);
}
| 29.129353
| 134
| 0.680956
|
senfti
|
9f720605a730030172b5aaa721d170d2a2e21961
| 1,595
|
cpp
|
C++
|
December-07/cpp_aw3someone.cpp
|
Aw3someOne/A-December-of-Algorithms-2019
|
0b17b3a0360d1906babc141dd8a4b9ac67d1b609
|
[
"MIT"
] | null | null | null |
December-07/cpp_aw3someone.cpp
|
Aw3someOne/A-December-of-Algorithms-2019
|
0b17b3a0360d1906babc141dd8a4b9ac67d1b609
|
[
"MIT"
] | null | null | null |
December-07/cpp_aw3someone.cpp
|
Aw3someOne/A-December-of-Algorithms-2019
|
0b17b3a0360d1906babc141dd8a4b9ac67d1b609
|
[
"MIT"
] | null | null | null |
#include <deque>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
struct Patient {
int token;
std::string id;
Patient(int token, std::string id) : token(token), id(id) {}
};
std::ostream& operator<<(std::ostream& os, const Patient* p) {
os << '(' << p->token << ", " << p->id << ')';
return os;
}
class Queue {
std::deque<Patient*> _d;
public:
bool promote(std::string id) {
for (auto it = _d.begin(); it != _d.end(); ++it) {
if ((*it)->id == id) {
Patient* tmp = *it;
_d.erase(it, it + 1);
_d.push_front(tmp);
return true;
}
}
return false;
}
void enqueue(Patient* p) {
_d.push_back(p);
}
size_t size() const {
return _d.size();
}
friend std::ostream& operator<<(std::ostream& os, const Queue& q);
};
std::ostream& operator<<(std::ostream& os, const Queue& q) {
for (const auto p : q._d)
os << p << std::endl;
return os;
}
int main() {
int N = 0;
for (std::string line; std::cout << "Enter N: " && getline(std::cin, line);) {
std::istringstream iss(line);
if (iss >> N && N > 0) break;
}
std::cout << "Enter (token no, id):" << std::endl;
Queue queue;
for (std::string line; queue.size() < N && getline(std::cin, line);) {
std::istringstream iss(line);
char _;
int token;
std::string id;
if (!(iss >> _ >> token >> _ >> id)) continue;
if ((*id.rbegin()) != ')') continue;
id.pop_back();
queue.enqueue(new Patient(token, id));
}
std::cout << "Enter k: ";
std::string k;
std::cin >> k;
queue.promote(k);
std::cout << "The order is:" << std::endl;
std::cout << queue << std::endl;
}
| 21.849315
| 79
| 0.574295
|
Aw3someOne
|
9f7553ebf2a7873002ca73d4855aed08e888f059
| 654
|
cpp
|
C++
|
examples/stream1.cpp
|
mjcaisse/cppnow-2017-network-ts-material
|
128bcf2a718e8f13c2991520a56ddc41b3ccb28b
|
[
"BSL-1.0"
] | 5
|
2017-05-19T23:03:26.000Z
|
2021-05-03T13:40:19.000Z
|
examples/stream1.cpp
|
mjcaisse/cppnow-2017-network-ts-material
|
128bcf2a718e8f13c2991520a56ddc41b3ccb28b
|
[
"BSL-1.0"
] | 1
|
2018-05-15T18:40:33.000Z
|
2018-05-15T18:40:33.000Z
|
examples/stream1.cpp
|
mjcaisse/cppnow-2017-network-ts-material
|
128bcf2a718e8f13c2991520a56ddc41b3ccb28b
|
[
"BSL-1.0"
] | 2
|
2017-10-03T13:23:34.000Z
|
2018-04-23T16:19:11.000Z
|
#include <experimental/net>
#include <chrono>
#include <string>
#include <iostream>
using namespace std::chrono_literals;
namespace net = std::experimental::net;
int main()
{
net::ip::tcp::iostream s;
s.expires_after(5s);
s.connect("www.boost.org", "https");
if(!s)
{
std::cout << "error: " << s.error().message() << std::endl;
return -1;
}
s << "GET / HTTP/1.0\r\n";
s << "Host: www.boost.org\r\n";
s << "Accept: */*\r\n";
s << "Connection: close\r\n\r\n";
std::string header;
while(s && std::getline(s, header) && header != "\r")
std::cout << header << "\n";
std::cout << s.rdbuf();
}
| 19.818182
| 65
| 0.553517
|
mjcaisse
|
9f76ed3dc86b8f58ae5eedad16f2b785be9667fc
| 1,436
|
cpp
|
C++
|
v1/CException.cpp
|
lanyj/mcts
|
8394acaf3e83020b0bdfaa6117553d1ad64be291
|
[
"MIT"
] | null | null | null |
v1/CException.cpp
|
lanyj/mcts
|
8394acaf3e83020b0bdfaa6117553d1ad64be291
|
[
"MIT"
] | null | null | null |
v1/CException.cpp
|
lanyj/mcts
|
8394acaf3e83020b0bdfaa6117553d1ad64be291
|
[
"MIT"
] | null | null | null |
#pragma once
#include "stdafx.h"
#include "CException.h"
CException::CException(const char* msg) {
this->name = "CException";
this->msg = msg;
}
void CException::printMsg() {
printf("%s:\n\t%s\n", name, msg);
exit(-1);
}
CIndexOutOfBoundsException::CIndexOutOfBoundsException(int index, int bounds, const char* msg) : CException(msg) {
this->index = index;
this->bounds = bounds;
this->name = "CIndexOutOfBoundsException";
}
void CIndexOutOfBoundsException::printMsg() {
printf("%s: Index: %d, Size: %d\n\t%s\n", name, index, bounds, msg);
exit(-1);
}
CKeyNotFoundException::CKeyNotFoundException(const char* msg) : CException(msg) {
this->name = "CKeyNotFoundException";
}
CEmptyStackException::CEmptyStackException(const char* msg) : CException(msg) {
this->name = "CEmptyStackException";
}
CEmptyQueueException::CEmptyQueueException(const char* msg) : CException(msg) {
this->name = "CEmptyQueueException";
}
CRootOfTreeException::CRootOfTreeException(const char* msg) : CException(msg) {
this->name = "CRootOfTreeException";
}
CNoSuchChildException::CNoSuchChildException(const char* msg) : CException(msg) {
this->name = "CNoSuchChildException";
}
CBoundsOfChildException::CBoundsOfChildException(const char* msg) : CException(msg) {
this->name = "CBoundsOfChildException";
}
CIllegalStateException::CIllegalStateException(const char* msg) : CException(msg) {
this->name = "CIllegalStateException";
};
| 27.09434
| 114
| 0.738162
|
lanyj
|
9f80bd6eeaad3f9add9d3e97470aba3629a4297a
| 11,605
|
cpp
|
C++
|
editor/renderer/src/Material.cpp
|
lizardkinger/blacksun
|
0119948726d2a057c13d208044c7664a8348a1ea
|
[
"Linux-OpenIB"
] | null | null | null |
editor/renderer/src/Material.cpp
|
lizardkinger/blacksun
|
0119948726d2a057c13d208044c7664a8348a1ea
|
[
"Linux-OpenIB"
] | null | null | null |
editor/renderer/src/Material.cpp
|
lizardkinger/blacksun
|
0119948726d2a057c13d208044c7664a8348a1ea
|
[
"Linux-OpenIB"
] | null | null | null |
/***************************************************************************
* Copyright (C) 2006-07 by Reinhard Jeschull
* rjeschu@fh-landshut.de
*
* 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 this program; if not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* (See COPYING for details.)
***************************************************************************
*
* Module: Renderer (BlackSun)
* File: Material.cpp
* Created: 28.11.2006
* Author: Reinhard Jeschull (rjeschu)
*
**************************************************************************/
#include "../include/Material.h"
#include "../include/Renderer.h"
namespace BSRenderer
{
int Material::nMagicNumber = 24022007;
Material::Material(const string& sName)
: QObject(), m_sName(sName)
{
setToDefault();
}
Material::Material(const Material& otherMaterial)
: QObject()
{
m_dSpecularFactor = otherMaterial.m_dSpecularFactor;
m_sName = otherMaterial.m_sName;
m_cColor = otherMaterial.m_cColor;
m_cAmbient = otherMaterial.m_cAmbient;
m_cDiffuse = otherMaterial.m_cDiffuse;
m_cSpecular = otherMaterial.m_cSpecular;
m_cEmissive = otherMaterial.m_cEmissive;
m_dSpecularFactor = otherMaterial.m_dSpecularFactor;
for(int i = 0 ; i < MAXTEXTURES ; i++)
{
m_tex[i] = otherMaterial.m_tex[i];
m_texState[i] = otherMaterial.m_texState[i];
}
}
void Material::set()
{
int nTexStage = 0;
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_TEXTURE_2D);
//First deactive all textures
for(int t=0; t<MAXTEXTURES; t++)
{
glActiveTextureARB(GL_TEXTURE0_ARB+t);
glDisable(GL_TEXTURE_2D);
}
for(int t=0; t<MAXTEXTURES; t++)
{
//Texture is not valid
if(m_tex[t] == -1)
{
//Disable the stage
glActiveTextureARB(GL_TEXTURE0_ARB+t);
glDisable(GL_TEXTURE_2D);
continue;
}
//Set the texture and the texture-state
m_texState[t].set(nTexStage);
TextureManager::getInstance()->getTexture(m_tex[t])->set(nTexStage);
nTexStage++;
}
//No textures are set, so the texturing can be disabled
if(nTexStage==0)
glDisable(GL_TEXTURE_2D);
//glMaterial does not support double-values. So it must be
//converted into a float-array
float fAmbient[4], fDiffuse[4], fSpecular[4], fEmissive[4];
m_cAmbient.getFloatArray(&fAmbient[0]);
m_cDiffuse.getFloatArray(&fDiffuse[0]);
m_cSpecular.getFloatArray(&fSpecular[0]);
m_cEmissive.getFloatArray(&fEmissive[0]);
//Set the material
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, fAmbient);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, fDiffuse);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, fSpecular);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, fEmissive);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, m_dSpecularFactor);
}
bool Material::save(const string& sFileName)
{
ofstream f(sFileName.c_str(), ios::binary);
//File can't be opened
if(f.rdstate())
{
stringstream msg;
msg << "Can't open file: \"" << sFileName << "\"";
LOG_Error(msg.str());
return false;
}
if(appendToFile(f)==false)
return false;
f.close();
stringstream msg;
msg << "Material saved: \"" << sFileName << "\"";
LOG_Ok(msg.str());
return true;
}
bool Material::load(const string& sFileName)
{
ifstream f(sFileName.c_str(), ios::binary);
//File can't be opened
if(f.rdstate())
{
stringstream msg;
msg << "Can't open file: \"" << sFileName << "\"";
LOG_Error(msg.str());
return false;
}
loadFromFilePos(f, 0);
f.close();
stringstream msg;
msg << "Material loaded: \"" << sFileName << "\"";
LOG_Ok(msg.str());
emit changed();
return true;
}
bool Material::appendToFile(ofstream& f)
{
//Write magic number of material file
f.write(reinterpret_cast<char*>(&nMagicNumber), sizeof(nMagicNumber));
//Write the material name
UINT nLength = m_sName.length();
f.write(reinterpret_cast<char*>(&nLength), sizeof(nLength));
for(UINT i=0; i<nLength; i++)
f.write(reinterpret_cast<char*>(&m_sName[i]), sizeof(m_sName[i]));
//Write texture-ID with path if needed
TextureManager* pTexMgr = TextureManager::getInstance();
vector<int> texturesNeeded;
for(int t=0; t<MAXTEXTURES; t++)
{
if(m_tex[t] < 0)
continue;
for(unsigned int i=0; i<texturesNeeded.size(); i++)
{
//Texture is already in list
if(texturesNeeded[i] == m_tex[t])
break;
}
texturesNeeded.push_back(m_tex[t]);
}
int nTexNum = texturesNeeded.size();
f.write(reinterpret_cast<char*>(&nTexNum), sizeof(UINT));
for(int t=0; t<nTexNum; t++)
{
//Write ID of the texture
f.write(reinterpret_cast<char*>(&texturesNeeded[t]), sizeof(int));
//Write the texture name/path
string sTexName = pTexMgr->getTexture(texturesNeeded[t])->getTextureInfo()->sName;
UINT nLength = sTexName.length();
f.write(reinterpret_cast<char*>(&nLength), sizeof(nLength));
for(UINT i=0; i<nLength; i++)
f.write(reinterpret_cast<char*>(&sTexName[i]), sizeof(sTexName[i]));
}
//Write the pure material data
f.write(reinterpret_cast<char*>(&m_cColor), sizeof(Color));
f.write(reinterpret_cast<char*>(&m_cAmbient), sizeof(Color));
f.write(reinterpret_cast<char*>(&m_cDiffuse), sizeof(Color));
f.write(reinterpret_cast<char*>(&m_cSpecular), sizeof(Color));
f.write(reinterpret_cast<char*>(&m_cEmissive), sizeof(Color));
f.write(reinterpret_cast<char*>(&m_dSpecularFactor), sizeof(m_dSpecularFactor));
//Write the max. texture stages per material
int nMaxTex = MAXTEXTURES;
f.write(reinterpret_cast<char*>(&nMaxTex), sizeof(nMaxTex));
//Write the textur stages of the material
for(int i=0; i<MAXTEXTURES; i++)
{
f.write(reinterpret_cast<char*>(&m_tex[i]), sizeof(int));
f.write(reinterpret_cast<char*>(&m_texState[i]), sizeof(TextureState));
}
return true;
}
bool Material::loadFromFilePos(ifstream& f, int nPos)
{
//Walk to the file position
f.seekg(nPos, ios::beg);
//Read magic number of material file
int nNumber;
f.read(reinterpret_cast<char*>(&nNumber), sizeof(nNumber));
//Its no material file, so return
if(nNumber != nMagicNumber)
{
stringstream msg;
msg << "Material-version file not supported: " << nNumber;
LOG_Error(msg.str());
return false;
}
//Read the material name
UINT nLength;
f.read(reinterpret_cast<char*>(&nLength), sizeof(nLength));
m_sName.resize(nLength);
for(UINT i=0; i<nLength; i++)
f.read(reinterpret_cast<char*>(&m_sName[i]), sizeof(m_sName[i]));
vector<int> texturesNeededID;
vector<string> texturesNeededName;
UINT nNumTex = 0;
f.read(reinterpret_cast<char*>(&nNumTex), sizeof(UINT));
for(unsigned int t=0; t<nNumTex; t++)
{
//Read ID of the texture
int nID = -1;
f.read(reinterpret_cast<char*>(&nID), sizeof(int));
//Write the texture name/path
string sTexName;
UINT nLength = 0;
f.read(reinterpret_cast<char*>(&nLength), sizeof(nLength));
sTexName.resize(nLength);
for(UINT i=0; i<nLength; i++)
f.read(reinterpret_cast<char*>(&sTexName[i]), sizeof(sTexName[i]));
texturesNeededID.push_back(nID);
texturesNeededName.push_back(sTexName);
}
//Read the pure material data
f.read(reinterpret_cast<char*>(&m_cColor), sizeof(Color));
f.read(reinterpret_cast<char*>(&m_cAmbient), sizeof(Color));
f.read(reinterpret_cast<char*>(&m_cDiffuse), sizeof(Color));
f.read(reinterpret_cast<char*>(&m_cSpecular), sizeof(Color));
f.read(reinterpret_cast<char*>(&m_cEmissive), sizeof(Color));
f.read(reinterpret_cast<char*>(&m_dSpecularFactor), sizeof(m_dSpecularFactor));
//Read the max. texture stages per material
int nMaxTex;
f.read(reinterpret_cast<char*>(&nMaxTex), sizeof(nMaxTex));
//Read the textur stages of the material
for(int i=0; i<nMaxTex; i++)
{
f.read(reinterpret_cast<char*>(&m_tex[i]), sizeof(int));
f.read(reinterpret_cast<char*>(&m_texState[i]), sizeof(TextureState));
//Load texture, if needed
if(m_tex[i]>=0)
{
TextureManager* pTexMgr = TextureManager::getInstance();
//Search for the texture-Name
for(unsigned int t=0; t<texturesNeededID.size(); t++)
{
//ID found?
if(texturesNeededID[t] == m_tex[i])
{
//Load texture
m_tex[i] = pTexMgr->loadTexture(texturesNeededName[t], m_tex[t]);
break;
}
}
}
}
emit changed();
return true;
}
int Material::getNumValidTextures() const
{
int nNum = 0;
for(int i=0; i<MAXTEXTURES; i++)
{
//Its valid, if the texture-id is not -1 and the texture is available
if(m_tex[i] != -1 &&
TextureManager::getInstance()->getTexture(m_tex[i]) != NULL)
{
nNum++;
}
}
return nNum;
}
void Material::getValidTextureStages(int* nTexStages) const
{
int nNum = 0;
for(int i=0; i<MAXTEXTURES; i++)
{
//Its valid, if the texture-id is not -1 and the texture is available
if(m_tex[i] != -1 &&
TextureManager::getInstance()->getTexture(m_tex[i]) != NULL)
{
nTexStages[nNum] = i;
nNum++;
}
}
}
void Material::setTexture(int nTexStage, int nTexID)
{
if((nTexStage >= 0) && (nTexStage < MAXTEXTURES))
m_tex[nTexStage] = nTexID;
emit changed();
}
int Material::getTexture(int nTexStage) const
{
if((nTexStage >= 0) && (nTexStage < MAXTEXTURES))
return m_tex[nTexStage];
return -1;
}
TextureState* Material::getTextureState(int nTexStage)
{
if((nTexStage >= 0) && (nTexStage < MAXTEXTURES))
return &m_texState[nTexStage];
return NULL;
}
void Material::setToDefault()
{
m_cColor.set(1.0, 1.0, 1.0);
m_cAmbient.set(0.2, 0.2, 0.2, 1.0);
m_cDiffuse.set(0.8, 0.8, 0.8);
m_cSpecular.set(0.1, 0.1, 0.1);
m_cEmissive.set(0.0, 0.0, 0.0);
m_dSpecularFactor = 0.0;
//Set the used textures to NULL, so that the texture do not use
//any textures
for(int t=0; t<MAXTEXTURES; t++)
m_tex[t] = -1;
//The first version must be set with other values than the others
m_texState[0].setCombineMethode(false, TEXMET_Replace);
//m_texState[0].setSourceCombine(TEXCOMB_ColorArg1, TEXOP_Disable);
m_texState[0].setCombineOperand(TEXCOMBOP_RGB0, TEXBLEND_SrcColor);
//m_texState[0].setCombineMethode(true, TEXMET_Replace);
//m_texState[0].setCombineMethode(false, TEXMET_Disable);
//m_texState[0].setSourceCombine(TEXCOMB_ColorArg0, TEXOP_Texture);
//m_texState[0].setSourceCombine(TEXCOMB_AlphaArg0, TEXOP_Disable);
//m_texState[0].setCombineOperand(TEXCOMBOP_RGB0, TEXBLEND_SrcColor);
//m_texState[1].setSourceCombine(TEXCOMB_AlphaArg0, TEXOP_Previous);
//m_texState[1].setCombineOperand(TEXCOMBOP_Alpha0, TEXBLEND_One);
//m_texState[1].setCombineMethode(false, TEXMET_Replace);
}
}
| 27.963855
| 85
| 0.650754
|
lizardkinger
|
9f85c9364e622713b8b8b52534e5febe4b3d3d1a
| 80
|
cpp
|
C++
|
src/enum-enhanced.cpp
|
zzlc/cxx11tests
|
d471b3f8b96548c762be6b7e410abe56a57811ae
|
[
"MIT"
] | 48
|
2015-01-06T20:50:45.000Z
|
2021-02-15T02:48:32.000Z
|
src/enum-enhanced.cpp
|
zzlc/cxx11tests
|
d471b3f8b96548c762be6b7e410abe56a57811ae
|
[
"MIT"
] | 3
|
2016-01-19T15:02:19.000Z
|
2019-04-29T08:51:13.000Z
|
src/enum-enhanced.cpp
|
zzlc/cxx11tests
|
d471b3f8b96548c762be6b7e410abe56a57811ae
|
[
"MIT"
] | 24
|
2015-02-13T17:40:04.000Z
|
2019-12-03T06:59:03.000Z
|
// Check if enhanced enums are supported
enum Days: unsigned short {Odd, Even};
| 26.666667
| 40
| 0.75
|
zzlc
|
9f89f4742acbce21760b5f7c242fea151b304b5f
| 1,629
|
cpp
|
C++
|
server/modules/FileReader/FileReaderManager.cpp
|
hotgloupi/zhttpd
|
0437ac2e34dde89abab26665df9cbee1777f1d44
|
[
"BSD-3-Clause"
] | 2
|
2015-01-29T17:23:23.000Z
|
2015-09-21T17:45:22.000Z
|
server/modules/FileReader/FileReaderManager.cpp
|
hotgloupi/zhttpd
|
0437ac2e34dde89abab26665df9cbee1777f1d44
|
[
"BSD-3-Clause"
] | null | null | null |
server/modules/FileReader/FileReaderManager.cpp
|
hotgloupi/zhttpd
|
0437ac2e34dde89abab26665df9cbee1777f1d44
|
[
"BSD-3-Clause"
] | null | null | null |
#include "utils/Logger.hpp"
#include "utils/Path.hpp"
#include "FileReaderManager.hpp"
using namespace zhttpd::mod;
FileReaderManager::FileReaderManager() : StatefullManager<FileReader>("mod_filereader"), _delay(0)
{
this->_defaultMimeType = "";
}
FileReaderManager::~FileReaderManager()
{
}
unsigned int FileReaderManager::getDelay() const
{
return this->_delay;
}
std::string const& FileReaderManager::getDefaultMimeType() const
{
return this->_defaultMimeType;
}
std::string const& FileReaderManager::getMimeType(std::string const& ext) const
{
std::map<std::string, std::string>::const_iterator it = this->_types.find(ext);
if (it == this->_types.end())
return this->_defaultMimeType;
return it->second;
}
void FileReaderManager::addConfigurationEntry(std::string const& key, std::string const& value)
{
#ifdef ZHTTPD_DEBUG
LOG_DEBUG("Adding mime type " + value + " for extension " + key);
#endif
if (key.size() > 0)
{
if (key[0] == '.')
{
std::string str = key;
str.erase(str.begin());
this->_types[str] = value;
}
else if (key == "delay")
{
std::stringstream ss;
ss << value;
ss >> this->_delay;
}
else
LOG_WARN("Unknown filereader option " + key + " = " + value);
}
}
zhttpd::api::category::Type FileReaderManager::getCategory() const
{
return zhttpd::api::category::PROCESSING;
}
bool FileReaderManager::isRequired(zhttpd::api::IRequest const& req) const
{
return !zhttpd::Path::isDirectory(req.getFilePath());
}
| 23.271429
| 98
| 0.63229
|
hotgloupi
|
9f8a9bdb1a6199734132cece4919fd93acfc166f
| 1,269
|
cpp
|
C++
|
examples/complex-multiple.cpp
|
tibbetts/inside-c
|
a72f6d44f15343e81b35da8edadd0e9c63315d40
|
[
"MIT"
] | 18
|
2015-01-19T04:18:49.000Z
|
2022-03-04T06:22:44.000Z
|
examples/complex-multiple.cpp
|
tibbetts/inside-c
|
a72f6d44f15343e81b35da8edadd0e9c63315d40
|
[
"MIT"
] | null | null | null |
examples/complex-multiple.cpp
|
tibbetts/inside-c
|
a72f6d44f15343e81b35da8edadd0e9c63315d40
|
[
"MIT"
] | 4
|
2020-02-19T22:29:23.000Z
|
2021-09-22T16:45:52.000Z
|
#include <stdio.h>
class baseA2 {
int dataA;
public:
void setDataA(int a);
virtual int getDataA() const;
};
class baseB2 {
int dataB;
public:
void setDataB(int b);
virtual int getDataB() const;
};
class subBoth2 : public baseA2, public baseB2 {
public:
virtual int getSum() const;
// Overrise get data methods for fun.
virtual int getDataA() const;
virtual int getDataB() const;
};
void baseA2::setDataA(int a) {
dataA = a;
}
int baseA2::getDataA() const {
return dataA;
}
void baseB2::setDataB(int b) {
dataB = b;
}
int baseB2::getDataB() const {
return dataB;
}
int subBoth2::getSum() const {
int total = 0;
total += getDataA();
total += getDataB();
return total;
}
int subBoth2::getDataA() const {
printf("calling getDataA()\n");
return baseA2::getDataA();
}
int subBoth2::getDataB() const {
printf("calling getDataB()\n");
return baseB2::getDataB();
}
int complexMultiple(int argc, const char **argv) {
subBoth2 *sb = new subBoth2;
sb->getSum();
baseA2 *ba = sb;
ba->setDataA(12);
ba->getDataA();
baseB2 *bb = sb;
bb->setDataB(13);
bb->getDataB();
printf("sb->getSum()=%d", sb->getSum());
return 0;
}
| 16.269231
| 50
| 0.600473
|
tibbetts
|
9f906a21c2240b9698af3b573e97a36b17ec10f5
| 694
|
hpp
|
C++
|
graphics-library/include/engine/buffer.hpp
|
thetorine/opengl3-library
|
3904d857fd1085ba2c57c4289eb0e0d123f11a14
|
[
"MIT"
] | null | null | null |
graphics-library/include/engine/buffer.hpp
|
thetorine/opengl3-library
|
3904d857fd1085ba2c57c4289eb0e0d123f11a14
|
[
"MIT"
] | null | null | null |
graphics-library/include/engine/buffer.hpp
|
thetorine/opengl3-library
|
3904d857fd1085ba2c57c4289eb0e0d123f11a14
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
#include <GL/glew.h>
namespace gl::engine {
template <class T>
class Buffer {
public:
Buffer(GLuint mode);
Buffer(const std::vector<T> &data, GLuint mode);
~Buffer();
void transferBuffer();
void useBuffer();
void addElement(T element);
void addAll(const std::vector<T> &elements);
void resize(size_t space);
void clear();
size_t size();
size_t capacity();
private:
GLuint m_bufferIndex;
bool m_bufferCreated;
GLuint m_mode;
T *m_data;
size_t m_size;
size_t m_capacity;
};
}
| 22.387097
| 57
| 0.538905
|
thetorine
|
9f958685b1a07c29dbdb337111f211b76513a1ed
| 1,791
|
cc
|
C++
|
Code/0023-merge-k-sorted-lists.cc
|
SMartQi/Leetcode
|
9e35c65a48ba1ecd5436bbe07dd65f993588766b
|
[
"MIT"
] | 2
|
2019-12-06T14:08:57.000Z
|
2020-01-15T15:25:32.000Z
|
Code/0023-merge-k-sorted-lists.cc
|
SMartQi/Leetcode
|
9e35c65a48ba1ecd5436bbe07dd65f993588766b
|
[
"MIT"
] | 1
|
2020-01-15T16:29:16.000Z
|
2020-01-26T12:40:13.000Z
|
Code/0023-merge-k-sorted-lists.cc
|
SMartQi/Leetcode
|
9e35c65a48ba1ecd5436bbe07dd65f993588766b
|
[
"MIT"
] | null | null | null |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
// devide and conquer
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 0) return NULL;
if (lists.size() == 1) return lists[0];
return mergeKListsHelper(lists, 0, lists.size() - 1);
}
ListNode* mergeKListsHelper(vector<ListNode*>& lists, int start, int end) {
if (start == end) {
return lists[start];
}
if (start + 1 == end) {
return mergeTwoLists(lists[start], lists[end]);
}
ListNode* l1 = mergeKListsHelper(lists, start, (start + end) / 2);
ListNode* l2 = mergeKListsHelper(lists, (start + end) / 2 + 1, end);
return mergeTwoLists(l1, l2);
}
// This is copied from #21 Merge Two Sorted Lists.
// Not the optimal solution.
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
// l1 == NULL -> !l1
if (!l1) {
return l2;
}
if (!l2) {
return l1;
}
ListNode *head = new ListNode(0);
ListNode *origin = head;
ListNode *nl1 = l1;
ListNode *nl2 = l2;
while (nl1 && nl2) {
if (nl1 -> val < nl2 -> val) {
head -> next = nl1;
head = head -> next;
nl1 = nl1 -> next;
} else {
head -> next = nl2;
head = head -> next;
nl2 = nl2 -> next;
}
}
if (nl1) {
head -> next = nl1;
}
if (nl2) {
head -> next = nl2;
}
return origin -> next;
}
};
| 28.428571
| 79
| 0.463987
|
SMartQi
|
7a0c22249608e06bf74446b494022b691247e020
| 3,225
|
cpp
|
C++
|
MonoNative.Tests/mscorlib/System/Runtime/Remoting/Channels/mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | 7
|
2015-03-10T03:36:16.000Z
|
2021-11-05T01:16:58.000Z
|
MonoNative.Tests/mscorlib/System/Runtime/Remoting/Channels/mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | 1
|
2020-06-23T10:02:33.000Z
|
2020-06-24T02:05:47.000Z
|
MonoNative.Tests/mscorlib/System/Runtime/Remoting/Channels/mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | null | null | null |
// Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Runtime.Remoting.Channels
// Name: BaseChannelWithProperties
// C++ Typed Name: mscorlib::System::Runtime::Remoting::Channels::BaseChannelWithProperties
#include <gtest/gtest.h>
#include <mscorlib/System/Runtime/Remoting/Channels/mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties.h>
#include <mscorlib/System/mscorlib_System_Array.h>
#include <mscorlib/System/mscorlib_System_Type.h>
#include <mscorlib/System/mscorlib_System_String.h>
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace Remoting
{
namespace Channels
{
//Public Methods Tests
//Public Properties Tests
// Property Properties
// Return Type: mscorlib::System::Collections::IDictionary
// Property Get Method
TEST(mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture,get_Properties_Test)
{
}
// Property Count
// Return Type: mscorlib::System::Int32
// Property Get Method
TEST(mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture,get_Count_Test)
{
}
// Property IsFixedSize
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture,get_IsFixedSize_Test)
{
}
// Property IsReadOnly
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture,get_IsReadOnly_Test)
{
}
// Property IsSynchronized
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture,get_IsSynchronized_Test)
{
}
// Property Item
// Return Type: mscorlib::System::Object
// Property Get Method
TEST(mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture,get_Item_Test)
{
}
// Property Item
// Return Type: mscorlib::System::Object
// Property Set Method
TEST(mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture,set_Item_Test)
{
}
// Property Keys
// Return Type: mscorlib::System::Collections::ICollection
// Property Get Method
TEST(mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture,get_Keys_Test)
{
}
// Property SyncRoot
// Return Type: mscorlib::System::Object
// Property Get Method
TEST(mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture,get_SyncRoot_Test)
{
}
// Property Values
// Return Type: mscorlib::System::Collections::ICollection
// Property Get Method
TEST(mscorlib_System_Runtime_Remoting_Channels_BaseChannelWithProperties_Fixture,get_Values_Test)
{
}
}
}
}
}
}
| 25.393701
| 122
| 0.694264
|
brunolauze
|
7a0c778cf62781d9395276c59eb7535998023619
| 1,655
|
cpp
|
C++
|
src/common/SettingsAPI/FileWatcher.cpp
|
tameemzabalawi/PowerToys
|
5c6f7b1aea90ecd9ebe5cb8c7ddf82f8113fcb45
|
[
"MIT"
] | 76,518
|
2019-05-06T22:50:10.000Z
|
2022-03-31T22:20:54.000Z
|
src/common/SettingsAPI/FileWatcher.cpp
|
Nakatai-0322/PowerToys
|
1f64c1cf837ca958ad14dc3eb7887f36220a1ef9
|
[
"MIT"
] | 15,530
|
2019-05-07T01:10:24.000Z
|
2022-03-31T23:48:46.000Z
|
src/common/SettingsAPI/FileWatcher.cpp
|
Nakatai-0322/PowerToys
|
1f64c1cf837ca958ad14dc3eb7887f36220a1ef9
|
[
"MIT"
] | 5,184
|
2019-05-06T23:32:32.000Z
|
2022-03-31T15:43:25.000Z
|
#include "pch.h"
#include "FileWatcher.h"
std::optional<FILETIME> FileWatcher::MyFileTime()
{
HANDLE hFile = CreateFileW(m_path.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
std::optional<FILETIME> result;
if (hFile != INVALID_HANDLE_VALUE)
{
FILETIME lastWrite;
if (GetFileTime(hFile, nullptr, nullptr, &lastWrite))
{
result = lastWrite;
}
CloseHandle(hFile);
}
return result;
}
void FileWatcher::Run()
{
while (1)
{
auto lastWrite = MyFileTime();
if (!m_lastWrite.has_value())
{
m_lastWrite = lastWrite;
}
else if (lastWrite.has_value())
{
if (m_lastWrite->dwHighDateTime != lastWrite->dwHighDateTime ||
m_lastWrite->dwLowDateTime != lastWrite->dwLowDateTime)
{
m_lastWrite = lastWrite;
m_callback();
}
}
if (WaitForSingleObject(m_abortEvent, m_refreshPeriod) == WAIT_OBJECT_0)
{
return;
}
}
}
FileWatcher::FileWatcher(const std::wstring& path, std::function<void()> callback, DWORD refreshPeriod) :
m_refreshPeriod(refreshPeriod),
m_path(path),
m_callback(callback)
{
m_abortEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (m_abortEvent)
{
m_thread = std::thread([this]() { Run(); });
}
}
FileWatcher::~FileWatcher()
{
if (m_abortEvent)
{
SetEvent(m_abortEvent);
m_thread.join();
CloseHandle(m_abortEvent);
}
}
| 23.985507
| 161
| 0.587311
|
tameemzabalawi
|
7a0dbe3744ce2ca50f734d850a0889314ee4abe4
| 396
|
cpp
|
C++
|
C++/Introduction/functions.cpp
|
abivilion/Hackerank-Solutions-
|
e195fb1fce1588171cf12d99d38da32ca5c8276a
|
[
"MIT"
] | null | null | null |
C++/Introduction/functions.cpp
|
abivilion/Hackerank-Solutions-
|
e195fb1fce1588171cf12d99d38da32ca5c8276a
|
[
"MIT"
] | null | null | null |
C++/Introduction/functions.cpp
|
abivilion/Hackerank-Solutions-
|
e195fb1fce1588171cf12d99d38da32ca5c8276a
|
[
"MIT"
] | null | null | null |
#include <iostream>
// #include<bits/stdc++.h>
#include <algorithm>
using namespace std;
int max_of_four(int a,int b,int c,int d)
{
return((a>b?a:b)>(c>d?c:d)?(a>b?a:b):(c>d?c:d));
}
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int main() {
int a, b, c, d;
cin>>a>>b>>c>>d;
int ans = max_of_four(a, b, c, d);
cout<<ans;
return 0;
}
| 18.857143
| 56
| 0.527778
|
abivilion
|
7a119a2a1f728861dc65230064dc8d0d8916cc26
| 1,053
|
hpp
|
C++
|
include/entity.hpp
|
alsymd/BreakOut
|
055befbb61b0a3080b9a7d67359c0dbaf13eb596
|
[
"WTFPL"
] | null | null | null |
include/entity.hpp
|
alsymd/BreakOut
|
055befbb61b0a3080b9a7d67359c0dbaf13eb596
|
[
"WTFPL"
] | null | null | null |
include/entity.hpp
|
alsymd/BreakOut
|
055befbb61b0a3080b9a7d67359c0dbaf13eb596
|
[
"WTFPL"
] | null | null | null |
#ifndef ALS_ENTITY_HPP
#define ALS_ENTITY_HPP
#include"rect_shape.hpp"
#include<memory>
#include<libguile.h>
namespace als
{
class texture;
class renderer;
class moving_entity;
class entity
{
public:
entity();
entity(const rect_shape &shape, const std::string &texture_path);
virtual ~entity()=default;
virtual void render(const renderer &rend)const;
void handle_collide(entity &rhs);
void register_ball_callback(SCM cb);
void register_entity_callback(SCM cb);
void set_x(float x);
void set_y(float y);
void set_texture(const std::string &texture_path);
rect_shape &collider();
const rect_shape &collider()const;
virtual void apply_scm_callback(entity &rhs);
virtual void apply_scm_callback_ball(moving_entity &rhs);
virtual void apply_scm_callback_entity(entity &rhs);
protected:
std::shared_ptr<SCM> on_collision_with_ball = nullptr;
std::shared_ptr<SCM> on_collision_with_entity = nullptr;
rect_shape collider_;
std::shared_ptr<texture>texture_;
};
}
#endif
| 28.459459
| 69
| 0.733143
|
alsymd
|
7a1254581b03595c27d4a4b5c40b45818d71b741
| 219
|
cpp
|
C++
|
most_significant_bit.cpp
|
WizArdZ3658/Data-Structures-and-Algorithms
|
4098c0680c13127473d7ce6a41ead519559ff962
|
[
"MIT"
] | 3
|
2020-09-14T04:50:13.000Z
|
2021-04-17T06:42:43.000Z
|
most_significant_bit.cpp
|
WizArdZ3658/Data-Structures-and-Algorithms
|
4098c0680c13127473d7ce6a41ead519559ff962
|
[
"MIT"
] | null | null | null |
most_significant_bit.cpp
|
WizArdZ3658/Data-Structures-and-Algorithms
|
4098c0680c13127473d7ce6a41ead519559ff962
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cmath>
using namespace std;
int setBit(int n)
{
int k = (int)(log2(n));
return 1<<k;
}
int main()
{
int n;
cin >> n;
cout << "Most significant bits : " << setBit(n) << '\n';
return 0;
}
| 14.6
| 57
| 0.593607
|
WizArdZ3658
|
7a12ec057d99a8474bb33f0fa20104b8d2b0179f
| 345
|
hpp
|
C++
|
include/lexer_helpers.hpp
|
mujido/moove
|
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
|
[
"Apache-2.0"
] | null | null | null |
include/lexer_helpers.hpp
|
mujido/moove
|
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
|
[
"Apache-2.0"
] | null | null | null |
include/lexer_helpers.hpp
|
mujido/moove
|
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "moove.tab.h"
namespace Moove
{
using symbol_type = BisonParser::parser::symbol_type;
symbol_type parseInteger(const char* text);
symbol_type parseReal(const char* text);
symbol_type parseObjnum(const char* text);
symbol_type parseID(const char* text);
symbol_type parseStr(const char* text);
}
| 23
| 57
| 0.727536
|
mujido
|
7a1334af9489800ebd8c62b4c5832e4b35a1dee8
| 2,220
|
cpp
|
C++
|
DBProCompiler/DBPCompiler/InstructionTableEntry.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 231
|
2018-01-28T00:06:56.000Z
|
2022-03-31T21:39:56.000Z
|
DBProCompiler/DBPCompiler/InstructionTableEntry.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 9
|
2016-02-10T10:46:16.000Z
|
2017-12-06T17:27:51.000Z
|
DBProCompiler/DBPCompiler/InstructionTableEntry.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 66
|
2018-01-28T21:54:52.000Z
|
2022-02-16T22:50:57.000Z
|
// InstructionTableEntry.cpp: implementation of the CInstructionTableEntry class.
//
//////////////////////////////////////////////////////////////////////
// Common Includes
#include "macros.h"
// Custom Includes
#include "Declaration.h"
#include "InstructionTableEntry.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CInstructionTableEntry::CInstructionTableEntry()
{
m_dwInternalID=0;
m_dwReturnParam=0;
m_dwParamMax=0;
m_pName=NULL;
m_pDLL=NULL;
m_pDecoratedName=NULL;
m_pParamTypes=NULL;
m_pParamDesc=NULL;
m_dwHardcoreInternalValue=0;
m_dwBuildID=0;
m_pDecChain=NULL;
m_pPrev=NULL;
m_pNext=NULL;
}
CInstructionTableEntry::~CInstructionTableEntry()
{
SAFE_DELETE(m_pName);
SAFE_DELETE(m_pDLL);
SAFE_DELETE(m_pDecoratedName);
SAFE_DELETE(m_pParamTypes);
SAFE_DELETE(m_pParamDesc);
SAFE_DELETE(m_pDecChain);
}
void CInstructionTableEntry::Free(void)
{
CInstructionTableEntry* pCurrent = this;
while(pCurrent)
{
CInstructionTableEntry* pNext = pCurrent->GetNext();
delete pCurrent;
pCurrent = pNext;
}
}
void CInstructionTableEntry::Add(CInstructionTableEntry* pNew)
{
CInstructionTableEntry* pCurrent = this;
while(pCurrent->m_pNext)
pCurrent=pCurrent->m_pNext;
pCurrent->m_pNext=pNew;
pNew->m_pPrev=pCurrent;
}
void CInstructionTableEntry::Insert(CInstructionTableEntry *pNew)
{
// Get neighbors
CInstructionTableEntry* pNeighA = m_pPrev;
CInstructionTableEntry* pNeighB = this;
// Instruct neighbours to point to me
if(pNeighA) pNeighA->m_pNext = pNew;
pNeighB->m_pPrev = pNew;
// Insruct new to point to neighbors
pNew->m_pNext = pNeighB;
pNew->m_pPrev = pNeighA;
}
void CInstructionTableEntry::SetData(DWORD InternalID, CStr* pStr, CStr* pDLL, CStr* pDecoratedName, CStr* pParamTypes, DWORD returnparam, DWORD param, DWORD dwInternalId, DWORD dwBuildID)
{
// Set Instruction Data
m_dwInternalID = InternalID;
m_dwReturnParam = returnparam;
m_dwParamMax = param;
m_pName = pStr;
m_pDLL = pDLL;
m_pDecoratedName = pDecoratedName;
m_pParamTypes = pParamTypes;
m_dwHardcoreInternalValue=dwInternalId;
m_dwBuildID=dwBuildID;
}
| 24.130435
| 188
| 0.704054
|
domydev
|
7a18901031429e80fb30b9c521ca5a276b2c08d3
| 21,358
|
hpp
|
C++
|
test/gemm/gemm_config.hpp
|
mkarunan/rocWMMA
|
390a2e793699a1e17c18e46d7fe51e245907f012
|
[
"MIT"
] | null | null | null |
test/gemm/gemm_config.hpp
|
mkarunan/rocWMMA
|
390a2e793699a1e17c18e46d7fe51e245907f012
|
[
"MIT"
] | null | null | null |
test/gemm/gemm_config.hpp
|
mkarunan/rocWMMA
|
390a2e793699a1e17c18e46d7fe51e245907f012
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
*
* MIT License
*
* Copyright 2021-2022 Advanced Micro Devices, Inc.
*
* 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.
*
*******************************************************************************/
#ifndef GEMM_CONFIG_HPP
#define GEMM_CONFIG_HPP
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#include <rocwmma/rocwmma.hpp>
#include <rocwmma/rocwmma_coop.hpp>
#include <rocwmma/rocwmma_transforms.hpp>
#pragma GCC diagnostic pop
#include "gemm_coop_schedule.hpp"
#include "gemm_driver.hpp"
#include "gemm_global_mapping.hpp"
#include "gemm_local_mapping.hpp"
namespace rocwmma
{
namespace CooperativeGemm
{
namespace BlockLevel
{
struct LdsNT
{
template <uint32_t BlockM,
uint32_t BlockN,
uint32_t BlockK,
typename InputT,
typename OutputT,
typename ComputeT,
typename LayoutA,
typename LayoutB,
typename LayoutC,
typename LayoutD,
uint32_t BlocksX,
uint32_t BlocksY,
uint32_t TBlockX = 0,
uint32_t TBlockY = 0>
using GlobalMapping = GlobalMapping::BlockLevelMapping<BlockM,
BlockN,
BlockK,
InputT,
OutputT,
ComputeT,
LayoutA,
LayoutB,
LayoutC,
LayoutD,
BlocksX,
BlocksY,
TBlockX,
TBlockY>;
template <typename GlobalMapping, typename LayoutLds>
using LdsMapping = LocalMapping::LdsMappingNT<GlobalMapping, LayoutLds>;
template <uint32_t TBlockX = 0, uint32_t TBlockY = 0>
using CoopSchedulerA = typename Schedule::SameRowFwd<TBlockX, TBlockY>;
template <uint32_t TBlockX = 0, uint32_t TBlockY = 0>
using CoopSchedulerB = typename Schedule::SameColFwd<TBlockX, TBlockY>;
template <typename GlobalMapping,
typename LdsMapping,
typename CoopSchedulerA,
typename CoopSchedulerB>
using GemmDriver
= GemmDriver<GlobalMapping, LdsMapping, CoopSchedulerA, CoopSchedulerB>;
};
struct LdsTN
{
template <uint32_t BlockM,
uint32_t BlockN,
uint32_t BlockK,
typename InputT,
typename OutputT,
typename ComputeT,
typename LayoutA,
typename LayoutB,
typename LayoutC,
typename LayoutD,
uint32_t BlocksX,
uint32_t BlocksY,
uint32_t TBlockX = 0,
uint32_t TBlockY = 0>
using GlobalMapping = GlobalMapping::BlockLevelMapping<BlockM,
BlockN,
BlockK,
InputT,
OutputT,
ComputeT,
LayoutA,
LayoutB,
LayoutC,
LayoutD,
BlocksX,
BlocksY,
TBlockX,
TBlockY>;
template <typename GlobalMapping, typename LayoutLds>
using LdsMapping = LocalMapping::LdsMappingTN<GlobalMapping, LayoutLds>;
template <uint32_t TBlockX = 0, uint32_t TBlockY = 0>
using CoopSchedulerA = typename Schedule::SameRowFwd<TBlockX, TBlockY>;
template <uint32_t TBlockX = 0, uint32_t TBlockY = 0>
using CoopSchedulerB = typename Schedule::SameColFwd<TBlockX, TBlockY>;
template <typename GlobalMapping,
typename LdsMapping,
typename CoopSchedulerA,
typename CoopSchedulerB>
using GemmDriver
= GemmDriver<GlobalMapping, LdsMapping, CoopSchedulerA, CoopSchedulerB>;
};
struct LdsRF
{
template <uint32_t BlockM,
uint32_t BlockN,
uint32_t BlockK,
typename InputT,
typename OutputT,
typename ComputeT,
typename LayoutA,
typename LayoutB,
typename LayoutC,
typename LayoutD,
uint32_t BlocksX,
uint32_t BlocksY,
uint32_t TBlockX = 0,
uint32_t TBlockY = 0>
using GlobalMapping = GlobalMapping::BlockLevelMapping<BlockM,
BlockN,
BlockK,
InputT,
OutputT,
ComputeT,
LayoutA,
LayoutB,
LayoutC,
LayoutD,
BlocksX,
BlocksY,
TBlockX,
TBlockY>;
template <typename GlobalMapping, typename LayoutLds>
using LdsMapping = LocalMapping::LdsMappingRF<GlobalMapping, LayoutLds>;
template <uint32_t TBlockX = 0, uint32_t TBlockY = 0>
using CoopSchedulerA = typename Schedule::SameRowFwd<TBlockX, TBlockY>;
template <uint32_t TBlockX = 0, uint32_t TBlockY = 0>
using CoopSchedulerB = typename Schedule::SameColFwd<TBlockX, TBlockY>;
template <typename GlobalMapping,
typename LdsMapping,
typename CoopSchedulerA,
typename CoopSchedulerB>
using GemmDriver
= GemmDriver<GlobalMapping, LdsMapping, CoopSchedulerA, CoopSchedulerB>;
};
} // BlockLevel
namespace WaveLevel
{
struct LdsNT
{
template <uint32_t BlockM,
uint32_t BlockN,
uint32_t BlockK,
typename InputT,
typename OutputT,
typename ComputeT,
typename LayoutA,
typename LayoutB,
typename LayoutC,
typename LayoutD,
uint32_t BlocksX,
uint32_t BlocksY,
uint32_t TBlockX = 0,
uint32_t TBlockY = 0>
using GlobalMapping = GlobalMapping::WaveLevelMapping<BlockM,
BlockN,
BlockK,
InputT,
OutputT,
ComputeT,
LayoutA,
LayoutB,
LayoutC,
LayoutD,
BlocksX,
BlocksY,
TBlockX,
TBlockY>;
template <typename GlobalMapping, typename LayoutLds>
using LdsMapping = LocalMapping::LdsMappingNT<GlobalMapping, LayoutLds>;
template <uint32_t TBlockX = 0, uint32_t TBlockY = 0>
using CoopSchedulerA = typename Schedule::SameRowFwd<TBlockX, TBlockY>;
template <uint32_t TBlockX = 0, uint32_t TBlockY = 0>
using CoopSchedulerB = typename Schedule::SameColFwd<TBlockX, TBlockY>;
template <typename GlobalMapping,
typename LdsMapping,
typename CoopSchedulerA,
typename CoopSchedulerB>
using GemmDriver
= GemmDriver<GlobalMapping, LdsMapping, CoopSchedulerA, CoopSchedulerB>;
};
struct LdsTN
{
template <uint32_t BlockM,
uint32_t BlockN,
uint32_t BlockK,
typename InputT,
typename OutputT,
typename ComputeT,
typename LayoutA,
typename LayoutB,
typename LayoutC,
typename LayoutD,
uint32_t BlocksX,
uint32_t BlocksY,
uint32_t TBlockX = 0,
uint32_t TBlockY = 0>
using GlobalMapping = GlobalMapping::WaveLevelMapping<BlockM,
BlockN,
BlockK,
InputT,
OutputT,
ComputeT,
LayoutA,
LayoutB,
LayoutC,
LayoutD,
BlocksX,
BlocksY,
TBlockX,
TBlockY>;
template <typename GlobalMapping, typename LayoutLds>
using LdsMapping = LocalMapping::LdsMappingTN<GlobalMapping, LayoutLds>;
template <uint32_t TBlockX = 0, uint32_t TBlockY = 0>
using CoopSchedulerA = typename Schedule::SameRowFwd<TBlockX, TBlockY>;
template <uint32_t TBlockX = 0, uint32_t TBlockY = 0>
using CoopSchedulerB = typename Schedule::SameColFwd<TBlockX, TBlockY>;
template <typename GlobalMapping,
typename LdsMapping,
typename CoopSchedulerA,
typename CoopSchedulerB>
using GemmDriver
= GemmDriver<GlobalMapping, LdsMapping, CoopSchedulerA, CoopSchedulerB>;
};
} // namespace WaveLevel
namespace WorkgroupLevel
{
struct LdsNT
{
template <uint32_t BlockM,
uint32_t BlockN,
uint32_t BlockK,
typename InputT,
typename OutputT,
typename ComputeT,
typename LayoutA,
typename LayoutB,
typename LayoutC,
typename LayoutD,
uint32_t BlocksX,
uint32_t BlocksY,
uint32_t TBlockX,
uint32_t TBlockY>
using GlobalMapping = GlobalMapping::WorkgroupLevelMapping<BlockM,
BlockN,
BlockK,
InputT,
OutputT,
ComputeT,
LayoutA,
LayoutB,
LayoutC,
LayoutD,
BlocksX,
BlocksY,
TBlockX,
TBlockY>;
template <typename GlobalMapping, typename LayoutLds>
using LdsMapping = LocalMapping::LdsMappingNT<GlobalMapping, LayoutLds>;
template <uint32_t TBlockX, uint32_t TBlockY>
using CoopSchedulerA = typename Schedule::AllRowMajor<TBlockX, TBlockY>;
template <uint32_t TBlockX, uint32_t TBlockY>
using CoopSchedulerB = typename Schedule::AllRowMajor<TBlockX, TBlockY>;
template <typename GlobalMapping,
typename LdsMapping,
typename CoopSchedulerA,
typename CoopSchedulerB>
using GemmDriver
= GemmDriver<GlobalMapping, LdsMapping, CoopSchedulerA, CoopSchedulerB>;
};
struct LdsTN
{
template <uint32_t BlockM,
uint32_t BlockN,
uint32_t BlockK,
typename InputT,
typename OutputT,
typename ComputeT,
typename LayoutA,
typename LayoutB,
typename LayoutC,
typename LayoutD,
uint32_t BlocksX,
uint32_t BlocksY,
uint32_t TBlockX,
uint32_t TBlockY>
using GlobalMapping = GlobalMapping::WorkgroupLevelMapping<BlockM,
BlockN,
BlockK,
InputT,
OutputT,
ComputeT,
LayoutA,
LayoutB,
LayoutC,
LayoutD,
BlocksX,
BlocksY,
TBlockX,
TBlockY>;
template <typename GlobalMapping, typename LayoutLds>
using LdsMapping = LocalMapping::LdsMappingTN<GlobalMapping, LayoutLds>;
template <uint32_t TBlockX, uint32_t TBlockY>
using CoopSchedulerA = typename Schedule::AllRowMajor<TBlockX, TBlockY>;
template <uint32_t TBlockX, uint32_t TBlockY>
using CoopSchedulerB = typename Schedule::AllRowMajor<TBlockX, TBlockY>;
template <typename GlobalMapping,
typename LdsMapping,
typename CoopSchedulerA,
typename CoopSchedulerB>
using GemmDriver
= GemmDriver<GlobalMapping, LdsMapping, CoopSchedulerA, CoopSchedulerB>;
};
} // namespace WorkgroupLevel
} // namespace CooperativeGemm
template <>
constexpr const char* dataTypeToString<typename CooperativeGemm::BlockLevel::LdsNT>()
{
return "Block_LdsNT";
}
template <>
constexpr const char* dataTypeToString<typename CooperativeGemm::BlockLevel::LdsTN>()
{
return "Block_LdsTN";
}
template <>
constexpr const char* dataTypeToString<typename CooperativeGemm::BlockLevel::LdsRF>()
{
return "Block_LdsRF";
}
template <>
constexpr const char* dataTypeToString<typename CooperativeGemm::WaveLevel::LdsNT>()
{
return "Wave_LdsNT";
}
template <>
constexpr const char* dataTypeToString<typename CooperativeGemm::WaveLevel::LdsTN>()
{
return "Wave_LdsTN";
}
template <>
constexpr const char* dataTypeToString<typename CooperativeGemm::WorkgroupLevel::LdsNT>()
{
return "Workgroup_LdsNT";
}
template <>
constexpr const char* dataTypeToString<typename CooperativeGemm::WorkgroupLevel::LdsTN>()
{
return "Workgroup_LdsTN";
}
} // namespace rocwmma
#endif // GEMM_CONFIG_HPP
| 48.651481
| 93
| 0.374895
|
mkarunan
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.