text
stringlengths 54
60.6k
|
---|
<commit_before>95cb7e33-2e4f-11e5-a5e7-28cfe91dbc4b<commit_msg>95d209de-2e4f-11e5-a08e-28cfe91dbc4b<commit_after>95d209de-2e4f-11e5-a08e-28cfe91dbc4b<|endoftext|> |
<commit_before>7727bb66-2d53-11e5-baeb-247703a38240<commit_msg>77283fa0-2d53-11e5-baeb-247703a38240<commit_after>77283fa0-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>799e02d8-2d53-11e5-baeb-247703a38240<commit_msg>799e8456-2d53-11e5-baeb-247703a38240<commit_after>799e8456-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>765dbd0c-2d53-11e5-baeb-247703a38240<commit_msg>765e3dc2-2d53-11e5-baeb-247703a38240<commit_after>765e3dc2-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>b78af5e8-4b02-11e5-b190-28cfe9171a43<commit_msg>Initial commit.2<commit_after>b79994b8-4b02-11e5-be88-28cfe9171a43<|endoftext|> |
<commit_before>7bf8b554-5216-11e5-9db3-6c40088e03e4<commit_msg>7bff48d8-5216-11e5-940a-6c40088e03e4<commit_after>7bff48d8-5216-11e5-940a-6c40088e03e4<|endoftext|> |
<commit_before>6cd42524-2fa5-11e5-87e6-00012e3d3f12<commit_msg>6cd5d2d2-2fa5-11e5-9d9c-00012e3d3f12<commit_after>6cd5d2d2-2fa5-11e5-9d9c-00012e3d3f12<|endoftext|> |
<commit_before>4d337568-5216-11e5-a5de-6c40088e03e4<commit_msg>4d3a1208-5216-11e5-936c-6c40088e03e4<commit_after>4d3a1208-5216-11e5-936c-6c40088e03e4<|endoftext|> |
<commit_before>b13a01d4-4b02-11e5-9824-28cfe9171a43<commit_msg>fixes, fixes for everyone<commit_after>b148df68-4b02-11e5-a447-28cfe9171a43<|endoftext|> |
<commit_before>1fc5abb0-2f67-11e5-81f1-6c40088e03e4<commit_msg>1fcd58e2-2f67-11e5-b70d-6c40088e03e4<commit_after>1fcd58e2-2f67-11e5-b70d-6c40088e03e4<|endoftext|> |
<commit_before>9bc1a264-35ca-11e5-98a5-6c40088e03e4<commit_msg>9bc83ad2-35ca-11e5-8942-6c40088e03e4<commit_after>9bc83ad2-35ca-11e5-8942-6c40088e03e4<|endoftext|> |
<commit_before>d6ba389a-35ca-11e5-a0e5-6c40088e03e4<commit_msg>d6c0dda6-35ca-11e5-a0b3-6c40088e03e4<commit_after>d6c0dda6-35ca-11e5-a0b3-6c40088e03e4<|endoftext|> |
<commit_before>b3967590-35ca-11e5-ab12-6c40088e03e4<commit_msg>b39d21d0-35ca-11e5-be88-6c40088e03e4<commit_after>b39d21d0-35ca-11e5-be88-6c40088e03e4<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <fstream>
typedef unsigned char byte;
typedef unsigned short word;
struct bitmapHeader
{
word type;
word lof;
word lof2;
word x_hot;
word y_hot;
word first_pixel;
word first_pixel2;
word header_size;
word header_size2;
word x_size;
word x_size2;
word y_size;
word y_size2;
word target;
word bits_per_pixel;
word compression_method;
word compression_method2;
word compressed_size;
word compressed_size2;
word x_res;
word x_res2;
word y_res;
word y_res2;
word used_clrs;
word used_clrs2;
word important_clrs;
word important_clrs2; // 54 bytes
} bitmap;
struct tga_header
{
int shite;
int shit1;
int shit2;
word xs;
word ys;
byte bpp;
byte magic;
} tga;
bool loadTGA24(const std::string& file)
{
std::ifstream fin;
fin.open(file, std::ifstream::binary);
}
<commit_msg>Using sf::Image for img loading. Argument handling done.<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <SFML/Graphics/Image.hpp>
typedef unsigned char byte;
typedef unsigned short word;
bool saveHGT(const std::string& file, unsigned hm);
int main(int argc, char** argv)
{
if(argc != 2 || argc == 3)
{
std::cout << "Incorrect # of args, must be 1 (image filename)\n";
return 1;
}
std::string file = argv[1];
std::string fileName = file.substr(0, file.find_last_of('.'));
std::string fileExt = file.substr(file.find_last_of('.') + 1);
// if second arg is given, it is the heightMod, otherwise, make it 0
unsigned heightMod = argv[2] ? std::stoi(argv[2]) : 0;
if(!(fileExt == "bmp" || fileExt == "png" || fileExt == "tga" || fileExt == "jpg" || fileExt == "gif" || fileExt == "psd" || fileExt == "hdr" || fileExt == "pic"))
{
std::cout << "Unsupported image type: " << fileExt << '\n';
return 2;
}
sf::Image image;
image.loadFromFile(file);
bool result = saveHGT(fileName + ".hgt", heightMod);
if(result)
std::cout << "HGT successfully created as " << fileName << ".hgt!\n";
else
{
std::cout << "Failed creating HGT.\n";
return 3;
}
return 0;
}
bool saveHGT(const std::string& file, unsigned hm)
{
std::ofstream fout;
fout.open(file, std::ofstream::binary);
return true;
}<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
using namespace std;
vector<string> split(const string& str) {
string buf; // Have a buffer string
stringstream ss(str); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
return tokens;
}
struct RoomObject
{
}
struct Map
{
static const int max_width = 100, max_height = 100;
static const int player_start_x = 50, player_start_y = 50;
enum Location
{
UNKNOWN,
GRAVEYARD,
GRAVEYARD_GATES,
KHATHARRS_MOMS_HOUSE,
};
Location map_location[max_width][max_height];
int x, y;
Map()
{
memset(map_location, UNKNOWN, sizeof(map_location));
x = 50;
y = 50;
map_location[50][50] = GRAVEYARD;
map_location[50][51] = GRAVEYARD_GATES;
map_location[50][52] = KHATHARRS_MOMS_HOUSE;
}
};
struct Entity
{
Entity(string name, int maxHealth) : name(name), health(maxHealth) {}
void heal(int points)
{
health = min(100, health + points);
cout << name << " healed to " << health << " health" << endl;
}
void damage(int points)
{
health = max(0, health - points);
cout << name << " damaged to " << health << "health" << endl;
}
int getHealth() const { return health; }
// Return false if the entity didn't know the command
virtual bool act(vector<string> commands) = 0;
string name;
Map map;
private:
int health;
};
struct Shogun : public Entity {
Shogun() : Entity("Shogibear", 100) {}
};
struct Item
{
virtual void apply(Entity* entity) = 0;
virtual string identify() const = 0;
};
struct HealthItem : public Item
{
HealthItem(int healPower) : healPower(healPower) {}
void apply(Entity* entity) override
{
entity->heal(healPower);
}
string identify() const override
{
stringstream ss;
ss << "Health Potion (" << healPower << ")";
return ss.str();
}
private:
int healPower;
};
struct TheFastcall : public Entity { TheFastcall("The Fastcall", 22); };
struct Player : public Entity
{
Player(string name, int health) : Entity(name, health) {}
virtual bool act(vector<string> commands) override
{
auto& cmd = commands[0];
if(cmd == "n") { commands = vector<string>{"go","north"}; }
if(cmd == "s") { commands = vector<string>{"go","south"}; }
if(cmd == "e") { commands = vector<string>{"go","east"}; }
if(cmd == "w") { commands = vector<string>{"go","west"}; }
if (commands.size() >= 1 && commands[0] == "look")
{
look();
return true;
}
else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
{
}
else if (commands.size() >= 2 && commands[0] == "go")
{
if (travel(commands[1]) == true)
{
look();
} else {
cout << "Can't travel " << commands[1] << endl;
}
return true;
}
else if (commands.size() >= 1 && commands[0] == "items")
{
showItems();
return true;
}
else if (commands.size() >= 2 && commands[0] == "use")
{
int index = stoi(commands[1]);
useItem(index);
return true;
}
return false;
}
bool travel(string direction)
{
if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
return false;
if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
return false;
if(direction=="north"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction=="south"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction=="east"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false
;if(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction=="north")map.y++;if(direction=="south")map.y--;if(direction=="east")map.x++;if(direction=="west")map.x--;
return true;/*
switch (map.map_location[map.x][map.y])
{
case Map::GRAVEYARD:
if (direction == "north")
{
map.y++;
return true;
}
break;
case Map::GRAVEYARD_GATES:
if (direction == "south")
{
map.y--;
return true;
}
if (direction == "north")
{
map.y++;
return true;
}
break;
}
cout << "Can't travel " << direction << endl;
return false;*/
}
void look()
{
switch (map.map_location[map.x][map.y])
{
case Map::GRAVEYARD:
cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
break;
case Map::GRAVEYARD_GATES:
cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
break;
case Map::KHATHARRS_MOMS_HOUSE:
cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
break;
}
}
void giveItem(shared_ptr<Item> item)
{
inventory.push_back(item);
}
void showItems()
{
if (inventory.size() == 0)
cout << "You have no items." << endl;
int i = 1;
for (auto item : inventory)
{
cout << " " << i++ << ". " << item->identify() << std::endl;
}
}
void useItem(int index)
{
if (index > inventory.size())
{
cout << "Invalid index" << endl;
return;
}
inventory[index-1]->apply(this);
inventory.erase(inventory.begin() + index - 1);
}
private:
vector<shared_ptr<Item>> inventory;
};
class Adventure
{
public:
void begin()
{
string command;
cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
cout << "> ";
getline(cin, command);
Player player(command, 100);
player.giveItem(make_shared<HealthItem>(20));
cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
player.look();
while (player.getHealth() > 0)
{
cout << "> ";
getline(cin, command);
if (player.act(split(command)) == false)
cout << "Unknown command" << endl;
}
cout << "You died. Game over." << endl;
}
};
int main()
{
Adventure adventure;
adventure.begin();
return 0;
}
<commit_msg>BlessedSword<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
using namespace std;
vector<string> split(const string& str) {
string buf; // Have a buffer string
stringstream ss(str); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
return tokens;
}
struct RoomObject
{
}
struct Map
{
static const int max_width = 100, max_height = 100;
static const int player_start_x = 50, player_start_y = 50;
enum Location
{
UNKNOWN,
GRAVEYARD,
GRAVEYARD_GATES,
KHATHARRS_MOMS_HOUSE,
};
Location map_location[max_width][max_height];
int x, y;
Map()
{
memset(map_location, UNKNOWN, sizeof(map_location));
x = 50;
y = 50;
map_location[50][50] = GRAVEYARD;
map_location[50][51] = GRAVEYARD_GATES;
map_location[50][52] = KHATHARRS_MOMS_HOUSE;
}
};
struct Entity
{
Entity(string name, int maxHealth) : name(name), health(maxHealth) {}
void heal(int points)
{
health = min(100, health + points);
cout << name << " healed to " << health << " health" << endl;
}
void damage(int points)
{
health = max(0, health - points);
cout << name << " damaged to " << health << "health" << endl;
}
int getHealth() const { return health; }
// Return false if the entity didn't know the command
virtual bool act(vector<string> commands) = 0;
string name;
Map map;
private:
int health;
};
struct Shogun : public Entity {
Shogun() : Entity("Shogibear", 100) {}
};
struct Item
{
virtual void apply(Entity* entity) = 0;
virtual string identify() const = 0;
};
struct HealthItem : public Item
{
HealthItem(int healPower) : healPower(healPower) {}
void apply(Entity* entity) override
{
entity->heal(healPower);
}
string identify() const override
{
stringstream ss;
ss << "Health Potion (" << healPower << ")";
return ss.str();
}
private:
int healPower;
};
struct BlessedSword : public Item{BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->weapon(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<
struct TheFastcall : public Entity { TheFastcall("The Fastcall", 22); };
struct Player : public Entity
{
Player(string name, int health) : Entity(name, health) {}
virtual bool act(vector<string> commands) override
{
auto& cmd = commands[0];
if(cmd == "n") { commands = vector<string>{"go","north"}; }
if(cmd == "s") { commands = vector<string>{"go","south"}; }
if(cmd == "e") { commands = vector<string>{"go","east"}; }
if(cmd == "w") { commands = vector<string>{"go","west"}; }
if (commands.size() >= 1 && commands[0] == "look")
{
look();
return true;
}
else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
{
}
else if (commands.size() >= 2 && commands[0] == "go")
{
if (travel(commands[1]) == true)
{
look();
} else {
cout << "Can't travel " << commands[1] << endl;
}
return true;
}
else if (commands.size() >= 1 && commands[0] == "items")
{
showItems();
return true;
}
else if (commands.size() >= 2 && commands[0] == "use")
{
int index = stoi(commands[1]);
useItem(index);
return true;
}
return false;
}
bool travel(string direction)
{
if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
return false;
if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
return false;
if(direction=="north"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction=="south"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction=="east"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false
;if(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction=="north")map.y++;if(direction=="south")map.y--;if(direction=="east")map.x++;if(direction=="west")map.x--;
return true;/*
switch (map.map_location[map.x][map.y])
{
case Map::GRAVEYARD:
if (direction == "north")
{
map.y++;
return true;
}
break;
case Map::GRAVEYARD_GATES:
if (direction == "south")
{
map.y--;
return true;
}
if (direction == "north")
{
map.y++;
return true;
}
break;
}
cout << "Can't travel " << direction << endl;
return false;*/
}
void look()
{
switch (map.map_location[map.x][map.y])
{
case Map::GRAVEYARD:
cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
break;
case Map::GRAVEYARD_GATES:
cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
break;
case Map::KHATHARRS_MOMS_HOUSE:
cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
break;
}
}
void giveItem(shared_ptr<Item> item)
{
inventory.push_back(item);
}
void showItems()
{
if (inventory.size() == 0)
cout << "You have no items." << endl;
int i = 1;
for (auto item : inventory)
{
cout << " " << i++ << ". " << item->identify() << std::endl;
}
}
void useItem(int index)
{
if (index > inventory.size())
{
cout << "Invalid index" << endl;
return;
}
inventory[index-1]->apply(this);
inventory.erase(inventory.begin() + index - 1);
}
private:
vector<shared_ptr<Item>> inventory;
};
class Adventure
{
public:
void begin()
{
string command;
cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
cout << "> ";
getline(cin, command);
Player player(command, 100);
player.giveItem(make_shared<HealthItem>(20));
cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
player.look();
while (player.getHealth() > 0)
{
cout << "> ";
getline(cin, command);
if (player.act(split(command)) == false)
cout << "Unknown command" << endl;
}
cout << "You died. Game over." << endl;
}
};
int main()
{
Adventure adventure;
adventure.begin();
return 0;
}
<|endoftext|> |
<commit_before>c997f2ab-2e4e-11e5-8bb8-28cfe91dbc4b<commit_msg>c99f18fd-2e4e-11e5-859c-28cfe91dbc4b<commit_after>c99f18fd-2e4e-11e5-859c-28cfe91dbc4b<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_ddr_phy_reset.C
/// @brief Reset the DDR PHY
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <stdint.h>
#include <string.h>
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_ddr_phy_reset.H>
#include <lib/utils/count_dimm.H>
#include <lib/phy/adr32s.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/fir/check.H>
#include <lib/fir/unmask.H>
using fapi2::TARGET_TYPE_MCBIST;
extern "C"
{
///
/// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist)
/// @param[in] the mcbist representing the PHY
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target)
{
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW),
"force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// New for Nimbus - perform duty cycle clock distortion calibration
#ifdef RUN_DCD
FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target) );
#endif
// 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value.
FAPI_TRY( mss::dp16::reset_sysclk(i_target) );
// (Note: The chip should already be in this state.)
FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values");
// 2. Assert reset to PHY for 32 memory clocks
FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) );
fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32));
// 3. Deassert reset_n
FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) );
//
// Flush output drivers
//
// 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register
// 9. Wait at least 32 dphy_gckn clock cycles.
// 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register
FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) );
//
// ZCTL Enable
//
// 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register
// 12. Wait at least 1024 dphy_gckn cycles
// 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL
FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) );
//
// DLL calibration
//
// 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers
// and DDRPHY_ADR_DLL_CNTL registers
// 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is
// complete. One of the 3 bits will be asserted for ADR and DP16.
FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) );
FAPI_TRY( mss::dll_calibration(i_target) );
//
// Start bang-bang-lock
//
// 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode,
FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) );
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON) );
// 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to
// perform initial alignment.
FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s",
mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) );
// 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE
FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target));
FAPI_TRY( mss::check_bang_bang_lock(i_target) );
// 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET.
FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target));
FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target) );
// 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and
// DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/
// SysClk alignment circuit out of the Continuous Update mode.
FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target));
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF),
"set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) );
// 21. Wait at least 32 dphy_nclk clock cycles.
FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)) );
//
// Done bang-bang-lock
//
// Per J. Bialas, force_mclk_low can be dasserted.
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH),
"force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// Workarounds
FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target) );
// mss::check::during_phy_reset checks to see if there are any FIR. We do this 'twice' once here
// (as part of the good-path) and once if we jump to the fapi_try label.
if ((fapi2::current_err = mss::check::during_phy_reset(i_target)) != fapi2::FAPI2_RC_SUCCESS)
{
goto leave_for_real;
}
// Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path."
// The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks
// which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless
// we're done with a success.
FAPI_TRY( mss::unmask::after_phy_reset(i_target) );
// Leave as we're all good and checked the FIR already ...
return fapi2::current_err;
// ... here on a bad-path, check FIR and leave ...
fapi_try_exit:
// mss::check::during_phy_reset handles the error/no error case internally. All we need to do is
// return the ReturnCode it hands us - it's taken care of commiting anything it needed to.
return mss::check::during_phy_reset(i_target);
// ... here if the good-path FIR check found an error. We jumped over the unmasking and are
// returning an error to the caller.
leave_for_real:
return fapi2::current_err;
}
}
<commit_msg>Updates code to run PHY DCD calibration<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_ddr_phy_reset.C
/// @brief Reset the DDR PHY
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <stdint.h>
#include <string.h>
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_ddr_phy_reset.H>
#include <lib/utils/count_dimm.H>
#include <lib/phy/adr32s.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/fir/check.H>
#include <lib/fir/unmask.H>
using fapi2::TARGET_TYPE_MCBIST;
extern "C"
{
///
/// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist)
/// @param[in] the mcbist representing the PHY
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target)
{
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW),
"force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value.
FAPI_TRY( mss::dp16::reset_sysclk(i_target) );
// (Note: The chip should already be in this state.)
FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values");
// 2. Assert reset to PHY for 32 memory clocks
FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) );
fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32));
// 3. Deassert reset_n
FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) );
//
// Flush output drivers
//
// 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register
// 9. Wait at least 32 dphy_gckn clock cycles.
// 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register
FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) );
//
// ZCTL Enable
//
// 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register
// 12. Wait at least 1024 dphy_gckn cycles
// 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL
FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) );
//
// DLL calibration
//
// 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers
// and DDRPHY_ADR_DLL_CNTL registers
// 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is
// complete. One of the 3 bits will be asserted for ADR and DP16.
FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) );
FAPI_TRY( mss::dll_calibration(i_target) );
//
// Start bang-bang-lock
//
// 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode,
FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) );
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON) );
// 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to
// perform initial alignment.
FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s",
mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) );
// 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE
FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target));
FAPI_TRY( mss::check_bang_bang_lock(i_target) );
// 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET.
FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target));
FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target) );
// 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and
// DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/
// SysClk alignment circuit out of the Continuous Update mode.
FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target));
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF),
"set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) );
// 21. Wait at least 32 dphy_nclk clock cycles.
FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)) );
//
// Done bang-bang-lock
//
// Per J. Bialas, force_mclk_low can be dasserted.
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH),
"force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// Workarounds
FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target) );
// New for Nimbus - perform duty cycle clock distortion calibration (DCD cal)
// Per PHY team's characterization, the DCD cal needs to be run after DLL calibration
FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target) );
// mss::check::during_phy_reset checks to see if there are any FIR. We do this 'twice' once here
// (as part of the good-path) and once if we jump to the fapi_try label.
if ((fapi2::current_err = mss::check::during_phy_reset(i_target)) != fapi2::FAPI2_RC_SUCCESS)
{
goto leave_for_real;
}
// Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path."
// The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks
// which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless
// we're done with a success.
FAPI_TRY( mss::unmask::after_phy_reset(i_target) );
// Leave as we're all good and checked the FIR already ...
return fapi2::current_err;
// ... here on a bad-path, check FIR and leave ...
fapi_try_exit:
// mss::check::during_phy_reset handles the error/no error case internally. All we need to do is
// return the ReturnCode it hands us - it's taken care of commiting anything it needed to.
return mss::check::during_phy_reset(i_target);
// ... here if the good-path FIR check found an error. We jumped over the unmasking and are
// returning an error to the caller.
leave_for_real:
return fapi2::current_err;
}
}
<|endoftext|> |
<commit_before>6eedfb3d-2d3e-11e5-967a-c82a142b6f9b<commit_msg>6f57a278-2d3e-11e5-9d0e-c82a142b6f9b<commit_after>6f57a278-2d3e-11e5-9d0e-c82a142b6f9b<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_chiplet_enable_ridi.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_chiplet_enable_ridi.C
///
/// @brief Enable RI/DI chip wide
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil Kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_chiplet_enable_ridi.H"
#include "p9_perv_scom_addresses.H"
static fapi2::ReturnCode p9_chiplet_enable_ridi_net_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);
fapi2::ReturnCode p9_chiplet_enable_ridi(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
FAPI_DBG("Entering ...");
for(auto l_target_cplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
(fapi2::TARGET_FILTER_SYNC_MODE_ALL_IO_EXCEPT_NEST, fapi2::TARGET_STATE_FUNCTIONAL))
{
FAPI_INF("Call p9_chiplet_enable_ridi_net_ctrl_action_function");
FAPI_TRY(p9_chiplet_enable_ridi_net_ctrl_action_function(l_target_cplt));
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief Enable Drivers/Recievers of MC, ABUS, OBUS, XBUS chiplet
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_chiplet_enable_ridi_net_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
bool l_read_reg = false;
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
FAPI_INF("Check for chiplet enable");
//Getting NET_CTRL0 register value
FAPI_TRY(fapi2::getScom(i_target_chiplet, PERV_NET_CTRL0, l_data64));
l_read_reg = l_data64.getBit<0>(); //l_read_reg = NET_CTRL0.CHIPLET_ENABLE
if ( l_read_reg )
{
FAPI_INF("Enable Recievers, Drivers DI1 & DI2");
//Setting NET_CTRL0 register value
l_data64.flush<0>();
l_data64.setBit<19>(); //NET_CTRL0.RI_N = 1
l_data64.setBit<20>(); //NET_CTRL0.DI1_N = 1
l_data64.setBit<21>(); //NET_CTRL0.DI2_N = 1
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WOR, l_data64));
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>security -- split p9_chiplet_scominit and p9_chiplet_enable_ridi isteps<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_chiplet_enable_ridi.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_chiplet_enable_ridi.C
///
/// @brief Enable RI/DI for all IO chiplets (excluding XBUS)
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil Kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_chiplet_enable_ridi.H"
#include "p9_perv_scom_addresses.H"
static fapi2::ReturnCode p9_chiplet_enable_ridi_net_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);
fapi2::ReturnCode p9_chiplet_enable_ridi(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
FAPI_DBG("Entering ...");
for(auto l_target_cplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
(static_cast<fapi2::TargetFilter>(fapi2::TARGET_FILTER_ALL_MC |
fapi2::TARGET_FILTER_ALL_PCI |
fapi2::TARGET_FILTER_ALL_OBUS),
fapi2::TARGET_STATE_FUNCTIONAL))
{
FAPI_INF("Call p9_chiplet_enable_ridi_net_ctrl_action_function");
FAPI_TRY(p9_chiplet_enable_ridi_net_ctrl_action_function(l_target_cplt));
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief Enable Drivers/Recievers of O, PCIE, MC chiplets
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_chiplet_enable_ridi_net_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
bool l_read_reg = false;
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
FAPI_INF("Check for chiplet enable");
//Getting NET_CTRL0 register value
FAPI_TRY(fapi2::getScom(i_target_chiplet, PERV_NET_CTRL0, l_data64));
l_read_reg = l_data64.getBit<0>(); //l_read_reg = NET_CTRL0.CHIPLET_ENABLE
if ( l_read_reg )
{
FAPI_INF("Enable Recievers, Drivers DI1 & DI2");
//Setting NET_CTRL0 register value
l_data64.flush<0>();
l_data64.setBit<19>(); //NET_CTRL0.RI_N = 1
l_data64.setBit<20>(); //NET_CTRL0.DI1_N = 1
l_data64.setBit<21>(); //NET_CTRL0.DI2_N = 1
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WOR, l_data64));
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>6a698dc6-2fa5-11e5-b53e-00012e3d3f12<commit_msg>6a6b8994-2fa5-11e5-b232-00012e3d3f12<commit_after>6a6b8994-2fa5-11e5-b232-00012e3d3f12<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_pgpe.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __PM_RECOVERY_FFDC_PGPE_
#define __PM_RECOVERY_FFDC_PGPE_
///
/// @file p9_pm_recovery_ffdc_pgpe.H
/// @brief Models PGPE platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner: Greg Still <[email protected]>
/// *HWP FW Owner: Prem S Jha <[email protected]>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <fapi2.H>
#include <stdint.h>
#include <p9_pm_recovery_ffdc_base.H>
namespace p9_stop_recov_ffdc
{
class PlatPgpe : public PlatPmComplex
{
public:
/// @brief constructor
PlatPgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt );
/// @brief destructor
virtual ~PlatPgpe() { };
/// @brief Initializes the PGPE FFDC Sub-Section in HOMER with default header
/// @param[in] i_pHomerBuf points to base of P9 HOMER.
/// @return fapi2 return code
fapi2::ReturnCode init ( void* i_pHomerBuf );
/// @brief collects FFDC pertaining to all functional PGPEs in the chip.
/// @param[in] i_pHomerBuf points to base of P9 HOMER.
/// @param[in] i_ffdcType indicates the content type to collect
/// @return fapi2 return code.
fapi2::ReturnCode collectFfdc( void* i_pHomerBuf,
uint8_t i_ffdcType = ALL );
private:
/// @brief collects trace info from PGPE's SRAM buffer.
/// @param[in] i_pHomerBuf points to location of HOMER meant for PGPE Trace info.
/// @return fapi2 return code.
fapi2::ReturnCode collectTrace( uint8_t * i_pHomerBuf );
/// @brief collects global variables from PGPE's's SRAM.
/// @param[in] i_pHomerBuf points to location of HOMER meant for PGPE's global variable
/// @return fapi2 return code.
fapi2::ReturnCode collectGlobals( uint8_t * i_pHomerBuf );
/// @brief collects PGPE state
/// @param[in] i_pHomerBuf points to location of HOMER meant for PGPE's state.
/// @return fapi2 return code.
fapi2::ReturnCode collectPgpeState( uint8_t * i_pHomerBuf );
/// @brief collects internal register info for a PGPE
/// @param[in] i_pHomerBuf points to location of HOMER meant for PGPE internal register.
/// @return fapi2 return code.
fapi2::ReturnCode collectInternalReg( uint8_t * i_pHomerBuf );
/// @brief collects PGPE Image Header info from PGPE SRAM buffer.
/// @param[in] i_pHomerBuf points to location of HOMER meant for PGPE's header.
/// @return fapi2 return code.
fapi2::ReturnCode collectImageHeader( uint8_t * i_pHomerBuf );
/// @brief updates the PGPE FFDC Header
///@param[in] i_pHomerBuf points to a location in HOMER meant for PGPE FFDC Header
///@param[in] i_sectionsValid bit vector summarizing FFDC validity
///@return fapi2 return code.
fapi2::ReturnCode updatePgpeFfdcHeader( uint8_t* i_pHomerBuf,
uint16_t i_sectionsValid );
///@brief returns type of platform
PmComplexPlatId getPlatType() { return iv_plat; }
private:
PmComplexPlatId iv_plat;
};
extern "C"
{
typedef fapi2::ReturnCode( *p9_pm_recovery_ffdc_pgpe_FP_t )
( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > & i_procChipTgt,
void * i_pgpeFfdcBuf );
}
} //namespace p9_stop_recov_ffdc ends
#endif //__PM_RECOVERY_FFDC_PGPE_
<commit_msg>PM: Generation of summarized version of STOP Recovery FFDC.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_pgpe.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __PM_RECOVERY_FFDC_PGPE_
#define __PM_RECOVERY_FFDC_PGPE_
///
/// @file p9_pm_recovery_ffdc_pgpe.H
/// @brief Models PGPE platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner: Greg Still <[email protected]>
/// *HWP FW Owner: Prem S Jha <[email protected]>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <fapi2.H>
#include <stdint.h>
#include <p9_pm_recovery_ffdc_base.H>
namespace p9_stop_recov_ffdc
{
class PlatPgpe : public PlatPmComplex
{
public:
/// @brief constructor
PlatPgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt );
/// @brief destructor
virtual ~PlatPgpe() { };
/// @brief Initializes the PGPE FFDC Sub-Section in HOMER with default header
/// @param[in] i_pHomerBuf points to base of P9 HOMER.
/// @return fapi2 return code
fapi2::ReturnCode init ( void* i_pHomerBuf );
/// @brief collects FFDC pertaining to all functional PGPEs in the chip.
/// @param[in] i_pHomerBuf points to base of P9 HOMER.
/// @param[in] i_ffdcType indicates the content type to collect
/// @return fapi2 return code.
fapi2::ReturnCode collectFfdc( void* i_pHomerBuf,
uint8_t i_ffdcType = ALL );
/// @brief generates summary of FFDC pertaining to a given platform.
/// @param[in] i_pHomer points to Homer base.
/// @return fapi2 return code
fapi2::ReturnCode generateSummary( void * i_pHomer );
private:
/// @brief collects trace info from PGPE's SRAM buffer.
/// @param[in] i_pHomerBuf points to location of HOMER meant for PGPE Trace info.
/// @return fapi2 return code.
fapi2::ReturnCode collectTrace( uint8_t * i_pHomerBuf );
/// @brief collects global variables from PGPE's's SRAM.
/// @param[in] i_pHomerBuf points to location of HOMER meant for PGPE's global variable
/// @return fapi2 return code.
fapi2::ReturnCode collectGlobals( uint8_t * i_pHomerBuf );
/// @brief collects PGPE state
/// @param[in] i_pHomerBuf points to location of HOMER meant for PGPE's state.
/// @return fapi2 return code.
fapi2::ReturnCode collectPgpeState( uint8_t * i_pHomerBuf );
/// @brief collects internal register info for a PGPE
/// @param[in] i_pHomerBuf points to location of HOMER meant for PGPE internal register.
/// @return fapi2 return code.
fapi2::ReturnCode collectInternalReg( uint8_t * i_pHomerBuf );
/// @brief collects PGPE Image Header info from PGPE SRAM buffer.
/// @param[in] i_pHomerBuf points to location of HOMER meant for PGPE's header.
/// @return fapi2 return code.
fapi2::ReturnCode collectImageHeader( uint8_t * i_pHomerBuf );
/// @brief updates the PGPE FFDC Header
///@param[in] i_pHomerBuf points to a location in HOMER meant for PGPE FFDC Header
///@param[in] i_sectionsValid bit vector summarizing FFDC validity
///@return fapi2 return code.
fapi2::ReturnCode updatePgpeFfdcHeader( uint8_t* i_pHomerBuf,
uint16_t i_sectionsValid );
///@brief returns type of platform
PmComplexPlatId getPlatType() { return iv_plat; }
///@brief initializes a list of register for generation of FFDC summary.
void initRegList();
private:
PmComplexPlatId iv_plat;
};
//---------------------------------------------------------------------------------------------
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode( *p9_pm_recovery_ffdc_pgpe_FP_t )
( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > & i_procChipTgt,
void * i_pgpeFfdcBuf );
extern "C"
{
// -----------------------------------------------------------------------------
// Function prototypes
// -----------------------------------------------------------------------------
///
/// @brief Populates the PGPE FFDC section with FFDC collected from PGPE.
///
/// @param[in] i_procChipTarget Proc Chip target
/// @param[in] i_pHomerImage Pointer to the base of the chip HOMER region
///
/// @return FAPI2_RC_SUCCESS on success or error return code
///
fapi2::ReturnCode p9_pm_recovery_ffdc_pgpe
( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_procChipTarget,
void* i_pHomerImage );
}
} //namespace p9_stop_recov_ffdc ends
#endif //__PM_RECOVERY_FFDC_PGPE_
<|endoftext|> |
<commit_before>3c8bac3d-2748-11e6-8f82-e0f84713e7b8<commit_msg>testing<commit_after>3c94666b-2748-11e6-95a7-e0f84713e7b8<|endoftext|> |
<commit_before>7fcc05e8-4b02-11e5-96f1-28cfe9171a43<commit_msg>fixes, fixes for everyone<commit_after>7fd895c2-4b02-11e5-a89c-28cfe9171a43<|endoftext|> |
<commit_before>60bb4785-2d16-11e5-af21-0401358ea401<commit_msg>60bb4786-2d16-11e5-af21-0401358ea401<commit_after>60bb4786-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>8b33260c-2d14-11e5-af21-0401358ea401<commit_msg>8b33260d-2d14-11e5-af21-0401358ea401<commit_after>8b33260d-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2010 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
#include <vpr/vpr.h>
#include <vpr/IO/Port/SerialPort.h>
#include <vpr/IO/Port/SerialTypes.h>
int main (int argc, char* argv[])
{
vpr::SerialPort* port;
port = new vpr::SerialPort(argv[1]);
port->setOpenReadWrite();
port->setBlocking(false);
try
{
port->open();
unsigned char read_buffer[27];
//int val;
std::cerr << "Port opened\n";
//port->setUpdateAction(vpr::SerialTypes::NOW);
//port->flushQueue(vpr::SerialTypes::IO_QUEUES);
port->clearAll();
port->setRead(true);
port->setMinInputSize(1);
//port->setCanonicalInput(false);
//port->setLocalAttach(true);
//port->setBreakByteIgnore(true);
port->setOutputBaudRate(115200); // Put me before input to be safe
port->setInputBaudRate(115200);
port->setCharacterSize(vpr::SerialTypes::CS_BITS_8);
//port->setHardwareFlowControl(false);
//port->setParityGeneration(false);
//port->setInputParityCheck(false);
//port->setStartStopInput(false);
//port->setStopBits(1);
std::cerr << "reading\n";
const char *hex = "0123456789abcdef";
unsigned int how_many = 0;
//port->flushQueue(vpr::SerialTypes::IO_QUEUES);
unsigned int min_val[14];
unsigned int max_val[14];
for ( int i = 0; i > -1; i++ )
{
std::vector<vpr::Uint8> sm_rd;
unsigned int how_many_start = 0;
unsigned int how_many_end = 0;
unsigned int bytes_read;
bytes_read = port->read(sm_rd, 1);
vpr::Uint8 switcher;
std::vector<unsigned int> glove_rec;
for(unsigned int j = 0; j < bytes_read; ++j)
{
//switcher = ((sm_rd[j] >> 4) & 0x0f) | ((sm_rd[j] << 4) & 0xf0);
switcher = sm_rd[j];
//std::cout
// << hex[((switcher & 0xf0) >> 4) & 0x0f ]
// << hex[((switcher & 0x0f) >> 0) & 0x0f ] << " " << std::endl;
while(switcher != 0x3c)
{
bytes_read = port->read(sm_rd, 1);
switcher = sm_rd[j];
//std::cout
// << hex[((switcher & 0xf0) >> 4) & 0x0f ]
// << hex[((switcher & 0x0f) >> 0) & 0x0f ] << " ";
}
#if 1
if(switcher == 0x3c)
{
//std::cout << float(sm_rd) / 255.0 << " ";
//port->read(&sm_rd, 1);
how_many_start++;
//std::cout << "<";
//std::cout << std::endl;
how_many = 0;
//std::cout
// << hex[((switcher & 0xf0) >> 4) & 0x0f ]
// << hex[((switcher & 0x0f) >> 0) & 0x0f ] ;
glove_rec.push_back( ( ((switcher & 0xf0) >> 4) & 0x0f ) );
glove_rec.push_back( ( ((switcher & 0x0f) >> 0) & 0x0f ) );
//std::cout << int( ((switcher & 0xf0) >> 4) & 0x0f ) << " "
// << int( ((switcher & 0x0f) >> 0) & 0x0f ) << std::endl;
bytes_read = 0;
while( bytes_read < 28 )
{
unsigned int bytes_this_read = 0;
bytes_this_read = port->read(sm_rd, 28 - bytes_read);
bytes_read+=bytes_this_read;
for( unsigned int kk=0; kk < bytes_this_read; ++kk)
{
//switcher = ((sm_rd[kk] >> 4) & 0x0f) | ((sm_rd[kk] << 4) & 0xf0);
switcher = sm_rd[kk]; // >> 4) & 0x0f) | ((sm_rd[kk] << 4) & 0xf0);
glove_rec.push_back( (((switcher & 0xf0) >> 4) & 0x0f ));
glove_rec.push_back( (((switcher & 0x0f) >> 0) & 0x0f ));
//std::cout << " "
// << int(((switcher & 0xf0) >> 4) & 0x0f);
// << hex[((switcher & 0x0f) >> 0) & 0x0f ] ;
}
}
//std::cout << int(glove_rec[6]) << std::endl;
unsigned int sens_num = 12;
unsigned int offset = 7;
unsigned int reading = 0;
//( ((glove_rec[sens_num + offset] & 0x0f) >> 4) & 0x0f ) |
//std::cout << int ( ( glove_rec[sens_num + offset] << 8) & 0x0f00) << " "
// << int ( ( glove_rec[sens_num + offset + 1] << 4) & 0x00f0) << " "
// << int ( ( glove_rec[sens_num + offset + 2] << 0) & 0x000f) << std::endl;
//( ((glove_rec[sens_num + offset + 1] & 0x0f) >> 4) & 0x0f );// |
//( ((glove_rec[sens_num + offset + 2] & 0x0f) >> 4) & 0x0f ) ;
reading = ( ( ( (glove_rec[sens_num + offset] & 0x000f) << 8) & 0x0f00) |
( ( (glove_rec[sens_num + offset + 1] & 0x000f) << 4) & 0x00f0) |
( ( (glove_rec[sens_num + offset + 2] & 0x000f) << 0) & 0x000f) );
for(unsigned int foo = 0; foo < glove_rec.size(); foo++)
{
if( /* (foo <= 5 && foo % 2 == 0) || */
(foo > 5 && foo % 3 == 0 && foo < 48) /*||
(foo >= 54 && foo % 2 == 0)*/
)
std::cout << "[";
if(foo > 5 && foo % 3 == 0 && foo < 48)
{
reading=( ( ( (glove_rec[foo] & 0x000f) << 8) & 0x0f00) |
( ( (glove_rec[foo + 1] & 0x000f) << 4) & 0x00f0) |
( ( (glove_rec[foo + 2] & 0x000f) << 0) & 0x000f) );
unsigned int entry = (foo - 6) / 3;
if(i == 0)
{
min_val[entry] = reading;
max_val[entry] = reading;
}
else
{
if( reading > max_val[entry] )
{
max_val[entry] = reading;
}
if( reading < min_val[entry] )
{
min_val[entry] = reading;
}
}
float top = (reading - min_val[entry]);
float bottom = (max_val[entry] - min_val[entry]);
float new_reading = (top / bottom);
//std::cout << reading;
std::cout << entry << "] " << std::fixed << std::setprecision(2) << new_reading << " ";
}
else if( foo <= 5 || foo >=54 )
{
//std::cout << hex[((glove_rec[foo] & 0x000f) >> 0) & 0x000f ] ;
}
//if( /* (foo <= 5 && foo % 2 == 1) || */
// (foo > 5 && foo % 3 == 2 && foo < 51) /* ||
// (foo >= 54 && foo % 2 == 1)*/
// )
// std::cout << "] ";
/*
if( foo == 5 )
{
std::cout << " ";
}
if( foo == 53 )
{
std::cout << " ";
}
*/
}
std::cout << std::endl;
//std::cout << " (" << sens_num << " : " << reading << ")" << std::endl;
bytes_read = 0;
glove_rec.clear();
}
//port->flushQueue(vpr::SerialTypes::INPUT_QUEUE);
#endif
#if 0
how_many++;
//std::cout << std::setbase(16) << sm_rd[j] << " ";;
//port->read(&sm_rd,1);
if(sm_rd[j] == 0x3e)
{
//std::cout << float(sm_rd) / 255.0 << " ";
//port->read(&sm_rd, 1);
//std::cout << ">";
how_many_end++;
std::cout << std::endl;
how_many = 0;
}
if (how_many > 28 )
{
std::cout << std::endl;
how_many = 0;
}
#endif
}
//std::cout << std::endl;
//std::cout << bytes_read << " < " << how_many_start << " >" << how_many_end << std::endl;
//port->flushQueue(vpr::SerialTypes::INPUT_QUEUE);
#if 0
std::cout << "... Got it! :" << std::setbase(16) << read_buffer[0] << std::endl;
memset((void*) &read_buffer, '\0', sizeof(read_buffer));
port->read(read_buffer, sizeof(read_buffer));
std::cout << "Type: " << std::setbase(16) << read_buffer[0];
std::cout << " Version: " << float(read_buffer[1]) << std::endl;
for( unsigned int i = 2; i < 25; ++i )
{
std::cout << float(read_buffer[i]) << " ";
}
std::cout << std::endl;
std::cout << "Checksum: " << int(read_buffer[25]);
std::cout << " " << std::setbase(16) << read_buffer[26] << std::endl;
//val = atoi(read_buffer);
//val++;
#endif
}
//std::cout << std::endl;
}
catch(...)
{
std::cout << "Serial Port Failed" << std::endl;
}
return 0;
}
<commit_msg>Silenced an unused variable warning.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2010 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
#include <vpr/vpr.h>
#include <vpr/IO/Port/SerialPort.h>
#include <vpr/IO/Port/SerialTypes.h>
int main (int argc, char* argv[])
{
vpr::SerialPort* port;
port = new vpr::SerialPort(argv[1]);
port->setOpenReadWrite();
port->setBlocking(false);
try
{
port->open();
//int val;
std::cerr << "Port opened\n";
//port->setUpdateAction(vpr::SerialTypes::NOW);
//port->flushQueue(vpr::SerialTypes::IO_QUEUES);
port->clearAll();
port->setRead(true);
port->setMinInputSize(1);
//port->setCanonicalInput(false);
//port->setLocalAttach(true);
//port->setBreakByteIgnore(true);
port->setOutputBaudRate(115200); // Put me before input to be safe
port->setInputBaudRate(115200);
port->setCharacterSize(vpr::SerialTypes::CS_BITS_8);
//port->setHardwareFlowControl(false);
//port->setParityGeneration(false);
//port->setInputParityCheck(false);
//port->setStartStopInput(false);
//port->setStopBits(1);
std::cerr << "reading\n";
const char *hex = "0123456789abcdef";
unsigned int how_many = 0;
//port->flushQueue(vpr::SerialTypes::IO_QUEUES);
unsigned int min_val[14];
unsigned int max_val[14];
for ( int i = 0; i > -1; i++ )
{
std::vector<vpr::Uint8> sm_rd;
unsigned int how_many_start = 0;
unsigned int how_many_end = 0;
unsigned int bytes_read;
bytes_read = port->read(sm_rd, 1);
vpr::Uint8 switcher;
std::vector<unsigned int> glove_rec;
for(unsigned int j = 0; j < bytes_read; ++j)
{
//switcher = ((sm_rd[j] >> 4) & 0x0f) | ((sm_rd[j] << 4) & 0xf0);
switcher = sm_rd[j];
//std::cout
// << hex[((switcher & 0xf0) >> 4) & 0x0f ]
// << hex[((switcher & 0x0f) >> 0) & 0x0f ] << " " << std::endl;
while(switcher != 0x3c)
{
bytes_read = port->read(sm_rd, 1);
switcher = sm_rd[j];
//std::cout
// << hex[((switcher & 0xf0) >> 4) & 0x0f ]
// << hex[((switcher & 0x0f) >> 0) & 0x0f ] << " ";
}
#if 1
if(switcher == 0x3c)
{
//std::cout << float(sm_rd) / 255.0 << " ";
//port->read(&sm_rd, 1);
how_many_start++;
//std::cout << "<";
//std::cout << std::endl;
how_many = 0;
//std::cout
// << hex[((switcher & 0xf0) >> 4) & 0x0f ]
// << hex[((switcher & 0x0f) >> 0) & 0x0f ] ;
glove_rec.push_back( ( ((switcher & 0xf0) >> 4) & 0x0f ) );
glove_rec.push_back( ( ((switcher & 0x0f) >> 0) & 0x0f ) );
//std::cout << int( ((switcher & 0xf0) >> 4) & 0x0f ) << " "
// << int( ((switcher & 0x0f) >> 0) & 0x0f ) << std::endl;
bytes_read = 0;
while( bytes_read < 28 )
{
unsigned int bytes_this_read = 0;
bytes_this_read = port->read(sm_rd, 28 - bytes_read);
bytes_read+=bytes_this_read;
for( unsigned int kk=0; kk < bytes_this_read; ++kk)
{
//switcher = ((sm_rd[kk] >> 4) & 0x0f) | ((sm_rd[kk] << 4) & 0xf0);
switcher = sm_rd[kk]; // >> 4) & 0x0f) | ((sm_rd[kk] << 4) & 0xf0);
glove_rec.push_back( (((switcher & 0xf0) >> 4) & 0x0f ));
glove_rec.push_back( (((switcher & 0x0f) >> 0) & 0x0f ));
//std::cout << " "
// << int(((switcher & 0xf0) >> 4) & 0x0f);
// << hex[((switcher & 0x0f) >> 0) & 0x0f ] ;
}
}
//std::cout << int(glove_rec[6]) << std::endl;
unsigned int sens_num = 12;
unsigned int offset = 7;
unsigned int reading = 0;
//( ((glove_rec[sens_num + offset] & 0x0f) >> 4) & 0x0f ) |
//std::cout << int ( ( glove_rec[sens_num + offset] << 8) & 0x0f00) << " "
// << int ( ( glove_rec[sens_num + offset + 1] << 4) & 0x00f0) << " "
// << int ( ( glove_rec[sens_num + offset + 2] << 0) & 0x000f) << std::endl;
//( ((glove_rec[sens_num + offset + 1] & 0x0f) >> 4) & 0x0f );// |
//( ((glove_rec[sens_num + offset + 2] & 0x0f) >> 4) & 0x0f ) ;
reading = ( ( ( (glove_rec[sens_num + offset] & 0x000f) << 8) & 0x0f00) |
( ( (glove_rec[sens_num + offset + 1] & 0x000f) << 4) & 0x00f0) |
( ( (glove_rec[sens_num + offset + 2] & 0x000f) << 0) & 0x000f) );
for(unsigned int foo = 0; foo < glove_rec.size(); foo++)
{
if( /* (foo <= 5 && foo % 2 == 0) || */
(foo > 5 && foo % 3 == 0 && foo < 48) /*||
(foo >= 54 && foo % 2 == 0)*/
)
std::cout << "[";
if(foo > 5 && foo % 3 == 0 && foo < 48)
{
reading=( ( ( (glove_rec[foo] & 0x000f) << 8) & 0x0f00) |
( ( (glove_rec[foo + 1] & 0x000f) << 4) & 0x00f0) |
( ( (glove_rec[foo + 2] & 0x000f) << 0) & 0x000f) );
unsigned int entry = (foo - 6) / 3;
if(i == 0)
{
min_val[entry] = reading;
max_val[entry] = reading;
}
else
{
if( reading > max_val[entry] )
{
max_val[entry] = reading;
}
if( reading < min_val[entry] )
{
min_val[entry] = reading;
}
}
float top = (reading - min_val[entry]);
float bottom = (max_val[entry] - min_val[entry]);
float new_reading = (top / bottom);
//std::cout << reading;
std::cout << entry << "] " << std::fixed << std::setprecision(2) << new_reading << " ";
}
else if( foo <= 5 || foo >=54 )
{
//std::cout << hex[((glove_rec[foo] & 0x000f) >> 0) & 0x000f ] ;
}
//if( /* (foo <= 5 && foo % 2 == 1) || */
// (foo > 5 && foo % 3 == 2 && foo < 51) /* ||
// (foo >= 54 && foo % 2 == 1)*/
// )
// std::cout << "] ";
/*
if( foo == 5 )
{
std::cout << " ";
}
if( foo == 53 )
{
std::cout << " ";
}
*/
}
std::cout << std::endl;
//std::cout << " (" << sens_num << " : " << reading << ")" << std::endl;
bytes_read = 0;
glove_rec.clear();
}
//port->flushQueue(vpr::SerialTypes::INPUT_QUEUE);
#endif
#if 0
how_many++;
//std::cout << std::setbase(16) << sm_rd[j] << " ";;
//port->read(&sm_rd,1);
if(sm_rd[j] == 0x3e)
{
//std::cout << float(sm_rd) / 255.0 << " ";
//port->read(&sm_rd, 1);
//std::cout << ">";
how_many_end++;
std::cout << std::endl;
how_many = 0;
}
if (how_many > 28 )
{
std::cout << std::endl;
how_many = 0;
}
#endif
}
//std::cout << std::endl;
//std::cout << bytes_read << " < " << how_many_start << " >" << how_many_end << std::endl;
//port->flushQueue(vpr::SerialTypes::INPUT_QUEUE);
#if 0
std::cout << "... Got it! :" << std::setbase(16) << read_buffer[0] << std::endl;
memset((void*) &read_buffer, '\0', sizeof(read_buffer));
port->read(read_buffer, sizeof(read_buffer));
std::cout << "Type: " << std::setbase(16) << read_buffer[0];
std::cout << " Version: " << float(read_buffer[1]) << std::endl;
for( unsigned int i = 2; i < 25; ++i )
{
std::cout << float(read_buffer[i]) << " ";
}
std::cout << std::endl;
std::cout << "Checksum: " << int(read_buffer[25]);
std::cout << " " << std::setbase(16) << read_buffer[26] << std::endl;
//val = atoi(read_buffer);
//val++;
#endif
}
//std::cout << std::endl;
}
catch(...)
{
std::cout << "Serial Port Failed" << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Dirk Holz (University of Bonn)
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#ifndef PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_
#define PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_
#include <pcl/surface/organized_fast_mesh.h>
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::performReconstruction (pcl::PolygonMesh &output)
{
reconstructPolygons (output.polygons);
// Get the field names
int x_idx = pcl::getFieldIndex (output.cloud, "x");
int y_idx = pcl::getFieldIndex (output.cloud, "y");
int z_idx = pcl::getFieldIndex (output.cloud, "z");
if (x_idx == -1 || y_idx == -1 || z_idx == -1)
return;
// correct all measurements,
// (running over complete image since some rows and columns are left out
// depending on triangle_pixel_size)
// avoid to do that here (only needed for ASCII mesh file output, e.g., in vtk files
for (unsigned int i = 0; i < input_->points.size (); ++i)
if (!isFinite (input_->points[i]))
resetPointData (i, output, 0.0f, x_idx, y_idx, z_idx);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::performReconstruction (std::vector<pcl::Vertices> &polygons)
{
reconstructPolygons (polygons);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::reconstructPolygons (std::vector<pcl::Vertices> &polygons)
{
if (triangulation_type_ == TRIANGLE_RIGHT_CUT)
makeRightCutMesh (polygons);
else if (triangulation_type_ == TRIANGLE_LEFT_CUT)
makeLeftCutMesh (polygons);
else if (triangulation_type_ == TRIANGLE_ADAPTIVE_CUT)
makeAdaptiveCutMesh (polygons);
else if (triangulation_type_ == QUAD_MESH)
makeQuadMesh (polygons);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeQuadMesh (std::vector<pcl::Vertices>& polygons)
{
int last_column = input_->width - triangle_pixel_size_;
int last_row = input_->height - triangle_pixel_size_;
int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
int y_big_incr = triangle_pixel_size_ * input_->width,
x_big_incr = y_big_incr + triangle_pixel_size_;
// Reserve enough space
polygons.resize (input_->width * input_->height);
// Go over the rows first
for (int y = 0; y < last_row; y += triangle_pixel_size_)
{
// Initialize a new row
i = y * input_->width;
index_right = i + triangle_pixel_size_;
index_down = i + y_big_incr;
index_down_right = i + x_big_incr;
// Go over the columns
for (int x = 0; x < last_column; x += triangle_pixel_size_,
i += triangle_pixel_size_,
index_right += triangle_pixel_size_,
index_down += triangle_pixel_size_,
index_down_right += triangle_pixel_size_)
{
if (isValidQuad (i, index_right, index_down_right, index_down))
if (store_shadowed_faces_ || !isShadowedQuad (i, index_right, index_down_right, index_down))
addQuad (i, index_right, index_down_right, index_down, idx++, polygons);
}
}
polygons.resize (idx);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeRightCutMesh (std::vector<pcl::Vertices>& polygons)
{
int last_column = input_->width - triangle_pixel_size_;
int last_row = input_->height - triangle_pixel_size_;
int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
int y_big_incr = triangle_pixel_size_ * input_->width,
x_big_incr = y_big_incr + triangle_pixel_size_;
// Reserve enough space
polygons.resize (input_->width * input_->height * 2);
// Go over the rows first
for (int y = 0; y < last_row; y += triangle_pixel_size_)
{
// Initialize a new row
i = y * input_->width;
index_right = i + triangle_pixel_size_;
index_down = i + y_big_incr;
index_down_right = i + x_big_incr;
// Go over the columns
for (int x = 0; x < last_column; x += triangle_pixel_size_,
i += triangle_pixel_size_,
index_right += triangle_pixel_size_,
index_down += triangle_pixel_size_,
index_down_right += triangle_pixel_size_)
{
if (isValidTriangle (i, index_down_right, index_right))
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
addTriangle (i, index_down_right, index_right, idx++, polygons);
if (isValidTriangle (i, index_down, index_down_right))
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
addTriangle (i, index_down, index_down_right, idx++, polygons);
}
}
polygons.resize (idx);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeLeftCutMesh (std::vector<pcl::Vertices>& polygons)
{
int last_column = input_->width - triangle_pixel_size_;
int last_row = input_->height - triangle_pixel_size_;
int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
int y_big_incr = triangle_pixel_size_ * input_->width,
x_big_incr = y_big_incr + triangle_pixel_size_;
// Reserve enough space
polygons.resize (input_->width * input_->height * 2);
// Go over the rows first
for (int y = 0; y < last_row; y += triangle_pixel_size_)
{
// Initialize a new row
i = y * input_->width;
index_right = i + triangle_pixel_size_;
index_down = i + y_big_incr;
index_down_right = i + x_big_incr;
// Go over the columns
for (int x = 0; x < last_column; x += triangle_pixel_size_,
i += triangle_pixel_size_,
index_right += triangle_pixel_size_,
index_down += triangle_pixel_size_,
index_down_right += triangle_pixel_size_)
{
if (isValidTriangle (i, index_down, index_right))
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
addTriangle (i, index_down, index_right, idx++, polygons);
if (isValidTriangle (index_right, index_down, index_down_right))
if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
addTriangle (index_right, index_down, index_down_right, idx++, polygons);
}
}
polygons.resize (idx);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeAdaptiveCutMesh (std::vector<pcl::Vertices>& polygons)
{
int last_column = input_->width - triangle_pixel_size_;
int last_row = input_->height - triangle_pixel_size_;
int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
int y_big_incr = triangle_pixel_size_ * input_->width,
x_big_incr = y_big_incr + triangle_pixel_size_;
// Reserve enough space
polygons.resize (input_->width * input_->height * 4);
// Go over the rows first
for (int y = 0; y < last_row; y += triangle_pixel_size_)
{
// Initialize a new row
i = y * input_->width;
index_right = i + triangle_pixel_size_;
index_down = i + y_big_incr;
index_down_right = i + x_big_incr;
// Go over the columns
for (int x = 0; x < last_column; x += triangle_pixel_size_,
i += triangle_pixel_size_,
index_right += triangle_pixel_size_,
index_down += triangle_pixel_size_,
index_down_right += triangle_pixel_size_)
{
const bool right_cut_upper = isValidTriangle (i, index_down_right, index_right);
const bool right_cut_lower = isValidTriangle (i, index_down, index_down_right);
const bool left_cut_upper = isValidTriangle (i, index_down, index_right);
const bool left_cut_lower = isValidTriangle (index_right, index_down, index_down_right);
if (right_cut_upper && right_cut_lower && left_cut_upper && left_cut_lower)
{
float dist_right_cut = fabs (input_->points[index_down].z - input_->points[index_right].z);
float dist_left_cut = fabs (input_->points[i].z - input_->points[index_down_right].z);
if (dist_right_cut >= dist_left_cut)
{
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
addTriangle (i, index_down_right, index_right, idx++, polygons);
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
addTriangle (i, index_down, index_down_right, idx++, polygons);
}
else
{
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
addTriangle (i, index_down, index_right, idx++, polygons);
if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
addTriangle (index_right, index_down, index_down_right, idx++, polygons);
}
}
else
{
if (right_cut_upper)
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
addTriangle (i, index_down_right, index_right, idx++, polygons);
if (right_cut_lower)
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
addTriangle (i, index_down, index_down_right, idx++, polygons);
if (left_cut_upper)
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
addTriangle (i, index_down, index_right, idx++, polygons);
if (left_cut_lower)
if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
addTriangle (index_right, index_down, index_down_right, idx++, polygons);
}
}
}
polygons.resize (idx);
}
#define PCL_INSTANTIATE_OrganizedFastMesh(T) \
template class PCL_EXPORTS pcl::OrganizedFastMesh<T>;
#endif // PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_
<commit_msg>Corrected OrganizedFastMesh quad vertex order<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Dirk Holz (University of Bonn)
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#ifndef PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_
#define PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_
#include <pcl/surface/organized_fast_mesh.h>
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::performReconstruction (pcl::PolygonMesh &output)
{
reconstructPolygons (output.polygons);
// Get the field names
int x_idx = pcl::getFieldIndex (output.cloud, "x");
int y_idx = pcl::getFieldIndex (output.cloud, "y");
int z_idx = pcl::getFieldIndex (output.cloud, "z");
if (x_idx == -1 || y_idx == -1 || z_idx == -1)
return;
// correct all measurements,
// (running over complete image since some rows and columns are left out
// depending on triangle_pixel_size)
// avoid to do that here (only needed for ASCII mesh file output, e.g., in vtk files
for (unsigned int i = 0; i < input_->points.size (); ++i)
if (!isFinite (input_->points[i]))
resetPointData (i, output, 0.0f, x_idx, y_idx, z_idx);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::performReconstruction (std::vector<pcl::Vertices> &polygons)
{
reconstructPolygons (polygons);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::reconstructPolygons (std::vector<pcl::Vertices> &polygons)
{
if (triangulation_type_ == TRIANGLE_RIGHT_CUT)
makeRightCutMesh (polygons);
else if (triangulation_type_ == TRIANGLE_LEFT_CUT)
makeLeftCutMesh (polygons);
else if (triangulation_type_ == TRIANGLE_ADAPTIVE_CUT)
makeAdaptiveCutMesh (polygons);
else if (triangulation_type_ == QUAD_MESH)
makeQuadMesh (polygons);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeQuadMesh (std::vector<pcl::Vertices>& polygons)
{
int last_column = input_->width - triangle_pixel_size_;
int last_row = input_->height - triangle_pixel_size_;
int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
int y_big_incr = triangle_pixel_size_ * input_->width,
x_big_incr = y_big_incr + triangle_pixel_size_;
// Reserve enough space
polygons.resize (input_->width * input_->height);
// Go over the rows first
for (int y = 0; y < last_row; y += triangle_pixel_size_)
{
// Initialize a new row
i = y * input_->width;
index_right = i + triangle_pixel_size_;
index_down = i + y_big_incr;
index_down_right = i + x_big_incr;
// Go over the columns
for (int x = 0; x < last_column; x += triangle_pixel_size_,
i += triangle_pixel_size_,
index_right += triangle_pixel_size_,
index_down += triangle_pixel_size_,
index_down_right += triangle_pixel_size_)
{
if (isValidQuad (i, index_down, index_right, index_down_right))
if (store_shadowed_faces_ || !isShadowedQuad (i, index_right, index_down_right, index_down))
addQuad (i, index_down, index_right, index_down_right, idx++, polygons);
}
}
polygons.resize (idx);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeRightCutMesh (std::vector<pcl::Vertices>& polygons)
{
int last_column = input_->width - triangle_pixel_size_;
int last_row = input_->height - triangle_pixel_size_;
int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
int y_big_incr = triangle_pixel_size_ * input_->width,
x_big_incr = y_big_incr + triangle_pixel_size_;
// Reserve enough space
polygons.resize (input_->width * input_->height * 2);
// Go over the rows first
for (int y = 0; y < last_row; y += triangle_pixel_size_)
{
// Initialize a new row
i = y * input_->width;
index_right = i + triangle_pixel_size_;
index_down = i + y_big_incr;
index_down_right = i + x_big_incr;
// Go over the columns
for (int x = 0; x < last_column; x += triangle_pixel_size_,
i += triangle_pixel_size_,
index_right += triangle_pixel_size_,
index_down += triangle_pixel_size_,
index_down_right += triangle_pixel_size_)
{
if (isValidTriangle (i, index_down_right, index_right))
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
addTriangle (i, index_down_right, index_right, idx++, polygons);
if (isValidTriangle (i, index_down, index_down_right))
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
addTriangle (i, index_down, index_down_right, idx++, polygons);
}
}
polygons.resize (idx);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeLeftCutMesh (std::vector<pcl::Vertices>& polygons)
{
int last_column = input_->width - triangle_pixel_size_;
int last_row = input_->height - triangle_pixel_size_;
int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
int y_big_incr = triangle_pixel_size_ * input_->width,
x_big_incr = y_big_incr + triangle_pixel_size_;
// Reserve enough space
polygons.resize (input_->width * input_->height * 2);
// Go over the rows first
for (int y = 0; y < last_row; y += triangle_pixel_size_)
{
// Initialize a new row
i = y * input_->width;
index_right = i + triangle_pixel_size_;
index_down = i + y_big_incr;
index_down_right = i + x_big_incr;
// Go over the columns
for (int x = 0; x < last_column; x += triangle_pixel_size_,
i += triangle_pixel_size_,
index_right += triangle_pixel_size_,
index_down += triangle_pixel_size_,
index_down_right += triangle_pixel_size_)
{
if (isValidTriangle (i, index_down, index_right))
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
addTriangle (i, index_down, index_right, idx++, polygons);
if (isValidTriangle (index_right, index_down, index_down_right))
if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
addTriangle (index_right, index_down, index_down_right, idx++, polygons);
}
}
polygons.resize (idx);
}
/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeAdaptiveCutMesh (std::vector<pcl::Vertices>& polygons)
{
int last_column = input_->width - triangle_pixel_size_;
int last_row = input_->height - triangle_pixel_size_;
int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
int y_big_incr = triangle_pixel_size_ * input_->width,
x_big_incr = y_big_incr + triangle_pixel_size_;
// Reserve enough space
polygons.resize (input_->width * input_->height * 4);
// Go over the rows first
for (int y = 0; y < last_row; y += triangle_pixel_size_)
{
// Initialize a new row
i = y * input_->width;
index_right = i + triangle_pixel_size_;
index_down = i + y_big_incr;
index_down_right = i + x_big_incr;
// Go over the columns
for (int x = 0; x < last_column; x += triangle_pixel_size_,
i += triangle_pixel_size_,
index_right += triangle_pixel_size_,
index_down += triangle_pixel_size_,
index_down_right += triangle_pixel_size_)
{
const bool right_cut_upper = isValidTriangle (i, index_down_right, index_right);
const bool right_cut_lower = isValidTriangle (i, index_down, index_down_right);
const bool left_cut_upper = isValidTriangle (i, index_down, index_right);
const bool left_cut_lower = isValidTriangle (index_right, index_down, index_down_right);
if (right_cut_upper && right_cut_lower && left_cut_upper && left_cut_lower)
{
float dist_right_cut = fabs (input_->points[index_down].z - input_->points[index_right].z);
float dist_left_cut = fabs (input_->points[i].z - input_->points[index_down_right].z);
if (dist_right_cut >= dist_left_cut)
{
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
addTriangle (i, index_down_right, index_right, idx++, polygons);
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
addTriangle (i, index_down, index_down_right, idx++, polygons);
}
else
{
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
addTriangle (i, index_down, index_right, idx++, polygons);
if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
addTriangle (index_right, index_down, index_down_right, idx++, polygons);
}
}
else
{
if (right_cut_upper)
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
addTriangle (i, index_down_right, index_right, idx++, polygons);
if (right_cut_lower)
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
addTriangle (i, index_down, index_down_right, idx++, polygons);
if (left_cut_upper)
if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
addTriangle (i, index_down, index_right, idx++, polygons);
if (left_cut_lower)
if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
addTriangle (index_right, index_down, index_down_right, idx++, polygons);
}
}
}
polygons.resize (idx);
}
#define PCL_INSTANTIATE_OrganizedFastMesh(T) \
template class PCL_EXPORTS pcl::OrganizedFastMesh<T>;
#endif // PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_
<|endoftext|> |
<commit_before>7695f190-2d53-11e5-baeb-247703a38240<commit_msg>76966fee-2d53-11e5-baeb-247703a38240<commit_after>76966fee-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>aa57b145-2747-11e6-b08d-e0f84713e7b8<commit_msg>Tuesday, turns out it was tuesday<commit_after>aa6a356e-2747-11e6-8217-e0f84713e7b8<|endoftext|> |
<commit_before>9afffbf5-2747-11e6-96f8-e0f84713e7b8<commit_msg>Fix that bug where things didn't work but now they should<commit_after>9b10193a-2747-11e6-8c9b-e0f84713e7b8<|endoftext|> |
<commit_before>9812a24c-327f-11e5-9305-9cf387a8033e<commit_msg>981a33e1-327f-11e5-b048-9cf387a8033e<commit_after>981a33e1-327f-11e5-b048-9cf387a8033e<|endoftext|> |
<commit_before>8431fc6b-2d15-11e5-af21-0401358ea401<commit_msg>8431fc6c-2d15-11e5-af21-0401358ea401<commit_after>8431fc6c-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>8b4a9c68-4b02-11e5-bf16-28cfe9171a43<commit_msg>Does anyone even read these anymore???<commit_after>8b57d247-4b02-11e5-b452-28cfe9171a43<|endoftext|> |
<commit_before>78f6cacc-2d53-11e5-baeb-247703a38240<commit_msg>78f7503c-2d53-11e5-baeb-247703a38240<commit_after>78f7503c-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>a1855de3-327f-11e5-97c3-9cf387a8033e<commit_msg>a18b4626-327f-11e5-aa6d-9cf387a8033e<commit_after>a18b4626-327f-11e5-aa6d-9cf387a8033e<|endoftext|> |
<commit_before>7428c7cf-ad5c-11e7-9161-ac87a332f658<commit_msg>Initial commit.2<commit_after>749c1fc7-ad5c-11e7-8bc3-ac87a332f658<|endoftext|> |
<commit_before>772b497a-2d53-11e5-baeb-247703a38240<commit_msg>772bfabe-2d53-11e5-baeb-247703a38240<commit_after>772bfabe-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>#include <vexcl/devlist.hpp>
#include <vexcl/spmat.hpp>
#include <vexcl/vector.hpp>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/DenseSubvector.h>
#include <blaze/util/serialization/Archive.h>
#include <blaze/math/serialization/MatrixSerializer.h>
#include <blaze/math/serialization/VectorSerializer.h>
#include <vector>
#include <sstream>
#include <string>
#include <iostream>
void ConvertSpMat(std::vector<size_t>& row, std::vector<size_t>& col, std::vector<double>& val, blaze::CompressedMatrix<double>& mat) {
uint non_zeros = mat.nonZeros();
row.clear();
col.clear();
val.clear();
uint count = 0;
for (int i = 0; i < mat.rows(); ++i) {
row.push_back(count);
for (blaze::CompressedMatrix<double>::Iterator it = mat.begin(i); it != mat.end(i); ++it) {
col.push_back(it->index());
val.push_back(it->value());
count++;
}
}
row.push_back(count);
}
std::string slurp(std::string fname){
std::ifstream file(fname.c_str());
std::string buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return buffer;
}
void readSPMAT(std::string & data, blaze::CompressedMatrix<double> & mat){
std::stringstream ss(data);
uint rows, cols, nonzeros;
ss>>rows>>cols>>nonzeros;
//printf("INFO: rows: %d, columns: %d, non zeros: %d\n",rows, cols, nonzeros);
mat.resize(rows,cols);
mat.reserve(nonzeros);
uint row_nonzeros;
uint colval;
double v;
for(int i=0; i<rows; i++){
if(i%1000000==0){printf("%d, ",i);}
ss>>row_nonzeros;
for(int j=0; j<row_nonzeros; j++){
ss>>colval>>v;
mat.append(i,colval,v);
}
mat.finalize(i);
}
printf("\n");
}
void readVector(std::string & data, std::vector<double> & vec){
std::stringstream ss(data);
uint size;
ss>>size;
vec.resize(size);
//printf("INFO: size: %d\n",size);
double v;
for(int i=0; i<size; i++){
ss>>v;
vec[i] = v;
}
}
int main(){
printf("start execution \n");
vex::Context ctx(vex::Filter::Env && vex::Filter::DoublePrecision);
std::cout<<ctx<<std::endl;
printf("create context \n");
blaze::CompressedMatrix<double> D_T, M_invD;
std::vector<double> g,b;
printf("read D^T \n");
{
std::string data = slurp("D_T.mat");
readSPMAT(data, D_T);
}
{
std::string data = slurp("M_invD.mat");
readSPMAT(data, M_invD);
}
{
std::string data = slurp("gamma.vec");
readVector(data, g);
}
{
std::string data = slurp("b.vec");
readVector(data, b);
}
printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T.rows(), D_T.columns(), D_T.nonZeros());
printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD.rows(), M_invD.columns(), M_invD.nonZeros());
printf("gamma: size: %d\n", g.size());
printf("b: size: %d\n", b.size());
std::vector<size_t> row;
std::vector<size_t> col;
std::vector<double> val;
ConvertSpMat(row, col, val, D_T);
vex::SpMat<double> _D_T(ctx, D_T.rows(), D_T.columns(), row.data(), col.data(), val.data());
ConvertSpMat(row, col, val, M_invD);
vex::SpMat<double> _M_invD(ctx, M_invD.rows(), M_invD.columns(), row.data(), col.data(), val.data());
blaze::DynamicVector<double> gamma(g.size()),rhs(g.size());
for(int i=0; i<g.size(); i++){
gamma[i] = g[i];
rhs[i] = b[i];
}
blaze::DynamicVector<double> res_cpu(g.size());
double start_cpu = omp_get_wtime();
res_cpu = M_invD*gamma;
res_cpu = D_T*res_cpu;
double end_cpu = omp_get_wtime();
vex::profiler<> prof;
vex::vector<double> gamma_gpu(ctx,g.size());
vex::vector<double> b_gpu(ctx,b.size());
vex::copy(g,gamma_gpu);
vex::copy(b,b_gpu);
vex::vector<double> tmp_gpu(ctx,g.size());
vex::vector<double> res_gpu(ctx,g.size());
prof.tic_cpu("GPU");
double start_gpu = omp_get_wtime();
tmp_gpu = _M_invD*gamma_gpu;
res_gpu = _D_T*tmp_gpu;
double end_gpu = omp_get_wtime();
double tot_time = prof.toc("GPU");
printf("CPU took %f sec. time.\n", end_cpu-start_cpu);
printf("GPU took %f sec. time, %f sec time.\n", end_gpu-start_gpu, tot_time);
printf("Speedup: %f\n", (end_cpu-start_cpu) /(end_gpu-start_gpu));
//std::vector<double> res_host(g.size());
//vex::copy(res_gpu,res_host);
//printf("copy\n");
// for(int i=0; i<g.size(); i++){
// if(res_host[i]!=res_cpu[i]){
// printf("%f\n",res_host[i]-res_cpu[i]);
// }
// }
return 0;
}<commit_msg>do more runs and average time<commit_after>#include <vexcl/devlist.hpp>
#include <vexcl/spmat.hpp>
#include <vexcl/vector.hpp>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/DenseSubvector.h>
#include <blaze/util/serialization/Archive.h>
#include <blaze/math/serialization/MatrixSerializer.h>
#include <blaze/math/serialization/VectorSerializer.h>
#include <vector>
#include <sstream>
#include <string>
#include <iostream>
void ConvertSpMat(std::vector<size_t>& row, std::vector<size_t>& col, std::vector<double>& val, blaze::CompressedMatrix<double>& mat) {
uint non_zeros = mat.nonZeros();
row.clear();
col.clear();
val.clear();
uint count = 0;
for (int i = 0; i < mat.rows(); ++i) {
row.push_back(count);
for (blaze::CompressedMatrix<double>::Iterator it = mat.begin(i); it != mat.end(i); ++it) {
col.push_back(it->index());
val.push_back(it->value());
count++;
}
}
row.push_back(count);
}
std::string slurp(std::string fname){
std::ifstream file(fname.c_str());
std::string buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return buffer;
}
void readSPMAT(std::string & data, blaze::CompressedMatrix<double> & mat){
std::stringstream ss(data);
uint rows, cols, nonzeros;
ss>>rows>>cols>>nonzeros;
//printf("INFO: rows: %d, columns: %d, non zeros: %d\n",rows, cols, nonzeros);
mat.resize(rows,cols);
mat.reserve(nonzeros);
uint row_nonzeros;
uint colval;
double v;
for(int i=0; i<rows; i++){
if(i%1000000==0){printf("%d, ",i);}
ss>>row_nonzeros;
for(int j=0; j<row_nonzeros; j++){
ss>>colval>>v;
mat.append(i,colval,v);
}
mat.finalize(i);
}
printf("\n");
}
void readVector(std::string & data, std::vector<double> & vec){
std::stringstream ss(data);
uint size;
ss>>size;
vec.resize(size);
//printf("INFO: size: %d\n",size);
double v;
for(int i=0; i<size; i++){
ss>>v;
vec[i] = v;
}
}
int main(){
printf("start execution \n");
vex::Context ctx(vex::Filter::Env && vex::Filter::DoublePrecision);
std::cout<<ctx<<std::endl;
printf("create context \n");
blaze::CompressedMatrix<double> D_T, M_invD;
std::vector<double> g,b;
printf("read D^T \n");
{
std::string data = slurp("D_T.mat");
readSPMAT(data, D_T);
}
{
std::string data = slurp("M_invD.mat");
readSPMAT(data, M_invD);
}
{
std::string data = slurp("gamma.vec");
readVector(data, g);
}
{
std::string data = slurp("b.vec");
readVector(data, b);
}
printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T.rows(), D_T.columns(), D_T.nonZeros());
printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD.rows(), M_invD.columns(), M_invD.nonZeros());
printf("gamma: size: %d\n", g.size());
printf("b: size: %d\n", b.size());
std::vector<size_t> row;
std::vector<size_t> col;
std::vector<double> val;
ConvertSpMat(row, col, val, D_T);
vex::SpMat<double> _D_T(ctx, D_T.rows(), D_T.columns(), row.data(), col.data(), val.data());
ConvertSpMat(row, col, val, M_invD);
vex::SpMat<double> _M_invD(ctx, M_invD.rows(), M_invD.columns(), row.data(), col.data(), val.data());
blaze::DynamicVector<double> gamma(g.size()),rhs(g.size());
for(int i=0; i<g.size(); i++){
gamma[i] = g[i];
rhs[i] = b[i];
}
blaze::DynamicVector<double> tmp_cpu(g.size());
blaze::DynamicVector<double> res_cpu(g.size());
double start_cpu = omp_get_wtime();
for(size_t i = 0; i < 100; i++){
tmp_cpu = M_invD*gamma;
res_cpu += D_T*tmp_cpu;
}
double end_cpu = omp_get_wtime();
vex::profiler<> prof;
vex::vector<double> gamma_gpu(ctx,g.size());
vex::vector<double> b_gpu(ctx,b.size());
vex::copy(g,gamma_gpu);
vex::copy(b,b_gpu);
vex::vector<double> tmp_gpu(ctx,g.size());
vex::vector<double> res_gpu(ctx,g.size());
tmp_gpu += _M_invD*gamma_gpu;
tmp_gpu = 0;
res_gpu += _D_T*tmp_gpu;
res_gpu = 0;
prof.tic_cpu("GPU");
double start_gpu = omp_get_wtime();
for(size_t i = 0; i < 100; i++){
tmp_gpu = _M_invD*gamma_gpu;
res_gpu += _D_T*tmp_gpu;
}
ctx.finish();
double end_gpu = omp_get_wtime();
double tot_time = prof.toc("GPU");
printf("CPU took %f sec. time.\n", (end_cpu-start_cpu)/100.0);
printf("GPU took %f sec. time, %f sec time.\n", (end_gpu-start_gpu)/100.0, tot_time/100.0);
printf("Speedup: %f\n", (end_cpu-start_cpu) /(end_gpu-start_gpu));
//std::vector<double> res_host(g.size());
//vex::copy(res_gpu,res_host);
//printf("copy\n");
// for(int i=0; i<g.size(); i++){
// if(res_host[i]!=res_cpu[i]){
// printf("%f\n",res_host[i]-res_cpu[i]);
// }
// }
return 0;
}<|endoftext|> |
<commit_before>2729f9fe-2e3a-11e5-938c-c03896053bdd<commit_msg>273742d8-2e3a-11e5-aaab-c03896053bdd<commit_after>273742d8-2e3a-11e5-aaab-c03896053bdd<|endoftext|> |
<commit_before><commit_msg>Prediction: update pytorch API to latest to mute warning (#9566)<commit_after><|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. 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.
==============================================================================*/
// See docs in ../ops/math_ops.cc.
#define EIGEN_USE_THREADS
#include "tensorflow/core/kernels/sparse_tensor_dense_matmul_op.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/kernels/fill_functor.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
template <typename Device, typename T>
class SparseTensorDenseMatMulOp : public OpKernel {
public:
explicit SparseTensorDenseMatMulOp(OpKernelConstruction* ctx)
: OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("adjoint_a", &adjoint_a_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("adjoint_b", &adjoint_b_));
}
void Compute(OpKernelContext* ctx) override {
const Tensor* a_indices;
const Tensor* a_values;
const Tensor* a_shape;
const Tensor* b;
OP_REQUIRES_OK(ctx, ctx->input("a_indices", &a_indices));
OP_REQUIRES_OK(ctx, ctx->input("a_values", &a_values));
OP_REQUIRES_OK(ctx, ctx->input("a_shape", &a_shape));
OP_REQUIRES_OK(ctx, ctx->input("b", &b));
// Check that the dimensions of the two matrices are valid.
OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(b->shape()),
errors::InvalidArgument("Tensor 'b' is not a matrix"));
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_shape->shape()),
errors::InvalidArgument("Tensor 'a_shape' is not a vector"));
OP_REQUIRES(
ctx, a_shape->NumElements() == 2,
errors::InvalidArgument("Tensor 'a_shape' must have 2 elements"));
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_values->shape()),
errors::InvalidArgument("Tensor 'a_values' is not a vector"));
OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a_indices->shape()),
errors::InvalidArgument("Tensor 'a_indices' is not a matrix"));
OP_REQUIRES(ctx, a_indices->shape().dim_size(0) == a_values->NumElements(),
errors::InvalidArgument("Number of rows of a_indices does not "
"match number of entries in a_values"));
OP_REQUIRES(
ctx, a_indices->shape().dim_size(1) == a_shape->NumElements(),
errors::InvalidArgument("Number of columns of a_indices does not match "
"number of entries in a_shape"));
auto a_shape_t = a_shape->vec<int64>();
const int64 outer_left = (adjoint_a_) ? a_shape_t(1) : a_shape_t(0);
const int64 outer_right =
(adjoint_b_) ? b->shape().dim_size(0) : b->shape().dim_size(1);
const int64 inner_left = (adjoint_a_) ? a_shape_t(0) : a_shape_t(1);
const int64 inner_right =
(adjoint_b_) ? b->shape().dim_size(1) : b->shape().dim_size(0);
OP_REQUIRES(
ctx, inner_right == inner_left,
errors::InvalidArgument(
"Cannot multiply A and B because inner dimension does not match: ",
inner_left, " vs. ", inner_right,
". Did you forget a transpose? "
"Dimensions of A: [",
a_shape_t(0), ", ", a_shape_t(1), "). Dimensions of B: ",
b->shape().DebugString()));
TensorShape out_shape({outer_left, outer_right});
Tensor* out = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out));
if (out->NumElements() == 0) {
// If a has shape [0, x] or b has shape [x, 0], the output shape
// is a 0-element matrix, so there is nothing to do.
return;
}
if (a_values->NumElements() == 0 || b->NumElements() == 0) {
// If a has shape [x, 0] and b has shape [0, y], the
// output shape is [x, y] where x and y are non-zero, so we fill
// the output with zeros.
functor::SetZeroFunctor<Device, T> f;
f(ctx->eigen_device<Device>(), out->flat<T>());
return;
}
Tensor scratch;
if (std::is_same<Device, GPUDevice>::value) {
// The GPU implementation is optimized to use 32 bit indexing, so
// give a friendly error to the programmer early on if they exceed.
OP_REQUIRES(
ctx,
FastBoundsCheck(inner_left, std::numeric_limits<int>::max()) &&
FastBoundsCheck(inner_right, std::numeric_limits<int>::max()) &&
FastBoundsCheck(outer_left, std::numeric_limits<int>::max()) &&
FastBoundsCheck(outer_right, std::numeric_limits<int>::max()) &&
FastBoundsCheck(b->NumElements(),
std::numeric_limits<int>::max()) &&
FastBoundsCheck(out->NumElements(),
std::numeric_limits<int>::max()) &&
FastBoundsCheck(a_values->NumElements(),
std::numeric_limits<int>::max()),
errors::InvalidArgument("Cannot use GPU for > 2^31 entry inputs"));
const int nnz = static_cast<const int>(a_values->NumElements());
// Need nnz length vec scratch space on the GPU.
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
TensorShape({nnz}), &scratch));
} else {
// We don't need scratch space on the CPU.
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
TensorShape({0}), &scratch));
}
#define MAYBE_ADJOINT(ADJ_A, ADJ_B) \
if (adjoint_a_ == ADJ_A && adjoint_b_ == ADJ_B) { \
functor::SparseTensorDenseMatMulFunctor<Device, T, ADJ_A, ADJ_B>::Compute( \
ctx->eigen_device<Device>(), out->matrix<T>(), \
a_indices->matrix<int64>(), a_values->vec<T>(), b->matrix<T>(), \
scratch.vec<T>()); \
}
MAYBE_ADJOINT(false, false);
MAYBE_ADJOINT(false, true);
MAYBE_ADJOINT(true, false);
MAYBE_ADJOINT(true, true);
#undef MAYBE_ADJOINT
}
private:
bool adjoint_a_;
bool adjoint_b_;
};
#define REGISTER_CPU(T) \
REGISTER_KERNEL_BUILDER(Name("SparseTensorDenseMatMul") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.HostMemory("a_shape"), \
SparseTensorDenseMatMulOp<CPUDevice, T>);
REGISTER_CPU(float);
REGISTER_CPU(double);
REGISTER_CPU(int32);
REGISTER_CPU(complex64);
REGISTER_CPU(complex128);
#if GOOGLE_CUDA
namespace functor {
#define DECLARE_GPU_SPEC(T, ADJ_A, ADJ_B) \
template <> \
void SparseTensorDenseMatMulFunctor<GPUDevice, T, ADJ_A, ADJ_B>::Compute( \
const GPUDevice& d, typename TTypes<T>::Matrix out, \
TTypes<int64>::ConstMatrix a_indices, \
typename TTypes<T>::ConstVec a_values, \
typename TTypes<T>::ConstMatrix b, typename TTypes<T>::Vec scratch); \
extern template struct SparseTensorDenseMatMulFunctor<GPUDevice, T, ADJ_A, \
ADJ_B>;
#define DECLARE_ADJOINT_GPU_SPEC(T) \
DECLARE_GPU_SPEC(T, false, false) \
DECLARE_GPU_SPEC(T, false, true) \
DECLARE_GPU_SPEC(T, true, false) \
DECLARE_GPU_SPEC(T, true, true)
DECLARE_ADJOINT_GPU_SPEC(float);
#undef DECLARE_ADJOINT_GPU_SPEC
#undef DECLARE_GPU_SPEC
} // namespace functor
#define REGISTER_GPU(T) \
REGISTER_KERNEL_BUILDER(Name("SparseTensorDenseMatMul") \
.Device(DEVICE_GPU) \
.TypeConstraint<T>("T") \
.HostMemory("a_shape"), \
SparseTensorDenseMatMulOp<GPUDevice, T>);
REGISTER_GPU(float);
#undef REGISTER_GPU
#endif // GOOGLE_CUDA
namespace functor {
template <typename T, bool ADJ_A, bool ADJ_B>
struct SparseTensorDenseMatMulFunctor<CPUDevice, T, ADJ_A, ADJ_B> {
// Vectorize certain operations above this size.
static const std::size_t kNumVectorize = 32;
static void Compute(const CPUDevice& d, typename TTypes<T>::Matrix out,
TTypes<int64>::ConstMatrix a_indices,
typename TTypes<T>::ConstVec a_values,
typename TTypes<T>::ConstMatrix b,
typename TTypes<T>::Vec scratch) {
const std::size_t nnz = a_values.size();
const std::size_t rhs_right = (ADJ_B ? b.dimension(0) : b.dimension(1));
const std::size_t lhs_right = (ADJ_B ? b.dimension(1) : b.dimension(0));
const int lhs_index_a = ADJ_A ? 1 : 0;
const int rhs_index_a = ADJ_A ? 0 : 1;
out.setZero();
// TODO(ebrevdo): After many failed experiments, can't find a multi-threaded
// approach that achieves the performance of the single threaded
// one. Perhaps Eigen threadpool implementation is just too slow?
if (rhs_right < kNumVectorize) {
// Disable vectorization if the RHS of output is too small
auto maybe_adjoint_b = MaybeAdjoint<decltype(b), ADJ_B>(b);
for (std::size_t i = 0; i < nnz; ++i) {
const int64 m = internal::SubtleMustCopy(a_indices(i, lhs_index_a));
const int64 k = internal::SubtleMustCopy(a_indices(i, rhs_index_a));
CHECK_LT(k, lhs_right);
CHECK_LT(m, out.dimension(0));
const T a_value = ADJ_A ? MaybeConj(a_values(i)) : a_values(i);
for (std::size_t n = 0; n < rhs_right; ++n) {
const T b_value = maybe_adjoint_b(k, n);
out(m, n) += a_value * b_value;
}
}
} else {
// Vectorization via Eigen.
const int b_chip_index = ADJ_B ? 1 : 0;
#define LOOP_NNZ(b_passed) \
for (std::size_t i = 0; i < nnz; ++i) { \
const int64 m = internal::SubtleMustCopy(a_indices(i, lhs_index_a)); \
const int64 k = internal::SubtleMustCopy(a_indices(i, rhs_index_a)); \
const T a_value = (ADJ_A) ? MaybeConj(a_values(i)) : a_values(i); \
CHECK_LT(m, out.dimension(0)); \
CHECK_LT(k, lhs_right); \
out.template chip<0>(m) += \
b_passed.template chip<b_chip_index>(k) * a_value; \
}
if (ADJ_B) {
// Perform transpose and conjugation on B once, since we chip out B's
// columns in the nnz loop.
Eigen::array<int, 2> shuffle(1, 0); // preserve dimension order
Eigen::Tensor<T, 2, Eigen::ColMajor> col_major_conj_b =
b.swap_layout().shuffle(shuffle).unaryExpr(
Eigen::internal::scalar_conjugate_op<T>());
LOOP_NNZ(col_major_conj_b);
} else {
LOOP_NNZ(b);
}
#undef LOOP_NNZ
}
}
};
} // namespace functor
} // namespace tensorflow
<commit_msg>Tiny cleanup: Use .conjugate() method for Eigen Tensors. Change: 134120413<commit_after>/* Copyright 2015 The TensorFlow Authors. 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.
==============================================================================*/
// See docs in ../ops/math_ops.cc.
#define EIGEN_USE_THREADS
#include "tensorflow/core/kernels/sparse_tensor_dense_matmul_op.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/kernels/fill_functor.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
template <typename Device, typename T>
class SparseTensorDenseMatMulOp : public OpKernel {
public:
explicit SparseTensorDenseMatMulOp(OpKernelConstruction* ctx)
: OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("adjoint_a", &adjoint_a_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("adjoint_b", &adjoint_b_));
}
void Compute(OpKernelContext* ctx) override {
const Tensor* a_indices;
const Tensor* a_values;
const Tensor* a_shape;
const Tensor* b;
OP_REQUIRES_OK(ctx, ctx->input("a_indices", &a_indices));
OP_REQUIRES_OK(ctx, ctx->input("a_values", &a_values));
OP_REQUIRES_OK(ctx, ctx->input("a_shape", &a_shape));
OP_REQUIRES_OK(ctx, ctx->input("b", &b));
// Check that the dimensions of the two matrices are valid.
OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(b->shape()),
errors::InvalidArgument("Tensor 'b' is not a matrix"));
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_shape->shape()),
errors::InvalidArgument("Tensor 'a_shape' is not a vector"));
OP_REQUIRES(
ctx, a_shape->NumElements() == 2,
errors::InvalidArgument("Tensor 'a_shape' must have 2 elements"));
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_values->shape()),
errors::InvalidArgument("Tensor 'a_values' is not a vector"));
OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a_indices->shape()),
errors::InvalidArgument("Tensor 'a_indices' is not a matrix"));
OP_REQUIRES(ctx, a_indices->shape().dim_size(0) == a_values->NumElements(),
errors::InvalidArgument("Number of rows of a_indices does not "
"match number of entries in a_values"));
OP_REQUIRES(
ctx, a_indices->shape().dim_size(1) == a_shape->NumElements(),
errors::InvalidArgument("Number of columns of a_indices does not match "
"number of entries in a_shape"));
auto a_shape_t = a_shape->vec<int64>();
const int64 outer_left = (adjoint_a_) ? a_shape_t(1) : a_shape_t(0);
const int64 outer_right =
(adjoint_b_) ? b->shape().dim_size(0) : b->shape().dim_size(1);
const int64 inner_left = (adjoint_a_) ? a_shape_t(0) : a_shape_t(1);
const int64 inner_right =
(adjoint_b_) ? b->shape().dim_size(1) : b->shape().dim_size(0);
OP_REQUIRES(
ctx, inner_right == inner_left,
errors::InvalidArgument(
"Cannot multiply A and B because inner dimension does not match: ",
inner_left, " vs. ", inner_right,
". Did you forget a transpose? "
"Dimensions of A: [",
a_shape_t(0), ", ", a_shape_t(1), "). Dimensions of B: ",
b->shape().DebugString()));
TensorShape out_shape({outer_left, outer_right});
Tensor* out = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out));
if (out->NumElements() == 0) {
// If a has shape [0, x] or b has shape [x, 0], the output shape
// is a 0-element matrix, so there is nothing to do.
return;
}
if (a_values->NumElements() == 0 || b->NumElements() == 0) {
// If a has shape [x, 0] and b has shape [0, y], the
// output shape is [x, y] where x and y are non-zero, so we fill
// the output with zeros.
functor::SetZeroFunctor<Device, T> f;
f(ctx->eigen_device<Device>(), out->flat<T>());
return;
}
Tensor scratch;
if (std::is_same<Device, GPUDevice>::value) {
// The GPU implementation is optimized to use 32 bit indexing, so
// give a friendly error to the programmer early on if they exceed.
OP_REQUIRES(
ctx,
FastBoundsCheck(inner_left, std::numeric_limits<int>::max()) &&
FastBoundsCheck(inner_right, std::numeric_limits<int>::max()) &&
FastBoundsCheck(outer_left, std::numeric_limits<int>::max()) &&
FastBoundsCheck(outer_right, std::numeric_limits<int>::max()) &&
FastBoundsCheck(b->NumElements(),
std::numeric_limits<int>::max()) &&
FastBoundsCheck(out->NumElements(),
std::numeric_limits<int>::max()) &&
FastBoundsCheck(a_values->NumElements(),
std::numeric_limits<int>::max()),
errors::InvalidArgument("Cannot use GPU for > 2^31 entry inputs"));
const int nnz = static_cast<const int>(a_values->NumElements());
// Need nnz length vec scratch space on the GPU.
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
TensorShape({nnz}), &scratch));
} else {
// We don't need scratch space on the CPU.
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
TensorShape({0}), &scratch));
}
#define MAYBE_ADJOINT(ADJ_A, ADJ_B) \
if (adjoint_a_ == ADJ_A && adjoint_b_ == ADJ_B) { \
functor::SparseTensorDenseMatMulFunctor<Device, T, ADJ_A, ADJ_B>::Compute( \
ctx->eigen_device<Device>(), out->matrix<T>(), \
a_indices->matrix<int64>(), a_values->vec<T>(), b->matrix<T>(), \
scratch.vec<T>()); \
}
MAYBE_ADJOINT(false, false);
MAYBE_ADJOINT(false, true);
MAYBE_ADJOINT(true, false);
MAYBE_ADJOINT(true, true);
#undef MAYBE_ADJOINT
}
private:
bool adjoint_a_;
bool adjoint_b_;
};
#define REGISTER_CPU(T) \
REGISTER_KERNEL_BUILDER(Name("SparseTensorDenseMatMul") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.HostMemory("a_shape"), \
SparseTensorDenseMatMulOp<CPUDevice, T>);
REGISTER_CPU(float);
REGISTER_CPU(double);
REGISTER_CPU(int32);
REGISTER_CPU(complex64);
REGISTER_CPU(complex128);
#if GOOGLE_CUDA
namespace functor {
#define DECLARE_GPU_SPEC(T, ADJ_A, ADJ_B) \
template <> \
void SparseTensorDenseMatMulFunctor<GPUDevice, T, ADJ_A, ADJ_B>::Compute( \
const GPUDevice& d, typename TTypes<T>::Matrix out, \
TTypes<int64>::ConstMatrix a_indices, \
typename TTypes<T>::ConstVec a_values, \
typename TTypes<T>::ConstMatrix b, typename TTypes<T>::Vec scratch); \
extern template struct SparseTensorDenseMatMulFunctor<GPUDevice, T, ADJ_A, \
ADJ_B>;
#define DECLARE_ADJOINT_GPU_SPEC(T) \
DECLARE_GPU_SPEC(T, false, false) \
DECLARE_GPU_SPEC(T, false, true) \
DECLARE_GPU_SPEC(T, true, false) \
DECLARE_GPU_SPEC(T, true, true)
DECLARE_ADJOINT_GPU_SPEC(float);
#undef DECLARE_ADJOINT_GPU_SPEC
#undef DECLARE_GPU_SPEC
} // namespace functor
#define REGISTER_GPU(T) \
REGISTER_KERNEL_BUILDER(Name("SparseTensorDenseMatMul") \
.Device(DEVICE_GPU) \
.TypeConstraint<T>("T") \
.HostMemory("a_shape"), \
SparseTensorDenseMatMulOp<GPUDevice, T>);
REGISTER_GPU(float);
#undef REGISTER_GPU
#endif // GOOGLE_CUDA
namespace functor {
template <typename T, bool ADJ_A, bool ADJ_B>
struct SparseTensorDenseMatMulFunctor<CPUDevice, T, ADJ_A, ADJ_B> {
// Vectorize certain operations above this size.
static const std::size_t kNumVectorize = 32;
static void Compute(const CPUDevice& d, typename TTypes<T>::Matrix out,
TTypes<int64>::ConstMatrix a_indices,
typename TTypes<T>::ConstVec a_values,
typename TTypes<T>::ConstMatrix b,
typename TTypes<T>::Vec scratch) {
const std::size_t nnz = a_values.size();
const std::size_t rhs_right = (ADJ_B ? b.dimension(0) : b.dimension(1));
const std::size_t lhs_right = (ADJ_B ? b.dimension(1) : b.dimension(0));
const int lhs_index_a = ADJ_A ? 1 : 0;
const int rhs_index_a = ADJ_A ? 0 : 1;
out.setZero();
// TODO(ebrevdo): After many failed experiments, can't find a multi-threaded
// approach that achieves the performance of the single threaded
// one. Perhaps Eigen threadpool implementation is just too slow?
if (rhs_right < kNumVectorize) {
// Disable vectorization if the RHS of output is too small
auto maybe_adjoint_b = MaybeAdjoint<decltype(b), ADJ_B>(b);
for (std::size_t i = 0; i < nnz; ++i) {
const int64 m = internal::SubtleMustCopy(a_indices(i, lhs_index_a));
const int64 k = internal::SubtleMustCopy(a_indices(i, rhs_index_a));
CHECK_LT(k, lhs_right);
CHECK_LT(m, out.dimension(0));
const T a_value = ADJ_A ? MaybeConj(a_values(i)) : a_values(i);
for (std::size_t n = 0; n < rhs_right; ++n) {
const T b_value = maybe_adjoint_b(k, n);
out(m, n) += a_value * b_value;
}
}
} else {
// Vectorization via Eigen.
const int b_chip_index = ADJ_B ? 1 : 0;
#define LOOP_NNZ(b_passed) \
for (std::size_t i = 0; i < nnz; ++i) { \
const int64 m = internal::SubtleMustCopy(a_indices(i, lhs_index_a)); \
const int64 k = internal::SubtleMustCopy(a_indices(i, rhs_index_a)); \
const T a_value = (ADJ_A) ? MaybeConj(a_values(i)) : a_values(i); \
CHECK_LT(m, out.dimension(0)); \
CHECK_LT(k, lhs_right); \
out.template chip<0>(m) += \
b_passed.template chip<b_chip_index>(k) * a_value; \
}
if (ADJ_B) {
// Perform transpose and conjugation on B once, since we chip out B's
// columns in the nnz loop.
Eigen::array<int, 2> shuffle(1, 0); // preserve dimension order
Eigen::Tensor<T, 2, Eigen::ColMajor> col_major_conj_b =
b.swap_layout().shuffle(shuffle).conjugate();
LOOP_NNZ(col_major_conj_b);
} else {
LOOP_NNZ(b);
}
#undef LOOP_NNZ
}
}
};
} // namespace functor
} // namespace tensorflow
<|endoftext|> |
<commit_before>442ff6e6-5216-11e5-9a97-6c40088e03e4<commit_msg>443828c0-5216-11e5-bd0d-6c40088e03e4<commit_after>443828c0-5216-11e5-bd0d-6c40088e03e4<|endoftext|> |
<commit_before>/*
* Copyright 2019 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/gpu/GrRecordingContext.h"
#include "include/gpu/GrContextThreadSafeProxy.h"
#include "src/core/SkArenaAlloc.h"
#include "src/gpu/GrAuditTrail.h"
#include "src/gpu/GrCaps.h"
#include "src/gpu/GrContextThreadSafeProxyPriv.h"
#include "src/gpu/GrDrawingManager.h"
#include "src/gpu/GrMemoryPool.h"
#include "src/gpu/GrProgramDesc.h"
#include "src/gpu/GrProxyProvider.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/GrSurfaceContext.h"
#include "src/gpu/GrSurfaceDrawContext.h"
#include "src/gpu/SkGr.h"
#include "src/gpu/effects/GrSkSLFP.h"
#include "src/gpu/ops/GrAtlasTextOp.h"
#include "src/gpu/text/GrTextBlob.h"
#include "src/gpu/text/GrTextBlobCache.h"
GrRecordingContext::ProgramData::ProgramData(std::unique_ptr<const GrProgramDesc> desc,
const GrProgramInfo* info)
: fDesc(std::move(desc))
, fInfo(info) {
}
GrRecordingContext::ProgramData::ProgramData(ProgramData&& other)
: fDesc(std::move(other.fDesc))
, fInfo(other.fInfo) {
}
GrRecordingContext::ProgramData::~ProgramData() = default;
GrRecordingContext::GrRecordingContext(sk_sp<GrContextThreadSafeProxy> proxy)
: INHERITED(std::move(proxy))
, fAuditTrail(new GrAuditTrail()) {
fProxyProvider = std::make_unique<GrProxyProvider>(this);
}
GrRecordingContext::~GrRecordingContext() {
GrAtlasTextOp::ClearCache();
}
int GrRecordingContext::maxSurfaceSampleCountForColorType(SkColorType colorType) const {
GrBackendFormat format =
this->caps()->getDefaultBackendFormat(SkColorTypeToGrColorType(colorType),
GrRenderable::kYes);
return this->caps()->maxRenderTargetSampleCount(format);
}
bool GrRecordingContext::init() {
if (!INHERITED::init()) {
return false;
}
GrPathRendererChain::Options prcOptions;
prcOptions.fAllowPathMaskCaching = this->options().fAllowPathMaskCaching;
#if GR_TEST_UTILS
prcOptions.fGpuPathRenderers = this->options().fGpuPathRenderers;
#endif
// FIXME: Once this is removed from Chrome and Android, rename to fEnable"".
if (this->options().fDisableDistanceFieldPaths) {
prcOptions.fGpuPathRenderers &= ~GpuPathRenderers::kSmall;
}
bool reduceOpsTaskSplitting = false;
if (GrContextOptions::Enable::kYes == this->options().fReduceOpsTaskSplitting) {
reduceOpsTaskSplitting = true;
} else if (GrContextOptions::Enable::kNo == this->options().fReduceOpsTaskSplitting) {
reduceOpsTaskSplitting = false;
}
fDrawingManager.reset(new GrDrawingManager(this,
prcOptions,
reduceOpsTaskSplitting));
return true;
}
void GrRecordingContext::abandonContext() {
INHERITED::abandonContext();
this->destroyDrawingManager();
}
GrDrawingManager* GrRecordingContext::drawingManager() {
return fDrawingManager.get();
}
void GrRecordingContext::destroyDrawingManager() {
fDrawingManager.reset();
}
GrRecordingContext::Arenas::Arenas(SkArenaAlloc* recordTimeAllocator,
GrSubRunAllocator* subRunAllocator)
: fRecordTimeAllocator(recordTimeAllocator)
, fRecordTimeSubRunAllocator(subRunAllocator) {
// OwnedArenas should instantiate these before passing the bare pointer off to this struct.
SkASSERT(recordTimeAllocator);
SkASSERT(subRunAllocator);
}
// Must be defined here so that std::unique_ptr can see the sizes of the various pools, otherwise
// it can't generate a default destructor for them.
GrRecordingContext::OwnedArenas::OwnedArenas() {}
GrRecordingContext::OwnedArenas::~OwnedArenas() {}
GrRecordingContext::OwnedArenas& GrRecordingContext::OwnedArenas::operator=(OwnedArenas&& a) {
fRecordTimeAllocator = std::move(a.fRecordTimeAllocator);
fRecordTimeSubRunAllocator = std::move(a.fRecordTimeSubRunAllocator);
return *this;
}
GrRecordingContext::Arenas GrRecordingContext::OwnedArenas::get() {
if (!fRecordTimeAllocator) {
// TODO: empirically determine a better number for SkArenaAlloc's firstHeapAllocation param
fRecordTimeAllocator = std::make_unique<SkArenaAlloc>(sizeof(GrPipeline) * 100);
}
if (!fRecordTimeSubRunAllocator) {
fRecordTimeSubRunAllocator = std::make_unique<GrSubRunAllocator>();
}
return {fRecordTimeAllocator.get(), fRecordTimeSubRunAllocator.get()};
}
GrRecordingContext::OwnedArenas&& GrRecordingContext::detachArenas() {
return std::move(fArenas);
}
GrTextBlobCache* GrRecordingContext::getTextBlobCache() {
return fThreadSafeProxy->priv().getTextBlobCache();
}
const GrTextBlobCache* GrRecordingContext::getTextBlobCache() const {
return fThreadSafeProxy->priv().getTextBlobCache();
}
GrThreadSafeCache* GrRecordingContext::threadSafeCache() {
return fThreadSafeProxy->priv().threadSafeCache();
}
const GrThreadSafeCache* GrRecordingContext::threadSafeCache() const {
return fThreadSafeProxy->priv().threadSafeCache();
}
void GrRecordingContext::addOnFlushCallbackObject(GrOnFlushCallbackObject* onFlushCBObject) {
this->drawingManager()->addOnFlushCallbackObject(onFlushCBObject);
}
////////////////////////////////////////////////////////////////////////////////
int GrRecordingContext::maxTextureSize() const { return this->caps()->maxTextureSize(); }
int GrRecordingContext::maxRenderTargetSize() const { return this->caps()->maxRenderTargetSize(); }
bool GrRecordingContext::colorTypeSupportedAsImage(SkColorType colorType) const {
GrBackendFormat format =
this->caps()->getDefaultBackendFormat(SkColorTypeToGrColorType(colorType),
GrRenderable::kNo);
return format.isValid();
}
///////////////////////////////////////////////////////////////////////////////////////////////////
sk_sp<const GrCaps> GrRecordingContextPriv::refCaps() const {
return fContext->refCaps();
}
void GrRecordingContextPriv::addOnFlushCallbackObject(GrOnFlushCallbackObject* onFlushCBObject) {
fContext->addOnFlushCallbackObject(onFlushCBObject);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef SK_ENABLE_DUMP_GPU
#include "src/utils/SkJSONWriter.h"
void GrRecordingContext::dumpJSON(SkJSONWriter* writer) const {
writer->beginObject();
#if GR_GPU_STATS
writer->appendS32("path_masks_generated", this->stats()->numPathMasksGenerated());
writer->appendS32("path_mask_cache_hits", this->stats()->numPathMaskCacheHits());
#endif
writer->endObject();
}
#else
void GrRecordingContext::dumpJSON(SkJSONWriter*) const { }
#endif
#if GR_TEST_UTILS
#if GR_GPU_STATS
void GrRecordingContext::Stats::dump(SkString* out) {
out->appendf("Num Path Masks Generated: %d\n", fNumPathMasksGenerated);
out->appendf("Num Path Mask Cache Hits: %d\n", fNumPathMaskCacheHits);
}
void GrRecordingContext::Stats::dumpKeyValuePairs(SkTArray<SkString>* keys,
SkTArray<double>* values) {
keys->push_back(SkString("path_masks_generated"));
values->push_back(fNumPathMasksGenerated);
keys->push_back(SkString("path_mask_cache_hits"));
values->push_back(fNumPathMaskCacheHits);
}
#endif // GR_GPU_STATS
#endif // GR_TEST_UTILS
<commit_msg>reduce record time allocator's initial block size<commit_after>/*
* Copyright 2019 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/gpu/GrRecordingContext.h"
#include "include/gpu/GrContextThreadSafeProxy.h"
#include "src/core/SkArenaAlloc.h"
#include "src/gpu/GrAuditTrail.h"
#include "src/gpu/GrCaps.h"
#include "src/gpu/GrContextThreadSafeProxyPriv.h"
#include "src/gpu/GrDrawingManager.h"
#include "src/gpu/GrMemoryPool.h"
#include "src/gpu/GrProgramDesc.h"
#include "src/gpu/GrProxyProvider.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/GrSurfaceContext.h"
#include "src/gpu/GrSurfaceDrawContext.h"
#include "src/gpu/SkGr.h"
#include "src/gpu/effects/GrSkSLFP.h"
#include "src/gpu/ops/GrAtlasTextOp.h"
#include "src/gpu/text/GrTextBlob.h"
#include "src/gpu/text/GrTextBlobCache.h"
GrRecordingContext::ProgramData::ProgramData(std::unique_ptr<const GrProgramDesc> desc,
const GrProgramInfo* info)
: fDesc(std::move(desc))
, fInfo(info) {
}
GrRecordingContext::ProgramData::ProgramData(ProgramData&& other)
: fDesc(std::move(other.fDesc))
, fInfo(other.fInfo) {
}
GrRecordingContext::ProgramData::~ProgramData() = default;
GrRecordingContext::GrRecordingContext(sk_sp<GrContextThreadSafeProxy> proxy)
: INHERITED(std::move(proxy))
, fAuditTrail(new GrAuditTrail()) {
fProxyProvider = std::make_unique<GrProxyProvider>(this);
}
GrRecordingContext::~GrRecordingContext() {
GrAtlasTextOp::ClearCache();
}
int GrRecordingContext::maxSurfaceSampleCountForColorType(SkColorType colorType) const {
GrBackendFormat format =
this->caps()->getDefaultBackendFormat(SkColorTypeToGrColorType(colorType),
GrRenderable::kYes);
return this->caps()->maxRenderTargetSampleCount(format);
}
bool GrRecordingContext::init() {
if (!INHERITED::init()) {
return false;
}
GrPathRendererChain::Options prcOptions;
prcOptions.fAllowPathMaskCaching = this->options().fAllowPathMaskCaching;
#if GR_TEST_UTILS
prcOptions.fGpuPathRenderers = this->options().fGpuPathRenderers;
#endif
// FIXME: Once this is removed from Chrome and Android, rename to fEnable"".
if (this->options().fDisableDistanceFieldPaths) {
prcOptions.fGpuPathRenderers &= ~GpuPathRenderers::kSmall;
}
bool reduceOpsTaskSplitting = false;
if (GrContextOptions::Enable::kYes == this->options().fReduceOpsTaskSplitting) {
reduceOpsTaskSplitting = true;
} else if (GrContextOptions::Enable::kNo == this->options().fReduceOpsTaskSplitting) {
reduceOpsTaskSplitting = false;
}
fDrawingManager.reset(new GrDrawingManager(this,
prcOptions,
reduceOpsTaskSplitting));
return true;
}
void GrRecordingContext::abandonContext() {
INHERITED::abandonContext();
this->destroyDrawingManager();
}
GrDrawingManager* GrRecordingContext::drawingManager() {
return fDrawingManager.get();
}
void GrRecordingContext::destroyDrawingManager() {
fDrawingManager.reset();
}
GrRecordingContext::Arenas::Arenas(SkArenaAlloc* recordTimeAllocator,
GrSubRunAllocator* subRunAllocator)
: fRecordTimeAllocator(recordTimeAllocator)
, fRecordTimeSubRunAllocator(subRunAllocator) {
// OwnedArenas should instantiate these before passing the bare pointer off to this struct.
SkASSERT(recordTimeAllocator);
SkASSERT(subRunAllocator);
}
// Must be defined here so that std::unique_ptr can see the sizes of the various pools, otherwise
// it can't generate a default destructor for them.
GrRecordingContext::OwnedArenas::OwnedArenas() {}
GrRecordingContext::OwnedArenas::~OwnedArenas() {}
GrRecordingContext::OwnedArenas& GrRecordingContext::OwnedArenas::operator=(OwnedArenas&& a) {
fRecordTimeAllocator = std::move(a.fRecordTimeAllocator);
fRecordTimeSubRunAllocator = std::move(a.fRecordTimeSubRunAllocator);
return *this;
}
GrRecordingContext::Arenas GrRecordingContext::OwnedArenas::get() {
if (!fRecordTimeAllocator) {
// TODO: empirically determine a better number for SkArenaAlloc's firstHeapAllocation param
fRecordTimeAllocator = std::make_unique<SkArenaAlloc>(1024);
}
if (!fRecordTimeSubRunAllocator) {
fRecordTimeSubRunAllocator = std::make_unique<GrSubRunAllocator>();
}
return {fRecordTimeAllocator.get(), fRecordTimeSubRunAllocator.get()};
}
GrRecordingContext::OwnedArenas&& GrRecordingContext::detachArenas() {
return std::move(fArenas);
}
GrTextBlobCache* GrRecordingContext::getTextBlobCache() {
return fThreadSafeProxy->priv().getTextBlobCache();
}
const GrTextBlobCache* GrRecordingContext::getTextBlobCache() const {
return fThreadSafeProxy->priv().getTextBlobCache();
}
GrThreadSafeCache* GrRecordingContext::threadSafeCache() {
return fThreadSafeProxy->priv().threadSafeCache();
}
const GrThreadSafeCache* GrRecordingContext::threadSafeCache() const {
return fThreadSafeProxy->priv().threadSafeCache();
}
void GrRecordingContext::addOnFlushCallbackObject(GrOnFlushCallbackObject* onFlushCBObject) {
this->drawingManager()->addOnFlushCallbackObject(onFlushCBObject);
}
////////////////////////////////////////////////////////////////////////////////
int GrRecordingContext::maxTextureSize() const { return this->caps()->maxTextureSize(); }
int GrRecordingContext::maxRenderTargetSize() const { return this->caps()->maxRenderTargetSize(); }
bool GrRecordingContext::colorTypeSupportedAsImage(SkColorType colorType) const {
GrBackendFormat format =
this->caps()->getDefaultBackendFormat(SkColorTypeToGrColorType(colorType),
GrRenderable::kNo);
return format.isValid();
}
///////////////////////////////////////////////////////////////////////////////////////////////////
sk_sp<const GrCaps> GrRecordingContextPriv::refCaps() const {
return fContext->refCaps();
}
void GrRecordingContextPriv::addOnFlushCallbackObject(GrOnFlushCallbackObject* onFlushCBObject) {
fContext->addOnFlushCallbackObject(onFlushCBObject);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef SK_ENABLE_DUMP_GPU
#include "src/utils/SkJSONWriter.h"
void GrRecordingContext::dumpJSON(SkJSONWriter* writer) const {
writer->beginObject();
#if GR_GPU_STATS
writer->appendS32("path_masks_generated", this->stats()->numPathMasksGenerated());
writer->appendS32("path_mask_cache_hits", this->stats()->numPathMaskCacheHits());
#endif
writer->endObject();
}
#else
void GrRecordingContext::dumpJSON(SkJSONWriter*) const { }
#endif
#if GR_TEST_UTILS
#if GR_GPU_STATS
void GrRecordingContext::Stats::dump(SkString* out) {
out->appendf("Num Path Masks Generated: %d\n", fNumPathMasksGenerated);
out->appendf("Num Path Mask Cache Hits: %d\n", fNumPathMaskCacheHits);
}
void GrRecordingContext::Stats::dumpKeyValuePairs(SkTArray<SkString>* keys,
SkTArray<double>* values) {
keys->push_back(SkString("path_masks_generated"));
values->push_back(fNumPathMasksGenerated);
keys->push_back(SkString("path_mask_cache_hits"));
values->push_back(fNumPathMaskCacheHits);
}
#endif // GR_GPU_STATS
#endif // GR_TEST_UTILS
<|endoftext|> |
<commit_before>8190619e-4b02-11e5-80bb-28cfe9171a43<commit_msg>oh my, I hate charles<commit_after>819dd11c-4b02-11e5-812c-28cfe9171a43<|endoftext|> |
<commit_before>#include <fstream>
#include <string>
#include <vpr/DynLoad/Library.h>
#include <vpr/System.h>
#include <modules/TestInterface.h>
#include <LibraryTest.h>
namespace vprTest
{
static const std::string C_MOD("libcmod.so");
void LibraryTest::setUp()
{
std::string c_lib_path(MODULE_DIR);
c_lib_path += "/" + C_MOD;
mCModuleName = c_lib_path;
std::string cxx_lib_path(MODULE_DIR);
cxx_lib_path += "/libcxxmod.so";
mCxxModuleName = cxx_lib_path;
}
void LibraryTest::namingTest()
{
const std::string lib_name("libTest.so");
vpr::Library lib(lib_name);
CPPUNIT_ASSERT(lib.getName() == lib_name && "Names do not match");
}
void LibraryTest::loadTest()
{
// Test for library existence. This could be done better.
std::ifstream mod_file;
mod_file.open(mCModuleName.c_str());
CPPUNIT_ASSERT(mod_file.good() && "Module does not exist");
mod_file.close();
vpr::ReturnStatus status;
vpr::Library c_lib(mCModuleName);
status = c_lib.load();
CPPUNIT_ASSERT(status.success() && "Load failed");
}
void LibraryTest::unloadTest()
{
// Test for library existence. This could be done better.
std::ifstream mod_file;
mod_file.open(mCModuleName.c_str());
CPPUNIT_ASSERT(mod_file.good() && "Module does not exist");
mod_file.close();
vpr::ReturnStatus status;
vpr::Library c_lib(mCModuleName);
status = c_lib.load();
CPPUNIT_ASSERT(status.success() && "Load failed");
status = c_lib.unload();
CPPUNIT_ASSERT(status.success() && "Unload failed");
}
void LibraryTest::libraryPathTest()
{
vpr::ReturnStatus status;
vpr::Library lib(C_MOD);
status = vpr::System::setenv(std::string("LD_LIBRARY_PATH"),
std::string(MODULE_DIR));
CPPUNIT_ASSERT(status.success() && "Failed to extend library path");
status = lib.load();
CPPUNIT_ASSERT(status.success() && "Library load failed");
}
void LibraryTest::loadCSymbolTest()
{
vpr::Library c_lib(mCModuleName);
int (*test_func)();
vpr::ReturnStatus status;
status = c_lib.load();
CPPUNIT_ASSERT(status.success() && "C module load failed");
// This is the weirdest cast I have ever written.
test_func = (int(*)()) c_lib.findSymbol("function");
CPPUNIT_ASSERT(NULL != test_func && "Symbol lookup failed");
int result = (*test_func)();
CPPUNIT_ASSERT(1 == result && "Wrong result from loaded function");
test_func = (int(*)()) c_lib.findSymbol("bogusFunc");
CPPUNIT_ASSERT(NULL == test_func && "Found non-existent symbol");
status = c_lib.unload();
CPPUNIT_ASSERT(status.success() && "C module unload failed");
}
void LibraryTest::loadCxxSymbolTest()
{
vpr::Library cxx_lib(mCxxModuleName);
void* (*creator)();
TestInterface* test_obj;
vpr::ReturnStatus status;
status = cxx_lib.load();
CPPUNIT_ASSERT(status.success() && "C++ module load failed");
// No, *this* is the weirdest cast I have ever written.
creator = (void*(*)()) cxx_lib.findSymbol("entryFunc");
CPPUNIT_ASSERT(NULL != creator && "Entry point lookup failed");
void* object = (*creator)();
CPPUNIT_ASSERT(NULL != test_obj && "Object creation failed");
// Is there a way to test that this cast was successful?
test_obj = static_cast<TestInterface*>(object);
// CPPUNIT_ASSERT(NULL != test_obj && "Dynamic casting of created object failed");
CPPUNIT_ASSERT(test_obj->function() == true && "Unexpected results from TestInterface object");
status = cxx_lib.unload();
CPPUNIT_ASSERT(status.success() && "C++ module unload failed");
}
}
<commit_msg>Bug fixed: The wrong pointer value was tested after the creator function was called.<commit_after>#include <fstream>
#include <string>
#include <vpr/DynLoad/Library.h>
#include <vpr/System.h>
#include <modules/TestInterface.h>
#include <LibraryTest.h>
namespace vprTest
{
static const std::string C_MOD("libcmod.so");
void LibraryTest::setUp()
{
std::string c_lib_path(MODULE_DIR);
c_lib_path += "/" + C_MOD;
mCModuleName = c_lib_path;
std::string cxx_lib_path(MODULE_DIR);
cxx_lib_path += "/libcxxmod.so";
mCxxModuleName = cxx_lib_path;
}
void LibraryTest::namingTest()
{
const std::string lib_name("libTest.so");
vpr::Library lib(lib_name);
CPPUNIT_ASSERT(lib.getName() == lib_name && "Names do not match");
}
void LibraryTest::loadTest()
{
// Test for library existence. This could be done better.
std::ifstream mod_file;
mod_file.open(mCModuleName.c_str());
CPPUNIT_ASSERT(mod_file.good() && "Module does not exist");
mod_file.close();
vpr::ReturnStatus status;
vpr::Library c_lib(mCModuleName);
status = c_lib.load();
CPPUNIT_ASSERT(status.success() && "Load failed");
}
void LibraryTest::unloadTest()
{
// Test for library existence. This could be done better.
std::ifstream mod_file;
mod_file.open(mCModuleName.c_str());
CPPUNIT_ASSERT(mod_file.good() && "Module does not exist");
mod_file.close();
vpr::ReturnStatus status;
vpr::Library c_lib(mCModuleName);
status = c_lib.load();
CPPUNIT_ASSERT(status.success() && "Load failed");
status = c_lib.unload();
CPPUNIT_ASSERT(status.success() && "Unload failed");
}
void LibraryTest::libraryPathTest()
{
vpr::ReturnStatus status;
vpr::Library lib(C_MOD);
status = vpr::System::setenv(std::string("LD_LIBRARY_PATH"),
std::string(MODULE_DIR));
CPPUNIT_ASSERT(status.success() && "Failed to extend library path");
status = lib.load();
CPPUNIT_ASSERT(status.success() && "Library load failed");
}
void LibraryTest::loadCSymbolTest()
{
vpr::Library c_lib(mCModuleName);
int (*test_func)();
vpr::ReturnStatus status;
status = c_lib.load();
CPPUNIT_ASSERT(status.success() && "C module load failed");
// This is the weirdest cast I have ever written.
test_func = (int(*)()) c_lib.findSymbol("function");
CPPUNIT_ASSERT(NULL != test_func && "Symbol lookup failed");
int result = (*test_func)();
CPPUNIT_ASSERT(1 == result && "Wrong result from loaded function");
test_func = (int(*)()) c_lib.findSymbol("bogusFunc");
CPPUNIT_ASSERT(NULL == test_func && "Found non-existent symbol");
status = c_lib.unload();
CPPUNIT_ASSERT(status.success() && "C module unload failed");
}
void LibraryTest::loadCxxSymbolTest()
{
vpr::Library cxx_lib(mCxxModuleName);
void* (*creator)();
TestInterface* test_obj(NULL);
vpr::ReturnStatus status;
status = cxx_lib.load();
CPPUNIT_ASSERT(status.success() && "C++ module load failed");
// No, *this* is the weirdest cast I have ever written.
creator = (void*(*)()) cxx_lib.findSymbol("entryFunc");
CPPUNIT_ASSERT(NULL != creator && "Entry point lookup failed");
void* object = (*creator)();
CPPUNIT_ASSERT(NULL != object && "Object creation failed");
// Is there a way to test that this cast was successful?
test_obj = static_cast<TestInterface*>(object);
// CPPUNIT_ASSERT(NULL != test_obj && "Dynamic casting of created object failed");
CPPUNIT_ASSERT(test_obj->function() == true && "Unexpected results from TestInterface object");
status = cxx_lib.unload();
CPPUNIT_ASSERT(status.success() && "C++ module unload failed");
}
}
<|endoftext|> |
<commit_before>8b33256d-2d14-11e5-af21-0401358ea401<commit_msg>8b33256e-2d14-11e5-af21-0401358ea401<commit_after>8b33256e-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include "aquila/global.h"
#include "aquila/source/generator/SquareGenerator.h"
#include "aquila/source/SignalSource.h"
#include "aquila/transform/FftFactory.h"
#include "aquila/tools/TextPlot.h"
#include "aquila/source/WaveFile.h"
#include <algorithm>
#include <functional>
#include <memory>
#include <iostream>
#include <cstdlib>
using namespace std;
const std::size_t SIZE = 512;
void findMax(Aquila::SpectrumType spectrum, Aquila::FrequencyType sampleFreq)
{
std::size_t halfLength = spectrum.size() / 2;
std::vector<double> absSpectrum(halfLength);
double max = 0;
int peak_freq = 0;
for (std::size_t i = 0; i < halfLength; ++i)
{
absSpectrum[i] = std::abs(spectrum[i]);
//cout << i*(sampleFreq/halfLength)<< " amp " <<absSpectrum[i] << endl;
if(absSpectrum[i] > max){
max = absSpectrum[i];
peak_freq = i*(sampleFreq/halfLength)/2;
}
}
cout << "\n\npeak freq for input with sample size: "<< halfLength*2 << " which needs to be pow of 2" <<endl;
cout <<peak_freq << " Hz max amp:" << max << endl;
//plot(absSpectrum);
}
void freqOfindex(std::size_t start, Aquila::WaveFile wav){
Aquila::FrequencyType sampleFreq = wav.getSampleFrequency();
vector<Aquila::SampleType> chunk;
for (std::size_t i =start; i< start+SIZE; ++i)
{
chunk.push_back(wav.sample(i));
}
Aquila::SignalSource data(chunk, sampleFreq);
Aquila::TextPlot plt("input wave");
auto fft = Aquila::FftFactory::getFft(SIZE);
Aquila::SpectrumType spectrum = fft->fft(data.toArray());
plt.setTitle("Signal spectrum of "+ std::to_string(start));
findMax(spectrum, sampleFreq);
plt.plotSpectrum(spectrum);
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
std::cout << "Usage: main <FILENAME>" << std::endl;
return 1;
}
Aquila::WaveFile wav(argv[1]);
const std::size_t END = wav.getSamplesCount();
std::size_t start = 0;
while(start < END && wav.sample(start) <= 1000 ) start++;
//220500
cout << END <<endl;
cout << start;
for(int x = start; x < END; x+=END/5) freqOfindex(x, wav);
return 0;
}
<commit_msg>track max freq<commit_after>#include "aquila/global.h"
#include "aquila/source/generator/SquareGenerator.h"
#include "aquila/source/SignalSource.h"
#include "aquila/transform/FftFactory.h"
#include "aquila/tools/TextPlot.h"
#include "aquila/source/WaveFile.h"
#include <algorithm>
#include <functional>
#include <memory>
#include <iostream>
#include <cstdlib>
using namespace std;
const std::size_t SIZE = 512;
void findMax(Aquila::SpectrumType spectrum, Aquila::FrequencyType sampleFreq)
{
std::size_t halfLength = spectrum.size() / 2;
std::vector<double> absSpectrum(halfLength);
double max = 0;
int peak_freq = 0;
for (std::size_t i = 0; i < halfLength; ++i)
{
absSpectrum[i] = std::abs(spectrum[i]);
//cout << i*(sampleFreq/halfLength)<< " amp " <<absSpectrum[i] << endl;
if(absSpectrum[i] > max){
max = absSpectrum[i];
peak_freq = i*(sampleFreq/halfLength)/2;
}
}
cout << "peak freq for input with sample size: "<< halfLength*2 << " which needs to be pow of 2" <<endl;
cout <<peak_freq << " Hz max amp:" << max << endl;
//plot(absSpectrum);
}
void freqOfindex(std::size_t start, Aquila::WaveFile wav){
Aquila::FrequencyType sampleFreq = wav.getSampleFrequency();
vector<Aquila::SampleType> chunk;
for (std::size_t i =start; i< start+SIZE; ++i)
{
chunk.push_back(wav.sample(i));
}
Aquila::SignalSource data(chunk, sampleFreq);
Aquila::TextPlot plt("input wave");
auto fft = Aquila::FftFactory::getFft(SIZE);
cout << "\n\nSignal spectrum of "<<start<< endl;
Aquila::SpectrumType spectrum = fft->fft(data.toArray());
plt.setTitle("Signal spectrum of "+ std::to_string(start));
findMax(spectrum, sampleFreq);
// plt.plotSpectrum(spectrum);
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
std::cout << "Usage: main <FILENAME>" << std::endl;
return 1;
}
Aquila::WaveFile wav(argv[1]);
const std::size_t END = wav.getSamplesCount();
std::size_t start = 0;
while(start < END && wav.sample(start) <= 1000 ) start++;
//220500 = 5*44100
// cout << END <<endl;
// cout << start;
for(int x = start; x < END; x+=END/5) freqOfindex(x, wav);
return 0;
}
<|endoftext|> |
<commit_before>64a652d4-2e4f-11e5-bbdc-28cfe91dbc4b<commit_msg>64adbd3a-2e4f-11e5-aee7-28cfe91dbc4b<commit_after>64adbd3a-2e4f-11e5-aee7-28cfe91dbc4b<|endoftext|> |
<commit_before>7614e924-2d53-11e5-baeb-247703a38240<commit_msg>761568e0-2d53-11e5-baeb-247703a38240<commit_after>761568e0-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>77458538-2d53-11e5-baeb-247703a38240<commit_msg>77460404-2d53-11e5-baeb-247703a38240<commit_after>77460404-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>1d92e1d1-2e4f-11e5-99bc-28cfe91dbc4b<commit_msg>1d9c0e38-2e4f-11e5-bad7-28cfe91dbc4b<commit_after>1d9c0e38-2e4f-11e5-bad7-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <GLFW/glfw3.h>
#include <GL/glu.h>
#include <iostream>
#include <vector>
#include <cmath>
#include <random>
#include <cctype>
#include "RubiksCube.hpp"
constexpr GLdouble const vertex[6][4][3] =
{
{
{-2, 1, 1},
{-2, 1, -1},
{-2, -1, -1},
{-2, -1, 1}
},
{
{1, -2, 1},
{-1, -2, 1},
{-1, -2, -1},
{1, -2, -1}
},
{
{1, 1, -2},
{1, -1, -2},
{-1, -1, -2},
{-1, 1, -2}
},
{
{1, 1, 2},
{1, -1, 2},
{-1, -1, 2},
{-1, 1, 2}
},
{
{1, 2, 1},
{-1, 2, 1},
{-1, 2, -1},
{1, 2, -1}
},
{
{2, 1, 1},
{2, 1, -1},
{2, -1, -1},
{2, -1, 1}
},
};
GLubyte color[][3] =
{
{0xFF, 0xA0, 0x00},
{0xFF, 0xFF, 0x00},
{0x00, 0xFF, 0x00},
{0x00, 0x00, 0xFF},
{0xFF, 0xFF, 0xFF},
{0xFF, 0x00, 0x00}
};
int main(int argc, char * argv[])
{
constexpr int SIZE = 3;
RubiksCube<SIZE> rc;
glfwInit();
int count;
GLFWmonitor ** monitors = glfwGetMonitors(&count);
GLFWmonitor * monitor = monitors[1];//glfwGetPrimaryMonitor();
GLFWvidmode const * mode = glfwGetVideoMode(monitor);
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
GLFWwindow * window = glfwCreateWindow(mode->width, mode->height, "RubiksCube", monitor, nullptr);
glfwMakeContextCurrent(window);
/*auto pa = [&](std::string s)
{
for (auto i = s.begin(); i != s.end(); ++i)
{
Axis axis = static_cast<Axis>(std::tolower(*i) - 'x');
bool isPrime = std::isupper(*i);
++i;
int index = *i - '0';
rc.rotate(axis, index, isPrime);
}
};*/
while(!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glPopMatrix();
glPushMatrix();
//window size chagne
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glLoadIdentity();
gluPerspective(90, static_cast<double>(width) / static_cast<double>(height), 1, 128);
gluLookAt(10, 10, 10, 0, 0, 0, 0, 1, 0);
//view
static int theta = 0;
static int iota = 0;
if (glfwGetKey(window, GLFW_KEY_RIGHT))
{
++theta;
}
if (glfwGetKey(window, GLFW_KEY_LEFT))
{
--theta;
}
if (glfwGetKey(window, GLFW_KEY_UP))
{
++iota;
}
if (glfwGetKey(window, GLFW_KEY_DOWN))
{
--iota;
}
//animation
static int index = 0;
static Axis axis = {};
static double angle = 0;
static bool isPrime = {};
//key
static bool key[256] = {};
for (int i = 0; i < 256; ++i)
{
if (glfwGetKey(window, static_cast<char>(i)))
{
if (!key[i])
{
switch (static_cast<char>(i))
{
case '1':
index = 0;
break;
case '2':
index = 1;
break;
case '3':
index = 2;
break;
case 'X':
axis = Axis::X;
isPrime = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT);
angle = 90;
rc.rotate(axis, index, isPrime);
break;
case 'C':
axis = Axis::Y;
isPrime = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT);
angle = 90;
rc.rotate(axis, index, isPrime);
break;
case 'Z':
axis = Axis::Z;
angle = 90;
isPrime = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT);
rc.rotate(axis, index, isPrime);
break;
case 'R':
{
//pa("X2Y2Z0x2y1z0");
static std::mt19937 engine(std::random_device{}());
std::uniform_int_distribution<int> axis(0, 2);
std::uniform_int_distribution<int> index(0, SIZE - 1);
std::uniform_int_distribution<bool> isPrime(false, true);
for (int i = 0; i < 128; ++i)
{
rc.rotate(static_cast<Axis>(axis(engine)), index(engine), isPrime(engine));
}
break;
}
case 'S':
rc.solve();
break;
default:
break;
}
}
key[i] = true;
}
else
{
key[i] = false;
}
}
//animation
if (angle > 0)
{
angle -= 10;
}
//view
glRotated(theta, 0, 1, 0);
glRotated(iota, 1, 0, 0);
//centralize
glTranslated(-4, -4, -4);
for (int i = 0; i < SIZE; ++i)
{
for (int j = 0; j < SIZE; ++j)
{
for (int k = 0; k < SIZE; ++k)
{
for (auto && e : rc.getCube(i, j, k))
{
glPushMatrix();
//animation
if (angle > 0)
{
std::array<int, 3> wrapper = {i, j, k};
if (wrapper[static_cast<int>(axis)] == index)
{
glTranslated(((axis == Axis::X) ? 0 : 4), ((axis == Axis::Y) ? 0 : 4), ((axis == Axis::Z) ? 0 : 4));
glRotated(isPrime ? -angle : angle, ((axis == Axis::X) ? 1 : 0), ((axis == Axis::Y) ? 1 : 0), ((axis == Axis::Z) ? 1 : 0));
glTranslated(((axis == Axis::X) ? 0 : -4), ((axis == Axis::Y) ? 0 : -4), ((axis == Axis::Z) ? 0 : -4));
}
}
glTranslated(i * 4, j * 4, k * 4);
glColor3ubv(color[static_cast<int>(e.second)]);
glBegin(GL_QUADS);
for (auto && e : vertex[static_cast<int>(e.first)])
{
glVertex3dv(e);
}
glEnd();
glPopMatrix();
}
}
}
}
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
}
<commit_msg>remove arg<commit_after>#include <GLFW/glfw3.h>
#include <GL/glu.h>
#include <iostream>
#include <vector>
#include <cmath>
#include <random>
#include <cctype>
#include "RubiksCube.hpp"
constexpr GLdouble const vertex[6][4][3] =
{
{
{-2, 1, 1},
{-2, 1, -1},
{-2, -1, -1},
{-2, -1, 1}
},
{
{1, -2, 1},
{-1, -2, 1},
{-1, -2, -1},
{1, -2, -1}
},
{
{1, 1, -2},
{1, -1, -2},
{-1, -1, -2},
{-1, 1, -2}
},
{
{1, 1, 2},
{1, -1, 2},
{-1, -1, 2},
{-1, 1, 2}
},
{
{1, 2, 1},
{-1, 2, 1},
{-1, 2, -1},
{1, 2, -1}
},
{
{2, 1, 1},
{2, 1, -1},
{2, -1, -1},
{2, -1, 1}
},
};
GLubyte color[][3] =
{
{0xFF, 0xA0, 0x00},
{0xFF, 0xFF, 0x00},
{0x00, 0xFF, 0x00},
{0x00, 0x00, 0xFF},
{0xFF, 0xFF, 0xFF},
{0xFF, 0x00, 0x00}
};
int main()
{
constexpr int SIZE = 3;
RubiksCube<SIZE> rc;
glfwInit();
int count;
GLFWmonitor ** monitors = glfwGetMonitors(&count);
GLFWmonitor * monitor = monitors[1];//glfwGetPrimaryMonitor();
GLFWvidmode const * mode = glfwGetVideoMode(monitor);
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
GLFWwindow * window = glfwCreateWindow(mode->width, mode->height, "RubiksCube", monitor, nullptr);
glfwMakeContextCurrent(window);
/*auto pa = [&](std::string s)
{
for (auto i = s.begin(); i != s.end(); ++i)
{
Axis axis = static_cast<Axis>(std::tolower(*i) - 'x');
bool isPrime = std::isupper(*i);
++i;
int index = *i - '0';
rc.rotate(axis, index, isPrime);
}
};*/
while(!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glPopMatrix();
glPushMatrix();
//window size chagne
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glLoadIdentity();
gluPerspective(90, static_cast<double>(width) / static_cast<double>(height), 1, 128);
gluLookAt(10, 10, 10, 0, 0, 0, 0, 1, 0);
//view
static int theta = 0;
static int iota = 0;
if (glfwGetKey(window, GLFW_KEY_RIGHT))
{
++theta;
}
if (glfwGetKey(window, GLFW_KEY_LEFT))
{
--theta;
}
if (glfwGetKey(window, GLFW_KEY_UP))
{
++iota;
}
if (glfwGetKey(window, GLFW_KEY_DOWN))
{
--iota;
}
//animation
static int index = 0;
static Axis axis = {};
static double angle = 0;
static bool isPrime = {};
//key
static bool key[256] = {};
for (int i = 0; i < 256; ++i)
{
if (glfwGetKey(window, static_cast<char>(i)))
{
if (!key[i])
{
switch (static_cast<char>(i))
{
case '1':
index = 0;
break;
case '2':
index = 1;
break;
case '3':
index = 2;
break;
case 'X':
axis = Axis::X;
isPrime = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT);
angle = 90;
rc.rotate(axis, index, isPrime);
break;
case 'C':
axis = Axis::Y;
isPrime = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT);
angle = 90;
rc.rotate(axis, index, isPrime);
break;
case 'Z':
axis = Axis::Z;
angle = 90;
isPrime = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT);
rc.rotate(axis, index, isPrime);
break;
case 'R':
{
//pa("X2Y2Z0x2y1z0");
static std::mt19937 engine(std::random_device{}());
std::uniform_int_distribution<int> axis(0, 2);
std::uniform_int_distribution<int> index(0, SIZE - 1);
std::uniform_int_distribution<bool> isPrime(false, true);
for (int i = 0; i < 128; ++i)
{
rc.rotate(static_cast<Axis>(axis(engine)), index(engine), isPrime(engine));
}
break;
}
case 'S':
rc.solve();
break;
default:
break;
}
}
key[i] = true;
}
else
{
key[i] = false;
}
}
//animation
if (angle > 0)
{
angle -= 10;
}
//view
glRotated(theta, 0, 1, 0);
glRotated(iota, 1, 0, 0);
//centralize
glTranslated(-4, -4, -4);
for (int i = 0; i < SIZE; ++i)
{
for (int j = 0; j < SIZE; ++j)
{
for (int k = 0; k < SIZE; ++k)
{
for (auto && e : rc.getCube(i, j, k))
{
glPushMatrix();
//animation
if (angle > 0)
{
std::array<int, 3> wrapper = {i, j, k};
if (wrapper[static_cast<int>(axis)] == index)
{
glTranslated(((axis == Axis::X) ? 0 : 4), ((axis == Axis::Y) ? 0 : 4), ((axis == Axis::Z) ? 0 : 4));
glRotated(isPrime ? -angle : angle, ((axis == Axis::X) ? 1 : 0), ((axis == Axis::Y) ? 1 : 0), ((axis == Axis::Z) ? 1 : 0));
glTranslated(((axis == Axis::X) ? 0 : -4), ((axis == Axis::Y) ? 0 : -4), ((axis == Axis::Z) ? 0 : -4));
}
}
glTranslated(i * 4, j * 4, k * 4);
glColor3ubv(color[static_cast<int>(e.second)]);
glBegin(GL_QUADS);
for (auto && e : vertex[static_cast<int>(e.first)])
{
glVertex3dv(e);
}
glEnd();
glPopMatrix();
}
}
}
}
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
}
<|endoftext|> |
<commit_before>f589b270-585a-11e5-93fc-6c40088e03e4<commit_msg>f590e04a-585a-11e5-94c2-6c40088e03e4<commit_after>f590e04a-585a-11e5-94c2-6c40088e03e4<|endoftext|> |
<commit_before>24fa16bd-2748-11e6-8f91-e0f84713e7b8<commit_msg>this is my first commit?<commit_after>2517bb75-2748-11e6-b4ad-e0f84713e7b8<|endoftext|> |
<commit_before>53c265be-2e3a-11e5-af4b-c03896053bdd<commit_msg>53cfd5a8-2e3a-11e5-8979-c03896053bdd<commit_after>53cfd5a8-2e3a-11e5-8979-c03896053bdd<|endoftext|> |
<commit_before>c720571e-327f-11e5-8d13-9cf387a8033e<commit_msg>c7273ab5-327f-11e5-9811-9cf387a8033e<commit_after>c7273ab5-327f-11e5-9811-9cf387a8033e<|endoftext|> |
<commit_before>17b1c574-585b-11e5-a19c-6c40088e03e4<commit_msg>17b83bdc-585b-11e5-9ebe-6c40088e03e4<commit_after>17b83bdc-585b-11e5-9ebe-6c40088e03e4<|endoftext|> |
<commit_before>8b3325f7-2d14-11e5-af21-0401358ea401<commit_msg>8b3325f8-2d14-11e5-af21-0401358ea401<commit_after>8b3325f8-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>81cf0db7-2d15-11e5-af21-0401358ea401<commit_msg>81cf0db8-2d15-11e5-af21-0401358ea401<commit_after>81cf0db8-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include <linux/input.h>
#include <linux/fb.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fstream>
#include <stdexcept>
class Fb {
public:
Fb() : m_fd(open("/dev/fb1", O_RDWR)) {
if (m_fd == -1) {
throw std::runtime_error(strerror(errno));
}
ioctl(m_fd, FBIOGET_VSCREENINFO, &m_vinfo);
ioctl(m_fd, FBIOGET_FSCREENINFO, &m_finfo);
}
~Fb() { close(m_fd); }
int getFd() const { return m_fd; }
int getScreenSize() const {
return m_vinfo.yres_virtual * m_finfo.line_length;
}
int adjust(int& x, int& y) const {
x = x % m_vinfo.xres;
y = y % m_vinfo.yres;
}
int getLocation(int x, int y) const {
return (x + m_vinfo.xoffset) * (m_vinfo.bits_per_pixel / 8) +
(y + m_vinfo.yoffset) * m_finfo.line_length;
}
private:
int m_fd;
fb_fix_screeninfo m_finfo;
fb_var_screeninfo m_vinfo;
};
class Map {
public:
Map()
: m_fb(),
m_ptr(static_cast<char*>(mmap(nullptr, m_fb.getScreenSize(),
PROT_READ | PROT_WRITE,
MAP_SHARED, m_fb.getFd(), 0))) {
if (m_ptr == MAP_FAILED) {
throw std::runtime_error(strerror(errno));
}
}
~Map() { munmap(m_ptr, m_fb.getScreenSize()); }
int adjust(int& x, int& y) const { m_fb.adjust(x, y); }
unsigned short& pixel(int x, int y) {
return reinterpret_cast<unsigned short&>(
m_ptr[m_fb.getLocation(x, y)]);
}
private:
Fb m_fb;
char* m_ptr;
};
int main(int argc, char* argv[]) {
Map map;
std::ifstream event("/dev/input/event0",
std::ifstream::in | std::ifstream::binary);
input_event ev;
int x(0), y(0);
unsigned short color(-1);
map.pixel(x, y) = -1;
while (event.read(reinterpret_cast<char*>(&ev), sizeof(ev))) {
if (ev.type == EV_KEY && ev.value != 0) {
map.pixel(x, y) = 0;
switch (ev.code) {
case KEY_UP:
--y;
break;
case KEY_DOWN:
++y;
break;
case KEY_LEFT:
--x;
break;
case KEY_RIGHT:
++x;
break;
case KEY_ENTER:
color = rand();
break;
}
map.adjust(x, y);
map.pixel(x, y) = color;
}
}
return 0;
}
<commit_msg>added a target to hunt<commit_after>#include <linux/input.h>
#include <linux/fb.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fstream>
#include <stdexcept>
class Fb {
public:
Fb() : m_fd(open("/dev/fb1", O_RDWR)) {
if (m_fd == -1) {
throw std::runtime_error(strerror(errno));
}
ioctl(m_fd, FBIOGET_VSCREENINFO, &m_vinfo);
ioctl(m_fd, FBIOGET_FSCREENINFO, &m_finfo);
}
~Fb() { close(m_fd); }
int getFd() const { return m_fd; }
int getScreenSize() const {
return m_vinfo.yres_virtual * m_finfo.line_length;
}
int adjust(int& x, int& y) const {
x = x % m_vinfo.xres;
y = y % m_vinfo.yres;
}
int getLocation(int x, int y) const {
return (x + m_vinfo.xoffset) * (m_vinfo.bits_per_pixel / 8) +
(y + m_vinfo.yoffset) * m_finfo.line_length;
}
private:
int m_fd;
fb_fix_screeninfo m_finfo;
fb_var_screeninfo m_vinfo;
};
class Map {
public:
Map()
: m_fb(),
m_ptr(static_cast<char*>(mmap(nullptr, m_fb.getScreenSize(),
PROT_READ | PROT_WRITE,
MAP_SHARED, m_fb.getFd(), 0))) {
if (m_ptr == MAP_FAILED) {
throw std::runtime_error(strerror(errno));
}
}
~Map() { munmap(m_ptr, m_fb.getScreenSize()); }
int adjust(int& x, int& y) const { m_fb.adjust(x, y); }
unsigned short& pixel(int x, int y) {
return reinterpret_cast<unsigned short&>(
m_ptr[m_fb.getLocation(x, y)]);
}
private:
Fb m_fb;
char* m_ptr;
};
int main(int argc, char* argv[]) {
Map map;
std::ifstream event("/dev/input/event0",
std::ifstream::in | std::ifstream::binary);
input_event ev;
int x(0), y(0);
int xt(0), yt(0);
unsigned short color(-1);
map.pixel(x, y) = -1;
while (event.read(reinterpret_cast<char*>(&ev), sizeof(ev))) {
if (ev.type == EV_KEY && ev.value != 0) {
map.pixel(x, y) = 0;
switch (ev.code) {
case KEY_UP:
--y;
break;
case KEY_DOWN:
++y;
break;
case KEY_LEFT:
--x;
break;
case KEY_RIGHT:
++x;
break;
case KEY_ENTER:
color = rand();
break;
}
map.adjust(x, y);
map.pixel(x, y) = color;
}
if (xt == x && yt == y) {
xt = rand();
yt = rand();
map.adjust(xt, yt);
map.pixel(xt, yt) = -1;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Turbo C++11 metaprogramming Library *
* *
* Copyright (C) 2013 - 2014, Manuel Sánchez Pérez *
* *
* This file is part of The Turbo Library. *
* *
* The Turbo Library is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation, version 2 of the License. *
* *
* The Turbo Library 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with The Turbo Library. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#include "eval.hpp"
#include "placeholders.hpp"
#include "let_expressions.hpp"
#include "lazy.hpp"
#include "lambda.hpp"
#include "algorithm.hpp"
#include "integral_lists.hpp"
#include "basic_types.hpp"
#include "utils/assert.hpp"
#include "warning.hpp"
#include "impl/demangle.hpp"
#include "integral_iterators.hpp"
#include "fixed_point.hpp"
#include "stl_adapters.hpp"
#include "bind.hpp"
#include "to_runtime.hpp"
#include <iostream>
#include <vector>
#include <memory>
#include <type_traits>
using namespace tml::placeholders;
#define RUN_UNIT_TESTS
#ifdef RUN_UNIT_TESTS
template<typename... ARGS>
struct f
{
using result = tml::list<ARGS...>;
};
using t1 = tml::eval<Int<0>>;
using t2 = tml::eval<f<_1,_2,_3>,Int<1>,Int<2>,Int<3>>;
using t3 = tml::eval<tml::lazy<f>,Int<1>,Int<2>,Int<3>>;
using t4 = tml::eval<tml::lambda<_1,f<_1,Int<2>,Int<3>>>,Int<1>>;
using t5 = tml::eval<tml::multi_let<_1,_2,_3,Int<1>,Int<2>,Int<3>,f<_1,_2,_3>>>;
using t6 = tml::eval<tml::multi_lambda<_1,_2,_3 , f<_1,_2,_3>>,Int<1>,Int<2>,Int<3>>;
constexpr bool a = tml::is_function<Int<0>>::value;
TURBO_ASSERT((std::is_same<TURBO_SFINAE(
DISABLE_IF(tml::is_function<Int<0>>) ,
DISABLE_IF(tml::overrides_eval<Int<0>>)
),tml::sfinae_return>));
TURBO_ASSERT((std::is_same<t1,tml::integer<0>>));
TURBO_ASSERT((std::is_same<t2,tml::integer_list<1,2,3>>));
TURBO_ASSERT((std::is_same<t3,tml::integer_list<1,2,3>>));
TURBO_ASSERT((std::is_same<t4,tml::integer_list<1,2,3>>));
TURBO_ASSERT((std::is_same<t5,tml::integer_list<1,2,3>>));
TURBO_ASSERT((std::is_same<t6,tml::integer_list<1,2,3>>));
#endif /* RUN_UNIT_TESTS */
template<typename N>
struct odd : public tml::function<tml::boolean<(N::value % 2) == 0>>
{};
#ifndef RANGE_END
#define RANGE_END 20
#endif
using numbers = tml::integer_list<0,1,2,3,4,5>;
using numbers2 = tml::integer_range<0,RANGE_END>;
using map_test = tml::map<tml::lazy<odd>,numbers2>;
using any_of_test = tml::any<tml::lazy<odd>,tml::iterator::begin<numbers> , tml::iterator::end<numbers>>;
using all_of_test = tml::all<tml::lazy<odd>,tml::integer_list<0,1,2,3,4,5>>;
using x = tml::fsingle<(1 << 7)>; //0.5
using y = tml::fsingle<(1 << 9)>; //2.0
using z = tml::eval<tml::div<x,y>>; //0.25?
using w = tml::eval<tml::mul<z,y>>; //0.5?
template<typename T>
using this_is_not_java_vector = std::vector<tml::eval<tml::stl::function<std::remove_pointer<T>>>>;
template<typename T>
using this_is_how_you_should_do_polymorphism = std::vector<std::unique_ptr<tml::stl::eval<std::remove_pointer<T>>>>;
TURBO_ASSERT(( std::is_same<std::vector<int>,this_is_not_java_vector<int*>> ));
template<typename T>
struct quux;
template<>
struct quux<char>
{};
//Conditional selection of potentially ill-formed types! Thanks to Turbo tml::lazy its easy:
using ok = tml::lazy_instance<tml::conditional<tml::false_type,
tml::lazy<quux,char>,
tml::lazy<quux,bool>
>
>;
TURBO_ASSERT(( std::is_same<ok,quux<bool>> ));
template<typename A , typename B , typename C>
struct third_arg : public tml::function<C>
{};
using b = tml::bind<third_arg,_3,_2,_1>;
using bcall = tml::eval<b,char,char,int>; //Equivalent to tml::eval<third_arg<int,bool,char>>
TURBO_ASSERT(( std::is_same<bcall,char> ));
int main()
{
std::cout << tml::to_string<numbers>() << std::endl;
std::cout << tml::to_string<map_test>() << std::endl;
std::cout << tml::to_string<any_of_test>() << std::endl;
std::cout << tml::to_string<all_of_test>() << std::endl;
std::cout << tml::to_string<numbers2>() << std::endl;
std::cout << tml::to_string<x>() << std::endl;
std::cout << tml::to_string<y>() << std::endl;
std::cout << tml::to_string<z>() << std::endl;
std::cout << tml::to_string<w>() << std::endl;
std::cout << tml::to_string<bcall>() << std::endl;
for( auto v : tml::to_runtime<numbers>() )
{
std::cout << v << std::endl;
}
std::cout << "(" << std::boolalpha
<< std::get<0>( tml::to_runtime<tml::list<tml::Char<'a'>,tml::Bool<true>,tml::Int<0>>>() ) << ","
<< std::get<1>( tml::to_runtime<tml::list<tml::Char<'a'>,tml::Bool<true>,tml::Int<0>>>() ) << ","
<< std::get<2>( tml::to_runtime<tml::list<tml::Char<'a'>,tml::Bool<true>,tml::Int<0>>>() ) << ")" << std::endl;
}
<commit_msg>Testing Travis LLVM toolchain<commit_after>/******************************************************************************
* Turbo C++11 metaprogramming Library *
* *
* Copyright (C) 2013 - 2014, Manuel Sánchez Pérez *
* *
* This file is part of The Turbo Library. *
* *
* The Turbo Library is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation, version 2 of the License. *
* *
* The Turbo Library 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with The Turbo Library. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#include "eval.hpp"
#include "placeholders.hpp"
#include "let_expressions.hpp"
#include "lazy.hpp"
#include "lambda.hpp"
#include "algorithm.hpp"
#include "integral_lists.hpp"
#include "basic_types.hpp"
#include "utils/assert.hpp"
#include "warning.hpp"
#include "impl/demangle.hpp"
#include "integral_iterators.hpp"
#include "fixed_point.hpp"
#include "stl_adapters.hpp"
#include "bind.hpp"
#include "to_runtime.hpp"
#include <iostream>
#include <vector>
#include <memory>
#include <type_traits>
using namespace tml::placeholders;
#define RUN_UNIT_TESTS
#ifdef RUN_UNIT_TESTS
template<typename... ARGS>
struct f
{
using result = tml::list<ARGS...>;
};
using t1 = tml::eval<Int<0>>;
using t2 = tml::eval<f<_1,_2,_3>,Int<1>,Int<2>,Int<3>>;
using t3 = tml::eval<tml::lazy<f>,Int<1>,Int<2>,Int<3>>;
using t4 = tml::eval<tml::lambda<_1,f<_1,Int<2>,Int<3>>>,Int<1>>;
using t5 = tml::eval<tml::multi_let<_1,_2,_3,Int<1>,Int<2>,Int<3>,f<_1,_2,_3>>>;
using t6 = tml::eval<tml::multi_lambda<_1,_2,_3 , f<_1,_2,_3>>,Int<1>,Int<2>,Int<3>>;
constexpr bool a = tml::is_function<Int<0>>::value;
TURBO_ASSERT((std::is_same<TURBO_SFINAE(
DISABLE_IF(tml::is_function<Int<0>>) ,
DISABLE_IF(tml::overrides_eval<Int<0>>)
),tml::sfinae_return>));
TURBO_ASSERT((std::is_same<t1,tml::integer<0>>));
TURBO_ASSERT((std::is_same<t2,tml::integer_list<1,2,3>>));
TURBO_ASSERT((std::is_same<t3,tml::integer_list<1,2,3>>));
TURBO_ASSERT((std::is_same<t4,tml::integer_list<1,2,3>>));
TURBO_ASSERT((std::is_same<t5,tml::integer_list<1,2,3>>));
TURBO_ASSERT((std::is_same<t6,tml::integer_list<1,2,3>>));
#endif /* RUN_UNIT_TESTS */
template<typename N>
struct odd : public tml::function<tml::boolean<(N::value % 2) == 0>>
{};
#ifndef RANGE_END
#define RANGE_END 20
#endif
using numbers = tml::integer_list<0,1,2,3,4,5>;
using numbers2 = tml::integer_range<0,RANGE_END>;
using map_test = tml::map<tml::lazy<odd>,numbers2>;
using any_of_test = tml::any<tml::lazy<odd>,tml::iterator::begin<numbers> , tml::iterator::end<numbers>>;
using all_of_test = tml::all<tml::lazy<odd>,tml::integer_list<0,1,2,3,4,5>>;
using x = tml::fsingle<(1 << 7)>; //0.5
using y = tml::fsingle<(1 << 9)>; //2.0
using z = tml::eval<tml::div<x,y>>; //0.25?
using w = tml::eval<tml::mul<z,y>>; //0.5?
template<typename T>
using this_is_not_java_vector = std::vector<tml::eval<tml::stl::function<std::remove_pointer<T>>>>;
template<typename T>
using this_is_how_you_should_do_polymorphism = std::vector<std::unique_ptr<tml::stl::eval<std::remove_pointer<T>>>>;
TURBO_ASSERT(( std::is_same<std::vector<int>,this_is_not_java_vector<int*>> ));
template<typename T>
struct quux;
template<>
struct quux<char>
{};
//Conditional selection of potentially ill-formed types! Thanks to Turbo tml::lazy its easy:
using ok = tml::lazy_instance<tml::conditional<tml::false_type,
tml::lazy<quux,char>,
tml::lazy<quux,bool>
>
>;
TURBO_ASSERT(( std::is_same<ok,quux<bool>> ));
template<typename A , typename B , typename C>
struct third_arg : public tml::function<C>
{};
using b = tml::bind<third_arg , _3,_2,_1>;
using bcall = tml::eval<b,char,char,int>; //Equivalent to tml::eval<third_arg<int,bool,char>>
TURBO_ASSERT(( std::is_same<bcall,char> ));
int main()
{
std::cout << tml::to_string<numbers>() << std::endl;
std::cout << tml::to_string<map_test>() << std::endl;
std::cout << tml::to_string<any_of_test>() << std::endl;
std::cout << tml::to_string<all_of_test>() << std::endl;
std::cout << tml::to_string<numbers2>() << std::endl;
std::cout << tml::to_string<x>() << std::endl;
std::cout << tml::to_string<y>() << std::endl;
std::cout << tml::to_string<z>() << std::endl;
std::cout << tml::to_string<w>() << std::endl;
std::cout << tml::to_string<bcall>() << std::endl;
for( auto v : tml::to_runtime<numbers>() )
{
std::cout << v << std::endl;
}
std::cout << "(" << std::boolalpha
<< std::get<0>( tml::to_runtime<tml::list<tml::Char<'a'>,tml::Bool<true>,tml::Int<0>>>() ) << ","
<< std::get<1>( tml::to_runtime<tml::list<tml::Char<'a'>,tml::Bool<true>,tml::Int<0>>>() ) << ","
<< std::get<2>( tml::to_runtime<tml::list<tml::Char<'a'>,tml::Bool<true>,tml::Int<0>>>() ) << ")" << std::endl;
}
<|endoftext|> |
<commit_before>3036a600-2748-11e6-ab1f-e0f84713e7b8<commit_msg>For roselyn to integrate at some point<commit_after>30436c5c-2748-11e6-8a32-e0f84713e7b8<|endoftext|> |
<commit_before>e8c15782-585a-11e5-bdb1-6c40088e03e4<commit_msg>e8c8046c-585a-11e5-afb0-6c40088e03e4<commit_after>e8c8046c-585a-11e5-afb0-6c40088e03e4<|endoftext|> |
<commit_before>//
// main.cpp
// fxtract
//
// Created by Connor Skennerton on 30/07/13.
// Copyright (c) 2013 Connor Skennerton. All rights reserved.
//
#include <unistd.h>
#include <cstdio>
#include <cassert>
#include "util.h"
#include "fileManager.h"
#include "Fx.h"
extern "C" {
#include "util/ssearch.h"
#include "util/bpsearch.h"
#include "util/msutil.h"
}
#define VERSION "1.0-alpha"
struct Options
{
bool H_flag;
bool Q_flag;
bool G_flag;
bool E_flag;
bool x_flag;
bool r_flag;
bool I_flag;
char * f_flag;
Options() : H_flag(false),
Q_flag(false),
G_flag(false),
E_flag(false),
x_flag(false),
r_flag(false),
I_flag(false),
f_flag(NULL)
{}
};
void printSingle(Fx * mate1, FILE * out ) {
mate1->puts(out);
}
void printPair(Fx* mate1, Fx* mate2, FILE * out) {
// match in the first read print out pair
printSingle(mate1, out);
printSingle(mate2, out);
}
//void usage() {
static const char usage_msg[] =\
"[-hHv] {-f pattern_file | pattern} <read1.fx> [<read2.fx>]\n"
"\t-H Evaluate patterns in the context of headers (default: sequences)\n"
"\t-Q Evaluate patterns in the context of quality scores (default: sequences)\n"
"\t-G pattern is a posix basic regular expression (default: literal substring)\n"
"\t-E pattern is a posix extended regular expression (default: literal substring)\n"
"\t-P pattern is a perl compatable regular expression (default: literal substring)\n"
"\t-x pattern exactly matches the whole string (default: literal substring)\n"
"\t-I The read file is interleaved (both pairs in a single file)\n"
"\t-f <file> File containing patterns, one per line\n"
"\t-h Print this help\n"
"\t-V Print version\n";
// exit(1);
//}
int parseOptions(int argc, char * argv[], Options& opts) {
int c;
while ((c = getopt(argc, argv, "HhIf:zjqVrQGEPx")) != -1 ) {
switch (c) {
case 'f':
opts.f_flag = optarg;
break;
case 'I':
opts.I_flag = true;
break;
case 'Q':
opts.Q_flag = true;
break;
case 'e':
opts.r_flag = true;
break;
case 'x':
opts.x_flag = true;
break;
case 'V':
puts(VERSION);
exit(1);
break;
case 'H':
opts.H_flag = true;
break;
case 'r':
opts.r_flag = true;
break;
case 'h':
default:
usage(usage_msg);
break;
}
}
return optind;
}
void split( std::vector<std::string> & theStringVector, /* Altered/returned value */
std::string theString,
const std::string theDelimiter)
{
assert(theDelimiter.size() > 0); // My own ASSERT macro.
size_t start = 0, end = 0;
while ( end != std::string::npos)
{
end = theString.find( theDelimiter, start);
// If at end, use length=maxLength. Else use length=end-start.
theStringVector.push_back( theString.substr( start,
(end == std::string::npos) ? std::string::npos : end - start));
// If at end, use start=maxSize. Else use start=end+delimiter.
start = ( ( end > (std::string::npos - theDelimiter.size()) )
? std::string::npos : end + theDelimiter.size());
}
}
void tokenizePatternFile(FILE * in, FileManager& fmanager) {
// tokenize a line from the pattern file. The first part will be the pattern and the second
// part is the file to write to.
char * lineptr = NULL;
size_t n;
while(getline(&lineptr, &n, in) != -1) {
std::vector<std::string> fields;
split(fields, lineptr, "\t");
switch(fields.size()) {
case 0:
break;
case 1:
fmanager.add(fields[0]);
break;
default:
fmanager.add(fields[0], fields[1]);
break;
}
}
free(lineptr);
}
static int
on_match(int strnum, const char *textp, void const * context)
{
Fx * read = (Fx *) context;
read->puts(stdout);
return 1;
}
int main(int argc, char * argv[])
{
//kvec_t(sds) pattern_list;
FileManager manager;
Options opts;
int opt_idx = parseOptions(argc, argv, opts);
if(opts.f_flag == NULL) {
if( opt_idx >= argc) {
puts("Please provide a pattern (or pattern file) and at least one input file");
usage(usage_msg);
} else if (opt_idx >= argc - 1) {
puts("Please provide an input file (or two)");
usage(usage_msg);
}
std::string pattern = argv[opt_idx];
++opt_idx;
manager.add(pattern);
if(opts.r_flag) {
std::string rcpattern = pattern;
reverseComplement(rcpattern);
manager.add(rcpattern);
}
} else {
if (opt_idx > argc - 1) {
puts("Please provide an input file (or two)");
usage(usage_msg);
}
FILE * in = fopen(opts.f_flag, "r");
tokenizePatternFile(in, manager);
}
Fxstream stream;
if(opt_idx == argc - 2) {
// two read files
stream.open(argv[opt_idx], argv[opt_idx+1], opts.I_flag);
} else if (opt_idx == argc - 1) {
// one read file
stream.open(argv[opt_idx], NULL, opts.I_flag);
}
Fx * mate1 = new Fx();
Fx * mate2 = new Fx();
std::string conc;
std::map<std::string, int>::iterator iter;
for (iter = manager.patternMapping.begin(); iter != manager.patternMapping.end() ; ++iter ) {
conc += iter->first + "\n";
}
char * concstr = (char *) malloc(conc.size() * sizeof(char *));
strncpy(concstr, conc.c_str(), conc.size());
concstr[conc.size()-1] = '\0';
int npatts;
MEMREF *pattv = refsplit(concstr, '\n', &npatts);
SSEARCH *ssp = ssearch_create(pattv, npatts);
while(stream.read(&mate1, &mate2) >= 0) {
MEMREF data;
if(opts.H_flag) {
data.ptr = mate1->name;
data.len = strlen(mate1->name);
} else if(opts.Q_flag){
if(!mate1->isFasta()) {
data.ptr = mate1->qual;
data.len = (size_t)mate1->len;
}
} else {
data.ptr = mate1->seq;
data.len = (size_t)mate1->len;
}
int ret = ssearch_scan(ssp, data, (SSEARCH_CB)on_match, (void *)mate1);
if(ret == 0){
// read one did not have a match check read 2 if it exists
if(mate2 != NULL) {
if(opts.H_flag) {
data.ptr = mate2->name;
data.len = strlen(mate2->name);
} else if(opts.Q_flag){
if(!mate2->isFasta()) {
data.ptr = mate2->seq;
data.len = (size_t)mate2->len;
}
} else {
data.ptr = mate2->seq;
data.len = (size_t)mate2->len;
}
ssearch_scan(ssp, data, (SSEARCH_CB)on_match, (void *)mate2);
}
}
}
free(concstr);
delete mate1;
delete mate2;
stream.close();
free(pattv);
return 0;
}
<commit_msg>fix memory leak<commit_after>//
// main.cpp
// fxtract
//
// Created by Connor Skennerton on 30/07/13.
// Copyright (c) 2013 Connor Skennerton. All rights reserved.
//
#include <unistd.h>
#include <cstdio>
#include <cassert>
#include "util.h"
#include "fileManager.h"
#include "Fx.h"
extern "C" {
#include "util/ssearch.h"
#include "util/bpsearch.h"
#include "util/msutil.h"
}
#define VERSION "1.0-alpha"
struct Options
{
bool H_flag;
bool Q_flag;
bool G_flag;
bool E_flag;
bool x_flag;
bool r_flag;
bool I_flag;
char * f_flag;
Options() : H_flag(false),
Q_flag(false),
G_flag(false),
E_flag(false),
x_flag(false),
r_flag(false),
I_flag(false),
f_flag(NULL)
{}
};
void printSingle(Fx * mate1, FILE * out ) {
mate1->puts(out);
}
void printPair(Fx* mate1, Fx* mate2, FILE * out) {
// match in the first read print out pair
printSingle(mate1, out);
printSingle(mate2, out);
}
//void usage() {
static const char usage_msg[] =\
"[-hHv] {-f pattern_file | pattern} <read1.fx> [<read2.fx>]\n"
"\t-H Evaluate patterns in the context of headers (default: sequences)\n"
"\t-Q Evaluate patterns in the context of quality scores (default: sequences)\n"
"\t-G pattern is a posix basic regular expression (default: literal substring)\n"
"\t-E pattern is a posix extended regular expression (default: literal substring)\n"
"\t-P pattern is a perl compatable regular expression (default: literal substring)\n"
"\t-x pattern exactly matches the whole string (default: literal substring)\n"
"\t-I The read file is interleaved (both pairs in a single file)\n"
"\t-f <file> File containing patterns, one per line\n"
"\t-h Print this help\n"
"\t-V Print version\n";
// exit(1);
//}
int parseOptions(int argc, char * argv[], Options& opts) {
int c;
while ((c = getopt(argc, argv, "HhIf:zjqVrQGEPx")) != -1 ) {
switch (c) {
case 'f':
opts.f_flag = optarg;
break;
case 'I':
opts.I_flag = true;
break;
case 'Q':
opts.Q_flag = true;
break;
case 'e':
opts.r_flag = true;
break;
case 'x':
opts.x_flag = true;
break;
case 'V':
puts(VERSION);
exit(1);
break;
case 'H':
opts.H_flag = true;
break;
case 'r':
opts.r_flag = true;
break;
case 'h':
default:
usage(usage_msg);
break;
}
}
return optind;
}
void split( std::vector<std::string> & theStringVector, /* Altered/returned value */
std::string theString,
const std::string theDelimiter)
{
assert(theDelimiter.size() > 0); // My own ASSERT macro.
size_t start = 0, end = 0;
while ( end != std::string::npos)
{
end = theString.find( theDelimiter, start);
// If at end, use length=maxLength. Else use length=end-start.
theStringVector.push_back( theString.substr( start,
(end == std::string::npos) ? std::string::npos : end - start));
// If at end, use start=maxSize. Else use start=end+delimiter.
start = ( ( end > (std::string::npos - theDelimiter.size()) )
? std::string::npos : end + theDelimiter.size());
}
}
void tokenizePatternFile(FILE * in, FileManager& fmanager) {
// tokenize a line from the pattern file. The first part will be the pattern and the second
// part is the file to write to.
char * lineptr = NULL;
size_t n;
while(getline(&lineptr, &n, in) != -1) {
std::vector<std::string> fields;
split(fields, lineptr, "\t");
switch(fields.size()) {
case 0:
break;
case 1:
fmanager.add(fields[0]);
break;
default:
fmanager.add(fields[0], fields[1]);
break;
}
}
free(lineptr);
}
static int
on_match(int strnum, const char *textp, void const * context)
{
Fx * read = (Fx *) context;
read->puts(stdout);
return 1;
}
int main(int argc, char * argv[])
{
//kvec_t(sds) pattern_list;
FileManager manager;
Options opts;
int opt_idx = parseOptions(argc, argv, opts);
if(opts.f_flag == NULL) {
if( opt_idx >= argc) {
puts("Please provide a pattern (or pattern file) and at least one input file");
usage(usage_msg);
} else if (opt_idx >= argc - 1) {
puts("Please provide an input file (or two)");
usage(usage_msg);
}
std::string pattern = argv[opt_idx];
++opt_idx;
manager.add(pattern);
if(opts.r_flag) {
std::string rcpattern = pattern;
reverseComplement(rcpattern);
manager.add(rcpattern);
}
} else {
if (opt_idx > argc - 1) {
puts("Please provide an input file (or two)");
usage(usage_msg);
}
FILE * in = fopen(opts.f_flag, "r");
tokenizePatternFile(in, manager);
}
Fxstream stream;
if(opt_idx == argc - 2) {
// two read files
stream.open(argv[opt_idx], argv[opt_idx+1], opts.I_flag);
} else if (opt_idx == argc - 1) {
// one read file
stream.open(argv[opt_idx], NULL, opts.I_flag);
}
Fx * mate1 = new Fx();
Fx * mate2 = new Fx();
std::string conc;
std::map<std::string, int>::iterator iter;
for (iter = manager.patternMapping.begin(); iter != manager.patternMapping.end() ; ++iter ) {
conc += iter->first + "\n";
}
char * concstr = (char *) malloc(conc.size() * sizeof(char *));
strncpy(concstr, conc.c_str(), conc.size());
concstr[conc.size()-1] = '\0';
int npatts;
MEMREF *pattv = refsplit(concstr, '\n', &npatts);
SSEARCH *ssp = ssearch_create(pattv, npatts);
while(stream.read(&mate1, &mate2) >= 0) {
MEMREF data;
if(opts.H_flag) {
data.ptr = mate1->name;
data.len = strlen(mate1->name);
} else if(opts.Q_flag){
if(!mate1->isFasta()) {
data.ptr = mate1->qual;
data.len = (size_t)mate1->len;
}
} else {
data.ptr = mate1->seq;
data.len = (size_t)mate1->len;
}
int ret = ssearch_scan(ssp, data, (SSEARCH_CB)on_match, (void *)mate1);
if(ret == 0){
// read one did not have a match check read 2 if it exists
if(mate2 != NULL) {
if(opts.H_flag) {
data.ptr = mate2->name;
data.len = strlen(mate2->name);
} else if(opts.Q_flag){
if(!mate2->isFasta()) {
data.ptr = mate2->seq;
data.len = (size_t)mate2->len;
}
} else {
data.ptr = mate2->seq;
data.len = (size_t)mate2->len;
}
ssearch_scan(ssp, data, (SSEARCH_CB)on_match, (void *)mate2);
}
}
}
free(concstr);
delete mate1;
delete mate2;
stream.close();
free(pattv);
ssearch_destroy(ssp);
return 0;
}
<|endoftext|> |
<commit_before>5f30daa8-5216-11e5-8eb5-6c40088e03e4<commit_msg>5f37e000-5216-11e5-82b9-6c40088e03e4<commit_after>5f37e000-5216-11e5-82b9-6c40088e03e4<|endoftext|> |
<commit_before>b9e1a378-35ca-11e5-9ff4-6c40088e03e4<commit_msg>b9e8725e-35ca-11e5-8e25-6c40088e03e4<commit_after>b9e8725e-35ca-11e5-8e25-6c40088e03e4<|endoftext|> |
<commit_before><commit_msg>BUG: extern shared variable used wrong directive<commit_after><|endoftext|> |
<commit_before>d1092575-4b02-11e5-b38c-28cfe9171a43<commit_msg>whoops<commit_after>d1174245-4b02-11e5-b566-28cfe9171a43<|endoftext|> |
<commit_before>a9396626-327f-11e5-86f7-9cf387a8033e<commit_msg>a9419047-327f-11e5-a118-9cf387a8033e<commit_after>a9419047-327f-11e5-a118-9cf387a8033e<|endoftext|> |
<commit_before>8c3d20bd-2d14-11e5-af21-0401358ea401<commit_msg>8c3d20be-2d14-11e5-af21-0401358ea401<commit_after>8c3d20be-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2012, Jeremie Papon
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_OCTREE_POINTCLOUD_ADJACENCY_HPP_
#define PCL_OCTREE_POINTCLOUD_ADJACENCY_HPP_
#include <pcl/octree/octree_pointcloud_adjacency.h>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT>
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::OctreePointCloudAdjacency (const double resolution_arg)
: OctreePointCloud<PointT, LeafContainerT, BranchContainerT
, OctreeBase<LeafContainerT, BranchContainerT> > (resolution_arg)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::addPointsFromInputCloud ()
{
//double t1,t2;
float minX = std::numeric_limits<float>::max (), minY = std::numeric_limits<float>::max (), minZ = std::numeric_limits<float>::max ();
float maxX = -std::numeric_limits<float>::max(), maxY = -std::numeric_limits<float>::max(), maxZ = -std::numeric_limits<float>::max();
for (int i = 0; i < input_->size (); ++i)
{
PointT temp (input_->points[i]);
if (transform_func_) //Search for point with
transform_func_ (temp);
if (temp.x < minX)
minX = temp.x;
if (temp.y < minY)
minY = temp.y;
if (temp.z < minZ)
minZ = temp.z;
if (temp.x > maxX)
maxX = temp.x;
if (temp.y > maxY)
maxY = temp.y;
if (temp.z > maxZ)
maxZ = temp.z;
}
this->defineBoundingBox (minX, minY, minZ, maxX, maxY, maxZ);
//t1 = timer_.getTime ();
OctreePointCloud<PointT, LeafContainerT, BranchContainerT>::addPointsFromInputCloud ();
//t2 = timer_.getTime ();
//std::cout << "Add Points:"<<t2-t1<<" ms Num leaves ="<<this->getLeafCount ()<<"\n";
std::list <std::pair<OctreeKey,LeafContainerT*> > delete_list;
//double t_temp, t_neigh, t_compute, t_getLeaf;
//t_neigh = t_compute = t_getLeaf = 0;
LeafContainerT *leaf_container;
typename OctreeAdjacencyT::LeafNodeIterator leaf_itr;
leaf_vector_.reserve (this->getLeafCount ());
for ( leaf_itr = this->leaf_begin () ; leaf_itr != this->leaf_end (); ++leaf_itr)
{
//t_temp = timer_.getTime ();
OctreeKey leaf_key = leaf_itr.getCurrentOctreeKey ();
leaf_container = &(leaf_itr.getLeafContainer ());
//t_getLeaf += timer_.getTime () - t_temp;
//t_temp = timer_.getTime ();
//Run the leaf's compute function
leaf_container->computeData ();
//t_compute += timer_.getTime () - t_temp;
//t_temp = timer_.getTime ();
// std::cout << "Computing neighbors\n";
computeNeighbors (leaf_key, leaf_container);
//t_neigh += timer_.getTime () - t_temp;
leaf_vector_.push_back (leaf_container);
}
//Go through and delete voxels scheduled
for (typename std::list<std::pair<OctreeKey,LeafContainerT*> >::iterator delete_itr = delete_list.begin (); delete_itr != delete_list.end (); ++delete_itr)
{
leaf_container = delete_itr->second;
//Remove pointer to it from all neighbors
typename std::set<LeafContainerT*>::iterator neighbor_itr = leaf_container->begin ();
typename std::set<LeafContainerT*>::iterator neighbor_end = leaf_container->end ();
for ( ; neighbor_itr != neighbor_end; ++neighbor_itr)
{
//Don't delete self neighbor
if (*neighbor_itr != leaf_container)
(*neighbor_itr)->removeNeighbor (leaf_container);
}
this->removeLeaf (delete_itr->first);
}
//Make sure our leaf vector is correctly sized
assert (leaf_vector_.size () == this->getLeafCount ());
// std::cout << "Time spent getting leaves ="<<t_getLeaf<<"\n";
// std::cout << "Time spent computing data in leaves="<<t_compute<<"\n";
// std::cout << "Time spent computing neighbors="<<t_neigh<<"\n";
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::genOctreeKeyforPoint (const PointT& point_arg,OctreeKey & key_arg) const
{
if (transform_func_)
{
PointT temp (point_arg);
transform_func_ (temp);
// calculate integer key for transformed point coordinates
key_arg.x = static_cast<unsigned int> ((temp.x - this->min_x_) / this->resolution_);
key_arg.y = static_cast<unsigned int> ((temp.y - this->min_y_) / this->resolution_);
key_arg.z = static_cast<unsigned int> ((temp.z - this->min_z_) / this->resolution_);
}
else
{
// calculate integer key for point coordinates
key_arg.x = static_cast<unsigned int> ((point_arg.x - this->min_x_) / this->resolution_);
key_arg.y = static_cast<unsigned int> ((point_arg.y - this->min_y_) / this->resolution_);
key_arg.z = static_cast<unsigned int> ((point_arg.z - this->min_z_) / this->resolution_);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::addPointIdx (const int pointIdx_arg)
{
OctreeKey key;
assert (pointIdx_arg < static_cast<int> (this->input_->points.size ()));
const PointT& point = this->input_->points[pointIdx_arg];
if (!pcl::isFinite (point))
return;
// generate key
this->genOctreeKeyforPoint (point, key);
// add point to octree at key
LeafContainerT* container = this->createLeaf(key);
container->addPoint (point);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::computeNeighbors (OctreeKey &key_arg, LeafContainerT* leaf_container)
{
OctreeKey neighbor_key;
for (int dx = -1; dx <= 1; ++dx)
{
for (int dy = -1; dy <= 1; ++dy)
{
for (int dz = -1; dz <= 1; ++dz)
{
neighbor_key.x = key_arg.x + dx;
neighbor_key.y = key_arg.y + dy;
neighbor_key.z = key_arg.z + dz;
LeafContainerT *neighbor = this->findLeaf (neighbor_key);
if (neighbor)
{
leaf_container->addNeighbor (neighbor);
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> LeafContainerT*
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::getLeafContainerAtPoint (
const PointT& point_arg) const
{
OctreeKey key;
LeafContainerT* leaf = 0;
// generate key
this->genOctreeKeyforPoint (point_arg, key);
leaf = this->findLeaf (key);
return leaf;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::computeVoxelAdjacencyGraph (VoxelAdjacencyList &voxel_adjacency_graph)
{
//TODO Change this to use leaf centers, not centroids!
voxel_adjacency_graph.clear ();
//Add a vertex for each voxel, store ids in map
std::map <LeafContainerT*, VoxelID> leaf_vertex_id_map;
for (typename OctreeAdjacencyT::LeafNodeIterator leaf_itr = this->leaf_begin () ; leaf_itr != this->leaf_end (); ++leaf_itr)
{
OctreeKey leaf_key = leaf_itr.getCurrentOctreeKey ();
PointT centroid_point;
this->genLeafNodeCenterFromOctreeKey (leaf_key, centroid_point);
VoxelID node_id = add_vertex (voxel_adjacency_graph);
voxel_adjacency_graph[node_id] = centroid_point;
LeafContainerT* leaf_container = &(leaf_itr.getLeafContainer ());
leaf_vertex_id_map[leaf_container] = node_id;
}
//Iterate through and add edges to adjacency graph
for ( typename std::vector<LeafContainerT*>::iterator leaf_itr = leaf_vector_.begin (); leaf_itr != leaf_vector_.end (); ++leaf_itr)
{
typename LeafContainerT::iterator neighbor_itr = (*leaf_itr)->begin ();
typename LeafContainerT::iterator neighbor_end = (*leaf_itr)->end ();
LeafContainerT* neighbor_container;
VoxelID u = (leaf_vertex_id_map.find (*leaf_itr))->second;
PointT p_u = voxel_adjacency_graph[u];
for ( ; neighbor_itr != neighbor_end; ++neighbor_itr)
{
neighbor_container = *neighbor_itr;
EdgeID edge;
bool edge_added;
VoxelID v = (leaf_vertex_id_map.find (neighbor_container))->second;
boost::tie (edge, edge_added) = add_edge (u,v,voxel_adjacency_graph);
PointT p_v = voxel_adjacency_graph[v];
float dist = (p_v.getVector3fMap () - p_u.getVector3fMap ()).norm ();
voxel_adjacency_graph[edge] = dist;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> bool
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::testForOcclusion (const PointT& point_arg, const PointXYZ &camera_pos)
{
OctreeKey key;
this->genOctreeKeyforPoint (point_arg, key);
// This code follows the method in Octree::PointCloud
Eigen::Vector3f sensor(camera_pos.x,
camera_pos.y,
camera_pos.z);
Eigen::Vector3f leaf_centroid(static_cast<float> ((static_cast<double> (key.x) + 0.5f) * this->resolution_ + this->min_x_),
static_cast<float> ((static_cast<double> (key.y) + 0.5f) * this->resolution_ + this->min_y_),
static_cast<float> ((static_cast<double> (key.z) + 0.5f) * this->resolution_ + this->min_z_));
Eigen::Vector3f direction = sensor - leaf_centroid;
float norm = direction.norm ();
direction.normalize ();
float precision = 1.0f;
const float step_size = static_cast<const float> (resolution_) * precision;
const int nsteps = std::max (1, static_cast<int> (norm / step_size));
OctreeKey prev_key = key;
// Walk along the line segment with small steps.
Eigen::Vector3f p = leaf_centroid;
PointT octree_p;
for (int i = 0; i < nsteps; ++i)
{
//Start at the leaf voxel, and move back towards sensor.
p += (direction * step_size);
octree_p.x = p.x ();
octree_p.y = p.y ();
octree_p.z = p.z ();
// std::cout << octree_p<< "\n";
OctreeKey key;
this->genOctreeKeyforPoint (octree_p, key);
// Not a new key, still the same voxel (starts at self).
if ((key == prev_key))
continue;
prev_key = key;
LeafContainerT *leaf = this->findLeaf (key);
//If the voxel is occupied, there is a possible occlusion
if (leaf)
{
return true;
}
}
//If we didn't run into a voxel on the way to this camera, it can't be occluded.
return false;
}
#define PCL_INSTANTIATE_OctreePointCloudAdjacency(T) template class PCL_EXPORTS pcl::octree::OctreePointCloudAdjacency<T>;
#endif
<commit_msg>Fix a bug in `OctreePointCloudAdjacency::computeNeighbors()`<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2012, Jeremie Papon
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_OCTREE_POINTCLOUD_ADJACENCY_HPP_
#define PCL_OCTREE_POINTCLOUD_ADJACENCY_HPP_
#include <pcl/octree/octree_pointcloud_adjacency.h>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT>
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::OctreePointCloudAdjacency (const double resolution_arg)
: OctreePointCloud<PointT, LeafContainerT, BranchContainerT
, OctreeBase<LeafContainerT, BranchContainerT> > (resolution_arg)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::addPointsFromInputCloud ()
{
//double t1,t2;
float minX = std::numeric_limits<float>::max (), minY = std::numeric_limits<float>::max (), minZ = std::numeric_limits<float>::max ();
float maxX = -std::numeric_limits<float>::max(), maxY = -std::numeric_limits<float>::max(), maxZ = -std::numeric_limits<float>::max();
for (int i = 0; i < input_->size (); ++i)
{
PointT temp (input_->points[i]);
if (transform_func_) //Search for point with
transform_func_ (temp);
if (temp.x < minX)
minX = temp.x;
if (temp.y < minY)
minY = temp.y;
if (temp.z < minZ)
minZ = temp.z;
if (temp.x > maxX)
maxX = temp.x;
if (temp.y > maxY)
maxY = temp.y;
if (temp.z > maxZ)
maxZ = temp.z;
}
this->defineBoundingBox (minX, minY, minZ, maxX, maxY, maxZ);
//t1 = timer_.getTime ();
OctreePointCloud<PointT, LeafContainerT, BranchContainerT>::addPointsFromInputCloud ();
//t2 = timer_.getTime ();
//std::cout << "Add Points:"<<t2-t1<<" ms Num leaves ="<<this->getLeafCount ()<<"\n";
std::list <std::pair<OctreeKey,LeafContainerT*> > delete_list;
//double t_temp, t_neigh, t_compute, t_getLeaf;
//t_neigh = t_compute = t_getLeaf = 0;
LeafContainerT *leaf_container;
typename OctreeAdjacencyT::LeafNodeIterator leaf_itr;
leaf_vector_.reserve (this->getLeafCount ());
for ( leaf_itr = this->leaf_begin () ; leaf_itr != this->leaf_end (); ++leaf_itr)
{
//t_temp = timer_.getTime ();
OctreeKey leaf_key = leaf_itr.getCurrentOctreeKey ();
leaf_container = &(leaf_itr.getLeafContainer ());
//t_getLeaf += timer_.getTime () - t_temp;
//t_temp = timer_.getTime ();
//Run the leaf's compute function
leaf_container->computeData ();
//t_compute += timer_.getTime () - t_temp;
//t_temp = timer_.getTime ();
// std::cout << "Computing neighbors\n";
computeNeighbors (leaf_key, leaf_container);
//t_neigh += timer_.getTime () - t_temp;
leaf_vector_.push_back (leaf_container);
}
//Go through and delete voxels scheduled
for (typename std::list<std::pair<OctreeKey,LeafContainerT*> >::iterator delete_itr = delete_list.begin (); delete_itr != delete_list.end (); ++delete_itr)
{
leaf_container = delete_itr->second;
//Remove pointer to it from all neighbors
typename std::set<LeafContainerT*>::iterator neighbor_itr = leaf_container->begin ();
typename std::set<LeafContainerT*>::iterator neighbor_end = leaf_container->end ();
for ( ; neighbor_itr != neighbor_end; ++neighbor_itr)
{
//Don't delete self neighbor
if (*neighbor_itr != leaf_container)
(*neighbor_itr)->removeNeighbor (leaf_container);
}
this->removeLeaf (delete_itr->first);
}
//Make sure our leaf vector is correctly sized
assert (leaf_vector_.size () == this->getLeafCount ());
// std::cout << "Time spent getting leaves ="<<t_getLeaf<<"\n";
// std::cout << "Time spent computing data in leaves="<<t_compute<<"\n";
// std::cout << "Time spent computing neighbors="<<t_neigh<<"\n";
}
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::genOctreeKeyforPoint (const PointT& point_arg,OctreeKey & key_arg) const
{
if (transform_func_)
{
PointT temp (point_arg);
transform_func_ (temp);
// calculate integer key for transformed point coordinates
key_arg.x = static_cast<unsigned int> ((temp.x - this->min_x_) / this->resolution_);
key_arg.y = static_cast<unsigned int> ((temp.y - this->min_y_) / this->resolution_);
key_arg.z = static_cast<unsigned int> ((temp.z - this->min_z_) / this->resolution_);
}
else
{
// calculate integer key for point coordinates
key_arg.x = static_cast<unsigned int> ((point_arg.x - this->min_x_) / this->resolution_);
key_arg.y = static_cast<unsigned int> ((point_arg.y - this->min_y_) / this->resolution_);
key_arg.z = static_cast<unsigned int> ((point_arg.z - this->min_z_) / this->resolution_);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::addPointIdx (const int pointIdx_arg)
{
OctreeKey key;
assert (pointIdx_arg < static_cast<int> (this->input_->points.size ()));
const PointT& point = this->input_->points[pointIdx_arg];
if (!pcl::isFinite (point))
return;
// generate key
this->genOctreeKeyforPoint (point, key);
// add point to octree at key
LeafContainerT* container = this->createLeaf(key);
container->addPoint (point);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::computeNeighbors (OctreeKey &key_arg, LeafContainerT* leaf_container)
{
OctreeKey neighbor_key;
for (int dx = -1; dx <= 1; ++dx)
{
int x = dx + key_arg.x;
if (x < 0 || x > this->max_key_.x)
continue;
neighbor_key.x = static_cast<uint32_t> (x);
for (int dy = -1; dy <= 1; ++dy)
{
int y = dy + key_arg.y;
if (y < 0 || y > this->max_key_.y)
continue;
neighbor_key.y = static_cast<uint32_t> (y);
for (int dz = -1; dz <= 1; ++dz)
{
int z = dz + key_arg.z;
if (z < 0 || z > this->max_key_.z)
continue;
neighbor_key.z = static_cast<uint32_t> (z);
LeafContainerT *neighbor = this->findLeaf (neighbor_key);
if (neighbor)
{
leaf_container->addNeighbor (neighbor);
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> LeafContainerT*
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::getLeafContainerAtPoint (
const PointT& point_arg) const
{
OctreeKey key;
LeafContainerT* leaf = 0;
// generate key
this->genOctreeKeyforPoint (point_arg, key);
leaf = this->findLeaf (key);
return leaf;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> void
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::computeVoxelAdjacencyGraph (VoxelAdjacencyList &voxel_adjacency_graph)
{
//TODO Change this to use leaf centers, not centroids!
voxel_adjacency_graph.clear ();
//Add a vertex for each voxel, store ids in map
std::map <LeafContainerT*, VoxelID> leaf_vertex_id_map;
for (typename OctreeAdjacencyT::LeafNodeIterator leaf_itr = this->leaf_begin () ; leaf_itr != this->leaf_end (); ++leaf_itr)
{
OctreeKey leaf_key = leaf_itr.getCurrentOctreeKey ();
PointT centroid_point;
this->genLeafNodeCenterFromOctreeKey (leaf_key, centroid_point);
VoxelID node_id = add_vertex (voxel_adjacency_graph);
voxel_adjacency_graph[node_id] = centroid_point;
LeafContainerT* leaf_container = &(leaf_itr.getLeafContainer ());
leaf_vertex_id_map[leaf_container] = node_id;
}
//Iterate through and add edges to adjacency graph
for ( typename std::vector<LeafContainerT*>::iterator leaf_itr = leaf_vector_.begin (); leaf_itr != leaf_vector_.end (); ++leaf_itr)
{
typename LeafContainerT::iterator neighbor_itr = (*leaf_itr)->begin ();
typename LeafContainerT::iterator neighbor_end = (*leaf_itr)->end ();
LeafContainerT* neighbor_container;
VoxelID u = (leaf_vertex_id_map.find (*leaf_itr))->second;
PointT p_u = voxel_adjacency_graph[u];
for ( ; neighbor_itr != neighbor_end; ++neighbor_itr)
{
neighbor_container = *neighbor_itr;
EdgeID edge;
bool edge_added;
VoxelID v = (leaf_vertex_id_map.find (neighbor_container))->second;
boost::tie (edge, edge_added) = add_edge (u,v,voxel_adjacency_graph);
PointT p_v = voxel_adjacency_graph[v];
float dist = (p_v.getVector3fMap () - p_u.getVector3fMap ()).norm ();
voxel_adjacency_graph[edge] = dist;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT> bool
pcl::octree::OctreePointCloudAdjacency<PointT, LeafContainerT, BranchContainerT>::testForOcclusion (const PointT& point_arg, const PointXYZ &camera_pos)
{
OctreeKey key;
this->genOctreeKeyforPoint (point_arg, key);
// This code follows the method in Octree::PointCloud
Eigen::Vector3f sensor(camera_pos.x,
camera_pos.y,
camera_pos.z);
Eigen::Vector3f leaf_centroid(static_cast<float> ((static_cast<double> (key.x) + 0.5f) * this->resolution_ + this->min_x_),
static_cast<float> ((static_cast<double> (key.y) + 0.5f) * this->resolution_ + this->min_y_),
static_cast<float> ((static_cast<double> (key.z) + 0.5f) * this->resolution_ + this->min_z_));
Eigen::Vector3f direction = sensor - leaf_centroid;
float norm = direction.norm ();
direction.normalize ();
float precision = 1.0f;
const float step_size = static_cast<const float> (resolution_) * precision;
const int nsteps = std::max (1, static_cast<int> (norm / step_size));
OctreeKey prev_key = key;
// Walk along the line segment with small steps.
Eigen::Vector3f p = leaf_centroid;
PointT octree_p;
for (int i = 0; i < nsteps; ++i)
{
//Start at the leaf voxel, and move back towards sensor.
p += (direction * step_size);
octree_p.x = p.x ();
octree_p.y = p.y ();
octree_p.z = p.z ();
// std::cout << octree_p<< "\n";
OctreeKey key;
this->genOctreeKeyforPoint (octree_p, key);
// Not a new key, still the same voxel (starts at self).
if ((key == prev_key))
continue;
prev_key = key;
LeafContainerT *leaf = this->findLeaf (key);
//If the voxel is occupied, there is a possible occlusion
if (leaf)
{
return true;
}
}
//If we didn't run into a voxel on the way to this camera, it can't be occluded.
return false;
}
#define PCL_INSTANTIATE_OctreePointCloudAdjacency(T) template class PCL_EXPORTS pcl::octree::OctreePointCloudAdjacency<T>;
#endif
<|endoftext|> |
<commit_before>670c8014-2fa5-11e5-bfd3-00012e3d3f12<commit_msg>670e7be4-2fa5-11e5-a45f-00012e3d3f12<commit_after>670e7be4-2fa5-11e5-a45f-00012e3d3f12<|endoftext|> |
<commit_before>af1c744c-2e4f-11e5-8f12-28cfe91dbc4b<commit_msg>af22e399-2e4f-11e5-8600-28cfe91dbc4b<commit_after>af22e399-2e4f-11e5-8600-28cfe91dbc4b<|endoftext|> |
<commit_before>6cf7916b-ad59-11e7-8785-ac87a332f658<commit_msg>roselyn added more bugs<commit_after>6df1291e-ad59-11e7-8a0c-ac87a332f658<|endoftext|> |
<commit_before>3324e254-ad58-11e7-986b-ac87a332f658<commit_msg>Tuesday, turns out it was tuesday<commit_after>338c5a61-ad58-11e7-8667-ac87a332f658<|endoftext|> |
<commit_before>d796edbe-585a-11e5-a4e5-6c40088e03e4<commit_msg>d79dc288-585a-11e5-b74b-6c40088e03e4<commit_after>d79dc288-585a-11e5-b74b-6c40088e03e4<|endoftext|> |
<commit_before>587f47f0-2e3a-11e5-ad53-c03896053bdd<commit_msg>588d7b5e-2e3a-11e5-9c4b-c03896053bdd<commit_after>588d7b5e-2e3a-11e5-9c4b-c03896053bdd<|endoftext|> |
<commit_before>60bb479f-2d16-11e5-af21-0401358ea401<commit_msg>60bb47a0-2d16-11e5-af21-0401358ea401<commit_after>60bb47a0-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>796e94bc-2d53-11e5-baeb-247703a38240<commit_msg>796f13e2-2d53-11e5-baeb-247703a38240<commit_after>796f13e2-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>a763bbd1-327f-11e5-9900-9cf387a8033e<commit_msg>a769e654-327f-11e5-b024-9cf387a8033e<commit_after>a769e654-327f-11e5-b024-9cf387a8033e<|endoftext|> |
<commit_before>65c50bf4-2fa5-11e5-ac13-00012e3d3f12<commit_msg>65c707c6-2fa5-11e5-9abd-00012e3d3f12<commit_after>65c707c6-2fa5-11e5-9abd-00012e3d3f12<|endoftext|> |
<commit_before>caa10014-327f-11e5-9e18-9cf387a8033e<commit_msg>caa7271e-327f-11e5-b0ac-9cf387a8033e<commit_after>caa7271e-327f-11e5-b0ac-9cf387a8033e<|endoftext|> |
<commit_before>#include "blp.h"
#include <SimpleOpt.h>
#include <iostream>
#include <string>
using namespace std;
/**************************** COMMAND-LINE PARSING ****************************/
// The valid options
enum
{
OPT_HELP,
OPT_INFOS,
};
const CSimpleOpt::SOption COMMAND_LINE_OPTIONS[] = {
{ OPT_HELP, "-h", SO_NONE },
{ OPT_HELP, "--help", SO_NONE },
{ OPT_INFOS, "-i", SO_NONE },
{ OPT_INFOS, "--infos", SO_NONE },
SO_END_OF_OPTIONS
};
/********************************** FUNCTIONS *********************************/
void showUsage(const std::string& strApplicationName)
{
cout << "BLPConverter" << endl
<< "Usage: " << strApplicationName << " [options] <blp_filename> [<destination>]" << endl
<< endl;
}
void showInfos(const std::string& strFileName, tBLP2Header* pHeader)
{
cout << endl
<< "Infos about '" << strFileName << "':" << endl
<< " - Format: " << blp_asString(blp_format(pHeader)) << endl
<< " - Dimensions: " << pHeader->width << "x" << pHeader->height << endl
<< " - Mip levels: " << blp_nbMipLevels(pHeader) << endl
<< endl;
}
int main(int argc, char** argv)
{
bool bInfos = false;
// Parse the command-line parameters
CSimpleOpt args(argc, argv, COMMAND_LINE_OPTIONS);
while (args.Next())
{
if (args.LastError() == SO_SUCCESS)
{
switch (args.OptionId())
{
case OPT_HELP:
showUsage(argv[0]);
return 0;
case OPT_INFOS:
bInfos = true;
break;
}
}
else
{
cerr << "Invalid argument: " << args.OptionText() << endl;
return -1;
}
}
if (args.FileCount() == 0)
{
cerr << "No BLP file specified" << endl;
return -1;
}
// Only support the '--infos' option at the moment
if (!bInfos)
{
cerr << "The conversion of BLP files isn't implemented yet" << endl;
return -1;
}
FILE* pFile = fopen(args.File(0), "rb");
if (!pFile)
{
cerr << "Failed to open the file '" << args.File(0) << "'" << endl;
return -1;
}
tBLP2Header header;
if (!blp_processFile(pFile, &header))
{
cerr << "Failed to process the file '" << args.File(0) << "'" << endl;
fclose(pFile);
return -1;
}
showInfos(args.File(0), &header);
fclose(pFile);
return 0;
}
<commit_msg>Can work on several input files now<commit_after>#include "blp.h"
#include <SimpleOpt.h>
#include <iostream>
#include <string>
using namespace std;
/**************************** COMMAND-LINE PARSING ****************************/
// The valid options
enum
{
OPT_HELP,
OPT_INFOS,
};
const CSimpleOpt::SOption COMMAND_LINE_OPTIONS[] = {
{ OPT_HELP, "-h", SO_NONE },
{ OPT_HELP, "--help", SO_NONE },
{ OPT_INFOS, "-i", SO_NONE },
{ OPT_INFOS, "--infos", SO_NONE },
SO_END_OF_OPTIONS
};
/********************************** FUNCTIONS *********************************/
void showUsage(const std::string& strApplicationName)
{
cout << "BLPConverter" << endl
<< "Usage: " << strApplicationName << " [options] <blp_filename> [<blp_filename> ... <blp_filename>]" << endl
<< endl;
}
void showInfos(const std::string& strFileName, tBLP2Header* pHeader)
{
cout << endl
<< "Infos about '" << strFileName << "':" << endl
<< " - Format: " << blp_asString(blp_format(pHeader)) << endl
<< " - Dimensions: " << pHeader->width << "x" << pHeader->height << endl
<< " - Mip levels: " << blp_nbMipLevels(pHeader) << endl
<< endl;
}
int main(int argc, char** argv)
{
bool bInfos = false;
// Parse the command-line parameters
CSimpleOpt args(argc, argv, COMMAND_LINE_OPTIONS);
while (args.Next())
{
if (args.LastError() == SO_SUCCESS)
{
switch (args.OptionId())
{
case OPT_HELP:
showUsage(argv[0]);
return 0;
case OPT_INFOS:
bInfos = true;
break;
}
}
else
{
cerr << "Invalid argument: " << args.OptionText() << endl;
return -1;
}
}
if (args.FileCount() == 0)
{
cerr << "No BLP file specified" << endl;
return -1;
}
// Only support the '--infos' option at the moment
if (!bInfos)
{
cerr << "The conversion of BLP files isn't implemented yet" << endl;
return -1;
}
for (unsigned int i = 0; i < args.FileCount(); ++i)
{
tBLP2Header header;
FILE* pFile = fopen(args.File(i), "rb");
if (!pFile)
{
cerr << "Failed to open the file '" << args.File(i) << "'" << endl;
continue;
}
if (!blp_processFile(pFile, &header))
{
cerr << "Failed to process the file '" << args.File(i) << "'" << endl;
fclose(pFile);
continue;
}
showInfos(args.File(i), &header);
fclose(pFile);
}
return 0;
}
<|endoftext|> |
<commit_before>9294f3da-35ca-11e5-aab7-6c40088e03e4<commit_msg>929bc930-35ca-11e5-9200-6c40088e03e4<commit_after>929bc930-35ca-11e5-9200-6c40088e03e4<|endoftext|> |
<commit_before>#include <cassert>
#include <cstdio>
#include <stack>
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Support/IRBuilder.h>
#include <llvm/Support/raw_ostream.h>
using namespace llvm;
static const uint64_t DATA_SIZE = 30000;
static const char *DATA_NAME = "data";
static const char *PTR_NAME = "ptr";
struct Loop {
BasicBlock *Entry, *Body, *Exit;
PHINode *DataPtrBody, *DataPtrExit;
};
int main() {
// LLVM context.
LLVMContext &Context = getGlobalContext();
Module MainModule("brainfuck program", Context);
IRBuilder<> Builder(Context);
// Some useful constants.
const IntegerType *CellType = Type::getInt8Ty(Context);
Constant *One = ConstantInt::get(CellType, 1);
// Function prototypes for the shim.
FunctionType *PutFunctionType = FunctionType::get(
Type::getVoidTy(Context) /* return type */,
std::vector<const Type *>(1, CellType) /* argument types */,
false /* var args */);
Function *PutFunction = Function::Create(PutFunctionType,
Function::ExternalLinkage, "brainfuck_put", &MainModule);
FunctionType *GetFunctionType = FunctionType::get(
CellType /* return type */,
std::vector<const Type *>() /* argument types */,
false /* var args */);
Function *GetFunction = Function::Create(GetFunctionType,
Function::ExternalLinkage, "brainfuck_get", &MainModule);
// Global data for a brainfuck program.
ArrayType *DataType = ArrayType::get(CellType, DATA_SIZE);
GlobalVariable *Data = new GlobalVariable(
MainModule, DataType, false /* constant */,
GlobalVariable::InternalLinkage, Constant::getNullValue(DataType),
DATA_NAME);
Value *DataPtr = Builder.CreateConstInBoundsGEP2_32(Data, 0, 0, PTR_NAME);
// Main function definition.
FunctionType *MainFunctionType = FunctionType::get(
Type::getVoidTy(Context) /* return type */,
std::vector<const Type *>() /* argument types */,
false /* var args */);
Function *MainFunction = Function::Create(MainFunctionType,
Function::ExternalLinkage, "brainfuck_main", &MainModule);
BasicBlock *MainBlock = BasicBlock::Create(Context, "entry", MainFunction);
Builder.SetInsertPoint(MainBlock);
// Code generation.
int c;
Value *Value;
std::stack<Loop> Loops;
Loop ThisLoop;
while ((c = getchar()) != EOF) {
switch (c) {
case '>':
DataPtr = Builder.CreateConstGEP1_32(DataPtr, 1, PTR_NAME);
break;
case '<':
DataPtr = Builder.CreateConstGEP1_32(DataPtr, -1, PTR_NAME);
break;
case '+':
Value = Builder.CreateLoad(DataPtr);
Value = Builder.CreateAdd(Value, One);
Builder.CreateStore(Value, DataPtr);
break;
case '-':
Value = Builder.CreateLoad(DataPtr);
Value = Builder.CreateSub(Value, One);
Builder.CreateStore(Value, DataPtr);
break;
case '.':
Value = Builder.CreateLoad(DataPtr);
Builder.CreateCall(PutFunction, Value);
break;
case ',':
Value = Builder.CreateCall(GetFunction);
Builder.CreateStore(Value, DataPtr);
break;
case '[':
// Prepare data for the stack.
ThisLoop.Entry = Builder.GetInsertBlock();
ThisLoop.Body = BasicBlock::Create(Context, "loop", MainFunction);
ThisLoop.Exit = BasicBlock::Create(Context, "exit", MainFunction);
// Emit the beginning conditional branch.
Value = Builder.CreateLoad(DataPtr);
Value = Builder.CreateIsNotNull(Value);
Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);
// Define the pointer after the loop.
Builder.SetInsertPoint(ThisLoop.Exit);
ThisLoop.DataPtrExit = Builder.CreatePHI(DataPtr->getType(), PTR_NAME);
ThisLoop.DataPtrExit->addIncoming(DataPtr, ThisLoop.Entry);
// Define the pointer within the loop.
Builder.SetInsertPoint(ThisLoop.Body);
ThisLoop.DataPtrBody = Builder.CreatePHI(DataPtr->getType(), PTR_NAME);
ThisLoop.DataPtrBody->addIncoming(DataPtr, ThisLoop.Entry);
// Continue generating code within the loop.
DataPtr = ThisLoop.DataPtrBody;
Loops.push(ThisLoop);
break;
case ']':
// Pop data off the stack.
if (Loops.empty()) {
fputs("] requires matching [\n", stderr);
abort();
}
ThisLoop = Loops.top();
Loops.pop();
// Finish off the phi nodes.
ThisLoop.DataPtrBody->addIncoming(DataPtr, Builder.GetInsertBlock());
ThisLoop.DataPtrExit->addIncoming(DataPtr, Builder.GetInsertBlock());
// Emit the ending conditional branch.
Value = Builder.CreateLoad(DataPtr);
Value = Builder.CreateIsNotNull(Value);
Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);
// Move insertion after the loop.
ThisLoop.Exit->moveAfter(Builder.GetInsertBlock());
DataPtr = ThisLoop.DataPtrExit;
Builder.SetInsertPoint(ThisLoop.Exit);
break;
}
}
// Ensure all loops have been closed.
if (!Loops.empty()) {
fputs("[ requires matching ]\n", stderr);
abort();
}
// Finish off brainfuck_main and dump.
Builder.CreateRetVoid();
MainModule.print(outs(), NULL /* assembly annotation writer */);
}
<commit_msg>Update LLVM lib calls to conform to llvm 3.3.<commit_after>#include <cassert>
#include <cstdio>
#include <stack>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/raw_ostream.h>
using namespace llvm;
static const uint64_t DATA_SIZE = 30000;
static const char *DATA_NAME = "data";
static const char *PTR_NAME = "ptr";
struct Loop {
BasicBlock *Entry, *Body, *Exit;
PHINode *DataPtrBody, *DataPtrExit;
};
int main() {
// LLVM context.
LLVMContext &Context = getGlobalContext();
Module MainModule("brainfuck program", Context);
IRBuilder<> Builder(Context);
// Some useful constants.
Type *CellType = Type::getInt8Ty(Context);
Constant *One = ConstantInt::get(CellType, 1);
// Function prototypes for the shim.
FunctionType *PutFunctionType = FunctionType::get(
Type::getVoidTy(Context) /* return type */,
std::vector<Type *>(1, CellType) /* argument types */,
false /* var args */);
Function *PutFunction = Function::Create(PutFunctionType,
Function::ExternalLinkage, "brainfuck_put", &MainModule);
FunctionType *GetFunctionType = FunctionType::get(
CellType /* return type */,
std::vector<Type *>() /* argument types */,
false /* var args */);
Function *GetFunction = Function::Create(GetFunctionType,
Function::ExternalLinkage, "brainfuck_get", &MainModule);
// Global data for a brainfuck program.
ArrayType *DataType = ArrayType::get(CellType, DATA_SIZE);
GlobalVariable *Data = new GlobalVariable(
MainModule, DataType, false /* constant */,
GlobalVariable::InternalLinkage, Constant::getNullValue(DataType),
DATA_NAME);
Value *DataPtr = Builder.CreateConstInBoundsGEP2_32(Data, 0, 0, PTR_NAME);
// Main function definition.
FunctionType *MainFunctionType = FunctionType::get(
Type::getVoidTy(Context) /* return type */,
std::vector<Type *>() /* argument types */,
false /* var args */);
Function *MainFunction = Function::Create(MainFunctionType,
Function::ExternalLinkage, "brainfuck_main", &MainModule);
BasicBlock *MainBlock = BasicBlock::Create(Context, "entry", MainFunction);
Builder.SetInsertPoint(MainBlock);
// Code generation.
int c;
Value *Value;
std::stack<Loop> Loops;
Loop ThisLoop;
while ((c = getchar()) != EOF) {
switch (c) {
case '>':
DataPtr = Builder.CreateConstGEP1_32(DataPtr, 1, PTR_NAME);
break;
case '<':
DataPtr = Builder.CreateConstGEP1_32(DataPtr, -1, PTR_NAME);
break;
case '+':
Value = Builder.CreateLoad(DataPtr);
Value = Builder.CreateAdd(Value, One);
Builder.CreateStore(Value, DataPtr);
break;
case '-':
Value = Builder.CreateLoad(DataPtr);
Value = Builder.CreateSub(Value, One);
Builder.CreateStore(Value, DataPtr);
break;
case '.':
Value = Builder.CreateLoad(DataPtr);
Builder.CreateCall(PutFunction, Value);
break;
case ',':
Value = Builder.CreateCall(GetFunction);
Builder.CreateStore(Value, DataPtr);
break;
case '[':
// Prepare data for the stack.
ThisLoop.Entry = Builder.GetInsertBlock();
ThisLoop.Body = BasicBlock::Create(Context, "loop", MainFunction);
ThisLoop.Exit = BasicBlock::Create(Context, "exit", MainFunction);
// Emit the beginning conditional branch.
Value = Builder.CreateLoad(DataPtr);
Value = Builder.CreateIsNotNull(Value);
Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);
// Define the pointer after the loop.
Builder.SetInsertPoint(ThisLoop.Exit);
ThisLoop.DataPtrExit = Builder.CreatePHI(DataPtr->getType(), 2,
PTR_NAME);
ThisLoop.DataPtrExit->addIncoming(DataPtr, ThisLoop.Entry);
// Define the pointer within the loop.
Builder.SetInsertPoint(ThisLoop.Body);
ThisLoop.DataPtrBody = Builder.CreatePHI(DataPtr->getType(), 2,
PTR_NAME);
ThisLoop.DataPtrBody->addIncoming(DataPtr, ThisLoop.Entry);
// Continue generating code within the loop.
DataPtr = ThisLoop.DataPtrBody;
Loops.push(ThisLoop);
break;
case ']':
// Pop data off the stack.
if (Loops.empty()) {
fputs("] requires matching [\n", stderr);
abort();
}
ThisLoop = Loops.top();
Loops.pop();
// Finish off the phi nodes.
ThisLoop.DataPtrBody->addIncoming(DataPtr, Builder.GetInsertBlock());
ThisLoop.DataPtrExit->addIncoming(DataPtr, Builder.GetInsertBlock());
// Emit the ending conditional branch.
Value = Builder.CreateLoad(DataPtr);
Value = Builder.CreateIsNotNull(Value);
Builder.CreateCondBr(Value, ThisLoop.Body, ThisLoop.Exit);
// Move insertion after the loop.
ThisLoop.Exit->moveAfter(Builder.GetInsertBlock());
DataPtr = ThisLoop.DataPtrExit;
Builder.SetInsertPoint(ThisLoop.Exit);
break;
}
}
// Ensure all loops have been closed.
if (!Loops.empty()) {
fputs("[ requires matching ]\n", stderr);
abort();
}
// Finish off brainfuck_main and dump.
Builder.CreateRetVoid();
MainModule.print(outs(), NULL /* assembly annotation writer */);
}
<|endoftext|> |
<commit_before>d2b37ea6-ad59-11e7-b3a5-ac87a332f658<commit_msg>NO CHANGES<commit_after>d3664766-ad59-11e7-ab81-ac87a332f658<|endoftext|> |
<commit_before>6c6f32e3-2749-11e6-94da-e0f84713e7b8<commit_msg>Fixed that one bug<commit_after>6c7ea435-2749-11e6-8467-e0f84713e7b8<|endoftext|> |
<commit_before>19a25018-585b-11e5-86a6-6c40088e03e4<commit_msg>19a95c0a-585b-11e5-89ec-6c40088e03e4<commit_after>19a95c0a-585b-11e5-89ec-6c40088e03e4<|endoftext|> |
<commit_before>#include "gui/squaredetailwindow.hpp"
#include "gui/ng/label.hpp"
#include "gui/texturemanager.hpp"
#include "gui/guihelper.hpp"
#include "engine/square.hpp"
namespace qrw
{
SquareDetailWindow::SquareDetailWindow()
{
setSize({400.0f, 150.0f});
setAnchor({0.0f, 1.0f});
setParentAnchor({0.0f, 1.0f});
float labelHeight = 50;
// ------------------
// Labels for displaying unit information
// ------------------
namelessgui::Label* label;
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("Unit name");
label->setImage(TextureManager::getInstance()->getTexture("p1swordman"));
label->setRelativePosition({0, 0});
_unitTitleLabel = label;
addWidget(_unitTitleLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("20 / 100 HP");
label->setImage(TextureManager::getInstance()->getTexture("health"));
label->setRelativePosition({0, labelHeight});
_unitHealthLabel = label;
addWidget(_unitHealthLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("movement");
label->setImage(TextureManager::getInstance()->getTexture("movement"));
label->setRelativePosition({150, labelHeight});
_unitMovementLabel = label;
addWidget(_unitMovementLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("3");
label->setImage(TextureManager::getInstance()->getTexture("attack"));
label->setRelativePosition({0, 2 * labelHeight});
_unitAttackLabel = label;
addWidget(_unitAttackLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("2");
label->setImage(TextureManager::getInstance()->getTexture("defense"));
label->setRelativePosition({150, 2 * labelHeight});
_unitDefenseLabel = label;
addWidget(_unitDefenseLabel);
// ------------------
// Labels for displaying terrain information
// ------------------
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("Wall");
label->setImage(TextureManager::getInstance()->getTexture("wall"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-200, 0});
_terrainTitleLabel = label;
addWidget(_terrainTitleLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("+1");
label->setImage(TextureManager::getInstance()->getTexture("attack"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-200, labelHeight});
_terrainAttackLabel = label;
addWidget(_terrainAttackLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("-1");
label->setImage(TextureManager::getInstance()->getTexture("defense"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-100, labelHeight});
_terrainDefenseLabel = label;
addWidget(_terrainDefenseLabel);
}
void SquareDetailWindow::setUnitAndTerrain(Unit::Ptr unit, Terrain::Ptr terrain)
{
checkAndSetVisibility(unit, terrain);
setUnit(unit);
setTerrain(terrain);
}
void SquareDetailWindow::setUnit(Unit::Ptr unit)
{
if(unit != nullptr)
{
_unitTitleLabel->setVisible(true);
_unitTitleLabel->setImage(unit->getTexture());
_unitTitleLabel->setText(GuiHelper::getUnitName(unit));
_unitHealthLabel->setVisible(true);
_unitHealthLabel->setText(std::to_string(unit->getHP()) + "/" + std::to_string(unit->getMaxHp()));
_unitMovementLabel->setVisible(true);
_unitMovementLabel->setText(std::to_string(unit->getCurrentMovement()) + "/" + std::to_string(unit->getMovement()));
_unitAttackLabel->setVisible(true);
_unitAttackLabel->setText(std::to_string(unit->getBaseAttack()));
_unitDefenseLabel->setVisible(true);
_unitDefenseLabel->setText(std::to_string(unit->getBaseDefense()));
}
else
{
_unitTitleLabel->setVisible(false);
_unitHealthLabel->setVisible(false);
_unitMovementLabel->setVisible(false);
_unitAttackLabel->setVisible(false);
_unitDefenseLabel->setVisible(false);
}
}
void SquareDetailWindow::setTerrain(Terrain::Ptr terrain)
{
if(terrain != nullptr)
{
_terrainTitleLabel->setVisible(true);
_terrainTitleLabel->setImage(GuiHelper::getTerrainTexture(terrain));
_terrainTitleLabel->setText(GuiHelper::getTerrainName(terrain));
_terrainAttackLabel->setVisible(true);
_terrainAttackLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_ATTACK)));
_terrainDefenseLabel->setVisible(true);
_terrainDefenseLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_DEFENSE)));
}
else
{
_terrainTitleLabel->setVisible(false);
_terrainAttackLabel->setVisible(false);
_terrainDefenseLabel->setVisible(false);
}
}
void SquareDetailWindow::checkAndSetVisibility(Unit::Ptr unit, Terrain::Ptr terrain)
{
setVisible(unit != nullptr || terrain != nullptr);
}
} // namespace qrw
<commit_msg>Fixed overlapping texts in square detail window.<commit_after>#include "gui/squaredetailwindow.hpp"
#include "gui/ng/label.hpp"
#include "gui/texturemanager.hpp"
#include "gui/guihelper.hpp"
#include "engine/square.hpp"
namespace qrw
{
SquareDetailWindow::SquareDetailWindow()
{
setSize({400.0f, 150.0f});
setAnchor({0.0f, 1.0f});
setParentAnchor({0.0f, 1.0f});
float labelHeight = 50;
// ------------------
// Labels for displaying unit information
// ------------------
namelessgui::Label* label;
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("Unit name");
label->setImage(TextureManager::getInstance()->getTexture("p1swordman"));
label->setRelativePosition({0, 0});
_unitTitleLabel = label;
addWidget(_unitTitleLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("20 / 100 HP");
label->setImage(TextureManager::getInstance()->getTexture("health"));
label->setRelativePosition({0, labelHeight});
_unitHealthLabel = label;
addWidget(_unitHealthLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("movement");
label->setImage(TextureManager::getInstance()->getTexture("movement"));
label->setRelativePosition({100, labelHeight});
_unitMovementLabel = label;
addWidget(_unitMovementLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("3");
label->setImage(TextureManager::getInstance()->getTexture("attack"));
label->setRelativePosition({0, 2 * labelHeight});
_unitAttackLabel = label;
addWidget(_unitAttackLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("2");
label->setImage(TextureManager::getInstance()->getTexture("defense"));
label->setRelativePosition({100, 2 * labelHeight});
_unitDefenseLabel = label;
addWidget(_unitDefenseLabel);
// ------------------
// Labels for displaying terrain information
// ------------------
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("Wall");
label->setImage(TextureManager::getInstance()->getTexture("wall"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-200, 0});
_terrainTitleLabel = label;
addWidget(_terrainTitleLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("+1");
label->setImage(TextureManager::getInstance()->getTexture("attack"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-200, labelHeight});
_terrainAttackLabel = label;
addWidget(_terrainAttackLabel);
label = new namelessgui::Label();
label->setSize({100, labelHeight});
label->setText("-1");
label->setImage(TextureManager::getInstance()->getTexture("defense"));
label->setParentAnchor({1, 0});
label->setRelativePosition({-100, labelHeight});
_terrainDefenseLabel = label;
addWidget(_terrainDefenseLabel);
}
void SquareDetailWindow::setUnitAndTerrain(Unit::Ptr unit, Terrain::Ptr terrain)
{
checkAndSetVisibility(unit, terrain);
setUnit(unit);
setTerrain(terrain);
}
void SquareDetailWindow::setUnit(Unit::Ptr unit)
{
if(unit != nullptr)
{
_unitTitleLabel->setVisible(true);
_unitTitleLabel->setImage(unit->getTexture());
_unitTitleLabel->setText(GuiHelper::getUnitName(unit));
_unitHealthLabel->setVisible(true);
_unitHealthLabel->setText(std::to_string(unit->getHP()) + "/" + std::to_string(unit->getMaxHp()));
_unitMovementLabel->setVisible(true);
_unitMovementLabel->setText(std::to_string(unit->getCurrentMovement()) + "/" + std::to_string(unit->getMovement()));
_unitAttackLabel->setVisible(true);
_unitAttackLabel->setText(std::to_string(unit->getBaseAttack()));
_unitDefenseLabel->setVisible(true);
_unitDefenseLabel->setText(std::to_string(unit->getBaseDefense()));
}
else
{
_unitTitleLabel->setVisible(false);
_unitHealthLabel->setVisible(false);
_unitMovementLabel->setVisible(false);
_unitAttackLabel->setVisible(false);
_unitDefenseLabel->setVisible(false);
}
}
void SquareDetailWindow::setTerrain(Terrain::Ptr terrain)
{
if(terrain != nullptr)
{
_terrainTitleLabel->setVisible(true);
_terrainTitleLabel->setImage(GuiHelper::getTerrainTexture(terrain));
_terrainTitleLabel->setText(GuiHelper::getTerrainName(terrain));
_terrainAttackLabel->setVisible(true);
_terrainAttackLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_ATTACK)));
_terrainDefenseLabel->setVisible(true);
_terrainDefenseLabel->setText(std::to_string(terrain->getModificator(MODIFICATORS::EM_DEFENSE)));
}
else
{
_terrainTitleLabel->setVisible(false);
_terrainAttackLabel->setVisible(false);
_terrainDefenseLabel->setVisible(false);
}
}
void SquareDetailWindow::checkAndSetVisibility(Unit::Ptr unit, Terrain::Ptr terrain)
{
setVisible(unit != nullptr || terrain != nullptr);
}
} // namespace qrw
<|endoftext|> |
<commit_before>a26f008c-2e4f-11e5-8341-28cfe91dbc4b<commit_msg>a277f4e6-2e4f-11e5-b2a5-28cfe91dbc4b<commit_after>a277f4e6-2e4f-11e5-b2a5-28cfe91dbc4b<|endoftext|> |
<commit_before>77101236-2d53-11e5-baeb-247703a38240<commit_msg>77109634-2d53-11e5-baeb-247703a38240<commit_after>77109634-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>44aee0ac-5216-11e5-9ec4-6c40088e03e4<commit_msg>44b5728a-5216-11e5-9285-6c40088e03e4<commit_after>44b5728a-5216-11e5-9285-6c40088e03e4<|endoftext|> |
<commit_before>35f91d8f-2e4f-11e5-bc6b-28cfe91dbc4b<commit_msg>3600315c-2e4f-11e5-8102-28cfe91dbc4b<commit_after>3600315c-2e4f-11e5-8102-28cfe91dbc4b<|endoftext|> |
<commit_before>#include "kyheader.h"
#ifdef _WIN32
#include <windows.h>
#include <shlobj.h>
#include <Commdlg.h>
#include <ShellAPI.h>
#else
#include <iostream>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
#endif
// Get image names from a wildcard. Eg: GetNames("D:\\*.jpg", imgNames);
int CmFile::GetNames(CStr &_nameW, vecS &_names)
{
string _dir = GetFolder(_nameW);
_names.clear();
DIR *dir;
struct dirent *ent;
if((dir = opendir(_dir.c_str()))!=NULL){
//print all the files and directories within directory
while((ent = readdir(dir))!=NULL){
if(ent->d_name[0] == '.')
continue;
if(ent->d_type ==4)
continue;
_names.push_back(ent->d_name);
}
closedir(dir);
} else {
perror("");
return EXIT_FAILURE;
}
return (int)_names.size();
}
int CmFile::GetNames(CStr &_nameW, vecS &_names, string &_dir)
{
_dir = GetFolder(_nameW);
_names.clear();
DIR *dir;
struct dirent *ent;
if((dir = opendir(_dir.c_str()))!=NULL){
//print all the files and directories within directory
while((ent = readdir(dir))!=NULL){
if(ent->d_name[0] == '.')
continue;
if(ent->d_type ==4)
continue;
_names.push_back(ent->d_name);
}
closedir(dir);
} else {
perror("");
return EXIT_FAILURE;
}
return (int)_names.size();
}
int CmFile::GetSubFolders(CStr &folder, vecS &subFolders)
{
subFolders.clear();
string nameWC = GetFolder(folder);//folder + "/*";
DIR *dir;
struct dirent *ent;
if((dir = opendir(nameWC.c_str()))!=NULL){
while((ent = readdir(dir))!=NULL){
if(ent->d_name[0] == '.')
continue;
if(ent->d_type == 4){
subFolders.push_back(ent->d_name);
}
}
closedir(dir);
} else {
perror("");
return EXIT_FAILURE;
}
return (int)subFolders.size();
}
int CmFile::GetNames(CStr& rootFolder, CStr &fileW, vecS &names)
{
GetNames(rootFolder + fileW, names);
vecS subFolders, tmpNames;
int subNum = CmFile::GetSubFolders(rootFolder, subFolders);//
for (int i = 0; i < subNum; i++){
subFolders[i] += "/";
int subNum = GetNames(rootFolder + subFolders[i], fileW, tmpNames);
for (int j = 0; j < subNum; j++)
names.push_back(subFolders[i] + tmpNames[j]);
}
return (int)names.size();
}
int CmFile::GetNamesNE(CStr& nameWC, vecS &names)
{
string dir = string();
string ext = string();
int fNum = GetNames(nameWC, names, dir);
ext = GetExtention(nameWC);
for (int i = 0; i < fNum; i++)
names[i] = GetNameNE(names[i]);
return fNum;
}
int CmFile::GetNamesNE(CStr& nameWC, vecS &names, string &dir, string &ext)
{
int fNum = GetNames(nameWC, names, dir);
ext = GetExtention(nameWC);
for (int i = 0; i < fNum; i++)
names[i] = GetNameNE(names[i]);
return fNum;
}
int CmFile::GetNamesNE(CStr& rootFolder, CStr &fileW, vecS &names)
{
int fNum = GetNames(rootFolder, fileW, names);
int extS = GetExtention(fileW).size();
for (int i = 0; i < fNum; i++)
names[i].resize(names[i].size() - extS);
return fNum;
}
bool CmFile::MkDir(CStr &_path)
{
if(_path.size() == 0)
return false;
static char buffer[1024];
strcpy(buffer, _S(_path));
#ifdef _WIN32
for (int i = 0; buffer[i] != 0; i ++) {
if (buffer[i] == '\\' || buffer[i] == '/') {
buffer[i] = '\0';
CreateDirectoryA(buffer, 0);
buffer[i] = '/';
}
}
return CreateDirectoryA(_S(_path), 0);
#else
for (int i = 0; buffer[i] != 0; i ++) {
if (buffer[i] == '\\' || buffer[i] == '/') {
buffer[i] = '\0';
mkdir(buffer, 0);
buffer[i] = '/';
}
}
return mkdir(_S(_path), 0);
#endif
}
vecS CmFile::loadStrList(CStr &fName)
{
ifstream fIn(fName);
string line;
vecS strs;
while(getline(fIn, line) && line.size()){
unsigned sz = line.size();
line.resize(sz - 1); //Please use script to convert the VOC format data into the OpenCV format data
//line.resize(sz);
strs.push_back(line);
}
return strs;
}
bool CmFile::writeStrList(CStr &fName, const vecS &strs)
{
FILE *f = fopen(_S(fName), "w");
if (f == NULL)
return false;
for (size_t i = 0; i < strs.size(); i++)
fprintf(f, "%s\n", _S(strs[i]));
fclose(f);
return true;
}
<commit_msg>Update CmFile.cpp<commit_after>#include "kyheader.h"
#ifdef _WIN32
#include <windows.h>
#include <shlobj.h>
#include <Commdlg.h>
#include <ShellAPI.h>
#else
#include <iostream>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
#endif
// Get image names from a wildcard. Eg: GetNames("D:\\*.jpg", imgNames);
int CmFile::GetNames(CStr &_nameW, vecS &_names)
{
string _dir = GetFolder(_nameW);
_names.clear();
DIR *dir;
struct dirent *ent;
if((dir = opendir(_dir.c_str()))!=NULL){
//print all the files and directories within directory
while((ent = readdir(dir))!=NULL){
if(ent->d_name[0] == '.')
continue;
if(ent->d_type ==4)
continue;
_names.push_back(ent->d_name);
}
closedir(dir);
} else {
perror("");
return EXIT_FAILURE;
}
return (int)_names.size();
}
int CmFile::GetNames(CStr &_nameW, vecS &_names, string &_dir)
{
_dir = GetFolder(_nameW);
_names.clear();
DIR *dir;
struct dirent *ent;
if((dir = opendir(_dir.c_str()))!=NULL){
//print all the files and directories within directory
while((ent = readdir(dir))!=NULL){
if(ent->d_name[0] == '.')
continue;
if(ent->d_type ==4)
continue;
_names.push_back(ent->d_name);
}
closedir(dir);
} else {
perror("");
return EXIT_FAILURE;
}
return (int)_names.size();
}
int CmFile::GetSubFolders(CStr &folder, vecS &subFolders)
{
subFolders.clear();
string nameWC = GetFolder(folder);//folder + "/*";
DIR *dir;
struct dirent *ent;
if((dir = opendir(nameWC.c_str()))!=NULL){
while((ent = readdir(dir))!=NULL){
if(ent->d_name[0] == '.')
continue;
if(ent->d_type == 4){
subFolders.push_back(ent->d_name);
}
}
closedir(dir);
} else {
perror("");
return EXIT_FAILURE;
}
return (int)subFolders.size();
}
int CmFile::GetNames(CStr& rootFolder, CStr &fileW, vecS &names)
{
GetNames(rootFolder + fileW, names);
vecS subFolders, tmpNames;
int subNum = CmFile::GetSubFolders(rootFolder, subFolders);//
for (int i = 0; i < subNum; i++){
subFolders[i] += "/";
int subNum = GetNames(rootFolder + subFolders[i], fileW, tmpNames);
for (int j = 0; j < subNum; j++)
names.push_back(subFolders[i] + tmpNames[j]);
}
return (int)names.size();
}
int CmFile::GetNamesNE(CStr& nameWC, vecS &names)
{
string dir = string();
string ext = string();
int fNum = GetNames(nameWC, names, dir);
ext = GetExtention(nameWC);
for (int i = 0; i < fNum; i++)
names[i] = GetNameNE(names[i]);
return fNum;
}
int CmFile::GetNamesNE(CStr& nameWC, vecS &names, string &dir, string &ext)
{
int fNum = GetNames(nameWC, names, dir);
ext = GetExtention(nameWC);
for (int i = 0; i < fNum; i++)
names[i] = GetNameNE(names[i]);
return fNum;
}
int CmFile::GetNamesNE(CStr& rootFolder, CStr &fileW, vecS &names)
{
int fNum = GetNames(rootFolder, fileW, names);
int extS = GetExtention(fileW).size();
for (int i = 0; i < fNum; i++)
names[i].resize(names[i].size() - extS);
return fNum;
}
bool CmFile::MkDir(CStr &_path)
{
if(_path.size() == 0)
return false;
static char buffer[1024];
strcpy(buffer, _S(_path));
#ifdef _WIN32
for (int i = 0; buffer[i] != 0; i ++) {
if (buffer[i] == '\\' || buffer[i] == '/') {
buffer[i] = '\0';
CreateDirectoryA(buffer, 0);
buffer[i] = '/';
}
}
return CreateDirectoryA(_S(_path), 0);
#else
for (int i = 0; buffer[i] != 0; i ++) {
if (buffer[i] == '\\' || buffer[i] == '/') {
buffer[i] = '\0';
mkdir(buffer, 0755);
buffer[i] = '/';
}
}
return mkdir(_S(_path), 0755);
#endif
}
vecS CmFile::loadStrList(CStr &fName)
{
ifstream fIn(fName);
string line;
vecS strs;
while(getline(fIn, line) && line.size()){
unsigned sz = line.size();
line.resize(sz - 1); //Please use script to convert the VOC format data into the OpenCV format data
//line.resize(sz);
strs.push_back(line);
}
return strs;
}
bool CmFile::writeStrList(CStr &fName, const vecS &strs)
{
FILE *f = fopen(_S(fName), "w");
if (f == NULL)
return false;
for (size_t i = 0; i < strs.size(); i++)
fprintf(f, "%s\n", _S(strs[i]));
fclose(f);
return true;
}
<|endoftext|> |
<commit_before>77a50d50-2d53-11e5-baeb-247703a38240<commit_msg>77a58f46-2d53-11e5-baeb-247703a38240<commit_after>77a58f46-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>// Copyright (c) 2013-2014 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
// and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file timer.cpp
*
* \brief Contains remaining implementation of sirius::Timer class.
*/
#include "timer.h"
namespace sirius
{
std::map<std::string, Timer*> ftimers;
std::map<std::string, std::vector<double> > Timer::timers_;
std::map<std::string, std::vector<double> > Timer::global_timers_;
void Timer::start()
{
if (active_)
{
printf("timer %s is already running\n", label_.c_str());
Platform::abort();
}
gettimeofday(&starting_time_, NULL);
active_ = true;
}
void Timer::stop()
{
if (!active_)
{
printf("timer %s was not running\n", label_.c_str());
Platform::abort();
}
timeval end;
gettimeofday(&end, NULL);
double val = double(end.tv_sec - starting_time_.tv_sec) +
double(end.tv_usec - starting_time_.tv_usec) / 1e6;
switch (timer_type_)
{
case _local_timer_:
{
timers_[label_].push_back(val);
break;
}
case _global_timer_:
{
global_timers_[label_].push_back(val);
break;
}
}
active_ = false;
}
double Timer::value()
{
if (active_)
{
std::stringstream s;
s << "timer " << label_ << " is active";
error_local(__FILE__, __LINE__, s);
}
std::vector<double> values;
switch (timer_type_)
{
case _local_timer_:
{
values = timers_[label_];
break;
}
case _global_timer_:
{
values = global_timers_[label_];
break;
}
}
double d = 0;
for (int i = 0; i < (int)values.size(); i++) d += values[i];
return d;
}
extern "C" void print_cuda_timers();
void Timer::print()
{
std::map< std::string, timer_stats> tstats = collect_timer_stats();
if (Platform::mpi_rank() == 0)
{
printf("\n");
printf("Timers\n");
for (int i = 0; i < 115; i++) printf("-");
printf("\n");
printf("name count total min max average\n");
for (int i = 0; i < 115; i++) printf("-");
printf("\n");
std::map<std::string, timer_stats>::iterator it;
for (it = tstats.begin(); it != tstats.end(); it++)
{
auto ts = it->second;
if (ts.timer_type == _local_timer_)
{
printf("%-60s : %5i %10.4f %10.4f %10.4f %10.4f\n", it->first.c_str(), ts.count, ts.total_value,
ts.min_value, ts.max_value, ts.average_value);
}
if (ts.timer_type == _global_timer_)
{
printf("%-60s : %5i %10.4f %10.4f %10.4f %10.4f +\n", it->first.c_str(), ts.count, ts.total_value,
ts.min_value, ts.max_value, ts.average_value);
}
}
#ifdef _GPU_
print_cuda_timers();
#endif
}
}
void Timer::delay(double dsec)
{
timeval t1;
timeval t2;
double d;
gettimeofday(&t1, NULL);
do
{
gettimeofday(&t2, NULL);
d = double(t2.tv_sec - t1.tv_sec) + double(t2.tv_usec - t1.tv_usec) / 1e6;
} while (d < dsec);
}
std::map< std::string, timer_stats> Timer::collect_timer_stats()
{
std::map< std::string, timer_stats> tstats;
//std::map<std::string, std::vector<double> >::iterator it;
/* collect local timers */
for (auto& it: timers_)
{
timer_stats ts;
ts.timer_type = _local_timer_;
ts.count = (int)it.second.size();
ts.total_value = 0.0;
ts.min_value = 1e100;
ts.max_value = 0.0;
for (int i = 0; i < ts.count; i++)
{
ts.total_value += it.second[i];
ts.min_value = std::min(ts.min_value, it.second[i]);
ts.max_value = std::max(ts.max_value, it.second[i]);
}
ts.average_value = (ts.count == 0) ? 0.0 : ts.total_value / ts.count;
if (ts.count == 0) ts.min_value = 0.0;
tstats[it.first] = ts;
}
/* collect and broadcast global timer labels from rank#0 */
std::vector< std::string > labels;
std::vector<int> label_sizes;
std::vector<char> label_str;
if (Platform::mpi_rank() == 0)
{
for (auto& it: global_timers_)
{
/* save timer's label */
labels.push_back(it.first);
/* save length of the label */
label_sizes.push_back((int)it.first.size());
/* save label in the single array */
for (int i = 0; i < (int)it.first.size(); i++) label_str.push_back(it.first[i]);
}
}
// TODO: this can be moved to Platform::bcast
/* broadcast the number of labels from rank#0 */
int n = (int)label_sizes.size();
Platform::bcast(&n, 1, 0);
/* each MPI rank allocates space for label sizes */
if (Platform::mpi_rank() != 0) label_sizes.resize(n);
/* broadacst label sizes from rank#0 */
Platform::bcast(&label_sizes[0], n, 0);
/* broadcast the size of labels buffer from rank#0 */
n = (int)label_str.size();
Platform::bcast(&n, 1, 0);
/* allocate space for labels buffer */
if (Platform::mpi_rank() != 0) label_str.resize(n);
/* broadcast labels buffer */
Platform::bcast(&label_str[0], n, 0);
/* construct list of labels exactly like on rank#0 */
if (Platform::mpi_rank() != 0)
{
int offset = 0;
for (int sz: label_sizes)
{
labels.push_back(std::string(&label_str[offset], sz));
offset += sz;
}
}
/* now all MPI ranks loop over the same sequence of global timer labels */
for (auto& label: labels)
{
timer_stats ts;
ts.timer_type = _global_timer_;
/* this MPI rank doesn't have a corresponding timer */
if (global_timers_.count(label) == 0)
{
ts.count = 0;
ts.total_value = 0.0;
ts.min_value = 0.0;
ts.max_value = 0.0;
ts.average_value = 0.0;
}
else
{
ts.count = (int)global_timers_[label].size();
ts.total_value = 0.0;
ts.min_value = 1e100;
ts.max_value = 0.0;
/* loop over timer measurements and collect total, min, max, average */
for (int k = 0; k < ts.count; k++)
{
double v = global_timers_[label][k];
ts.total_value += v;
ts.min_value = std::min(ts.min_value, v);
ts.max_value = std::max(ts.max_value, v);
}
ts.average_value = (ts.count == 0) ? 0.0 : ts.total_value / ts.count;
if (ts.count == 0) ts.min_value = 0.0;
}
/* collect timer counts from all ranks */
std::vector<int> counts(Platform::num_mpi_ranks());
counts[Platform::mpi_rank()] = ts.count;
Platform::allgather(&counts[0], Platform::mpi_rank(), 1);
/* collect timer statistics from all ranks */
std::vector<double> values(4 * Platform::num_mpi_ranks());
values[4 * Platform::mpi_rank() + 0] = ts.total_value;
values[4 * Platform::mpi_rank() + 1] = ts.min_value;
values[4 * Platform::mpi_rank() + 2] = ts.max_value;
values[4 * Platform::mpi_rank() + 3] = ts.average_value;
Platform::allgather(&values[0], 4 * Platform::mpi_rank(), 4);
double max_total_value = 0;
double total_value = 0;
int total_count = 0;
for (int k = 0; k < Platform::num_mpi_ranks(); k++)
{
/* maximum total value across all ranks */
max_total_value = std::max(max_total_value, values[4 * k + 0]);
/* minimum value across all ranks */
ts.min_value = std::min(ts.min_value, values[4 * k + 1]);
/* maximum value across all ranks */
ts.max_value = std::max(ts.max_value, values[4 * k + 2]);
/* total global value */
total_value += values[4 * k + 0];
/* total number of counts */
total_count += counts[k];
}
/* report maximum total value across all ranks */
ts.total_value = max_total_value;
ts.average_value = (total_count == 0) ? 0.0 : total_value / total_count;
tstats[label] = ts;
}
return tstats;
}
};
<commit_msg>no namespace for Fortran timers<commit_after>// Copyright (c) 2013-2014 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
// and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file timer.cpp
*
* \brief Contains remaining implementation of sirius::Timer class.
*/
#include "timer.h"
std::map<std::string, sirius::Timer*> ftimers;
namespace sirius
{
std::map<std::string, std::vector<double> > Timer::timers_;
std::map<std::string, std::vector<double> > Timer::global_timers_;
void Timer::start()
{
if (active_)
{
printf("timer %s is already running\n", label_.c_str());
Platform::abort();
}
gettimeofday(&starting_time_, NULL);
active_ = true;
}
void Timer::stop()
{
if (!active_)
{
printf("timer %s was not running\n", label_.c_str());
Platform::abort();
}
timeval end;
gettimeofday(&end, NULL);
double val = double(end.tv_sec - starting_time_.tv_sec) +
double(end.tv_usec - starting_time_.tv_usec) / 1e6;
switch (timer_type_)
{
case _local_timer_:
{
timers_[label_].push_back(val);
break;
}
case _global_timer_:
{
global_timers_[label_].push_back(val);
break;
}
}
active_ = false;
}
double Timer::value()
{
if (active_)
{
std::stringstream s;
s << "timer " << label_ << " is active";
error_local(__FILE__, __LINE__, s);
}
std::vector<double> values;
switch (timer_type_)
{
case _local_timer_:
{
values = timers_[label_];
break;
}
case _global_timer_:
{
values = global_timers_[label_];
break;
}
}
double d = 0;
for (int i = 0; i < (int)values.size(); i++) d += values[i];
return d;
}
extern "C" void print_cuda_timers();
void Timer::print()
{
std::map< std::string, timer_stats> tstats = collect_timer_stats();
if (Platform::mpi_rank() == 0)
{
printf("\n");
printf("Timers\n");
for (int i = 0; i < 115; i++) printf("-");
printf("\n");
printf("name count total min max average\n");
for (int i = 0; i < 115; i++) printf("-");
printf("\n");
std::map<std::string, timer_stats>::iterator it;
for (it = tstats.begin(); it != tstats.end(); it++)
{
auto ts = it->second;
if (ts.timer_type == _local_timer_)
{
printf("%-60s : %5i %10.4f %10.4f %10.4f %10.4f\n", it->first.c_str(), ts.count, ts.total_value,
ts.min_value, ts.max_value, ts.average_value);
}
if (ts.timer_type == _global_timer_)
{
printf("%-60s : %5i %10.4f %10.4f %10.4f %10.4f +\n", it->first.c_str(), ts.count, ts.total_value,
ts.min_value, ts.max_value, ts.average_value);
}
}
#ifdef _GPU_
print_cuda_timers();
#endif
}
}
void Timer::delay(double dsec)
{
timeval t1;
timeval t2;
double d;
gettimeofday(&t1, NULL);
do
{
gettimeofday(&t2, NULL);
d = double(t2.tv_sec - t1.tv_sec) + double(t2.tv_usec - t1.tv_usec) / 1e6;
} while (d < dsec);
}
std::map< std::string, timer_stats> Timer::collect_timer_stats()
{
std::map< std::string, timer_stats> tstats;
//std::map<std::string, std::vector<double> >::iterator it;
/* collect local timers */
for (auto& it: timers_)
{
timer_stats ts;
ts.timer_type = _local_timer_;
ts.count = (int)it.second.size();
ts.total_value = 0.0;
ts.min_value = 1e100;
ts.max_value = 0.0;
for (int i = 0; i < ts.count; i++)
{
ts.total_value += it.second[i];
ts.min_value = std::min(ts.min_value, it.second[i]);
ts.max_value = std::max(ts.max_value, it.second[i]);
}
ts.average_value = (ts.count == 0) ? 0.0 : ts.total_value / ts.count;
if (ts.count == 0) ts.min_value = 0.0;
tstats[it.first] = ts;
}
/* collect and broadcast global timer labels from rank#0 */
std::vector< std::string > labels;
std::vector<int> label_sizes;
std::vector<char> label_str;
if (Platform::mpi_rank() == 0)
{
for (auto& it: global_timers_)
{
/* save timer's label */
labels.push_back(it.first);
/* save length of the label */
label_sizes.push_back((int)it.first.size());
/* save label in the single array */
for (int i = 0; i < (int)it.first.size(); i++) label_str.push_back(it.first[i]);
}
}
// TODO: this can be moved to Platform::bcast
/* broadcast the number of labels from rank#0 */
int n = (int)label_sizes.size();
Platform::bcast(&n, 1, 0);
/* each MPI rank allocates space for label sizes */
if (Platform::mpi_rank() != 0) label_sizes.resize(n);
/* broadacst label sizes from rank#0 */
Platform::bcast(&label_sizes[0], n, 0);
/* broadcast the size of labels buffer from rank#0 */
n = (int)label_str.size();
Platform::bcast(&n, 1, 0);
/* allocate space for labels buffer */
if (Platform::mpi_rank() != 0) label_str.resize(n);
/* broadcast labels buffer */
Platform::bcast(&label_str[0], n, 0);
/* construct list of labels exactly like on rank#0 */
if (Platform::mpi_rank() != 0)
{
int offset = 0;
for (int sz: label_sizes)
{
labels.push_back(std::string(&label_str[offset], sz));
offset += sz;
}
}
/* now all MPI ranks loop over the same sequence of global timer labels */
for (auto& label: labels)
{
timer_stats ts;
ts.timer_type = _global_timer_;
/* this MPI rank doesn't have a corresponding timer */
if (global_timers_.count(label) == 0)
{
ts.count = 0;
ts.total_value = 0.0;
ts.min_value = 0.0;
ts.max_value = 0.0;
ts.average_value = 0.0;
}
else
{
ts.count = (int)global_timers_[label].size();
ts.total_value = 0.0;
ts.min_value = 1e100;
ts.max_value = 0.0;
/* loop over timer measurements and collect total, min, max, average */
for (int k = 0; k < ts.count; k++)
{
double v = global_timers_[label][k];
ts.total_value += v;
ts.min_value = std::min(ts.min_value, v);
ts.max_value = std::max(ts.max_value, v);
}
ts.average_value = (ts.count == 0) ? 0.0 : ts.total_value / ts.count;
if (ts.count == 0) ts.min_value = 0.0;
}
/* collect timer counts from all ranks */
std::vector<int> counts(Platform::num_mpi_ranks());
counts[Platform::mpi_rank()] = ts.count;
Platform::allgather(&counts[0], Platform::mpi_rank(), 1);
/* collect timer statistics from all ranks */
std::vector<double> values(4 * Platform::num_mpi_ranks());
values[4 * Platform::mpi_rank() + 0] = ts.total_value;
values[4 * Platform::mpi_rank() + 1] = ts.min_value;
values[4 * Platform::mpi_rank() + 2] = ts.max_value;
values[4 * Platform::mpi_rank() + 3] = ts.average_value;
Platform::allgather(&values[0], 4 * Platform::mpi_rank(), 4);
double max_total_value = 0;
double total_value = 0;
int total_count = 0;
for (int k = 0; k < Platform::num_mpi_ranks(); k++)
{
/* maximum total value across all ranks */
max_total_value = std::max(max_total_value, values[4 * k + 0]);
/* minimum value across all ranks */
ts.min_value = std::min(ts.min_value, values[4 * k + 1]);
/* maximum value across all ranks */
ts.max_value = std::max(ts.max_value, values[4 * k + 2]);
/* total global value */
total_value += values[4 * k + 0];
/* total number of counts */
total_count += counts[k];
}
/* report maximum total value across all ranks */
ts.total_value = max_total_value;
ts.average_value = (total_count == 0) ? 0.0 : total_value / total_count;
tstats[label] = ts;
}
return tstats;
}
};
<|endoftext|> |
<commit_before>a225e374-35ca-11e5-8ec5-6c40088e03e4<commit_msg>a22dcacc-35ca-11e5-9977-6c40088e03e4<commit_after>a22dcacc-35ca-11e5-9977-6c40088e03e4<|endoftext|> |
<commit_before>/******************************************************************************
*
* timer.cpp
*
* @author Copyright (C) 2015 Kotone Itaya
* @version 2.1.0
* @created 2015/11/02 Kotone Itaya -- Created!
* @@
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*****************************************************************************/
#include "spira/timer.hpp"
namespace spira {
struct timer::impl {
std::chrono::steady_clock::time_point init;
std::chrono::steady_clock::time_point curr;
double fps;
unsigned long long int frame;
unsigned long long int time;
};
timer::timer(double fps) : pimpl(std::shared_ptr<impl>(new impl())) {
this->reset();
}
timer::timer(const timer& other) {
this->pimpl = other.pimpl;
}
timer& timer::operator =(timer& other) {
swap(*this, other);
return *this;
}
void swap(timer& a, timer& b) {
std::swap(a.pimpl, b.pimpl);
}
void timer::poll() {
this->pimpl->curr = std::chrono::steady_clock::now();
std::chrono::nanoseconds duration = (this->pimpl->curr - this->pimpl->init);
this->pimpl->time = duration.count();
unsigned long long int now = ((this->pimpl->time * this->pimpl->fps) / 1000000000);
if(now > this->pimpl->frame) {
while(now > this->pimpl->frame) this->dump(++this->pimpl->frame);
}
}
void timer::reset() {
this->pimpl->init = std::chrono::steady_clock::now();
this->pimpl->frame = 0;
this->pimpl->time = 0;
this->dump(0);
}
}
<commit_msg>Fixed bug in `timer` constructor.<commit_after>/******************************************************************************
*
* timer.cpp
*
* @author Copyright (C) 2015 Kotone Itaya
* @version 2.1.0
* @created 2015/11/02 Kotone Itaya -- Created!
* @@
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*****************************************************************************/
#include "spira/timer.hpp"
namespace spira {
struct timer::impl {
std::chrono::steady_clock::time_point init;
std::chrono::steady_clock::time_point curr;
double fps;
unsigned long long int frame;
unsigned long long int time;
};
timer::timer(double fps) : pimpl(std::shared_ptr<impl>(new impl())) {
this->pimpl->fps = fps;
this->reset();
}
timer::timer(const timer& other) {
this->pimpl = other.pimpl;
}
timer& timer::operator =(timer& other) {
swap(*this, other);
return *this;
}
void swap(timer& a, timer& b) {
std::swap(a.pimpl, b.pimpl);
}
void timer::poll() {
this->pimpl->curr = std::chrono::steady_clock::now();
std::chrono::nanoseconds duration = (this->pimpl->curr - this->pimpl->init);
this->pimpl->time = duration.count();
unsigned long long int now = ((this->pimpl->time * this->pimpl->fps) / 1000000000);
if(now > this->pimpl->frame) {
while(now > this->pimpl->frame) this->dump(++this->pimpl->frame);
}
}
void timer::reset() {
this->pimpl->init = std::chrono::steady_clock::now();
this->pimpl->frame = 0;
this->pimpl->time = 0;
this->dump(0);
}
}
<|endoftext|> |
<commit_before>7d5b50ae-2e4f-11e5-a062-28cfe91dbc4b<commit_msg>7d636fd1-2e4f-11e5-819b-28cfe91dbc4b<commit_after>7d636fd1-2e4f-11e5-819b-28cfe91dbc4b<|endoftext|> |
<commit_before>30436c5c-2748-11e6-8a32-e0f84713e7b8<commit_msg>Fixed that one bug<commit_after>3054d542-2748-11e6-a941-e0f84713e7b8<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.