hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
deb17cc9b7275ab1aa770170580ab8645cf8393e | 10,691 | cpp | C++ | src/modules/user/LevelModule.cpp | caelwithcats/UmikoBot | e7e3ee0fd7e4bb296b85ea5f384e21ca59f44fe9 | [
"MIT"
] | null | null | null | src/modules/user/LevelModule.cpp | caelwithcats/UmikoBot | e7e3ee0fd7e4bb296b85ea5f384e21ca59f44fe9 | [
"MIT"
] | null | null | null | src/modules/user/LevelModule.cpp | caelwithcats/UmikoBot | e7e3ee0fd7e4bb296b85ea5f384e21ca59f44fe9 | [
"MIT"
] | null | null | null | #include "LevelModule.h"
#include "UmikoBot.h"
#include "core/Permissions.h"
using namespace Discord;
LevelModule::LevelModule(UmikoBot* client)
: Module("levels", true), m_client(client)
{
m_timer.setInterval(30 * 1000);
QObject::connect(&m_timer, &QTimer::timeout,
[this]()
{
for (auto it = m_exp.begin(); it != m_exp.end(); it++)
{
for (GuildLevelData& data : it.value())
{
if (data.messageCount > 0)
{
data.messageCount = 0;
data.exp += 10 + qrand() % 6;
}
}
}
});
m_timer.start();
QTime now = QTime::currentTime();
qsrand(now.msec());
RegisterCommand(Commands::LEVEL_MODULE_TOP, "top",
[this](Client& client, const Message& message, const Channel& channel)
{
auto& exp = m_exp[channel.guildId()];
QStringList args = message.content().split(' ');
GuildSetting s = GuildSettings::GetGuildSetting(channel.guildId());
QString prefix = s.prefix;
if (args.size() == 2) {
qSort(exp.begin(), exp.end(),
[](const LevelModule::GuildLevelData& v1, const LevelModule::GuildLevelData& v2)
{
return v1.exp > v2.exp;
});
Embed embed;
embed.setColor(qrand() % 16777216);
embed.setTitle("Top " + args.back());
QString desc = "";
bool ok;
int count = args.back().toInt(&ok);
if (!ok)
{
client.createMessage(message.channelId(), "**Invalid Count**");
return;
}
if (count < 1)
{
client.createMessage(message.channelId(), "**Invalid Count**");
return;
}
if (count > 30)
{
client.createMessage(message.channelId(), "**Invalid Count**: The max count is `30`");
return;
}
unsigned int numberOfDigits = QString::number(std::min(count, exp.size())).size();
for (int i = 0; i < count; i++)
{
if (i >= exp.size())
{
embed.setTitle("Top " + QString::number(i));
break;
}
LevelModule::GuildLevelData& curr = exp[i];
desc += "`" + QString::number(i + 1).rightJustified(numberOfDigits, ' ') + "`) ";
desc += "**" + reinterpret_cast<UmikoBot*>(&client)->GetName(channel.guildId(), exp[i].user) + "**";
unsigned int xp = GetData(channel.guildId(), exp[i].user).exp;
unsigned int xpRequirement = s.expRequirement;
unsigned int level = 1;
while (xp > xpRequirement && level < s.maximumLevel) {
level++;
xp -= xpRequirement;
xpRequirement *= s.growthRate;
}
if (level >= s.maximumLevel)
level = s.maximumLevel;
desc += " - Level " + QString::number(level) + "\n";
}
embed.setDescription(desc);
client.createMessage(message.channelId(), embed);
}
else if (args.size() == 3)
{
qSort(exp.begin(), exp.end(),
[](const LevelModule::GuildLevelData& v1, const LevelModule::GuildLevelData& v2) -> bool
{
return v1.exp > v2.exp;
});
bool ok1, ok2;
int count1 = args[1].toInt(&ok1);
int count2 = args[2].toInt(&ok2);
if (!ok1 || !ok2)
{
client.createMessage(message.channelId(), "**Invalid Count**");
return;
}
if (count1 < 1 || count2 < 1)
{
client.createMessage(message.channelId(), "**Invalid Count**");
return;
}
if (count2 < count1)
{
client.createMessage(message.channelId(), "**Invalid Range**");
return;
}
if (count2 - count1 > 30) {
client.createMessage(message.channelId(), "**Invalid Count**: The max offset is `30`");
return;
}
Embed embed;
embed.setColor(qrand() % 16777216);
if (count2 == count1)
{
embed.setTitle("Top " + QString::number(count1));
}
else
{
embed.setTitle("Top from " + QString::number(count1) + " to " + QString::number(count2));
}
QString desc = "";
if (count1 > exp.size())
{
client.createMessage(channel.id(), "**Not enough members to create the list.**");
return;
}
unsigned int numberOfDigits = QString::number(std::min(count2, exp.size())).size();
for (int i = count1 - 1; i < count2; i++)
{
if (i >= exp.size())
{
embed.setTitle("Top from " + QString::number(count1) + " to " + QString::number(i));
break;
}
LevelModule::GuildLevelData& curr = exp[i];
desc += "`" + QString::number(i + 1).rightJustified(numberOfDigits, ' ') + "`) ";
desc += "**" + reinterpret_cast<UmikoBot*>(&client)->GetName(channel.guildId(), exp[i].user) + "**";
unsigned int xp = GetData(channel.guildId(), exp[i].user).exp;
unsigned int xpRequirement = s.expRequirement;
unsigned int level = 1;
while (xp > xpRequirement && level < s.maximumLevel) {
level++;
xp -= xpRequirement;
xpRequirement *= s.growthRate;
}
if (level >= s.maximumLevel)
level = s.maximumLevel;
desc += " - Level " + QString::number(level) + "\n";
}
embed.setDescription(desc);
client.createMessage(message.channelId(), embed);
}
else
{
UmikoBot* bot = reinterpret_cast<UmikoBot*>(&client);
Embed embed;
embed.setColor(qrand() % 16777216);
embed.setTitle("Help top");
QString description = bot->GetCommandHelp("top", prefix);
embed.setDescription(description);
bot->createMessage(message.channelId(), embed);
}
});
initiateAdminCommands();
}
void LevelModule::OnSave(QJsonDocument& doc) const
{
QJsonObject json;
QJsonObject levels;
QJsonObject backups;
for (auto it = m_exp.begin(); it != m_exp.end(); it++)
for (int i = 0; i < it.value().size(); i++)
if (m_client->GetName(it.key(), it.value()[i].user) == "")
{
bool found = false;
for (GuildLevelData& data : m_backupexp[it.key()])
if (data.user == it.value()[i].user) {
data.exp += it.value()[i].exp;
found = true;
break;
}
if (!found)
m_backupexp[it.key()].append(it.value()[i]);
it.value().erase(it.value().begin() + i);
}
for (auto it = m_backupexp.begin(); it != m_backupexp.end(); it++)
for (int i = 0; i < it.value().size(); i++)
if (m_client->GetName(it.key(), it.value()[i].user) != "")
{
bool found = false;
for (GuildLevelData& data : m_exp[it.key()])
if (data.user == it.value()[i].user) {
data.exp += it.value()[i].exp;
found = true;
break;
}
if (!found)
m_exp[it.key()].append(it.value()[i]);
it.value().erase(it.value().begin() + i);
}
if(m_exp.size() > 0)
for (auto it = m_exp.begin(); it != m_exp.end(); it++)
{
QJsonObject level;
for (int i = 0; i < it.value().size(); i++)
level[QString::number(it.value()[i].user)] = it.value()[i].exp;
levels[QString::number(it.key())] = level;
}
if(m_backupexp.size() > 0)
for (auto it = m_backupexp.begin(); it != m_backupexp.end(); it++)
{
QJsonObject backup;
for (int i = 0; i < it.value().size(); i++)
backup[QString::number(it.value()[i].user)] = it.value()[i].exp;
backups[QString::number(it.key())] = backup;
}
json["levels"] = levels;
json["backups"] = backups;
doc.setObject(json);
}
void LevelModule::OnLoad(const QJsonDocument& doc)
{
QJsonObject json = doc.object();
QJsonObject backups = json["backups"].toObject();
QJsonObject levels = json["levels"].toObject();
QStringList guildIds = levels.keys();
for (const QString& guild : guildIds)
{
snowflake_t guildId = guild.toULongLong();
QJsonObject level = levels[guild].toObject();
QJsonObject backup = backups[guild].toObject();
for (const QString& user : level.keys())
m_exp[guildId].append({ user.toULongLong(), level[user].toInt(), 0 });
for (const QString& user : backup.keys())
m_backupexp[guildId].append({ user.toULongLong(), backup[user].toInt(), 0 });
}
}
ExpLevelData LevelModule::ExpToLevel(snowflake_t guild, unsigned int exp)
{
GuildSetting s = GuildSettings::GetGuildSetting(guild);
ExpLevelData res;
res.xpRequirement = s.expRequirement;
res.level = 1;
res.exp = exp;
while (res.exp > res.xpRequirement && res.level < s.maximumLevel)
{
res.level++;
res.exp -= res.xpRequirement;
res.xpRequirement *= s.growthRate;
}
if (res.level >= s.maximumLevel)
{
res.exp = 0;
res.level = s.maximumLevel;
//res.xpRequirement = 0;
}
return res;
}
void LevelModule::StatusCommand(QString& result, snowflake_t guild, snowflake_t user)
{
GuildSetting s = GuildSettings::GetGuildSetting(guild);
unsigned int xp = GetData(guild, user).exp;
ExpLevelData res = ExpToLevel(guild, xp);
// Sort to get leaderboard index
auto& exp = m_exp[guild];
qSort(exp.begin(), exp.end(),
[](const LevelModule::GuildLevelData& v1, const LevelModule::GuildLevelData& v2)
{
return v1.exp > v2.exp;
});
int leaderboardIndex = -1;
for (int i = 0; i < exp.size(); ++i)
{
if (exp.at(i).user == user)
{
leaderboardIndex = i;
break;
}
}
unsigned int rankLevel = res.level;
QString rank = "";
if (s.ranks.size() > 0) {
for (int i = 0; i < s.ranks.size() - 1; i++)
{
if (rankLevel >= s.ranks[i].minimumLevel && rankLevel < s.ranks[i + 1].minimumLevel)
{
rank = s.ranks[i].name;
break;
}
}
if (rank == "")
rank = s.ranks[s.ranks.size() - 1].name;
if (leaderboardIndex >= 0)
result += "Rank: " + rank + " (#" + QString::number(leaderboardIndex + 1) + ")\n";
else
result += "Rank: " + rank + "\n";
}
else if (leaderboardIndex >= 0) {
result += "Rank: #" + QString::number(leaderboardIndex + 1) + "\n";
}
result += "Level: " + QString::number(res.level) + "\n";
result += "Total XP: " + QString::number(GetData(guild, user).exp) + "\n";
if(res.level < s.maximumLevel)
result += QString("XP until next level: %1\n").arg(res.xpRequirement - res.exp);
result += "\n";
}
void LevelModule::OnMessage(Client& client, const Message& message)
{
Module::OnMessage(client, message);
client.getChannel(message.channelId()).then(
[this, message](const Channel& channel)
{
auto& exp = m_exp[channel.guildId()];
if (!GuildSettings::IsModuleEnabled(channel.guildId(), GetName(), IsEnabledByDefault()))
return;
if (message.author().bot())
return;
if(!GuildSettings::ExpAllowed(channel.guildId(), channel.id()))
return;
QList<Command> commands = UmikoBot::Instance().GetAllCommands();
GuildSetting setting = GuildSettings::GetGuildSetting(channel.guildId());
for (Command& command : commands)
{
if (message.content().startsWith(setting.prefix + command.name))
return;
}
for (GuildLevelData& data : exp) {
if (data.user == message.author().id()) {
data.messageCount++;
return;
}
}
exp.append({ message.author().id(), 0, 1 });
});
}
LevelModule::GuildLevelData LevelModule::GetData(snowflake_t guild, snowflake_t user)
{
for (GuildLevelData data : m_exp[guild])
{
if (data.user == user) {
return data;
}
}
return { user, 0,0 };
}
| 24.520642 | 104 | 0.612571 | [
"object"
] |
deb5789c776d8b10ff6ce8249d7573915d04ecbe | 227 | cc | C++ | src/matrix_vector.cc | j-haj/ublas-eigen-benchmark | 8dec4a509a486f5812719ec612367c6df5026412 | [
"MIT"
] | 1 | 2017-09-22T04:29:40.000Z | 2017-09-22T04:29:40.000Z | src/matrix_vector.cc | j-haj/ublas-eigen-benchmark | 8dec4a509a486f5812719ec612367c6df5026412 | [
"MIT"
] | null | null | null | src/matrix_vector.cc | j-haj/ublas-eigen-benchmark | 8dec4a509a486f5812719ec612367c6df5026412 | [
"MIT"
] | null | null | null | /* vim: set ts=2 sts=2 et sw=2 tw=80: */
/**
* matrix_vector.hpp
*
* Author: Jeff Hajewski
* Created: 7/25/2017
*
* Matrix vector multiplication benchmarks
*/
#include <Eigen/Dense>
struct MatrixMatrixBenchmarks {
};
| 14.1875 | 42 | 0.665198 | [
"vector"
] |
deb801e365db136a0610884c8341429bc0cc7235 | 5,274 | cpp | C++ | tests/test.cpp | karel-chladek/basic_slot_map | 0645e2c07b3a9c1ea9810665e92dd143137d9543 | [
"MIT"
] | 2 | 2021-05-19T17:12:25.000Z | 2021-11-25T08:49:51.000Z | tests/test.cpp | karel-chladek/basic_slot_map | 0645e2c07b3a9c1ea9810665e92dd143137d9543 | [
"MIT"
] | null | null | null | tests/test.cpp | karel-chladek/basic_slot_map | 0645e2c07b3a9c1ea9810665e92dd143137d9543 | [
"MIT"
] | null | null | null | #include <iostream>
#include "slotmap.hpp"
#include "catch.hpp"
template struct slot_map< int >;
TEST_CASE( "constructors" ) {
slot_map< int > sm;
REQUIRE( sm.empty() );
REQUIRE( sm.size() == 0 );
slot_map< int > sm2( sm );
REQUIRE( sm.empty() );
REQUIRE( sm.size() == 0 );
typename slot_map< int >::handle h;
}
TEST_CASE( "basic interface" ) {
slot_map< int > sm;
auto h0 = sm.insert( 0 );
auto h1 = sm.insert( 1 );
REQUIRE( sm.valid( h0 ) );
sm.erase( h1 );
sm[ h0 ] = 42;
for ( auto &x : sm )
REQUIRE( x == 42 );
REQUIRE( sm.get( h0 ) != nullptr );
}
TEST_CASE( "basic insert" ) {
slot_map< int > sm;
auto h0 = sm.insert( 0 );
REQUIRE( sm.size() == 1 );
REQUIRE( sm.valid( h0 ) );
REQUIRE( *sm.get( h0 ) == 0 );
}
TEST_CASE( "large insert and erase" ) {
slot_map< int > sm;
std::vector<slot_map< int >::handle> handlers;
for(int i = 0; i < 1000; i++){
handlers.push_back(sm.insert(i));
}
for(int i = 0; i < 1000; i++){
REQUIRE( *sm.get( handlers[i] ) == i );
sm.erase(handlers[i]);
}
REQUIRE(sm.empty());
REQUIRE(sm.size() == 0);
}
TEST_CASE("total erase"){
slot_map< int > sm;
std::vector<slot_map< int >::handle> handlers;
for(int i = 0; i < 10; i++){
handlers.push_back(sm.insert(i));
}
for(int i = 0; i < 10; i++){
REQUIRE( *sm.get( handlers[i] ) == i );
REQUIRE(sm.size() == 10 - i);
sm.erase(handlers[i]);
}
REQUIRE(sm.empty());
//nothing happens
sm.erase(handlers[1]);
sm.insert(0);
REQUIRE(!sm.empty());
}
TEST_CASE("copy + asign"){
slot_map< int > sm;
std::vector<slot_map< int >::handle> handlers;
for(int i = 0; i < 10; i++){
handlers.push_back(sm.insert(i));
}
slot_map< int > copy(sm);
slot_map< int > assigned;
assigned = sm;
REQUIRE(sm == copy);
REQUIRE(sm == assigned);
}
TEST_CASE("swap"){
slot_map< int > fst;
std::vector<slot_map< int >::handle> handlers;
for(int i = 0; i < 10; i++){
fst.insert(i);
}
slot_map< int > snd;
REQUIRE(fst.size() == 10);
REQUIRE(!fst.empty());
REQUIRE(snd.size() == 0);
REQUIRE(snd.empty());
fst.swap(snd);
REQUIRE(snd.size() == 10);
REQUIRE(!snd.empty());
REQUIRE(fst.size() == 0);
REQUIRE(fst.empty());
swap(fst,snd);
REQUIRE(fst.size() == 10);
REQUIRE(!fst.empty());
REQUIRE(snd.size() == 0);
REQUIRE(snd.empty());
}
TEST_CASE("const slotmap + copy"){
slot_map< int > sm;
std::vector<slot_map< int >::handle> handlers;
for(int i = 0; i < 10; i++){
handlers.push_back(sm.insert(i));
}
const slot_map<int> cpy = sm;
for(int i = 0; i < 10; i++){
REQUIRE( *cpy.get( handlers[i] ) == i );
}
}
TEST_CASE("insert-erase-insert"){
slot_map< int > sm;
auto h0 = sm.insert(0);
auto h5 = sm.insert(5);
auto h6 = sm.insert(6);
auto h3 = sm.insert(3);
auto h1 = sm.insert(1);
sm.erase(h6);
REQUIRE(sm.get(h6) == nullptr);
REQUIRE(sm.size() == 4);
REQUIRE(!sm.valid(h6));
REQUIRE(sm.valid(h5));
REQUIRE(sm.valid(h3));
REQUIRE(sm.valid(h0));
REQUIRE(sm.valid(h1));
h6 = sm.insert(6);
REQUIRE(sm.valid(h6));
REQUIRE(sm.valid(h5));
REQUIRE(sm.valid(h3));
REQUIRE(sm.valid(h0));
REQUIRE(sm.valid(h1));
}
TEST_CASE("handle interface"){
slot_map<int>::handle h;
slot_map<int>::handle cpy(h);
slot_map<int>::handle assigned;
assigned = h;
const slot_map<int>::handle c_h;
const slot_map<int>::handle c_cpy(h);
const slot_map<int>::handle c_assigned;
assigned = h;
}
TEST_CASE("Big objects"){
slot_map< std::vector<int> > sm;
std::vector<slot_map< std::vector<int> >::handle> handlers;
for(int i = 1; i < 10; i++){
handlers.push_back(sm.insert(std::vector<int>(i, 0)));
}
for(int i = 0; i < 9; i++){
std::vector<int> actual = *sm.get( handlers[i] );
REQUIRE( actual.size() == i+1 );
REQUIRE( actual[i] == 0);
sm.erase(handlers[i]);
}
REQUIRE(sm.empty());
//nothing happens
sm.erase(handlers[1]);
sm.insert({0});
REQUIRE(!sm.empty());
}
TEST_CASE("long usage"){
slot_map< int > sm;
auto h0 = sm.insert(0);
auto h1 = sm.insert(1);
auto h4 = sm.insert(4);
auto h2 = sm.insert(2);
auto h5 = sm.insert(5);
auto h6 = sm.insert(6);
auto h3 = sm.insert(3);
auto h7 = sm.insert(7);
sm.erase(h2);
sm.erase(h4);
sm.erase(h6);
REQUIRE(sm[h0] == 0);
REQUIRE(sm[h1] == 1);
REQUIRE(sm[h3] == 3);
REQUIRE(sm[h5] == 5);
REQUIRE(sm[h7] == 7);
auto h8 = sm.insert(8);
auto h9 = sm.insert(9);
sm.erase(h1);
sm.erase(h8);
REQUIRE(sm[h0] == 0);
REQUIRE(sm[h3] == 3);
REQUIRE(sm[h5] == 5);
REQUIRE(sm[h7] == 7);
REQUIRE(sm[h9] == 9);
REQUIRE( sm.valid(h0));
REQUIRE(!sm.valid(h1));
REQUIRE(!sm.valid(h2));
REQUIRE( sm.valid(h3));
REQUIRE(!sm.valid(h4));
REQUIRE( sm.valid(h5));
REQUIRE(!sm.valid(h6));
REQUIRE( sm.valid(h7));
REQUIRE(!sm.valid(h8));
REQUIRE( sm.valid(h9));
REQUIRE(sm.size() == 5);
}
| 23.544643 | 63 | 0.539818 | [
"vector"
] |
6311e8765f5699d6b728e02a04604c9a58e3efb6 | 7,673 | cpp | C++ | Network.cpp | AODQ/Pulcher-Client | 9d62526d4072fd0a4ac7ce438d86ae5bc8dd03b1 | [
"BSD-3-Clause"
] | null | null | null | Network.cpp | AODQ/Pulcher-Client | 9d62526d4072fd0a4ac7ce438d86ae5bc8dd03b1 | [
"BSD-3-Clause"
] | null | null | null | Network.cpp | AODQ/Pulcher-Client | 9d62526d4072fd0a4ac7ce438d86ae5bc8dd03b1 | [
"BSD-3-Clause"
] | null | null | null | /* (c) CiggBit. All rights reserved.
* See license.txt for more information
*/
#include "AOD.h"
#include "Client_Vars.h"
#include "Game_Manager.h"
#include "Network.h"
#include "Player.h"
#include "PulNet_Handler.h"
#include <fstream>
#include <future>
#include <iostream>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <utility>
#include <WS2tcpip.h>
#ifndef ENET_INCLUDE_H_
#define ENET_INCLUDE_H_
#include <enet\enet.h>
#endif
namespace PulNet {
ENetAddress client_address;
uint8_t server_timestamp,
client_timestamp;
ENetHost* client_host;
ENetPeer* server_peer = nullptr;
static std::vector<std::string> tcp_packets_to_send;
using pe = PacketEvent;
}
static std::vector<std::tuple<char*,int,PulNet::PacketFlag>> packets_to_send;
std::mutex send_packet_mutex;
std::atomic<bool> packets_to_send_lock; // don't Send_Packet until this is true
void PulNet::Send_Packet(const void* data, int len, uint8_t sizeof_data,
PacketFlag flag) {
std::lock_guard<std::mutex> send_packet_lock ( send_packet_mutex );
if ( PulNet::server_peer ) {
// wait until we can send packets
while ( packets_to_send_lock.load() != 0 );
packets_to_send_lock.store(1);
ENetPacket* packet = enet_packet_create(data, len*sizeof_data,
(_ENetPacketFlag)flag);
enet_peer_send(PulNet::server_peer, 0, packet);
enet_host_flush(PulNet::client_host);
packets_to_send_lock.store(0);
}
}
void PulNet::Send_Packet(const std::string& data, PacketFlag flag) {
if ( PulNet::server_peer != nullptr )
Send_Packet((void*)data.c_str(), data.size(), sizeof(char), flag);
}
void PulNet::Send_Packet(PacketEvent preamble, const std::string& data,
PacketFlag flag) {
Send_Packet(std::to_string((int)preamble) + data, flag);
}
void PulNet::Send_Packet(std::vector<uint8_t>& data, PacketFlag pflag) {
Send_Packet((void*)&data[0], data.size(), 1, pflag);
}
void PulNet::Send_Packet(PacketEvent preamble, std::vector<uint8_t>& data,
PacketFlag flag) {
data.insert(data.begin(), (uint8_t)preamble);
Send_Packet((const void*)&data[0], data.size(), 1, flag);
}
// ---- utility functions -----------------------------------------------------
/*,
if ( arg1 == "DMAP" ) { // download map
AOD::Output("Downloading map " + arg2 + " " + str);
std::ofstream d_map(arg2, std::ios::binary);
std::stringstream conv;
conv << arg3;,
unsigned int fil_len;
conv >> fil_len;
AOD::Output("Bytes left: " + std::to_string(fil_len));
char* content;
while ( fil_len > 0 ) {
int len = Recv_TCP_Packet(Network::server_tcp_sock, content);
if ( len <= 0 ) break;
fil_len -= len;
AOD::Output("Bytes left: " + std::to_string(fil_len));
d_map.write(content,len);
}
AOD::Output("Finished downloading map");
continue;
}
} while ( str != "" );
*/
// returns next parameter from a string received from TCP packet
static std::string R_Next_Parameter(std::string& str) {
std::string arg = "";
if ( str.size() == 0 ) return "";
while ( str[0] == ' ' ) str.erase(str.begin(), str.begin() + 1);
if ( str[0] == '"' ) { // look until end of \"
str.erase(str.begin(), str.begin()+1);
while ( str.size() != 0 && str[0] != '"' ) {
arg += str[0];
str.erase(str.begin(), str.begin()+1);
}
if ( str.size() != 0 ) // remove \"
str.erase(str.begin(), str.begin()+1);
} else { // look until end of space
while ( str.size() != 0 && str[0] != ' ' ) {
arg += str[0];
str.erase(str.begin(), str.begin()+1);
}
}
if ( str.size() != 0 ) // remove space if one exists
str.erase(str.begin(), str.begin()+1);
return arg;
}
// ---- declared functions ----------------------------------------------------
void PulNet::Init() {
ex_assert(enet_initialize() == 0, "Couldn't init ENet");
client_host = enet_host_create(nullptr, 1, 2,
57600 / 8, // 56 K modem, 56 Kbps downstream
14400 / 8 // 56 K modem, 14 Kbps upstream
);
ex_assert(client_host != nullptr, "Could not create client host");
packets_to_send_lock.store(0);
packets_to_send.clear();
}
void PulNet::Connect(std::string ip) {
game_manager->State_Update(Loading_State::connecting_to_server);
ENetEvent client_event;
// string IP to integer IP
sockaddr_in adr;
inet_pton(AF_INET, ip.c_str(), &adr.sin_addr);
client_address.host = adr.sin_addr.S_un.S_addr;
if ( ip == "" )
client_address.host = ENET_HOST_BROADCAST;
client_address.port = 9113;
server_peer = enet_host_connect(client_host, &client_address, 2, 0);
if ( server_peer == nullptr ) {
AOD::Output("No available peers for connection");
game_manager->State_Update(Loading_State::error);
return;
}
// wait for connection to succeed
if ( enet_host_service(client_host, &client_event, 15000) > 0 &&
client_event.type == ENET_EVENT_TYPE_CONNECT ) {
AOD::Output("Connection to " + Util::R_IP(client_event.peer->address.host)
+ ":" + std::to_string(client_event.peer->address.port) + " success");
//Send_Packet(PulNet::packet_event::ch_name, CV::username);
client_event.peer->timeoutMinimum = 9000000;
client_event.peer->timeoutMaximum = 9000000;
} else {
AOD::Output("Could not connect to server");
game_manager->State_Update(Loading_State::error);
}
// etc
server_timestamp = client_timestamp = 0;
}
void PulNet::Disconnect() {
enet_peer_disconnect(server_peer, 0);
}
// ---- PulNet handlers -------------------------------------------------------
void PulNet::Handle_Network() {
static ENetEvent netevent;
while ( enet_host_service(client_host, &netevent, 0) > 0 ) {
switch ( netevent.type ) {
case ENET_EVENT_TYPE_RECEIVE:
// get packet type
PulNet::Handle_Packet(netevent.packet->data,
netevent.packet->dataLength, netevent.peer);
enet_packet_destroy( netevent.packet );
break;
case ENET_EVENT_TYPE_DISCONNECT:
Handle_Disconnect(netevent.peer);
break;
}
}
// packets to send
// wait until lock is OK then lock
/*
while ( packets_to_send_lock.load() != 0 );
packets_to_send_lock.store(1);
for ( auto& i : packets_to_send ) {
//AOD::Output("Sending " + std::string(std::get<0>(i)));
// send packet
ENetPacket* packet = enet_packet_create(
std::get<0>(i), std::get<1>(i), (int)std::get<2>(i));
enet_peer_send(server_peer, 0, packet);
enet_host_flush(PulNet::client_host);
// dealloc char*
free ( (void*)std::get<0>(i) );
}
packets_to_send.clear();
packets_to_send_lock.store(0); // clear lock
// standard player refresh
PulNet::Handle_Player_Send();
*/
}
void PulNet::Send_Hard_Client_Refresh() {
std::vector<uint8_t> hcr_vec;
hcr_vec.push_back((uint8_t)PulNet::PacketEvent::hard_client_refresh);
AOD::Output("HCR: " + std::to_string(hcr_vec[0]));
Util::Append_Pack_String(hcr_vec, CV::username);
hcr_vec.push_back(0);
Util::Append_Pack_String(hcr_vec, "NIL");
hcr_vec.push_back(0);
auto pl = game_manager->c_player;
Util::Append_Pack_String(hcr_vec, R_Player_Status_Str(pl));
hcr_vec.push_back(0);
Util::Append_Pack_Num(hcr_vec, 0);
Util::Append_Pack_Num(hcr_vec, 0);
PulNet::Send_Packet(hcr_vec);
}
| 31.446721 | 80 | 0.61762 | [
"vector"
] |
6316ccdd04b238701d96ee5c59e2eafcda8bfc2f | 18,603 | cpp | C++ | src/TAO/API/session.cpp | Zephyr-blues/LLL-TAO | 83fa6fff3dc3f911d99abc9be2474c75c1bcfd93 | [
"MIT"
] | null | null | null | src/TAO/API/session.cpp | Zephyr-blues/LLL-TAO | 83fa6fff3dc3f911d99abc9be2474c75c1bcfd93 | [
"MIT"
] | null | null | null | src/TAO/API/session.cpp | Zephyr-blues/LLL-TAO | 83fa6fff3dc3f911d99abc9be2474c75c1bcfd93 | [
"MIT"
] | null | null | null | /*__________________________________________________________________________________________
(c) Hash(BEGIN(Satoshi[2010]), END(Sunny[2012])) == Videlicet[2014] ++
(c) Copyright The Nexus Developers 2014 - 2019
Distributed under the MIT software license, see the accompanying
file COPYING or http://www.opensource.org/licenses/mit-license.php.
"ad vocem populi" - To the Voice of the People
____________________________________________________________________________________________*/
#include <TAO/API/types/session.h>
#include <TAO/API/include/utils.h>
#include <TAO/API/types/exception.h>
#include <LLD/include/global.h>
#include <TAO/Ledger/types/sigchain.h>
#include <LLC/include/argon2.h>
#include <LLC/include/encrypt.h>
#include <LLC/include/random.h>
/* Global TAO namespace. */
namespace TAO
{
/* API Layer namespace. */
namespace API
{
/* Default Constructor. */
Session::Session()
: CREATE_MUTEX ()
, hashAuth ()
, MUTEX ()
, nID (0)
, nStarted (0)
, nLastActive (0)
, nAuthAttempts (0)
, pSigChain ()
, pActivePIN ()
, nNetworkKey (0)
, vP2PIncoming ()
, vP2POutgoing ()
{
}
/* Move constructor. */
Session::Session(Session&& session) noexcept
: hashAuth (std::move(session.hashAuth))
, nID (std::move(session.nID))
, nStarted (std::move(session.nStarted))
, nLastActive (std::move(session.nLastActive))
, nAuthAttempts (std::move(session.nAuthAttempts))
, pSigChain (std::move(session.pSigChain))
, pActivePIN (std::move(session.pActivePIN))
, nNetworkKey (std::move(session.nNetworkKey))
, vP2PIncoming (std::move(session.vP2PIncoming))
, vP2POutgoing (std::move(session.vP2POutgoing))
{
}
/** Move assignment. **/
Session& Session::operator=(Session&& session) noexcept
{
hashAuth = (std::move(session.hashAuth));
nID = (std::move(session.nID));
nStarted = (std::move(session.nStarted));
nLastActive = (std::move(session.nLastActive));
nAuthAttempts = (std::move(session.nAuthAttempts));
pSigChain = (std::move(session.pSigChain));
pActivePIN = (std::move(session.pActivePIN));
nNetworkKey = (std::move(session.nNetworkKey));
vP2PIncoming = (std::move(session.vP2PIncoming));
vP2POutgoing = (std::move(session.vP2POutgoing));
return *this;
}
/* Default Destructor. */
Session::~Session()
{
/* Free up values in encrypted memory */
if(!pSigChain.IsNull())
pSigChain.free();
if(!pActivePIN.IsNull())
pActivePIN.free();
if(!nNetworkKey.IsNull())
nNetworkKey.free();
}
/* Initializes the session from username / password / pin */
void Session::Initialize(const TAO::Ledger::SignatureChain& pUser, const SecureString& strPin, const uint256_t& nSessionID)
{
{
LOCK(MUTEX);
/* Set the session ID */
nID = nSessionID;
/* Set the initial start time */
nStarted = runtime::unifiedtimestamp();
/* Set the last active time */
nLastActive = runtime::unifiedtimestamp();
/* Instantiate the sig chain */
pSigChain = new TAO::Ledger::SignatureChain(pUser);
}
/* Cache the pin with no unlocked actions */
UpdatePIN(strPin, TAO::Ledger::PinUnlock::UnlockActions::NONE);
}
/* Returns true if the session has not been initialised. */
bool Session::IsNull() const
{
/* Simply check to see whether the started timestamp has been set */
return nStarted == 0;
}
/* Returns the session ID for this session */
uint256_t Session::ID() const
{
return nID;
}
/* Returns the active PIN for this session. */
const memory::encrypted_ptr<TAO::Ledger::PinUnlock>& Session::GetActivePIN() const
{
return pActivePIN;
}
/* Clears the active PIN for this session. */
void Session::ClearActivePIN()
{
LOCK(MUTEX);
/* Clean up the existing pin */
if(!pActivePIN.IsNull())
pActivePIN.free();
}
/* Updates the cached pin and its unlocked actions */
void Session::UpdatePIN(const SecureString& strPin, uint8_t nUnlockedActions)
{
LOCK(MUTEX);
/* Clean up the existing pin */
if(!pActivePIN.IsNull())
pActivePIN.free();
/* Instantiate new pin */
pActivePIN = new TAO::Ledger::PinUnlock(strPin, nUnlockedActions);
}
/* Updates the password stored in the internal sig chain */
void Session::UpdatePassword(const SecureString& strPassword)
{
LOCK(MUTEX);
/* Get the existing username so that we can use it for the new sig chain */
SecureString strUsername = pSigChain->UserName();
/* Clear the existing sig chain pointer */
pSigChain.free();
/* Instantate a new one with the existing username and the new password */
pSigChain = new TAO::Ledger::SignatureChain(strUsername, strPassword);
}
/* Returns the cached network private key. */
uint512_t Session::GetNetworkKey() const
{
/* Lazily generate the network key the first time it is requested */
if(nNetworkKey.IsNull())
/* Generate and cache the network private key */
nNetworkKey = new memory::encrypted_type<uint512_t>(pSigChain->Generate("network", 0, pActivePIN->PIN()));
return nNetworkKey->DATA;
}
/* Logs activity by updating the last active timestamp. */
void Session::SetLastActive()
{
LOCK(MUTEX);
nLastActive = runtime::unifiedtimestamp();
}
/* Gets last active timestamp. */
uint64_t Session::GetLastActive() const
{
return nLastActive;
}
/* Determine if the Users are locked. */
bool Session::Locked() const
{
LOCK(MUTEX);
if(pActivePIN.IsNull() || pActivePIN->PIN().empty())
return true;
return false;
}
/* Checks that the active sig chain has been unlocked to allow transactions. */
bool Session::CanTransact() const
{
LOCK(MUTEX);
if(!pActivePIN.IsNull() && pActivePIN->CanTransact())
return true;
return false;
}
/* Checks that the active sig chain has been unlocked to allow mining */
bool Session::CanMine() const
{
LOCK(MUTEX);
if(!config::fMultiuser.load() && (!pActivePIN.IsNull() && pActivePIN->CanMine()))
return true;
return false;
}
/* Checks that the active sig chain has been unlocked to allow staking */
bool Session::CanStake() const
{
LOCK(MUTEX);
if(!config::fMultiuser.load() &&(!pActivePIN.IsNull() && pActivePIN->CanStake()))
return true;
return false;
}
/* Checks that the active sig chain has been unlocked to allow notifications to be processed */
bool Session::CanProcessNotifications() const
{
LOCK(MUTEX);
if(!pActivePIN.IsNull() && pActivePIN->ProcessNotifications())
return true;
return false;
}
/* Returns the sigchain the account logged in. */
const memory::encrypted_ptr<TAO::Ledger::SignatureChain>& Session::GetAccount() const
{
return pSigChain;
}
/* Adds a new P2P Request. */
void Session::AddP2PRequest(const LLP::P2P::ConnectionRequest& request, bool fIncoming)
{
/* Lock mutex so p2p request vector can't be accessed by another thread */
LOCK(MUTEX);
/* Reference to the vector to work on, based on the fIncoming flag */
std::vector<LLP::P2P::ConnectionRequest>& vP2PRequests = fIncoming ? vP2PIncoming : vP2POutgoing;
/* Add the request */
vP2PRequests.push_back(request);
}
/* Gets P2P Request matching the app id / hashPeer criteria. */
LLP::P2P::ConnectionRequest Session::GetP2PRequest(const std::string& strAppID, const uint256_t& hashPeer, bool fIncoming) const
{
/* Lock mutex so p2p request vector can't be accessed by another thread */
LOCK(MUTEX);
/* Reference to the vector to work on, based on the fIncoming flag */
const std::vector<LLP::P2P::ConnectionRequest>& vP2PRequests = fIncoming ? vP2PIncoming : vP2POutgoing;
/* Check each request */
for(const auto request : vP2PRequests)
{
/* If the request matches the appID and hashPeer then return it*/
if(request.strAppID == strAppID && request.hashPeer == hashPeer)
return request;
}
/* If we haven't found one then return an empty connection request */
return LLP::P2P::ConnectionRequest();
}
/* Checks to see if a P2P Request matching the app id / hashPeer criteria exists. */
bool Session::HasP2PRequest(const std::string& strAppID, const uint256_t& hashPeer, bool fIncoming) const
{
/* Lock mutex so p2p request vector can't be accessed by another thread */
LOCK(MUTEX);
/* Reference to the vector to work on, based on the fIncoming flag */
const std::vector<LLP::P2P::ConnectionRequest>& vP2PRequests = fIncoming ? vP2PIncoming : vP2POutgoing;
/* Check each request */
for(const auto request : vP2PRequests)
{
/* Check the appID and hashPeer */
if(request.strAppID == strAppID && request.hashPeer == hashPeer)
return true;
}
/* No match found */
return false;
}
/* Deletes the P2P Request matching the app id / hashPeer criteria exists. */
void Session::DeleteP2PRequest(const std::string& strAppID, const uint256_t& hashPeer, bool fIncoming)
{
/* Lock mutex so p2p request vector can't be accessed by another thread */
LOCK(MUTEX);
/* Reference to the vector to work on, based on the fIncoming flag */
std::vector<LLP::P2P::ConnectionRequest>& vP2PRequests = fIncoming ? vP2PIncoming : vP2POutgoing;
vP2PRequests.erase
(
/* Use std remove_if function to return the iterator to erase. This allows us to pass in a lambda function,
which itself can check to see if a match exists */
std::remove_if(vP2PRequests.begin(), vP2PRequests.end(),
[&](const LLP::P2P::ConnectionRequest& request)
{
return (request.strAppID == strAppID && request.hashPeer == hashPeer);
}),
vP2PRequests.end()
);
}
/* Returns a vector of all connection requests. NOTE: This will copy the internal vector to protect against
direct manipulation by calling code */
const std::vector<LLP::P2P::ConnectionRequest> Session::GetP2PRequests(bool fIncoming) const
{
/* Lock mutex so p2p request vector can't be accessed by another thread */
LOCK(MUTEX);
/* Reference to the vector to work on, based on the fIncoming flag */
const std::vector<LLP::P2P::ConnectionRequest>& vP2PRequests = fIncoming ? vP2PIncoming : vP2POutgoing;
/* Return the required vector. */
return vP2PRequests;
}
/* Returns the number of incorrect authentication attempts made in this session */
uint8_t Session::GetAuthAttempts() const
{
return nAuthAttempts;
}
/* Increments the number of incorrect authentication attempts made in this session */
void Session::IncrementAuthAttempts()
{
/* Lock mutex so two threads can't increment at the same time */
LOCK(MUTEX);
nAuthAttempts++;
}
/* Encrypts the current session and saves it to the local database */
void Session::Save(const SecureString& strPin) const
{
/* Use a data stream to help serialize */
DataStream ssData(SER_LLD, 1);
/* Serialize the session data */
/* Session */
ssData << nStarted;
ssData << nAuthAttempts;
if(!nNetworkKey.IsNull())
ssData << nNetworkKey->DATA;
else
ssData << uint512_t(0);
ssData << hashAuth;
/* Sig Chain */
ssData << pSigChain->UserName();
ssData << pSigChain->Password();
/* PinUnlock */
ssData << pActivePIN->UnlockedActions();
/* Get the session bytes */
std::vector<uint8_t> vchData = ssData.Bytes();
/* Generate a symmetric key to encrypt it based on the genesis and pin */
std::vector<uint8_t> vchKey;
/* Get the users genesis */
uint256_t hashGenesis = GetAccount()->Genesis();
/* Add the genesis */
vchKey = hashGenesis.GetBytes();
/* Add the pin */
vchKey.insert(vchKey.end(), strPin.begin(), strPin.end());
/* For added security we don't directly use the genesis + PIN as the symmetric key, but a hash of it instead.
NOTE: the AES256 function requires a 32-byte key, so we reduce the length if necessary by using
the 256-bit version of the Argon2 hashing function */
uint256_t nKey = LLC::Argon2Fast_256(vchKey);
/* Put the key back into the vector */
vchKey = nKey.GetBytes();
/* The encrypted data */
std::vector<uint8_t> vchCipherText;
/* Encrypt the data */
if(!LLC::EncryptAES256(vchKey, vchData, vchCipherText))
throw APIException(-270, "Failed to encrypt data.");
/* Write the session to local DB */
LLD::Local->WriteSession(hashGenesis, vchCipherText);
}
/* Decrypts and loads an existing session from disk */
void Session::Load(const uint256_t& nSessionID, const uint256_t& hashGenesis, const SecureString& strPin)
{
/* The encrypted session bytes */
std::vector<uint8_t> vchEncrypted;
/* Load the encrypted data from the local DB */
if(!LLD::Local->ReadSession(hashGenesis, vchEncrypted))
throw APIException(-309, "Error loading session.");
/* Generate a symmetric key to encrypt it based on the session ID and pin */
std::vector<uint8_t> vchKey;
/* Add the genesis ID */
vchKey = hashGenesis.GetBytes();
/* Add the pin */
vchKey.insert(vchKey.end(), strPin.begin(), strPin.end());
/* For added security we don't directly use the session ID + PIN as the symmetric key, but a hash of it instead.
NOTE: the AES256 function requires a 32-byte key, so we reduce the length if necessary by using
the 256-bit version of the Argon2 hashing function */
uint256_t nKey = LLC::Argon2Fast_256(vchKey);
/* Put the key back into the vector */
vchKey = nKey.GetBytes();
/* The decrypted session bytes */
std::vector<uint8_t> vchSession;
/* Encrypt the data */
if(!LLC::DecryptAES256(vchKey, vchEncrypted, vchSession))
throw APIException(-309, "Error loading session."); // generic message callers can't brute force session id's
try
{
/* Use a data stream to help deserialize */
DataStream ssData(vchSession, SER_LLD, 1);
/* Deserialize the session data*/
ssData >> nStarted;
ssData >> nAuthAttempts;
/* Network key */
uint512_t nKey;
ssData >> nKey;
if(nKey != 0)
nNetworkKey = new memory::encrypted_type<uint512_t>(nKey);
ssData >> hashAuth;
/* Sig Chain */
SecureString strUsername;
ssData >> strUsername;
SecureString strPassword;
ssData >> strPassword;
/* Initialise the sig chain */
pSigChain = new TAO::Ledger::SignatureChain(strUsername, strPassword);
/* PinUnlock */
uint8_t nUnlockActions;
ssData >> nUnlockActions;
/* Restore the unlock actions and cache pin */
UpdatePIN(strPin, nUnlockActions);
/* Update the last active time */
nLastActive = runtime::unifiedtimestamp();
/* Finally set the new session ID */
nID = nSessionID;
}
catch(const std::exception& e)
{
throw APIException(-309, "Error loading session."); // generic message callers can't brute force session id's
}
}
}
}
| 34.386322 | 136 | 0.54545 | [
"vector"
] |
6318fa3995c1b40380d7dbf3ab4c0cb2d35d23a1 | 15,428 | hh | C++ | RAVL2/Core/Container/Buffer/SizeBufferAccess.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Core/Container/Buffer/SizeBufferAccess.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Core/Container/Buffer/SizeBufferAccess.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2001, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
#ifndef RAVL_SIZEBUFFERACCESS_HEADER
#define RAVL_SIZEBUFFERACCESS_HEADER 1
/////////////////////////////////////////////////////////////////////////
//! file="Ravl/Core/Container/Buffer/SizeBufferAccess.hh"
//! lib=RavlCore
//! author="Radek Marik"
//! docentry="Ravl.API.Core.Arrays.Buffer"
//! date="14/02/1997"
//! userlevel=Develop
//! rcsid="$Id$"
#include "Ravl/IndexRange1d.hh"
#include "Ravl/BufferAccess.hh"
#include "Ravl/Types.hh"
#include "Ravl/TFVector.hh"
namespace RavlN {
template <class DataT> class SizeBufferAccessC;
template <class DataT> class Slice1dC;
class BinOStreamC;
class BinIStreamC;
//: Basic access to buffer with limited size
// The class SizeBufferAccessC enables to random indexed access to
// a sequentially organised continous part of memory called buffer.
// The access functions check if an accessed element is valid only in
// debug mode.
template <class DataT>
class SizeBufferAccessC
: public BufferAccessC<DataT>
{
public:
typedef DataT ElementT;
// Constructors, copies, assigment, and destructor
// -----------------------------------------------
inline SizeBufferAccessC()
: sz(0)
{}
//: Default constructor.
inline SizeBufferAccessC(DataT * data, SizeT size = 0)
: BufferAccessC<DataT>(data),
sz(size)
{}
// Creates an access to a buffer pointed by the pointer 'bp'. If
// 'bp' is 0, the access is not valid.
inline SizeBufferAccessC(const BufferAccessC<DataT> & bp,SizeT s);
// Creates an access to a buffer referenced by 'bp' with size 's'.
inline SizeBufferAccessC(const SizeBufferAccessC<DataT> & ba);
// Creates a physical copy of the access 'ba'.
inline SizeBufferAccessC(const SizeBufferAccessC<DataT> & ba,SizeT s);
// Creates a physical copy of the access 'ba' limited by new size 's'.
inline const SizeBufferAccessC<DataT> & operator=(DataT * bp);
// Changes the reference element to the element pointed by 'bp'.
// Access to the object
// --------------------
inline DataT * ReferenceElm() const
{ return this->m_buff; }
// Returns the pointer to the reference element of the attached buffer.
// The reference element need not to be the valid element of the buffer.
inline void * ReferenceVoid() const
{ return (void *) this->m_buff; }
// Returns the pointer to the reference element of the attached buffer.
// The reference element need not to be the valid element of the buffer.
// The function is intended to be used in printing.
inline DataT * DataStart() const
{ return this->m_buff; }
// Returns the address of the first element of the buffer.
inline SizeT Size() const
{ return sz; }
// Returns the number of elements of the array.
inline IndexRangeC Limits() const
{ return IndexRangeC(0,sz-1); }
// Returns the usable range of indeces expressed by this object.
inline IndexRangeC Range() const
{ return IndexRangeC(0,sz-1); }
// Returns the usable range of indeces expressed by this object.
inline IndexC IMin() const
{ return 0; }
// Returns the minimum index of the range of this access.
inline IndexC IMax() const
{ return sz-1; }
// Returns the maximum index of the range of this access.
inline DataT *PointerTo(IndexC i)
{ return ReferenceElm() + i.V(); }
//: Generate pointer to the location of an element
// NOTE: This does not range check, the element may not be part of the array
inline const DataT *PointerTo(IndexC i) const
{ return ReferenceElm() + i.V(); }
//: Generate pointer to the location of an element
// NOTE: This does not range check, the element may not be part of the array
inline const DataT & operator[](IntT i) const {
#if RAVL_CHECK
if (!Contains(i))
IssueError(__FILE__,__LINE__,"Index %d out of range 0 - %zu ",i,static_cast<size_t>(Size()-1));
#endif
return BufferAccessC<DataT>::operator[](i);
}
// Read-only access to the 'i'-th element of the buffer.
inline DataT & operator[](IntT i) {
#if RAVL_CHECK
if (!Contains(i))
IssueError(__FILE__,__LINE__,"Index %d out of range 0 - %zu ",i,static_cast<size_t>(Size()-1));
#endif
return BufferAccessC<DataT>::operator[](i);
}
// Read-write access to the 'i'-th element of the buffer.
inline const DataT & operator[](const SizeC &i) const {
#if RAVL_CHECK
if (!Contains(i))
IssueError(__FILE__,__LINE__,"Index %u out of range 0 - %zu ",i.V(),static_cast<size_t>(Size()-1));
#endif
return BufferAccessC<DataT>::operator[](i);
}
// Read-only access to the 'i'-th element of the buffer.
inline DataT & operator[](const SizeC &i) {
#if RAVL_CHECK
if (!Contains(i))
IssueError(__FILE__,__LINE__,"Index %u out of range 0 - %zu ",i.V(),static_cast<size_t>(Size()-1));
#endif
return BufferAccessC<DataT>::operator[](i);
}
// Read-write access to the 'i'-th element of the buffer.
inline const DataT & operator[](const IndexC &i) const {
#if RAVL_CHECK
if (!Contains(i))
IssueError(__FILE__,__LINE__,"Index %d out of range 0 - %zu ",i.V(),static_cast<size_t>(Size()-1));
#endif
return BufferAccessC<DataT>::operator[](i);
}
// Read-only access to the 'i'-th element of the buffer.
inline DataT & operator[](const IndexC &i) {
#if RAVL_CHECK
if (!Contains(i))
IssueError(__FILE__,__LINE__,"Index %d out of range 0 - %zu ",i.V(),static_cast<size_t>(Size()-1));
#endif
return BufferAccessC<DataT>::operator[](i);
}
// Read-write access to the 'i'-th element of the buffer.
inline const SizeBufferAccessC<DataT> & SAccess(void) const
{ return *this; }
// Returns this object.
// Logical functions
// -----------------
inline bool IsEmpty() const
{ return sz == 0; }
// Returns TRUE if the size of the array is zero.
inline bool Contains(const IndexC &i) const
{ return static_cast<size_t>(i.V()) < sz; }
// Returns TRUE if the array contains an item with the index 'i'.
// Modifications of the access
// ---------------------------
inline SizeT ShrinkHigh(const SizeT &k) {
RavlAssert(k <= sz);
sz -= k;
return sz;
}
// Changes the number of elements by subtracting the last 'k' elements.
inline
const SizeBufferAccessC<DataT> & Swap(SizeBufferAccessC<DataT> & a);
// Exchanges the contents of this buffer with buffer 'a'.
inline void Attach(const SizeBufferAccessC<DataT> & b);
// Changes this buffer access to have the same access rights as 'b'.
inline void Attach(const BufferAccessC<DataT> & b,
SizeT size);
// Changes this buffer access to have the access rights as 'b' limited
// for 'size' elements.
inline SizeBufferAccessC<DataT> operator+(SizeT i) const;
// Creates the new access object shifted 'i' elements to the right
// (towards next elements). The size is descreased to fit the
// the original range of this access.
// Modifications of the buffer contents
// ------------------------------------
void Fill(const DataT & d);
// 'd' value is assigned to all elements of the buffer.
void CopyFrom(const SizeBufferAccessC<DataT> &oth);
//: Copy contents of another buffer into this one.
// NB. Buffers MUST be the same length.
void CopyFrom(const Slice1dC<DataT> &slice);
//: Copy slice into this array.
// slice must have the same length as this buffer. <br>
// Implementation can be found in Slice1d.hh
template<unsigned int N>
void CopyFrom(const TFVectorC<DataT, N> &vec) {
RavlAssert(Size() == N);
register DataT *to = ReferenceElm();
register const DataT *from = &(vec[0]);
register const DataT *endOfRow = &to[Size()];
for(;to != endOfRow;to++,from++)
*to = *from;
}
//: Copy values from vec into this array.
// Vector must have the same length as this buffer.
void Reverse();
//: Reverse the order of elements in this array in place.
SizeBufferAccessC<DataT> BufferFrom(UIntT first);
//: Get an access for this buffer starting from the 'first' element to the end of the buffer.
SizeBufferAccessC<DataT> BufferFrom(UIntT first,UIntT len);
//: Get an access for this buffer starting from the 'first' element for 'len' elements.
// An error will be generated if the requested buffer isn't contains within this one.
bool operator==(const SizeBufferAccessC<DataT> &ba) const
{ return (this->m_buff == ba.m_buff) && (this->sz == ba.sz); }
//: Are two accesses the same ?
IndexC IndexOf(const DataT &element) const {
IndexC ret = &element - &ReferenceElm();
RavlAssertMsg(Range().Contains(ret),"Element not from this array.");
return ret;
}
//: Compute index of element.
// Note, 'element' must be a direct reference
protected:
// Copy
// ----
SizeBufferAccessC<DataT> Copy(void) const;
// Returns a physical copy of this access pointing to the physical
// copy of the accessed buffer in the range accessible by this access.
// The new copy is necessary to attach to reference counted buffer
// or to delete at the end of the life of this object.
UIntT sz; // size of the buffer in elements.
};
/////////////////////////////////////////////////////////////////////////////
template <class DataT>
void
SizeBufferAccessC<DataT>::CopyFrom(const SizeBufferAccessC<DataT> &oth) {
RavlAssert(oth.Size() == Size());
register DataT *to = ReferenceElm();
register const DataT *from = oth.ReferenceElm();
register DataT *endOfRow = &to[Size()];
for(;to != endOfRow;to++,from++)
*to = *from;
}
template <class DataT>
inline
SizeBufferAccessC<DataT>::SizeBufferAccessC(const BufferAccessC<DataT> & bp,SizeT s)
: BufferAccessC<DataT>(bp),
sz(s)
{}
template <class DataT>
inline
SizeBufferAccessC<DataT>::
SizeBufferAccessC(const SizeBufferAccessC<DataT> & ba)
: BufferAccessC<DataT>(ba),
sz(ba.sz)
{}
template <class DataT>
inline
SizeBufferAccessC<DataT>::
SizeBufferAccessC(const SizeBufferAccessC<DataT> & ba,SizeT s)
: BufferAccessC<DataT>(ba),
sz(s)
{
#if RAVL_CHECK
if (s > ba.Size())
IssueError(__FILE__,__LINE__,"Size %zu out of index range 0-%zu ",static_cast<size_t>(s) ,static_cast<size_t>(ba.Size()-1));
#endif
}
template <class DataT>
inline
const SizeBufferAccessC<DataT> &
SizeBufferAccessC<DataT>::operator=(DataT * bp) {
((BufferAccessC<DataT> &) *this) = bp;
return *this;
}
template <class DataT>
inline
const SizeBufferAccessC<DataT> &
SizeBufferAccessC<DataT>::Swap(SizeBufferAccessC<DataT> & a) {
BufferAccessC<DataT>::Swap(a);
Swap(sz,a.sz);
return *this;
}
template <class DataT>
inline
void
SizeBufferAccessC<DataT>::Attach(const SizeBufferAccessC<DataT> & b)
{ *this=b; }
template <class DataT>
inline
void
SizeBufferAccessC<DataT>::Attach(const BufferAccessC<DataT> & b,
SizeT size) {
((BufferAccessC<DataT> &)(*this)) = b;
sz=size;
}
template <class DataT>
inline
SizeBufferAccessC<DataT>
SizeBufferAccessC<DataT>::operator+(SizeT i) const {
RavlAssert(i <= sz);
return SizeBufferAccessC<DataT>(this->m_buff + i, sz - i);
}
template <class DataT>
SizeBufferAccessC<DataT>
SizeBufferAccessC<DataT>::Copy(void) const {
if (IsEmpty())
return SizeBufferAccessC<DataT>();
DataT * bp = new DataT[Size()];
SizeBufferAccessC<DataT> b(bp, Size());
DataT *at = DataStart();
DataT *at2 = b.DataStart();
DataT *endOfRow = &at[sz];
for(;at != endOfRow;at++,at2++)
*at2 = *at;
return b;
}
template <class DataT>
void SizeBufferAccessC<DataT>::Fill(const DataT & d) {
DataT *at = DataStart();
DataT *endOfRow = &at[sz];
for(;at != endOfRow;at++)
*at = d;
}
template<class DataT>
void SizeBufferAccessC<DataT>::Reverse() {
DataT *at = &((*this)[IMin()]);
DataT *end = &((*this)[IMax()]);
DataT tmp;
for(;at < end;at++,end--) {
tmp = *at;
*at = *end;
*end = tmp;
}
}
template<class DataT>
SizeBufferAccessC<DataT> SizeBufferAccessC<DataT>::BufferFrom(UIntT first) {
RavlAssert(first < sz);
return SizeBufferAccessC<DataT>(&(ReferenceElm()[first]),sz - first);
}
template<class DataT>
SizeBufferAccessC<DataT> SizeBufferAccessC<DataT>::BufferFrom(UIntT first,UIntT len) {
RavlAssert((first + len) <= sz);
return SizeBufferAccessC<DataT>(&(ReferenceElm()[first]),len);
}
template <class DataT>
std::ostream &operator<<(std::ostream &out,const SizeBufferAccessC<DataT> &dat) {
const DataT *at = dat.DataStart();
const DataT *endOfRow = &at[dat.Size()];
if(dat.Size() == 0)
return out;
out << *at;
at++;
for(;at != endOfRow;at++)
out << ' ' << *at;
return out;
}
//: Read buffer from stream.
// NB. The buffer must be pre-allocated.
template <class DataT>
std::istream &operator>>(std::istream &strm,SizeBufferAccessC<DataT> &dat) {
DataT *at = dat.DataStart();
DataT *endOfRow = &at[dat.Size()];
for(;at != endOfRow;at++)
strm >> *at;
return strm;
}
//: Wrtie buffer to stream.
// NB. This size of the buffer is NOT written.
template <class DataT>
BinOStreamC &operator<<(BinOStreamC &out,const SizeBufferAccessC<DataT> &dat) {
const DataT *at = dat.DataStart();
const DataT *endOfRow = &at[dat.Size()];
if(dat.Size() == 0)
return out;
for(;at != endOfRow;at++)
out << *at;
return out;
}
//: Read buffer from stream.
// NB. The buffer must be pre-allocated.
template <class DataT>
BinIStreamC &operator>>(BinIStreamC &strm,SizeBufferAccessC<DataT> &dat) {
DataT *at = dat.DataStart();
DataT *endOfRow = &at[dat.Size()];
for(;at != endOfRow;at++)
strm >> *at;
return strm;
}
//: Save real array to binary stream
BinOStreamC &operator<<(BinOStreamC &out,const SizeBufferAccessC<RealT> &img);
//: Load real array image from binary stream
BinIStreamC &operator>>(BinIStreamC &in,SizeBufferAccessC<RealT> &img);
//: Save float array image to binary stream
BinOStreamC &operator<<(BinOStreamC &out,const SizeBufferAccessC<FloatT> &img);
//: Load float array image from binary stream
BinIStreamC &operator>>(BinIStreamC &in,SizeBufferAccessC<FloatT> &img);
//: Save byte array to binary stream
BinOStreamC &operator<<(BinOStreamC &out,const SizeBufferAccessC<ByteT> &img);
//: Load byte array from binary stream
BinIStreamC &operator>>(BinIStreamC &in,SizeBufferAccessC<ByteT> &img);
}
#endif
| 32.208768 | 131 | 0.633977 | [
"object",
"vector"
] |
63225940c722d30ce6037d60e9da455307c7e9b1 | 12,366 | cpp | C++ | BackEnd.cpp | aaraia/msg_app_king | e6e0dc4166d473d3077c76bdfe646b63452d9916 | [
"CC0-1.0"
] | null | null | null | BackEnd.cpp | aaraia/msg_app_king | e6e0dc4166d473d3077c76bdfe646b63452d9916 | [
"CC0-1.0"
] | null | null | null | BackEnd.cpp | aaraia/msg_app_king | e6e0dc4166d473d3077c76bdfe646b63452d9916 | [
"CC0-1.0"
] | null | null | null | #include "BackEnd.h"
// app
#include "CommsLayer.h"
#include "Message.h"
namespace MessageService {
void BackEnd::shutdown()
{
BaseQueue<BaseMessageRef>::shutdown();
}
void BackEnd::work(BaseMessageRef msg)
{
// check if a shutdown has been intitated
if (m_shutdown) return;
switch (msg->getId())
{
case MessageID::AddUserMessageID:
AddUserHandler(msg);
break;
case MessageID::SendMessageID:
SendMessageHandler(msg);
break;
case MessageID::GetMessagesID:
GetMessagesHandler(msg);
break;
case MessageID::GetReportID:
GetReportHandler(msg);
break;
default:
break;
}
}
void BackEnd::AddUserHandler(BaseMessageRef msg)
{
std::unique_lock<std::mutex> lock{ m_usersMutex };
auto addUserMsg = std::dynamic_pointer_cast<AddUserMessage>(msg);
auto inputedUserName = addUserMsg->getUserName();
// max users reached
if (m_users.size() >= m_limits.MAX_USERS)
{
// send reply
auto reply = AddUserReply::create(msg->getFromID(), m_id, "cannot add user: " + inputedUserName + " max users reached");
m_commsLayer.push(reply);
return;
}
// already exists?
auto fnd = m_users.find(inputedUserName);
if (fnd != m_users.end())
{
// send reply back
auto reply = AddUserReply::create(msg->getFromID(), m_id, "cannot add user: " + inputedUserName + " already exists");
m_commsLayer.push(reply);
return;
}
// add the user
auto add = m_users.emplace(inputedUserName);
if (!add.second)
{
// send reply back
auto reply = AddUserReply::create(msg->getFromID(), m_id, "cannot add user: " + inputedUserName + " add failed");
m_commsLayer.push(reply);
return;
}
// send reply back
auto reply = AddUserReply::create(msg->getFromID(), m_id, "User: " + inputedUserName + " added successfully");
m_commsLayer.push(reply);
}
void BackEnd::SendMessageHandler(BaseMessageRef msg)
{
if (!msg) return;
// cast down to get access to the message data
auto sendMsgRef = std::dynamic_pointer_cast<SendMessage>(msg);
auto inputedSender = sendMsgRef->getSender();
auto inputedRecipent = sendMsgRef->getRecipient();
auto inputedMessage = sendMsgRef->getMessage();
{
// lock will be released at end of block
std::unique_lock<std::mutex> lock{ m_usersMutex };
// first check if the sender exists
auto fnd = m_users.find(inputedSender);
if (fnd == m_users.end())
{
// send reply back
auto reply = SendMessageReply::create(msg->getFromID(), m_id, "cannot send message: sender does not exist");
m_commsLayer.push(reply);
return;
}
// first check if the recipient exists
fnd = m_users.find(inputedRecipent);
if (fnd == m_users.end())
{
// send reply back
auto reply = SendMessageReply::create(msg->getFromID(), m_id, "cannot send message: recipient does not exist");
m_commsLayer.push(reply);
return;
}
}
{
// lock will be released at end of block
std::unique_lock<std::mutex> lock{ m_messagesMutex };
// max total messages reached?
if (m_totalMessagesStored >= m_limits.MAX_TOTAL_MESSAGES)
{
// send reply back
auto reply = SendMessageReply::create(msg->getFromID(), m_id, "cannot send message: max total messages reached");
m_commsLayer.push(reply);
return;
}
// recipient does not exist
auto inbox = m_messages.find(inputedRecipent);
if (inbox == m_messages.end())
{
auto add = m_messages.emplace(inputedRecipent, EmailVec{});
if (!add.second)
{
// send reply back
auto reply = SendMessageReply::create(msg->getFromID(), m_id, "cannot send message: could not add recipient");
m_commsLayer.push(reply);
return;
}
inbox = add.first;
}
// recipient inbox full
if (inbox->second.size() >= m_limits.MAX_MESSAGES_PER_USER)
{
// send reply back
auto reply = SendMessageReply::create(msg->getFromID(), m_id, "cannot send message: recipient inbox full");
m_commsLayer.push(reply);
return;
}
// add message to recipent inbox
Email email;
email.m_content = inputedMessage;
email.m_sender = inputedSender;
inbox->second.emplace_back(email);
// send reply that it was successfully sent
auto reply = SendMessageReply::create(msg->getFromID(), m_id, "Message sent");
m_commsLayer.push(std::move(reply));
++m_totalMessagesStored;
}
{
std::unique_lock<std::mutex> lock{ m_reportsMutex };
// the backend generates the timestamps
TimeStamp timeStamp = std::chrono::system_clock::now();
// add to our report, keep a record of this message meta data
auto fnd = m_reports.find(inputedSender);
if (fnd == m_reports.end())
{
// create a new report
Report report;
report.m_count = 1;
report.m_sender = inputedSender;
// add recipient
TimeStampVec timeStamps;
timeStamps.emplace_back(timeStamp);
report.m_sentList.emplace(inputedRecipent, timeStamps); // this could fail but the message was still sent, maybe some logging instead
// add report
m_reports.emplace(inputedSender, report); // this could fail but the message was still sent, maybe some logging instead
}
else
{
auto& report = fnd->second;
// find the recipent
auto fndRpt = report.m_sentList.find(inputedRecipent);
if (fndRpt == report.m_sentList.end())
{
// add recipient
TimeStampVec timeStamps;
timeStamps.emplace_back(timeStamp);
report.m_sentList.emplace(inputedRecipent, timeStamps); // this could fail but the message was still sent, maybe log
}
else
{
// add the new time stamp
fndRpt->second.emplace_back(timeStamp);
}
report.m_count += 1; // new message increment
}
}
}
void BackEnd::GetMessagesHandler(BaseMessageRef msg)
{
if (!msg) return;
auto getMessageRef = std::dynamic_pointer_cast<GetMessages>(msg);
auto user = getMessageRef->getUserName();
uint32_t sequenceID = 0;
{
// lock will be released at end of block
std::unique_lock<std::mutex> lock{ m_usersMutex };
// first check if the user exists
auto fnd = m_users.find(user);
if (fnd == m_users.end())
{
// send reply back
auto reply = GetMessagesReply::create(msg->getFromID(), m_id, MessagesVec{}, "cannot retrieve messages : user does not exist", ++sequenceID, true);
m_commsLayer.push(reply);
return;
}
}
// acquire lock on message data
std::unique_lock<std::mutex> lock{ m_messagesMutex };
// double check that this user is valid?
auto inbox = m_messages.find(user);
if (inbox == m_messages.end())
{
// no such user, send reply back
auto reply = GetMessagesReply::create(msg->getFromID(), m_id, MessagesVec{}, "cannot retrieve message: user does not have any messages", ++sequenceID, true);
m_commsLayer.push(reply);
return;
}
// any messages?
if (inbox->second.empty())
{
// no messages, send reply back
auto reply = GetMessagesReply::create(msg->getFromID(), m_id, MessagesVec{}, "cannot retrieve message: no messages exist", ++sequenceID, true);
m_commsLayer.push(reply);
return;
}
// batch the messages and send
uint32_t count = 0;
uint32_t total = 0;
std::vector<std::pair<std::string, std::string>> messages;
// loop until we have retireved all messages or hit the limit
auto iter = inbox->second.begin();
while (iter != inbox->second.end() && total < m_limits.MAX_TOTAL_MESSAGES_RETRIEVED)
{
if (count >= m_limits.MAX_MESSAGES_RETRIEVED_PER_REPLY)
{
// create and send reply
auto reply = GetMessagesReply::create(msg->getFromID(), m_id, messages, "", ++sequenceID, false);
m_commsLayer.push(reply);
// create new message reply
messages.clear();
count = 0;
}
messages.emplace_back(iter->m_sender, iter->m_content);
++iter;
++count;
++total;
}
// any messages left?
// send them now
if (!messages.empty())
{
// create and send reply
auto reply = GetMessagesReply::create(msg->getFromID(), m_id, messages, "", ++sequenceID, false);
m_commsLayer.push(reply);
}
// transmission of data ended
auto reply = GetMessagesReply::create(msg->getFromID(), m_id, MessagesVec{}, "", ++sequenceID, true);
m_commsLayer.push(reply);
}
void BackEnd::GetReportHandler(BaseMessageRef msg)
{
if (!msg) return;
std::unique_lock<std::mutex> lock{ m_reportsMutex };
uint32_t sequenceID = 0;
// no reports
if (m_reports.empty())
{
// no reports, send reply back
auto reply = GetReportReply::create(msg->getFromID(), m_id, ReportVec{}, "cannot retrieve report: report empty", ++sequenceID, true);
m_commsLayer.push(reply);
return;
}
// compile a printable report
uint32_t count = 0;
uint32_t total = 0;
ReportVec printableReport;
auto reportIter = m_reports.begin();
while (reportIter != m_reports.end() && total < m_limits.MAX_TOTAL_MESSAGES_RETRIEVED)
{
auto report = reportIter->second;
auto num = report.m_count;
// create the title of each entry
auto title = report.m_sender + " " + "(" + std::to_string(num) + (num > 1 ? " messages" : " message") + "):\n";
printableReport.emplace_back(title);
// loop through each reports sent list
auto sentIter = report.m_sentList.begin();
while (sentIter != report.m_sentList.end())
{
// timestamps, sort them in order
auto recipientName = sentIter->first;
auto& timeStampList = sentIter->second;
std::sort(timeStampList.begin(), timeStampList.end()); // maybe a dirty flag to avoid needless sort
auto timeStampIter = timeStampList.begin();
while (timeStampIter != timeStampList.end() && total < m_limits.MAX_TOTAL_MESSAGES_RETRIEVED)
{
if (count >= m_limits.MAX_MESSAGES_RETRIEVED_PER_REPLY)
{
// send a batch of messages
auto reply = GetReportReply::create(msg->getFromID(), m_id, printableReport, "", ++sequenceID, false);
m_commsLayer.push(reply);
printableReport.clear();
count = 0;
}
// convert time to string
auto time = std::chrono::system_clock::to_time_t(*timeStampIter);
// create the recipent entry in the report
std::string recipientStr = " " + std::to_string(time) + ", " + recipientName + "\n";
printableReport.emplace_back(recipientStr);
++timeStampIter;
++count;
++total;
}
++sentIter;
}
++reportIter;
}
if (!printableReport.empty())
{
// send any remaining messages in the buffer
auto reply = GetReportReply::create(msg->getFromID(), m_id, printableReport, "", ++sequenceID, false);
m_commsLayer.push(reply);
}
// send end of transmission message
auto reply = GetReportReply::create(msg->getFromID(), m_id, ReportVec{}, "", ++sequenceID, true);
m_commsLayer.push(reply);
}
} | 31.953488 | 165 | 0.585638 | [
"vector"
] |
632fa09a31b28dd9ad3575c807cf81c59312a13c | 2,254 | cpp | C++ | Miscellaneous/kirito.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | 1 | 2020-10-16T18:14:30.000Z | 2020-10-16T18:14:30.000Z | Miscellaneous/kirito.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | null | null | null | Miscellaneous/kirito.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | 1 | 2021-01-06T04:45:38.000Z | 2021-01-06T04:45:38.000Z | #define __USE_MINGW_ANSI_STDIO 0
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <stack>
#include <deque>
#include <string.h>
#include <math.h>
using namespace std;
int N, M, Q;
int tree [8001], mp [2001];
vector<long long> hashes [2001];
int left(int p){ return p<<1; }
int right(int p){ return (p<<1)+1; }
void hashIt(string s, int a){
int h = 1;
for(int i = 0; i < s.length(); i++){
h = h*43; if(s[i] == '1') h++;
hashes[a].push_back(h);
}
}
int findLow(int a, int b, int lo, int hi){
int ans = -1;
while(lo <= hi){
int mid = (lo+hi)/2;
if(hashes[a][mid] == hashes[b][mid]){
ans = mid;
lo = mid+1;
}
else hi = mid-1;
}
return ans;
}
void build(int p, int L, int R){
if(L == R){
tree[p] = M-1;
return;
}
int li = left(p); int ri = right(p);
build(li, L, (L+R)/2); build(ri, (L+R)/2+1, R);
tree[p] = findLow(mp[L], mp[R], 0, min(tree[li], tree[ri]));
}
void update(int p, int L, int R, int place){
if(L > R || L > place || R < place) return;
if(L == R) return;
int li = left(p); int ri = right(p);
update(li, L, (L+R)/2, place); update(ri, (L+R)/2+1, R, place);
tree[p] = findLow(mp[L], mp[R], 0, min(tree[li], tree[ri]));
}
int query(int p, int L, int R, int i, int j){
if(i > R || j < L) return -2;
if(i <= L && j >= R) return tree[p];
int li = left(p); int ri = right(p);
int a1 = query(li, L, (L+R)/2, i, j);
int a2 = query(ri, (L+R)/2+1, R, i, j);
if(a1 == -2) return a2;
if(a2 == -2) return a1;
return findLow(mp[max(L, i)], mp[min(R, j)], 0, min(a1, a2));
}
int main(){
scanf("%d %d", &N, &M);
for(int i = 0; i < N; i++){
string temp; cin >> temp; mp[i] = i;
hashIt(temp, i);
}
build(1, 0, N-1); scanf("%d", &Q);
for(int i = 0; i < Q; i++){
int a, b; scanf("%d %d", &a, &b);
cout << (query(1, 0, N-1, a-1, b-1)+1)*(b-a+1) << endl;
swap(mp[a-1], mp[b-1]);
update(1, 0, N-1, a-1); update(1, 0, N-1, b-1);
}
return 0;
}
| 24.769231 | 67 | 0.495563 | [
"vector"
] |
6349e7706cc7c70e892f342ad3f5d43f9bb6ff52 | 57,177 | cpp | C++ | TravelCrash/Plugins/HoudiniEngine/Source/HoudiniEngineRuntime/Private/HoudiniAssetInstanceInput.cpp | all-in-one-of/HoudiniBugs | 00ccf448e4536241c9e4cf25ee4906f38479032c | [
"Unlicense"
] | null | null | null | TravelCrash/Plugins/HoudiniEngine/Source/HoudiniEngineRuntime/Private/HoudiniAssetInstanceInput.cpp | all-in-one-of/HoudiniBugs | 00ccf448e4536241c9e4cf25ee4906f38479032c | [
"Unlicense"
] | null | null | null | TravelCrash/Plugins/HoudiniEngine/Source/HoudiniEngineRuntime/Private/HoudiniAssetInstanceInput.cpp | all-in-one-of/HoudiniBugs | 00ccf448e4536241c9e4cf25ee4906f38479032c | [
"Unlicense"
] | null | null | null | /*
* Copyright (c) <2017> Side Effects Software 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.
*
*/
#include "HoudiniApi.h"
#include "HoudiniAssetInstanceInput.h"
#include "HoudiniEngineRuntimePrivatePCH.h"
#include "HoudiniEngineUtils.h"
#include "HoudiniAssetComponent.h"
#include "HoudiniAssetInstanceInputField.h"
#include "HoudiniEngine.h"
#include "HoudiniEngineString.h"
#include "HoudiniInstancedActorComponent.h"
#include "HoudiniMeshSplitInstancerComponent.h"
#include "Components/AudioComponent.h"
#include "Components/InstancedStaticMeshComponent.h"
#include "Components/HierarchicalInstancedStaticMeshComponent.h"
#include "Particles/ParticleSystemComponent.h"
#include "Sound/SoundBase.h"
#include "Internationalization/Internationalization.h"
#include "HoudiniEngineBakeUtils.h"
#define LOCTEXT_NAMESPACE HOUDINI_LOCTEXT_NAMESPACE
UHoudiniAssetInstanceInput::UHoudiniAssetInstanceInput( const FObjectInitializer& ObjectInitializer )
: Super( ObjectInitializer )
, ObjectToInstanceId( -1 )
{
Flags.HoudiniAssetInstanceInputFlagsPacked = 0;
TupleSize = 0;
}
UHoudiniAssetInstanceInput *
UHoudiniAssetInstanceInput::Create(
UHoudiniAssetComponent * InPrimaryObject,
const FHoudiniGeoPartObject & InHoudiniGeoPartObject )
{
if (!InPrimaryObject || InPrimaryObject->IsPendingKill())
return nullptr;
UHoudiniAssetInstanceInput * NewInstanceInput = nullptr;
// Get object to be instanced.
HAPI_NodeId ObjectToInstance = InHoudiniGeoPartObject.HapiObjectGetToInstanceId();
auto Flags = GetInstancerFlags(InHoudiniGeoPartObject);
// This is invalid combination, no object to instance and input is not an attribute instancer.
if ( !Flags.bIsAttributeInstancer && !Flags.bAttributeInstancerOverride && ObjectToInstance == -1 && !Flags.bIsPackedPrimitiveInstancer )
return nullptr;
NewInstanceInput = NewObject< UHoudiniAssetInstanceInput >(
InPrimaryObject,
UHoudiniAssetInstanceInput::StaticClass(),
NAME_None, RF_Public | RF_Transactional );
if ( !NewInstanceInput || NewInstanceInput->IsPendingKill() )
return nullptr;
NewInstanceInput->PrimaryObject = InPrimaryObject;
NewInstanceInput->HoudiniGeoPartObject = InHoudiniGeoPartObject;
NewInstanceInput->SetNameAndLabel( InHoudiniGeoPartObject.ObjectName );
NewInstanceInput->ObjectToInstanceId = ObjectToInstance;
NewInstanceInput->Flags = Flags;
return NewInstanceInput;
}
UHoudiniAssetInstanceInput::FHoudiniAssetInstanceInputFlags
UHoudiniAssetInstanceInput::GetInstancerFlags(const FHoudiniGeoPartObject & InHoudiniGeoPartObject)
{
FHoudiniAssetInstanceInputFlags Flags;
Flags.HoudiniAssetInstanceInputFlagsPacked = 0;
// Get object to be instanced.
HAPI_NodeId ObjectToInstance = InHoudiniGeoPartObject.HapiObjectGetToInstanceId();
Flags.bIsPackedPrimitiveInstancer = InHoudiniGeoPartObject.IsPackedPrimitiveInstancer();
// If this is an attribute instancer, see if attribute exists.
Flags.bIsAttributeInstancer = InHoudiniGeoPartObject.IsAttributeInstancer();
// Check if this is an attribute override instancer (on detail or point).
Flags.bAttributeInstancerOverride = InHoudiniGeoPartObject.IsAttributeOverrideInstancer();
// Check if this is a No-Instancers ( unreal_split_instances )
Flags.bIsSplitMeshInstancer =
InHoudiniGeoPartObject.HapiCheckAttributeExistance(
HAPI_UNREAL_ATTRIB_SPLIT_INSTANCES, HAPI_ATTROWNER_DETAIL );
return Flags;
}
UHoudiniAssetInstanceInput *
UHoudiniAssetInstanceInput::Create(
UHoudiniAssetComponent * InPrimaryObject,
const UHoudiniAssetInstanceInput * OtherInstanceInput )
{
if (!InPrimaryObject || InPrimaryObject->IsPendingKill() )
return nullptr;
UHoudiniAssetInstanceInput * HoudiniAssetInstanceInput =
DuplicateObject( OtherInstanceInput, InPrimaryObject );
if (!HoudiniAssetInstanceInput || HoudiniAssetInstanceInput->IsPendingKill())
return nullptr;
// We need to duplicate field objects manually
HoudiniAssetInstanceInput->InstanceInputFields.Empty();
for ( const auto& OtherField : OtherInstanceInput->InstanceInputFields )
{
UHoudiniAssetInstanceInputField * NewField =
UHoudiniAssetInstanceInputField::Create( InPrimaryObject, OtherField );
if (!NewField || NewField->IsPendingKill())
continue;
HoudiniAssetInstanceInput->InstanceInputFields.Add( NewField );
}
// Fix the back-reference to the component
HoudiniAssetInstanceInput->PrimaryObject = InPrimaryObject;
return HoudiniAssetInstanceInput;
}
bool
UHoudiniAssetInstanceInput::CreateInstanceInput()
{
if ( !PrimaryObject || PrimaryObject->IsPendingKill() )
return false;
HAPI_NodeId AssetId = GetAssetId();
// Retrieve instance transforms (for each point).
TArray< FTransform > AllTransforms;
HoudiniGeoPartObject.HapiGetInstanceTransforms( AssetId, AllTransforms );
// List of new fields. Reused input fields will also be placed here.
TArray< UHoudiniAssetInstanceInputField * > NewInstanceInputFields;
if ( Flags.bIsPackedPrimitiveInstancer )
{
// This is using packed primitives
HAPI_PartInfo PartInfo;
HOUDINI_CHECK_ERROR_RETURN( FHoudiniApi::GetPartInfo(
FHoudiniEngine::Get().GetSession(), HoudiniGeoPartObject.GeoId, HoudiniGeoPartObject.PartId,
&PartInfo ), false );
// Retrieve part name.
//FString PartName;
//FHoudiniEngineString HoudiniEngineStringPartName( PartInfo.nameSH );
//HoudiniEngineStringPartName.ToFString( PartName );
//HOUDINI_LOG_MESSAGE( TEXT( "Part Instancer (%s): IPC=%d, IC=%d" ), *PartName, PartInfo.instancedPartCount, PartInfo.instanceCount );
// Get transforms for each instance
TArray<HAPI_Transform> InstancerPartTransforms;
InstancerPartTransforms.SetNumZeroed( PartInfo.instanceCount );
HOUDINI_CHECK_ERROR_RETURN( FHoudiniApi::GetInstancerPartTransforms(
FHoudiniEngine::Get().GetSession(), HoudiniGeoPartObject.GeoId, PartInfo.id,
HAPI_RSTORDER_DEFAULT, InstancerPartTransforms.GetData(), 0, PartInfo.instanceCount ), false );
// Get the part ids for parts being instanced
TArray<HAPI_PartId> InstancedPartIds;
InstancedPartIds.SetNumZeroed( PartInfo.instancedPartCount );
HOUDINI_CHECK_ERROR_RETURN( FHoudiniApi::GetInstancedPartIds(
FHoudiniEngine::Get().GetSession(), HoudiniGeoPartObject.GeoId, PartInfo.id,
InstancedPartIds.GetData(), 0, PartInfo.instancedPartCount ), false );
for ( auto InstancedPartId : InstancedPartIds )
{
HAPI_PartInfo InstancedPartInfo;
HOUDINI_CHECK_ERROR_RETURN(
FHoudiniApi::GetPartInfo(
FHoudiniEngine::Get().GetSession(), HoudiniGeoPartObject.GeoId, InstancedPartId,
&InstancedPartInfo ), false );
TArray<FTransform> ObjectTransforms;
ObjectTransforms.SetNumUninitialized( InstancerPartTransforms.Num() );
for ( int32 InstanceIdx = 0; InstanceIdx < InstancerPartTransforms.Num(); ++InstanceIdx )
{
const auto& InstanceTransform = InstancerPartTransforms[InstanceIdx];
FHoudiniEngineUtils::TranslateHapiTransform( InstanceTransform, ObjectTransforms[InstanceIdx] );
//HOUDINI_LOG_MESSAGE( TEXT( "Instance %d:%d Transform: %s for Part Id %d" ), HoudiniGeoPartObject.PartId, InstanceIdx, *ObjectTransforms[ InstanceIdx ].ToString(), InstancedPartId );
}
// Create this instanced input field for this instanced part
//
FHoudiniGeoPartObject InstancedPart( HoudiniGeoPartObject.AssetId, HoudiniGeoPartObject.ObjectId, HoudiniGeoPartObject.GeoId, InstancedPartId );
InstancedPart.TransformMatrix = HoudiniGeoPartObject.TransformMatrix;
InstancedPart.UpdateCustomName();
CreateInstanceInputField( InstancedPart, ObjectTransforms, InstanceInputFields, NewInstanceInputFields );
}
}
else if ( Flags.bIsAttributeInstancer )
{
int32 NumPoints = HoudiniGeoPartObject.HapiPartGetPointCount();
TArray< HAPI_NodeId > InstancedObjectIds;
InstancedObjectIds.SetNumUninitialized( NumPoints );
HOUDINI_CHECK_ERROR_RETURN( FHoudiniApi::GetInstancedObjectIds(
FHoudiniEngine::Get().GetSession(), HoudiniGeoPartObject.GeoId,
InstancedObjectIds.GetData(),
0, NumPoints), false );
// Find the set of instanced object ids and locate the corresponding parts
TSet< int32 > UniqueInstancedObjectIds( InstancedObjectIds );
TArray< FTransform > InstanceTransforms;
for ( int32 InstancedObjectId : UniqueInstancedObjectIds )
{
UHoudiniAssetComponent* Comp = GetHoudiniAssetComponent();
if( Comp && !Comp->IsPendingKill() )
{
TArray< FHoudiniGeoPartObject > PartsToInstance;
if( Comp->LocateStaticMeshes( InstancedObjectId, PartsToInstance ) )
{
// copy out the transforms for this instance id
InstanceTransforms.Empty();
for( int32 Ix = 0; Ix < InstancedObjectIds.Num(); ++Ix )
{
if( ( InstancedObjectIds[ Ix ] == InstancedObjectId ) && ( AllTransforms.IsValidIndex( Ix ) ) )
{
InstanceTransforms.Add( AllTransforms[ Ix ] );
}
}
// Locate or create an instance input field for each part for this instanced object id
for( FHoudiniGeoPartObject& Part : PartsToInstance )
{
// Change the transform of the part being instanced to match the instancer
Part.TransformMatrix = HoudiniGeoPartObject.TransformMatrix;
Part.UpdateCustomName();
CreateInstanceInputField( Part, InstanceTransforms, InstanceInputFields, NewInstanceInputFields );
}
}
}
}
}
else if ( Flags.bAttributeInstancerOverride )
{
// This is an attribute override. Unreal mesh is specified through an attribute and we use points.
std::string MarshallingAttributeInstanceOverride = HAPI_UNREAL_ATTRIB_INSTANCE_OVERRIDE;
UHoudiniRuntimeSettings::GetSettingsValue(
TEXT( "MarshallingAttributeInstanceOverride" ),
MarshallingAttributeInstanceOverride );
HAPI_AttributeInfo ResultAttributeInfo;
FMemory::Memzero< HAPI_AttributeInfo >( ResultAttributeInfo );
if ( !HoudiniGeoPartObject.HapiGetAttributeInfo(
AssetId, MarshallingAttributeInstanceOverride, ResultAttributeInfo ) )
{
// We had an error while retrieving the attribute info.
return false;
}
if ( !ResultAttributeInfo.exists )
{
// Attribute does not exist.
return false;
}
if ( ResultAttributeInfo.owner == HAPI_ATTROWNER_DETAIL )
{
// Attribute is on detail, this means it gets applied to all points.
TArray< FString > DetailInstanceValues;
if ( !HoudiniGeoPartObject.HapiGetAttributeDataAsString(
AssetId, MarshallingAttributeInstanceOverride,
HAPI_ATTROWNER_DETAIL, ResultAttributeInfo, DetailInstanceValues ) )
{
// This should not happen - attribute exists, but there was an error retrieving it.
return false;
}
if ( DetailInstanceValues.Num() <= 0 )
{
// No values specified.
return false;
}
// Attempt to load specified asset.
const FString & AssetName = DetailInstanceValues[ 0 ];
UObject * AttributeObject =
StaticLoadObject(
UObject::StaticClass(), nullptr, *AssetName, nullptr, LOAD_None, nullptr );
if ( AttributeObject && !AttributeObject->IsPendingKill() )
{
CreateInstanceInputField(
AttributeObject, AllTransforms, InstanceInputFields, NewInstanceInputFields );
}
else
{
return false;
}
}
else if ( ResultAttributeInfo.owner == HAPI_ATTROWNER_POINT )
{
TArray< FString > PointInstanceValues;
if ( !HoudiniGeoPartObject.HapiGetAttributeDataAsString(
AssetId, MarshallingAttributeInstanceOverride,
HAPI_ATTROWNER_POINT, ResultAttributeInfo, PointInstanceValues ) )
{
// This should not happen - attribute exists, but there was an error retrieving it.
return false;
}
// Attribute is on points, number of points must match number of transforms.
if ( PointInstanceValues.Num() != AllTransforms.Num() )
{
// This should not happen, we have mismatch between number of instance values and transforms.
return false;
}
// If instance attribute exists on points, we need to get all unique values.
TMap< FString, UObject * > ObjectsToInstance;
for ( auto Iter : PointInstanceValues )
{
const FString & UniqueName = *Iter;
if ( !ObjectsToInstance.Contains( UniqueName ) )
{
UObject * AttributeObject = StaticLoadObject(
UObject::StaticClass(), nullptr, *UniqueName, nullptr, LOAD_None, nullptr );
if ( AttributeObject && !AttributeObject->IsPendingKill() )
ObjectsToInstance.Add( UniqueName, AttributeObject );
}
}
bool Success = false;
for( auto Iter : ObjectsToInstance )
{
const FString & InstancePath = Iter.Key;
UObject * AttributeObject = Iter.Value;
if ( AttributeObject && !AttributeObject->IsPendingKill() )
{
TArray< FTransform > ObjectTransforms;
GetPathInstaceTransforms( InstancePath, PointInstanceValues, AllTransforms, ObjectTransforms );
CreateInstanceInputField( AttributeObject, ObjectTransforms, InstanceInputFields, NewInstanceInputFields );
Success = true;
}
}
if ( !Success )
return false;
}
else
{
// We don't support this attribute on other owners.
return false;
}
}
else
{
// This is a standard object type instancer.
// Locate all geo objects requiring instancing (can be multiple if geo / part / object split took place).
TArray< FHoudiniGeoPartObject > ObjectsToInstance;
if( UHoudiniAssetComponent* Comp = GetHoudiniAssetComponent() )
{
if ( !Comp->IsPendingKill() )
Comp->LocateStaticMeshes( ObjectToInstanceId, ObjectsToInstance );
}
// Process each existing detected object that needs to be instanced.
for ( int32 GeoIdx = 0; GeoIdx < ObjectsToInstance.Num(); ++GeoIdx )
{
FHoudiniGeoPartObject & ItemHoudiniGeoPartObject = ObjectsToInstance[ GeoIdx ];
// Change the transform of the part being instanced to match the instancer
ItemHoudiniGeoPartObject.TransformMatrix = HoudiniGeoPartObject.TransformMatrix;
ItemHoudiniGeoPartObject.UpdateCustomName();
// Locate or create an input field.
CreateInstanceInputField(
ItemHoudiniGeoPartObject, AllTransforms, InstanceInputFields, NewInstanceInputFields );
}
}
// Sort and store new fields.
NewInstanceInputFields.Sort( FHoudiniAssetInstanceInputFieldSortPredicate() );
CleanInstanceInputFields( InstanceInputFields );
InstanceInputFields = NewInstanceInputFields;
return true;
}
UHoudiniAssetInstanceInputField *
UHoudiniAssetInstanceInput::LocateInputField(
const FHoudiniGeoPartObject & GeoPartObject)
{
UHoudiniAssetInstanceInputField * FoundHoudiniAssetInstanceInputField = nullptr;
for ( int32 FieldIdx = 0; FieldIdx < InstanceInputFields.Num(); ++FieldIdx )
{
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField = InstanceInputFields[ FieldIdx ];
if (!HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill())
continue;
if ( HoudiniAssetInstanceInputField->GetHoudiniGeoPartObject().GetNodePath() == GeoPartObject.GetNodePath() )
{
FoundHoudiniAssetInstanceInputField = HoudiniAssetInstanceInputField;
break;
}
}
return FoundHoudiniAssetInstanceInputField;
}
void
UHoudiniAssetInstanceInput::CleanInstanceInputFields( TArray< UHoudiniAssetInstanceInputField * > & InInstanceInputFields )
{
UHoudiniAssetInstanceInputField * FoundHoudiniAssetInstanceInputField = nullptr;
for ( int32 FieldIdx = 0; FieldIdx < InstanceInputFields.Num(); ++FieldIdx )
{
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField = InstanceInputFields[ FieldIdx ];
if ( HoudiniAssetInstanceInputField && !HoudiniAssetInstanceInputField->IsPendingKill() )
HoudiniAssetInstanceInputField->ConditionalBeginDestroy();
}
InInstanceInputFields.Empty();
}
UHoudiniAssetComponent*
UHoudiniAssetInstanceInput::GetHoudiniAssetComponent()
{
return Cast<UHoudiniAssetComponent>( PrimaryObject );
}
const UHoudiniAssetComponent*
UHoudiniAssetInstanceInput::GetHoudiniAssetComponent() const
{
return Cast<const UHoudiniAssetComponent>( PrimaryObject );
}
HAPI_NodeId
UHoudiniAssetInstanceInput::GetAssetId() const
{
if( const UHoudiniAssetComponent* Comp = GetHoudiniAssetComponent() )
return Comp->GetAssetId();
return -1;
}
void
UHoudiniAssetInstanceInput::CreateInstanceInputField(
const FHoudiniGeoPartObject & InHoudiniGeoPartObject,
const TArray< FTransform > & ObjectTransforms,
const TArray< UHoudiniAssetInstanceInputField * > & OldInstanceInputFields,
TArray<UHoudiniAssetInstanceInputField * > & NewInstanceInputFields)
{
UHoudiniAssetComponent* Comp = GetHoudiniAssetComponent();
UStaticMesh * StaticMesh = nullptr;
if ( Comp && !Comp->IsPendingKill() )
StaticMesh = Comp->LocateStaticMesh(InHoudiniGeoPartObject, false);
// Locate static mesh for this geo part.
if ( StaticMesh && !StaticMesh->IsPendingKill() )
{
// Locate corresponding input field.
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField =
LocateInputField( InHoudiniGeoPartObject );
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
{
// Input field does not exist, we need to create it.
HoudiniAssetInstanceInputField = UHoudiniAssetInstanceInputField::Create(
PrimaryObject, this, InHoudiniGeoPartObject );
if (HoudiniAssetInstanceInputField && !HoudiniAssetInstanceInputField->IsPendingKill())
{
// Assign original and static mesh.
HoudiniAssetInstanceInputField->OriginalObject = StaticMesh;
HoudiniAssetInstanceInputField->AddInstanceVariation(StaticMesh, 0);
}
}
else
{
// refresh the geo part
HoudiniAssetInstanceInputField->SetGeoPartObject( InHoudiniGeoPartObject );
// Remove item from old list.
InstanceInputFields.RemoveSingleSwap( HoudiniAssetInstanceInputField, false );
TArray< int > MatchingIndices;
HoudiniAssetInstanceInputField->FindObjectIndices(
HoudiniAssetInstanceInputField->GetOriginalObject(),
MatchingIndices );
for ( int Idx = 0; Idx < MatchingIndices.Num(); Idx++ )
{
int ReplacementIndex = MatchingIndices[ Idx ];
HoudiniAssetInstanceInputField->ReplaceInstanceVariation( StaticMesh, ReplacementIndex );
}
HoudiniAssetInstanceInputField->OriginalObject = StaticMesh;
}
if ( HoudiniAssetInstanceInputField && !HoudiniAssetInstanceInputField->IsPendingKill() )
{
// Set transforms for this input.
HoudiniAssetInstanceInputField->SetInstanceTransforms(ObjectTransforms);
HoudiniAssetInstanceInputField->UpdateInstanceUPropertyAttributes();
// Add field to list of fields.
NewInstanceInputFields.Add(HoudiniAssetInstanceInputField);
}
}
else if ( InHoudiniGeoPartObject.IsPackedPrimitiveInstancer() )
{
HAPI_Result Result = HAPI_RESULT_SUCCESS;
// We seem to be instancing a PP instancer, we need to get the transforms
HAPI_PartInfo PartInfo;
HOUDINI_CHECK_ERROR( &Result, FHoudiniApi::GetPartInfo(
FHoudiniEngine::Get().GetSession(), InHoudiniGeoPartObject.GeoId, InHoudiniGeoPartObject.PartId,
&PartInfo ) );
// Get transforms for each instance
TArray<HAPI_Transform> InstancerPartTransforms;
InstancerPartTransforms.SetNumZeroed( PartInfo.instanceCount );
HOUDINI_CHECK_ERROR( &Result, FHoudiniApi::GetInstancerPartTransforms(
FHoudiniEngine::Get().GetSession(), InHoudiniGeoPartObject.GeoId, PartInfo.id,
HAPI_RSTORDER_DEFAULT, InstancerPartTransforms.GetData(), 0, PartInfo.instanceCount ) );
// Get the part ids for parts being instanced
TArray<HAPI_PartId> InstancedPartIds;
InstancedPartIds.SetNumZeroed( PartInfo.instancedPartCount );
HOUDINI_CHECK_ERROR( &Result, FHoudiniApi::GetInstancedPartIds(
FHoudiniEngine::Get().GetSession(), InHoudiniGeoPartObject.GeoId, PartInfo.id,
InstancedPartIds.GetData(), 0, PartInfo.instancedPartCount ) );
for ( auto InstancedPartId : InstancedPartIds )
{
HAPI_PartInfo InstancedPartInfo;
HOUDINI_CHECK_ERROR( &Result,
FHoudiniApi::GetPartInfo(
FHoudiniEngine::Get().GetSession(), InHoudiniGeoPartObject.GeoId, InstancedPartId,
&InstancedPartInfo ) );
TArray<FTransform> PPObjectTransforms;
PPObjectTransforms.SetNumUninitialized( InstancerPartTransforms.Num() );
for ( int32 InstanceIdx = 0; InstanceIdx < InstancerPartTransforms.Num(); ++InstanceIdx )
{
const auto& InstanceTransform = InstancerPartTransforms[InstanceIdx];
FHoudiniEngineUtils::TranslateHapiTransform( InstanceTransform, PPObjectTransforms[InstanceIdx] );
}
// Create this instanced input field for this instanced part
// find static mesh for this instancer
FHoudiniGeoPartObject TempInstancedPart( InHoudiniGeoPartObject.AssetId, InHoudiniGeoPartObject.ObjectId, InHoudiniGeoPartObject.GeoId, InstancedPartId );
UStaticMesh* FoundStaticMesh = Comp->LocateStaticMesh(TempInstancedPart, false);
if ( FoundStaticMesh && !FoundStaticMesh->IsPendingKill() )
{
// Build the list of transforms for this instancer
TArray< FTransform > AllTransforms;
AllTransforms.Empty( PPObjectTransforms.Num() * ObjectTransforms.Num() );
for ( const FTransform& ObjectTransform : ObjectTransforms )
{
for ( const FTransform& PPTransform : PPObjectTransforms )
{
AllTransforms.Add( PPTransform * ObjectTransform );
}
}
CreateInstanceInputField( FoundStaticMesh, AllTransforms, InstanceInputFields, NewInstanceInputFields );
}
else
{
HOUDINI_LOG_WARNING(
TEXT( "CreateInstanceInputField for Packed Primitive: Could not find static mesh for object [%d %s], geo %d, part %d]" ), InHoudiniGeoPartObject.ObjectId, *InHoudiniGeoPartObject.ObjectName, InHoudiniGeoPartObject.GeoId, InstancedPartId );
}
}
}
else
{
HOUDINI_LOG_WARNING(
TEXT( "CreateInstanceInputField: Could not find static mesh for object [%d %s], geo %d, part %d]" ), InHoudiniGeoPartObject.ObjectId, *InHoudiniGeoPartObject.ObjectName, InHoudiniGeoPartObject.GeoId, InHoudiniGeoPartObject.PartId );
}
}
void
UHoudiniAssetInstanceInput::CreateInstanceInputField(
UObject * InstancedObject,
const TArray< FTransform > & ObjectTransforms,
const TArray< UHoudiniAssetInstanceInputField * > & OldInstanceInputFields,
TArray< UHoudiniAssetInstanceInputField * > & NewInstanceInputFields )
{
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField = nullptr;
// Locate all fields which have this static mesh set as original mesh.
TArray< UHoudiniAssetInstanceInputField * > CandidateFields = InstanceInputFields;
CandidateFields.FilterByPredicate( [&]( const UHoudiniAssetInstanceInputField* Field ) {
return Field->GetOriginalObject() == InstancedObject;
} );
if ( CandidateFields.Num() > 0 )
{
HoudiniAssetInstanceInputField = CandidateFields[ 0 ];
InstanceInputFields.RemoveSingleSwap( HoudiniAssetInstanceInputField, false );
TArray< int32 > MatchingIndices;
HoudiniAssetInstanceInputField->FindObjectIndices(
HoudiniAssetInstanceInputField->GetOriginalObject(),
MatchingIndices );
for ( int32 ReplacementIndex : MatchingIndices )
{
HoudiniAssetInstanceInputField->ReplaceInstanceVariation( InstancedObject, ReplacementIndex );
}
HoudiniAssetInstanceInputField->OriginalObject = InstancedObject;
// refresh the geo part
FHoudiniGeoPartObject RefreshedGeoPart = HoudiniAssetInstanceInputField->GetHoudiniGeoPartObject();
RefreshedGeoPart.TransformMatrix = HoudiniGeoPartObject.TransformMatrix;
HoudiniAssetInstanceInputField->SetGeoPartObject( RefreshedGeoPart );
// Update component transformation.
HoudiniAssetInstanceInputField->UpdateRelativeTransform();
}
else
{
// Create a dummy part for this field
FHoudiniGeoPartObject InstancedPart;
InstancedPart.TransformMatrix = HoudiniGeoPartObject.TransformMatrix;
HoudiniAssetInstanceInputField = UHoudiniAssetInstanceInputField::Create(
PrimaryObject, this, InstancedPart );
// Assign original and static mesh.
HoudiniAssetInstanceInputField->OriginalObject = InstancedObject;
HoudiniAssetInstanceInputField->AddInstanceVariation( InstancedObject, 0 );
}
// Set transforms for this input.
HoudiniAssetInstanceInputField->SetInstanceTransforms( ObjectTransforms );
// Add field to list of fields.
NewInstanceInputFields.Add( HoudiniAssetInstanceInputField );
}
void
UHoudiniAssetInstanceInput::RecreateRenderStates()
{
for ( int32 Idx = 0; Idx < InstanceInputFields.Num(); ++Idx )
{
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField = InstanceInputFields[ Idx ];
HoudiniAssetInstanceInputField->RecreateRenderState();
}
}
void
UHoudiniAssetInstanceInput::RecreatePhysicsStates()
{
for ( int32 Idx = 0; Idx < InstanceInputFields.Num(); ++Idx )
{
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField = InstanceInputFields[ Idx ];
HoudiniAssetInstanceInputField->RecreatePhysicsState();
}
}
void UHoudiniAssetInstanceInput::SetGeoPartObject( const FHoudiniGeoPartObject& InGeoPartObject )
{
HoudiniGeoPartObject = InGeoPartObject;
if ( ObjectToInstanceId == -1 )
{
ObjectToInstanceId = InGeoPartObject.HapiObjectGetToInstanceId();
}
}
bool
UHoudiniAssetInstanceInput::CreateParameter(
UObject * InPrimaryObject,
UHoudiniAssetParameter * InParentParameter,
HAPI_NodeId InNodeId, const HAPI_ParmInfo & ParmInfo)
{
// This implementation is not a true parameter. This method should not be called.
check( false );
return false;
}
#if WITH_EDITOR
void
UHoudiniAssetInstanceInput::OnAddInstanceVariation( UHoudiniAssetInstanceInputField * InstanceInputField, int32 Index )
{
InstanceInputField->AddInstanceVariation( InstanceInputField->GetInstanceVariation( Index ), Index );
OnParamStateChanged();
}
void
UHoudiniAssetInstanceInput::OnRemoveInstanceVariation( UHoudiniAssetInstanceInputField * InstanceInputField, int32 Index )
{
InstanceInputField->RemoveInstanceVariation( Index );
OnParamStateChanged();
}
FString UHoudiniAssetInstanceInput::GetFieldLabel( int32 FieldIdx, int32 VariationIdx ) const
{
FString FieldNameText = FString();
if (!InstanceInputFields.IsValidIndex(FieldIdx))
return FieldNameText;
UHoudiniAssetInstanceInputField * Field = InstanceInputFields[ FieldIdx ];
if ( !Field || Field->IsPendingKill() )
return FieldNameText;
if ( Flags.bIsPackedPrimitiveInstancer )
{
if ( Field->GetHoudiniGeoPartObject().HasCustomName() )
FieldNameText = Field->GetHoudiniGeoPartObject().PartName;
else
FieldNameText = Field->GetHoudiniGeoPartObject().GetNodePath();
}
else if ( Flags.bAttributeInstancerOverride )
{
if ( HoudiniGeoPartObject.HasCustomName() )
FieldNameText = HoudiniGeoPartObject.PartName;
else
FieldNameText = HoudiniGeoPartObject.GetNodePath() + TEXT( "/Override_" ) + FString::FromInt( FieldIdx );
}
else
{
// For object-instancers we use the instancer's name as well
if (HoudiniGeoPartObject.HasCustomName())
FieldNameText = HoudiniGeoPartObject.PartName;
else
FieldNameText = HoudiniGeoPartObject.GetNodePath() + TEXT( "/" ) + Field->GetHoudiniGeoPartObject().ObjectName;
}
if ( Field->InstanceVariationCount() > 1 )
FieldNameText += FString::Printf( TEXT( " [%d]" ), VariationIdx );
return FieldNameText;
}
#endif
void
UHoudiniAssetInstanceInput::BeginDestroy()
{
for ( int32 Idx = 0; Idx < InstanceInputFields.Num(); ++Idx )
InstanceInputFields[ Idx ]->ConditionalBeginDestroy();
InstanceInputFields.Empty();
Super::BeginDestroy();
}
void
UHoudiniAssetInstanceInput::SetHoudiniAssetComponent( UHoudiniAssetComponent * InComponent )
{
UHoudiniAssetParameter::SetHoudiniAssetComponent( InComponent );
for ( int32 Idx = 0; Idx < InstanceInputFields.Num(); ++Idx )
{
InstanceInputFields[ Idx ]->HoudiniAssetComponent = InComponent;
InstanceInputFields[ Idx ]->HoudiniAssetInstanceInput = this;
}
}
void
UHoudiniAssetInstanceInput::Serialize( FArchive & Ar )
{
// Call base implementation.
Super::Serialize( Ar );
Ar.UsingCustomVersion( FHoudiniCustomSerializationVersion::GUID );
Ar << Flags.HoudiniAssetInstanceInputFlagsPacked;
Ar << HoudiniGeoPartObject;
Ar << ObjectToInstanceId;
// Object id is transient
if ( Ar.IsLoading() && !Ar.IsTransacting() )
ObjectToInstanceId = -1;
// Serialize fields.
Ar << InstanceInputFields;
}
void
UHoudiniAssetInstanceInput::AddReferencedObjects( UObject * InThis, FReferenceCollector & Collector )
{
UHoudiniAssetInstanceInput * HoudiniAssetInstanceInput = Cast< UHoudiniAssetInstanceInput >( InThis );
if ( HoudiniAssetInstanceInput && !HoudiniAssetInstanceInput->IsPendingKill() )
{
// Add references to all used fields.
for ( int32 Idx = 0; Idx < HoudiniAssetInstanceInput->InstanceInputFields.Num(); ++Idx )
{
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField =
HoudiniAssetInstanceInput->InstanceInputFields[ Idx ];
if ( HoudiniAssetInstanceInputField && !HoudiniAssetInstanceInputField->IsPendingKill() )
Collector.AddReferencedObject( HoudiniAssetInstanceInputField, InThis );
}
}
// Call base implementation.
Super::AddReferencedObjects( InThis, Collector );
}
#if WITH_EDITOR
void
UHoudiniAssetInstanceInput::CloneComponentsAndAttachToActor( AActor * Actor )
{
if (!Actor || Actor->IsPendingKill())
return;
USceneComponent * RootComponent = Actor->GetRootComponent();
TMap< const UStaticMesh*, UStaticMesh* > OriginalToBakedMesh;
for ( int32 Idx = 0; Idx < InstanceInputFields.Num(); ++Idx )
{
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField = InstanceInputFields[ Idx ];
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
continue;
for ( int32 VariationIdx = 0;
VariationIdx < HoudiniAssetInstanceInputField->InstanceVariationCount(); VariationIdx++ )
{
UInstancedStaticMeshComponent * ISMC =
Cast<UInstancedStaticMeshComponent>( HoudiniAssetInstanceInputField->GetInstancedComponent( VariationIdx ) );
UHoudiniMeshSplitInstancerComponent * MSIC =
Cast<UHoudiniMeshSplitInstancerComponent>( HoudiniAssetInstanceInputField->GetInstancedComponent( VariationIdx ) );
if ( ( !ISMC || ISMC->IsPendingKill() ) && ( !MSIC || MSIC->IsPendingKill() ) )
{
UHoudiniInstancedActorComponent* IAC = Cast<UHoudiniInstancedActorComponent>(HoudiniAssetInstanceInputField->GetInstancedComponent(VariationIdx));
if ( !IAC || IAC->IsPendingKill() || !IAC->InstancedAsset )
continue;
UClass* ObjectClass = IAC->InstancedAsset->GetClass();
if ( !ObjectClass || ObjectClass->IsPendingKill() )
continue;
TSubclassOf<AActor> ActorClass;
if( ObjectClass->IsChildOf<AActor>() )
{
ActorClass = ObjectClass;
}
else if( ObjectClass->IsChildOf<UBlueprint>() )
{
UBlueprint* BlueprintObj = StaticCast<UBlueprint*>( IAC->InstancedAsset );
if ( BlueprintObj && !BlueprintObj->IsPendingKill() )
ActorClass = *BlueprintObj->GeneratedClass;
}
if( *ActorClass )
{
for( AActor* InstancedActor : IAC->Instances )
{
if( !InstancedActor || InstancedActor->IsPendingKill() )
continue;
UChildActorComponent* CAC = NewObject< UChildActorComponent >( Actor, UChildActorComponent::StaticClass(), NAME_None, RF_Public );
if ( !CAC || CAC->IsPendingKill() )
continue;
Actor->AddInstanceComponent( CAC );
CAC->SetChildActorClass( ActorClass );
CAC->RegisterComponent();
CAC->SetWorldTransform( InstancedActor->GetTransform() );
if ( RootComponent && !RootComponent->IsPendingKill() )
CAC->AttachToComponent( RootComponent, FAttachmentTransformRules::KeepWorldTransform );
}
}
else if( ObjectClass->IsChildOf<UParticleSystem>() )
{
for( AActor* InstancedActor : IAC->Instances )
{
if( InstancedActor && !InstancedActor->IsPendingKill() )
{
UParticleSystemComponent* PSC = NewObject< UParticleSystemComponent >( Actor, UParticleSystemComponent::StaticClass(), NAME_None, RF_Public );
if ( !PSC || PSC->IsPendingKill() )
continue;
Actor->AddInstanceComponent( PSC );
PSC->SetTemplate( StaticCast<UParticleSystem*>( IAC->InstancedAsset ) );
PSC->RegisterComponent();
PSC->SetWorldTransform( InstancedActor->GetTransform() );
if ( RootComponent && !RootComponent->IsPendingKill() )
PSC->AttachToComponent( RootComponent, FAttachmentTransformRules::KeepWorldTransform );
}
}
}
else if( ObjectClass->IsChildOf<USoundBase>() )
{
for( AActor* InstancedActor : IAC->Instances )
{
if( InstancedActor && !InstancedActor->IsPendingKill() )
{
UAudioComponent* AC = NewObject< UAudioComponent >( Actor, UAudioComponent::StaticClass(), NAME_None, RF_Public );
if ( !AC || AC->IsPendingKill() )
continue;
Actor->AddInstanceComponent( AC );
AC->SetSound( StaticCast<USoundBase*>( IAC->InstancedAsset ) );
AC->RegisterComponent();
AC->SetWorldTransform( InstancedActor->GetTransform() );
if ( RootComponent && !RootComponent->IsPendingKill() )
AC->AttachToComponent( RootComponent, FAttachmentTransformRules::KeepWorldTransform );
}
}
}
else
{
// Oh no, the asset is not something we know. We will need to handle each asset type case by case.
// for example we could create a bunch of ParticleSystemComponent if given an emitter asset
HOUDINI_LOG_ERROR( TEXT( "Can not bake instanced actor component for asset type %s" ), *ObjectClass->GetName() );
}
}
// If original static mesh is used, then we need to bake it (once) and use that one instead.
UStaticMesh* OutStaticMesh = Cast<UStaticMesh>( HoudiniAssetInstanceInputField->GetInstanceVariation( VariationIdx ) );
if ( HoudiniAssetInstanceInputField->IsOriginalObjectUsed( VariationIdx ) )
{
UStaticMesh* OriginalSM = Cast<UStaticMesh>(HoudiniAssetInstanceInputField->GetOriginalObject());
if( OriginalSM && !OriginalSM->IsPendingKill() )
{
auto Comp = GetHoudiniAssetComponent();
if ( Comp && !Comp->IsPendingKill() )
{
auto&& ItemGeoPartObject = Comp->LocateGeoPartObject(OutStaticMesh);
FHoudiniEngineBakeUtils::CheckedBakeStaticMesh(Comp, OriginalToBakedMesh, ItemGeoPartObject, OriginalSM);
OutStaticMesh = OriginalToBakedMesh[OutStaticMesh];
}
}
}
if( ISMC && !ISMC->IsPendingKill() )
{
// Do we need a Hierarchical ISMC ?
UHierarchicalInstancedStaticMeshComponent * HISMC =
Cast<UHierarchicalInstancedStaticMeshComponent>( HoudiniAssetInstanceInputField->GetInstancedComponent( VariationIdx ) );
UInstancedStaticMeshComponent* DuplicatedComponent = nullptr;
if ( HISMC && !HISMC->IsPendingKill() )
DuplicatedComponent = NewObject< UHierarchicalInstancedStaticMeshComponent >(
Actor, UHierarchicalInstancedStaticMeshComponent::StaticClass(), NAME_None, RF_Public );
else
DuplicatedComponent = NewObject< UInstancedStaticMeshComponent >(
Actor, UInstancedStaticMeshComponent::StaticClass(), NAME_None, RF_Public );
if (DuplicatedComponent && !DuplicatedComponent->IsPendingKill())
{
Actor->AddInstanceComponent(DuplicatedComponent);
DuplicatedComponent->SetStaticMesh(OutStaticMesh);
// Reapply the uproperties modified by attributes on the duplicated component
FHoudiniEngineUtils::UpdateUPropertyAttributesOnObject(DuplicatedComponent, HoudiniGeoPartObject);
TArray<FTransform> ProcessedTransforms;
HoudiniAssetInstanceInputField->GetProcessedTransforms(ProcessedTransforms, VariationIdx);
// Set component instances.
UHoudiniInstancedActorComponent::UpdateInstancerComponentInstances(
DuplicatedComponent, ProcessedTransforms, HoudiniAssetInstanceInputField->GetInstancedColors( VariationIdx ) );
// Copy visibility.
DuplicatedComponent->SetVisibility(ISMC->IsVisible());
if ( RootComponent && !RootComponent->IsPendingKill() )
DuplicatedComponent->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
DuplicatedComponent->RegisterComponent();
DuplicatedComponent->GetBodyInstance()->bAutoWeld = false;
}
}
else if ( MSIC && !MSIC->IsPendingKill() )
{
for( UStaticMeshComponent* OtherSMC : MSIC->GetInstances() )
{
if ( !OtherSMC || OtherSMC->IsPendingKill() )
continue;
FString CompName = OtherSMC->GetName();
CompName.ReplaceInline( TEXT("StaticMeshComponent"), TEXT("StaticMesh") );
UStaticMeshComponent* NewSMC = DuplicateObject< UStaticMeshComponent >(OtherSMC, Actor, *CompName);
if( NewSMC && !NewSMC->IsPendingKill() )
{
if ( RootComponent && !RootComponent->IsPendingKill() )
NewSMC->SetupAttachment( RootComponent );
NewSMC->SetStaticMesh( OutStaticMesh );
Actor->AddInstanceComponent( NewSMC );
NewSMC->SetWorldTransform( OtherSMC->GetComponentTransform() );
NewSMC->RegisterComponent();
}
}
}
}
}
}
#endif
void
UHoudiniAssetInstanceInput::GetPathInstaceTransforms(
const FString & ObjectInstancePath,
const TArray< FString > & PointInstanceValues, const TArray< FTransform > & Transforms,
TArray< FTransform > & OutTransforms)
{
OutTransforms.Empty();
for ( int32 Idx = 0; Idx < PointInstanceValues.Num(); ++Idx )
{
if ( ObjectInstancePath.Equals( PointInstanceValues[ Idx ] ) )
OutTransforms.Add( Transforms[ Idx ] );
}
}
#if WITH_EDITOR
void
UHoudiniAssetInstanceInput::OnStaticMeshDropped(
UObject * InObject,
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField,
int32 Idx, int32 VariationIdx )
{
if ( !InObject || InObject->IsPendingKill() )
return;
ULevel* CurrentLevel = GWorld->GetCurrentLevel();
ULevel* MyLevel = GetHoudiniAssetComponent()->GetOwner()->GetLevel();
if( MyLevel != CurrentLevel )
{
HOUDINI_LOG_ERROR( TEXT( "%s: Could not spawn instanced actor because the actor's level is not the Current Level." ), *GetHoudiniAssetComponent()->GetOwner()->GetName() );
FHoudiniEngineUtils::CreateSlateNotification( TEXT( "Could not spawn instanced actor because the actor's level is not the Current Level." ) );
return;
}
UObject * UsedObj = HoudiniAssetInstanceInputField->GetInstanceVariation( VariationIdx );
if ( UsedObj != InObject )
{
FScopedTransaction Transaction(
TEXT( HOUDINI_MODULE_RUNTIME ),
LOCTEXT( "HoudiniInstanceInputChange", "Houdini Instance Input Change" ),
PrimaryObject );
HoudiniAssetInstanceInputField->Modify();
HoudiniAssetInstanceInputField->ReplaceInstanceVariation( InObject, VariationIdx );
OnParamStateChanged();
}
}
FReply
UHoudiniAssetInstanceInput::OnThumbnailDoubleClick(
const FGeometry & InMyGeometry, const FPointerEvent & InMouseEvent, UObject * Object )
{
if ( Object && GEditor )
GEditor->EditObject( Object );
return FReply::Handled();
}
void UHoudiniAssetInstanceInput::OnInstancedObjectBrowse( UObject* InstancedObject )
{
if ( GEditor )
{
TArray< UObject * > Objects;
Objects.Add( InstancedObject );
GEditor->SyncBrowserToObjects( Objects );
}
}
FReply
UHoudiniAssetInstanceInput::OnResetStaticMeshClicked(
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField,
int32 Idx, int32 VariationIdx )
{
UObject * Obj = HoudiniAssetInstanceInputField->GetOriginalObject();
OnStaticMeshDropped( Obj, HoudiniAssetInstanceInputField, Idx, VariationIdx );
return FReply::Handled();
}
void
UHoudiniAssetInstanceInput::CloseStaticMeshComboButton(
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField,
int32 Idx, int32 VariationIdx )
{
// Do nothing.
}
void
UHoudiniAssetInstanceInput::ChangedStaticMeshComboButton(
bool bOpened, UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 Idx, int32 VariationIdx )
{
if ( !bOpened )
{
// If combo button has been closed, update the UI.
OnParamStateChanged();
}
}
TOptional< float >
UHoudiniAssetInstanceInput::GetRotationRoll(
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx ) const
{
const FRotator & Rotator = HoudiniAssetInstanceInputField->GetRotationOffset( VariationIdx );
return Rotator.Roll;
}
TOptional< float >
UHoudiniAssetInstanceInput::GetRotationPitch(
UHoudiniAssetInstanceInputField* HoudiniAssetInstanceInputField, int32 VariationIdx ) const
{
const FRotator & Rotator = HoudiniAssetInstanceInputField->GetRotationOffset( VariationIdx );
return Rotator.Pitch;
}
TOptional< float >
UHoudiniAssetInstanceInput::GetRotationYaw(
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx ) const
{
const FRotator& Rotator = HoudiniAssetInstanceInputField->GetRotationOffset( VariationIdx );
return Rotator.Yaw;
}
void
UHoudiniAssetInstanceInput::SetRotationRoll(
float Value, UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx )
{
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
return;
FScopedTransaction Transaction(
TEXT( HOUDINI_MODULE_RUNTIME ),
LOCTEXT( "HoudiniInstanceInputChange", "Houdini Instance Input Change" ),
PrimaryObject );
HoudiniAssetInstanceInputField->Modify();
FRotator Rotator = HoudiniAssetInstanceInputField->GetRotationOffset( VariationIdx );
Rotator.Roll = Value;
HoudiniAssetInstanceInputField->SetRotationOffset( Rotator, VariationIdx );
HoudiniAssetInstanceInputField->UpdateInstanceTransforms( false );
}
void
UHoudiniAssetInstanceInput::SetRotationPitch(
float Value, UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx )
{
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
return;
FScopedTransaction Transaction(
TEXT( HOUDINI_MODULE_RUNTIME ),
LOCTEXT( "HoudiniInstanceInputChange", "Houdini Instance Input Change" ),
PrimaryObject );
HoudiniAssetInstanceInputField->Modify();
FRotator Rotator = HoudiniAssetInstanceInputField->GetRotationOffset( VariationIdx );
Rotator.Pitch = Value;
HoudiniAssetInstanceInputField->SetRotationOffset( Rotator, VariationIdx );
HoudiniAssetInstanceInputField->UpdateInstanceTransforms( false );
}
void
UHoudiniAssetInstanceInput::SetRotationYaw(
float Value, UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx )
{
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
return;
FScopedTransaction Transaction(
TEXT( HOUDINI_MODULE_RUNTIME ),
LOCTEXT( "HoudiniInstanceInputChange", "Houdini Instance Input Change" ),
PrimaryObject );
HoudiniAssetInstanceInputField->Modify();
FRotator Rotator = HoudiniAssetInstanceInputField->GetRotationOffset( VariationIdx );
Rotator.Yaw = Value;
HoudiniAssetInstanceInputField->SetRotationOffset( Rotator, VariationIdx );
HoudiniAssetInstanceInputField->UpdateInstanceTransforms( false );
}
TOptional< float >
UHoudiniAssetInstanceInput::GetScaleX(
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx ) const
{
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
return 1.0f;
const FVector & Scale3D = HoudiniAssetInstanceInputField->GetScaleOffset( VariationIdx );
return Scale3D.X;
}
TOptional< float >
UHoudiniAssetInstanceInput::GetScaleY(
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx ) const
{
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
return 1.0f;
const FVector & Scale3D = HoudiniAssetInstanceInputField->GetScaleOffset( VariationIdx );
return Scale3D.Y;
}
TOptional< float >
UHoudiniAssetInstanceInput::GetScaleZ(
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx ) const
{
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
return 1.0f;
const FVector & Scale3D = HoudiniAssetInstanceInputField->GetScaleOffset( VariationIdx );
return Scale3D.Z;
}
void
UHoudiniAssetInstanceInput::SetScaleX(
float Value, UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx )
{
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
return;
FScopedTransaction Transaction(
TEXT( HOUDINI_MODULE_RUNTIME ),
LOCTEXT( "HoudiniInstanceInputChange", "Houdini Instance Input Change" ),
PrimaryObject );
HoudiniAssetInstanceInputField->Modify();
FVector Scale3D = HoudiniAssetInstanceInputField->GetScaleOffset( VariationIdx );
Scale3D.X = Value;
if ( HoudiniAssetInstanceInputField->AreOffsetsScaledLinearly( VariationIdx ) )
{
Scale3D.Y = Value;
Scale3D.Z = Value;
}
HoudiniAssetInstanceInputField->SetScaleOffset( Scale3D, VariationIdx );
HoudiniAssetInstanceInputField->UpdateInstanceTransforms( false );
}
void
UHoudiniAssetInstanceInput::SetScaleY(
float Value, UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx)
{
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
return;
FScopedTransaction Transaction(
TEXT( HOUDINI_MODULE_RUNTIME ),
LOCTEXT( "HoudiniInstanceInputChange", "Houdini Instance Input Change" ),
PrimaryObject );
HoudiniAssetInstanceInputField->Modify();
FVector Scale3D = HoudiniAssetInstanceInputField->GetScaleOffset( VariationIdx );
Scale3D.Y = Value;
if ( HoudiniAssetInstanceInputField->AreOffsetsScaledLinearly( VariationIdx ) )
{
Scale3D.X = Value;
Scale3D.Z = Value;
}
HoudiniAssetInstanceInputField->SetScaleOffset( Scale3D, VariationIdx );
HoudiniAssetInstanceInputField->UpdateInstanceTransforms( false );
}
void
UHoudiniAssetInstanceInput::SetScaleZ(
float Value, UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx)
{
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
return;
FScopedTransaction Transaction(
TEXT( HOUDINI_MODULE_RUNTIME ),
LOCTEXT( "HoudiniInstanceInputChange", "Houdini Instance Input Change" ),
PrimaryObject );
HoudiniAssetInstanceInputField->Modify();
FVector Scale3D = HoudiniAssetInstanceInputField->GetScaleOffset( VariationIdx );
Scale3D.Z = Value;
if ( HoudiniAssetInstanceInputField->AreOffsetsScaledLinearly( VariationIdx ) )
{
Scale3D.Y = Value;
Scale3D.X = Value;
}
HoudiniAssetInstanceInputField->SetScaleOffset( Scale3D, VariationIdx );
HoudiniAssetInstanceInputField->UpdateInstanceTransforms( false );
}
void
UHoudiniAssetInstanceInput::CheckStateChanged(
bool IsChecked, UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField, int32 VariationIdx )
{
if ( !HoudiniAssetInstanceInputField || HoudiniAssetInstanceInputField->IsPendingKill() )
return;
FScopedTransaction Transaction(
TEXT( HOUDINI_MODULE_RUNTIME ),
LOCTEXT( "HoudiniInstanceInputChange", "Houdini Instance Input Change" ),
PrimaryObject );
HoudiniAssetInstanceInputField->Modify();
HoudiniAssetInstanceInputField->SetLinearOffsetScale( IsChecked, VariationIdx );
}
#endif
bool
UHoudiniAssetInstanceInput::CollectAllInstancedStaticMeshComponents(
TArray< UInstancedStaticMeshComponent * > & Components, const UStaticMesh * StaticMesh )
{
bool bCollected = false;
for ( int32 Idx = 0; Idx < InstanceInputFields.Num(); ++Idx )
{
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField = InstanceInputFields[ Idx ];
if ( HoudiniAssetInstanceInputField && !HoudiniAssetInstanceInputField->IsPendingKill() )
{
UStaticMesh * OriginalStaticMesh = Cast< UStaticMesh >( HoudiniAssetInstanceInputField->GetOriginalObject() );
if ( OriginalStaticMesh == StaticMesh )
{
for ( int32 IdxMesh = 0; IdxMesh < HoudiniAssetInstanceInputField->InstancedObjects.Num(); ++IdxMesh )
{
UStaticMesh * UsedStaticMesh = Cast< UStaticMesh >( HoudiniAssetInstanceInputField->InstancedObjects[ IdxMesh ] );
if ( UsedStaticMesh == StaticMesh )
{
if ( !HoudiniAssetInstanceInputField->InstancerComponents.IsValidIndex(IdxMesh) )
continue;
UInstancedStaticMeshComponent* ISMC = Cast< UInstancedStaticMeshComponent >( HoudiniAssetInstanceInputField->InstancerComponents[ IdxMesh ] );
if ( !ISMC || ISMC->IsPendingKill() )
continue;
Components.Add( ISMC );
bCollected = true;
}
}
}
}
}
return bCollected;
}
bool
UHoudiniAssetInstanceInput::GetMaterialReplacementMeshes(
UMaterialInterface * Material,
TMap< UStaticMesh *, int32 > & MaterialReplacementsMap )
{
bool bResult = false;
for ( int32 Idx = 0; Idx < InstanceInputFields.Num(); ++Idx )
{
UHoudiniAssetInstanceInputField * HoudiniAssetInstanceInputField = InstanceInputFields[ Idx ];
if ( HoudiniAssetInstanceInputField && !HoudiniAssetInstanceInputField->IsPendingKill() )
bResult |= HoudiniAssetInstanceInputField->GetMaterialReplacementMeshes( Material, MaterialReplacementsMap );
}
return bResult;
}
#undef LOCTEXT_NAMESPACE | 41.075431 | 259 | 0.66999 | [
"mesh",
"object",
"transform"
] |
635049a9bcdc72ef088737318c88d87406c54a4e | 43,788 | hpp | C++ | include/psi/path_base.hpp | cartoonist/psi | 56caf15a9e1b1e395d99e42bad3972ee00bb0d8d | [
"MIT"
] | 19 | 2019-03-26T05:01:04.000Z | 2022-03-04T00:09:11.000Z | include/psi/path_base.hpp | cartoonist/psi | 56caf15a9e1b1e395d99e42bad3972ee00bb0d8d | [
"MIT"
] | 1 | 2020-01-27T23:09:08.000Z | 2020-01-27T23:09:08.000Z | include/psi/path_base.hpp | cartoonist/psi | 56caf15a9e1b1e395d99e42bad3972ee00bb0d8d | [
"MIT"
] | 1 | 2019-07-23T01:42:56.000Z | 2019-07-23T01:42:56.000Z | /**
* @file path_base.hpp
* @brief Path template class definitions.
*
* This header file defines Path template class in variation graph, its specializations
* for different purposes.
*
* @author Ali Ghaffaari (\@cartoonist), <ali.ghaffaari@mpi-inf.mpg.de>
*
* @internal
* Created: Sat Mar 31, 2018 22:17
* Organization: Max-Planck-Institut fuer Informatik
* Copyright: Copyright (c) 2018, Ali Ghaffaari
*
* This source code is released under the terms of the MIT License.
* See LICENSE file for more information.
*/
#ifndef PSI_PATH_BASE_HPP__
#define PSI_PATH_BASE_HPP__
#include <fstream>
#include <stdexcept>
#include <type_traits>
#include <vector>
#include <string>
#include <set>
#include <deque>
#include <algorithm>
#include <utility>
#include <seqan/basic.h>
#include <sdsl/bit_vectors.hpp>
#include "sequence.hpp"
#include "utils.hpp"
namespace psi {
/* Path specialization tags. */
struct DefaultStrategy;
struct DynamicStrategy;
struct MicroStrategy;
struct CompactStrategy;
struct HaplotypeStrategy;
typedef seqan::Tag< DefaultStrategy > Default;
typedef seqan::Tag< DynamicStrategy > Dynamic;
typedef seqan::Tag< CompactStrategy > Compact;
typedef seqan::Tag< MicroStrategy > Micro;
typedef seqan::Tag< HaplotypeStrategy > Haplotype;
/* Path node existence query strategies */
struct OrderedStrategy;
struct UnorderedStrategy;
typedef seqan::Tag< OrderedStrategy > Ordered;
typedef seqan::Tag< UnorderedStrategy > Unordered;
template< typename TGraph, typename TSpec >
struct PathTraits;
template< typename TGraph >
struct PathTraits< TGraph, Default > {
typedef std::vector< typename TGraph::id_type > TNodeSequence;
typedef TNodeSequence TNodeVector;
};
template< typename TGraph >
struct PathTraits< TGraph, Dynamic > {
typedef std::deque< typename TGraph::id_type > TNodeSequence;
typedef TNodeSequence TNodeVector;
};
template< typename TGraph >
struct PathTraits< TGraph, Compact > {
typedef sdsl::enc_vector< sdsl::coder::elias_delta > TNodeSequence;
typedef TNodeSequence::int_vector_type TNodeVector;
};
template< typename TGraph >
struct PathTraits< TGraph, Haplotype > {
typedef sdsl::bit_vector TNodeSequence;
typedef TNodeSequence TNodeVector;
};
/**
* @brief Path template class.
*
* Represent a path in the variation graph with efficient node ID query.
*/
template< typename TGraph, typename TSpec = Default >
class Path
{
private:
/* ==================== TYPEDEFS ======================================= */
typedef PathTraits< TGraph, TSpec > TTraits;
public:
/* ==================== TYPEDEFS ======================================= */
typedef TGraph graph_type;
typedef TSpec spec_type;
typedef std::string string_type;
typedef string_type::size_type seqsize_type;
typedef typename TTraits::TNodeSequence nodes_type;
typedef typename TTraits::TNodeVector mutable_nodes_type;
typedef typename graph_type::id_type value_type;
typedef typename graph_type::offset_type offset_type;
typedef typename nodes_type::size_type size_type;
typedef ptrdiff_t difference_type;
typedef typename nodes_type::const_iterator const_iterator;
private:
/* ==================== DATA MEMBERS ======================================= */
const graph_type* graph_ptr;
nodes_type nodes;
offset_type left; /**< @brief The length of the first node sequence */
offset_type right; /**< @brief The length of the last node sequence */
seqsize_type seqlen;
/* Loaded on demand. */
string_type seq;
/* Loaded after calling `initialize`. */
bool initialized;
sdsl::bit_vector bv_node_breaks;
sdsl::bit_vector::rank_1_type rs_node_breaks;
sdsl::bit_vector::select_1_type ss_node_breaks;
public:
/* ==================== LIFECYCLE ======================================= */
Path( const graph_type* g )
: graph_ptr( g ), left( 0 ), right( 0 ), seqlen( 0 ), initialized( false )
{ }
/**
* XXX NOTE: Be careful of assigning `left` and `right` offset. The zero value
* means all sequence of first node or last one is included in the
* path. Any value < len(node) indicates the lenght of the suffix or
* the prefix of the sequence of first or last node respectively.
* They are NOT sequence offsets of the first or last node.
*/
Path( const graph_type* g, nodes_type p, offset_type l=0, offset_type r=0 )
: Path( g )
{
this->set_nodes( std::move( p ), l, r );
}
Path( const Path& other )
{
this->graph_ptr = other.graph_ptr;
this->nodes = other.nodes;
this->left = other.left;
this->right = other.right;
this->seqlen = other.seqlen;
this->seq = other.seq;
this->initialized = other.initialized;
this->bv_node_breaks = other.bv_node_breaks;
sdsl::util::init_support( this->rs_node_breaks, &this->bv_node_breaks );
sdsl::util::init_support( this->ss_node_breaks, &this->bv_node_breaks );
}
Path( Path&& other )
{
this->graph_ptr = other.graph_ptr;
this->nodes = std::move( other.nodes );
this->left = other.left;
this->right = other.right;
this->seqlen = other.seqlen;
this->seq = std::move( other.seq );
this->initialized = other.initialized;
this->bv_node_breaks.swap( other.bv_node_breaks );
sdsl::util::init_support( this->rs_node_breaks, &this->bv_node_breaks );
sdsl::util::init_support( this->ss_node_breaks, &this->bv_node_breaks );
// Free up memory first of `other`.
// :TODO:Sun Oct 21 23:33:\@cartoonist: Clear does not free up memory!
sdsl::util::clear( other.rs_node_breaks );
sdsl::util::clear( other.ss_node_breaks );
}
Path& operator=( const Path& other )
{
this->graph_ptr = other.graph_ptr;
this->nodes = other.nodes;
this->left = other.left;
this->right = other.right;
this->seqlen = other.seqlen;
this->seq = other.seq;
this->initialized = other.initialized;
this->bv_node_breaks = other.bv_node_breaks;
sdsl::util::init_support( this->rs_node_breaks, &this->bv_node_breaks );
sdsl::util::init_support( this->ss_node_breaks, &this->bv_node_breaks );
return *this;
}
Path& operator=( Path&& other )
{
this->graph_ptr = other.graph_ptr;
this->nodes = std::move( other.nodes );
this->left = other.left;
this->right = other.right;
this->seqlen = other.seqlen;
this->seq = std::move( other.seq );
this->initialized = other.initialized;
// Free up memory of `this` first.
sdsl::util::clear( this->bv_node_breaks );
sdsl::util::clear( this->rs_node_breaks );
sdsl::util::clear( this->ss_node_breaks );
this->bv_node_breaks.swap( other.bv_node_breaks );
sdsl::util::init_support( this->rs_node_breaks, &this->bv_node_breaks );
sdsl::util::init_support( this->ss_node_breaks, &this->bv_node_breaks );
// Free up memory first of `other`.
sdsl::util::clear( other.rs_node_breaks );
sdsl::util::clear( other.ss_node_breaks );
return *this;
}
~Path() = default;
/* ==================== OPERATORS ======================================= */
template< typename TSpec2 >
inline Path& operator=( Path< graph_type, TSpec2 >&& other );
template< typename TSpec2 >
inline Path& operator=( const Path< graph_type, TSpec2 >& other );
/* ==================== ACCESSORS ======================================= */
/**
* @brief getter function for graph_ptr.
*/
inline const graph_type*
get_graph_ptr( ) const
{
return this->graph_ptr;
}
/**
* @brief getter function for nodes.
*/
inline const nodes_type&
get_nodes( ) const
{
return this->nodes;
}
/**
* @brief get the node offset of the head node (front node).
*/
inline offset_type
get_head_offset( ) const
{
if ( this->left == 0 ) return 0;
assert( !this->empty() ); /* Left offset of an empty path should be always 0 */
return this->graph_ptr->node_length( this->front() ) - this->left;
}
/**
* @brief getter function for seqlen.
*/
inline seqsize_type
get_sequence_len( ) const
{
return this->seqlen;
}
/**
* @brief get left offset value.
*/
inline offset_type
get_left_len( ) const
{
assert( !this->empty() );
return this->left ? this->left : this->graph_ptr->node_length( this->front() );
}
/**
* @brief get right offset value.
*/
inline offset_type
get_right_len( ) const
{
assert( !this->empty() );
return this->right ? this->right : this->graph_ptr->node_length( this->back() );
}
/**
* @brief get the sequence length of the head node (front node).
*/
inline seqsize_type
get_seqlen_head( ) const
{
if ( this->empty() ) return 0;
if ( this->size() == 1 ) return this->seqlen;
return this->get_left_len();
}
/**
* @brief get the sequence length of the tail node (back node).
*/
inline seqsize_type
get_seqlen_tail( ) const
{
if ( this->empty() ) return 0;
if ( this->size() == 1 ) return this->seqlen;
return this->get_right_len();
}
/**
* @brief getter function for seq.
*
* @note The sequence is constructed on demand by calling this function.
*/
inline const string_type&
get_sequence( )
{
if ( this->seq.empty() ) this->seq = sequence( *this );
return this->seq;
}
/**
* @brief Is path initialized?
*
* @return `true` if the path is initialized; `false` otherwise.
*
* Initialization constructs node breaks bit vector, rank, and select supports.
*/
inline bool
is_initialized( ) const
{
return this->initialized;
}
inline value_type
operator[]( size_t idx ) const
{
return this->get_nodes()[ idx ];
}
inline value_type
at( size_t idx ) const
{
return this->get_nodes().at( idx );
}
inline size_type
size( ) const
{
return this->get_nodes().size();
}
inline bool
empty( ) const
{
return this->size() == 0;
}
inline const_iterator
begin( ) const
{
return this->get_nodes().begin();
}
inline const_iterator
end( ) const
{
return this->get_nodes().end();
}
inline value_type
front( ) const
{
return *this->begin();
}
inline value_type
back( ) const
{
return *( this->end() - 1 );
}
/* ==================== MUTATORS ======================================= */
/**
* @brief setter function for graph_ptr.
*/
inline void
set_graph_ptr( const graph_type* value )
{
this->graph_ptr = value;
}
inline void
set_left_by_len( offset_type value )
{
if ( this->empty() ) {
throw std::runtime_error( "Cannot set offset for an empty path" );
}
offset_type front_len = this->graph_ptr->node_length( this->front() );
if ( value > front_len || value == 0 ) value = front_len;
if ( this->size() == 1 && front_len - value >= this->get_right_len() ) {
throw std::runtime_error( "left exceeds right on the one-node path" );
}
std::ptrdiff_t diff = value - this->get_left_len();
if ( diff == 0 ) return;
this->seqlen += diff;
if ( !this->seq.empty() ) {
if ( diff < 0 ) {
this->seq.erase( 0, -diff );
}
else {
auto nstr = this->graph_ptr->node_sequence( this->front() );
this->seq.insert( 0, nstr.substr( front_len - value, diff ) );
}
}
this->left = ( value == front_len ) ? 0 : value;
this->initialized = false;
}
inline void
set_right_by_len( offset_type value )
{
if ( this->empty() ) {
throw std::runtime_error( "Cannot set offset for an empty path" );
}
offset_type back_len = this->graph_ptr->node_length( this->back() );
if ( value > back_len || value == 0 ) value = back_len;
if ( this->size() == 1 && value <= this->get_head_offset() ) {
throw std::runtime_error( "right exceeds left on the one-node path" );
}
std::ptrdiff_t diff = value - this->get_right_len();
if ( diff == 0 ) return;
this->seqlen += diff;
if ( !this->seq.empty() ) {
if ( diff < 0 ) {
this->seq.resize( this->seqlen );
}
else {
auto nstr = this->graph_ptr->node_sequence( this->back() );
this->seq += nstr.substr( this->right, diff ); /**< @brief `right` is always non-zero here */
}
}
this->right = ( value == back_len ) ? 0 : value;
this->initialized = false;
}
inline void
set_nodes( nodes_type value, offset_type l=0, offset_type r=0 );
template< typename TIter >
inline void
set_nodes( TIter begin, TIter end, offset_type l=0, offset_type r=0 )
{
nodes_type nd( end - begin );
std::copy( begin, end, nd.begin() );
this->set_nodes( std::move( nd ), l, r );
}
/* ==================== METHODS ======================================= */
/**
* @brief Initialize data structures for efficient rank and select queries.
*
* @param path The path.
*
* It constructs node breaks bit vector and corresponding rank and select supports.
*/
inline void
initialize( )
{
if ( this->is_initialized() || this->size() == 0 ) return;
assert( this->graph_ptr != nullptr );
this->init_bv_node_breaks();
sdsl::util::init_support( this->rs_node_breaks, &this->bv_node_breaks );
sdsl::util::init_support( this->ss_node_breaks, &this->bv_node_breaks );
this->initialized = true;
}
inline void
push_back( value_type const& nid )
{
assert( this->graph_ptr != nullptr );
if ( this->right != 0 ) this->set_right_by_len( 0 );
this->nodes.push_back( nid );
this->seqlen += this->graph_ptr->node_length( nid );
if ( !this->seq.empty() ) {
this->seq += this->graph_ptr->node_sequence( nid );
}
this->initialized = false;
}
/**
* @brief Append a new node to the back of the path.
*
* @param nid Node ID.
* @param noff Node offset.
*
* XXX NOTE: When appending the first node `noff` indicates the first locus
* should be included in the path. So, `noff == 0` will append all the node
* sequence to the path (i.e. `left == 0`). However, for further appending
* `noff` points to "one locus after" the locus need to be appended. In this
* case, `noff == 0` or `noff == len` will also append the whole node to the
* path (i.e. `right == 0`); where `len` is the sequence length of node `nid`.
*/
inline void
push_back( value_type const& nid, offset_type noff )
{
assert( this->graph_ptr != nullptr );
bool first = this->empty();
offset_type nlen = this->graph_ptr->node_length( nid );
if ( noff < 0 ) noff = 0;
this->initialized = false;
if ( first ) {
if ( noff >= nlen ) noff = nlen - 1;
this->nodes.push_back( nid );
this->seqlen += nlen - noff;
this->left = noff ? seqlen : 0;
assert( this->seq.empty() );
}
else {
if ( this->right != 0 ) this->set_right_by_len( 0 );
if ( noff > nlen || noff == 0 ) noff = nlen;
this->nodes.push_back( nid );
this->seqlen += noff;
this->right = ( noff == nlen ) ? 0 : noff;
if ( !this->seq.empty() ) {
this->seq += this->graph_ptr->node_sequence( nid ).substr( 0, noff );
}
}
}
inline void
pop_back( );
inline void
pop_front( );
inline void
clear( )
{
psi::clear( this->nodes );
this->left = 0;
this->right = 0;
this->seqlen = 0;
this->seq.clear();
sdsl::util::clear( this->bv_node_breaks );
sdsl::util::clear( this->rs_node_breaks );
sdsl::util::clear( this->ss_node_breaks );
this->initialized = false;
}
inline void
reserve( size_type size )
{
psi::reserve( this->nodes, size ); /* defined in `utils.h` */
}
inline void
serialize( std::ostream& out ) const
{
ASSERT( this->is_initialized() ); // Path must be initialized to be serialized
nodes_type cnodes = this->nodes_in_coordinate();
psi::serialize( out, cnodes );
psi::serialize( out, static_cast< uint64_t >( this->left ) );
psi::serialize( out, static_cast< uint64_t >( this->right ) );
this->bv_node_breaks.serialize( out );
}
inline void
serialize( std::ostream& out )
{
this->initialize();
const Path* const_this = this;
const_this->serialize( out );
}
inline void
load( std::istream& in )
{
nodes_type tmp;
offset_type l, r;
uint64_t offset;
deserialize( in, tmp );
deserialize( in, offset );
l = offset;
deserialize( in, offset );
r = offset;
this->drop_coordinate( tmp );
this->set_nodes( std::move( tmp ), l, r );
this->bv_node_breaks.load( in );
sdsl::util::init_support( this->rs_node_breaks, &this->bv_node_breaks );
sdsl::util::init_support( this->ss_node_breaks, &this->bv_node_breaks );
this->initialized = true;
}
/**
* @brief Get the node rank (0-based) in the path by a position in its sequence.
*
* @param pos The position in the path (0-based).
* @return The node rank in the nodes queue (0-based) on whose label the position
* `pos` in the path sequence relies.
*
* The value of `rank(pos)` is the node rank in the path's nodes queue.
*/
inline size_type
rank( seqsize_type pos ) const
{
assert( this->is_initialized() );
if ( pos < 0 || pos >= this->seqlen ) {
throw std::runtime_error( "Position out of range." );
}
return this->rs_node_breaks( pos );
}
/**
* @brief Get the position in the sequence from which the node with rank `rank` starts.
*
* @param path The path.
* @return The position in the path sequence from which the node with rank `rank`
* starts.
*
* Since the position corresponding to the last base in the node label is set in the
* bit vector, the value of `select(rank)` is one base before the actual position to
* be returned. So, `select(rank) + 1` would be the desired position.
*/
inline seqsize_type
select( size_type rank ) const
{
assert( this->is_initialized() );
if ( rank < 0 || rank >= this->size() ) {
throw std::runtime_error( "Rank out of range." );
}
if ( rank == 0 ) return 0;
return this->ss_node_breaks( rank ) + 1;
}
inline bool
contains( value_type nid ) const
{
if ( std::find( this->begin(), this->end(), nid ) != this->end() ) return true;
return false;
}
/* ==================== FRIENDSHIPS ======================================= */
friend class Path< graph_type, Default >;
friend class Path< graph_type, Dynamic >;
friend class Path< graph_type, Compact >;
friend class Path< graph_type, Haplotype >;
private:
/**
* @brief Initialize node breaks bitvector.
*
* @param path The path.
*
* The node breaks bit vector is a bit vector of sequence length. A bit at position
* `i` is set if a node ends at that position in the sequence. For example for this
* path:
*
* (GCAAT) -> (A) -> (TTAGCC) -> (GCA)
*
* the corresponding path is:
*
* GCAATATTAGCCGCA
*
* and its bit vector is:
*
* 000011000001001
*
* which has a set bit at the first position of each node in the path.
*/
inline void
init_bv_node_breaks( )
{
assert( this->size() != 0 );
sdsl::util::assign( this->bv_node_breaks, sdsl::bit_vector( this->seqlen, 0 ) );
seqsize_type cursor = this->get_seqlen_head();
this->bv_node_breaks[ cursor - 1 ] = 1;
if ( this->size() > 1 ) {
for ( auto it = this->begin()+1; it != this->end()-1; ++it ) {
cursor += this->graph_ptr->node_length( *it );
this->bv_node_breaks[ cursor - 1 ] = 1;
}
cursor += this->get_seqlen_tail();
this->bv_node_breaks[ cursor - 1 ] = 1;
}
}
inline void
drop_coordinate( mutable_nodes_type& path_nodes )
{
std::transform( path_nodes.begin(), path_nodes.end(), path_nodes.begin(),
[this]( value_type id ) -> value_type {
return this->graph_ptr->id_by_coordinate( id );
} );
}
template< typename TNodes >
inline void
drop_coordinate( TNodes& path_nodes )
{
mutable_nodes_type tmp( path_nodes.size() );
std::transform( path_nodes.begin(), path_nodes.end(), tmp.begin(),
[this]( value_type id ) -> value_type {
return this->graph_ptr->id_by_coordinate( id );
} );
sdsl::util::assign( path_nodes, tmp );
}
inline mutable_nodes_type
nodes_in_coordinate( ) const
{
mutable_nodes_type cnodes( this->nodes.size() );
std::transform( this->nodes.begin(), this->nodes.end(), cnodes.begin(),
[this]( value_type id ) -> value_type {
return this->graph_ptr->coordinate_id( id );
} );
return cnodes;
}
}; /* --- end of template class Path --- */
/* Path member functions ---------------------------------------------------- */
/**
* @brief Move assignment from other type of path.
*
* @param other The other path.
* @return The reference to this instance after move.
*/
template< typename TGraph, typename TSpec1 >
template< typename TSpec2 >
inline Path< TGraph, TSpec1 >&
Path< TGraph, TSpec1 >::operator=( Path< TGraph, TSpec2 >&& other )
{
using namespace sdsl::util;
this->graph_ptr = other.graph_ptr;
assign( this->nodes, other.nodes );
psi::clear( other.nodes );
this->left = other.left;
this->right = other.right;
this->seqlen = other.seqlen;
this->seq = std::move( other.seq );
this->initialized = other.initialized;
sdsl::util::clear( this->bv_node_breaks );
this->bv_node_breaks.swap( other.bv_node_breaks );
init_support( this->rs_node_breaks, &this->bv_node_breaks );
init_support( this->ss_node_breaks, &this->bv_node_breaks );
sdsl::util::clear( other.rs_node_breaks );
sdsl::util::clear( other.ss_node_breaks );
return *this;
}
/**
* @brief Assign a path with another type of path.
*
* @param other The Dynamic path.
* @return The reference to this instance after assignment.
*/
template< typename TGraph, typename TSpec1 >
template< typename TSpec2 >
inline Path< TGraph, TSpec1 >&
Path< TGraph, TSpec1 >::operator=( const Path< TGraph, TSpec2 >& other )
{
using namespace sdsl::util;
this->graph_ptr = other.graph_ptr;
assign( this->nodes, other.nodes );
this->left = other.left;
this->right = other.right;
this->seqlen = other.seqlen;
this->seq = other.seq;
this->initialized = other.initialized;
this->bv_node_breaks = other.bv_node_breaks;
init_support( this->rs_node_breaks, &this->bv_node_breaks );
init_support( this->ss_node_breaks, &this->bv_node_breaks );
return *this;
}
/**
* @brief setter function for nodes.
*/
template< typename TGraph, typename TSpec >
inline void
Path< TGraph, TSpec >::set_nodes( nodes_type value, offset_type l, offset_type r )
{
this->clear();
if ( value.empty() ) return;
assert( this->graph_ptr != nullptr );
this->nodes = std::move( value );
for ( auto n : this->nodes ) this->seqlen += this->graph_ptr->node_length( n );
this->set_left_by_len( l );
this->set_right_by_len( r );
}
template< typename TGraph, typename TSpec >
inline void
Path< TGraph, TSpec >::pop_back( )
{
assert( this->graph_ptr != nullptr );
if ( this->empty() ) return;
this->seqlen -= this->get_seqlen_tail();
this->nodes.pop_back();
this->initialized = false;
if ( !this->seq.empty() ) this->seq.resize( this->seqlen );
this->right = 0;
if ( this->empty() ) this->left = 0;
}
template< typename TGraph, typename TSpec >
inline void
Path< TGraph, TSpec >::pop_front( )
{
assert( this->graph_ptr != nullptr );
if ( this->nodes.empty() ) return;
offset_type diff = this->get_seqlen_head();
this->seqlen -= diff;
this->nodes.pop_front();
this->initialized = false;
if ( !this->seq.empty() ) this->seq = this->seq.substr( diff );
this->left = 0;
if ( this->empty() ) this->right = 0;
}
template< typename TPathSpec >
class is_generic_path : public std::true_type {};
/* END OF Path member functions --------------------------------------------- */
/**
* @brief Path template class Micro specialization.
*
* Represent a path in the variation graph with efficient node ID query.
*/
template< typename TGraph >
class Path< TGraph, Micro >
{
public:
/* ==================== TYPEDEFS ======================================= */
typedef TGraph graph_type;
typedef Micro spec_type;
typedef typename graph_type::id_type value_type;
typedef std::set< value_type > nodes_set_type;
typedef typename nodes_set_type::size_type size_type;
typedef typename nodes_set_type::difference_type difference_type;
typedef typename nodes_set_type::const_iterator const_iterator;
/* ==================== LIFECYCLE ======================================= */
Path( ) = default;
Path( const std::vector< value_type >& p )
{
this->set_nodes( p );
}
template< typename TSpec >
Path( const Path< graph_type, TSpec >& other )
{
this->set_nodes( other.get_nodes() );
}
template< typename TSpec >
Path& operator=( const Path< graph_type, TSpec >& other )
{
this->set_nodes( other.get_nodes() );
}
Path( const Path& ) = default;
Path( Path&& ) = default;
Path& operator=( const Path& ) = default;
Path& operator=( Path&& ) = default;
~Path() = default;
/* ==================== ACCESSORS ======================================= */
/**
* @brief getter function for nodes_set.
*/
inline const nodes_set_type&
get_nodes_set( ) const
{
return this->nodes_set;
}
inline size_type
size( ) const
{
return this->nodes_set.size();
}
inline bool
empty( ) const
{
return this->size() == 0;
}
inline const_iterator
begin( ) const
{
return nodes_set.begin();
}
inline const_iterator
end( ) const
{
return nodes_set.end();
}
/* ==================== MUTATORS ======================================= */
/**
* @brief Set the nodes in the path (clear the previous state).
*/
inline void
set_nodes( const std::vector< value_type >& value )
{
this->clear( );
psi::reserve( this->nodes_set, value.size() );
std::copy( value.begin(), value.end(),
std::inserter( this->nodes_set, this->nodes_set.end() ) );
}
/* ==================== METHODS ======================================= */
inline void
push_back( value_type const& node_id )
{
this->nodes_set.insert( node_id );
}
inline void
clear( )
{
this->nodes_set.clear();
}
inline void
reserve( size_type size )
{
psi::reserve( this->nodes_set, size );
}
inline void
serialize( std::ostream& out ) const
{
psi::serialize( out, this->nodes_set, this->nodes_set.begin(), this->nodes_set.end() );
}
inline void
load( std::istream& in )
{
deserialize( in, this->nodes_set, std::inserter( this->nodes_set, this->nodes_set.end() ) );
}
inline bool
contains( value_type nid ) const
{
return this->nodes_set.find( nid ) != this->nodes_set.end();
}
private:
/* ==================== DATA MEMBERS ======================================= */
nodes_set_type nodes_set;
}; /* --- end of specialized template class Path --- */
template< >
class is_generic_path< Micro > : public std::false_type {};
/**
* @brief Path specialized template class for representing a Haplotype in DAG graphs.
*
* NOTE: Apart from assuming that the underlying variation graph is DAG, it assumes
* that the node ranks are a topological sort of nodes.
*/
template< typename TGraph >
class Path< TGraph, Haplotype > {
private:
/* ==================== TYPEDEFS ======================================= */
typedef PathTraits< TGraph, Haplotype > TTraits;
public:
/* ==================== TYPEDEFS ======================================= */
typedef TGraph graph_type;
typedef Haplotype spec_type;
typedef typename TTraits::TNodeSequence nodes_type;
typedef typename graph_type::id_type value_type;
typedef typename nodes_type::size_type size_type;
typedef ptrdiff_t difference_type;
typedef sdsl::random_access_const_iterator< Path > const_iterator;
private:
/* ==================== DATA MEMBERS ======================================= */
const graph_type* graph_ptr;
nodes_type nodes;
typename graph_type::rank_type last_node_rank;
bool initialized;
typename nodes_type::rank_1_type rs_nodes;
typename nodes_type::select_1_type ss_nodes;
public:
/* ==================== LIFECYCLE ======================================= */
Path( const graph_type* g ) :
graph_ptr( g ),
nodes( g->get_node_count(), 0 ),
last_node_rank( 0 ),
initialized( false )
{ }
template< typename TContainer >
Path( const graph_type* g, const TContainer& node_ids )
: Path( g )
{
this->set_nodes( node_ids );
}
Path( const Path& other )
{
this->graph_ptr = other.graph_ptr;
this->nodes = other.nodes;
this->last_node_rank = other.last_node_rank;
this->initialize();
}
Path( Path&& other )
{
this->graph_ptr = other.graph_ptr;
this->nodes = std::move( other.nodes );
this->last_node_rank = other.last_node_rank;
this->initialize();
sdsl::util::clear( other.rs_nodes );
sdsl::util::clear( other.ss_nodes );
}
Path&
operator=( const Path& other )
{
this->graph_ptr = other.graph_ptr;
this->nodes = other.nodes;
this->last_node_rank = other.last_node_rank;
this->initialize();
return *this;
}
Path&
operator=( Path&& other )
{
this->graph_ptr = other.graph_ptr;
this->nodes = std::move( other.nodes );
this->last_node_rank = other.last_node_rank;
this->initialize();
sdsl::util::clear( other.rs_nodes );
sdsl::util::clear( other.ss_nodes );
return *this;
}
~Path() = default;
/* ==================== OPERATORS ======================================= */
template< typename TSpec2 >
inline Path&
operator=( const Path< graph_type, TSpec2 >& other )
{
this->graph_ptr = other.graph_ptr;
this->set_nodes( other.nodes );
return *this;
}
/* ==================== ACCESSORS ======================================= */
/**
* @brief getter function for graph_ptr.
*/
inline const graph_type*
get_graph_ptr( ) const
{
return this->graph_ptr;
}
/**
* @brief getter function for nodes.
*/
inline const Path&
get_nodes( ) const
{
return *this;
}
/**
* @brief Is path initialized?
*
* @return `true` if the path is initialized; `false` otherwise.
*
* This function initializes nodes rank and select support data structures.
*/
inline bool
is_initialized( ) const
{
return this->initialized;
}
inline value_type
operator[]( size_t idx ) const
{
assert( this->is_initialized() );
return this->graph_ptr->rank_to_id( this->ss_nodes( idx + 1 ) + 1 );
}
inline value_type
at( size_t idx ) const
{
if ( ! this->is_initialized() )
throw std::runtime_error( "Path must be initialized to be operational" );
if ( idx < 0 || idx >= this->size() )
throw std::runtime_error( "Index out of range" );
return (*this)[ idx ];
}
inline size_type
size( ) const
{
assert( this->is_initialized() );
return this->rs_nodes( this->nodes.size() );
}
inline bool
empty( ) const
{
return this->size() == 0;
}
inline const_iterator
begin( ) const
{
return const_iterator( this, 0 );
}
inline const_iterator
end( ) const
{
return const_iterator( this, this->size() );
}
inline value_type
front( ) const
{
return *this->begin();
}
inline value_type
back( ) const
{
return *( this->end() - 1 );
}
/* ==================== MUTATORS ======================================= */
/**
* @brief setter function for graph_ptr.
*/
inline void
set_graph_ptr( const graph_type* value )
{
this->graph_ptr = value;
}
template< typename TIter >
inline void
set_nodes( TIter begin, TIter end )
{
this->clear();
for ( ; begin != end; ++begin ) this->push_back( *begin );
this->initialize();
}
template< typename TContainer >
inline void
set_nodes( const TContainer& node_ids )
{
this->set_nodes( node_ids.begin(), node_ids.end() );
}
/* ==================== METHODS ======================================= */
inline void
push_back( value_type const& nid )
{
assert( this->graph_ptr != nullptr );
auto nrank = this->graph_ptr->id_to_rank( nid );
if ( nrank <= this->last_node_rank )
throw std::runtime_error( "Path IDs sequence must be non-decreasing" );
this->nodes[ nrank - 1 ] = 1;
this->initialized = false;
this->last_node_rank = nrank;
}
/**
* @brief Remove the last node from the path.
*
* XXX: This method requires re-initialization of the path which is costly.
*/
inline void
pop_back( )
{
if ( this->empty() ) return;
if ( this->size() == 1 ) this->last_node_rank = 0;
else this->last_node_rank = this->ss_nodes( this->size() - 1 ) + 1;
this->nodes[ this->ss_nodes( this->size() ) ] = 0;
this->initialize();
}
/**
* @brief Remove the first node from the path.
*
* XXX: This method requires re-initialization of the path which is costly.
*/
inline void
pop_front( )
{
if ( this->empty() ) return;
if ( this->size() == 1 ) this->last_node_rank = 0;
this->nodes[ this->ss_nodes( 1 ) ] = 0;
this->initialize();
}
/**
* @brief Initialize data structures for efficient rank and select queries.
*
* @param path The path.
*
* It initializes the rank and select supports for nodes bit vector.
*
* @overload for Haplotype paths.
*/
inline void
initialize( )
{
sdsl::util::init_support( this->rs_nodes, &this->nodes );
sdsl::util::init_support( this->ss_nodes, &this->nodes );
this->initialized = true;
}
inline void
serialize( std::ostream& out ) const
{
this->nodes.serialize( out );
}
inline void
load( std::istream& in )
{
this->nodes.load( in );
this->initialize();
this->last_node_rank = this->ss_nodes( this->size() ) + 1;
}
inline void
clear( )
{
sdsl::util::assign( this->nodes,
sdsl::bit_vector( this->graph_ptr->get_node_count(), 0 ) );
this->initialize();
this->last_node_rank = 0;
}
inline bool
contains( value_type nid ) const
{
if ( ! this->graph_ptr->has_node( nid ) ) return false;
auto nrank = this->graph_ptr->id_to_rank( nid );
return this->contains_by_rank( nrank );
}
template< typename TIter >
inline bool
contains( TIter begin, TIter end ) const
{
if ( begin == end ||
!this->graph_ptr->has_node( *begin ) ||
!this->graph_ptr->has_node( *( end - 1 ) ) ) return false;
auto brank = this->graph_ptr->id_to_rank( *begin );
auto erank = this->graph_ptr->id_to_rank( *( end - 1 ) );
if ( erank < brank || brank == 0 || erank == 0 ) return false;
long int plen = this->rs_nodes( erank ) - this->rs_nodes( brank - 1 );
long int qlen = end - begin;
if ( plen != qlen || plen < 0 ) return false;
typename graph_type::rank_type prev = 0;
for ( ; begin != end; ++begin ) {
auto curr = this->graph_ptr->id_to_rank( *begin );
if ( curr <= prev || !this->contains_by_rank( curr ) ) return false;
prev = curr;
}
return true;
}
template< typename TIter >
inline bool
rcontains( TIter rbegin, TIter rend ) const
{
if ( rbegin == rend ||
!this->graph_ptr->has_node( *rbegin ) ||
!this->graph_ptr->has_node( *( rend - 1 ) ) ) return false;
auto rbrank = this->graph_ptr->id_to_rank( *rbegin );
auto rerank = this->graph_ptr->id_to_rank( *( rend - 1 ) );
if ( rbrank < rerank || rbrank == 0 || rerank == 0 ) return false;
long int plen = this->rs_nodes( rbrank ) - this->rs_nodes( rerank - 1 );
long int qlen = rend - rbegin;
if ( plen != qlen || plen < 0 ) return false;
auto prev = this->graph_ptr->id_to_rank( *rbegin ) + 1;
for ( ; rbegin != rend; ++rbegin ) {
auto curr = this->graph_ptr->id_to_rank( *rbegin );
if ( curr >= prev || !this->contains_by_rank( curr ) ) return false;
prev = curr;
}
return true;
}
private:
inline bool
contains_by_rank( typename graph_type::rank_type rank ) const
{
if ( rank == 0 ) return false;
return this->nodes[ rank - 1 ] == 1;
}
}; /* --- end of specialized template class Path --- */
template< >
class is_generic_path< Haplotype > : public std::false_type {};
} /* --- end of namespace psi --- */
#endif /* --- #ifndef PSI_PATH_BASE_HPP__ --- */
| 33.197877 | 108 | 0.510345 | [
"vector",
"transform"
] |
6353e4bd8859d7bc81c1a667989ecd0e6374ba3d | 5,823 | cpp | C++ | src/app/core/log.cpp | botorabi/Meet4Eat-Desktop | a3f27df5ab4b4697fcb5682900f48716b2021869 | [
"MIT"
] | 1 | 2018-03-20T08:21:34.000Z | 2018-03-20T08:21:34.000Z | src/app/core/log.cpp | botorabi/Meet4Eat-Desktop | a3f27df5ab4b4697fcb5682900f48716b2021869 | [
"MIT"
] | 2 | 2018-03-15T10:13:59.000Z | 2018-03-15T10:20:15.000Z | src/app/core/log.cpp | botorabi/Meet4Eat-Desktop | a3f27df5ab4b4697fcb5682900f48716b2021869 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2017 by Botorabi. All rights reserved.
* https://github.com/botorabi/Meet4Eat
*
* License: MIT License (MIT), read the LICENSE text in
* main directory for more details.
*/
/*
General purpose log system
This code is basing on the open-source project yag2002.sf.net
*/
#include "log.h"
#include "utils.h"
#include <cassert>
#include <fstream>
namespace m4e
{
namespace core
{
//! This is the default system log instance
Log defaultlog;
//! Implementation of logging system
Log::Log() :
std::basic_ostream< char >( &_stream ),
_severity( L_DEBUG ),
_printSeverityLevel( true ),
_enableTimeStamp( true )
{
_stream.setLog( this );
}
Log::~Log()
{
reset();
}
bool Log::addSink( const std::string& sinkname, const std::string& filename, unsigned int loglevel )
{
if( loglevel > L_INFO || loglevel < L_VERBOSE )
{
log_error << "invalid log level for given sink '" << sinkname << "'" << std::endl;
return false;
}
// check if there is already a sink with requested sink name
std::vector< Sink* >::iterator p_sink = _sinks.begin(), p_sinkEnd = _sinks.end();
for ( ; p_sink != p_sinkEnd; ++p_sink )
{
if ( ( *p_sink )->_name == sinkname )
{
log_warning << "sink name '" << sinkname << "' already exists!" << std::endl;
return false;
}
}
std::fstream* p_stream = new std::fstream;
p_stream->open( filename.c_str(), std::ios_base::binary | std::ios_base::out );
if ( !*p_stream )
{
delete p_stream;
log_error << "cannot open log file '" << filename << "' for sink '" << sinkname << "'" << std::endl;
return false;
}
else
{
Sink* p_s = new Sink( sinkname, p_stream, loglevel );
_sinks.push_back( p_s );
}
return true;
}
bool Log::addSink( const std::string& sinkname, std::ostream& sink, unsigned int loglevel )
{
if( loglevel > L_INFO || loglevel < L_VERBOSE )
{
log_error << "invalid log level for given sink '" << sinkname << "'" << std::endl;
return false;
}
// check if there is already a sink with requested sink name
std::vector< Sink* >::iterator p_beg = _sinks.begin(), p_end = _sinks.end();
for ( ; p_beg != p_end; ++p_beg )
{
if ( ( *p_beg )->_name == sinkname )
{
log_warning << "sink name '" << sinkname << "' already exists!" << std::endl;
return false;
}
}
Sink* p_sink = new Sink( sinkname, &sink, loglevel, true );
_sinks.push_back( p_sink );
return true;
}
void Log::removeSink( const std::string& sinkname )
{
std::vector< Sink* >::iterator p_sink = _sinks.begin(), p_sinkEnd = _sinks.end();
for ( ; p_sink != p_sinkEnd; ++p_sink )
{
if ( ( *p_sink )->_name == sinkname )
{
delete *p_sink;
_sinks.erase( p_sink );
return;
}
}
assert( false && "sink name does not exist!" );
}
void Log::setSeverity( unsigned int severity )
{
_severity = severity;
}
void Log::enableSeverityLevelPrinting( bool en )
{
_printSeverityLevel = en;
}
void Log::enableTimeStamp( bool en )
{
_enableTimeStamp = en;
}
void Log::reset()
{
// delete all allocated streams, except the std streams
std::vector< Sink* >::iterator p_sink = _sinks.begin(), p_sinkEnd = _sinks.end();
for ( ; p_sink != p_sinkEnd; ++p_sink )
delete *p_sink;
_sinks.clear();
}
void Log::out( const std::string& msg )
{
std::vector< Sink* >::iterator p_sink = _sinks.begin(), p_sinkEnd = _sinks.end();
for ( ; p_sink != p_sinkEnd; ++p_sink )
{
if ( ( *p_sink )->_logLevel <= _severity )
{
*( ( *p_sink )->_p_stream ) << msg;
( ( *p_sink )->_p_stream )->flush();
}
}
}
//---------------------------
Log::LogStreamBuf::LogStreamBuf() :
std::basic_streambuf< char >(),
_p_log ( NULL )
{
}
Log::LogStreamBuf::~LogStreamBuf()
{
}
void Log::LogStreamBuf::setLog( Log *p_log )
{
_p_log = p_log;
}
std::basic_ios< char >::int_type Log::LogStreamBuf::overflow( int_type c )
{
if( !std::char_traits< char >::eq_int_type( c, std::char_traits< char >::eof() ) )
{
_msg += static_cast< char >( c );
if( c == '\n' )
{
std::string severity;
if ( _p_log->_printSeverityLevel )
{
switch ( _p_log->_severity )
{
case L_INFO:
severity = "[info] ";
break;
case L_DEBUG:
severity = "[debug] ";
break;
case L_WARNING:
severity = "[warning] ";
break;
case L_ERROR:
severity = "[error] ";
break;
case L_VERBOSE:
severity = "[verbose] ";
break;
default:
assert( false && "unknown log severity" );
}
}
// add a carriage return to end of line
_msg[ _msg.length() - 1 ] = '\r';
_msg += "\n";
if ( _p_log->_enableTimeStamp )
_p_log->out( "[" + getFormatedTime() + "] " + severity + _msg );
else
_p_log->out( severity + _msg );
_msg = "";
}
}
return std::char_traits< char >::not_eof( c );
}
std::ostream& Log::operator << ( const Log::LogLevel& ll )
{
setSeverity( ll._level );
return *this;
}
} // namespace core
} // namespace m4e
std::ostream& operator << ( std::ostream& stream, const QString& msg )
{
stream << msg.toStdString();
return stream;
}
| 24.56962 | 108 | 0.531685 | [
"vector"
] |
63581ac3ceb058b9fb072f639369a22be96f7302 | 571 | hpp | C++ | include/utils.hpp | PurplePachyderm/tensorslow | 3ccd881700b301b81154a5b1a787ec91461a6436 | [
"Unlicense"
] | 2 | 2020-10-19T08:57:25.000Z | 2020-10-26T17:50:50.000Z | include/utils.hpp | PurplePachyderm/tensorslow | 3ccd881700b301b81154a5b1a787ec91461a6436 | [
"Unlicense"
] | 5 | 2020-10-23T14:50:07.000Z | 2020-11-26T12:28:11.000Z | include/utils.hpp | PurplePachyderm/tensorslow | 3ccd881700b301b81154a5b1a787ec91461a6436 | [
"Unlicense"
] | 2 | 2020-10-26T17:49:04.000Z | 2021-08-31T00:51:09.000Z | /*
* Misc utility functions to be reused in main parts of the library
* NOTE For now, this has only been created to avoid double definition of split
*/
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#define BARWIDTH 30
namespace ts {
std::vector<std::string> split(std::string str, char delimeter);
std::string serializeUnsignedVec2D(
std::vector<std::vector<unsigned>> &vec2d
);
std::vector<std::vector<unsigned>> parseUnsignedVec2D(
std::ifstream &in
);
void progressBar(unsigned current, unsigned max);
}
| 21.148148 | 78 | 0.7338 | [
"vector"
] |
6360bd98e4d0dc37f94314d39ef7bb97c85cd14c | 1,308 | cpp | C++ | src/ex4_delete_def/main.cpp | pumpkin-code/dsba-ads-lect8 | 237c0c2624fc0fa2606bbd8389d674bf4bf51ae4 | [
"BSD-3-Clause"
] | null | null | null | src/ex4_delete_def/main.cpp | pumpkin-code/dsba-ads-lect8 | 237c0c2624fc0fa2606bbd8389d674bf4bf51ae4 | [
"BSD-3-Clause"
] | null | null | null | src/ex4_delete_def/main.cpp | pumpkin-code/dsba-ads-lect8 | 237c0c2624fc0fa2606bbd8389d674bf4bf51ae4 | [
"BSD-3-Clause"
] | null | null | null | /*! \file main.cpp
* \author Sergey Shershakov
* \version 0.1
* \date 11.02.2020
*
* Demonstrates how to lock copy constructor and copy assignment operator
* from being used.
*/
#include <iostream>
//#include <stdexcept>
//#include <cassert>
/***************************************************************************//**
* Represents a custom object w/ no copy ability
******************************************************************************/
class NonCopyable {
public:
NonCopyable()
{
std::cout << "Default constructor called\n";
}
NonCopyable(int a)
{
std::cout << "Init constructor called\n";
}
// the following is "modern" approach
NonCopyable(const NonCopyable& other) = delete;
const NonCopyable& operator = (const NonCopyable& rhv) = delete;
//// this is "classical" approach
//private:
// NonCopyable(const NonCopyable& other); // CC is not available
// const NonCopyable& operator = (const NonCopyable& rhv); // CAO is not available
};
void demo1()
{
NonCopyable o1; // default
NonCopyable o2(42); // init
//NonCopyable o3(o2); // not available
//o2 = o1; // not available
}
int main()
{
demo1();
return 0;
}
| 21.8 | 85 | 0.521407 | [
"object"
] |
636440f36ebee2caf0c6d9fff07b94dd0546de98 | 993 | hpp | C++ | inc/ojlibs/disjoint_set.hpp | georeth/OJLIBS | de59d4fd21255cc2f0a580db7726b634449e6885 | [
"MIT"
] | 15 | 2017-03-26T03:54:16.000Z | 2021-04-04T13:10:43.000Z | inc/ojlibs/disjoint_set.hpp | georeth/OJLIBS | de59d4fd21255cc2f0a580db7726b634449e6885 | [
"MIT"
] | null | null | null | inc/ojlibs/disjoint_set.hpp | georeth/OJLIBS | de59d4fd21255cc2f0a580db7726b634449e6885 | [
"MIT"
] | 1 | 2018-03-06T09:59:14.000Z | 2018-03-06T09:59:14.000Z | #ifndef OJLIBS_INC_DISJOINT_SET_H_
#define OJLIBS_INC_DISJOINT_SET_H_
#include <vector>
namespace ojlibs { // TO_BE_REMOVED
struct disjoint_set {
std::vector<int> parent;
void reset(int size){
parent.resize(size);
for (int i = 0; i < (int)parent.size(); i++){
parent[i] = i;
}
}
disjoint_set(int size){ reset(size); }
int find(int c){
int pc = parent[c];
return (pc == c) ? c : (parent[c] = find(pc));
}
// ancestor(p) is parent of ancestor(c)
bool union_if(int p, int c){
int pp = find(p), pc = find(c);
if (pp == pc) return false;
parent[pc] = pp;
return true;
}
};
// extension: distance function and function f TO_BE_REMOVED
// dist(u, u) = 0 TO_BE_REMOVED
// dist(u, w) = f(dist(u, v), dist(v, w)) TO_BE_REMOVED
} // ojlibs TO_BE_REMOVED
#endif /* end of include guard: OJLIBS_INC_DISJOINT_SET_H_ */
| 26.131579 | 69 | 0.55287 | [
"vector"
] |
636533e890a11d30a1bf69b4045c6fda202fb7d3 | 2,216 | hpp | C++ | services/disk/disk.hpp | jinntechio/RocketJoe | 9b08a21fda1609c57b40ef8b9750897797ac815b | [
"BSD-3-Clause"
] | 7 | 2019-06-02T12:04:22.000Z | 2019-10-15T18:01:21.000Z | services/disk/disk.hpp | jinntechio/RocketJoe | 9b08a21fda1609c57b40ef8b9750897797ac815b | [
"BSD-3-Clause"
] | 26 | 2019-10-27T12:58:42.000Z | 2020-05-30T16:43:48.000Z | services/disk/disk.hpp | jinntechio/RocketJoe | 9b08a21fda1609c57b40ef8b9750897797ac815b | [
"BSD-3-Clause"
] | 1 | 2020-05-25T09:28:46.000Z | 2020-05-25T09:28:46.000Z | #pragma once
#include <components/document/document.hpp>
#include <components/document/document_id.hpp>
#include <components/protocol/base.hpp>
#include <core/file/file.hpp>
#include <boost/filesystem.hpp>
#include <wal/base.hpp>
namespace rocksdb {
class DB;
}
namespace services::disk {
class metadata_t;
using path_t = boost::filesystem::path;
using rocks_id = std::string;
using metadata_ptr = std::unique_ptr<metadata_t>;
using db_ptr = std::unique_ptr<rocksdb::DB>;
using components::document::document_ptr;
using components::document::document_id_t;
using file_ptr = std::unique_ptr<core::file::file_t>;
class disk_t {
public:
explicit disk_t(const path_t &file_name);
disk_t(const disk_t &) = delete;
disk_t &operator=(disk_t const&) = delete;
~disk_t();
void save_document(const database_name_t &database, const collection_name_t &collection, const document_id_t &id, const document_ptr &document);
[[nodiscard]] document_ptr load_document(const rocks_id& id_rocks) const;
[[nodiscard]] document_ptr load_document(const database_name_t &database, const collection_name_t &collection, const document_id_t& id) const;
void remove_document(const database_name_t &database, const collection_name_t &collection, const document_id_t &id);
[[nodiscard]] std::vector<rocks_id> load_list_documents(const database_name_t &database, const collection_name_t &collection) const;
[[nodiscard]] std::vector<database_name_t> databases() const;
bool append_database(const database_name_t &database);
bool remove_database(const database_name_t &database);
[[nodiscard]] std::vector<collection_name_t> collections(const database_name_t &database) const;
bool append_collection(const database_name_t &database, const collection_name_t &collection);
bool remove_collection(const database_name_t &database, const collection_name_t &collection);
void fix_wal_id(wal::id_t wal_id);
wal::id_t wal_id() const;
private:
db_ptr db_;
metadata_ptr metadata_;
file_ptr file_wal_id_;
};
} //namespace services::disk
| 39.571429 | 152 | 0.722924 | [
"vector"
] |
6367784fa4287fa5b5720080942fe84846462db6 | 528 | cxx | C++ | Algorithms/Implementation/non-divisible-subset.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Implementation/non-divisible-subset.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Implementation/non-divisible-subset.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, k; cin >> n >> k;
vector<int> counts (k, 0);
for ( int i = n, Si; --i >= 0; cin >> Si, ++counts[ Si % k ] )
;
int i, j;
for ( i = 0, j = counts.size(); ++i < --j; n -= min( counts[i], counts[j] ) )
;
if ( i == j && counts[i] )
n -= ( counts[i] - 1 );
if ( counts[0] )
n -= ( counts[0] - 1 );
cout << n << endl;
return 0;
}
| 22 | 81 | 0.456439 | [
"vector"
] |
63753480700061fa690338a1cb585eac3473eff5 | 1,658 | cpp | C++ | src/node_log.cpp | cutting-room-floor/node-mapbox-gl-native | a4c3a043604de518bbdd289871aed1df862a77cf | [
"BSD-3-Clause"
] | 1 | 2019-11-25T11:51:33.000Z | 2019-11-25T11:51:33.000Z | src/node_log.cpp | cutting-room-floor/node-mapbox-gl-native | a4c3a043604de518bbdd289871aed1df862a77cf | [
"BSD-3-Clause"
] | 1 | 2018-03-26T06:48:05.000Z | 2018-03-26T06:48:05.000Z | src/node_log.cpp | cutting-room-floor/node-mapbox-gl-native | a4c3a043604de518bbdd289871aed1df862a77cf | [
"BSD-3-Clause"
] | null | null | null | #include "node_log.hpp"
#include "util/async_queue.hpp"
namespace node_mbgl {
struct NodeLogObserver::LogMessage {
mbgl::EventSeverity severity;
mbgl::Event event;
int64_t code;
std::string text;
LogMessage(mbgl::EventSeverity severity_, mbgl::Event event_, int64_t code_, std::string text_)
: severity(severity_),
event(event_),
code(code_),
text(text_) {}
};
NodeLogObserver::NodeLogObserver(v8::Handle<v8::Object> target)
: queue(new Queue(uv_default_loop(), [this](LogMessage &message) {
NanScope();
auto msg = NanNew<v8::Object>();
msg->Set(NanNew("class"), NanNew(mbgl::EventClass(message.event).c_str()));
msg->Set(NanNew("severity"), NanNew(mbgl::EventSeverityClass(message.severity).c_str()));
if (message.code != -1) {
msg->Set(NanNew("code"), NanNew<v8::Number>(message.code));
}
if (!message.text.empty()) {
msg->Set(NanNew("text"), NanNew(message.text));
}
v8::Local<v8::Value> argv[] = { NanNew("message"), msg };
auto handle = NanNew<v8::Object>(module);
auto emit = handle->Get(NanNew("emit"))->ToObject();
emit->CallAsFunction(handle, 2, argv);
})) {
NanScope();
NanAssignPersistent(module, target);
// Don't keep the event loop alive.
queue->unref();
}
NodeLogObserver::~NodeLogObserver() {
queue->stop();
}
bool NodeLogObserver::onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string &text) {
queue->send({ severity, event, code, text });
return true;
}
}
| 30.145455 | 120 | 0.610374 | [
"object"
] |
63774b250ddc0b6fbab0cb4ac303f057aa1a0eb2 | 19,498 | cc | C++ | src/net/cert/internal/cert_issuer_source_aia_unittest.cc | Mr-Sheep/naiveproxy | 9f6e9768295f6d1d41517a15a621d4756bd7d6be | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | src/net/cert/internal/cert_issuer_source_aia_unittest.cc | Mr-Sheep/naiveproxy | 9f6e9768295f6d1d41517a15a621d4756bd7d6be | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | src/net/cert/internal/cert_issuer_source_aia_unittest.cc | Mr-Sheep/naiveproxy | 9f6e9768295f6d1d41517a15a621d4756bd7d6be | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/cert/internal/cert_issuer_source_aia.h"
#include <memory>
#include "net/cert/cert_net_fetcher.h"
#include "net/cert/internal/cert_errors.h"
#include "net/cert/internal/parsed_certificate.h"
#include "net/cert/internal/test_helpers.h"
#include "net/cert/x509_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace net {
namespace {
using ::testing::ByMove;
using ::testing::Mock;
using ::testing::Return;
using ::testing::StrictMock;
using ::testing::_;
::testing::AssertionResult ReadTestPem(const std::string& file_name,
const std::string& block_name,
std::string* result) {
const PemBlockMapping mappings[] = {
{block_name.c_str(), result},
};
return ReadTestDataFromPemFile(file_name, mappings);
}
::testing::AssertionResult ReadTestCert(
const std::string& file_name,
scoped_refptr<ParsedCertificate>* result) {
std::string der;
::testing::AssertionResult r =
ReadTestPem("net/data/cert_issuer_source_aia_unittest/" + file_name,
"CERTIFICATE", &der);
if (!r)
return r;
CertErrors errors;
*result = ParsedCertificate::Create(x509_util::CreateCryptoBuffer(der), {},
&errors);
if (!*result) {
return ::testing::AssertionFailure()
<< "ParsedCertificate::Create() failed:\n"
<< errors.ToDebugString();
}
return ::testing::AssertionSuccess();
}
std::vector<uint8_t> CertDataVector(const ParsedCertificate* cert) {
std::vector<uint8_t> data(
cert->der_cert().UnsafeData(),
cert->der_cert().UnsafeData() + cert->der_cert().Length());
return data;
}
// MockCertNetFetcher is an implementation of CertNetFetcher for testing.
class MockCertNetFetcher : public CertNetFetcher {
public:
MockCertNetFetcher() = default;
MOCK_METHOD0(Shutdown, void());
MOCK_METHOD3(FetchCaIssuers,
std::unique_ptr<Request>(const GURL& url,
int timeout_milliseconds,
int max_response_bytes));
MOCK_METHOD3(FetchCrl,
std::unique_ptr<Request>(const GURL& url,
int timeout_milliseconds,
int max_response_bytes));
MOCK_METHOD3(FetchOcsp,
std::unique_ptr<Request>(const GURL& url,
int timeout_milliseconds,
int max_response_bytes));
protected:
~MockCertNetFetcher() override = default;
};
// MockCertNetFetcherRequest gives back the indicated error and bytes.
class MockCertNetFetcherRequest : public CertNetFetcher::Request {
public:
MockCertNetFetcherRequest(Error error, std::vector<uint8_t> bytes)
: error_(error), bytes_(std::move(bytes)) {}
void WaitForResult(Error* error, std::vector<uint8_t>* bytes) override {
DCHECK(!did_consume_result_);
*error = error_;
*bytes = std::move(bytes_);
did_consume_result_ = true;
}
private:
Error error_;
std::vector<uint8_t> bytes_;
bool did_consume_result_ = false;
};
// Creates a CertNetFetcher::Request that completes with an error.
std::unique_ptr<CertNetFetcher::Request> CreateMockRequest(Error error) {
return std::make_unique<MockCertNetFetcherRequest>(error,
std::vector<uint8_t>());
}
// Creates a CertNetFetcher::Request that completes with the specified error
// code and bytes.
std::unique_ptr<CertNetFetcher::Request> CreateMockRequest(
const std::vector<uint8_t>& bytes) {
return std::make_unique<MockCertNetFetcherRequest>(OK, bytes);
}
// CertIssuerSourceAia does not return results for SyncGetIssuersOf.
TEST(CertIssuerSourceAiaTest, NoSyncResults) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_two_aia.pem", &cert));
// No methods on |mock_fetcher| should be called.
auto mock_fetcher = base::MakeRefCounted<StrictMock<MockCertNetFetcher>>();
CertIssuerSourceAia aia_source(mock_fetcher);
ParsedCertificateList issuers;
aia_source.SyncGetIssuersOf(cert.get(), &issuers);
EXPECT_EQ(0U, issuers.size());
}
// If the AuthorityInfoAccess extension is not present, AsyncGetIssuersOf should
// synchronously indicate no results.
TEST(CertIssuerSourceAiaTest, NoAia) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_no_aia.pem", &cert));
// No methods on |mock_fetcher| should be called.
auto mock_fetcher = base::MakeRefCounted<StrictMock<MockCertNetFetcher>>();
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> request;
aia_source.AsyncGetIssuersOf(cert.get(), &request);
EXPECT_EQ(nullptr, request);
}
// If the AuthorityInfoAccess extension only contains non-HTTP URIs,
// AsyncGetIssuersOf should create a Request object. The URL scheme check is
// part of the specific CertNetFetcher implementation, this tests that we handle
// ERR_DISALLOWED_URL_SCHEME properly. If FetchCaIssuers is modified to fail
// synchronously in that case, this test will be more interesting.
TEST(CertIssuerSourceAiaTest, FileAia) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_file_aia.pem", &cert));
auto mock_fetcher = base::MakeRefCounted<StrictMock<MockCertNetFetcher>>();
EXPECT_CALL(*mock_fetcher, FetchCaIssuers(GURL("file:///dev/null"), _, _))
.WillOnce(Return(ByMove(CreateMockRequest(ERR_DISALLOWED_URL_SCHEME))));
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> cert_source_request;
aia_source.AsyncGetIssuersOf(cert.get(), &cert_source_request);
ASSERT_NE(nullptr, cert_source_request);
// No results.
ParsedCertificateList result_certs;
cert_source_request->GetNext(&result_certs);
EXPECT_TRUE(result_certs.empty());
}
// If the AuthorityInfoAccess extension contains an invalid URL,
// AsyncGetIssuersOf should synchronously indicate no results.
TEST(CertIssuerSourceAiaTest, OneInvalidURL) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_invalid_url_aia.pem", &cert));
auto mock_fetcher = base::MakeRefCounted<StrictMock<MockCertNetFetcher>>();
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> request;
aia_source.AsyncGetIssuersOf(cert.get(), &request);
EXPECT_EQ(nullptr, request);
}
// AuthorityInfoAccess with a single HTTP url pointing to a single DER cert.
TEST(CertIssuerSourceAiaTest, OneAia) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_one_aia.pem", &cert));
scoped_refptr<ParsedCertificate> intermediate_cert;
ASSERT_TRUE(ReadTestCert("i.pem", &intermediate_cert));
auto mock_fetcher = base::MakeRefCounted<StrictMock<MockCertNetFetcher>>();
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia/I.cer"), _, _))
.WillOnce(Return(
ByMove(CreateMockRequest(CertDataVector(intermediate_cert.get())))));
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> cert_source_request;
aia_source.AsyncGetIssuersOf(cert.get(), &cert_source_request);
ASSERT_NE(nullptr, cert_source_request);
ParsedCertificateList result_certs;
cert_source_request->GetNext(&result_certs);
ASSERT_EQ(1u, result_certs.size());
ASSERT_EQ(result_certs.front()->der_cert(), intermediate_cert->der_cert());
result_certs.clear();
cert_source_request->GetNext(&result_certs);
EXPECT_TRUE(result_certs.empty());
}
// AuthorityInfoAccess with two URIs, one a FILE, the other a HTTP.
// Simulate a ERR_DISALLOWED_URL_SCHEME for the file URL. If FetchCaIssuers is
// modified to synchronously reject disallowed schemes, this test will be more
// interesting.
TEST(CertIssuerSourceAiaTest, OneFileOneHttpAia) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_file_and_http_aia.pem", &cert));
scoped_refptr<ParsedCertificate> intermediate_cert;
ASSERT_TRUE(ReadTestCert("i2.pem", &intermediate_cert));
auto mock_fetcher = base::MakeRefCounted<StrictMock<MockCertNetFetcher>>();
EXPECT_CALL(*mock_fetcher, FetchCaIssuers(GURL("file:///dev/null"), _, _))
.WillOnce(Return(ByMove(CreateMockRequest(ERR_DISALLOWED_URL_SCHEME))));
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia2/I2.foo"), _, _))
.WillOnce(Return(
ByMove(CreateMockRequest(CertDataVector(intermediate_cert.get())))));
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> cert_source_request;
aia_source.AsyncGetIssuersOf(cert.get(), &cert_source_request);
ASSERT_NE(nullptr, cert_source_request);
ParsedCertificateList result_certs;
cert_source_request->GetNext(&result_certs);
ASSERT_EQ(1u, result_certs.size());
ASSERT_EQ(result_certs.front()->der_cert(), intermediate_cert->der_cert());
cert_source_request->GetNext(&result_certs);
EXPECT_EQ(1u, result_certs.size());
}
// AuthorityInfoAccess with two URIs, one is invalid, the other HTTP.
TEST(CertIssuerSourceAiaTest, OneInvalidOneHttpAia) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_invalid_and_http_aia.pem", &cert));
scoped_refptr<ParsedCertificate> intermediate_cert;
ASSERT_TRUE(ReadTestCert("i2.pem", &intermediate_cert));
scoped_refptr<StrictMock<MockCertNetFetcher>> mock_fetcher(
new StrictMock<MockCertNetFetcher>());
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia2/I2.foo"), _, _))
.WillOnce(Return(
ByMove(CreateMockRequest(CertDataVector(intermediate_cert.get())))));
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> cert_source_request;
aia_source.AsyncGetIssuersOf(cert.get(), &cert_source_request);
ASSERT_NE(nullptr, cert_source_request);
ParsedCertificateList result_certs;
cert_source_request->GetNext(&result_certs);
ASSERT_EQ(1u, result_certs.size());
EXPECT_EQ(result_certs.front()->der_cert(), intermediate_cert->der_cert());
// No more results.
result_certs.clear();
cert_source_request->GetNext(&result_certs);
EXPECT_EQ(0u, result_certs.size());
}
// AuthorityInfoAccess with two HTTP urls, each pointing to a single DER cert.
// One request completes, results are retrieved, then the next request completes
// and the results are retrieved.
TEST(CertIssuerSourceAiaTest, TwoAiaCompletedInSeries) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_two_aia.pem", &cert));
scoped_refptr<ParsedCertificate> intermediate_cert;
ASSERT_TRUE(ReadTestCert("i.pem", &intermediate_cert));
scoped_refptr<ParsedCertificate> intermediate_cert2;
ASSERT_TRUE(ReadTestCert("i2.pem", &intermediate_cert2));
scoped_refptr<StrictMock<MockCertNetFetcher>> mock_fetcher(
new StrictMock<MockCertNetFetcher>());
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia/I.cer"), _, _))
.WillOnce(Return(
ByMove(CreateMockRequest(CertDataVector(intermediate_cert.get())))));
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia2/I2.foo"), _, _))
.WillOnce(Return(
ByMove(CreateMockRequest(CertDataVector(intermediate_cert2.get())))));
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> cert_source_request;
aia_source.AsyncGetIssuersOf(cert.get(), &cert_source_request);
ASSERT_NE(nullptr, cert_source_request);
// GetNext() should return intermediate_cert followed by intermediate_cert2.
// They are returned in two separate batches.
ParsedCertificateList result_certs;
cert_source_request->GetNext(&result_certs);
ASSERT_EQ(1u, result_certs.size());
EXPECT_EQ(result_certs.front()->der_cert(), intermediate_cert->der_cert());
result_certs.clear();
cert_source_request->GetNext(&result_certs);
ASSERT_EQ(1u, result_certs.size());
EXPECT_EQ(result_certs.front()->der_cert(), intermediate_cert2->der_cert());
// No more results.
result_certs.clear();
cert_source_request->GetNext(&result_certs);
EXPECT_EQ(0u, result_certs.size());
}
// AuthorityInfoAccess with a single HTTP url pointing to a single DER cert,
// CertNetFetcher request fails.
TEST(CertIssuerSourceAiaTest, OneAiaHttpError) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_one_aia.pem", &cert));
scoped_refptr<StrictMock<MockCertNetFetcher>> mock_fetcher(
new StrictMock<MockCertNetFetcher>());
// HTTP request returns with an error.
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia/I.cer"), _, _))
.WillOnce(Return(ByMove(CreateMockRequest(ERR_FAILED))));
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> cert_source_request;
aia_source.AsyncGetIssuersOf(cert.get(), &cert_source_request);
ASSERT_NE(nullptr, cert_source_request);
// No results.
ParsedCertificateList result_certs;
cert_source_request->GetNext(&result_certs);
ASSERT_EQ(0u, result_certs.size());
}
// AuthorityInfoAccess with a single HTTP url pointing to a single DER cert,
// CertNetFetcher request completes, but the DER cert fails to parse.
TEST(CertIssuerSourceAiaTest, OneAiaParseError) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_one_aia.pem", &cert));
scoped_refptr<StrictMock<MockCertNetFetcher>> mock_fetcher(
new StrictMock<MockCertNetFetcher>());
// HTTP request returns invalid certificate data.
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia/I.cer"), _, _))
.WillOnce(Return(
ByMove(CreateMockRequest(std::vector<uint8_t>({1, 2, 3, 4, 5})))));
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> cert_source_request;
aia_source.AsyncGetIssuersOf(cert.get(), &cert_source_request);
ASSERT_NE(nullptr, cert_source_request);
// No results.
ParsedCertificateList result_certs;
cert_source_request->GetNext(&result_certs);
ASSERT_EQ(0u, result_certs.size());
}
// AuthorityInfoAccess with two HTTP urls, each pointing to a single DER cert.
// One request fails.
TEST(CertIssuerSourceAiaTest, TwoAiaCompletedInSeriesFirstFails) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_two_aia.pem", &cert));
scoped_refptr<ParsedCertificate> intermediate_cert2;
ASSERT_TRUE(ReadTestCert("i2.pem", &intermediate_cert2));
scoped_refptr<StrictMock<MockCertNetFetcher>> mock_fetcher(
new StrictMock<MockCertNetFetcher>());
// Request for I.cer completes first, but fails.
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia/I.cer"), _, _))
.WillOnce(Return(ByMove(CreateMockRequest(ERR_INVALID_RESPONSE))));
// Request for I2.foo succeeds.
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia2/I2.foo"), _, _))
.WillOnce(Return(
ByMove(CreateMockRequest(CertDataVector(intermediate_cert2.get())))));
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> cert_source_request;
aia_source.AsyncGetIssuersOf(cert.get(), &cert_source_request);
ASSERT_NE(nullptr, cert_source_request);
// GetNext() should return intermediate_cert2.
ParsedCertificateList result_certs;
cert_source_request->GetNext(&result_certs);
ASSERT_EQ(1u, result_certs.size());
EXPECT_EQ(result_certs.front()->der_cert(), intermediate_cert2->der_cert());
// No more results.
result_certs.clear();
cert_source_request->GetNext(&result_certs);
EXPECT_EQ(0u, result_certs.size());
}
// AuthorityInfoAccess with two HTTP urls, each pointing to a single DER cert.
// First request completes, result is retrieved, then the second request fails.
TEST(CertIssuerSourceAiaTest, TwoAiaCompletedInSeriesSecondFails) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_two_aia.pem", &cert));
scoped_refptr<ParsedCertificate> intermediate_cert;
ASSERT_TRUE(ReadTestCert("i.pem", &intermediate_cert));
scoped_refptr<StrictMock<MockCertNetFetcher>> mock_fetcher(
new StrictMock<MockCertNetFetcher>());
// Request for I.cer completes first.
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia/I.cer"), _, _))
.WillOnce(Return(
ByMove(CreateMockRequest(CertDataVector(intermediate_cert.get())))));
// Request for I2.foo fails.
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia2/I2.foo"), _, _))
.WillOnce(Return(ByMove(CreateMockRequest(ERR_INVALID_RESPONSE))));
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> cert_source_request;
aia_source.AsyncGetIssuersOf(cert.get(), &cert_source_request);
ASSERT_NE(nullptr, cert_source_request);
// GetNext() should return intermediate_cert.
ParsedCertificateList result_certs;
cert_source_request->GetNext(&result_certs);
ASSERT_EQ(1u, result_certs.size());
EXPECT_EQ(result_certs.front()->der_cert(), intermediate_cert->der_cert());
// No more results.
result_certs.clear();
cert_source_request->GetNext(&result_certs);
EXPECT_EQ(0u, result_certs.size());
}
// AuthorityInfoAccess with six HTTP URLs. kMaxFetchesPerCert is 5, so the
// sixth URL should be ignored.
TEST(CertIssuerSourceAiaTest, MaxFetchesPerCert) {
scoped_refptr<ParsedCertificate> cert;
ASSERT_TRUE(ReadTestCert("target_six_aia.pem", &cert));
scoped_refptr<StrictMock<MockCertNetFetcher>> mock_fetcher(
new StrictMock<MockCertNetFetcher>());
std::vector<uint8_t> bad_der({1, 2, 3, 4, 5});
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia/I.cer"), _, _))
.WillOnce(Return(ByMove(CreateMockRequest(bad_der))));
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia2/I2.foo"), _, _))
.WillOnce(Return(ByMove(CreateMockRequest(bad_der))));
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia3/I3.foo"), _, _))
.WillOnce(Return(ByMove(CreateMockRequest(bad_der))));
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia4/I4.foo"), _, _))
.WillOnce(Return(ByMove(CreateMockRequest(bad_der))));
EXPECT_CALL(*mock_fetcher,
FetchCaIssuers(GURL("http://url-for-aia5/I5.foo"), _, _))
.WillOnce(Return(ByMove(CreateMockRequest(bad_der))));
// Note that the sixth URL (http://url-for-aia6/I6.foo) will not be requested.
CertIssuerSourceAia aia_source(mock_fetcher);
std::unique_ptr<CertIssuerSource::Request> cert_source_request;
aia_source.AsyncGetIssuersOf(cert.get(), &cert_source_request);
ASSERT_NE(nullptr, cert_source_request);
// GetNext() will not get any certificates (since the first 5 fail to be
// parsed, and the sixth URL is not attempted).
ParsedCertificateList result_certs;
cert_source_request->GetNext(&result_certs);
ASSERT_EQ(0u, result_certs.size());
}
} // namespace
} // namespace net
| 38.840637 | 80 | 0.736999 | [
"object",
"vector"
] |
637beae93a5526845d5de502a001183c7e1c57a2 | 5,210 | cpp | C++ | src/mainwindow.cpp | Sangeun44/Half-Edge-Mesh | 0ab055fd5aee275c64167ac2b5ae75278e9dc488 | [
"MIT"
] | null | null | null | src/mainwindow.cpp | Sangeun44/Half-Edge-Mesh | 0ab055fd5aee275c64167ac2b5ae75278e9dc488 | [
"MIT"
] | null | null | null | src/mainwindow.cpp | Sangeun44/Half-Edge-Mesh | 0ab055fd5aee275c64167ac2b5ae75278e9dc488 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include <ui_mainwindow.h>
#include "cameracontrolshelp.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->mygl->setFocus();
//obj pressed clear lists
connect(ui->mygl, SIGNAL(sendOBJ(bool)), this, SLOT(loadOBJclicked(bool)));
//adding faces to QLISTWIDGET
connect(ui->mygl, SIGNAL(addFace(Face*)), this, SLOT(addFace(Face*)));
connect(ui->mygl, SIGNAL(addHE(HalfEdge*)), this, SLOT(addHE(HalfEdge*)));
connect(ui->mygl, SIGNAL(addVertex(Vertex*)), this, SLOT(addVertex(Vertex*)));
//select component
connect(ui->Face_list, SIGNAL(itemClicked(QListWidgetItem*)), ui->mygl, SLOT(clickFace(QListWidgetItem*)));
connect(ui->HalfEdge_list, SIGNAL(itemClicked(QListWidgetItem*)), ui->mygl, SLOT(clickHalfEdge(QListWidgetItem*)));
connect(ui->Vertex_list, SIGNAL(itemClicked(QListWidgetItem*)), ui->mygl, SLOT(clickVertex(QListWidgetItem*)));
//change face color
connect(ui->face_color_r, SIGNAL(valueChanged(double)), ui->mygl, SLOT(valueChangedR(double)));
connect(ui->face_color_g, SIGNAL(valueChanged(double)), ui->mygl, SLOT(valueChangedG(double)));
connect(ui->face_color_b, SIGNAL(valueChanged(double)), ui->mygl, SLOT(valueChangedB(double)));
//change vertex position
connect(ui->vertex_x, SIGNAL(valueChanged(double)), ui->mygl, SLOT(valueChangedX(double)));
connect(ui->vertex_y, SIGNAL(valueChanged(double)), ui->mygl, SLOT(valueChangedY(double)));
connect(ui->vertex_z, SIGNAL(valueChanged(double)), ui->mygl, SLOT(valueChangedZ(double)));
//set initial rgb
connect(ui->mygl, SIGNAL(initialR(double)), this, SLOT(updateColorR(double)));
connect(ui->mygl, SIGNAL(initialG(double)), this, SLOT(updateColorG(double)));
connect(ui->mygl, SIGNAL(initialB(double)), this, SLOT(updateColorB(double)));
//set initial vertex
connect(ui->mygl, SIGNAL(initialX(double)), this, SLOT(updateX(double)));
connect(ui->mygl, SIGNAL(initialY(double)), this, SLOT(updateY(double)));
connect(ui->mygl, SIGNAL(initialZ(double)), this, SLOT(updateZ(double)));
//midpoint adding
connect(ui->Addmidpoint, SIGNAL(pressed()), ui->mygl, SLOT(pressedMidpoint()));
//triangulate
connect(ui->triangulate, SIGNAL(pressed()), ui->mygl, SLOT(pressedTriangulate()));
//Catmull-Clark Subdivision
connect(ui->subdivide, SIGNAL(pressed()), ui->mygl, SLOT(pressedSubdivide()));
//Extrude
connect(ui->extrude, SIGNAL(pressed()), ui->mygl, SLOT(pressedExtrude()));
//load obj
connect(ui->loadobj, SIGNAL(pressed()), ui->mygl, SLOT(pressedOBJ()));
//load JSON
connect(ui->json, SIGNAL(pressed()), ui->mygl, SLOT(pressedJson()));
//adding joints to QTreeWidget
connect(ui->mygl, SIGNAL(addJoint(Joint*)), this, SLOT(addJoint(Joint*)));
//select joint
connect(ui->joint_list, SIGNAL(itemClicked(QTreeWidgetItem*, int)), ui->mygl, SLOT(clickJoint(QTreeWidgetItem*, int)));
//change joint rotation xyz value displayed on the GUI
connect(ui->mygl, SIGNAL(sendRotateXCurr(int)), this, SLOT(updateXrot(int)));
connect(ui->mygl, SIGNAL(sendRotateYCurr(int)), this, SLOT(updateYrot(int)));
connect(ui->mygl, SIGNAL(sendRotateZCurr(int)), this, SLOT(updateZrot(int)));
//change joint rotation
connect(ui->rotatex, SIGNAL(pressed()), ui->mygl, SLOT(rotateX()));
connect(ui->rotatey, SIGNAL(pressed()), ui->mygl, SLOT(rotateY()));
connect(ui->rotatez, SIGNAL(pressed()), ui->mygl, SLOT(rotateZ()));
//skin mesh button
connect(ui->skinMesh, SIGNAL(pressed()), ui->mygl, SLOT(skin()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionQuit_triggered()
{
QApplication::exit();
}
void MainWindow::on_actionCamera_Controls_triggered()
{
CameraControlsHelp* c = new CameraControlsHelp();
c->show();
}
//OBJ clicked
void MainWindow::loadOBJclicked(bool)
{
ui->Vertex_list->clear();
ui->HalfEdge_list->clear();
ui->Face_list->clear();
}
//add face to Qlistwidget
void MainWindow::addFace(Face* e)
{
ui->Face_list->addItem(e);
}
//add HE to Qlistwidget
void MainWindow::addHE(HalfEdge* e)
{
ui->HalfEdge_list->addItem(e);
}
//add vert to Qlistwidget
void MainWindow::addVertex(Vertex* e)
{
ui->Vertex_list->addItem(e);
}
//add HE to QTreeList
void MainWindow::addJoint(Joint* e)
{
ui->joint_list->addTopLevelItem(e);
}
//update color spinboxes
void MainWindow::updateColorR(double r) {
ui->face_color_r->setValue(r);
}
void MainWindow::updateColorG(double g) {
ui->face_color_g->setValue(g);
}
void MainWindow::updateColorB(double b) {
ui->face_color_b->setValue(b);
}
//update spinboxes xyz
void MainWindow::updateX(double x) {
ui->vertex_x->setValue(x);
}
void MainWindow::updateY(double y) {
ui->vertex_y->setValue(y);
}
void MainWindow::updateZ(double z) {
ui->vertex_z->setValue(z);
}
//update rotation xyz
void MainWindow::updateXrot(int x) {
ui->currRotateX->setValue(x);
}
void MainWindow::updateYrot(int y) {
ui->currRotateY->setValue(y);
}
void MainWindow::updateZrot(int z) {
ui->currRotateZ->setValue(z);
}
| 30.828402 | 123 | 0.691363 | [
"mesh"
] |
6384d9fba487ab159416a322c6ed25a88940cc53 | 33,405 | cpp | C++ | PacMan_CANOpen/Core1.cpp | CS150Student/PacManFirmware | 4ea440d419f02ba715865b602f0bdc30c0e9a1c0 | [
"MIT"
] | 1 | 2020-06-23T04:10:11.000Z | 2020-06-23T04:10:11.000Z | PacMan_CANOpen/Core1.cpp | CS150Student/PacManFirmware | 4ea440d419f02ba715865b602f0bdc30c0e9a1c0 | [
"MIT"
] | 1 | 2020-02-27T23:29:43.000Z | 2020-02-27T23:29:43.000Z | PacMan_CANOpen/Core1.cpp | CS150Student/PacManFirmware | 4ea440d419f02ba715865b602f0bdc30c0e9a1c0 | [
"MIT"
] | 1 | 2021-05-19T07:08:10.000Z | 2021-05-19T07:08:10.000Z | /**
* @file Core1.cpp
* @author Clement Hathaway (cwbh10@gmail.com)
* @brief The Code running on Core1 controlling much of the data processing
* @version 1.0
* @date 2020-04-13
*
* @copyright Copyright (c) 2020
*
*/
#include "Core1.h"
uint8_t cellFaults[16];
/**
* @brief A Callback triggered by the warning timer
* Locks Object Dictionary
* Updates the Object Dictionary with the cellFaults warnings that have been set prior to their appropriate values
* Unlocks Object Dictionary
* @param pxTimer parameter used in the callback in the timers - given by ESP IDF guidelines
*/
void warningCallBack(TimerHandle_t pxTimer){
CO_LOCK_OD();
//Serial.println("15 seconds has past setting warnings!");
for(int i = 0; i < 16; i++){
OD_warning[i] = cellFaults[i];
}
CO_UNLOCK_OD();
}
/**
* @brief A Callback triggered by the safetyloop timer
* Opens Safety loop
* Locks Object Dictionary
* Updates the Object Dictionary with the cellFaults faults that have been set prior to their appropriate values
* Unlocks Object Dictionary+
* @param pxTimer parameter used in the callback in the timers - given by ESP IDF guideline
*/
void openSafetyLoopCallBack(TimerHandle_t pxTimer){
digitalWrite(PIN_SLOOP_EN, LOW);
OD_SLOOP_Relay = false;
Serial.println("SAFETY LOOP OPENED!");
CO_LOCK_OD();
for(int i = 0; i < 16; i++){
OD_fault[i] = cellFaults[i];
}
CO_UNLOCK_OD();
}
// CONSTRUCTOR
/**
* @brief Constructs a new Core 1::Core 1 object
* Created interrupt Semaphores
* Starts I2C driver and joins the bus on specified pins in PacMan.h
* Creates all the warning and fault timers
* @param CO The CANopen object which is passed in via the toplevel PacMan file
*/
Core1::Core1(CO_t *CO) {
// Interrupt Semaphores
if (DEBUG) printf("Core 1: Initialising");
I2C_InterrupterSemaphore = xSemaphoreCreateBinary();
chargeDetectSemaphore = xSemaphoreCreateBinary();
if (DEBUG) printf("Core 1: I2C and Charge Detect Interrupt Semaphores Created");
Wire.begin(PIN_SDA, PIN_SCL); // Join the I2C bus (address optional for master) -- CHANGE THIS FOR DISPLAY
if (DEBUG) printf("Core 1: Joined I2C Bus");
currentSensor.init(LTC4151::L, LTC4151::L); // Init the LTC4151 responsible for PacMan power consumption and TSV consumption
consumedMAH = 0; // Should be made into OB stuff so we can save this upon loss of power or reset -- Complex issue
totalMAH = 60000;
// Create safetyloop timers
underVoltageTimer = xTimerCreate(
/* Just a text name, not used by the RTOS kernel. */
"underVoltageTimer",
/* The timer period in ticks. From Time To Trigger *1000 for ms */
pdMS_TO_TICKS(TTT*1000),
/* The timer is a one-shot timer. */
pdFALSE,
/* The id is not used by the callback so can take any
value. */
0,
/* The callback function that switches the LCD back-light
off. */
openSafetyLoopCallBack);
underVoltageWarningTimer = xTimerCreate("underVoltageWarningTimer", pdMS_TO_TICKS(TTT*1000/6), pdFALSE, 0, warningCallBack);
overVoltageTimer = xTimerCreate("overVoltageTimer", pdMS_TO_TICKS(TTT*1000), pdFALSE, 0, openSafetyLoopCallBack);
overVoltageWarningTimer = xTimerCreate("overVoltageWarningTimer", pdMS_TO_TICKS(TTT*1000/6), pdFALSE, 0, warningCallBack);
overTemperatureTimer = xTimerCreate("overTemperatureTimer", pdMS_TO_TICKS(TTT*1000), pdFALSE, 0, openSafetyLoopCallBack);
overTemperatureWarningTimer = xTimerCreate("overTemperatureWarningTimer", pdMS_TO_TICKS(TTT*1000/6), pdFALSE, 0, warningCallBack);
if (DEBUG) printf("Core 1: Created Software Safety Timers!");
}
// Quick sorts out struct of addressVoltage based off of the .addressMinusVoltage property
/**
* @brief Sorts an array of AddressVoltage structs by ascending voltage reference level
* Uses quicksort as the main sorting method
* @param addressVoltages The array of structs of type addressVoltage
* @param first Part of the recursion in Quicksort
* @param last Part of the recursion in Quicksort
*/
void Core1::addressVoltageQuickSort(addressVoltage* addressVoltages, int first, int last) {
int i, j, pivot;
uint16_t tempVoltage;
uint8_t tempAddress;
if (first < last) {
pivot = first;
i = first;
j = last;
while (i < j) {
while (addressVoltages[i].addressMinusVoltage <= addressVoltages[pivot].addressMinusVoltage && i < last)
i++;
while (addressVoltages[j].addressMinusVoltage > addressVoltages[pivot].addressMinusVoltage)
j--;
if (i < j) {
tempAddress = addressVoltages[i].address;
tempVoltage = addressVoltages[i].addressMinusVoltage;
addressVoltages[i].address = addressVoltages[j].address;
addressVoltages[i].addressMinusVoltage = addressVoltages[j].addressMinusVoltage;
addressVoltages[j].address = tempAddress;
addressVoltages[j].addressMinusVoltage = tempVoltage;
}
}
tempAddress = addressVoltages[pivot].address;
tempVoltage = addressVoltages[pivot].addressMinusVoltage;
addressVoltages[pivot].address = addressVoltages[j].address;
addressVoltages[pivot].addressMinusVoltage = addressVoltages[j].addressMinusVoltage;
addressVoltages[j].address = tempAddress;
addressVoltages[j].addressMinusVoltage = tempVoltage;
addressVoltageQuickSort(addressVoltages, first, j - 1);
addressVoltageQuickSort(addressVoltages, j + 1, last);
}
}
bool Core1::addressVoltageSorter(addressVoltage const lhs, addressVoltage const rhs) {
return (lhs.addressMinusVoltage < rhs.addressMinusVoltage);
}
// Discovery I2C devices, excluding I2C devices on PacMan
/**
* @brief Discover the CellMen that are connected to the I2C bus
* Scans for devices between all available I2C addresses (1-127)
* Excludes known non-cellman devices defined in PacMan.h
* @return uint8_t number of CellMen found
*/
uint8_t Core1::discoverCellMen() {
uint8_t cellMenCount = 0;
// Since we are using a set array size, let's initialise all values in the array to 0
for (int i = 0; i < 16; i++) {
addresses[i] = 0x00;
}
// Start the scan for I2C devices between 1 and 127
for (int address = 1; address < 127; address++ )
{
// The I2C scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
byte error = Wire.endTransmission();
if (error == 0) {
// Exclude PacMan I2C devices
if (address != I2C_ADDR_MCP9804
&& address != I2C_ADDR_MCP23008
&& address != I2C_ADDR_BQ32002
&& address != I2C_ADDR_LTC4151
&& address != I2C_ADDR_LTC4151_GLOB)
{
Serial.print("CellMan I2C device found at address 0x");
if (address < 16) Serial.print("0");
Serial.print(address, HEX);
Serial.println(" !");
// Add the new address to our address array and increment the number we have found
addresses[cellMenCount] = address;
cellMenCount++;
}
}
else if (error == 4) {
Serial.print("Unknown error at address 0x");
if (address < 16)
Serial.print("0");
Serial.print(address, HEX);
Serial.println(" skipping...");
}
}
return cellMenCount;
}
// Request byte array from specified CellMan I2C address, using index and preCollect we know when to check for I2C faults
/**
* @brief Requests data from an I2C slave
* Requests data from I2C slaves, used for collecting data from CellMen
* Can be used before we have information about what CellMan is in what position during precollection
* @param address The address of the I2C Device/CellMan
* @param index The index for where the data will be stored - Not relevant in precollection mode
* @param preCollect A boolean to decide if the method is collecting data in the beginning for processing or just gathering new data
* @return unsigned* char returns data array sent from the I2C slave
*/
unsigned char* Core1::requestDataFromSlave(unsigned char address, uint8_t index, bool preCollect) {
uint8_t physicalODAddress = physicalLocationFromSortedArray(index);
if(!preCollect) toggleCellManLED(address, true);
Wire.requestFrom((int) address, REQUEST_LENGTH); // 24 is the max data length expected in bytes
if (DEBUG) {
Serial.print("Requesting data from CellMan on Address: ");
Serial.println(address);
}
if (Wire.available()) {
if (DEBUG) Serial.println("Wire Available!");
if(cellFaults[physicalODAddress] == 9 && !preCollect){
if(DEBUG) Serial.println("CellMan I2C Re-established!");
cellFaults[physicalODAddress] = 0; // If the Cellman comes back online, set the fault back to 0
}
for (int i = 0; i < REQUEST_LENGTH; i++) {
*(cellDs + i) = Wire.read(); // Append the read character (byte) to our cellData array
if (DEBUG) {
Serial.println(cellDs[i], HEX); // Print the character (byte) in HEX
Serial.println(cellDs[i], DEC); // Print the character (byte) in DEC
}
}
}else{
if(!preCollect && cellFaults[physicalODAddress] != 9){
if(DEBUG) Serial.println("Got a fault!");
cellFaults[physicalODAddress] = 9;
}
}
if(!preCollect) toggleCellManLED(address, false);
// Only update the faults if its 0 or 9, otherwise it negates the timer's purpose - Gets called a lot, maybe we can reduce the OD usage here sometime
if(!preCollect){
if(cellFaults[physicalODAddress] == 9 || cellFaults[physicalODAddress] == 0){
CO_LOCK_OD();
OD_warning[physicalODAddress] = cellFaults[physicalODAddress];
CO_UNLOCK_OD();
}
}
return cellDs;
}
// Process the celldata into our private arrays to be stored into the OD later
/**
* @brief Process the collected cellData array from the CellMan into its respective arrays in the class
* Since we get data from each CellMan at a time, but in the Object Dictionary it is stored by Data and then CellMan
* We have to preprocess the data so it is ready to be inserted in the OD with minimal locking time
* @param cellData Pass in the CellData array of bytes obtained from requestDataFromSlave
* @param cellPhysicalLocation Pass in the physical location of the cell so it matches in the array, e.g. physical location 8 is 7 in the array
*/
void Core1::processCellData(unsigned char* cellData, uint8_t cellPhysicalLocation) {
cellPositions[cellPhysicalLocation] = cellPhysicalLocation;
cellVoltages[cellPhysicalLocation] = (uint16_t)((cellData[2] << 8) + cellData[1]); // Shift MSBs over 8 bits, then add the LSBs to the first 8 bits and cast as a uint16_t
cellTemperatures[cellPhysicalLocation] = (uint16_t)((cellData[4] << 8) + cellData[3]);
minusTerminalVoltages[cellPhysicalLocation] = (uint16_t)((cellData[6] << 8) + cellData[5]);
cellBalanceCurrents[cellPhysicalLocation] = (uint16_t)((cellData[8] << 8) + cellData[7]);
// If we are in I2C Debug Mode
if (DEBUG) {
LEDStatuses[cellPhysicalLocation] = (bool)cellData[9];
balanceStatuses[cellPhysicalLocation] = (bool)cellData[10];
balanceDutyCycles[cellPhysicalLocation] = (uint8_t)cellData[10];
balanceFrequencies[cellPhysicalLocation] = (uint16_t)((cellData[13] << 8) + cellData[12]);
temperatureSlopes[cellPhysicalLocation] = (uint16_t)((cellData[15] << 8) + cellData[14]);
temperatureOffsets[cellPhysicalLocation] = (uint16_t)((cellData[17] << 8) + cellData[16]);
balanceCurrentSlopes[cellPhysicalLocation] = (uint16_t)((cellData[19] << 8) + cellData[18]);
balanceVoltageSlopes[cellPhysicalLocation] = (uint16_t)((cellData[21] << 8) + cellData[20]);
}
}
// Check the safety of our measurements, trigger warnings and safetyloop here
/**
* @brief Checks the safety our of CellMen Data in the Object Dictionary
* Looks through the number of CellMen we have detected and checks their values for
* Undervoltage, Overvoltage, Overtemperature, and I2C disconnect/error
* Starts/Stops appropriate warning and fault timers
* @param numberOfDiscoveredCellMen Integer with the number of detected CellMan so we don't check bad data
*/
void Core1::checkSafety(uint8_t numberOfDiscoveredCellMen){
tempUV = false;
tempOV = false;
tempOT = false;
int i;
int newIndex;
if (DEBUG) printf("Core 1: Checking Safety of Data in Object Dictionary");
CO_LOCK_OD();
if (DEBUG) printf("Core 1: Obtained Object Dictionary Lock");
for(i = 0; i < numberOfDiscoveredCellMen; i++){
// Because we have everything stored in physical locations in the array. e.g. 0 goes to Cell 0, 1 goes to Cell 8 in the array since they are in different segments
newIndex = physicalLocationFromSortedArray(i);
// Voltages are below the threshold trigger the tempValue to symbolise at least one voltage low
if(cellVoltages[newIndex] < OD_minCellVoltage[newIndex] && cellFaults[newIndex] != 9){
cellFaults[newIndex] = 2;
tempUV = true;
} else if(cellVoltages[newIndex] > OD_maxCellVoltage[newIndex] && cellFaults[newIndex] != 9){
cellFaults[newIndex] = 1;
tempOV = true;
} else if(cellTemperatures[newIndex] > OD_maxCellTemp[newIndex] && cellFaults[newIndex] != 9){
cellFaults[newIndex] = 3;
tempOT = true;
/* Reset values here so that we get rid of warnings and reset timers
Except if it is 9, since this means the cellman is not on I2C
and the data is old and therefore not trustworthy*/
}else if(cellFaults[newIndex] != 9){
cellFaults[newIndex] = 0;
OD_warning[newIndex] = 0;
OD_fault[newIndex] = 0;
}
}
CO_UNLOCK_OD();
if (DEBUG) printf("Core 1: Released Object Dictionary Lock");
// At least 1 cell was found below the voltage threshold - start undervoltage counter
if(tempUV){
if(xTimerIsTimerActive(underVoltageTimer) == pdFALSE){
if(xTimerStart(underVoltageTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start underVoltage Timer");
}else{
if(DEBUG) Serial.println("Core 1: underVoltage Timer as begun!");
}
}
if(xTimerIsTimerActive(underVoltageWarningTimer) == pdFALSE){
if(xTimerStart(underVoltageWarningTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start underVoltage Warning Timer");
}else{
if(DEBUG) Serial.println("Core 1: underVoltage Warning Timer as begun!");
}
}
// No cells were found below the minimum voltage - stop and reset both counters
}else{
// Reset puts the timer in an active state - Resets time, but need to stop it to put it in a dormant state
xTimerReset(underVoltageTimer, 0);
xTimerReset(underVoltageWarningTimer, 0);
// Stop puts timer in a dormant state which lets us use xTimerIsTimerActive
xTimerStop(underVoltageTimer, 0);
xTimerStop(underVoltageWarningTimer, 0);
}
// At least 1 cell was found above the voltage threshold - start overvoltage counter
if(tempOV){
if(xTimerIsTimerActive(overVoltageTimer) == pdFALSE){ // Check to see if the timer has not been started yet, we don't want to start an already started timer
if(xTimerStart(overVoltageTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start overVoltage Timer");
}else{
if(DEBUG) Serial.println("Core 1: overVoltage Timer as begun!");
}
if(xTimerIsTimerActive(overVoltageWarningTimer) == pdFALSE){ // Check to see if the timer has not been started yet, we don't want to start an already started timer
if(xTimerStart(overVoltageWarningTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start overVoltage Warning Timer");
}else{
if(DEBUG) Serial.println("Core 1: overVoltage Timer warning as begun!");
}
}
}
// No cells were found above the maximum voltage - stop and reset counters
}else{
xTimerReset(overVoltageTimer, 0);
xTimerReset(overVoltageWarningTimer, 0);
xTimerStop(overVoltageTimer, 0);
xTimerStop(overVoltageWarningTimer, 0);
}
// At least 1 cell temp was found above the temp threshold - start overTemperature counter
if(tempOT){
if(xTimerIsTimerActive(overTemperatureTimer) == pdFALSE){
if(xTimerStart(overTemperatureTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start overTemperature Timer");
}else{
if(DEBUG) Serial.println("Core 1: overTemperature Timer as begun!");
}
}
if(xTimerIsTimerActive(overTemperatureWarningTimer) == pdFALSE){
if(xTimerStart(overTemperatureWarningTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start overTemperature Warning Timer");
}else{
if (DEBUG) Serial.println("Core 1: overTemperature Timer Warning as begun!");
}
}
// No cell temps were found above the maximum temp - stop and reset counter
}else{
xTimerReset(overTemperatureTimer, 0);
xTimerReset(overTemperatureWarningTimer, 0);
xTimerStop(overTemperatureTimer, 0);
xTimerStop(overTemperatureWarningTimer, 0);
}
}
// Maps the arrayIndex to a physical cell location in the packs (since we can't tell between segments right now) by saying the second instance of a same voltage potential cell is in the other segment
/**
* @brief Maps an arrayIndex into the physical Cell Location in the Packs
* This method is using a work around since the PacMan hardware this firmware was developed on has a flaw
* We cannot differentiate between segments since they have their own grounds.
* A PacMan board revision should have been made to fix this but this method randomises in which seg a cell gets placed
* This way you have a 50% chance of knowing what cell the data is about by looking in the Packs, this is better than otherwise
* This function will need to be rewritten or swapped for something else once segment detection works
* Segment detection will eventually be done by reseting a known segment and performing a CellMen discovery
* @param arrayIndex Integer of the array's Index (not physical location!)
* @return uint8_t Returns an integer of the physical location which can be used as an index for physically indexed arrays (e.g OD)
*/
uint8_t Core1::physicalLocationFromSortedArray(uint8_t arrayIndex) {
uint8_t physicalAddress;
if (arrayIndex % 2 == 0) { // If Even
physicalAddress = arrayIndex / 2;
} else { // If Odd
physicalAddress = ((arrayIndex - 1) / 2) + 8;
}
// return physicalAddress;
return arrayIndex;
}
// Simple voltage-based SOC - Very inaccurate
/**
* @brief Calculates a simple Voltage based State of Charge
* This shouldn't be used in production and should be replaced
* A simple EKF based model would be best here
* Columb counting is the easier and better soltion than voltage but worse than EKF models
*/
void Core1::calculateTotalPackSOC() {
int SOCTotal = 0;
for (int index = 0; index < 16; index++) {
//SOCTotal += privateCells[index].SOC; // Sum up all of our SOCs from all the cells to get an average for the 16 cells in a pack
}
packSOC = (float)(SOCTotal / 16); // Return the average SOC from the cells
}
void Core1::toggleCellManLED(unsigned char address, bool state){
// If on
if(state){
Wire.beginTransmission(address);
Wire.write(0x23); // 0x23 is the LED register
Wire.write(0x00); // MSB
Wire.write(0x01); // LSB
Wire.endTransmission();
}else{ //If off
Wire.beginTransmission(address);
Wire.write(0x23); // 0x23 is the LED register
Wire.write(0x00); // MSB
Wire.write(0x00); // LSB
Wire.endTransmission();
}
}
// Toggle LEDs on CellMen in segment position order to indicate that they are properly connected and communicating
// addressVoltages should be sorted at this point
// Will need to modify when the segments are distinguishable so that the order is correct
/**
* @brief Flashes CellMen LEDs in order of detection
* Follows the order of flashing each CellMan and then all of them at once
*/
void Core1::indicateCellMen(){
if(DEBUG){
Serial.print("Flashing CellMen LEDs at time ");
Serial.println(millis());
}
// Light up each LED incrementally every 250ms
for (int i = 0; i < numberOfDiscoveredCellMen; i++)
{
toggleCellManLED(addressVoltages[i].address, true);
delay(250);
}
// Blink the LEDs off and on 4 times
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < numberOfDiscoveredCellMen; i++)
{
toggleCellManLED(addressVoltages[i].address, false);
}
delay(250);
for (int i = 0; i < numberOfDiscoveredCellMen; i++)
{
toggleCellManLED(addressVoltages[i].address, true);
}
delay(250);
}
// Turn each LED off
for (int i = 0; i < numberOfDiscoveredCellMen; i++)
{
toggleCellManLED(addressVoltages[i].address, false);
}
if(DEBUG){
Serial.print("Done flashing CellMen LEDs at time ");
Serial.println(millis());
}
}
/**
* @brief Updates the Object Dictionary with udpated local CellMan data that was collected
* Goes through the detected CellMen and collects, processes, and checks safety of CellMen Data
* Locks the Object Dictionary
* Updates all of the data from the warnings, faults, and measurements into the OD
* Unlocks the OD
*/
void Core1::updateCellMenData(){
//Collect data from all the CellMen & Update Object Dictionary Interrupt
if (DEBUG) printf("Core 1: Attempting to take I2C Interrupt Semaphore");
if (xSemaphoreTake(I2C_InterrupterSemaphore, 0) == pdTRUE) {
if (DEBUG) printf("Core 1: Took I2C Interrupt Semaphore");
// Update CellMan Code
for (int i = 0; i < numberOfDiscoveredCellMen; i++) {
if (DEBUG) printf("Core 1: Requesting Data From CellMan");
unsigned char* celldata = requestDataFromSlave(addressVoltages[i].address, i, false);
if (DEBUG) printf("Core 1: Processing Collected Data");
processCellData(celldata, physicalLocationFromSortedArray(i)); // Process data retrieved from each cellman and is inerted based off of physicalAddress
if (DEBUG) printf("Core 1: Checking Safety of Collected Data");
checkSafety(numberOfDiscoveredCellMen);
}
if (DEBUG) printf("Core 1: Finishing Collecting CellMen Data");
// Update the Object Dictionary Here
if (DEBUG) printf("Core 1: Updating Object Dictionary");
CO_LOCK_OD();
if (DEBUG) printf("Core 1: Obtained Object Dictionary Lock");
// index i here will go through the array, but in this array the physical stuff is already set - I hate how confusing the indexes are depending on where you are in the code
for (int i = 0; i < 16; i++) {
// If this cell is disconnected, set all its useful data to 0 prior to changing the O
if(minusTerminalVoltages[i] != 0) // TODO: Examine this, the first cells should be at zero -- Removing this causes shit values so gotta fix this
{
if(cellFaults[i] == 9)
{
cellVoltages[i] = 0;
cellTemperatures[i] = 0;
cellBalancingEnabled[i] = 0;
cellBalanceCurrents[i] = 0;
}
OD_cellPosition[i] = cellPositions[i];
OD_cellVoltage[i] = cellVoltages[i];
OD_cellTemperature[i] = cellTemperatures[i];
OD_minusTerminalVoltage[i] = minusTerminalVoltages[i];
OD_cellBalancingEnabled[i] = cellBalancingEnabled[i];
OD_cellBalancingCurrent[i] = cellBalanceCurrents[i];
maxCellVoltage[i] = OD_maxCellVoltage[i];
maxCellTemp[i] = OD_maxCellTemp[i];
}
}
CO_UNLOCK_OD();
if (DEBUG) printf("Core 1: Updated Object Dictionary and Released OD Lock");
}
}
bool Core1::handleChargingSafety(){
bool charge = true;
int newIndex; // Gets us the actual physical location which is how the array in defined
// Check all cells are within spec -- This might cause issue for balancing if 1 cell becomes too high it'll turn off the relay, voltage will drop, and we will have relay oscillations
// UPDATE: ^ Above statement fixed by haiving the currentlyCharging variable which gives us hysteresis until the plug is taken out and put back in
for (int i = 0; i < numberOfDiscoveredCellMen; i++) {
newIndex = physicalLocationFromSortedArray(i);
if(cellVoltages[newIndex] > maxCellVoltage[newIndex] || cellTemperatures[newIndex] > maxCellTemp[newIndex]){
charge = false;
}
}
return charge;
}
bool Core1::handleChargingInterrupt(bool chargingState){
// Charge detect interrupt
if (xSemaphoreTake(chargeDetectSemaphore, 0) == pdTRUE) {
if(DEBUG) Serial.println("Detected Charging thing!");
// TODO: Prevent inverted state from occuring when lowering voltage when connector is in and then unplugging
if(chargingState == true){
if(digitalRead(PIN_CHRG_EN) == LOW && currentlyCharging == false){ // It's not already on, e.g. we've plugged the cable in
digitalWrite(PIN_CHRG_EN, HIGH);
OD_chargingEnabled = true;
currentlyCharging = true;
}else{ // The state changed because we removed the connector
digitalWrite(PIN_CHRG_EN, LOW);
OD_chargingEnabled = false;
currentlyCharging = false;
}
}
}
}
/**
* @brief Handles the charging interrupt and relays
* Checks to make sure all cells are within acceptable voltage ranges
* Trys to take the interrupt semaphore for the charge connector
* Adjusts the state of the relay based on the safety and state of charge connector
* This provides some hysteresis until the connector is replugged in if a cell goes out of safety spec
* @bug Can get the state inverted in certain cases (Relay on when plug out, and vice-versa), some additional logic should be put in to fix this
*/
void Core1::handleCharging(){
// Reordered to seperate the functionality for more flexibility in the algorithm later in the road
bool charge = handleChargingSafety();
charge = handleChargingInterrupt(charge);
if(charge == false){
digitalWrite(PIN_CHRG_EN, LOW);
OD_chargingEnabled = false;
//currentlyCharging = false; -- Don't do this here, this gives us hysteresis without this and fixes bug that when we lower voltage and remove plug it turns on
}
}
// This code is relatively untested due to being unable to test currents at home, please don't think this code works properly but take it as a basis to work off of
void Core1::updateMAH(){
newMeasTime = micros();
int pacManCurrent = (int)(currentSensor.getLoadCurrent(0.82)*PacManDisConst*1000); // Parameter is the shunt resistor value in Ohms - Measuring power consumed by PacMan
int dischargeCurrent = (int)(currentSensor.getADCInVoltage()*DischargeConst);
consumedMAH += (pacManCurrent*((newMeasTime-oldMeasTime)/1000000) + (dischargeCurrent*(newMeasTime-oldMeasTime)/1000000));
oldMeasTime = newMeasTime;
}
// Start main loop for thread
/**
* @brief The main loop for Core 1 thread
* Initialises various variables
* Discovers CellMen
* Quick Sorts discovered CellMen into voltage ascending over
* Begins main loop of:
* Updating CellMen Data
* Handling Charging
* Short delay to avoid triggering the Watchdog built into the ESP due to overloading Core1
*/
void Core1::start() {
if (DEBUG) printf("Core 1: Starting");
///// Initial Functions
unsigned char* tempCellData;
/* We know this because in the PacMan.ino file we start
the ESP32 with charging false and this occurs before we start checking */
currentlyCharging = false;
oldMeasTime = 0;
DischargeConst = 1;
PacManDisConst = 1;
ChargeConst = 1;
// Not really needed to zero the array of structures but why not
for (int i = 0; i < 16; i++) {
addressVoltages[i].address = 0x00;
addressVoltages[i].addressMinusVoltage = 0;
cellPositions[i]=i;
minusTerminalVoltages[i]=0;
}
if (DEBUG) printf("Core 1: Initalised & Zeroed AddressVoltages Array");
// Get all CellMan Addresses - loop discovering until we get some devices to prevent crashing of the CPU
numberOfDiscoveredCellMen = 0;
if (DEBUG) printf("Core 1: Beginning Discovery of CellMen on I2C Bus");
while (numberOfDiscoveredCellMen == 0) {
if(DEBUG) Serial.println("In the while loop, looking for CellMen");
numberOfDiscoveredCellMen = discoverCellMen();
}
if (DEBUG) printf("Core 1: Finished Discoverying CellMen");
if (DEBUG) {
Serial.print("Core 1: The number of address found: ");
Serial.println(numberOfDiscoveredCellMen);
}
// Put together addressVoltages array by requesting data from each cellman
if (DEBUG) printf("Core 1: Collecting Initial Data from CellMen for Location Calculation");
for (int i = 0; i < numberOfDiscoveredCellMen; i++) {
tempCellData = requestDataFromSlave(addresses[i], i, true);
addressVoltages[i].address = addresses[i];
addressVoltages[i].addressMinusVoltage = (uint16_t)((tempCellData[6] << 8) + tempCellData[5]);
if(DEBUG){
Serial.print("Cell 1: Address minus voltage for address ");
Serial.print(addressVoltages[i].address);
Serial.print(": ");
Serial.println(addressVoltages[i].addressMinusVoltage);
}
}
if (DEBUG) printf("Core 1: Quicksorting the AddressVoltage Array");
// for (int i = 0; i < numberOfDiscoveredCellMen; i++)
// {
// Serial.print("Index ");
// Serial.print(i);
// Serial.print(": ");
// Serial.print(addressVoltages[i].address);
// Serial.print(", ");
// Serial.println(addressVoltages[i].addressMinusVoltage);
// }
// Sort the addressVoltages by ascending voltages - Wow this bug fix took FOREVER, forgot the -1 (haha jouny) after the numberOfDiscoveredCellMen oof
addressVoltageQuickSort(addressVoltages, 0, numberOfDiscoveredCellMen - 1);
// Serial.println("After quicksort:");
// for (int i = 0; i < numberOfDiscoveredCellMen; i++)
// {
// Serial.print("Index ");
// Serial.print(i);
// Serial.print(": ");
// Serial.print(addressVoltages[i].address);
// Serial.print(", ");
// Serial.println(addressVoltages[i].addressMinusVoltage);
// }
// Flash the LEDs on each CellMen in position order
if (DEBUG) printf("Core 1: Flashing CellMen in Detected Order");
indicateCellMen();
///// Main Loop
if (DEBUG) printf("Core 1: Entering Main Loop");
for (;;) {
// Interrupt based updating of CellMen data and OD
updateCellMenData();
// Interrupt based charging detect method
handleCharging();
// High Priority Main Loop Code Here -- If empty put a fucking delay you faff
delay(10);
}
}
| 44.838926 | 199 | 0.650382 | [
"object",
"model"
] |
638c518eb4e9277568f14fb1a43cb671a388295b | 51,715 | cxx | C++ | com/ole32/com/moniker2/citemmon.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/ole32/com/moniker2/citemmon.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/ole32/com/moniker2/citemmon.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1993 - 1993.
//
// File: citemmon.cxx
//
// Contents: Implementation of CItemMoniker
//
// Classes:
//
// Functions:
//
// History: 12-27-93 ErikGav Created
// 01-14-94 KevinRo Updated so it actually works
// 06-14-94 Rickhi Fix type casting
// 10-13-95 stevebl threadsafty
//
//----------------------------------------------------------------------------
#include <ole2int.h>
#include "cbasemon.hxx"
#include "citemmon.hxx"
#include "cantimon.hxx"
#include "mnk.h"
#include <olepfn.hxx>
#include <rotdata.hxx>
INTERNAL RegisterContainerBound(LPBC pbc, LPOLEITEMCONTAINER pOleCont);
INTERNAL_(CItemMoniker *) IsItemMoniker( LPMONIKER pmk )
{
CItemMoniker *pIMk;
if ((pmk->QueryInterface(CLSID_ItemMoniker, (void **)&pIMk)) == S_OK)
{
// we release the AddRef done by QI, but still return the pointer
pIMk->Release();
return pIMk;
}
// dont rely on user implementations to set pIMk to NULL on failed QI.
return pIMk;
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::CItemMoniker
//
// Synopsis: Constructor
//
// Effects:
//
// Arguments: (none)
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-17-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
CItemMoniker::CItemMoniker() CONSTR_DEBUG
{
mnkDebugOut((DEB_ITRACE,
"CItemMoniker::CItemMoniker(%x)\n",
this));
m_lpszItem = NULL;
m_lpszDelimiter = NULL;
m_pszAnsiItem = NULL;
m_pszAnsiDelimiter = NULL;
m_fHashValueValid = FALSE;
m_ccItem = 0;
m_cbAnsiItem = 0;
m_cbAnsiDelimiter = 0;
m_ccDelimiter = 0;
m_dwHashValue = 0x12345678;
//
// CoQueryReleaseObject needs to have the address of the this objects
// query interface routine.
//
if (adwQueryInterfaceTable[QI_TABLE_CItemMoniker] == 0)
{
adwQueryInterfaceTable[QI_TABLE_CItemMoniker] =
**(ULONG_PTR **)((IMoniker *)this);
}
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::ValidateMoniker
//
// Synopsis: Check the consistency of this moniker
//
// Effects: In a DBG build, check to see if the member variables are
// sane values.
//
// Arguments: (none)
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-17-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
#if DBG == 1
void CItemMoniker::ValidateMoniker()
{
Assert( (m_lpszItem == NULL && m_ccItem == 0) ||
(m_ccItem == lstrlenW(m_lpszItem)));
Assert( (m_lpszDelimiter == NULL && m_ccDelimiter == 0) ||
(m_ccDelimiter == lstrlenW(m_lpszDelimiter)));
//
// cbAnsi* fields are NOT string lengths. However, the size of the
// buffer should be at least equal or bigger to the length of the
// Ansi part.
//
Assert( (m_pszAnsiItem == NULL && m_cbAnsiItem == 0) ||
(m_cbAnsiItem >= strlen(m_pszAnsiItem)+1));
Assert( (m_pszAnsiDelimiter == NULL && m_cbAnsiDelimiter == 0) ||
(m_cbAnsiDelimiter >= strlen(m_pszAnsiDelimiter)+1));
Assert( !m_fHashValueValid || (m_dwHashValue != 0x12345678) );
}
#endif
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::~CItemMoniker
//
// Synopsis:
//
// Effects:
//
// Arguments: [void] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-17-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
CItemMoniker::~CItemMoniker( void )
{
mnkDebugOut((DEB_ITRACE,
"CItemMoniker::~CItemMoniker(%x)\n",
this));
UnInit();
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::UnInit
//
// Synopsis: Uninitialize the Item moniker
//
// Effects: Free's path memory stored in Item Moniker.
//
// Arguments: (none)
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-16-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
void
CItemMoniker::UnInit()
{
mnkDebugOut((DEB_ITRACE,
"CItemMoniker::UnInit(%x)\n",
this));
ValidateMoniker();
if (m_lpszDelimiter != NULL)
{
PrivMemFree(m_lpszDelimiter);
m_lpszDelimiter = NULL;
m_ccDelimiter = 0;
}
if (m_pszAnsiDelimiter != NULL)
{
PrivMemFree(m_pszAnsiDelimiter);
m_pszAnsiDelimiter = NULL;
m_cbAnsiDelimiter = 0;
}
if (m_lpszItem != NULL)
{
PrivMemFree(m_lpszItem);
m_lpszItem = NULL;
m_ccItem = 0;
}
if (m_pszAnsiItem != NULL)
{
PrivMemFree(m_pszAnsiItem);
m_pszAnsiItem = NULL;
m_cbAnsiItem = 0;
}
m_fHashValueValid = FALSE;
m_dwHashValue = 0x12345678;
ValidateMoniker();
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::Initialize
//
// Synopsis: Initilaize an Item Moniker
//
// Effects: Clears the current state, then sets new state
//
// Arguments: [lpwcsDelimiter] -- Delimiter string
// [ccDelimiter] -- char count of delimiter
// [lpszAnsiDelimiter] -- Ansi version of delimiter
// [cbAnsiDelimiter] -- Count of bytes in AnsiDelimiter
// [lpwcsItem] -- Item string
// [ccItem] -- Count of characters in item string
// [lpszAnsiItem] -- Ansi version of item string
// [cbAnsiItem] -- Count of bytes in Ansi version
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-16-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
void
CItemMoniker::Initialize ( LPWSTR lpwcsDelimiter,
USHORT ccDelimiter,
LPSTR lpszAnsiDelimiter,
USHORT cbAnsiDelimiter,
LPWSTR lpwcsItem,
USHORT ccItem,
LPSTR lpszAnsiItem,
USHORT cbAnsiItem )
{
//
// OleLoadFromStream causes two inits; the member vars may already be set
// UnInit() will free existing resources
//
UnInit();
ValidateMoniker();
m_lpszItem = lpwcsItem;
m_ccItem = ccItem;
m_pszAnsiItem = lpszAnsiItem;
m_cbAnsiItem = cbAnsiItem;
m_lpszDelimiter = lpwcsDelimiter;
m_ccDelimiter = ccDelimiter;
m_pszAnsiDelimiter = lpszAnsiDelimiter;
m_cbAnsiDelimiter = cbAnsiDelimiter;
ValidateMoniker();
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::Initialize
//
// Synopsis: Initialize the contents of this moniker
//
// Effects:
// Copies the input parameters using PrivMemAlloc(), then passes them
// to the other version of Initialize, which takes control of the
// pointers.
//
// Arguments: [lpszDelimiter] --
// [lpszItemName] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-17-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
INTERNAL_(BOOL)
CItemMoniker::Initialize ( LPCWSTR lpszDelimiter,
LPCWSTR lpszItemName )
{
ValidateMoniker();
USHORT ccItem;
USHORT ccDelimiter;
LPWSTR pwcsDelimiter = NULL;
LPWSTR pwcsItem = NULL;
if (m_mxs.FInit() == FALSE)
{
goto errRet;
}
//VDATEPTRIN rejects NULL
if( lpszDelimiter )
{
GEN_VDATEPTRIN(lpszDelimiter,WCHAR, FALSE);
}
if( lpszItemName )
{
GEN_VDATEPTRIN(lpszItemName,WCHAR, FALSE);
}
if (FAILED(DupWCHARString(lpszDelimiter,
pwcsDelimiter,
ccDelimiter)))
{
goto errRet;
}
if (FAILED(DupWCHARString(lpszItemName,pwcsItem,ccItem)))
{
goto errRet;
}
Initialize(pwcsDelimiter,
ccDelimiter,
NULL,
0,
pwcsItem,
ccItem,
NULL,
0);
return TRUE;
errRet:
if (pwcsDelimiter != NULL)
{
PrivMemFree(pwcsDelimiter);
}
return(FALSE);
}
CItemMoniker FAR *CItemMoniker::Create (
LPCWSTR lpszDelimiter, LPCWSTR lpszItemName)
{
mnkDebugOut((DEB_ITRACE,
"CItemMoniker::Create() item(%ws) delim(%ws)\n",
lpszItemName,
lpszDelimiter));
//
// Parameter validation is handled in Initialize
//
CItemMoniker FAR * pCIM = new CItemMoniker();
if (pCIM)
{
if (pCIM->Initialize( lpszDelimiter, lpszItemName ))
return pCIM;
delete pCIM;
}
return NULL;
}
STDMETHODIMP CItemMoniker::QueryInterface (THIS_ REFIID riid,
LPVOID FAR* ppvObj)
{
VDATEIID (riid);
VDATEPTROUT(ppvObj, LPVOID);
*ppvObj = NULL;
#ifdef _DEBUG
if (riid == IID_IDebug)
{
*ppvObj = &(m_Debug);
return NOERROR;
}
#endif
if (IsEqualIID(riid, CLSID_ItemMoniker))
{
// called by IsItemMoniker.
AddRef();
*ppvObj = this;
return S_OK;
}
return CBaseMoniker::QueryInterface(riid, ppvObj);
}
STDMETHODIMP CItemMoniker::GetClassID (LPCLSID lpClassId)
{
VDATEPTROUT(lpClassId, CLSID);
*lpClassId = CLSID_ItemMoniker;
return NOERROR;
}
//+---------------------------------------------------------------------------
//
// Function: WriteDoubleString
//
// Synopsis: Writes a double string to stream. See ExtractUnicodeString
//
// Effects:
//
// Arguments: [pStm] --
// [pwcsWide] --
// [ccWide] --
// [pszAnsi] --
// [cbAnsi] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 1-16-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
HRESULT
WriteDoubleString( LPSTREAM pStm,
LPWSTR pwcsWide,
USHORT ccWide,
LPSTR pszAnsi,
USHORT cbAnsi)
{
mnkDebugOut((DEB_ITRACE,
"WriteDoubleString pwcsWide(%ws) cbWide(0x%x) psz(%s) cb(0x%x)\n",
pwcsWide?pwcsWide:L"<NULL>",
ccWide,
pszAnsi?pszAnsi:"<NULL>",
cbAnsi));
HRESULT hr;
//
// The string size is always written, but not including the size of the
// preceding DWORD so we conform to the way WriteAnsiString does it
//
ULONG ulTotalSize = 0;
//
// The entire reason we are supposed to be in this routine is that the
// pwcsWide could not be converted to ANSI. Therefore, it had better
// be valid.
//
Assert( (pwcsWide != NULL) && (ccWide == lstrlenW(pwcsWide)));
Assert( (pszAnsi == NULL) || (cbAnsi == (strlen(pszAnsi) + 1)));
ulTotalSize += ccWide * sizeof(WCHAR);
// Lets assume most ItemStrings will fit in this buffer
BYTE achQuickBuffer[256];
BYTE *pcbQuickBuffer = achQuickBuffer;
//
// Since we are going to cheat, and write something to the back of the
// ANSI string, the ANSI string must contain at least a NULL character.
// If it doesn't, we are going to cheat one in.
//
if (pszAnsi == NULL)
{
ulTotalSize += sizeof(char);
}
else
{
ulTotalSize += cbAnsi;
}
//
// If we don't fit in the QuickBuffer, allocate some memory
//
// 1996.4.24 v-hidekk
if ((ulTotalSize + sizeof(ULONG)) > sizeof(achQuickBuffer))
{
pcbQuickBuffer = (BYTE *)PrivMemAlloc((ulTotalSize + sizeof(ULONG)));
if (pcbQuickBuffer == NULL)
{
return(E_OUTOFMEMORY);
}
}
//
// First DWORD in the buffer is the total size of the string. This
// value includes strlen's of both strings, plus the size of the NULL
// on the Ansi string.
//
// Intrinsics will make this into a move of the correct alignment.
// Casting pcbQuickBuffer to a ULONG pointer is dangerous, since
// the alignment may be incorrect. Let the compiler figure out the
// correct thing to do.
//
memcpy(pcbQuickBuffer,&ulTotalSize,sizeof(ulTotalSize));
//
// Here, we make sure that pszAnsi ends up writing at least the NULL
// character
//
ULONG ulAnsiWritten;
memcpy(pcbQuickBuffer + sizeof(ulTotalSize),
pszAnsi?pszAnsi:"",
ulAnsiWritten = pszAnsi?cbAnsi:1);
//
// At this point, there should be a ULONG followed by at least 1
// character. The pointer arithmetic below puts us just past the
// null terminator of the Ansi string
//
memcpy(pcbQuickBuffer + sizeof(ulTotalSize) + ulAnsiWritten,
pwcsWide,
ccWide * sizeof(WCHAR));
mnkDebugOut((DEB_ITRACE,
"WriteDoubleString ulTotalSize(0x%x)\n",
ulTotalSize));
hr = pStm->Write(pcbQuickBuffer, ulTotalSize + sizeof(ULONG) ,NULL);
if (pcbQuickBuffer != achQuickBuffer)
{
PrivMemFree(pcbQuickBuffer);
}
return(hr);
}
//+---------------------------------------------------------------------------
//
// Function: ExtractUnicodeString
//
// Synopsis: Given an ANSI string buffer, return a UNICODE path
//
// Effects:
// If it exists, this routine will extract the UNICODE section
// of a string written out in the following format:
//
// <ANSI string><0><UNICODESTRING>
// ^ cbAnsiString ^
//
//
// If the UNICODE string doesn't exist, then the Ansi string is converted
// to UNICODE and returned
//
// Arguments: [pszAnsiString] -- Ansi string with potential UNICODE end
// [cbAnsiString] -- Total number of bytes in pszAnsiString
// [pwcsWideString] -- Reference to output string pointer
// [ccWideString] -- Reference to output cound of characters
//
// Requires:
//
// Returns:
// pwcsWideString will be a PrivMemAlloc()'d UNICODE string
// ccWideString will be the character count (excluding the NULL)
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 1-16-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
HRESULT ExtractUnicodeString(LPSTR pszAnsiString,
USHORT cbAnsiString,
LPWSTR & pwcsString,
USHORT & ccString)
{
mnkDebugOut((DEB_ITRACE,
"ExtractUnicodeString pszAnsi(%s) cbAnsi(0x%x)\n",
ANSICHECK(pszAnsiString),
cbAnsiString));
USHORT cbAnsiStrLen;
HRESULT hr;
//
// If the Ansi string is NULL, then the Wide char will be also
//
if (pszAnsiString == NULL)
{
pwcsString = NULL;
ccString = 0;
return(NOERROR);
}
Assert( pwcsString == NULL);
//
// If strlen(pszAnsiString)+1 == cbAnsiString, then there is no
// UNICODE extent.
//
cbAnsiStrLen = (USHORT)strlen(pszAnsiString);
if ((cbAnsiStrLen + 1) == cbAnsiString)
{
//
// There is not a UNICODE extent. Convert from Ansi to UNICODE
//
pwcsString = NULL;
hr= MnkMultiToUnicode(pszAnsiString,
pwcsString,
0,
ccString,
CP_ACP);
mnkDebugOut((DEB_ITRACE,
"ExtractUnicodeString converted (%s) to (%ws) ccString(0x%x)\n",
ANSICHECK(pszAnsiString),
WIDECHECK(pwcsString),
ccString));
}
else
{
mnkDebugOut((DEB_ITRACE,
"ExtractUnicodeString found UNICODE extent\n"));
//
// There are extra characters following the AnsiString. Make a
// new buffer to copy them. Don't forget to add an extra WCHAR for
// the NULL termination
//
// AnsiStrLen + AnsiNull char
USHORT cbWideString = cbAnsiString - (cbAnsiStrLen + 1);
Assert(cbWideString != 0);
//
// There had best be an even number of bytes, or else something
// has gone wrong.
//
Assert( ! (cbWideString & 1));
// Strlen + sizeof(1 NULL char)
pwcsString = (WCHAR *) PrivMemAlloc(cbWideString + sizeof(WCHAR));
if (pwcsString == NULL)
{
hr = E_OUTOFMEMORY;
goto errRet;
}
memcpy(pwcsString,pszAnsiString + cbAnsiStrLen + 1, cbWideString);
ccString = cbWideString / sizeof(WCHAR);
pwcsString[ccString] = 0;
hr = NOERROR;
}
errRet:
mnkDebugOut((DEB_ITRACE,
"ExtractUnicodeString result hr(%x) pwcsString(%ws) ccString(0x%x)\n",
hr,
WIDECHECK(pwcsString),
ccString));
return(hr);
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::Load
//
// Synopsis: Loads an Item moniker from a stream
//
// Effects: The first version of CItemMoniker stored two counted strings
// in the stream. Both were stored in ANSI.
//
// This version saves a UNICODE string on the end of the ANSI
// string. Therefore, when it is read back in, the count of
// bytes read as the ANSI string may include a UNICODE string.
//
// See ::Save() for more details.
//
//
// Arguments: [pStm] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-16-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
STDMETHODIMP CItemMoniker::Load (LPSTREAM pStm)
{
mnkDebugOut((DEB_ITRACE,
"CItemMoniker::Load(%x)\n",
this));
VDATEIFACE(pStm);
ValidateMoniker();
HRESULT hresult;
LPSTR pszAnsiItem = NULL;
LPSTR pszAnsiDelim = NULL;
LPWSTR pwcsItem = NULL;
LPWSTR pwcsDelim = NULL;
USHORT cbAnsiDelim;
USHORT cbAnsiItem;
USHORT ccDelim;
USHORT ccItem;
//
// First, read in the two strings into the Ansi versions
//
hresult = ReadAnsiStringStream( pStm, pszAnsiDelim,cbAnsiDelim );
if (hresult != NOERROR)
{
goto errRet;
}
mnkDebugOut((DEB_ITRACE,
"::Load(%x) pszAnsiDelim(%s) cbAnsiDelim(0x%x)\n",
this,
pszAnsiDelim,
cbAnsiDelim));
hresult = ReadAnsiStringStream( pStm, pszAnsiItem, cbAnsiItem );
if (hresult != NOERROR)
{
goto errRet;
}
mnkDebugOut((DEB_ITRACE,
"::Load(%x) pszAnsiItem(%s) cbAnsiItem(0x%x)\n",
this,
pszAnsiItem,
cbAnsiItem));
//
// Now, determine the UNICODE strings. They may be stashed at the
// end of the Ansi strings.
//
hresult = ExtractUnicodeString(pszAnsiDelim,
cbAnsiDelim,
pwcsDelim,
ccDelim);
if (FAILED(hresult))
{
goto errRet;
}
hresult = ExtractUnicodeString(pszAnsiItem,
cbAnsiItem,
pwcsItem,
ccItem);
if (FAILED(hresult))
{
goto errRet;
}
Initialize ( pwcsDelim,
ccDelim,
pszAnsiDelim,
cbAnsiDelim,
pwcsItem,
ccItem,
pszAnsiItem,
cbAnsiItem );
ValidateMoniker();
return(NOERROR);
errRet:
PrivMemFree(pszAnsiItem);
PrivMemFree(pszAnsiDelim);
PrivMemFree(pwcsItem);
PrivMemFree(pwcsDelim);
return hresult;
}
//+---------------------------------------------------------------------------
//
// Function: SaveUnicodeAsAnsi
//
// Synopsis: This function will save a string to the stream
//
// Effects:
// This routine always attempts to save the string in Ansi. If it isn't
// possible to save an Ansi version of the string, it will save an
// Ansi version (which may be NULL), and a UNICODE version.
//
// Arguments: [pStm] -- Stream to write to
// [pwcsWide] -- Unicode string
// [ccWide] -- Count of UNICODE characters (EXCL NULL)
// [pszAnsi] -- Ansi string
// [cbAnsi] -- Count of bytes (INCL NULL)
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 1-17-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
HRESULT SaveUnicodeAsAnsi( LPSTREAM pStm,
LPWSTR pwcsWide,
USHORT ccWide,
LPSTR pszAnsi,
USHORT cbAnsi)
{
mnkDebugOut((DEB_ITRACE,
"::SaveUnicodeAsAnsi pwcsWide(%ws) ccWide(0x%x) pwsAnsi(%s) cbAnsi(0x%x)\n",
WIDECHECK(pwcsWide),
ccWide,
ANSICHECK(pszAnsi),
cbAnsi));
HRESULT hr;
BOOL fFastConvert;
//
// If the Ansi version exists, or the Unicode string is NULL,
// write out the Ansi version
//
if ((pszAnsi != NULL) || (pwcsWide == NULL))
{
mnkDebugOut((DEB_ITRACE,
"::SaveUnicodeAsAnsi Ansi Only (%s)\n",
ANSICHECK(pszAnsi)));
hr = WriteAnsiStringStream( pStm,
pszAnsi,
cbAnsi);
}
else
{
//
// There isn't an AnsiVersion, and the UNICODE version isn't NULL
// Try to convert the UNICODE to Ansi
//
Assert( (pwcsWide != NULL) &&
(ccWide == lstrlenW(pwcsWide)));
mnkDebugOut((DEB_ITRACE,
"::SaveUnicodeAsAnsi Unicode string exists(%ws)\n",
WIDECHECK(pwcsWide)));
//
// We can use the pszAnsi pointer since it is NULL
//
Assert( pszAnsi == NULL);
hr = MnkUnicodeToMulti( pwcsWide,
ccWide,
pszAnsi,
cbAnsi,
fFastConvert);
Assert( (pszAnsi == NULL) || (cbAnsi == strlen(pszAnsi)+1) );
//
// A failure would mean out of memory, or some other terrible thing
// happened.
//
if (FAILED(hr))
{
goto errRet;
}
//
// If fFastConvert, then the UnicodeString was converted using a
// truncation algorithm, and the resulting Ansi string can be saved
// without the Unicode section appended
//
if (fFastConvert)
{
mnkDebugOut((DEB_ITRACE,
"::SaveUnicodeAsAnsi Fast converted wide(%ws) to (%s) cbAnsi(0x%x)\n",
WIDECHECK(pwcsWide),
ANSICHECK(pszAnsi),
cbAnsi));
hr = WriteAnsiStringStream( pStm,
pszAnsi,
cbAnsi);
}
else
{
mnkDebugOut((DEB_ITRACE,
"::SaveUnicodeAsAnsi Full conversion wide(%ws) to (%s) cbAnsi(0x%x)\n",
WIDECHECK(pwcsWide),
ANSICHECK(pszAnsi),
cbAnsi));
hr = WriteDoubleString( pStm,
pwcsWide,
ccWide,
pszAnsi,
cbAnsi);
}
//
// We are done with the Ansi string.
//
// (KevinRo) It would be nice if we could get the double
// string back from WriteDoubleString and cache it. Perhaps later
// this can be done. [Suggestion]
//
PrivMemFree(pszAnsi);
}
errRet:
return(hr);
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::Save
//
// Synopsis: Save the moniker to a stream
//
// Effects: The first version of CItemMoniker stored two counted strings
// in the stream. Both were stored in ANSI.
//
// This version saves a UNICODE string on the end of the ANSI
// string. Therefore, when it is read back in, the count of
// bytes read as the ANSI string may include a UNICODE string.
//
// We don't actually write the UNICODE string unless we have
// to.
//
// Arguments: [pStm] --
// [fClearDirty] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-16-94 kevinro Created
//
// Notes:
//
// There are two ways to create a CItemMoniker. Using CreateItemMoniker(),
// and Load().
//
// If we were Load()'d, then it will be the case that we already have an
// Ansi version of both strings. In this case, we will just save those
// Ansi strings back out. If they already contain the UNICODE sections,
// then they are saved as part of the package. Hopefully, this will be
// the common case.
//
// Another possibility is the moniker was created using CreateItemMoniker.
// If this is the case, then there are no Ansi versions of the strings.
// We need to create Ansi strings, if possible. If we can't convert the
// string to Ansi cleanly, then we need to save away a UNICODE section
// of the string.
//
//----------------------------------------------------------------------------
STDMETHODIMP CItemMoniker::Save (LPSTREAM pStm, BOOL fClearDirty)
{
mnkDebugOut((DEB_ITRACE,
"CItemMoniker::Save(%x)\n",
this));
ValidateMoniker();
VDATEIFACE(pStm);
UNREFERENCED(fClearDirty);
HRESULT hr;
//
// If a AnsiDelimiter exists, OR the UNICODE version is NULL, then
// write out the Ansi version
//
hr = SaveUnicodeAsAnsi( pStm,
m_lpszDelimiter,
m_ccDelimiter,
m_pszAnsiDelimiter,
m_cbAnsiDelimiter);
if (FAILED(hr))
{
mnkDebugOut((DEB_ITRACE,
"CItemMoniker::Save(%x) SaveUnicodeAsAnsi Delim failed (%x)\n",
this,
hr));
goto errRet;
}
hr = SaveUnicodeAsAnsi( pStm,
m_lpszItem,
m_ccItem,
m_pszAnsiItem,
m_cbAnsiItem);
if (FAILED(hr))
{
mnkDebugOut((DEB_ITRACE,
"CItemMoniker::Save(%x) SaveUnicodeAsAnsi Item failed (%x)\n",
this,
hr));
goto errRet;
}
errRet:
return hr;
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::GetSizeMax
//
// Synopsis: Get the maximum size required to serialize this moniker
//
// Effects:
//
// Arguments: [pcbSize] -- Place to return value
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-17-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
STDMETHODIMP CItemMoniker::GetSizeMax (ULARGE_INTEGER FAR* pcbSize)
{
ValidateMoniker();
VDATEPTROUT(pcbSize, ULARGE_INTEGER);
UINT cb = 0;
//
// The largest a UNICODE to MBSTRING should end up being is
// 2 * character count.
//
if (m_lpszItem)
{
cb = (m_ccItem + 1) * 2 * sizeof(WCHAR);
}
if (m_lpszDelimiter)
{
cb += (m_ccDelimiter + 1) * 2 * sizeof(WCHAR);
}
//
// sizeof(CLSID) accounts for the GUID that OleSaveToStream might
// write on our behalf. The two ULONGs are the string lengths,
// and cb is the max string sizes.
//
ULISet32(*pcbSize, sizeof(CLSID) + 2*(1 + sizeof(ULONG)) + cb);
return(NOERROR);
}
#define dwModerateTime 2500
// 2.5 seconds divides immediate from moderate.
DWORD BindSpeedFromBindCtx( LPBC pbc )
{
BIND_OPTS bindopts;
HRESULT hresult;
DWORD dwBindSpeed = BINDSPEED_INDEFINITE;
bindopts.cbStruct = sizeof(bindopts);
hresult = pbc->GetBindOptions( &bindopts );
if (hresult != NOERROR) return dwBindSpeed;
Assert( bindopts.cbStruct >= 16);
if (bindopts.dwTickCountDeadline != 0)
{
if (bindopts.dwTickCountDeadline < dwModerateTime)
dwBindSpeed = BINDSPEED_IMMEDIATE;
else dwBindSpeed = BINDSPEED_MODERATE;
}
// else speed = default, BINDSPEED_INDEFINITE
return dwBindSpeed;
}
STDMETHODIMP CItemMoniker::BindToObject ( LPBC pbc,
LPMONIKER pmkToLeft, REFIID iidResult,
VOID FAR * FAR * ppvResult)
{
M_PROLOG(this);
VDATEPTROUT(ppvResult, LPVOID);
*ppvResult = NULL;
VDATEIFACE(pbc);
if (pmkToLeft) VDATEIFACE(pmkToLeft);
VDATEIID(iidResult);
ValidateMoniker();
HRESULT hresult;
LPOLEITEMCONTAINER pOleCont;
if (pmkToLeft)
{
hresult = pmkToLeft->BindToObject( pbc, NULL, IID_IOleItemContainer,
(LPVOID FAR*)&pOleCont);
// AssertOutPtrIface(hresult, pOleCont);
if (hresult != NOERROR) return hresult;
hresult = RegisterContainerBound(pbc, pOleCont);
hresult = pOleCont->GetObject(m_lpszItem, BindSpeedFromBindCtx(pbc),
pbc, iidResult, ppvResult);
// AssertOutPtrIface(hresult, *ppvResult);
pOleCont->Release();
return hresult;
}
return ResultFromScode(E_INVALIDARG); // needs non-null moniker to left.
}
STDMETHODIMP CItemMoniker::BindToStorage (LPBC pbc, LPMONIKER
pmkToLeft, REFIID riid, LPVOID FAR* ppvObj)
{
M_PROLOG(this);
VDATEPTROUT(ppvObj,LPVOID);
*ppvObj = NULL;
VDATEIFACE(pbc);
if (pmkToLeft) VDATEIFACE(pmkToLeft);
VDATEIID(riid);
HRESULT hresult;
LPOLEITEMCONTAINER pOleCont;
ValidateMoniker();
if (pmkToLeft)
{
hresult = pmkToLeft->BindToObject( pbc, NULL, IID_IOleItemContainer,
(LPVOID FAR*)&pOleCont);
// AssertOutPtrIface(hresult, pOleCont);
if (hresult != NOERROR) return hresult;
hresult = RegisterContainerBound(pbc, pOleCont);
hresult = pOleCont->GetObjectStorage(m_lpszItem, pbc,
riid, ppvObj);
// AssertOutPtrIface(hresult, *ppvObj);
pOleCont->Release();
return hresult;
}
return ResultFromScode(E_INVALIDARG); // needs non-null moniker to left.
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::ComposeWith
//
// Synopsis: Compose this moniker with another moniker
//
// Effects:
//
// Arguments: [pmkRight] --
// [fOnlyIfNotGeneric] --
// [ppmkComposite] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 2-04-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
STDMETHODIMP CItemMoniker::ComposeWith ( LPMONIKER pmkRight,
BOOL fOnlyIfNotGeneric, LPMONIKER FAR* ppmkComposite)
{
VDATEPTROUT(ppmkComposite,LPMONIKER);
*ppmkComposite = NULL;
VDATEIFACE(pmkRight);
HRESULT hresult = NOERROR;
ValidateMoniker();
//
// If this is an AntiMoniker, then we are going to ask the AntiMoniker
// for the composite. This is a backward compatibility problem. Check
// out the CAntiMoniker::EatOne() routine for details.
//
CAntiMoniker *pCAM = IsAntiMoniker(pmkRight);
if (pCAM)
{
pCAM->EatOne(ppmkComposite);
}
else
{
if (!fOnlyIfNotGeneric)
{
hresult = CreateGenericComposite( this, pmkRight, ppmkComposite );
}
else
{
hresult = ResultFromScode(MK_E_NEEDGENERIC);
*ppmkComposite = NULL;
}
}
return hresult;
}
STDMETHODIMP CItemMoniker::Enum (THIS_ BOOL fForward, LPENUMMONIKER FAR* ppenumMoniker)
{
M_PROLOG(this);
VDATEPTROUT(ppenumMoniker,LPENUMMONIKER);
*ppenumMoniker = NULL;
noError;
}
STDMETHODIMP CItemMoniker::IsEqual (THIS_ LPMONIKER pmkOtherMoniker)
{
M_PROLOG(this);
VDATEIFACE(pmkOtherMoniker);
ValidateMoniker();
CItemMoniker FAR* pCIM = IsItemMoniker(pmkOtherMoniker);
if (!pCIM)
return ResultFromScode(S_FALSE);
// the other moniker is a item moniker.
// for the names, we do a case-insensitive compare.
if (m_lpszItem && pCIM->m_lpszItem)
{
if (0 == lstrcmpiW(pCIM->m_lpszItem, m_lpszItem))
return NOERROR; // S_TRUE;
}
else
return (m_lpszItem || pCIM->m_lpszItem ? ResultFromScode(S_FALSE ) : NOERROR /*S_TRUE*/);
return ResultFromScode(S_FALSE);
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::Hash
//
// Synopsis: Compute a hash value
//
// Effects: Computes a hash using the same basic algorithm as the
// file moniker.
//
// Arguments: [pdwHash] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-17-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
STDMETHODIMP CItemMoniker::Hash (THIS_ LPDWORD pdwHash)
{
CLock2 lck(m_mxs); // protect m_fHashValueValid and m_dwHashValue
VDATEPTROUT(pdwHash, DWORD);
ValidateMoniker();
if (m_fHashValueValid == FALSE)
{
m_dwHashValue = CalcFileMonikerHash(m_lpszItem, m_ccItem);
m_fHashValueValid = TRUE;
}
*pdwHash = m_dwHashValue;
return(NOERROR);
}
STDMETHODIMP CItemMoniker::IsRunning (THIS_ LPBC pbc, LPMONIKER pmkToLeft,
LPMONIKER pmkNewlyRunning)
{
VDATEIFACE (pbc);
HRESULT hresult;
if (pmkToLeft)
VDATEIFACE (pmkToLeft);
if (pmkNewlyRunning)
VDATEIFACE (pmkNewlyRunning);
LPMONIKER pmk = NULL;
LPOLEITEMCONTAINER pCont = NULL;
LPRUNNINGOBJECTTABLE prot = NULL;
if (pmkToLeft == NULL)
{
if (pmkNewlyRunning != NULL)
{
hresult = IsEqual(pmkNewlyRunning);
if (hresult == NOERROR) goto errRet;
hresult = IsEqual(pmkNewlyRunning);
if (hresult != NOERROR)
{
hresult = ResultFromScode(S_FALSE);
goto errRet;
}
}
pbc->GetRunningObjectTable( &prot );
// check to see if "this" is in ROT
hresult = prot->IsRunning(this);
goto errRet;
}
hresult = pmkToLeft->IsRunning(pbc, NULL, NULL);
if (hresult == NOERROR)
{
hresult = pmkToLeft->BindToObject(pbc, NULL, IID_IOleItemContainer,
(LPVOID FAR *)&pCont );
if (hresult == NOERROR)
{
// don't use RegisterContainerBound(pbc, pCont) here since we
// will lock/unlock the container unecessarily and possibly
// shut it down.
hresult = pbc->RegisterObjectBound(pCont);
if (hresult != NOERROR) goto errRet;
hresult = pCont->IsRunning(m_lpszItem);
}
}
errRet:
if (pCont) pCont->Release();
if (prot) prot->Release();
return hresult;
}
STDMETHODIMP CItemMoniker::GetTimeOfLastChange (THIS_ LPBC pbc, LPMONIKER pmkToLeft,
FILETIME FAR* pfiletime)
{
M_PROLOG(this);
VDATEIFACE(pbc);
if (pmkToLeft) VDATEIFACE(pmkToLeft);
VDATEPTROUT(pfiletime, FILETIME);
ValidateMoniker();
HRESULT hresult;
LPMONIKER pmkTemp = NULL;
LPRUNNINGOBJECTTABLE prot = NULL;
if (pmkToLeft == NULL)
return ResultFromScode(MK_E_NOTBINDABLE);
// Getting time of last change
// for an orphan item moniker.
// Check to see if the composite is in the running object table
hresult = CreateGenericComposite( pmkToLeft, this, &pmkTemp );
if (hresult != NOERROR) goto errRet;
hresult = pbc->GetRunningObjectTable(& prot);
if (hresult != NOERROR) goto errRet;
hresult = prot->GetTimeOfLastChange( pmkTemp, pfiletime);
if (hresult != MK_E_UNAVAILABLE) goto errRet;
// if not, pass on to the left.
hresult = pmkToLeft->GetTimeOfLastChange(pbc, NULL, pfiletime);
errRet:
if (pmkTemp) pmkTemp->Release();
if (prot) prot->Release();
return hresult;
}
STDMETHODIMP CItemMoniker::Inverse (THIS_ LPMONIKER FAR* ppmk)
{
M_PROLOG(this);
VDATEPTROUT(ppmk, LPMONIKER);
return CreateAntiMoniker(ppmk);
}
STDMETHODIMP CItemMoniker::CommonPrefixWith (LPMONIKER pmkOther, LPMONIKER FAR*
ppmkPrefix)
{
ValidateMoniker();
VDATEPTROUT(ppmkPrefix,LPMONIKER);
*ppmkPrefix = NULL;
VDATEIFACE(pmkOther);
if (!IsItemMoniker(pmkOther))
{
return(MonikerCommonPrefixWith(this,pmkOther,ppmkPrefix));
}
if (NOERROR == IsEqual(pmkOther))
{
*ppmkPrefix = this;
AddRef();
return ResultFromScode(MK_S_US);
}
return ResultFromScode(MK_E_NOPREFIX);
}
STDMETHODIMP CItemMoniker::RelativePathTo (THIS_ LPMONIKER pmkOther, LPMONIKER FAR*
ppmkRelPath)
{
ValidateMoniker();
VDATEPTROUT(ppmkRelPath,LPMONIKER);
*ppmkRelPath = NULL;
VDATEIFACE(pmkOther);
return ResultFromScode(MK_E_NOTBINDABLE);
}
STDMETHODIMP CItemMoniker::GetDisplayName ( LPBC pbc, LPMONIKER
pmkToLeft, LPWSTR FAR * lplpszDisplayName )
{
mnkDebugOut((DEB_ITRACE,
"CItemMoniker::GetDisplayName(%x)\n",
this));
ValidateMoniker();
VDATEPTROUT(lplpszDisplayName, LPWSTR);
*lplpszDisplayName = NULL;
VDATEIFACE(pbc);
if (pmkToLeft)
{
VDATEIFACE(pmkToLeft);
}
ULONG cc = m_ccItem + m_ccDelimiter;
//
// cc holds the count of characters. Make extra room for the NULL
//
*lplpszDisplayName = (LPWSTR) CoTaskMemAlloc(sizeof(WCHAR)*(1 + cc));
if (*lplpszDisplayName == NULL)
{
mnkDebugOut((DEB_ITRACE,
"::GetDisplayName(%x) returning out of memory\n",
this));
return E_OUTOFMEMORY;
}
//
// To handle the case where both strings are NULL, we set the first
// (and perhaps only) character to 0
//
*lplpszDisplayName[0] = 0;
//
// Concat the two strings. Don't forget the NULL! Thats what the
// extra character is for.
//
if (m_lpszDelimiter != NULL)
{
memcpy( *lplpszDisplayName,
m_lpszDelimiter,
(m_ccDelimiter + 1) * sizeof(WCHAR));
}
//
// The existing string was NULL terminated to just in case the
// Item string is NULL.
//
// Concat the Item string on the end of the Delimiter Again, don't
// forget the NULL.
//
if (m_lpszItem != NULL)
{
memcpy( *lplpszDisplayName + m_ccDelimiter,
m_lpszItem,
(m_ccItem + 1) * sizeof(WCHAR));
}
mnkDebugOut((DEB_ITRACE,
"::GetDisplayName(%x) returning %ws\n",
this,
*lplpszDisplayName));
return(NOERROR);
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::ParseDisplayName
//
// Synopsis:
//
// Effects:
//
// Arguments: [pbc] -- Bind Context
// [pmkToLeft] -- Left moniker
// [lpszDisplayName] -- String to parse
// [pchEaten] -- Output number of characters eaten
// [ppmkOut] -- Output moniker
//
// Requires:
// pmkToLeft MUST be valid. NULL is inappropriate
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 2-03-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
STDMETHODIMP CItemMoniker::ParseDisplayName ( LPBC pbc,
LPMONIKER pmkToLeft,
LPWSTR lpszDisplayName,
ULONG FAR* pchEaten,
LPMONIKER FAR* ppmkOut)
{
HRESULT hresult;
VDATEPTRIN(lpszDisplayName, WCHAR);
VDATEPTROUT(pchEaten,ULONG);
VDATEPTROUT(ppmkOut,LPMONIKER);
IParseDisplayName FAR * pPDN = NULL;
IOleItemContainer FAR * pOIC = NULL;
ValidateMoniker();
*pchEaten = 0;
*ppmkOut = NULL;
VDATEIFACE(pbc);
//
// Item monikers require the moniker on the left to be non-null, so
// they can get the container to parse the display name
//
if (pmkToLeft != NULL)
{
VDATEIFACE(pmkToLeft);
}
else
{
hresult = MK_E_SYNTAX;
goto errRet;
}
hresult = pmkToLeft->BindToObject( pbc,
NULL,
IID_IOleItemContainer,
(VOID FAR * FAR *)&pOIC );
if (FAILED(hresult))
{
goto errRet;
}
hresult = RegisterContainerBound(pbc, pOIC);
if (FAILED(hresult))
{
goto errRet;
}
hresult = pOIC->GetObject( m_lpszItem,
BindSpeedFromBindCtx(pbc),
pbc,
IID_IParseDisplayName,
(LPVOID FAR*)&pPDN);
if (FAILED(hresult))
{
goto errRet;
}
hresult = pPDN->ParseDisplayName(pbc,
lpszDisplayName,
pchEaten,
ppmkOut );
if (FAILED(hresult))
{
goto errRet;
}
hresult = pbc->RegisterObjectBound( pPDN );
errRet:
if (pPDN)
{
pPDN->Release();
}
if (pOIC)
{
pOIC->Release();
}
return hresult;
}
STDMETHODIMP CItemMoniker::IsSystemMoniker (THIS_ LPDWORD pdwType)
{
M_PROLOG(this);
VDATEPTROUT(pdwType,DWORD);
*pdwType = MKSYS_ITEMMONIKER;
return NOERROR;
}
//+---------------------------------------------------------------------------
//
// Method: CItemMoniker::GetComparisonData
//
// Synopsis: Get comparison data for registration in the ROT
//
// Arguments: [pbData] - buffer to put the data in.
// [cbMax] - size of the buffer
// [pcbData] - count of bytes used in the buffer
//
// Returns: NOERROR
// E_OUTOFMEMORY
//
// Algorithm: Build the ROT data from internal data of the item moniker.
//
// History: 03-Feb-95 ricksa Created
//
// Note: Validating the arguments is skipped intentionally because this
// will typically be called internally by OLE with valid buffers.
//
//----------------------------------------------------------------------------
STDMETHODIMP CItemMoniker::GetComparisonData(
byte *pbData,
ULONG cbMax,
DWORD *pcbData)
{
//
// CLSID plus delimiter plus item plus one NULL
//
ULONG ulLength = sizeof(CLSID_ItemMoniker) +
(m_ccItem + m_ccDelimiter + 1) * sizeof(WCHAR);
Assert(pcbData != NULL);
Assert(pbData != NULL);
if (cbMax < ulLength)
{
return(E_OUTOFMEMORY);
}
//
// Copy the classID
//
memcpy(pbData,&CLSID_ItemMoniker,sizeof(CLSID_FileMoniker));
//
// Copy the delimiter WITHOUT the NULL. This saves a little space,
// and allows us to uppercase them both as a single string
//
memcpy(pbData+sizeof(CLSID_FileMoniker),
m_lpszDelimiter,
m_ccDelimiter * sizeof(WCHAR));
//
// Copy the item plus the NULL
//
memcpy(pbData+sizeof(CLSID_FileMoniker)+(m_ccDelimiter * sizeof(WCHAR)),
m_lpszItem,
(m_ccItem + 1)*sizeof(WCHAR));
//
// Insure entire string is upper case, since the item monikers are spec'd
// (and already do) case insensitive comparisions
//
CharUpperW((WCHAR *)(pbData+sizeof(CLSID_FileMoniker)));
*pcbData = ulLength;
return NOERROR;
}
#ifdef _DEBUG
STDMETHODIMP_(void) NC(CItemMoniker,CDebug)::Dump ( IDebugStream FAR * pdbstm)
{
VOID_VDATEIFACE(pdbstm);
*pdbstm << "CItemMoniker @" << (VOID FAR *)m_pItemMoniker;
*pdbstm << '\n';
pdbstm->Indent();
*pdbstm << "Refcount is " << (int)(m_pItemMoniker->m_refs) << '\n';
*pdbstm << "Item string is " << m_pItemMoniker->m_lpszItem << '\n';
*pdbstm << "Delimiter is " << m_pItemMoniker->m_lpszDelimiter << '\n';
pdbstm->UnIndent();
}
STDMETHODIMP_(BOOL) NC(CItemMoniker,CDebug)::IsValid ( BOOL fSuspicious )
{
return ((LONG)(m_pItemMoniker->m_refs) > 0);
// add more later, maybe
}
#endif
//
// Unlock Delay object
//
class FAR CDelayUnlockContainer : public CPrivAlloc, public IUnknown
{
public:
STDMETHOD(QueryInterface) ( REFIID iid, LPVOID FAR* ppvObj);
STDMETHOD_(ULONG,AddRef) (void);
STDMETHOD_(ULONG,Release) (void);
CDelayUnlockContainer();
private:
ULONG m_refs;
IOleItemContainer FAR * m_pOleCont;
friend INTERNAL RegisterContainerBound(LPBC pbc, LPOLEITEMCONTAINER pOleCont);
};
CDelayUnlockContainer::CDelayUnlockContainer()
{
m_pOleCont = NULL;
m_refs = 1;
}
STDMETHODIMP CDelayUnlockContainer::QueryInterface (REFIID iid, LPLPVOID ppv)
{
M_PROLOG(this);
if (IsEqualIID(iid, IID_IUnknown))
{
*ppv = this;
AddRef();
return NOERROR;
}
else {
*ppv = NULL;
return ResultFromScode(E_NOINTERFACE);
}
}
STDMETHODIMP_(ULONG) CDelayUnlockContainer::AddRef ()
{
return(InterlockedIncrement((long *)&m_refs));
}
STDMETHODIMP_(ULONG) CDelayUnlockContainer::Release ()
{
if (InterlockedDecrement((long *)&m_refs) == 0)
{
if (m_pOleCont != NULL)
{
m_pOleCont->LockContainer(FALSE);
m_pOleCont->Release();
}
delete this;
return 0;
}
return 1;
}
INTERNAL RegisterContainerBound (LPBC pbc, LPOLEITEMCONTAINER pOleCont)
{
// don't give the delay object the pOleCont before we lock it; do in
// this order so error checking is correct and we don't lock/unlock
// inappropriately.
CDelayUnlockContainer FAR* pCDelay = new CDelayUnlockContainer();
if (pCDelay == NULL)
return ResultFromScode(E_OUTOFMEMORY);
HRESULT hresult;
if ((hresult = pbc->RegisterObjectBound(pCDelay)) != NOERROR)
goto errRet;
if ((hresult = pOleCont->LockContainer(TRUE)) != NOERROR) {
// the delay object is still in the bindctx; no harm
hresult = E_FAIL;
goto errRet;
}
pCDelay->m_pOleCont = pOleCont;
pOleCont->AddRef();
errRet:
pCDelay->Release();
return hresult;
}
| 25.870435 | 102 | 0.506313 | [
"object"
] |
638cc94f83ab54b3c432757373d53f5f0dd225b3 | 7,911 | cc | C++ | third_party/blink/renderer/core/html/track/automatic_track_selection.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/core/html/track/automatic_track_selection.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/core/html/track/automatic_track_selection.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/html/track/automatic_track_selection.h"
#include "third_party/blink/renderer/core/html/track/text_track.h"
#include "third_party/blink/renderer/core/html/track/text_track_list.h"
#include "third_party/blink/renderer/platform/language.h"
namespace blink {
class TrackGroup {
STACK_ALLOCATED();
public:
enum GroupKind { kCaptionsAndSubtitles, kDescription, kChapter, kMetadata };
explicit TrackGroup(GroupKind kind)
: visible_track(nullptr),
default_track(nullptr),
kind(kind),
has_src_lang(false) {}
HeapVector<Member<TextTrack>> tracks;
Member<TextTrack> visible_track;
Member<TextTrack> default_track;
GroupKind kind;
bool has_src_lang;
};
static int TextTrackLanguageSelectionScore(const TextTrack& track) {
if (track.language().IsEmpty())
return 0;
Vector<AtomicString> languages = UserPreferredLanguages();
size_t language_match_index =
IndexOfBestMatchingLanguageInList(track.language(), languages);
if (language_match_index >= languages.size())
return 0;
return languages.size() - language_match_index;
}
static int TextTrackSelectionScore(const TextTrack& track) {
if (!track.IsVisualKind())
return 0;
return TextTrackLanguageSelectionScore(track);
}
AutomaticTrackSelection::AutomaticTrackSelection(
const Configuration& configuration)
: configuration_(configuration) {}
const AtomicString& AutomaticTrackSelection::PreferredTrackKind() const {
if (configuration_.text_track_kind_user_preference ==
TextTrackKindUserPreference::kSubtitles)
return TextTrack::SubtitlesKeyword();
if (configuration_.text_track_kind_user_preference ==
TextTrackKindUserPreference::kCaptions)
return TextTrack::CaptionsKeyword();
return g_null_atom;
}
void AutomaticTrackSelection::PerformAutomaticTextTrackSelection(
const TrackGroup& group) {
DCHECK(group.tracks.size());
// First, find the track in the group that should be enabled (if any).
HeapVector<Member<TextTrack>> currently_enabled_tracks;
TextTrack* track_to_enable = nullptr;
TextTrack* default_track = nullptr;
TextTrack* preferred_track = nullptr;
TextTrack* fallback_track = nullptr;
int highest_track_score = 0;
for (const auto& text_track : group.tracks) {
if (configuration_.disable_currently_enabled_tracks &&
text_track->mode() == TextTrack::ShowingKeyword())
currently_enabled_tracks.push_back(text_track);
int track_score = TextTrackSelectionScore(*text_track);
if (text_track->kind() == PreferredTrackKind())
track_score += 1;
if (track_score) {
// * If the text track kind is subtitles or captions and the user has
// indicated an interest in having a track with this text track kind, text
// track language, and text track label enabled, and there is no other
// text track in the media element's list of text tracks with a text track
// kind of either subtitles or captions whose text track mode is showing
// Let the text track mode be showing.
if (track_score > highest_track_score) {
preferred_track = text_track;
highest_track_score = track_score;
}
if (!default_track && text_track->IsDefault())
default_track = text_track;
if (!fallback_track)
fallback_track = text_track;
} else if (!group.visible_track && !default_track &&
text_track->IsDefault()) {
// * If the track element has a default attribute specified, and there is
// no other text track in the media element's list of text tracks whose
// text track mode is showing or showing by default
// Let the text track mode be showing by default.
default_track = text_track;
}
}
if (configuration_.text_track_kind_user_preference !=
TextTrackKindUserPreference::kDefault)
track_to_enable = preferred_track;
if (!track_to_enable && default_track)
track_to_enable = default_track;
if (!track_to_enable &&
configuration_.force_enable_subtitle_or_caption_track &&
group.kind == TrackGroup::kCaptionsAndSubtitles) {
if (fallback_track)
track_to_enable = fallback_track;
else
track_to_enable = group.tracks[0];
}
if (currently_enabled_tracks.size()) {
for (const auto& text_track : currently_enabled_tracks) {
if (text_track != track_to_enable)
text_track->setMode(TextTrack::DisabledKeyword());
}
}
if (track_to_enable)
track_to_enable->setMode(TextTrack::ShowingKeyword());
}
void AutomaticTrackSelection::EnableDefaultMetadataTextTracks(
const TrackGroup& group) {
DCHECK(group.tracks.size());
// https://html.spec.whatwg.org/multipage/embedded-content.html#honor-user-preferences-for-automatic-text-track-selection
// 4. If there are any text tracks in the media element's list of text
// tracks whose text track kind is metadata that correspond to track
// elements with a default attribute set whose text track mode is set to
// disabled, then set the text track mode of all such tracks to hidden
for (auto& text_track : group.tracks) {
if (text_track->mode() != TextTrack::DisabledKeyword())
continue;
if (!text_track->IsDefault())
continue;
text_track->setMode(TextTrack::HiddenKeyword());
}
}
void AutomaticTrackSelection::Perform(TextTrackList& text_tracks) {
TrackGroup caption_and_subtitle_tracks(TrackGroup::kCaptionsAndSubtitles);
TrackGroup description_tracks(TrackGroup::kDescription);
TrackGroup chapter_tracks(TrackGroup::kChapter);
TrackGroup metadata_tracks(TrackGroup::kMetadata);
for (size_t i = 0; i < text_tracks.length(); ++i) {
TextTrack* text_track = text_tracks.AnonymousIndexedGetter(i);
if (!text_track)
continue;
String kind = text_track->kind();
TrackGroup* current_group;
if (kind == TextTrack::SubtitlesKeyword() ||
kind == TextTrack::CaptionsKeyword()) {
current_group = &caption_and_subtitle_tracks;
} else if (kind == TextTrack::DescriptionsKeyword()) {
current_group = &description_tracks;
} else if (kind == TextTrack::ChaptersKeyword()) {
current_group = &chapter_tracks;
} else {
DCHECK_EQ(kind, TextTrack::MetadataKeyword());
current_group = &metadata_tracks;
}
if (!current_group->visible_track &&
text_track->mode() == TextTrack::ShowingKeyword())
current_group->visible_track = text_track;
if (!current_group->default_track && text_track->IsDefault())
current_group->default_track = text_track;
// Do not add this track to the group if it has already been automatically
// configured as we only want to perform selection once per track so that
// adding another track after the initial configuration doesn't reconfigure
// every track - only those that should be changed by the new addition. For
// example all metadata tracks are disabled by default, and we don't want a
// track that has been enabled by script to be disabled automatically when a
// new metadata track is added later.
if (text_track->HasBeenConfigured())
continue;
if (text_track->language().length())
current_group->has_src_lang = true;
current_group->tracks.push_back(text_track);
}
if (caption_and_subtitle_tracks.tracks.size())
PerformAutomaticTextTrackSelection(caption_and_subtitle_tracks);
if (description_tracks.tracks.size())
PerformAutomaticTextTrackSelection(description_tracks);
if (chapter_tracks.tracks.size())
PerformAutomaticTextTrackSelection(chapter_tracks);
if (metadata_tracks.tracks.size())
EnableDefaultMetadataTextTracks(metadata_tracks);
}
} // namespace blink
| 36.625 | 123 | 0.727594 | [
"vector"
] |
b0cf1a83ecab791868d7106e157d38a8a14296b4 | 11,561 | cpp | C++ | src/enemies.cpp | suryanshsrivastava/jetpack-joyride-opengl | a67136c456dbbacc5c11ba5425dc2a8d4e656656 | [
"MIT"
] | null | null | null | src/enemies.cpp | suryanshsrivastava/jetpack-joyride-opengl | a67136c456dbbacc5c11ba5425dc2a8d4e656656 | [
"MIT"
] | null | null | null | src/enemies.cpp | suryanshsrivastava/jetpack-joyride-opengl | a67136c456dbbacc5c11ba5425dc2a8d4e656656 | [
"MIT"
] | null | null | null | #include "enemies.h"
#include "main.h"
FireLine::FireLine(float x, float y, double angle, color_t color) {
this->position = glm::vec3(x, y, 0);
this->rotation = rand()%180;
this->radius=0.1;
this->length=1;
GLfloat vertex_buffer_data_circular[2000];
int sides = 100;
float theta = (2*M_PIl)/sides;
for(int i = 0; i < sides; i++)
{
vertex_buffer_data_circular[9*i] = 0.0f;
vertex_buffer_data_circular[9*i + 1] = 0.0f;
vertex_buffer_data_circular[9*i + 2] = 0.0f;
vertex_buffer_data_circular[9*i + 3] = radius*cos(i*theta);
vertex_buffer_data_circular[9*i + 4] = radius*sin(i*theta) ;
vertex_buffer_data_circular[9*i + 5] = 0.0f;
vertex_buffer_data_circular[9*i + 6] = radius*cos((i+1)*theta);
vertex_buffer_data_circular[9*i + 7] = radius*sin((i+1)*theta);
vertex_buffer_data_circular[9*i + 8] = 0.0f;
}
static const GLfloat vertex_buffer_data_cylinderical[]={
0.0f-0.025f*sin(angle), 0.025f+0.025*cos(angle), 0.0f,
0.0f+length-0.025f*sin(angle), 0.025f+0.025*cos(angle), 0.0f,
0.0f+length+0.025f*sin(angle), -0.025f-0.025*cos(angle), 0.0f,
0.0f-0.025f*sin(angle), 0.025f+0.025*cos(angle), 0.0f,
0.0f-0.025f*sin(angle), -0.025f-0.025*cos(angle), 0.0f,
0.0f+length+0.025f*sin(angle), -0.025f-0.025*cos(angle), 0.0f,
};
for(int j = 101; j < sides+101; j++)
{
vertex_buffer_data_circular[9*j] = 0.0f + length*cos(angle);
vertex_buffer_data_circular[9*j + 1] = 0.0f + length*sin(angle);
vertex_buffer_data_circular[9*j + 2] = 0.0f;
vertex_buffer_data_circular[9*j + 3] = radius*cos(j*theta) + length*cos(angle);
vertex_buffer_data_circular[9*j + 4] = radius*sin(j*theta) + length*sin(angle);
vertex_buffer_data_circular[9*j + 5] = 0.0f;
vertex_buffer_data_circular[9*j + 6] = radius*cos((j+1)*theta) + length*cos(angle);
vertex_buffer_data_circular[9*j + 7] = radius*sin((j+1)*theta) + length*sin(angle);
vertex_buffer_data_circular[9*j + 8] = 0.0f;
}
this->circular = create3DObject(GL_TRIANGLES, 6*sides, vertex_buffer_data_circular, color, GL_FILL);
this->cylindrical = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data_cylinderical, color, GL_FILL);
}
void FireLine::draw(glm::mat4 VP) {
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1));
rotate = glm::translate(glm::vec3(0, 0, 0)) * rotate * glm::translate(glm::vec3(0, 0, 0));
Matrices.model *= (translate * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->circular);
draw3DObject(this->cylindrical);
}
bool FireLine::detect_collision(Player Player) {
return (std::sqrt(std::pow(Player.position.x - this->position.x, 2) + std::pow(Player.position.y - this->position.y, 2)*1.0)
+ std::sqrt(std::pow(Player.position.x - this->position.x - length*cos(this->rotation* M_PI / 180.0f), 2) +
std::pow(Player.position.y - this->position.y -length*sin(this->rotation* M_PI / 180.0f), 2)*1.0))
- length < 0.1;
}
bool FireLine::extinguish(Balloons Balloons) {
return (std::sqrt(std::pow(Balloons.position.x - this->position.x, 2) + std::pow(Balloons.position.y - this->position.y, 2)*1.0)
+ std::sqrt(std::pow(Balloons.position.x - this->position.x - length*cos(this->rotation* M_PI / 180.0f), 2) +
std::pow(Balloons.position.y - this->position.y -length*sin(this->rotation* M_PI / 180.0f), 2)*1.0))
- length < 0.1;
}
FireBeam::FireBeam(float x, float y, color_t color) {
this->position = glm::vec3(x, y, 0);
this->rotation = 0;
this->radius=0.15;
this->length=3;
this->seperation=0.5;
this->speed=0.025;
this->moveup=false;
GLfloat vertex_buffer_data_circular[4000];
int sides = 100;
float theta = (2*M_PIl)/sides;
for(int i = 0; i < sides; i++)
{
vertex_buffer_data_circular[9*i] = 0.0f;
vertex_buffer_data_circular[9*i + 1] = 0.0f;
vertex_buffer_data_circular[9*i + 2] = 0.0f;
vertex_buffer_data_circular[9*i + 3] = radius*cos(i*theta);
vertex_buffer_data_circular[9*i + 4] = radius*sin(i*theta) ;
vertex_buffer_data_circular[9*i + 5] = 0.0f;
vertex_buffer_data_circular[9*i + 6] = radius*cos((i+1)*theta);
vertex_buffer_data_circular[9*i + 7] = radius*sin((i+1)*theta);
vertex_buffer_data_circular[9*i + 8] = 0.0f;
}
static const GLfloat vertex_buffer_data_cylinderical[]={
0.0f, 0.05f, 0.0f,
0.0f+length, 0.05f, 0.0f,
0.0f+length, -0.05f, 0.0f,
0.0f, 0.05f, 0.0f,
0.0f, -0.05f, 0.0f,
0.0f+length, -0.05f, 0.0f,
0.0f, 0.05f-this->seperation, 0.0f,
0.0f+length, 0.05f-this->seperation, 0.0f,
0.0f+length, -0.05f-this->seperation, 0.0f,
0.0f, 0.05f-this->seperation, 0.0f,
0.0f, -0.05f-this->seperation, 0.0f,
0.0f+length, -0.05f-this->seperation, 0.0f,
};
for(int j = 100; j < sides+101; j++)
{
vertex_buffer_data_circular[9*j] = 0.0f + length;
vertex_buffer_data_circular[9*j + 1] = 0.0f;
vertex_buffer_data_circular[9*j + 2] = 0.0f;
vertex_buffer_data_circular[9*j + 3] = radius*cos(j*theta) + length;
vertex_buffer_data_circular[9*j + 4] = radius*sin(j*theta);
vertex_buffer_data_circular[9*j + 5] = 0.0f;
vertex_buffer_data_circular[9*j + 6] = radius*cos((j+1)*theta) + length;
vertex_buffer_data_circular[9*j + 7] = radius*sin((j+1)*theta);
vertex_buffer_data_circular[9*j + 8] = 0.0f;
}
for(int i = 200; i < sides+201; i++)
{
vertex_buffer_data_circular[9*i] = 0.0f;
vertex_buffer_data_circular[9*i + 1] = 0.0f-this->seperation;
vertex_buffer_data_circular[9*i + 2] = 0.0f;
vertex_buffer_data_circular[9*i + 3] = radius*cos(i*theta);
vertex_buffer_data_circular[9*i + 4] = radius*sin(i*theta)-this->seperation;
vertex_buffer_data_circular[9*i + 5] = 0.0f;
vertex_buffer_data_circular[9*i + 6] = radius*cos((i+1)*theta);
vertex_buffer_data_circular[9*i + 7] = radius*sin((i+1)*theta)-this->seperation;
vertex_buffer_data_circular[9*i + 8] = 0.0f;
}
for(int j = 300; j < sides+301; j++)
{
vertex_buffer_data_circular[9*j] = 0.0f + length;
vertex_buffer_data_circular[9*j + 1] = 0.0f-this->seperation;
vertex_buffer_data_circular[9*j + 2] = 0.0f;
vertex_buffer_data_circular[9*j + 3] = radius*cos(j*theta) + length;
vertex_buffer_data_circular[9*j + 4] = radius*sin(j*theta)-this->seperation;
vertex_buffer_data_circular[9*j + 5] = 0.0f;
vertex_buffer_data_circular[9*j + 6] = radius*cos((j+1)*theta) + length;
vertex_buffer_data_circular[9*j + 7] = radius*sin((j+1)*theta)-this->seperation;
vertex_buffer_data_circular[9*j + 8] = 0.0f;
}
this->circular = create3DObject(GL_TRIANGLES, 12*sides, vertex_buffer_data_circular, color, GL_FILL);
this->cylindrical = create3DObject(GL_TRIANGLES, 12, vertex_buffer_data_cylinderical, color, GL_FILL);
}
void FireBeam::draw(glm::mat4 VP) {
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1));
rotate = glm::translate(glm::vec3(0, 0, 0)) * rotate * glm::translate(glm::vec3(0, 0, 0));
Matrices.model *= (translate * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->circular);
draw3DObject(this->cylindrical);
}
void FireBeam::movement() {
if(moveup){
this->position.y += this->speed;
if(this->position.y >= 4)
moveup=false;
}
else
{
this->position.y -= this->speed;
if(this->position.y < -1.5f)
moveup=true;
}
}
bounding_box_t FireBeam::bounding_box() {
float x = this->position.x + 1.5f, y = this->position.y-0.25f;
bounding_box_t bbox = { x, y, 3.3f, 0.6f };
return bbox;
}
Boomerang::Boomerang(float x, float y, color_t color) {
this->position = glm::vec3(x, y, 0);
this->rotation = 0;
this->back=true;
this->speed_x=-0.15f;
this->speed_y=0.05f;
this->rotation_speed=5;
this->spawn=true;
// printf("yay\n");
static const GLfloat vertex_buffer_data[]={
-0.25f, 0.0f, 0.0f,
-0.5f, 0.0f, 0.0f,
0.0f, 0.75f, 0.0f,
-0.25f, 0.0f, 0.0f,
-0.5f, 0.0f, 0.0f,
0.0f, -0.75f, 0.0f,
};
this->boomerang = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color, GL_FILL);
}
void Boomerang::draw(glm::mat4 VP) {
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1));
rotate = glm::translate(glm::vec3(0, 0, 0)) * rotate * glm::translate(glm::vec3(0, 0, 0));
Matrices.model *= (translate * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->boomerang);
}
void Boomerang::movement() {
this->rotation+=this->rotation_speed;
this->position.y-=this->speed_y;
this->position.x+=this->speed_x;
this->speed_x+=0.00163f;
}
void Boomerang::set_position(float x, float y) {
this->position = glm::vec3(x, y, 0);
}
bounding_box_t Boomerang::bounding_box() {
float x = this->position.x -0.25f, y = this->position.y;
bounding_box_t bbox = { x, y, 1.0f, 1.0f };
return bbox;
}
Viserion::Viserion(float x, float y, color_t color) {
this->position = glm::vec3(x, y, 0);
this->rotation = 0;
this->health = 50;
this->spawn=true;
static const GLfloat vertex_buffer_data[]={
-0.25f, 0.0f, 0.0f,
-0.5f, 0.0f, 0.0f,
0.0f, 0.75f, 0.0f,
-0.25f, 0.0f, 0.0f,
-0.5f, 0.0f, 0.0f,
0.0f, -0.75f, 0.0f,
};
this->dragon = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color, GL_FILL);
}
void Viserion::draw(glm::mat4 VP) {
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1));
rotate = glm::translate(glm::vec3(0, 0, 0)) * rotate * glm::translate(glm::vec3(0, 0, 0));
Matrices.model *= (translate * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->dragon);
}
void Viserion::movement(Player Player) {
// this->rotation+=this->rotation_speed;
this->position.y=Player.position.y;
this->position.x=screen_center_x+3;
// this->speed_x+=0.00163f;
}
void Viserion::set_position(float x, float y) {
this->position = glm::vec3(x, y, 0);
}
bounding_box_t Viserion::bounding_box() {
float x = this->position.x -0.25f, y = this->position.y;
bounding_box_t bbox = { x, y, 1.0f, 1.0f };
return bbox;
} | 37.535714 | 132 | 0.613961 | [
"model"
] |
b0db0f8cddfc87616c5aff1ed4764b17108e1039 | 1,032 | cpp | C++ | toonz/sources/toonzlib/observer.cpp | ss23/opentoonz | b42e43d4b8d9fedc26022d145218b9a147a30985 | [
"BSD-3-Clause"
] | null | null | null | toonz/sources/toonzlib/observer.cpp | ss23/opentoonz | b42e43d4b8d9fedc26022d145218b9a147a30985 | [
"BSD-3-Clause"
] | null | null | null | toonz/sources/toonzlib/observer.cpp | ss23/opentoonz | b42e43d4b8d9fedc26022d145218b9a147a30985 | [
"BSD-3-Clause"
] | 1 | 2019-10-07T17:12:30.000Z | 2019-10-07T17:12:30.000Z |
#include "toonz/observer.h"
// OBSOLETO??
TNotifier *TNotifier::instance()
{
static TNotifier theNotifier;
return &theNotifier;
}
/*
void TNotifier::attach(TChangeObserver*observer)
{
std::vector<TObserverList*>::iterator it;
for(it = m_obsList.begin(); it != m_obsList.end(); ++it)
(*it)->attach(observer);
if(TGlobalObserver *go = dynamic_cast<TGlobalObserver *>(observer))
{
if(m_newSceneNotifiedObs.find(go) == m_newSceneNotifiedObs.end())
{
go->update(TGlobalChange(true));
m_newSceneNotifiedObs.insert(go);
}
}
}
void TNotifier::detach(TChangeObserver*observer)
{
std::vector<TObserverList*>::iterator it;
for(it = m_obsList.begin(); it != m_obsList.end(); ++it)
(*it)->detach(observer);
}
*/
void TNotifier::notify(const TGlobalChange &c)
{
m_globalObs.notify(c);
if (c.isSceneChanged()) {
m_newSceneNotifiedObs.clear();
for (int i = 0; i < (int)m_globalObs.m_observers.size(); i++)
m_newSceneNotifiedObs.insert(m_globalObs.m_observers[i]);
}
}
| 22.434783 | 70 | 0.675388 | [
"vector"
] |
b0eb2add4d025aad67b754a15120e4072e32092e | 3,651 | cpp | C++ | leetcode/212.cpp | Moonshile/MyAlgorithmCandy | e1ab006a5abe7d2749ae564ad2bffc4a628ed31b | [
"Apache-2.0"
] | 2 | 2016-11-26T02:56:35.000Z | 2019-06-17T04:09:02.000Z | leetcode/212.cpp | Moonshile/MyAlgorithmCandy | e1ab006a5abe7d2749ae564ad2bffc4a628ed31b | [
"Apache-2.0"
] | null | null | null | leetcode/212.cpp | Moonshile/MyAlgorithmCandy | e1ab006a5abe7d2749ae564ad2bffc4a628ed31b | [
"Apache-2.0"
] | 3 | 2016-07-18T14:13:20.000Z | 2019-06-17T04:08:32.000Z | class TrieNode {
friend class Trie;
public:
// Initialize your data structure here.
TrieNode(char charactor): c(charactor), word_end(false) {
for (auto &c: children) {
c = nullptr;
}
}
TrieNode(): TrieNode('.') {}
~TrieNode() {
for (auto &c: children) {
if (c) {
delete c;
c = nullptr;
}
}
}
private:
char c;
bool word_end;
TrieNode *children[26];
};
class Trie {
public:
Trie(): root() {}
// Inserts a word into the trie.
void insert(string &word) {
TrieNode *parent = &root;
for (char c: word) {
if (parent->children[c - 'a'] == nullptr) {
auto ptr = new TrieNode(c);
parent->children[c - 'a'] = ptr;
}
parent = parent->children[c - 'a'];
}
parent->word_end = true;
}
// Returns if the word is in the trie.
bool search(string &word) {
TrieNode *parent = &root;
for (char c: word) {
if (parent->children[c - 'a'] == nullptr) {
return false;
}
parent = parent->children[c - 'a'];
}
bool res = parent->word_end;
// this line is just for this problem to prevent a same word to be added more than twice
parent->word_end = false;
return res;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string &prefix) {
TrieNode *parent = &root;
for (char c: prefix) {
if (parent->children[c - 'a'] == nullptr) {
return false;
}
parent = parent->children[c - 'a'];
}
return true;
}
private:
TrieNode root;
};
class Solution {
private:
inline vector<pair<int, int>> sequence(int i, int j) {
return vector<pair<int, int>>{
pair<int, int>({i - 1, j}),
pair<int, int>({i + 1, j}),
pair<int, int>({i, j - 1}),
pair<int, int>({i, j + 1})
};
}
void dfs(vector<vector<char>> &board, int i, int j, int m, int n, string cur, vector<string> &res, Trie &trie) {
cur = cur + board[i][j];
if (trie.startsWith(cur)) {
board[i][j] = '\0';
auto sequences = sequence(i, j);
for (auto &p: sequences) {
int &ii = p.first, &jj = p.second;
if (ii >= 0 && ii < m && jj >= 0 && jj < n && board[ii][jj]) {
dfs(board, ii, jj, m, n, cur, res, trie);
}
}
board[i][j] = cur.back();
if (trie.search(cur)) {
res.push_back(cur);
}
}
}
public:
vector<string> findWords(vector<vector<char>> &board, vector<string>& words) {
unordered_set<char> chars;
for (auto &line: board) {
for (char c: line) {
chars.insert(c);
}
}
Trie trie;
for (auto &w: words) {
bool clean = true;
for (auto c: w) {
if (chars.count(c) == 0) {
clean = false;
break;
}
}
if (clean) {
trie.insert(w);
}
}
vector<string> res;
for (int i = 0, m = board.size(); i < m; ++i) {
for (int j = 0, n = board[i].size(); j < n; ++j) {
dfs(board, i, j, m, n, "", res, trie);
}
}
return res;
}
};
| 26.845588 | 116 | 0.435771 | [
"vector"
] |
b0f3679c200c691ac896c1f209f461699da4db28 | 40,063 | cpp | C++ | ugene/src/plugins/workflow_designer/src/library/CreateExternalProcessDialog.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins/workflow_designer/src/library/CreateExternalProcessDialog.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins/workflow_designer/src/library/CreateExternalProcessDialog.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* 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., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "CreateExternalProcessDialog.h"
#include <QtGui/QMessageBox>
#include <U2Core/DocumentModel.h>
#include <U2Core/BaseDocumentFormats.h>
#include <U2Core/AppContext.h>
#include <U2Lang/WorkflowEnv.h>
#include <U2Lang/BaseTypes.h>
#include <U2Lang/ExternalToolCfg.h>
#include <U2Lang/HRSchemaSerializer.h>
#include <U2Lang/WorkflowSettings.h>
#include <U2Lang/ConfigurationEditor.h>
#include <U2Lang/WorkflowEnv.h>
#include <U2Lang/ActorPrototypeRegistry.h>
#include <U2Designer/DelegateEditors.h>
#include "WorkflowEditorDelegates.h"
namespace U2 {
class CreateExternalProcessDialog;
class CfgExternalToolItem {
public:
CfgExternalToolItem() {
dfr = AppContext::getDocumentFormatRegistry();
dtr = Workflow::WorkflowEnv::getDataTypeRegistry();
delegateForTypes = NULL;
delegateForFormats = NULL;
itemData.type = BaseTypes::DNA_SEQUENCE_TYPE()->getId();
itemData.format = BaseDocumentFormats::FASTA;
}
~CfgExternalToolItem() {
delete delegateForTypes;
delete delegateForFormats;
}
QString getDataType() const {return itemData.type;}
void setDataType(const QString& id) {
itemData.type = id;
}
QString getName() const {return itemData.attrName;}
void setName(const QString &_name) {itemData.attrName = _name;}
QString getFormat() const {return itemData.format;}
void setFormat(const QString & f) {itemData.format = f;}
QString getDescription() const {return itemData.description;}
void setDescription(const QString & _descr) {itemData.description = _descr;}
PropertyDelegate *delegateForTypes;
PropertyDelegate *delegateForFormats;
DataConfig itemData;
private:
DocumentFormatRegistry *dfr;
DataTypeRegistry *dtr;
};
class CfgExternalToolModel: public QAbstractTableModel {
public:
CfgExternalToolModel(bool isInput, QObject *obj = NULL): QAbstractTableModel(obj), isInput(isInput) {
init();
/*CfgListItem *newItem = new CfgListItem();
newItem->delegateForTypes = new ComboBoxDelegate(types);
items.append(newItem);*/
}
int rowCount(const QModelIndex & /* = QModelIndex */) const{
return items.size();
}
int columnCount(const QModelIndex & /* = QModelIndex */) const {
return 4;
}
Qt::ItemFlags flags(const QModelIndex &) const{
return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
CfgExternalToolItem* getItem(const QModelIndex &index) const {
return items.at(index.row());
}
QList<CfgExternalToolItem*> getItems() const {
return items;
}
QVariant data(const QModelIndex &index, int role /* = Qt::DisplayRole */) const {
CfgExternalToolItem *item = getItem(index);
int col = index.column();
switch(role) {
case Qt::DisplayRole:
case Qt::ToolTipRole:
if(col == 0) return item->getName();
else if(col == 1) return item->delegateForTypes->getDisplayValue(item->getDataType());
else if(col == 2) return item->delegateForFormats->getDisplayValue(item->getFormat());
else if(col == 3) return item->getDescription();
else return QVariant();
case DelegateRole:
if(col == 1) return qVariantFromValue<PropertyDelegate*>(item->delegateForTypes);
else if(col == 2) return qVariantFromValue<PropertyDelegate*>(item->delegateForFormats);
else return QVariant();
case Qt::EditRole:
case ConfigurationEditor::ItemValueRole:
if(col == 1) return item->getDataType();
else if(col == 2) return item->getFormat();
else return QVariant();
default:
return QVariant();
}
}
void createFormatDelegate(const QString &newType, CfgExternalToolItem *item) {
PropertyDelegate *delegate;
QString format;
if(newType == BaseTypes::DNA_SEQUENCE_TYPE()->getId()) {
delegate = new ComboBoxDelegate(seqFormatsW);
format = seqFormatsW.values().first().toString();
} else if(newType == BaseTypes::MULTIPLE_ALIGNMENT_TYPE()->getId()) {
delegate = new ComboBoxDelegate(msaFormatsW);
format = msaFormatsW.values().first().toString();
} else if(newType == BaseTypes::ANNOTATION_TABLE_TYPE()->getId()) {
delegate = new ComboBoxDelegate(annFormatsW);
format = annFormatsW.values().first().toString();
} else if(newType == SEQ_WITH_ANNS){
delegate = new ComboBoxDelegate(annFormatsW);
format = annFormatsW.values().first().toString();
} else if(newType == BaseTypes::STRING_TYPE()->getId()) {
delegate = new ComboBoxDelegate(textFormat);
format = textFormat.values().first().toString();
} else{
return;
}
item->setFormat(format);
item->delegateForFormats = delegate;
}
bool setData(const QModelIndex &index, const QVariant &value, int role) {
int col = index.column();
CfgExternalToolItem * item = getItem(index);
switch (role) {
case Qt::EditRole:
case ConfigurationEditor::ItemValueRole:
if(col == 0) {
if(item->getName() != value.toString()) {
item->setName(value.toString());
}
}else if(col == 1) {
QString newType = value.toString();
if(item->getDataType() != newType) {
if(!newType.isEmpty()) {
item->setDataType(newType);
createFormatDelegate(newType, item);
}
}
} else if(col == 2) {
if(item->getFormat() != value.toString() && !value.toString().isEmpty()) {
item->setFormat(value.toString());
}
} else if(col == 3) {
if(item->getDescription() != value.toString()) {
item->setDescription(value.toString());
}
}
emit dataChanged(index, index);
}
return true;
}
QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const {
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch(section) {
case 0: return CreateExternalProcessDialog::tr("Name for command line parameter");
case 1: return CreateExternalProcessDialog::tr("Type");
case 2:
if (isInput) {
return CreateExternalProcessDialog::tr("Read as");
} else {
return CreateExternalProcessDialog::tr("Write as");
}
case 3: return CreateExternalProcessDialog::tr("Description");
default: return QVariant();
}
}
return QVariant();
}
bool insertRows ( int row, int count = 0, const QModelIndex & parent = QModelIndex() ) {
Q_UNUSED(row);
Q_UNUSED(count);
beginInsertRows(parent, items.size(), items.size());
CfgExternalToolItem *newItem = new CfgExternalToolItem();
newItem->delegateForTypes = new ComboBoxDelegate(types);
newItem->delegateForFormats = new ComboBoxDelegate(seqFormatsW);
items.append(newItem);
endInsertRows();
return true;
}
bool removeRows(int row, int count = 0, const QModelIndex & parent = QModelIndex()) {
Q_UNUSED(count);
if(row >= 0 && row < items.size()) {
beginRemoveRows(parent, row, row);
items.removeAt(row);
endRemoveRows();
return true;
} else {
return false;
}
}
void init() {
initTypes();
initFormats();
}
void initFormats() {
QList<DocumentFormatId> ids = AppContext::getDocumentFormatRegistry()->getRegisteredFormats();
DocumentFormatConstraints seqWrite;
seqWrite.supportedObjectTypes+=GObjectTypes::SEQUENCE;
seqWrite.addFlagToSupport(DocumentFormatFlag_SupportWriting);
seqWrite.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat);
DocumentFormatConstraints seqRead;
seqRead.supportedObjectTypes+=GObjectTypes::SEQUENCE;
seqRead.addFlagToSupport(DocumentFormatFlag_SupportStreaming);
seqRead.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat);
DocumentFormatConstraints msaWrite;
msaWrite.supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT;
msaWrite.addFlagToSupport(DocumentFormatFlag_SupportWriting);
msaWrite.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat);
DocumentFormatConstraints msaRead;
msaRead.supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT;
msaRead.addFlagToSupport(DocumentFormatFlag_SupportStreaming);
msaRead.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat);
DocumentFormatConstraints annWrite;
annWrite.supportedObjectTypes+=GObjectTypes::ANNOTATION_TABLE;
annWrite.addFlagToSupport(DocumentFormatFlag_SupportWriting);
annWrite.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat);
DocumentFormatConstraints annRead;
annRead.supportedObjectTypes+=GObjectTypes::ANNOTATION_TABLE;
annRead.addFlagToSupport(DocumentFormatFlag_SupportStreaming);
annRead.addFlagToExclude(DocumentFormatFlag_SingleObjectFormat);
foreach(const DocumentFormatId& id, ids) {
DocumentFormat* df = AppContext::getDocumentFormatRegistry()->getFormatById(id);
if (df->checkConstraints(seqWrite)) {
seqFormatsW[df->getFormatName()] = df->getFormatId();
}
if (df->checkConstraints(seqRead)) {
seqFormatsR[df->getFormatName()] = df->getFormatId();
}
if (df->checkConstraints(msaWrite)) {
msaFormatsW[df->getFormatName()] = df->getFormatId();
}
if (df->checkConstraints(msaRead)) {
msaFormatsR[df->getFormatName()] = df->getFormatId();
}
if (df->checkConstraints(annWrite)) {
annFormatsW[df->getFormatName()] = df->getFormatId();
}
if (df->checkConstraints(annRead)) {
annFormatsR[df->getFormatName()] = df->getFormatId();
}
}
DocumentFormat *df = AppContext::getDocumentFormatRegistry()->getFormatById(BaseDocumentFormats::PLAIN_TEXT);
if (isInput) {
textFormat[tr("String value")] = DataConfig::StringValue;
}
textFormat[tr("Text file")] = df->getFormatId();
if (!isInput) {
textFormat[tr("Output file url")] = DataConfig::OutputFileUrl;
}
}
void initTypes() {
DataTypePtr ptr = BaseTypes::DNA_SEQUENCE_TYPE();
types[ptr->getDisplayName()] = ptr->getId();
ptr = BaseTypes::ANNOTATION_TABLE_TYPE();
types[ptr->getDisplayName()] = ptr->getId();
ptr = BaseTypes::MULTIPLE_ALIGNMENT_TYPE();
types[ptr->getDisplayName()] = ptr->getId();
ptr = BaseTypes::STRING_TYPE();
types[ptr->getDisplayName()] = ptr->getId();
types["Sequence with annotations"] = SEQ_WITH_ANNS;
}
private:
bool isInput;
QList<CfgExternalToolItem*> items;
QVariantMap types;
QVariantMap seqFormatsW;
QVariantMap msaFormatsW;
QVariantMap annFormatsW;
QVariantMap seqFormatsR;
QVariantMap msaFormatsR;
QVariantMap annFormatsR;
QVariantMap textFormat;
};
class AttributeItem {
public:
QString getName() const {return name;}
void setName(const QString& _name) {name = _name;}
QString getDataType() const {return type;}
void setDataType(const QString &_type) {type = _type;}
QString getDescription() const {return description;}
void setDescription(const QString &_description) {description = _description;}
private:
QString name;
QString type;
QString description;
};
class CfgExternalToolModelAttributes: public QAbstractTableModel {
public:
CfgExternalToolModelAttributes() {
types["URL"] = "URL";
types["String"] = "String";
types["Number"] = "Number";
types["Boolean"] = "Boolean";
delegate = new ComboBoxDelegate(types);
}
~CfgExternalToolModelAttributes() {
foreach(AttributeItem* item, items) {
delete item;
}
}
int rowCount(const QModelIndex & /* = QModelIndex */) const{
return items.size();
}
int columnCount(const QModelIndex & /* = QModelIndex */) const {
return 3;
}
Qt::ItemFlags flags(const QModelIndex &) const{
return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
AttributeItem* getItem(const QModelIndex &index) const {
return items.at(index.row());
}
QList<AttributeItem*> getItems() const {
return items;
}
QVariant data(const QModelIndex &index, int role /* = Qt::DisplayRole */) const {
AttributeItem *item = getItem(index);
int col = index.column();
switch(role) {
case Qt::DisplayRole:
case Qt::ToolTipRole:
if(col == 0) return item->getName();
else if(col == 1) return delegate->getDisplayValue(item->getDataType());
else if(col == 2) return item->getDescription();
else return QVariant();
case DelegateRole:
if(col == 1) return qVariantFromValue<PropertyDelegate*>(delegate);
else return QVariant();
case Qt::EditRole:
case ConfigurationEditor::ItemValueRole:
if(col == 1) return item->getDataType();
else return QVariant();
default:
return QVariant();
}
}
bool setData(const QModelIndex &index, const QVariant &value, int role) {
int col = index.column();
AttributeItem * item = getItem(index);
switch (role) {
case Qt::EditRole:
case ConfigurationEditor::ItemValueRole:
if(col == 0) {
if(item->getName() != value.toString()) {
item->setName(value.toString());
}
}else if(col == 1) {
QString newType = value.toString();
if(item->getDataType() != newType) {
if(!newType.isEmpty()) {
item->setDataType(newType);
}
}
} else if(col == 2) {
if(item->getDescription() != value.toString()) {
item->setDescription(value.toString());
}
}
emit dataChanged(index, index);
}
return true;
}
QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const {
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch(section) {
case 0: return CreateExternalProcessDialog::tr("Name");
case 1: return CreateExternalProcessDialog::tr("Type");
case 2: return CreateExternalProcessDialog::tr("Description");
default: return QVariant();
}
}
return QVariant();
}
bool insertRows ( int row, int count = 0, const QModelIndex & parent = QModelIndex() ) {
Q_UNUSED(row);
Q_UNUSED(count);
beginInsertRows(parent, items.size(), items.size());
AttributeItem *newItem = new AttributeItem();
newItem->setDataType("String");
items.append(newItem);
endInsertRows();
return true;
}
bool removeRows(int row, int count = 0, const QModelIndex & parent = QModelIndex()) {
Q_UNUSED(count);
if(row >= 0 && row < items.size()) {
beginRemoveRows(parent, row, row);
items.removeAt(row);
endRemoveRows();
return true;
} else {
return false;
}
}
private:
QList<AttributeItem*> items;
PropertyDelegate *delegate;
QVariantMap types;
};
CreateExternalProcessDialog::CreateExternalProcessDialog(QWidget *p, ExternalProcessConfig *cfg, bool lastPage)
: QWizard(p), initialCfg(NULL), lastPage(lastPage) {
ui.setupUi(this);
connect(ui.addInputButton, SIGNAL(clicked()), SLOT(sl_addInput()));
connect(ui.addOutputButton, SIGNAL(clicked()), SLOT(sl_addOutput()));
connect(ui.deleteInputButton, SIGNAL(clicked()), SLOT(sl_deleteInput()));
connect(ui.deleteOutputButton, SIGNAL(clicked()), SLOT(sl_deleteOutput()));
connect(ui.addAttributeButton, SIGNAL(clicked()), SLOT(sl_addAttribute()));
connect(ui.deleteAttributeButton, SIGNAL(clicked()), SLOT(sl_deleteAttribute()));
//connect(button(QWizard::NextButton), SIGNAL(clicked()), SLOT(validateNextPage()));
connect(this, SIGNAL(currentIdChanged(int)), SLOT(sl_validatePage(int)));
//connect(button(QWizard::FinishButton), SIGNAL(clicked()), SLOT(sl_OK()));
//connect(button(QWizard::NextButton), SIGNAL(clicked()), SLOT(sl_generateTemplateString()));
QFontMetrics info(ui.descr1TextEdit->font());
ui.descr1TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM);
ui.descr2TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM);
ui.descr3TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM);
ui.descr4TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM);
ui.inputTableView->setModel(new CfgExternalToolModel(true));
ui.outputTableView->setModel(new CfgExternalToolModel(false));
ui.attributesTableView->setModel(new CfgExternalToolModelAttributes());
ui.inputTableView->setItemDelegate(new ProxyDelegate());
ui.outputTableView->setItemDelegate(new ProxyDelegate());
ui.attributesTableView->setItemDelegate(new ProxyDelegate());
ui.inputTableView->horizontalHeader()->setStretchLastSection(true);
ui.outputTableView->horizontalHeader()->setStretchLastSection(true);
ui.attributesTableView->horizontalHeader()->setStretchLastSection(true);
ui.inputTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui.outputTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui.attributesTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
QFontMetrics fm(ui.inputTableView->font());
ui.inputTableView->setColumnWidth(1, fm.width(SEQ_WITH_ANNS)*1.5);
ui.outputTableView->setColumnWidth(1, fm.width(SEQ_WITH_ANNS)*1.5);
initialCfg = new ExternalProcessConfig(*cfg);
init(cfg);
editing = true;
connect(ui.nameLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(sl_validateName(const QString &)));
connect(ui.templateLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(sl_validateCmdLine(const QString &)));
connect(ui.inputTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateDataModel(const QModelIndex &, const QModelIndex &)));
connect(ui.outputTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateDataModel(const QModelIndex &, const QModelIndex &)));
connect(ui.attributesTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateAttributeModel(const QModelIndex &, const QModelIndex &)));
descr1 = ui.descr1TextEdit->toHtml();
//validateNextPage();
}
static void clearModel(QAbstractItemModel *model) {
int count = model->rowCount();
while (count > 0) {
model->removeRow(0);
count--;
}
}
void CreateExternalProcessDialog::init(ExternalProcessConfig *cfg) {
int ind = 0;
clearModel(ui.inputTableView->model());
foreach(const DataConfig &dataCfg, cfg->inputs) {
ui.inputTableView->model()->insertRow(0, QModelIndex());
QModelIndex index = ui.inputTableView->model()->index(ind,0);
ui.inputTableView->model()->setData(index, dataCfg.attrName);
index = ui.inputTableView->model()->index(ind,1);
ui.inputTableView->model()->setData(index, dataCfg.type);
index = ui.inputTableView->model()->index(ind,2);
ui.inputTableView->model()->setData(index, dataCfg.format);
index = ui.inputTableView->model()->index(ind,3);
ui.inputTableView->model()->setData(index, dataCfg.description);
ind++;
}
ind = 0;
clearModel(ui.outputTableView->model());
foreach(const DataConfig &dataCfg, cfg->outputs) {
ui.outputTableView->model()->insertRow(0, QModelIndex());
QModelIndex index = ui.outputTableView->model()->index(ind,0);
ui.outputTableView->model()->setData(index, dataCfg.attrName);
index = ui.outputTableView->model()->index(ind,1);
ui.outputTableView->model()->setData(index, dataCfg.type);
index = ui.outputTableView->model()->index(ind,2);
ui.outputTableView->model()->setData(index, dataCfg.format);
index = ui.outputTableView->model()->index(ind,3);
ui.outputTableView->model()->setData(index, dataCfg.description);
ind++;
}
ind = 0;
clearModel(ui.attributesTableView->model());
foreach(const AttributeConfig &attrCfg, cfg->attrs) {
ui.attributesTableView->model()->insertRow(0, QModelIndex());
QModelIndex index = ui.attributesTableView->model()->index(ind,0);
ui.attributesTableView->model()->setData(index, attrCfg.attrName);
index = ui.attributesTableView->model()->index(ind,1);
ui.attributesTableView->model()->setData(index, attrCfg.type);
index = ui.attributesTableView->model()->index(ind,2);
ui.attributesTableView->model()->setData(index, attrCfg.description);
ind++;
}
ui.nameLineEdit->setText(cfg->name);
ui.descriptionTextEdit->setText(cfg->description);
ui.templateLineEdit->setText(cfg->cmdLine);
ui.prompterTextEdit->setText(cfg->templateDescription);
}
void CreateExternalProcessDialog::sl_addInput() {
ui.inputTableView->model()->insertRow(0, QModelIndex());
validateDataModel();
}
void CreateExternalProcessDialog::sl_addOutput() {
ui.outputTableView->model()->insertRow(0, QModelIndex());
validateDataModel();
}
void CreateExternalProcessDialog::sl_deleteInput() {
QModelIndex index = ui.inputTableView->currentIndex();
ui.inputTableView->model()->removeRow(index.row());
validateDataModel();
}
void CreateExternalProcessDialog::sl_deleteOutput() {
QModelIndex index = ui.outputTableView->currentIndex();
ui.outputTableView->model()->removeRow(index.row());
validateDataModel();
}
void CreateExternalProcessDialog::sl_addAttribute() {
ui.attributesTableView->model()->insertRow(0, QModelIndex());
validateAttributeModel();
}
void CreateExternalProcessDialog::sl_deleteAttribute() {
QModelIndex index = ui.attributesTableView->currentIndex();
ui.attributesTableView->model()->removeRow(index.row());
validateAttributeModel();
}
CreateExternalProcessDialog::CreateExternalProcessDialog( QWidget *p /* = NULL*/ )
: QWizard(p), initialCfg(NULL), lastPage(false) {
ui.setupUi(this);
connect(ui.addInputButton, SIGNAL(clicked()), SLOT(sl_addInput()));
connect(ui.addOutputButton, SIGNAL(clicked()), SLOT(sl_addOutput()));
connect(ui.deleteInputButton, SIGNAL(clicked()), SLOT(sl_deleteInput()));
connect(ui.deleteOutputButton, SIGNAL(clicked()), SLOT(sl_deleteOutput()));
connect(ui.addAttributeButton, SIGNAL(clicked()), SLOT(sl_addAttribute()));
connect(ui.deleteAttributeButton, SIGNAL(clicked()), SLOT(sl_deleteAttribute()));
//connect(button(QWizard::FinishButton), SIGNAL(clicked()), SLOT(sl_OK()));
connect(button(QWizard::NextButton), SIGNAL(clicked()), SLOT(sl_generateTemplateString()));
//connect(button(QWizard::NextButton), SIGNAL(clicked()), SLOT(validateNextPage()));
connect(this, SIGNAL(currentIdChanged(int)), SLOT(sl_validatePage(int)));
connect(ui.nameLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(sl_validateName(const QString &)));
connect(ui.templateLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(sl_validateCmdLine(const QString &)));
ui.inputTableView->setModel(new CfgExternalToolModel(true));
ui.outputTableView->setModel(new CfgExternalToolModel(false));
ui.attributesTableView->setModel(new CfgExternalToolModelAttributes());
connect(ui.inputTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateDataModel(const QModelIndex &, const QModelIndex &)));
connect(ui.outputTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateDataModel(const QModelIndex &, const QModelIndex &)));
connect(ui.attributesTableView->model(), SIGNAL(dataChanged ( const QModelIndex &, const QModelIndex &)), SLOT(validateAttributeModel(const QModelIndex &, const QModelIndex &)));
ui.inputTableView->setItemDelegate(new ProxyDelegate());
ui.outputTableView->setItemDelegate(new ProxyDelegate());
ui.attributesTableView->setItemDelegate(new ProxyDelegate());
ui.inputTableView->horizontalHeader()->setStretchLastSection(true);
ui.outputTableView->horizontalHeader()->setStretchLastSection(true);
ui.attributesTableView->horizontalHeader()->setStretchLastSection(true);
ui.inputTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui.outputTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui.attributesTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
QFontMetrics fm(ui.inputTableView->font());
ui.inputTableView->setColumnWidth(1, fm.width(SEQ_WITH_ANNS)*1.5);
ui.outputTableView->setColumnWidth(1, fm.width(SEQ_WITH_ANNS)*1.5);
QFontMetrics info(ui.descr1TextEdit->font());
ui.descr1TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM);
ui.descr2TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM);
ui.descr3TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM);
ui.descr4TextEdit->setFixedHeight(info.height() * INFO_STRINGS_NUM);
descr1 = ui.descr1TextEdit->toHtml();
editing = false;
}
CreateExternalProcessDialog::~CreateExternalProcessDialog() {
delete initialCfg;
}
void CreateExternalProcessDialog::showEvent(QShowEvent *event) {
QDialog::showEvent(event);
if (lastPage) {
for (int i=0; i<(pageIds().size()-1); i++) {
next();
}
}
}
void CreateExternalProcessDialog::accept() {
CfgExternalToolModel *model;
cfg = new ExternalProcessConfig();
cfg->name = ui.nameLineEdit->text();
cfg->description = ui.descriptionTextEdit->toPlainText();
cfg->templateDescription = ui.prompterTextEdit->toPlainText();
model = static_cast<CfgExternalToolModel*>(ui.inputTableView->model());
foreach(CfgExternalToolItem *item, model->getItems()) {
cfg->inputs << item->itemData;
}
model = static_cast<CfgExternalToolModel*>(ui.outputTableView->model());
foreach(CfgExternalToolItem *item, model->getItems()) {
cfg->outputs << item->itemData;
}
CfgExternalToolModelAttributes *aModel = static_cast<CfgExternalToolModelAttributes*>(ui.attributesTableView->model());
foreach(AttributeItem *item, aModel->getItems()) {
AttributeConfig attributeData;
attributeData.attrName = item->getName();
attributeData.type = item->getDataType();
attributeData.description = item->getDescription();
cfg->attrs << attributeData;
}
cfg->cmdLine = ui.templateLineEdit->text();
if(!validate()) {
return;
}
if (NULL != initialCfg) {
if (!(*initialCfg == *cfg)) {
int res = QMessageBox::question(this, tr("Warning"),
tr("You have changed the structure of the element (name, slots, attributes' names and types). "
"All elements on the scene would be removed. Do you really want to change it?\n"
"You could also reset the dialog to the initial state."),
QMessageBox::Yes | QMessageBox::No | QMessageBox::Reset, QMessageBox::No);
if (QMessageBox::No == res) {
return;
} else if (QMessageBox::Reset == res) {
init(initialCfg);
return;
}
}
}
QString str = HRSchemaSerializer::actor2String(cfg);
QString dir = WorkflowSettings::getExternalToolDirectory();
QDir d(dir);
if(!d.exists()) {
d.mkdir(dir);
}
cfg->filePath = dir + cfg->name + ".etc";
QFile file(cfg->filePath);
file.open(QIODevice::WriteOnly);
file.write(str.toAscii());
file.close();
done(QDialog::Accepted);
}
bool CreateExternalProcessDialog::validate() {
QString title = tr("Create Element");
if(cfg->inputs.isEmpty() && cfg->outputs.isEmpty()) {
QMessageBox::critical(this, title, tr("Please set the input/output data."));
return false;
}
if(cfg->cmdLine.isEmpty()) {
QMessageBox::critical(this, title, tr("Please set the command line to run external tool."));
return false;
}
if(cfg->name.isEmpty()) {
QMessageBox::critical(this, title, tr("Please set the name for the new element."));
return false;
}
QRegExp invalidSymbols("[\\.,:;\\?]");
if(cfg->name.contains(invalidSymbols)) {
QMessageBox::critical(this, title, tr("Invalid symbols in the element name."));
return false;
}
if(WorkflowEnv::getProtoRegistry()->getProto(cfg->name) && !editing) {
QMessageBox::critical(this, title, tr("Element with this name already exists."));
return false;
}
invalidSymbols = QRegExp("\\W");
QStringList nameList;
foreach(const DataConfig & dc, cfg->inputs) {
if(dc.attrName.isEmpty()) {
QMessageBox::critical(this, title, tr("For one or more parameter name was not set."));
return false;
}
if(dc.attrName.contains(invalidSymbols)) {
QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName));
return false;
}
nameList << dc.attrName;
}
foreach(const DataConfig & dc, cfg->outputs) {
if(dc.attrName.isEmpty()) {
QMessageBox::critical(this, title, tr("For one or more parameter name was not set."));
return false;
}
if(dc.attrName.contains(invalidSymbols)) {
QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName));
return false;
}
nameList << dc.attrName;
}
foreach(const AttributeConfig & ac, cfg->attrs) {
if(ac.attrName.isEmpty()) {
QMessageBox::critical(this, title, tr("For one or more parameter name was not set."));
return false;
}
if(ac.attrName.contains(invalidSymbols)) {
QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(ac.attrName));
return false;
}
nameList << ac.attrName;
}
if(nameList.removeDuplicates() > 0) {
QMessageBox::critical(this, title, tr("The same name of element parameters was found"));
return false;
}
foreach(const QString &str, nameList) {
if(!cfg->cmdLine.contains("$" + str)) {
QMessageBox msgBox(this);
msgBox.setWindowTitle(title);
msgBox.setText(tr("You don't use parameter %1 in template string. Continue?").arg(str));
msgBox.addButton(tr("Continue"), QMessageBox::ActionRole);
QPushButton *cancel = msgBox.addButton(tr("Abort"), QMessageBox::ActionRole);
msgBox.exec();
if(msgBox.clickedButton() == cancel) {
return false;
}
}
}
return true;
}
void CreateExternalProcessDialog::sl_generateTemplateString() {
QString cmd = "<My tool>";
CfgExternalToolModel *model = static_cast<CfgExternalToolModel*>(ui.inputTableView->model());
foreach(CfgExternalToolItem *item, model->getItems()) {
cmd += " $" + item->itemData.attrName;
}
model = static_cast<CfgExternalToolModel*>(ui.outputTableView->model());
foreach(CfgExternalToolItem *item, model->getItems()) {
cmd += " $" + item->itemData.attrName;
}
CfgExternalToolModelAttributes *aModel = static_cast<CfgExternalToolModelAttributes*>(ui.attributesTableView->model());
int i = 0;
foreach(AttributeItem *item, aModel->getItems()) {
i++;
cmd += " -p" + QString::number(i) + " $" + item->getName();
}
ui.templateLineEdit->setText(cmd);
}
bool CreateExternalProcessDialog::validateProcessName(const QString &name, QString &error) {
if(name.isEmpty()) {
error = tr("Please set the name for the new element.");
return false;
}
QRegExp spaces("\\s");
if(name.contains(spaces)) {
error = tr("Spaces in the element name.");
return false;
}
QRegExp invalidSymbols("\\W");
if(name.contains(invalidSymbols)) {
error = tr("Invalid symbols in the element name.");
return false;
}
if(WorkflowEnv::getProtoRegistry()->getProto(name) && !editing) {
error = tr("Element with this name already exists.");
return false;
}
return true;
}
static QString statusTemplate = QString("<font color=\"%1\">%2</font>");
void CreateExternalProcessDialog::sl_validateName( const QString &text) {
QString error;
bool res = validateProcessName(text, error);
button(QWizard::NextButton)->setEnabled(res);
QString statusStr;
if (res) {
statusStr = statusTemplate.arg("green").arg(tr("It is the correct name"));
} else {
statusStr = statusTemplate.arg("red").arg(error);
}
ui.descr1TextEdit->setText(descr1.arg(statusStr));
}
void CreateExternalProcessDialog::sl_validateCmdLine( const QString & text) {
if(text.isEmpty()) {
button(QWizard::FinishButton)->setEnabled(false);
} else {
button(QWizard::FinishButton)->setEnabled(true);
}
}
void CreateExternalProcessDialog::validateDataModel(const QModelIndex &, const QModelIndex & ) {
bool res = true;
CfgExternalToolModel *model;
QRegExp invalidSymbols("\\W");
QStringList nameList;
model = static_cast<CfgExternalToolModel*>(ui.inputTableView->model());
foreach(CfgExternalToolItem *item, model->getItems()) {
if(item->itemData.attrName.isEmpty()) {
//QMessageBox::critical(this, title, tr("For one or more parameter name was not set."));
res = false;
}
if(item->itemData.attrName.contains(invalidSymbols)) {
//QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName));
res = false;
}
nameList << item->itemData.attrName;
}
model = static_cast<CfgExternalToolModel*>(ui.outputTableView->model());
foreach(CfgExternalToolItem *item, model->getItems()) {
if(item->itemData.attrName.isEmpty()) {
//QMessageBox::critical(this, title, tr("For one or more parameter name was not set."));
res = false;
}
if(item->itemData.attrName.contains(invalidSymbols)) {
//QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName));
res = false;
}
nameList << item->itemData.attrName;
}
if(nameList.removeDuplicates() > 0) {
//QMessageBox::critical(this, title, tr("The same name of element parameters was found"));
res = false;
}
if(nameList.isEmpty()) {
res = false;
}
button(QWizard::NextButton)->setEnabled(res);
}
void CreateExternalProcessDialog::validateAttributeModel(const QModelIndex &, const QModelIndex & ) {
bool res = true;
CfgExternalToolModel *model;
QRegExp invalidSymbols("\\W");
QStringList nameList;
model = static_cast<CfgExternalToolModel*>(ui.inputTableView->model());
foreach(CfgExternalToolItem *item, model->getItems()) {
if(item->itemData.attrName.isEmpty()) {
//QMessageBox::critical(this, title, tr("For one or more parameter name was not set."));
res = false;
}
if(item->itemData.attrName.contains(invalidSymbols)) {
//QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName));
res = false;
}
nameList << item->itemData.attrName;
}
model = static_cast<CfgExternalToolModel*>(ui.outputTableView->model());
foreach(CfgExternalToolItem *item, model->getItems()) {
if(item->itemData.attrName.isEmpty()) {
//QMessageBox::critical(this, title, tr("For one or more parameter name was not set."));
res = false;
}
if(item->itemData.attrName.contains(invalidSymbols)) {
//QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(dc.attrName));
res = false;
}
nameList << item->itemData.attrName;
}
CfgExternalToolModelAttributes *aModel = static_cast<CfgExternalToolModelAttributes*>(ui.attributesTableView->model());
foreach(AttributeItem *item, aModel->getItems()) {
if(item->getName().isEmpty()) {
//QMessageBox::critical(this, title, tr("For one or more parameter name was not set."));
res = false;
}
if(item->getName().contains(invalidSymbols)) {
//QMessageBox::critical(this, title, tr("Invalid symbols in a name.").arg(ac.attrName));
res = false;
}
nameList << item->getName();
}
if(nameList.removeDuplicates() > 0) {
//QMessageBox::critical(this, title, tr("The same name of element parameters was found"));
res = false;
}
button(QWizard::NextButton)->setEnabled(res);
}
void CreateExternalProcessDialog::validateNextPage() {
int id = currentId();
switch(id) {
case 0:
sl_validateName(ui.nameLineEdit->text());
break;
case 1:
validateDataModel();
break;
case 2:
validateAttributeModel();
case 3:
sl_validateCmdLine(ui.templateLineEdit->text());
}
}
void CreateExternalProcessDialog::sl_validatePage(int id) {
switch(id) {
case 0:
sl_validateName(ui.nameLineEdit->text());
break;
case 1:
validateDataModel();
break;
case 2:
validateAttributeModel();
case 3:
sl_validateCmdLine(ui.templateLineEdit->text());
}
}
}
| 38.228053 | 182 | 0.63817 | [
"model"
] |
b0fb01fa7b1be34a32493fbb49659bb615ccd454 | 1,178 | cpp | C++ | LeetCode/100/67.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | LeetCode/100/67.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | LeetCode/100/67.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | // created by Kona @VSCode
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <queue>
#include <vector>
#include <string.h>
// #define LOCAL_TEST
typedef long long ll;
using std::cin;
using std::cout;
using std::endl;
using std::map;
using std::queue;
using std::string;
using std::vector;
class Solution {
public:
string addBinary(string a, string b) {
int i = a.size(), j = b.size();
int end = std::max(j, i) + 1;
string res(end, '0');
int rem = 0;
while (i and j) {
int tmp = a[--i] - '0' + b[--j] - '0' + rem;
res[--end] = tmp % 2 + '0';
rem = tmp / 2;
}
while (i) {
int tmp = a[--i] - '0' + rem;
res[--end] = tmp % 2 + '0';
rem = tmp / 2;
}
while (j) {
int tmp = b[--j] - '0' + rem;
res[--end] = tmp % 2 + '0';
rem = tmp / 2;
}
if (rem)
res[--end] = rem + '0';
return res.substr(end);
}
};
int main() {
std::ios_base::sync_with_stdio(false);
#ifdef LOCAL_TEST
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* code */
cout << Solution().addBinary("1", "111") << endl;
return 0;
} | 19.633333 | 51 | 0.526316 | [
"vector"
] |
b0fb5f8d00c706d04b8f2f84fdc1b9d26a8dd34d | 31,360 | cpp | C++ | matlab/external/external_codes/sfop-1.0/src/CImageCl.cpp | kmyid/TILDE | a9fcedd805a1531144b6701187ad061055c12a99 | [
"ImageMagick",
"Unlicense"
] | 36 | 2015-06-05T22:09:34.000Z | 2019-01-06T12:15:45.000Z | matlab/external/external_codes/sfop-1.0/src/CImageCl.cpp | Raverstern/TILDE | a5c2b98835fe61ca20f3139c1d82ab97f5f1779d | [
"ImageMagick",
"Unlicense"
] | 5 | 2020-01-02T15:01:36.000Z | 2021-12-05T18:05:35.000Z | matlab/external/external_codes/sfop-1.0/src/CImageCl.cpp | Raverstern/TILDE | a5c2b98835fe61ca20f3139c1d82ab97f5f1779d | [
"ImageMagick",
"Unlicense"
] | 18 | 2015-06-11T01:26:18.000Z | 2018-07-26T08:46:25.000Z | #include "CImageCl.h"
namespace SFOP {
COpenCl* CImageCl::s_opencl_p = NULL;
void CImageCl::initOpenCl()
{
std::string kernelNames[] = {
"downsample", "findLocalMax", "convRow", "convCol",
"hessian", "inverse", "gradient", "solver", "negDefinite", "filter",
"triSqr", "lambda2", "triSqrAlpha", "triSum", "precision", "bestOmega"
};
s_opencl_p = new COpenCl("sfopKernels.cl", kernelNames, NUM_KERNELS);
if (!s_opencl_p) {
std::cerr << "Error in CImageCl::initOpenCl(): new COpenCl() failed." << std::endl;
exit(1);
}
}
cl_mem CImageCl::newMem(
const size_t f_size) const
{
cl_int l_err = CL_SUCCESS;
cl_mem l_result_p = clCreateBuffer(s_opencl_p->context(), CL_MEM_READ_WRITE, f_size, NULL, &l_err);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCL::newMem(): clCreateBuffer() failed." << std::endl;
exit(1);
}
return l_result_p;
}
void CImageCl::freeMem(
cl_mem f_mem_p) const
{
if (f_mem_p == NULL) {
std::cerr << "Error in CImageCl::~CImageCl(): f_mem_p is NULL." << std::endl;
exit(1);
}
cl_int l_err = clReleaseMemObject(f_mem_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::~CImageCl(): clReleaseMemObject() failed." << std::endl;
exit(1);
}
f_mem_p = NULL;
}
CImageCl::CImageCl() :
m_mem_p(NULL), m_width(0), m_height(0)
{
if (!s_opencl_p) initOpenCl();
}
CImageCl::CImageCl(
const cl_mem f_mem_p,
const unsigned int f_width,
const unsigned int f_height) :
m_mem_p(f_mem_p), m_width(f_width), m_height(f_height)
{
cl_int l_err = clRetainMemObject(f_mem_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::CImageCl(cl_mem, int, int): clRetainMemObject() failed." << std::endl;
exit(1);
}
}
CImageCl::CImageCl(
const cimg_library::CImg<float>& f_img) :
m_mem_p(NULL), m_width(f_img.width()), m_height(f_img.height())
{
if (!s_opencl_p) initOpenCl();
cl_int l_err = CL_SUCCESS;
m_mem_p = clCreateBuffer(s_opencl_p->context(), CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float) * m_width * m_height, (void*)f_img.data(), &l_err);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::CImageCl(CImg): clCreateBuffer() failed." << std::endl;
exit(1);
}
}
CImageCl::CImageCl(
const EFilterNames f_filterName,
const float f_sigma) :
m_mem_p(NULL), m_width(2 * (int)(4.0f * f_sigma) + 1), m_height(1)
{
if (!s_opencl_p) initOpenCl();
const unsigned short int l_kSize = 4.0f * f_sigma;
cl_int l_err = CL_SUCCESS;
m_mem_p = newMem(sizeof(cl_float) * m_width);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FIL], 0, sizeof(short), (void*)&f_filterName);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FIL], 1, sizeof(float), (void*)&f_sigma);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FIL], 2, sizeof(short), (void*)&l_kSize);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FIL], 3, sizeof(cl_mem), (void*)&m_mem_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::CImageCl(EFilternames, float): clSetKernelArg() failed." << std::endl;
exit(1);
}
size_t l_globalWorksize_p = m_width;
runKernel(FIL, &l_globalWorksize_p);
}
CImageCl::~CImageCl()
{
freeMem(m_mem_p);
}
void CImageCl::load(const char f_filename[])
{
cimg_library::CImg<float> l_loader;
l_loader.load(f_filename);
if (l_loader.spectrum() > 1) l_loader.RGBtoHSV().channel(2);
while (l_loader.max() > 1) l_loader /= 255.0f;
unsigned int modX = ROWS_BLOCKDIM_X * ROWS_RESULT_STEPS;
unsigned int modY = COLUMNS_BLOCKDIM_Y * COLUMNS_RESULT_STEPS;
m_width = ((l_loader.width() - 1) / modX + 1) * modX;
m_height = ((l_loader.height() - 1) / modY + 1) * modY;
l_loader.crop(0, 0, m_width - 1, m_height - 1, true);
cl_int l_err = CL_SUCCESS;
m_mem_p = clCreateBuffer(s_opencl_p->context(), CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float) * m_width * m_height, (void*)l_loader.data(), &l_err);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::load(): clCreateBuffer() failed." << std::endl;
exit(1);
}
}
void CImageCl::runKernel(
const unsigned int f_kernel,
const size_t* f_globalWorksize_p,
const size_t* f_localWorksize_p,
const unsigned int f_dim) const
{
const size_t l_defaultSize = 1;
const size_t* l_localWorksize_p = f_localWorksize_p ? f_localWorksize_p : &l_defaultSize;
const size_t* l_globalWorksize_p = f_globalWorksize_p ? f_globalWorksize_p : &l_defaultSize;
cl_int l_err = clEnqueueNDRangeKernel(
s_opencl_p->queue(), s_opencl_p->kernels()[f_kernel],
f_dim, NULL, l_globalWorksize_p, l_localWorksize_p, 0, NULL, NULL);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::runKernel(): clEnqueueNDRangeKernel() failed." << std::endl;
exit(1);
}
l_err = clFinish(s_opencl_p->queue());
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::runKernel(): clFinish() failed." << std::endl;
exit(1);
}
}
CImage* CImageCl::conv(
const CImage *f_rowFilter_p,
const CImage *f_colFilter_p)
{
cl_int l_rowRadius = f_rowFilter_p->width() * f_rowFilter_p->height() / 2;
cl_int l_colRadius = f_colFilter_p->width() * f_colFilter_p->height() / 2;
cl_mem l_tmp_p = newMem(sizeof(cl_float) * m_width * m_height);
cl_mem l_rowFilter_mask_p = dynamic_cast<const CImageCl*>(f_rowFilter_p)->mem_p();
cl_mem l_colFilter_mask_p = dynamic_cast<const CImageCl*>(f_colFilter_p)->mem_p();
// run first kernel
size_t l_localWorkSizeRow_p[2] = {ROWS_BLOCKDIM_X, ROWS_BLOCKDIM_Y};
size_t l_globalWorkSizeRow_p[2] = {m_width / ROWS_RESULT_STEPS, m_height};
cl_int l_err = CL_SUCCESS;
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVR], 0, sizeof(cl_mem), (void*)&l_tmp_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVR], 1, sizeof(cl_mem), (void*)&m_mem_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVR], 2, sizeof(cl_mem), (void*)&l_rowFilter_mask_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVR], 3, sizeof(cl_int), (void*)&m_width);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVR], 4, sizeof(cl_int), (void*)&m_height);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVR], 5, sizeof(cl_int), (void*)&m_width);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVR], 6, sizeof(cl_int), (void*)&l_rowRadius);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::conv(): clSetKernelArg() failed." << std::endl;
exit(1);
}
runKernel(CONVR, l_globalWorkSizeRow_p, l_localWorkSizeRow_p, 2);
// run second kernel
size_t l_localWorkSizeCol_p[2] = {COLUMNS_BLOCKDIM_X, COLUMNS_BLOCKDIM_Y};
size_t l_globalWorkSizeCol_p[2] = {m_width, m_height / COLUMNS_RESULT_STEPS};
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVC], 0, sizeof(cl_mem), (void*)&m_mem_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVC], 1, sizeof(cl_mem), (void*)&l_tmp_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVC], 2, sizeof(cl_mem), (void*)&l_colFilter_mask_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVC], 3, sizeof(cl_int), (void*)&m_width);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVC], 4, sizeof(cl_int), (void*)&m_height);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVC], 5, sizeof(cl_int), (void*)&m_width);
l_err |= clSetKernelArg(s_opencl_p->kernels()[CONVC], 6, sizeof(cl_int), (void*)&l_colRadius);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::conv(): clSetKernelArg() failed." << std::endl;
exit(1);
}
runKernel(CONVC, l_globalWorkSizeCol_p, l_localWorkSizeCol_p, 2);
// clean up
l_err = clReleaseMemObject(l_tmp_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::conv(): clReleaseMemObject() failed." << std::endl;
exit(1);
}
return this;
}
void CImageCl::triSqr(
const CImage* f_gx_p,
const CImage* f_gy_p,
CImage* &f_gx2_p,
CImage* &f_gxy_p,
CImage* &f_gy2_p) const
{
unsigned int l_width = f_gx_p->width();
unsigned int l_height = f_gx_p->height();
cl_mem l_gx_p = dynamic_cast<const CImageCl*>(f_gx_p)->mem_p();
cl_mem l_gy_p = dynamic_cast<const CImageCl*>(f_gy_p)->mem_p();
cl_mem l_gx2_p = newMem(sizeof(cl_float) * l_width * l_height);
cl_mem l_gxy_p = newMem(sizeof(cl_float) * l_width * l_height);
cl_mem l_gy2_p = newMem(sizeof(cl_float) * l_width * l_height);
cl_int l_err = CL_SUCCESS;
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISQR], 0, sizeof(cl_mem), (void*)&l_gx_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISQR], 1, sizeof(cl_mem), (void*)&l_gy_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISQR], 2, sizeof(cl_mem), (void*)&l_gx2_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISQR], 3, sizeof(cl_mem), (void*)&l_gxy_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISQR], 4, sizeof(cl_mem), (void*)&l_gy2_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::triSqr(): clSetKernelArg() failed." << std::endl;
exit(1);
}
size_t l_global_size = (size_t) l_width * l_height;
runKernel(TRISQR, &l_global_size);
f_gx2_p = new CImageCl(l_gx2_p, l_width, l_height);
f_gxy_p = new CImageCl(l_gxy_p, l_width, l_height);
f_gy2_p = new CImageCl(l_gy2_p, l_width, l_height);
freeMem(l_gx2_p);
freeMem(l_gxy_p);
freeMem(l_gy2_p);
}
CImage* CImageCl::lambda2(
const float f_M,
const CImage* f_Nxx_p,
const CImage* f_Nxy_p,
const CImage* f_Nyy_p) const
{
unsigned int l_width = f_Nxx_p->width();
unsigned int l_height = f_Nxx_p->height();
cl_mem l_Nxx_p = dynamic_cast<const CImageCl*>(f_Nxx_p)->mem_p();
cl_mem l_Nxy_p = dynamic_cast<const CImageCl*>(f_Nxy_p)->mem_p();
cl_mem l_Nyy_p = dynamic_cast<const CImageCl*>(f_Nyy_p)->mem_p();
cl_mem l_lambda2_p = newMem(sizeof(cl_float) * l_width * l_height);
cl_int l_err = CL_SUCCESS;
l_err |= clSetKernelArg(s_opencl_p->kernels()[LAMBDA2], 0, sizeof(float), (void*)&f_M);
l_err |= clSetKernelArg(s_opencl_p->kernels()[LAMBDA2], 1, sizeof(cl_mem), (void*)&l_Nxx_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[LAMBDA2], 2, sizeof(cl_mem), (void*)&l_Nxy_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[LAMBDA2], 3, sizeof(cl_mem), (void*)&l_Nyy_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[LAMBDA2], 4, sizeof(cl_mem), (void*)&l_lambda2_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::lambda2(): clSetKernelArg() failed." << std::endl;
exit(1);
}
size_t l_global_size = (size_t) l_width * l_height;
runKernel(LAMBDA2, &l_global_size);
CImageCl* l_result_p = new CImageCl(l_lambda2_p, l_width, l_height);
freeMem(l_lambda2_p);
return l_result_p;
}
void CImageCl::triSqrAlpha(
const float f_alpha,
const CImage* f_gx_p,
const CImage* f_gy_p,
CImage* &f_gx2a_p,
CImage* &f_2gxya_p,
CImage* &f_gy2a_p) const
{
unsigned int l_width = f_gx_p->width();
unsigned int l_height = f_gx_p->height();
cl_mem l_gx_p = dynamic_cast<const CImageCl*>(f_gx_p)->mem_p();
cl_mem l_gy_p = dynamic_cast<const CImageCl*>(f_gy_p)->mem_p();
cl_mem l_gx2a_p = newMem(sizeof(cl_float) * l_width * l_height);
cl_mem l_2gxya_p = newMem(sizeof(cl_float) * l_width * l_height);
cl_mem l_gy2a_p = newMem(sizeof(cl_float) * l_width * l_height);
cl_int l_err = CL_SUCCESS;
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISQRALPHA], 0, sizeof(float), (void*)&f_alpha);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISQRALPHA], 1, sizeof(cl_mem), (void*)&l_gx_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISQRALPHA], 2, sizeof(cl_mem), (void*)&l_gy_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISQRALPHA], 3, sizeof(cl_mem), (void*)&l_gx2a_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISQRALPHA], 4, sizeof(cl_mem), (void*)&l_2gxya_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISQRALPHA], 5, sizeof(cl_mem), (void*)&l_gy2a_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::triSqrAlpha(): clSetKernelArg() failed." << std::endl;
exit(1);
}
size_t l_global_size = (size_t) l_width * l_height;
runKernel(TRISQRALPHA, &l_global_size);
f_gx2a_p = new CImageCl(l_gx2a_p, l_width, l_height);
f_2gxya_p = new CImageCl(l_2gxya_p, l_width, l_height);
f_gy2a_p = new CImageCl(l_gy2a_p, l_width, l_height);
freeMem(l_gx2a_p);
freeMem(l_2gxya_p);
freeMem(l_gy2a_p);
}
CImage* CImageCl::triSum(
const CImage* f_a_p,
const CImage* f_b_p,
const CImage* f_c_p) const
{
unsigned int l_width = f_a_p->width();
unsigned int l_height = f_a_p->height();
cl_mem l_a_p = dynamic_cast<const CImageCl*>(f_a_p)->mem_p();
cl_mem l_b_p = dynamic_cast<const CImageCl*>(f_b_p)->mem_p();
cl_mem l_c_p = dynamic_cast<const CImageCl*>(f_c_p)->mem_p();
cl_mem l_sum_p = newMem(sizeof(cl_float) * l_width * l_height);
cl_int l_err = CL_SUCCESS;
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISUM], 0, sizeof(cl_mem), (void*)&l_a_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISUM], 1, sizeof(cl_mem), (void*)&l_b_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISUM], 2, sizeof(cl_mem), (void*)&l_c_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[TRISUM], 3, sizeof(cl_mem), (void*)&l_sum_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::triSum(): clSetKernelArg() failed." << std::endl;
exit(1);
}
size_t l_global_size = (size_t) l_width * l_height;
runKernel(TRISUM, &l_global_size);
CImageCl* l_result_p = new CImageCl(l_sum_p, l_width, l_height);
freeMem(l_sum_p);
return l_result_p;
}
CImage* CImageCl::precision(
const float f_factor,
const CImage* f_lambda2_p,
const CImage* f_omega_p) const
{
unsigned int l_width = f_lambda2_p->width();
unsigned int l_height = f_lambda2_p->height();
cl_mem l_lambda2_p = dynamic_cast<const CImageCl*>(f_lambda2_p)->mem_p();
cl_mem l_omega_p = dynamic_cast<const CImageCl*>(f_omega_p )->mem_p();
cl_mem l_precision_p = newMem(sizeof(cl_float) * l_width * l_height);
cl_int l_err = CL_SUCCESS;
l_err |= clSetKernelArg(s_opencl_p->kernels()[PRECISION], 0, sizeof(float), (void*)&f_factor);
l_err |= clSetKernelArg(s_opencl_p->kernels()[PRECISION], 1, sizeof(cl_mem), (void*)&l_lambda2_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[PRECISION], 2, sizeof(cl_mem), (void*)&l_omega_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[PRECISION], 3, sizeof(cl_mem), (void*)&l_precision_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::precision(): clSetKernelArg() failed." << std::endl;
exit(1);
}
size_t l_global_size = (size_t) l_width * l_height;
runKernel(PRECISION, &l_global_size);
CImageCl* l_result_p = new CImageCl(l_precision_p, l_width, l_height);
freeMem(l_precision_p);
return l_result_p;
}
CImage* CImageCl::bestOmega(
const CImage* f_omega0_p,
const CImage* f_omega60_p,
const CImage* f_omega120_p) const
{
unsigned int l_width = f_omega0_p->width();
unsigned int l_height = f_omega0_p->height();
cl_mem l_omega0_p = dynamic_cast<const CImageCl*>(f_omega0_p)->mem_p();
cl_mem l_omega60_p = dynamic_cast<const CImageCl*>(f_omega60_p)->mem_p();
cl_mem l_omega120_p = dynamic_cast<const CImageCl*>(f_omega120_p)->mem_p();
cl_mem l_omegaMin_p = newMem(sizeof(cl_float) * l_width * l_height);
cl_int l_err = CL_SUCCESS;
l_err |= clSetKernelArg(s_opencl_p->kernels()[BESTOMEGA], 0, sizeof(cl_mem), (void*)&l_omega0_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[BESTOMEGA], 1, sizeof(cl_mem), (void*)&l_omega60_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[BESTOMEGA], 2, sizeof(cl_mem), (void*)&l_omega120_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[BESTOMEGA], 3, sizeof(cl_mem), (void*)&l_omegaMin_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::bestOmega(): clSetKernelArg() failed." << std::endl;
exit(1);
}
size_t l_global_size = (size_t) l_width * l_height;
runKernel(BESTOMEGA, &l_global_size);
CImageCl* l_result_p = new CImageCl(l_omegaMin_p, l_width, l_height);
freeMem(l_omegaMin_p);
return l_result_p;
}
CImage* CImageCl::downsample()
{
unsigned int l_oldWidth = m_width;
unsigned int l_oldHeight = m_height;
unsigned int modX = ROWS_BLOCKDIM_X * ROWS_RESULT_STEPS;
unsigned int modY = COLUMNS_BLOCKDIM_Y * COLUMNS_RESULT_STEPS;
m_width = ((m_width / 2 - 1) / modX + 1) * modX;
m_height = ((m_height / 2 - 1) / modY + 1) * modY;
cl_int l_err = CL_SUCCESS;
cl_mem l_result_p = newMem(sizeof(cl_float) * m_width * m_height);
l_err |= clSetKernelArg(s_opencl_p->kernels()[DOWN], 0, sizeof(cl_mem), (void*)&m_mem_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[DOWN], 1, sizeof(cl_int), (void*)&l_oldWidth);
l_err |= clSetKernelArg(s_opencl_p->kernels()[DOWN], 2, sizeof(cl_int), (void*)&l_oldHeight);
l_err |= clSetKernelArg(s_opencl_p->kernels()[DOWN], 3, sizeof(cl_int), (void*)&m_width);
l_err |= clSetKernelArg(s_opencl_p->kernels()[DOWN], 4, sizeof(cl_mem), (void*)&l_result_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::downsample(): clSetKernelArg() failed." << std::endl;
exit(1);
}
size_t l_localWorksize_p[2] = {1, 1};
size_t l_globalWorksize_p[2] = {m_width, m_height};
runKernel(DOWN, l_globalWorksize_p, l_localWorksize_p, 2);
freeMem(m_mem_p);
m_mem_p = l_result_p;
return this;
}
CImage* CImageCl::clone() const
{
cl_mem l_copy_p = newMem(sizeof(cl_float) * m_width * m_height);
cl_int l_err = clEnqueueCopyBuffer(s_opencl_p->queue(), m_mem_p, l_copy_p, 0, 0,
(size_t) (sizeof(cl_float) * m_width * m_height), 0, NULL, NULL);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::clone(): clEnqueueCopyBuffer() failed." << std::endl;
exit(1);
}
l_err = clFinish(s_opencl_p->queue());
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::clone(): clFinish() failed." << std::endl;
exit(1);
}
CImageCl* l_result_p = new CImageCl(l_copy_p, m_width, m_height);
freeMem(l_copy_p);
return l_result_p;
}
cimg_library::CImg<float> CImageCl::computeGradient(
const cimg_library::CImg<float> &f_cube) const
{
cl_int l_err = CL_SUCCESS;
cl_mem l_matrix_p = clCreateBuffer(s_opencl_p->context(),
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float) * 3 * 3 * 3, (void*)f_cube.data(), &l_err);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeGradient(): clCreateBuffer() failed." << std::endl;
exit(1);
}
cl_mem l_result_p = newMem(sizeof(cl_float) * 3);
l_err |= clSetKernelArg(s_opencl_p->kernels()[GRD], 0, sizeof(cl_mem), (void*)&l_matrix_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[GRD], 1, sizeof(cl_mem), (void*)&l_result_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeGradient(): clSetKernelArg() failed." << std::endl;
exit(1);
}
runKernel(GRD);
l_err = clReleaseMemObject(l_matrix_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeGradient(): clReleaseMemObject() failed." << std::endl;
exit(1);
}
CImageCl l_result = CImageCl(l_result_p, 1, 3);
freeMem(l_result_p);
return l_result.asCimg();
}
cimg_library::CImg<float> CImageCl::computeHessian(
const cimg_library::CImg<float> &f_cube) const
{
cl_int l_err = CL_SUCCESS;
cl_mem l_matrix_p = clCreateBuffer(s_opencl_p->context(),
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float) * 3 * 3 * 3, (void*)f_cube.data(), &l_err);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeHessian(): clCreateBuffer() failed." << std::endl;
exit(1);
}
cl_mem l_result_p = newMem(sizeof(cl_float) * 3 * 3);
l_err |= clSetKernelArg(s_opencl_p->kernels()[HES], 0, sizeof(cl_mem), (void*)&l_matrix_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[HES], 1, sizeof(cl_mem), (void*)&l_result_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeHessian(): clSetKernelArg() failed." << std::endl;
exit(1);
}
runKernel(HES);
l_err = clReleaseMemObject(l_matrix_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeHessian(): clReleaseMemObject() failed." << std::endl;
exit(1);
}
CImageCl l_result = CImageCl(l_result_p, 3, 3);
freeMem(l_result_p);
return l_result.asCimg();
}
cimg_library::CImg<float> CImageCl::computeInverse(
const cimg_library::CImg<float> &f_matrix) const
{
cl_int l_err = CL_SUCCESS;
cl_mem l_matrix_p = clCreateBuffer(s_opencl_p->context(),
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float) * 3 * 3, (void*)f_matrix.data(), &l_err);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeInverse(): clCreateBuffer() failed." << std::endl;
exit(1);
}
cl_mem l_result_p = newMem(sizeof(cl_float) * 3 * 3);
l_err |= clSetKernelArg(s_opencl_p->kernels()[INV], 0, sizeof(cl_mem), (void*)&l_matrix_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[INV], 1, sizeof(cl_mem), (void*)&l_result_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeInverse(): clSetKernelArg() failed." << std::endl;
exit(1);
}
runKernel(INV);
l_err = clReleaseMemObject(l_matrix_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeInverse(): clReleaseMemObject() failed." << std::endl;
exit(1);
}
CImageCl l_result = CImageCl(l_result_p, 3, 3);
freeMem(l_result_p);
return l_result.asCimg();
}
cimg_library::CImg<float> CImageCl::computeSolver(
const cimg_library::CImg<float> &f_matrix,
const cimg_library::CImg<float> &f_vector) const
{
cl_int l_err = CL_SUCCESS;
cl_mem l_matrix_p = clCreateBuffer(s_opencl_p->context(),
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float) * 3 * 3, (void*)f_matrix.data(), &l_err);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeSolver(): clCreateBuffer() (matrix) failed." << std::endl;
exit(1);
}
cl_mem l_vector_p = clCreateBuffer(s_opencl_p->context(),
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float) * 3, (void*)f_vector.data(), &l_err);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeSolver(): clCreateBuffer() (vector) failed." << std::endl;
exit(1);
}
cl_mem l_result_p = newMem(sizeof(cl_float) * 3);
l_err |= clSetKernelArg(s_opencl_p->kernels()[SLV], 0, sizeof(cl_mem), (void*)&l_matrix_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[SLV], 1, sizeof(cl_mem), (void*)&l_vector_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[SLV], 2, sizeof(cl_mem), (void*)&l_result_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeSolver(): clSetKernelArg() failed." << std::endl;
exit(1);
}
runKernel(SLV);
l_err = clReleaseMemObject(l_matrix_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeSolver(): clReleaseMemObject() (matrix) failed." << std::endl;
exit(1);
}
l_err = clReleaseMemObject(l_vector_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeSolver(): clReleaseMemObject() (vector) failed." << std::endl;
exit(1);
}
CImageCl l_result = CImageCl(l_result_p, 1, 3);
freeMem(l_result_p);
return l_result.asCimg();
}
bool CImageCl::computeIfNegDefinite(
const cimg_library::CImg<float> &f_matrix) const
{
cl_int l_err = CL_SUCCESS;
cl_mem l_matrix_p = clCreateBuffer(s_opencl_p->context(),
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float) * 3 * 3, (void*)f_matrix.data(), &l_err);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeIfNegDefinite(): clCreateBuffer() failed." << std::endl;
exit(1);
}
cl_mem l_result_p = newMem(sizeof(cl_float));
l_err |= clSetKernelArg(s_opencl_p->kernels()[DEF], 0, sizeof(cl_mem), (void*)&l_matrix_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[DEF], 1, sizeof(cl_mem), (void*)&l_result_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeIfNegDefinite(): clSetKernelArg() failed." << std::endl;
exit(1);
}
runKernel(DEF);
l_err = clReleaseMemObject(l_matrix_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::computeIfNegDefinite(): clReleaseMemObject() failed." << std::endl;
exit(1);
}
cimg_library::CImg<float> l_cimgResult = CImageCl(l_result_p, 1, 1).asCimg();
freeMem(l_result_p);
return l_cimgResult(0) != 0.0f;
}
cimg_library::CImg<float> CImageCl::asCimg() const
{
cimg_library::CImg<float> l_cimg =
cimg_library::CImg<float>(m_width, m_height);
cl_int l_err = clEnqueueReadBuffer(s_opencl_p->queue(), m_mem_p, CL_TRUE, 0,
sizeof(cl_float) * m_width * m_height, l_cimg.data(), 0, NULL, NULL);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::asCimg(): clEnqueueReadBuffer() failed." << std::endl;
exit(1);
}
return l_cimg;
}
void CImageCl::findLocalMax(
std::list<CFeature>* f_features_p,
const CImage* f_below_p,
const CImage* f_above_p,
const CImage* f_lambda2_p,
const float f_sigma,
const unsigned int f_numLayers,
const unsigned int f_factor) const
{
unsigned int blockWidth = FLM_L_WG_S_X;
unsigned int blockHeight = FLM_L_WG_S_Y;
size_t sharedMemSize = (blockWidth + 2) * (blockHeight + 2) * sizeof(cl_float);
cl_mem l_below_p = (dynamic_cast <const CImageCl*> (f_below_p))->mem_p();
cl_mem l_above_p = (dynamic_cast <const CImageCl*> (f_above_p))->mem_p();
cl_mem l_result_p = newMem(sizeof(cl_float4) * m_width * m_height);
// run kernel with the 3 layers
cl_int l_err = CL_SUCCESS;
l_err |= clSetKernelArg(s_opencl_p->kernels()[FLM], 0, sizeof(cl_mem), (void*)&l_below_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FLM], 1, sizeof(cl_mem), (void*)&m_mem_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FLM], 2, sizeof(cl_mem), (void*)&l_above_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FLM], 3, sizeof(cl_mem), (void*)&l_result_p);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FLM], 4, sizeof(cl_int), (void*)&m_width);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FLM], 5, sizeof(cl_int), (void*)&m_height);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FLM], 6, sharedMemSize, NULL);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FLM], 7, sharedMemSize, NULL);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FLM], 8, sharedMemSize, NULL);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FLM], 9, sizeof(cl_int), (void*)&blockWidth);
l_err |= clSetKernelArg(s_opencl_p->kernels()[FLM], 10, sizeof(cl_int), (void*)&blockHeight);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::findLocalMax(): clSetKernelArg() failed." << std::endl;
exit(1);
}
size_t l_workGroupSize[2] = {FLM_L_WG_S_X, FLM_L_WG_S_Y};
size_t l_numWorkItems[2] = {
m_width + (l_workGroupSize[0] - m_width % l_workGroupSize[0]),
m_height + (l_workGroupSize[1] - m_height % l_workGroupSize[1])};
runKernel(FLM, l_numWorkItems, l_workGroupSize, 2);
// copy result float4 layer with the information for the maximas back to the cpu ram
cl_float4* l_resultCpu_p = (cl_float4*) malloc(sizeof(cl_float4) * m_width * m_height);
if (l_resultCpu_p == NULL) {
std::cerr << "Error in CImageCl::findLocalMax(): malloc() failed." << std::endl;
exit(1);
}
l_err = clEnqueueReadBuffer(s_opencl_p->queue(), l_result_p, CL_TRUE, 0,
sizeof(cl_float4) * m_width * m_height, (void*)l_resultCpu_p, 0, NULL, NULL);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::findLocalMax(): clEnqueueReadBuffer() failed." << std::endl;
exit(1);
}
// scan through 1st result layer to identify local maxima and build up a list
const cimg_library::CImg<float> l_lambda2 = f_lambda2_p->asCimg();
cimg_for_insideXY(l_lambda2, x, y, 1) {
const unsigned int l_idx = x + y * m_width;
if (l_resultCpu_p[l_idx].s[3] == 0.0f) continue;
const float l_x = l_resultCpu_p[l_idx].s[0];
const float l_y = l_resultCpu_p[l_idx].s[1];
const float l_s = l_resultCpu_p[l_idx].s[2];
const float l_p = l_resultCpu_p[l_idx].s[3];
const float l_sigma = f_sigma * pow(2.0f, l_s / f_numLayers);
const float l_l2 = l_lambda2(floor(l_x + 0.5f), floor(l_y + 0.5f));
f_features_p->push_back(CFeature(
l_x * (float) f_factor,
l_y * (float) f_factor,
l_sigma * (float) f_factor,
l_l2 / (float) f_factor / (float) f_factor,
l_p * (float) f_factor * (float) f_factor));
}
l_err = clReleaseMemObject(l_result_p);
if (!s_opencl_p->checkErr(l_err)) {
std::cerr << "Error in CImageCl::findLocalMax(): clReleaseMemObject() failed." << std::endl;
exit(1);
}
free(l_resultCpu_p);
}
}
| 44.928367 | 112 | 0.639254 | [
"vector"
] |
b0ffa21e57a0c3c1cf15945fac476e3171a876f2 | 5,872 | cc | C++ | src/lib/fidl_codec/builtin_semantic_test.cc | sysidos/fuchsia | 0c00fd3c78a9c0111af4689f1e038b3926c4dc9b | [
"BSD-3-Clause"
] | null | null | null | src/lib/fidl_codec/builtin_semantic_test.cc | sysidos/fuchsia | 0c00fd3c78a9c0111af4689f1e038b3926c4dc9b | [
"BSD-3-Clause"
] | null | null | null | src/lib/fidl_codec/builtin_semantic_test.cc | sysidos/fuchsia | 0c00fd3c78a9c0111af4689f1e038b3926c4dc9b | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include "gtest/gtest.h"
#include "library_loader.h"
#include "src/lib/fidl_codec/semantic.h"
#include "src/lib/fidl_codec/semantic_parser_test.h"
#include "src/lib/fidl_codec/wire_object.h"
namespace fidl_codec {
namespace semantic {
constexpr uint64_t kPid = 0x1234;
constexpr uint32_t kHandle = 0x1111;
constexpr uint32_t kChannel0 = 0x1000;
constexpr uint32_t kChannel1 = 0x2000;
class BuiltinSemanticTest : public SemanticParserTest {
public:
BuiltinSemanticTest();
void SetHandleSemantic(std::string_view type, std::string_view path) {
handle_semantic_.AddHandleDescription(kPid, kHandle, type, path);
}
void ExecuteWrite(const MethodSemantic* method_semantic, const StructValue* request,
const StructValue* response);
void ExecuteRead(const MethodSemantic* method_semantic, const StructValue* request,
const StructValue* response);
protected:
HandleSemantic handle_semantic_;
const zx_handle_info_t channel0_;
};
BuiltinSemanticTest::BuiltinSemanticTest() : channel0_({kChannel0, 0, 0, 0}) {
library_loader_.ParseBuiltinSemantic();
handle_semantic_.AddLinkedHandles(kPid, kChannel0, kChannel1);
}
void BuiltinSemanticTest::ExecuteWrite(const MethodSemantic* method_semantic,
const StructValue* request, const StructValue* response) {
fidl_codec::semantic::SemanticContext context(&handle_semantic_, kPid, kHandle,
ContextType::kWrite, request, response);
method_semantic->ExecuteAssignments(&context);
}
void BuiltinSemanticTest::ExecuteRead(const MethodSemantic* method_semantic,
const StructValue* request, const StructValue* response) {
fidl_codec::semantic::SemanticContext context(&handle_semantic_, kPid, kHandle,
ContextType::kRead, request, response);
method_semantic->ExecuteAssignments(&context);
}
// Check Node::Clone: request.object = handle
TEST_F(BuiltinSemanticTest, CloneWrite) {
// Checks that Node::Clone exists in fuchsia.io.
Library* library = library_loader_.GetLibraryFromName("fuchsia.io");
ASSERT_NE(library, nullptr);
library->DecodeTypes();
Interface* interface = nullptr;
library->GetInterfaceByName("fuchsia.io/Node", &interface);
ASSERT_NE(interface, nullptr);
InterfaceMethod* method = interface->GetMethodByName("Clone");
ASSERT_NE(method, nullptr);
// Checks that the builtin semantic is defined for Clone.
ASSERT_NE(method->semantic(), nullptr);
// Check that by writing on this handle:
SetHandleSemantic("dir", "/svc");
// This message (we only define the fields used by the semantic):
StructValue request(*method->request());
request.AddField("object", std::make_unique<HandleValue>(channel0_));
ExecuteWrite(method->semantic(), &request, nullptr);
// We have this handle semantic for kChannel1.
const HandleDescription* description = handle_semantic_.GetHandleDescription(kPid, kChannel1);
ASSERT_NE(description, nullptr);
ASSERT_EQ(description->type(), "dir");
ASSERT_EQ(description->path(), "/svc");
}
// Check Node::Clone: request.object = handle
TEST_F(BuiltinSemanticTest, CloneRead) {
// Checks that Node::Clone exists in fuchsia.io.
Library* library = library_loader_.GetLibraryFromName("fuchsia.io");
ASSERT_NE(library, nullptr);
library->DecodeTypes();
Interface* interface = nullptr;
library->GetInterfaceByName("fuchsia.io/Node", &interface);
ASSERT_NE(interface, nullptr);
InterfaceMethod* method = interface->GetMethodByName("Clone");
ASSERT_NE(method, nullptr);
// Checks that the builtin semantic is defined for Clone.
ASSERT_NE(method->semantic(), nullptr);
// Check that by writing on this handle:
SetHandleSemantic("dir", "/svc");
// This message (we only define the fields used by the semantic):
StructValue request(*method->request());
request.AddField("object", std::make_unique<HandleValue>(channel0_));
ExecuteRead(method->semantic(), &request, nullptr);
// We have this handle semantic for kChannel1.
const HandleDescription* description = handle_semantic_.GetHandleDescription(kPid, kChannel0);
ASSERT_NE(description, nullptr);
ASSERT_EQ(description->type(), "dir");
ASSERT_EQ(description->path(), "/svc");
}
// Check Directory::Open: request.object = handle / request.path
TEST_F(BuiltinSemanticTest, Open) {
// Checks that Directory::Open exists in fuchsia.io.
Library* library = library_loader_.GetLibraryFromName("fuchsia.io");
ASSERT_NE(library, nullptr);
library->DecodeTypes();
Interface* interface = nullptr;
library->GetInterfaceByName("fuchsia.io/Directory", &interface);
ASSERT_NE(interface, nullptr);
InterfaceMethod* method = interface->GetMethodByName("Open");
ASSERT_NE(method, nullptr);
// Checks that the builtin semantic is defined for Open.
ASSERT_NE(method->semantic(), nullptr);
// Check that by writing on this handle:
SetHandleSemantic("dir", "/svc");
// This message (we only define the fields used by the semantic):
StructValue request(*method->request());
request.AddField("path", std::make_unique<StringValue>("fuchsia.sys.Launcher"));
request.AddField("object", std::make_unique<HandleValue>(channel0_));
ExecuteWrite(method->semantic(), &request, nullptr);
// We have this handle semantic for kChannel1.
const HandleDescription* description = handle_semantic_.GetHandleDescription(kPid, kChannel1);
ASSERT_NE(description, nullptr);
ASSERT_EQ(description->type(), "dir");
ASSERT_EQ(description->path(), "/svc/fuchsia.sys.Launcher");
}
} // namespace semantic
} // namespace fidl_codec
| 38.631579 | 97 | 0.731267 | [
"object"
] |
7c028cec1eef4f8ca121e979df41121ba184c8d6 | 2,839 | cpp | C++ | tx2-setup/robust_pose_graph_optimization/buzz_slam/src/argos/simulation_random_walk/buzz_closures_quadmapper_no_sensing.cpp | SnowCarter/DOOR-SLAM | cf56d2b4b7a21ed7c6445f01600408c9dd5235c6 | [
"MIT"
] | 3 | 2021-07-05T17:59:01.000Z | 2022-03-31T12:46:25.000Z | tx2-setup/robust_pose_graph_optimization/buzz_slam/src/argos/simulation_random_walk/buzz_closures_quadmapper_no_sensing.cpp | SnowCarter/DOOR-SLAM | cf56d2b4b7a21ed7c6445f01600408c9dd5235c6 | [
"MIT"
] | null | null | null | tx2-setup/robust_pose_graph_optimization/buzz_slam/src/argos/simulation_random_walk/buzz_closures_quadmapper_no_sensing.cpp | SnowCarter/DOOR-SLAM | cf56d2b4b7a21ed7c6445f01600408c9dd5235c6 | [
"MIT"
] | 3 | 2020-03-25T16:21:25.000Z | 2021-07-05T16:37:34.000Z | #include "buzz_controller_quadmapper_no_sensing.h"
namespace buzz_quadmapper {
/****************************************/
/************ Buzz Closures *************/
/****************************************/
/****************************************/
/****************************************/
static int BuzzMoveForwardFakeOdometry(buzzvm_t vm) {
/* Push the vector components */
buzzvm_lload(vm, 1);
buzzvm_lload(vm, 2);
/* Create a new vector with that */
CVector3 translation;
int simulation_time_divider;
buzzobj_t step = buzzvm_stack_at(vm, 2);
buzzobj_t b_simulation_time_divider = buzzvm_stack_at(vm, 1);
if(step->o.type == BUZZTYPE_INT) translation.SetX(step->i.value);
else if(step->o.type == BUZZTYPE_FLOAT) translation.SetX(step->f.value);
else {
buzzvm_seterror(vm,
BUZZVM_ERROR_TYPE,
"move_forward(x,y): expected %s, got %s in first argument",
buzztype_desc[BUZZTYPE_FLOAT],
buzztype_desc[step->o.type]
);
return vm->state;
}
if(b_simulation_time_divider->o.type == BUZZTYPE_INT) simulation_time_divider = b_simulation_time_divider->i.value;
else {
buzzvm_seterror(vm,
BUZZVM_ERROR_TYPE,
"move_forward(x,y): expected %s, got %s in second argument",
buzztype_desc[BUZZTYPE_INT],
buzztype_desc[b_simulation_time_divider->o.type]
);
return vm->state;
}
/* Get pointer to the controller */
buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1));
buzzvm_gload(vm);
/* Call function */
int current_pose_id = reinterpret_cast<CBuzzControllerQuadMapperNoSensing*>(buzzvm_stack_at(vm, 1)->u.value)->MoveForwardFakeOdometry(translation, simulation_time_divider);
buzzvm_pushi(vm, current_pose_id);
return buzzvm_ret1(vm);
}
/****************************************/
/************ Registration **************/
/****************************************/
buzzvm_state CBuzzControllerQuadMapperNoSensing::RegisterFunctions() {
CBuzzControllerQuadMapper::RegisterFunctions();
buzz_slam::BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<buzz_slam::BuzzSLAMNoSensing>(m_tBuzzVM->robot)->RegisterSLAMFunctions(this->GetBuzzVM());
/* Register mapping without sensing specific functions */
buzzvm_pushs(m_tBuzzVM, buzzvm_string_register(m_tBuzzVM, "move_forward_fake_odometry", 1));
buzzvm_pushcc(m_tBuzzVM, buzzvm_function_register(m_tBuzzVM, BuzzMoveForwardFakeOdometry));
buzzvm_gstore(m_tBuzzVM);
return m_tBuzzVM->state;
}
/****************************************/
/****************************************/
REGISTER_CONTROLLER(CBuzzControllerQuadMapperNoSensing, "buzz_controller_quadmapper_no_sensing");
} | 38.364865 | 175 | 0.602677 | [
"vector"
] |
7c07140eaed4dc006ebf1411db967e92d165f643 | 262,838 | cpp | C++ | lib/wx/c_src/gen/wxe_wrapper_3.cpp | martin-g/otp | bb07f4fb30e93be9844227558ef1f83a69909eb3 | [
"Apache-2.0"
] | 1 | 2019-02-27T19:13:07.000Z | 2019-02-27T19:13:07.000Z | lib/wx/c_src/gen/wxe_wrapper_3.cpp | martin-g/otp | bb07f4fb30e93be9844227558ef1f83a69909eb3 | [
"Apache-2.0"
] | 1 | 2021-01-20T17:39:01.000Z | 2021-01-20T17:39:01.000Z | lib/wx/c_src/gen/wxe_wrapper_3.cpp | martin-g/otp | bb07f4fb30e93be9844227558ef1f83a69909eb3 | [
"Apache-2.0"
] | null | null | null | /*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2008-2020. 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.
*
* %CopyrightEnd%
*/
/***** This file is generated do not edit ****/
#include <wx/wx.h>
#include "../wxe_impl.h"
#include "../wxe_events.h"
#include "../wxe_return.h"
#include "../wxe_gl.h"
#include "wxe_macros.h"
#include "wxe_derived_dest.h"
// wxAcceleratorTable::wxAcceleratorTable
void wxAcceleratorTable_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxAcceleratorTable * Result = new EwxAcceleratorTable();
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxAcceleratorTable"));
}
// wxAcceleratorTable::wxAcceleratorTable
void wxAcceleratorTable_new_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int n;
if(!enif_get_int(env, argv[0], &n)) Badarg("n"); // int
unsigned entriesLen;
ERL_NIF_TERM entriesHead, entriesTail;
if(!enif_get_list_length(env, argv[1], &entriesLen)) Badarg("entries");
std::vector <wxAcceleratorEntry> entries;
entriesTail = argv[1];
while(!enif_is_empty_list(env, entriesTail)) {
if(!enif_get_list_cell(env, entriesTail, &entriesHead, &entriesTail)) Badarg("entries");
entries.push_back(* (wxAcceleratorEntry *) memenv->getPtr(env, entriesHead,"entries"));
};
wxAcceleratorTable * Result = new EwxAcceleratorTable(n,entries.data());
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxAcceleratorTable"));
}
// wxAcceleratorTable::IsOk
void wxAcceleratorTable_IsOk(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxAcceleratorTable *This;
This = (wxAcceleratorTable *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsOk();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxAcceleratorEntry::wxAcceleratorEntry
void wxAcceleratorEntry_new_1_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int flags=0;
int keyCode=0;
int cmd=0;
wxMenuItem * item=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[0];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "flags"))) {
if(!enif_get_int(env, tpl[1], &flags)) Badarg("flags"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "keyCode"))) {
if(!enif_get_int(env, tpl[1], &keyCode)) Badarg("keyCode"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "cmd"))) {
if(!enif_get_int(env, tpl[1], &cmd)) Badarg("cmd"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "item"))) {
item = (wxMenuItem *) memenv->getPtr(env, tpl[1], "item");
} else Badarg("Options");
};
wxAcceleratorEntry * Result = new wxAcceleratorEntry(flags,keyCode,cmd,item);
app->newPtr((void *) Result, 70, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxAcceleratorEntry"));
}
// wxAcceleratorEntry::wxAcceleratorEntry
void wxAcceleratorEntry_new_1_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxAcceleratorEntry *entry;
entry = (wxAcceleratorEntry *) memenv->getPtr(env, argv[0], "entry");
wxAcceleratorEntry * Result = new wxAcceleratorEntry(*entry);
app->newPtr((void *) Result, 70, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxAcceleratorEntry"));
}
// wxAcceleratorEntry::GetCommand
void wxAcceleratorEntry_GetCommand(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxAcceleratorEntry *This;
This = (wxAcceleratorEntry *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetCommand();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxAcceleratorEntry::GetFlags
void wxAcceleratorEntry_GetFlags(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxAcceleratorEntry *This;
This = (wxAcceleratorEntry *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetFlags();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxAcceleratorEntry::GetKeyCode
void wxAcceleratorEntry_GetKeyCode(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxAcceleratorEntry *This;
This = (wxAcceleratorEntry *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetKeyCode();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxAcceleratorEntry::Set
void wxAcceleratorEntry_Set(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxMenuItem * item=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxAcceleratorEntry *This;
This = (wxAcceleratorEntry *) memenv->getPtr(env, argv[0], "This");
int flags;
if(!enif_get_int(env, argv[1], &flags)) Badarg("flags"); // int
int keyCode;
if(!enif_get_int(env, argv[2], &keyCode)) Badarg("keyCode"); // int
int cmd;
if(!enif_get_int(env, argv[3], &cmd)) Badarg("cmd"); // int
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[4];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "item"))) {
item = (wxMenuItem *) memenv->getPtr(env, tpl[1], "item");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
This->Set(flags,keyCode,cmd,item);
}
// wxAcceleratorEntry::destroy
void wxAcceleratorEntry_destroy(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxAcceleratorEntry *This;
This = (wxAcceleratorEntry *) memenv->getPtr(env, argv[0], "This");
if(This) { ((WxeApp *) wxTheApp)->clearPtr((void *) This);
delete This;}
}
// wxCaret::wxCaret
void wxCaret_new_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *window;
window = (wxWindow *) memenv->getPtr(env, argv[0], "window");
int width;
if(!enif_get_int(env, argv[1], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[2], &height)) Badarg("height"); // int
wxCaret * Result = new wxCaret(window,width,height);
app->newPtr((void *) Result, 71, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxCaret"));
}
// wxCaret::wxCaret
void wxCaret_new_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *window;
window = (wxWindow *) memenv->getPtr(env, argv[0], "window");
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
wxCaret * Result = new wxCaret(window,size);
app->newPtr((void *) Result, 71, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxCaret"));
}
// wxCaret::Create
void wxCaret_Create_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
wxWindow *window;
window = (wxWindow *) memenv->getPtr(env, argv[1], "window");
int width;
if(!enif_get_int(env, argv[2], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[3], &height)) Badarg("height"); // int
if(!This) throw wxe_badarg("This");
bool Result = This->Create(window,width,height);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCaret::Create
void wxCaret_Create_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
wxWindow *window;
window = (wxWindow *) memenv->getPtr(env, argv[1], "window");
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[2], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
if(!This) throw wxe_badarg("This");
bool Result = This->Create(window,size);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCaret::GetBlinkTime
void wxCaret_GetBlinkTime(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int Result = wxCaret::GetBlinkTime();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxCaret::GetPosition
void wxCaret_GetPosition(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxPoint Result = This->GetPosition();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxCaret::GetSize
void wxCaret_GetSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSize Result = This->GetSize();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxCaret::GetWindow
void wxCaret_GetWindow(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxWindow * Result = (wxWindow*)This->GetWindow();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxWindow"));
}
// wxCaret::Hide
void wxCaret_Hide(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->Hide();
}
// wxCaret::IsOk
void wxCaret_IsOk(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsOk();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCaret::IsVisible
void wxCaret_IsVisible(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsVisible();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCaret::Move
void wxCaret_Move_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
int x;
if(!enif_get_int(env, argv[1], &x)) Badarg("x"); // int
int y;
if(!enif_get_int(env, argv[2], &y)) Badarg("y"); // int
if(!This) throw wxe_badarg("This");
This->Move(x,y);
}
// wxCaret::Move
void wxCaret_Move_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *pt_t;
int pt_sz;
if(!enif_get_tuple(env, argv[1], &pt_sz, &pt_t)) Badarg("pt");
int ptX;
if(!enif_get_int(env, pt_t[0], &ptX)) Badarg("pt");
int ptY;
if(!enif_get_int(env, pt_t[1], &ptY)) Badarg("pt");
wxPoint pt = wxPoint(ptX,ptY);
if(!This) throw wxe_badarg("This");
This->Move(pt);
}
// wxCaret::SetBlinkTime
void wxCaret_SetBlinkTime(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int milliseconds;
if(!enif_get_int(env, argv[0], &milliseconds)) Badarg("milliseconds"); // int
wxCaret::SetBlinkTime(milliseconds);
}
// wxCaret::SetSize
void wxCaret_SetSize_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
int width;
if(!enif_get_int(env, argv[1], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[2], &height)) Badarg("height"); // int
if(!This) throw wxe_badarg("This");
This->SetSize(width,height);
}
// wxCaret::SetSize
void wxCaret_SetSize_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
if(!This) throw wxe_badarg("This");
This->SetSize(size);
}
// wxCaret::Show
void wxCaret_Show(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool show=true;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "show"))) {
show = enif_is_identical(tpl[1], WXE_ATOM_true);
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
This->Show(show);
}
// wxCaret::destroy
void wxCaret_destroy(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCaret *This;
This = (wxCaret *) memenv->getPtr(env, argv[0], "This");
if(This) { ((WxeApp *) wxTheApp)->clearPtr((void *) This);
delete This;}
}
// wxSizer::Add
void wxSizer_Add_2_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
wxSizerFlags *flags;
flags = (wxSizerFlags *) memenv->getPtr(env, argv[2], "flags");
if(!This) throw wxe_badarg("This");
wxSizerItem * Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = (wxSizerItem*)This->Add(static_cast<wxWindow*> (window),*flags);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = (wxSizerItem*)This->Add(static_cast<wxSizer*> (window),*flags);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Add
void wxSizer_Add_2_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int proportion=0;
int flag=0;
int border=0;
wxObject * userData=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "proportion"))) {
if(!enif_get_int(env, tpl[1], &proportion)) Badarg("proportion"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "flag"))) {
if(!enif_get_int(env, tpl[1], &flag)) Badarg("flag"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "border"))) {
if(!enif_get_int(env, tpl[1], &border)) Badarg("border"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "userData"))) {
userData = (wxObject *) memenv->getPtr(env, tpl[1], "userData");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = (wxSizerItem*)This->Add(static_cast<wxWindow*> (window),proportion,flag,border,userData);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = (wxSizerItem*)This->Add(static_cast<wxSizer*> (window),proportion,flag,border,userData);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Add
void wxSizer_Add_3_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int proportion=0;
int flag=0;
int border=0;
wxObject * userData=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
int width;
if(!enif_get_int(env, argv[1], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[2], &height)) Badarg("height"); // int
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "proportion"))) {
if(!enif_get_int(env, tpl[1], &proportion)) Badarg("proportion"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "flag"))) {
if(!enif_get_int(env, tpl[1], &flag)) Badarg("flag"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "border"))) {
if(!enif_get_int(env, tpl[1], &border)) Badarg("border"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "userData"))) {
userData = (wxObject *) memenv->getPtr(env, tpl[1], "userData");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->Add(width,height,proportion,flag,border,userData);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Add
void wxSizer_Add_3_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
int width;
if(!enif_get_int(env, argv[1], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[2], &height)) Badarg("height"); // int
wxSizerFlags *flags;
flags = (wxSizerFlags *) memenv->getPtr(env, argv[3], "flags");
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->Add(width,height,*flags);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::AddSpacer
void wxSizer_AddSpacer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
int size;
if(!enif_get_int(env, argv[1], &size)) Badarg("size"); // int
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->AddSpacer(size);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::AddStretchSpacer
void wxSizer_AddStretchSpacer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int prop=1;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "prop"))) {
if(!enif_get_int(env, tpl[1], &prop)) Badarg("prop"); // int
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->AddStretchSpacer(prop);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::CalcMin
void wxSizer_CalcMin(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSize Result = This->CalcMin();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxSizer::Clear
void wxSizer_Clear(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool delete_windows=false;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "delete_windows"))) {
delete_windows = enif_is_identical(tpl[1], WXE_ATOM_true);
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
This->Clear(delete_windows);
}
// wxSizer::Detach
void wxSizer_Detach_1_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
if(!This) throw wxe_badarg("This");
bool Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = This->Detach(static_cast<wxWindow*> (window));
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = This->Detach(static_cast<wxSizer*> (window));
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::Detach
void wxSizer_Detach_1_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
int index;
if(!enif_get_int(env, argv[1], &index)) Badarg("index"); // int
if(!This) throw wxe_badarg("This");
bool Result = This->Detach(index);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::Fit
void wxSizer_Fit(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
wxWindow *window;
window = (wxWindow *) memenv->getPtr(env, argv[1], "window");
if(!This) throw wxe_badarg("This");
wxSize Result = This->Fit(window);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxSizer::FitInside
void wxSizer_FitInside(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
wxWindow *window;
window = (wxWindow *) memenv->getPtr(env, argv[1], "window");
if(!This) throw wxe_badarg("This");
This->FitInside(window);
}
// wxSizer::GetChildren
void wxSizer_GetChildren(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
const wxSizerItemList Result = This->GetChildren();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_list_objs(Result, app, "wxSizerItem"));
}
// wxSizer::GetItem
void wxSizer_GetItem_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool recursive=false;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "recursive"))) {
recursive = enif_is_identical(tpl[1], WXE_ATOM_true);
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = (wxSizerItem*)This->GetItem(static_cast<wxWindow*> (window),recursive);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = (wxSizerItem*)This->GetItem(static_cast<wxSizer*> (window),recursive);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::GetItem
void wxSizer_GetItem_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->GetItem(index);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::GetSize
void wxSizer_GetSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSize Result = This->GetSize();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxSizer::GetPosition
void wxSizer_GetPosition(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxPoint Result = This->GetPosition();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxSizer::GetMinSize
void wxSizer_GetMinSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSize Result = This->GetMinSize();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxSizer::Hide
void wxSizer_Hide_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool recursive=false;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "recursive"))) {
recursive = enif_is_identical(tpl[1], WXE_ATOM_true);
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = This->Hide(static_cast<wxWindow*> (window),recursive);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = This->Hide(static_cast<wxSizer*> (window),recursive);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::Hide
void wxSizer_Hide_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
if(!This) throw wxe_badarg("This");
bool Result = This->Hide(index);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::Insert
void wxSizer_Insert_3_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[2], "window", &window_type);
wxSizerFlags *flags;
flags = (wxSizerFlags *) memenv->getPtr(env, argv[3], "flags");
if(!This) throw wxe_badarg("This");
wxSizerItem * Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = (wxSizerItem*)This->Insert(index,static_cast<wxWindow*> (window),*flags);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = (wxSizerItem*)This->Insert(index,static_cast<wxSizer*> (window),*flags);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Insert
void wxSizer_Insert_3_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int proportion=0;
int flag=0;
int border=0;
wxObject * userData=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[2], "window", &window_type);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "proportion"))) {
if(!enif_get_int(env, tpl[1], &proportion)) Badarg("proportion"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "flag"))) {
if(!enif_get_int(env, tpl[1], &flag)) Badarg("flag"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "border"))) {
if(!enif_get_int(env, tpl[1], &border)) Badarg("border"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "userData"))) {
userData = (wxObject *) memenv->getPtr(env, tpl[1], "userData");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = (wxSizerItem*)This->Insert(index,static_cast<wxWindow*> (window),proportion,flag,border,userData);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = (wxSizerItem*)This->Insert(index,static_cast<wxSizer*> (window),proportion,flag,border,userData);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Insert
void wxSizer_Insert_4_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int proportion=0;
int flag=0;
int border=0;
wxObject * userData=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
int width;
if(!enif_get_int(env, argv[2], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[3], &height)) Badarg("height"); // int
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[4];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "proportion"))) {
if(!enif_get_int(env, tpl[1], &proportion)) Badarg("proportion"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "flag"))) {
if(!enif_get_int(env, tpl[1], &flag)) Badarg("flag"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "border"))) {
if(!enif_get_int(env, tpl[1], &border)) Badarg("border"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "userData"))) {
userData = (wxObject *) memenv->getPtr(env, tpl[1], "userData");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->Insert(index,width,height,proportion,flag,border,userData);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Insert
void wxSizer_Insert_4_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
int width;
if(!enif_get_int(env, argv[2], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[3], &height)) Badarg("height"); // int
wxSizerFlags *flags;
flags = (wxSizerFlags *) memenv->getPtr(env, argv[4], "flags");
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->Insert(index,width,height,*flags);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Insert
void wxSizer_Insert_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
wxSizerItem *item;
item = (wxSizerItem *) memenv->getPtr(env, argv[2], "item");
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->Insert(index,item);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::InsertSpacer
void wxSizer_InsertSpacer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
int size;
if(!enif_get_int(env, argv[2], &size)) Badarg("size"); // int
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->InsertSpacer(index,size);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::InsertStretchSpacer
void wxSizer_InsertStretchSpacer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int prop=1;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "prop"))) {
if(!enif_get_int(env, tpl[1], &prop)) Badarg("prop"); // int
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->InsertStretchSpacer(index,prop);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::IsShown
void wxSizer_IsShown_1_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
if(!This) throw wxe_badarg("This");
bool Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = This->IsShown(static_cast<wxWindow*> (window));
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = This->IsShown(static_cast<wxSizer*> (window));
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::IsShown
void wxSizer_IsShown_1_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
if(!This) throw wxe_badarg("This");
bool Result = This->IsShown(index);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::Layout
void wxSizer_Layout(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->Layout();
}
// wxSizer::Prepend
void wxSizer_Prepend_2_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
wxSizerFlags *flags;
flags = (wxSizerFlags *) memenv->getPtr(env, argv[2], "flags");
if(!This) throw wxe_badarg("This");
wxSizerItem * Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = (wxSizerItem*)This->Prepend(static_cast<wxWindow*> (window),*flags);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = (wxSizerItem*)This->Prepend(static_cast<wxSizer*> (window),*flags);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Prepend
void wxSizer_Prepend_2_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int proportion=0;
int flag=0;
int border=0;
wxObject * userData=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "proportion"))) {
if(!enif_get_int(env, tpl[1], &proportion)) Badarg("proportion"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "flag"))) {
if(!enif_get_int(env, tpl[1], &flag)) Badarg("flag"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "border"))) {
if(!enif_get_int(env, tpl[1], &border)) Badarg("border"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "userData"))) {
userData = (wxObject *) memenv->getPtr(env, tpl[1], "userData");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = (wxSizerItem*)This->Prepend(static_cast<wxWindow*> (window),proportion,flag,border,userData);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = (wxSizerItem*)This->Prepend(static_cast<wxSizer*> (window),proportion,flag,border,userData);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Prepend
void wxSizer_Prepend_3_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int proportion=0;
int flag=0;
int border=0;
wxObject * userData=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
int width;
if(!enif_get_int(env, argv[1], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[2], &height)) Badarg("height"); // int
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "proportion"))) {
if(!enif_get_int(env, tpl[1], &proportion)) Badarg("proportion"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "flag"))) {
if(!enif_get_int(env, tpl[1], &flag)) Badarg("flag"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "border"))) {
if(!enif_get_int(env, tpl[1], &border)) Badarg("border"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "userData"))) {
userData = (wxObject *) memenv->getPtr(env, tpl[1], "userData");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->Prepend(width,height,proportion,flag,border,userData);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Prepend
void wxSizer_Prepend_3_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
int width;
if(!enif_get_int(env, argv[1], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[2], &height)) Badarg("height"); // int
wxSizerFlags *flags;
flags = (wxSizerFlags *) memenv->getPtr(env, argv[3], "flags");
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->Prepend(width,height,*flags);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Prepend
void wxSizer_Prepend_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
wxSizerItem *item;
item = (wxSizerItem *) memenv->getPtr(env, argv[1], "item");
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->Prepend(item);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::PrependSpacer
void wxSizer_PrependSpacer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
int size;
if(!enif_get_int(env, argv[1], &size)) Badarg("size"); // int
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->PrependSpacer(size);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::PrependStretchSpacer
void wxSizer_PrependStretchSpacer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int prop=1;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "prop"))) {
if(!enif_get_int(env, tpl[1], &prop)) Badarg("prop"); // int
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->PrependStretchSpacer(prop);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizer::Remove
void wxSizer_Remove_1_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
wxSizer *sizer;
sizer = (wxSizer *) memenv->getPtr(env, argv[1], "sizer");
if(!This) throw wxe_badarg("This");
bool Result = This->Remove(sizer);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::Remove
void wxSizer_Remove_1_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
int index;
if(!enif_get_int(env, argv[1], &index)) Badarg("index"); // int
if(!This) throw wxe_badarg("This");
bool Result = This->Remove(index);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::Replace
void wxSizer_Replace_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool recursive=false;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM oldwin_type;
void * oldwin = memenv->getPtr(env, argv[1], "oldwin", &oldwin_type);
ERL_NIF_TERM newwin_type;
void * newwin = memenv->getPtr(env, argv[2], "newwin", &newwin_type);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "recursive"))) {
recursive = enif_is_identical(tpl[1], WXE_ATOM_true);
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result;
if(enif_is_identical(oldwin_type, WXE_ATOM_wxWindow) && enif_is_identical(newwin_type, WXE_ATOM_wxWindow))
Result = This->Replace(static_cast<wxWindow*> (oldwin),static_cast<wxWindow*> (newwin),recursive);
else if(enif_is_identical(oldwin_type, WXE_ATOM_wxSizer) && enif_is_identical(newwin_type, WXE_ATOM_wxSizer))
Result = This->Replace(static_cast<wxSizer*> (oldwin),static_cast<wxSizer*> (newwin),recursive);
else throw wxe_badarg("oldwin");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::Replace
void wxSizer_Replace_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
wxSizerItem *newitem;
newitem = (wxSizerItem *) memenv->getPtr(env, argv[2], "newitem");
if(!This) throw wxe_badarg("This");
bool Result = This->Replace(index,newitem);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::SetDimension
void wxSizer_SetDimension_4(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
int x;
if(!enif_get_int(env, argv[1], &x)) Badarg("x"); // int
int y;
if(!enif_get_int(env, argv[2], &y)) Badarg("y"); // int
int width;
if(!enif_get_int(env, argv[3], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[4], &height)) Badarg("height"); // int
if(!This) throw wxe_badarg("This");
This->SetDimension(x,y,width,height);
}
// wxSizer::SetDimension
void wxSizer_SetDimension_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, argv[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
wxPoint pos = wxPoint(posX,posY);
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[2], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
if(!This) throw wxe_badarg("This");
This->SetDimension(pos,size);
}
// wxSizer::SetMinSize
void wxSizer_SetMinSize_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
if(!This) throw wxe_badarg("This");
This->SetMinSize(size);
}
// wxSizer::SetMinSize
void wxSizer_SetMinSize_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
int width;
if(!enif_get_int(env, argv[1], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[2], &height)) Badarg("height"); // int
if(!This) throw wxe_badarg("This");
This->SetMinSize(width,height);
}
// wxSizer::SetItemMinSize
void wxSizer_SetItemMinSize_3_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
int width;
if(!enif_get_int(env, argv[2], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[3], &height)) Badarg("height"); // int
if(!This) throw wxe_badarg("This");
bool Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = This->SetItemMinSize(static_cast<wxWindow*> (window),width,height);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = This->SetItemMinSize(static_cast<wxSizer*> (window),width,height);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::SetItemMinSize
void wxSizer_SetItemMinSize_2_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[2], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
if(!This) throw wxe_badarg("This");
bool Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = This->SetItemMinSize(static_cast<wxWindow*> (window),size);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = This->SetItemMinSize(static_cast<wxSizer*> (window),size);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::SetItemMinSize
void wxSizer_SetItemMinSize_3_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
int width;
if(!enif_get_int(env, argv[2], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[3], &height)) Badarg("height"); // int
if(!This) throw wxe_badarg("This");
bool Result = This->SetItemMinSize(index,width,height);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::SetItemMinSize
void wxSizer_SetItemMinSize_2_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[2], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
if(!This) throw wxe_badarg("This");
bool Result = This->SetItemMinSize(index,size);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::SetSizeHints
void wxSizer_SetSizeHints(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
wxWindow *window;
window = (wxWindow *) memenv->getPtr(env, argv[1], "window");
if(!This) throw wxe_badarg("This");
This->SetSizeHints(window);
}
// wxSizer::Show
void wxSizer_Show_2_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool show=true;
bool recursive=false;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "show"))) {
show = enif_is_identical(tpl[1], WXE_ATOM_true);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "recursive"))) {
recursive = enif_is_identical(tpl[1], WXE_ATOM_true);
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = This->Show(static_cast<wxWindow*> (window),show,recursive);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = This->Show(static_cast<wxSizer*> (window),show,recursive);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::Show
void wxSizer_Show_2_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool show=true;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "show"))) {
show = enif_is_identical(tpl[1], WXE_ATOM_true);
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Show(index,show);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizer::Show
void wxSizer_Show_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
bool show;
show = enif_is_identical(argv[1], WXE_ATOM_true);
if(!This) throw wxe_badarg("This");
This->Show(show);
}
// wxSizer::ShowItems
void wxSizer_ShowItems(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizer *This;
This = (wxSizer *) memenv->getPtr(env, argv[0], "This");
bool show;
show = enif_is_identical(argv[1], WXE_ATOM_true);
if(!This) throw wxe_badarg("This");
This->ShowItems(show);
}
// wxSizerFlags::wxSizerFlags
void wxSizerFlags_new(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int proportion=0;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[0];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "proportion"))) {
if(!enif_get_int(env, tpl[1], &proportion)) Badarg("proportion"); // int
} else Badarg("Options");
};
wxSizerFlags * Result = new wxSizerFlags(proportion);
app->newPtr((void *) Result, 73, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerFlags"));
}
// wxSizerFlags::Align
void wxSizerFlags_Align(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerFlags *This;
This = (wxSizerFlags *) memenv->getPtr(env, argv[0], "This");
int alignment;
if(!enif_get_int(env, argv[1], &alignment)) Badarg("alignment"); // int
if(!This) throw wxe_badarg("This");
wxSizerFlags * Result = &This->Align(alignment);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerFlags"));
}
// wxSizerFlags::Border
void wxSizerFlags_Border_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerFlags *This;
This = (wxSizerFlags *) memenv->getPtr(env, argv[0], "This");
int direction;
if(!enif_get_int(env, argv[1], &direction)) Badarg("direction"); // int
int borderinpixels;
if(!enif_get_int(env, argv[2], &borderinpixels)) Badarg("borderinpixels"); // int
if(!This) throw wxe_badarg("This");
wxSizerFlags * Result = &This->Border(direction,borderinpixels);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerFlags"));
}
// wxSizerFlags::Border
void wxSizerFlags_Border_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int direction=wxALL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerFlags *This;
This = (wxSizerFlags *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "direction"))) {
if(!enif_get_int(env, tpl[1], &direction)) Badarg("direction"); // int
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerFlags * Result = &This->Border(direction);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerFlags"));
}
// wxSizerFlags::Center
void wxSizerFlags_Center(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerFlags *This;
This = (wxSizerFlags *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSizerFlags * Result = &This->Center();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerFlags"));
}
// wxSizerFlags::Expand
void wxSizerFlags_Expand(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerFlags *This;
This = (wxSizerFlags *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSizerFlags * Result = &This->Expand();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerFlags"));
}
// wxSizerFlags::Left
void wxSizerFlags_Left(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerFlags *This;
This = (wxSizerFlags *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSizerFlags * Result = &This->Left();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerFlags"));
}
// wxSizerFlags::Proportion
void wxSizerFlags_Proportion(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerFlags *This;
This = (wxSizerFlags *) memenv->getPtr(env, argv[0], "This");
int proportion;
if(!enif_get_int(env, argv[1], &proportion)) Badarg("proportion"); // int
if(!This) throw wxe_badarg("This");
wxSizerFlags * Result = &This->Proportion(proportion);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerFlags"));
}
// wxSizerFlags::Right
void wxSizerFlags_Right(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerFlags *This;
This = (wxSizerFlags *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSizerFlags * Result = &This->Right();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerFlags"));
}
// wxSizerFlags::destroy
void wxSizerFlags_destroy(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerFlags *This;
This = (wxSizerFlags *) memenv->getPtr(env, argv[0], "This");
if(This) { ((WxeApp *) wxTheApp)->clearPtr((void *) This);
delete This;}
}
// wxSizerItem::wxSizerItem
void wxSizerItem_new_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int proportion=0;
int flag=0;
int border=0;
wxObject * userData=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int width;
if(!enif_get_int(env, argv[0], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[1], &height)) Badarg("height"); // int
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "proportion"))) {
if(!enif_get_int(env, tpl[1], &proportion)) Badarg("proportion"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "flag"))) {
if(!enif_get_int(env, tpl[1], &flag)) Badarg("flag"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "border"))) {
if(!enif_get_int(env, tpl[1], &border)) Badarg("border"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "userData"))) {
userData = (wxObject *) memenv->getPtr(env, tpl[1], "userData");
} else Badarg("Options");
};
wxSizerItem * Result = new EwxSizerItem(width,height,proportion,flag,border,userData);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizerItem::wxSizerItem
void wxSizerItem_new_2_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[0], "window", &window_type);
wxSizerFlags *flags;
flags = (wxSizerFlags *) memenv->getPtr(env, argv[1], "flags");
wxSizerItem * Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = new EwxSizerItem(static_cast<wxWindow*> (window),*flags);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = new EwxSizerItem(static_cast<wxSizer*> (window),*flags);
else throw wxe_badarg("window");
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizerItem::wxSizerItem
void wxSizerItem_new_2_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int proportion=0;
int flag=0;
int border=0;
wxObject * userData=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[0], "window", &window_type);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "proportion"))) {
if(!enif_get_int(env, tpl[1], &proportion)) Badarg("proportion"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "flag"))) {
if(!enif_get_int(env, tpl[1], &flag)) Badarg("flag"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "border"))) {
if(!enif_get_int(env, tpl[1], &border)) Badarg("border"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "userData"))) {
userData = (wxObject *) memenv->getPtr(env, tpl[1], "userData");
} else Badarg("Options");
};
wxSizerItem * Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = new EwxSizerItem(static_cast<wxWindow*> (window),proportion,flag,border,userData);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = new EwxSizerItem(static_cast<wxSizer*> (window),proportion,flag,border,userData);
else throw wxe_badarg("window");
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxSizerItem::CalcMin
void wxSizerItem_CalcMin(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSize Result = This->CalcMin();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxSizerItem::DeleteWindows
void wxSizerItem_DeleteWindows(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->DeleteWindows();
}
// wxSizerItem::DetachSizer
void wxSizerItem_DetachSizer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->DetachSizer();
}
// wxSizerItem::GetBorder
void wxSizerItem_GetBorder(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetBorder();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxSizerItem::GetFlag
void wxSizerItem_GetFlag(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetFlag();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxSizerItem::GetMinSize
void wxSizerItem_GetMinSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSize Result = This->GetMinSize();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxSizerItem::GetPosition
void wxSizerItem_GetPosition(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxPoint Result = This->GetPosition();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxSizerItem::GetProportion
void wxSizerItem_GetProportion(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetProportion();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxSizerItem::GetRatio
void wxSizerItem_GetRatio(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
float Result = This->GetRatio();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_double(Result));
}
// wxSizerItem::GetRect
void wxSizerItem_GetRect(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxRect Result = This->GetRect();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxSizerItem::GetSize
void wxSizerItem_GetSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSize Result = This->GetSize();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxSizerItem::GetSizer
void wxSizerItem_GetSizer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSizer * Result = (wxSizer*)This->GetSizer();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizer"));
}
// wxSizerItem::GetSpacer
void wxSizerItem_GetSpacer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSize Result = This->GetSpacer();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxSizerItem::GetUserData
void wxSizerItem_GetUserData(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxObject * Result = (wxObject*)This->GetUserData();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wx"));
}
// wxSizerItem::GetWindow
void wxSizerItem_GetWindow(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxWindow * Result = (wxWindow*)This->GetWindow();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxWindow"));
}
// wxSizerItem::IsSizer
void wxSizerItem_IsSizer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsSizer();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizerItem::IsShown
void wxSizerItem_IsShown(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsShown();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizerItem::IsSpacer
void wxSizerItem_IsSpacer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsSpacer();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizerItem::IsWindow
void wxSizerItem_IsWindow(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsWindow();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxSizerItem::SetBorder
void wxSizerItem_SetBorder(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
int border;
if(!enif_get_int(env, argv[1], &border)) Badarg("border"); // int
if(!This) throw wxe_badarg("This");
This->SetBorder(border);
}
// wxSizerItem::SetDimension
void wxSizerItem_SetDimension(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, argv[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
wxPoint pos = wxPoint(posX,posY);
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[2], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
if(!This) throw wxe_badarg("This");
This->SetDimension(pos,size);
}
// wxSizerItem::SetFlag
void wxSizerItem_SetFlag(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
int flag;
if(!enif_get_int(env, argv[1], &flag)) Badarg("flag"); // int
if(!This) throw wxe_badarg("This");
This->SetFlag(flag);
}
// wxSizerItem::SetInitSize
void wxSizerItem_SetInitSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
int x;
if(!enif_get_int(env, argv[1], &x)) Badarg("x"); // int
int y;
if(!enif_get_int(env, argv[2], &y)) Badarg("y"); // int
if(!This) throw wxe_badarg("This");
This->SetInitSize(x,y);
}
// wxSizerItem::SetMinSize
void wxSizerItem_SetMinSize_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
if(!This) throw wxe_badarg("This");
This->SetMinSize(size);
}
// wxSizerItem::SetMinSize
void wxSizerItem_SetMinSize_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
int x;
if(!enif_get_int(env, argv[1], &x)) Badarg("x"); // int
int y;
if(!enif_get_int(env, argv[2], &y)) Badarg("y"); // int
if(!This) throw wxe_badarg("This");
This->SetMinSize(x,y);
}
// wxSizerItem::SetProportion
void wxSizerItem_SetProportion(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
int proportion;
if(!enif_get_int(env, argv[1], &proportion)) Badarg("proportion"); // int
if(!This) throw wxe_badarg("This");
This->SetProportion(proportion);
}
// wxSizerItem::SetRatio
void wxSizerItem_SetRatio_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
int width;
if(!enif_get_int(env, argv[1], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[2], &height)) Badarg("height"); // int
if(!This) throw wxe_badarg("This");
This->SetRatio(width,height);
}
// wxSizerItem::SetRatio
void wxSizerItem_SetRatio_1_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
if(!This) throw wxe_badarg("This");
This->SetRatio(size);
}
// wxSizerItem::SetRatio
void wxSizerItem_SetRatio_1_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
float ratio;
if(!wxe_get_float(env, argv[1], &ratio)) Badarg("ratio");
if(!This) throw wxe_badarg("This");
This->SetRatio(ratio);
}
// wxSizerItem::AssignSizer
void wxSizerItem_AssignSizer(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
wxSizer *sizer;
sizer = (wxSizer *) memenv->getPtr(env, argv[1], "sizer");
if(!This) throw wxe_badarg("This");
This->AssignSizer(sizer);
}
// wxSizerItem::AssignSpacer
void wxSizerItem_AssignSpacer_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
if(!This) throw wxe_badarg("This");
This->AssignSpacer(size);
}
// wxSizerItem::AssignSpacer
void wxSizerItem_AssignSpacer_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
int w;
if(!enif_get_int(env, argv[1], &w)) Badarg("w"); // int
int h;
if(!enif_get_int(env, argv[2], &h)) Badarg("h"); // int
if(!This) throw wxe_badarg("This");
This->AssignSpacer(w,h);
}
// wxSizerItem::AssignWindow
void wxSizerItem_AssignWindow(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
wxWindow *window;
window = (wxWindow *) memenv->getPtr(env, argv[1], "window");
if(!This) throw wxe_badarg("This");
This->AssignWindow(window);
}
// wxSizerItem::Show
void wxSizerItem_Show(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxSizerItem *This;
This = (wxSizerItem *) memenv->getPtr(env, argv[0], "This");
bool show;
show = enif_is_identical(argv[1], WXE_ATOM_true);
if(!This) throw wxe_badarg("This");
This->Show(show);
}
// wxBoxSizer::wxBoxSizer
void wxBoxSizer_new(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int orient;
if(!enif_get_int(env, argv[0], &orient)) Badarg("orient"); // int
wxBoxSizer * Result = new EwxBoxSizer(orient);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxBoxSizer"));
}
// wxBoxSizer::GetOrientation
void wxBoxSizer_GetOrientation(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxBoxSizer *This;
This = (wxBoxSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetOrientation();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxStaticBoxSizer::wxStaticBoxSizer
void wxStaticBoxSizer_new_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxStaticBox *box;
box = (wxStaticBox *) memenv->getPtr(env, argv[0], "box");
int orient;
if(!enif_get_int(env, argv[1], &orient)) Badarg("orient"); // int
wxStaticBoxSizer * Result = new EwxStaticBoxSizer(box,orient);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxStaticBoxSizer"));
}
// wxStaticBoxSizer::wxStaticBoxSizer
void wxStaticBoxSizer_new_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxString label= wxEmptyString;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int orient;
if(!enif_get_int(env, argv[0], &orient)) Badarg("orient"); // int
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "label"))) {
ErlNifBinary label_bin;
if(!enif_inspect_binary(env, tpl[1], &label_bin)) Badarg("label");
label = wxString(label_bin.data, wxConvUTF8, label_bin.size);
} else Badarg("Options");
};
wxStaticBoxSizer * Result = new EwxStaticBoxSizer(orient,parent,label);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxStaticBoxSizer"));
}
// wxStaticBoxSizer::GetStaticBox
void wxStaticBoxSizer_GetStaticBox(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxStaticBoxSizer *This;
This = (wxStaticBoxSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxStaticBox * Result = (wxStaticBox*)This->GetStaticBox();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxStaticBox"));
}
// wxGridSizer::wxGridSizer
void wxGridSizer_new_3_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int cols;
if(!enif_get_int(env, argv[0], &cols)) Badarg("cols"); // int
int vgap;
if(!enif_get_int(env, argv[1], &vgap)) Badarg("vgap"); // int
int hgap;
if(!enif_get_int(env, argv[2], &hgap)) Badarg("hgap"); // int
wxGridSizer * Result = new EwxGridSizer(cols,vgap,hgap);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGridSizer"));
}
// wxGridSizer::wxGridSizer
void wxGridSizer_new_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxSize gap= wxSize(0, 0);
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int cols;
if(!enif_get_int(env, argv[0], &cols)) Badarg("cols"); // int
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "gap"))) {
const ERL_NIF_TERM *gap_t;
int gap_sz;
if(!enif_get_tuple(env, tpl[1], &gap_sz, &gap_t)) Badarg("gap");
int gapW;
if(!enif_get_int(env, gap_t[0], &gapW)) Badarg("gap");
int gapH;
if(!enif_get_int(env, gap_t[1], &gapH)) Badarg("gap");
gap = wxSize(gapW,gapH);
} else Badarg("Options");
};
wxGridSizer * Result = new EwxGridSizer(cols,gap);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGridSizer"));
}
// wxGridSizer::wxGridSizer
void wxGridSizer_new_4(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int rows;
if(!enif_get_int(env, argv[0], &rows)) Badarg("rows"); // int
int cols;
if(!enif_get_int(env, argv[1], &cols)) Badarg("cols"); // int
int vgap;
if(!enif_get_int(env, argv[2], &vgap)) Badarg("vgap"); // int
int hgap;
if(!enif_get_int(env, argv[3], &hgap)) Badarg("hgap"); // int
wxGridSizer * Result = new EwxGridSizer(rows,cols,vgap,hgap);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGridSizer"));
}
// wxGridSizer::wxGridSizer
void wxGridSizer_new_3_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int rows;
if(!enif_get_int(env, argv[0], &rows)) Badarg("rows"); // int
int cols;
if(!enif_get_int(env, argv[1], &cols)) Badarg("cols"); // int
const ERL_NIF_TERM *gap_t;
int gap_sz;
if(!enif_get_tuple(env, argv[2], &gap_sz, &gap_t)) Badarg("gap");
int gapW;
if(!enif_get_int(env, gap_t[0], &gapW)) Badarg("gap");
int gapH;
if(!enif_get_int(env, gap_t[1], &gapH)) Badarg("gap");
wxSize gap = wxSize(gapW,gapH);
wxGridSizer * Result = new EwxGridSizer(rows,cols,gap);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGridSizer"));
}
// wxGridSizer::GetCols
void wxGridSizer_GetCols(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridSizer *This;
This = (wxGridSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetCols();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxGridSizer::GetHGap
void wxGridSizer_GetHGap(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridSizer *This;
This = (wxGridSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetHGap();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxGridSizer::GetRows
void wxGridSizer_GetRows(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridSizer *This;
This = (wxGridSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetRows();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxGridSizer::GetVGap
void wxGridSizer_GetVGap(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridSizer *This;
This = (wxGridSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetVGap();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxGridSizer::SetCols
void wxGridSizer_SetCols(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridSizer *This;
This = (wxGridSizer *) memenv->getPtr(env, argv[0], "This");
int cols;
if(!enif_get_int(env, argv[1], &cols)) Badarg("cols"); // int
if(!This) throw wxe_badarg("This");
This->SetCols(cols);
}
// wxGridSizer::SetHGap
void wxGridSizer_SetHGap(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridSizer *This;
This = (wxGridSizer *) memenv->getPtr(env, argv[0], "This");
int gap;
if(!enif_get_int(env, argv[1], &gap)) Badarg("gap"); // int
if(!This) throw wxe_badarg("This");
This->SetHGap(gap);
}
// wxGridSizer::SetRows
void wxGridSizer_SetRows(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridSizer *This;
This = (wxGridSizer *) memenv->getPtr(env, argv[0], "This");
int rows;
if(!enif_get_int(env, argv[1], &rows)) Badarg("rows"); // int
if(!This) throw wxe_badarg("This");
This->SetRows(rows);
}
// wxGridSizer::SetVGap
void wxGridSizer_SetVGap(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridSizer *This;
This = (wxGridSizer *) memenv->getPtr(env, argv[0], "This");
int gap;
if(!enif_get_int(env, argv[1], &gap)) Badarg("gap"); // int
if(!This) throw wxe_badarg("This");
This->SetVGap(gap);
}
// wxFlexGridSizer::wxFlexGridSizer
void wxFlexGridSizer_new_3_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int cols;
if(!enif_get_int(env, argv[0], &cols)) Badarg("cols"); // int
int vgap;
if(!enif_get_int(env, argv[1], &vgap)) Badarg("vgap"); // int
int hgap;
if(!enif_get_int(env, argv[2], &hgap)) Badarg("hgap"); // int
wxFlexGridSizer * Result = new EwxFlexGridSizer(cols,vgap,hgap);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxFlexGridSizer"));
}
// wxFlexGridSizer::wxFlexGridSizer
void wxFlexGridSizer_new_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxSize gap= wxSize(0, 0);
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int cols;
if(!enif_get_int(env, argv[0], &cols)) Badarg("cols"); // int
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "gap"))) {
const ERL_NIF_TERM *gap_t;
int gap_sz;
if(!enif_get_tuple(env, tpl[1], &gap_sz, &gap_t)) Badarg("gap");
int gapW;
if(!enif_get_int(env, gap_t[0], &gapW)) Badarg("gap");
int gapH;
if(!enif_get_int(env, gap_t[1], &gapH)) Badarg("gap");
gap = wxSize(gapW,gapH);
} else Badarg("Options");
};
wxFlexGridSizer * Result = new EwxFlexGridSizer(cols,gap);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxFlexGridSizer"));
}
// wxFlexGridSizer::wxFlexGridSizer
void wxFlexGridSizer_new_4(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int rows;
if(!enif_get_int(env, argv[0], &rows)) Badarg("rows"); // int
int cols;
if(!enif_get_int(env, argv[1], &cols)) Badarg("cols"); // int
int vgap;
if(!enif_get_int(env, argv[2], &vgap)) Badarg("vgap"); // int
int hgap;
if(!enif_get_int(env, argv[3], &hgap)) Badarg("hgap"); // int
wxFlexGridSizer * Result = new EwxFlexGridSizer(rows,cols,vgap,hgap);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxFlexGridSizer"));
}
// wxFlexGridSizer::wxFlexGridSizer
void wxFlexGridSizer_new_3_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int rows;
if(!enif_get_int(env, argv[0], &rows)) Badarg("rows"); // int
int cols;
if(!enif_get_int(env, argv[1], &cols)) Badarg("cols"); // int
const ERL_NIF_TERM *gap_t;
int gap_sz;
if(!enif_get_tuple(env, argv[2], &gap_sz, &gap_t)) Badarg("gap");
int gapW;
if(!enif_get_int(env, gap_t[0], &gapW)) Badarg("gap");
int gapH;
if(!enif_get_int(env, gap_t[1], &gapH)) Badarg("gap");
wxSize gap = wxSize(gapW,gapH);
wxFlexGridSizer * Result = new EwxFlexGridSizer(rows,cols,gap);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxFlexGridSizer"));
}
// wxFlexGridSizer::AddGrowableCol
void wxFlexGridSizer_AddGrowableCol(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int proportion=0;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFlexGridSizer *This;
This = (wxFlexGridSizer *) memenv->getPtr(env, argv[0], "This");
size_t idx;
if(!wxe_get_size_t(env, argv[1], &idx)) Badarg("idx");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "proportion"))) {
if(!enif_get_int(env, tpl[1], &proportion)) Badarg("proportion"); // int
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
This->AddGrowableCol(idx,proportion);
}
// wxFlexGridSizer::AddGrowableRow
void wxFlexGridSizer_AddGrowableRow(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int proportion=0;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFlexGridSizer *This;
This = (wxFlexGridSizer *) memenv->getPtr(env, argv[0], "This");
size_t idx;
if(!wxe_get_size_t(env, argv[1], &idx)) Badarg("idx");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "proportion"))) {
if(!enif_get_int(env, tpl[1], &proportion)) Badarg("proportion"); // int
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
This->AddGrowableRow(idx,proportion);
}
// wxFlexGridSizer::GetFlexibleDirection
void wxFlexGridSizer_GetFlexibleDirection(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFlexGridSizer *This;
This = (wxFlexGridSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetFlexibleDirection();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxFlexGridSizer::GetNonFlexibleGrowMode
void wxFlexGridSizer_GetNonFlexibleGrowMode(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFlexGridSizer *This;
This = (wxFlexGridSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetNonFlexibleGrowMode();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxFlexGridSizer::RemoveGrowableCol
void wxFlexGridSizer_RemoveGrowableCol(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFlexGridSizer *This;
This = (wxFlexGridSizer *) memenv->getPtr(env, argv[0], "This");
size_t idx;
if(!wxe_get_size_t(env, argv[1], &idx)) Badarg("idx");
if(!This) throw wxe_badarg("This");
This->RemoveGrowableCol(idx);
}
// wxFlexGridSizer::RemoveGrowableRow
void wxFlexGridSizer_RemoveGrowableRow(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFlexGridSizer *This;
This = (wxFlexGridSizer *) memenv->getPtr(env, argv[0], "This");
size_t idx;
if(!wxe_get_size_t(env, argv[1], &idx)) Badarg("idx");
if(!This) throw wxe_badarg("This");
This->RemoveGrowableRow(idx);
}
// wxFlexGridSizer::SetFlexibleDirection
void wxFlexGridSizer_SetFlexibleDirection(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFlexGridSizer *This;
This = (wxFlexGridSizer *) memenv->getPtr(env, argv[0], "This");
int direction;
if(!enif_get_int(env, argv[1], &direction)) Badarg("direction"); // int
if(!This) throw wxe_badarg("This");
This->SetFlexibleDirection(direction);
}
// wxFlexGridSizer::SetNonFlexibleGrowMode
void wxFlexGridSizer_SetNonFlexibleGrowMode(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFlexGridSizer *This;
This = (wxFlexGridSizer *) memenv->getPtr(env, argv[0], "This");
wxFlexSizerGrowMode mode;
if(!enif_get_int(env, argv[1], (int *) &mode)) Badarg("mode"); // enum
if(!This) throw wxe_badarg("This");
This->SetNonFlexibleGrowMode(mode);
}
// wxGridBagSizer::wxGridBagSizer
void wxGridBagSizer_new(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int vgap=0;
int hgap=0;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[0];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "vgap"))) {
if(!enif_get_int(env, tpl[1], &vgap)) Badarg("vgap"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "hgap"))) {
if(!enif_get_int(env, tpl[1], &hgap)) Badarg("hgap"); // int
} else Badarg("Options");
};
wxGridBagSizer * Result = new EwxGridBagSizer(vgap,hgap);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGridBagSizer"));
}
// wxGridBagSizer::Add
void wxGridBagSizer_Add_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxGBSpan span= wxDefaultSpan;
int flag=0;
int border=0;
wxObject * userData=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, argv[2], &pos_sz, &pos_t)) Badarg("pos");
int posR;
if(!enif_get_int(env, pos_t[0], &posR)) Badarg("pos");
int posC;
if(!enif_get_int(env, pos_t[1], &posC)) Badarg("pos");
wxGBPosition pos = wxGBPosition(posR,posC);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "span"))) {
const ERL_NIF_TERM *span_t;
int span_sz;
if(!enif_get_tuple(env, tpl[1], &span_sz, &span_t)) Badarg("span");
int spanRS;
if(!enif_get_int(env, span_t[0], &spanRS)) Badarg("span");
int spanCS;
if(!enif_get_int(env, span_t[1], &spanCS)) Badarg("span");
span = wxGBSpan(spanRS,spanCS);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "flag"))) {
if(!enif_get_int(env, tpl[1], &flag)) Badarg("flag"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "border"))) {
if(!enif_get_int(env, tpl[1], &border)) Badarg("border"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "userData"))) {
userData = (wxObject *) memenv->getPtr(env, tpl[1], "userData");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = (wxSizerItem*)This->Add(static_cast<wxWindow*> (window),pos,span,flag,border,userData);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = (wxSizerItem*)This->Add(static_cast<wxSizer*> (window),pos,span,flag,border,userData);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxGridBagSizer::Add
void wxGridBagSizer_Add_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
wxGBSizerItem *item;
item = (wxGBSizerItem *) memenv->getPtr(env, argv[1], "item");
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->Add(item);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxGridBagSizer::Add
void wxGridBagSizer_Add_4(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxGBSpan span= wxDefaultSpan;
int flag=0;
int border=0;
wxObject * userData=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
int width;
if(!enif_get_int(env, argv[1], &width)) Badarg("width"); // int
int height;
if(!enif_get_int(env, argv[2], &height)) Badarg("height"); // int
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, argv[3], &pos_sz, &pos_t)) Badarg("pos");
int posR;
if(!enif_get_int(env, pos_t[0], &posR)) Badarg("pos");
int posC;
if(!enif_get_int(env, pos_t[1], &posC)) Badarg("pos");
wxGBPosition pos = wxGBPosition(posR,posC);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[4];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "span"))) {
const ERL_NIF_TERM *span_t;
int span_sz;
if(!enif_get_tuple(env, tpl[1], &span_sz, &span_t)) Badarg("span");
int spanRS;
if(!enif_get_int(env, span_t[0], &spanRS)) Badarg("span");
int spanCS;
if(!enif_get_int(env, span_t[1], &spanCS)) Badarg("span");
span = wxGBSpan(spanRS,spanCS);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "flag"))) {
if(!enif_get_int(env, tpl[1], &flag)) Badarg("flag"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "border"))) {
if(!enif_get_int(env, tpl[1], &border)) Badarg("border"); // int
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "userData"))) {
userData = (wxObject *) memenv->getPtr(env, tpl[1], "userData");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
wxSizerItem * Result = (wxSizerItem*)This->Add(width,height,pos,span,flag,border,userData);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxSizerItem"));
}
// wxGridBagSizer::CalcMin
void wxGridBagSizer_CalcMin(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSize Result = This->CalcMin();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGridBagSizer::CheckForIntersection
void wxGridBagSizer_CheckForIntersection_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxGBSizerItem * excludeItem=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
wxGBSizerItem *item;
item = (wxGBSizerItem *) memenv->getPtr(env, argv[1], "item");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "excludeItem"))) {
excludeItem = (wxGBSizerItem *) memenv->getPtr(env, tpl[1], "excludeItem");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->CheckForIntersection(item,excludeItem);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxGridBagSizer::CheckForIntersection
void wxGridBagSizer_CheckForIntersection_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxGBSizerItem * excludeItem=NULL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, argv[1], &pos_sz, &pos_t)) Badarg("pos");
int posR;
if(!enif_get_int(env, pos_t[0], &posR)) Badarg("pos");
int posC;
if(!enif_get_int(env, pos_t[1], &posC)) Badarg("pos");
wxGBPosition pos = wxGBPosition(posR,posC);
const ERL_NIF_TERM *span_t;
int span_sz;
if(!enif_get_tuple(env, argv[2], &span_sz, &span_t)) Badarg("span");
int spanRS;
if(!enif_get_int(env, span_t[0], &spanRS)) Badarg("span");
int spanCS;
if(!enif_get_int(env, span_t[1], &spanCS)) Badarg("span");
wxGBSpan span = wxGBSpan(spanRS,spanCS);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "excludeItem"))) {
excludeItem = (wxGBSizerItem *) memenv->getPtr(env, tpl[1], "excludeItem");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->CheckForIntersection(pos,span,excludeItem);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxGridBagSizer::FindItem
void wxGridBagSizer_FindItem(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
if(!This) throw wxe_badarg("This");
wxGBSizerItem * Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = (wxGBSizerItem*)This->FindItem(static_cast<wxWindow*> (window));
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = (wxGBSizerItem*)This->FindItem(static_cast<wxSizer*> (window));
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGBSizerItem"));
}
// wxGridBagSizer::FindItemAtPoint
void wxGridBagSizer_FindItemAtPoint(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *pt_t;
int pt_sz;
if(!enif_get_tuple(env, argv[1], &pt_sz, &pt_t)) Badarg("pt");
int ptX;
if(!enif_get_int(env, pt_t[0], &ptX)) Badarg("pt");
int ptY;
if(!enif_get_int(env, pt_t[1], &ptY)) Badarg("pt");
wxPoint pt = wxPoint(ptX,ptY);
if(!This) throw wxe_badarg("This");
wxGBSizerItem * Result = (wxGBSizerItem*)This->FindItemAtPoint(pt);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGBSizerItem"));
}
// wxGridBagSizer::FindItemAtPosition
void wxGridBagSizer_FindItemAtPosition(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, argv[1], &pos_sz, &pos_t)) Badarg("pos");
int posR;
if(!enif_get_int(env, pos_t[0], &posR)) Badarg("pos");
int posC;
if(!enif_get_int(env, pos_t[1], &posC)) Badarg("pos");
wxGBPosition pos = wxGBPosition(posR,posC);
if(!This) throw wxe_badarg("This");
wxGBSizerItem * Result = (wxGBSizerItem*)This->FindItemAtPosition(pos);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGBSizerItem"));
}
// wxGridBagSizer::FindItemWithData
void wxGridBagSizer_FindItemWithData(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
wxObject *userData;
userData = (wxObject *) memenv->getPtr(env, argv[1], "userData");
if(!This) throw wxe_badarg("This");
wxGBSizerItem * Result = (wxGBSizerItem*)This->FindItemWithData(userData);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGBSizerItem"));
}
// wxGridBagSizer::GetCellSize
void wxGridBagSizer_GetCellSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
int row;
if(!enif_get_int(env, argv[1], &row)) Badarg("row"); // int
int col;
if(!enif_get_int(env, argv[2], &col)) Badarg("col"); // int
if(!This) throw wxe_badarg("This");
wxSize Result = This->GetCellSize(row,col);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGridBagSizer::GetEmptyCellSize
void wxGridBagSizer_GetEmptyCellSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxSize Result = This->GetEmptyCellSize();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGridBagSizer::GetItemPosition
void wxGridBagSizer_GetItemPosition_1_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
if(!This) throw wxe_badarg("This");
wxGBPosition Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = This->GetItemPosition(static_cast<wxWindow*> (window));
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = This->GetItemPosition(static_cast<wxSizer*> (window));
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGridBagSizer::GetItemPosition
void wxGridBagSizer_GetItemPosition_1_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
if(!This) throw wxe_badarg("This");
wxGBPosition Result = This->GetItemPosition(index);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGridBagSizer::GetItemSpan
void wxGridBagSizer_GetItemSpan_1_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
if(!This) throw wxe_badarg("This");
wxGBSpan Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = This->GetItemSpan(static_cast<wxWindow*> (window));
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = This->GetItemSpan(static_cast<wxSizer*> (window));
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGridBagSizer::GetItemSpan
void wxGridBagSizer_GetItemSpan_1_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
if(!This) throw wxe_badarg("This");
wxGBSpan Result = This->GetItemSpan(index);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGridBagSizer::SetEmptyCellSize
void wxGridBagSizer_SetEmptyCellSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *sz_t;
int sz_sz;
if(!enif_get_tuple(env, argv[1], &sz_sz, &sz_t)) Badarg("sz");
int szW;
if(!enif_get_int(env, sz_t[0], &szW)) Badarg("sz");
int szH;
if(!enif_get_int(env, sz_t[1], &szH)) Badarg("sz");
wxSize sz = wxSize(szW,szH);
if(!This) throw wxe_badarg("This");
This->SetEmptyCellSize(sz);
}
// wxGridBagSizer::SetItemPosition
void wxGridBagSizer_SetItemPosition_2_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, argv[2], &pos_sz, &pos_t)) Badarg("pos");
int posR;
if(!enif_get_int(env, pos_t[0], &posR)) Badarg("pos");
int posC;
if(!enif_get_int(env, pos_t[1], &posC)) Badarg("pos");
wxGBPosition pos = wxGBPosition(posR,posC);
if(!This) throw wxe_badarg("This");
bool Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = This->SetItemPosition(static_cast<wxWindow*> (window),pos);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = This->SetItemPosition(static_cast<wxSizer*> (window),pos);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxGridBagSizer::SetItemPosition
void wxGridBagSizer_SetItemPosition_2_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, argv[2], &pos_sz, &pos_t)) Badarg("pos");
int posR;
if(!enif_get_int(env, pos_t[0], &posR)) Badarg("pos");
int posC;
if(!enif_get_int(env, pos_t[1], &posC)) Badarg("pos");
wxGBPosition pos = wxGBPosition(posR,posC);
if(!This) throw wxe_badarg("This");
bool Result = This->SetItemPosition(index,pos);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxGridBagSizer::SetItemSpan
void wxGridBagSizer_SetItemSpan_2_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM window_type;
void * window = memenv->getPtr(env, argv[1], "window", &window_type);
const ERL_NIF_TERM *span_t;
int span_sz;
if(!enif_get_tuple(env, argv[2], &span_sz, &span_t)) Badarg("span");
int spanRS;
if(!enif_get_int(env, span_t[0], &spanRS)) Badarg("span");
int spanCS;
if(!enif_get_int(env, span_t[1], &spanCS)) Badarg("span");
wxGBSpan span = wxGBSpan(spanRS,spanCS);
if(!This) throw wxe_badarg("This");
bool Result;
if(enif_is_identical(window_type, WXE_ATOM_wxWindow))
Result = This->SetItemSpan(static_cast<wxWindow*> (window),span);
else if(enif_is_identical(window_type, WXE_ATOM_wxSizer))
Result = This->SetItemSpan(static_cast<wxSizer*> (window),span);
else throw wxe_badarg("window");
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxGridBagSizer::SetItemSpan
void wxGridBagSizer_SetItemSpan_2_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGridBagSizer *This;
This = (wxGridBagSizer *) memenv->getPtr(env, argv[0], "This");
size_t index;
if(!wxe_get_size_t(env, argv[1], &index)) Badarg("index");
const ERL_NIF_TERM *span_t;
int span_sz;
if(!enif_get_tuple(env, argv[2], &span_sz, &span_t)) Badarg("span");
int spanRS;
if(!enif_get_int(env, span_t[0], &spanRS)) Badarg("span");
int spanCS;
if(!enif_get_int(env, span_t[1], &spanCS)) Badarg("span");
wxGBSpan span = wxGBSpan(spanRS,spanCS);
if(!This) throw wxe_badarg("This");
bool Result = This->SetItemSpan(index,span);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxStdDialogButtonSizer::wxStdDialogButtonSizer
void wxStdDialogButtonSizer_new(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxStdDialogButtonSizer * Result = new EwxStdDialogButtonSizer();
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxStdDialogButtonSizer"));
}
// wxStdDialogButtonSizer::AddButton
void wxStdDialogButtonSizer_AddButton(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxStdDialogButtonSizer *This;
This = (wxStdDialogButtonSizer *) memenv->getPtr(env, argv[0], "This");
wxButton *button;
button = (wxButton *) memenv->getPtr(env, argv[1], "button");
if(!This) throw wxe_badarg("This");
This->AddButton(button);
}
// wxStdDialogButtonSizer::Realize
void wxStdDialogButtonSizer_Realize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxStdDialogButtonSizer *This;
This = (wxStdDialogButtonSizer *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->Realize();
}
// wxStdDialogButtonSizer::SetAffirmativeButton
void wxStdDialogButtonSizer_SetAffirmativeButton(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxStdDialogButtonSizer *This;
This = (wxStdDialogButtonSizer *) memenv->getPtr(env, argv[0], "This");
wxButton *button;
button = (wxButton *) memenv->getPtr(env, argv[1], "button");
if(!This) throw wxe_badarg("This");
This->SetAffirmativeButton(button);
}
// wxStdDialogButtonSizer::SetCancelButton
void wxStdDialogButtonSizer_SetCancelButton(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxStdDialogButtonSizer *This;
This = (wxStdDialogButtonSizer *) memenv->getPtr(env, argv[0], "This");
wxButton *button;
button = (wxButton *) memenv->getPtr(env, argv[1], "button");
if(!This) throw wxe_badarg("This");
This->SetCancelButton(button);
}
// wxStdDialogButtonSizer::SetNegativeButton
void wxStdDialogButtonSizer_SetNegativeButton(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxStdDialogButtonSizer *This;
This = (wxStdDialogButtonSizer *) memenv->getPtr(env, argv[0], "This");
wxButton *button;
button = (wxButton *) memenv->getPtr(env, argv[1], "button");
if(!This) throw wxe_badarg("This");
This->SetNegativeButton(button);
}
// wxFont::wxFont
void wxFont_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxFont * Result = new EwxFont();
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxFont"));
}
// wxFont::wxFont
void wxFont_new_1_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *font;
font = (wxFont *) memenv->getPtr(env, argv[0], "font");
wxFont * Result = new EwxFont(*font);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxFont"));
}
// wxFont::wxFont
void wxFont_new_5_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool underlined=false;
wxString face= wxEmptyString;
wxFontEncoding encoding=wxFONTENCODING_DEFAULT;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
int pointSize;
if(!enif_get_int(env, argv[0], &pointSize)) Badarg("pointSize"); // int
wxFontFamily family;
if(!enif_get_int(env, argv[1], (int *) &family)) Badarg("family"); // enum
wxFontStyle style;
if(!enif_get_int(env, argv[2], (int *) &style)) Badarg("style"); // enum
wxFontWeight weight;
if(!enif_get_int(env, argv[3], (int *) &weight)) Badarg("weight"); // enum
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[4];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "underlined"))) {
underlined = enif_is_identical(tpl[1], WXE_ATOM_true);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "face"))) {
ErlNifBinary face_bin;
if(!enif_inspect_binary(env, tpl[1], &face_bin)) Badarg("face");
face = wxString(face_bin.data, wxConvUTF8, face_bin.size);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "encoding"))) {
if(!enif_get_int(env, tpl[1], (int *) &encoding)) Badarg("encoding"); // enum
} else Badarg("Options");
};
wxFont * Result = new EwxFont(pointSize,family,style,weight,underlined,face,encoding);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxFont"));
}
// wxFont::wxFont
void wxFont_new_5_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool underline=false;
wxString faceName= wxEmptyString;
wxFontEncoding encoding=wxFONTENCODING_DEFAULT;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
const ERL_NIF_TERM *pixelSize_t;
int pixelSize_sz;
if(!enif_get_tuple(env, argv[0], &pixelSize_sz, &pixelSize_t)) Badarg("pixelSize");
int pixelSizeW;
if(!enif_get_int(env, pixelSize_t[0], &pixelSizeW)) Badarg("pixelSize");
int pixelSizeH;
if(!enif_get_int(env, pixelSize_t[1], &pixelSizeH)) Badarg("pixelSize");
wxSize pixelSize = wxSize(pixelSizeW,pixelSizeH);
wxFontFamily family;
if(!enif_get_int(env, argv[1], (int *) &family)) Badarg("family"); // enum
wxFontStyle style;
if(!enif_get_int(env, argv[2], (int *) &style)) Badarg("style"); // enum
wxFontWeight weight;
if(!enif_get_int(env, argv[3], (int *) &weight)) Badarg("weight"); // enum
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[4];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "underline"))) {
underline = enif_is_identical(tpl[1], WXE_ATOM_true);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "faceName"))) {
ErlNifBinary faceName_bin;
if(!enif_inspect_binary(env, tpl[1], &faceName_bin)) Badarg("faceName");
faceName = wxString(faceName_bin.data, wxConvUTF8, faceName_bin.size);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "encoding"))) {
if(!enif_get_int(env, tpl[1], (int *) &encoding)) Badarg("encoding"); // enum
} else Badarg("Options");
};
wxFont * Result = new EwxFont(pixelSize,family,style,weight,underline,faceName,encoding);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxFont"));
}
// wxFont::wxFont
void wxFont_new_1_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
ErlNifBinary nativeInfoString_bin;
wxString nativeInfoString;
if(!enif_inspect_binary(env, argv[0], &nativeInfoString_bin)) Badarg("nativeInfoString");
nativeInfoString = wxString(nativeInfoString_bin.data, wxConvUTF8, nativeInfoString_bin.size);
wxFont * Result = new EwxFont(nativeInfoString);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxFont"));
}
// wxFont::IsFixedWidth
void wxFont_IsFixedWidth(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsFixedWidth();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxFont::GetDefaultEncoding
void wxFont_GetDefaultEncoding(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int Result = wxFont::GetDefaultEncoding();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxFont::GetFaceName
void wxFont_GetFaceName(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxString Result = This->GetFaceName();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxFont::GetFamily
void wxFont_GetFamily(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetFamily();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxFont::GetNativeFontInfoDesc
void wxFont_GetNativeFontInfoDesc(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxString Result = This->GetNativeFontInfoDesc();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxFont::GetNativeFontInfoUserDesc
void wxFont_GetNativeFontInfoUserDesc(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxString Result = This->GetNativeFontInfoUserDesc();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxFont::GetPointSize
void wxFont_GetPointSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetPointSize();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxFont::GetStyle
void wxFont_GetStyle(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetStyle();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxFont::GetUnderlined
void wxFont_GetUnderlined(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->GetUnderlined();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxFont::GetWeight
void wxFont_GetWeight(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetWeight();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxFont::IsOk
void wxFont_IsOk(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsOk();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxFont::SetDefaultEncoding
void wxFont_SetDefaultEncoding(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFontEncoding encoding;
if(!enif_get_int(env, argv[0], (int *) &encoding)) Badarg("encoding"); // enum
wxFont::SetDefaultEncoding(encoding);
}
// wxFont::SetFaceName
void wxFont_SetFaceName(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
ErlNifBinary faceName_bin;
wxString faceName;
if(!enif_inspect_binary(env, argv[1], &faceName_bin)) Badarg("faceName");
faceName = wxString(faceName_bin.data, wxConvUTF8, faceName_bin.size);
if(!This) throw wxe_badarg("This");
bool Result = This->SetFaceName(faceName);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxFont::SetFamily
void wxFont_SetFamily(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
wxFontFamily family;
if(!enif_get_int(env, argv[1], (int *) &family)) Badarg("family"); // enum
if(!This) throw wxe_badarg("This");
This->SetFamily(family);
}
// wxFont::SetPointSize
void wxFont_SetPointSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
int pointSize;
if(!enif_get_int(env, argv[1], &pointSize)) Badarg("pointSize"); // int
if(!This) throw wxe_badarg("This");
This->SetPointSize(pointSize);
}
// wxFont::SetStyle
void wxFont_SetStyle(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
wxFontStyle style;
if(!enif_get_int(env, argv[1], (int *) &style)) Badarg("style"); // enum
if(!This) throw wxe_badarg("This");
This->SetStyle(style);
}
// wxFont::SetUnderlined
void wxFont_SetUnderlined(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
bool underlined;
underlined = enif_is_identical(argv[1], WXE_ATOM_true);
if(!This) throw wxe_badarg("This");
This->SetUnderlined(underlined);
}
// wxFont::SetWeight
void wxFont_SetWeight(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxFont *This;
This = (wxFont *) memenv->getPtr(env, argv[0], "This");
wxFontWeight weight;
if(!enif_get_int(env, argv[1], (int *) &weight)) Badarg("weight"); // enum
if(!This) throw wxe_badarg("This");
This->SetWeight(weight);
}
// wxToolTip::Enable
void wxToolTip_Enable(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ERL_NIF_TERM * argv = Ecmd.args;
bool flag;
flag = enif_is_identical(argv[0], WXE_ATOM_true);
wxToolTip::Enable(flag);
}
// wxToolTip::SetDelay
void wxToolTip_SetDelay(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
long msecs;
if(!enif_get_long(env, argv[0], &msecs)) Badarg("msecs");
wxToolTip::SetDelay(msecs);
}
// wxToolTip::wxToolTip
void wxToolTip_new(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
ErlNifBinary tip_bin;
wxString tip;
if(!enif_inspect_binary(env, argv[0], &tip_bin)) Badarg("tip");
tip = wxString(tip_bin.data, wxConvUTF8, tip_bin.size);
wxToolTip * Result = new EwxToolTip(tip);
app->newPtr((void *) Result, 1, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxToolTip"));
}
// wxToolTip::SetTip
void wxToolTip_SetTip(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxToolTip *This;
This = (wxToolTip *) memenv->getPtr(env, argv[0], "This");
ErlNifBinary tip_bin;
wxString tip;
if(!enif_inspect_binary(env, argv[1], &tip_bin)) Badarg("tip");
tip = wxString(tip_bin.data, wxConvUTF8, tip_bin.size);
if(!This) throw wxe_badarg("This");
This->SetTip(tip);
}
// wxToolTip::GetTip
void wxToolTip_GetTip(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxToolTip *This;
This = (wxToolTip *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxString Result = This->GetTip();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxToolTip::GetWindow
void wxToolTip_GetWindow(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxToolTip *This;
This = (wxToolTip *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxWindow * Result = (wxWindow*)This->GetWindow();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxWindow"));
}
// wxButton::wxButton
void wxButton_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxButton * Result = new EwxButton();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxButton"));
}
// wxButton::wxButton
void wxButton_new_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxString label= wxEmptyString;
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
int id;
if(!enif_get_int(env, argv[1], &id)) Badarg("id"); // wxWindowID
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "label"))) {
ErlNifBinary label_bin;
if(!enif_inspect_binary(env, tpl[1], &label_bin)) Badarg("label");
label = wxString(label_bin.data, wxConvUTF8, label_bin.size);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
wxButton * Result = new EwxButton(parent,id,label,pos,size,style,*validator);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxButton"));
}
// wxButton::Create
void wxButton_Create(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxString label= wxEmptyString;
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxButton *This;
This = (wxButton *) memenv->getPtr(env, argv[0], "This");
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
int id;
if(!enif_get_int(env, argv[2], &id)) Badarg("id"); // wxWindowID
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "label"))) {
ErlNifBinary label_bin;
if(!enif_inspect_binary(env, tpl[1], &label_bin)) Badarg("label");
label = wxString(label_bin.data, wxConvUTF8, label_bin.size);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Create(parent,id,label,pos,size,style,*validator);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxButton::GetDefaultSize
void wxButton_GetDefaultSize_STAT_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxSize Result = wxButton::GetDefaultSize();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
#if wxCHECK_VERSION(3,1,3)
// wxButton::GetDefaultSize
void wxButton_GetDefaultSize_STAT_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *win;
win = (wxWindow *) memenv->getPtr(env, argv[0], "win");
wxSize Result = wxButton::GetDefaultSize(win);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
#endif
// wxButton::SetDefault
void wxButton_SetDefault(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxButton *This;
This = (wxButton *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxWindow * Result = (wxWindow*)This->SetDefault();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxWindow"));
}
// wxButton::SetLabel
void wxButton_SetLabel(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxButton *This;
This = (wxButton *) memenv->getPtr(env, argv[0], "This");
ErlNifBinary label_bin;
wxString label;
if(!enif_inspect_binary(env, argv[1], &label_bin)) Badarg("label");
label = wxString(label_bin.data, wxConvUTF8, label_bin.size);
if(!This) throw wxe_badarg("This");
This->SetLabel(label);
}
// wxButton::GetBitmapDisabled
void wxButton_GetBitmapDisabled(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxButton *This;
This = (wxButton *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxBitmap * Result = new wxBitmap(This->GetBitmapDisabled()); app->newPtr((void *) Result,3, memenv);;
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxBitmap"));
}
// wxButton::GetBitmapFocus
void wxButton_GetBitmapFocus(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxButton *This;
This = (wxButton *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxBitmap * Result = new wxBitmap(This->GetBitmapFocus()); app->newPtr((void *) Result,3, memenv);;
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxBitmap"));
}
// wxButton::GetBitmapLabel
void wxButton_GetBitmapLabel(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxButton *This;
This = (wxButton *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxBitmap * Result = new wxBitmap(This->GetBitmapLabel()); app->newPtr((void *) Result,3, memenv);;
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxBitmap"));
}
// wxButton::SetBitmapDisabled
void wxButton_SetBitmapDisabled(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxButton *This;
This = (wxButton *) memenv->getPtr(env, argv[0], "This");
wxBitmap *bitmap;
bitmap = (wxBitmap *) memenv->getPtr(env, argv[1], "bitmap");
if(!This) throw wxe_badarg("This");
This->SetBitmapDisabled(*bitmap);
}
// wxButton::SetBitmapFocus
void wxButton_SetBitmapFocus(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxButton *This;
This = (wxButton *) memenv->getPtr(env, argv[0], "This");
wxBitmap *bitmap;
bitmap = (wxBitmap *) memenv->getPtr(env, argv[1], "bitmap");
if(!This) throw wxe_badarg("This");
This->SetBitmapFocus(*bitmap);
}
// wxButton::SetBitmapLabel
void wxButton_SetBitmapLabel(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxButton *This;
This = (wxButton *) memenv->getPtr(env, argv[0], "This");
wxBitmap *bitmap;
bitmap = (wxBitmap *) memenv->getPtr(env, argv[1], "bitmap");
if(!This) throw wxe_badarg("This");
This->SetBitmapLabel(*bitmap);
}
// wxBitmapButton::wxBitmapButton
void wxBitmapButton_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxBitmapButton * Result = new EwxBitmapButton();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxBitmapButton"));
}
// wxBitmapButton::wxBitmapButton
void wxBitmapButton_new_4(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
int id;
if(!enif_get_int(env, argv[1], &id)) Badarg("id"); // wxWindowID
wxBitmap *bitmap;
bitmap = (wxBitmap *) memenv->getPtr(env, argv[2], "bitmap");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
wxBitmapButton * Result = new EwxBitmapButton(parent,id,*bitmap,pos,size,style,*validator);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxBitmapButton"));
}
// wxBitmapButton::Create
void wxBitmapButton_Create(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxBitmapButton *This;
This = (wxBitmapButton *) memenv->getPtr(env, argv[0], "This");
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
int id;
if(!enif_get_int(env, argv[2], &id)) Badarg("id"); // wxWindowID
wxBitmap *bitmap;
bitmap = (wxBitmap *) memenv->getPtr(env, argv[3], "bitmap");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[4];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Create(parent,id,*bitmap,pos,size,style,*validator);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxBitmapButton::NewCloseButton
void wxBitmapButton_NewCloseButton(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
int winid;
if(!enif_get_int(env, argv[1], &winid)) Badarg("winid"); // wxWindowID
wxBitmapButton * Result = (wxBitmapButton*)wxBitmapButton::NewCloseButton(parent,winid);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxBitmapButton"));
}
// wxToggleButton::wxToggleButton
void wxToggleButton_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxToggleButton * Result = new EwxToggleButton();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxToggleButton"));
}
// wxToggleButton::wxToggleButton
void wxToggleButton_new_4(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
int id;
if(!enif_get_int(env, argv[1], &id)) Badarg("id"); // wxWindowID
ErlNifBinary label_bin;
wxString label;
if(!enif_inspect_binary(env, argv[2], &label_bin)) Badarg("label");
label = wxString(label_bin.data, wxConvUTF8, label_bin.size);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
wxToggleButton * Result = new EwxToggleButton(parent,id,label,pos,size,style,*validator);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxToggleButton"));
}
// wxToggleButton::Create
void wxToggleButton_Create(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxToggleButton *This;
This = (wxToggleButton *) memenv->getPtr(env, argv[0], "This");
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
int id;
if(!enif_get_int(env, argv[2], &id)) Badarg("id"); // wxWindowID
ErlNifBinary label_bin;
wxString label;
if(!enif_inspect_binary(env, argv[3], &label_bin)) Badarg("label");
label = wxString(label_bin.data, wxConvUTF8, label_bin.size);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[4];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Create(parent,id,label,pos,size,style,*validator);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxToggleButton::GetValue
void wxToggleButton_GetValue(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxToggleButton *This;
This = (wxToggleButton *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->GetValue();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxToggleButton::SetValue
void wxToggleButton_SetValue(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxToggleButton *This;
This = (wxToggleButton *) memenv->getPtr(env, argv[0], "This");
bool state;
state = enif_is_identical(argv[1], WXE_ATOM_true);
if(!This) throw wxe_badarg("This");
This->SetValue(state);
}
// wxCalendarCtrl::wxCalendarCtrl
void wxCalendarCtrl_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxCalendarCtrl * Result = new EwxCalendarCtrl();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxCalendarCtrl"));
}
// wxCalendarCtrl::wxCalendarCtrl
void wxCalendarCtrl_new_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxDateTime date= wxDefaultDateTime;
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=wxCAL_SHOW_HOLIDAYS;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
int id;
if(!enif_get_int(env, argv[1], &id)) Badarg("id"); // wxWindowID
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "date"))) {
const ERL_NIF_TERM *date_t;
int date_sz;
if(!enif_get_tuple(env, tpl[1], &date_sz, &date_t)) Badarg("date");
int dateD;
if(!enif_get_int(env, date_t[0], &dateD)) Badarg("date");
int dateMo;
if(!enif_get_int(env, date_t[1], &dateMo)) Badarg("date");
int dateY;
if(!enif_get_int(env, date_t[2], &dateY)) Badarg("date");
int dateH;
if(!enif_get_int(env, date_t[3], &dateH)) Badarg("date");
int dateMi;
if(!enif_get_int(env, date_t[4], &dateMi)) Badarg("date");
int dateS;
if(!enif_get_int(env, date_t[5], &dateS)) Badarg("date");
date = wxDateTime((wxDateTime::wxDateTime_t) dateD,(wxDateTime::Month) (dateMo-1),dateY,(wxDateTime::wxDateTime_t) dateH,(wxDateTime::wxDateTime_t) dateMi,(wxDateTime::wxDateTime_t) dateS);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else Badarg("Options");
};
wxCalendarCtrl * Result = new EwxCalendarCtrl(parent,id,date,pos,size,style);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxCalendarCtrl"));
}
// wxCalendarCtrl::Create
void wxCalendarCtrl_Create(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxDateTime date= wxDefaultDateTime;
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=wxCAL_SHOW_HOLIDAYS;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
int id;
if(!enif_get_int(env, argv[2], &id)) Badarg("id"); // wxWindowID
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "date"))) {
const ERL_NIF_TERM *date_t;
int date_sz;
if(!enif_get_tuple(env, tpl[1], &date_sz, &date_t)) Badarg("date");
int dateD;
if(!enif_get_int(env, date_t[0], &dateD)) Badarg("date");
int dateMo;
if(!enif_get_int(env, date_t[1], &dateMo)) Badarg("date");
int dateY;
if(!enif_get_int(env, date_t[2], &dateY)) Badarg("date");
int dateH;
if(!enif_get_int(env, date_t[3], &dateH)) Badarg("date");
int dateMi;
if(!enif_get_int(env, date_t[4], &dateMi)) Badarg("date");
int dateS;
if(!enif_get_int(env, date_t[5], &dateS)) Badarg("date");
date = wxDateTime((wxDateTime::wxDateTime_t) dateD,(wxDateTime::Month) (dateMo-1),dateY,(wxDateTime::wxDateTime_t) dateH,(wxDateTime::wxDateTime_t) dateMi,(wxDateTime::wxDateTime_t) dateS);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Create(parent,id,date,pos,size,style);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCalendarCtrl::SetDate
void wxCalendarCtrl_SetDate(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *date_t;
int date_sz;
if(!enif_get_tuple(env, argv[1], &date_sz, &date_t)) Badarg("date");
int dateD;
if(!enif_get_int(env, date_t[0], &dateD)) Badarg("date");
int dateMo;
if(!enif_get_int(env, date_t[1], &dateMo)) Badarg("date");
int dateY;
if(!enif_get_int(env, date_t[2], &dateY)) Badarg("date");
int dateH;
if(!enif_get_int(env, date_t[3], &dateH)) Badarg("date");
int dateMi;
if(!enif_get_int(env, date_t[4], &dateMi)) Badarg("date");
int dateS;
if(!enif_get_int(env, date_t[5], &dateS)) Badarg("date");
wxDateTime date = wxDateTime((wxDateTime::wxDateTime_t) dateD,(wxDateTime::Month) (dateMo-1),dateY,(wxDateTime::wxDateTime_t) dateH,(wxDateTime::wxDateTime_t) dateMi,(wxDateTime::wxDateTime_t) dateS);
if(!This) throw wxe_badarg("This");
bool Result = This->SetDate(date);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCalendarCtrl::GetDate
void wxCalendarCtrl_GetDate(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxDateTime Result = This->GetDate();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
#if !wxCHECK_VERSION(2,9,0)
// wxCalendarCtrl::EnableYearChange
void wxCalendarCtrl_EnableYearChange(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool enable=true;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "enable"))) {
enable = enif_is_identical(tpl[1], WXE_ATOM_true);
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
This->EnableYearChange(enable);
}
#endif
// wxCalendarCtrl::EnableMonthChange
void wxCalendarCtrl_EnableMonthChange(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool enable=true;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "enable"))) {
enable = enif_is_identical(tpl[1], WXE_ATOM_true);
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->EnableMonthChange(enable);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCalendarCtrl::EnableHolidayDisplay
void wxCalendarCtrl_EnableHolidayDisplay(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool display=true;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "display"))) {
display = enif_is_identical(tpl[1], WXE_ATOM_true);
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
This->EnableHolidayDisplay(display);
}
// wxCalendarCtrl::SetHeaderColours
void wxCalendarCtrl_SetHeaderColours(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *colFg_t;
int colFg_sz;
if(!enif_get_tuple(env, argv[1], &colFg_sz, &colFg_t)) Badarg("colFg");
int colFgR;
if(!enif_get_int(env, colFg_t[0], &colFgR)) Badarg("colFg");
int colFgG;
if(!enif_get_int(env, colFg_t[1], &colFgG)) Badarg("colFg");
int colFgB;
if(!enif_get_int(env, colFg_t[2], &colFgB)) Badarg("colFg");
int colFgA;
if(!enif_get_int(env, colFg_t[3], &colFgA)) Badarg("colFg");
wxColour colFg = wxColour(colFgR,colFgG,colFgB,colFgA);
const ERL_NIF_TERM *colBg_t;
int colBg_sz;
if(!enif_get_tuple(env, argv[2], &colBg_sz, &colBg_t)) Badarg("colBg");
int colBgR;
if(!enif_get_int(env, colBg_t[0], &colBgR)) Badarg("colBg");
int colBgG;
if(!enif_get_int(env, colBg_t[1], &colBgG)) Badarg("colBg");
int colBgB;
if(!enif_get_int(env, colBg_t[2], &colBgB)) Badarg("colBg");
int colBgA;
if(!enif_get_int(env, colBg_t[3], &colBgA)) Badarg("colBg");
wxColour colBg = wxColour(colBgR,colBgG,colBgB,colBgA);
if(!This) throw wxe_badarg("This");
This->SetHeaderColours(colFg,colBg);
}
// wxCalendarCtrl::GetHeaderColourFg
void wxCalendarCtrl_GetHeaderColourFg(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
const wxColour * Result = &This->GetHeaderColourFg();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make((*Result)));
}
// wxCalendarCtrl::GetHeaderColourBg
void wxCalendarCtrl_GetHeaderColourBg(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
const wxColour * Result = &This->GetHeaderColourBg();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make((*Result)));
}
// wxCalendarCtrl::SetHighlightColours
void wxCalendarCtrl_SetHighlightColours(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *colFg_t;
int colFg_sz;
if(!enif_get_tuple(env, argv[1], &colFg_sz, &colFg_t)) Badarg("colFg");
int colFgR;
if(!enif_get_int(env, colFg_t[0], &colFgR)) Badarg("colFg");
int colFgG;
if(!enif_get_int(env, colFg_t[1], &colFgG)) Badarg("colFg");
int colFgB;
if(!enif_get_int(env, colFg_t[2], &colFgB)) Badarg("colFg");
int colFgA;
if(!enif_get_int(env, colFg_t[3], &colFgA)) Badarg("colFg");
wxColour colFg = wxColour(colFgR,colFgG,colFgB,colFgA);
const ERL_NIF_TERM *colBg_t;
int colBg_sz;
if(!enif_get_tuple(env, argv[2], &colBg_sz, &colBg_t)) Badarg("colBg");
int colBgR;
if(!enif_get_int(env, colBg_t[0], &colBgR)) Badarg("colBg");
int colBgG;
if(!enif_get_int(env, colBg_t[1], &colBgG)) Badarg("colBg");
int colBgB;
if(!enif_get_int(env, colBg_t[2], &colBgB)) Badarg("colBg");
int colBgA;
if(!enif_get_int(env, colBg_t[3], &colBgA)) Badarg("colBg");
wxColour colBg = wxColour(colBgR,colBgG,colBgB,colBgA);
if(!This) throw wxe_badarg("This");
This->SetHighlightColours(colFg,colBg);
}
// wxCalendarCtrl::GetHighlightColourFg
void wxCalendarCtrl_GetHighlightColourFg(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
const wxColour * Result = &This->GetHighlightColourFg();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make((*Result)));
}
// wxCalendarCtrl::GetHighlightColourBg
void wxCalendarCtrl_GetHighlightColourBg(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
const wxColour * Result = &This->GetHighlightColourBg();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make((*Result)));
}
// wxCalendarCtrl::SetHolidayColours
void wxCalendarCtrl_SetHolidayColours(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *colFg_t;
int colFg_sz;
if(!enif_get_tuple(env, argv[1], &colFg_sz, &colFg_t)) Badarg("colFg");
int colFgR;
if(!enif_get_int(env, colFg_t[0], &colFgR)) Badarg("colFg");
int colFgG;
if(!enif_get_int(env, colFg_t[1], &colFgG)) Badarg("colFg");
int colFgB;
if(!enif_get_int(env, colFg_t[2], &colFgB)) Badarg("colFg");
int colFgA;
if(!enif_get_int(env, colFg_t[3], &colFgA)) Badarg("colFg");
wxColour colFg = wxColour(colFgR,colFgG,colFgB,colFgA);
const ERL_NIF_TERM *colBg_t;
int colBg_sz;
if(!enif_get_tuple(env, argv[2], &colBg_sz, &colBg_t)) Badarg("colBg");
int colBgR;
if(!enif_get_int(env, colBg_t[0], &colBgR)) Badarg("colBg");
int colBgG;
if(!enif_get_int(env, colBg_t[1], &colBgG)) Badarg("colBg");
int colBgB;
if(!enif_get_int(env, colBg_t[2], &colBgB)) Badarg("colBg");
int colBgA;
if(!enif_get_int(env, colBg_t[3], &colBgA)) Badarg("colBg");
wxColour colBg = wxColour(colBgR,colBgG,colBgB,colBgA);
if(!This) throw wxe_badarg("This");
This->SetHolidayColours(colFg,colBg);
}
// wxCalendarCtrl::GetHolidayColourFg
void wxCalendarCtrl_GetHolidayColourFg(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
const wxColour * Result = &This->GetHolidayColourFg();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make((*Result)));
}
// wxCalendarCtrl::GetHolidayColourBg
void wxCalendarCtrl_GetHolidayColourBg(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
const wxColour * Result = &This->GetHolidayColourBg();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make((*Result)));
}
// wxCalendarCtrl::GetAttr
void wxCalendarCtrl_GetAttr(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
size_t day;
if(!wxe_get_size_t(env, argv[1], &day)) Badarg("day");
if(!This) throw wxe_badarg("This");
wxCalendarDateAttr * Result = (wxCalendarDateAttr*)This->GetAttr(day);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxCalendarDateAttr"));
}
// wxCalendarCtrl::SetAttr
void wxCalendarCtrl_SetAttr(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
size_t day;
if(!wxe_get_size_t(env, argv[1], &day)) Badarg("day");
wxCalendarDateAttr *attr;
attr = (wxCalendarDateAttr *) memenv->getPtr(env, argv[2], "attr");
if(!This) throw wxe_badarg("This");
This->SetAttr(day,attr);
}
// wxCalendarCtrl::SetHoliday
void wxCalendarCtrl_SetHoliday(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
size_t day;
if(!wxe_get_size_t(env, argv[1], &day)) Badarg("day");
if(!This) throw wxe_badarg("This");
This->SetHoliday(day);
}
// wxCalendarCtrl::ResetAttr
void wxCalendarCtrl_ResetAttr(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
size_t day;
if(!wxe_get_size_t(env, argv[1], &day)) Badarg("day");
if(!This) throw wxe_badarg("This");
This->ResetAttr(day);
}
// wxCalendarCtrl::HitTest
void wxCalendarCtrl_HitTest(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxDateTime date;
wxDateTime::WeekDay wd;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarCtrl *This;
This = (wxCalendarCtrl *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, argv[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
wxPoint pos = wxPoint(posX,posY);
if(!This) throw wxe_badarg("This");
int Result = This->HitTest(pos,&date,&wd);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
ERL_NIF_TERM msg = enif_make_tuple3(rt.env,
rt.make_int(Result),
rt.make(date),
rt.make_int(wd));
rt.send(msg);
}
// wxCalendarDateAttr::wxCalendarDateAttr
void wxCalendarDateAttr_new_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxColour colText= wxNullColour;
wxColour colBack= wxNullColour;
wxColour colBorder= wxNullColour;
const wxFont * font= &wxNullFont;
wxCalendarDateBorder border=wxCAL_BORDER_NONE;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[0];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "colText"))) {
const ERL_NIF_TERM *colText_t;
int colText_sz;
if(!enif_get_tuple(env, tpl[1], &colText_sz, &colText_t)) Badarg("colText");
int colTextR;
if(!enif_get_int(env, colText_t[0], &colTextR)) Badarg("colText");
int colTextG;
if(!enif_get_int(env, colText_t[1], &colTextG)) Badarg("colText");
int colTextB;
if(!enif_get_int(env, colText_t[2], &colTextB)) Badarg("colText");
int colTextA;
if(!enif_get_int(env, colText_t[3], &colTextA)) Badarg("colText");
colText = wxColour(colTextR,colTextG,colTextB,colTextA);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "colBack"))) {
const ERL_NIF_TERM *colBack_t;
int colBack_sz;
if(!enif_get_tuple(env, tpl[1], &colBack_sz, &colBack_t)) Badarg("colBack");
int colBackR;
if(!enif_get_int(env, colBack_t[0], &colBackR)) Badarg("colBack");
int colBackG;
if(!enif_get_int(env, colBack_t[1], &colBackG)) Badarg("colBack");
int colBackB;
if(!enif_get_int(env, colBack_t[2], &colBackB)) Badarg("colBack");
int colBackA;
if(!enif_get_int(env, colBack_t[3], &colBackA)) Badarg("colBack");
colBack = wxColour(colBackR,colBackG,colBackB,colBackA);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "colBorder"))) {
const ERL_NIF_TERM *colBorder_t;
int colBorder_sz;
if(!enif_get_tuple(env, tpl[1], &colBorder_sz, &colBorder_t)) Badarg("colBorder");
int colBorderR;
if(!enif_get_int(env, colBorder_t[0], &colBorderR)) Badarg("colBorder");
int colBorderG;
if(!enif_get_int(env, colBorder_t[1], &colBorderG)) Badarg("colBorder");
int colBorderB;
if(!enif_get_int(env, colBorder_t[2], &colBorderB)) Badarg("colBorder");
int colBorderA;
if(!enif_get_int(env, colBorder_t[3], &colBorderA)) Badarg("colBorder");
colBorder = wxColour(colBorderR,colBorderG,colBorderB,colBorderA);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "font"))) {
font = (wxFont *) memenv->getPtr(env, tpl[1], "font");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "border"))) {
if(!enif_get_int(env, tpl[1], (int *) &border)) Badarg("border"); // enum
} else Badarg("Options");
};
wxCalendarDateAttr * Result = new wxCalendarDateAttr(colText,colBack,colBorder,*font,border);
app->newPtr((void *) Result, 89, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxCalendarDateAttr"));
}
// wxCalendarDateAttr::wxCalendarDateAttr
void wxCalendarDateAttr_new_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxColour colBorder= wxNullColour;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateBorder border;
if(!enif_get_int(env, argv[0], (int *) &border)) Badarg("border"); // enum
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "colBorder"))) {
const ERL_NIF_TERM *colBorder_t;
int colBorder_sz;
if(!enif_get_tuple(env, tpl[1], &colBorder_sz, &colBorder_t)) Badarg("colBorder");
int colBorderR;
if(!enif_get_int(env, colBorder_t[0], &colBorderR)) Badarg("colBorder");
int colBorderG;
if(!enif_get_int(env, colBorder_t[1], &colBorderG)) Badarg("colBorder");
int colBorderB;
if(!enif_get_int(env, colBorder_t[2], &colBorderB)) Badarg("colBorder");
int colBorderA;
if(!enif_get_int(env, colBorder_t[3], &colBorderA)) Badarg("colBorder");
colBorder = wxColour(colBorderR,colBorderG,colBorderB,colBorderA);
} else Badarg("Options");
};
wxCalendarDateAttr * Result = new wxCalendarDateAttr(border,colBorder);
app->newPtr((void *) Result, 89, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxCalendarDateAttr"));
}
// wxCalendarDateAttr::SetTextColour
void wxCalendarDateAttr_SetTextColour(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *colText_t;
int colText_sz;
if(!enif_get_tuple(env, argv[1], &colText_sz, &colText_t)) Badarg("colText");
int colTextR;
if(!enif_get_int(env, colText_t[0], &colTextR)) Badarg("colText");
int colTextG;
if(!enif_get_int(env, colText_t[1], &colTextG)) Badarg("colText");
int colTextB;
if(!enif_get_int(env, colText_t[2], &colTextB)) Badarg("colText");
int colTextA;
if(!enif_get_int(env, colText_t[3], &colTextA)) Badarg("colText");
wxColour colText = wxColour(colTextR,colTextG,colTextB,colTextA);
if(!This) throw wxe_badarg("This");
This->SetTextColour(colText);
}
// wxCalendarDateAttr::SetBackgroundColour
void wxCalendarDateAttr_SetBackgroundColour(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *colBack_t;
int colBack_sz;
if(!enif_get_tuple(env, argv[1], &colBack_sz, &colBack_t)) Badarg("colBack");
int colBackR;
if(!enif_get_int(env, colBack_t[0], &colBackR)) Badarg("colBack");
int colBackG;
if(!enif_get_int(env, colBack_t[1], &colBackG)) Badarg("colBack");
int colBackB;
if(!enif_get_int(env, colBack_t[2], &colBackB)) Badarg("colBack");
int colBackA;
if(!enif_get_int(env, colBack_t[3], &colBackA)) Badarg("colBack");
wxColour colBack = wxColour(colBackR,colBackG,colBackB,colBackA);
if(!This) throw wxe_badarg("This");
This->SetBackgroundColour(colBack);
}
// wxCalendarDateAttr::SetBorderColour
void wxCalendarDateAttr_SetBorderColour(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
const ERL_NIF_TERM *col_t;
int col_sz;
if(!enif_get_tuple(env, argv[1], &col_sz, &col_t)) Badarg("col");
int colR;
if(!enif_get_int(env, col_t[0], &colR)) Badarg("col");
int colG;
if(!enif_get_int(env, col_t[1], &colG)) Badarg("col");
int colB;
if(!enif_get_int(env, col_t[2], &colB)) Badarg("col");
int colA;
if(!enif_get_int(env, col_t[3], &colA)) Badarg("col");
wxColour col = wxColour(colR,colG,colB,colA);
if(!This) throw wxe_badarg("This");
This->SetBorderColour(col);
}
// wxCalendarDateAttr::SetFont
void wxCalendarDateAttr_SetFont(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
wxFont *font;
font = (wxFont *) memenv->getPtr(env, argv[1], "font");
if(!This) throw wxe_badarg("This");
This->SetFont(*font);
}
// wxCalendarDateAttr::SetBorder
void wxCalendarDateAttr_SetBorder(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
wxCalendarDateBorder border;
if(!enif_get_int(env, argv[1], (int *) &border)) Badarg("border"); // enum
if(!This) throw wxe_badarg("This");
This->SetBorder(border);
}
// wxCalendarDateAttr::SetHoliday
void wxCalendarDateAttr_SetHoliday(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
bool holiday;
holiday = enif_is_identical(argv[1], WXE_ATOM_true);
if(!This) throw wxe_badarg("This");
This->SetHoliday(holiday);
}
// wxCalendarDateAttr::HasTextColour
void wxCalendarDateAttr_HasTextColour(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->HasTextColour();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCalendarDateAttr::HasBackgroundColour
void wxCalendarDateAttr_HasBackgroundColour(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->HasBackgroundColour();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCalendarDateAttr::HasBorderColour
void wxCalendarDateAttr_HasBorderColour(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->HasBorderColour();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCalendarDateAttr::HasFont
void wxCalendarDateAttr_HasFont(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->HasFont();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCalendarDateAttr::HasBorder
void wxCalendarDateAttr_HasBorder(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->HasBorder();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCalendarDateAttr::IsHoliday
void wxCalendarDateAttr_IsHoliday(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsHoliday();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCalendarDateAttr::GetTextColour
void wxCalendarDateAttr_GetTextColour(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
const wxColour * Result = &This->GetTextColour();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make((*Result)));
}
// wxCalendarDateAttr::GetBackgroundColour
void wxCalendarDateAttr_GetBackgroundColour(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
const wxColour * Result = &This->GetBackgroundColour();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make((*Result)));
}
// wxCalendarDateAttr::GetBorderColour
void wxCalendarDateAttr_GetBorderColour(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
const wxColour * Result = &This->GetBorderColour();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make((*Result)));
}
// wxCalendarDateAttr::GetFont
void wxCalendarDateAttr_GetFont(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
const wxFont * Result = &This->GetFont();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxFont"));
}
// wxCalendarDateAttr::GetBorder
void wxCalendarDateAttr_GetBorder(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetBorder();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxCalendarDateAttr::destroy
void wxCalendarDateAttr_destroy(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCalendarDateAttr *This;
This = (wxCalendarDateAttr *) memenv->getPtr(env, argv[0], "This");
if(This) { ((WxeApp *) wxTheApp)->clearPtr((void *) This);
delete This;}
}
// wxCheckBox::wxCheckBox
void wxCheckBox_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxCheckBox * Result = new EwxCheckBox();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxCheckBox"));
}
// wxCheckBox::wxCheckBox
void wxCheckBox_new_4(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
int id;
if(!enif_get_int(env, argv[1], &id)) Badarg("id"); // wxWindowID
ErlNifBinary label_bin;
wxString label;
if(!enif_inspect_binary(env, argv[2], &label_bin)) Badarg("label");
label = wxString(label_bin.data, wxConvUTF8, label_bin.size);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
wxCheckBox * Result = new EwxCheckBox(parent,id,label,pos,size,style,*validator);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxCheckBox"));
}
// wxCheckBox::Create
void wxCheckBox_Create(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCheckBox *This;
This = (wxCheckBox *) memenv->getPtr(env, argv[0], "This");
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
int id;
if(!enif_get_int(env, argv[2], &id)) Badarg("id"); // wxWindowID
ErlNifBinary label_bin;
wxString label;
if(!enif_inspect_binary(env, argv[3], &label_bin)) Badarg("label");
label = wxString(label_bin.data, wxConvUTF8, label_bin.size);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[4];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Create(parent,id,label,pos,size,style,*validator);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCheckBox::GetValue
void wxCheckBox_GetValue(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCheckBox *This;
This = (wxCheckBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->GetValue();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCheckBox::Get3StateValue
void wxCheckBox_Get3StateValue(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCheckBox *This;
This = (wxCheckBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->Get3StateValue();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxCheckBox::Is3rdStateAllowedForUser
void wxCheckBox_Is3rdStateAllowedForUser(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCheckBox *This;
This = (wxCheckBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->Is3rdStateAllowedForUser();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCheckBox::Is3State
void wxCheckBox_Is3State(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCheckBox *This;
This = (wxCheckBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->Is3State();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCheckBox::IsChecked
void wxCheckBox_IsChecked(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCheckBox *This;
This = (wxCheckBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsChecked();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxCheckBox::SetValue
void wxCheckBox_SetValue(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCheckBox *This;
This = (wxCheckBox *) memenv->getPtr(env, argv[0], "This");
bool state;
state = enif_is_identical(argv[1], WXE_ATOM_true);
if(!This) throw wxe_badarg("This");
This->SetValue(state);
}
// wxCheckBox::Set3StateValue
void wxCheckBox_Set3StateValue(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCheckBox *This;
This = (wxCheckBox *) memenv->getPtr(env, argv[0], "This");
wxCheckBoxState state;
if(!enif_get_int(env, argv[1], (int *) &state)) Badarg("state"); // enum
if(!This) throw wxe_badarg("This");
This->Set3StateValue(state);
}
// wxCheckListBox::wxCheckListBox
void wxCheckListBox_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxCheckListBox * Result = new EwxCheckListBox();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxCheckListBox"));
}
// wxCheckListBox::wxCheckListBox
void wxCheckListBox_new_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
wxArrayString choices;
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
int id;
if(!enif_get_int(env, argv[1], &id)) Badarg("id"); // wxWindowID
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "choices"))) {
ERL_NIF_TERM choicesHead, choicesTail;
ErlNifBinary choices_bin;
choicesTail = tpl[1];
while(!enif_is_empty_list(env, choicesTail)) {
if(!enif_get_list_cell(env, choicesTail, &choicesHead, &choicesTail)) Badarg("choices");
if(!enif_inspect_binary(env, choicesHead, &choices_bin)) Badarg("choices");
choices.Add(wxString(choices_bin.data, wxConvUTF8, choices_bin.size));
};
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
wxCheckListBox * Result = new EwxCheckListBox(parent,id,pos,size,choices,style,*validator);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxCheckListBox"));
}
// wxCheckListBox::Check
void wxCheckListBox_Check(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
bool check=true;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCheckListBox *This;
This = (wxCheckListBox *) memenv->getPtr(env, argv[0], "This");
unsigned int item;
if(!enif_get_uint(env, argv[1], &item)) Badarg("item");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "check"))) {
check = enif_is_identical(tpl[1], WXE_ATOM_true);
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
This->Check(item,check);
}
// wxCheckListBox::IsChecked
void wxCheckListBox_IsChecked(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxCheckListBox *This;
This = (wxCheckListBox *) memenv->getPtr(env, argv[0], "This");
unsigned int item;
if(!enif_get_uint(env, argv[1], &item)) Badarg("item");
if(!This) throw wxe_badarg("This");
bool Result = This->IsChecked(item);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxChoice::wxChoice
void wxChoice_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxChoice * Result = new EwxChoice();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxChoice"));
}
// wxChoice::wxChoice
void wxChoice_new_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
wxArrayString choices;
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
int id;
if(!enif_get_int(env, argv[1], &id)) Badarg("id"); // wxWindowID
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "choices"))) {
ERL_NIF_TERM choicesHead, choicesTail;
ErlNifBinary choices_bin;
choicesTail = tpl[1];
while(!enif_is_empty_list(env, choicesTail)) {
if(!enif_get_list_cell(env, choicesTail, &choicesHead, &choicesTail)) Badarg("choices");
if(!enif_inspect_binary(env, choicesHead, &choices_bin)) Badarg("choices");
choices.Add(wxString(choices_bin.data, wxConvUTF8, choices_bin.size));
};
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
wxChoice * Result = new EwxChoice(parent,id,pos,size,choices,style,*validator);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxChoice"));
}
// wxChoice::Create
void wxChoice_Create(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxChoice *This;
This = (wxChoice *) memenv->getPtr(env, argv[0], "This");
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
int id;
if(!enif_get_int(env, argv[2], &id)) Badarg("id"); // wxWindowID
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, argv[3], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
wxPoint pos = wxPoint(posX,posY);
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[4], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
ERL_NIF_TERM choicesHead, choicesTail;
ErlNifBinary choices_bin;
wxArrayString choices;
choicesTail = argv[5];
while(!enif_is_empty_list(env, choicesTail)) {
if(!enif_get_list_cell(env, choicesTail, &choicesHead, &choicesTail)) Badarg("choices");
if(!enif_inspect_binary(env, choicesHead, &choices_bin)) Badarg("choices");
choices.Add(wxString(choices_bin.data, wxConvUTF8, choices_bin.size));
};
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[6];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Create(parent,id,pos,size,choices,style,*validator);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxChoice::Delete
void wxChoice_Delete(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxChoice *This;
This = (wxChoice *) memenv->getPtr(env, argv[0], "This");
unsigned int n;
if(!enif_get_uint(env, argv[1], &n)) Badarg("n");
if(!This) throw wxe_badarg("This");
This->Delete(n);
}
// wxChoice::GetColumns
void wxChoice_GetColumns(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxChoice *This;
This = (wxChoice *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetColumns();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxChoice::SetColumns
void wxChoice_SetColumns(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int n=1;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxChoice *This;
This = (wxChoice *) memenv->getPtr(env, argv[0], "This");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "n"))) {
if(!enif_get_int(env, tpl[1], &n)) Badarg("n"); // int
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
This->SetColumns(n);
}
// wxComboBox::wxComboBox
void wxComboBox_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxComboBox * Result = new EwxComboBox();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxComboBox"));
}
// wxComboBox::wxComboBox
void wxComboBox_new_3(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxString value= wxEmptyString;
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
wxArrayString choices;
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
int id;
if(!enif_get_int(env, argv[1], &id)) Badarg("id"); // wxWindowID
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "value"))) {
ErlNifBinary value_bin;
if(!enif_inspect_binary(env, tpl[1], &value_bin)) Badarg("value");
value = wxString(value_bin.data, wxConvUTF8, value_bin.size);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "choices"))) {
ERL_NIF_TERM choicesHead, choicesTail;
ErlNifBinary choices_bin;
choicesTail = tpl[1];
while(!enif_is_empty_list(env, choicesTail)) {
if(!enif_get_list_cell(env, choicesTail, &choicesHead, &choicesTail)) Badarg("choices");
if(!enif_inspect_binary(env, choicesHead, &choices_bin)) Badarg("choices");
choices.Add(wxString(choices_bin.data, wxConvUTF8, choices_bin.size));
};
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
wxComboBox * Result = new EwxComboBox(parent,id,value,pos,size,choices,style,*validator);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxComboBox"));
}
// wxComboBox::Create
void wxComboBox_Create(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
long style=0;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
int id;
if(!enif_get_int(env, argv[2], &id)) Badarg("id"); // wxWindowID
ErlNifBinary value_bin;
wxString value;
if(!enif_inspect_binary(env, argv[3], &value_bin)) Badarg("value");
value = wxString(value_bin.data, wxConvUTF8, value_bin.size);
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, argv[4], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
wxPoint pos = wxPoint(posX,posY);
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, argv[5], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
wxSize size = wxSize(sizeW,sizeH);
ERL_NIF_TERM choicesHead, choicesTail;
ErlNifBinary choices_bin;
wxArrayString choices;
choicesTail = argv[6];
while(!enif_is_empty_list(env, choicesTail)) {
if(!enif_get_list_cell(env, choicesTail, &choicesHead, &choicesTail)) Badarg("choices");
if(!enif_inspect_binary(env, choicesHead, &choices_bin)) Badarg("choices");
choices.Add(wxString(choices_bin.data, wxConvUTF8, choices_bin.size));
};
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[7];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Create(parent,id,value,pos,size,choices,style,*validator);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxComboBox::CanCopy
void wxComboBox_CanCopy(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->CanCopy();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxComboBox::CanCut
void wxComboBox_CanCut(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->CanCut();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxComboBox::CanPaste
void wxComboBox_CanPaste(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->CanPaste();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxComboBox::CanRedo
void wxComboBox_CanRedo(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->CanRedo();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxComboBox::CanUndo
void wxComboBox_CanUndo(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->CanUndo();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxComboBox::Copy
void wxComboBox_Copy(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->Copy();
}
// wxComboBox::Cut
void wxComboBox_Cut(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->Cut();
}
// wxComboBox::GetInsertionPoint
void wxComboBox_GetInsertionPoint(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
long Result = This->GetInsertionPoint();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxComboBox::GetLastPosition
void wxComboBox_GetLastPosition(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxTextPos Result = This->GetLastPosition();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxComboBox::GetValue
void wxComboBox_GetValue(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxString Result = This->GetValue();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxComboBox::Paste
void wxComboBox_Paste(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->Paste();
}
// wxComboBox::Redo
void wxComboBox_Redo(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->Redo();
}
// wxComboBox::Replace
void wxComboBox_Replace(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
long from;
if(!enif_get_long(env, argv[1], &from)) Badarg("from");
long to;
if(!enif_get_long(env, argv[2], &to)) Badarg("to");
ErlNifBinary value_bin;
wxString value;
if(!enif_inspect_binary(env, argv[3], &value_bin)) Badarg("value");
value = wxString(value_bin.data, wxConvUTF8, value_bin.size);
if(!This) throw wxe_badarg("This");
This->Replace(from,to,value);
}
// wxComboBox::Remove
void wxComboBox_Remove(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
long from;
if(!enif_get_long(env, argv[1], &from)) Badarg("from");
long to;
if(!enif_get_long(env, argv[2], &to)) Badarg("to");
if(!This) throw wxe_badarg("This");
This->Remove(from,to);
}
// wxComboBox::SetInsertionPoint
void wxComboBox_SetInsertionPoint(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
long pos;
if(!enif_get_long(env, argv[1], &pos)) Badarg("pos");
if(!This) throw wxe_badarg("This");
This->SetInsertionPoint(pos);
}
// wxComboBox::SetInsertionPointEnd
void wxComboBox_SetInsertionPointEnd(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->SetInsertionPointEnd();
}
// wxComboBox::SetSelection
void wxComboBox_SetSelection_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
long from;
if(!enif_get_long(env, argv[1], &from)) Badarg("from");
long to;
if(!enif_get_long(env, argv[2], &to)) Badarg("to");
if(!This) throw wxe_badarg("This");
This->SetSelection(from,to);
}
// wxComboBox::SetSelection
void wxComboBox_SetSelection_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
int n;
if(!enif_get_int(env, argv[1], &n)) Badarg("n"); // int
if(!This) throw wxe_badarg("This");
This->SetSelection(n);
}
// wxComboBox::SetValue
void wxComboBox_SetValue(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
ErlNifBinary text_bin;
wxString text;
if(!enif_inspect_binary(env, argv[1], &text_bin)) Badarg("text");
text = wxString(text_bin.data, wxConvUTF8, text_bin.size);
if(!This) throw wxe_badarg("This");
This->SetValue(text);
}
// wxComboBox::Undo
void wxComboBox_Undo(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxComboBox *This;
This = (wxComboBox *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->Undo();
}
// wxGauge::wxGauge
void wxGauge_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxGauge * Result = new EwxGauge();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGauge"));
}
// wxGauge::wxGauge
void wxGauge_new_4(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=wxGA_HORIZONTAL;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
int id;
if(!enif_get_int(env, argv[1], &id)) Badarg("id"); // wxWindowID
int range;
if(!enif_get_int(env, argv[2], &range)) Badarg("range"); // int
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
wxGauge * Result = new EwxGauge(parent,id,range,pos,size,style,*validator);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGauge"));
}
// wxGauge::Create
void wxGauge_Create(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=wxGA_HORIZONTAL;
const wxValidator * validator= &wxDefaultValidator;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGauge *This;
This = (wxGauge *) memenv->getPtr(env, argv[0], "This");
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
int id;
if(!enif_get_int(env, argv[2], &id)) Badarg("id"); // wxWindowID
int range;
if(!enif_get_int(env, argv[3], &range)) Badarg("range"); // int
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[4];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "validator"))) {
validator = (wxValidator *) memenv->getPtr(env, tpl[1], "validator");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Create(parent,id,range,pos,size,style,*validator);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxGauge::GetRange
void wxGauge_GetRange(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGauge *This;
This = (wxGauge *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetRange();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxGauge::GetValue
void wxGauge_GetValue(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGauge *This;
This = (wxGauge *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetValue();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxGauge::IsVertical
void wxGauge_IsVertical(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGauge *This;
This = (wxGauge *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsVertical();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxGauge::SetRange
void wxGauge_SetRange(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGauge *This;
This = (wxGauge *) memenv->getPtr(env, argv[0], "This");
int range;
if(!enif_get_int(env, argv[1], &range)) Badarg("range"); // int
if(!This) throw wxe_badarg("This");
This->SetRange(range);
}
// wxGauge::SetValue
void wxGauge_SetValue(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGauge *This;
This = (wxGauge *) memenv->getPtr(env, argv[0], "This");
int pos;
if(!enif_get_int(env, argv[1], &pos)) Badarg("pos"); // int
if(!This) throw wxe_badarg("This");
This->SetValue(pos);
}
// wxGauge::Pulse
void wxGauge_Pulse(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGauge *This;
This = (wxGauge *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->Pulse();
}
// wxGenericDirCtrl::wxGenericDirCtrl
void wxGenericDirCtrl_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxGenericDirCtrl * Result = new EwxGenericDirCtrl();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGenericDirCtrl"));
}
// wxGenericDirCtrl::wxGenericDirCtrl
void wxGenericDirCtrl_new_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxWindowID id=wxID_ANY;
wxString dir= wxDirDialogDefaultFolderStr;
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=wxDIRCTRL_3D_INTERNAL;
wxString filter= wxEmptyString;
int defaultFilter=0;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "id"))) {
if(!enif_get_int(env, tpl[1], &id)) Badarg("id"); // wxWindowID
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "dir"))) {
ErlNifBinary dir_bin;
if(!enif_inspect_binary(env, tpl[1], &dir_bin)) Badarg("dir");
dir = wxString(dir_bin.data, wxConvUTF8, dir_bin.size);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "filter"))) {
ErlNifBinary filter_bin;
if(!enif_inspect_binary(env, tpl[1], &filter_bin)) Badarg("filter");
filter = wxString(filter_bin.data, wxConvUTF8, filter_bin.size);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "defaultFilter"))) {
if(!enif_get_int(env, tpl[1], &defaultFilter)) Badarg("defaultFilter"); // int
} else Badarg("Options");
};
wxGenericDirCtrl * Result = new EwxGenericDirCtrl(parent,id,dir,pos,size,style,filter,defaultFilter);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxGenericDirCtrl"));
}
// wxGenericDirCtrl::Create
void wxGenericDirCtrl_Create(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxWindowID id=wxID_ANY;
wxString dir= wxDirDialogDefaultFolderStr;
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=wxDIRCTRL_3D_INTERNAL;
wxString filter= wxEmptyString;
int defaultFilter=0;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "id"))) {
if(!enif_get_int(env, tpl[1], &id)) Badarg("id"); // wxWindowID
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "dir"))) {
ErlNifBinary dir_bin;
if(!enif_inspect_binary(env, tpl[1], &dir_bin)) Badarg("dir");
dir = wxString(dir_bin.data, wxConvUTF8, dir_bin.size);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "filter"))) {
ErlNifBinary filter_bin;
if(!enif_inspect_binary(env, tpl[1], &filter_bin)) Badarg("filter");
filter = wxString(filter_bin.data, wxConvUTF8, filter_bin.size);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "defaultFilter"))) {
if(!enif_get_int(env, tpl[1], &defaultFilter)) Badarg("defaultFilter"); // int
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Create(parent,id,dir,pos,size,style,filter,defaultFilter);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxGenericDirCtrl::Init
void wxGenericDirCtrl_Init(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->Init();
}
// wxGenericDirCtrl::CollapseTree
void wxGenericDirCtrl_CollapseTree(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->CollapseTree();
}
// wxGenericDirCtrl::ExpandPath
void wxGenericDirCtrl_ExpandPath(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
ErlNifBinary path_bin;
wxString path;
if(!enif_inspect_binary(env, argv[1], &path_bin)) Badarg("path");
path = wxString(path_bin.data, wxConvUTF8, path_bin.size);
if(!This) throw wxe_badarg("This");
bool Result = This->ExpandPath(path);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxGenericDirCtrl::GetDefaultPath
void wxGenericDirCtrl_GetDefaultPath(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxString Result = This->GetDefaultPath();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGenericDirCtrl::GetPath
void wxGenericDirCtrl_GetPath_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxString Result = This->GetPath();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGenericDirCtrl::GetPath
void wxGenericDirCtrl_GetPath_1(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
ErlNifUInt64 itemId_tmp;
if(!enif_get_uint64(env, argv[1], &itemId_tmp)) Badarg("itemId");
wxTreeItemId itemId = wxTreeItemId((void *) (wxUint64) itemId_tmp);
if(!This) throw wxe_badarg("This");
wxString Result = This->GetPath(itemId);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGenericDirCtrl::GetFilePath
void wxGenericDirCtrl_GetFilePath(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxString Result = This->GetFilePath();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGenericDirCtrl::GetFilter
void wxGenericDirCtrl_GetFilter(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxString Result = This->GetFilter();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make(Result));
}
// wxGenericDirCtrl::GetFilterIndex
void wxGenericDirCtrl_GetFilterIndex(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
int Result = This->GetFilterIndex();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
// wxGenericDirCtrl::GetRootId
void wxGenericDirCtrl_GetRootId(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxTreeItemId Result = This->GetRootId();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make((wxUIntPtr *) Result.m_pItem));
}
// wxGenericDirCtrl::GetTreeCtrl
void wxGenericDirCtrl_GetTreeCtrl(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
wxTreeCtrl * Result = (wxTreeCtrl*)This->GetTreeCtrl();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxTreeCtrl"));
}
// wxGenericDirCtrl::ReCreateTree
void wxGenericDirCtrl_ReCreateTree(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
This->ReCreateTree();
}
// wxGenericDirCtrl::SetDefaultPath
void wxGenericDirCtrl_SetDefaultPath(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
ErlNifBinary path_bin;
wxString path;
if(!enif_inspect_binary(env, argv[1], &path_bin)) Badarg("path");
path = wxString(path_bin.data, wxConvUTF8, path_bin.size);
if(!This) throw wxe_badarg("This");
This->SetDefaultPath(path);
}
// wxGenericDirCtrl::SetFilter
void wxGenericDirCtrl_SetFilter(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
ErlNifBinary filter_bin;
wxString filter;
if(!enif_inspect_binary(env, argv[1], &filter_bin)) Badarg("filter");
filter = wxString(filter_bin.data, wxConvUTF8, filter_bin.size);
if(!This) throw wxe_badarg("This");
This->SetFilter(filter);
}
// wxGenericDirCtrl::SetFilterIndex
void wxGenericDirCtrl_SetFilterIndex(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
int n;
if(!enif_get_int(env, argv[1], &n)) Badarg("n"); // int
if(!This) throw wxe_badarg("This");
This->SetFilterIndex(n);
}
// wxGenericDirCtrl::SetPath
void wxGenericDirCtrl_SetPath(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxGenericDirCtrl *This;
This = (wxGenericDirCtrl *) memenv->getPtr(env, argv[0], "This");
ErlNifBinary path_bin;
wxString path;
if(!enif_inspect_binary(env, argv[1], &path_bin)) Badarg("path");
path = wxString(path_bin.data, wxConvUTF8, path_bin.size);
if(!This) throw wxe_badarg("This");
This->SetPath(path);
}
// wxStaticBox::wxStaticBox
void wxStaticBox_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxStaticBox * Result = new EwxStaticBox();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxStaticBox"));
}
// wxStaticBox::wxStaticBox
void wxStaticBox_new_4(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=0;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
int id;
if(!enif_get_int(env, argv[1], &id)) Badarg("id"); // wxWindowID
ErlNifBinary label_bin;
wxString label;
if(!enif_inspect_binary(env, argv[2], &label_bin)) Badarg("label");
label = wxString(label_bin.data, wxConvUTF8, label_bin.size);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[3];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else Badarg("Options");
};
wxStaticBox * Result = new EwxStaticBox(parent,id,label,pos,size,style);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxStaticBox"));
}
// wxStaticBox::Create
void wxStaticBox_Create(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=0;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxStaticBox *This;
This = (wxStaticBox *) memenv->getPtr(env, argv[0], "This");
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
int id;
if(!enif_get_int(env, argv[2], &id)) Badarg("id"); // wxWindowID
ErlNifBinary label_bin;
wxString label;
if(!enif_inspect_binary(env, argv[3], &label_bin)) Badarg("label");
label = wxString(label_bin.data, wxConvUTF8, label_bin.size);
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[4];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Create(parent,id,label,pos,size,style);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxStaticLine::wxStaticLine
void wxStaticLine_new_0(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxStaticLine * Result = new EwxStaticLine();
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxStaticLine"));
}
// wxStaticLine::wxStaticLine
void wxStaticLine_new_2(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxWindowID id=wxID_ANY;
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=wxLI_HORIZONTAL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[0], "parent");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[1];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "id"))) {
if(!enif_get_int(env, tpl[1], &id)) Badarg("id"); // wxWindowID
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else Badarg("Options");
};
wxStaticLine * Result = new EwxStaticLine(parent,id,pos,size,style);
app->newPtr((void *) Result, 0, memenv);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_ref(app->getRef((void *)Result,memenv), "wxStaticLine"));
}
// wxStaticLine::Create
void wxStaticLine_Create(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
wxWindowID id=wxID_ANY;
wxPoint pos= wxDefaultPosition;
wxSize size= wxDefaultSize;
long style=wxLI_HORIZONTAL;
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxStaticLine *This;
This = (wxStaticLine *) memenv->getPtr(env, argv[0], "This");
wxWindow *parent;
parent = (wxWindow *) memenv->getPtr(env, argv[1], "parent");
ERL_NIF_TERM lstHead, lstTail;
lstTail = argv[2];
if(!enif_is_list(env, lstTail)) Badarg("Options");
const ERL_NIF_TERM *tpl;
int tpl_sz;
while(!enif_is_empty_list(env, lstTail)) {
if(!enif_get_list_cell(env, lstTail, &lstHead, &lstTail)) Badarg("Options");
if(!enif_get_tuple(env, lstHead, &tpl_sz, &tpl) || tpl_sz != 2) Badarg("Options");
if(enif_is_identical(tpl[0], enif_make_atom(env, "id"))) {
if(!enif_get_int(env, tpl[1], &id)) Badarg("id"); // wxWindowID
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "pos"))) {
const ERL_NIF_TERM *pos_t;
int pos_sz;
if(!enif_get_tuple(env, tpl[1], &pos_sz, &pos_t)) Badarg("pos");
int posX;
if(!enif_get_int(env, pos_t[0], &posX)) Badarg("pos");
int posY;
if(!enif_get_int(env, pos_t[1], &posY)) Badarg("pos");
pos = wxPoint(posX,posY);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "size"))) {
const ERL_NIF_TERM *size_t;
int size_sz;
if(!enif_get_tuple(env, tpl[1], &size_sz, &size_t)) Badarg("size");
int sizeW;
if(!enif_get_int(env, size_t[0], &sizeW)) Badarg("size");
int sizeH;
if(!enif_get_int(env, size_t[1], &sizeH)) Badarg("size");
size = wxSize(sizeW,sizeH);
} else if(enif_is_identical(tpl[0], enif_make_atom(env, "style"))) {
if(!enif_get_long(env, tpl[1], &style)) Badarg("style");
} else Badarg("Options");
};
if(!This) throw wxe_badarg("This");
bool Result = This->Create(parent,id,pos,size,style);
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxStaticLine::IsVertical
void wxStaticLine_IsVertical(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
ErlNifEnv *env = Ecmd.env;
ERL_NIF_TERM * argv = Ecmd.args;
wxStaticLine *This;
This = (wxStaticLine *) memenv->getPtr(env, argv[0], "This");
if(!This) throw wxe_badarg("This");
bool Result = This->IsVertical();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_bool(Result));
}
// wxStaticLine::GetDefaultSize
void wxStaticLine_GetDefaultSize(WxeApp *app, wxeMemEnv *memenv, wxeCommand& Ecmd)
{
int Result = wxStaticLine::GetDefaultSize();
wxeReturn rt = wxeReturn(memenv, Ecmd.caller, true);
rt.send( rt.make_int(Result));
}
| 35.523449 | 201 | 0.68874 | [
"vector"
] |
7c0a43d0ecb79a72c612b4514cf1f1aea82913ac | 1,211 | cc | C++ | LeetCode-210.cc | therainmak3r/dirty-laundry | 39e295e9390b62830bef53282cdcb63716efac45 | [
"MIT"
] | 20 | 2015-12-22T14:14:59.000Z | 2019-10-25T12:14:23.000Z | LeetCode-210.cc | therainmak3r/dirty-laundry | 39e295e9390b62830bef53282cdcb63716efac45 | [
"MIT"
] | null | null | null | LeetCode-210.cc | therainmak3r/dirty-laundry | 39e295e9390b62830bef53282cdcb63716efac45 | [
"MIT"
] | 2 | 2016-06-27T13:34:08.000Z | 2018-10-02T20:36:54.000Z | class Solution {
public:
void recur(vector<vector<int>> &adj, vector<int> &visited, vector<int> &cycle, queue<int> &nodes, int current, int &valid)
{
if (cycle[current] == 1)
valid = 0;
if (valid == 0)
return;
if (visited[current] == 1)
return;
cycle[current] = 1;
visited[current] = 1;
for (int i = 0; i < adj[current].size(); i++)
recur(adj, visited, cycle, nodes, adj[current][i], valid);
nodes.push(current);
cycle[current] = 0;
return;
}
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prereq)
{
vector<vector<int>> adj;
adj.resize(numCourses);
for (int i = 0; i < prereq.size(); i++)
adj[prereq[i].first].push_back(prereq[i].second);
vector<int> visited;
visited.resize(numCourses);
vector<int> cycle;
cycle.resize(numCourses);
queue<int> nodes;
int valid = 1;
for (int i = 0; i < numCourses; i++)
recur(adj, visited, cycle, nodes, i, valid);
vector<int> ans;
if (valid == 0)
return ans;
while (nodes.empty() != 1)
{
ans.push_back(nodes.front());
nodes.pop();
}
return ans;
}
}; | 27.522727 | 125 | 0.554088 | [
"vector"
] |
7c137049460cac28ee930b0c80ee8ec799cdf39a | 31,825 | cpp | C++ | mysql-dst/mysql-cluster/storage/ndb/src/kernel/vm/ndbd_malloc_impl.cpp | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 9 | 2020-12-17T01:59:13.000Z | 2022-03-30T16:25:08.000Z | mysql-dst/mysql-cluster/storage/ndb/src/kernel/vm/ndbd_malloc_impl.cpp | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-07-30T12:06:33.000Z | 2021-07-31T10:16:09.000Z | mysql-dst/mysql-cluster/storage/ndb/src/kernel/vm/ndbd_malloc_impl.cpp | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-08-01T13:47:07.000Z | 2021-08-01T13:47:07.000Z | /*
Copyright (c) 2006, 2017, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the License.
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "ndbd_malloc_impl.hpp"
#include <ndb_global.h>
#include <EventLogger.hpp>
#include <portlib/NdbMem.h>
#ifdef NDB_WIN
void *sbrk(int increment)
{
return (void*)-1;
}
#endif
extern EventLogger * g_eventLogger;
static int f_method_idx = 0;
#ifdef NDBD_MALLOC_METHOD_SBRK
static const char * f_method = "SMsm";
#else
static const char * f_method = "MSms";
#endif
#define MAX_CHUNKS 10
#ifdef VM_TRACE
#ifndef NDBD_RANDOM_START_PAGE
#define NDBD_RANDOM_START_PAGE
#endif
#endif
#ifdef NDBD_RANDOM_START_PAGE
static Uint32 g_random_start_page_id = 0;
#endif
/*
* For muti-threaded ndbd, these calls are used for locking around
* memory allocation operations.
*
* For single-threaded ndbd, they are no-ops (but still called, to avoid
* having to compile this file twice).
*/
extern void mt_mem_manager_init();
extern void mt_mem_manager_lock();
extern void mt_mem_manager_unlock();
#include <NdbOut.hpp>
extern void ndbd_alloc_touch_mem(void * p, size_t sz, volatile Uint32 * watchCounter);
static
bool
do_malloc(Uint32 pages,
InitChunk* chunk,
Uint32 *watchCounter,
void * baseaddress)
{
pages += 1;
void * ptr = 0;
Uint32 sz = pages;
retry:
if (watchCounter)
*watchCounter = 9;
char method = f_method[f_method_idx];
switch(method){
case 0:
return false;
case 'S':
case 's':
{
ptr = 0;
while (ptr == 0)
{
if (watchCounter)
*watchCounter = 9;
ptr = sbrk(sizeof(Alloc_page) * sz);
if (ptr == (void*)-1)
{
if (method == 'S')
{
f_method_idx++;
goto retry;
}
ptr = 0;
sz = 1 + (9 * sz) / 10;
if (pages >= 32 && sz < 32)
{
sz = pages;
f_method_idx++;
goto retry;
}
}
else if (UintPtr(ptr) < UintPtr(baseaddress))
{
/**
* Unusable memory :(
*/
ndbout_c("sbrk(%lluMb) => %p which is less than baseaddress!!",
Uint64((sizeof(Alloc_page) * sz) >> 20), ptr);
f_method_idx++;
goto retry;
}
}
break;
}
case 'M':
case 'm':
{
ptr = 0;
while (ptr == 0)
{
if (watchCounter)
*watchCounter = 9;
ptr = malloc(sizeof(Alloc_page) * sz);
if (UintPtr(ptr) < UintPtr(baseaddress))
{
ndbout_c("malloc(%lluMb) => %p which is less than baseaddress!!",
Uint64((sizeof(Alloc_page) * sz) >> 20), ptr);
free(ptr);
ptr = 0;
}
if (ptr == 0)
{
if (method == 'M')
{
f_method_idx++;
goto retry;
}
sz = 1 + (9 * sz) / 10;
if (pages >= 32 && sz < 32)
{
f_method_idx++;
goto retry;
}
}
}
break;
}
default:
return false;
}
chunk->m_cnt = sz;
chunk->m_ptr = (Alloc_page*)ptr;
const UintPtr align = sizeof(Alloc_page) - 1;
if (UintPtr(ptr) & align)
{
chunk->m_cnt--;
chunk->m_ptr = (Alloc_page*)((UintPtr(ptr) + align) & ~align);
}
#ifdef UNIT_TEST
ndbout_c("do_malloc(%d) -> %p %d", pages, ptr, chunk->m_cnt);
if (1)
{
Uint32 sum = 0;
Alloc_page* page = chunk->m_ptr;
for (Uint32 i = 0; i<chunk->m_cnt; i++, page++)
{
page->m_data[0*1024] = 0;
page->m_data[1*1024] = 0;
page->m_data[2*1024] = 0;
page->m_data[3*1024] = 0;
page->m_data[4*1024] = 0;
page->m_data[5*1024] = 0;
page->m_data[6*1024] = 0;
page->m_data[7*1024] = 0;
}
}
#endif
return true;
}
/**
* Resource_limits
*/
Resource_limits::Resource_limits()
{
m_allocated = 0;
m_free_reserved = 0;
m_in_use = 0;
m_spare = 0;
m_max_page = 0;
memset(m_limit, 0, sizeof(m_limit));
}
#ifndef VM_TRACE
inline
#endif
void
Resource_limits::check() const
{
#ifdef VM_TRACE
const Resource_limit* rl = m_limit;
Uint32 curr = 0;
Uint32 spare = 0;
Uint32 res_alloc = 0;
Uint32 shared_alloc = 0;
Uint32 sumres = 0;
for (Uint32 i = 0; i < MM_RG_COUNT; i++)
{
curr += rl[i].m_curr;
spare += rl[i].m_spare;
sumres += rl[i].m_min;
// assert(rl[i].m_max == 0 || rl[i].m_curr <= rl[i].m_max);
if (rl[i].m_curr + rl[i].m_spare > rl[i].m_min)
{
shared_alloc += rl[i].m_curr + rl[i].m_spare - rl[i].m_min;
res_alloc += rl[i].m_min;
}
else
{
res_alloc += rl[i].m_curr + rl[i].m_spare;
}
}
if(!((curr == get_in_use()) &&
(spare == get_spare()) &&
(res_alloc + shared_alloc == curr + spare) &&
(res_alloc <= sumres) &&
(sumres == res_alloc + get_free_reserved()) &&
(get_in_use() + get_spare() <= get_allocated())))
{
dump();
}
assert(curr == get_in_use());
assert(spare == get_spare());
assert(res_alloc + shared_alloc == curr + spare);
assert(res_alloc <= sumres);
assert(sumres == res_alloc + get_free_reserved());
assert(get_in_use() + get_spare() <= get_allocated());
#endif
}
void
Resource_limits::dump() const
{
printf("ri: global "
"max_page: %u free_reserved: %u in_use: %u allocated: %u spare: %u\n",
m_max_page,
m_free_reserved,
m_in_use,
m_allocated,
m_spare);
for (Uint32 i = 0; i < MM_RG_COUNT; i++)
{
printf("ri: %u id: %u min: %u curr: %u max: %u spare: %u spare_pct: %u\n",
i,
m_limit[i].m_resource_id,
m_limit[i].m_min,
m_limit[i].m_curr,
m_limit[i].m_max,
m_limit[i].m_spare,
m_limit[i].m_spare_pct);
}
}
/**
*
* resource N has following semantics:
*
* m_min = reserved
* m_curr = currently used
* m_max = max alloc, 0 = no limit
*
*/
void
Resource_limits::init_resource_limit(Uint32 id, Uint32 min, Uint32 max)
{
assert(id > 0);
assert(id <= MM_RG_COUNT);
m_limit[id - 1].m_resource_id = id;
m_limit[id - 1].m_curr = 0;
m_limit[id - 1].m_max = max;
m_limit[id - 1].m_min = min;
Uint32 reserve = min;
Uint32 current_reserved = get_free_reserved();
set_free_reserved(current_reserved + reserve);
}
void
Resource_limits::init_resource_spare(Uint32 id, Uint32 pct)
{
require(m_limit[id - 1].m_spare_pct == 0);
m_limit[id - 1].m_spare_pct = pct;
(void) alloc_resource_spare(id, 0);
}
/**
* Ndbd_mem_manager
*/
Uint32
Ndbd_mem_manager::ndb_log2(Uint32 input)
{
if (input > 65535)
return 16;
input = input | (input >> 8);
input = input | (input >> 4);
input = input | (input >> 2);
input = input | (input >> 1);
Uint32 output = (input & 0x5555) + ((input >> 1) & 0x5555);
output = (output & 0x3333) + ((output >> 2) & 0x3333);
output = output + (output >> 4);
output = (output & 0xf) + ((output >> 8) & 0xf);
return output;
}
Ndbd_mem_manager::Ndbd_mem_manager()
{
m_base_page = 0;
memset(m_buddy_lists, 0, sizeof(m_buddy_lists));
if (sizeof(Free_page_data) != (4 * (1 << FPD_2LOG)))
{
g_eventLogger->error("Invalid build, ndbd_malloc_impl.cpp:%d", __LINE__);
abort();
}
mt_mem_manager_init();
}
void*
Ndbd_mem_manager::get_memroot() const
{
#ifdef NDBD_RANDOM_START_PAGE
return (void*)(m_base_page - g_random_start_page_id);
#else
return (void*)m_base_page;
#endif
}
/**
*
* resource N has following semantics:
*
* m_min = reserved
* m_curr = currently used including spare pages
* m_max = max alloc, 0 = no limit
* m_spare = pages reserved for restart or special use
*
*/
void
Ndbd_mem_manager::set_resource_limit(const Resource_limit& rl)
{
require(rl.m_resource_id > 0);
mt_mem_manager_lock();
m_resource_limits.init_resource_limit(rl.m_resource_id, rl.m_min, rl.m_max);
mt_mem_manager_unlock();
}
bool
Ndbd_mem_manager::get_resource_limit(Uint32 id, Resource_limit& rl) const
{
/**
* DUMP DumpPageMemory(1000) is agnostic about what resource groups exists.
* Allowing use of any id.
*/
if (1 <= id && id <= MM_RG_COUNT)
{
mt_mem_manager_lock();
m_resource_limits.get_resource_limit(id, rl);
mt_mem_manager_unlock();
return true;
}
return false;
}
bool
Ndbd_mem_manager::get_resource_limit_nolock(Uint32 id, Resource_limit& rl) const
{
assert(id > 0);
if (id <= MM_RG_COUNT)
{
m_resource_limits.get_resource_limit(id, rl);
return true;
}
return false;
}
int
cmp_chunk(const void * chunk_vptr_1, const void * chunk_vptr_2)
{
InitChunk * ptr1 = (InitChunk*)chunk_vptr_1;
InitChunk * ptr2 = (InitChunk*)chunk_vptr_2;
if (ptr1->m_ptr < ptr2->m_ptr)
return -1;
if (ptr1->m_ptr > ptr2->m_ptr)
return 1;
assert(false);
return 0;
}
bool
Ndbd_mem_manager::init(Uint32 *watchCounter, Uint32 max_pages , bool alloc_less_memory)
{
assert(m_base_page == 0);
assert(max_pages > 0);
assert(m_resource_limits.get_allocated() == 0);
if (watchCounter)
*watchCounter = 9;
Uint32 pages = max_pages;
Uint32 max_page = 0;
const Uint64 pg = Uint64(sizeof(Alloc_page));
g_eventLogger->info("Ndbd_mem_manager::init(%d) min: %lluMb initial: %lluMb",
alloc_less_memory,
(pg*m_resource_limits.get_free_reserved())>>20,
(pg*pages) >> 20);
if (pages == 0)
{
return false;
}
#if SIZEOF_CHARP == 4
Uint64 sum = (pg*pages);
if (sum >= (Uint64(1) << 32))
{
g_eventLogger->error("Trying to allocate more that 4Gb with 32-bit binary!!");
return false;
}
#endif
#ifdef NDBD_RANDOM_START_PAGE
/**
* In order to find bad-users of page-id's
* we add a random offset to the page-id's returned
* however, due to ZONE_19 that offset can't be that big
* (since we at get_page don't know if it's a HI/LO page)
*/
Uint32 max_rand_start = ZONE_19_BOUND - 1;
if (max_rand_start > pages)
{
max_rand_start -= pages;
if (max_rand_start > 0x10000)
g_random_start_page_id = 0x10000 + (rand() % (max_rand_start - 0x10000));
else if (max_rand_start)
g_random_start_page_id = rand() % max_rand_start;
assert(Uint64(pages) + Uint64(g_random_start_page_id) <= 0xFFFFFFFF);
ndbout_c("using g_random_start_page_id: %u (%.8x)",
g_random_start_page_id, g_random_start_page_id);
}
#endif
/**
* Do malloc
*/
Uint32 allocated = 0;
while (m_unmapped_chunks.size() < MAX_CHUNKS && allocated < pages)
{
InitChunk chunk;
memset(&chunk, 0, sizeof(chunk));
if (do_malloc(pages - allocated, &chunk, watchCounter, m_base_page))
{
if (watchCounter)
*watchCounter = 9;
m_unmapped_chunks.push_back(chunk);
allocated += chunk.m_cnt;
}
else
{
break;
}
}
if (allocated < m_resource_limits.get_free_reserved())
{
g_eventLogger->
error("Unable to alloc min memory from OS: min: %lldMb "
" allocated: %lldMb",
(Uint64)(sizeof(Alloc_page)*m_resource_limits.get_free_reserved()) >> 20,
(Uint64)(sizeof(Alloc_page)*allocated) >> 20);
return false;
}
else if (allocated < pages)
{
g_eventLogger->
warning("Unable to alloc requested memory from OS: min: %lldMb"
" requested: %lldMb allocated: %lldMb",
(Uint64)(sizeof(Alloc_page)*m_resource_limits.get_free_reserved())>>20,
(Uint64)(sizeof(Alloc_page)*max_pages)>>20,
(Uint64)(sizeof(Alloc_page)*allocated)>>20);
if (!alloc_less_memory)
return false;
}
/**
* Sort chunks...
*/
qsort(m_unmapped_chunks.getBase(), m_unmapped_chunks.size(),
sizeof(InitChunk), cmp_chunk);
m_base_page = m_unmapped_chunks[0].m_ptr;
for (Uint32 i = 0; i<m_unmapped_chunks.size(); i++)
{
UintPtr start = UintPtr(m_unmapped_chunks[i].m_ptr) - UintPtr(m_base_page);
start >>= (2 + BMW_2LOG);
assert((Uint64(start) >> 32) == 0);
m_unmapped_chunks[i].m_start = Uint32(start);
Uint64 last64 = start + m_unmapped_chunks[i].m_cnt;
assert((last64 >> 32) == 0);
Uint32 last = Uint32(last64);
if (last > max_page)
max_page = last;
}
m_resource_limits.set_max_page(max_page);
m_resource_limits.set_allocated(0);
return true;
}
void
Ndbd_mem_manager::map(Uint32 * watchCounter, bool memlock, Uint32 resources[])
{
Uint32 limit = ~(Uint32)0;
Uint32 sofar = 0;
if (resources != 0)
{
limit = 0;
for (Uint32 i = 0; resources[i] ; i++)
{
limit += m_resource_limits.get_resource_reserved(resources[i]);
}
}
while (m_unmapped_chunks.size() && sofar < limit)
{
Uint32 remain = limit - sofar;
unsigned idx = m_unmapped_chunks.size() - 1;
InitChunk * chunk = &m_unmapped_chunks[idx];
if (watchCounter)
*watchCounter = 9;
if (chunk->m_cnt > remain)
{
/**
* Split chunk
*/
Uint32 extra = chunk->m_cnt - remain;
chunk->m_cnt = remain;
InitChunk newchunk;
newchunk.m_start = chunk->m_start + remain;
newchunk.m_ptr = m_base_page + newchunk.m_start;
newchunk.m_cnt = extra;
m_unmapped_chunks.push_back(newchunk);
// pointer could have changed after m_unmapped_chunks.push_back
chunk = &m_unmapped_chunks[idx];
}
g_eventLogger->info("Touch Memory Starting, %u pages, page size = %d",
chunk->m_cnt,
(int)sizeof(Alloc_page));
ndbd_alloc_touch_mem(chunk->m_ptr,
chunk->m_cnt * sizeof(Alloc_page),
watchCounter);
g_eventLogger->info("Touch Memory Completed");
if (memlock)
{
/**
* memlock pages that I added...
*/
if (watchCounter)
*watchCounter = 9;
/**
* Don't memlock everything in one go...
* cause then process won't be killable
*/
const Alloc_page * start = chunk->m_ptr;
Uint32 cnt = chunk->m_cnt;
g_eventLogger->info("Lock Memory Starting, %u pages, page size = %d",
chunk->m_cnt,
(int)sizeof(Alloc_page));
while (cnt > 32768) // 1G
{
if (watchCounter)
*watchCounter = 9;
NdbMem_MemLock(start, 32768 * sizeof(Alloc_page));
start += 32768;
cnt -= 32768;
}
if (watchCounter)
*watchCounter = 9;
NdbMem_MemLock(start, cnt * sizeof(Alloc_page));
g_eventLogger->info("Lock memory Completed");
}
grow(chunk->m_start, chunk->m_cnt);
sofar += chunk->m_cnt;
m_unmapped_chunks.erase(idx);
}
mt_mem_manager_lock();
m_resource_limits.check();
mt_mem_manager_unlock();
if (resources == 0 && memlock)
{
NdbMem_MemLockAll(1);
}
}
void
Ndbd_mem_manager::init_resource_spare(Uint32 id, Uint32 pct)
{
mt_mem_manager_lock();
m_resource_limits.init_resource_spare(id, pct);
mt_mem_manager_unlock();
}
#include <NdbOut.hpp>
void
Ndbd_mem_manager::grow(Uint32 start, Uint32 cnt)
{
assert(cnt);
Uint32 start_bmp = start >> BPP_2LOG;
Uint32 last_bmp = (start + cnt - 1) >> BPP_2LOG;
#if SIZEOF_CHARP == 4
assert(start_bmp == 0 && last_bmp == 0);
#endif
if (start_bmp != last_bmp)
{
Uint32 tmp = ((start_bmp + 1) << BPP_2LOG) - start;
grow(start, tmp);
grow((start_bmp + 1) << BPP_2LOG, cnt - tmp);
return;
}
if ((start + cnt) == ((start_bmp + 1) << BPP_2LOG))
{
cnt--; // last page is always marked as empty
}
for (Uint32 i = 0; i<m_used_bitmap_pages.size(); i++)
if (m_used_bitmap_pages[i] == start_bmp)
goto found;
if (start != (start_bmp << BPP_2LOG))
{
ndbout_c("ndbd_malloc_impl.cpp:%d:grow(%d, %d) %d!=%d not using %uMb"
" - Unable to use due to bitmap pages missaligned!!",
__LINE__, start, cnt, start, (start_bmp << BPP_2LOG),
(cnt >> (20 - 15)));
g_eventLogger->error("ndbd_malloc_impl.cpp:%d:grow(%d, %d) not using %uMb"
" - Unable to use due to bitmap pages missaligned!!",
__LINE__, start, cnt,
(cnt >> (20 - 15)));
dump();
return;
}
#ifdef UNIT_TEST
ndbout_c("creating bitmap page %d", start_bmp);
#endif
{
Alloc_page* bmp = m_base_page + start;
memset(bmp, 0, sizeof(Alloc_page));
cnt--;
start++;
}
m_used_bitmap_pages.push_back(start_bmp);
found:
if (cnt)
{
mt_mem_manager_lock();
const Uint32 allocated = m_resource_limits.get_allocated();
m_resource_limits.set_allocated(allocated + cnt);
const Uint64 mbytes = ((Uint64(cnt)*32) + 1023) / 1024;
/**
* grow first split large page ranges to ranges completely within
* a BPP regions.
* Boundary between lo and high zone coincide with a BPP region
* boundary.
*/
NDB_STATIC_ASSERT((ZONE_19_BOUND & ((1 << BPP_2LOG) - 1)) == 0);
if (start < ZONE_19_BOUND)
{
require(start + cnt < ZONE_19_BOUND);
g_eventLogger->info("Adding %uMb to ZONE_19 (%u, %u)",
(Uint32)mbytes,
start,
cnt);
}
else if (start < ZONE_27_BOUND)
{
require(start + cnt < ZONE_27_BOUND);
g_eventLogger->info("Adding %uMb to ZONE_27 (%u, %u)",
(Uint32)mbytes,
start,
cnt);
}
else if (start < ZONE_30_BOUND)
{
require(start + cnt < ZONE_30_BOUND);
g_eventLogger->info("Adding %uMb to ZONE_30 (%u, %u)",
(Uint32)mbytes,
start,
cnt);
}
else
{
g_eventLogger->info("Adding %uMb to ZONE_32 (%u, %u)",
(Uint32)mbytes,
start,
cnt);
}
release(start, cnt);
mt_mem_manager_unlock();
}
}
void
Ndbd_mem_manager::release(Uint32 start, Uint32 cnt)
{
assert(start);
set(start, start+cnt-1);
Uint32 zone = get_page_zone(start);
release_impl(zone, start, cnt);
}
void
Ndbd_mem_manager::release_impl(Uint32 zone, Uint32 start, Uint32 cnt)
{
assert(start);
Uint32 test = check(start-1, start+cnt);
if (test & 1)
{
Free_page_data *fd = get_free_page_data(m_base_page + start - 1,
start - 1);
Uint32 sz = fd->m_size;
Uint32 left = start - sz;
remove_free_list(zone, left, fd->m_list);
cnt += sz;
start = left;
}
Uint32 right = start + cnt;
if (test & 2)
{
Free_page_data *fd = get_free_page_data(m_base_page+right, right);
Uint32 sz = fd->m_size;
remove_free_list(zone, right, fd->m_list);
cnt += sz;
}
insert_free_list(zone, start, cnt);
}
void
Ndbd_mem_manager::alloc(AllocZone zone,
Uint32* ret,
Uint32 *pages,
Uint32 min)
{
const Uint32 save = * pages;
for (Uint32 z = zone; ; z--)
{
alloc_impl(z, ret, pages, min);
if (*pages)
return;
if (z == 0)
return;
* pages = save;
}
}
void
Ndbd_mem_manager::alloc_impl(Uint32 zone,
Uint32* ret,
Uint32 *pages,
Uint32 min)
{
Int32 i;
Uint32 start;
Uint32 cnt = * pages;
Uint32 list = ndb_log2(cnt - 1);
assert(cnt);
assert(list <= 16);
for (i = list; i < 16; i++)
{
if ((start = m_buddy_lists[zone][i]))
{
/* ---------------------------------------------------------------- */
/* PROPER AMOUNT OF PAGES WERE FOUND. NOW SPLIT THE FOUND */
/* AREA AND RETURN THE PART NOT NEEDED. */
/* ---------------------------------------------------------------- */
Uint32 sz = remove_free_list(zone, start, i);
Uint32 extra = sz - cnt;
assert(sz >= cnt);
if (extra)
{
insert_free_list(zone, start + cnt, extra);
clear_and_set(start, start+cnt-1);
}
else
{
clear(start, start+cnt-1);
}
* ret = start;
assert(m_resource_limits.get_in_use() + cnt <= m_resource_limits.get_allocated());
return;
}
}
/**
* Could not find in quaranteed list...
* search in other lists...
*/
Int32 min_list = ndb_log2(min - 1);
assert((Int32)list >= min_list);
for (i = list - 1; i >= min_list; i--)
{
if ((start = m_buddy_lists[zone][i]))
{
Uint32 sz = remove_free_list(zone, start, i);
Uint32 extra = sz - cnt;
if (sz > cnt)
{
insert_free_list(zone, start + cnt, extra);
sz -= extra;
clear_and_set(start, start+sz-1);
}
else
{
clear(start, start+sz-1);
}
* ret = start;
* pages = sz;
assert(m_resource_limits.get_in_use() + sz <= m_resource_limits.get_allocated());
return;
}
}
* pages = 0;
}
void
Ndbd_mem_manager::insert_free_list(Uint32 zone, Uint32 start, Uint32 size)
{
Uint32 list = ndb_log2(size) - 1;
Uint32 last = start + size - 1;
Uint32 head = m_buddy_lists[zone][list];
Free_page_data* fd_first = get_free_page_data(m_base_page+start,
start);
fd_first->m_list = list;
fd_first->m_next = head;
fd_first->m_prev = 0;
fd_first->m_size = size;
Free_page_data* fd_last = get_free_page_data(m_base_page+last, last);
fd_last->m_list = list;
fd_last->m_next = head;
fd_last->m_prev = 0;
fd_last->m_size = size;
if (head)
{
Free_page_data* fd = get_free_page_data(m_base_page+head, head);
assert(fd->m_prev == 0);
assert(fd->m_list == list);
fd->m_prev = start;
}
m_buddy_lists[zone][list] = start;
}
Uint32
Ndbd_mem_manager::remove_free_list(Uint32 zone, Uint32 start, Uint32 list)
{
Free_page_data* fd = get_free_page_data(m_base_page+start, start);
Uint32 size = fd->m_size;
Uint32 next = fd->m_next;
Uint32 prev = fd->m_prev;
assert(fd->m_list == list);
if (prev)
{
assert(m_buddy_lists[zone][list] != start);
fd = get_free_page_data(m_base_page+prev, prev);
assert(fd->m_next == start);
assert(fd->m_list == list);
fd->m_next = next;
}
else
{
assert(m_buddy_lists[zone][list] == start);
m_buddy_lists[zone][list] = next;
}
if (next)
{
fd = get_free_page_data(m_base_page+next, next);
assert(fd->m_list == list);
assert(fd->m_prev == start);
fd->m_prev = prev;
}
return size;
}
void
Ndbd_mem_manager::dump() const
{
mt_mem_manager_lock();
for (Uint32 zone = 0; zone < ZONE_COUNT; zone ++)
{
for (Uint32 i = 0; i<16; i++)
{
printf(" list: %d - ", i);
Uint32 head = m_buddy_lists[zone][i];
while(head)
{
Free_page_data* fd = get_free_page_data(m_base_page+head, head);
printf("[ i: %d prev %d next %d list %d size %d ] ",
head, fd->m_prev, fd->m_next, fd->m_list, fd->m_size);
head = fd->m_next;
}
printf("EOL\n");
}
m_resource_limits.dump();
}
mt_mem_manager_unlock();
}
void
Ndbd_mem_manager::lock()
{
mt_mem_manager_lock();
}
void
Ndbd_mem_manager::unlock()
{
mt_mem_manager_unlock();
}
void*
Ndbd_mem_manager::alloc_page(Uint32 type,
Uint32* i,
AllocZone zone,
bool locked)
{
Uint32 idx = type & RG_MASK;
assert(idx && idx <= MM_RG_COUNT);
if (!locked)
mt_mem_manager_lock();
Uint32 cnt = 1;
const Uint32 min = 1;
const Uint32 free_res = m_resource_limits.get_resource_free_reserved(idx);
if (free_res < cnt)
{
const Uint32 free_shr = m_resource_limits.get_free_shared();
const Uint32 free = m_resource_limits.get_resource_free(idx);
if (free < min || (free_shr + free_res < min))
{
if (!locked)
mt_mem_manager_unlock();
return NULL;
}
}
alloc(zone, i, &cnt, min);
if (likely(cnt))
{
const Uint32 spare_taken = m_resource_limits.post_alloc_resource_pages(idx, cnt);
if (spare_taken > 0)
{
require(spare_taken == cnt);
release(*i, spare_taken);
m_resource_limits.check();
if (!locked)
mt_mem_manager_unlock();
*i = RNIL;
return NULL;
}
m_resource_limits.check();
if (!locked)
mt_mem_manager_unlock();
#ifdef NDBD_RANDOM_START_PAGE
*i += g_random_start_page_id;
return m_base_page + *i - g_random_start_page_id;
#else
return m_base_page + *i;
#endif
}
if (!locked)
mt_mem_manager_unlock();
return 0;
}
void*
Ndbd_mem_manager::alloc_spare_page(Uint32 type, Uint32* i, AllocZone zone)
{
Uint32 idx = type & RG_MASK;
assert(idx && idx <= MM_RG_COUNT);
mt_mem_manager_lock();
Uint32 cnt = 1;
const Uint32 min = 1;
if (m_resource_limits.get_resource_spare(idx) >= min)
{
alloc(zone, i, &cnt, min);
if (likely(cnt))
{
assert(cnt == min);
m_resource_limits.post_alloc_resource_spare(idx, cnt);
m_resource_limits.check();
mt_mem_manager_unlock();
#ifdef NDBD_RANDOM_START_PAGE
*i += g_random_start_page_id;
return m_base_page + *i - g_random_start_page_id;
#else
return m_base_page + *i;
#endif
}
}
mt_mem_manager_unlock();
return 0;
}
void
Ndbd_mem_manager::release_page(Uint32 type, Uint32 i, bool locked)
{
Uint32 idx = type & RG_MASK;
assert(idx && idx <= MM_RG_COUNT);
if (!locked)
mt_mem_manager_lock();
#ifdef NDBD_RANDOM_START_PAGE
i -= g_random_start_page_id;
#endif
release(i, 1);
m_resource_limits.post_release_resource_pages(idx, 1);
m_resource_limits.check();
if (!locked)
mt_mem_manager_unlock();
}
void
Ndbd_mem_manager::alloc_pages(Uint32 type,
Uint32* i,
Uint32 *cnt,
Uint32 min,
AllocZone zone,
bool locked)
{
Uint32 idx = type & RG_MASK;
assert(idx && idx <= MM_RG_COUNT);
if (!locked)
mt_mem_manager_lock();
Uint32 req = *cnt;
const Uint32 free_res = m_resource_limits.get_resource_free_reserved(idx);
if (free_res < req)
{
const Uint32 free = m_resource_limits.get_resource_free(idx);
if (free < req)
{
req = free;
}
const Uint32 free_shr = m_resource_limits.get_free_shared();
if (free_shr + free_res < req)
{
req = free_shr + free_res;
}
if (req < min)
{
*cnt = 0;
if (!locked)
mt_mem_manager_unlock();
return;
}
}
// Hi order allocations can always use any zone
alloc(zone, i, &req, min);
const Uint32 spare_taken = m_resource_limits.post_alloc_resource_pages(idx, req);
if (spare_taken > 0)
{
req -= spare_taken;
release(*i + req, spare_taken);
}
if (0 < req && req < min)
{
release(*i, req);
m_resource_limits.post_release_resource_pages(idx, req);
req = 0;
}
* cnt = req;
m_resource_limits.check();
if (!locked)
mt_mem_manager_unlock();
#ifdef NDBD_RANDOM_START_PAGE
*i += g_random_start_page_id;
#endif
}
void
Ndbd_mem_manager::release_pages(Uint32 type, Uint32 i, Uint32 cnt, bool locked)
{
Uint32 idx = type & RG_MASK;
assert(idx && idx <= MM_RG_COUNT);
if (!locked)
mt_mem_manager_lock();
#ifdef NDBD_RANDOM_START_PAGE
i -= g_random_start_page_id;
#endif
release(i, cnt);
m_resource_limits.post_release_resource_pages(idx, cnt);
m_resource_limits.check();
if (!locked)
mt_mem_manager_unlock();
}
#ifdef UNIT_TEST
#include <Vector.hpp>
struct Chunk {
Uint32 pageId;
Uint32 pageCount;
};
struct Timer
{
Uint64 sum;
Uint32 cnt;
Timer() { sum = cnt = 0;}
struct timeval st;
void start() {
gettimeofday(&st, 0);
}
Uint64 calc_diff() {
struct timeval st2;
gettimeofday(&st2, 0);
Uint64 diff = st2.tv_sec;
diff -= st.tv_sec;
diff *= 1000000;
diff += st2.tv_usec;
diff -= st.tv_usec;
return diff;
}
void stop() {
add(calc_diff());
}
void add(Uint64 diff) { sum += diff; cnt++;}
void print(const char * title) const {
float ps = sum;
ps /= cnt;
printf("%s %fus/call %lld %d\n", title, ps, sum, cnt);
}
};
int
main(int argc, char** argv)
{
int sz = 1*32768;
int run_time = 30;
if (argc > 1)
sz = 32*atoi(argv[1]);
if (argc > 2)
run_time = atoi(argv[2]);
char buf[255];
Timer timer[4];
printf("Startar modul test av Page Manager %dMb %ds\n",
(sz >> 5), run_time);
g_eventLogger->createConsoleHandler();
g_eventLogger->setCategory("keso");
g_eventLogger->enable(Logger::LL_ON, Logger::LL_INFO);
g_eventLogger->enable(Logger::LL_ON, Logger::LL_CRITICAL);
g_eventLogger->enable(Logger::LL_ON, Logger::LL_ERROR);
g_eventLogger->enable(Logger::LL_ON, Logger::LL_WARNING);
#define DEBUG 0
Ndbd_mem_manager mem;
Resource_limit rl;
rl.m_min = 0;
rl.m_max = sz;
rl.m_curr = 0;
rl.m_spare = 0;
rl.m_resource_id = 0;
mem.set_resource_limit(rl);
rl.m_min = sz < 16384 ? sz : 16384;
rl.m_max = 0;
rl.m_resource_id = 1;
mem.set_resource_limit(rl);
mem.init(NULL);
mem.dump();
printf("pid: %d press enter to continue\n", getpid());
fgets(buf, sizeof(buf), stdin);
Vector<Chunk> chunks;
time_t stop = time(0) + run_time;
for(Uint32 i = 0; time(0) < stop; i++){
//mem.dump();
// Case
Uint32 c = (rand() % 100);
if (c < 50)
{
c = 0;
}
else if (c < 93)
{
c = 1;
}
else
{
c = 2;
}
Uint32 alloc = 1 + rand() % 3200;
if(chunks.size() == 0 && c == 0)
{
c = 1 + rand() % 2;
}
if(DEBUG)
printf("loop=%d ", i);
switch(c){
case 0:{ // Release
const int ch = rand() % chunks.size();
Chunk chunk = chunks[ch];
chunks.erase(ch);
timer[0].start();
mem.release(chunk.pageId, chunk.pageCount);
timer[0].stop();
if(DEBUG)
printf(" release %d %d\n", chunk.pageId, chunk.pageCount);
}
break;
case 2: { // Seize(n) - fail
alloc += sz;
// Fall through
}
case 1: { // Seize(n) (success)
Chunk chunk;
chunk.pageCount = alloc;
if (DEBUG)
{
printf(" alloc %d -> ", alloc); fflush(stdout);
}
timer[0].start();
mem.alloc(&chunk.pageId, &chunk.pageCount, 1);
Uint64 diff = timer[0].calc_diff();
if (DEBUG)
printf("%d %d", chunk.pageId, chunk.pageCount);
assert(chunk.pageCount <= alloc);
if(chunk.pageCount != 0){
chunks.push_back(chunk);
if(chunk.pageCount != alloc) {
timer[2].add(diff);
if (DEBUG)
printf(" - Tried to allocate %d - only allocated %d - free: %d",
alloc, chunk.pageCount, 0);
}
else
{
timer[1].add(diff);
}
} else {
timer[3].add(diff);
if (DEBUG)
printf(" Failed to alloc %d pages with %d pages free",
alloc, 0);
}
if (DEBUG)
printf("\n");
}
break;
}
}
if (!DEBUG)
while(chunks.size() > 0){
Chunk chunk = chunks.back();
mem.release(chunk.pageId, chunk.pageCount);
chunks.erase(chunks.size() - 1);
}
const char *title[] = {
"release ",
"alloc full",
"alloc part",
"alloc fail"
};
for(Uint32 i = 0; i<4; i++)
timer[i].print(title[i]);
mem.dump();
}
template class Vector<Chunk>;
#endif
#define JAM_FILE_ID 296
template class Vector<InitChunk>;
| 22.994942 | 88 | 0.595287 | [
"vector"
] |
7c193c511abcd1037a9f81ae4af5663181497e46 | 16,310 | cxx | C++ | Software/SlicerModules/AAA_GenerateAbaqusFile/AAA_GenerateAbaqusFile/AAA_GenerateAbaqusFile.cxx | ISML-UWA/BioPARR | 48dfaa9c94416ec6f67e29082e75c06f9471d9b7 | [
"BSD-3-Clause"
] | 1 | 2021-11-03T04:08:51.000Z | 2021-11-03T04:08:51.000Z | Software/SlicerModules/AAA_GenerateAbaqusFile/AAA_GenerateAbaqusFile/AAA_GenerateAbaqusFile.cxx | ISML-UWA/BioPARR | 48dfaa9c94416ec6f67e29082e75c06f9471d9b7 | [
"BSD-3-Clause"
] | 1 | 2021-11-03T07:07:15.000Z | 2021-11-03T07:07:15.000Z | Software/SlicerModules/AAA_GenerateAbaqusFile/AAA_GenerateAbaqusFile/AAA_GenerateAbaqusFile.cxx | ISML-UWA/BioPARR | 48dfaa9c94416ec6f67e29082e75c06f9471d9b7 | [
"BSD-3-Clause"
] | null | null | null | // VTK includes
#include <vtkDebugLeaks.h>
#include <vtkSmartPointer.h>
#include <vtkUnstructuredGridReader.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkGeometryFilter.h>
#include <vtkAppendFilter.h>
#include <vtkUnstructuredGrid.h>
#include <vtkPoints.h>
#include <vtkQuadraticTetra.h>
#include <vtkMath.h>
#include <vtkIdTypeArray.h>
#include <vtkPolyData.h>
#include <vtkKdTreePointLocator.h>
#include <vtkPointData.h>
#include <vtkCellData.h>
#include <vtkQuadraticTetra.h>
#include <vtkCellArray.h>
#include <vtkMergePoints.h>
#include <vtkCellDataToPointData.h>
#include "AAA_GenerateAbaqusFileCLP.h"
#include "AAA_defines.h"
#define LENGTH_PER_CAP_SIZE 200
int main( int argc, char * argv[] )
{
PARSE_ARGS;
vtkDebugLeaks::SetExitError(true);
// Check inputs
if (meshFile.size() == 0)
{
std::cerr << "ERROR: no input mesh specified!" << std::endl;
return EXIT_FAILURE;
}
if (inSurface.size() == 0)
{
std::cerr << "ERROR: no surface specified!" << std::endl;
return EXIT_FAILURE;
}
// Read input mesh
vtkSmartPointer<vtkUnstructuredGridReader> pdReader = vtkSmartPointer<vtkUnstructuredGridReader>::New();
pdReader->SetFileName(meshFile.c_str() );
pdReader->Update();
if( pdReader->GetErrorCode() != 0 )
{
std::cerr << "ERROR: Failed to read mesh from " << meshFile.c_str() << std::endl;
return EXIT_FAILURE;
}
// Read surface
vtkSmartPointer<vtkXMLPolyDataReader> pdReader1 = vtkSmartPointer<vtkXMLPolyDataReader>::New();
pdReader1->SetFileName(inSurface.c_str() );
pdReader1->Update();
if( pdReader1->GetErrorCode() != 0 )
{
std::cerr << "ERROR: Failed to read surface from " << inSurface.c_str() << std::endl;
return EXIT_FAILURE;
}
vtkPolyData *pSplitSurface = pdReader1->GetOutput();
// check which volume we are handling (ILT/Wall)
std::string partName;
bool boHandlingILT = false;
vtkIdType numCellsSurf = pSplitSurface->GetNumberOfCells();
pSplitSurface->GetCellData()->SetActiveScalars(SURF_ID_NAME);
for (vtkIdType i = 0; i < numCellsSurf; i++)
{
double *pSurfID = pSplitSurface->GetCellData()->GetScalars()->GetTuple(i);
if ((*pSurfID) == INT_ILT_SURF_ID)
{
boHandlingILT = true;
break;
}
}
if (boHandlingILT) partName="ILT";
else partName="Wall";
// Extract outside mesh surface
vtkSmartPointer<vtkGeometryFilter> pdExtractSurf = vtkSmartPointer<vtkGeometryFilter>::New();
pdExtractSurf->SetInputConnection(pdReader->GetOutputPort());
pdExtractSurf->Update();
// Merge surface with mesh
vtkSmartPointer<vtkAppendFilter> pdAppendFilter = vtkSmartPointer<vtkAppendFilter>::New();
pdAppendFilter->MergePointsOn();
pdAppendFilter->AddInputConnection(pdReader->GetOutputPort());
pdAppendFilter->AddInputConnection(pdExtractSurf->GetOutputPort());
pdAppendFilter->Update();
vtkUnstructuredGrid *mesh = pdAppendFilter->GetOutput();
vtkIdType numNodes = mesh->GetNumberOfPoints();
vtkPoints *pPoints = mesh->GetPoints();
vtkIdType totalNumNodes = numNodes;
// find number of tetras
vtkIdType numTetras = 0;
vtkIdType numTrias = 0;
vtkIdType numElements = mesh->GetNumberOfCells();
for (vtkIdType i = 0; i < numElements; i++)
{
if (mesh->GetCellType(i) == VTK_TETRA) numTetras++;
else if (mesh->GetCellType(i) == VTK_TRIANGLE) numTrias++;
}
if (numTetras+numTrias != numElements)
{
std::cout << "WARNING: Unexpected element type in the input file!" << std::endl;
}
// create 10 noded elements
vtkSmartPointer<vtkCellArray> cellsQuadratic = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkUnsignedCharArray> cellsIdsQuadratic = vtkSmartPointer<vtkUnsignedCharArray>::New();
vtkSmartPointer<vtkIdTypeArray> cellLocations = vtkSmartPointer<vtkIdTypeArray>::New();
cellsIdsQuadratic->SetNumberOfValues(numElements);
cellLocations->SetNumberOfValues(numElements);
cellsQuadratic->Allocate(numElements*11);
vtkIdType location = 0;
if (boQuadratic)
{
// merge middle nodes when inserting
vtkSmartPointer<vtkMergePoints> mergePoints = vtkSmartPointer<vtkMergePoints>::New();
mergePoints->SetDataSet(mesh);
//mergePoints->SetDivisions(100,100,100);
mergePoints->AutomaticOn();
mergePoints->SetNumberOfPointsPerBucket(10);
mergePoints->InitPointInsertion(mesh->GetPoints(), mesh->GetBounds());
mergePoints->SetTolerance(0.0000000001);
// insert the existing points
vtkIdType n = mesh->GetNumberOfPoints();
for (vtkIdType i = 0; i < n; i++)
{
double p[3];
pPoints->GetPoint(i, p);
mergePoints->InsertNextPoint(p);
}
// create middle points
vtkIdType nodeIdx;
for (vtkIdType i = 0; i < numElements; i++)
{
if (mesh->GetCellType(i) == VTK_TETRA)
{
// change cell types
vtkIdType pQTetraIds[10];
// create intermediate points
vtkIdType nodeId = mesh->GetCell(i)->GetPointId(0);
pQTetraIds[0] = nodeId;
double n1[3];
pPoints->GetPoint(nodeId, n1);
nodeId = mesh->GetCell(i)->GetPointId(1);
pQTetraIds[1] = nodeId;
double n2[3];
pPoints->GetPoint(nodeId, n2);
nodeId = mesh->GetCell(i)->GetPointId(2);
pQTetraIds[2] = nodeId;
double n3[3];
pPoints->GetPoint(nodeId, n3);
nodeId = mesh->GetCell(i)->GetPointId(3);
pQTetraIds[3] = nodeId;
double n4[3];
pPoints->GetPoint(nodeId, n4);
double n[3];
// generate center nodes
// 5: 1-2
vtkMath::Add(n1, n2, n);
vtkMath::MultiplyScalar(n, 0.5);
mergePoints->InsertUniquePoint(n, nodeIdx);
pQTetraIds[4] = nodeIdx;
// 6: 2-3
vtkMath::Add(n3, n2, n);
vtkMath::MultiplyScalar(n, 0.5);
mergePoints->InsertUniquePoint(n, nodeIdx);
pQTetraIds[5] = nodeIdx;
// 7: 1-3
vtkMath::Add(n3, n1, n);
vtkMath::MultiplyScalar(n, 0.5);
mergePoints->InsertUniquePoint(n, nodeIdx);
pQTetraIds[6] = nodeIdx;
// 8: 1-4
vtkMath::Add(n4, n1, n);
vtkMath::MultiplyScalar(n, 0.5);
mergePoints->InsertUniquePoint(n, nodeIdx);
pQTetraIds[7] = nodeIdx;
// 9: 2-4
vtkMath::Add(n4, n2, n);
vtkMath::MultiplyScalar(n, 0.5);
mergePoints->InsertUniquePoint(n, nodeIdx);
pQTetraIds[8] = nodeIdx;
// 10: 3-4
vtkMath::Add(n4, n3, n);
vtkMath::MultiplyScalar(n, 0.5);
mergePoints->InsertUniquePoint(n, nodeIdx);
pQTetraIds[9] = nodeIdx;
cellsIdsQuadratic->SetValue(i, VTK_QUADRATIC_TETRA);
cellsQuadratic->InsertNextCell(10, pQTetraIds);
cellLocations->SetValue(i, location);
location += 11;
}
else
{
cellsQuadratic->InsertNextCell(mesh->GetCell(i));
cellsIdsQuadratic->SetValue(i, mesh->GetCellType(i));
cellLocations->SetValue(i, location);
location += mesh->GetCell(i)->GetNumberOfPoints()+1;
}
}
totalNumNodes = mesh->GetNumberOfPoints();
mesh->SetCells(cellsIdsQuadratic, cellLocations, cellsQuadratic);
}
// create output file
FILE *fid_out = fopen(outputFile.c_str(), "w");
if (!fid_out)
{
std::cerr << "Failed to create file " << outputFile.c_str() << std::endl;
return EXIT_FAILURE;
}
// write header
fprintf(fid_out, "*Heading\n"
"** Generated by Slicer module AAA_GenerateAbaqusFile\n");
// Create a part
fprintf(fid_out, "*Part, name=%s\n", partName.c_str());
// Write nodes
fprintf(fid_out, "*NODE\n");
for (vtkIdType i = 0; i < numNodes; i++)
{
double pcoord[3];
pPoints->GetPoint(i, pcoord);
fprintf(fid_out, "%d, %.10g, %.10g, %.10g\n", i+1, pcoord[0], pcoord[1], pcoord[2]);
}
// create middle nodes for bilinear tetra elements
if (boQuadratic)
{
for (vtkIdType i = numNodes; i < totalNumNodes; i++)
{
double pcoord[3];
pPoints->GetPoint(i, pcoord);
fprintf(fid_out, "%d, %.10g, %.10g, %.10g\n", i+1, pcoord[0], pcoord[1], pcoord[2]);
}
}
// Write tetras
fprintf(fid_out, "*Element, type=C3D%d%s\n", boQuadratic?10:4, boHybrid?"H":"");
for (vtkIdType i = 0; i < numElements; i++)
{
if (mesh->GetCellType(i) == VTK_TETRA)
{
vtkIdType n1 = mesh->GetCell(i)->GetPointId(0);
vtkIdType n2 = mesh->GetCell(i)->GetPointId(1);
vtkIdType n3 = mesh->GetCell(i)->GetPointId(2);
vtkIdType n4 = mesh->GetCell(i)->GetPointId(3);
fprintf(fid_out, "%d, %d, %d, %d, %d\n", i+1, n1+1, n2+1, n3+1, n4+1);
}
else if (boQuadratic && (mesh->GetCellType(i) == VTK_QUADRATIC_TETRA))
{
vtkIdType n1 = mesh->GetCell(i)->GetPointId(0);
vtkIdType n2 = mesh->GetCell(i)->GetPointId(1);
vtkIdType n3 = mesh->GetCell(i)->GetPointId(2);
vtkIdType n4 = mesh->GetCell(i)->GetPointId(3);
vtkIdType n5 = mesh->GetCell(i)->GetPointId(4);
vtkIdType n6 = mesh->GetCell(i)->GetPointId(5);
vtkIdType n7 = mesh->GetCell(i)->GetPointId(6);
vtkIdType n8 = mesh->GetCell(i)->GetPointId(7);
vtkIdType n9 = mesh->GetCell(i)->GetPointId(8);
vtkIdType n10 = mesh->GetCell(i)->GetPointId(9);
fprintf(fid_out, "%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n", i+1, n1+1, n2+1, n3+1, n4+1,
n5+1, n6+1, n7+1, n8+1, n9+1, n10+1);
}
}
// define an element set with all elements
fprintf(fid_out, "*Elset, elset=AllElements, generate\n"
" 1, %d, 1\n", numTetras);
// define a node set with all nodes (except middle ones)
fprintf(fid_out, "*Nset, Nset=AllNodes, generate\n"
" 1, %d, 1\n", numNodes);
// Create node sets at the ends
double bounds[6];
mesh->GetBounds(bounds);
double zMin = bounds[4];
double zMax = bounds[5];
double dz = (zMax - zMin)/LENGTH_PER_CAP_SIZE;
fprintf(fid_out, "*NSET, nset=Upper_cap\n");
vtkIdType np = 0;
for (vtkIdType i = 0; i < numNodes; i++)
{
double p[3];
pPoints->GetPoint(i, p);
if(p[2] > zMax - dz)
{
np++;
fprintf(fid_out, "%d, ", i+1);
if (np == 8)
{
np = 0;
fprintf(fid_out, "\n");
}
}
}
if (np != 0) fprintf(fid_out, "\n");
fprintf(fid_out, "*NSET, nset=Lower_cap\n");
np = 0;
for (vtkIdType i = 0; i < numNodes; i++)
{
double p[3];
pPoints->GetPoint(i, p);
if(p[2] < zMin + dz)
{
np++;
fprintf(fid_out, "%d, ", i+1);
if (np == 8)
{
np = 0;
fprintf(fid_out, "\n");
}
}
}
if (np != 0) fprintf(fid_out, "\n");
// find surface nodes close to the mesh surface
vtkSmartPointer<vtkKdTreePointLocator> locator = vtkSmartPointer<vtkKdTreePointLocator>::New();
locator->SetDataSet(pSplitSurface);
locator->BuildLocator();
vtkSmartPointer<vtkCellDataToPointData> transferCellDataToPoints = vtkSmartPointer<vtkCellDataToPointData>::New();
transferCellDataToPoints->SetInputData(pSplitSurface);
transferCellDataToPoints->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_POINTS, SURF_ID_NAME);
transferCellDataToPoints->Update();
vtkIdTypeArray *surfIds = (vtkIdTypeArray *)transferCellDataToPoints->GetPolyDataOutput()->GetPointData()->GetScalars(SURF_ID_NAME);
double pCoord[3];//the coordinates of the test point
// Find neighbours of triangular cells
int intSurfID, extSurfID;
if (boHandlingILT)
{
intSurfID = INT_ILT_SURF_ID;
extSurfID = INT_WALL_SURF_ID;
}
else
{
intSurfID = INT_WALL_SURF_ID;
extSurfID = EXT_WALL_SURF_ID;
}
vtkSmartPointer<vtkIdList> nIds = vtkSmartPointer<vtkIdList>::New();
vtkSmartPointer<vtkIdList> tetraNodeIds = vtkSmartPointer<vtkIdList>::New();
vtkSmartPointer<vtkIdList> cellIds = vtkSmartPointer<vtkIdList>::New();
vtkSmartPointer<vtkIdList> faceIds = vtkSmartPointer<vtkIdList>::New();
faceIds->SetNumberOfIds(numElements);
for (vtkIdType i = 0; i < numElements; i++) { faceIds->SetId(i, 0);};
np = 0;
for (vtkIdType i = 0; i < numElements; i++)
{
if (mesh->GetCellType(i) == VTK_TRIANGLE)
{
// get node ids
nIds = mesh->GetCell(i)->GetPointIds();
vtkIdType res = 0;
for (vtkIdType k = 0; k < 3; k++)
{
// get coordinates of node
pPoints->GetPoint(nIds->GetId(k), pCoord);
vtkIdType id = locator->FindClosestPoint(pCoord);
if (surfIds->GetValue(id) == intSurfID)
{
res = intSurfID;
break;
}
if (surfIds->GetValue(id) == extSurfID)
{
res = extSurfID;
break;
}
}
if (res > 0)
{
// triangle on the interior or exterior surface
mesh->GetCellNeighbors(i, nIds, cellIds);
for (vtkIdType n = 0; n < cellIds->GetNumberOfIds(); n++)
{
vtkIdType id = cellIds->GetId(n);
if (mesh->GetCellType(id) != VTK_TRIANGLE)
{
// check which face
tetraNodeIds = mesh->GetCell(id)->GetPointIds();
if (nIds->GetId(0) != tetraNodeIds->GetId(0) &&
nIds->GetId(1) != tetraNodeIds->GetId(0) &&
nIds->GetId(2) != tetraNodeIds->GetId(0))
{
// node 1 not in common face
faceIds->SetId(id, res*10+3);
}
else if (nIds->GetId(0) != tetraNodeIds->GetId(1) &&
nIds->GetId(1) != tetraNodeIds->GetId(1) &&
nIds->GetId(2) != tetraNodeIds->GetId(1))
{
// node 2 not in common face
faceIds->SetId(id, res*10+4);
}
else if (nIds->GetId(0) != tetraNodeIds->GetId(2) &&
nIds->GetId(1) != tetraNodeIds->GetId(2) &&
nIds->GetId(2) != tetraNodeIds->GetId(2))
{
// node 3 not in common face
faceIds->SetId(id, res*10+2);
}
else faceIds->SetId(id, res*10+1);
}
}
}
}
}
// create interior surface set
fprintf(fid_out, "*Elset, elset=_INTERIORS_S1, internal\n");
np = 0;
for (vtkIdType i = 0; i < numElements; i++)
{
if (faceIds->GetId(i) == (intSurfID*10+1))
{
np++;
fprintf(fid_out, "%d, ", i+1);
if (np == 8)
{
np = 0;
fprintf(fid_out, "\n");
}
}
}
if (np != 0) fprintf(fid_out, "\n");
fprintf(fid_out, "*Elset, elset=_INTERIORS_S2, internal\n");
np = 0;
for (vtkIdType i = 0; i < numElements; i++)
{
if (faceIds->GetId(i) == (intSurfID*10+2))
{
np++;
fprintf(fid_out, "%d, ", i+1);
if (np == 8)
{
np = 0;
fprintf(fid_out, "\n");
}
}
}
if (np != 0) fprintf(fid_out, "\n");
fprintf(fid_out, "*Elset, elset=_INTERIORS_S3, internal\n");
np = 0;
for (vtkIdType i = 0; i < numElements; i++)
{
if (faceIds->GetId(i) == (intSurfID*10+3))
{
np++;
fprintf(fid_out, "%d, ", i+1);
if (np == 8)
{
np = 0;
fprintf(fid_out, "\n");
}
}
}
if (np != 0) fprintf(fid_out, "\n");
fprintf(fid_out, "*Elset, elset=_INTERIORS_S4, internal\n");
np = 0;
for (vtkIdType i = 0; i < numElements; i++)
{
if (faceIds->GetId(i) == (intSurfID*10+4))
{
np++;
fprintf(fid_out, "%d, ", i+1);
if (np == 8)
{
np = 0;
fprintf(fid_out, "\n");
}
}
}
if (np != 0) fprintf(fid_out, "\n");
// create interior surface
fprintf(fid_out, "*Surface, name=InteriorS, TYPE=ELEMENT\n"
"_INTERIORS_S1, S1\n"
"_INTERIORS_S2, S2\n"
"_INTERIORS_S3, S3\n"
"_INTERIORS_S4, S4\n");
// create exterior surface set
fprintf(fid_out, "*Elset, elset=_EXTERIORS_S1, internal\n");
np = 0;
for (vtkIdType i = 0; i < numElements; i++)
{
if (faceIds->GetId(i) == (extSurfID*10+1))
{
np++;
fprintf(fid_out, "%d, ", i+1);
if (np == 8)
{
np = 0;
fprintf(fid_out, "\n");
}
}
}
if (np != 0) fprintf(fid_out, "\n");
fprintf(fid_out, "*Elset, elset=_EXTERIORS_S2, internal\n");
np = 0;
for (vtkIdType i = 0; i < numElements; i++)
{
if (faceIds->GetId(i) == (extSurfID*10+2))
{
np++;
fprintf(fid_out, "%d, ", i+1);
if (np == 8)
{
np = 0;
fprintf(fid_out, "\n");
}
}
}
if (np != 0) fprintf(fid_out, "\n");
fprintf(fid_out, "*Elset, elset=_EXTERIORS_S3, internal\n");
np = 0;
for (vtkIdType i = 0; i < numElements; i++)
{
if (faceIds->GetId(i) == (extSurfID*10+3))
{
np++;
fprintf(fid_out, "%d, ", i+1);
if (np == 8)
{
np = 0;
fprintf(fid_out, "\n");
}
}
}
if (np != 0) fprintf(fid_out, "\n");
fprintf(fid_out, "*Elset, elset=_EXTERIORS_S4, internal\n");
np = 0;
for (vtkIdType i = 0; i < numElements; i++)
{
if (faceIds->GetId(i) == (extSurfID*10+4))
{
np++;
fprintf(fid_out, "%d, ", i+1);
if (np == 8)
{
np = 0;
fprintf(fid_out, "\n");
}
}
}
if (np != 0) fprintf(fid_out, "\n");
// create interior surface
fprintf(fid_out, "*Surface, name=ExteriorS, TYPE=ELEMENT\n"
"_EXTERIORS_S1, S1\n"
"_EXTERIORS_S2, S2\n"
"_EXTERIORS_S3, S3\n"
"_EXTERIORS_S4, S4\n");
// define section
fprintf(fid_out, "*Solid Section, elset=AllElements, material=%s\n", partName.c_str());
// end part and start assembly with node sets
fprintf(fid_out, "*End Part\n");
fclose(fid_out);
return EXIT_SUCCESS;
} | 28.024055 | 133 | 0.643593 | [
"mesh",
"solid"
] |
7c1d8e769f374a84a8b55b6e649595e85252dcd6 | 643 | hpp | C++ | src/rogue-card/scene/GameOver.hpp | padawin/RogueCard | 7a5d04fa2d7be47c1542b6d4908e277ccbbd01fc | [
"MIT"
] | null | null | null | src/rogue-card/scene/GameOver.hpp | padawin/RogueCard | 7a5d04fa2d7be47c1542b6d4908e277ccbbd01fc | [
"MIT"
] | null | null | null | src/rogue-card/scene/GameOver.hpp | padawin/RogueCard | 7a5d04fa2d7be47c1542b6d4908e277ccbbd01fc | [
"MIT"
] | null | null | null | #ifndef __GAMEOVER_STATE__
#define __GAMEOVER_STATE__
#include <string.h>
#include "../game/SceneState.hpp"
#include "../sdl2/Renderer.hpp"
#include "../sdl2/Text.hpp"
#include "menus/EndGame.hpp"
class GameOverScene : public SceneState {
private:
std::shared_ptr<SDL2Renderer> m_renderer;
int m_iTitleXPos = 0;
Text m_title;
EndGameMenu m_menu;
void _executeMenuAction(StateMachine<SceneState> &stateMachine);
public:
GameOverScene(UserActions &userActions, std::shared_ptr<SDL2Renderer> renderer);
bool onEnter();
void update(StateMachine<SceneState> &stateMachine);
void render();
std::string getStateID() const;
};
#endif
| 22.964286 | 81 | 0.765163 | [
"render"
] |
7c2792708ef2ad4f24bcab797cee8834fcb9c7bd | 7,343 | cc | C++ | PiMulator/Bank_Hardware_Design/software_src/main.cc | hplp/PiMulator | 498cbe0b1e176c7d1cc2721f20d7bc0f193a3e3b | [
"BSD-2-Clause"
] | null | null | null | PiMulator/Bank_Hardware_Design/software_src/main.cc | hplp/PiMulator | 498cbe0b1e176c7d1cc2721f20d7bc0f193a3e3b | [
"BSD-2-Clause"
] | null | null | null | PiMulator/Bank_Hardware_Design/software_src/main.cc | hplp/PiMulator | 498cbe0b1e176c7d1cc2721f20d7bc0f193a3e3b | [
"BSD-2-Clause"
] | null | null | null | /*
* DRAM Bank Hardware Test for (i) Bank Software Model and (ii) Bank Hardware Model
* The main idea of this test is to (1) first, write all Bank memory location with known data
* (all NUM_ROWS * NUM_COLS locations) and then (2) second, to read all Bank memory locations
* and make sure the read data for each Bank location matches the written data to that location
* in step (1).
*
* This is done either for Software Simulation, which includes only the Bank Software Model
* (Hint: see all other .cpp and .h files, which model the Bank in software) or it can be done
* for Bank Hardware Emulation, which uses the Bank Hardware created in the Vivado Project
*
* This was done for consistency in the timing measurement, so that the time the Read / Write benchmark takes
* for either software simulation or hardware emulation is measured in terms of clock cycles
* on the Zynq CPU
*
* Here is an explanation how the benchmark works:
* I. Write All Memory Locations:
* 1. Loop through each memory row (NUM_ROW times) and activate each row (or place row in row buffer)
* 1.1. Loop through each memory column (NUM_COLS times) and write it with known data (or write row buffer)
* 2. issue PRECHARGE command to clear row buffer before moving on to another row
* II. Read All Memory Locations:
* 1. Loop through each memory row (NUM_ROW times) and activate each row (or place row in row buffer)
* 1.1. Loop through each memory column (NUM_COLS times) and read it (or read row buffer)
* 1.2 Optionally, check whether the read data matches the data that was written to that location
* 2. issue PRECHARGE command to clear row buffer before moving on to another row
*
* Macros control what testing takes place, here is an explanation of each:
*
* SOFTWARE: turn ON Bank Software Test (Make sure to turn OFF HARDWARE test)
* HARDWARE: turn ON Bank Hardware Test (Make sure to turn OFF SOFTWARE test)
* REPORT_TIMING: Reports the timing of the test, in terms of Zynq clock cycles
* (will specify whether Emulation or Simulation was timed)
* CHECK: Turns ON checking whether the read data matches the data previously written to that
* memory location, recommended to turn it OFF if you want an exact timing comparison to avoid extra latency
*
* Feel free to modify this code and use the provided functions to issue different Bank Commands
* and see how timing is affected by that.
*/
#include "Bank.h"
#include "xil_printf.h"
#include "xtime_l.h"
#include "xil_types.h"
#include "xtime_l.h"
#include "xil_io.h"
#include "xbank.h"
// Software or Hardware Test
#define HARDWARE // SOFTWARE HARDWARE
// Whether to report timing
#define REPORT_TIMING
// Whether to check if read data is correct
#define CHECK
// Easy trick
#define printf xil_printf
// Helps format input for Bank Interface
#ifdef HARDWARE
#define format_input(busPacketType,row,column,data_in) (((((((0|data_in) << 8) | column) << 8) | row) << 8) | busPacketType)
#endif
#ifdef SOFTWARE
bank_in format_input(BusPacketType busPacketType, unsigned char row, unsigned char column, unsigned char data_in) {
bank_in input;
input.busPacketType = busPacketType;
input.row = row;
input.column = column;
input.data_in = data_in;
return input;
}
#endif
// Hardware-related (only needed for HARDWARE test)
#ifdef HARDWARE
void setup(XBank *do_xbank) {
// Setup Bank HLS
int status;
XBank_Config *do_xbank_cfg;
do_xbank_cfg = XBank_LookupConfig(
XPAR_XBANK_0_DEVICE_ID);
if (!do_xbank_cfg) {
printf("Error loading configuration for do_xbank_cfg \n\r");
return;
}
status = XBank_CfgInitialize(do_xbank, do_xbank_cfg);
if (status != XST_SUCCESS) {
printf("Error initializing for do_xbank \n\r");
return;
}
XBank_Initialize(do_xbank, XPAR_XBANK_0_DEVICE_ID); // this is optional in this case
}
void wait(XBank *do_xbank) {
// Start, wait to finish
XBank_Start(do_xbank);
// Wait until it's done (optional here)
while (!XBank_IsDone(do_xbank))
;
}
// Following are functions to interface with Bank
// Input Values to Bank (WRITE, ACTIVATE, REFRESH, PRECHARGE)
void toBank(XBank *do_xbank, u32 input) {
XBank_Set_bankpacket_in(do_xbank, input);
wait(do_xbank);
}
// Get Values to Bank (READ)
u32 fromBank(XBank *do_xbank, u32 input) {
XBank_Set_bankpacket_in(do_xbank, input);
wait(do_xbank);
return XBank_Get_data_out(do_xbank);
}
#endif
int main() {
//
#ifdef HARDWARE
#ifdef SOFTWARE
return 0;
#endif
#endif
#ifndef HARDWARE
#ifndef SOFTWARE
return 0;
#endif
#endif
//
xil_printf("Start ...\n");
unsigned char data_o;
XTime tStart, tEnd, difference;
// Bank Hardware Test
#ifdef HARDWARE
// Setup Bank HLS
XBank do_xbank;
setup(&do_xbank);
// Start timer
XTime_GetTime(&tStart);
// Test 1: Write / Read all memory location
// Write all memory location
for (unsigned short i = 0; i < NUM_ROWS; i++) {
// (1) Activate row
toBank(&do_xbank, format_input(ACTIVATE, i, 0, 0));
for (unsigned short j = 0; j < NUM_COLS; j++) {
// (2) Write bank
toBank(&do_xbank, format_input(WRITE, i, j, (u32 ) ((i + j) % 256)));
}
// (3) PRECHARGE row buffer
toBank(&do_xbank, format_input(PRECHARGE, 0, 0, 0));
}
// Read all memory location & check
for (unsigned short i = 0; i < NUM_ROWS; i++) {
// (1) Activate row
toBank(&do_xbank, format_input(ACTIVATE, i, 0, 0));
for (unsigned short j = 0; j < NUM_COLS; j++) {
// (2) READ bank
data_o = fromBank(&do_xbank, format_input(READ, i, j, 0));
// Check if read data is correct
#ifdef CHECK
if (data_o != (i + j) % 256) {
printf("Mismatch at (%d, %d), Data is supposed to be %d, but it is %d\n", i, j, (i + j) % 256, data_o);
return 0;
} // else printf("Equal at (%d, %d), %d = %d\n", i, j, (i + j) % 256, data_o);
#endif
}
// (3) PRECHARGE row buffer
toBank(&do_xbank, format_input(PRECHARGE, 0, 0, 0));
}
#endif
// Bank Software Model Test
#ifdef SOFTWARE
// start timer
XTime_GetTime(&tStart);
// Write all memory location
for (unsigned i = 0; i < NUM_ROWS; i++) {
// (1) Activate row
Bank(format_input(ACTIVATE, i, 0, 0), data_o);
for (unsigned j = 0; j < NUM_COLS; j++) {
// (2) Write bank
Bank(format_input(WRITE, i, j, (unsigned char) ((i + j) % 256)), data_o);
}
// (3) PRECHARGE row buffer
Bank(format_input(PRECHARGE, 0, 0, 0), data_o);
}
// Read all memory location & check that contents are correct
for (unsigned short i = 0; i < NUM_ROWS; i++) {
// (1) Activate row
Bank(format_input(ACTIVATE, i, 0, 0), data_o);
for (unsigned short j = 0; j < NUM_COLS; j++) {
// (2) Read bank
Bank(format_input(READ, i, j, 0), data_o);
// Check
#ifdef CHECK
if (data_o != (i + j) % 256) {
printf("Mismatch at (%d, %d), Data is supposed to be %d, but it is %d\n", i, j, (i + j) % 256, data_o);
return 0;
} //else printf("Equal at (%d, %d), %d = %d\n", i, j, (i + j) % 256, data_o);
#endif
}
// (3) PRECHARGE row buffer
Bank(format_input(PRECHARGE, 0, 0, 0), data_o);
}
#endif
// Report timing information
#ifdef REPORT_TIMING
XTime_GetTime(&tEnd);
difference = tEnd - tStart;
#ifdef SOFTWARE
printf("(SOFTWARE) Simulation ");
#endif
#ifdef HARDWARE
printf("(HARDWARE) Emulation ");
#endif
printf("took %u CC.\n", (unsigned) (difference));
#endif
printf("End of script.\n");
return 0;
}
| 29.023715 | 124 | 0.689773 | [
"model"
] |
7c3c734cef8b410fe9397f9cdf28b40b36123b77 | 6,219 | cpp | C++ | BLAXED/NightMode.cpp | prismatical/BX-CSGO | 24b2cadefdc40cb8d3fca0aab08ec54241518958 | [
"MIT"
] | 19 | 2018-03-04T08:04:29.000Z | 2022-01-27T11:28:36.000Z | BLAXED/NightMode.cpp | prismatical/BX-CSGO | 24b2cadefdc40cb8d3fca0aab08ec54241518958 | [
"MIT"
] | 1 | 2019-12-27T15:43:41.000Z | 2020-05-18T19:16:42.000Z | BLAXED/NightMode.cpp | prismatical/BX-CSGO | 24b2cadefdc40cb8d3fca0aab08ec54241518958 | [
"MIT"
] | 9 | 2019-03-30T22:39:25.000Z | 2021-08-13T19:27:27.000Z | #include "SDK.h"
#include "Global.h"
#include "NightMode.h"
#include "ConvarSpoofer.h"
#include "AutoWall.h"
namespace NightMode
{
bool done = false;
class MaterialBackup
{
public:
MaterialHandle_t handle;
IMaterial* pMaterial;
float color[3];
float alpha;
bool translucent;
bool nodraw;
MaterialBackup()
{
}
MaterialBackup(MaterialHandle_t h, IMaterial* p)
{
handle = handle;
pMaterial = p;
pMaterial->GetColorModulation(&color[0], &color[1], &color[2]);
alpha = pMaterial->GetAlphaModulation();
translucent = pMaterial->GetMaterialVarFlag(MATERIAL_VAR_TRANSLUCENT);
nodraw = pMaterial->GetMaterialVarFlag(MATERIAL_VAR_NO_DRAW);
}
void Restore()
{
pMaterial->ColorModulate(color[0], color[1], color[2]);
pMaterial->AlphaModulate(alpha);
pMaterial->SetMaterialVarFlag(MATERIAL_VAR_TRANSLUCENT, translucent);
pMaterial->SetMaterialVarFlag(MATERIAL_VAR_NO_DRAW, nodraw);
}
};
std::vector<MaterialBackup> materials;
std::vector<MaterialBackup> skyboxes;
void DoNightMode(MaterialHandle_t i, IMaterial *pMaterial, bool saveBackup = false)
{
if (strstr(pMaterial->GetTextureGroupName(), xorstr("Model")))
{
if (saveBackup)
materials.push_back(MaterialBackup(i, pMaterial));
pMaterial->ColorModulate(0.6f, 0.6f, 0.6f);
}
else if (strstr(pMaterial->GetTextureGroupName(), xorstr("World")))
{
if (saveBackup)
materials.push_back(MaterialBackup(i, pMaterial));
pMaterial->ColorModulate(0.15f, 0.15f, 0.15f);
//pMaterial->ColorModulate(0.07f, 0.07f, 0.07f);
}
else if (strstr(pMaterial->GetTextureGroupName(), xorstr("Static")))
{
if (saveBackup)
materials.push_back(MaterialBackup(i, pMaterial));
//pMaterial->ColorModulate(0.35f, 0.35f, 0.35f);
pMaterial->ColorModulate(0.30f, 0.30f, 0.30f);
//pMaterial->ColorModulate(0.17f, 0.17f, 0.17f);
if (strstr(pMaterial->GetName(), xorstr("barrel")) || strstr(pMaterial->GetName(), xorstr("dome")))
{
pMaterial->SetMaterialVarFlag(MATERIAL_VAR_TRANSLUCENT, true);
pMaterial->AlphaModulate(0.7f);
}
else if (strstr(pMaterial->GetName(), xorstr("door")))
{
if (!strstr(pMaterial->GetName(), xorstr("temple")))
{
pMaterial->AlphaModulate(0.83f);
}
}
else if (strstr(pMaterial->GetName(), xorstr("box")) || pMaterial->GetName(), xorstr("crate"))
{
pMaterial->AlphaModulate(0.93f);
}
}
else if (strstr(pMaterial->GetTextureGroupName(), xorstr("SkyBox")))
{
if (saveBackup)
skyboxes.push_back(MaterialBackup(i, pMaterial));
//pMaterial->ColorModulate(0.09f, 0.11f, 0.13f);
//pMaterial->ColorModulate(0.29f, 0.31f, 0.33f);
//pMaterial->ColorModulate(0.18f, 0.18f, 0.18f);
pMaterial->ColorModulate(0.23f, 0.22f, 0.22f);
}
}
void Apply()
{
if (done)
return;
if (!ConvarSpoofer::IsReady())
return;
done = true;
//ConvarSpoofer::Get(xorstr("sv_skyname"))->SetString(xorstr("sky_csgo_night02"));
ConvarSpoofer::Get(xorstr("sv_skyname"))->SetString(xorstr("vertigo"));
ConvarSpoofer::Get(xorstr("r_drawspecificstaticprop"))->SetValue(0);
ConvarSpoofer::Get(xorstr("r_dlightsenable"))->SetValue(1);
if (materials.size() == 0)
{
materials.clear();
skyboxes.clear();
for (MaterialHandle_t i = I::pMaterialSystem->FirstMaterial(); i != I::pMaterialSystem->InvalidMaterial(); i = I::pMaterialSystem->NextMaterial(i))
{
IMaterial* pMaterial = I::pMaterialSystem->GetMaterial(i);
if (!pMaterial || pMaterial->IsErrorMaterial())
continue;
if (pMaterial->GetReferenceCount() <= 0)
continue;
DoNightMode(i, pMaterial, true);
}
}
else
{
for (int i = 0; i < (int)materials.size(); i++)
{
DoNightMode(materials[i].handle, materials[i].pMaterial);
}
for (int i = 0; i < (int)skyboxes.size(); i++)
{
DoNightMode(skyboxes[i].handle, skyboxes[i].pMaterial);
}
}
}
void Remove()
{
if (!done || !ConvarSpoofer::IsReady())
return;
done = false;
for (int i = 0; i < (int)materials.size(); i++)
{
if (materials[i].pMaterial->GetReferenceCount() <= 0)
continue;
materials[i].Restore();
materials[i].pMaterial->Refresh();
}
for (int i = 0; i < (int)skyboxes.size(); i++)
{
if (materials[i].pMaterial->GetReferenceCount() <= 0)
continue;
skyboxes[i].Restore();
skyboxes[i].pMaterial->Refresh();
}
materials.clear();
skyboxes.clear();
cfg.Visual.nightMode = false;
ConvarSpoofer::Get(xorstr("sv_skyname"))->SetString(I::pCVar->FindVar(xorstr("sv_skyname"))->GetString());
ConvarSpoofer::Get(xorstr("r_drawspecificstaticprop"))->SetValue(I::pCVar->FindVar(xorstr("r_DrawSpecificStaticProp"))->GetInt());
ConvarSpoofer::Get(xorstr("fog_override"))->SetValue(I::pCVar->FindVar(xorstr("fog_override"))->GetInt());
ConvarSpoofer::Get(xorstr("fog_enable"))->SetValue(I::pCVar->FindVar(xorstr("fog_enable"))->GetInt());
ConvarSpoofer::Get(xorstr("fog_enableskybox"))->SetValue(I::pCVar->FindVar(xorstr("fog_enableskybox"))->GetInt());
ConvarSpoofer::Get(xorstr("fog_colorskybox"))->SetString(I::pCVar->FindVar(xorstr("fog_colorskybox"))->GetString());
ConvarSpoofer::Get(xorstr("r_dlightsenable"))->SetValue(I::pCVar->FindVar(xorstr("r_dlightsenable"))->GetInt());
}
void FrameStageNotify(ClientFrameStage_t stage)
{
CBaseEntity *pLocal = G::pLocal;
if (!(I::pEngineClient->IsInGame() && I::pEngineClient->IsConnected()))
{
materials.clear();
skyboxes.clear();
return;
}
if (stage == FRAME_RENDER_END)
{
if (cfg.Visual.nightMode)
Apply();
else
Remove();
}
if (stage == FRAME_RENDER_START)
{
if (pLocal && cfg.Visual.flashLight && pLocal->IsAlive())
{
Vector f, r, u;
Vector viewAngles;
I::pEngineClient->GetViewAngles(viewAngles);
Math::AngleVectors(viewAngles, &f, &r, &u);
Vector origin = pLocal->GetAbsOrigin() + pLocal->GetViewOffset();
}
else
{
}
}
}
void HandleGameEvent(IGameEvent *pEvent)
{
const char *name = pEvent->GetName();
if (!strcmp(name, xorstr("round_start")))
{
if (cfg.Visual.nightMode)
{
Remove();
Apply();
cfg.Visual.nightMode = true;
}
}
}
};
| 25.383673 | 150 | 0.662164 | [
"vector",
"model"
] |
7c48a3af579de80679da3f47f3c111a62ba0581f | 1,527 | hpp | C++ | jarngreipr/geometry/dihedral.hpp | yutakasi634/Jarngreipr | 1213ec5200c650fc6afd4c9f0a842a077a73d050 | [
"MIT"
] | 2 | 2018-10-05T11:17:59.000Z | 2020-12-20T02:26:58.000Z | jarngreipr/geometry/dihedral.hpp | yutakasi634/Jarngreipr | 1213ec5200c650fc6afd4c9f0a842a077a73d050 | [
"MIT"
] | 8 | 2018-10-22T18:34:17.000Z | 2019-11-20T08:20:55.000Z | jarngreipr/geometry/dihedral.hpp | yutakasi634/Jarngreipr | 1213ec5200c650fc6afd4c9f0a842a077a73d050 | [
"MIT"
] | 4 | 2018-10-05T12:30:11.000Z | 2021-04-28T11:58:34.000Z | #ifndef JARNGREIPR_GEOMETRY_DIHEDRAL
#define JARNGREIPR_GEOMETRY_DIHEDRAL
#include <jarngreipr/geometry/angle.hpp>
namespace jarngreipr
{
/*! @brief Calculate dihedral angle formed by p1, p2, p3, and p4.
* o p1 | o p1
* / | dih _ /
* p2 o | / /
* \ | p4 o----o p2 & p3
* o p3 |
* / |
* p4 o |
* |
* */
template<typename realT>
realT dihedral_angle(const mjolnir::math::Vector<realT, 3>& p1,
const mjolnir::math::Vector<realT, 3>& p2,
const mjolnir::math::Vector<realT, 3>& p3,
const mjolnir::math::Vector<realT, 3>& p4)
{
const auto r_ij = p1 - p2;
const auto r_kj = p3 - p2;
const auto r_lk = p4 - p3;
const auto r_kj_lensq_inv = 1. / mjolnir::math::length_sq(r_kj);
const auto n = mjolnir::math::cross_product(r_kj, -1e0 * r_lk);
const auto R = r_ij - (mjolnir::math::dot_product(r_ij, r_kj) * r_kj_lensq_inv) * r_kj;
const auto S = r_lk - (mjolnir::math::dot_product(r_lk, r_kj) * r_kj_lensq_inv) * r_kj;
const auto cos_RS = mjolnir::math::dot_product(R, S) * mjolnir::math::rsqrt(
mjolnir::math::length_sq(R) * mjolnir::math::length_sq(S));
const auto cos_phi = (-1e0 <= cos_RS && cos_RS <= 1e0)
? cos_RS : std::copysign(1.0, cos_RS);
return std::copysign(std::acos(cos_phi), mjolnir::math::dot_product(r_ij, n));
}
} // jarngreipr
#endif /* JARNGREIPR_GEOMETRY_DIHEDRAL */
| 33.933333 | 91 | 0.574984 | [
"geometry",
"vector"
] |
7c55287b32dc2ae9627bd56a818e3d639e0120e4 | 9,052 | cpp | C++ | Source/Renderer.cpp | Nickelium/Rasterizer | 76673ec0ab9eb472e1bb097a2b98effe8e5668e6 | [
"MIT"
] | 14 | 2019-02-08T10:14:36.000Z | 2022-02-05T20:37:30.000Z | Source/Renderer.cpp | dimutch833/Rasterizer | 76673ec0ab9eb472e1bb097a2b98effe8e5668e6 | [
"MIT"
] | null | null | null | Source/Renderer.cpp | dimutch833/Rasterizer | 76673ec0ab9eb472e1bb097a2b98effe8e5668e6 | [
"MIT"
] | 1 | 2019-12-02T17:10:47.000Z | 2019-12-02T17:10:47.000Z | #include "Renderer.h"
#include "SDL2/include/SDL.h"
#include <algorithm>
#include "Window.h"
#include "Triangle.h"
#include "Maths.h"
#include "Scene.h"
#include "Texture.h"
#include "Camera.h"
#include "IShader.h"
#include "Shaders.h"
Renderer::Renderer(Window* window)
:renderMode(RENDER_MODE::RM_WIREFRAME),
width(window->GetWidth()),
height(window->GetHeight()),
window(window),
cBuffer(width, height),
zBuffer(width, height),
backgroundColor(234.0f / Color::MAX_VALUEI,
239.0f / Color::MAX_VALUEI,
247.0f / Color::MAX_VALUEI),
index(0u),
wireframeRender(true)
{
shaders.push_back(new FlatShading());
shaders.push_back(new GouraudShading());
shaders.push_back(new PhongShading());
shaders.push_back(new TexturedShader());
shaders.push_back(new DepthShader());
ConfigureRenderSettings();
}
Renderer::~Renderer()
{
for (auto& shad : shaders)
delete shad;
}
void Renderer::Clear()
{
cBuffer.Clear(ColorToInt(backgroundColor));
zBuffer.Clear(1.0f);
}
void Renderer::Finalize()
{
window->SwapBuffer(cBuffer);
}
void Renderer::ConfigureRenderSettings()
{
switch(renderMode)
{
case RENDER_MODE::RM_WIREFRAME:
wireframeRender = true;
shader = shaders[static_cast<unsigned char>(SHADER_TYPES::ST_FLAT)];
break;
case RENDER_MODE::RM_FLAT:
wireframeRender = false;
shader = shaders[static_cast<unsigned char>(SHADER_TYPES::ST_FLAT)];
break;
case RENDER_MODE::RM_GOURAUD:
wireframeRender = false;
shader = shaders[static_cast<unsigned char>(SHADER_TYPES::ST_GOURAUD)];
break;
case RENDER_MODE::RM_PHONG:
wireframeRender = false;
shader = shaders[static_cast<unsigned char>(SHADER_TYPES::ST_PHONG)];
break;
case RENDER_MODE::RM_TEXTURED:
wireframeRender = false;
shader = shaders[static_cast<unsigned char>(SHADER_TYPES::ST_TEXTURED)];
break;
case RENDER_MODE::RM_DEPTH:
wireframeRender = false;
shader = shaders[static_cast<unsigned char>(SHADER_TYPES::ST_DEPTH)];
break;
default:
break;
}
}
void Renderer::Render(Scene& scene)
{
Clear();
Matrix4f V = scene.GetCamera().GetViewMatrix();
Matrix4f P = Matrix4f::Perspective(60.0f, float(width) / height, 1.0f, 200.0f);
Matrix4f S = Matrix4f::Viewport(width, height);
LightParam lightInfo;
lightInfo.direction = Vector3f(1.0f, 1.0f, 1.0f).Normalize();
const float invMaxValue = 1.0f / 255.0f;
lightInfo.diffuseColor =
Color
(
255.0f * invMaxValue,
249.0f * invMaxValue,
232.0f * invMaxValue
);
for (const Object& object : scene.GetObjects())
{
Texture* texture = object.GetDiffuseMap();
Matrix4f M = object.GetTransform().GetMatrix();
shader->UpdateUniforms(M, V, P, S, object, lightInfo);
for (const Triangle& objectSpaceTriangle : object.GetMesh()->GetTriangles())
{
Vector3f vertices[3];
for (int i = 0; i < 3; ++i)
{
bool clip = shader->VertexShader(objectSpaceTriangle, i, vertices[i]);
if (clip)
goto outerloopEnd;
}
if(wireframeRender)
DrawTriangle(Triangle(vertices[0], vertices[1], vertices[2]));
else
{
Vector3f normal = Cross(vertices[1] - vertices[0], vertices[2] - vertices[0]);
bool backfaceCulling = normal.z < 0;
if (backfaceCulling)
continue;
{
float depths[3] = { vertices[0].z, vertices[1].z, vertices[2].z };
shader->StoreDepthValues(depths);
}
//ScanlineFast(*shader, vertices);
ScanlineClean(*shader, vertices);
}
outerloopEnd:;
}
}
Finalize();
}
void Renderer::ChangeRenderMode()
{
renderMode = static_cast<RENDER_MODE>((static_cast<unsigned char>(renderMode) + 1) % static_cast<unsigned char>(RENDER_MODE::RM_NUMBER_MODES));
ConfigureRenderSettings();
}
void Renderer::DrawTriangle(const Triangle& triangle)
{
for (int i = 0; i < 3; ++i)
{
Vector2i p0 (int(triangle[i % 3].x), int(triangle[i % 3].y));
Vector2i p1 (int(triangle[(i + 1) % 3].x), int(triangle[(i + 1) % 3].y));
DrawLine(p0, p1);
}
}
//Bresenham's line algorithm
void Renderer::DrawLine(Vector2i p0, Vector2i p1)
{
Color color(1.0f, 0.0f, 0);
bool steep = false;
if (abs(p0.x - p1.x) < abs(p0.y - p1.y))
{
p0 = Vector2i(p0.y, p0.x);
p1 = Vector2i(p1.y, p1.x);
steep = true;
}
if (p0.x > p1.x)
std::swap(p0, p1);
//Always map to one octant, either (I or VIII) with derivative/slope [-1, 1]
int dx = p1.x - p0.x;
int dy = p1.y - p0.y;
float dydx = (float)dy / dx;
int totalError = 0;
//This deals with wether octant I or VIII
int derror = dydx > 0 ? +1 : -1;
int error = 2 * dy;
Vector2i pi(p0);
for ( pi.x = p0.x; pi.x < p1.x; ++pi.x)
{
if (!steep)
cBuffer.SetElement(pi.x, pi.y, ColorToInt(color));
else
cBuffer.SetElement(pi.y, pi.x, ColorToInt(color));
totalError += error;
if (abs(totalError) > dx)
{
pi.y += derror;
totalError -= 2 * dx * derror;
}
}
}
void Renderer::ScanlineClean(IShader& shader, Vector3f* vertScreen)
{
if (abs(vertScreen[0].y - vertScreen[1].y) < 0.0001f &&
abs(vertScreen[1].y - vertScreen[2].y) < 0.0001f)
return;
Vector3f edge0 = vertScreen[2] - vertScreen[1];
Vector3f edge1 = vertScreen[0] - vertScreen[2];
Vector3f edge2 = vertScreen[1] - vertScreen[0];
Vector2f min(std::numeric_limits<float>::max()),
max(-std::numeric_limits<float>::max());
for (int i = 0; i < Triangle::Size(); ++i)
{
Vector3f p = vertScreen[i];
Vector2f p2D(p.x, p.y);
min = Maths::Min(min, p2D);
max = Maths::Max(max, p2D);
}
Color color(1.0f, 1.0f, 1.0f);
float u, v, w;
int xMin = std::max(0, std::min(window->GetWidth(), static_cast<int>(std::floor(min.x))));
int yMin = std::max(0, std::min(window->GetHeight(), static_cast<int>(std::floor(min.y))));
int xMax = std::max(0, std::min(window->GetWidth(), static_cast<int>(std::floor(max.x))));
int yMax = std::max(0, std::min(window->GetHeight(), static_cast<int>(std::floor(max.y))));
int count = 0;
for (int y = yMin, endY = yMax; y <= endY; ++y)
for (int x = xMin, endX = xMax; x <= endX; ++x)
{
Triangle::Barycentric(vertScreen, Vector3f(float(x + 0.5f), float(y + 0.5f), 0.0f), u, v, w);
if (!(0.0f <= u && u <= 1.0f
&& 0.0f <= v && v <= 1.0f
&& 0.0f <= w && w <= 1.0f)) continue;
float Z = 1.0f / (u * (1.0f / vertScreen[0].z) + v * (1.0f / vertScreen[1].z) + w * (1.0f / vertScreen[2].z));
//float Z = 1.0f / zInv;
float Zlin = u * vertScreen[0].z + v * vertScreen[1].z + w * vertScreen[2].z;
float zBufferValue = zBuffer(x, y);
if (Z < zBufferValue)
{
zBuffer.SetElement(x, y, Z);
shader.FragmentShader(Vector3f(u, v, w), Z, color);
cBuffer.SetElement(x, y, ColorToInt(color));
}
}
}
//Scanline algorithm
void Renderer::ScanlineFast(IShader& shader, Vector3f* vertices)
{
if (abs(vertices[0].y - vertices[1].y) < 0.0001f &&
abs(vertices[1].y - vertices[2].y) < 0.0001f)
return;
Maths::Sort(vertices, 3);
Color color(1.0f, 1.0f, 1.0f);
//Draw lower half
float totalHeight = vertices[2].y - vertices[0].y;
float heightT1T0 = vertices[1].y - vertices[0].y + 1;
for (int y = int(vertices[0].y); y <= vertices[1].y; ++y)
{
float alpha = (y - int(vertices[0].y)) / totalHeight;
float beta = (y - int(vertices[0].y)) / heightT1T0;
Vector3f A = vertices[0] + (vertices[2] - vertices[0]) * alpha;
Vector3f B = vertices[0] + (vertices[1] - vertices[0]) * beta;
if (A.x > B.x)
std::swap(A, B);
uint32_t colorInt = color.GetInt();
float u = 0.0f, v = 0.0f, w = 0.0f;
for (uint32_t* p = cBuffer.GetBuffer() + y * cBuffer.GetWidth() + int(A.x),
*end = cBuffer.GetBuffer() + y * cBuffer.GetWidth() + int(B.x),
x = int(A.x); p <= end; ++p, ++x)
{
Triangle::Barycentric(vertices, Vector3f(float(x + 0.5f), float(y + 0.5f), 0.0f), u, v, w);
if (u < 0.0f || v < 0.0f || w < 0.0f) continue;
float Z = u * vertices[0].z + v * vertices[1].z + w * vertices[2].z;
float zBufferValue = zBuffer(x, y);
if (Z < zBufferValue)
{
zBuffer(x, y) = Z;
shader.FragmentShader(Vector3f(u, v, w), Z, color);
cBuffer(x, y) = ColorToInt(color);
}
}
}
//Draw upper half
float heightT1T2 = vertices[2].y - vertices[1].y + 1;
for (int y = int(vertices[1].y); y <= vertices[2].y; ++y)
{
float alpha = (y - vertices[0].y) / totalHeight;
float beta = (y - vertices[1].y) / heightT1T2;
Vector3f A = vertices[0] + (vertices[2] - vertices[0]) * alpha;
Vector3f B = vertices[1] + (vertices[2] - vertices[1]) * beta;
if (A.x > B.x)
std::swap(A, B);
uint32_t colorInt = color.GetInt();
float u = 0.0f, v = 0.0f, w = 0.0f;
for (uint32_t* p = cBuffer.GetBuffer() + y * cBuffer.GetWidth() + int(A.x),
*end = cBuffer.GetBuffer() + y * cBuffer.GetWidth() + int(B.x),
x = int(A.x); p <= end; ++p, ++x)
{
Triangle::Barycentric(vertices, Vector3f(float(x + 0.5f), float(y + 0.5f), 0.0f), u, v, w);
if (u < 0.0f || v < 0.0f || w < 0.0f) continue;
float Z = u * vertices[0].z + v * vertices[1].z + w * vertices[2].z;
float zBufferValue = zBuffer(x, y);
if (Z < zBufferValue)
{
zBuffer(x, y) = Z;
shader.FragmentShader(Vector3f(u, v, w), Z, color);
cBuffer(x, y) = ColorToInt(color);
}
}
}
}
| 28.199377 | 144 | 0.634666 | [
"render",
"object"
] |
7c570a193489f78b3aa34065021c6fc5fa3c777c | 13,848 | cpp | C++ | hw3/myplugin.cpp | adityag6994/quad_arrt | 4235b3985fb5327cffaa136929859bac124ee934 | [
"BSD-2-Clause"
] | null | null | null | hw3/myplugin.cpp | adityag6994/quad_arrt | 4235b3985fb5327cffaa136929859bac124ee934 | [
"BSD-2-Clause"
] | null | null | null | hw3/myplugin.cpp | adityag6994/quad_arrt | 4235b3985fb5327cffaa136929859bac124ee934 | [
"BSD-2-Clause"
] | null | null | null | #include <openrave/openrave.h>
#include <openrave/plugin.h>
#include <openrave/planningutils.h>
#include <boost/bind.hpp>
#include <boost/algorithm/string/classification.hpp> // Include boost::for is_any_of
#include <boost/algorithm/string/split.hpp> // Include for boost::split
#include <iostream>
#include <string.h>
#include <tuple>
#include <ctime>
#include <cstdio>
#include "myplugin.h"
using namespace OpenRAVE;
using namespace std;
size_t MAX_ITERATIONS = 200;//used for smoothing
int RRTNode::CurrentID = 0;
dReal GOAL_BIAS = 0.16;//biasing towards goal 16% OPTIMAL
dReal delta_Q = 0.35;//step size
int flag = 0;//checks if goal is reached
typedef std::vector<OpenRAVE::dReal> Config; //configration for robot
typedef boost::shared_ptr<RRTNode> Node; //node containing configration and parents address
typedef boost::shared_ptr<NodeTree> Tree;//tree to hold vector of nodes
//main RRT class
class RRTModule : public ModuleBase
{
public:
//to connect with python
RRTModule(EnvironmentBasePtr penv, std::istream& ss) : ModuleBase(penv) {
_penv = penv;
RegisterCommand("MyCommand",boost::bind(&RRTModule::MyCommand,this,_1,_2),
"This is an example command hello");
}
virtual ~RRTModule() {}
bool MyCommand(std::ostream& sout, std::istream& sinput)
{
cout << "*PLUGIN STARTED" << endl;
//setting up clocks
// clock_t start;
// start = clock();
//setenvironment and robot
_penv->GetRobots(_robots);
_robot = _robots.at(0);
_robot->GetActiveDOFValues(_startConfig);
// set goal config
_goalConfig.push_back(0.449);
_goalConfig.push_back(-0.201);
_goalConfig.push_back(-0.151);
_goalConfig.push_back(-0.11);
_goalConfig.push_back(0);
_goalConfig.push_back(-0.11);
_goalConfig.push_back(0);
//get active dof limits
_robot->GetActiveDOFLimits(_lowerLimit, _upperLimit);
//changing the limits of last and second last DOF
_lowerLimit[4] = -3.14;
_lowerLimit[6] = -3.14;
_upperLimit[4] = 3.14;
_upperLimit[6] = 3.14;
/*
Lower Limits: Config: -0.564602 -0.3536 -2.12131 -2.00001 -10000 -2.00001 -10000
Upper Limits: Config: 2.13539 1.2963 -0.15 -0.1 10000 -0.1 10000
*/
//weights used while calculating neirest node
_weight.push_back(3.17104);
_weight.push_back(2.75674);
_weight.push_back(2.2325);
_weight.push_back(2.2325);
_weight.push_back(1.78948);
_weight.push_back(0);
_weight.push_back(0.809013);
_weight.push_back(0);
//initialising tree
_startNode = Node(new RRTNode());
_startNode->setConfig(_startConfig);
_startNode->setParent(nullptr);
Config test = _startNode->getConfig();
//adding start to tree
_mainTree.setrootNode(_startNode);
_mainTree.nodeAdd(_startNode);
_randomConfig = _startConfig;
//Main Algorithm Starts Here
count = 0;
int cc=0;
//do until goal is reached
while(count++ < 100000){
//------------------------get random node
_randomConfig = randomnodeGenerator();
//------------------------check for nearest node in tree
_nearestNode = NNNode();
//------------------------Get the step size
_stepSize = step();
if(flag){
//-----------------------if goal is reached, break out of while loop
cout << "Goal Found" << endl;
break;
}else{
//------------------------else get the next node
EXTEND(count);
//--------------------just to get an idea where we stand currently
if(cc % 1000 == 0){
cout << "Searching.." << count << endl;
}
cc++;
}
}
//clock stops as, we are out of loop with path searched :)
// duration = (clock() - start)/(double)CLOCKS_PER_SEC;
//get the path trajector
getPath();
//exectue the path using robots controller
ExecuteTrajectory();
cout << "*PLUGIN FINISHED" << endl;
//draw the path
Draw();
//finish the loop
return true;
}
//getPath from last found goal as nearest neibhour, used to get path from reached tree
void getPath(){
//save in _path
_path.push_back(_nearestNode);
while(_nearestNode->getParent() != nullptr){
_nearestNode = _nearestNode->getParent();
_path.push_back(_nearestNode);
}
}
//Print config function
void printConfig(string s ,Config config){
cout << s <<" Config: " ;
for(size_t i = 0; i < 7 ; i++){
cout << config[i] << ' ';
}
cout << endl;
}
//getStringVector,used to read vector from python as string
vector<dReal> getStringVector(std::ostream& sout, std::istream& sinput){
vector<std::string> words;
string s;
ostringstream os;
os<<sinput.rdbuf();
s=os.str();
std::vector<dReal> goal_config;
boost::split(words, s, boost::is_any_of(", "), boost::token_compress_on);
for(int i=0; i<7; i++){
dReal num = atof(words.at(i).c_str());
goal_config.push_back(num);
}
return goal_config;
}
//check if config are in limits
bool checkConfigLimits(Config config){
/*
Lower Limits: Config: -0.564602 -0.3536 -2.12131 -2.00001 -10000 -2.00001 -10000
Upper Limits: Config: 2.13539 1.2963 -0.15 -0.1 10000 -0.1 10000
*/
int sum = 0;
for(size_t i = 0; i<7 ;i++){
if(config[i] < _upperLimit[i] && config[i] > _lowerLimit[i]){
sum++;
// cout << " i : " << i;
}
}
if(sum==7)
return true;
else
return false;
}
//generate random node
Config randomnodeGenerator(){
//generate random number
dReal bias= RaveRandomFloat();
Config temp_config = _goalConfig;
if(bias < GOAL_BIAS){
temp_config = _goalConfig;
}else{
do{
for (size_t i = 0; i < 7; ++i) {
temp_config[i] = static_cast<dReal>(bias*(_upperLimit[i] - _lowerLimit[i]) + _lowerLimit[i]);
bias = RaveRandomFloat();//change random configration next time <common sense , not so common :'D :| >
}
//check for validity
}while(CheckCollision(temp_config)||!inLimits(temp_config));
}
return temp_config;
}
//nearest node
boost::shared_ptr<RRTNode> NNNode(){
dReal temp_val = 0;
dReal min_val = 1000000;
dReal diff;
size_t range = _mainTree.getTreeSize();
vector< boost::shared_ptr<RRTNode> > temp_tree = _mainTree.getfullPath();
for(size_t i=0; i<range; i++){
Config temp_config = temp_tree[i]->getConfig();
for(size_t j=0; j<7; j++){
temp_val += pow((-temp_config[j] + _randomConfig[j])*_weight[j], 2);
}
temp_val = sqrt(temp_val);
diff = min_val - temp_val;
if(diff > 0){
min_val = temp_val;
_nearestNode = temp_tree[i];
_nearestNode->setUniqueId(i);
}
}
return _nearestNode;
}
//difference berween node and goal
dReal differenceCost(Config config){
dReal temp_val;
for(size_t j=0; j<7; j++){
temp_val += pow((-_goalConfig[j] + config[j]), 2);//*_weight[j]
}
temp_val = sqrt(temp_val);
return temp_val;
}
//difference between node and random config
dReal differencebetweenTwo(Config config){
dReal temp_val;
for(size_t j=0; j<7; j++){
temp_val += pow((-_randomConfig[j] + config[j]), 2);//*_weight[j]
}
temp_val = sqrt(temp_val);
return temp_val;
}
//find step size as vector in direcion toward random node from nearest node
Config step(){
Config temp_step = _randomConfig;
dReal magnitude = 0.0;
for(size_t i=0 ; i<7 ; i++){
temp_step[i] = _randomConfig[i] - _nearestNode->getConfig()[i];
}
for(size_t i=0; i<7; i++){
magnitude += pow(temp_step[i], 2.0);
}
magnitude = sqrt(magnitude);
for (size_t i = 0; i < 7; ++i) {
temp_step[i] = ((temp_step[i]) * delta_Q) / magnitude;
}
return temp_step;
}
//extend in the direction of nearest node
void EXTEND(int count){
string s;
//flag = 0;
Config temp_new_config = _nearestNode->getConfig();
do{
temp_new_config = _nearestNode->getConfig();
for(size_t i=0; i<7 ; i++){
temp_new_config[i] += _stepSize[i];
}
//if not in limits start over again
if(!inLimits(temp_new_config) || CheckCollision(temp_new_config)){
break;
}
_mainTree.nodeAdd(Node(new RRTNode(temp_new_config, _nearestNode)));
_nearestNode = _mainTree.getLast();
_diffConfig = differencebetweenTwo(temp_new_config);
if(_diffConfig < delta_Q){
_mainTree.nodeAdd(Node(new RRTNode(_randomConfig, _nearestNode)));
_diffGoal = differenceCost(_randomConfig);
if(_diffGoal < delta_Q){
_mainTree.nodeAdd(Node(new RRTNode(_goalConfig, _nearestNode)));
flag = 1;
break;
}
}
}while(!CheckCollision(temp_new_config) && inLimits(temp_new_config));// && checkConfigLimits(temp_new_config));
}
//check if config is in limit or not
bool inLimits(Config config){
for(size_t i=0; i<7; i++){
if(config[i] < _lowerLimit[i] || config[i] > _upperLimit[i]){
return false;
}
}
return true;
}
//check for collision
bool CheckCollision(Config config){
_robot->SetActiveDOFValues(config);
bool flag1 = _penv->CheckCollision(_robot);
//bool flag2 = _penv->CheckSelfCollision(_robot);
_robot->SetActiveDOFValues(_startConfig);
return flag1 ;//|| flag2;
}
//execute trajectory Refference : OpenRave Examples
void ExecuteTrajectory(){
EnvironmentMutex& lock = _penv->GetMutex();
lock.lock();
TrajectoryBasePtr traj = RaveCreateTrajectory(_penv);
traj->Init(_robot->GetActiveConfigurationSpecification());
for(size_t i=0; i< _path.size(); i++){
traj->Insert(0, _path[i]->getConfig());
}
traj->Insert(0, _startConfig);
// traj->Insert(0, _ggoalConfig);
planningutils::RetimeActiveDOFTrajectory(traj, _robot);
_robot->GetController()->SetPath(traj);
lock.unlock();
}
//Draw a point at the end effector position
void Draw(){
std::vector<float> endEffector;
float red[4] = {1,0,0,1};
for(size_t i=0 ; i<_path.size() ; i++ ){
_robot->SetActiveDOFValues(_path[i]->getConfig());
_robot->SetActiveManipulator("leftarm");
RobotBase::ManipulatorPtr hand;
hand = _robot->GetActiveManipulator();
RaveVector<dReal> point = hand->GetEndEffectorTransform().trans;
std::vector<float> endEffector;
endEffector.push_back(point.x);
endEffector.push_back(point.y);
endEffector.push_back(point.z);
handler.push_back(_penv->plot3(&endEffector[0],1,1,5,red,0,true));
}
}
private:
//openrave variables
vector<RobotBasePtr> _robots;
EnvironmentBasePtr _penv;
RobotBasePtr _robot;
Config _startConfig ;
Config _goalConfig;
Config _randomConfig; //get it from random generator
Config _lowerLimit;
Config _upperLimit;
Config _stepSize; //get from config
Config _extendConfig_new; //has new config from extend function
Config _weight; //weight matrix used while calculating cost
Config _ggoalConfig;
Node _startNode;
Node _nearestNode;
Node _extendNode_new;
Node _goalNode;
// Node _temp;
NodeTree _mainTree;
dReal _diffGoal;
dReal _diffConfig;
std::vector<GraphHandlePtr> handler;
size_t count;
vector< boost::shared_ptr<RRTNode> > _path;
};
// called to create a new plugin
InterfaceBasePtr CreateInterfaceValidated(InterfaceType type, const std::string& interfacename, std::istream& sinput, EnvironmentBasePtr penv)
{
if( type == PT_Module && interfacename == "rrtmodule" ) {
return InterfaceBasePtr(new RRTModule(penv,sinput));
}
return InterfaceBasePtr();
}
// called to query available plugins
void GetPluginAttributesValidated(PLUGININFO& info)
{
info.interfacenames[PT_Module].push_back("RRTModule");
}
// called before plugin is terminated
OPENRAVE_PLUGIN_API void DestroyPlugin()
{
}
| 28.552577 | 142 | 0.553871 | [
"vector"
] |
7c5e64447e7b54e18002b82ec3714a6738eee889 | 303 | cc | C++ | Tests/Base/Tie.cc | hung0913208/Base | 420b4ce8e08f9624b4e884039218ffd233b88335 | [
"BSD-3-Clause"
] | null | null | null | Tests/Base/Tie.cc | hung0913208/Base | 420b4ce8e08f9624b4e884039218ffd233b88335 | [
"BSD-3-Clause"
] | null | null | null | Tests/Base/Tie.cc | hung0913208/Base | 420b4ce8e08f9624b4e884039218ffd233b88335 | [
"BSD-3-Clause"
] | 2 | 2020-11-04T08:00:37.000Z | 2020-11-06T08:33:33.000Z | #include <Auto.h>
#include <Unittest.h>
#include <Utils.h>
TEST(Tie, Simple) {
Vector<Base::Auto> args;
Int a, b;
args.push_back(Base::Auto::As(1));
args.push_back(Base::Auto::As(2));
Base::Bond(a, b) = args;
EXPECT_EQ(a, 1);
EXPECT_EQ(b, 2);
}
int main() { return RUN_ALL_TESTS(); }
| 15.947368 | 38 | 0.617162 | [
"vector"
] |
7c624e5acfca91c077569f37a9a31e5a00bbbbc6 | 4,031 | hpp | C++ | include/bsl/ut_scenario.hpp | Bareflank/dynarray | 6509cfff948fa34b98585512d7be33a36e2f9522 | [
"MIT"
] | 52 | 2019-10-28T19:05:52.000Z | 2022-03-31T18:04:47.000Z | include/bsl/ut_scenario.hpp | Bareflank/dynarray | 6509cfff948fa34b98585512d7be33a36e2f9522 | [
"MIT"
] | 44 | 2019-11-01T16:53:36.000Z | 2022-02-24T07:52:08.000Z | include/bsl/ut_scenario.hpp | Bareflank/dynarray | 6509cfff948fa34b98585512d7be33a36e2f9522 | [
"MIT"
] | 5 | 2019-10-28T19:05:53.000Z | 2021-07-28T20:20:42.000Z | /// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// 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:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
///
/// @file ut_scenario.hpp
///
#ifndef BSL_UT_SCENARIO_HPP
#define BSL_UT_SCENARIO_HPP
#include "bsl/cstr_type.hpp"
#include "bsl/discard.hpp"
namespace bsl
{
/// @class bsl::ut_scenario
///
/// <!-- description -->
/// @brief Defines a unit test scenario. A scenario defines a user
/// story, describing the "scenario" being tested. A scenario
/// should be paired with ut_given, ut_when and ut_then to define
/// the scenario in english.
///
class ut_scenario final
{
public:
/// <!-- description -->
/// @brief Constructs a scenario
///
/// <!-- inputs/outputs -->
/// @param name the name of the scenario (i.e., test case)
///
explicit constexpr ut_scenario(cstr_type const name) noexcept
{
bsl::discard(name);
}
/// <!-- description -->
/// @brief Executes a lambda function as the body of the
/// scenario.
///
/// <!-- inputs/outputs -->
/// @tparam FUNC_T the type of lambda being executed
/// @param mut_func the lambda being executed
/// @return Returns a reference to the scenario.
///
template<typename FUNC_T>
[[maybe_unused]] constexpr auto
operator=(FUNC_T &&mut_func) &&noexcept -> ut_scenario &
{
mut_func();
return *this;
}
/// <!-- description -->
/// @brief Destroyes a previously created bsl::ut_scenario
///
constexpr ~ut_scenario() noexcept = default;
/// <!-- description -->
/// @brief copy constructor
///
/// <!-- inputs/outputs -->
/// @param o the object being copied
///
constexpr ut_scenario(ut_scenario const &o) noexcept = default;
/// <!-- description -->
/// @brief move constructor
///
/// <!-- inputs/outputs -->
/// @param mut_o the object being moved
///
constexpr ut_scenario(ut_scenario &&mut_o) noexcept = default;
/// <!-- description -->
/// @brief copy assignment
///
/// <!-- inputs/outputs -->
/// @param o the object being copied
/// @return a reference to *this
///
[[maybe_unused]] constexpr auto operator=(ut_scenario const &o) &noexcept
-> ut_scenario & = default;
/// <!-- description -->
/// @brief move assignment
///
/// <!-- inputs/outputs -->
/// @param mut_o the object being moved
/// @return a reference to *this
///
[[maybe_unused]] constexpr auto operator=(ut_scenario &&mut_o) &noexcept
-> ut_scenario & = default;
};
}
#endif
| 33.87395 | 81 | 0.589432 | [
"object"
] |
7c77e51a6f958ad67b4101672255f43459cb0899 | 906 | cpp | C++ | sources/chap01/ex05.cpp | ClazyChen/ds-lab | d7ce031bb1e22230be5687ac848e897a6d589ddf | [
"MIT"
] | 4 | 2022-03-12T14:42:21.000Z | 2022-03-30T02:09:55.000Z | sources/chap01/ex05.cpp | ClazyChen/ds-lab | d7ce031bb1e22230be5687ac848e897a6d589ddf | [
"MIT"
] | null | null | null | sources/chap01/ex05.cpp | ClazyChen/ds-lab | d7ce031bb1e22230be5687ac848e897a6d589ddf | [
"MIT"
] | 1 | 2022-03-29T18:17:55.000Z | 2022-03-29T18:17:55.000Z | #include <iostream>
#include <vector>
using namespace std;
// 这个例子展示角谷猜想
// 输入:正整数x
// 输出:对x反复进行操作:如果是奇数,乘3再加1;如果是偶数,除以2。直到x变为1为止。
// 目前的猜想是,任何整数都会通过若干次操作变为1,然后重复1、4、2的循环。
// 因此,角谷猜想的验证程序,是否满足有限性是一个未解决的问题
// 从而在严格的定义下,这不能够成为一个算法
class Collatz {
public:
vector<int> generate(int x) {
vector<int> result {x};
while (x > 1) { // 执行到x变为1为止
if (x % 2 == 1) {
result.push_back(x = 3*x + 1);
} else /* x % 2 == 0 */ {
result.push_back(x = x / 2);
}
}
return result;
}
};
Collatz collatz;
// 在这个例子中,您可以自己输入一个测试数据
// 您也可以仿照之前几个例子,改写成自动选取一些节点测试的形式
int main() {
int x;
// 对于int范围内的数据角谷猜想均正确
// 但对于较大的数,进行3x+1操作可能会出现溢出
cin >> x;
auto seq = collatz.generate(x);
cout << "sequence: " << endl;
for (int y : seq) {
cout << y << endl;
}
return 0;
}
| 20.590909 | 46 | 0.537528 | [
"vector"
] |
7c790db36cd3e6a322ff4027e37717b959299739 | 1,930 | cpp | C++ | src/z_subsystem_group.cpp | thekannman/z_terahertz | 3fdf2d42c1c7fb58757074527b43e0a33a059c22 | [
"MIT"
] | 2 | 2019-03-28T04:19:56.000Z | 2021-12-27T12:05:04.000Z | src/z_subsystem_group.cpp | thekannman/z_terahertz | 3fdf2d42c1c7fb58757074527b43e0a33a059c22 | [
"MIT"
] | null | null | null | src/z_subsystem_group.cpp | thekannman/z_terahertz | 3fdf2d42c1c7fb58757074527b43e0a33a059c22 | [
"MIT"
] | 1 | 2019-03-28T03:02:55.000Z | 2019-03-28T03:02:55.000Z | //Copyright (c) 2015 Zachary Kann
//
//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.
// ---
// Author: Zachary Kann
// Implementation of AtomGroup class. See include/z_atom_group.hpp for
// more details about the class.
#include "z_subsystem_group.hpp"
#include "z_molecule_group.hpp"
#include "z_atom_group.hpp"
#include "z_string.hpp"
#include "z_vec.hpp"
#include <algorithm>
SubsystemGroup* SubsystemGroup::MakeSubsystemGroup(
std::string name, std::vector<int> indices, const SystemGroup& all_atoms) {
std::vector<int> atom_count(all_atoms.num_molecules());
for (std::vector<int>::const_iterator i_index = indices.begin();
i_index != indices.end(); ++i_index) {
if (atom_count[all_atoms.index_to_molecule(*i_index)] > 0)
return new MoleculeGroup(name, indices, all_atoms);
atom_count[all_atoms.index_to_molecule(*i_index)]++;
}
return new AtomGroup(name, indices, all_atoms);
}
| 41.956522 | 80 | 0.757513 | [
"vector"
] |
7c794ee2ddac3e4305209afed481e921d16a9918 | 21,822 | cpp | C++ | 3.7.0/lldb-3.7.0.src/source/DataFormatters/ValueObjectPrinter.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | 3 | 2016-02-10T14:18:40.000Z | 2018-02-05T03:15:56.000Z | 3.7.0/lldb-3.7.0.src/source/DataFormatters/ValueObjectPrinter.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | 1 | 2016-02-10T15:40:03.000Z | 2016-02-10T15:40:03.000Z | 3.7.0/lldb-3.7.0.src/source/DataFormatters/ValueObjectPrinter.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | null | null | null | //===-- ValueObjectPrinter.cpp -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/DataFormatters/ValueObjectPrinter.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Core/Debugger.h"
#include "lldb/DataFormatters/DataVisualization.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Target/Target.h"
using namespace lldb;
using namespace lldb_private;
DumpValueObjectOptions::DumpValueObjectOptions (ValueObject& valobj) :
DumpValueObjectOptions()
{
m_use_dynamic = valobj.GetDynamicValueType();
m_use_synthetic = valobj.IsSynthetic();
}
ValueObjectPrinter::ValueObjectPrinter (ValueObject* valobj,
Stream* s)
{
if (valobj)
{
DumpValueObjectOptions options(*valobj);
Init (valobj,s,options,options.m_max_ptr_depth,0);
}
else
{
DumpValueObjectOptions options;
Init (valobj,s,options,options.m_max_ptr_depth,0);
}
}
ValueObjectPrinter::ValueObjectPrinter (ValueObject* valobj,
Stream* s,
const DumpValueObjectOptions& options)
{
Init(valobj,s,options,options.m_max_ptr_depth,0);
}
ValueObjectPrinter::ValueObjectPrinter (ValueObject* valobj,
Stream* s,
const DumpValueObjectOptions& options,
uint32_t ptr_depth,
uint32_t curr_depth)
{
Init(valobj,s,options,ptr_depth,curr_depth);
}
void
ValueObjectPrinter::Init (ValueObject* valobj,
Stream* s,
const DumpValueObjectOptions& options,
uint32_t ptr_depth,
uint32_t curr_depth)
{
m_orig_valobj = valobj;
m_valobj = nullptr;
m_stream = s;
this->options = options;
m_ptr_depth = ptr_depth;
m_curr_depth = curr_depth;
assert (m_orig_valobj && "cannot print a NULL ValueObject");
assert (m_stream && "cannot print to a NULL Stream");
m_should_print = eLazyBoolCalculate;
m_is_nil = eLazyBoolCalculate;
m_is_ptr = eLazyBoolCalculate;
m_is_ref = eLazyBoolCalculate;
m_is_aggregate = eLazyBoolCalculate;
m_summary_formatter = {nullptr,false};
m_value.assign("");
m_summary.assign("");
m_error.assign("");
}
bool
ValueObjectPrinter::PrintValueObject ()
{
if (!GetMostSpecializedValue () || m_valobj == nullptr)
return false;
if (ShouldPrintValueObject())
{
PrintValidationMarkerIfNeeded();
PrintLocationIfNeeded();
m_stream->Indent();
bool show_type = PrintTypeIfNeeded();
PrintNameIfNeeded(show_type);
}
bool value_printed = false;
bool summary_printed = false;
bool val_summary_ok = PrintValueAndSummaryIfNeeded (value_printed,summary_printed);
if (val_summary_ok)
PrintChildrenIfNeeded (value_printed, summary_printed);
else
m_stream->EOL();
PrintValidationErrorIfNeeded();
return true;
}
bool
ValueObjectPrinter::GetMostSpecializedValue ()
{
if (m_valobj)
return true;
bool update_success = m_orig_valobj->UpdateValueIfNeeded (true);
if (!update_success)
{
m_valobj = m_orig_valobj;
}
else
{
if (m_orig_valobj->IsDynamic())
{
if (options.m_use_dynamic == eNoDynamicValues)
{
ValueObject *static_value = m_orig_valobj->GetStaticValue().get();
if (static_value)
m_valobj = static_value;
else
m_valobj = m_orig_valobj;
}
else
m_valobj = m_orig_valobj;
}
else
{
if (options.m_use_dynamic != eNoDynamicValues)
{
ValueObject *dynamic_value = m_orig_valobj->GetDynamicValue(options.m_use_dynamic).get();
if (dynamic_value)
m_valobj = dynamic_value;
else
m_valobj = m_orig_valobj;
}
else
m_valobj = m_orig_valobj;
}
if (m_valobj->IsSynthetic())
{
if (options.m_use_synthetic == false)
{
ValueObject *non_synthetic = m_valobj->GetNonSyntheticValue().get();
if (non_synthetic)
m_valobj = non_synthetic;
}
}
else
{
if (options.m_use_synthetic == true)
{
ValueObject *synthetic = m_valobj->GetSyntheticValue().get();
if (synthetic)
m_valobj = synthetic;
}
}
}
m_clang_type = m_valobj->GetClangType();
m_type_flags = m_clang_type.GetTypeInfo ();
return true;
}
const char*
ValueObjectPrinter::GetDescriptionForDisplay ()
{
const char* str = m_valobj->GetObjectDescription();
if (!str)
str = m_valobj->GetSummaryAsCString();
if (!str)
str = m_valobj->GetValueAsCString();
return str;
}
const char*
ValueObjectPrinter::GetRootNameForDisplay (const char* if_fail)
{
const char *root_valobj_name = options.m_root_valobj_name.empty() ?
m_valobj->GetName().AsCString() :
options.m_root_valobj_name.c_str();
return root_valobj_name ? root_valobj_name : if_fail;
}
bool
ValueObjectPrinter::ShouldPrintValueObject ()
{
if (m_should_print == eLazyBoolCalculate)
m_should_print = (options.m_flat_output == false || m_type_flags.Test (eTypeHasValue)) ? eLazyBoolYes : eLazyBoolNo;
return m_should_print == eLazyBoolYes;
}
bool
ValueObjectPrinter::IsNil ()
{
if (m_is_nil == eLazyBoolCalculate)
m_is_nil = m_valobj->IsObjCNil() ? eLazyBoolYes : eLazyBoolNo;
return m_is_nil == eLazyBoolYes;
}
bool
ValueObjectPrinter::IsPtr ()
{
if (m_is_ptr == eLazyBoolCalculate)
m_is_ptr = m_type_flags.Test (eTypeIsPointer) ? eLazyBoolYes : eLazyBoolNo;
return m_is_ptr == eLazyBoolYes;
}
bool
ValueObjectPrinter::IsRef ()
{
if (m_is_ref == eLazyBoolCalculate)
m_is_ref = m_type_flags.Test (eTypeIsReference) ? eLazyBoolYes : eLazyBoolNo;
return m_is_ref == eLazyBoolYes;
}
bool
ValueObjectPrinter::IsAggregate ()
{
if (m_is_aggregate == eLazyBoolCalculate)
m_is_aggregate = m_type_flags.Test (eTypeHasChildren) ? eLazyBoolYes : eLazyBoolNo;
return m_is_aggregate == eLazyBoolYes;
}
bool
ValueObjectPrinter::PrintLocationIfNeeded ()
{
if (options.m_show_location)
{
m_stream->Printf("%s: ", m_valobj->GetLocationAsCString());
return true;
}
return false;
}
bool
ValueObjectPrinter::PrintTypeIfNeeded ()
{
bool show_type = true;
// if we are at the root-level and been asked to hide the root's type, then hide it
if (m_curr_depth == 0 && options.m_hide_root_type)
show_type = false;
else
// otherwise decide according to the usual rules (asked to show types - always at the root level)
show_type = options.m_show_types || (m_curr_depth == 0 && !options.m_flat_output);
if (show_type)
{
// Some ValueObjects don't have types (like registers sets). Only print
// the type if there is one to print
ConstString type_name;
if (options.m_use_type_display_name)
type_name = m_valobj->GetDisplayTypeName();
else
type_name = m_valobj->GetQualifiedTypeName();
if (type_name)
m_stream->Printf("(%s) ", type_name.GetCString());
else
show_type = false;
}
return show_type;
}
bool
ValueObjectPrinter::PrintNameIfNeeded (bool show_type)
{
if (options.m_flat_output)
{
// If we are showing types, also qualify the C++ base classes
const bool qualify_cxx_base_classes = show_type;
if (!options.m_hide_name)
{
m_valobj->GetExpressionPath(*m_stream, qualify_cxx_base_classes);
m_stream->PutCString(" =");
return true;
}
}
else if (!options.m_hide_name)
{
const char *name_cstr = GetRootNameForDisplay("");
m_stream->Printf ("%s =", name_cstr);
return true;
}
return false;
}
bool
ValueObjectPrinter::CheckScopeIfNeeded ()
{
if (options.m_scope_already_checked)
return true;
return m_valobj->IsInScope();
}
TypeSummaryImpl*
ValueObjectPrinter::GetSummaryFormatter ()
{
if (m_summary_formatter.second == false)
{
TypeSummaryImpl* entry = options.m_summary_sp ? options.m_summary_sp.get() : m_valobj->GetSummaryFormat().get();
if (options.m_omit_summary_depth > 0)
entry = NULL;
m_summary_formatter.first = entry;
m_summary_formatter.second = true;
}
return m_summary_formatter.first;
}
void
ValueObjectPrinter::GetValueSummaryError (std::string& value,
std::string& summary,
std::string& error)
{
if (options.m_format != eFormatDefault && options.m_format != m_valobj->GetFormat())
{
m_valobj->GetValueAsCString(options.m_format,
value);
}
else
{
const char* val_cstr = m_valobj->GetValueAsCString();
if (val_cstr)
value.assign(val_cstr);
}
const char* err_cstr = m_valobj->GetError().AsCString();
if (err_cstr)
error.assign(err_cstr);
if (ShouldPrintValueObject())
{
if (IsNil())
summary.assign("nil");
else if (options.m_omit_summary_depth == 0)
{
TypeSummaryImpl* entry = GetSummaryFormatter();
if (entry)
m_valobj->GetSummaryAsCString(entry, summary);
else
{
const char* sum_cstr = m_valobj->GetSummaryAsCString();
if (sum_cstr)
summary.assign(sum_cstr);
}
}
}
}
bool
ValueObjectPrinter::PrintValueAndSummaryIfNeeded (bool& value_printed,
bool& summary_printed)
{
bool error_printed = false;
if (ShouldPrintValueObject())
{
if (!CheckScopeIfNeeded())
m_error.assign("out of scope");
if (m_error.empty())
{
GetValueSummaryError(m_value, m_summary, m_error);
}
if (m_error.size())
{
error_printed = true;
m_stream->Printf (" <%s>\n", m_error.c_str());
}
else
{
// Make sure we have a value and make sure the summary didn't
// specify that the value should not be printed - and do not print
// the value if this thing is nil
// (but show the value if the user passes a format explicitly)
TypeSummaryImpl* entry = GetSummaryFormatter();
if (!IsNil() && !m_value.empty() && (entry == NULL || (entry->DoesPrintValue(m_valobj) || options.m_format != eFormatDefault) || m_summary.empty()) && !options.m_hide_value)
{
m_stream->Printf(" %s", m_value.c_str());
value_printed = true;
}
if (m_summary.size())
{
m_stream->Printf(" %s", m_summary.c_str());
summary_printed = true;
}
}
}
return !error_printed;
}
bool
ValueObjectPrinter::PrintObjectDescriptionIfNeeded (bool value_printed,
bool summary_printed)
{
if (ShouldPrintValueObject())
{
// let's avoid the overly verbose no description error for a nil thing
if (options.m_use_objc && !IsNil())
{
if (!options.m_hide_value || !options.m_hide_name)
m_stream->Printf(" ");
const char *object_desc = nullptr;
if (value_printed || summary_printed)
object_desc = m_valobj->GetObjectDescription();
else
object_desc = GetDescriptionForDisplay();
if (object_desc && *object_desc)
{
m_stream->Printf("%s\n", object_desc);
return true;
}
else if (value_printed == false && summary_printed == false)
return true;
else
return false;
}
}
return true;
}
bool
ValueObjectPrinter::ShouldPrintChildren (bool is_failed_description,
uint32_t& curr_ptr_depth)
{
const bool is_ref = IsRef ();
const bool is_ptr = IsPtr ();
if (is_failed_description || m_curr_depth < options.m_max_depth)
{
// We will show children for all concrete types. We won't show
// pointer contents unless a pointer depth has been specified.
// We won't reference contents unless the reference is the
// root object (depth of zero).
// Use a new temporary pointer depth in case we override the
// current pointer depth below...
if (is_ptr || is_ref)
{
// We have a pointer or reference whose value is an address.
// Make sure that address is not NULL
AddressType ptr_address_type;
if (m_valobj->GetPointerValue (&ptr_address_type) == 0)
return false;
else if (is_ref && m_curr_depth == 0 && curr_ptr_depth == 0)
{
// If this is the root object (depth is zero) that we are showing
// and it is a reference, and no pointer depth has been supplied
// print out what it references. Don't do this at deeper depths
// otherwise we can end up with infinite recursion...
curr_ptr_depth = 1;
}
return (curr_ptr_depth > 0);
}
TypeSummaryImpl* entry = GetSummaryFormatter();
return (!entry || entry->DoesPrintChildren(m_valobj) || m_summary.empty());
}
return false;
}
ValueObject*
ValueObjectPrinter::GetValueObjectForChildrenGeneration ()
{
return m_valobj;
}
void
ValueObjectPrinter::PrintChildrenPreamble ()
{
if (options.m_flat_output)
{
if (ShouldPrintValueObject())
m_stream->EOL();
}
else
{
if (ShouldPrintValueObject())
m_stream->PutCString(IsRef () ? ": {\n" : " {\n");
m_stream->IndentMore();
}
}
void
ValueObjectPrinter::PrintChild (ValueObjectSP child_sp,
uint32_t curr_ptr_depth)
{
DumpValueObjectOptions child_options(options);
child_options.SetFormat(options.m_format).SetSummary().SetRootValueObjectName();
child_options.SetScopeChecked(true).SetHideName(options.m_hide_name).SetHideValue(options.m_hide_value)
.SetOmitSummaryDepth(child_options.m_omit_summary_depth > 1 ? child_options.m_omit_summary_depth - 1 : 0);
if (child_sp.get())
{
ValueObjectPrinter child_printer(child_sp.get(),
m_stream,
child_options,
(IsPtr() || IsRef()) && curr_ptr_depth >= 1 ? curr_ptr_depth - 1 : curr_ptr_depth,
m_curr_depth + 1);
child_printer.PrintValueObject();
}
}
uint32_t
ValueObjectPrinter::GetMaxNumChildrenToPrint (bool& print_dotdotdot)
{
ValueObject* synth_m_valobj = GetValueObjectForChildrenGeneration();
size_t num_children = synth_m_valobj->GetNumChildren();
print_dotdotdot = false;
if (num_children)
{
const size_t max_num_children = m_valobj->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
if (num_children > max_num_children && !options.m_ignore_cap)
{
print_dotdotdot = true;
return max_num_children;
}
}
return num_children;
}
void
ValueObjectPrinter::PrintChildrenPostamble (bool print_dotdotdot)
{
if (!options.m_flat_output)
{
if (print_dotdotdot)
{
m_valobj->GetTargetSP()->GetDebugger().GetCommandInterpreter().ChildrenTruncated();
m_stream->Indent("...\n");
}
m_stream->IndentLess();
m_stream->Indent("}\n");
}
}
void
ValueObjectPrinter::PrintChildren (uint32_t curr_ptr_depth)
{
ValueObject* synth_m_valobj = GetValueObjectForChildrenGeneration();
bool print_dotdotdot = false;
size_t num_children = GetMaxNumChildrenToPrint(print_dotdotdot);
if (num_children)
{
PrintChildrenPreamble ();
for (size_t idx=0; idx<num_children; ++idx)
{
ValueObjectSP child_sp(synth_m_valobj->GetChildAtIndex(idx, true));
PrintChild (child_sp, curr_ptr_depth);
}
PrintChildrenPostamble (print_dotdotdot);
}
else if (IsAggregate())
{
// Aggregate, no children...
if (ShouldPrintValueObject())
{
// if it has a synthetic value, then don't print {}, the synthetic children are probably only being used to vend a value
if (m_valobj->DoesProvideSyntheticValue())
m_stream->PutCString( "\n");
else
m_stream->PutCString(" {}\n");
}
}
else
{
if (ShouldPrintValueObject())
m_stream->EOL();
}
}
bool
ValueObjectPrinter::PrintChildrenOneLiner (bool hide_names)
{
if (!GetMostSpecializedValue () || m_valobj == nullptr)
return false;
ValueObject* synth_m_valobj = GetValueObjectForChildrenGeneration();
bool print_dotdotdot = false;
size_t num_children = GetMaxNumChildrenToPrint(print_dotdotdot);
if (num_children)
{
m_stream->PutChar('(');
for (uint32_t idx=0; idx<num_children; ++idx)
{
lldb::ValueObjectSP child_sp(synth_m_valobj->GetChildAtIndex(idx, true));
if (child_sp)
child_sp = child_sp->GetQualifiedRepresentationIfAvailable(options.m_use_dynamic, options.m_use_synthetic);
if (child_sp)
{
if (idx)
m_stream->PutCString(", ");
if (!hide_names)
{
const char* name = child_sp.get()->GetName().AsCString();
if (name && *name)
{
m_stream->PutCString(name);
m_stream->PutCString(" = ");
}
}
child_sp->DumpPrintableRepresentation(*m_stream,
ValueObject::eValueObjectRepresentationStyleSummary,
lldb::eFormatInvalid,
ValueObject::ePrintableRepresentationSpecialCasesDisable);
}
}
if (print_dotdotdot)
m_stream->PutCString(", ...)");
else
m_stream->PutChar(')');
}
return true;
}
void
ValueObjectPrinter::PrintChildrenIfNeeded (bool value_printed,
bool summary_printed)
{
// this flag controls whether we tried to display a description for this object and failed
// if that happens, we want to display the children, if any
bool is_failed_description = !PrintObjectDescriptionIfNeeded(value_printed, summary_printed);
uint32_t curr_ptr_depth = m_ptr_depth;
bool print_children = ShouldPrintChildren (is_failed_description,curr_ptr_depth);
bool print_oneline = (curr_ptr_depth > 0 ||
options.m_show_types ||
!options.m_allow_oneliner_mode ||
options.m_flat_output ||
options.m_show_location) ? false : DataVisualization::ShouldPrintAsOneLiner(*m_valobj);
if (print_children)
{
if (print_oneline)
{
m_stream->PutChar(' ');
PrintChildrenOneLiner (false);
m_stream->EOL();
}
else
PrintChildren (curr_ptr_depth);
}
else if (m_curr_depth >= options.m_max_depth && IsAggregate() && ShouldPrintValueObject())
{
m_stream->PutCString("{...}\n");
}
else
m_stream->EOL();
}
bool
ValueObjectPrinter::ShouldPrintValidation ()
{
return options.m_run_validator;
}
bool
ValueObjectPrinter::PrintValidationMarkerIfNeeded ()
{
if (!ShouldPrintValidation())
return false;
m_validation = m_valobj->GetValidationStatus();
if (TypeValidatorResult::Failure == m_validation.first)
{
m_stream->Printf("! ");
return true;
}
return false;
}
bool
ValueObjectPrinter::PrintValidationErrorIfNeeded ()
{
if (!ShouldPrintValidation())
return false;
if (TypeValidatorResult::Success == m_validation.first)
return false;
if (m_validation.second.empty())
m_validation.second.assign("unknown error");
m_stream->Printf(" ! validation error: %s", m_validation.second.c_str());
m_stream->EOL();
return true;
}
| 30.266297 | 185 | 0.581248 | [
"object"
] |
75adef17f4301a0ea4cf7cc9e998f53f386cfd21 | 137 | cpp | C++ | src/projectiles/projectileAssets.cpp | dannyoboy/HurtEngine | 858412502ba97e38e424ff69d51dfdd3d5ad125b | [
"MIT"
] | null | null | null | src/projectiles/projectileAssets.cpp | dannyoboy/HurtEngine | 858412502ba97e38e424ff69d51dfdd3d5ad125b | [
"MIT"
] | null | null | null | src/projectiles/projectileAssets.cpp | dannyoboy/HurtEngine | 858412502ba97e38e424ff69d51dfdd3d5ad125b | [
"MIT"
] | null | null | null | #include "projectileAssets.h"
Mesh * bulletMesh = nullptr;
Material * bulletMaterial = nullptr;
Material * cannonballMaterial = nullptr; | 27.4 | 40 | 0.781022 | [
"mesh"
] |
75bdc0144cfac1297cd35a32610950ac3f0a7893 | 1,819 | cpp | C++ | soj/1687.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | soj/1687.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | soj/1687.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct Edge
{
int from,to;
int d;
Edge(int from, int to, int d) {this->from=from; this->to=to; this->d=d;}
};
const int INF = 0x7fffffff;
const int maxn = 50010;
int n,st,ed;
int dis[maxn];
int cnt[maxn];
bool vis[maxn];
vector<Edge> edges;
vector<int> g[maxn];
void init()
{
for (int i=0;i<=50000;i++)
g[i].clear();
edges.clear();
}
void addEdge(int from,int to,int d)
{
edges.push_back(Edge(from,to,d));
int t=edges.size();
g[from].push_back(t-1);
}
void spfa()
{
for (int i=st;i<=ed;i++)
dis[i]=INF;
dis[st]=0;
for (int i=st;i<=ed;i++)
vis[i]=0;
for (int i=st;i<=ed;i++)
cnt[i]=0;
queue<int> Q;
while (!Q.empty()) Q.pop();
Q.push(st);
vis[st]=1;
cnt[st]=1;
while (!Q.empty())
{
int u = Q.front();
for(unsigned int i=0;i<g[u].size();i++)
{
Edge &e=edges[g[u][i]];
if (dis[e.to]==INF || dis[u]+e.d>dis[e.to])
{
dis[e.to]=dis[u]+e.d;
if(!vis[e.to])
{
Q.push(e.to);
vis[e.to]=1;
cnt[e.to]++;
}
}
}
Q.pop();
vis[u]=0;
}
}
int main()
{
int a,b,c;
while (scanf("%d",&n)==1)
{
init();
st=INF; ed=-INF;
for (int i=1;i<=n;i++)
{
scanf("%d%d%d",&a,&b,&c);
addEdge(a,b+1,c);
if (a<st) st=a;
if (b+1>ed) ed=b+1;
}
for (int i=st;i<ed;i++)
{
addEdge(i,i+1,0);
addEdge(i+1,i,-1);
}
spfa();
printf("%d\n",dis[ed]);
}
return 0;
} | 18.947917 | 76 | 0.418362 | [
"vector"
] |
75c2d520de0575b97ee180f4c333a9b6c05eb7ad | 1,525 | cpp | C++ | interfaces/native_cpp/nfc_standard/test/nfc_ce_gtestcase/src/test_nfc_ce_host_service.cpp | dawmlight/communication_nfc | 84a10d69eb9cb3128e864230c53d5a5e6660dfb9 | [
"Apache-2.0"
] | null | null | null | interfaces/native_cpp/nfc_standard/test/nfc_ce_gtestcase/src/test_nfc_ce_host_service.cpp | dawmlight/communication_nfc | 84a10d69eb9cb3128e864230c53d5a5e6660dfb9 | [
"Apache-2.0"
] | null | null | null | interfaces/native_cpp/nfc_standard/test/nfc_ce_gtestcase/src/test_nfc_ce_host_service.cpp | dawmlight/communication_nfc | 84a10d69eb9cb3128e864230c53d5a5e6660dfb9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2021 Huawei Device 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.
*/
#include "test_nfc_ce_host_service.h"
#include "loghelper.h"
namespace OHOS::nfc::test {
TestNfcCEHostService::TestNfcCEHostService() {}
std::vector<unsigned char> TestNfcCEHostService::HandleApdu(const std::vector<unsigned char>& apdu)
{
return apduExpectionCB_(apdu);
}
void TestNfcCEHostService::OnDeactivated(int reason)
{
DebugLog("reason: %d\n", reason);
}
void TestNfcCEHostService::SetApduExpection(std::function<std::vector<unsigned char>(std::vector<unsigned char>)> f)
{
apduExpectionCB_ = std::move(f);
}
bool TestNfcCEHostService::IsApduBeginWith(const std::vector<unsigned char>& apduCmd,
const std::vector<unsigned char>& prefix)
{
if (apduCmd.size() < prefix.size()) {
return false;
}
return std::equal(apduCmd.cbegin(), apduCmd.cbegin() + prefix.size(), prefix.cbegin(), prefix.cend());
}
} // namespace OHOS::nfc::test
| 34.659091 | 116 | 0.707541 | [
"vector"
] |
75c555af1f98842108998f66e67f5d023d784048 | 2,105 | cc | C++ | leetcode/ds_graph_clone_graph.cc | prashrock/C- | 3ed46815d40b3e42cd9f36d23c8ee2a9de742323 | [
"MIT"
] | 1 | 2016-12-05T10:42:46.000Z | 2016-12-05T10:42:46.000Z | leetcode/ds_graph_clone_graph.cc | prashrock/CPP | 3ed46815d40b3e42cd9f36d23c8ee2a9de742323 | [
"MIT"
] | null | null | null | leetcode/ds_graph_clone_graph.cc | prashrock/CPP | 3ed46815d40b3e42cd9f36d23c8ee2a9de742323 | [
"MIT"
] | null | null | null | //g++-5 --std=c++11 -g -Wall -Werror -o ds_graph_clone_graph ds_graph_clone_graph.cc
/**
* @file Clone Graph
* @brief Given an undirected graph, clone (deep copy) it
*/
// https://leetcode.com/problems/clone-graph/
#include <iostream> /* std::cout */
#include <algorithm> /* std::max */
#include <vector> /* std::vector */
#include <unordered_map> /* std::unordered_map container */
using namespace std;
/*
* Clone an undirected graph. Each node in the graph contains
* a label and a list of its neighbors.
* OJ's undirected graph serialization:
* Nodes are labeled uniquely.
* We use # as a separator for each node, and , as a separator
* for node label and each neighbor of the node.
* As an example, consider the serialized graph {0,1,2#1,2#2,2}.
* The graph has a total of three nodes, and therefore contains
* three parts as separated by #.
* First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
* Second node is labeled as 1. Connect node 1 to node 2.
* Third node is labeled as 2. Connect node 2 to node 2 (itself),
* thus forming a self-cycle. Visually, the graph looks like the following:
*
* 1
* / \
* / \
* 0 --- 2
* / \
* \_/
*/
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
std::unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> clones;
/* DFS based recursive approach to clone an undirected graph */
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == nullptr) return nullptr;
/* If we have not seen this node before, explore all neighbors */
if(clones.find(node) == clones.end()) {
auto cln = clones[node] = new UndirectedGraphNode(node->label);
for(auto x : node->neighbors) {
cln->neighbors.push_back(cloneGraph(x));
}
}
return clones[node];
}
int main() {
cout << "Info: Test cases yet to be implemented." << endl;
return 0;
}
| 32.890625 | 84 | 0.631354 | [
"vector"
] |
75c5e451333bfd517bcf6da125b365f64f680018 | 789 | cpp | C++ | week7/w7d1/sortk.cpp | ash20012003/IPMPRepo | 3d288e8ab1c1a25113c45e983da7f7e780ff66d4 | [
"MIT"
] | 2 | 2021-11-13T05:41:49.000Z | 2022-02-06T16:12:56.000Z | week7/w7d1/sortk.cpp | ash20012003/IPMPRepo | 3d288e8ab1c1a25113c45e983da7f7e780ff66d4 | [
"MIT"
] | null | null | null | week7/w7d1/sortk.cpp | ash20012003/IPMPRepo | 3d288e8ab1c1a25113c45e983da7f7e780ff66d4 | [
"MIT"
] | null | null | null | void sortk(int nums[], int k, int n) {
priority_queue<int, vector<int>, greater<int> > gq(nums,nums+k+1);
vector<int> ans;
int index = 0;
for (int i = k + 1; i < n; i++) {
// ans.push_back(gq.top());
nums[index++] = gq.top();
gq.pop();
gq.push(nums[i]);
}
while (gq.empty() == false) {
//ans.push_back(gq.top());
nums[index++] = gq.top();
gq.pop();
}
for (int j = 0; j < n; j++) cout << nums[j]<<" ";
}
/*
Construct min heap with first k elements
pop the heap and make it the index th element
push the next element of the array into the heap
automatically, heap gets heapified as we are using stl
There will still be some elements in the heap, so keep poping the heap and insert it into the array
*/
| 29.222222 | 99 | 0.580482 | [
"vector"
] |
75c669770931e94fd645e14ab781ec5ba41fcf87 | 5,416 | cpp | C++ | TRAP/src/Graphics/API/Vulkan/Internals/Objects/VulkanRenderPass.cpp | GamesTrap/TRAP | 007de9ce70273cb8ae11066cc8488d9db78b1038 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2018-06-23T18:18:19.000Z | 2019-05-27T21:10:07.000Z | TRAP/src/Graphics/API/Vulkan/Internals/Objects/VulkanRenderPass.cpp | GamesTrap/TRAP | 007de9ce70273cb8ae11066cc8488d9db78b1038 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | 88 | 2018-08-02T01:08:04.000Z | 2019-07-24T19:13:26.000Z | TRAP/src/Graphics/API/Vulkan/Internals/Objects/VulkanRenderPass.cpp | GamesTrap/TRAP | 007de9ce70273cb8ae11066cc8488d9db78b1038 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2018-08-02T01:10:40.000Z | 2020-08-14T14:05:58.000Z | #include "TRAPPCH.h"
#include "VulkanRenderPass.h"
#include "VulkanDevice.h"
#include "Graphics/API/Vulkan/VulkanCommon.h"
#include "Graphics/API/Vulkan/Internals/VulkanInitializers.h"
#include "VulkanSurface.h"
#include "Graphics/API/Vulkan/VulkanRenderer.h"
#include "VulkanCommandBuffer.h"
#include "VulkanSwapchain.h"
TRAP::Graphics::API::Vulkan::RenderPass::RenderPass(const Scope<Device>& device, Surface& surface)
: m_renderPass(), m_device(device.get()), m_clearValues({ {{{0.1f, 0.1f, 0.1f, 1.0f}}} }), m_recording(false)
{
//std::vector<VkAttachmentDescription> attachments(2);
std::vector<VkAttachmentDescription> attachments(1);
//Color attachment
attachments[0].flags = 0;
attachments[0].format = surface.GetOptimalSurfaceFormat().format;
attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
//Depth attachment
/*attachments[1].flags = 0;
attachments[1].format = *surface.GetOptimalDepthFormat();
attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;*/
VkAttachmentReference colorReference
{
0,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
};
/*VkAttachmentReference depthReference
{
1,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
};*/
VkSubpassDescription subPassDescription
{
0,
VK_PIPELINE_BIND_POINT_GRAPHICS,
0,
nullptr,
1,
&colorReference,
nullptr,
//&depthReference,
nullptr,
0,
nullptr
};
//SubPass dependencies for layout transitions
std::vector<VkSubpassDependency> dependencies(1);
//std::vector<VkSubpassDependency> dependencies(2);
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].srcAccessMask = 0;
dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[0].dependencyFlags = 0;
VkRenderPassCreateInfo info = Initializers::RenderPassCreateInfo(attachments, subPassDescription, dependencies);
VkCall(vkCreateRenderPass(m_device->GetDevice(), &info, nullptr, &m_renderPass));
}
//-------------------------------------------------------------------------------------------------------------------//
TRAP::Graphics::API::Vulkan::RenderPass::~RenderPass()
{
if(m_renderPass)
{
vkDestroyRenderPass(m_device->GetDevice(), m_renderPass, nullptr);
m_renderPass = nullptr;
}
}
//-------------------------------------------------------------------------------------------------------------------//
VkRenderPass& TRAP::Graphics::API::Vulkan::RenderPass::GetRenderPass()
{
return m_renderPass;
}
//-------------------------------------------------------------------------------------------------------------------//
void TRAP::Graphics::API::Vulkan::RenderPass::SetClearColor(const VkClearColorValue& color)
{
m_clearValues[0].color = color;
}
//-------------------------------------------------------------------------------------------------------------------//
void TRAP::Graphics::API::Vulkan::RenderPass::StartRenderPass(const Scope<CommandBuffer>& graphicsCommandBuffer)
{
if (!m_recording)
{
VkRenderPassBeginInfo renderPassBeginInfo = Initializers::RenderPassBeginInfo(m_renderPass,
VulkanRenderer::GetCurrentSwapchain().GetFrameBuffers()[VulkanRenderer::GetCurrentSwapchain().GetCurrentFrameBufferIndex()],
VulkanRenderer::GetCurrentSwapchain().GetExtent().width,
VulkanRenderer::GetCurrentSwapchain().GetExtent().height,
m_clearValues);
vkCmdBeginRenderPass(graphicsCommandBuffer->GetCommandBuffer(), &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
m_recording = true;
}
}
//-------------------------------------------------------------------------------------------------------------------//
void TRAP::Graphics::API::Vulkan::RenderPass::StartRenderPass(const Scope<Swapchain>& swapchain, CommandBuffer& graphicsCommandBuffer)
{
if (swapchain && !m_recording)
{
VkRenderPassBeginInfo renderPassBeginInfo = Initializers::RenderPassBeginInfo(m_renderPass,
swapchain->GetFrameBuffers()[swapchain->GetCurrentFrameBufferIndex()],
swapchain->GetExtent().width,
swapchain->GetExtent().height,
m_clearValues);
vkCmdBeginRenderPass(graphicsCommandBuffer.GetCommandBuffer(), &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
m_recording = true;
}
}
//-------------------------------------------------------------------------------------------------------------------//
void TRAP::Graphics::API::Vulkan::RenderPass::EndRenderPass(const Scope<CommandBuffer>& graphicsCommandBuffer)
{
if(m_recording)
{
vkCmdEndRenderPass(graphicsCommandBuffer->GetCommandBuffer());
m_recording = false;
}
} | 35.168831 | 134 | 0.687223 | [
"vector"
] |
75c8ca14d0bd9668cbe4d56fbaaba8be4f388ca0 | 690 | cpp | C++ | Homeworks/2_ImageWarping/myproject/src/App/Warp.cpp | SqrtiZhang/CG | 462415eea0af981797172281a023066ff557a33a | [
"MIT"
] | 5 | 2021-06-02T02:41:48.000Z | 2022-02-09T09:56:10.000Z | Homeworks/2_ImageWarping/myproject/src/App/Warp.cpp | SqrtiZhang/CG | 462415eea0af981797172281a023066ff557a33a | [
"MIT"
] | null | null | null | Homeworks/2_ImageWarping/myproject/src/App/Warp.cpp | SqrtiZhang/CG | 462415eea0af981797172281a023066ff557a33a | [
"MIT"
] | 1 | 2022-01-06T11:22:14.000Z | 2022-01-06T11:22:14.000Z | #include "Warp.h"
Warp::Warp()
{
}
Warp::~Warp()
{
}
double Warp::get_distance(QPoint p1, QPoint p2)
{
return qSqrt((p1.x() - p2.x())*(p1.x() - p2.x()) + (p1.y() - p2.y())*(p1.y() - p2.y()));
}
void Warp::set_s(QPoint s)
{
this->start_point=s;
}
void Warp::set_q(vector<QPoint> q_)
{
for(int i=0;i<q_.size();i++)
{
QPoint temp;
temp=q_[i];
this->q_.push_back(QPoint(temp.x()-start_point.x(),temp.y()-start_point.y()));
}
}
void Warp::set_p(vector<QPoint> p_)
{
for(int i=0;i<p_.size();i++)
{
QPoint temp;
temp=p_[i];
this->p_.push_back(QPoint(temp.x()-start_point.x(),temp.y()-start_point.y()));
}
}
| 15.681818 | 92 | 0.531884 | [
"vector"
] |
75c8de5f732784a9fb4583930892131ec898e2ce | 701 | cpp | C++ | src/sleek/node/billboard/billboard.cpp | Phirxian/sleek-engine | 741d55c8daad67ddf631e8b8fbdced59402d7bda | [
"BSD-2-Clause"
] | null | null | null | src/sleek/node/billboard/billboard.cpp | Phirxian/sleek-engine | 741d55c8daad67ddf631e8b8fbdced59402d7bda | [
"BSD-2-Clause"
] | null | null | null | src/sleek/node/billboard/billboard.cpp | Phirxian/sleek-engine | 741d55c8daad67ddf631e8b8fbdced59402d7bda | [
"BSD-2-Clause"
] | null | null | null | #include "../scene.h"
#include "billboard.h"
namespace sleek
{
namespace scene3d
{
namespace billboard
{
Billboard::Billboard(Scene *smgr) noexcept : Node(smgr)
{
}
Billboard::Billboard(Scene *smgr, driver::texture *i) noexcept : Node(smgr)
{
//mat->Texture[0] = i;
}
void Billboard::render() noexcept
{
if(!enabled)
return;
Node::render();
//if(mat->Texture[0])
// smgr->getDrawManager()->drawTextureCenter(mat->Texture[0].get(), pos, rot);
}
}
}
}
| 21.90625 | 96 | 0.442225 | [
"render"
] |
75cb4b2eae6b3912eedb8f7258132d28314ae675 | 1,303 | cpp | C++ | 252/D[ Playing with Permutations ].cpp | mejanvijay/codeforces-jvj_iit-submissions | 2a2aac7e93ca92e75887eff92361174aa36207c8 | [
"MIT"
] | null | null | null | 252/D[ Playing with Permutations ].cpp | mejanvijay/codeforces-jvj_iit-submissions | 2a2aac7e93ca92e75887eff92361174aa36207c8 | [
"MIT"
] | null | null | null | 252/D[ Playing with Permutations ].cpp | mejanvijay/codeforces-jvj_iit-submissions | 2a2aac7e93ca92e75887eff92361174aa36207c8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <stdio.h>
#include <set>
#include <vector>
#include <map>
#include <cmath>
#include <algorithm>
#include <memory.h>
#include <string>
#include <sstream>
using namespace std;
const int N = 11111;
int n, k, i, z;
int a[N], q[N], v[N], b[N], s[N];
int main() {
// freopen("in", "r", stdin);
// freopen("out", "w", stdout);
scanf("%d %d", &n, &k);
for (i=1;i<=n;i++) scanf("%d", q+i);
for (i=1;i<=n;i++) v[q[i]] = i;
for (i=1;i<=n;i++) scanf("%d", s+i);
int left = -k-1, right = k+1;
for (i=1;i<=n;i++) a[i] = i;
for (z=0;z<=k;z++) {
int ok = 1;
for (i=1;i<=n;i++)
if (a[i] != s[i]) ok = 0;
if (ok) {
right = z;
break;
}
for (i=1;i<=n;i++) b[i] = a[q[i]];
for (i=1;i<=n;i++) a[i] = b[i];
}
for (i=1;i<=n;i++) a[i] = i;
for (z=0;z>=-k;z--) {
int ok = 1;
for (i=1;i<=n;i++)
if (a[i] != s[i]) ok = 0;
if (ok) {
left = z;
break;
}
for (i=1;i<=n;i++) b[i] = a[v[i]];
for (i=1;i<=n;i++) a[i] = b[i];
}
if (left == 0 && right == 0) puts("NO"); else
if (k == 1 && (left == -1 || right == 1)) puts("YES"); else
if (left == -1 && right == 1) puts("NO"); else
if ((k+left) % 2 == 0 || (k-right) % 2 == 0) puts("YES");
else puts("NO");
return 0;
} | 22.465517 | 61 | 0.444359 | [
"vector"
] |
75d37bfacc786e4781ad406bf073d71e99c45209 | 5,516 | cpp | C++ | tests/integration/streamingmemory_tests/executionphase_gradsumdec_test.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | tests/integration/streamingmemory_tests/executionphase_gradsumdec_test.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | tests/integration/streamingmemory_tests/executionphase_gradsumdec_test.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2020 Graphcore Ltd. All rights reserved.
#define BOOST_TEST_MODULE ExecutionPhaseGradSumDecTest
#include <../test_runner.hpp>
#include <boost/test/unit_test.hpp>
#include <string>
#include <popart/builder.hpp>
#include <popart/ir.hpp>
#include <popart/op/add.hpp>
#include <popart/op/identity.hpp>
#include <popart/op/init.hpp>
#include <popart/op/l1.hpp>
#include <popart/op/matmul.hpp>
#include <popart/op/reshape.hpp>
#include <popart/tensorinfo.hpp>
#include <popart/tensornames.hpp>
using namespace popart;
// Model: N parallel matmuls, sharing weights, separate execution phases
// _________________________________________
// phase 0:
// in0 -
// \
// Matmul0 -- ReLU ----.
// / |
// w0 - |
// ___________________________|_____________
// phase 2: |
// in1 - |
// \ |
// Matmul1 -- ReLU --. |
// / | |
// w0 - | |
// _________________________|_|_____________
// phase 4: | |
// in2 - | |
// \ | |
// Matmul2 -- ReLU - Sum -- out
// /
// w0 -
// _________________________________________
// Note that the number of ops from the loss to the original grad-sum is the
// same for all matmuls.
// We then verify that the grad of w0 is correctly added in the bwd phases:
// 1. Add to w0-grad in phase 4 (Matmul2)
// 2. Add to w0-grad in phase 6 (Matmul1)
// 3. Add to w0-grad in phase 8 (Matmul0)
BOOST_AUTO_TEST_CASE(TestDecomposeAcrossExecutionPhases) {
TestRunner runner;
runner.isTraining = true;
int numLayers = 3;
int size = 100;
// Weights are [size, size], Input and Acts are [1, size]
TensorInfo wInfo{"FLOAT", std::vector<int64_t>{size, size}};
std::vector<TestTensor> inputs;
std::vector<TestTensor> outputs;
std::vector<float> w0Data(wInfo.nelms(), 0);
ConstVoidData w0CVData{w0Data.data(), wInfo};
runner.buildModel([&](auto &builder) {
auto aiOnnx = builder.aiOnnxOpset9();
TensorInfo inInfo{"FLOAT", std::vector<int64_t>{1, size}};
auto w0 = builder.addInitializedInputTensor(w0CVData);
std::vector<std::string> outVec;
for (int layer = 0; layer < numLayers; layer++) {
auto input = builder.addInputTensor(inInfo);
auto out = aiOnnx.matmul({input, w0}, "mm_layer" + std::to_string(layer));
builder.executionPhase(out, layer * 2);
out = aiOnnx.relu({out}, "relu_layer" + std::to_string(layer));
builder.executionPhase(out, layer * 2);
outVec.push_back(out);
}
auto sum = aiOnnx.sum(outVec);
auto l1 = builder.aiGraphcoreOpset1().l1loss({sum}, 0.1);
builder.executionPhase(l1, (numLayers - 1) * 2);
// To make introspecting the IR easy
runner.opts.enableOutlining = false;
// Enable feature-under-test
runner.opts.decomposeGradSum = true;
// Use every second execution phase only (maps to one IPU)
runner.opts.executionPhaseSettings.phases = numLayers * 2 - 1;
runner.opts.virtualGraphMode = VirtualGraphMode::ExecutionPhases;
runner.patterns = Patterns(PatternsLevel::Default);
runner.loss = l1;
return sum;
});
runner.checkIr([&](Ir &ir) {
std::vector<Op *> schedule =
ir.getOpSchedule({}, RequireOptimalSchedule::Yes);
std::vector<Op *> gradPartialAddsOrder;
size_t addOpNumber = 0;
for (size_t i = 0; i < schedule.size(); i++) {
Op *op = schedule.at(i);
if (op->isConvertibleTo<AddLhsInplaceOp>() ||
op->isConvertibleTo<AddRhsInplaceOp>()) {
gradPartialAddsOrder.push_back(op);
auto addLhs = AddOp::getArg0InIndex();
auto addRhs = AddOp::getArg1InIndex();
size_t mmLayer = numLayers - 1 - addOpNumber;
std::string mmLayerStr = "mm_layer" + std::to_string(mmLayer);
ExecutionPhase expectedPhase = numLayers + 1 + addOpNumber * 2;
// Check that the add occurs in the expected phase (4, 6, 8)
BOOST_CHECK(op->getExecutionPhase() == expectedPhase);
// Check that the rhs input is produced in the same phase
BOOST_CHECK(
op->input->tensor(addRhs)->getProducer()->getExecutionPhase() ==
expectedPhase);
// Check that the add comes as soon as possible
// after the weight partial tensor becomes live
auto checkForMatMulRhsReshape = [&](Op *op) {
BOOST_CHECK(op->getName().find("MatMulOp_RhsReshape") !=
std::string::npos);
BOOST_CHECK(op->getName().find(mmLayerStr) != std::string::npos);
BOOST_CHECK(op->isConvertibleTo<ReshapeInplaceOp>());
};
auto checkForMatMulRhsGrad = [&](Op *op) {
BOOST_CHECK(op->getName().find("MatMulRhsGradOp") !=
std::string::npos);
BOOST_CHECK(op->getName().find(mmLayerStr) != std::string::npos);
BOOST_CHECK(op->isConvertibleTo<MatMulOp>());
};
if (addOpNumber == 0) {
BOOST_CHECK(schedule.at(i - 1)->isConvertibleTo<InitOp>());
checkForMatMulRhsReshape(schedule.at(i - 2));
checkForMatMulRhsGrad(schedule.at(i - 3));
} else {
checkForMatMulRhsReshape(schedule.at(i - 1));
checkForMatMulRhsGrad(schedule.at(i - 2));
}
addOpNumber++;
}
}
BOOST_CHECK_EQUAL(gradPartialAddsOrder.size(), numLayers);
});
}
| 36.529801 | 80 | 0.612582 | [
"vector",
"model"
] |
75d55729af3422f0e6654e3a45411d2d70f37a03 | 20,083 | cxx | C++ | TPC/TPCbase/AliTPCBoundaryVoltError.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | TPC/TPCbase/AliTPCBoundaryVoltError.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | TPC/TPCbase/AliTPCBoundaryVoltError.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/// \class AliTPCBoundaryVoltError
///
/// <h2> AliTPCBoundaryVoltError class </h2>
/// This class calculates the space point distortions due to residual voltage errors on
/// the main boundaries of the TPC. For example, the inner vessel of the TPC is shifted
/// by a certain amount, whereas the ROCs on the A side and the C side follow this mechanical
/// shift (at the inner vessel) in z direction. This example can be named "conical deformation"
/// of the TPC field cage (see example below).
///
/// The boundary conditions can be set via two arrays (A and C side) which contain the
/// residual voltage setting modeling a possible shift or an inhomogeneity on the TPC field
/// cage. In order to avoid that the user splits the Central Electrode (CE), the settings for
/// the C side is taken from the array on the A side (points: A.6 and A.7). The region betweem
/// the points is interpolated linearly onto the boundaries.
///
/// The class uses the PoissonRelaxation2D (see AliTPCCorrection) to calculate the resulting
/// electrical field inhomogeneities in the (r,z)-plane. Then, the Langevin-integral formalism
/// is used to calculate the space point distortions.
/// Note: This class assumes a homogeneous magnetic field.
///
/// One has two possibilities when calculating the $dz$ distortions. The resulting distortions
/// are purely due to the change of the drift velocity (along with the change of the drift field)
/// when the SetROCDisplacement is FALSE. This emulates for example a Gating-Grid Voltage offset
/// without moving the ROCs. When the flag is set to TRUE, the ROCs are assumed to be misaligned
/// and the corresponding offset in z is added.
/// 
///
/// \author Jim Thomas, Stefan Rossegger
/// \date 01/06/2010
#include "AliMagF.h"
#include "TGeoGlobalMagField.h"
#include "AliTPCcalibDB.h"
#include "AliTPCParam.h"
#include "AliLog.h"
#include "TMatrixD.h"
#include "TMath.h"
#include "AliTPCROC.h"
#include "AliTPCBoundaryVoltError.h"
/// \cond CLASSIMP
ClassImp(AliTPCBoundaryVoltError)
/// \endcond
AliTPCBoundaryVoltError::AliTPCBoundaryVoltError()
: AliTPCCorrection("BoundaryVoltError","Boundary Voltage Error"),
fC0(0.),fC1(0.),
fROCdisplacement(kTRUE),
fInitLookUp(kFALSE)
{
//
// default constructor
//
for (Int_t i=0; i<8; i++){
fBoundariesA[i]= 0;
if (i<6) fBoundariesC[i]= 0;
}
}
AliTPCBoundaryVoltError::~AliTPCBoundaryVoltError() {
/// default destructor
}
Bool_t AliTPCBoundaryVoltError::AddCorrectionCompact(AliTPCCorrection* corr, Double_t weight){
/// Add correction and make them compact
/// Assumptions:
/// - origin of distortion/correction are additive
/// - only correction ot the same type supported ()
if (corr==NULL) {
AliError("Zerro pointer - correction");
return kFALSE;
}
AliTPCBoundaryVoltError* corrC = dynamic_cast<AliTPCBoundaryVoltError *>(corr);
if (corrC == NULL) {
AliError(TString::Format("Inconsistent class types: %s\%s",IsA()->GetName(),corr->IsA()->GetName()).Data());
return kFALSE;
}
if (fROCdisplacement!=corrC->fROCdisplacement){
AliError(TString::Format("Inconsistent fROCdisplacement : %s\%s",IsA()->GetName(),corr->IsA()->GetName()).Data());
return kFALSE;
}
for (Int_t i=0;i <8; i++){
fBoundariesA[i]+= corrC->fBoundariesA[i]*weight;
fBoundariesC[i]+= corrC->fBoundariesC[i]*weight;
}
//
return kTRUE;
}
void AliTPCBoundaryVoltError::Init() {
/// Initialization funtion
AliMagF* magF= (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
if (!magF) AliError("Magneticd field - not initialized");
Double_t bzField = magF->SolenoidField()/10.; //field in T
AliTPCParam *param= AliTPCcalibDB::Instance()->GetParameters();
if (!param) AliError("Parameters - not initialized");
Double_t vdrift = param->GetDriftV()/1000000.; // [cm/us] // From dataBase: to be updated: per second (ideally)
Double_t ezField = 400; // [V/cm] // to be updated: never (hopefully)
Double_t wt = -10.0 * (bzField*10) * vdrift / ezField ;
// Correction Terms for effective omegaTau; obtained by a laser calibration run
SetOmegaTauT1T2(wt,fT1,fT2);
InitBoundaryVoltErrorDistortion();
}
void AliTPCBoundaryVoltError::Update(const TTimeStamp &/*timeStamp*/) {
/// Update function
AliMagF* magF= (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
if (!magF) AliError("Magneticd field - not initialized");
Double_t bzField = magF->SolenoidField()/10.; //field in T
AliTPCParam *param= AliTPCcalibDB::Instance()->GetParameters();
if (!param) AliError("Parameters - not initialized");
Double_t vdrift = param->GetDriftV()/1000000.; // [cm/us] // From dataBase: to be updated: per second (ideally)
Double_t ezField = 400; // [V/cm] // to be updated: never (hopefully)
Double_t wt = -10.0 * (bzField*10) * vdrift / ezField ;
// Correction Terms for effective omegaTau; obtained by a laser calibration run
SetOmegaTauT1T2(wt,fT1,fT2);
}
void AliTPCBoundaryVoltError::GetCorrection(const Float_t x[],const Short_t roc,Float_t dx[]) {
/// Calculates the correction due e.g. residual voltage errors on the TPC boundaries
if (!fInitLookUp) {
AliInfo("Lookup table was not initialized! Perform the inizialisation now ...");
InitBoundaryVoltErrorDistortion();
}
Int_t order = 1 ; // FIXME: hardcoded? Linear interpolation = 1, Quadratic = 2
// note that the poisson solution was linearly mirroed on this grid!
Double_t intEr, intEphi, intdEz ;
Double_t r, phi, z ;
Int_t sign;
r = TMath::Sqrt( x[0]*x[0] + x[1]*x[1] ) ;
phi = TMath::ATan2(x[1],x[0]) ;
if ( phi < 0 ) phi += TMath::TwoPi() ; // Table uses phi from 0 to 2*Pi
z = x[2] ; // Create temporary copy of x[2]
if ( (roc%36) < 18 ) {
sign = 1; // (TPC A side)
} else {
sign = -1; // (TPC C side)
}
if ( sign==1 && z < fgkZOffSet ) z = fgkZOffSet; // Protect against discontinuity at CE
if ( sign==-1 && z > -fgkZOffSet ) z = -fgkZOffSet; // Protect against discontinuity at CE
intEphi = 0.0; // Efield is symmetric in phi - 2D calculation
if ( (sign==1 && z<0) || (sign==-1 && z>0) ) // just a consistency check
AliError("ROC number does not correspond to z coordinate! Calculation of distortions is most likely wrong!");
// Get the E field integral
Interpolate2DEdistortion( order, r, z, fLookUpErOverEz, intEr );
// Get DeltaEz field integral
Interpolate2DEdistortion( order, r, z, fLookUpDeltaEz, intdEz );
// Calculate distorted position
if ( r > 0.0 ) {
phi = phi + ( fC0*intEphi - fC1*intEr ) / r;
r = r + ( fC0*intEr + fC1*intEphi );
}
// Calculate correction in cartesian coordinates
dx[0] = r * TMath::Cos(phi) - x[0];
dx[1] = r * TMath::Sin(phi) - x[1];
dx[2] = intdEz; // z distortion - (internally scaled with driftvelocity dependency
// on the Ez field plus the actual ROC misalignment (if set TRUE)
}
void AliTPCBoundaryVoltError::InitBoundaryVoltErrorDistortion() {
/// Initialization of the Lookup table which contains the solutions of the
/// Dirichlet boundary problem
const Float_t gridSizeR = (fgkOFCRadius-fgkIFCRadius) / (kRows-1) ;
const Float_t gridSizeZ = fgkTPCZ0 / (kColumns-1) ;
TMatrixD voltArrayA(kRows,kColumns), voltArrayC(kRows,kColumns); // boundary vectors
TMatrixD chargeDensity(kRows,kColumns); // dummy charge
TMatrixD arrayErOverEzA(kRows,kColumns), arrayErOverEzC(kRows,kColumns); // solution
TMatrixD arrayDeltaEzA(kRows,kColumns), arrayDeltaEzC(kRows,kColumns); // solution
Double_t rList[kRows], zedList[kColumns] ;
// Fill arrays with initial conditions. V on the boundary and ChargeDensity in the volume.
for ( Int_t j = 0 ; j < kColumns ; j++ ) {
Double_t zed = j*gridSizeZ ;
zedList[j] = zed ;
for ( Int_t i = 0 ; i < kRows ; i++ ) {
Double_t radius = fgkIFCRadius + i*gridSizeR ;
rList[i] = radius ;
voltArrayA(i,j) = 0; // Initialize voltArrayA to zero
voltArrayC(i,j) = 0; // Initialize voltArrayC to zero
chargeDensity(i,j) = 0; // Initialize ChargeDensity to zero - not used in this class
}
}
// check if boundary values are the same for the C side (for later, saving some calculation time)
Int_t symmetry = -1; // assume that A and C side are identical (but anti-symmetric!) // e.g conical deformation
Int_t sVec[8];
// check if boundaries are different (regardless the sign)
for (Int_t i=0; i<8; i++) {
if (TMath::Abs(TMath::Abs(fBoundariesA[i]) - TMath::Abs(fBoundariesC[i])) > 1e-5)
symmetry = 0;
sVec[i] = (Int_t)( TMath::Sign((Float_t)1.,fBoundariesA[i]) * TMath::Sign((Float_t)1.,fBoundariesC[i]));
}
if (symmetry==-1) { // still the same values?
// check the kind of symmetry , if even ...
if (sVec[0]==1 && sVec[1]==1 && sVec[2]==1 && sVec[3]==1 && sVec[4]==1 && sVec[5]==1 && sVec[6]==1 && sVec[7]==1 )
symmetry = 1;
else if (sVec[0]==-1 && sVec[1]==-1 && sVec[2]==-1 && sVec[3]==-1 && sVec[4]==-1 && sVec[5]==-1 && sVec[6]==-1 && sVec[7]==-1 )
symmetry = -1;
else
symmetry = 0; // some of the values differ in the sign -> neither symmetric nor antisymmetric
}
// Solve the electrosatic problem in 2D
// Fill the complete Boundary vectors
// Start at IFC at CE and work anti-clockwise through IFC, ROC, OFC, and CE (clockwise for C side)
for ( Int_t j = 0 ; j < kColumns ; j++ ) {
Double_t zed = j*gridSizeZ ;
for ( Int_t i = 0 ; i < kRows ; i++ ) {
Double_t radius = fgkIFCRadius + i*gridSizeR ;
// A side boundary vectors
if ( i == 0 ) voltArrayA(i,j) += zed *((fBoundariesA[1]-fBoundariesA[0])/((kColumns-1)*gridSizeZ))
+ fBoundariesA[0] ; // IFC
if ( j == kColumns-1 ) voltArrayA(i,j) += (radius-fgkIFCRadius)*((fBoundariesA[3]-fBoundariesA[2])/((kRows-1)*gridSizeR))
+ fBoundariesA[2] ; // ROC
if ( i == kRows-1 ) voltArrayA(i,j) += zed *((fBoundariesA[4]-fBoundariesA[5])/((kColumns-1)*gridSizeZ))
+ fBoundariesA[5] ; // OFC
if ( j == 0 ) voltArrayA(i,j) += (radius-fgkIFCRadius)*((fBoundariesA[6]-fBoundariesA[7])/((kRows-1)*gridSizeR))
+ fBoundariesA[7] ; // CE
if (symmetry==0) {
// C side boundary vectors
if ( i == 0 ) voltArrayC(i,j) += zed *((fBoundariesC[1]-fBoundariesC[0])/((kColumns-1)*gridSizeZ))
+ fBoundariesC[0] ; // IFC
if ( j == kColumns-1 ) voltArrayC(i,j) += (radius-fgkIFCRadius)*((fBoundariesC[3]-fBoundariesC[2])/((kRows-1)*gridSizeR))
+ fBoundariesC[2] ; // ROC
if ( i == kRows-1 ) voltArrayC(i,j) += zed *((fBoundariesC[4]-fBoundariesC[5])/((kColumns-1)*gridSizeZ))
+ fBoundariesC[5] ; // OFC
if ( j == 0 ) voltArrayC(i,j) += (radius-fgkIFCRadius)*((fBoundariesC[6]-fBoundariesC[7])/((kRows-1)*gridSizeR))
+ fBoundariesC[7] ; // CE
}
}
}
voltArrayA(0,0) *= 0.5 ; // Use average boundary condition at corner
voltArrayA(kRows-1,0) *= 0.5 ; // Use average boundary condition at corner
voltArrayA(0,kColumns-1) *= 0.5 ; // Use average boundary condition at corner
voltArrayA(kRows-1,kColumns-1)*= 0.5 ; // Use average boundary condition at corner
if (symmetry==0) {
voltArrayC(0,0) *= 0.5 ; // Use average boundary condition at corner
voltArrayC(kRows-1,0) *= 0.5 ; // Use average boundary condition at corner
voltArrayC(0,kColumns-1) *= 0.5 ; // Use average boundary condition at corner
voltArrayC(kRows-1,kColumns-1)*= 0.5 ; // Use average boundary condition at corner
}
// always solve the problem on the A side
PoissonRelaxation2D( voltArrayA, chargeDensity, arrayErOverEzA, arrayDeltaEzA,
kRows, kColumns, kIterations, fROCdisplacement ) ;
if (symmetry!=0) { // A and C side are the same ("anti-symmetric" or "symmetric")
for ( Int_t j = 0 ; j < kColumns ; j++ ) {
for ( Int_t i = 0 ; i < kRows ; i++ ) {
arrayErOverEzC(i,j) = symmetry*arrayErOverEzA(i,j);
arrayDeltaEzC(i,j) = -symmetry*arrayDeltaEzA(i,j);
}
}
} else if (symmetry==0) { // A and C side are different - Solve the problem on the C side too
PoissonRelaxation2D( voltArrayC, chargeDensity, arrayErOverEzC, arrayDeltaEzC,
kRows, kColumns, kIterations, fROCdisplacement ) ;
for ( Int_t j = 0 ; j < kColumns ; j++ ) {
for ( Int_t i = 0 ; i < kRows ; i++ ) {
arrayDeltaEzC(i,j) = -arrayDeltaEzC(i,j); // negative z coordinate!
}
}
}
// Interpolate results onto standard grid for Electric Fields
Int_t ilow=0, jlow=0 ;
Double_t z,r;
Float_t saveEr[2] ;
Float_t saveEz[2] ;
for ( Int_t i = 0 ; i < kNZ ; ++i ) {
z = TMath::Abs( fgkZList[i] ) ;
for ( Int_t j = 0 ; j < kNR ; ++j ) {
// Linear interpolation !!
r = fgkRList[j] ;
Search( kRows, rList, r, ilow ) ; // Note switch - R in rows and Z in columns
Search( kColumns, zedList, z, jlow ) ;
if ( ilow < 0 ) ilow = 0 ; // check if out of range
if ( jlow < 0 ) jlow = 0 ;
if ( ilow + 1 >= kRows - 1 ) ilow = kRows - 2 ;
if ( jlow + 1 >= kColumns - 1 ) jlow = kColumns - 2 ;
if (fgkZList[i]>0) { // A side solution
saveEr[0] = arrayErOverEzA(ilow,jlow) +
(arrayErOverEzA(ilow,jlow+1)-arrayErOverEzA(ilow,jlow))*(z-zedList[jlow])/gridSizeZ ;
saveEr[1] = arrayErOverEzA(ilow+1,jlow) +
(arrayErOverEzA(ilow+1,jlow+1)-arrayErOverEzA(ilow+1,jlow))*(z-zedList[jlow])/gridSizeZ ;
saveEz[0] = arrayDeltaEzA(ilow,jlow) +
(arrayDeltaEzA(ilow,jlow+1)-arrayDeltaEzA(ilow,jlow))*(z-zedList[jlow])/gridSizeZ ;
saveEz[1] = arrayDeltaEzA(ilow+1,jlow) +
(arrayDeltaEzA(ilow+1,jlow+1)-arrayDeltaEzA(ilow+1,jlow))*(z-zedList[jlow])/gridSizeZ ;
} else if (fgkZList[i]<0) { // C side solution
saveEr[0] = arrayErOverEzC(ilow,jlow) +
(arrayErOverEzC(ilow,jlow+1)-arrayErOverEzC(ilow,jlow))*(z-zedList[jlow])/gridSizeZ ;
saveEr[1] = arrayErOverEzC(ilow+1,jlow) +
(arrayErOverEzC(ilow+1,jlow+1)-arrayErOverEzC(ilow+1,jlow))*(z-zedList[jlow])/gridSizeZ ;
saveEz[0] = arrayDeltaEzC(ilow,jlow) +
(arrayDeltaEzC(ilow,jlow+1)-arrayDeltaEzC(ilow,jlow))*(z-zedList[jlow])/gridSizeZ ;
saveEz[1] = arrayDeltaEzC(ilow+1,jlow) +
(arrayDeltaEzC(ilow+1,jlow+1)-arrayDeltaEzC(ilow+1,jlow))*(z-zedList[jlow])/gridSizeZ ;
} else {
AliWarning("Field calculation at z=0 (CE) is not allowed!");
saveEr[0]=0; saveEr[1]=0;
saveEz[0]=0; saveEz[1]=0;
}
fLookUpErOverEz[i][j] = saveEr[0] + (saveEr[1]-saveEr[0])*(r-rList[ilow])/gridSizeR ;
fLookUpDeltaEz[i][j] = saveEz[0] + (saveEz[1]-saveEz[0])*(r-rList[ilow])/gridSizeR ;
}
}
voltArrayA.Clear();
voltArrayC.Clear();
chargeDensity.Clear();
arrayErOverEzA.Clear();
arrayErOverEzC.Clear();
arrayDeltaEzA.Clear();
arrayDeltaEzC.Clear();
fInitLookUp = kTRUE;
}
void AliTPCBoundaryVoltError::Print(const Option_t* option) const {
/// Print function to check the settings of the boundary vectors
/// option=="a" prints the C0 and C1 coefficents for calibration purposes
TString opt = option; opt.ToLower();
printf("%s\n",GetTitle());
printf(" - Voltage settings (on the TPC boundaries) - linearly interpolated\n");
printf(" : A-side (anti-clockwise)\n");
printf(" (0,1):\t IFC (CE) : %3.1f V \t IFC (ROC): %3.1f V \n",fBoundariesA[0],fBoundariesA[1]);
printf(" (2,3):\t ROC (IFC): %3.1f V \t ROC (OFC): %3.1f V \n",fBoundariesA[2],fBoundariesA[3]);
printf(" (4,5):\t OFC (ROC): %3.1f V \t OFC (CE) : %3.1f V \n",fBoundariesA[4],fBoundariesA[5]);
printf(" (6,7):\t CE (OFC): %3.1f V \t CE (IFC): %3.1f V \n",fBoundariesA[6],fBoundariesA[7]);
printf(" : C-side (clockwise)\n");
printf(" (0,1):\t IFC (CE) : %3.1f V \t IFC (ROC): %3.1f V \n",fBoundariesC[0],fBoundariesC[1]);
printf(" (2,3):\t ROC (IFC): %3.1f V \t ROC (OFC): %3.1f V \n",fBoundariesC[2],fBoundariesC[3]);
printf(" (4,5):\t OFC (ROC): %3.1f V \t OFC (CE) : %3.1f V \n",fBoundariesC[4],fBoundariesC[5]);
printf(" (6,7):\t CE (OFC): %3.1f V \t CE (IFC): %3.1f V \n",fBoundariesC[6],fBoundariesC[7]);
// Check wether the settings of the Central Electrode agree (on the A and C side)
// Note: they have to be antisymmetric!
if (( TMath::Abs(fBoundariesA[6]+fBoundariesC[6])>1e-5) || ( TMath::Abs(fBoundariesA[7]+fBoundariesC[7])>1e-5 ) ){
AliWarning("Boundary parameters for the Central Electrode (CE) are not anti-symmetric! HOW DID YOU MANAGE THAT?");
AliWarning("Congratulations, you just splitted the Central Electrode of the TPC!");
AliWarning("Non-physical settings of the boundary parameter at the Central Electrode");
}
if (opt.Contains("a")) { // Print all details
printf(" - T1: %1.4f, T2: %1.4f \n",fT1,fT2);
printf(" - C1: %1.4f, C0: %1.4f \n",fC1,fC0);
}
if (!fInitLookUp)
AliError("Lookup table was not initialized! You should do InitBoundaryVoltErrorDistortion() ...");
}
void AliTPCBoundaryVoltError::SetBoundariesA(Float_t boundariesA[8]){
/// set voltage errors on the TPC boundaries - A side
///
/// Start at IFC at the Central electrode and work anti-clockwise (clockwise for C side) through
/// IFC, ROC, OFC, and CE. The boundary conditions are currently defined to be a linear
/// interpolation between pairs of numbers in the Boundary (e.g. fBoundariesA) vector.
/// The first pair of numbers represent the beginning and end of the Inner Field cage, etc.
/// The unit of the error potential vector is [Volt], whereas 1mm shift of the IFC would
/// correspond to ~ 40 V
///
/// Note: The setting for the CE will be passed to the C side!
for (Int_t i=0; i<8; i++) {
fBoundariesA[i]= boundariesA[i];
if (i>5) fBoundariesC[i]= -boundariesA[i]; // setting for the CE is passed to C side
}
fInitLookUp=kFALSE;
}
void AliTPCBoundaryVoltError::SetBoundariesC(Float_t boundariesC[6]){
/// set voltage errors on the TPC boundaries - C side
///
/// Start at IFC at the Central electrode and work clockwise (for C side) through
/// IFC, ROC and OFC. The boundary conditions are currently defined to be a linear
/// interpolation between pairs of numbers in the Boundary (e.g. fBoundariesC) vector.
/// The first pair of numbers represent the beginning and end of the Inner Field cage, etc.
/// The unit of the error potential vector is [Volt], whereas 1mm shift of the IFC would
/// correspond to ~ 40 V
///
/// Note: The setting for the CE will be taken from the A side (pos 6 and 7)!
for (Int_t i=0; i<6; i++) {
fBoundariesC[i]= boundariesC[i];
}
fInitLookUp=kFALSE;
}
| 44.235683 | 132 | 0.637604 | [
"vector"
] |
75ec66e1d50005888961e18a59f9cc73597c8501 | 29,446 | cpp | C++ | sta-src/SEM/StructureSubsystem.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 6 | 2018-09-05T12:41:59.000Z | 2021-07-01T05:34:23.000Z | sta-src/SEM/StructureSubsystem.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-02-07T19:09:21.000Z | 2015-08-14T03:15:42.000Z | sta-src/SEM/StructureSubsystem.cpp | hoehnp/SpaceDesignTool | 9abd34048274b2ce9dbbb685124177b02d6a34ca | [
"IJG"
] | 2 | 2015-03-25T15:50:31.000Z | 2017-12-06T12:16:47.000Z | /*
This program is free software; you can redistribute it and/or modify it under
the terms of the European Union Public Licence - EUPL v.1.1 as published by
the European Commission.
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 European Union Public Licence - EUPL v.1.1
for more details.
You should have received a copy of the European Union Public Licence - EUPL v.1.1
along with this program.
Further information about the European Union Public Licence - EUPL v.1.1 can
also be found on the world wide web at http://ec.europa.eu/idabc/eupl
*/
/*
------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----
------------------ Author: Ozgun YILMAZ ---------------------------------------------
------------------ email: ozgunus@yahoo.com ---------------------------------------------
*/
#include "StructureSubsystem.h"
#include <math.h>
//to Read and write to file
#include <QFile>
#include <QTextStream>
#include <QDir>
#include <QProcess>
#include "Astro-Core/constants.h"
//----------------- Constructor -------------------------------------//
StructureSubsystem::StructureSubsystem()
{
SCSizing.setZero();
// SCVolume = 0.0;
// BatteryVolume = 0.0;
MomentsOfInertia.setZero();
SecondMomentsOfInertia.setZero();
SCShape = Undefined;
NaturalFrequency.Axial = 0.0;
NaturalFrequency.Lateral = 0.0;
SCMaterial.Name = "";
SCMaterial.ModulusOfElasticity = 0.0;
SCMaterial.Absorptivity = 0.0;
SCMaterial.Emmissivity = 0.0;
SCMassDetails.OBDHSubsystemMass = 0.0;
SCMassDetails.StructureSubsystemMass = 0.0;
SCMassDetails.ThermalSubsystemMass = 0.0;
SCMassDetails.TotalPayloadMass = 0.0;
SCMassDetails.TTCSubsystemMass = 0.0;
SCMassDetails.PowerSubsystemMass = 0.0;
SCMassDetails.SCTotal = 0.0;
//initialize the estimate calculations
SCMassEstimatePercentages.MissionType = "";
SCMassEstimatePercentages.OBDHSubsystemPercentage = 0.0;
SCMassEstimatePercentages.PayloadPercentage = 0.0;
SCMassEstimatePercentages.PowerSubsystemPercentage = 0.0;
SCMassEstimatePercentages.StructureSubsystemPercentage = 0.0;
SCMassEstimatePercentages.ThermalSubsystemPercentage = 0.0;
SCMassEstimatePercentages.TTCSubsystemPercentage = 0.0;
//For thermal calculations set the size of areas
SCThermalDetails.AreaOfColdFace = 0.0;
SCThermalDetails.AreaOfHotFace = 0.0;
SCThermalDetails.TotalAreaOfColdFace = 0.0;
SCThermalDetails.TotalAreaOfHotFace = 0.0;
// //this setting is done by wizard but for now it is constant
// setMassEstimations("Light_Satellite");
SCVolumeDetails.OBDHSubsystemVolume = 0.0;
SCVolumeDetails.PowerSubsystemVolume = 0.0;
SCVolumeDetails.SCTotalVolume = 0.0;
SCVolumeDetails.StructureSubsystemVolume = 0.0;
SCVolumeDetails.ThermalSubsystemVolume = 0.0;
SCVolumeDetails.TTCSubsystemVolume = 0.0;
int i ;
for (i=0; i<NumberOfPayloads; i++)
{
PayloadStructureDetails[i].Name = "";
PayloadStructureDetails[i].PayloadMass = 0.0;
PayloadStructureDetails[i].PayloadVolume = 0.0;
PayloadStructureDetails[i].PayloadStructure.setZero();
}
}
//----------------- Functions ---------------------------------------//
void StructureSubsystem::CalculateAndSetSCVolume()
{
double tempSCVolume = 0.0;
int i;
for(i=0; i<NumberOfPayloads; i++)
{
tempSCVolume += PayloadStructureDetails[i].PayloadVolume
* (1.0 + 0.2);
}
qDebug()<<"tempSC VOLUME"<<tempSCVolume;
tempSCVolume += SCVolumeDetails.PowerSubsystemVolume * (1.0 + 0.2)
//20% margin -> (1.0 + 0.2)
+ SCVolumeDetails.TTCSubsystemVolume * (1.0 + 0.2)
+ SCVolumeDetails.OBDHSubsystemVolume * (1.0 + 0.2)
// + SCVolumeDetails.StructureSubsystemVolume * (1.0 + 0.2)
+ SCVolumeDetails.ThermalSubsystemVolume * (1.0 + 0.2);
SCVolumeDetails.SCTotalVolume = tempSCVolume * (1.0 + 0.2);
qDebug()<<"SCVolumeDetails.PowerSubsystemVolume"<<SCVolumeDetails.PowerSubsystemVolume;
qDebug()<<"SCVolumeDetails.TTCSubsystemVolume"<<SCVolumeDetails.TTCSubsystemVolume;
qDebug()<<"SCVolumeDetails.OBDHSubsystemVolume"<<SCVolumeDetails.OBDHSubsystemVolume;
qDebug()<<"SCVolumeDetails.StructureSubsystemVolume"<<SCVolumeDetails.StructureSubsystemVolume;
qDebug()<<"SCVolumeDetails.ThermalSubsystemVolume"<<SCVolumeDetails.ThermalSubsystemVolume;
qDebug()<<"tempSC VOLUME"<<tempSCVolume;
}
void StructureSubsystem::setSCVolume(double volume)
{
SCVolumeDetails.SCTotalVolume = volume;
}
double StructureSubsystem::getSCVolume()
{
return SCVolumeDetails.SCTotalVolume;
}
void StructureSubsystem::CalculateAndSetSpacecraftDimension()
{
switch (SCShape)
{
case Cube: // Cube
{
SCSizing.x() = cbrt(SCVolumeDetails.SCTotalVolume)+0.02;//2 mm for the structural extention
SCSizing.y() = SCSizing.x();
SCSizing.z() = SCSizing.y();
//For thermal calculations set the size of areas
SCThermalDetails.AreaOfColdFace = SCSizing.x() * SCSizing.y();
SCThermalDetails.AreaOfHotFace = SCSizing.x() * SCSizing.y() ;
SCThermalDetails.TotalAreaOfColdFace = 2 * SCSizing.x() * SCSizing.y();
SCThermalDetails.TotalAreaOfHotFace = 4 * SCSizing.x() * SCSizing.y();
qDebug()<<"cube";
break;
}
case Cylindrical:
{
SCSizing.x() = cbrt(SCVolumeDetails.SCTotalVolume/mypi)*2+0.02;//2 mm for the structural extention //Diameter
SCSizing.y() = cbrt(SCVolumeDetails.SCTotalVolume/mypi)+0.02;//2 mm for the structural extention
SCSizing.z() = 0.0;
//For thermal calculations set the size of areas
SCThermalDetails.AreaOfColdFace = mypi * pow(SCSizing.x(),2.0) / 4;
SCThermalDetails.AreaOfHotFace = mypi * SCSizing.x()/2 * SCSizing.y();
SCThermalDetails.TotalAreaOfColdFace = 2 * SCThermalDetails.AreaOfColdFace ;
SCThermalDetails.TotalAreaOfHotFace = 2 * SCThermalDetails.AreaOfHotFace;
qDebug()<<"cylinder";
break;
}
case Spherical:
{
SCSizing.x() = cbrt((3 * SCVolumeDetails.SCTotalVolume)
/ (4 * mypi))*2+0.02;//2 mm for the structural extention //Diameter
SCSizing.y() = 0.0;
SCSizing.z() = 0.0;
//For thermal calculations set the size of areas
SCThermalDetails.AreaOfColdFace = 0.0;
SCThermalDetails.AreaOfHotFace = 0.5 * mypi * pow(SCSizing.x(),2.0);
SCThermalDetails.TotalAreaOfColdFace = 0.0;
SCThermalDetails.TotalAreaOfHotFace = 2 * SCThermalDetails.AreaOfHotFace;
qDebug()<<"sphere";
break;
}
default:
{
SCSizing.x() = 0.0;
SCSizing.y() = 0.0;
SCSizing.z() = 0.0;
}
}
qDebug()<<SCThermalDetails.AreaOfColdFace;
qDebug()<<SCThermalDetails.AreaOfHotFace ;
qDebug()<<SCThermalDetails.TotalAreaOfColdFace ;
qDebug()<<SCThermalDetails.TotalAreaOfHotFace;
qWarning("TODO: %s %d",__FILE__,__LINE__);
}
void StructureSubsystem::setSpacecraftDimension(double width,
double height,
double length)
{
SCSizing.x() = width;
SCSizing.y() = height;
SCSizing.z() = length;
}
Vector3d StructureSubsystem::getSpacecraftDimension()
{
return SCSizing;
}
void StructureSubsystem::CalculateAndSetSCMass()
{
// if the masses are Zero, it will estimate
//otherwise it will set the existing values
double estimate = 0.0;
if (SCMassDetails.PowerSubsystemMass <= 0.0)
estimate += SCMassDetails.TotalPayloadMass
/ SCMassEstimatePercentages.PayloadPercentage
* SCMassEstimatePercentages.PowerSubsystemPercentage;
qDebug()<<"estimate"<<estimate;
SCMassDetails.StructureSubsystemMass = getStructureSubsystemMass();
if (SCMassDetails.StructureSubsystemMass <= 0.0)
estimate += SCMassDetails.TotalPayloadMass
/ SCMassEstimatePercentages.PayloadPercentage
* SCMassEstimatePercentages.StructureSubsystemPercentage;
qDebug()<<"SCMassEstimatePercentages.PayloadPercentage"<<SCMassEstimatePercentages.PayloadPercentage;
qDebug()<<"estimate"<<estimate;
if (SCMassDetails.ThermalSubsystemMass <= 0.0)
estimate += SCMassDetails.TotalPayloadMass
/ SCMassEstimatePercentages.PayloadPercentage
* SCMassEstimatePercentages.ThermalSubsystemPercentage;
qDebug()<<"estimate"<<estimate;
if (SCMassDetails.TTCSubsystemMass <= 0.0)
estimate += SCMassDetails.TotalPayloadMass
/ SCMassEstimatePercentages.PayloadPercentage
* SCMassEstimatePercentages.TTCSubsystemPercentage;
qDebug()<<"estimate"<<estimate;
SCMassDetails.SCTotal = SCMassDetails.PowerSubsystemMass
+ SCMassDetails.OBDHSubsystemMass
+ SCMassDetails.StructureSubsystemMass
+ SCMassDetails.ThermalSubsystemMass
+ SCMassDetails.TTCSubsystemMass
+ SCMassDetails.TotalPayloadMass
+ estimate;
qDebug()<<"SCMassDetails.Power"<<SCMassDetails.PowerSubsystemMass;
qDebug()<<"SCMassDetails"<<SCMassDetails.OBDHSubsystemMass;
qDebug()<<"SCMassDetails"<<SCMassDetails.StructureSubsystemMass;
qDebug()<<"SCMassDetails"<<SCMassDetails.ThermalSubsystemMass;
qDebug()<<"SCMassDetails"<<SCMassDetails.TTCSubsystemMass;
qDebug()<<"SCMassDetails"<<SCMassDetails.TotalPayloadMass;
qDebug()<<"SCMassDetails.TotalPayloadMass"<<SCMassDetails.TotalPayloadMass;
qDebug()<<"estimate"<<estimate;
}
void StructureSubsystem::setSCMass(double Mass)
{
SCMassDetails.SCTotal = Mass;
}
double StructureSubsystem::getSCMass()
{
return SCMassDetails.SCTotal;
}
void StructureSubsystem::CalculateAndSetMomentsOfInertia()
{
switch (SCShape)
{
case Cube:
{
MomentsOfInertia.x() = (SCMassDetails.SCTotal * pow(SCSizing.x(),2))/6;
MomentsOfInertia.y() = (SCMassDetails.SCTotal * pow(SCSizing.y(),2))/6;
MomentsOfInertia.z() = (SCMassDetails.SCTotal * pow(SCSizing.z(),2))/6;
break;
}
case Cylindrical:
{
MomentsOfInertia.x() = SCMassDetails.SCTotal *
( ( pow(SCSizing.x(),2)/16 )+(SCSizing.y()/12) );
MomentsOfInertia.y() = SCMassDetails.SCTotal *
( ( pow(SCSizing.x(),2)/16 )+(SCSizing.y()/12) );
MomentsOfInertia.z() = SCMassDetails.SCTotal * pow(SCSizing.x(),2) / 8;
break;
}
case Spherical:
{
MomentsOfInertia.x() = 0.1 * SCMassDetails.SCTotal * pow(SCSizing.x(),2);
MomentsOfInertia.y() = 0.1 * SCMassDetails.SCTotal * pow(SCSizing.x(),2);
MomentsOfInertia.z() = 0.1 * SCMassDetails.SCTotal * pow(SCSizing.x(),2);
break;
}
default:
{
MomentsOfInertia.x() = 0.0;
MomentsOfInertia.y() = 0.0;
MomentsOfInertia.z() = 0.0;
break;
}
}
}
void StructureSubsystem::setMomentsOfInertia(double x, double y, double z)
{
MomentsOfInertia.x() = x;
MomentsOfInertia.y() = y;
MomentsOfInertia.z() = z;
}
Vector3d StructureSubsystem::getMomentsOfInertia()
{
return MomentsOfInertia;
}
void StructureSubsystem::CalculateAndSetSecondMomentsOfInertia()
{
switch (SCShape)
{
case Cube:
{
SecondMomentsOfInertia.x() = (pow(SCSizing.x(),4.0)/ 12);
SecondMomentsOfInertia.y() = (pow(SCSizing.y(),4.0)/ 12);
SecondMomentsOfInertia.z() = (pow(SCSizing.x(),4.0)/ 12);
break;
}
case Cylindrical:
{
SecondMomentsOfInertia.x() =(mypi * pow(SCSizing.x(),4.0) / 64);
SecondMomentsOfInertia.y() =(mypi * pow(SCSizing.x(),4.0) / 64);
SecondMomentsOfInertia.z() =(mypi * pow(SCSizing.x(),4.0) / 32);
break;
}
case Spherical:
{
SecondMomentsOfInertia.x() =(mypi * pow(SCSizing.x(),4.0) / 64);
SecondMomentsOfInertia.y() =(mypi * pow(SCSizing.x(),4.0) / 64);
SecondMomentsOfInertia.z() =(mypi * pow(SCSizing.x(),4.0) / 32);
break;
}
default:
{
SecondMomentsOfInertia.x() = 0.0;
SecondMomentsOfInertia.y() = 0.0;
SecondMomentsOfInertia.z() = 0.0;
break;
}
}
}
void StructureSubsystem::setSecondMomentsOfInertia(double x, double y, double z)
{
SecondMomentsOfInertia.x() = x;
SecondMomentsOfInertia.y() = y;
SecondMomentsOfInertia.z() = z;
}
Vector3d StructureSubsystem::getSecondMomentsOfInertia()
{
return SecondMomentsOfInertia;
}
void StructureSubsystem::setSCShape(Shape DefinedShape)
{
SCShape = DefinedShape;
}
void StructureSubsystem::setSCShape(QString Shape)
{
if (Shape=="Cube")
SCShape = Cube;
else
{
if (Shape =="Cylinder")
SCShape = Cylindrical;
else
{
if (Shape == "Sphere")
SCShape = Spherical;
else
SCShape = Undefined;
}
}
}
Shape StructureSubsystem::getSCShape()
{
return SCShape;
}
QString StructureSubsystem::getSCShapeString()
{
switch(SCShape)
{
case Cube:
return "Cube";
break;
case Cylindrical:
return "Cylinder";
break;
case Spherical:
return "Sphere";
break;
default:
return "";
break;
}
}
void StructureSubsystem::CalculateAndSetLateralFrequency()
{
switch (SCShape)
{
case Cube:
{
NaturalFrequency.Lateral = (0.560 *
sqrt((SCMaterial.ModulusOfElasticity * SecondMomentsOfInertia.x())
/
(SCMassDetails.SCTotal * pow(SCSizing.z(),3.0))
) );
break;
}
case Cylindrical:
{
NaturalFrequency.Lateral = (0.560 *
sqrt((SCMaterial.ModulusOfElasticity * SecondMomentsOfInertia.x())
/
(SCMassDetails.SCTotal * pow(SCSizing.y(),3))
) );
break;
}
case Spherical:
{
NaturalFrequency.Lateral = (0.560 *
sqrt((SCMaterial.ModulusOfElasticity * SecondMomentsOfInertia.x())
/
(SCMassDetails.SCTotal * pow(SCSizing.x(),3))
) );
break;
}
default:
NaturalFrequency.Lateral = 0;
break;
}
}
void StructureSubsystem::setLateralFrequency(double Frequency)
{
NaturalFrequency.Lateral = Frequency;
}
double StructureSubsystem::getLateralFrequency()
{
return NaturalFrequency.Lateral;
}
void StructureSubsystem::CalculateAndSetAxialFrequency()
{
//first find the area of the SC that is going to bound to launcher
double AreaOfLauncherInterface;
switch(SCShape)
{
case Cube:
{
AreaOfLauncherInterface = SCSizing.x() * SCSizing.y();
NaturalFrequency.Axial = (0.250 *
sqrt((AreaOfLauncherInterface * SCMaterial.ModulusOfElasticity )
/ (SCMassDetails.SCTotal * SCSizing.z()) ) );
break;
}
case Cylindrical:
{
AreaOfLauncherInterface = mypi * pow(SCSizing.x(),2.0);
NaturalFrequency.Axial = (0.250 *
sqrt((AreaOfLauncherInterface * SCMaterial.ModulusOfElasticity )
/ (SCMassDetails.SCTotal * SCSizing.y()) ));
break;
}
case Spherical:
{
// As there is a point interface, area is averaged to half radius
AreaOfLauncherInterface = mypi * pow((SCSizing.x()/2),2.0);
NaturalFrequency.Axial = (0.250 *
sqrt((AreaOfLauncherInterface * SCMaterial.ModulusOfElasticity )
/ (SCMassDetails.SCTotal * SCSizing.x()) ));
break;
}
default:
{
NaturalFrequency.Axial = 0.0;
break;
}
}
}
void StructureSubsystem::setAxialFrequency(double Frequency)
{
NaturalFrequency.Axial = Frequency;
}
double StructureSubsystem::getAxialFrequency()
{
return NaturalFrequency.Axial;
}
void StructureSubsystem::setPayloadsStructure(int Index,
QString Name,
Vector3d PayloadStructure,
double PayloadVolume,
double PayloadMass)
{
PayloadStructureDetails[Index].Name = Name;
PayloadStructureDetails[Index].PayloadStructure = PayloadStructure;
PayloadStructureDetails[Index].PayloadVolume = PayloadVolume;
PayloadStructureDetails[Index].PayloadMass = PayloadMass;
//calculate total payload mass
int i;
SCMassDetails.TotalPayloadMass = 0.0;
for (i=0; i<4; i++)
{
SCMassDetails.TotalPayloadMass += PayloadStructureDetails[i].PayloadMass;
}
}
PayloadStructureInfo* StructureSubsystem::getPayloadStructure()
{
return PayloadStructureDetails;
}
void StructureSubsystem::setMaterialProperties(QString Name)
{
QString path = QString("data/MaterialDatabase/MaterialsStructuralProperties.stad");
QFile MaterialsStructureProperties(path);
MaterialsStructureProperties.open(QIODevice::ReadOnly);
// qDebug()<<MaterialsStructureProperties.fileName();
// qDebug()<<MaterialsStructureProperties.isOpen();
QTextStream MaterialsStructurePropertiesStream(&MaterialsStructureProperties);
//to skip the first descriptive line of the "MaterialsStructureProperties.stad"
QString InfosOfStadFile;
int NumberOfColumns = 5;
int i;
for (i=0;i<NumberOfColumns;i++)
{
MaterialsStructurePropertiesStream >> InfosOfStadFile;
qDebug() << InfosOfStadFile;
}
//find the values from the database
QString CName = "";
double Emmissivity;
double Absorptivity;
double ModulusOfElasticity;
double Density;
do
{
MaterialsStructurePropertiesStream >> CName;
qDebug()<< CName;
MaterialsStructurePropertiesStream >> ModulusOfElasticity;
qDebug()<< ModulusOfElasticity;
MaterialsStructurePropertiesStream >> Emmissivity;
qDebug()<< Emmissivity;
MaterialsStructurePropertiesStream >> Absorptivity;
qDebug()<< Absorptivity;
MaterialsStructurePropertiesStream >> Density;
qDebug()<< Density;
qDebug()<< "while - " <<((!(CName==Name))&&(!(CName=="UNDEFINED")));
}
while ((!(CName==Name))&&(!(CName=="UNDEFINED")));
// set the values from the database
SCMaterial.Name = CName;
qDebug()<<"SCMATerial" <<SCMaterial.Name;
qDebug()<<"enquiry" <<Name;
SCMaterial.ModulusOfElasticity = ModulusOfElasticity;
SCMaterial.Emmissivity = Emmissivity;
SCMaterial.Absorptivity = Absorptivity;
SCMaterial.Density = Density;
qDebug()<<"SCMaterial.Density"<<SCMaterial.Density;
MaterialsStructureProperties.close();
}
double StructureSubsystem::getModulusOfElasticity()
{
return SCMaterial.ModulusOfElasticity;
}
MaterialProperties StructureSubsystem::getSCMaterial()
{
return SCMaterial;
}
void StructureSubsystem::setMassEstimations(QString SCMission)
{
QString path = QString("data/Estimations/MassEstimations.stad");
QFile MassEstimations(path);
MassEstimations.open(QIODevice::ReadOnly);
// qDebug()<<MaterialsStructureProperties.fileName();
// qDebug()<<MaterialsStructureProperties.isOpen();
QTextStream MassEstimationsStream(&MassEstimations);
//to skip the first descriptive line of the "MaterialsStructureProperties.stad"
QString InfosOfStadFile;
int NumberOfColumns = 8;
int i;
for (i=0;i<NumberOfColumns;i++)
{
MassEstimationsStream >> InfosOfStadFile;
// qDebug() << InfosOfStadFile;
}
//find the values from the database
QString Mission = "";
double Payload;
double Structure;
double Thermal;
double Power;
double TTC;
double ADCS;
double Propulsion;
do
{
MassEstimationsStream >> Mission;
// qDebug()<< Mission;
MassEstimationsStream >> Payload;
// qDebug()<< Payload;
MassEstimationsStream >> Structure;
// qDebug()<< Structure;
MassEstimationsStream >> Thermal;
// qDebug()<< Thermal;
MassEstimationsStream >> Power;
// qDebug()<< Power;
MassEstimationsStream >> TTC;
// qDebug()<< TTC;
MassEstimationsStream >> ADCS;
// qDebug()<< ADCS;
MassEstimationsStream >> Propulsion;
// qDebug()<< Propulsion;
// qDebug()<< "while - " <<((!(Mission==SCMission))&&(!(Mission=="UNDEFINED")));
}
while ((!(Mission==SCMission))&&(!(Mission=="UNDEFINED")));
// set the values from the database
SCMassEstimatePercentages.MissionType = Mission;
qDebug()<<"SC Mission" <<SCMassEstimatePercentages.MissionType;
// qDebug()<<"enquiry" <<SCMission;
SCMassEstimatePercentages.PayloadPercentage = Payload;
SCMassEstimatePercentages.PowerSubsystemPercentage = Power;
SCMassEstimatePercentages.StructureSubsystemPercentage = Structure;
SCMassEstimatePercentages.ThermalSubsystemPercentage = Thermal;
SCMassEstimatePercentages.TTCSubsystemPercentage = TTC;
MassEstimations.close();
}
void StructureSubsystem::setPowerSubsystemMass(double mass)
{
SCMassDetails.PowerSubsystemMass = mass;
StructureSubsystem::CalculateAndSetSCMass();
}
double StructureSubsystem::getPowerSubsystemMass()
{
if (SCMassDetails.PowerSubsystemMass > 0.0)
return SCMassDetails.PowerSubsystemMass;
else
return (SCMassDetails.TotalPayloadMass
/ SCMassEstimatePercentages.PayloadPercentage
* SCMassEstimatePercentages.PowerSubsystemPercentage);
}
void StructureSubsystem::setOBDHSubsystemMass(double mass)
{
SCMassDetails.OBDHSubsystemMass = mass;
StructureSubsystem::CalculateAndSetSCMass();
}
double StructureSubsystem::getOBDHSubsystemMass()
{
if (SCMassDetails.OBDHSubsystemMass > 0.0)
return SCMassDetails.OBDHSubsystemMass;
else
return SCMassDetails.OBDHSubsystemMass; // has to be added to database
}
void StructureSubsystem::setThermalSubsystemMass(double mass)
{
SCMassDetails.ThermalSubsystemMass = mass;
StructureSubsystem::CalculateAndSetSCMass();
}
double StructureSubsystem::getThermalSubsystemMass()
{
if (SCMassDetails.ThermalSubsystemMass > 0.0)
return SCMassDetails.ThermalSubsystemMass;
else
return (SCMassDetails.TotalPayloadMass
/ SCMassEstimatePercentages.PayloadPercentage
* SCMassEstimatePercentages.ThermalSubsystemPercentage);
}
void StructureSubsystem::setTTCSubsystemMass(double mass)
{
SCMassDetails.TTCSubsystemMass = mass;
StructureSubsystem::CalculateAndSetSCMass();
}
double StructureSubsystem::getTTCSubsystemMass()
{
if (SCMassDetails.TTCSubsystemMass > 0.0)
return SCMassDetails.TTCSubsystemMass;
else
return (SCMassDetails.TotalPayloadMass
/ SCMassEstimatePercentages.PayloadPercentage
* SCMassEstimatePercentages.TTCSubsystemPercentage);
}
void StructureSubsystem::setStructureSubsystemMass(double mass)
{
SCMassDetails.StructureSubsystemMass = mass;
}
double StructureSubsystem::getStructureSubsystemMass()
{
/*calculate the mass of the Structure sum of the TotalAreaOfColdFace
* and TotalAreaOfHotFace is the Total Area of the Spacecraft
* if we assume the shell of the SC is 0.2cm. the mass will be as the following
* 20% margin is to consider the internal structure of the SC for the stability
*/
if (((SCThermalDetails.TotalAreaOfHotFace + SCThermalDetails.TotalAreaOfColdFace) > 0.0)
&&
(SCMaterial.Density > 0.0))
{
SCMassDetails.StructureSubsystemMass
= (SCThermalDetails.TotalAreaOfHotFace
+ SCThermalDetails.TotalAreaOfColdFace)
* 0.002 //0.2cm thickness
* SCMaterial.Density
* 1.2; //20% margin
// StructureSubsystem::CalculateAndSetSCMass();
}
if (SCMassDetails.StructureSubsystemMass > 0.0)
return SCMassDetails.StructureSubsystemMass;
else
return (SCMassDetails.TotalPayloadMass
/ SCMassEstimatePercentages.PayloadPercentage
* SCMassEstimatePercentages.StructureSubsystemPercentage);
}
void StructureSubsystem::setPowerSubsystemVolume(double volume)
{
SCVolumeDetails.PowerSubsystemVolume = volume;
// re-calculate the values with the new SC volume
CalculateAndSetSCVolume();
CalculateAndSetSpacecraftDimension();
CalculateAndSetMomentsOfInertia();
CalculateAndSetSecondMomentsOfInertia();
CalculateAndSetLateralFrequency();
CalculateAndSetAxialFrequency();
}
double StructureSubsystem::getPowerSubsystemVolume()
{
return SCVolumeDetails.PowerSubsystemVolume;
}
void StructureSubsystem::setOBDHSubsystemVolume(double volume)
{
SCVolumeDetails.OBDHSubsystemVolume = volume;
// re-calculate the values with the new SC volume
CalculateAndSetSCVolume();
CalculateAndSetSpacecraftDimension();
CalculateAndSetMomentsOfInertia();
CalculateAndSetSecondMomentsOfInertia();
CalculateAndSetLateralFrequency();
CalculateAndSetAxialFrequency();
}
double StructureSubsystem::getOBDHSubsystemVolume()
{
return SCVolumeDetails.OBDHSubsystemVolume;
}
void StructureSubsystem::setThermalSubsystemVolume(double volume)
{
SCVolumeDetails.ThermalSubsystemVolume = volume;
// re-calculate the values with the new SC volume
CalculateAndSetSCVolume();
CalculateAndSetSpacecraftDimension();
CalculateAndSetMomentsOfInertia();
CalculateAndSetSecondMomentsOfInertia();
CalculateAndSetLateralFrequency();
CalculateAndSetAxialFrequency();
}
double StructureSubsystem::getThermalSubsystemVolume()
{
return SCVolumeDetails.ThermalSubsystemVolume;
}
void StructureSubsystem::setTTCSubsystemVolume(double volume)
{
SCVolumeDetails.TTCSubsystemVolume = volume;
// re-calculate the values with the new SC volume
CalculateAndSetSCVolume();
CalculateAndSetSpacecraftDimension();
CalculateAndSetMomentsOfInertia();
CalculateAndSetSecondMomentsOfInertia();
CalculateAndSetLateralFrequency();
CalculateAndSetAxialFrequency();
}
double StructureSubsystem::getTTCSubsystemVolume()
{
return SCVolumeDetails.TTCSubsystemVolume;
}
double StructureSubsystem::getStructureSubsystemVolume()
{
SCVolumeDetails.StructureSubsystemVolume =
(SCThermalDetails.TotalAreaOfHotFace
+ SCThermalDetails.TotalAreaOfColdFace)
* 0.002; //2mm thickness
return SCVolumeDetails.StructureSubsystemVolume;
}
ThermalDetails * StructureSubsystem::getSCThermalDetails()
{
return &SCThermalDetails;
}
double StructureSubsystem::getTotalPayloadMass()
{
return SCMassDetails.TotalPayloadMass;
}
//----------------- End of StructureSubsystem Class Declaration -----------------//
| 33.197294 | 125 | 0.619439 | [
"shape"
] |
75ecf6ac9bf6ff6ac3f9b3e254728cac5dd7d300 | 866 | hpp | C++ | common/VectorNut.hpp | cjang/chai | 7faba752cc4491d1b30590abef21edc4efffa0f6 | [
"Unlicense"
] | 11 | 2015-06-12T19:54:14.000Z | 2021-11-26T10:45:18.000Z | common/VectorNut.hpp | cjang/chai | 7faba752cc4491d1b30590abef21edc4efffa0f6 | [
"Unlicense"
] | null | null | null | common/VectorNut.hpp | cjang/chai | 7faba752cc4491d1b30590abef21edc4efffa0f6 | [
"Unlicense"
] | null | null | null | // Copyright 2012 Chris Jang (fastkor@gmail.com) under The Artistic License 2.0
#ifndef _CHAI_VECTOR_NUT_HPP_
#define _CHAI_VECTOR_NUT_HPP_
#include <stdint.h>
#include <vector>
#include "FrontMem.hpp"
#include "SingleNut.hpp"
namespace chai_internal {
class AstVariable;
////////////////////////////////////////
// read and write to array variable
// nuts as vectors
class VectorNut
{
// array variable nuts store data values (and AST objects in alternative)
std::vector< SingleNut* > _nutVector;
public:
VectorNut(void);
void push(SingleNut*);
std::vector< FrontMem* > getNutMem(const uint32_t version);
AstVariable* getNutVar(const uint32_t version);
void setNutMem(const uint32_t version, const std::vector< FrontMem* >&);
void setNutVar(const uint32_t version, AstVariable*);
};
}; // namespace chai_internal
#endif
| 21.65 | 79 | 0.699769 | [
"vector"
] |
75f39888a3338b771017fd95c7fcf0373ddfa0b5 | 9,494 | cpp | C++ | p/interlinked-dylibs/update_dyld_shared_cache_compat.cpp | AgesX/old_dyld | 33d635b73c47ac6e7de93d3ebd6c3afa8d9458b4 | [
"MIT"
] | 672 | 2019-10-09T11:15:13.000Z | 2021-09-21T10:02:33.000Z | dyld-635.2/interlinked-dylibs/update_dyld_shared_cache_compat.cpp | KaiserFeng/KFAppleOpenSource | 7ea6ab19f1492a2da262d3554f90882393f975a4 | [
"MIT"
] | 19 | 2019-11-05T03:32:31.000Z | 2021-07-15T11:16:25.000Z | dyld-635.2/interlinked-dylibs/update_dyld_shared_cache_compat.cpp | KaiserFeng/KFAppleOpenSource | 7ea6ab19f1492a2da262d3554f90882393f975a4 | [
"MIT"
] | 216 | 2019-10-10T01:47:36.000Z | 2021-09-23T07:56:54.000Z | /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
*
* Copyright (c) 2014 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <signal.h>
#include <errno.h>
#include <sys/uio.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/resource.h>
#include <dirent.h>
#include <vector>
#include <set>
#include <map>
#include "mega-dylib-utils.h"
/*
This is a compatibility driver to allow us to support migrating to the new cache codebase and format without forcing B&I to alter gencaches.
This tool only supports flags used by B&I
This intention is for this tool to be removed in the near future and replaced with a tool that is not commandline compatible,
but allows shared caches to be built directly out of BuildRecords.
*/
/*
Example commandline:
[60042] INFO - Executing Command: /SWE/Teams/DT-SWB/iOS/Binaries/Binaries5/update_dyld_shared_cache/update_dyld_shared_cache-357.0.91~2/Root/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/usr/local/bin/update_dyld_shared_cache
-debug
-root /BuildRoot//Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.Internal.sdk
-dylib_list /tmp/dylibs.K93aInternalOS.60042
-cache_dir /tmp/K93aInternalOS.60042
-arch armv7
-iPhone
-dont_map_local_symbols
-overlay /SWE/Teams/DT-SWB/iOS/Binaries/Binaries5/XPCService_caches/XPCService_caches-119~94/Root/K93aInternalOS/
-overlay /SWE/Teams/DT-SWB/iOS/Binaries/Binaries5/libxpc_caches/libxpc_caches-649~18/Root/K93aInternalOS/
*/
// record warnings and add to .map file
static std::vector<std::unique_ptr<const char>> sWarnings;
static void write_cache(const char* cachePath, SharedCache& cache) {
// create temp file for cache
int fd = ::open(cachePath, O_CREAT | O_RDWR | O_TRUNC, 0644);
if ( fd == -1 )
terminate("can't create temp file %s, errnor=%d", cachePath, errno);
// try to allocate whole cache file contiguously
fstore_t fcntlSpec = { F_ALLOCATECONTIG|F_ALLOCATEALL, F_PEOFPOSMODE, 0, static_cast<off_t>(cache.fileSize()), 0 };
::fcntl(fd, F_PREALLOCATE, &fcntlSpec);
// write out cache file
if ( ::pwrite(fd, cache.buffer().get(), cache.fileSize(), 0) != cache.fileSize() )
terminate("write() failure creating cache file, errno=%d", errno);
// flush to disk and close
int result = ::fcntl(fd, F_FULLFSYNC, NULL);
if ( result == -1 )
warning("fcntl(F_FULLFSYNC) failed with errno=%d for %s\n", errno, cachePath);
::close(fd);
// write .map file
char mapPath[MAXPATHLEN];
strlcpy(mapPath, cachePath, MAXPATHLEN);
strlcat(mapPath, ".map", MAXPATHLEN);
cache.writeCacheMapFile(mapPath);
// append any warnings encountered
if ( !sWarnings.empty() ) {
FILE* fmap = ::fopen(mapPath, "a");
if ( fmap != NULL ) {
fprintf(fmap, "\n\n");
for ( std::unique_ptr<const char>& msg : sWarnings ) {
fprintf(fmap, "# %s", &*msg);
}
::fclose(fmap);
}
}
}
int main(int argc, const char* argv[])
{
std::set<ArchPair> onlyArchs;
const char *rootPath = NULL;
std::vector<const char*> searchPaths;
std::vector<std::unique_ptr<DylibProxy>> dylibs;
const char* dylibListFile = NULL;
// bool force = false;
// bool keepSignatures = false;
bool explicitCacheDir = false;
bool dontMapLocalSymbols = false;
bool verbose = false;
bool iPhoneOS = false;
const char* cacheDir = NULL;
const char* archStr = NULL;
ArchPair archPair(CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL);
// parse command line options
for(int i=1; i < argc; ++i) {
const char* arg = argv[i];
if ( arg[0] == '-' ) {
if ( strcmp(arg, "-debug") == 0 ) {
verbose = true;
}
else if ( strcmp(arg, "-dont_map_local_symbols") == 0 ) {
dontMapLocalSymbols = true;
}
else if ( strcmp(arg, "-iPhone") == 0 ) {
iPhoneOS = true;
}
else if ( strcmp(arg, "-dylib_list") == 0 ) {
dylibListFile = argv[++i];
if ( dylibListFile == NULL )
terminate("-dylib_list missing path argument\n");
}
else if ( (strcmp(arg, "-root") == 0) || (strcmp(arg, "--root") == 0) ) {
rootPath = argv[++i];
}
else if ( strcmp(arg, "-overlay") == 0 ) {
const char* path = argv[++i];
if ( path == NULL )
terminate("-overlay missing path argument\n");
searchPaths.push_back(path);
}
else if ( strcmp(arg, "-cache_dir") == 0 ) {
cacheDir = argv[++i];
if ( cacheDir == NULL )
terminate("-cache_dir missing path argument\n");
explicitCacheDir = true;
}
else if ( strcmp(arg, "-arch") == 0 ) {
archStr = argv[++i];
archPair = archForString(archStr); // terminates if unknown
}
else if ( strcmp(arg, "-force") == 0 ) {
// ignore. always forced for iOS
}
else {
//usage();
terminate("unknown option: %s\n", arg);
}
}
else {
//usage();
terminate("unknown option: %s\n", arg);
}
}
if (!rootPath) {
terminate("-root is a required option\n");
}
if (!iPhoneOS) {
terminate("-iPhone is a required option\n");
}
if (!cacheDir) {
terminate("-cache_dir is a required option\n");
}
if (!dylibListFile) {
terminate("-dylib_list is a required option\n");
}
if (!archStr) {
terminate("-arch is a required option\n");
}
char prodCachePath[MAXPATHLEN];
char devCachePath[MAXPATHLEN];
strcpy(prodCachePath, cacheDir);
if ( prodCachePath[strlen(prodCachePath)-1] != '/' )
strcat(prodCachePath, "/");
strcat(prodCachePath, "dyld_shared_cache_");
strcat(prodCachePath, archStr);
strcpy(devCachePath, prodCachePath);
strcat(devCachePath, ".development");
verboseLog("developement cache path = %s\n", devCachePath);
verboseLog("cache path = %s\n", prodCachePath);
// create cache dirs if needed
char neededDirs[1024];
strcpy(neededDirs, prodCachePath);
char* lastSlash = strrchr(neededDirs, '/');
if ( lastSlash != NULL )
lastSlash[1] = '\0';
struct stat stat_buf;
if ( stat(neededDirs, &stat_buf) != 0 ) {
const char* afterSlash = &neededDirs[1];
char* slash;
while ( (slash = strchr(afterSlash, '/')) != NULL ) {
*slash = '\0';
::mkdir(neededDirs, S_IRWXU | S_IRGRP|S_IXGRP | S_IROTH|S_IXOTH);
*slash = '/';
afterSlash = slash+1;
}
}
std::string dylibOrderFile = toolDir() + "/dylib-order.txt";
std::string dirtyDataOrderFile = toolDir() + "/dirty-data-segments-order.txt";
std::unordered_map<std::string, std::unordered_set<std::string>> dependents;
SharedCache devCache(rootPath, searchPaths, dylibListFile, archPair, dylibOrderFile, dirtyDataOrderFile);
if ( devCache.fileSize() == 0 )
terminate("Could not find all necessary dylibs\n");
devCache.buildUnoptimizedCache();
SharedCache prodCache = devCache;
prodCache.optimizeForProduction();
devCache.optimizeForDevelopment();
verboseLog("developement cache size = %llu", devCache.fileSize());
verboseLog("developement cache vm size = %llu", devCache.vmSize());
// optimize cache
write_cache(devCachePath, devCache);
if ( devCache.vmSize()+align(devCache.vmSize()/200, sharedRegionRegionAlignment(archPair)) > sharedRegionRegionSize(archPair)) {
terminate("update_dyld_shared_cache[%u] for arch=%s, shared cache will not fit in shared regions address space. Overflow amount: %llu\n",
getpid(), archStr, devCache.vmSize()+align(devCache.vmSize()/200, sharedRegionRegionAlignment(archPair)) - sharedRegionRegionSize(archPair));
}
write_cache(prodCachePath, prodCache);
return 0;
}
void uniqueWarning(const char* format, ...)
{
va_list list;
va_start(list, format);
vfprintf(stderr, format, list);
va_end(list);
fprintf(stderr, "\n");
}
void log(const char * __restrict format, ...)
{
va_list list;
va_start(list, format);
vfprintf(stderr, format, list);
va_end(list);
fprintf(stderr, "\n");
}
void verboseLog(const char* format, ...)
{
va_list list;
va_start(list, format);
vfprintf(stderr, format, list);
va_end(list);
fprintf(stderr, "\n");
}
void warning(const char* format, ...)
{
fprintf(stderr, "update_dyld_shared_cache warning: ");
va_list list;
va_start(list, format);
char* msg;
vasprintf(&msg, format, list);
va_end(list);
fprintf(stderr, "%s\n", msg);
sWarnings.push_back(std::unique_ptr<const char>(msg));
}
void terminate(const char* format, ...)
{
fprintf(stderr, "update_dyld_shared_cache error: ");
va_list list;
va_start(list, format);
vfprintf(stderr, format, list);
va_end(list);
exit(1);
}
| 30.625806 | 252 | 0.69328 | [
"vector"
] |
75ffdf002938274064b615a0cc8f7499849c9261 | 2,849 | cpp | C++ | lintcode/smallestRecwithBlack.cpp | Broadroad/learnLeetcode | c4af121b3451caa4d53819c5f8c62b38e8e5fb87 | [
"Apache-2.0"
] | null | null | null | lintcode/smallestRecwithBlack.cpp | Broadroad/learnLeetcode | c4af121b3451caa4d53819c5f8c62b38e8e5fb87 | [
"Apache-2.0"
] | null | null | null | lintcode/smallestRecwithBlack.cpp | Broadroad/learnLeetcode | c4af121b3451caa4d53819c5f8c62b38e8e5fb87 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
/**
* @param image: a binary matrix with '0' and '1'
* @param x: the location of one of the black pixels
* @param y: the location of one of the black pixels
* @return: an integer
*/
int minArea(vector<vector<char>> &image, int x, int y) {
if (image.size() == 0 || image[0].size() == 0) {
return 0;
}
int n = image.size();
int m = image[0].size();
int left = findLeft(image, 0, y);
int right = findRight(image, y, m - 1);
int top = findTop(image, 0, x);
int bottom = findBottom(image, x, n - 1);
return (right - left + 1) * (bottom - top + 1);
}
private:
int findLeft(vector<vector<char>> &image, int start, int end) {
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (isEmptyCol(image, mid)) {
start = mid;
} else {
end = mid;
}
}
if (isEmptyCol(image, start)) {
return end;
}
return start;
}
int findRight(vector<vector<char>> &image, int start, int end) {
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (isEmptyCol(image, mid)) {
end = mid;
} else {
start = mid;
}
}
if (isEmptyCol(image, end)) {
return start;
}
return end;
}
int findTop(vector<vector<char>> &image, int start, int end) {
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (isEmptyRow(image, mid)) {
start = mid;
} else {
end = mid;
}
}
if (isEmptyRow(image, start)) {
return end;
}
return start;
}
int findBottom(vector<vector<char>> &image, int start, int end) {
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (isEmptyRow(image, mid)) {
end = mid;
} else {
start = mid;
}
}
if (isEmptyRow(image, end)) {
return start;
}
return end;
}
bool isEmptyCol(vector<vector<char>> &image, int col) {
for (int i = 0; i < image.size(); i++) {
if (image[i][col] == '1') {
return false;
}
}
return true;
}
bool isEmptyRow(vector<vector<char>> &image, int row) {
for (int i = 0; i < image[0].size(); i++) {
if (image[row][i] == '1') {
return false;
}
}
return true;
}
}; | 26.37963 | 69 | 0.41769 | [
"vector"
] |
2f0f9d00b6886e96861e70f3015b349306d2963e | 1,369 | cpp | C++ | ch10/ex10_3_4.cpp | jl1987/Cpp-Primer | 028dcb44318667bb8713c82ce0c86676a3dcda27 | [
"CC0-1.0"
] | 1 | 2019-05-02T19:19:11.000Z | 2019-05-02T19:19:11.000Z | ch10/ex10_3_4.cpp | jl1987/Cpp-Primer | 028dcb44318667bb8713c82ce0c86676a3dcda27 | [
"CC0-1.0"
] | null | null | null | ch10/ex10_3_4.cpp | jl1987/Cpp-Primer | 028dcb44318667bb8713c82ce0c86676a3dcda27 | [
"CC0-1.0"
] | null | null | null | //! @Alan
//!
//! Exercise 10.3:
//! Use accumulate to sum the elements in a vector<int>.
//!
//! Exercise 10.4:
//! Assuming v is a vector<double>, what, if anything,
//! is wrong with calling accumulate(v.cbegin(), v.cend(), 0)?
// Check the comments below.
//!
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
//! Exercise 10.3
int
accumulate_int_fromVec(const std::vector<int> &v);
int main()
{
//! Exercise 10.3
std::vector<int> v = {1,2,3,4};
std::cout << accumulate_int_fromVec(v) << " ";
//! Exercise 10.4
std::vector<double> vd = {1.1, 0.5, 3.3};
std::cout << std::accumulate(vd.cbegin(), vd.cend(), 0);
//! ^
//! The ouput is 4 rather than 4.9.
//! The reason is std::accumulate is a template function. The third parameter is _Tp __init
//! When "0" , an integer, had been specified here, the compiler considered _Tp should been
//! an interger.As a result ,when the following statments were being excuted :
// for (; __first != __last; ++__first)
// __init = __init + *__first;
// return __init;
//! all calculation would be converted to integer.
return 0;
}
//! Exercise 10.3
int accumulate_int_fromVec(const std::vector<int> &v)
{
return std::accumulate(v.cbegin(), v.cend(), 0);
}
| 27.38 | 95 | 0.609204 | [
"vector"
] |
2f17a5a93cad518445b0fe25303e2d1a93d860b9 | 3,628 | cpp | C++ | aws-cpp-sdk-location/source/model/CalculateRouteRequest.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-location/source/model/CalculateRouteRequest.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-location/source/model/CalculateRouteRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/location/model/CalculateRouteRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::LocationService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
CalculateRouteRequest::CalculateRouteRequest() :
m_calculatorNameHasBeenSet(false),
m_carModeOptionsHasBeenSet(false),
m_departNow(false),
m_departNowHasBeenSet(false),
m_departurePositionHasBeenSet(false),
m_departureTimeHasBeenSet(false),
m_destinationPositionHasBeenSet(false),
m_distanceUnit(DistanceUnit::NOT_SET),
m_distanceUnitHasBeenSet(false),
m_includeLegGeometry(false),
m_includeLegGeometryHasBeenSet(false),
m_travelMode(TravelMode::NOT_SET),
m_travelModeHasBeenSet(false),
m_truckModeOptionsHasBeenSet(false),
m_waypointPositionsHasBeenSet(false)
{
}
Aws::String CalculateRouteRequest::SerializePayload() const
{
JsonValue payload;
if(m_carModeOptionsHasBeenSet)
{
payload.WithObject("CarModeOptions", m_carModeOptions.Jsonize());
}
if(m_departNowHasBeenSet)
{
payload.WithBool("DepartNow", m_departNow);
}
if(m_departurePositionHasBeenSet)
{
Array<JsonValue> departurePositionJsonList(m_departurePosition.size());
for(unsigned departurePositionIndex = 0; departurePositionIndex < departurePositionJsonList.GetLength(); ++departurePositionIndex)
{
departurePositionJsonList[departurePositionIndex].AsDouble(m_departurePosition[departurePositionIndex]);
}
payload.WithArray("DeparturePosition", std::move(departurePositionJsonList));
}
if(m_departureTimeHasBeenSet)
{
payload.WithString("DepartureTime", m_departureTime.ToGmtString(DateFormat::ISO_8601));
}
if(m_destinationPositionHasBeenSet)
{
Array<JsonValue> destinationPositionJsonList(m_destinationPosition.size());
for(unsigned destinationPositionIndex = 0; destinationPositionIndex < destinationPositionJsonList.GetLength(); ++destinationPositionIndex)
{
destinationPositionJsonList[destinationPositionIndex].AsDouble(m_destinationPosition[destinationPositionIndex]);
}
payload.WithArray("DestinationPosition", std::move(destinationPositionJsonList));
}
if(m_distanceUnitHasBeenSet)
{
payload.WithString("DistanceUnit", DistanceUnitMapper::GetNameForDistanceUnit(m_distanceUnit));
}
if(m_includeLegGeometryHasBeenSet)
{
payload.WithBool("IncludeLegGeometry", m_includeLegGeometry);
}
if(m_travelModeHasBeenSet)
{
payload.WithString("TravelMode", TravelModeMapper::GetNameForTravelMode(m_travelMode));
}
if(m_truckModeOptionsHasBeenSet)
{
payload.WithObject("TruckModeOptions", m_truckModeOptions.Jsonize());
}
if(m_waypointPositionsHasBeenSet)
{
Array<JsonValue> waypointPositionsJsonList(m_waypointPositions.size());
for(unsigned waypointPositionsIndex = 0; waypointPositionsIndex < waypointPositionsJsonList.GetLength(); ++waypointPositionsIndex)
{
Array<JsonValue> positionJsonList(m_waypointPositions[waypointPositionsIndex].size());
for(unsigned positionIndex = 0; positionIndex < positionJsonList.GetLength(); ++positionIndex)
{
positionJsonList[positionIndex].AsDouble(m_waypointPositions[waypointPositionsIndex][positionIndex]);
}
waypointPositionsJsonList[waypointPositionsIndex].AsArray(std::move(positionJsonList));
}
payload.WithArray("WaypointPositions", std::move(waypointPositionsJsonList));
}
return payload.View().WriteReadable();
}
| 29.983471 | 141 | 0.777563 | [
"model"
] |
2f1a0c44d02b0b85d6c5d76db5d908e1d6f63554 | 8,077 | cpp | C++ | examples/ThirdPartyLibs/Gwen/Controls/TreeControl.cpp | felipeek/bullet3 | 6a59241074720e9df119f2f86bc01765917feb1e | [
"Zlib"
] | 9,136 | 2015-01-02T00:41:45.000Z | 2022-03-31T15:30:02.000Z | examples/ThirdPartyLibs/Gwen/Controls/TreeControl.cpp | felipeek/bullet3 | 6a59241074720e9df119f2f86bc01765917feb1e | [
"Zlib"
] | 2,424 | 2015-01-05T08:55:58.000Z | 2022-03-30T19:34:55.000Z | examples/ThirdPartyLibs/Gwen/Controls/TreeControl.cpp | felipeek/bullet3 | 6a59241074720e9df119f2f86bc01765917feb1e | [
"Zlib"
] | 2,921 | 2015-01-02T10:19:30.000Z | 2022-03-31T02:48:42.000Z | /*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#include "Gwen/Controls/TreeControl.h"
#include "Gwen/Controls/ScrollControl.h"
#include "Gwen/Utility.h"
using namespace Gwen;
using namespace Gwen::Controls;
GWEN_CONTROL_CONSTRUCTOR(TreeControl)
{
m_TreeControl = this;
m_bUpdateScrollBar = 2;
m_ToggleButton->DelayedDelete();
m_ToggleButton = NULL;
m_Title->DelayedDelete();
m_Title = NULL;
m_InnerPanel->DelayedDelete();
m_InnerPanel = NULL;
m_bAllowMultipleSelection = false;
m_ScrollControl = new ScrollControl(this);
m_ScrollControl->Dock(Pos::Fill);
m_ScrollControl->SetScroll(false, true);
m_ScrollControl->SetAutoHideBars(true);
m_ScrollControl->SetMargin(Margin(1, 1, 1, 1));
m_InnerPanel = m_ScrollControl;
m_ScrollControl->SetInnerSize(1000, 1000);
}
void TreeControl::Render(Skin::Base* skin)
{
if (ShouldDrawBackground())
skin->DrawTreeControl(this);
}
void TreeControl::ForceUpdateScrollBars()
{
m_ScrollControl->UpdateScrollBars();
}
void TreeControl::OnChildBoundsChanged(Gwen::Rect /*oldChildBounds*/, Base* /*pChild*/)
{
}
void TreeControl::Clear()
{
m_ScrollControl->Clear();
}
void TreeControl::Layout(Skin::Base* skin)
{
BaseClass::BaseClass::Layout(skin);
}
void TreeControl::PostLayout(Skin::Base* skin)
{
BaseClass::BaseClass::PostLayout(skin);
}
void TreeControl::OnNodeAdded(TreeNode* pNode)
{
pNode->onNamePress.Add(this, &TreeControl::OnNodeSelection);
}
void TreeControl::OnNodeSelection(Controls::Base* /*control*/)
{
//printf("TreeControl::OnNodeSelection\n");
if (!m_bAllowMultipleSelection || !Gwen::Input::IsKeyDown(Key::Control))
DeselectAll();
}
void TreeControl::iterate(int action, int* maxItem, int* curItem)
{
Base::List& children = m_InnerPanel->GetChildren();
for (Base::List::iterator iter = children.begin(); iter != children.end(); ++iter)
{
TreeNode* pChild = (*iter)->DynamicCastTreeNode();
if (!pChild)
continue;
pChild->iterate(action, maxItem, curItem);
}
}
bool TreeControl::OnKeyUp(bool bDown)
{
if (bDown)
{
// int maxIndex = 0;
int newIndex = 0;
int maxItem = 0;
int curItem = -1;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX, &maxItem, &curItem);
// maxIndex = maxItem;
int targetItem = curItem;
if (curItem > 0)
{
maxItem = 0;
int deselectIndex = targetItem;
targetItem--;
newIndex = targetItem;
iterate(ITERATE_ACTION_SELECT, &maxItem, &targetItem);
if (targetItem < 0)
{
maxItem = 0;
iterate(ITERATE_ACTION_DESELECT_INDEX, &maxItem, &deselectIndex);
}
curItem = newIndex;
// float amount = float(newIndex)/float(maxIndex);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
// float minCoordViewableWindow = curAmount*contSize;
//float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem * 16.f;
// float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize != viewSize)
{
{
float newAmount = float(minCoordSelectedItem) / (contSize - viewSize);
if (newAmount < curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount, true);
}
}
{
int numItems = (viewSize) / 16 - 1;
float newAmount = float((curItem - numItems) * 16) / (contSize - viewSize);
if (newAmount > curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount, true);
}
}
}
}
}
ForceUpdateScrollBars();
return true;
}
bool TreeControl::OnKeyDown(bool bDown)
{
if (bDown)
{
// int maxIndex = 0;
int newIndex = 0;
int maxItem = 0;
int curItem = -1;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX, &maxItem, &curItem);
// maxIndex = maxItem;
int targetItem = curItem;
if (curItem >= 0)
{
maxItem = 0;
int deselectIndex = targetItem;
targetItem++;
newIndex = targetItem;
iterate(ITERATE_ACTION_SELECT, &maxItem, &targetItem);
if (targetItem < 0)
{
maxItem = 0;
iterate(ITERATE_ACTION_DESELECT_INDEX, &maxItem, &deselectIndex);
}
curItem = newIndex;
// float amount = (int)float(newIndex)/float(maxIndex);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
// float minCoordViewableWindow = curAmount*contSize;
//float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem * 16.f;
//float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize != viewSize)
{
{
float newAmount = float(minCoordSelectedItem) / (contSize - viewSize);
if (newAmount < curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount, true);
}
}
{
int numItems = (viewSize) / 16 - 1;
float newAmount = float((curItem - numItems) * 16) / (contSize - viewSize);
if (newAmount > curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount, true);
}
}
}
}
}
ForceUpdateScrollBars();
return true;
}
extern int avoidUpdate;
bool TreeControl::OnKeyRight(bool bDown)
{
if (bDown)
{
avoidUpdate = -3;
iterate(ITERATE_ACTION_OPEN, 0, 0);
int maxItem = 0;
int curItem = 0;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX, &maxItem, &curItem);
// float amount = float(curItem)/float(maxItem);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
// float minCoordViewableWindow = curAmount*contSize;
// float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem * 16.f;
// float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize != viewSize)
{
{
float newAmount = float(minCoordSelectedItem) / (contSize - viewSize);
if (newAmount < curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount, true);
}
}
{
int numItems = (viewSize) / 16 - 1;
float newAmount = float((curItem - numItems) * 16) / (contSize - viewSize);
if (newAmount > curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount, true);
}
}
}
Invalidate();
}
ForceUpdateScrollBars();
return true;
}
bool TreeControl::OnKeyLeft(bool bDown)
{
if (bDown)
{
avoidUpdate = -3;
iterate(ITERATE_ACTION_CLOSE, 0, 0);
int maxItems = 0;
int curItem = 0;
iterate(ITERATE_ACTION_FIND_SELECTED_INDEX, &maxItems, &curItem);
// float amount = float(curItem)/float(maxItems);
// m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(amount,true);
float viewSize = m_ScrollControl->m_VerticalScrollBar->getViewableContentSize();
float contSize = m_ScrollControl->m_VerticalScrollBar->getContentSize();
float curAmount = m_ScrollControl->m_VerticalScrollBar->GetScrolledAmount();
// float minCoordViewableWindow = curAmount*contSize;
// float maxCoordViewableWindow = minCoordViewableWindow+viewSize;
float minCoordSelectedItem = curItem * 16.f;
// float maxCoordSelectedItem = (curItem+1)*16.f;
if (contSize != viewSize)
{
{
float newAmount = float(minCoordSelectedItem) / (contSize - viewSize);
if (newAmount < curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount, true);
}
}
{
int numItems = (viewSize) / 16 - 1;
float newAmount = float((curItem - numItems) * 16) / (contSize - viewSize);
if (newAmount > curAmount)
{
m_ScrollControl->m_VerticalScrollBar->SetScrolledAmount(newAmount, true);
}
Invalidate();
}
}
//viewSize/contSize
//printf("!\n");
//this->Layout(0);
}
ForceUpdateScrollBars();
return true;
}
| 26.656766 | 87 | 0.704469 | [
"render"
] |
2f20fd97398b99a321b82a394fb47942f408f9d1 | 5,711 | cc | C++ | DPGAnalysis/Skims/src/ZElectronsSelector.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | DPGAnalysis/Skims/src/ZElectronsSelector.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | DPGAnalysis/Skims/src/ZElectronsSelector.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | // -*- C++ -*-
// Class: ZElectronsSelector
//
// Original Author: Silvia Taroni
// Created: Wed, 29 Nov 2017 18:23:54 GMT
//
//
#include "FWCore/PluginManager/interface/ModuleDef.h"
// system include files
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// user include files
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/global/EDFilter.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/EgammaCandidates/interface/GsfElectron.h"
#include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h"
#include "DataFormats/GsfTrackReco/interface/GsfTrack.h"
#include "DataFormats/JetReco/interface/PFJetCollection.h"
#include "CommonTools/UtilAlgos/interface/SingleObjectSelector.h"
//
#include "FWCore/Utilities/interface/InputTag.h"
#include "FWCore/Framework/interface/ConsumesCollector.h"
#include "CommonTools/UtilAlgos/interface/SingleObjectSelector.h"
#include "DataFormats/Common/interface/View.h"
using namespace std;
using namespace reco;
namespace edm { class EventSetup; }
class ZElectronsSelector {
public:
ZElectronsSelector(const edm::ParameterSet&, edm::ConsumesCollector & iC );
bool operator()(const reco::GsfElectron & ) const;
void newEvent (const edm::Event&, const edm::EventSetup&);
const float getEffectiveArea(float eta) const;
void printEffectiveAreas() const;
edm::EDGetTokenT<double> theRhoToken;
edm::EDGetTokenT<reco::GsfElectronCollection> theGsfEToken;
edm::Handle< double > _rhoHandle;
std::vector<double> absEtaMin_; // low limit of the eta range
std::vector<double> absEtaMax_; // upper limit of the eta range
std::vector<double> effectiveAreaValues_; // effective area for this eta range
edm::ParameterSet eleIDWP;
vector<int> missHits ;
vector<double> sigmaIEtaIEtaCut;
vector<double> dEtaInSeedCut ;
vector<double> dPhiInCut ;
vector<double> hOverECut ;
vector<double> relCombIso ;
vector<double> EInvMinusPInv ;
};
void ZElectronsSelector::printEffectiveAreas() const {
printf(" eta_min eta_max effective area\n");
uint nEtaBins = absEtaMin_.size();
for(uint iEta = 0; iEta<nEtaBins; iEta++){
printf(" %8.4f %8.4f %8.5f\n",
absEtaMin_[iEta], absEtaMax_[iEta],
effectiveAreaValues_[iEta]);
}
}
const float ZElectronsSelector::getEffectiveArea(float eta) const{
float effArea = 0;
uint nEtaBins = absEtaMin_.size();
for(uint iEta = 0; iEta<nEtaBins; iEta++){
if( std::abs(eta) >= absEtaMin_[iEta]
&& std::abs(eta) < absEtaMax_[iEta] ){
effArea = effectiveAreaValues_[iEta];
break;
}
}
return effArea;
}
ZElectronsSelector::ZElectronsSelector(const edm::ParameterSet& cfg, edm::ConsumesCollector & iC ) :
theRhoToken(iC.consumes <double> (cfg.getParameter<edm::InputTag>("rho")))
{
absEtaMin_ = cfg.getParameter<std::vector<double> >("absEtaMin");
absEtaMax_ = cfg.getParameter<std::vector<double> >("absEtaMax");
effectiveAreaValues_= cfg.getParameter<std::vector<double> >("effectiveAreaValues");
//printEffectiveAreas();
eleIDWP = cfg.getParameter<edm::ParameterSet>("eleID");
missHits = eleIDWP.getParameter<std::vector<int> >("missingHitsCut");
sigmaIEtaIEtaCut= eleIDWP.getParameter<std::vector<double> >("full5x5_sigmaIEtaIEtaCut");
dEtaInSeedCut = eleIDWP.getParameter<std::vector<double> >("dEtaInSeedCut");
dPhiInCut = eleIDWP.getParameter<std::vector<double> >("dPhiInCut");
hOverECut = eleIDWP.getParameter<std::vector<double> >("hOverECut");
relCombIso = eleIDWP.getParameter<std::vector<double> >("relCombIsolationWithEACut");
EInvMinusPInv = eleIDWP.getParameter<std::vector<double> >("EInverseMinusPInverseCut");
}
void ZElectronsSelector::newEvent(const edm::Event& ev, const edm::EventSetup& ){
ev.getByToken(theRhoToken,_rhoHandle);
}
bool ZElectronsSelector::operator()(const reco::GsfElectron& el) const{
float pt_e = el.pt();
unsigned int ind=0;
auto etrack = el.gsfTrack();
float abseta = fabs((el.superCluster().get())->position().eta());
if (el.isEB()){
if (abseta> 1.479) return false; // check if it is really needed
}
if (el.isEE()){
ind=1;
if (abseta< 1.479) return false; // check if it is really needed
if (abseta>=2.5 ) return false; // check if it is really needed
}
if (etrack->hitPattern().numberOfLostHits(reco::HitPattern::MISSING_INNER_HITS)>missHits[ind]) return false;
if (el.full5x5_sigmaIetaIeta() > sigmaIEtaIEtaCut[ind]) return false;
if (fabs(el.deltaPhiSuperClusterTrackAtVtx())> dPhiInCut[ind]) return false;
if (fabs(el.deltaEtaSeedClusterTrackAtVtx())> dEtaInSeedCut[ind]) return false;
if (el.hadronicOverEm()>hOverECut[ind]) return false;
const float eA = getEffectiveArea( abseta );
const float rho = _rhoHandle.isValid() ? (float)(*_rhoHandle.product()) : 0;
if (( el.pfIsolationVariables().sumChargedHadronPt +
std::max(float(0.0), el.pfIsolationVariables().sumNeutralHadronEt +
el.pfIsolationVariables().sumPhotonEt - eA*rho )
) > relCombIso[ind]*pt_e) return false;
const float ecal_energy_inverse = 1.0/el.ecalEnergy();
const float eSCoverP = el.eSuperClusterOverP();
if ( std::abs(1.0 - eSCoverP)*ecal_energy_inverse > EInvMinusPInv[ind]) return false;
return true;
}
EVENTSETUP_STD_INIT(ZElectronsSelector);
typedef SingleObjectSelector<
edm::View<reco::GsfElectron>,
ZElectronsSelector
> ZElectronsSelectorAndSkim;
DEFINE_FWK_MODULE( ZElectronsSelectorAndSkim );
| 33.397661 | 111 | 0.725092 | [
"vector"
] |
2f2de0ed0f4a03facaadf556e2cf840a6e39dc8b | 17,216 | cxx | C++ | ThirdParty/CosmoHaloFinder/vtkcosmohalofinder/FOFDistribute.cxx | xj361685640/ParaView | 0a27eef5abc5a0c0472ab0bc806c4db881156e64 | [
"Apache-2.0",
"BSD-3-Clause"
] | 815 | 2015-01-03T02:14:04.000Z | 2022-03-26T07:48:07.000Z | ThirdParty/CosmoHaloFinder/vtkcosmohalofinder/FOFDistribute.cxx | xj361685640/ParaView | 0a27eef5abc5a0c0472ab0bc806c4db881156e64 | [
"Apache-2.0",
"BSD-3-Clause"
] | 9 | 2015-04-28T20:10:37.000Z | 2021-08-20T18:19:01.000Z | ThirdParty/CosmoHaloFinder/vtkcosmohalofinder/FOFDistribute.cxx | xj361685640/ParaView | 0a27eef5abc5a0c0472ab0bc806c4db881156e64 | [
"Apache-2.0",
"BSD-3-Clause"
] | 328 | 2015-01-22T23:11:46.000Z | 2022-03-14T06:07:52.000Z | /*=========================================================================
Copyright (c) 2007, Los Alamos National Security, LLC
All rights reserved.
Copyright 2007. Los Alamos National Security, LLC.
This software was produced under U.S. Government contract DE-AC52-06NA25396
for Los Alamos National Laboratory (LANL), which is operated by
Los Alamos National Security, LLC for the U.S. Department of Energy.
The U.S. Government has rights to use, reproduce, and distribute this software.
NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY,
EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.
If software is modified to produce derivative works, such modified software
should be clearly marked, so as not to confuse it with the version available
from LANL.
Additionally, redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of Los Alamos National Security, LLC, Los Alamos National
Laboratory, LANL, the U.S. Government, nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY LOS ALAMOS NATIONAL SECURITY, LLC AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL LOS ALAMOS NATIONAL SECURITY, LLC OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <stddef.h>
#include <sys/types.h>
#include <dirent.h>
#include "Partition.h"
#include "FOFDistribute.h"
#include "GenericIOMPIReader.h"
#include "SimpleTimings.h"
#include <cstring>
using namespace std;
namespace cosmotk {
/////////////////////////////////////////////////////////////////////////
//
// Halo data space is partitioned for the number of processors
// which currently is a factor of two but is easily extended. Halos
// are read in from files where each processor reads one file into a buffer,
// extracts the halos which really belong on the processor (ALIVE) and
// those in a buffer region around the edge (DEAD). The buffer is then
// passed round robin to every other processor so that all halos are
// examined by all processors. All dead halos are tagged with the
// neighbor zone (26 neighbors in 3D) so that later halos can be associated
// with zones.
//
/////////////////////////////////////////////////////////////////////////
FOFDistribute::FOFDistribute()
{
// Get the number of processors running this problem and rank
this->numProc = Partition::getNumProc();
this->myProc = Partition::getMyProc();
// Get the number of processors in each dimension
Partition::getDecompSize(this->layoutSize);
// Get my position within the Cartesian topology
Partition::getMyPosition(this->layoutPos);
// Get neighbors of this processor including the wraparound
Partition::getNeighbors(this->neighbor);
this->numberOfAliveHalos = 0;
}
FOFDistribute::~FOFDistribute()
{
}
/////////////////////////////////////////////////////////////////////////
//
// Set parameters for halo distribution
//
/////////////////////////////////////////////////////////////////////////
void FOFDistribute::setParameters(
const string& baseName,
POSVEL_T rL)
{
// Base file name which will have processor id appended for actual files
this->baseFile = baseName;
// Physical total space and amount of physical space to use for dead halos
this->boxSize = rL;
if (this->myProc == MASTER) {
cout << endl << "------------------------------------" << endl;
cout << "boxSize: " << this->boxSize << endl;
}
}
/////////////////////////////////////////////////////////////////////////
//
// Set box sizes for determining if a halo is in the alive or dead
// region of this processor. Data space is a DIMENSION torus.
//
/////////////////////////////////////////////////////////////////////////
void FOFDistribute::initialize()
{
#ifdef DEBUG
if (this->myProc == MASTER)
cout << "Decomposition: [" << this->layoutSize[0] << ":"
<< this->layoutSize[1] << ":" << this->layoutSize[2] << "]" << endl;
#endif
// Set subextents on halo locations for this processor
POSVEL_T boxStep[DIMENSION];
for (int dim = 0; dim < DIMENSION; dim++) {
boxStep[dim] = this->boxSize / this->layoutSize[dim];
// Alive halos
this->minAlive[dim] = this->layoutPos[dim] * boxStep[dim];
this->maxAlive[dim] = this->minAlive[dim] + boxStep[dim];
if (this->maxAlive[dim] > this->boxSize)
this->maxAlive[dim] = this->boxSize;
}
}
void FOFDistribute::setHalos(vector<POSVEL_T>* xLoc,
vector<POSVEL_T>* yLoc,
vector<POSVEL_T>* zLoc,
vector<POSVEL_T>* xVel,
vector<POSVEL_T>* yVel,
vector<POSVEL_T>* zVel,
vector<POSVEL_T>* mass,
vector<POSVEL_T>* xCenter,
vector<POSVEL_T>* yCenter,
vector<POSVEL_T>* zCenter,
vector<POSVEL_T>* vDisp,
vector<ID_T>* id,
vector<int>* cnt)
{
this->xx = xLoc;
this->yy = yLoc;
this->zz = zLoc;
this->vx = xVel;
this->vy = yVel;
this->vz = zVel;
this->ms = mass;
this->cx = xCenter;
this->cy = yCenter;
this->cz = zCenter;
this->vdisp = vDisp;
this->tag = id;
this->count = cnt;
}
void FOFDistribute::readHalosGIO(int reserveQ, bool useAlltoallv,
bool redistCenter)
{
gio::GenericIOMPIReader GIO;
GIO.SetCommunicator(Partition::getComm());
GIO.SetFileName(this->baseFile);
GIO.OpenAndReadHeader();
MPI_Datatype CosmoHaloType;
{
MPI_Datatype type[3] = { MPI_FLOAT, MPI_LONG, MPI_UB };
int blocklen[3] = { 11, 2, 1 };
MPI_Aint disp[3] = { offsetof(CosmoHalo, floatData),
offsetof(CosmoHalo, intData),
sizeof(CosmoHalo) };
MPI_Type_struct(3, blocklen, disp, type, &CosmoHaloType);
MPI_Type_commit(&CosmoHaloType);
}
std::vector<int> pCounts(numProc), pRecvCounts(numProc),
pDisp(numProc), pRecvDisp(numProc);
std::vector< std::vector<CosmoHalo> > pByProc(numProc);
std::vector<CosmoHalo> pBuffer, pRecvBuffer;
this->haloCount = GIO.GetNumberOfElements();
this->xx->resize(haloCount + gio::CRCSize/sizeof(POSVEL_T));
this->yy->resize(haloCount + gio::CRCSize/sizeof(POSVEL_T));
this->zz->resize(haloCount + gio::CRCSize/sizeof(POSVEL_T));
this->vx->resize(haloCount + gio::CRCSize/sizeof(POSVEL_T));
this->vy->resize(haloCount + gio::CRCSize/sizeof(POSVEL_T));
this->vz->resize(haloCount + gio::CRCSize/sizeof(POSVEL_T));
this->ms->resize(haloCount + gio::CRCSize/sizeof(POSVEL_T));
this->cx->resize(haloCount + gio::CRCSize/sizeof(POSVEL_T));
this->cy->resize(haloCount + gio::CRCSize/sizeof(POSVEL_T));
this->cz->resize(haloCount + gio::CRCSize/sizeof(POSVEL_T));
this->vdisp->resize(haloCount + gio::CRCSize/sizeof(POSVEL_T));
this->tag->resize(haloCount + gio::CRCSize/sizeof(ID_T));
this->count->resize(haloCount + gio::CRCSize/sizeof(int));
GIO.AddVariable("fof_halo_mean_x", *this->xx, gio::GenericIOBase::ValueHasExtraSpace);
GIO.AddVariable("fof_halo_mean_y", *this->yy, gio::GenericIOBase::ValueHasExtraSpace);
GIO.AddVariable("fof_halo_mean_z", *this->zz, gio::GenericIOBase::ValueHasExtraSpace);
GIO.AddVariable("fof_halo_mean_vx", *this->vx, gio::GenericIOBase::ValueHasExtraSpace);
GIO.AddVariable("fof_halo_mean_vy", *this->vy, gio::GenericIOBase::ValueHasExtraSpace);
GIO.AddVariable("fof_halo_mean_vz", *this->vz, gio::GenericIOBase::ValueHasExtraSpace);
GIO.AddVariable("fof_halo_mass", *this->ms, gio::GenericIOBase::ValueHasExtraSpace);
GIO.AddVariable("fof_halo_center_x", *this->cx, gio::GenericIOBase::ValueHasExtraSpace);
GIO.AddVariable("fof_halo_center_y", *this->cy, gio::GenericIOBase::ValueHasExtraSpace);
GIO.AddVariable("fof_halo_center_z", *this->cz, gio::GenericIOBase::ValueHasExtraSpace);
GIO.AddVariable("fof_halo_tag", *this->tag, gio::GenericIOBase::ValueHasExtraSpace);
GIO.AddVariable("fof_halo_count", *this->count, gio::GenericIOBase::ValueHasExtraSpace);
GIO.ReadData();
this->xx->resize(haloCount);
this->yy->resize(haloCount);
this->zz->resize(haloCount);
this->vx->resize(haloCount);
this->vy->resize(haloCount);
this->vz->resize(haloCount);
this->ms->resize(haloCount);
this->cx->resize(haloCount);
this->cy->resize(haloCount);
this->cz->resize(haloCount);
this->vdisp->resize(haloCount);
this->tag->resize(haloCount);
this->count->resize(haloCount);
// Find a home for every halo...
for (int i = 0; i < haloCount; ++i) {
if ((*this->xx)[i] >= this->boxSize)
(*this->xx)[i] -= this->boxSize;
if ((*this->yy)[i] >= this->boxSize)
(*this->yy)[i] -= this->boxSize;
if ((*this->zz)[i] >= this->boxSize)
(*this->zz)[i] -= this->boxSize;
if ((*this->xx)[i] < 0)
(*this->xx)[i] += this->boxSize;
if ((*this->yy)[i] < 0)
(*this->yy)[i] += this->boxSize;
if ((*this->zz)[i] < 0)
(*this->zz)[i] += this->boxSize;
if ((*this->cx)[i] >= this->boxSize)
(*this->cx)[i] -= this->boxSize;
if ((*this->cy)[i] >= this->boxSize)
(*this->cy)[i] -= this->boxSize;
if ((*this->cz)[i] >= this->boxSize)
(*this->cz)[i] -= this->boxSize;
if ((*this->cx)[i] < 0)
(*this->cx)[i] += this->boxSize;
if ((*this->cy)[i] < 0)
(*this->cy)[i] += this->boxSize;
if ((*this->cz)[i] < 0)
(*this->cz)[i] += this->boxSize;
// Figure out to which rank this halo belongs
POSVEL_T xCoord = redistCenter ? (*this->cx)[i] : (*this->xx)[i];
POSVEL_T yCoord = redistCenter ? (*this->cy)[i] : (*this->yy)[i];
POSVEL_T zCoord = redistCenter ? (*this->cz)[i] : (*this->zz)[i];
float sizeX = this->boxSize / this->layoutSize[0];
float sizeY = this->boxSize / this->layoutSize[1];
float sizeZ = this->boxSize / this->layoutSize[2];
int coords[3] = { (int) (xCoord/sizeX),
(int) (yCoord/sizeY),
(int) (zCoord/sizeZ)
};
int home;
MPI_Cart_rank(Partition::getComm(), coords, &home);
CosmoHalo halo = { { (*this->xx)[i],
(*this->yy)[i],
(*this->zz)[i],
(*this->vx)[i],
(*this->vy)[i],
(*this->vz)[i],
(*this->ms)[i],
(*this->cx)[i],
(*this->cy)[i],
(*this->cz)[i],
(*this->vdisp)[i]
}, {
(*this->tag)[i],
(*this->count)[i]
}
};
pByProc[home].push_back(halo);
}
this->xx->resize(0);
this->yy->resize(0);
this->zz->resize(0);
this->vx->resize(0);
this->vy->resize(0);
this->vz->resize(0);
this->ms->resize(0);
this->cx->resize(0);
this->cy->resize(0);
this->cz->resize(0);
this->vdisp->resize(0);
this->tag->resize(0);
this->count->resize(0);
if (reserveQ) {
this->xx->reserve(haloCount);
this->yy->reserve(haloCount);
this->zz->reserve(haloCount);
this->vx->reserve(haloCount);
this->vy->reserve(haloCount);
this->vz->reserve(haloCount);
this->ms->reserve(haloCount);
this->cx->reserve(haloCount);
this->cy->reserve(haloCount);
this->cz->reserve(haloCount);
this->vdisp->reserve(haloCount);
this->tag->reserve(haloCount);
this->count->reserve(haloCount);
}
SimpleTimings::TimerRef t_ala2a = SimpleTimings::getTimer("ala2a");
SimpleTimings::startTimer(t_ala2a);
this->haloCount = 0;
// Record all sizes into a single buffer and send this to all ranks
long totalToSend = 0;
for (int i = 0; i < numProc; ++i) {
int sz = (int) pByProc[i].size();
pCounts[i] = sz;
totalToSend += sz;
}
MPI_Alltoall(&pCounts[0], 1, MPI_INT,
&pRecvCounts[0], 1, MPI_INT,
Partition::getComm());
// pRecvCounts now holds the number of halos that this rank should
// get from every other rank
long totalToRecv = 0;
for (int i = 0; i < numProc; ++i) {
totalToRecv += pRecvCounts[i];
}
// Allocate and pack the buffer with all halos to send
pBuffer.reserve(totalToSend);
for (int i = 0; i < numProc; ++i)
for (int j = 0; j < (int) pByProc[i].size(); ++j) {
pBuffer.push_back(pByProc[i][j]);
}
// Calculate displacements
pDisp[0] = pRecvDisp[0] = 0;
for (int i = 1; i < numProc; ++i) {
pDisp[i] = pDisp[i-1] + pCounts[i-1];
pRecvDisp[i] = pRecvDisp[i-1] + pRecvCounts[i-1];
}
// Send all halos to their new homes
pRecvBuffer.resize(totalToRecv);
if (useAlltoallv) {
MPI_Alltoallv(&pBuffer[0], &pCounts[0], &pDisp[0], CosmoHaloType,
&pRecvBuffer[0], &pRecvCounts[0], &pRecvDisp[0], CosmoHaloType,
Partition::getComm());
} else {
vector<MPI_Request> requests;
for (int i = 0; i < numProc; ++i) {
if (pRecvCounts[i] == 0)
continue;
requests.resize(requests.size()+1);
MPI_Irecv(&pRecvBuffer[pRecvDisp[i]], pRecvCounts[i], CosmoHaloType, i, 0,
Partition::getComm(), &requests[requests.size()-1]);
}
MPI_Barrier(Partition::getComm());
for (int i = 0; i < numProc; ++i) {
if (pCounts[i] == 0)
continue;
requests.resize(requests.size()+1);
MPI_Isend(&pBuffer[pDisp[i]], pCounts[i], CosmoHaloType, i, 0,
Partition::getComm(), &requests[requests.size()-1]);
}
vector<MPI_Status> status(requests.size());
MPI_Waitall((int) requests.size(), &requests[0], &status[0]);
}
// We now have all of our halos, put them in our local arrays
for (long i = 0; i < totalToRecv; ++i) {
POSVEL_T loc[DIMENSION], vel[DIMENSION], mass, cent[DIMENSION], vd;
ID_T id, cnt;
int j = 0;
for (int dim = 0; dim < DIMENSION; dim++) {
loc[dim] = pRecvBuffer[i].floatData[j++];
}
for (int dim = 0; dim < DIMENSION; dim++) {
vel[dim] = pRecvBuffer[i].floatData[j++];
}
mass = pRecvBuffer[i].floatData[j++];
for (int dim = 0; dim < DIMENSION; dim++) {
cent[dim] = pRecvBuffer[i].floatData[j++];
}
vd = pRecvBuffer[i].floatData[j++];
id = pRecvBuffer[i].intData[0];
cnt = pRecvBuffer[i].intData[1];
POSVEL_T rpx = redistCenter ? cent[0] : loc[0];
POSVEL_T rpy = redistCenter ? cent[1] : loc[1];
POSVEL_T rpz = redistCenter ? cent[2] : loc[2];
// Is the halo ALIVE on this processor
if ((rpx >= minAlive[0] && rpx < maxAlive[0]) &&
(rpy >= minAlive[1] && rpy < maxAlive[1]) &&
(rpz >= minAlive[2] && rpz < maxAlive[2])) {
this->xx->push_back(loc[0]);
this->yy->push_back(loc[1]);
this->zz->push_back(loc[2]);
this->vx->push_back(vel[0]);
this->vy->push_back(vel[1]);
this->vz->push_back(vel[2]);
this->ms->push_back(mass);
this->cx->push_back(cent[0]);
this->cy->push_back(cent[1]);
this->cz->push_back(cent[2]);
this->vdisp->push_back(vd);
this->tag->push_back(id);
this->count->push_back(cnt);
this->numberOfAliveHalos++;
this->haloCount++;
}
}
// Count the halos across processors
long totalAliveHalos = 0;
MPI_Allreduce((void*) &this->numberOfAliveHalos,
(void*) &totalAliveHalos,
1, MPI_LONG, MPI_SUM, Partition::getComm());
#ifdef DEBUG
cout << "Rank " << setw(3) << this->myProc
<< " #alive = " << this->numberOfAliveHalos << endl;
#endif
MPI_Type_free(&CosmoHaloType);
if (this->myProc == MASTER) {
cout << "ReadHalosGIO TotalAliveHalos "
<< totalAliveHalos << endl;
}
SimpleTimings::stopTimerStats(t_ala2a);
}
} // END namespace cosmotk
| 35.351129 | 90 | 0.601359 | [
"vector",
"3d"
] |
2f32bb287b54dc9101a9143f3c10107319a2ffe9 | 23,072 | cpp | C++ | src/data/Scenario.cpp | wssuite/NurseScheduler | e5059e06b97154d5993a67aa3a0aa2c65ff45d0a | [
"MIT"
] | 14 | 2020-05-04T01:24:36.000Z | 2022-03-20T15:04:52.000Z | src/data/Scenario.cpp | legraina/StaticNurseScheduler | e5059e06b97154d5993a67aa3a0aa2c65ff45d0a | [
"MIT"
] | 19 | 2020-04-28T18:55:00.000Z | 2020-05-15T08:59:00.000Z | src/data/Scenario.cpp | legraina/NurseScheduler | e5059e06b97154d5993a67aa3a0aa2c65ff45d0a | [
"MIT"
] | 6 | 2018-09-28T01:51:31.000Z | 2020-04-19T04:53:03.000Z | //
// Scenario.cpp
// Project:RosterDesNurses
//
// Created by J��r��my Omer on 18/12/2013.
// Copyright (c) 2014 J��r��my Omer. All rights reserved.
//
#include <sstream>
#include <string>
#include <solvers/Solver.h>
#include "data/Scenario.h"
#include "data/Nurse.h"
#include "tools/MyTools.h"
using std::string;
using std::vector;
using std::map;
using std::pair;
//-----------------------------------------------------------------------------
//
// S t r u c t u r e S t a t e
//
//-----------------------------------------------------------------------------
// Destructor
State::~State(){}
// // Updates the state if a new day is worked on shiftType of newShiftType
// void State::addNewDay(int newShiftType){
// // Total shifts worked if it is a worked day
// totalTimeWorked_ += (newShiftType ? 1 : 0);
// // Total weekends worked :
// // +1 IF : new day is a Sunday and the nurse works on shift_ or newShift
// if( Tools::isSunday(dayId_-1) and (newShiftType or shiftType_) )
// totalWeekendsWorked_ ++;
// // Consecutives : +1 iff it is the same as the previous one
// consShifts_ = (shiftType_==newShiftType) ? (consShifts_ + 1) : 1;
// // Consecutive Days Worked : +1 if the new one is worked (!=0), 0 if it is a rest (==0)
// consDaysWorked_ = shiftType_ ? (consDaysWorked_ + 1) : 0;
// // Current shiftType worked : updated with the new one
// shiftType_ = newShiftType;
// // increment the day index
// dayId_++;
// }
// // Function that appends a new day worked on a given shift to an input state
// //
// void State::addDayToState(const State& prevState, int newShift, const PScenario pScenario) {
// int newShiftType = pScenario->shiftIDToShiftTypeID_[newShift];
// addDayToState(prevState, newShiftType);
// }
// Function that appends a new day worked on a given shiftType to an input state
// to update this state
// RqJO: I slghtly modified the method to take into account the possibility to
// add in the state that no task has been assigned on this day
//
void State::addDayToState(const State& prevState, int newShiftType, int newShift, int timeWorked) {
// int timeWorked = 1; // days worked
// int timeWorked = timeDurationToWork_[newShift]; // hours worked
// Total shifts worked if it is a worked day
totalTimeWorked_ = prevState.totalTimeWorked_+(newShiftType > 0 ? timeWorked : 0);
// index of the previous shift
int prevShiftType = prevState.shiftType_;
// Treat the case in which no shift is assigned to the nurse on this day
if (newShiftType < 0) {
totalWeekendsWorked_ = prevState.totalWeekendsWorked_;
consShifts_ = prevState.consShifts_;
consDaysWorked_ = prevState.consDaysWorked_;
consDaysOff_ = prevState.consDaysOff_;
shiftType_ = prevShiftType < 0 ? prevShiftType-1:-1;
shift_ = 0;
}
else if (prevShiftType >= 0) {
// Total weekends worked:
// +1 IF : new day is a Sunday and the nurse works on prevState.shift_ or newShift
if( Tools::isSunday(dayId_-1) and (newShiftType or prevState.shiftType_) )
totalWeekendsWorked_ = prevState.totalWeekendsWorked_+1;
else {
totalWeekendsWorked_ = prevState.totalWeekendsWorked_;
}
// Consecutives : +1 iff it is the same as the previous one
consShifts_ = (newShiftType && newShiftType==prevState.shiftType_) ? prevState.consShifts_+1 : (newShiftType? 1:0);
// Consecutive Days Worked : +1 if the new one is worked (!=0), 0 if it is a rest (==0)
consDaysWorked_ = newShiftType ? (prevState.consDaysWorked_ + 1) : 0;
// Consecutive Days off : +1 if the new one is off (==0), 0 if it is worked (!=0)
consDaysOff_ = newShiftType ? 0 : (prevState.consDaysOff_ + 1);
shiftType_ = newShiftType;
shift_ = newShift;
}
else { // the previous shift was not assigned but this one is
if (newShiftType >0) {
totalTimeWorked_ = prevState.totalTimeWorked_+timeWorked+(prevState.consDaysWorked_ > 0 ? (-prevShiftType):0); // SERGEB ??????
totalWeekendsWorked_ = Tools::isSunday(dayId_) ? prevState.totalWeekendsWorked_+1:prevState.totalWeekendsWorked_;
consDaysWorked_ = (prevState.consDaysWorked_ > 0) ? (prevState.consDaysWorked_ + 1 - prevShiftType) : 1;
consShifts_ = 1;
consDaysOff_ = 0;
shiftType_ = newShiftType;
shift_ = newShift;
}
else {
totalTimeWorked_ = prevState.totalTimeWorked_;
totalWeekendsWorked_ = prevState.totalWeekendsWorked_;
consDaysWorked_ = 0;
consShifts_ = 0;
consDaysOff_ = (prevState.consDaysOff_ > 0) ? (prevState.consDaysOff_ + 1 - prevShiftType) : 1;
shiftType_ = newShiftType;
shift_ = newShift;
}
}
// increment the day index
dayId_ = prevState.dayId_+1;
}
// Display method: toString
//
string State::toString(){
std::stringstream rep;
rep << totalTimeWorked_ << " " << totalWeekendsWorked_ << " " << shiftType_ << " ";
if(shiftType_) rep << consShifts_ << " " << consDaysWorked_; else rep << "0 0";
if(shiftType_) rep << " 0"; else rep << " " << consShifts_;
rep << std::endl;
return rep.str();
}
//-----------------------------------------------------------------------------
//
// C l a s s S c e n a r i o
//
// Class that contains all the attributes describing the scenario
//
//-----------------------------------------------------------------------------
// Constructor and destructor
//
Scenario::Scenario(string name, int nbWeeks,
int nbSkills, vector<string> intToSkill, map<string,int> skillToInt,
int nbShifts, vector<string> intToShift, map<string,int> shiftToInt,
vector<int> hoursToWork, vector<int> shiftIDToShiftTypeID,
int nbShiftsType, vector<string> intToShiftType, map<string,int> shiftTypeToInt,
vector2D<int> shiftTypeIDToShiftID, vector<int> minConsShiftType, vector<int> maxConsShiftType,
vector<int> nbForbiddenSuccessors, vector2D<int> forbiddenSuccessors,
int nbContracts, vector<string> intToContract, map<string,PConstContract> contracts,
int nbNurses, vector<PNurse>& theNurses, map<string,int> nurseNameToInt) :
name_(name), nbWeeks_(nbWeeks),
nbSkills_(nbSkills), intToSkill_(intToSkill), skillToInt_(skillToInt),
nbShifts_(nbShifts), intToShift_(intToShift), shiftToInt_(shiftToInt),
timeDurationToWork_(hoursToWork), shiftIDToShiftTypeID_(shiftIDToShiftTypeID),
nbShiftsType_(nbShiftsType), intToShiftType_(intToShiftType), shiftTypeToInt_(shiftTypeToInt),
shiftTypeIDToShiftID_(shiftTypeIDToShiftID),
nbContracts_(nbContracts), intToContract_(intToContract), contracts_(contracts),
nbNurses_(nbNurses), theNurses_(theNurses), nurseNameToInt_(nurseNameToInt),
minConsShiftType_(minConsShiftType), maxConsShiftType_(maxConsShiftType),
nbForbiddenSuccessors_(nbForbiddenSuccessors), forbiddenSuccessors_(forbiddenSuccessors),
pWeekDemand_(0), nbShiftOffRequests_(0), nbShiftOnRequests_(0), nbPositions_(0) {
// To make sure that it is modified later when reading the history data file
//
thisWeek_ = -1;
nbWeeksLoaded_ = 1;
// Preprocess the vector of nurses
// This creates the positions
//
this->preprocessTheNurses();
}
// Hybrid copy constructor : this is only called when constructing a new scenario that copies most parameters
// from the input scenario but for only a subgroup of nurses
//
Scenario::Scenario(PScenario pScenario, const vector<PNurse>& theNurses, PDemand pDemand, PPreferences pWeekPreferences):
name_(pScenario->name_), nbWeeks_(pScenario->nbWeeks_),
nbSkills_(pScenario->nbSkills_), intToSkill_(pScenario->intToSkill_), skillToInt_(pScenario->skillToInt_),
nbShifts_(pScenario->nbShifts_), intToShift_(pScenario->intToShift_), shiftToInt_(pScenario->shiftToInt_),
timeDurationToWork_(pScenario->timeDurationToWork_), shiftIDToShiftTypeID_(pScenario->shiftIDToShiftTypeID_),
nbShiftsType_(pScenario->nbShiftsType_), intToShiftType_(pScenario->intToShiftType_), shiftTypeToInt_(pScenario->shiftTypeToInt_),
shiftTypeIDToShiftID_(pScenario->shiftTypeIDToShiftID_),
nbContracts_(pScenario->nbContracts_), intToContract_(pScenario->intToContract_), contracts_(pScenario->contracts_),
nbNurses_(theNurses.size()), theNurses_(theNurses), nurseNameToInt_(pScenario->nurseNameToInt_),
minConsShiftType_(pScenario->minConsShiftType_), maxConsShiftType_(pScenario->maxConsShiftType_),
nbForbiddenSuccessors_(pScenario->nbForbiddenSuccessors_), forbiddenSuccessors_(pScenario->forbiddenSuccessors_),
pWeekDemand_(nullptr), nbShiftOffRequests_(0), nbShiftOnRequests_(0), pWeekPreferences_(nullptr), thisWeek_(pScenario->thisWeek()), nbWeeksLoaded_(pScenario->nbWeeksLoaded()),
nbPositions_(0), nursesPerPosition_(0){
// Preprocess the vector of nurses
// This creates the positions
//
this->preprocessTheNurses();
// The nurses are already preprocessed at this stage
// Load the input week demand and preferences
//
this->linkWithDemand(pDemand);
this->linkWithPreferences(pWeekPreferences);
}
Scenario::~Scenario(){}
void Scenario::setWeekPreferences(PPreferences weekPreferences){
pWeekPreferences_ = weekPreferences;
}
// return true if the shift shNext is a forbidden successor of sh
//
// bool Scenario::isForbiddenSuccessor(int shNext, int shLast) {
// if (shLast <= 0) return false;
// for (int i = 0; i < nbForbiddenSuccessors_[shLast]; i++) {
// if (shNext == forbiddenSuccessors_[shLast][i]) {
// return true;
// }
// }
// return false;
// }
// return true if the shift shNext is a forbidden successor of shift shLast (via types)
bool Scenario::isForbiddenSuccessorShift_Shift(int shNext, int shLast) {
if (shLast <= 0) return false;
int shTypeNext = shiftIDToShiftTypeID_[shNext];
int shTypeLast = shiftIDToShiftTypeID_[shLast];
return isForbiddenSuccessorShiftType_ShiftType(shTypeNext, shTypeLast);
}
// return true if the shift shNext is a forbidden successor of shiftType shTypeLast
bool Scenario::isForbiddenSuccessorShift_ShiftType(int shNext, int shTypeLast) {
if (shTypeLast <= 0) return false;
int shTypeNext = shiftIDToShiftTypeID_[shNext];
return isForbiddenSuccessorShiftType_ShiftType(shTypeNext, shTypeLast);
}
// return true if the shiftType shTypeNext is a forbidden successor of shiftType shTypeLast
bool Scenario::isForbiddenSuccessorShiftType_Shift(int shTypeNext, int shLast) {
if (shLast <= 0) return false;
int shTypeLast = shiftIDToShiftTypeID_[shLast];
return isForbiddenSuccessorShiftType_ShiftType(shTypeNext, shTypeLast);
}
// return true if the shiftType shTypeNext is a forbidden successor of shiftType shTypeLast
bool Scenario::isForbiddenSuccessorShiftType_ShiftType(int shTypeNext, int shTypeLast) {
if (shTypeLast <= 0) return false;
for (int i = 0; i < nbForbiddenSuccessors_[shTypeLast]; i++) {
if (shTypeNext == forbiddenSuccessors_[shTypeLast][i]) {
return true;
}
}
return false;
}
const int Scenario::minTotalShiftsOf(int whichNurse) const {
return theNurses_[whichNurse]->minTotalShifts();
}
int Scenario::maxTotalShiftsOf(int whichNurse) const {
return theNurses_[whichNurse]->maxTotalShifts();
}
int Scenario::minConsDaysWorkOf(int whichNurse) const {
return theNurses_[whichNurse]->minConsDaysWork();
}
int Scenario::maxConsDaysWorkOf(int whichNurse) const {
return theNurses_[whichNurse]->maxConsDaysWork();
}
int Scenario::minConsDaysOffOf(int whichNurse) const {
return theNurses_[whichNurse]->maxConsDaysOff();
}
int Scenario::maxConsDaysOffOf(int whichNurse) const {
return theNurses_[whichNurse]->maxConsDaysOff();
}
int Scenario::maxTotalWeekendsOf(int whichNurse) const {
return theNurses_[whichNurse]->maxTotalWeekends();
}
bool Scenario::isCompleteWeekendsOf(int whichNurse) const {
return theNurses_[whichNurse]->needCompleteWeekends();
}
// return the min/max consecutive shifts of the same type as the argument
int Scenario::minConsShiftsOfTypeOf(int whichShift) {
int shiftType = shiftIDToShiftTypeID_[whichShift];
return minConsShiftsOf(shiftType);
}
int Scenario::maxConsShiftsOfTypeOf(int whichShift) {
int shiftType = shiftIDToShiftTypeID_[whichShift];
return maxConsShiftsOf(shiftType);
}
int Scenario::minConsShiftsOf(int whichShiftType) {
return minConsShiftType_[whichShiftType];
}
int Scenario::maxConsShiftsOf(int whichShiftType) {
return maxConsShiftType_[whichShiftType];
}
// update the scenario to treat a new week
//
void Scenario::updateNewWeek(PDemand pDemand, PPreferences pPreferences, vector<State> &initialStates) {
// set the demand, preferences and initial states
this->linkWithDemand(pDemand);
this->linkWithPreferences(pPreferences);
this->setInitialState(initialStates);
// update the index of the week
thisWeek_++;
}
inline void Scenario::linkWithPreferences(PPreferences pPreferences) {
pWeekPreferences_ = pPreferences;
nbShiftOffRequests_ = 0;
for (PNurse nurse:theNurses_) {
nbShiftOffRequests_ += pWeekPreferences_->howManyShiftsOff(nurse->id_);
}
nbShiftOnRequests_ = 0;
for (PNurse nurse:theNurses_) {
nbShiftOnRequests_ += pWeekPreferences_->howManyShiftsOn(nurse->id_);
}
}
//------------------------------------------------
// Display functions
//------------------------------------------------
// Display methods: toString + override operator<< (easier)
//
string Scenario::toString(){
std::stringstream rep;
rep << "############################################################################" << std::endl;
rep << "############################## Scenario ##############################" << std::endl;
rep << "############################################################################" << std::endl;
rep << "# " << std::endl;
rep << "# NAME \t= " << name_ << std::endl;
rep << "# NUMBER_OF_WEEKS \t= " << nbWeeks_ <<std::endl;
rep << "# " << std::endl;
rep << "# SKILLS \t= " << nbSkills_ << std::endl;
for(int i=0; i<nbSkills_; i++){
rep << "# \t= " << i << ":" << intToSkill_[i] << std::endl;
}
rep << "# " << std::endl;
rep << "# SHIFTS \t= " << nbShifts_ << std::endl;
for(int i=0; i<nbShifts_; i++){
rep << "# \t= ";
rep << i << ":" << intToShift_[i] << " \t(" << minConsShiftsOfTypeOf(i) << "," << maxConsShiftsOfTypeOf(i) << ")" << std::endl;
}
rep << "# " << std::endl;
rep << "# FORBIDDEN " << std::endl;
for(int i=0; i<nbShifts_; i++){
rep << "#\t\t\t" << intToShift_[i] << "\t-> ";
for(int j=0; j<nbForbiddenSuccessors_[i]; j++){
rep << intToShift_[forbiddenSuccessors_[i][j]] << " ";
}
rep << std::endl;
}
rep << "# CONTRACTS " << std::endl;
for(const auto& contract: contracts_){
rep << "#\t\t\t" << *(contract.second) << std::endl;
}
rep << "# " << std::endl;
rep << "# NURSES \t= " << nbNurses_ << std::endl;
for(int i=0; i<nbNurses_; i++){
rep << "#\t\t\t" << theNurses_[i]->toString() << std::endl;
}
rep << "# " << std::endl;
rep << "# POSITIONS \t= " << nbPositions_ << std::endl;
for (int i=0; i<nbPositions_; i++) {
rep << "#\t\t\t" << pPositions_[i]->toString() << std::endl;
}
if (weekName_!=""){
// write the demand using the member method toString
// do not write the preprocessed information at this stage
//
rep << pWeekDemand_->toString(false) << std::endl;
// write the preferences
//
rep << "# " << std::endl;
rep << "# WISHED SHIFTS OFF" << std::endl;
for(PNurse nurse:theNurses_){
// Display only if the nurse has preferences
const map<int,vector<Wish> >& prefNurse = pWeekPreferences_->nurseWishesOff(nurse->id_);
if(!prefNurse.empty()){
rep << "#\t\t\t" << nurse->id_ << "\t" << nurse->name_ << "\t";
for(const auto &itWishlist: prefNurse){
rep << Tools::intToDay(itWishlist.first) << ": ";
bool first = true;
for(const auto& itShift: itWishlist.second){
if(first) first = false; else rep << ",";
rep << intToShift_[itShift.shift];
}
rep << " ";
}
rep << std::endl;
}
}
for(PNurse nurse:theNurses_){
// Display only if the nurse has preferences
const map<int,vector<Wish> >& prefNurse = pWeekPreferences_->nurseWishesOn(nurse->id_);
if(!prefNurse.empty()){
rep << "#\t\t\t" << nurse->id_ << "\t" << nurse->name_ << "\t";
for(const auto &itWishlist: prefNurse){
rep << Tools::intToDay(itWishlist.first) << ": ";
bool first = true;
for(const auto& itShift: itWishlist.second){
if(first) first = false; else rep << ",";
rep << intToShift_[itShift.shift];
}
rep << " ";
}
rep << std::endl;
}
}
}
if(thisWeek_ > -1){
rep << "# " << std::endl;
rep << "# INITIAL STATE \t= WEEK Nb " << thisWeek_ << std::endl;
for(int n=0; n<nbNurses_; n++){
rep << "#\t\t\t" << theNurses_[n]->name_ << " ";
State s = initialState_[n];
rep << s.totalTimeWorked_ << " " << s.totalWeekendsWorked_ << " " << intToShiftType_[s.shiftType_] << " ";
if(s.shiftType_) rep << s.consShifts_ << " " << s.consDaysWorked_; else rep << "0 0";
if(s.shiftType_) rep << " 0"; else rep << " " << s.consShifts_;
rep << std::endl;
}
}
rep << "############################################################################" << std::endl;
return rep.str();
}
//------------------------------------------------
// Preprocess functions
//------------------------------------------------
// preprocess the nurses to get the types
//
void Scenario::preprocessTheNurses() {
if (nbPositions_) {
Tools::throwError("The nurse preprocessing is run for the second time!");
}
// Go through the nurses, and create their positions when it has not already
// been done
//
for (PNurse nurse: theNurses_) {
bool positionExists = nbPositions_ != 0;
int nbSkills = nurse->nbSkills_;
vector<int> skills = nurse->skills_;
// go through every existing position to see if the position of this nurse
// has already been created
for (PPosition pos: pPositions_) {
positionExists = true;
if (pos->nbSkills_ == nbSkills) {
for (int i = 0; i < nbSkills; i++) {
if (skills[i] != pos->skills_[i]) {
positionExists = false;
break;
}
}
}
else positionExists = false;
if (positionExists) break;
}
// create the position if if doesn't exist
if (!positionExists) {
pPositions_.emplace_back(std::make_shared<Position>(nbPositions_, nbSkills, skills));
nbPositions_++;
}
}
// build the list of position dominance
for (int i=0; i<nbPositions_; i++) {
for (int j=i+1; j<nbPositions_; j++) {
if(pPositions_[i]->compare(*pPositions_[j]) == 1) {
pPositions_[i]->addBelow(pPositions_[j]);
pPositions_[j]->addAbove(pPositions_[i]);
}
if(pPositions_[i]->compare(*pPositions_[j]) == -1) {
pPositions_[i]->addAbove(pPositions_[j]);
pPositions_[j]->addBelow(pPositions_[i]);
}
}
}
// compute the rank of each position
vector<bool> isRanked;
bool isAllRanked = false;
for (int i =0; i < nbPositions_; i++) {
isRanked.push_back(false);
pPositions_[i]->rank(0);
pPositions_[i]->resetAbove();
pPositions_[i]->resetBelow();
}
while (!isAllRanked) {
for (int i=0; i<nbPositions_; i++) {
if (!isRanked[i]) {
int rankIni = pPositions_[i]->rank();
// go through the positions above the considered position to increment
// its rank
if (pPositions_[i]->nbAbove()) {
for (int j = 0; j < pPositions_[i]->nbAbove(); j++) {
int currentRank = pPositions_[i]->rank();
int newRank = pPositions_[j]->rank()+1;
pPositions_[i]->rank(std::max(currentRank, newRank));
}
}
// the position is treated when the rank is not modified by the loop above
if (pPositions_[i]->rank() == rankIni) isRanked[i] = true;
}
}
// check if all the positions are ranked
isAllRanked = true;
for (int i=0; i<nbPositions_; i++) {
if (!isRanked[i]) {
isAllRanked = false;
break;
}
}
}
// Organize the nurses by position
for (int i = 0; i < nbPositions(); i++) {
vector<PNurse> nursesInThisPosition;
nursesPerPosition_.push_back(nursesInThisPosition);
}
for (PNurse nurse: theNurses_) {
// the skills of the nurse need to be compared to the skills of each
// existing position to determine the position of the nurse
bool isPosition = true;
for (int i = 0; i < nbPositions() ; i++) {
PPosition pPosition = pPositions_[i];
isPosition = true;
if (pPosition->nbSkills_ == nurse->nbSkills_) {
for (int i = 0; i < nurse->nbSkills_; i++) {
if (nurse->skills_[i] != pPosition->skills_[i]) {
isPosition = false;
break;
}
}
}
else isPosition = false;
if (isPosition) {
nursesPerPosition_[pPosition->id()].push_back(nurse);
break;
}
}
if (!isPosition) {
Tools::throwError("The nurse has no position!");
}
}
}
// Compare nurses in ascending order of their ideas
//
bool compareNursesById(PNurse n1, PNurse n2) {
return (n1->id_ < n2->id_);
}
bool comparePairSecond(pair<int,int> p1, pair<int,int> p2) {
return p1.second < p2.second;
}
// compute the connex components of the positions rcspp
// (one edge between two positions indicate that they share a skill)
//
void Scenario::computeConnexPositions() {
vector<PPosition> pRemainingPositions(pPositions_);
PPosition pPos = pRemainingPositions.back();
pRemainingPositions.pop_back();
// First build the connex components of positions
while (!pRemainingPositions.empty()) {
vector<PPosition> connexPositions;
connexPositions.push_back(pPos);
vector<PPosition> nextPositions;
nextPositions.push_back(pPos);
while (!nextPositions.empty()) {
// treat the next position in the waiting list
pPos = nextPositions.back();
nextPositions.pop_back();
// add all the positions with a common skill in the connex component
int nbRemaining = pRemainingPositions.size();
int ind = 0;
while(ind < nbRemaining ) {
if ( pPos->shareSkill(*pRemainingPositions[ind]) ) {
// update the connex component, the waiting list and the list of
// positions which are not in any connex component
connexPositions.push_back(pRemainingPositions[ind]);
nextPositions.push_back(pRemainingPositions[ind]);
pRemainingPositions.erase(pRemainingPositions.begin()+ind);
nbRemaining--;
}
else {
ind++;
}
}
}
componentsOfConnexPositions_.push_back(connexPositions);
// load the next remaining position
if (!pRemainingPositions.empty()) {
pPos = pRemainingPositions.back();
pRemainingPositions.pop_back();
}
}
// Get the nurses that belong to each component
for (unsigned int c = 0; c < componentsOfConnexPositions_.size(); c++) {
vector<PNurse> pNursesInThisComponent;
for (PPosition p:componentsOfConnexPositions_[c])
for (unsigned int i=0; i<nursesPerPosition_[p->id()].size(); i++)
// nursesInThisComponent.push_back(nursesPerPosition_[p->id()][i]);
pNursesInThisComponent.push_back(nursesPerPosition_[p->id()][i]);
std::stable_sort(pNursesInThisComponent.begin(),pNursesInThisComponent.end(),compareNursesById);
nursesPerConnexComponentOfPositions_.push_back(pNursesInThisComponent);
}
}
| 34.333333 | 177 | 0.666826 | [
"vector"
] |
2f44f23fad1dc14256fa4f61e71ddcb84aae5809 | 4,187 | cpp | C++ | source/GFX/CelImages.cpp | BodbDearg/phoenix_doom | 9648b1cc742634d5aefc18cd3699cd7cb2c0e21c | [
"MIT"
] | 29 | 2019-09-25T06:29:07.000Z | 2022-02-20T23:52:36.000Z | source/GFX/CelImages.cpp | monyarm/phoenix_doom | 78c75f985803b94b981469ac32764169ed56aee4 | [
"MIT"
] | 4 | 2019-09-25T03:24:31.000Z | 2020-09-07T18:38:32.000Z | source/GFX/CelImages.cpp | monyarm/phoenix_doom | 78c75f985803b94b981469ac32764169ed56aee4 | [
"MIT"
] | 4 | 2019-09-26T06:43:12.000Z | 2020-09-05T16:25:03.000Z | #include "CelImages.h"
#include "Base/Resource.h"
#include "Game/Resources.h"
#include <vector>
BEGIN_NAMESPACE(CelImages)
// Note: I'm using a flat vector here instead of something like a map because it offers constant time access.
// There is one array slot here per resource in the resource manager. This might seem wasteful of memory but
// there are not that many resources in the resource file and the 'CelImageArray' struct is small, so the
// tradeoff is probably worth it.
static std::vector<CelImageArray> gImageArrays;
static void loadImages(
CelImageArray& imageArray,
const uint32_t resourceNum,
const CelLoadFlags loadFlags,
const bool bLoadImageArray
) noexcept {
// Firstly load up the resource.
// Note: don't need to check for an error since if this fails it will be a fatal error!
ASSERT(!imageArray.pImages);
const Resource* const pResource = Resources::load(resourceNum);
const std::byte* const pResourceData = pResource->pData;
const uint32_t resourceSize = pResource->size;
// Read each individual image.
// Note: could be dealing with an array of images or just one.
if (bLoadImageArray) {
if (!CelUtils::loadRezFileCelImages(pResourceData, resourceSize, loadFlags, imageArray)) {
FATAL_ERROR("Failed to load a CEL format image used by the game!");
}
} else {
imageArray.numImages = 1;
imageArray.loadFlags = loadFlags;
imageArray.pImages = new CelImage[1];
if (!CelUtils::loadRezFileCelImage(pResourceData, resourceSize, loadFlags, imageArray.pImages[0])) {
FATAL_ERROR("Failed to load a CEL format image used by the game!");
}
}
// After we are done we can free the raw resource - done at this point
Resources::free(resourceNum);
}
void init() noexcept {
// Expect the resource manager to be initialized and for this module to NOT be initialized
ASSERT(gImageArrays.empty());
ASSERT(Resources::getEndResourceNum() > 0);
// Alloc room for each potential image (one per resource, even though not all resources are CEL images)
gImageArrays.resize(Resources::getEndResourceNum());
}
void shutdown() noexcept {
freeAll();
gImageArrays.clear();
}
void freeAll() noexcept {
for (CelImageArray& imageArray : gImageArrays) {
imageArray.free();
}
}
const CelImageArray* getImages(const uint32_t resourceNum) noexcept {
if (resourceNum < (uint32_t) gImageArrays.size()) {
return &gImageArrays[resourceNum];
} else {
return nullptr;
}
}
const CelImage* getImage(const uint32_t resourceNum) noexcept {
const CelImageArray* const pImageArray = getImages(resourceNum);
if (pImageArray && resourceNum < pImageArray->numImages) {
return &pImageArray->pImages[0];
}
return nullptr;
}
const CelImageArray& loadImages(const uint32_t resourceNum, const CelLoadFlags loadFlags) noexcept {
if (resourceNum >= (uint32_t) gImageArrays.size()) {
FATAL_ERROR_F("Invalid resource number '%u': unable to load this resource!", resourceNum);
}
CelImageArray& imageArray = gImageArrays[resourceNum];
if (!imageArray.pImages) {
loadImages(imageArray, resourceNum, loadFlags, true);
}
return imageArray;
}
const CelImage& loadImage(const uint32_t resourceNum, const CelLoadFlags loadFlags) noexcept {
if (resourceNum >= (uint32_t) gImageArrays.size()) {
FATAL_ERROR_F("Invalid resource number '%u': unable to load this resource!", resourceNum);
}
CelImageArray& imageArray = gImageArrays[resourceNum];
if (!imageArray.pImages) {
loadImages(imageArray, resourceNum, loadFlags, false);
}
return imageArray.pImages[0];
}
void freeImages(const uint32_t resourceNum) noexcept {
if (resourceNum < (uint32_t) gImageArrays.size()) {
gImageArrays[resourceNum].free();
}
}
void releaseImages(const uint32_t resourceNum) noexcept {
// Note: function does nothing at the moment deliberately, just here as a statement of intent.
// For why this is, see 'Resources::release()'.
MARK_UNUSED(resourceNum);
}
END_NAMESPACE(CelImages)
| 32.968504 | 109 | 0.703368 | [
"vector"
] |
2f4e5a096f1cc5de465effeb722ae30d24875f76 | 5,652 | hpp | C++ | engine/include/Utils/utils.hpp | Vbif/geometric-diversity | 6e9d5a923db68acb14a0a603bd2859f4772db201 | [
"MIT"
] | null | null | null | engine/include/Utils/utils.hpp | Vbif/geometric-diversity | 6e9d5a923db68acb14a0a603bd2859f4772db201 | [
"MIT"
] | null | null | null | engine/include/Utils/utils.hpp | Vbif/geometric-diversity | 6e9d5a923db68acb14a0a603bd2859f4772db201 | [
"MIT"
] | null | null | null | #ifndef __UTILS_UTILS_H__
#define __UTILS_UTILS_H__
#pragma once
#include "platform.h"
#include "Utils/IPoint.h"
#include "Utils/Color.h"
#include "Utils/Float.hpp"
#include "Utils/Int.h"
#include "EngineAssert.h"
#include "ThreadSupport.h"
#define DECLARE_ENUM_CLASS_FLAGS(Enum) \
constexpr Enum operator|(Enum lhs, Enum rhs) noexcept { return (Enum)((__underlying_type(Enum))lhs | (__underlying_type(Enum))rhs); } \
constexpr Enum operator&(Enum lhs, Enum rhs) noexcept { return (Enum)((__underlying_type(Enum))lhs & (__underlying_type(Enum))rhs); } \
constexpr Enum operator~(Enum e) noexcept { return (Enum)~(__underlying_type(Enum))e; } \
constexpr bool operator!(Enum e) noexcept { return !(__underlying_type(Enum))e; }
enum class CompressMode {
Zip,
GZip
};
namespace utils {
/// Возвращает описание ошибки
std::string error_code_message(const boost::system::error_code& ec);
// Кодирует массив байтов в base64 строку
std::string encode64(const std::vector<uint8_t>& data);
// Декодирует массив байтов из base64 строки
std::vector<uint8_t> decode64(const std::string& base64);
// Сжимает данные в zip/gzip поток
bool deflate(CompressMode mode, const void* uncompressedData, size_t length, std::vector<uint8_t>& compressedData);
// Распаковывает данные из zip/gzip потока
bool inflate(CompressMode mode, const void* compressedData, size_t length, std::vector<uint8_t>& uncompressedData);
FILE* fopen(const std::string& filename, const std::string& mode);
FILE* fopen(const std::wstring& filename, const std::wstring& mode);
// это служит для открытия сайтов в системном браузере а не то что вы подумали
// для iOS тело определёно в Platform/iphone.mm
void OpenPath(const std::string& sitePath);
/// Мультиплатформенный sleep, время в миллисекундах (в тысячных долях)
void Sleep(uint32_t msec);
//
// Вероятно, переводится как "Read `name=value` pair";
// парсит строку формата `name=value`, записывает имя в name и значение в value.
// Возвращает true, если строка в нужном формате и false в противном случае.
//
bool ReadNvp(const std::string& str, std::string& name, std::string& value);
template <class Coll>
inline void tokenize(const std::string& str, Coll &token, const std::string& separators = std::string(" /\t:,()"))
{
std::string input(str);
std::string::size_type idx = 0;
if ((idx = input.find_first_not_of(separators)) == std::string::npos) {
return;
}
input = input.substr(idx);
while ((idx = input.find_first_of(separators)) != std::string::npos) {
token.push_back(input.substr(0, idx));
input = input.substr(idx + 1);
idx = input.find_first_not_of(separators);
if (idx == std::string::npos) {
break;
}
input = input.substr(idx);
}
if ((input.find_first_of(separators)) == std::string::npos) {
token.push_back(input);
}
}
bool equals(const char* a, const char* b);
bool iequals(const char* a, const char* b);
template <class T>
inline T lexical_cast(const char* str);
template <class T>
inline T lexical_cast(const std::string& str) { return lexical_cast<T>(str.c_str()); }
template <>
inline float lexical_cast(const char* str)
{
Assert(str != NULL);
return Float::ParseFixed(str);
}
template <>
inline double lexical_cast(const char* str)
{
Assert(str != NULL);
return Float::ParseDouble(str);
}
template <>
inline short lexical_cast(const char* str)
{
Assert(str != NULL);
return (short)Int::Parse(str);
}
template <>
inline int lexical_cast(const char* str)
{
Assert(str != NULL);
return Int::Parse(str);
}
template <>
inline unsigned int lexical_cast(const char* str)
{
Assert(str != NULL);
return Int::ParseUint(str);
}
template <>
inline long lexical_cast(const char* str)
{
Assert(str != NULL);
return Int::ParseLong(str);
}
template <>
inline unsigned long lexical_cast(const char* str)
{
Assert(str != NULL);
return Int::ParseLong(str);
}
template <>
inline long long lexical_cast(const char* str)
{
return Int::ParseLongLong(str);
}
template <>
inline unsigned char lexical_cast(const char* str)
{
Assert(str != NULL);
return (unsigned char)Int::Parse(str);
}
template <>
inline bool lexical_cast(const char* str)
{
Assert(str != NULL);
if (iequals(str, "true") || iequals(str, "yes") || equals(str, "1")) {
return true;
}
return false;
}
template <>
inline std::string lexical_cast(const char* value)
{
return value;
}
template <>
inline Color lexical_cast(const char* str)
{
return Color(str);
}
template <>
inline Color lexical_cast(const std::string& str)
{
return Color(str);
}
inline std::string lexical_cast(const std::string& value) {
return value;
}
inline std::string lexical_cast(float value, int precision = 16)
{
std::ostringstream ss;
ss << std::setprecision(precision) << value;
return ss.str();
}
inline std::string lexical_cast(double value, int precision = 16)
{
std::ostringstream ss;
ss << std::setprecision(precision) << value;
return ss.str();
}
inline std::string lexical_cast(char value)
{
std::ostringstream ss;
ss << (int)value;
return ss.str();
}
inline std::string lexical_cast(unsigned char value)
{
std::ostringstream ss;
ss << (int)value;
return ss.str();
}
inline std::string lexical_cast(Color color)
{
char buffer[16];
sprintf_s(buffer, sizeof(buffer), "#%02X%02X%02X%02X", color.red, color.green, color.blue, color.alpha);
return std::string(buffer);
}
template <class T>
inline std::string lexical_cast(const T& value)
{
std::ostringstream ss;
ss << value;
return ss.str();
}
/// Выводит в лог список текстур и занимаемую ими память
void DumpTextures();
bool IsMainThread();
void SetCurrentThreadAsMainThread();
}
#endif // __UTILS_UTILS_H__
| 23.848101 | 136 | 0.715145 | [
"vector"
] |
2f4f0b36b0fbfd8bb010a937085e22baf0c63a01 | 2,274 | hpp | C++ | framework/include/node.hpp | ttobollik/CGLab_-Haffky117185_Tobollik118988 | 74c2bb2fdba634de95a74224369ae55913a3c7b5 | [
"MIT"
] | null | null | null | framework/include/node.hpp | ttobollik/CGLab_-Haffky117185_Tobollik118988 | 74c2bb2fdba634de95a74224369ae55913a3c7b5 | [
"MIT"
] | null | null | null | framework/include/node.hpp | ttobollik/CGLab_-Haffky117185_Tobollik118988 | 74c2bb2fdba634de95a74224369ae55913a3c7b5 | [
"MIT"
] | null | null | null | #ifndef NODE_HPP
#define NODE_HPP
#include <glm/glm.hpp>
#include <iostream>
#include <vector>
#include <memory>
/*
Node which models transformations existing for all types of nodes (transform, name etc.)
*/
class Node {
public:
//constructors
//default
Node();
//using pointer to parent and name
Node(std::shared_ptr<Node> parent, std::string const& name);
//using pointer to parent, name, size, speed and position
Node(std::shared_ptr<Node> parent, std::string const& name, float size, float speed,
glm::fvec3 const& position);
//getter and setter
//gives nack smart pointer to parent
std::shared_ptr<Node> getParent() const;
// sets parent node using a smart pointer (object gets destroyed if it has no pointer attached to it)
void setParent(std::shared_ptr<Node> const& parent);
//gives back a vector of pointers to all children of the current node
std::vector<std::shared_ptr<Node>> getChildrenList() const;
//gives back pointer to a specific child by comparing the name attribute
std::shared_ptr<Node> const& getChild(std::string name);
std::string getName() const; //name of node
std::string getPath() const; //path, where the node is
int getDepth() const; //depth, where the node is on the graph
glm::mat4 getLocalTransform() const; //Transformation Matrix in Object Space
glm::mat4 getWorldTransform() const; //Transformation Matrix in World Space
float getSpeed() const;
float getDistanceToCenter() const;
void setLocalTransform(glm::mat4 const& transform);
void setWorldTransform(glm::mat4 const& transform);
void addChild(std::shared_ptr<Node> const& node);
std::shared_ptr<Node> removeChild(std::string const& node);
bool hasChild(std::string const& name);
void setSpeed(float speed); //setting speed and multiplying before drawing
void setDistanceToCenter(float distance);
virtual std::ostream& print(std::ostream& os) const; //little helper for Debugging
protected:
std::shared_ptr<Node> parent_;
std::vector<std::shared_ptr<Node>> children_;
std::string name_;
int depth_;
std::string path_;
glm::mat4 localTransform_;
glm::mat4 worldTransform_{glm::mat4(1.0f)};
float speed_;
float distance_to_center_;
};
std::ostream& operator<<(std::ostream& os, Node const& n); //little helper for Debugging
#endif | 33.940299 | 102 | 0.747581 | [
"object",
"vector",
"transform"
] |
2f523969d10a120a8ebeb6ebd3e7744d6f23a171 | 12,182 | cpp | C++ | AADC/src/adtfUser/dev/src/objectFilter/object_filter.cpp | AADC-Fruit/AADC_2015_FRUIT | 88bd18871228cb48c46a3bd803eded6f14dbac08 | [
"BSD-3-Clause"
] | 1 | 2018-05-10T22:35:25.000Z | 2018-05-10T22:35:25.000Z | AADC/src/adtfUser/dev/src/objectFilter/object_filter.cpp | AADC-Fruit/AADC_2015_FRUIT | 88bd18871228cb48c46a3bd803eded6f14dbac08 | [
"BSD-3-Clause"
] | null | null | null | AADC/src/adtfUser/dev/src/objectFilter/object_filter.cpp | AADC-Fruit/AADC_2015_FRUIT | 88bd18871228cb48c46a3bd803eded6f14dbac08 | [
"BSD-3-Clause"
] | null | null | null | #include "stdafx.h"
#include "object_filter.h"
#include <opencv/cv.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "cvBlob/cvblob.h"
#include "../util/point_transformer.h"
#include "../util/vector2.h"
#include <fstream>
#include <sstream>
#include <iostream>
using namespace cv;
using namespace cvb;
ADTF_FILTER_PLUGIN("FRUIT Object Filter", OID_ADTF_OBJECT_FILTER, ObjectFilter);
// -------------------------------------------------------------------------------------------------
ObjectFilter::ObjectFilter(const tChar* __info) {
// -------------------------------------------------------------------------------------------------
cMemoryBlock::MemSet(&input_format_, 0, sizeof(input_format_));
cMemoryBlock::MemSet(&output_format_, 0, sizeof(output_format_));
SetPropertyStr("basePath", "/home/odroid/AADC/aux/base.png");
SetPropertyInt("diffThreshold", 45);
SetPropertyInt("whiteThreshold", 245);
SetPropertyFloat("scaleWidth", 1);
SetPropertyFloat("scaleHeight", 1);
SetPropertyInt("offsetHor", 0);
SetPropertyInt("minBlobSize", 500);
SetPropertyInt("maxBlobSize", 1000000);
}
// -------------------------------------------------------------------------------------------------
ObjectFilter::~ObjectFilter() {
// -------------------------------------------------------------------------------------------------
}
// -------------------------------------------------------------------------------------------------
tResult ObjectFilter::Init(tInitStage stage, __exception) {
// -------------------------------------------------------------------------------------------------
RETURN_IF_FAILED(cFilter::Init(stage, __exception_ptr));
if (stage == StageFirst) {
// Create and register the video input pin
RETURN_IF_FAILED(video_input_pin_.Create("Video_Input", IPin::PD_Input,
static_cast<IPinEventSink*>(this)));
RETURN_IF_FAILED(RegisterPin(&video_input_pin_));
// Create and register the video output pin
RETURN_IF_FAILED(video_output_pin_.Create("Video_Output", IPin::PD_Output, NULL));
RETURN_IF_FAILED(RegisterPin(&video_output_pin_));
// Set up the media description manager object for object output
cObjectPtr<IMediaDescriptionManager> description_manager;
RETURN_IF_FAILED(_runtime->GetObject(OID_ADTF_MEDIA_DESCRIPTION_MANAGER,
IID_ADTF_MEDIA_DESCRIPTION_MANAGER, (tVoid**) &description_manager, __exception_ptr));
// Create the output stream description for object data output
tChar const * output_stream_type = description_manager->GetMediaDescription("ObjectArray");
RETURN_IF_POINTER_NULL(output_stream_type);
cObjectPtr<IMediaType> output_type_signal_value = new cMediaType(0, 0, 0, "ObjectArray",
output_stream_type, IMediaDescription::MDF_DDL_DEFAULT_VERSION);
RETURN_IF_FAILED(output_type_signal_value->GetInterface(IID_ADTF_MEDIA_TYPE_DESCRIPTION,
(tVoid**) &object_data_description_));
// Create and register the object data output pin
RETURN_IF_FAILED(object_output_pin_.Create("objects", output_type_signal_value, NULL));
RETURN_IF_FAILED(RegisterPin(&object_output_pin_));
RETURN_IF_FAILED(mapped_object_output_pin_.Create("mapped_objects", output_type_signal_value, NULL));
RETURN_IF_FAILED(RegisterPin(&mapped_object_output_pin_));
}
else if (stage == StageGraphReady) {
cObjectPtr<IMediaType> type;
RETURN_IF_FAILED(video_input_pin_.GetMediaType(&type));
cObjectPtr<IMediaTypeVideo> type_video;
RETURN_IF_FAILED(type->GetInterface(IID_ADTF_MEDIA_TYPE_VIDEO, (tVoid**) &type_video));
const tBitmapFormat* format = type_video->GetFormat();
tBitmapFormat output_format;
output_format.nWidth = 640;
output_format.nHeight = 480;
output_format.nBitsPerPixel = 24;
output_format.nPixelFormat = 45;
output_format.nBytesPerLine = 1920;
output_format.nSize = 921600;
output_format.nPaletteSize = 0;
if (format == NULL) RETURN_ERROR(ERR_NOT_SUPPORTED);
cMemoryBlock::MemCopy(&input_format_, format, sizeof(tBitmapFormat));
cMemoryBlock::MemCopy(&output_format_, &output_format, sizeof(tBitmapFormat));
video_output_pin_.SetFormat(&output_format_, NULL);
}
RETURN_NOERROR;
}
// -------------------------------------------------------------------------------------------------
tResult ObjectFilter::Shutdown(tInitStage stage, __exception) {
// -------------------------------------------------------------------------------------------------
return cFilter::Shutdown(stage,__exception_ptr);
}
// -------------------------------------------------------------------------------------------------
tResult ObjectFilter::OnPinEvent(IPin* source, tInt event_code, tInt param1, tInt param2,
IMediaSample* media_sample) {
// -------------------------------------------------------------------------------------------------
RETURN_IF_POINTER_NULL(source);
RETURN_IF_POINTER_NULL(media_sample);
if (event_code == IPinEventSink::PE_MediaSampleReceived) {
if (source == &video_input_pin_) {
processImage(media_sample);
}
}
RETURN_NOERROR;
}
// -------------------------------------------------------------------------------------------------
tResult ObjectFilter::processImage(IMediaSample* sample) {
// -------------------------------------------------------------------------------------------------
// Check if the sample is valid
RETURN_IF_POINTER_NULL(sample);
// Create the new image sample to transmit at the end
cObjectPtr<IMediaSample> image_sample;
RETURN_IF_FAILED(_runtime->CreateInstance(OID_ADTF_MEDIA_SAMPLE, IID_ADTF_MEDIA_SAMPLE, (tVoid**) &image_sample));
RETURN_IF_FAILED(image_sample->AllocBuffer(output_format_.nSize));
// Initialize the data buffers
const tVoid* source_buffer;
tVoid* dest_buffer;
std::vector<Object> objects;
std::vector<Object> mapped_objects;
if (IS_OK(sample->Lock(&source_buffer))) {
if (IS_OK(image_sample->WriteLock(&dest_buffer))) {
int source_width = input_format_.nWidth;
int source_height = input_format_.nHeight;
// Create the source image matrix
Mat source_image(source_height, source_width, CV_8UC2, (uchar*)source_buffer);
// Retrieve the actual depth image
Mat source_channels[2];
split(source_image, source_channels);
Mat depth_image = source_channels[1];
// Retrieve the base image
Mat base_image = imread(GetPropertyStr("basePath"), 0);
int base_threshold = GetPropertyInt("diffThreshold");
int white_threshold = GetPropertyInt("whiteThreshold");
for (int i = 0; i < depth_image.rows; i++) {
for (int j = 0; j < depth_image.cols; j++) {
// Merge white and black noise and substract from base
if (depth_image.at<uchar>(i,j) >= white_threshold) depth_image.at<uchar>(i,j) = 0;
// Substract the base image from the actual image
int grey_diff = depth_image.at<uchar>(i,j) - base_image.at<uchar>(i,j);
if (depth_image.at<uchar>(i,j) == 0 || abs(grey_diff) < base_threshold) {
depth_image.at<uchar>(i,j) = 0;
} else if (i >= 113 && i <= 130) {
depth_image.at<uchar>(i,j) = depth_image.at<uchar>(i-1, j);
}
}
}
// Create objects used for blob detection
Mat blob_image;
cvtColor(depth_image, blob_image, COLOR_GRAY2BGR);
CvBlobs blobs;
IplImage *blob_label = cvCreateImage(cvSize(depth_image.cols, depth_image.rows), IPL_DEPTH_LABEL, 1);
IplImage ipl_depth_image = depth_image;
IplImage ipl_blob_image = blob_image;
cvLabel(&ipl_depth_image, blob_label, blobs);
cvFilterByArea(blobs, GetPropertyInt("minBlobSize"), GetPropertyInt("maxBlobSize"));
for (CvBlobs::iterator i = blobs.begin(); i != blobs.end(); i++) {
// Retrieve the blob data
int minx = i->second->minx;
int miny = i->second->miny;
int maxx = i->second->maxx;
int maxy = i->second->maxy;
int width = i->second->maxx - i->second->minx;
int height = i->second->maxy - i->second->miny;
// Add blob object
/*Vector2 min_point(2 * minx - GetPropertyInt("OffsetHor"), 2 * miny);
Vector2 max_point(2 * maxx - GetPropertyInt("OffsetHor"), 2 * maxy);
Vector2 source_scale(2 * source_width, 2 * source_height);
min_point = PointTransformer::map_to_aerial_view(min_point);
max_point = PointTransformer::map_to_aerial_view(max_point);
source_scale = PointTransformer::map_to_aerial_view(source_scale);
Object cur_mapped(
min_point.get_x(), min_point.get_y(),
(max_point.get_x() - min_point.get_x()) * GetPropertyFloat("ScaleWidth"), (max_point.get_y() - min_point.get_y()) * GetPropertyFloat("ScaleHeight"),
source_scale.get_x(), source_scale.get_y());
mapped_objects.push_back(cur_mapped);*/
Object cur(
2 * minx - GetPropertyInt("OffsetHor"), 2 * miny,
2 * width * GetPropertyFloat("ScaleWidth"), 2* height * GetPropertyFloat("ScaleHeight"),
2 * source_width, 2 * source_height);
objects.push_back(cur);
if (cur.get_relative_height() <= cur.get_relative_width() * 1.2) {
Vector2 cur_origin(cur.get_absolute_x(), cur.get_absolute_y() + cur.get_absolute_height());
Vector2 cur_max(cur.get_absolute_x() + cur.get_absolute_width(), cur.get_absolute_y() + cur.get_absolute_height());
Vector2 cur_source(cur.get_absolute_x() + cur.get_absolute_width(), cur.get_absolute_y() + cur.get_absolute_height());
cur_origin = PointTransformer::map_to_aerial_view(cur_origin);
cur_max = PointTransformer::map_to_aerial_view(cur_max);
cur_source = PointTransformer::map_to_aerial_view(cur_source);
int obj_width = cur_max.get_x() - cur_origin.get_x();
int obj_height = cur_max.get_y() - cur_max.get_y();
Object cur_mapped(cur_origin.get_x(), cur_origin.get_y(), obj_width, obj_height, cur_source.get_y(), cur_source.get_x());
mapped_objects.push_back(cur_mapped);
}
}
// Render the blobs into the image to be transmitted
cvRenderBlobs(blob_label, blobs, &ipl_blob_image, &ipl_blob_image);
// Copy the blobbed image into the destination buffer
int output_height = output_format_.nHeight;
int output_width = output_format_.nWidth;
resize(blob_image, blob_image, Size(output_width, output_height));
memcpy((uchar*)dest_buffer, (uchar*)blob_image.data, 3 * output_height * output_width);
// Release the images used for blobbing
cvReleaseImage(&blob_label);
cvReleaseBlobs(blobs);
image_sample->Unlock(dest_buffer);
}
image_sample->SetTime(sample->GetTime());
sample->Unlock(source_buffer);
}
// Transmit the blobs via the object list output pin
transmitObjects(objects, object_output_pin_);
transmitObjects(mapped_objects, mapped_object_output_pin_);
RETURN_IF_FAILED(video_output_pin_.Transmit(image_sample));
RETURN_NOERROR;
}
// -------------------------------------------------------------------------------------------------
tResult ObjectFilter::transmitObjects(std::vector<Object> const & objects, cOutputPin & output_pin) {
// -------------------------------------------------------------------------------------------------
cObjectPtr<IMediaSample> objects_sample;
RETURN_IF_FAILED(AllocMediaSample(&objects_sample));
RETURN_IF_FAILED(objects_sample->AllocBuffer(sizeof(tUInt32) + sizeof(Object) * objects.size()));
tUInt32* dest_buffer = NULL;
RETURN_IF_FAILED(objects_sample->WriteLock((tVoid**)&dest_buffer));
(*dest_buffer) = (tUInt32)objects.size();
dest_buffer++;
cMemoryBlock::MemCopy(dest_buffer, &(objects[0]), sizeof(Object) * objects.size());
RETURN_IF_FAILED(objects_sample->Unlock((tVoid*)dest_buffer));
output_pin.Transmit(objects_sample);
RETURN_NOERROR;
}
| 43.045936 | 161 | 0.621491 | [
"render",
"object",
"vector"
] |
01694919c31fd5b6c8238be46bc7e8b680a69055 | 1,126 | cpp | C++ | Plugins/org.blueberry.ui.qt/src/berryShowInContext.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.blueberry.ui.qt/src/berryShowInContext.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.blueberry.ui.qt/src/berryShowInContext.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "berryShowInContext.h"
#include "berryISelection.h"
namespace berry {
ShowInContext::ShowInContext(const Object::Pointer& input, const SmartPointer<const ISelection>& selection)
: input(input)
, selection(selection)
{
}
Object::Pointer ShowInContext::GetInput() const
{
return input;
}
SmartPointer<const ISelection> ShowInContext::GetSelection() const
{
return selection;
}
void ShowInContext::SetInput(const Object::Pointer& input)
{
this->input = input;
}
void ShowInContext::SetSelection(const SmartPointer<const ISelection>& selection)
{
this->selection = selection;
}
}
| 22.52 | 108 | 0.64476 | [
"object"
] |
018926413ecb9664fb39c1987d94c48b3c7d9a2c | 6,199 | cpp | C++ | 3rdparty/openmm/platforms/opencl/tests/TestOpenCLDeviceQuery.cpp | merkys/MMB | 0531385b8367405e1188e31c3eef7aa4cc50170b | [
"MIT"
] | 5 | 2020-07-31T17:33:03.000Z | 2022-01-01T19:24:37.000Z | 3rdparty/openmm/platforms/opencl/tests/TestOpenCLDeviceQuery.cpp | merkys/MMB | 0531385b8367405e1188e31c3eef7aa4cc50170b | [
"MIT"
] | 11 | 2020-06-16T05:05:42.000Z | 2022-03-30T09:59:14.000Z | 3rdparty/openmm/platforms/opencl/tests/TestOpenCLDeviceQuery.cpp | merkys/MMB | 0531385b8367405e1188e31c3eef7aa4cc50170b | [
"MIT"
] | 9 | 2020-01-24T12:02:37.000Z | 2020-10-16T06:23:56.000Z | /**
* This file is adapted from vexcl's (https://github.com/ddemidov/vexcl)
* example "devlist.cpp", which is
*
* Copyright (c) 2012-2014 Denis Demidov <dennis.demidov@gmail.com>
*
* 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 <iostream>
#include <iomanip>
#include <sstream>
#include <iterator>
#include <set>
#include <algorithm>
#include <vector>
#include "OpenCLContext.h"
using namespace std;
#define SHOW_DEVPROP(name) \
cout << " " << left << setw(32) << #name << " = " \
<< d.getInfo< name >() << endl
int main() {
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
cout << "OpenCL devices:" << endl << endl;
for (int j = 0; j < platforms.size(); j++) {
vector<cl::Device> devices;
try {
platforms[j].getDevices(CL_DEVICE_TYPE_ALL, &devices);
}
catch (...) {
// There are no devices available for this platform.
continue;
}
for (int i = 0; i < devices.size(); i++) {
cl::Device d = devices[i];
cout << "OpenCLPlatformIndex " << j << ", OpenCLDeviceIndex " << i << ": \"" << d.getInfo<CL_DEVICE_NAME>()
<< "\"" << endl << " " << left << setw(32) << "CL_PLATFORM_NAME" << " = "
<< cl::Platform(d.getInfo<CL_DEVICE_PLATFORM>()).getInfo<CL_PLATFORM_NAME>()
<< endl
<< " " << left << setw(32) << "CL_PLATFORM_VENDOR" << " = "
<< platforms[j].getInfo<CL_PLATFORM_VENDOR>()
<< endl;
SHOW_DEVPROP(CL_DEVICE_VENDOR);
SHOW_DEVPROP(CL_DEVICE_VERSION);
cout << " " << left << setw(32) << "CL_DEVICE_TYPE" << " = ";
if (d.getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_CPU) {
cout << "CL_DEVICE_TYPE_CPU" << endl;
} else if (d.getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_GPU) {
cout << "CL_DEVICE_TYPE_GPU" << endl;
} else if (d.getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_ACCELERATOR) {
cout << "CL_DEVICE_TYPE_ACCELERATOR" << endl;
} else {
cout << "Unknown" << endl;
}
SHOW_DEVPROP(CL_DEVICE_MAX_COMPUTE_UNITS);
cout << " " << left << setw(32) << "CL_DEVICE_MAX_WORK_ITEM_SIZES" << " = [";
for (int k = 0; k < d.getInfo<CL_DEVICE_MAX_WORK_ITEM_SIZES>().size(); k++) {
cout << d.getInfo<CL_DEVICE_MAX_WORK_ITEM_SIZES>()[k];
if (k < d.getInfo<CL_DEVICE_MAX_WORK_ITEM_SIZES>().size() - 1)
cout << ", ";
}
cout << "]" << endl;
SHOW_DEVPROP(CL_DEVICE_HOST_UNIFIED_MEMORY);
SHOW_DEVPROP(CL_DEVICE_GLOBAL_MEM_SIZE);
SHOW_DEVPROP(CL_DEVICE_LOCAL_MEM_SIZE);
SHOW_DEVPROP(CL_DEVICE_MAX_MEM_ALLOC_SIZE);
SHOW_DEVPROP(CL_DEVICE_ADDRESS_BITS);
SHOW_DEVPROP(CL_DEVICE_MAX_CLOCK_FREQUENCY);
int processingElementsPerComputeUnit;
if (d.getInfo<CL_DEVICE_TYPE>() != CL_DEVICE_TYPE_GPU) {
processingElementsPerComputeUnit = 1;
} else if (d.getInfo<CL_DEVICE_EXTENSIONS>().find("cl_nv_device_attribute_query") != string::npos) {
cl_uint computeCapabilityMajor;
#ifdef CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV
clGetDeviceInfo(d(), CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV, sizeof(cl_uint), &computeCapabilityMajor, NULL);
processingElementsPerComputeUnit = (computeCapabilityMajor < 2 ? 8 : 32);
#endif
} else if (d.getInfo<CL_DEVICE_EXTENSIONS>().find("cl_amd_device_attribute_query") != string::npos) {
#ifdef CL_DEVICE_SIMD_PER_COMPUTE_UNIT_AMD
try {
processingElementsPerComputeUnit = d.getInfo<CL_DEVICE_SIMD_PER_COMPUTE_UNIT_AMD>() *
d.getInfo<CL_DEVICE_SIMD_WIDTH_AMD>() *
d.getInfo<CL_DEVICE_SIMD_INSTRUCTION_WIDTH_AMD>();
} catch (cl::Error err) {}
#endif
}
cout << " processingElementsPerComputeUnit" << " = " << processingElementsPerComputeUnit << endl;
int speed = devices[i].getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>()*processingElementsPerComputeUnit*d.getInfo<CL_DEVICE_MAX_CLOCK_FREQUENCY>();
cout << " estimatedSpeed = " << speed << endl;
cout << " " << left << setw(32) << "CL_DEVICE_EXTENSIONS" << " = ";
istringstream iss(d.getInfo<CL_DEVICE_EXTENSIONS>());
set<string> extensions;
extensions.insert(istream_iterator<string>(iss), istream_iterator<string>());
size_t w = 40;
for (set<string>::iterator s = extensions.begin(); s != extensions.end(); ++s) {
w += s->length() + 1;
if (w > 80) {
cout << endl << setw(w = 8) << "";
w += s->length() + 1;
}
cout << *s << " ";
}
cout << endl << endl;
}
}
}
| 44.597122 | 150 | 0.58461 | [
"vector"
] |
019be7764e70d0b07af091de60cfc0b3bf597f76 | 2,815 | cc | C++ | lib/feature_names.cc | tmcombi/tmcombi | 976d3f333c01104e5efcabd8834854ad7677ea73 | [
"MIT"
] | null | null | null | lib/feature_names.cc | tmcombi/tmcombi | 976d3f333c01104e5efcabd8834854ad7677ea73 | [
"MIT"
] | null | null | null | lib/feature_names.cc | tmcombi/tmcombi | 976d3f333c01104e5efcabd8834854ad7677ea73 | [
"MIT"
] | 3 | 2019-03-31T19:04:20.000Z | 2020-01-13T22:32:09.000Z | #ifndef TMC_UNIT_TESTS
#define BOOST_TEST_MODULE lib_test_feature_names
#endif
#include <boost/test/included/unit_test.hpp>
#include "feature_names.h"
#ifndef TMC_UNIT_TESTS
bool is_critical(const std::exception& ) { return true; }
#endif
BOOST_AUTO_TEST_SUITE( feature_names )
BOOST_AUTO_TEST_CASE( from_string_stream )
{
std::string buffer("| this is comment\n"
"target_feature.| one more comment\n"
"\n"
" feature1: continuous. \n"
"feature2: continuous. | third comment\n"
"feature3: ignore.\n"
"feature4: continuous.\n"
"target_feature: v1, v2.\n"
"case weight: continuous.\n"
"feature5: continuous.\n"
"\n"
" | one more comment here\n"
"\n");
BOOST_TEST_MESSAGE("Testing names created from buffer:\n"
<< "#######################################################\n"
<< buffer
<< "#######################################################\n" );
std::stringstream ss((std::stringstream(buffer)));
FeatureNames fn(ss);
BOOST_CHECK_EQUAL(fn.dim(), 4);
BOOST_CHECK(fn.get_feature_indices() == std::vector<size_t>({0,1,3,6}));
BOOST_CHECK(fn.get_feature_names() == std::vector<std::string>({
"feature1",
"feature2",
"feature4",
"feature5"
}));
BOOST_CHECK_EQUAL(fn.get_target_feature_index(), 4);
BOOST_CHECK_EQUAL(fn.get_target_feature_name(), "target_feature");
BOOST_CHECK_EQUAL(fn.get_negatives_label(), "v1");
BOOST_CHECK_EQUAL(fn.get_positives_label(), "v2");
BOOST_CHECK_EQUAL(fn.get_weight_index(), 5);
}
BOOST_AUTO_TEST_CASE( exceptions ) {
std::string buffer("target_feature.\n"
"feature1: continuous.\n"
"feature2: continuous.\n"
"target_feature: v1, v2, v3.\n");
BOOST_TEST_MESSAGE("Testing names created from buffer:\n"
<< "#######################################################\n"
<< buffer
<< "#######################################################\n" );
std::stringstream ss((std::stringstream(buffer)));
BOOST_CHECK_EXCEPTION( FeatureNames fn(ss), std::invalid_argument, is_critical);
}
BOOST_AUTO_TEST_CASE( from_file ) {
const std::string names_file("data/tmc_paper_9/tmc_paper.names");
std::shared_ptr<FeatureNames> pFN = std::make_shared<FeatureNames>(names_file);
BOOST_CHECK_EQUAL(pFN->dim(), 2);
}
BOOST_AUTO_TEST_SUITE_END()
| 39.647887 | 96 | 0.512966 | [
"vector"
] |
019cddc27e1cdf897df4c8e1825e61cdc8fb8182 | 1,239 | hpp | C++ | examples/Example_get_apr_by_block.hpp | mosaic-group/LibAPR | 69097a662bf671d77a548fc47dae2c590675bfac | [
"Apache-2.0"
] | 27 | 2018-12-03T20:38:44.000Z | 2022-03-23T17:53:51.000Z | examples/Example_get_apr_by_block.hpp | mosaic-group/LibAPR | 69097a662bf671d77a548fc47dae2c590675bfac | [
"Apache-2.0"
] | 49 | 2018-11-28T09:10:56.000Z | 2022-01-12T20:42:11.000Z | examples/Example_get_apr_by_block.hpp | mosaic-group/LibAPR | 69097a662bf671d77a548fc47dae2c590675bfac | [
"Apache-2.0"
] | 7 | 2018-02-13T07:41:56.000Z | 2018-04-11T13:54:39.000Z | //
// Created by joel on 03.11.20.
//
#ifndef LIBAPR_EXAMPLE_GET_APR_BY_BLOCK_HPP
#define LIBAPR_EXAMPLE_GET_APR_BY_BLOCK_HPP
#include <functional>
#include <string>
#include "algorithm/APRParameters.hpp"
#include "data_structures/Mesh/PixelData.hpp"
#include "data_structures/APR/APR.hpp"
#include "algorithm/APRConverter.hpp"
#include "io/APRWriter.hpp"
struct cmdLineOptions{
std::string output_dir = "";
std::string output = "output";
std::string directory = "";
std::string input = "";
std::string mask_file = "";
bool neighborhood_optimization = true;
bool output_steps = false;
bool store_tree = false;
float sigma_th = 5;
float Ip_th = 0;
float lambda = 3;
float rel_error = 0.1;
float grad_th = 1;
int z_block_size = 128;
int z_ghost = 16; // number of "ghost slices" to use in the APR pipeline
int z_ghost_sampling = 64; // number of "ghost slices" to use when sampling intensities
};
bool command_option_exists(char **begin, char **end, const std::string &option);
char* get_command_option(char **begin, char **end, const std::string &option);
cmdLineOptions read_command_line_options(int argc, char **argv);
#endif //LIBAPR_EXAMPLE_GET_APR_BY_BLOCK_HPP
| 27.533333 | 91 | 0.715093 | [
"mesh"
] |
01a0a230d0f03f91df0ff5662142fa984b484f5b | 1,210 | cpp | C++ | Codechef/DSA Learning Series/Dynamic Programming Basics/AMSGAME2.cpp | JanaSabuj/cpmaster | d943780c7ca4badbefbce2d300848343c4032650 | [
"MIT"
] | null | null | null | Codechef/DSA Learning Series/Dynamic Programming Basics/AMSGAME2.cpp | JanaSabuj/cpmaster | d943780c7ca4badbefbce2d300848343c4032650 | [
"MIT"
] | null | null | null | Codechef/DSA Learning Series/Dynamic Programming Basics/AMSGAME2.cpp | JanaSabuj/cpmaster | d943780c7ca4badbefbce2d300848343c4032650 | [
"MIT"
] | null | null | null | /*
Sabuj Jana / @greenindia
https://www.janasabuj.github.io
*/
#include <bits/stdc++.h>
using namespace std;
#define crap ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define int long long int
#define double long double
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
#define endl "\n"
void print1d(const vector<int>& vec) {for (auto val : vec) {cout << val << " ";} cout << endl;}
void print2d(const vector<vector<int>>& vec) {for (auto row : vec) {for (auto val : row) {cout << val << " ";} cout << endl;}}
const int mod = 1e9 + 7;
// recursive dp go approach
// bcoz no idea of gcd inverse
int n;
int arr[61];
int cache[61][10004];
int go(int idx, int g) {
// base
if (idx == n) {
return (g == 1);
}
if (cache[idx][g] != -1)
return cache[idx][g];
// main
int sum = go(idx + 1, g) + go(idx + 1, __gcd(g, arr[idx]));
return cache[idx][g] = sum;
}
void solve() {
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
// cout << __gcd(55, 0) << endl;
memset(cache, -1, sizeof(cache));
int ans = go(0, 0);
cout << ans << endl;
}
signed main() {
crap;
int t = 1;
cin >> t;
while (t--) solve();
return 0;
} | 22.407407 | 127 | 0.568595 | [
"vector"
] |
01a54bd2bad5f2b4595f2920fe2bd6dba75802ba | 4,768 | cpp | C++ | src/tmx/TmxTools/src/j2735dump/j2735dump.cpp | networkmodeling/V2X-Hub | d363f49a4c9af76823a23033b9f7983f2f6ae095 | [
"Apache-2.0"
] | 56 | 2019-04-25T19:06:11.000Z | 2022-03-25T20:26:25.000Z | src/tmx/TmxTools/src/j2735dump/j2735dump.cpp | networkmodeling/V2X-Hub | d363f49a4c9af76823a23033b9f7983f2f6ae095 | [
"Apache-2.0"
] | 184 | 2019-04-24T18:20:08.000Z | 2022-03-22T18:56:45.000Z | src/tmx/TmxTools/src/j2735dump/j2735dump.cpp | networkmodeling/V2X-Hub | d363f49a4c9af76823a23033b9f7983f2f6ae095 | [
"Apache-2.0"
] | 34 | 2019-04-03T15:21:16.000Z | 2022-03-20T04:26:53.000Z | /*
* j2735dump.cpp
*
* Created on: Dec 15, 2016
* @author: gmb
*/
#include <boost/property_tree/ptree.hpp>
#include <boost/version.hpp>
#include <cstdio>
#include <tmx/j2735_messages/J2735MessageFactory.hpp>
#include <tmx/messages/message_converter.hpp>
#include <PluginExec.h>
#include <BsmConverter.h>
#ifndef DEFAULT_TREEREPAIR
#define DEFAULT_TREEREPAIR treerepair.xml
#endif
using namespace std;
using namespace tmx;
using namespace tmx::messages;
using namespace tmx::utils;
namespace j2735dump
{
#if BOOST_VERSION < 105800
typedef typename std::string::value_type xml_settings_type;
#else
typedef std::string xml_settings_type;
#endif
class J2735Dump: public Runnable
{
public:
J2735Dump(): Runnable(), msg("-")
{
AddOptions()
("repair-file,r", boost::program_options::value<string>()->default_value(quoted_attribute_name(DEFAULT_TREEREPAIR)), "XML to JSON repair file.")
("no-pretty-print", "Do not pretty print the output. Default is false")
("no-blobs", "Do not crack the BSM blobs. Default is false")
("xml,x", "Write output as XML. Default is to convert to JSON");
}
inline int Main()
{
if (msg == "-")
{
char buf[4000];
cin.getline(buf, sizeof(buf));
msg = string(buf);
}
PLOG(logDEBUG) << "Decoding message: " << msg;
// Figure out if this is a JSON message or just the bytes
bool jsonMsg = false;
int i;
for (i = 0; i < (int)msg.size() && (msg[i] == '\t' || msg[i] == ' '); i++); // Skip white space
if (msg[i] == '{') jsonMsg = true;
byte_stream bytes;
if (jsonMsg)
{
routeable_message routeableMsg;
routeableMsg.set_contents(msg);
PLOG(logDEBUG) << "Decoding routeable message: " << routeableMsg;
bytes = routeableMsg.get_payload_bytes();
}
else
{
bytes = battelle::attributes::attribute_lexical_cast<byte_stream>(msg);
}
PLOG(logDEBUG) << "Decoding bytes: " << bytes;
J2735MessageFactory factory;
TmxJ2735EncodedMessageBase *tmxMsg = factory.NewMessage(bytes);
if (!tmxMsg)
{
BOOST_THROW_EXCEPTION(factory.get_event());
exit(-1);
}
// Get a copy of the property tree to use and manipulate
PLOG(logDEBUG) << "Trying to copy message " << *tmxMsg;
PLOG(logDEBUG) << "Payload: " << tmxMsg->get_payload();
xml_message msg(tmxMsg->get_payload().get_container());
// Obtain a copy of the ptree for manipulation
message_tree_type tree = msg.get_container().get_storage().get_tree();
PLOG(logDEBUG) << "Copy: " << msg;
delete tmxMsg;
// If this is a BSM, then replace the contents of the blob with the decoded information
if (blobs && tree.count("BasicSafetyMessage"))
{
static DecodedBsmMessage crackedBsm;
// Decode the BSM
BsmMessage bsmMessage;
bsmMessage.set_contents(tree);
PLOG(logDEBUG) << "Cracking BSM " << bsmMessage;
BsmConverter::ToDecodedBsmMessage(*(bsmMessage.get_j2735_data()), crackedBsm);
// Reset the blob1 data in the message with the decoded information
string old_val = tree.get<string>("BasicSafetyMessage.blob1", "?");
tree.put_child("BasicSafetyMessage.blob1", crackedBsm.get_container().get_storage().get_tree());
tree.put("BasicSafetyMessage.blob1.Bytes", old_val);
msg.set_contents(tree);
}
if (xml)
{
boost::property_tree::xml_writer_settings<xml_settings_type> xmlSettings;
if (pretty)
xmlSettings = boost::property_tree::xml_writer_make_settings<xml_settings_type>('\t', 1);
boost::property_tree::write_xml(cout, msg.get_container().get_storage().get_tree(), xmlSettings);
}
else
{
tmx::XML ser;
message_converter *conv;
try
{
PLOG(logDEBUG) << "Trying to open converter file " << converter;
conv = new message_converter(ser, converter);
}
catch (exception &ex)
{
PLOG(logDEBUG2) << ex.what();
conv = 0;
}
json_message json(msg, conv);
boost::property_tree::write_json(cout, json.get_container().get_storage().get_tree(), pretty);
}
return (0);
}
inline bool ProcessOptions(const boost::program_options::variables_map &opts)
{
Runnable::ProcessOptions(opts);
if (opts.count(INPUT_FILES_PARAM))
{
vector<string> files = opts[INPUT_FILES_PARAM].as< vector<string> >();
if (files.size())
msg = files[0];
}
xml = opts.count("xml");
pretty = !(opts.count("no-pretty-print"));
blobs = !(opts.count("no-blobs"));
converter = opts["repair-file"].as<string>();
return true;
}
private:
string msg;
string converter;
bool xml = false;
bool pretty = true;
bool blobs = true;
};
} /* End namespace */
int main(int argc, char *argv[])
{
FILELog::ReportingLevel() = logERROR;
try
{
j2735dump::J2735Dump myExec;
run("", argc, argv, myExec);
}
catch (exception &ex)
{
cerr << ExceptionToString(ex) << endl;
throw;
}
}
| 24.326531 | 147 | 0.681628 | [
"vector"
] |
01a6837400450853544ea7a57f98e34bdb5758de | 221 | cpp | C++ | Dataset/Leetcode/test/55/484.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/55/484.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/55/484.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
bool XXX(vector<int>& nums) {
int n=nums.size();
for(int i=0,j=0;i<n;i++){
if(j<i)return false;
j=max(j,i+nums[i]);
}
return true;
}
};
| 17 | 33 | 0.452489 | [
"vector"
] |
01af5263f44f8a9ffcf31cca14c9a381a950af33 | 11,540 | cpp | C++ | include/hydro/engine/document/Resolver.cpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/engine/document/Resolver.cpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/engine/document/Resolver.cpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | //
// __ __ __
// / / / /__ __ ____/ /_____ ____
// / /_/ // / / // __ // ___// __ \
// / __ // /_/ // /_/ // / / /_/ /
// /_/ /_/ \__, / \__,_//_/ \____/
// /____/
//
// The Hydro Programming Language
//
#include "Resolver.hpp"
namespace hydro::engine
{
Resolver::Resolver(compiler::ErrorReporter *errorReporter)
{
mErrorReporter = errorReporter;
}
Resolver::~Resolver()
{
}
void Resolver::resolve(Document *document)
{
push(document);
document->accept(this);
pop();
}
void Resolver::visit(Document *document)
{
for(auto attr : document->attributes())
attr->accept(this);
for(auto child : document->children())
child->accept(this);
}
void Resolver::visit(Element *element)
{
push(element);
element->getIdentity()->accept(this);
for(auto attr : element->attributes())
attr->accept(this);
for(auto child : element->children())
child->accept(this);
pop();
}
void Resolver::visit(ElementIdentity *identity)
{
identity->getSubject()->accept(this);
}
void Resolver::visit(ElementClass *_class)
{
Symbol *symbol = resolvePrototype(_class->getName()->getValue());
if(!symbol)
{
mErrorReporter->reportError("The prototype '" + _class->getName()->getValue() + "' is undefined.", _class->getName()->getSourcePosition());
}
}
void Resolver::visit(ElementReference *reference)
{
}
void Resolver::visit(Procedure *procedure)
{
}
void Resolver::visit(ProcedureIdentity *identity)
{
}
void Resolver::visit(ProcedureClass *_class)
{
}
void Resolver::visit(ProcedureReference *reference)
{
}
void Resolver::visit(Snapshot *snapshot)
{
}
void Resolver::visit(SnapshotIdentity *identity)
{
}
void Resolver::visit(SnapshotDomain *domain)
{
}
void Resolver::visit(SnapshotReference *reference)
{
}
void Resolver::visit(Keyframe *keyframe)
{
}
void Resolver::visit(KeyframeReference *reference)
{
}
void Resolver::visit(Action *action)
{
}
void Resolver::visit(ActionIdentity *identity)
{
}
void Resolver::visit(EventClass *_class)
{
}
void Resolver::visit(ActionReference *reference)
{
}
void Resolver::visit(Prototype *prototype)
{
}
void Resolver::visit(PrototypeIdentity *identity)
{
}
void Resolver::visit(Invocation *invocation)
{
}
void Resolver::visit(InvocationIdentity *identity)
{
}
void Resolver::visit(InvocationTarget *target)
{
}
void Resolver::visit(InvocationReference *reference)
{
}
void Resolver::visit(Query *query)
{
}
void Resolver::visit(QueryIdentity *identity)
{
}
void Resolver::visit(QueryTarget *target)
{
}
void Resolver::visit(Model *model)
{
}
void Resolver::visit(ModelIdentity *identity)
{
}
void Resolver::visit(ModelDescription *description)
{
}
void Resolver::visit(CompoundReference *reference)
{
}
void Resolver::visit(IdentityRelationshipsList *relationships)
{
}
void Resolver::visit(Attribute *attribute)
{
}
void Resolver::visit(Mirror *mirror)
{
}
void Resolver::visit(SimpleName *name)
{
}
void Resolver::visit(QualifiedName *name)
{
}
void Resolver::visit(ElementID *name)
{
}
void Resolver::visit(SelectorInitializer *expression)
{
}
void Resolver::visit(AttributeSelector *selector)
{
}
void Resolver::visit(ElementSelector *selector)
{
}
void Resolver::visit(ProcedureSelector *selector)
{
}
void Resolver::visit(InvocationSelector *selector)
{
}
void Resolver::visit(SnapshotSelector *selector)
{
}
void Resolver::visit(KeyframeSelector *selector)
{
}
void Resolver::visit(ActionSelector *selector)
{
}
void Resolver::visit(ChildSelector *selector)
{
}
void Resolver::visit(DescendantSelector *selector)
{
}
/**
* Visits the index selector.
* @param selector The selector to Resolver::visit.
*/
void Resolver::visit(IndexSelector *selector)
{
}
/**
* Visits the self selector.
* @param selector The selector to Resolver::visit.
*/
void Resolver::visit(SelfSelector *selector)
{
}
/**
* Visits the parent selector.
* @param selector The selector to Resolver::visit.
*/
void Resolver::visit(ParentSelector *selector)
{
}
/**
* Visits the root selector.
* @param selector The selector to Resolver::visit.
*/
void Resolver::visit(RootSelector *selector)
{
}
/**
* Visits the document selector.
* @param selector The selector to Resolver::visit.
*/
void Resolver::visit(DocumentSelector *selector)
{
}
/**
* Visits a undefined expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(UndefinedExpression *expression)
{
}
/**
* Visits a null expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(NullExpression *expression)
{
}
/**
* Visits a boolean literal expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(BooleanLiteral *expression)
{
}
/**
* Visits a color literal expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(ColorLiteral *expression)
{
}
/**
* Visits a multiplicity literal expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(MultiplicityLiteral *expression)
{
}
/**
* Visits a number literal expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(NumberLiteral *expression)
{
}
/**
* Visits a time point literal expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(TimePointLiteral *expression)
{
}
/**
* Visits a percent literal expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(PercentLiteral *expression)
{
}
/**
* Visits a string literal expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(StringLiteral *expression)
{
}
/**
* Visits a nested expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(NestedExpression *expression)
{
}
/**
* Visits a logical NOT unary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(LogicalNOTExpression *expression)
{
}
/**
* Visits a bitwise NOT unary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(BitwiseNOTExpression *expression)
{
}
/**
* Visits a positive expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(PositiveExpression *expression)
{
}
/**
* Visits a negative unary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(NegationExpression *expression)
{
}
/**
* Visits an exponentiation binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(ExponentiationExpression *expression)
{
}
/**
* Visits a multiplication binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(MultiplicationExpression *expression)
{
}
/**
* Visits a division binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(DivisionExpression *expression)
{
}
/**
* Visits a remainder (modulo) binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(RemainderExpression *expression)
{
}
/**
* Visits an addition binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(AdditionExpression *expression)
{
}
/**
* Visits a subtraction binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(SubtractionExpression *expression)
{
}
/**
* Visits a equality binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(EqualityExpression *expression)
{
}
/**
* Visits a inequality binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(InequalityExpression *expression)
{
}
/**
* Visits a greater than binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(GreaterThanExpression *expression)
{
}
/**
* Visits a greater than or equal binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(GreaterThanOrEqualExpression *expression)
{
}
/**
* Visits a less than binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(LessThanExpression *expression)
{
}
/**
* Visits a less than or equal binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(LessThanOrEqualExpression *expression)
{
}
/**
* Visits a logical AND binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(LogicalANDExpression *expression)
{
}
/**
* Visits a bitwise AND binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(BitwiseANDExpression *expression)
{
}
/**
* Visits a logical OR binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(LogicalORExpression *expression)
{
}
/**
* Visits a bitwise OR binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(BitwiseORExpression *expression)
{
}
/**
* Visits a bitwise XOR binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(BitwiseXORExpression *expression)
{
}
/**
* Visits a bitwise left shift binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(BitwiseLeftShiftExpression *expression)
{
}
/**
* Visits a bitwise right shift binary expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(BitwiseRightShiftExpression *expression)
{
}
/**
* Visits a member access expression.
* @param expression The expression to Resolver::visit.
*/
void Resolver::visit(MemberAccess *expression)
{
}
void Resolver::visit(SubscriptAccess *expression)
{
}
void Resolver::visit(ConditionalExpression *expression)
{
}
void Resolver::visit(WhenBinding *binding)
{
}
void Resolver::visit(WhileBinding *binding)
{
}
void Resolver::push(Entity *node)
{
mNodeStack.push_back(node);
}
void Resolver::pop()
{
mNodeStack.pop_back();
}
Entity *Resolver::top() const
{
return !mNodeStack.empty() ? mNodeStack[mNodeStack.size() - 1] : nullptr;
}
PrototypeSymbol *Resolver::resolvePrototype(std::string name)
{
Entity *node = top();
if (node)
{
PDocumentContext *context = node->getContext();
while (context)
{
for(Symbol *symbol : context->symbols())
if(PrototypeSymbol *prototype = dynamic_cast<PrototypeSymbol *>(symbol))
if(prototype->getName() == name)
return prototype;
context = context->getParent();
}
}
// fail
return nullptr;
}
} // namespace hydro::engine
| 16.485714 | 147 | 0.67149 | [
"model"
] |
01ba8e8337e8cb773d6420ea68d6eb2b2b95ae4a | 1,107 | hpp | C++ | DataSpec/DNAMP1/ScriptObjects/VisorGoo.hpp | jackoalan/urde | 413483a996805a870f002324ee46cfc123f4df06 | [
"MIT"
] | 267 | 2016-03-10T21:59:16.000Z | 2021-03-28T18:21:03.000Z | DataSpec/DNAMP1/ScriptObjects/VisorGoo.hpp | cobalt2727/metaforce | 3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a | [
"MIT"
] | 129 | 2016-03-12T10:17:32.000Z | 2021-04-05T20:45:19.000Z | DataSpec/DNAMP1/ScriptObjects/VisorGoo.hpp | cobalt2727/metaforce | 3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a | [
"MIT"
] | 31 | 2016-03-20T00:20:11.000Z | 2021-03-10T21:14:11.000Z | #pragma once
#include "../../DNACommon/DNACommon.hpp"
#include "IScriptObject.hpp"
#include "Parameters.hpp"
namespace DataSpec::DNAMP1 {
struct VisorGoo : IScriptObject {
AT_DECL_DNA_YAMLV
String<-1> name;
Value<atVec3f> position;
UniqueID32 particle;
UniqueID32 electric;
Value<float> minDist;
Value<float> maxDist;
Value<float> nearProb;
Value<float> farProb;
DNAColor color;
Value<atUint32> sfx;
Value<bool> skipAngleTest;
void nameIDs(PAKRouter<PAKBridge>& pakRouter) const override {
if (particle.isValid()) {
PAK::Entry* ent = (PAK::Entry*)pakRouter.lookupEntry(particle);
ent->name = name + "_part";
}
if (electric.isValid()) {
PAK::Entry* ent = (PAK::Entry*)pakRouter.lookupEntry(electric);
ent->name = name + "_elsc";
}
}
void gatherDependencies(std::vector<hecl::ProjectPath>& pathsOut,
std::vector<hecl::ProjectPath>& lazyOut) const override {
g_curSpec->flattenDependencies(particle, pathsOut);
g_curSpec->flattenDependencies(electric, pathsOut);
}
};
} // namespace DataSpec::DNAMP1
| 27.675 | 83 | 0.682023 | [
"vector"
] |
01c16bddf7609824f7a7a3f9762b506db0e7bdb7 | 47,370 | cc | C++ | chromeos/dbus/session_manager_client.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromeos/dbus/session_manager_client.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromeos/dbus/session_manager_client.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/dbus/session_manager_client.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/task_scheduler/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chromeos/chromeos_paths.h"
#include "chromeos/cryptohome/cryptohome_parameters.h"
#include "chromeos/dbus/blocking_method_caller.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/login_manager/arc.pb.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "crypto/sha2.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_path.h"
#include "dbus/object_proxy.h"
#include "dbus/scoped_dbus_error.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace chromeos {
namespace {
using RetrievePolicyResponseType =
SessionManagerClient::RetrievePolicyResponseType;
constexpr char kStubPolicyFile[] = "stub_policy";
constexpr char kStubDevicePolicyFile[] = "stub_device_policy";
constexpr char kStubStateKeysFile[] = "stub_state_keys";
// Returns a location for |file| that is specific to the given |cryptohome_id|.
// These paths will be relative to DIR_USER_POLICY_KEYS, and can be used only
// to store stub files.
base::FilePath GetUserFilePath(const cryptohome::Identification& cryptohome_id,
const char* file) {
base::FilePath keys_path;
if (!PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &keys_path))
return base::FilePath();
const std::string sanitized =
CryptohomeClient::GetStubSanitizedUsername(cryptohome_id);
return keys_path.AppendASCII(sanitized).AppendASCII(file);
}
// Helper to asynchronously retrieve a file's content.
std::string GetFileContent(const base::FilePath& path) {
std::string result;
if (!path.empty())
base::ReadFileToString(path, &result);
return result;
}
// Helper to write a file in a background thread.
void StoreFile(const base::FilePath& path, const std::string& data) {
const int size = static_cast<int>(data.size());
if (path.empty() ||
!base::CreateDirectory(path.DirName()) ||
base::WriteFile(path, data.data(), size) != size) {
LOG(WARNING) << "Failed to write to " << path.value();
}
}
// Helper to asynchronously read (or if missing create) state key stubs.
std::vector<std::string> ReadCreateStateKeysStub(const base::FilePath& path) {
std::string contents;
if (base::PathExists(path)) {
contents = GetFileContent(path);
} else {
// Create stub state keys on the fly.
for (int i = 0; i < 5; ++i) {
contents += crypto::SHA256HashString(
base::IntToString(i) +
base::Int64ToString(base::Time::Now().ToJavaTime()));
}
StoreFile(path, contents);
}
std::vector<std::string> state_keys;
for (size_t i = 0; i < contents.size() / 32; ++i) {
state_keys.push_back(contents.substr(i * 32, 32));
}
return state_keys;
}
// Turn pass-by-value into pass-by-reference as expected by StateKeysCallback.
void RunStateKeysCallbackStub(SessionManagerClient::StateKeysCallback callback,
std::vector<std::string> state_keys) {
callback.Run(state_keys);
}
// Helper to notify the callback with SUCCESS, to be used by the stub.
void NotifyOnRetrievePolicySuccess(
const SessionManagerClient::RetrievePolicyCallback& callback,
const std::string& protobuf) {
callback.Run(protobuf, RetrievePolicyResponseType::SUCCESS);
}
// Helper to get the enum type of RetrievePolicyResponseType based on error
// name.
RetrievePolicyResponseType GetResponseTypeBasedOnError(
base::StringPiece error_name) {
if (error_name == login_manager::dbus_error::kNone) {
return RetrievePolicyResponseType::SUCCESS;
} else if (error_name == login_manager::dbus_error::kSessionDoesNotExist) {
return RetrievePolicyResponseType::SESSION_DOES_NOT_EXIST;
} else if (error_name == login_manager::dbus_error::kSigEncodeFail) {
return RetrievePolicyResponseType::POLICY_ENCODE_ERROR;
}
return RetrievePolicyResponseType::OTHER_ERROR;
}
// Logs UMA stat for retrieve policy request, corresponding to D-Bus method name
// used.
void LogPolicyResponseUma(base::StringPiece method_name,
RetrievePolicyResponseType response) {
if (method_name == login_manager::kSessionManagerRetrievePolicy) {
UMA_HISTOGRAM_ENUMERATION("Enterprise.RetrievePolicyResponse.Device",
response, RetrievePolicyResponseType::COUNT);
} else if (method_name ==
login_manager::kSessionManagerRetrieveDeviceLocalAccountPolicy) {
UMA_HISTOGRAM_ENUMERATION(
"Enterprise.RetrievePolicyResponse.DeviceLocalAccount", response,
RetrievePolicyResponseType::COUNT);
} else if (method_name ==
login_manager::kSessionManagerRetrievePolicyForUser) {
UMA_HISTOGRAM_ENUMERATION("Enterprise.RetrievePolicyResponse.User",
response, RetrievePolicyResponseType::COUNT);
} else if (method_name ==
login_manager::
kSessionManagerRetrievePolicyForUserWithoutSession) {
UMA_HISTOGRAM_ENUMERATION(
"Enterprise.RetrievePolicyResponse.UserDuringLogin", response,
RetrievePolicyResponseType::COUNT);
} else {
LOG(ERROR) << "Invalid method_name: " << method_name;
}
}
} // namespace
// The SessionManagerClient implementation used in production.
class SessionManagerClientImpl : public SessionManagerClient {
public:
SessionManagerClientImpl() : weak_ptr_factory_(this) {}
~SessionManagerClientImpl() override = default;
// SessionManagerClient overrides:
void SetStubDelegate(StubDelegate* delegate) override {
// Do nothing; this isn't a stub implementation.
}
void AddObserver(Observer* observer) override {
observers_.AddObserver(observer);
}
void RemoveObserver(Observer* observer) override {
observers_.RemoveObserver(observer);
}
bool HasObserver(const Observer* observer) const override {
return observers_.HasObserver(observer);
}
bool IsScreenLocked() const override { return screen_is_locked_; }
void EmitLoginPromptVisible() override {
SimpleMethodCallToSessionManager(
login_manager::kSessionManagerEmitLoginPromptVisible);
for (auto& observer : observers_)
observer.EmitLoginPromptVisibleCalled();
}
void RestartJob(int socket_fd,
const std::vector<std::string>& argv,
VoidDBusMethodCallback callback) override {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
login_manager::kSessionManagerRestartJob);
dbus::MessageWriter writer(&method_call);
writer.AppendFileDescriptor(socket_fd);
writer.AppendArrayOfStrings(argv);
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnRestartJob,
weak_ptr_factory_.GetWeakPtr(),
base::Passed(std::move(callback))));
}
void StartSession(const cryptohome::Identification& cryptohome_id) override {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
login_manager::kSessionManagerStartSession);
dbus::MessageWriter writer(&method_call);
writer.AppendString(cryptohome_id.id());
writer.AppendString(""); // Unique ID is deprecated
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
dbus::ObjectProxy::EmptyResponseCallback());
}
void StopSession() override {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
login_manager::kSessionManagerStopSession);
dbus::MessageWriter writer(&method_call);
writer.AppendString(""); // Unique ID is deprecated
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
dbus::ObjectProxy::EmptyResponseCallback());
}
void StartDeviceWipe() override {
SimpleMethodCallToSessionManager(
login_manager::kSessionManagerStartDeviceWipe);
}
void StartTPMFirmwareUpdate(const std::string& update_mode) override {
dbus::MethodCall method_call(
login_manager::kSessionManagerInterface,
login_manager::kSessionManagerStartTPMFirmwareUpdate);
dbus::MessageWriter writer(&method_call);
writer.AppendString(update_mode);
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
dbus::ObjectProxy::EmptyResponseCallback());
}
void RequestLockScreen() override {
SimpleMethodCallToSessionManager(login_manager::kSessionManagerLockScreen);
}
void NotifyLockScreenShown() override {
SimpleMethodCallToSessionManager(
login_manager::kSessionManagerHandleLockScreenShown);
}
void NotifyLockScreenDismissed() override {
SimpleMethodCallToSessionManager(
login_manager::kSessionManagerHandleLockScreenDismissed);
}
void NotifySupervisedUserCreationStarted() override {
SimpleMethodCallToSessionManager(
login_manager::kSessionManagerHandleSupervisedUserCreationStarting);
}
void NotifySupervisedUserCreationFinished() override {
SimpleMethodCallToSessionManager(
login_manager::kSessionManagerHandleSupervisedUserCreationFinished);
}
void RetrieveActiveSessions(const ActiveSessionsCallback& callback) override {
dbus::MethodCall method_call(
login_manager::kSessionManagerInterface,
login_manager::kSessionManagerRetrieveActiveSessions);
session_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnRetrieveActiveSessions,
weak_ptr_factory_.GetWeakPtr(),
login_manager::kSessionManagerRetrieveActiveSessions,
callback));
}
void RetrieveDevicePolicy(const RetrievePolicyCallback& callback) override {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
login_manager::kSessionManagerRetrievePolicy);
session_manager_proxy_->CallMethodWithErrorCallback(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnRetrievePolicySuccess,
weak_ptr_factory_.GetWeakPtr(),
login_manager::kSessionManagerRetrievePolicy, callback),
base::Bind(&SessionManagerClientImpl::OnRetrievePolicyError,
weak_ptr_factory_.GetWeakPtr(),
login_manager::kSessionManagerRetrievePolicy, callback));
}
RetrievePolicyResponseType BlockingRetrieveDevicePolicy(
std::string* policy_out) override {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
login_manager::kSessionManagerRetrievePolicy);
dbus::ScopedDBusError error;
std::unique_ptr<dbus::Response> response =
blocking_method_caller_->CallMethodAndBlockWithError(&method_call,
&error);
RetrievePolicyResponseType result = RetrievePolicyResponseType::SUCCESS;
if (error.is_set() && error.name()) {
result = GetResponseTypeBasedOnError(error.name());
}
if (result == RetrievePolicyResponseType::SUCCESS) {
ExtractString(login_manager::kSessionManagerRetrievePolicy,
response.get(), policy_out);
} else {
*policy_out = "";
}
LogPolicyResponseUma(login_manager::kSessionManagerRetrievePolicy, result);
return result;
}
void RetrievePolicyForUser(const cryptohome::Identification& cryptohome_id,
const RetrievePolicyCallback& callback) override {
CallRetrievePolicyByUsername(
login_manager::kSessionManagerRetrievePolicyForUser, cryptohome_id.id(),
callback);
}
RetrievePolicyResponseType BlockingRetrievePolicyForUser(
const cryptohome::Identification& cryptohome_id,
std::string* policy_out) override {
return BlockingRetrievePolicyByUsername(
login_manager::kSessionManagerRetrievePolicyForUser, cryptohome_id.id(),
policy_out);
}
void RetrievePolicyForUserWithoutSession(
const cryptohome::Identification& cryptohome_id,
const RetrievePolicyCallback& callback) override {
const std::string method_name =
login_manager::kSessionManagerRetrievePolicyForUserWithoutSession;
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
method_name);
dbus::MessageWriter writer(&method_call);
writer.AppendString(cryptohome_id.id());
session_manager_proxy_->CallMethodWithErrorCallback(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnRetrievePolicySuccess,
weak_ptr_factory_.GetWeakPtr(), method_name, callback),
base::Bind(&SessionManagerClientImpl::OnRetrievePolicyError,
weak_ptr_factory_.GetWeakPtr(), method_name, callback));
}
void RetrieveDeviceLocalAccountPolicy(
const std::string& account_name,
const RetrievePolicyCallback& callback) override {
CallRetrievePolicyByUsername(
login_manager::kSessionManagerRetrieveDeviceLocalAccountPolicy,
account_name, callback);
}
RetrievePolicyResponseType BlockingRetrieveDeviceLocalAccountPolicy(
const std::string& account_name,
std::string* policy_out) override {
return BlockingRetrievePolicyByUsername(
login_manager::kSessionManagerRetrieveDeviceLocalAccountPolicy,
account_name, policy_out);
}
void StoreDevicePolicy(const std::string& policy_blob,
const StorePolicyCallback& callback) override {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
login_manager::kSessionManagerStorePolicy);
dbus::MessageWriter writer(&method_call);
// static_cast does not work due to signedness.
writer.AppendArrayOfBytes(
reinterpret_cast<const uint8_t*>(policy_blob.data()),
policy_blob.size());
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnNoOutputParamResponse,
weak_ptr_factory_.GetWeakPtr(), callback));
}
void StorePolicyForUser(const cryptohome::Identification& cryptohome_id,
const std::string& policy_blob,
const StorePolicyCallback& callback) override {
CallStorePolicyByUsername(login_manager::kSessionManagerStorePolicyForUser,
cryptohome_id.id(), policy_blob, callback);
}
void StoreDeviceLocalAccountPolicy(
const std::string& account_name,
const std::string& policy_blob,
const StorePolicyCallback& callback) override {
CallStorePolicyByUsername(
login_manager::kSessionManagerStoreDeviceLocalAccountPolicy,
account_name,
policy_blob,
callback);
}
bool SupportsRestartToApplyUserFlags() const override { return true; }
void SetFlagsForUser(const cryptohome::Identification& cryptohome_id,
const std::vector<std::string>& flags) override {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
login_manager::kSessionManagerSetFlagsForUser);
dbus::MessageWriter writer(&method_call);
writer.AppendString(cryptohome_id.id());
writer.AppendArrayOfStrings(flags);
session_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
dbus::ObjectProxy::EmptyResponseCallback());
}
void GetServerBackedStateKeys(const StateKeysCallback& callback) override {
dbus::MethodCall method_call(
login_manager::kSessionManagerInterface,
login_manager::kSessionManagerGetServerBackedStateKeys);
// Infinite timeout needed because the state keys are not generated as long
// as the time sync hasn't been done (which requires network).
// TODO(igorcov): Since this is a resource allocated that could last a long
// time, we will need to change the behavior to either listen to
// LastSyncInfo event from tlsdated or communicate through signals with
// session manager in this particular flow.
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_INFINITE,
base::Bind(&SessionManagerClientImpl::OnGetServerBackedStateKeys,
weak_ptr_factory_.GetWeakPtr(), callback));
}
void CheckArcAvailability(const ArcCallback& callback) override {
dbus::MethodCall method_call(
login_manager::kSessionManagerInterface,
login_manager::kSessionManagerCheckArcAvailability);
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnCheckArcAvailability,
weak_ptr_factory_.GetWeakPtr(), callback));
}
void StartArcInstance(ArcStartupMode startup_mode,
const cryptohome::Identification& cryptohome_id,
bool skip_boot_completed_broadcast,
bool scan_vendor_priv_app,
const StartArcInstanceCallback& callback) override {
dbus::MethodCall method_call(
login_manager::kSessionManagerInterface,
login_manager::kSessionManagerStartArcInstance);
dbus::MessageWriter writer(&method_call);
login_manager::StartArcInstanceRequest request;
switch (startup_mode) {
case ArcStartupMode::FULL:
request.set_account_id(cryptohome_id.id());
request.set_skip_boot_completed_broadcast(
skip_boot_completed_broadcast);
request.set_scan_vendor_priv_app(scan_vendor_priv_app);
break;
case ArcStartupMode::LOGIN_SCREEN:
request.set_for_login_screen(true);
break;
}
writer.AppendProtoAsArrayOfBytes(request);
session_manager_proxy_->CallMethodWithErrorCallback(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnStartArcInstanceSucceeded,
weak_ptr_factory_.GetWeakPtr(), callback),
base::Bind(&SessionManagerClientImpl::OnStartArcInstanceFailed,
weak_ptr_factory_.GetWeakPtr(), callback));
}
void StopArcInstance(const ArcCallback& callback) override {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
login_manager::kSessionManagerStopArcInstance);
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnNoOutputParamResponse,
weak_ptr_factory_.GetWeakPtr(), callback));
}
void SetArcCpuRestriction(
login_manager::ContainerCpuRestrictionState restriction_state,
const ArcCallback& callback) override {
dbus::MethodCall method_call(
login_manager::kSessionManagerInterface,
login_manager::kSessionManagerSetArcCpuRestriction);
dbus::MessageWriter writer(&method_call);
writer.AppendUint32(restriction_state);
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnNoOutputParamResponse,
weak_ptr_factory_.GetWeakPtr(), callback));
}
void EmitArcBooted(const cryptohome::Identification& cryptohome_id,
const ArcCallback& callback) override {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
login_manager::kSessionManagerEmitArcBooted);
dbus::MessageWriter writer(&method_call);
writer.AppendString(cryptohome_id.id());
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnNoOutputParamResponse,
weak_ptr_factory_.GetWeakPtr(), callback));
}
void GetArcStartTime(const GetArcStartTimeCallback& callback) override {
dbus::MethodCall method_call(
login_manager::kSessionManagerInterface,
login_manager::kSessionManagerGetArcStartTimeTicks);
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnGetArcStartTime,
weak_ptr_factory_.GetWeakPtr(), callback));
}
void RemoveArcData(const cryptohome::Identification& cryptohome_id,
const ArcCallback& callback) override {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
login_manager::kSessionManagerRemoveArcData);
dbus::MessageWriter writer(&method_call);
writer.AppendString(cryptohome_id.id());
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnNoOutputParamResponse,
weak_ptr_factory_.GetWeakPtr(), callback));
}
protected:
void Init(dbus::Bus* bus) override {
session_manager_proxy_ = bus->GetObjectProxy(
login_manager::kSessionManagerServiceName,
dbus::ObjectPath(login_manager::kSessionManagerServicePath));
blocking_method_caller_.reset(
new BlockingMethodCaller(bus, session_manager_proxy_));
// Signals emitted on the session manager's interface.
session_manager_proxy_->ConnectToSignal(
login_manager::kSessionManagerInterface,
login_manager::kOwnerKeySetSignal,
base::Bind(&SessionManagerClientImpl::OwnerKeySetReceived,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&SessionManagerClientImpl::SignalConnected,
weak_ptr_factory_.GetWeakPtr()));
session_manager_proxy_->ConnectToSignal(
login_manager::kSessionManagerInterface,
login_manager::kPropertyChangeCompleteSignal,
base::Bind(&SessionManagerClientImpl::PropertyChangeCompleteReceived,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&SessionManagerClientImpl::SignalConnected,
weak_ptr_factory_.GetWeakPtr()));
session_manager_proxy_->ConnectToSignal(
login_manager::kSessionManagerInterface,
login_manager::kScreenIsLockedSignal,
base::Bind(&SessionManagerClientImpl::ScreenIsLockedReceived,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&SessionManagerClientImpl::SignalConnected,
weak_ptr_factory_.GetWeakPtr()));
session_manager_proxy_->ConnectToSignal(
login_manager::kSessionManagerInterface,
login_manager::kScreenIsUnlockedSignal,
base::Bind(&SessionManagerClientImpl::ScreenIsUnlockedReceived,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&SessionManagerClientImpl::SignalConnected,
weak_ptr_factory_.GetWeakPtr()));
session_manager_proxy_->ConnectToSignal(
login_manager::kSessionManagerInterface,
login_manager::kArcInstanceStopped,
base::Bind(&SessionManagerClientImpl::ArcInstanceStoppedReceived,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&SessionManagerClientImpl::SignalConnected,
weak_ptr_factory_.GetWeakPtr()));
}
private:
// Makes a method call to the session manager with no arguments and no
// response.
void SimpleMethodCallToSessionManager(const std::string& method_name) {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
method_name);
session_manager_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
dbus::ObjectProxy::EmptyResponseCallback());
}
// Calls given callback (if non-null), with the |success| boolean
// representing the dbus call was successful or not.
void OnNoOutputParamResponse(
const base::Callback<void(bool success)>& callback,
dbus::Response* response) {
if (!callback.is_null())
callback.Run(response != nullptr);
}
// Helper for RetrieveDeviceLocalAccountPolicy and RetrievePolicyForUser.
void CallRetrievePolicyByUsername(const std::string& method_name,
const std::string& account_id,
const RetrievePolicyCallback& callback) {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
method_name);
dbus::MessageWriter writer(&method_call);
writer.AppendString(account_id);
session_manager_proxy_->CallMethodWithErrorCallback(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnRetrievePolicySuccess,
weak_ptr_factory_.GetWeakPtr(), method_name, callback),
base::Bind(&SessionManagerClientImpl::OnRetrievePolicyError,
weak_ptr_factory_.GetWeakPtr(), method_name, callback));
}
// Helper for blocking RetrievePolicyForUser and
// RetrieveDeviceLocalAccountPolicy.
RetrievePolicyResponseType BlockingRetrievePolicyByUsername(
const std::string& method_name,
const std::string& account_name,
std::string* policy_out) {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
method_name);
dbus::MessageWriter writer(&method_call);
writer.AppendString(account_name);
dbus::ScopedDBusError error;
std::unique_ptr<dbus::Response> response =
blocking_method_caller_->CallMethodAndBlockWithError(&method_call,
&error);
RetrievePolicyResponseType result = RetrievePolicyResponseType::SUCCESS;
if (error.is_set() && error.name()) {
result = GetResponseTypeBasedOnError(error.name());
}
if (result == RetrievePolicyResponseType::SUCCESS) {
ExtractString(method_name, response.get(), policy_out);
} else {
*policy_out = "";
}
LogPolicyResponseUma(method_name, result);
return result;
}
void CallStorePolicyByUsername(const std::string& method_name,
const std::string& account_id,
const std::string& policy_blob,
const StorePolicyCallback& callback) {
dbus::MethodCall method_call(login_manager::kSessionManagerInterface,
method_name);
dbus::MessageWriter writer(&method_call);
writer.AppendString(account_id);
// static_cast does not work due to signedness.
writer.AppendArrayOfBytes(
reinterpret_cast<const uint8_t*>(policy_blob.data()),
policy_blob.size());
session_manager_proxy_->CallMethod(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::Bind(&SessionManagerClientImpl::OnNoOutputParamResponse,
weak_ptr_factory_.GetWeakPtr(), callback));
}
// Called when kSessionManagerRestartJob method is complete.
void OnRestartJob(VoidDBusMethodCallback callback, dbus::Response* response) {
LOG_IF(ERROR, !response)
<< "Failed to call "
<< login_manager::kSessionManagerRestartJob;
std::move(callback).Run(response ? DBUS_METHOD_CALL_SUCCESS
: DBUS_METHOD_CALL_FAILURE);
}
// Called when kSessionManagerRetrieveActiveSessions method is complete.
void OnRetrieveActiveSessions(const std::string& method_name,
const ActiveSessionsCallback& callback,
dbus::Response* response) {
ActiveSessionsMap sessions;
bool success = false;
if (!response) {
callback.Run(sessions, success);
return;
}
dbus::MessageReader reader(response);
dbus::MessageReader array_reader(nullptr);
if (!reader.PopArray(&array_reader)) {
LOG(ERROR) << method_name << " response is incorrect: "
<< response->ToString();
} else {
while (array_reader.HasMoreData()) {
dbus::MessageReader dict_entry_reader(nullptr);
std::string key;
std::string value;
if (!array_reader.PopDictEntry(&dict_entry_reader) ||
!dict_entry_reader.PopString(&key) ||
!dict_entry_reader.PopString(&value)) {
LOG(ERROR) << method_name << " response is incorrect: "
<< response->ToString();
} else {
sessions[cryptohome::Identification::FromString(key)] = value;
}
}
success = true;
}
callback.Run(sessions, success);
}
void ExtractString(const std::string& method_name,
dbus::Response* response,
std::string* extracted) {
if (!response) {
LOG(ERROR) << "Failed to call " << method_name;
return;
}
dbus::MessageReader reader(response);
const uint8_t* values = nullptr;
size_t length = 0;
if (!reader.PopArrayOfBytes(&values, &length)) {
LOG(ERROR) << "Invalid response: " << response->ToString();
return;
}
// static_cast does not work due to signedness.
extracted->assign(reinterpret_cast<const char*>(values), length);
}
// Called when kSessionManagerRetrievePolicy or
// kSessionManagerRetrievePolicyForUser method is successfully complete.
void OnRetrievePolicySuccess(const std::string& method_name,
const RetrievePolicyCallback& callback,
dbus::Response* response) {
std::string serialized_proto;
ExtractString(method_name, response, &serialized_proto);
callback.Run(serialized_proto, RetrievePolicyResponseType::SUCCESS);
LogPolicyResponseUma(method_name, RetrievePolicyResponseType::SUCCESS);
}
// Called when kSessionManagerRetrievePolicy or
// kSessionManagerRetrievePolicyForUser method fails.
void OnRetrievePolicyError(const std::string& method_name,
const RetrievePolicyCallback& callback,
dbus::ErrorResponse* response) {
RetrievePolicyResponseType response_type =
GetResponseTypeBasedOnError(response->GetErrorName());
callback.Run(std::string(), response_type);
LogPolicyResponseUma(method_name, response_type);
}
// Called when the owner key set signal is received.
void OwnerKeySetReceived(dbus::Signal* signal) {
dbus::MessageReader reader(signal);
std::string result_string;
if (!reader.PopString(&result_string)) {
LOG(ERROR) << "Invalid signal: " << signal->ToString();
return;
}
const bool success = base::StartsWith(result_string, "success",
base::CompareCase::INSENSITIVE_ASCII);
for (auto& observer : observers_)
observer.OwnerKeySet(success);
}
// Called when the property change complete signal is received.
void PropertyChangeCompleteReceived(dbus::Signal* signal) {
dbus::MessageReader reader(signal);
std::string result_string;
if (!reader.PopString(&result_string)) {
LOG(ERROR) << "Invalid signal: " << signal->ToString();
return;
}
const bool success = base::StartsWith(result_string, "success",
base::CompareCase::INSENSITIVE_ASCII);
for (auto& observer : observers_)
observer.PropertyChangeComplete(success);
}
void ScreenIsLockedReceived(dbus::Signal* signal) {
screen_is_locked_ = true;
for (auto& observer : observers_)
observer.ScreenIsLocked();
}
void ScreenIsUnlockedReceived(dbus::Signal* signal) {
screen_is_locked_ = false;
for (auto& observer : observers_)
observer.ScreenIsUnlocked();
}
void ArcInstanceStoppedReceived(dbus::Signal* signal) {
dbus::MessageReader reader(signal);
bool clean = false;
std::string container_instance_id;
if (!reader.PopBool(&clean) || !reader.PopString(&container_instance_id)) {
LOG(ERROR) << "Invalid signal: " << signal->ToString();
return;
}
for (auto& observer : observers_)
observer.ArcInstanceStopped(clean, container_instance_id);
}
// Called when the object is connected to the signal.
void SignalConnected(const std::string& interface_name,
const std::string& signal_name,
bool success) {
LOG_IF(ERROR, !success) << "Failed to connect to " << signal_name;
}
// Called when kSessionManagerGetServerBackedStateKeys method is complete.
void OnGetServerBackedStateKeys(const StateKeysCallback& callback,
dbus::Response* response) {
std::vector<std::string> state_keys;
if (response) {
dbus::MessageReader reader(response);
dbus::MessageReader array_reader(nullptr);
if (!reader.PopArray(&array_reader)) {
LOG(ERROR) << "Bad response: " << response->ToString();
} else {
while (array_reader.HasMoreData()) {
const uint8_t* data = nullptr;
size_t size = 0;
if (!array_reader.PopArrayOfBytes(&data, &size)) {
LOG(ERROR) << "Bad response: " << response->ToString();
state_keys.clear();
break;
}
state_keys.emplace_back(reinterpret_cast<const char*>(data), size);
}
}
}
if (!callback.is_null())
callback.Run(state_keys);
}
// Called when kSessionManagerCheckArcAvailability method is complete.
void OnCheckArcAvailability(const ArcCallback& callback,
dbus::Response* response) {
bool available = false;
if (response) {
dbus::MessageReader reader(response);
if (!reader.PopBool(&available))
LOG(ERROR) << "Invalid response: " << response->ToString();
}
if (!callback.is_null())
callback.Run(available);
}
void OnGetArcStartTime(const GetArcStartTimeCallback& callback,
dbus::Response* response) {
bool success = false;
base::TimeTicks arc_start_time;
if (response) {
dbus::MessageReader reader(response);
int64_t ticks = 0;
if (reader.PopInt64(&ticks)) {
success = true;
arc_start_time = base::TimeTicks::FromInternalValue(ticks);
} else {
LOG(ERROR) << "Invalid response: " << response->ToString();
}
}
callback.Run(success, arc_start_time);
}
void OnStartArcInstanceSucceeded(const StartArcInstanceCallback& callback,
dbus::Response* response) {
DCHECK(response);
dbus::MessageReader reader(response);
std::string container_instance_id;
if (!reader.PopString(&container_instance_id)) {
LOG(ERROR) << "Invalid response: " << response->ToString();
if (!callback.is_null())
callback.Run(StartArcInstanceResult::UNKNOWN_ERROR, std::string());
return;
}
if (!callback.is_null())
callback.Run(StartArcInstanceResult::SUCCESS, container_instance_id);
}
void OnStartArcInstanceFailed(const StartArcInstanceCallback& callback,
dbus::ErrorResponse* response) {
LOG(ERROR) << "Failed to call StartArcInstance: "
<< (response ? response->ToString() : "(null)");
if (!callback.is_null()) {
callback.Run(response && response->GetErrorName() ==
login_manager::dbus_error::kLowFreeDisk
? StartArcInstanceResult::LOW_FREE_DISK_SPACE
: StartArcInstanceResult::UNKNOWN_ERROR,
std::string());
}
}
dbus::ObjectProxy* session_manager_proxy_ = nullptr;
std::unique_ptr<BlockingMethodCaller> blocking_method_caller_;
base::ObserverList<Observer> observers_;
// Most recent screen-lock state received from session_manager.
bool screen_is_locked_ = false;
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<SessionManagerClientImpl> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(SessionManagerClientImpl);
};
// The SessionManagerClient implementation used on Linux desktop,
// which does nothing.
class SessionManagerClientStubImpl : public SessionManagerClient {
public:
SessionManagerClientStubImpl() = default;
~SessionManagerClientStubImpl() override = default;
// SessionManagerClient overrides
void Init(dbus::Bus* bus) override {}
void SetStubDelegate(StubDelegate* delegate) override {
delegate_ = delegate;
}
void AddObserver(Observer* observer) override {
observers_.AddObserver(observer);
}
void RemoveObserver(Observer* observer) override {
observers_.RemoveObserver(observer);
}
bool HasObserver(const Observer* observer) const override {
return observers_.HasObserver(observer);
}
bool IsScreenLocked() const override { return screen_is_locked_; }
void EmitLoginPromptVisible() override {}
void RestartJob(int socket_fd,
const std::vector<std::string>& argv,
VoidDBusMethodCallback callback) override {}
void StartSession(const cryptohome::Identification& cryptohome_id) override {}
void StopSession() override {}
void NotifySupervisedUserCreationStarted() override {}
void NotifySupervisedUserCreationFinished() override {}
void StartDeviceWipe() override {}
void StartTPMFirmwareUpdate(const std::string& update_mode) override {}
void RequestLockScreen() override {
if (delegate_)
delegate_->LockScreenForStub();
}
void NotifyLockScreenShown() override {
screen_is_locked_ = true;
for (auto& observer : observers_)
observer.ScreenIsLocked();
}
void NotifyLockScreenDismissed() override {
screen_is_locked_ = false;
for (auto& observer : observers_)
observer.ScreenIsUnlocked();
}
void RetrieveActiveSessions(const ActiveSessionsCallback& callback) override {
}
void RetrieveDevicePolicy(const RetrievePolicyCallback& callback) override {
base::FilePath owner_key_path;
if (!PathService::Get(chromeos::FILE_OWNER_KEY, &owner_key_path)) {
callback.Run("", RetrievePolicyResponseType::SUCCESS);
return;
}
base::FilePath device_policy_path =
owner_key_path.DirName().AppendASCII(kStubDevicePolicyFile);
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE,
{base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
base::Bind(&GetFileContent, device_policy_path),
base::Bind(&NotifyOnRetrievePolicySuccess, callback));
}
RetrievePolicyResponseType BlockingRetrieveDevicePolicy(
std::string* policy_out) override {
base::FilePath owner_key_path;
if (!PathService::Get(chromeos::FILE_OWNER_KEY, &owner_key_path)) {
*policy_out = "";
return RetrievePolicyResponseType::SUCCESS;
}
base::FilePath device_policy_path =
owner_key_path.DirName().AppendASCII(kStubDevicePolicyFile);
*policy_out = GetFileContent(device_policy_path);
return RetrievePolicyResponseType::SUCCESS;
}
void RetrievePolicyForUser(const cryptohome::Identification& cryptohome_id,
const RetrievePolicyCallback& callback) override {
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE,
{base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
base::Bind(&GetFileContent,
GetUserFilePath(cryptohome_id, kStubPolicyFile)),
base::Bind(&NotifyOnRetrievePolicySuccess, callback));
}
RetrievePolicyResponseType BlockingRetrievePolicyForUser(
const cryptohome::Identification& cryptohome_id,
std::string* policy_out) override {
*policy_out =
GetFileContent(GetUserFilePath(cryptohome_id, kStubPolicyFile));
return RetrievePolicyResponseType::SUCCESS;
}
void RetrievePolicyForUserWithoutSession(
const cryptohome::Identification& cryptohome_id,
const RetrievePolicyCallback& callback) override {
RetrievePolicyForUser(cryptohome_id, callback);
}
void RetrieveDeviceLocalAccountPolicy(
const std::string& account_id,
const RetrievePolicyCallback& callback) override {
RetrievePolicyForUser(cryptohome::Identification::FromString(account_id),
callback);
}
RetrievePolicyResponseType BlockingRetrieveDeviceLocalAccountPolicy(
const std::string& account_id,
std::string* policy_out) override {
return BlockingRetrievePolicyForUser(
cryptohome::Identification::FromString(account_id), policy_out);
}
void StoreDevicePolicy(const std::string& policy_blob,
const StorePolicyCallback& callback) override {
enterprise_management::PolicyFetchResponse response;
base::FilePath owner_key_path;
if (!response.ParseFromString(policy_blob) ||
!PathService::Get(chromeos::FILE_OWNER_KEY, &owner_key_path)) {
callback.Run(false);
return;
}
if (response.has_new_public_key()) {
base::PostTaskWithTraits(
FROM_HERE,
{base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
base::Bind(&StoreFile, owner_key_path, response.new_public_key()));
}
// Chrome will attempt to retrieve the device policy right after storing
// during enrollment, so make sure it's written before signaling
// completion.
// Note also that the owner key will be written before the device policy,
// if it was present in the blob.
base::FilePath device_policy_path =
owner_key_path.DirName().AppendASCII(kStubDevicePolicyFile);
base::PostTaskWithTraitsAndReply(
FROM_HERE,
{base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
base::Bind(&StoreFile, device_policy_path, policy_blob),
base::Bind(callback, true));
}
void StorePolicyForUser(const cryptohome::Identification& cryptohome_id,
const std::string& policy_blob,
const StorePolicyCallback& callback) override {
// The session manager writes the user policy key to a well-known
// location. Do the same with the stub impl, so that user policy works and
// can be tested on desktop builds.
enterprise_management::PolicyFetchResponse response;
if (!response.ParseFromString(policy_blob)) {
callback.Run(false);
return;
}
if (response.has_new_public_key()) {
base::FilePath key_path = GetUserFilePath(cryptohome_id, "policy.pub");
base::PostTaskWithTraits(
FROM_HERE,
{base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
base::Bind(&StoreFile, key_path, response.new_public_key()));
}
// This file isn't read directly by Chrome, but is used by this class to
// reload the user policy across restarts.
base::FilePath stub_policy_path =
GetUserFilePath(cryptohome_id, kStubPolicyFile);
base::PostTaskWithTraitsAndReply(
FROM_HERE,
{base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
base::Bind(&StoreFile, stub_policy_path, policy_blob),
base::Bind(callback, true));
}
void StoreDeviceLocalAccountPolicy(
const std::string& account_id,
const std::string& policy_blob,
const StorePolicyCallback& callback) override {
StorePolicyForUser(cryptohome::Identification::FromString(account_id),
policy_blob, callback);
}
bool SupportsRestartToApplyUserFlags() const override { return false; }
void SetFlagsForUser(const cryptohome::Identification& cryptohome_id,
const std::vector<std::string>& flags) override {}
void GetServerBackedStateKeys(const StateKeysCallback& callback) override {
base::FilePath owner_key_path;
CHECK(PathService::Get(chromeos::FILE_OWNER_KEY, &owner_key_path));
const base::FilePath state_keys_path =
owner_key_path.DirName().AppendASCII(kStubStateKeysFile);
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE,
{base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
base::Bind(&ReadCreateStateKeysStub, state_keys_path),
base::Bind(&RunStateKeysCallbackStub, callback));
}
void CheckArcAvailability(const ArcCallback& callback) override {
callback.Run(false);
}
void StartArcInstance(ArcStartupMode startup_mode,
const cryptohome::Identification& cryptohome_id,
bool disable_boot_completed_broadcast,
bool enable_vendor_privileged,
const StartArcInstanceCallback& callback) override {
callback.Run(StartArcInstanceResult::UNKNOWN_ERROR, std::string());
}
void SetArcCpuRestriction(
login_manager::ContainerCpuRestrictionState restriction_state,
const ArcCallback& callback) override {
callback.Run(false);
}
void EmitArcBooted(const cryptohome::Identification& cryptohome_id,
const ArcCallback& callback) override {
callback.Run(false);
}
void StopArcInstance(const ArcCallback& callback) override {
callback.Run(false);
}
void GetArcStartTime(const GetArcStartTimeCallback& callback) override {
callback.Run(false, base::TimeTicks::Now());
}
void RemoveArcData(const cryptohome::Identification& cryptohome_id,
const ArcCallback& callback) override {
if (callback.is_null())
return;
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
base::Bind(callback, false));
}
private:
StubDelegate* delegate_ = nullptr; // Weak pointer; may be nullptr.
base::ObserverList<Observer> observers_;
std::string device_policy_;
bool screen_is_locked_ = false;
DISALLOW_COPY_AND_ASSIGN(SessionManagerClientStubImpl);
};
SessionManagerClient::SessionManagerClient() {
}
SessionManagerClient::~SessionManagerClient() {
}
SessionManagerClient* SessionManagerClient::Create(
DBusClientImplementationType type) {
if (type == REAL_DBUS_CLIENT_IMPLEMENTATION)
return new SessionManagerClientImpl();
DCHECK_EQ(FAKE_DBUS_CLIENT_IMPLEMENTATION, type);
return new SessionManagerClientStubImpl();
}
} // namespace chromeos
| 40.765921 | 80 | 0.696707 | [
"object",
"vector"
] |
01d2c696023a22b2d19e3d4c179327a6f65ef54e | 373 | hpp | C++ | corex/src/corex/core/components/RenderLineSegments.hpp | seanballais/gwo-visualization | 470561c603236d6a858b78a8585fd0bae71612a5 | [
"MIT"
] | null | null | null | corex/src/corex/core/components/RenderLineSegments.hpp | seanballais/gwo-visualization | 470561c603236d6a858b78a8585fd0bae71612a5 | [
"MIT"
] | null | null | null | corex/src/corex/core/components/RenderLineSegments.hpp | seanballais/gwo-visualization | 470561c603236d6a858b78a8585fd0bae71612a5 | [
"MIT"
] | null | null | null | #ifndef COREX_CORE_COMPONENTS_RENDER_LINE_SEGMENTS_HPP
#define COREX_CORE_COMPONENTS_RENDER_LINE_SEGMENTS_HPP
#include <EASTL/vector.h>
#include <SDL2/SDL.h>
#include <corex/core/ds/Point.hpp>
namespace corex::core
{
struct RenderLineSegments
{
eastl::vector<Point> vertices;
SDL_Color colour;
};
}
namespace cx
{
using namespace corex::core;
}
#endif
| 15.541667 | 54 | 0.761394 | [
"vector"
] |
01d73250523a57e3cb41ae39213d215014a370ad | 35,187 | cpp | C++ | Tests/GPUTestFramework/src/GPUTestingEnvironment.cpp | AnomalousMedical/DiligentCore | 5751cdba04373ced8c49ef40ce6a9dffb41a141e | [
"Apache-2.0"
] | null | null | null | Tests/GPUTestFramework/src/GPUTestingEnvironment.cpp | AnomalousMedical/DiligentCore | 5751cdba04373ced8c49ef40ce6a9dffb41a141e | [
"Apache-2.0"
] | null | null | null | Tests/GPUTestFramework/src/GPUTestingEnvironment.cpp | AnomalousMedical/DiligentCore | 5751cdba04373ced8c49ef40ce6a9dffb41a141e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-2022 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <atomic>
#include "GPUTestingEnvironment.hpp"
#include "PlatformDebug.hpp"
#include "TestingSwapChainBase.hpp"
#include "StringTools.hpp"
#include "GraphicsAccessories.hpp"
#if D3D11_SUPPORTED
# include "EngineFactoryD3D11.h"
#endif
#if D3D12_SUPPORTED
# include "EngineFactoryD3D12.h"
#endif
#if GL_SUPPORTED || GLES_SUPPORTED
# include "EngineFactoryOpenGL.h"
#endif
#if VULKAN_SUPPORTED
# include "EngineFactoryVk.h"
#endif
#if METAL_SUPPORTED
# include "EngineFactoryMtl.h"
#endif
#if ARCHIVER_SUPPORTED
# include "ArchiverFactoryLoader.h"
#endif
namespace Diligent
{
namespace Testing
{
#if D3D11_SUPPORTED
GPUTestingEnvironment* CreateTestingEnvironmentD3D11(const GPUTestingEnvironment::CreateInfo& CI, const SwapChainDesc& SCDesc);
#endif
#if D3D12_SUPPORTED
GPUTestingEnvironment* CreateTestingEnvironmentD3D12(const GPUTestingEnvironment::CreateInfo& CI, const SwapChainDesc& SCDesc);
#endif
#if GL_SUPPORTED || GLES_SUPPORTED
GPUTestingEnvironment* CreateTestingEnvironmentGL(const GPUTestingEnvironment::CreateInfo& CI, const SwapChainDesc& SCDesc);
#endif
#if VULKAN_SUPPORTED
GPUTestingEnvironment* CreateTestingEnvironmentVk(const GPUTestingEnvironment::CreateInfo& CI, const SwapChainDesc& SCDesc);
#endif
#if METAL_SUPPORTED
GPUTestingEnvironment* CreateTestingEnvironmentMtl(const GPUTestingEnvironment::CreateInfo& CI, const SwapChainDesc& SCDesc);
#endif
Uint32 GPUTestingEnvironment::FindAdapter(const std::vector<GraphicsAdapterInfo>& Adapters,
ADAPTER_TYPE AdapterType,
Uint32 AdapterId)
{
if (AdapterId != DEFAULT_ADAPTER_ID && AdapterId >= Adapters.size())
{
LOG_ERROR_MESSAGE("Adapter ID (", AdapterId, ") is invalid. Only ", Adapters.size(), " adapter(s) found on the system");
AdapterId = DEFAULT_ADAPTER_ID;
}
if (AdapterId == DEFAULT_ADAPTER_ID && AdapterType != ADAPTER_TYPE_UNKNOWN)
{
for (Uint32 i = 0; i < Adapters.size(); ++i)
{
if (Adapters[i].Type == AdapterType)
{
AdapterId = i;
m_AdapterType = AdapterType;
break;
}
}
if (AdapterId == DEFAULT_ADAPTER_ID)
LOG_WARNING_MESSAGE("Unable to find the requested adapter type. Using default adapter.");
}
if (AdapterId != DEFAULT_ADAPTER_ID)
LOG_INFO_MESSAGE("Using adapter ", AdapterId, ": '", Adapters[AdapterId].Description, "'");
return AdapterId;
}
GPUTestingEnvironment::GPUTestingEnvironment(const CreateInfo& CI, const SwapChainDesc& SCDesc) :
m_DeviceType{CI.deviceType}
{
Uint32 NumDeferredCtx = 0;
std::vector<IDeviceContext*> ppContexts;
std::vector<GraphicsAdapterInfo> Adapters;
std::vector<ImmediateContextCreateInfo> ContextCI;
auto EnumerateAdapters = [&Adapters](IEngineFactory* pFactory, Version MinVersion) //
{
Uint32 NumAdapters = 0;
pFactory->EnumerateAdapters(MinVersion, NumAdapters, 0);
if (NumAdapters > 0)
{
Adapters.resize(NumAdapters);
pFactory->EnumerateAdapters(MinVersion, NumAdapters, Adapters.data());
// Validate adapter info
for (auto& Adapter : Adapters)
{
VERIFY_EXPR(Adapter.NumQueues >= 1);
}
}
};
auto AddContext = [&ContextCI, &Adapters](COMMAND_QUEUE_TYPE Type, const char* Name, Uint32 AdapterId) //
{
if (AdapterId >= Adapters.size())
AdapterId = 0;
constexpr auto QueueMask = COMMAND_QUEUE_TYPE_PRIMARY_MASK;
auto* Queues = Adapters[AdapterId].Queues;
for (Uint32 q = 0, Count = Adapters[AdapterId].NumQueues; q < Count; ++q)
{
auto& CurQueue = Queues[q];
if (CurQueue.MaxDeviceContexts == 0)
continue;
if ((CurQueue.QueueType & QueueMask) == Type)
{
CurQueue.MaxDeviceContexts -= 1;
ImmediateContextCreateInfo Ctx{};
Ctx.QueueId = static_cast<Uint8>(q);
Ctx.Name = Name;
Ctx.Priority = QUEUE_PRIORITY_MEDIUM;
ContextCI.push_back(Ctx);
return;
}
}
};
#if D3D11_SUPPORTED || D3D12_SUPPORTED
auto PrintAdapterInfo = [](Uint32 AdapterId, const GraphicsAdapterInfo& AdapterInfo, const std::vector<DisplayModeAttribs>& DisplayModes) //
{
const char* AdapterTypeStr = nullptr;
switch (AdapterInfo.Type)
{
case ADAPTER_TYPE_DISCRETE:
case ADAPTER_TYPE_INTEGRATED: AdapterTypeStr = "HW"; break;
case ADAPTER_TYPE_SOFTWARE: AdapterTypeStr = "SW"; break;
default: AdapterTypeStr = "Type unknown";
}
LOG_INFO_MESSAGE("Adapter ", AdapterId, ": '", AdapterInfo.Description, "' (",
AdapterTypeStr, ", ", AdapterInfo.Memory.LocalMemory / (1 << 20), " MB); ",
DisplayModes.size(), (DisplayModes.size() == 1 ? " display mode" : " display modes"));
};
#endif
{
bool FeaturesPrinted = false;
DeviceFeatures::Enumerate(CI.Features,
[&FeaturesPrinted](const char* FeatName, DEVICE_FEATURE_STATE State) //
{
if (State != DEVICE_FEATURE_STATE_OPTIONAL)
{
std::cout << "Features." << FeatName << " = " << (State == DEVICE_FEATURE_STATE_ENABLED ? "On" : "Off") << '\n';
FeaturesPrinted = true;
}
return true;
});
if (FeaturesPrinted)
std::cout << '\n';
}
switch (m_DeviceType)
{
#if D3D11_SUPPORTED
case RENDER_DEVICE_TYPE_D3D11:
{
# if ENGINE_DLL
// Load the dll and import GetEngineFactoryD3D11() function
auto GetEngineFactoryD3D11 = LoadGraphicsEngineD3D11();
if (GetEngineFactoryD3D11 == nullptr)
{
LOG_ERROR_AND_THROW("Failed to load the engine");
}
# endif
auto* pFactoryD3D11 = GetEngineFactoryD3D11();
pFactoryD3D11->SetMessageCallback(MessageCallback);
EngineD3D11CreateInfo CreateInfo;
CreateInfo.GraphicsAPIVersion = Version{11, 0};
CreateInfo.Features = CI.Features;
# ifdef DILIGENT_DEVELOPMENT
CreateInfo.SetValidationLevel(VALIDATION_LEVEL_2);
# endif
EnumerateAdapters(pFactoryD3D11, CreateInfo.GraphicsAPIVersion);
LOG_INFO_MESSAGE("Found ", Adapters.size(), " compatible adapters");
for (Uint32 i = 0; i < Adapters.size(); ++i)
{
const auto& AdapterInfo = Adapters[i];
std::vector<DisplayModeAttribs> DisplayModes;
if (AdapterInfo.NumOutputs > 0)
{
Uint32 NumDisplayModes = 0;
pFactoryD3D11->EnumerateDisplayModes(CreateInfo.GraphicsAPIVersion, i, 0, TEX_FORMAT_RGBA8_UNORM, NumDisplayModes, nullptr);
DisplayModes.resize(NumDisplayModes);
pFactoryD3D11->EnumerateDisplayModes(CreateInfo.GraphicsAPIVersion, i, 0, TEX_FORMAT_RGBA8_UNORM, NumDisplayModes, DisplayModes.data());
}
PrintAdapterInfo(i, AdapterInfo, DisplayModes);
}
CreateInfo.AdapterId = FindAdapter(Adapters, CI.AdapterType, CI.AdapterId);
NumDeferredCtx = CI.NumDeferredContexts;
CreateInfo.NumDeferredContexts = NumDeferredCtx;
ppContexts.resize(std::max(size_t{1}, ContextCI.size()) + NumDeferredCtx);
pFactoryD3D11->CreateDeviceAndContextsD3D11(CreateInfo, &m_pDevice, ppContexts.data());
}
break;
#endif
#if D3D12_SUPPORTED
case RENDER_DEVICE_TYPE_D3D12:
{
# if ENGINE_DLL
// Load the dll and import GetEngineFactoryD3D12() function
auto GetEngineFactoryD3D12 = LoadGraphicsEngineD3D12();
if (GetEngineFactoryD3D12 == nullptr)
{
LOG_ERROR_AND_THROW("Failed to load the engine");
}
# endif
auto* pFactoryD3D12 = GetEngineFactoryD3D12();
pFactoryD3D12->SetMessageCallback(MessageCallback);
if (!pFactoryD3D12->LoadD3D12())
{
LOG_ERROR_AND_THROW("Failed to load d3d12 dll");
}
EngineD3D12CreateInfo CreateInfo;
CreateInfo.GraphicsAPIVersion = Version{11, 0};
EnumerateAdapters(pFactoryD3D12, CreateInfo.GraphicsAPIVersion);
// Always enable validation
CreateInfo.SetValidationLevel(VALIDATION_LEVEL_1);
CreateInfo.Features = CI.Features;
LOG_INFO_MESSAGE("Found ", Adapters.size(), " compatible adapters");
for (Uint32 i = 0; i < Adapters.size(); ++i)
{
const auto& AdapterInfo = Adapters[i];
std::vector<DisplayModeAttribs> DisplayModes;
if (AdapterInfo.NumOutputs > 0)
{
Uint32 NumDisplayModes = 0;
pFactoryD3D12->EnumerateDisplayModes(CreateInfo.GraphicsAPIVersion, i, 0, TEX_FORMAT_RGBA8_UNORM, NumDisplayModes, nullptr);
DisplayModes.resize(NumDisplayModes);
pFactoryD3D12->EnumerateDisplayModes(CreateInfo.GraphicsAPIVersion, i, 0, TEX_FORMAT_RGBA8_UNORM, NumDisplayModes, DisplayModes.data());
}
PrintAdapterInfo(i, AdapterInfo, DisplayModes);
}
CreateInfo.AdapterId = FindAdapter(Adapters, CI.AdapterType, CI.AdapterId);
AddContext(COMMAND_QUEUE_TYPE_GRAPHICS, "Graphics", CI.AdapterId);
AddContext(COMMAND_QUEUE_TYPE_COMPUTE, "Compute", CI.AdapterId);
AddContext(COMMAND_QUEUE_TYPE_TRANSFER, "Transfer", CI.AdapterId);
AddContext(COMMAND_QUEUE_TYPE_GRAPHICS, "Graphics 2", CI.AdapterId);
CreateInfo.NumImmediateContexts = static_cast<Uint32>(ContextCI.size());
CreateInfo.pImmediateContextInfo = CreateInfo.NumImmediateContexts > 0 ? ContextCI.data() : nullptr;
//CreateInfo.EnableGPUBasedValidation = true;
CreateInfo.CPUDescriptorHeapAllocationSize[0] = 64; // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
CreateInfo.CPUDescriptorHeapAllocationSize[1] = 32; // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
CreateInfo.CPUDescriptorHeapAllocationSize[2] = 16; // D3D12_DESCRIPTOR_HEAP_TYPE_RTV
CreateInfo.CPUDescriptorHeapAllocationSize[3] = 16; // D3D12_DESCRIPTOR_HEAP_TYPE_DSV
CreateInfo.DynamicDescriptorAllocationChunkSize[0] = 8; // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
CreateInfo.DynamicDescriptorAllocationChunkSize[1] = 8; // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
NumDeferredCtx = CI.NumDeferredContexts;
CreateInfo.NumDeferredContexts = NumDeferredCtx;
ppContexts.resize(std::max(size_t{1}, ContextCI.size()) + NumDeferredCtx);
pFactoryD3D12->CreateDeviceAndContextsD3D12(CreateInfo, &m_pDevice, ppContexts.data());
}
break;
#endif
#if GL_SUPPORTED || GLES_SUPPORTED
case RENDER_DEVICE_TYPE_GL:
case RENDER_DEVICE_TYPE_GLES:
{
# if EXPLICITLY_LOAD_ENGINE_GL_DLL
// Declare function pointer
// Load the dll and import GetEngineFactoryOpenGL() function
auto GetEngineFactoryOpenGL = LoadGraphicsEngineOpenGL();
if (GetEngineFactoryOpenGL == nullptr)
{
LOG_ERROR_AND_THROW("Failed to load the engine");
}
# endif
auto* pFactoryOpenGL = GetEngineFactoryOpenGL();
pFactoryOpenGL->SetMessageCallback(MessageCallback);
EnumerateAdapters(pFactoryOpenGL, Version{});
auto Window = CreateNativeWindow();
EngineGLCreateInfo CreateInfo;
// Always enable validation
CreateInfo.SetValidationLevel(VALIDATION_LEVEL_1);
CreateInfo.Window = Window;
CreateInfo.Features = CI.Features;
NumDeferredCtx = 0;
ppContexts.resize(std::max(size_t{1}, ContextCI.size()) + NumDeferredCtx);
RefCntAutoPtr<ISwapChain> pSwapChain; // We will use testing swap chain instead
pFactoryOpenGL->CreateDeviceAndSwapChainGL(
CreateInfo, &m_pDevice, ppContexts.data(), SCDesc, &pSwapChain);
}
break;
#endif
#if VULKAN_SUPPORTED
case RENDER_DEVICE_TYPE_VULKAN:
{
# if EXPLICITLY_LOAD_ENGINE_VK_DLL
// Load the dll and import GetEngineFactoryVk() function
auto GetEngineFactoryVk = LoadGraphicsEngineVk();
if (GetEngineFactoryVk == nullptr)
{
LOG_ERROR_AND_THROW("Failed to load the engine");
}
# endif
auto* pFactoryVk = GetEngineFactoryVk();
pFactoryVk->SetMessageCallback(MessageCallback);
if (CI.EnableDeviceSimulation)
pFactoryVk->EnableDeviceSimulation();
EnumerateAdapters(pFactoryVk, Version{});
AddContext(COMMAND_QUEUE_TYPE_GRAPHICS, "Graphics", CI.AdapterId);
AddContext(COMMAND_QUEUE_TYPE_COMPUTE, "Compute", CI.AdapterId);
AddContext(COMMAND_QUEUE_TYPE_TRANSFER, "Transfer", CI.AdapterId);
AddContext(COMMAND_QUEUE_TYPE_GRAPHICS, "Graphics 2", CI.AdapterId);
EngineVkCreateInfo CreateInfo;
// Always enable validation
CreateInfo.SetValidationLevel(VALIDATION_LEVEL_1);
CreateInfo.AdapterId = CI.AdapterId;
CreateInfo.NumImmediateContexts = static_cast<Uint32>(ContextCI.size());
CreateInfo.pImmediateContextInfo = CreateInfo.NumImmediateContexts > 0 ? ContextCI.data() : nullptr;
CreateInfo.MainDescriptorPoolSize = VulkanDescriptorPoolSize{64, 64, 256, 256, 64, 32, 32, 32, 32, 16, 16};
CreateInfo.DynamicDescriptorPoolSize = VulkanDescriptorPoolSize{64, 64, 256, 256, 64, 32, 32, 32, 32, 16, 16};
CreateInfo.UploadHeapPageSize = 32 * 1024;
//CreateInfo.DeviceLocalMemoryReserveSize = 32 << 20;
//CreateInfo.HostVisibleMemoryReserveSize = 48 << 20;
CreateInfo.Features = CI.Features;
NumDeferredCtx = CI.NumDeferredContexts;
CreateInfo.NumDeferredContexts = NumDeferredCtx;
ppContexts.resize(std::max(size_t{1}, ContextCI.size()) + NumDeferredCtx);
pFactoryVk->CreateDeviceAndContextsVk(CreateInfo, &m_pDevice, ppContexts.data());
}
break;
#endif
#if METAL_SUPPORTED
case RENDER_DEVICE_TYPE_METAL:
{
auto* pFactoryMtl = GetEngineFactoryMtl();
pFactoryMtl->SetMessageCallback(MessageCallback);
EnumerateAdapters(pFactoryMtl, Version{});
AddContext(COMMAND_QUEUE_TYPE_GRAPHICS, "Graphics", CI.AdapterId);
AddContext(COMMAND_QUEUE_TYPE_COMPUTE, "Compute", CI.AdapterId);
AddContext(COMMAND_QUEUE_TYPE_TRANSFER, "Transfer", CI.AdapterId);
AddContext(COMMAND_QUEUE_TYPE_GRAPHICS, "Graphics 2", CI.AdapterId);
EngineMtlCreateInfo CreateInfo;
CreateInfo.AdapterId = CI.AdapterId;
CreateInfo.NumImmediateContexts = static_cast<Uint32>(ContextCI.size());
CreateInfo.pImmediateContextInfo = CreateInfo.NumImmediateContexts ? ContextCI.data() : nullptr;
CreateInfo.Features = CI.Features;
// Always enable validation
CreateInfo.SetValidationLevel(VALIDATION_LEVEL_1);
NumDeferredCtx = CI.NumDeferredContexts;
CreateInfo.NumDeferredContexts = NumDeferredCtx;
ppContexts.resize(std::max(size_t{1}, ContextCI.size()) + NumDeferredCtx);
pFactoryMtl->CreateDeviceAndContextsMtl(CreateInfo, &m_pDevice, ppContexts.data());
}
break;
#endif
default:
LOG_ERROR_AND_THROW("Unknown device type");
break;
}
{
const auto& ActualFeats = m_pDevice->GetDeviceInfo().Features;
#define CHECK_FEATURE_STATE(Feature) \
if (CI.Features.Feature != DEVICE_FEATURE_STATE_OPTIONAL && CI.Features.Feature != ActualFeats.Feature) \
{ \
LOG_ERROR_MESSAGE("requested state (", GetDeviceFeatureStateString(CI.Features.Feature), ") of the '", #Feature, \
"' feature does not match the actual feature state (", GetDeviceFeatureStateString(ActualFeats.Feature), ")."); \
UNEXPECTED("Requested feature state does not match the actual state."); \
}
ENUMERATE_DEVICE_FEATURES(CHECK_FEATURE_STATE)
#undef CHECK_FEATURE_STATE
}
constexpr Uint8 InvalidQueueId = 64; // MAX_COMMAND_QUEUES
m_NumImmediateContexts = std::max(1u, static_cast<Uint32>(ContextCI.size()));
m_pDeviceContexts.resize(ppContexts.size());
for (size_t i = 0; i < ppContexts.size(); ++i)
{
if (ppContexts[i] == nullptr)
LOG_ERROR_AND_THROW("Context must not be null");
const auto CtxDesc = ppContexts[i]->GetDesc();
VERIFY(CtxDesc.ContextId == static_cast<Uint8>(i), "Invalid context index");
if (i < m_NumImmediateContexts)
{
VERIFY(!CtxDesc.IsDeferred, "Immediate context expected");
}
else
{
VERIFY(CtxDesc.IsDeferred, "Deferred context expected");
VERIFY(CtxDesc.QueueId >= InvalidQueueId, "Hardware queue id must be invalid");
}
m_pDeviceContexts[i].Attach(ppContexts[i]);
}
for (size_t i = 0; i < ContextCI.size(); ++i)
{
const auto& CtxCI = ContextCI[i];
const auto CtxDesc = m_pDeviceContexts[i]->GetDesc();
if (CtxCI.QueueId != CtxDesc.QueueId)
LOG_ERROR_MESSAGE("QueueId mismatch");
if (i != CtxDesc.ContextId)
LOG_ERROR_MESSAGE("CommandQueueId mismatch");
}
const auto& AdapterInfo = m_pDevice->GetAdapterInfo();
std::string AdapterInfoStr;
AdapterInfoStr = "Adapter description: ";
AdapterInfoStr += AdapterInfo.Description;
AdapterInfoStr += ". Vendor: ";
static_assert(ADAPTER_VENDOR_LAST == 10, "Please update the switch below to handle the new adapter type");
switch (AdapterInfo.Vendor)
{
case ADAPTER_VENDOR_NVIDIA:
AdapterInfoStr += "NVidia";
break;
case ADAPTER_VENDOR_AMD:
AdapterInfoStr += "AMD";
break;
case ADAPTER_VENDOR_INTEL:
AdapterInfoStr += "Intel";
break;
case ADAPTER_VENDOR_ARM:
AdapterInfoStr += "ARM";
break;
case ADAPTER_VENDOR_QUALCOMM:
AdapterInfoStr += "Qualcomm";
break;
case ADAPTER_VENDOR_IMGTECH:
AdapterInfoStr += "Imagination tech";
break;
case ADAPTER_VENDOR_MSFT:
AdapterInfoStr += "Microsoft";
break;
case ADAPTER_VENDOR_APPLE:
AdapterInfoStr += "Apple";
break;
case ADAPTER_VENDOR_MESA:
AdapterInfoStr += "Mesa";
break;
case ADAPTER_VENDOR_BROADCOM:
AdapterInfoStr += "Broadcom";
break;
default:
AdapterInfoStr += "Unknown";
}
AdapterInfoStr += ". Local memory: ";
AdapterInfoStr += std::to_string(AdapterInfo.Memory.LocalMemory >> 20);
AdapterInfoStr += " MB. Host-visible memory: ";
AdapterInfoStr += std::to_string(AdapterInfo.Memory.HostVisibleMemory >> 20);
AdapterInfoStr += " MB. Unified memory: ";
AdapterInfoStr += std::to_string(AdapterInfo.Memory.UnifiedMemory >> 20);
AdapterInfoStr += " MB.";
LOG_INFO_MESSAGE(AdapterInfoStr);
#if ARCHIVER_SUPPORTED
// Create archiver factory
{
# if EXPLICITLY_LOAD_ARCHIVER_FACTORY_DLL
auto GetArchiverFactory = LoadArchiverFactory();
if (GetArchiverFactory != nullptr)
{
m_ArchiverFactory = GetArchiverFactory();
}
# else
m_ArchiverFactory = Diligent::GetArchiverFactory();
# endif
m_ArchiverFactory->SetMessageCallback(MessageCallback);
}
#endif
}
GPUTestingEnvironment::~GPUTestingEnvironment()
{
for (Uint32 i = 0; i < GetNumImmediateContexts(); ++i)
{
auto* pCtx = GetDeviceContext(i);
pCtx->Flush();
pCtx->FinishFrame();
}
}
// Override this to define how to set up the environment.
void GPUTestingEnvironment::SetUp()
{
}
// Override this to define how to tear down the environment.
void GPUTestingEnvironment::TearDown()
{
}
void GPUTestingEnvironment::ReleaseResources()
{
// It is necessary to call Flush() to force the driver to release resources.
// Without flushing the command buffer, the memory may not be released until sometimes
// later causing out-of-memory error.
for (Uint32 i = 0; i < GetNumImmediateContexts(); ++i)
{
auto* pCtx = GetDeviceContext(i);
pCtx->Flush();
pCtx->FinishFrame();
pCtx->WaitForIdle();
}
m_pDevice->ReleaseStaleResources();
}
void GPUTestingEnvironment::Reset()
{
for (Uint32 i = 0; i < GetNumImmediateContexts(); ++i)
{
auto* pCtx = GetDeviceContext(i);
pCtx->Flush();
pCtx->FinishFrame();
pCtx->InvalidateState();
}
m_pDevice->IdleGPU();
m_pDevice->ReleaseStaleResources();
m_NumAllowedErrors = 0;
}
RefCntAutoPtr<ITexture> GPUTestingEnvironment::CreateTexture(const char* Name, TEXTURE_FORMAT Fmt, BIND_FLAGS BindFlags, Uint32 Width, Uint32 Height, void* pInitData)
{
TextureDesc TexDesc;
TexDesc.Name = Name;
TexDesc.Type = RESOURCE_DIM_TEX_2D;
TexDesc.Format = Fmt;
TexDesc.BindFlags = BindFlags;
TexDesc.Width = Width;
TexDesc.Height = Height;
const auto FmtAttribs = GetTextureFormatAttribs(Fmt);
TextureSubResData Mip0Data{pInitData, FmtAttribs.ComponentSize * FmtAttribs.NumComponents * Width};
TextureData TexData{&Mip0Data, 1};
RefCntAutoPtr<ITexture> pTexture;
m_pDevice->CreateTexture(TexDesc, pInitData ? &TexData : nullptr, &pTexture);
VERIFY_EXPR(pTexture != nullptr);
return pTexture;
}
RefCntAutoPtr<ISampler> GPUTestingEnvironment::CreateSampler(const SamplerDesc& Desc)
{
RefCntAutoPtr<ISampler> pSampler;
m_pDevice->CreateSampler(Desc, &pSampler);
return pSampler;
}
void GPUTestingEnvironment::SetDefaultCompiler(SHADER_COMPILER compiler)
{
switch (m_pDevice->GetDeviceInfo().Type)
{
case RENDER_DEVICE_TYPE_D3D12:
switch (compiler)
{
case SHADER_COMPILER_DEFAULT:
case SHADER_COMPILER_FXC:
case SHADER_COMPILER_DXC:
m_ShaderCompiler = compiler;
break;
default:
LOG_WARNING_MESSAGE(GetShaderCompilerTypeString(compiler), " is not supported by Direct3D12 backend. Using default compiler");
m_ShaderCompiler = SHADER_COMPILER_DEFAULT;
}
break;
case RENDER_DEVICE_TYPE_D3D11:
switch (compiler)
{
case SHADER_COMPILER_DEFAULT:
case SHADER_COMPILER_FXC:
m_ShaderCompiler = compiler;
break;
default:
LOG_WARNING_MESSAGE(GetShaderCompilerTypeString(compiler), " is not supported by Direct3D11 backend. Using default compiler");
m_ShaderCompiler = SHADER_COMPILER_DEFAULT;
}
break;
case RENDER_DEVICE_TYPE_GL:
case RENDER_DEVICE_TYPE_GLES:
switch (compiler)
{
case SHADER_COMPILER_DEFAULT:
m_ShaderCompiler = compiler;
break;
default:
LOG_WARNING_MESSAGE(GetShaderCompilerTypeString(compiler), " is not supported by OpenGL/GLES backend. Using default compiler");
m_ShaderCompiler = SHADER_COMPILER_DEFAULT;
}
break;
case RENDER_DEVICE_TYPE_VULKAN:
switch (compiler)
{
case SHADER_COMPILER_DEFAULT:
case SHADER_COMPILER_GLSLANG:
m_ShaderCompiler = compiler;
case SHADER_COMPILER_DXC:
if (HasDXCompiler())
m_ShaderCompiler = compiler;
break;
default:
LOG_WARNING_MESSAGE(GetShaderCompilerTypeString(compiler), " is not supported by Vulkan backend. Using default compiler");
m_ShaderCompiler = SHADER_COMPILER_DEFAULT;
}
break;
case RENDER_DEVICE_TYPE_METAL:
switch (compiler)
{
case SHADER_COMPILER_DEFAULT:
m_ShaderCompiler = compiler;
break;
default:
LOG_WARNING_MESSAGE(GetShaderCompilerTypeString(compiler), " is not supported by Metal backend. Using default compiler");
m_ShaderCompiler = SHADER_COMPILER_DEFAULT;
}
break;
default:
LOG_WARNING_MESSAGE("Unexpected device type");
m_ShaderCompiler = SHADER_COMPILER_DEFAULT;
}
LOG_INFO_MESSAGE("Selected shader compiler: ", GetShaderCompilerTypeString(m_ShaderCompiler));
}
SHADER_COMPILER GPUTestingEnvironment::GetDefaultCompiler(SHADER_SOURCE_LANGUAGE lang) const
{
if (m_pDevice->GetDeviceInfo().Type == RENDER_DEVICE_TYPE_VULKAN &&
lang != SHADER_SOURCE_LANGUAGE_HLSL)
return SHADER_COMPILER_GLSLANG;
else
return m_ShaderCompiler;
}
static bool ParseFeatureState(const char* Arg, DeviceFeatures& Features)
{
static const std::string ArgStart = "--Features.";
if (ArgStart.compare(0, ArgStart.length(), Arg, ArgStart.length()) != 0)
return false;
Arg += ArgStart.length();
DeviceFeatures::Enumerate(Features,
[Arg](const char* FeatName, DEVICE_FEATURE_STATE& State) //
{
const auto NameLen = strlen(FeatName);
if (strncmp(FeatName, Arg, NameLen) != 0)
return true;
if (Arg[NameLen] != '=')
return true; // Continue processing
const auto Value = Arg + NameLen + 1;
static const std::string Off = "Off";
static const std::string On = "On";
static const std::string Disabled = "Disabled";
static const std::string Enabled = "Enabled";
if (StrCmpNoCase(Value, On.c_str()) == 0 || StrCmpNoCase(Value, Enabled.c_str()) == 0)
State = DEVICE_FEATURE_STATE_ENABLED;
else if (StrCmpNoCase(Value, Off.c_str()) == 0 || StrCmpNoCase(Value, Disabled.c_str()) == 0)
State = DEVICE_FEATURE_STATE_DISABLED;
else
{
LOG_ERROR_MESSAGE('\'', Value, "' is not a valid value for feature '", FeatName, "'. The following values are allowed: '",
Off, "', '", Disabled, "', '", On, "', '", Enabled, "'.");
}
return false;
});
return false;
}
GPUTestingEnvironment* GPUTestingEnvironment::Initialize(int argc, char** argv)
{
GPUTestingEnvironment::CreateInfo TestEnvCI;
SHADER_COMPILER ShCompiler = SHADER_COMPILER_DEFAULT;
for (int i = 1; i < argc; ++i)
{
const std::string AdapterArgName = "--adapter=";
const auto* arg = argv[i];
if (strcmp(arg, "--mode=d3d11") == 0)
{
TestEnvCI.deviceType = RENDER_DEVICE_TYPE_D3D11;
}
else if (strcmp(arg, "--mode=d3d11_sw") == 0)
{
TestEnvCI.deviceType = RENDER_DEVICE_TYPE_D3D11;
TestEnvCI.AdapterType = ADAPTER_TYPE_SOFTWARE;
}
else if (strcmp(arg, "--mode=d3d12") == 0)
{
TestEnvCI.deviceType = RENDER_DEVICE_TYPE_D3D12;
}
else if (strcmp(arg, "--mode=d3d12_sw") == 0)
{
TestEnvCI.deviceType = RENDER_DEVICE_TYPE_D3D12;
TestEnvCI.AdapterType = ADAPTER_TYPE_SOFTWARE;
}
else if (strcmp(arg, "--mode=vk") == 0)
{
TestEnvCI.deviceType = RENDER_DEVICE_TYPE_VULKAN;
}
else if (strcmp(arg, "--mode=gl") == 0)
{
TestEnvCI.deviceType = RENDER_DEVICE_TYPE_GL;
}
else if (strcmp(arg, "--mode=mtl") == 0)
{
TestEnvCI.deviceType = RENDER_DEVICE_TYPE_METAL;
}
else if (AdapterArgName.compare(0, AdapterArgName.length(), arg, AdapterArgName.length()) == 0)
{
TestEnvCI.AdapterId = static_cast<Uint32>(atoi(arg + AdapterArgName.length()));
}
else if (strcmp(arg, "--shader_compiler=dxc") == 0)
{
ShCompiler = SHADER_COMPILER_DXC;
}
else if (strcmp(arg, "--non_separable_progs") == 0)
{
TestEnvCI.Features.SeparablePrograms = DEVICE_FEATURE_STATE_DISABLED;
}
else if (strcmp(arg, "--vk_dev_sim") == 0)
{
TestEnvCI.EnableDeviceSimulation = true;
}
else if (ParseFeatureState(arg, TestEnvCI.Features))
{
// Feature state has been updated by ParseFeatureState
}
}
if (TestEnvCI.deviceType == RENDER_DEVICE_TYPE_UNDEFINED)
{
LOG_ERROR_MESSAGE("Device type is not specified");
return nullptr;
}
SwapChainDesc SCDesc;
SCDesc.Width = 512;
SCDesc.Height = 512;
SCDesc.ColorBufferFormat = TEX_FORMAT_RGBA8_UNORM;
SCDesc.DepthBufferFormat = TEX_FORMAT_D32_FLOAT;
Diligent::Testing::GPUTestingEnvironment* pEnv = nullptr;
try
{
switch (TestEnvCI.deviceType)
{
#if D3D11_SUPPORTED
case RENDER_DEVICE_TYPE_D3D11:
if (TestEnvCI.AdapterType == ADAPTER_TYPE_SOFTWARE)
std::cout << "\n\n\n================ Running tests in Direct3D11-SW mode =================\n\n";
else
std::cout << "\n\n\n================== Running tests in Direct3D11 mode ==================\n\n";
pEnv = CreateTestingEnvironmentD3D11(TestEnvCI, SCDesc);
break;
#endif
#if D3D12_SUPPORTED
case RENDER_DEVICE_TYPE_D3D12:
if (TestEnvCI.AdapterType == ADAPTER_TYPE_SOFTWARE)
std::cout << "\n\n\n================ Running tests in Direct3D12-SW mode =================\n\n";
else
std::cout << "\n\n\n================== Running tests in Direct3D12 mode ==================\n\n";
pEnv = CreateTestingEnvironmentD3D12(TestEnvCI, SCDesc);
break;
#endif
#if GL_SUPPORTED || GLES_SUPPORTED
case RENDER_DEVICE_TYPE_GL:
case RENDER_DEVICE_TYPE_GLES:
std::cout << "\n\n\n==================== Running tests in OpenGL mode ====================\n\n";
pEnv = CreateTestingEnvironmentGL(TestEnvCI, SCDesc);
break;
#endif
#if VULKAN_SUPPORTED
case RENDER_DEVICE_TYPE_VULKAN:
std::cout << "\n\n\n==================== Running tests in Vulkan mode ====================\n\n";
pEnv = CreateTestingEnvironmentVk(TestEnvCI, SCDesc);
break;
#endif
#if METAL_SUPPORTED
case RENDER_DEVICE_TYPE_METAL:
std::cout << "\n\n\n==================== Running tests in Metal mode ====================\n\n";
pEnv = CreateTestingEnvironmentMtl(TestEnvCI, SCDesc);
break;
#endif
default:
LOG_ERROR_AND_THROW("Unsupported device type");
}
}
catch (...)
{
return nullptr;
}
pEnv->SetDefaultCompiler(ShCompiler);
return pEnv;
}
} // namespace Testing
} // namespace Diligent
| 38.667033 | 166 | 0.594538 | [
"vector"
] |
01e272703daa79f9da6b5f1103df07f7a09a55b3 | 2,215 | cpp | C++ | app/src/main/jni/RenderingText/RenderingText.cpp | qige023/learning-opengles3-android | cbe0742637a6eeed41c76756021913cc570cc30e | [
"MIT"
] | 10 | 2015-05-06T17:59:51.000Z | 2019-12-03T10:08:23.000Z | app/src/main/jni/RenderingText/RenderingText.cpp | qige023/OpenGL-ES3-Programming-On-Android | cbe0742637a6eeed41c76756021913cc570cc30e | [
"MIT"
] | null | null | null | app/src/main/jni/RenderingText/RenderingText.cpp | qige023/OpenGL-ES3-Programming-On-Android | cbe0742637a6eeed41c76756021913cc570cc30e | [
"MIT"
] | null | null | null | #include "RenderingText.h"
#include <iostream>
using std::cout;
using std::endl;
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtx/string_cast.hpp>
using glm::vec3;
using glm::vec4;
#include "esutil.h"
#include "esfile.h"
RenderingText::RenderingText() { }
RenderingText::~RenderingText() {
delete charactersHolder;
}
void RenderingText::initScene(ESContext *esContext) {
compileAndLinkShader();
charactersHolder = new ESCharactersHolder();
charactersHolder->loadFont("font/youyuan.ttf");
// Set OpenGL options
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
}
void RenderingText::update(ESContext *esContext, float t ) {
}
void RenderingText::render(ESContext *esContext) {
glClear(GL_COLOR_BUFFER_BIT);
projection = mat4(1.0f);
projection *= glm::ortho(0.0f, static_cast<GLfloat>(esContext->width), 0.0f, static_cast<GLfloat>(esContext-> height));
//we omit model and view matrix , they are by default mat4(1.0f)
prog.setUniform("projection", projection);
prog.setUniform("textColor", glm::vec3(0.5, 0.8f, 0.2f));
charactersHolder->displayText("こんにちは、新世界は、ここに来ます", 25.0f, 25.0f, 1.0f);
prog.setUniform("textColor", glm::vec3(0.3, 0.7f, 0.9f));
charactersHolder->displayText("(C) Glorex 3D Framework", 300.0f, 570.0f, 1.5f);
prog.setUniform("textColor", glm::vec3(1.0, 1.0f, 0.0f));
charactersHolder->displayText("格里斯三维影像渲染框架", 100.0f, 250.0f, 2.0f);
}
void RenderingText::resize(ESContext *esContext) {
glViewport(0,0,esContext->width,esContext->height);
}
void RenderingText::compileAndLinkShader() {
cout << "exec RenderingText::compileAndLinkShader" << endl;
try {
prog.compileShader("shader/rendertext.vert");
prog.compileShader("shader/rendertext.frag");
prog.link();
prog.validate();
prog.use();
} catch (ESProgramException & e) {
cerr << e.what() << endl;
exit( EXIT_FAILURE);
}
}
ESScene *esCreateScene(ESContext *esContext) {
cout << "exec esCreateScene -> create scene RenderingText" << endl;
return new RenderingText();
}
| 28.397436 | 123 | 0.684876 | [
"render",
"model",
"transform",
"3d"
] |
01e644b382028d1c1c28875169a58de067446ed0 | 1,686 | cc | C++ | Codeforces/236 Division 1/Problem D/D.cc | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | Codeforces/236 Division 1/Problem D/D.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | Codeforces/236 Division 1/Problem D/D.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <utility>
#include <queue>
#include <stack>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define LET(x, a) __typeof(a) x(a)
#define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define tr(x) cout<<x<<endl;
#define tr2(x,y) cout<<x<<" "<<y<<endl;
#define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl;
#define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl;
#define tr5(v,w,x,y,z) cout<<v<<" "<<w<<" "<<x<<" "<<y<<" "<<z<<endl;
#define tr6(u,v,w,x,y,z) cout<<u<<" "<<v<<" "<<w<<" "<<x<<" "<<y<<" "<<z<<endl;
using namespace std;
typedef long long ll;
int t, n, k, dp[51][1001], r[51][1001];
ll f[51], MOD = 1e9 + 7;
int main(){
f[0] = 1;
for(int i = 1; i < 51; i++) f[i] = (f[i-1]*i)%MOD;
for(int i = 0; i < 1001; i++) r[0][i] = 1;
for(int i = 1; i < 1001; i++){
for(int j = 1; j < 51; j++){
for(int k = i; k < 1001; k++){
dp[j][k] += r[j-1][k-i]; if(dp[j][k] >= MOD) dp[j][k] -= MOD;
}
}
for(int j = 1; j < 51; j++){
int tot = 0;
for(int k = 0; k < 1001; k++){
tot += dp[j][k]; if(tot >= MOD) tot -= MOD;
r[j][k] = tot;
}
}
}
sd(t);
while(t--){
sd2(n,k);
if(k > 50) printf("0\n");
else printf("%d\n", (int) (((ll) f[k] * r[k][n])%MOD));
}
return 0;
}
| 24.794118 | 79 | 0.520759 | [
"vector"
] |
543fe0b1e7814d5a8b6e666e7a031eb9de56ed08 | 855 | cpp | C++ | 692.top-k-frequent-words.158916980.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | 692.top-k-frequent-words.158916980.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | 692.top-k-frequent-words.158916980.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
struct compare{
bool operator()(pair<string,int>a, pair<string,int>b)
{
if(a.second!=b.second)return a.second<b.second;
else return a.first>b.first;
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
priority_queue<pair<string,int>,vector<pair<string,int>>,compare>pq;
unordered_map<string,int> m;
vector<string> ans;
for(int i=0;i<words.size();i++)
{
if(m.find(words[i])==m.end())m[words[i]]=1;
else m[words[i]]++;
}
for(auto it = m.begin();it!=m.end();it++)pq.push({it->first,it->second});
for(int ct=0;ct<k;ct++)
{
pair<string,int> top = pq.top();
pq.pop();
ans.push_back(top.first);
}
return ans;
}
};
| 28.5 | 79 | 0.509942 | [
"vector"
] |
5443b39bc6522ebe1ed91096ddce8b2caf9be196 | 26,136 | cc | C++ | alljoyn_c/src/PermissionConfigurator.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 33 | 2018-01-12T00:37:43.000Z | 2022-03-24T02:31:36.000Z | alljoyn_c/src/PermissionConfigurator.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 1 | 2020-01-05T05:51:27.000Z | 2020-01-05T05:51:27.000Z | alljoyn_c/src/PermissionConfigurator.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 30 | 2017-12-13T23:24:00.000Z | 2022-01-25T02:11:19.000Z | /**
* @file
* PermissionConfigurator is responsible for managing an application's Security 2.0 settings.
*/
/******************************************************************************
* Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source
* Project (AJOSP) Contributors and others.
*
* SPDX-License-Identifier: Apache-2.0
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Open Connectivity Foundation and Contributors to AllSeen
* Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#include <alljoyn/BusAttachment.h>
#include <alljoyn/PermissionConfigurator.h>
#include <alljoyn/PermissionPolicy.h>
#include <alljoyn_c/PermissionConfigurator.h>
#include <alljoyn_c/SecurityApplicationProxy.h>
#include <stdio.h>
#include <qcc/Debug.h>
#include <qcc/StringUtil.h>
#include "XmlManifestConverter.h"
#include "XmlPoliciesConverter.h"
#include "KeyInfoHelper.h"
#include "CertificateUtilities.h"
#define QCC_MODULE "ALLJOYN_C"
using namespace qcc;
using namespace ajn;
alljoyn_claimcapabilities AJ_CALL alljoyn_permissionconfigurator_getdefaultclaimcapabilities()
{
return PermissionConfigurator::CLAIM_CAPABILITIES_DEFAULT;
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getapplicationstate(const alljoyn_permissionconfigurator configurator, alljoyn_applicationstate* state)
{
QCC_DbgTrace(("%s", __FUNCTION__));
PermissionConfigurator::ApplicationState returnedState;
QStatus status = ((const PermissionConfigurator*)configurator)->GetApplicationState(returnedState);
if (ER_OK == status) {
*state = (alljoyn_applicationstate)returnedState;
}
return status;
}
QStatus AJ_CALL alljoyn_permissionconfigurator_setapplicationstate(alljoyn_permissionconfigurator configurator, const alljoyn_applicationstate state)
{
QCC_DbgTrace(("%s", __FUNCTION__));
return ((PermissionConfigurator*)configurator)->SetApplicationState((PermissionConfigurator::ApplicationState)state);
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getpublickey(alljoyn_permissionconfigurator configurator, AJ_PSTR* publicKey)
{
QCC_DbgTrace(("%s", __FUNCTION__));
KeyInfoNISTP256 keyInfo;
QStatus status = ((PermissionConfigurator*)configurator)->GetSigningPublicKey(keyInfo);
if (ER_OK != status) {
return status;
}
String encodedPem;
status = CertificateX509::EncodePublicKeyPEM(keyInfo.GetPublicKey(), encodedPem);
if (ER_OK != status) {
return status;
}
*publicKey = CreateStringCopy(static_cast<std::string>(encodedPem));
if (nullptr == *publicKey) {
return ER_OUT_OF_MEMORY;
}
return ER_OK;
}
void AJ_CALL alljoyn_permissionconfigurator_publickey_destroy(AJ_PSTR publicKey)
{
DestroyStringCopy(publicKey);
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getconnectedpeerpublickey(alljoyn_permissionconfigurator configurator, const uint8_t* groupId, AJ_PSTR* publicKey)
{
QCC_DbgTrace(("%s", __FUNCTION__));
qcc::ECCPublicKey eccKey;
qcc::String eccKeyStr;
GUID128 gid;
gid.SetBytes(groupId);
QStatus status = ((PermissionConfigurator*)configurator)->GetConnectedPeerPublicKey(gid, &eccKey);
if (ER_OK != status) {
return status;
}
eccKeyStr = eccKey.ToString();
*publicKey = CreateStringCopy(static_cast<std::string>(eccKeyStr));
if (nullptr == *publicKey) {
return ER_OUT_OF_MEMORY;
}
return ER_OK;
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getmanifesttemplate(alljoyn_permissionconfigurator configurator, AJ_PSTR* manifestTemplateXml)
{
QCC_DbgTrace(("%s", __FUNCTION__));
std::string manifestTemplateString;
QStatus status = ((PermissionConfigurator*)configurator)->GetManifestTemplateAsXml(manifestTemplateString);
if (ER_OK != status) {
return status;
}
*manifestTemplateXml = CreateStringCopy(manifestTemplateString);
if (nullptr == *manifestTemplateXml) {
return ER_OUT_OF_MEMORY;
}
return ER_OK;
}
void AJ_CALL alljoyn_permissionconfigurator_manifesttemplate_destroy(AJ_PSTR manifestTemplateXml)
{
QCC_DbgTrace(("%s", __FUNCTION__));
DestroyStringCopy(manifestTemplateXml);
}
void AJ_CALL alljoyn_permissionconfigurator_manifest_destroy(AJ_PSTR manifestXml)
{
QCC_DbgTrace(("%s", __FUNCTION__));
DestroyStringCopy(manifestXml);
}
QStatus AJ_CALL alljoyn_permissionconfigurator_setmanifesttemplatefromxml(alljoyn_permissionconfigurator configurator, AJ_PCSTR manifestTemplateXml)
{
QCC_DbgTrace(("%s", __FUNCTION__));
return ((PermissionConfigurator*)configurator)->SetManifestTemplateFromXml(manifestTemplateXml);
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getclaimcapabilities(const alljoyn_permissionconfigurator configurator, alljoyn_claimcapabilities* claimCapabilities)
{
QCC_DbgTrace(("%s", __FUNCTION__));
PermissionConfigurator::ClaimCapabilities returnedClaimCapabilities;
QStatus status = ((const PermissionConfigurator*)configurator)->GetClaimCapabilities(returnedClaimCapabilities);
if (ER_OK == status) {
*claimCapabilities = (alljoyn_claimcapabilities)returnedClaimCapabilities;
}
return status;
}
QStatus AJ_CALL alljoyn_permissionconfigurator_setclaimcapabilities(alljoyn_permissionconfigurator configurator, alljoyn_claimcapabilities claimCapabilities)
{
QCC_DbgTrace(("%s", __FUNCTION__));
return ((PermissionConfigurator*)configurator)->SetClaimCapabilities((PermissionConfigurator::ClaimCapabilities)claimCapabilities);
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getclaimcapabilitiesadditionalinfo(const alljoyn_permissionconfigurator configurator, alljoyn_claimcapabilitiesadditionalinfo* additionalInfo)
{
QCC_DbgTrace(("%s", __FUNCTION__));
PermissionConfigurator::ClaimCapabilityAdditionalInfo returnedClaimCapabilitiesAdditionalInfo;
QStatus status = ((const PermissionConfigurator*)configurator)->GetClaimCapabilityAdditionalInfo(returnedClaimCapabilitiesAdditionalInfo);
if (ER_OK == status) {
*additionalInfo = (alljoyn_claimcapabilitiesadditionalinfo)returnedClaimCapabilitiesAdditionalInfo;
}
return status;
}
QStatus AJ_CALL alljoyn_permissionconfigurator_setclaimcapabilitiesadditionalinfo(alljoyn_permissionconfigurator configurator, alljoyn_claimcapabilitiesadditionalinfo additionalInfo)
{
QCC_DbgTrace(("%s", __FUNCTION__));
return ((PermissionConfigurator*)configurator)->SetClaimCapabilityAdditionalInfo((PermissionConfigurator::ClaimCapabilityAdditionalInfo)additionalInfo);
}
QStatus AJ_CALL alljoyn_permissionconfigurator_reset(alljoyn_permissionconfigurator configurator)
{
QCC_DbgTrace(("%s", __FUNCTION__));
return ((PermissionConfigurator*)configurator)->Reset();
}
QStatus AJ_CALL alljoyn_permissionconfigurator_claim(alljoyn_permissionconfigurator configurator,
AJ_PCSTR caKey,
AJ_PCSTR identityCertificateChain,
const uint8_t* groupId,
size_t groupSize,
AJ_PCSTR groupAuthority,
AJ_PCSTR* manifestsXmls,
size_t manifestsCount)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
size_t identCertCount = 0;
KeyInfoNISTP256 caPublicKey;
KeyInfoNISTP256 groupPublicKey;
GUID128 groupGuid;
PermissionConfigurator* pc = (PermissionConfigurator*)configurator;
CertificateX509* identityCerts = nullptr;
status = GetGroupId(groupId, groupSize, groupGuid);
if (ER_OK == status) {
status = KeyInfoHelper::PEMToKeyInfoNISTP256(caKey, caPublicKey);
}
if (ER_OK == status) {
status = KeyInfoHelper::PEMToKeyInfoNISTP256(groupAuthority, groupPublicKey);
}
if (ER_OK == status) {
status = ExtractCertificates(identityCertificateChain, &identCertCount, &identityCerts);
}
if (ER_OK == status) {
status = pc->Claim(caPublicKey,
groupGuid,
groupPublicKey,
identityCerts, identCertCount,
manifestsXmls, manifestsCount);
}
delete[] identityCerts;
return status;
}
QStatus AJ_CALL alljoyn_permissionconfigurator_updateidentity(alljoyn_permissionconfigurator configurator,
AJ_PCSTR identityCertificateChain,
AJ_PCSTR* manifestsXmls, size_t manifestsCount)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
size_t certCount = 0;
PermissionConfigurator* pc = (PermissionConfigurator*)configurator;
CertificateX509* certs = nullptr;
status = ExtractCertificates(identityCertificateChain, &certCount, &certs);
if (ER_OK == status) {
status = pc->UpdateIdentity(certs,
certCount,
manifestsXmls,
manifestsCount);
}
delete[] certs;
return status;
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getidentity(alljoyn_permissionconfigurator configurator,
AJ_PSTR* identityCertificateChain)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
PermissionConfigurator* pc = (PermissionConfigurator*)configurator;
std::vector<CertificateX509> certChain;
status = pc->GetIdentity(certChain);
if (ER_OK != status) {
return status;
}
qcc::String chainPEM;
qcc::String individualCertificate;
for (std::vector<CertificateX509>::size_type i = 0; i < certChain.size(); i++) {
status = certChain[i].EncodeCertificatePEM(individualCertificate);
if (ER_OK != status) {
return status;
}
chainPEM.append(individualCertificate);
}
*identityCertificateChain = CreateStringCopy(static_cast<std::string>(chainPEM));
if (nullptr == *identityCertificateChain) {
return ER_OUT_OF_MEMORY;
}
return ER_OK;
}
void AJ_CALL alljoyn_permissionconfigurator_certificatechain_destroy(AJ_PSTR certificateChain)
{
QCC_DbgTrace(("%s", __FUNCTION__));
DestroyStringCopy(certificateChain);
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getmanifests(alljoyn_permissionconfigurator configurator,
alljoyn_manifestarray* manifestArray)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
PermissionConfigurator* pc = (PermissionConfigurator*)configurator;
std::vector<Manifest> manifests;
status = pc->GetManifests(manifests);
if (ER_OK != status) {
return status;
}
QCC_ASSERT(manifests.size() > 0);
std::vector<std::string> manifestsStrings;
status = XmlManifestConverter::ManifestsToXmlArray(manifests.data(), manifests.size(), manifestsStrings);
if (ER_OK != status) {
return status;
}
std::vector<std::string>::size_type count = manifestsStrings.size();
manifestArray->xmls = new (std::nothrow) AJ_PSTR[count];
if (nullptr == manifestArray->xmls) {
manifestArray->count = 0;
return ER_OUT_OF_MEMORY;
}
memset(manifestArray->xmls, 0, sizeof(AJ_PSTR) * count);
manifestArray->count = manifestsStrings.size();
for (std::vector<std::string>::size_type i = 0; i < count; i++) {
manifestArray->xmls[i] = CreateStringCopy(manifestsStrings[i]);
if (nullptr == manifestArray->xmls[i]) {
alljoyn_permissionconfigurator_manifestarray_cleanup(manifestArray);
memset(manifestArray, 0, sizeof(*manifestArray));
return ER_OUT_OF_MEMORY;
}
}
return ER_OK;
}
void AJ_CALL alljoyn_permissionconfigurator_manifestarray_cleanup(alljoyn_manifestarray* manifestArray)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QCC_ASSERT(nullptr != manifestArray);
for (size_t i = 0; i < manifestArray->count; i++) {
DestroyStringCopy(manifestArray->xmls[i]);
}
delete[] manifestArray->xmls;
memset(manifestArray, 0, sizeof(*manifestArray));
}
void AJ_CALL alljoyn_permissionconfigurator_certificatechainarray_cleanup(alljoyn_certificatechainarray* certChainArray)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QCC_ASSERT(nullptr != certChainArray);
for (size_t i = 0; i < certChainArray->count; ++i) {
for (size_t j = 0; j < certChainArray->chains[i].count; ++j) {
// Guard nullptr case instead of using QCC_ASSERT in case this function is called due to
// allocation failure for a particular chains[i].certificates
if (nullptr != certChainArray->chains[i].certificates) {
DestroyStringCopy(certChainArray->chains[i].certificates[j]);
}
}
delete[] certChainArray->chains[i].certificates;
}
delete[] certChainArray->chains;
memset(certChainArray, 0, sizeof(*certChainArray));
}
QStatus AJ_CALL alljoyn_permissionconfigurator_installmanifests(alljoyn_permissionconfigurator configurator,
AJ_PCSTR* manifestsXmls,
size_t manifestsCount,
QCC_BOOL append)
{
QCC_DbgTrace(("%s", __FUNCTION__));
return ((PermissionConfigurator*)configurator)->InstallManifests(manifestsXmls, manifestsCount, (QCC_TRUE == append));
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getidentitycertificateid(alljoyn_permissionconfigurator configurator,
alljoyn_certificateid* certificateId)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
PermissionConfigurator* pc = (PermissionConfigurator*)configurator;
String serialString;
KeyInfoNISTP256 keyInfo;
String keyInfoString;
status = pc->GetIdentityCertificateId(serialString, keyInfo);
if (ER_OK != status) {
return status;
}
status = KeyInfoHelper::KeyInfoNISTP256ToPEM(keyInfo, keyInfoString);
if (ER_OK != status) {
return status;
}
uint8_t* serialBuffer = new (std::nothrow) uint8_t[serialString.size()];
if (nullptr == serialBuffer) {
return ER_OUT_OF_MEMORY;
}
memcpy(serialBuffer, serialString.data(), serialString.size());
certificateId->serial = serialBuffer;
certificateId->serialLen = serialString.size();
certificateId->issuerPublicKey = CreateStringCopy(keyInfoString);
if (nullptr == certificateId->issuerPublicKey) {
delete[] certificateId->serial;
certificateId->serial = nullptr;
certificateId->serialLen = 0;
return ER_OUT_OF_MEMORY;
}
certificateId->issuerAki = nullptr;
certificateId->issuerAkiLen = 0;
return ER_OK;
}
void AJ_CALL alljoyn_permissionconfigurator_certificateid_cleanup(alljoyn_certificateid* certificateId)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QCC_ASSERT(nullptr != certificateId);
delete[] certificateId->serial;
DestroyStringCopy(certificateId->issuerPublicKey);
delete[] certificateId->issuerAki;
memset(certificateId, 0, sizeof(*certificateId));
}
QStatus AJ_CALL alljoyn_permissionconfigurator_updatepolicy(alljoyn_permissionconfigurator configurator,
AJ_PCSTR policyXml)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
PermissionPolicy policy;
status = XmlPoliciesConverter::FromXml(policyXml, policy);
if (ER_OK != status) {
return status;
}
return ((PermissionConfigurator*)configurator)->UpdatePolicy(policy);
}
QStatus PolicyToString(const PermissionPolicy& policy, AJ_PSTR* policyXml)
{
std::string policyString;
QStatus status = XmlPoliciesConverter::ToXml(policy, policyString);
if (ER_OK != status) {
*policyXml = nullptr;
return status;
}
*policyXml = CreateStringCopy(policyString);
if (nullptr == policyXml) {
return ER_OUT_OF_MEMORY;
}
return ER_OK;
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getpolicy(alljoyn_permissionconfigurator configurator,
AJ_PSTR* policyXml)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
PermissionPolicy policy;
status = ((PermissionConfigurator*)configurator)->GetPolicy(policy);
if (ER_OK != status) {
*policyXml = nullptr;
return status;
}
return PolicyToString(policy, policyXml);
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getdefaultpolicy(alljoyn_permissionconfigurator configurator,
AJ_PSTR* policyXml)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
PermissionPolicy policy;
status = ((PermissionConfigurator*)configurator)->GetDefaultPolicy(policy);
if (ER_OK != status) {
*policyXml = nullptr;
return status;
}
return PolicyToString(policy, policyXml);
}
void AJ_CALL alljoyn_permissionconfigurator_policy_destroy(AJ_PSTR policyXml)
{
QCC_DbgTrace(("%s", __FUNCTION__));
DestroyStringCopy(policyXml);
}
QStatus AJ_CALL alljoyn_permissionconfigurator_resetpolicy(alljoyn_permissionconfigurator configurator)
{
QCC_DbgTrace(("%s", __FUNCTION__));
return ((PermissionConfigurator*)configurator)->ResetPolicy();
}
QStatus AJ_CALL alljoyn_permissionconfigurator_getmembershipsummaries(alljoyn_permissionconfigurator configurator,
alljoyn_certificateidarray* certificateIds)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
PermissionConfigurator* pc = (PermissionConfigurator*)configurator;
std::vector<String> serialsVector;
std::vector<KeyInfoNISTP256> keyInfosVector;
memset(certificateIds, 0, sizeof(*certificateIds));
status = pc->GetMembershipSummaries(serialsVector, keyInfosVector);
if (ER_OK != status) {
return status;
}
QCC_ASSERT(serialsVector.size() == keyInfosVector.size());
if (serialsVector.empty()) {
return ER_OK;
}
certificateIds->ids = new (std::nothrow) alljoyn_certificateid[serialsVector.size()];
if (nullptr == certificateIds->ids) {
return ER_OUT_OF_MEMORY;
}
memset(certificateIds->ids, 0, sizeof(alljoyn_certificateid) * serialsVector.size());
certificateIds->count = serialsVector.size();
for (std::vector<KeyInfoNISTP256>::size_type i = 0; i < keyInfosVector.size(); i++) {
String publicKeyString;
String akiString;
status = KeyInfoHelper::KeyInfoNISTP256ToPEM(keyInfosVector[i], publicKeyString);
if (ER_OK != status) {
alljoyn_permissionconfigurator_certificateidarray_cleanup(certificateIds);
return status;
}
status = KeyInfoHelper::KeyInfoNISTP256ExtractAki(keyInfosVector[i], akiString);
if (ER_OK != status) {
alljoyn_permissionconfigurator_certificateidarray_cleanup(certificateIds);
return status;
}
uint8_t* serialBuffer = new (std::nothrow) uint8_t[serialsVector[i].size()];
if (nullptr == serialBuffer) {
alljoyn_permissionconfigurator_certificateidarray_cleanup(certificateIds);
return ER_OUT_OF_MEMORY;
}
memcpy(serialBuffer, serialsVector[i].data(), serialsVector[i].size());
certificateIds->ids[i].serial = serialBuffer;
certificateIds->ids[i].serialLen = serialsVector[i].size();
certificateIds->ids[i].issuerPublicKey = CreateStringCopy(publicKeyString);
if (nullptr == certificateIds->ids[i].issuerPublicKey) {
alljoyn_permissionconfigurator_certificateidarray_cleanup(certificateIds);
return ER_OUT_OF_MEMORY;
}
uint8_t* akiBuffer = new (std::nothrow) uint8_t[akiString.size()];
if (nullptr == akiBuffer) {
alljoyn_permissionconfigurator_certificateidarray_cleanup(certificateIds);
return ER_OUT_OF_MEMORY;
}
memcpy(akiBuffer, akiString.data(), akiString.size());
certificateIds->ids[i].issuerAki = akiBuffer;
certificateIds->ids[i].issuerAkiLen = akiString.size();
}
return ER_OK;
}
void AJ_CALL alljoyn_permissionconfigurator_certificateidarray_cleanup(alljoyn_certificateidarray* certificateIdArray)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QCC_ASSERT(nullptr != certificateIdArray);
for (size_t i = 0; i < certificateIdArray->count; i++) {
alljoyn_permissionconfigurator_certificateid_cleanup(&certificateIdArray->ids[i]);
}
delete[] certificateIdArray->ids;
memset(certificateIdArray, 0, sizeof(*certificateIdArray));
}
QStatus AJ_CALL alljoyn_permissionconfigurator_installmembership(alljoyn_permissionconfigurator configurator,
AJ_PCSTR membershipCertificateChain)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
size_t certCount = 0;
PermissionConfigurator* pc = (PermissionConfigurator*)configurator;
CertificateX509* certs = nullptr;
status = ExtractCertificates(membershipCertificateChain, &certCount, &certs);
if (ER_OK == status) {
status = pc->InstallMembership(certs, certCount);
}
delete[] certs;
return status;
}
QStatus AJ_CALL alljoyn_permissionconfigurator_removemembership(alljoyn_permissionconfigurator configurator,
const uint8_t* serial,
size_t serialLen,
AJ_PCSTR issuerPublicKey,
const uint8_t* issuerAki,
size_t issuerAkiLen)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
qcc::ECCPublicKey pubKey;
status = qcc::CertificateX509::DecodePublicKeyPEM(issuerPublicKey, &pubKey);
if (ER_OK != status) {
return status;
}
return ((PermissionConfigurator*)configurator)->RemoveMembership(String(reinterpret_cast<AJ_PCSTR>(serial), serialLen), &pubKey, String(reinterpret_cast<AJ_PCSTR>(issuerAki), issuerAkiLen));
}
QStatus AJ_CALL alljoyn_permissionconfigurator_startmanagement(alljoyn_permissionconfigurator configurator)
{
QCC_DbgTrace(("%s", __FUNCTION__));
return ((PermissionConfigurator*)configurator)->StartManagement();
}
QStatus AJ_CALL alljoyn_permissionconfigurator_endmanagement(alljoyn_permissionconfigurator configurator)
{
QCC_DbgTrace(("%s", __FUNCTION__));
return ((PermissionConfigurator*)configurator)->EndManagement();
}
QStatus AJ_CALL alljoyn_permissionconfigurator_signcertificate(alljoyn_permissionconfigurator configurator, AJ_PCSTR unsignedCertificate, AJ_PSTR* signedCertificate)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
PermissionConfigurator* pc = (PermissionConfigurator*)configurator;
CertificateX509 cert;
qcc::String certificateStr(unsignedCertificate);
status = cert.LoadPEM(certificateStr);
if (ER_OK != status) {
return status;
}
status = pc->SignCertificate(cert);
if (ER_OK != status) {
return status;
}
certificateStr = cert.GetPEM();
*signedCertificate = CreateStringCopy(certificateStr);
if (nullptr == *signedCertificate) {
return ER_OUT_OF_MEMORY;
}
return status;
}
AJ_API QStatus AJ_CALL alljoyn_permissionconfigurator_signmanifest(alljoyn_permissionconfigurator configurator,
AJ_PCSTR subjectCertificate,
AJ_PCSTR unsignedManifestXml,
AJ_PSTR* signedManifestXml)
{
QCC_DbgTrace(("%s", __FUNCTION__));
QStatus status;
PermissionConfigurator* pc = (PermissionConfigurator*)configurator;
CertificateX509 cert;
std::string input_str(unsignedManifestXml);
qcc::String certificate_str(subjectCertificate);
status = cert.LoadPEM(certificate_str);
if (ER_OK != status) {
return status;
}
status = pc->ComputeThumbprintAndSignManifestXml(cert, input_str);
if (ER_OK != status) {
return status;
}
*signedManifestXml = CreateStringCopy(input_str);
if (nullptr == *signedManifestXml) {
return ER_OUT_OF_MEMORY;
}
return status;
}
| 33.811125 | 194 | 0.677189 | [
"vector"
] |
545b1bc559eb572a3ba0d85b7528de3d375f114f | 5,034 | hpp | C++ | src/yael_io.hpp | LiliMeng/btrf | c13da164b11c5ada522fa40deeaffc32192c4bf9 | [
"BSD-2-Clause"
] | 9 | 2017-10-28T15:24:04.000Z | 2021-12-28T13:51:05.000Z | src/yael_io.hpp | LiliMeng/btrf | c13da164b11c5ada522fa40deeaffc32192c4bf9 | [
"BSD-2-Clause"
] | null | null | null | src/yael_io.hpp | LiliMeng/btrf | c13da164b11c5ada522fa40deeaffc32192c4bf9 | [
"BSD-2-Clause"
] | 3 | 2017-11-08T16:10:39.000Z | 2019-05-21T03:40:02.000Z | //
// yael_io.h
// OLNN
//
// Created by jimmy on 2016-12-01.
// Copyright (c) 2016 Nowhere Planet. All rights reserved.
//
#ifndef OLNN_yael_io_h
#define OLNN_yael_io_h
// file IO for http://corpus-texmex.irisa.fr/
#include <stdio.h>
#include <Eigen/Dense>
#include <assert.h>
using Eigen::MatrixXf;
using Eigen::Matrix;
class YaelIO
{
public:
// n: number
// d: dimension
static bool read_fvecs_file(const char *file_name,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & data);
static bool read_ivecs_file(const char *file_name,
Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & data);
// .fvecs
static bool write_fvecs_file(const char *file_name,
const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & data);
static bool write_ivecs_file(const char *file_name,
const Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & data);
private:
static float *fvec_new (long n);
static int *ivec_new(long n);
static int fvecs_read(const char *fname, int d, int n, float *v);
static int ivecs_read(const char *fname, int d, int n, int *v);
/*! Read the number of vectors in a file and their dimension
(vectors of same size). Output the number of bytes of the file. */
static long fvecs_fsize (const char * fname, int *d_out, int *n_out);
static long ivecs_fsize (const char * fname, int *d_out, int *n_out);
static long bvecs_fsize (const char * fname, int *d_out, int *n_out);
static long lvecs_fsize (const char * fname, int *d_out, int *n_out);
/*! write a set of vectors into an open file */
static int ivecs_fwrite(FILE *f, int d, int n, const int *v);
static int fvecs_fwrite(FILE *fo, int d, int n, const float *vf);
/*! write a vector into an open file */
static int ivec_fwrite(FILE *f, const int *v, int d);
static int fvec_fwrite(FILE *f, const float *v, int d);
};
class YaelIOUtil
{
public:
static void load_1k_dataset(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & base_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & learn_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & query_data,
Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & ground_truth);
static void load_1k_reorder_dataset(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & base_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & learn_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & query_data,
Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & ground_truth);
static void load_10k_dataset(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & base_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & learn_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & query_data,
Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & ground_truth);
static void load_10k_32dim_dataset(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & base_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & learn_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & query_data,
Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & ground_truth);
static void load_100k_dataset(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & base_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & learn_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & query_data,
Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & ground_truth);
static void load_1m_dataset(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & base_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & learn_data,
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & query_data,
Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> & ground_truth);
};
#endif
| 49.841584 | 124 | 0.605085 | [
"vector"
] |
545e8b0bdf0624a7f64a09ed4a335e48c045d312 | 2,533 | cpp | C++ | QuickSort_Viz/source/rects.cpp | AkashBujju/Practice_Excercises | 850ad69e8f77f5e34428f7264ca94fc54605b351 | [
"MIT"
] | null | null | null | QuickSort_Viz/source/rects.cpp | AkashBujju/Practice_Excercises | 850ad69e8f77f5e34428f7264ca94fc54605b351 | [
"MIT"
] | null | null | null | QuickSort_Viz/source/rects.cpp | AkashBujju/Practice_Excercises | 850ad69e8f77f5e34428f7264ca94fc54605b351 | [
"MIT"
] | null | null | null | #include "rects.h"
#include <cstdlib>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
extern float map(float src, float src_start, float src_end, float des_start, float des_end);
void Rects::init(GLint program, std::vector<glm::vec3> colors, std::vector<float> numbers) {
this->program = program;
this->per_width = (1.98f / numbers.size()) - (0.05f * (1.98f / numbers.size()));
float max_number = -99999999;
float min_number = +99999999;
for(unsigned int i = 0; i < numbers.size(); ++i) {
if(numbers[i] < min_number)
min_number = numbers[i];
if(numbers[i] > max_number)
max_number = numbers[i];
}
float start_x_pos = -0.98 + per_width / 2.0f;
for(unsigned int i = 0; i < numbers.size(); ++i) {
float height = map(numbers[i], min_number, max_number, -1, +1);
add_number(numbers[i], start_x_pos, height, colors[i]);
start_x_pos += per_width + (per_width * 0.05f);
}
}
void Rects::swap_positions(int index_0, int index_1) {
float index_0_pos = numbers[index_0].x_position;
float index_1_pos = numbers[index_1].x_position;
numbers[index_0].x_position = index_1_pos;
numbers[index_1].x_position = index_0_pos;
Number tmp = numbers[index_0];
numbers[index_0] = numbers[index_1];
numbers[index_1] = tmp;
}
void Rects::add_number(float num, float x_pos, float height, glm::vec3 color) {
Number number;
number.number = num;
number.x_position = x_pos;
float vertices[] = {
-per_width / 2, height, color.x, color.y, color.z,
+per_width / 2, height, color.x, color.y, color.z,
+per_width / 2, -0.98f, color.x, color.y, color.z,
-per_width / 2, height, color.x, color.y, color.z,
-per_width / 2, -0.98f, color.x, color.y, color.z,
+per_width / 2, -0.98f, color.x, color.y, color.z
};
glGenVertexArrays(1, &number.vao);
glGenBuffers(1, &vbo);
glBindVertexArray(number.vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(2 * sizeof(float)));
glEnableVertexAttribArray(1);
numbers.push_back(number);
}
void Rects::draw() {
for(unsigned int i = 0; i < numbers.size(); ++i) {
glUseProgram(program);
int position_loc = glGetUniformLocation(program, "x_pos");
if (position_loc != -1) {
glUniform1f(position_loc, numbers[i].x_position);
}
glBindVertexArray(numbers[i].vao);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
}
| 31.271605 | 96 | 0.694828 | [
"vector"
] |
546398288a5869ef5f68d960fe16d0e58af90b95 | 3,251 | cpp | C++ | SOCEngine/SOCEngine/Rendering/Postprocessing/DepthOfField.cpp | Jin02/SOCEngine | 7a04d914149783f54aecf2fbbc4e78a7325f0fbd | [
"MIT"
] | 14 | 2015-12-24T03:08:59.000Z | 2021-12-13T13:29:07.000Z | SOCEngine/SOCEngine/Rendering/Postprocessing/DepthOfField.cpp | Jin02/SOCEngine | 7a04d914149783f54aecf2fbbc4e78a7325f0fbd | [
"MIT"
] | 106 | 2015-08-16T10:32:47.000Z | 2018-10-08T19:01:44.000Z | SOCEngine/SOCEngine/Rendering/Postprocessing/DepthOfField.cpp | Jin02/SOCEngine | 7a04d914149783f54aecf2fbbc4e78a7325f0fbd | [
"MIT"
] | 2 | 2018-03-02T06:17:08.000Z | 2020-02-11T11:19:41.000Z | #include "DepthOfField.h"
#include "AutoBinder.hpp"
using namespace Device;
using namespace Rendering;
using namespace Rendering::Buffer;
using namespace Rendering::Shader;
using namespace Rendering::PostProcessing;
using namespace Rendering::Texture;
using namespace Rendering::Renderer;
using namespace Rendering::RenderState;
using namespace Rendering::Camera;
void DepthOfField::Initialize(Device::DirectX& dx, Manager::ShaderManager& shaderMgr, const Size<uint>& renderSize)
{
std::vector<ShaderMacro> psMacro{ dx.GetMSAAShaderMacro() };
FullScreen::InitParam param;
{
param.psMacros = nullptr;
param.psName = "DoF_InFullScreen_PS";
param.shaderFileName = "DepthOfField";
param.psMacros = &psMacro;
}
_screen.Initialize(dx, param, shaderMgr);
_paramCB.Initialize(dx);
_paramCB.UpdateSubResource(dx, ParamCBData());
_blur.Initialize(dx, shaderMgr);
{
_blurParamCBData.sigma = 1.5f;
_blurParamCBData.numPixelPerSide = 4.0f;
_blurParamCBData.blurSize = 4.0f;
_blurParamCBData.scale = 1.0f;
}
_blur.UpdateParamCB(dx, _blurParamCBData);
_blurredColorMap.Initialize(dx, renderSize, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_UNKNOWN, 0, 1, 1);
}
void DepthOfField::Destroy()
{
_screen.Destroy();
_blur.Destroy();
_blurredColorMap.Destroy();
_paramCB.Destroy();
}
void DepthOfField::UpdateParamCB(Device::DirectX& dx)
{
if(_dirty == false)
return;
_paramCB.UpdateSubResource(dx, _paramData);
_blur.UpdateParamCB(dx, _blurParamCBData);
_dirty = false;
}
void DepthOfField::Render(DirectX& dx, RenderTexture& outRT, const RenderTexture& inColorMap, const MainRenderingSystemParam&& mains, const Copy& copy, TempTextures& tempTextures)
{
// Blur color map
{
// down scale
{
AutoBinderSampler<PixelShader> sampler(dx, SamplerStateBindIndex(0), SamplerState::Linear);
copy.Render(dx, tempTextures.downScaledTextures[0], *inColorMap.GetTexture2D());
}
for (uint i = 0; i < 2; ++i)
_blur.Render(dx, tempTextures.downScaledTextures[0], tempTextures.downScaledTextures[0], tempTextures.halfSizeMap);
// up
{
AutoBinderSampler<PixelShader> sampler(dx, SamplerStateBindIndex(0), SamplerState::Linear);
copy.Render(dx, _blurredColorMap, *tempTextures.downScaledTextures[0].GetTexture2D());
}
}
AutoBinderSRV<PixelShader> color(dx, TextureBindIndex(0), inColorMap.GetTexture2D()->GetShaderResourceView());
AutoBinderSRV<PixelShader> blurred(dx, TextureBindIndex(1), _blurredColorMap.GetTexture2D()->GetShaderResourceView());
AutoBinderSRV<PixelShader> depth(dx, TextureBindIndex::GBuffer_Depth, mains.renderer.GetGBuffers().opaqueDepthBuffer.GetTexture2D().GetShaderResourceView());
AutoBinderCB<PixelShader> tbrParam(dx, ConstBufferBindIndex::TBRParam, mains.renderer.GetTBRParamCB());
AutoBinderCB<PixelShader> dofParam(dx, ConstBufferBindIndex(1), _paramCB);
AutoBinderCB<PixelShader> camParam(dx, ConstBufferBindIndex::Camera, mains.camera.GetCameraCB());
AutoBinderSampler<PixelShader> pointSampler(dx, SamplerStateBindIndex(0), SamplerState::Point);
AutoBinderSampler<PixelShader> linearSampler(dx,SamplerStateBindIndex(1), SamplerState::Linear);
_screen.Render(dx, outRT, true);
} | 34.585106 | 179 | 0.767764 | [
"render",
"vector"
] |
54720f7350eb33db0364dd9152714d57caaa53d9 | 2,728 | cpp | C++ | src/closed_loop_control/main.cpp | karanchawla/CallistoRover | c83c1eb155dd9045f296238252fe412894b93beb | [
"MIT"
] | 5 | 2019-03-16T09:41:42.000Z | 2021-09-07T05:04:33.000Z | src/closed_loop_control/main.cpp | karanchawla/CallistoRover | c83c1eb155dd9045f296238252fe412894b93beb | [
"MIT"
] | null | null | null | src/closed_loop_control/main.cpp | karanchawla/CallistoRover | c83c1eb155dd9045f296238252fe412894b93beb | [
"MIT"
] | 6 | 2017-05-15T15:30:51.000Z | 2020-07-24T13:48:57.000Z | #include "mbed.h"
#include "QEI.h"
#include <cstdlib>
#include <ros.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Int32.h>
#include "Sabertooth.h"
#include <cmath>
//Defining the pins
#ifdef TARGET_LPC1768
#define MOTORSHIELD_IN1 p23
#define MOTORSHIELD_IN2 p24
#define MOTORSHIELD_IN3 p29
#define MOTORSHIELD_IN4 p30
#define SPEEDPIN_A p13
#define SPEEDPIN_B p9
#define SPEEDPIN_C p10
#endif
//Encoder and Sabertooth object intializations
QEI wheelL(MOTORSHIELD_IN3, MOTORSHIELD_IN4, NC, 624);
QEI wheelR(MOTORSHIELD_IN1, MOTORSHIELD_IN2, NC, 624);
//Geometric parameters
float L=0.28;
float R=0.03;
// Max and min motor commands
int motor_cmd_max = 127;
int motor_cmd_min = -127;
//Mapping motor commands and angular velocities
float motor_max_angular_vel = 4233.334;
float motor_min_angular_vel = -666.667;
int encoderRes = 20000;
//Time interval for PID controller
float dt = 0.01;
// PID Gains
float Kp = 20;
float Ki = 0;
float Kd = 5;
float lwheel_tangent_vel_target = 0;
float rwheel_tangent_vel_target = 0;
//Subscribing to left wheel and right wheel velocities
void lwheel_tangent_vel_target_callback( const std_msgs::Float32& float_msg)
{
lwheel_tangent_vel_target = (float)float_msg.data;
}
void rwheel_tangent_vel_target_callback( const std_msgs::Float32& float_msg)
{
rwheel_tangent_vel_target = (float)float_msg.data;
}
//Subscriber initialization
ros::Subscriber<std_msgs::Float32> lwheel_tangent_vel_target_sub("lwheel_tangent_vel_target", lwheel_tangent_vel_target_callback);
ros::Subscriber<std_msgs::Float32> rwheel_tangent_vel_target_sub("rwheel_tangent_vel_target", rwheel_tangent_vel_target_callback);
float tangentToAngular(float tangent_vel)
{
//V = omega * R
float angularVel = tangent_vel/R;
return angularVel;
}
//TO DO:
// Add publisher defintions and maybe a method in class to get the required variables
// for publishing to ros out.
ros::NodeHandle nh;
rover Callisto(L,R,encoderRes,SPEEDPIN_A,129,9600,Kp,Ki,Kd,motor_cmd_max,motor_cmd_min,motor_max_angular_vel,motor_min_angular_vel,dt);
int main()
{
nh.initNode();
nh.subscribe(lwheel_tangent_vel_target_sub);
nh.subscribe(rwheel_tangent_vel_target_sub);
while(1)//Change to ros::ok() later on
{
nh.spinOnce();
wait_ms(1);
int lTarget, rTarget;
lTarget = tangentToAngular(lwheel_tangent_vel_target);
rTarget = tangentToAngular(rwheel_angular_vel_target);
Callisto.setTarget(lTarget,rTarget);
int pulseL, pulseR;
pulseL = wheelL.getPulses();
pulseR = wheelR.getPulses();
Callisto.computeEncoderVelocity(pulseL,pulseR);
Callisto.updateState();
Callisto.cmdVel();
nh.spinOnce();
wait_ms(1);
}
}
| 19.768116 | 135 | 0.756598 | [
"object"
] |
547e8c024aa6ffe5fbc05d80d4ebceb87531c07c | 1,216 | hpp | C++ | libs/core/include/fcppt/mpl/list/drop.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | libs/core/include/fcppt/mpl/list/drop.hpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | libs/core/include/fcppt/mpl/list/drop.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// 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 FCPPT_MPL_LIST_DROP_HPP_INCLUDED
#define FCPPT_MPL_LIST_DROP_HPP_INCLUDED
#include <fcppt/mpl/arg.hpp>
#include <fcppt/mpl/bind.hpp>
#include <fcppt/mpl/constant.hpp>
#include <fcppt/mpl/lambda.hpp>
#include <fcppt/mpl/size_type_concept.hpp>
#include <fcppt/mpl/list/at.hpp>
#include <fcppt/mpl/list/interval.hpp>
#include <fcppt/mpl/list/map.hpp>
#include <fcppt/mpl/list/object_concept.hpp>
#include <fcppt/mpl/list/size.hpp>
namespace fcppt::mpl::list
{
/**
\brief Removes some elements of a list from the beginning.
\ingroup fcpptmpl
If <code>List = list::object<L_1,...,L_n></code> then the result is
\code
list::object<L_{S+1},...,L_n>
\endcode
*/
template <fcppt::mpl::list::object_concept List, fcppt::mpl::size_type_concept S>
using drop = fcppt::mpl::list::map<
fcppt::mpl::list::interval<S, fcppt::mpl::list::size<List>>,
fcppt::mpl::bind<
fcppt::mpl::lambda<fcppt::mpl::list::at>,
fcppt::mpl::constant<List>,
fcppt::mpl::arg<1>>>;
}
#endif
| 30.4 | 81 | 0.703947 | [
"object"
] |
5484228dff22e66c5d1465e727a7fd3f2f2a9389 | 10,748 | cpp | C++ | extra_visitors/rosparam/src/reader.cpp | asherikov/ariles | cab7f0498f036fbb15ae152804ead56200af5d45 | [
"Apache-2.0"
] | 4 | 2020-03-08T17:09:25.000Z | 2021-05-02T08:53:14.000Z | extra_visitors/rosparam/src/reader.cpp | asherikov/ariles | cab7f0498f036fbb15ae152804ead56200af5d45 | [
"Apache-2.0"
] | 12 | 2019-09-19T09:35:51.000Z | 2021-07-08T18:49:20.000Z | extra_visitors/rosparam/src/reader.cpp | asherikov/ariles | cab7f0498f036fbb15ae152804ead56200af5d45 | [
"Apache-2.0"
] | 3 | 2020-06-02T08:14:47.000Z | 2021-05-02T08:54:09.000Z | /**
@file
@author Alexander Sherikov
@copyright 2018 Alexander Sherikov, Licensed under the Apache License, Version 2.0.
(see @ref LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
@brief
*/
#include <boost/lexical_cast.hpp>
#include "common.h"
namespace ariles2
{
namespace ns_rosparam
{
namespace impl
{
class ARILES2_VISIBILITY_ATTRIBUTE Reader : public ariles2::ns_rosparam::ImplBase
{
public:
std::vector<XmlRpc::XmlRpcValue::iterator> iterator_stack_;
public:
explicit Reader(const ::ros::NodeHandle &nh)
{
nh_ = nh;
}
};
} // namespace impl
} // namespace ns_rosparam
} // namespace ariles2
namespace ariles2
{
namespace ns_rosparam
{
Reader::Reader(const ::ros::NodeHandle &nh)
{
impl_ = ImplPtr(new Impl(nh));
}
void Reader::startMap(const SizeLimitEnforcementType limit_type, const std::size_t min, const std::size_t max)
{
ARILES2_TRACE_FUNCTION;
if (XmlRpc::XmlRpcValue::TypeStruct == impl_->getRawNode().getType())
{
checkSize(limit_type, impl_->getRawNode().size(), min, max);
}
else
{
ARILES2_PERSISTENT_ASSERT(0 == min and min == max, "Expected struct.");
}
}
bool Reader::startMapEntry(const std::string &child_name)
{
if (impl_->node_stack_.empty())
{
impl_->root_name_ = child_name;
impl_->nh_.getParam(impl_->root_name_, impl_->root_value_);
impl_->node_stack_.push_back(&impl_->root_value_);
return (true);
}
XmlRpc::XmlRpcValue &node = impl_->getRawNode();
if ((XmlRpc::XmlRpcValue::TypeStruct == node.getType()) && (true == node.hasMember(child_name)))
{
impl_->node_stack_.push_back(NodeWrapper(&(node[child_name])));
return (true);
}
return (false);
}
void Reader::endMapEntry()
{
impl_->node_stack_.pop_back();
}
bool Reader::startIteratedMap(
const SizeLimitEnforcementType limit_type,
const std::size_t min,
const std::size_t max)
{
ARILES2_TRACE_FUNCTION;
if (XmlRpc::XmlRpcValue::TypeStruct == impl_->getRawNode().getType())
{
checkSize(limit_type, impl_->getRawNode().size(), min, max);
impl_->iterator_stack_.push_back(impl_->getRawNode().begin());
return (true);
}
ARILES2_PERSISTENT_ASSERT(0 == min and min == max, "Expected struct.");
return (false);
}
bool Reader::startIteratedMapElement(std::string &entry_name)
{
if (impl_->iterator_stack_.back() != impl_->getRawNode().end())
{
impl_->node_stack_.push_back(&impl_->iterator_stack_.back()->second);
entry_name = impl_->iterator_stack_.back()->first;
return (true);
}
return (false);
}
void Reader::endIteratedMapElement()
{
++impl_->iterator_stack_.back();
impl_->node_stack_.pop_back();
}
void Reader::endIteratedMap()
{
ARILES2_ASSERT(
impl_->iterator_stack_.back() == impl_->getRawNode().end(),
"End of iterated map has not been reached.");
impl_->iterator_stack_.pop_back();
}
std::size_t Reader::startArray()
{
ARILES2_ASSERT(XmlRpc::XmlRpcValue::TypeArray == impl_->getRawNode().getType(), "Expected array.");
std::size_t size = impl_->getRawNode().size();
impl_->node_stack_.push_back(NodeWrapper(0, size));
return (size);
}
void Reader::startArrayElement()
{
ARILES2_ASSERT(
impl_->node_stack_.back().index_ < impl_->node_stack_.back().size_,
"Internal error: namevalue.has more elements than expected.");
}
void Reader::endArrayElement()
{
ARILES2_ASSERT(true == impl_->node_stack_.back().isArray(), "Internal error: expected array.");
++impl_->node_stack_.back().index_;
}
void Reader::endArray()
{
impl_->node_stack_.pop_back();
}
bool Reader::startRoot(const std::string &name)
{
ARILES2_TRACE_FUNCTION;
if (true == name.empty())
{
return (startMapEntry("ariles"));
}
return (startMapEntry(name));
}
void Reader::endRoot(const std::string & /*name*/)
{
ARILES2_TRACE_FUNCTION;
endMapEntry();
}
#define ARILES2_BASIC_TYPE(type) \
void Reader::readElement(type &element) \
{ \
ARILES2_ASSERT(impl_->getRawNode().getType() == XmlRpc::XmlRpcValue::TypeInt, "Integer type expected."); \
int tmp_value = static_cast<int>(impl_->getRawNode()); \
ARILES2_ASSERT( \
static_cast<int64_t>(tmp_value) <= std::numeric_limits<type>::max() \
&& static_cast<int64_t>(tmp_value) >= std::numeric_limits<type>::min(), \
"Value is out of range."); \
element = static_cast<type>(tmp_value); \
}
ARILES2_MACRO_SUBSTITUTE(ARILES2_BASIC_SIGNED_INTEGER_TYPES_LIST)
#undef ARILES2_BASIC_TYPE
#define ARILES2_BASIC_TYPE(type) \
void Reader::readElement(type &element) \
{ \
ARILES2_ASSERT(impl_->getRawNode().getType() == XmlRpc::XmlRpcValue::TypeInt, "Integer type expected."); \
int tmp_value = static_cast<int>(impl_->getRawNode()); \
ARILES2_ASSERT(tmp_value >= 0, "Expected positive value."); \
ARILES2_ASSERT(static_cast<uint64_t>(tmp_value) <= std::numeric_limits<type>::max(), "Value is too large."); \
element = static_cast<type>(tmp_value); \
}
ARILES2_MACRO_SUBSTITUTE(ARILES2_BASIC_UNSIGNED_INTEGER_TYPES_LIST)
#undef ARILES2_BASIC_TYPE
#define ARILES2_BASIC_TYPE(type) \
void Reader::readElement(type &element) \
{ \
switch (impl_->getRawNode().getType()) \
{ \
case XmlRpc::XmlRpcValue::TypeDouble: \
element = static_cast<double>(impl_->getRawNode()); \
break; \
case XmlRpc::XmlRpcValue::TypeString: \
element = boost::lexical_cast<double>(static_cast<std::string>(impl_->getRawNode())); \
break; \
case XmlRpc::XmlRpcValue::TypeInt: \
element = static_cast<int>(impl_->getRawNode()); \
break; \
default: \
ARILES2_THROW("Could not convert value to type."); \
break; \
} \
}
ARILES2_MACRO_SUBSTITUTE(ARILES2_BASIC_REAL_TYPES_LIST)
#undef ARILES2_BASIC_TYPE
void Reader::readElement(std::string &element)
{
element = static_cast<std::string>(impl_->getRawNode());
}
void Reader::readElement(bool &element)
{
switch (impl_->getRawNode().getType())
{
case XmlRpc::XmlRpcValue::TypeString:
element = boost::lexical_cast<bool>(static_cast<std::string>(impl_->getRawNode()));
break;
case XmlRpc::XmlRpcValue::TypeBoolean:
element = static_cast<bool>(impl_->getRawNode());
break;
case XmlRpc::XmlRpcValue::TypeInt:
element = static_cast<int>(impl_->getRawNode()) > 0;
break;
default:
ARILES2_THROW("Could not convert value to boolean.");
break;
}
}
} // namespace ns_rosparam
} // namespace ariles2
| 41.022901 | 120 | 0.414682 | [
"vector"
] |
548876e87d01fa61de02d30ca078e84fdf426e9a | 4,508 | cpp | C++ | src/ui/widgets/group.cpp | CommitteeOfZero/impacto | 87e0aa27d59d8f350849dfb20048679b2a3db1e3 | [
"0BSD"
] | 45 | 2020-02-01T19:10:13.000Z | 2022-03-11T01:45:52.000Z | src/ui/widgets/group.cpp | Enorovan/impacto | 807c5247dca2720e3e1205fca4724ad1fafb1ab4 | [
"0BSD"
] | 7 | 2020-01-26T17:30:00.000Z | 2021-09-26T10:00:46.000Z | src/ui/widgets/group.cpp | Enorovan/impacto | 807c5247dca2720e3e1205fca4724ad1fafb1ab4 | [
"0BSD"
] | 11 | 2020-02-01T23:01:50.000Z | 2021-12-15T14:39:27.000Z | #include "group.h"
#include "../../profile/game.h"
#include "../../inputsystem.h"
#include "../../renderer2d.h"
namespace Impacto {
namespace UI {
namespace Widgets {
Group::Group(Menu* ctx) {
MenuContext = ctx;
Bounds = RectF(0.0f, 0.0f, 0.0f, 0.0f);
RenderingBounds =
RectF(0.0f, 0.0f, Profile::DesignWidth, Profile::DesignHeight);
}
Group::Group(Menu* ctx, glm::vec2 pos) : Group(ctx) {
Bounds = RectF(pos.x, pos.y, 0.0f, 0.0f);
}
void Group::Add(Widget* widget) { Children.push_back(widget); }
void Group::Add(Widget* widget, FocusDirection dir) {
FocusDirection oppositeDir;
switch (dir) {
case FDIR_LEFT:
oppositeDir = FDIR_RIGHT;
break;
case FDIR_RIGHT:
oppositeDir = FDIR_LEFT;
break;
case FDIR_UP:
oppositeDir = FDIR_DOWN;
break;
case FDIR_DOWN:
oppositeDir = FDIR_UP;
break;
}
if (LastFocusableElementId != -1) {
auto el = Children.at(LastFocusableElementId);
el->SetFocus(widget, dir);
widget->SetFocus(el, oppositeDir);
if (!FocusStart[dir]) FocusStart[dir] = el;
if (!FocusStart[oppositeDir]) FocusStart[oppositeDir] = el;
} else {
FirstFocusableElementId = Children.size();
}
Add(widget);
LastFocusableElementId = Children.size() - 1;
if (WrapFocus) {
auto firstEl = Children.at(FirstFocusableElementId);
widget->SetFocus(firstEl, dir);
firstEl->SetFocus(widget, oppositeDir);
FocusStart[oppositeDir] = widget;
}
}
WidgetType Group::GetType() { return WT_GROUP; }
void Group::UpdateInput() {
for (const auto& el : Children) {
if (el->GetType() == WT_NORMAL) {
el->UpdateInput();
if (el->Enabled && el->Hovered &&
Input::CurrentInputDevice == Input::IDEV_Mouse) {
if (MenuContext->CurrentlyFocusedElement)
MenuContext->CurrentlyFocusedElement->HasFocus = false;
el->HasFocus = true;
MenuContext->CurrentlyFocusedElement = el;
}
}
}
}
void Group::Update(float dt) {
if (IsShown) {
Widget::Update(dt);
if ((FocusLock && HasFocus) || !FocusLock) {
UpdateInput();
}
bool isFocused = false;
for (const auto& el : Children) {
if (!FocusLock) {
isFocused = isFocused ||
(el == MenuContext->CurrentlyFocusedElement ? true : false);
HasFocus = isFocused;
}
el->Update(dt);
}
}
}
void Group::Render() {
if (IsShown) {
Renderer2D::EnableScissor();
Renderer2D::SetScissorRect(RenderingBounds);
for (const auto& el : Children) {
if (RenderingBounds.Intersects(el->Bounds)) {
auto tint = el->Tint;
el->Tint *= Tint;
el->Render();
el->Tint = tint;
}
}
Renderer2D::DisableScissor();
}
}
Widget* Group::GetFocus(FocusDirection dir) {
if (!Children.empty()) {
if (dir == FDIR_DOWN || dir == FDIR_RIGHT)
return Children.front();
else if (dir == FDIR_UP || dir == FDIR_LEFT)
return Children.back();
} else
return 0;
}
void Group::Show() {
Tint.a = 1.0f;
IsShown = true;
if (FocusLock) {
HasFocus = true;
if (!Children.empty()) {
PreviousFocusElement = MenuContext->CurrentlyFocusedElement;
MenuContext->CurrentlyFocusedElement = 0;
memcpy(PreviousFocusStart, MenuContext->FocusStart,
sizeof(MenuContext->FocusStart));
memcpy(MenuContext->FocusStart, FocusStart,
sizeof(MenuContext->FocusStart));
}
}
for (const auto& el : Children) {
el->Show();
}
}
void Group::Hide() {
Tint.a = 0.0f;
IsShown = false;
HasFocus = false;
if (FocusLock) {
if (MenuContext->CurrentlyFocusedElement)
MenuContext->CurrentlyFocusedElement->HasFocus = false;
MenuContext->CurrentlyFocusedElement = PreviousFocusElement;
memcpy(MenuContext->FocusStart, PreviousFocusStart,
sizeof(MenuContext->FocusStart));
}
for (const auto& el : Children) {
el->Hide();
}
}
void Group::Move(glm::vec2 relativePosition) {
for (const auto& el : Children) {
el->Move(relativePosition);
}
Widget::Move(relativePosition);
}
void Group::MoveTo(glm::vec2 pos) {
auto relativePosition = pos - glm::vec2(Bounds.X, Bounds.Y);
for (const auto& el : Children) {
el->Move(relativePosition);
}
Widget::MoveTo(pos);
}
void Group::Clear() {
for (auto el : Children) {
delete el;
}
Children.clear();
LastFocusableElementId = -1;
}
} // namespace Widgets
} // namespace UI
} // namespace Impacto | 24.769231 | 80 | 0.626886 | [
"render"
] |
5490e7b369d3a799d0b62ed5557511db10e58af2 | 1,541 | hpp | C++ | data/test/cpp/5490e7b369d3a799d0b62ed5557511db10e58af2Core.hpp | harshp8l/deep-learning-lang-detection | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/test/cpp/5490e7b369d3a799d0b62ed5557511db10e58af2Core.hpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 5 | 2018-03-29T11:50:46.000Z | 2021-04-26T13:33:18.000Z | data/test/cpp/5490e7b369d3a799d0b62ed5557511db10e58af2Core.hpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | #ifndef ___INANITY_OIL_CORE_HPP___
#define ___INANITY_OIL_CORE_HPP___
#include "oil.hpp"
#include "../inanity/script/script.hpp"
#include "../inanity/script/np/np.hpp"
#include "../inanity/meta/decl.hpp"
#include "../inanity/String.hpp"
BEGIN_INANITY
class FileSystem;
class File;
END_INANITY
BEGIN_INANITY_SCRIPT
class Any;
END_INANITY_SCRIPT
BEGIN_INANITY_NP
class State;
END_INANITY_NP
BEGIN_INANITY_OIL
class ClientRepo;
class RemoteRepo;
class ScriptRepo;
class EntitySchemeManager;
class Engine;
class Core : public Object
{
private:
ptr<Script::Np::State> scriptState;
ptr<FileSystem> nativeFileSystem;
ptr<EntitySchemeManager> entitySchemeManager;
String profilePath;
ptr<FileSystem> profileFileSystem;
ptr<Engine> engine;
public:
Core(ptr<Script::Np::State> scriptState);
ptr<Script::Any> GetRootNamespace() const;
ptr<FileSystem> GetNativeFileSystem() const;
ptr<FileSystem> GetProfileFileSystem() const;
void SetProfilePath(const String& profilePath);
void Init();
ptr<ClientRepo> CreateLocalClientRepo(const String& fileName);
ptr<ClientRepo> CreateTempClientRepo();
ptr<ClientRepo> CreateMemoryClientRepo();
ptr<RemoteRepo> CreateUrlRemoteRepo(const String& url);
ptr<RemoteRepo> CreateLocalRemoteRepo(const String& fileName);
ptr<RemoteRepo> CreateTempRemoteRepo();
ptr<RemoteRepo> CreateMemoryRemoteRepo();
ptr<ScriptRepo> CreateScriptRepo(ptr<ClientRepo> clientRepo, ptr<RemoteRepo> remoteRepo);
ptr<Engine> GetEngine() const;
META_DECLARE_CLASS(Core);
};
END_INANITY_OIL
#endif
| 20.012987 | 90 | 0.791694 | [
"object"
] |
5495c9314b97a1005a48e7fd2c11239ba632bf6b | 16,315 | hh | C++ | aspects/thermal/GunnsThermalPhaseChangeBattery.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 18 | 2020-01-23T12:14:09.000Z | 2022-02-27T22:11:35.000Z | aspects/thermal/GunnsThermalPhaseChangeBattery.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 39 | 2020-11-20T12:19:35.000Z | 2022-02-22T18:45:55.000Z | aspects/thermal/GunnsThermalPhaseChangeBattery.hh | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 7 | 2020-02-10T19:25:43.000Z | 2022-03-16T01:10:00.000Z | #ifndef GunnsThermalPhaseChangeBattery_EXISTS
#define GunnsThermalPhaseChangeBattery_EXISTS
/**
@file
@brief GUNNS Thermal Phase Change Battery Link declarations
@defgroup TSM_GUNNS_THERMAL_PHASE_CHANGE_BATTERY GUNNS Thermal Phase Change Battery Link
@ingroup TSM_GUNNS_THERMAL
@copyright Copyright 2019 United States Government as represented by the Administrator of the
National Aeronautics and Space Administration. All Rights Reserved.
@details
PURPOSE:
(This models a Phase Change Thermal Battery for heat storage. The battery casing contains a mass
of material with a significant thermal capacity. This link can model the thermal capacity (as
its mass times the specific heat) for two different phases of matter of the material (typically
ice & liquid), and the heat of phase change between the phases. The specific heats and heat of
phase change are provided as configuration data, so the link can model any kind of material and
any two phases. The link labels these phases as "hot" and "cold" since they can be applied to
any arbitrary paring of phases. Liquid (hot) and Ice (cold) are the most typical, but you can
use any phases.
When all of the phase-change material is in the same phase, either below (cold phase) or above
(hot phase) the phase change temperature, this link acts like a regular thermal capacitor,
applies a capacitance to the Port 0 node, and heat into or out of the node changes its
temperature. However while in mixed-phase, the link switches to a potential source to constrain
the node to the phase change temperature, and any heat into or out of the node goes into phase
change.
This is a 1-port link. We do away with the Port 1 in other capacitor-type links since it's never
used in the thermal aspect.
There is a leak malfunction for leaking out the hotter phase when it is present. The hotter
phase is usually the less viscous and more prone to escape the battery through cracks in the
enclosure, etc.)
REFERENCE:
()
ASSUMPTIONS AND LIMITATIONS:
((Internal fluid properties like pressure & thermal expansion are not modeled)
(The phase change temperature is constant)
(The specific heats are constant)
(The entire battery & phase-change medium always has uniform temperature))
LIBRARY_DEPENDENCY:
(GunnsThermalPhaseChangeBattery.o)
PROGRAMMERS:
(
((Jason Harvey) (CACI) (Novenber 2016) (Initial))
)
@{
*/
#include "core/GunnsBasicLink.hh"
#include "aspects/thermal/GunnsThermalCapacitor.hh"
#include "software/SimCompatibility/TsSimCompatibility.hh"
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Thermal Phase Change Battery link Configuration Data
///
/// @details The sole purpose of this class is to provide a data structure for the Thermal Phase
/// Change Battery link configuration data.
////////////////////////////////////////////////////////////////////////////////////////////////////
class GunnsThermalPhaseChangeBatteryConfigData : public GunnsBasicLinkConfigData
{
public:
double mPhaseChangeTemperature; /**< (K) trick_chkpnt_io(**) Temperature at which the thermal battery medium changes phase. */
double mPhaseChangeHeat; /**< (J/g) trick_chkpnt_io(**) Heat of phase change of the thermal battery medium. */
double mHotPhaseSpecificHeat; /**< (J/g/K) trick_chkpnt_io(**) Specific heat of the thermal battery medium in the hotter phase. */
double mColdPhaseSpecificHeat; /**< (J/g/K) trick_chkpnt_io(**) Specific heat of the thermal battery medium in the colder phase. */
double mStructureCapacitance; /**< (J/K) trick_chkpnt_io(**) Thermal capacitance of non-phase changing structure. */
/// @brief Default constructs this Thermal Phase Change Battery link configuration data.
GunnsThermalPhaseChangeBatteryConfigData(const std::string& name = "",
GunnsNodeList* nodes = 0,
const double phaseChangeTemperature = 0.0,
const double phaseChangeHeat = 0.0,
const double hotPhaseSpecificHeat = 0.0,
const double coldPhaseSpecificHeat = 0.0,
const double structureCapacitance = 0.0);
/// @brief Default destructs this Thermal Phase Change Battery link configuration data.
virtual ~GunnsThermalPhaseChangeBatteryConfigData();
private:
/// @brief Copy constructor unavailable since declared private and not implemented.
GunnsThermalPhaseChangeBatteryConfigData(const GunnsThermalPhaseChangeBatteryConfigData& that);
/// @brief Assignment operator unavailable since declared private and not implemented.
GunnsThermalPhaseChangeBatteryConfigData& operator =(const GunnsThermalPhaseChangeBatteryConfigData&);
};
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Thermal Phase Change Battery link Input Data
///
/// @details The sole purpose of this class is to provide a data structure for the Thermal Phase
/// Change Battery link input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
class GunnsThermalPhaseChangeBatteryInputData : public GunnsBasicLinkInputData
{
public:
double mMass; /**< (kg) trick_chkpnt_io(**) Initial mass of the phase-changing thermal battery medium. */
double mTemperature; /**< (K) trick_chkpnt_io(**) Initial temperature of the thermal battery medium. */
double mHotPhaseFraction; /**< (--) trick_chkpnt_io(**) Initial mass fraction (0-1) of the phase-changing thermal battery medium in the hotter phase. */
bool mMalfHotPhaseLeakFlag; /**< (--) trick_chkpnt_io(**) Initial hot phase mass leak malfunction activation flag. */
double mMalfHotPhaseLeakRate; /**< (kg/s) trick_chkpnt_io(**) Initial hot phase mass leak malfunction leak rate. */
/// @brief Default constructs this Thermal Phase Change Battery link input data.
GunnsThermalPhaseChangeBatteryInputData(const double mass = 0.0,
const double temperature = 0.0,
const double hotPhaseFraction = 0.0,
const bool malfHotPhaseLeakFlag = false,
const double malfHotPhaseLeakRate = 0.0);
/// @brief Default destructs this Thermal Phase Change Battery link input data.
virtual ~GunnsThermalPhaseChangeBatteryInputData();
private:
/// @details Copy constructor unavailable since declared private and not implemented.
GunnsThermalPhaseChangeBatteryInputData(const GunnsThermalPhaseChangeBatteryInputData& that);
/// @details Assignment operator unavailable since declared private and not implemented.
GunnsThermalPhaseChangeBatteryInputData& operator =(const GunnsThermalPhaseChangeBatteryInputData&);
};
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief GUNNS Thermal Phase Change Battery Link
///
/// @details Refer to class Purpose.
////////////////////////////////////////////////////////////////////////////////////////////////////
class GunnsThermalPhaseChangeBattery : public GunnsBasicLink
{
TS_MAKE_SIM_COMPATIBLE(GunnsThermalPhaseChangeBattery);
public:
/// @name Malfunctions.
/// @{
/// @details Malfunctions are public to allow access from the Trick events processor.
bool mMalfHotPhaseLeakFlag; /**< (--) Hot phase mass leak malfunction activation flag. */
double mMalfHotPhaseLeakRate; /**< (kg/s) Hot phase mass leak malfunction leak rate. */
/// @}
/// @brief Default Constructor
GunnsThermalPhaseChangeBattery();
/// @brief Default Destructor
virtual ~GunnsThermalPhaseChangeBattery();
/// @brief Initialize method
void initialize(const GunnsThermalPhaseChangeBatteryConfigData& configData,
const GunnsThermalPhaseChangeBatteryInputData& inputData,
std::vector<GunnsBasicLink*>& networkLinks,
const int port0);
/// @brief Updates the link contributions to the network system of equations.
virtual void step(const double dt);
/// @brief Computes & transports flows resulting from the network solution.
virtual void computeFlows(const double dt);
/// @brief Updates the link admittance for inclusion in the network solution.
virtual void updateState(const double dt);
/// @brief Updates the battery mass & phase in response to flows.
virtual void updateFlux(const double dt, const double flux);
/// @brief Sets and resets the hot phase leak malfunction.
void setMalfHotPhaseLeak(const bool flag = false, const double rate = 0.0);
/// @brief Returns the uniform temperature of the battery material.
double getTemperature() const;
/// @brief Returns the mass fraction of the hot phase of the phase-change material.
double getHotPhaseFraction() const;
/// @brief Returns the actual leak rate of the hot phase out of the battery.
double getActualLeakRate() const;
protected:
double mPhaseChangeTemperature; /**< (K) trick_chkpnt_io(**) Temperature at which the thermal battery medium changes phase. */
double mPhaseChangeHeat; /**< (J/g) trick_chkpnt_io(**) Heat of phase change of the thermal battery medium. */
double mHotPhaseSpecificHeat; /**< (J/g/K) trick_chkpnt_io(**) Specific heat of the thermal battery medium in the hotter phase. */
double mColdPhaseSpecificHeat; /**< (J/g/K) trick_chkpnt_io(**) Specific heat of the thermal battery medium in the colder phase. */
double mStructureCapacitance; /**< (J/K) trick_chkpnt_io(**) Thermal capacitance of non-phase changing structure. */
double mMass; /**< (kg) Mass of the phase-changing thermal battery medium. */
double mTemperature; /**< (K) Temperature of the thermal battery medium. */
double mHotPhaseFraction; /**< (--) Mass fraction (0-1) of the phase-changing thermal battery medium in the hotter phase. */
double mActualLeakRate; /**< (kg/s) Actual leak rate of hot phase out of the battery. */
double mExternalHeatFlux[GunnsThermalCapacitor::NUM_EXT_HEATFLUXES]; /**< (W) trick_chkpnt_io(**) Array of external heat fluxes into the battery. */
double mSumExternalHeatFluxes; /**< (W) trick_chkpnt_io(**) Sum of the external heat fluxes. */
double mAdmittance; /**< (W/K) trick_chkpnt_io(**) Current value of link admittance. */
static const double mIdealAdmittance; /**< ** (W/K) trick_chkpnt_io(**) Admittance constant for mixed-phase operation. */
/// @brief Validates the given link configuration and input data.
void validate(const GunnsThermalPhaseChangeBatteryConfigData& configData,
const GunnsThermalPhaseChangeBatteryInputData& inputData) const;
/// @brief Virtual method for derived links to perform their restart functions.
virtual void restartModel();
/// @brief Computes and returns the capacitance effect value.
virtual double computeCapacitance() const;
/// @brief Computes flux across the link.
virtual void computeFlux();
/// @brief Computes power across the link.
virtual void computePower();
/// @brief Adds fluxes to nodes.
virtual void transportFlux(const int fromPort = 0, const int toPort = 1);
/// @brief Updates the hot phase mass fraction.
virtual void updatePhaseFraction(const double dt);
/// @brief Models the hot phase leak malfunction.
virtual void updateMassLeak(const double dt);
/// @brief Clears the external heat flux terms.
void zeroExternalFluxes();
/// @brief Sum the external heat fluxes.
void sumExternalFluxes();
/// @brief Sets various terms in the link and node to the given temperature.
void setTemperature(const double temperature);
private:
/// @details Define the number of ports this link class has. All objects of the same link
/// class always have the same number of ports. We use an enum rather than a
/// static const int so that we can reuse the NPORTS name and allow each class to
/// define its own value.
enum {NPORTS = 1};
/// @brief Copy constructor unavailable since declared private and not implemented.
GunnsThermalPhaseChangeBattery(const GunnsThermalPhaseChangeBattery& that);
/// @brief Assignment operator unavailable since declared private and not implemented.
GunnsThermalPhaseChangeBattery& operator =(const GunnsThermalPhaseChangeBattery& that);
};
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] flag (--) Malfunction activation flag, true activates.
/// @param[in] rate (kg/s) Malfunction leak rate value.
///
/// @details Sets the hot-phase leak rate malfunction to the given state. Calling this method with
/// default arguments resets the malfunction.
////////////////////////////////////////////////////////////////////////////////////////////////////
inline void GunnsThermalPhaseChangeBattery::setMalfHotPhaseLeak(const bool flag,
const double rate)
{
mMalfHotPhaseLeakFlag = flag;
mMalfHotPhaseLeakRate = rate;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @returns double (K) Uniform temperature of the thermal battery.
///
/// @details Returns mTemperature.
////////////////////////////////////////////////////////////////////////////////////////////////////
inline double GunnsThermalPhaseChangeBattery::getTemperature() const
{
return mTemperature;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @returns double (--) Mass fraction (0-1) of the phase-changing thermal battery medium in the
/// hotter phase.
///
/// @details Returns mHotPhaseFraction.
////////////////////////////////////////////////////////////////////////////////////////////////////
inline double GunnsThermalPhaseChangeBattery::getHotPhaseFraction() const
{
return mHotPhaseFraction;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @returns double (kg/s) Actual leak rate of hot phase out of the battery.
///
/// @details Returns mActualLeakRate.
////////////////////////////////////////////////////////////////////////////////////////////////////
inline double GunnsThermalPhaseChangeBattery::getActualLeakRate() const
{
return mActualLeakRate;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Computes flux across the link.
////////////////////////////////////////////////////////////////////////////////////////////////////
inline void GunnsThermalPhaseChangeBattery::computeFlux()
{
mFlux = mPotentialDrop * mAdmittanceMatrix[0] - mSourceVector[0];
}
#endif
| 59.981618 | 166 | 0.595587 | [
"vector",
"model"
] |
54a79a96d9e434bf871ac059bd63c4d26b9afaed | 395 | cpp | C++ | src/test_app/constructors/player.cpp | rationalis-petra/mecs | 461eacff6b9449eb1a6bdf2f9faf45c6d2265d65 | [
"MIT"
] | null | null | null | src/test_app/constructors/player.cpp | rationalis-petra/mecs | 461eacff6b9449eb1a6bdf2f9faf45c6d2265d65 | [
"MIT"
] | null | null | null | src/test_app/constructors/player.cpp | rationalis-petra/mecs | 461eacff6b9449eb1a6bdf2f9faf45c6d2265d65 | [
"MIT"
] | null | null | null | #include <string>
#include "engine.hpp"
#include "test_app.hpp"
using std::string;
void make_player(World& world) {
world.create_entity()
.add_component<Model>(new Model(world, "container.jpg", "player", {0, 0, 0}))
.add_component<Input>(new Input)
.add_component<RigidBody>(new RigidBody(0, 0, 0))
.add_component<Camera>(new Camera(0.5235987756f, 1.57079632679f, 5.0f));
}
| 26.333333 | 81 | 0.696203 | [
"model"
] |
54b2ce92bf2ea85d7879ee7d42c03e7313d8e0e2 | 1,089 | cpp | C++ | p130/p130_2.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | 1 | 2019-10-07T05:00:21.000Z | 2019-10-07T05:00:21.000Z | p130/p130_2.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | p130/p130_2.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | class Solution {
public:
void solve(vector<vector<char>>& board) {
int n = board.size();
if (n == 0)
return;
int m = board[0].size();
if (m == 0)
return;
for (int i = 0; i < n; ++i)
{
dfs(i,0,n,m,board);
dfs(i,m-1,n,m,board);
}
for (int i = 0; i < m; ++i)
{
dfs(0,i,n,m,board);
dfs(n-1,i,n,m,board);
}
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (board[i][j] == 'O')
board[i][j] = 'X';
else
if (board[i][j] == 'A')
board[i][j] = 'O';
}
void dfs(int x,int y,int n,int m,vector<vector<char>>& board)
{
if (board[x][y] == 'O')
{
board[x][y] = 'A';
if (x<n-1)
dfs(x+1,y,n,m,board);
if (x>0)
dfs(x-1,y,n,m,board);
if (y<m-1)
dfs(x,y+1,n,m,board);
if (y>0)
dfs(x,y-1,n,m,board);
}
}
};
| 22.22449 | 65 | 0.332415 | [
"vector"
] |
2a5e5b34884b1cbe82b173381a0752a281ca2ded | 1,080 | hpp | C++ | third_party/amo/amo/object.hpp | amoylel/NCUI | a3b315ebf97d9903766efdafa42c24d4212d5ad6 | [
"BSD-2-Clause"
] | 24 | 2018-11-20T14:45:57.000Z | 2021-12-30T13:38:42.000Z | third_party/amo/amo/object.hpp | amoylel/NCUI | a3b315ebf97d9903766efdafa42c24d4212d5ad6 | [
"BSD-2-Clause"
] | null | null | null | third_party/amo/amo/object.hpp | amoylel/NCUI | a3b315ebf97d9903766efdafa42c24d4212d5ad6 | [
"BSD-2-Clause"
] | 11 | 2018-11-29T00:09:14.000Z | 2021-11-23T08:13:17.000Z | #ifndef AMO_OBJECT_HPP__
#define AMO_OBJECT_HPP__
#include <amo/uid.hpp>
#include <amo/logger.hpp>
#include <set>
namespace amo {
class object {
public:
object() : valid_object(true) { }
virtual ~object() {}
operator bool() {
return is_valid();
}
object& operator=(bool valid_) {
set_valid(!valid_);
return *this;
}
void set_last_error(int64_t last_error_) {
last_error = last_error_;
}
const int64_t& get_last_error() const {
return last_error;
}
amo::uid get_object_id() const {
return object_id;
}
void set_valid(bool invalid = true) {
valid_object = invalid;
}
bool is_valid() const {
return valid_object;
}
protected:
bool valid_object;
int64_t last_error;
amo::uid object_id;
};
}
#endif // AMO_OBJECT_HPP__
| 18.947368 | 50 | 0.491667 | [
"object"
] |
2a688b441e30f3e8e3aa293c8ca77cf0d247bcb0 | 4,554 | cpp | C++ | source/file/sequence/GenBankFile.cpp | Frangou-Lab/libgene | 28d11eea1489dd473f8376ff6475b53f12594fe6 | [
"Apache-2.0"
] | null | null | null | source/file/sequence/GenBankFile.cpp | Frangou-Lab/libgene | 28d11eea1489dd473f8376ff6475b53f12594fe6 | [
"Apache-2.0"
] | null | null | null | source/file/sequence/GenBankFile.cpp | Frangou-Lab/libgene | 28d11eea1489dd473f8376ff6475b53f12594fe6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 Frangou Lab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cassert>
#include <string_view>
#include <string>
#include <cctype>
#include "GenBankFile.hpp"
using std::string_view;
namespace gene {
GenBankFile::GenBankFile(const std::string& path,
const std::unique_ptr<CommandLineFlags>& flags,
OpenMode mode)
: SequenceFile(path, flags, FileType::GenBank, mode)
{
}
std::vector<std::string> GenBankFile::extensions()
{
return {"gb", "gbk"};
}
std::string GenBankFile::defaultExtension()
{
return "gb";
}
std::string GenBankFile::displayExtension()
{
return defaultExtension();
}
SequenceRecord GenBankFile::Read()
{
last_read_line_ = in_file_->ReadLine();
if (last_read_line_.find("LOCUS") != 0) {
last_read_line_.clear();
return SequenceRecord();
}
int64_t id_start_position = last_read_line_.find_first_not_of(' ', sizeof("LOCUS") - 1);
std::string desc;
std::string name;
if (id_start_position != std::string::npos) {
int64_t id_end_position = last_read_line_.find_first_of(' ', id_start_position);
if (id_end_position == std::string::npos)
id_end_position = last_read_line_.size();
name = last_read_line_.substr(id_start_position, id_end_position - id_start_position);
if (id_end_position != last_read_line_.size()) {
int64_t description_start = last_read_line_.find_first_not_of(' ', id_end_position + 1);
desc = last_read_line_.substr(description_start);
}
} else {
// No ID found. Consider this a format error
return SequenceRecord();
}
std::string annotation_lines;
// Skip the rest of the information that we don't need and look for the line that starts with
// "ORIGIN".
bool entered_feature_section = false;
while (!(last_read_line_ = in_file_->ReadLine()).empty()) {
if (last_read_line_.empty() || last_read_line_.find("ORIGIN") == 0) {
// Found the beginning of the "ORIGIN" section (which is the beginning of the sequence
// lines).
break;
} else if (entered_feature_section) {
string_view skipped_5_spaces = string_view(last_read_line_).substr(5);
annotation_lines.append(skipped_5_spaces.data(), skipped_5_spaces.size());
annotation_lines += '\n';
} else if (last_read_line_.find("FEATURES") == 0) {
entered_feature_section = true;
}
}
GenBankAnnotation annotation(annotation_lines);
std::string data;
while (!(last_read_line_ = in_file_->ReadLine()).empty()) {
if (last_read_line_.empty() || last_read_line_.find("//") == 0) {
// Found the beginning of the next sequence
break;
}
int64_t sequence_block_starts_position = -1;
std::string sequence_block;
while ((sequence_block_starts_position = last_read_line_.find_first_of("atgcunATGCUN", sequence_block_starts_position + 1)) != std::string::npos) {
int64_t next_space_position = last_read_line_.find(' ', sequence_block_starts_position + 1);
sequence_block = last_read_line_.substr(sequence_block_starts_position, next_space_position - sequence_block_starts_position);
for (char &c: sequence_block)
c = std::toupper(c);
data += sequence_block;
if (next_space_position == std::string::npos)
break;
sequence_block_starts_position = next_space_position;
}
}
return SequenceRecord(std::move(name), std::move(desc), std::move(data), std::move(annotation));
}
std::vector<std::string> GenBankFile::ReadVec()
{
std::vector<std::string> components;
assert(false); // Not implemented
return components;
}
void GenBankFile::Write(const SequenceRecord& record)
{
assert(false);
}
bool GenBankFile::isValidGeneFile() const
{
return true;
}
} // namespace gene
| 32.070423 | 155 | 0.659859 | [
"vector"
] |
2a9a2fa5b5f08aeb987023b093626fc9224073d7 | 1,874 | cpp | C++ | Engine/Source/FishEngine/Physics/Rigidbody.cpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 240 | 2017-02-17T10:08:19.000Z | 2022-03-25T14:45:29.000Z | Engine/Source/FishEngine/Physics/Rigidbody.cpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 2 | 2016-10-12T07:08:38.000Z | 2017-04-05T01:56:30.000Z | Engine/Source/FishEngine/Physics/Rigidbody.cpp | yushroom/FishEngine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 39 | 2017-03-02T09:40:07.000Z | 2021-12-04T07:28:53.000Z | #include <FishEngine/Rigidbody.hpp>
#include <FishEngine/GameObject.hpp>
#include <FishEngine/PhysicsSystem.hpp>
#include <FishEngine/Gizmos.hpp>
#include <FishEngine/Transform.hpp>
#include <FishEngine/PhysicsSystem.hpp>
#include <FishEngine/Collider.hpp>
using namespace FishEngine;
using namespace physx;
extern physx::PxPhysics* gPhysics;
extern physx::PxScene* gScene;
extern physx::PxMaterial* gMaterial;
inline physx::PxVec3 PxVec3(const FishEngine::Vector3& v)
{
return physx::PxVec3(v.x, v.y, v.z);
}
void FishEngine::Rigidbody::Initialize(PxShape* shape)
{
const auto& t = transform();
const Vector3 p = t->position();
const auto& q = t->rotation();
m_physxRigidDynamic = gPhysics->createRigidDynamic(PxTransform(p.x, p.y, p.z, PxQuat(q.x, q.y, q.z, q.w)));
if (shape)
{
m_physxRigidDynamic->attachShape(*shape);
shape->release();
}
}
void FishEngine::Rigidbody::Start()
{
auto collider = gameObject()->GetComponent<Collider>();
if (collider != nullptr)
Initialize(collider->physicsShape());
else
Initialize(nullptr);
const auto& t = transform();
const Vector3 p = t->position();
const auto& q = t->rotation();
m_physxRigidDynamic->setGlobalPose(PxTransform(p.x, p.y, p.z, PxQuat(q.x, q.y, q.z, q.w)));
PxRigidBodyExt::updateMassAndInertia(*m_physxRigidDynamic, 10.0f);
m_physxRigidDynamic->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, !m_useGravity);
gScene->addActor(*m_physxRigidDynamic);
}
void FishEngine::Rigidbody::Update()
{
//m_physxRigidDynamic->user
const auto& t = m_physxRigidDynamic->getGlobalPose();
//const auto& pt = t.actor2World;
transform()->setPosition(t.p.x, t.p.y, t.p.z);
transform()->setLocalRotation(Quaternion(t.q.x, t.q.y, t.q.z, t.q.w));
}
void Rigidbody::OnDestroy()
{
m_physxRigidDynamic = nullptr;
}
bool Rigidbody::IsInitialized() const
{
return m_physxRigidDynamic != nullptr;
}
| 27.15942 | 108 | 0.726788 | [
"shape",
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.