hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d1a48e71dfcdd1cb0d06f2946bc29c12c489b357 | 1,923 | hpp | C++ | SpelJongEmu/src/Op.hpp | fallahn/speljongen | 57cb5e09eec7db8c21ee7b3e7943fa0a76738c51 | [
"Unlicense"
] | 17 | 2018-06-23T14:40:56.000Z | 2019-07-02T11:58:55.000Z | SpelJongEmu/src/Op.hpp | fallahn/speljongen | 57cb5e09eec7db8c21ee7b3e7943fa0a76738c51 | [
"Unlicense"
] | 3 | 2018-06-23T12:35:12.000Z | 2018-06-23T12:38:54.000Z | SpelJongEmu/src/Op.hpp | fallahn/speljongen | 57cb5e09eec7db8c21ee7b3e7943fa0a76738c51 | [
"Unlicense"
] | null | null | null | /*
MIT License
Copyright(c) 2017 Tomasz R?kawek(Coffee GB)
Copyright(c) 2018 Matt Marchant(Speljongen)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <cstdint>
#include <cstddef>
#include <array>
#include <functional>
class AddressSpace;
class Registers;
class InterruptManager;
using OpArgs = std::array<std::uint8_t, 2>;
using OpExecution = std::function<std::uint16_t(Registers&, AddressSpace&, const OpArgs&, std::uint16_t)>;
struct Op final
{
bool readsMemory = false;
bool writesMemory = false;
std::size_t operandLength = 0;
OpExecution execute =
[](Registers&, AddressSpace&, const OpArgs&, std::uint16_t context)
{
return context;
};
std::function<void(InterruptManager& interruptManager)> switchInterrupts = [](InterruptManager&) {};
std::function<bool(Registers& registers)>proceed = [](Registers&) { return true; };
bool forceFinishCycle = false;
}; | 34.339286 | 106 | 0.75767 | fallahn |
d1a543a5924c328cefb16dc22a80cf0542a54145 | 2,947 | cpp | C++ | src/editor/views/MooClock.cpp | XD-chill-bro/ptcollab | 757a7cc099bf28009438471b93d0def483e95dfa | [
"MIT"
] | null | null | null | src/editor/views/MooClock.cpp | XD-chill-bro/ptcollab | 757a7cc099bf28009438471b93d0def483e95dfa | [
"MIT"
] | null | null | null | src/editor/views/MooClock.cpp | XD-chill-bro/ptcollab | 757a7cc099bf28009438471b93d0def483e95dfa | [
"MIT"
] | null | null | null | #include "MooClock.h"
MooClock::MooClock(PxtoneClient *client)
: QObject(client),
m_client(client),
m_prev_clock(0),
m_this_seek(0),
m_this_seek_caught_up(false) {
connect(m_client->controller(), &PxtoneController::seeked, [this](int clock) {
m_this_seek = clock;
m_this_seek_caught_up = false;
});
}
int MooClock::last_clock() const {
const pxtnMaster *master = m_client->pxtn()->master;
return master->get_beat_clock() * master->get_play_meas() *
master->get_beat_num();
}
int MooClock::repeat_clock() const {
const pxtnMaster *master = m_client->pxtn()->master;
return master->get_repeat_meas() * master->get_beat_num() *
master->get_beat_clock();
}
int MooClock::now() {
int clock = m_client->pxtn()->moo_get_now_clock(*m_client->moo());
// Some really hacky magic to get the playhead smoother given that
// there's a ton of buffering that makes it hard to actually tell where the
// playhead is accurately. We do this:
// 1. Subtract the buffer duration.
// 2. Track how long since the last (laggy) clock update and add.
// 3. Works most of the time, but leads to a wrong clock after a seek or at
// the end of a song, because it'll put the playhead before the repeat or
// the seek position.
// 4. To account for this, if we're before the current seek position, clamp
// to seek position. Also track if we've looped and render at the end of
// song instead of before repeat if so.
// 5. The tracking if we've looped or not is also necessary to tell if we've
// actually caught up to a seek.
int bytes_per_second = 4 * 44100; // bytes in sample * bytes per second
if (m_prev_clock != clock) {
m_prev_clock = clock;
timeSinceLastClock.restart();
}
int64_t offset_from_buffer =
m_client->audioState()->bufferSize(); // - m_audio_output->bytesFree()
double estimated_buffer_offset =
-offset_from_buffer / double(bytes_per_second);
if (!m_client->isPlaying())
timeSinceLastClock.restart();
else
estimated_buffer_offset += timeSinceLastClock.elapsed() / 1000.0;
clock += (last_clock() - repeat_clock()) * m_client->moo()->num_loop;
const pxtnMaster *master = m_client->pxtn()->master;
clock += std::min(estimated_buffer_offset, 0.0) * master->get_beat_tempo() *
master->get_beat_clock() / 60;
if (clock >= m_this_seek) m_this_seek_caught_up = true;
if (!m_this_seek_caught_up) clock = m_this_seek;
if (clock >= last_clock())
clock = (clock - repeat_clock()) % (last_clock() - repeat_clock()) +
repeat_clock();
// Because of offsetting it might seem like even though we've repeated the
// clock is before [repeat_clock]. So fix it here.
if (m_client->moo()->num_loop > 0 && clock < repeat_clock())
clock += last_clock() - repeat_clock();
return clock;
}
bool MooClock::has_last() const {
return m_client->pxtn()->master->get_last_meas() > 0;
}
| 35.939024 | 80 | 0.684425 | XD-chill-bro |
d1a5aea2963cedc749bf9be286cf65bb74c85ccc | 44,821 | cc | C++ | xpdf/TileMap.cc | haephrati/SG_PDF2Text | 393ba8b500de6d10ab7c38936c009a5c44fa4189 | [
"Apache-2.0"
] | 1 | 2021-10-30T07:53:44.000Z | 2021-10-30T07:53:44.000Z | xpdf/TileMap.cc | haephrati/SG_PDF2Text | 393ba8b500de6d10ab7c38936c009a5c44fa4189 | [
"Apache-2.0"
] | null | null | null | xpdf/TileMap.cc | haephrati/SG_PDF2Text | 393ba8b500de6d10ab7c38936c009a5c44fa4189 | [
"Apache-2.0"
] | null | null | null | //========================================================================
//
// TileMap.cc
//
// Copyright 2014 Glyph & Cog, LLC
//
//========================================================================
#include <aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif
#include "gmem.h"
#include "gmempp.h"
#include "GList.h"
#include "PDFDoc.h"
#include "DisplayState.h"
#include "TileMap.h"
//------------------------------------------------------------------------
// Number of pixels of matte color between pages (above and below each
// other) in continuous mode.
#define continuousPageSpacing 3
// Number of pixels of matte color between facing pages (left and
// right of each other) in side-by-side mode.
#define sideBySidePageSpacing 3
// Number of pixels of matte color between pages (left and right of
// each other) in horizontal continuous mode.
#define horizContinuousPageSpacing 3
//------------------------------------------------------------------------
TileMap::TileMap(DisplayState *stateA) {
state = stateA;
state->setTileMap(this);
pageDPI = NULL;
pageW = pageH = NULL;
tileW = tileH = NULL;
pageBoxW = pageBoxH = NULL;
pageX = pageY = NULL;
tiles = NULL;
}
TileMap::~TileMap() {
clearPageParams();
clearContinuousModeParams();
gfree(pageBoxW);
gfree(pageBoxH);
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
}
}
GList *TileMap::getTileList() {
double pageDPI1, pageDPI2;
int pageW1, pageH1, tileW1, tileH1, pageW2, pageH2, tileW2, tileH2;
int offsetX, offsetY, offsetX2;
int x0, y0, x1, y1, x, y, tx, ty, tw, th, page;
if (tiles) {
return tiles;
}
tiles = new GList();
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
return tiles;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
page = state->getScrollPage();
pageDPI1 = pageDPI[page - 1];
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
tileW1 = tileW[page - 1];
tileH1 = tileH[page - 1];
if (pageW1 < state->getWinW()) {
offsetX = (state->getWinW() - pageW1) / 2;
} else {
offsetX = 0;
}
if (pageH1 < state->getWinH()) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = 0;
}
if ((x0 = state->getScrollX() - offsetX) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX) >= pageW1) {
x1 = pageW1 - 1;
}
if ((y1 = state->getScrollY() + state->getWinH() - 1 - offsetY) >= pageH1) {
y1 = pageH1 - 1;
}
for (y = y0 / tileH1; y <= y1 / tileH1; ++y) {
for (x = x0 / tileW1; x <= x1 / tileW1; ++x) {
tx = x * tileW1;
ty = y * tileH1;
tw = tileW1;
if (tx + tw > pageW1) {
tw = pageW1 - tx;
}
th = tileH1;
if (ty + th > pageH1) {
th = pageH1 - ty;
}
tiles->append(new PlacedTileDesc(page, state->getRotate(), pageDPI1,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX,
ty - state->getScrollY() + offsetY));
}
}
break;
case displayContinuous:
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
page = findContinuousPage(state->getScrollY());
while (page <= state->getDoc()->getNumPages() &&
pageY[page - 1] < state->getScrollY() + state->getWinH()) {
pageDPI1 = pageDPI[page - 1];
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
tileW1 = tileW[page - 1];
tileH1 = tileH[page - 1];
if (maxW < state->getWinW()) {
offsetX = (state->getWinW() - maxW) / 2;
} else {
offsetX = 0;
}
offsetX += (maxW - pageW1) / 2;
if ((x0 = state->getScrollX() - offsetX) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - pageY[page - 1] - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX)
>= pageW1) {
x1 = pageW1 - 1;
}
if ((y1 = state->getScrollY() - pageY[page - 1]
+ state->getWinH() - 1 - offsetY)
>= pageH1) {
y1 = pageH1 - 1;
}
for (y = y0 / tileH1; y <= y1 / tileH1; ++y) {
for (x = x0 / tileW1; x <= x1 / tileW1; ++x) {
tx = x * tileW1;
ty = y * tileH1;
tw = tileW1;
if (tx + tw > pageW1) {
tw = pageW1 - tx;
}
th = tileH1;
if (ty + th > pageH1) {
th = pageH1 - ty;
}
tiles->append(new PlacedTileDesc(
page, state->getRotate(), pageDPI1,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX,
ty - state->getScrollY() + pageY[page - 1]
+ offsetY));
}
}
++page;
}
break;
case displaySideBySideSingle:
page = state->getScrollPage();
pageDPI1 = pageDPI[page - 1];
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
tileW1 = tileW[page - 1];
tileH1 = tileH[page - 1];
if (page + 1 <= state->getDoc()->getNumPages()) {
pageDPI2 = pageDPI[page];
pageW2 = pageW[page];
pageH2 = pageH[page];
tileW2 = tileW[page];
tileH2 = tileH[page];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageDPI2 = pageDPI1;
pageW2 = pageW1;
pageH2 = pageH1;
tileW2 = tileW1;
tileH2 = tileH1;
}
if (pageW1 + sideBySidePageSpacing + pageW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(pageW1 + sideBySidePageSpacing + pageW2)) / 2;
} else {
offsetX = 0;
}
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
if (pageH1 < state->getWinH() && pageH2 < state->getWinH()) {
if (pageH1 > pageH2) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = (state->getWinH() - pageH2) / 2;
}
} else {
offsetY = 0;
}
// left page
if ((x0 = state->getScrollX() - offsetX) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX) >= pageW1) {
x1 = pageW1 - 1;
} else if (x1 < 0) {
x1 = -tileW2;
}
if ((y1 = state->getScrollY() + state->getWinH() - 1 - offsetY) >= pageH1) {
y1 = pageH1 - 1;
} else if (y1 < 0) {
y1 = -tileH2;
}
for (y = y0 / tileH1; y <= y1 / tileH1; ++y) {
for (x = x0 / tileW1; x <= x1 / tileW1; ++x) {
tx = x * tileW1;
ty = y * tileH1;
tw = tileW1;
if (tx + tw > pageW1) {
tw = pageW1 - tx;
}
th = tileH1;
if (ty + th > pageH1) {
th = pageH1 - ty;
}
tiles->append(new PlacedTileDesc(page,
state->getRotate(), pageDPI1,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX,
ty - state->getScrollY() + offsetY));
}
}
// right page
if (page + 1 <= state->getDoc()->getNumPages()) {
if ((x0 = state->getScrollX() - offsetX2) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX2)
>= pageW2) {
x1 = pageW2 - 1;
} else if (x1 < 0) {
x1 = -tileW2;
}
if ((y1 = state->getScrollY() + state->getWinH() - 1 - offsetY)
>= pageH2) {
y1 = pageH2 - 1;
} else if (y1 < 0) {
y1 = -tileH2;
}
for (y = y0 / tileH2; y <= y1 / tileH2; ++y) {
for (x = x0 / tileW2; x <= x1 / tileW2; ++x) {
tx = x * tileW2;
ty = y * tileH2;
tw = tileW2;
if (tx + tw > pageW2) {
tw = pageW2 - tx;
}
th = tileH2;
if (ty + th > pageH2) {
th = pageH2 - ty;
}
tiles->append(new PlacedTileDesc(page + 1,
state->getRotate(), pageDPI2,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX2,
ty - state->getScrollY() + offsetY));
}
}
}
break;
case displaySideBySideContinuous:
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
page = findSideBySideContinuousPage(state->getScrollY());
while (page <= state->getDoc()->getNumPages() &&
(pageY[page - 1] < state->getScrollY() + state->getWinH() ||
(page + 1 <= state->getDoc()->getNumPages() &&
pageY[page] < state->getScrollY() + state->getWinH()))) {
pageDPI1 = pageDPI[page - 1];
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
tileW1 = tileW[page - 1];
tileH1 = tileH[page - 1];
if (page + 1 <= state->getDoc()->getNumPages()) {
pageDPI2 = pageDPI[page];
pageW2 = pageW[page];
pageH2 = pageH[page];
tileW2 = tileW[page];
tileH2 = tileH[page];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageDPI2 = pageDPI1;
pageW2 = pageW1;
pageH2 = pageH1;
tileW2 = tileW1;
tileH2 = tileH1;
}
if (maxW + sideBySidePageSpacing + maxW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(maxW + sideBySidePageSpacing + maxW2)) / 2;
} else {
offsetX = 0;
}
offsetX += maxW - pageW1;
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
// left page
if ((x0 = state->getScrollX() - offsetX) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - pageY[page - 1] - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX)
>= pageW1) {
x1 = pageW1 - 1;
} else if (x1 < 0) {
x1 = -tileW2;
}
if ((y1 = state->getScrollY() - pageY[page - 1]
+ state->getWinH() - 1 - offsetY)
>= pageH1) {
y1 = pageH1 - 1;
} else if (y1 < 0) {
y1 = -tileH2;
}
for (y = y0 / tileH1; y <= y1 / tileH1; ++y) {
for (x = x0 / tileW1; x <= x1 / tileW1; ++x) {
tx = x * tileW1;
ty = y * tileH1;
tw = tileW1;
if (tx + tw > pageW1) {
tw = pageW1 - tx;
}
th = tileH1;
if (ty + th > pageH1) {
th = pageH1 - ty;
}
tiles->append(new PlacedTileDesc(
page, state->getRotate(), pageDPI1,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX,
ty - state->getScrollY() + pageY[page - 1]
+ offsetY));
}
}
++page;
// right page
if (page <= state->getDoc()->getNumPages()) {
if ((x0 = state->getScrollX() - offsetX2) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - pageY[page - 1] - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() + state->getWinW() - 1 - offsetX2)
>= pageW2) {
x1 = pageW2 - 1;
} else if (x1 < 0) {
x1 = -tileW2;
}
if ((y1 = state->getScrollY() - pageY[page - 1]
+ state->getWinH() - 1 - offsetY)
>= pageH2) {
y1 = pageH2 - 1;
} else if (y1 < 0) {
y1 = -tileH2;
}
for (y = y0 / tileH2; y <= y1 / tileH2; ++y) {
for (x = x0 / tileW2; x <= x1 / tileW2; ++x) {
tx = x * tileW2;
ty = y * tileH2;
tw = tileW2;
if (tx + tw > pageW2) {
tw = pageW2 - tx;
}
th = tileH2;
if (ty + th > pageH2) {
th = pageH2 - ty;
}
tiles->append(new PlacedTileDesc(
page, state->getRotate(), pageDPI2,
tx, ty, tw, th,
tx - state->getScrollX() + offsetX2,
ty - state->getScrollY() + pageY[page - 1]
+ offsetY));
}
}
}
++page;
}
break;
case displayHorizontalContinuous:
if (totalW < state->getWinW()) {
offsetX = (state->getWinW() - totalW) / 2;
} else {
offsetX = 0;
}
page = findHorizContinuousPage(state->getScrollX());
while (page <= state->getDoc()->getNumPages() &&
pageX[page - 1] < state->getScrollX() + state->getWinW()) {
pageDPI1 = pageDPI[page - 1];
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
tileW1 = tileW[page - 1];
tileH1 = tileH[page - 1];
if (maxH < state->getWinH()) {
offsetY = (state->getWinH() - maxH) / 2;
} else {
offsetY = 0;
}
if ((x0 = state->getScrollX() - pageX[page - 1] - offsetX) < 0) {
x0 = 0;
}
if ((y0 = state->getScrollY() - offsetY) < 0) {
y0 = 0;
}
if ((x1 = state->getScrollX() - pageX[page - 1]
+ state->getWinW() - 1 - offsetX)
>= pageW1) {
x1 = pageW1 - 1;
}
if ((y1 = state->getScrollY() + state->getWinH() - 1 - offsetY)
>= pageH1) {
y1 = pageH1 - 1;
}
for (y = y0 / tileH1; y <= y1 / tileH1; ++y) {
for (x = x0 / tileW1; x <= x1 / tileW1; ++x) {
tx = x * tileW1;
ty = y * tileH1;
tw = tileW1;
if (tx + tw > pageW1) {
tw = pageW1 - tx;
}
th = tileH1;
if (ty + th > pageH1) {
th = pageH1 - ty;
}
tiles->append(new PlacedTileDesc(
page, state->getRotate(), pageDPI1,
tx, ty, tw, th,
tx - state->getScrollX() + pageX[page - 1]
+ offsetX,
ty - state->getScrollY() + offsetY));
}
}
++page;
}
break;
}
return tiles;
}
void TileMap::getScrollLimits(int *horizMax, int *vertMax) {
int pageW1, pageH1, pageW2, pageH2;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
*horizMax = *vertMax = 0;
return;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
*horizMax = pageW[state->getScrollPage() - 1];
*vertMax = pageH[state->getScrollPage() - 1];
break;
case displayContinuous:
*horizMax = maxW;
*vertMax = totalH;
break;
case displaySideBySideSingle:
pageW1 = pageW[state->getScrollPage() - 1];
pageH1 = pageH[state->getScrollPage() - 1];
if (state->getScrollPage() + 1 <= state->getDoc()->getNumPages()) {
pageW2 = pageW[state->getScrollPage()];
pageH2 = pageH[state->getScrollPage()];
} else {
pageW2 = pageW1;
pageH2 = pageH1;
}
*horizMax = pageW1 + sideBySidePageSpacing + pageW2;
*vertMax = pageH1 > pageH2 ? pageH1 : pageH2;
break;
case displaySideBySideContinuous:
*horizMax = maxW + sideBySidePageSpacing + maxW2;
*vertMax = totalH;
break;
case displayHorizontalContinuous:
*horizMax = totalW;
*vertMax = maxH;
break;
default: // should never happen
*horizMax = *vertMax = 0;
break;
}
}
GBool TileMap::cvtWindowToUser(int xw, int yw,
int *pg, double *xu, double *yu) {
GBool ok;
int xd, yd;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
*pg = 0;
*xu = *yu = 0;
return gFalse;
}
ok = cvtWindowToDev(xw, yw, pg, &xd, &yd);
cvtDevToUser(*pg, xd, yd, xu, yu);
return ok;
}
GBool TileMap::cvtWindowToDev(int xw, int yw,
int *pg, int *xd, int *yd) {
int pageW1, pageH1, pageW2, pageH2, offsetX, offsetX2, offsetY;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
*pg = 0;
*xd = *yd = 0;
return gFalse;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
*pg = state->getScrollPage();
pageW1 = pageW[*pg - 1];
pageH1 = pageH[*pg - 1];
if (pageW1 < state->getWinW()) {
offsetX = (state->getWinW() - pageW1) / 2;
} else {
offsetX = 0;
}
if (pageH1 < state->getWinH()) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = 0;
}
*xd = xw - offsetX + state->getScrollX();
*yd = yw - offsetY + state->getScrollY();
return *xd >= 0 && *xd < pageW1 && *yd >= 0 && *yd < pageH1;
case displayContinuous:
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
*pg = findContinuousPage(yw - offsetY + state->getScrollY());
if (*pg < 1 || *pg > state->getDoc()->getNumPages()) {
*pg = 0;
*xd = *yd = 0;
return gFalse;
}
pageW1 = pageW[*pg - 1];
pageH1 = pageH[*pg - 1];
if (maxW < state->getWinW()) {
offsetX = (state->getWinW() - maxW) / 2;
} else {
offsetX = 0;
}
offsetX += (maxW - pageW1) / 2;
*xd = xw - offsetX + state->getScrollX();
*yd = yw - offsetY - pageY[*pg - 1] + state->getScrollY();
return *xd >= 0 && *xd < pageW1 && *yd >= 0 && *yd < pageH1;
case displaySideBySideSingle:
pageW1 = pageW[state->getScrollPage() - 1];
pageH1 = pageH[state->getScrollPage() - 1];
if (state->getScrollPage() + 1 <= state->getDoc()->getNumPages()) {
pageW2 = pageW[state->getScrollPage()];
pageH2 = pageH[state->getScrollPage()];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageW2 = pageW1;
pageH2 = pageH1;
}
if (pageW1 + sideBySidePageSpacing + pageW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(pageW1 + sideBySidePageSpacing + pageW2)) / 2;
} else {
offsetX = 0;
}
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
if (pageH1 < state->getWinH() && pageH2 < state->getWinH()) {
if (pageH1 > pageH2) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = (state->getWinH() - pageH2) / 2;
}
} else {
offsetY = 0;
}
if (xw + state->getScrollX() < offsetX2) {
*pg = state->getScrollPage();
*xd = xw - offsetX + state->getScrollX();
*yd = yw - offsetY + state->getScrollY();
return *xd >= 0 && *xd < pageW1 && *yd >= 0 && *yd < pageH1;
} else {
if (state->getScrollPage() + 1 > state->getDoc()->getNumPages()) {
*pg = *xd = *yd = 0;
return gFalse;
}
*pg = state->getScrollPage() + 1;
*xd = xw - offsetX2 + state->getScrollX();
*yd = yw - offsetY + state->getScrollY();
return *xd >= 0 && *xd < pageW2 && *yd >= 0 && *yd < pageH2;
}
case displaySideBySideContinuous:
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
*pg = findSideBySideContinuousPage(yw - offsetY + state->getScrollY());
if (*pg < 1 || *pg > state->getDoc()->getNumPages()) {
*pg = 0;
*xd = *yd = 0;
return gFalse;
}
pageW1 = pageW[*pg - 1];
pageH1 = pageH[*pg - 1];
if (*pg + 1 <= state->getDoc()->getNumPages()) {
pageW2 = pageW[*pg];
pageH2 = pageH[*pg];
} else {
pageW2 = pageH2 = 0;
}
if (maxW + sideBySidePageSpacing + maxW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(maxW + sideBySidePageSpacing + maxW2)) / 2;
} else {
offsetX = 0;
}
offsetX += maxW - pageW1;
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
if (xw + state->getScrollX() < offsetX2) {
*xd = xw - offsetX + state->getScrollX();
*yd = yw - offsetY - pageY[*pg - 1] + state->getScrollY();
return *xd >= 0 && *xd < pageW1 && *yd >= 0 && *yd < pageH1;
} else {
if (*pg + 1 > state->getDoc()->getNumPages()) {
*pg = *xd = *yd = 0;
return false;
}
++*pg;
*xd = xw - offsetX2 + state->getScrollX();
*yd = yw - offsetY - pageY[*pg - 1] + state->getScrollY();
return *xd >= 0 && *xd < pageW2 && *yd >= 0 && *yd < pageH2;
}
case displayHorizontalContinuous:
if (totalW < state->getWinW()) {
offsetX = (state->getWinW() - totalW) / 2;
} else {
offsetX = 0;
}
*pg = findHorizContinuousPage(xw - offsetX + state->getScrollX());
if (*pg < 1 || *pg > state->getDoc()->getNumPages()) {
*pg = 0;
*xd = *yd = 0;
return gFalse;
}
pageW1 = pageW[*pg - 1];
pageH1 = pageH[*pg - 1];
if (maxH < state->getWinH()) {
offsetY = (state->getWinH() - maxH) / 2;
} else {
offsetY = 0;
}
*xd = xw - offsetX - pageX[*pg - 1] + state->getScrollX();
*yd = yw - offsetY + state->getScrollY();
return *xd >= 0 && *xd < pageW1 && *yd >= 0 && *yd < pageH1;
}
return gFalse;
}
GBool TileMap::cvtUserToWindow(int pg, double xu, double yu,
int *xw, int *yw) {
int xd, yd;
cvtUserToDev(pg, xu, yu, &xd, &yd);
return cvtDevToWindow(pg, xd, yd, xw, yw);
}
GBool TileMap::cvtDevToWindow(int pg, int xd, int yd,
int *xw, int *yw) {
int leftPg, pageW1, pageH1, pageW2, pageH2, offsetX, offsetX2, offsetY;
if (!state->getDoc() ||
pg < 1 || pg > state->getDoc()->getNumPages()) {
*xw = *yw = 0;
return gFalse;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
if (pg != state->getScrollPage()) {
*xw = *yw = 0;
return gFalse;
}
pageW1 = pageW[pg - 1];
pageH1 = pageH[pg - 1];
if (pageW1 < state->getWinW()) {
offsetX = (state->getWinW() - pageW1) / 2;
} else {
offsetX = 0;
}
if (pageH1 < state->getWinH()) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = 0;
}
*xw = xd + offsetX - state->getScrollX();
*yw = yd + offsetY - state->getScrollY();
break;
case displayContinuous:
pageW1 = pageW[pg - 1];
pageH1 = pageH[pg - 1];
if (maxW < state->getWinW()) {
offsetX = (state->getWinW() - maxW) / 2;
} else {
offsetX = 0;
}
offsetX += (maxW - pageW1) / 2;
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
*xw = xd + offsetX - state->getScrollX();
*yw = pageY[pg - 1] + yd + offsetY - state->getScrollY();
break;
case displaySideBySideSingle:
if (!(pg == state->getScrollPage() ||
(pg == state->getScrollPage() + 1 &&
state->getScrollPage() + 1 <= state->getDoc()->getNumPages()))) {
*xw = *yw = 0;
return gFalse;
}
pageW1 = pageW[state->getScrollPage() - 1];
pageH1 = pageH[state->getScrollPage() - 1];
if (state->getScrollPage() + 1 <= state->getDoc()->getNumPages()) {
pageW2 = pageW[state->getScrollPage()];
pageH2 = pageH[state->getScrollPage()];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageW2 = pageW1;
pageH2 = pageH1;
}
if (pageW1 + sideBySidePageSpacing + pageW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(pageW1 + sideBySidePageSpacing + pageW2)) / 2;
} else {
offsetX = 0;
}
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
if (pageH1 < state->getWinH() && pageH2 < state->getWinH()) {
if (pageH1 > pageH2) {
offsetY = (state->getWinH() - pageH1) / 2;
} else {
offsetY = (state->getWinH() - pageH2) / 2;
}
} else {
offsetY = 0;
}
if (pg == state->getScrollPage()) {
*xw = xd + offsetX - state->getScrollX();
*yw = yd + offsetY - state->getScrollY();
} else {
*xw = xd + offsetX2 - state->getScrollX();
*yw = yd + offsetY - state->getScrollY();
}
break;
case displaySideBySideContinuous:
leftPg = (pg - 1) | 1;
pageW1 = pageW[leftPg - 1];
pageH1 = pageH[leftPg - 1];
if (maxW + sideBySidePageSpacing + maxW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(maxW + sideBySidePageSpacing + maxW2)) / 2;
} else {
offsetX = 0;
}
offsetX += maxW - pageW1;
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
if (totalH < state->getWinH()) {
offsetY = (state->getWinH() - totalH) / 2;
} else {
offsetY = 0;
}
if (pg == leftPg) {
*xw = xd + offsetX - state->getScrollX();
} else {
*xw = xd + offsetX2 - state->getScrollX();
}
*yw = pageY[pg - 1] + yd + offsetY - state->getScrollY();
break;
case displayHorizontalContinuous:
if (totalW < state->getWinW()) {
offsetX = (state->getWinW() - totalW) / 2;
} else {
offsetX = 0;
}
if (maxH < state->getWinH()) {
offsetY = (state->getWinH() - maxH) / 2;
} else {
offsetY = 0;
}
*xw = pageX[pg - 1] + xd + offsetX - state->getScrollX();
*yw = yd + offsetY - state->getScrollY();
break;
}
return gTrue;
}
void TileMap::cvtUserToDev(int pg, double xu, double yu, int *xd, int *yd) {
double m[6];
if (!state->getDoc() ||
pg < 1 || pg > state->getDoc()->getNumPages()) {
*xd = *yd = 0;
return;
}
computePageMatrix(pg, m);
*xd = (int)(xu * m[0] + yu * m[2] + m[4] + 0.5);
*yd = (int)(xu * m[1] + yu * m[3] + m[5] + 0.5);
}
void TileMap::cvtDevToUser(int pg, int xd, int yd, double *xu, double *yu) {
double m[6], im[6];
if (!state->getDoc() ||
pg < 1 || pg > state->getDoc()->getNumPages()) {
*xu = *yu = 0;
return;
}
computePageMatrix(pg, m);
invertMatrix(m, im);
*xu = xd * im[0] + yd * im[2] + im[4];
*yu = xd * im[1] + yd * im[3] + im[5];
}
void TileMap::getWindowPageRange(int x, int y, int w, int h,
int *firstPage, int *lastPage) {
GList *tiles;
PlacedTileDesc *tile;
int i;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
*firstPage = *lastPage = 0;
return;
}
*firstPage = state->getDoc()->getNumPages();
*lastPage = 0;
tiles = getTileList();
for (i = 0; i < tiles->getLength(); ++i) {
tile = (PlacedTileDesc *)tiles->get(i);
if (tile->px < x + w &&
tile->px + tile->tw > x &&
tile->py < y + h &&
tile->py + tile->th > y) {
if (tile->page < *firstPage) {
*firstPage = tile->page;
}
if (tile->page > *lastPage) {
*lastPage = tile->page;
}
}
}
}
int TileMap::getPageTopY(int page) {
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
return 0;
}
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
case displaySideBySideSingle:
case displayHorizontalContinuous:
default:
return 0;
case displayContinuous:
case displaySideBySideContinuous:
return pageY[page - 1];
}
}
int TileMap::getPageBottomY(int page) {
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
return 0;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
case displaySideBySideSingle:
case displayHorizontalContinuous:
default:
return pageH[page - 1] - state->getWinH();
case displayContinuous:
case displaySideBySideContinuous:
return pageY[page - 1] + pageH[page - 1] - state->getWinH();
}
}
int TileMap::getPageLeftX(int page) {
int leftPage, rightPage, pageW1, pageW2, offsetX, offsetX2;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
return 0;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
default:
return 0;
case displayContinuous:
return (maxW - pageW[page - 1]) / 2;
case displaySideBySideSingle:
leftPage = ((page - 1) & ~1) + 1;
rightPage = leftPage + 1;
pageW1 = pageW[leftPage - 1];
if (rightPage <= state->getDoc()->getNumPages()) {
pageW2 = pageW[rightPage - 1];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageW2 = pageW1;
}
if (pageW1 + sideBySidePageSpacing + pageW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(pageW1 + sideBySidePageSpacing + pageW2)) / 2;
} else {
offsetX = 0;
}
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
return (page == leftPage) ? offsetX : offsetX2;
case displaySideBySideContinuous:
leftPage = ((page - 1) & ~1) + 1;
rightPage = leftPage + 1;
pageW1 = pageW[leftPage - 1];
if (maxW + sideBySidePageSpacing + maxW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(maxW + sideBySidePageSpacing + maxW2)) / 2;
} else {
offsetX = 0;
}
offsetX += maxW - pageW1;
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
return (page == leftPage) ? offsetX : offsetX2;
case displayHorizontalContinuous:
return pageX[page - 1];
}
}
int TileMap::getPageRightX(int page) {
int leftPage, rightPage, pageW1, pageW2, offsetX, offsetX2;
if (!state->getDoc() || !state->getDoc()->getNumPages()) {
return 0;
}
updatePageParams();
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
default:
return pageW[page - 1] - state->getWinW();
case displayContinuous:
return (maxW + pageW[page - 1]) / 2 - state->getWinW();
case displaySideBySideSingle:
leftPage = ((page - 1) & ~1) + 1;
rightPage = leftPage + 1;
pageW1 = pageW[leftPage - 1];
if (rightPage <= state->getDoc()->getNumPages()) {
pageW2 = pageW[rightPage - 1];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageW2 = pageW1;
}
if (pageW1 + sideBySidePageSpacing + pageW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(pageW1 + sideBySidePageSpacing + pageW2)) / 2;
} else {
offsetX = 0;
}
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
return (page == leftPage) ? offsetX + pageW1 - state->getWinW()
: offsetX2 + pageW2 - state->getWinW();
case displaySideBySideContinuous:
leftPage = ((page - 1) & ~1) + 1;
rightPage = leftPage + 1;
pageW1 = pageW[leftPage - 1];
if (rightPage <= state->getDoc()->getNumPages()) {
pageW2 = pageW[rightPage - 1];
} else {
// display a single page as though there were a blank facing
// page of the same size
pageW2 = pageW1;
}
if (maxW + sideBySidePageSpacing + maxW2 < state->getWinW()) {
offsetX = (state->getWinW() -
(maxW + sideBySidePageSpacing + maxW2)) / 2;
} else {
offsetX = 0;
}
offsetX += maxW - pageW1;
offsetX2 = offsetX + pageW1 + sideBySidePageSpacing;
return (page == leftPage) ? offsetX + pageW1 - state->getWinW()
: offsetX2 + pageW2 - state->getWinW();
case displayHorizontalContinuous:
return pageX[page - 1] + pageW[page - 1] - state->getWinW();
}
}
int TileMap::getFirstPage() {
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
default:
return state->getScrollPage();
case displayContinuous:
return findContinuousPage(state->getScrollY());
case displaySideBySideSingle:
return state->getScrollPage();
case displaySideBySideContinuous:
return findSideBySideContinuousPage(state->getScrollY());
case displayHorizontalContinuous:
return findHorizContinuousPage(state->getScrollX());
}
}
int TileMap::getFirstPageTop() {
int page;
updateContinuousModeParams();
switch (state->getDisplayMode()) {
case displaySingle:
default:
return state->getScrollPage();
case displayContinuous:
page = findContinuousPage(state->getScrollY());
if (page < state->getDoc()->getNumPages() &&
pageY[page - 1] < state->getScrollY()) {
return page + 1;
} else {
return page;
}
case displaySideBySideSingle:
return state->getScrollPage();
case displaySideBySideContinuous:
page = findSideBySideContinuousPage(state->getScrollY());
if (page < state->getDoc()->getNumPages() &&
pageY[page - 1] < state->getScrollY()) {
return page + 1;
} else {
return page;
}
case displayHorizontalContinuous:
page = findHorizContinuousPage(state->getScrollX());
if (page < state->getDoc()->getNumPages() &&
pageX[page - 1] < state->getScrollX()) {
return page + 1;
} else {
return page;
}
}
}
int TileMap::getMidPage() {
int wx, wy, pg, x, y;
wx = state->getWinW() / 2;
wy = state->getWinH() / 2;
if (!cvtWindowToDev(wx, wy, &pg, &x, &y)) {
if (state->getDisplayMode() == displayContinuous) {
wy += continuousPageSpacing;
} else if (state->getDisplayMode() == displaySideBySideContinuous) {
wx += sideBySidePageSpacing;
wy += continuousPageSpacing;
} else if (state->getDisplayMode() == displayHorizontalContinuous) {
wx += horizContinuousPageSpacing;
} else {
return state->getScrollPage();
}
if (!cvtWindowToDev(wx, wy, &pg, &x, &y)) {
return 1;
}
}
return pg;
}
int TileMap::getLastPage() {
int pg, x, y, n;
switch (state->getDisplayMode()) {
case displaySingle:
default:
return state->getScrollPage();
case displayContinuous:
if (!cvtWindowToDev(state->getWinW() / 2, state->getWinH() - 1,
&pg, &x, &y)) {
return state->getDoc()->getNumPages();
}
return pg;
case displaySideBySideSingle:
pg = state->getScrollPage() + 1;
n = state->getDoc()->getNumPages();
if (pg > n) {
pg = n;
}
return pg;
case displaySideBySideContinuous:
if (!cvtWindowToDev(state->getWinW() / 2, state->getWinH() - 1,
&pg, &x, &y)) {
return state->getScrollPage();
}
pg = ((pg - 1) & ~1) + 2;
n = state->getDoc()->getNumPages();
if (pg > n) {
pg = n;
}
return pg;
case displayHorizontalContinuous:
x = state->getWinW() - 1;
y = state->getWinH() / 2;
if (!cvtWindowToDev(state->getWinW() - 1, state->getWinH() / 2,
&pg, &x, &y)) {
return state->getDoc()->getNumPages();
}
return pg;
}
}
double TileMap::getDPI(int page) {
if (page < 1 || page > state->getDoc()->getNumPages()) {
return 0;
}
updatePageParams();
return pageDPI[page - 1];
}
double TileMap::getPageBoxWidth(int page) {
return pageBoxW[page - 1];
}
double TileMap::getPageBoxHeight(int page) {
return pageBoxH[page - 1];
}
int TileMap::getContinuousPageSpacing() {
return continuousPageSpacing;
}
int TileMap::getSideBySidePageSpacing() {
return sideBySidePageSpacing;
}
int TileMap::getHorizContinuousPageSpacing() {
return horizContinuousPageSpacing;
}
void TileMap::docChanged() {
PDFDoc *doc;
int nPages, pg, rot;
doc = state->getDoc();
if (doc) {
nPages = doc->getNumPages();
} else {
nPages = 0;
}
pageBoxW = (double *)greallocn(pageBoxW, nPages, sizeof(double));
pageBoxH = (double *)greallocn(pageBoxH, nPages, sizeof(double));
for (pg = 1; pg <= nPages; ++pg) {
rot = doc->getPageRotate(pg);
if (rot == 0 || rot == 180) {
pageBoxW[pg - 1] = doc->getPageCropWidth(pg);
pageBoxH[pg - 1] = doc->getPageCropHeight(pg);
} else {
pageBoxW[pg - 1] = doc->getPageCropHeight(pg);
pageBoxH[pg - 1] = doc->getPageCropWidth(pg);
}
}
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::windowSizeChanged() {
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::displayModeChanged() {
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::zoomChanged() {
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::rotateChanged() {
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::scrollPositionChanged() {
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::forceRedraw() {
clearPageParams();
clearContinuousModeParams();
if (tiles) {
deleteGList(tiles, PlacedTileDesc);
tiles = NULL;
}
}
void TileMap::clearPageParams() {
gfree(pageDPI);
gfree(pageW);
gfree(pageH);
gfree(tileW);
gfree(tileH);
pageDPI = NULL;
pageW = pageH = NULL;
tileW = tileH = NULL;
}
void TileMap::updatePageParams() {
double rotPageBoxW, rotPageBoxW2, rotPageBoxH, rotPageBoxH2, rotPageBoxHMax;
double hDPI, vDPI, dpi;
int page, otherPage, nxTiles, nyTiles;
//--- check to see if the continuous mode params have already been updated
if (pageDPI) {
return;
}
//--- allocate memory
pageDPI = (double *)gmallocn(state->getDoc()->getNumPages(), sizeof(double));
pageW = (int *)gmallocn(state->getDoc()->getNumPages(), sizeof(int));
pageH = (int *)gmallocn(state->getDoc()->getNumPages(), sizeof(int));
tileW = (int *)gmallocn(state->getDoc()->getNumPages(), sizeof(int));
tileH = (int *)gmallocn(state->getDoc()->getNumPages(), sizeof(int));
for (page = 1; page <= state->getDoc()->getNumPages(); ++page) {
//--- special handling for side-by-side modes
if (state->displayModeIsSideBySide()) {
// rotate the page boxes
if (page & 1) {
otherPage = page + 1;
if (otherPage >= state->getDoc()->getNumPages()) {
otherPage = page;
}
} else {
otherPage = page - 1;
if (otherPage < 1) {
otherPage = page;
}
}
if (state->getRotate() == 0 || state->getRotate() == 180) {
rotPageBoxW = pageBoxW[page - 1];
rotPageBoxW2 = pageBoxW[otherPage - 1];
rotPageBoxH = pageBoxH[page - 1];
rotPageBoxH2 = pageBoxH[otherPage - 1];
} else {
rotPageBoxW = pageBoxH[page - 1];
rotPageBoxW2 = pageBoxH[otherPage - 1];
rotPageBoxH = pageBoxW[page - 1];
rotPageBoxH2 = pageBoxW[otherPage - 1];
}
rotPageBoxHMax = (rotPageBoxH > rotPageBoxH2) ? rotPageBoxH
: rotPageBoxH2;
// compute resolution
if (state->getZoom() == zoomPage) {
hDPI = ((state->getWinW() - sideBySidePageSpacing) /
(rotPageBoxW + rotPageBoxW2)) * 72.0;
vDPI = (state->getWinH() / rotPageBoxHMax) * 72.0;
dpi = hDPI < vDPI ? hDPI : vDPI;
// allow for some floating point jitter
dpi -= 0.01;
} else if (state->getZoom() == zoomWidth) {
dpi = ((state->getWinW() - sideBySidePageSpacing) /
(rotPageBoxW + rotPageBoxW2)) * 72.0;
// allow for some floating point jitter
dpi -= 0.01;
} else if (state->getZoom() == zoomHeight) {
dpi = (state->getWinH() / rotPageBoxHMax) * 72.0;
// allow for some floating point jitter
dpi -= 0.01;
} else {
dpi = 0.01 * state->getZoom() * 72.0;
}
//--- all other (non-side-by-side) modes
} else {
// rotate the page boxes
if (state->getRotate() == 0 || state->getRotate() == 180) {
rotPageBoxW = pageBoxW[page - 1];
rotPageBoxH = pageBoxH[page - 1];
} else {
rotPageBoxW = pageBoxH[page - 1];
rotPageBoxH = pageBoxW[page - 1];
}
// compute resolution
if (state->getZoom() == zoomPage) {
hDPI = (state->getWinW() / rotPageBoxW) * 72.0;
vDPI = (state->getWinH() / rotPageBoxH) * 72.0;
dpi = hDPI < vDPI ? hDPI : vDPI;
// allow for some floating point jitter
dpi -= 0.01;
} else if (state->getZoom() == zoomWidth) {
dpi = (state->getWinW() / rotPageBoxW) * 72.0;
// allow for some floating point jitter
dpi -= 0.01;
} else if (state->getZoom() == zoomHeight) {
dpi = (state->getWinH() / rotPageBoxH) * 72.0;
// allow for some floating point jitter
dpi -= 0.01;
} else {
dpi = 0.01 * state->getZoom() * 72.0;
}
}
pageDPI[page - 1] = dpi;
// compute bitmap size
pageW[page - 1] = (int)((rotPageBoxW * dpi / 72.0) + 0.5);
if (pageW[page - 1] < 1) {
pageW[page - 1] = 1;
}
pageH[page - 1] = (int)((rotPageBoxH * dpi / 72.0) + 0.5);
if (pageH[page - 1] < 1) {
pageH[page - 1] = 1;
}
// compute tile size
// (tile width and height are rounded up -- the bottom and right
// tiles may be slightly smaller than the computed size)
if (pageW[page - 1] <= state->getMaxTileWidth()) {
nxTiles = 1;
tileW[page - 1] = pageW[page - 1];
} else {
nxTiles = (pageW[page - 1] + state->getMaxTileWidth() - 1)
/ state->getMaxTileWidth();
tileW[page - 1] = (pageW[page - 1] + nxTiles - 1) / nxTiles;
}
if (pageH[page - 1] <= state->getMaxTileHeight()) {
nyTiles = 1;
tileH[page - 1] = pageH[page - 1];
} else {
nyTiles = (pageH[page - 1] + state->getMaxTileHeight() - 1)
/ state->getMaxTileHeight();
tileH[page - 1] = (pageH[page - 1] + nyTiles - 1) / nyTiles;
}
}
}
void TileMap::clearContinuousModeParams() {
gfree(pageX);
pageX = pageY = NULL;
}
void TileMap::updateContinuousModeParams() {
int page, pageW1, pageH1, pageW2, pageH2, x, y;
// check to see if the continuous mode params have already been updated
if (pageX) {
return;
}
updatePageParams();
switch (state->getDisplayMode()) {
case displayContinuous:
if (!pageX) {
pageX = pageY = (int *)gmallocn(state->getDoc()->getNumPages(),
sizeof(int));
}
y = 0;
maxW = 0;
for (page = 1; page <= state->getDoc()->getNumPages(); ++page) {
pageY[page - 1] = y;
y += pageH[page - 1] + continuousPageSpacing;
if (page == 1 || pageW[page - 1] > maxW) {
maxW = pageW[page - 1];
}
}
totalH = y - continuousPageSpacing;
break;
case displaySideBySideContinuous:
if (!pageX) {
pageX = pageY = (int *)gmallocn(state->getDoc()->getNumPages(),
sizeof(int));
}
y = 0;
maxW = maxW2 = 0;
for (page = 1; page <= state->getDoc()->getNumPages(); page += 2) {
pageW1 = pageW[page - 1];
pageH1 = pageH[page - 1];
if (page + 1 <= state->getDoc()->getNumPages()) {
pageW2 = pageW[page];
pageH2 = pageH[page];
} else {
pageW2 = pageW1;
pageH2 = pageH1;
}
pageY[page - 1] = y;
if (page == 1 || pageW1 > maxW) {
maxW = pageW1;
}
if (page + 1 <= state->getDoc()->getNumPages()) {
pageY[page] = y;
}
if (pageW2 > maxW2) {
maxW2 = pageW2;
}
y += (pageH1 > pageH2) ? pageH1 : pageH2;
y += continuousPageSpacing;
}
totalH = y - continuousPageSpacing;
break;
case displayHorizontalContinuous:
if (!pageX) {
pageX = pageY = (int *)gmallocn(state->getDoc()->getNumPages(),
sizeof(int));
}
x = 0;
maxH = 0;
for (page = 1; page <= state->getDoc()->getNumPages(); ++page) {
pageX[page - 1] = x;
x += pageW[page - 1] + horizContinuousPageSpacing;
if (page == 1 || pageH[page - 1] > maxH) {
maxH = pageH[page - 1];
}
}
totalW = x - horizContinuousPageSpacing;
break;
default:
break;
}
}
void TileMap::computePageMatrix(int page, double *m) {
PDFRectangle *cropBox;
double px1, py1, px2, py2, k;
int rotate;
updatePageParams();
cropBox = state->getDoc()->getCatalog()->getPage(page)->getCropBox();
px1 = cropBox->x1;
py1 = cropBox->y1;
px2 = cropBox->x2;
py2 = cropBox->y2;
k = pageDPI[page - 1] / 72.0;
rotate = state->getRotate() +
state->getDoc()->getCatalog()->getPage(page)->getRotate();
if (rotate > 360) {
rotate -= 360;
}
switch (rotate) {
case 0:
default:
m[0] = k;
m[1] = 0;
m[2] = 0;
m[3] = -k;
m[4] = -k * px1;
m[5] = k * py2;
break;
case 90:
m[0] = 0;
m[1] = k;
m[2] = k;
m[3] = 0;
m[4] = -k * py1;
m[5] = -k * px1;
break;
case 180:
m[0] = -k;
m[1] = 0;
m[2] = 0;
m[3] = k;
m[4] = k * px2;
m[5] = -k * py1;
break;
case 270:
m[0] = 0;
m[1] = -k;
m[2] = -k;
m[3] = 0;
m[4] = k * py2;
m[5] = k * px2;
break;
}
}
void TileMap::invertMatrix(double *m, double *im) {
double det;
det = 1 / (m[0] * m[3] - m[1] * m[2]);
im[0] = m[3] * det;
im[1] = -m[1] * det;
im[2] = -m[2] * det;
im[3] = m[0] * det;
im[4] = (m[2] * m[5] - m[3] * m[4]) * det;
im[5] = (m[1] * m[4] - m[0] * m[5]) * det;
}
int TileMap::findContinuousPage(int y) {
int a, b, m;
if (y < pageY[0]) {
return 0;
}
if (y >= totalH) {
return state->getDoc()->getNumPages() + 1;
}
a = -1;
b = state->getDoc()->getNumPages();
// invariant: pageY[a] < y < pageY[b]
while (b - a > 1) {
m = (a + b) / 2;
if (y > pageY[m] - continuousPageSpacing) {
a = m;
} else if (y < pageY[m] - continuousPageSpacing) {
b = m;
} else {
return m + 1;
}
}
return a + 1;
}
int TileMap::findSideBySideContinuousPage(int y) {
int a, b, m;
if (y < pageY[0]) {
return 0;
}
if (y >= totalH) {
return (state->getDoc()->getNumPages() + 2) & ~1;
}
a = -2;
b = (state->getDoc()->getNumPages() + 1) & ~1;
// invariant: pageY[a] < y < pageY[b]
while (b - a > 2) {
m = ((a + b) / 2) & ~1;
if (y > pageY[m] - continuousPageSpacing) {
a = m;
} else if (y < pageY[m] - continuousPageSpacing) {
b = m;
} else {
return m + 1;
}
}
return a + 1;
}
int TileMap::findHorizContinuousPage(int x) {
int a, b, m;
if (x < pageX[0]) {
return 0;
}
if (x >= totalW) {
return state->getDoc()->getNumPages() + 1;
}
a = -1;
b = state->getDoc()->getNumPages();
// invariant: pageX[a] < x < pageX[b]
while (b - a > 1) {
m = (a + b) / 2;
if (x > pageX[m] - horizContinuousPageSpacing) {
a = m;
} else if (x < pageX[m] - horizContinuousPageSpacing) {
b = m;
} else {
return m + 1;
}
}
return a + 1;
}
| 26.505618 | 80 | 0.555142 | haephrati |
d1a98a953358cb46afc8910fa6c15d3b19d71edd | 580 | hpp | C++ | include/LegacyForwardIterator.hpp | jharmer95/cpp_named_concepts | 6cf81562f893b03baf365d5a9dc8b3f0f828fd1a | [
"CC0-1.0"
] | null | null | null | include/LegacyForwardIterator.hpp | jharmer95/cpp_named_concepts | 6cf81562f893b03baf365d5a9dc8b3f0f828fd1a | [
"CC0-1.0"
] | null | null | null | include/LegacyForwardIterator.hpp | jharmer95/cpp_named_concepts | 6cf81562f893b03baf365d5a9dc8b3f0f828fd1a | [
"CC0-1.0"
] | null | null | null | #pragma once
#include "LegacyInputIterator.hpp"
#include "DefaultConstructible.hpp"
#include "LegacyOutputIterator.hpp"
#include <concepts>
#include <iterator>
namespace concepts
{
template<typename It>
concept LegacyForwardIterator = requires(It i)
{
requires !LegacyOutputIterator<It>
|| (LegacyOutputIterator<It> && std::same_as<typename std::iterator_traits<It>::value_type&, typename std::iterator_traits<It>::reference>);
{ i++ } -> std::same_as<It>;
{ *i++ } -> std::same_as<typename std::iterator_traits<It>::reference>;
};
} // namespace concepts
| 26.363636 | 148 | 0.72069 | jharmer95 |
d1ab7935225b9144683e4cc016362bd67187522a | 3,409 | cpp | C++ | src/nec/datamanager.cpp | krikienoid/nectarispcmapeditor | f51cb89c2550a2ec17fa0d75d2741f1106ee5dd9 | [
"MIT"
] | null | null | null | src/nec/datamanager.cpp | krikienoid/nectarispcmapeditor | f51cb89c2550a2ec17fa0d75d2741f1106ee5dd9 | [
"MIT"
] | null | null | null | src/nec/datamanager.cpp | krikienoid/nectarispcmapeditor | f51cb89c2550a2ec17fa0d75d2741f1106ee5dd9 | [
"MIT"
] | null | null | null | #include "datamanager.h"
namespace Nec {
const std::string DataManager::FILENAME_BIGINFO = "biginfo.bin";
const std::string DataManager::FILENAME_BIGUNIT = "bigunit.bin";
const std::string DataManager::FILENAME_BIGMAP = "bigmap.bin";
DataManager::DataManager() {
bigInfo = new BigInfo();
// bigUnit = new BigUnit();
bigMap = new BigMap(bigInfo);
}
DataManager::~DataManager() {
delete bigInfo;
delete bigMap;
}
void DataManager::read(const std::string& filepath) {
// Assume working directory by default
std::string filedir = "";
std::string filename = filepath;
// If directory is given
const auto slashPos = filepath.find_last_of("/\\");
if (slashPos != std::string::npos) {
filedir = filepath.substr(0, slashPos + 1);
filename = filepath.substr(slashPos + 1);
}
// Check file name
std::transform(
filename.begin(),
filename.end(),
filename.begin(),
::tolower
);
if (
filename == FILENAME_BIGINFO ||
filename == FILENAME_BIGUNIT ||
filename == FILENAME_BIGMAP
) {
constexpr auto fileReadMode = std::ios::in | std::ios::binary;
// Open files for reading
std::ifstream bigInfoBin;
std::ifstream bigUnitBin;
std::ifstream bigMapBin;
bigInfoBin.open(filedir + FILENAME_BIGINFO, fileReadMode);
bigUnitBin.open(filedir + FILENAME_BIGUNIT, fileReadMode);
bigMapBin.open(filedir + FILENAME_BIGMAP, fileReadMode);
// Read Data
if (bigInfoBin.good() && bigUnitBin.good() && bigMapBin.good()) {
// biginfo.bin must be read first
bigInfo->read(bigInfoBin);
// bigmap.bin
bigMap->read(bigMapBin);
}
// Close Files
bigInfoBin.close();
bigUnitBin.close();
bigMapBin.close();
}
}
void DataManager::write(const std::string& filepath) {
// Assume working directory by default
std::string filedir = "";
std::string filename = filepath;
// If directory is given
const auto slashPos = filepath.find_last_of("/\\");
if (slashPos != std::string::npos) {
filedir = filepath.substr(0, slashPos + 1);
filename = filepath.substr(slashPos + 1);
}
// Check file name
std::transform(
filename.begin(),
filename.end(),
filename.begin(),
::tolower
);
if (
filename == FILENAME_BIGINFO ||
filename == FILENAME_BIGUNIT ||
filename == FILENAME_BIGMAP
) {
constexpr auto fileWriteMode = std::ios::out | std::ios::binary;
// Open files for writing
std::ofstream bigInfoBin;
std::ofstream bigUnitBin;
std::ofstream bigMapBin;
bigInfoBin.open(filedir + FILENAME_BIGINFO, fileWriteMode);
// bigUnitBin.open(filedir + FILENAME_BIGUNIT, fileWriteMode);
bigMapBin.open(filedir + FILENAME_BIGMAP, fileWriteMode);
if (bigInfoBin.good() && bigUnitBin.good() && bigMapBin.good()) {
// bigmap.bin
bigMap->write(bigMapBin);
// biginfo.bin must be written last
bigInfo->write(bigInfoBin);
}
// Close Files
bigInfoBin.close();
bigUnitBin.close();
bigMapBin.close();
}
}
} // namespace Nec
| 27.055556 | 78 | 0.589909 | krikienoid |
d1b1c496a22b266da0710e4fe0d40c67a03c01aa | 5,805 | cpp | C++ | QtKnobs/styles/piestyle.cpp | eyecreate/QtKnobs | 242643bab6c38d8acbee1101edb83bb10f332bb6 | [
"MIT"
] | 68 | 2015-03-15T01:25:22.000Z | 2022-03-25T11:27:55.000Z | QtKnobs/styles/piestyle.cpp | darongE/QtKnobs | 0395e265fdc06bd70debe68e904d2ef6acb90bce | [
"MIT"
] | 9 | 2015-03-12T14:40:28.000Z | 2018-12-10T04:15:30.000Z | QtKnobs/styles/piestyle.cpp | darongE/QtKnobs | 0395e265fdc06bd70debe68e904d2ef6acb90bce | [
"MIT"
] | 23 | 2015-03-16T14:33:46.000Z | 2021-12-22T06:06:53.000Z | /*************************************************************************************
** The MIT License (MIT)
**
** Knobs is a free Qt and QML based widget.
** Copyright (c) 2015 Ashish Dabhade
** Email: [email protected]
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
************************************************************************************/
#include "piestyle.h"
#define M_180_D_PI 180/M_PI
#define M_PI_D_180 M_PI/180
PieStyle::PieStyle(QQuickItem *parent) :
QQuickPaintedItem(parent),
m_value(0),
m_minValue(0),
m_maxValue(100),
m_percent(0),
m_readOnly(false),
m_color(QColor(135,206,235)),
m_mode(PieStyle::Normal),
m_style(PieStyle::Flat),
m_multiColor(false),
m_factor(57.6),
m_scale(16 / m_factor),
m_startAngle((m_value * m_factor) + (1440)),
m_spanAngle(0)
{
setAntialiasing(true);
#if defined Q_OS_LINUX || defined Q_OS_MAC
setRenderTarget(QQuickPaintedItem::FramebufferObject);
#endif
}
void PieStyle::paint(QPainter *painter)
{
qreal w = (width()/3.0)-1.0;
static const qreal m = 1.5;
painter->setPen(Qt::NoPen);
if(m_style==PieStyle::Flat) {
if(!m_multiColor) {
painter->setBrush(m_color);
painter->drawPie(boundingRect().marginsRemoved(QMarginsF(m,m,m,m)), m_startAngle, -m_spanAngle);
} else {
qreal parts = m_spanAngle/1440 + 1;
for(int i=0;i<parts;i++)
{
switch(i)
{
case 0:
m_startAngle = 1440;
painter->setBrush(m_chunkColors[i]);
break;
case 1:
case 2:
case 3:
m_startAngle = m_startAngle - 1440;
m_spanAngle = m_spanAngle - 1440;
painter->setBrush(m_chunkColors.at(i));
break;
}
painter->drawPie(boundingRect().marginsRemoved(QMarginsF(m,m,m,m)), m_startAngle, -m_spanAngle);
}
}
} else {
if(m_value==0)
return;
qreal w = width();
qreal h = height();
qreal a = ((m_spanAngle/16.0)-90.0)*M_PI_D_180;
qreal d = qCeil((w-w/1.2)/2.0)+1.0;
qreal x = w/2.0+(w/2.0-d)*qCos(a);
qreal y = h/2.0+(h/2.0-d)*qSin(a);
painter->setBrush(m_color);
painter->drawPie(boundingRect().marginsRemoved(QMarginsF(m,m,m,m)), m_startAngle, -m_spanAngle);
painter->drawEllipse(QPointF(w/2.0,d),d-2.0,d-2.0);
painter->drawEllipse(QPointF(x,y),d-2.0,d-2.0);
}
painter->setBrush(Qt::white);
painter->drawEllipse(boundingRect().center(),w,w);
}
int PieStyle::endValueFromPoint(qreal x, qreal y)
{
qreal theta = qAtan2(x,-y);
qreal angle = fmod((theta * M_180_D_PI) + 360.0,360.0);
int v = qCeil(angle * m_scale) + m_minValue;
return m_mode==PieStyle::Percent ? (v-m_minValue)*100/(m_maxValue-m_minValue) : v;
}
void PieStyle::classBegin()
{}
void PieStyle::componentComplete()
{
m_anim = children().first()->children().first();
}
bool PieStyle::animationRunning()
{
return m_anim->property("running").toBool();
}
void PieStyle::setValue(int arg)
{
if (m_value == arg)
return;
m_value = arg;
if(m_value>m_maxValue)
m_value = m_maxValue;
if(m_value<m_minValue)
m_value = m_minValue;
int diff = (m_value-m_minValue);
m_spanAngle = diff * m_factor;
m_percent = diff*100/(m_maxValue-m_minValue);
if(m_mode == PieStyle::Normal) {
emit percentChanged(m_percent);
emit valueChanged(m_value);
} else {
emit valueChanged(m_value);
emit percentChanged(m_percent);
}
update();
}
void PieStyle::setMinValue(int arg)
{
if (m_minValue == arg)
return;
m_minValue = arg;
m_value = m_minValue;
emit minValueChanged(arg);
}
void PieStyle::setMaxValue(int arg)
{
m_maxValue = arg;
m_factor = (360.0/(m_maxValue-m_minValue)) * 16.0;
m_scale = 16.0 / m_factor;
if (m_maxValue == arg)
return;
emit maxValueChanged(arg);
}
void PieStyle::setPercent(int arg)
{
if (m_percent == arg)
return;
m_percent = arg;
int value = qCeil(m_percent*(m_maxValue-m_minValue)/100.0) + m_minValue;
setValue(value);
}
void PieStyle::setMultiColor(bool arg)
{
if (m_multiColor != arg) {
m_multiColor = arg;
if(m_multiColor)
m_chunkColors << QColor(197,81,134)
<< QColor(232,156,132)
<< QColor(254,197,107)
<< QColor(81,197,212);
emit multiColorChanged(arg);
}
}
| 29.92268 | 112 | 0.591214 | eyecreate |
d1b36490f57fd3b7f85237d450662d9b5fb6add8 | 39,453 | cpp | C++ | qws/src/qtc_x_core.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 42 | 2015-02-16T19:29:16.000Z | 2021-07-25T11:09:03.000Z | qws/src/qtc_x_core.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 1 | 2017-11-23T12:49:25.000Z | 2017-11-23T12:49:25.000Z | qws/src/qtc_x_core.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 5 | 2015-10-15T21:25:30.000Z | 2017-11-22T13:18:24.000Z | /////////////////////////////////////////////////////////////////////////////
//
// File : qtc_x_core.cpp
// Copyright : (c) David Harley 2010
// Project : qtHaskell
// Version : 1.1.4
// Modified : 2010-09-02 17:01:54
//
// Warning : this file is machine generated - do not modify.
//
/////////////////////////////////////////////////////////////////////////////
#include <wchar.h>
#include <qtc_wrp_core.h>
#include <qtc_subclass.h>
#include <dynamicqobject.h>
#include <QMutex>
extern "C"
{
QTCEXPORT(void*,qtc_QObject)(void *x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
qtc_DynamicQObject*tr = new qtc_DynamicQObject(tx0);
QPointer<qtc_DynamicQObject> * ttr = new QPointer<qtc_DynamicQObject>(tr);
return (void *) ttr;
}
QTCEXPORT(void,qtc_QObject_finalizer)(void* x0) {
delete ((QPointer<qtc_DynamicQObject>*)x0);
}
QTCEXPORT(void*,qtc_QObject_getFinalizer)() {
return (void*)(&qtc_QObject_finalizer);
}
QTCEXPORT(void,qtc_QObject_delete)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
delete ((qtc_DynamicQObject*)tx0);
}
QTCEXPORT(void*,qtc_QObject_parent)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject * tr = ((QObject*)tx0)->parent();
QPointer<QObject> * ttr = new QPointer<QObject>(tr);
return (void *) ttr;
}
QTCEXPORT(void*,qtc_QObject_parentSc)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
QObject * tr = ((QObject*)tx0)->parent();
QPointer<QObject> * ttr = new QPointer<QObject>(tr);
return (void *) ttr;
}
QTCEXPORT(void*,qtc_QObject_parentref)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject * tr = ((QObject*)tx0)->parent();
QPointer<QObject> * ttr = new QPointer<QObject>(tr);
return (void *) ttr;
}
QTCEXPORT(void,qtc_QObject_setParent)(void* x0, void* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject*tx1 = *((QPointer<QObject>*)x1);
if (((QObject*)tx1)->property(QTC_PROP).isValid()) tx1 = (((qtc_DynamicQObject *)tx1)->parent());
((QObject*)tx0)->setParent((QObject*)tx1);
}
QTCEXPORT(void*,qtc_QObject_property)(void* x0, wchar_t* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QString tx1(from_method(x1));
QByteArray txa1(tx1.toAscii());
QVariant*tr = new QVariant(((QObject*)tx0)->property(txa1.data()));
return (void*) tr;
}
QTCEXPORT(int,qtc_QObject_setProperty)(void* x0, wchar_t* x1, void* x2) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QString tx1(from_method(x1));
QByteArray txa1(tx1.toAscii());
return (int) ((QObject*)tx0)->setProperty(txa1.data(), (const QVariant&)(*(QVariant*)x2));
}
QTCEXPORT(int,qtc_QObject_blockSignals)(void* x0, int x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
bool tb = ((QObject*)tx0)->blockSignals(((bool)x1));
if (((QObject*)tx0)->property(QTC_PROP).isValid()) {
tx0 = (((qtc_DynamicQObject *)tx0)->parent());
tb |= ((QObject*)tx0)->blockSignals(((bool)x1));
}
return (int) tb;
}
QTCEXPORT(int,qtc_QObject_signalsBlocked)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
bool tb = ((QObject*)tx0)->signalsBlocked();
if (((QObject*)tx0)->property(QTC_PROP).isValid()) {
tx0 = (((qtc_DynamicQObject *)tx0)->parent());
tb |= ((QObject*)tx0)->signalsBlocked();
}
return (int) tb;
}
QTCEXPORT(void,qtc_QObject_installEventFilter)(void* x0, void* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject*tx1 = *((QPointer<QObject>*)x1);
if (((QObject*)tx1)->property(QTC_PROP).isValid()) tx1 = (((qtc_DynamicQObject *)tx0)->parent());
((QObject*)tx0)->installEventFilter((QObject*)tx1);
}
QTCEXPORT(void,qtc_QObject_removeEventFilter)(void* x0, void* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject*tx1 = *((QPointer<QObject>*)x1);
if (((QObject*)tx1)->property(QTC_PROP).isValid()) tx1 = (((qtc_DynamicQObject *)tx0)->parent());
((QObject*)tx0)->removeEventFilter((QObject*)tx1);
}
QTCEXPORT(int,qtc_QObject_isWidgetType)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
return (int) ((QObject*)tx0)->isWidgetType();
}
QTCEXPORT(void,qtc_QObject_killTimer)(void* x0, int x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
((QObject*)tx0)->killTimer(x1);
}
QTCEXPORT(int,qtc_QObject_startTimer)(void* x0, int x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
return ((QObject*)tx0)->startTimer(x1);
}
QTCEXPORT (int,qtc_QObject_pa_eq) (void* x0, void* x1)
{
QObject*tx0 = *((QPointer<QObject>*)x0);
QObject*tx1 = *((QPointer<QObject>*)x1);
bool ltc = tx0 == tx1 ? true : false;
return (int) ltc;
}
QTCEXPORT (int,qtc_QObject_pa_oeq) (void* x0, void* x1)
{
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QObject*tx1 = *((QPointer<QObject>*)x1);
if (((QObject*)tx1)->property(QTC_PROP).isValid()) tx1 = (((qtc_DynamicQObject *)tx1)->parent());
bool ltc = tx0 == tx1 ? true : false;
return (int) ltc;
}
QTCEXPORT (int,qtc_QObject_pa_lt) (void* x0, void* x1)
{
QObject*tx0 = *((QPointer<QObject>*)x0);
QObject*tx1 = *((QPointer<QObject>*)x1);
bool ltc = tx0 < tx1 ? true : false;
return (int) ltc;
}
QTCEXPORT (int,qtc_QObject_children) (void* x0, void* _ref)
{
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
QList<QObject *> tql = ((QObject*)tx0)->children();
if (_ref != NULL) {
for (int i = 0; i < tql.size(); i++) {
QPointer<QObject> * ttr = new QPointer<QObject>(tql.at(i));
((void**)_ref)[i] = (void*)ttr;
}
}
return tql.size();
}
QTCEXPORT(int,qtc_QString_GetString)(void* x0, wchar_t* x1) {
if (x1) {
((QString*)x0)->toWCharArray(x1);
}
return ((QByteArray*)x0)->length();
}
QTCEXPORT(void,qtc_QString_Delete)(void* x0) {
delete (QString*)x0;
}
QTCEXPORT(void*,qtc_QByteArray)() {
QByteArray*tba = new QByteArray();
return (void*) tba;
}
QTCEXPORT(int,qtc_QByteArray_isEmpty)(void* x0) {
return (int) ((QByteArray*)x0)->isEmpty();
}
QTCEXPORT(int,qtc_QByteArray_GetByteArray)(void* x0, char* x1) {
if (x1) {
char * tqba_data = ((QByteArray*)x0)->data();
for (int i = 0; i < ((QByteArray*)x0)->length(); i++) {
x1[i] = tqba_data[i];
}
}
return ((QByteArray*)x0)->length();
}
QTCEXPORT(void,qtc_QByteArray_finalizer)(void* x0) {
delete ((QByteArray*)x0);
}
QTCEXPORT(void*,qtc_QByteArray_getFinalizer)() {
return (void*)(&qtc_QByteArray_finalizer);
}
QTCEXPORT(void,qtc_QByteArray_Delete)(void* x0) {
delete (QByteArray*)x0;
}
QTCEXPORT(void*,qtc_QObject_metaObject)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
if (((QObject*)tx0)->property(QTC_PROP).isValid()) tx0 = (((qtc_DynamicQObject *)tx0)->parent());
return (void*) ((QObject*)tx0)->metaObject();
}
QTCEXPORT(int,qtc_QObject_inherits)(void* x0, wchar_t* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
QString tx1(from_method(x1));
QByteArray txa1(tx1.toAscii());
return (int) ((QObject*)tx0)->inherits(txa1.data());
}
QTCEXPORT(void*,qtc_QObject_objectName)(void* x0) {
QObject*tx0 = *((QPointer<QObject>*)x0);
QString * tq = new QString(((QObject*)tx0)->objectName());
return (void*)(tq);
}
QTCEXPORT(void,qtc_QObject_setObjectName)(void* x0, wchar_t* x1) {
QObject*tx0 = *((QPointer<QObject>*)x0);
return ((QObject*)tx0)->setObjectName(from_method(x1));
}
QTCEXPORT(void,qtc_connectSlot_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ, void* rf_ptr, void* st_ptr) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QPointer<QObject> * ttslt_obj = new QPointer<QObject>(tslt_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, rf_ptr, st_ptr, (void*)ttslt_obj);
}
QTCEXPORT(void,qtc_connectSlot)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, void* rf_ptr, void* st_ptr) {
qtc_connectSlot_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection, rf_ptr, st_ptr);
}
QTCEXPORT(void,qtc_connectSlot_int_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ, void* rf_ptr, void* stptr) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QPointer<QObject> * ttslt_obj = new QPointer<QObject>(tslt_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, rf_ptr, stptr, (void*)ttslt_obj);
}
QTCEXPORT(void,qtc_connectSlot_int)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, void* rf_ptr, void* st_ptr) {
qtc_connectSlot_int_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection, rf_ptr, st_ptr);
}
QTCEXPORT(void,qtc_connectSlot_bool_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ, void* rf_ptr, void* stptr) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QPointer<QObject> * ttslt_obj = new QPointer<QObject>(tslt_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, rf_ptr, stptr, (void*)ttslt_obj);
}
QTCEXPORT(void,qtc_connectSlot_bool)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, void* rf_ptr, void* st_ptr) {
qtc_connectSlot_bool_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection, rf_ptr, st_ptr);
}
QTCEXPORT(void,qtc_connectSlot_ptr_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ, void* rf_ptr, void* stptr) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QPointer<QObject> * ttslt_obj = new QPointer<QObject>(tslt_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, rf_ptr, stptr, (void*)ttslt_obj);
}
QTCEXPORT(void,qtc_connectSlot_ptr)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, void* rf_ptr, void* st_ptr) {
qtc_connectSlot_ptr_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection, rf_ptr, st_ptr);
}
QTCEXPORT(void,qtc_connectSlot_str_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ, void* rf_ptr, void* stptr) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QPointer<QObject> * ttslt_obj = new QPointer<QObject>(tslt_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, rf_ptr, stptr, (void*)ttslt_obj);
}
QTCEXPORT(void,qtc_connectSlot_str)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, void* rf_ptr, void* st_ptr) {
qtc_connectSlot_str_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection, rf_ptr, st_ptr);
}
QTCEXPORT(void,qtc_connectSlot_public_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tslt_obj)->connectDynamicSlot((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data(), (Qt::ConnectionType)con_typ, NULL, NULL, NULL);
}
QTCEXPORT(void,qtc_connectSlot_public)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ) {
qtc_connectSlot_public_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection);
}
QTCEXPORT(void,qtc_connectSignal_m)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ, long con_typ) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
((qtc_DynamicQObject*)tsig_obj)->connectDynamicSignal(tqba_sig.data(), (qtc_DynamicQObject *)tslt_obj, tqba_slt.data(), (Qt::ConnectionType)con_typ);
}
QTCEXPORT(void,qtc_connectSignal)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ) {
qtc_connectSignal_m(sig_obj, sig_typ, slt_obj, slt_typ, Qt::AutoConnection);
}
QTCEXPORT(void,qtc_emitSignal_nll)(void* sig_obj, wchar_t* sig_typ) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
void * tvpp[1];
((qtc_DynamicQObject*)tsig_obj)->emitDynamicSignal(tqba_sig.data(), tvpp);
}
QTCEXPORT(void,qtc_emitSignal_int)(void* sig_obj, wchar_t* sig_typ, int val) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
void * tvpp[2];
tvpp[1] = (void*)(&val);
((qtc_DynamicQObject*)tsig_obj)->emitDynamicSignal(tqba_sig.data(), tvpp);
}
QTCEXPORT(void,qtc_emitSignal_bool)(void* sig_obj, wchar_t* sig_typ, int val) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
void * tvpp[2];
tvpp[1] = (void*)(&val);
((qtc_DynamicQObject*)tsig_obj)->emitDynamicSignal(tqba_sig.data(), tvpp);
}
QTCEXPORT(void,qtc_emitSignal_str)(void* sig_obj, wchar_t* sig_typ, wchar_t* val) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_val(from_method(val));
QByteArray tqba_val(tq_val.toAscii());
void * tvpp[2];
tvpp[1] = (void*)(&tq_val);
((qtc_DynamicQObject*)tsig_obj)->emitDynamicSignal(tqba_sig.data(), tvpp);
}
QTCEXPORT (void,qtc_emitSignal_ptr)(void* sig_obj, wchar_t* sig_typ, void* sig_ptr) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
void * tvpp[2];
if (!tqba_sig.endsWith("*)")) {
tvpp[1] = sig_ptr;
} else {
tvpp[1] = (void *) (&sig_ptr);
}
((qtc_DynamicQObject*)tsig_obj)->emitDynamicSignal(tqba_sig.data(), tvpp);
}
QTCEXPORT(int,qtc_disconnectSlot_sos)(void* sig_obj, wchar_t* sig_typ, void* slt_obj, wchar_t* slt_typ) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
QString tq_slt(from_method(slt_typ));
QByteArray tqba_slt(tq_slt.toAscii());
return (int) ((qtc_DynamicQObject*)tslt_obj)->disconnectDynamicSlot_sos((qtc_DynamicQObject*)tsig_obj, tqba_sig.data(), tqba_slt.data());
}
QTCEXPORT(int,qtc_disconnectSlot_so)(void* sig_obj, wchar_t* sig_typ, void* slt_obj) {
QObject*tslt_obj = *((QPointer<QObject>*)slt_obj);
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
return (int) ((qtc_DynamicQObject*)tslt_obj)->disconnectDynamicSlot_so((qtc_DynamicQObject*)tsig_obj, tqba_sig.data());
}
QTCEXPORT(int,qtc_disconnectSlot_s)(void* sig_obj, wchar_t* sig_typ) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
QString tq_sig(from_method(sig_typ));
QByteArray tqba_sig(tq_sig.toAscii());
return (int) ((qtc_DynamicQObject*)tsig_obj)->disconnectDynamicSlot_s(tqba_sig.data());
}
QTCEXPORT(int,qtc_disconnectSlot)(void* sig_obj) {
QObject*tsig_obj = *((QPointer<QObject>*)sig_obj);
return (int) ((qtc_DynamicQObject*)tsig_obj)->disconnectDynamicSlot();
}
QTCEXPORT (void, qtc_freeDynamicSlots)(void * obj) {
((qtc_DynamicQObject *)obj)->freeDynamicSlots();
}
QTCEXPORT(void*,qtc_QResource)() {
return (void*) new QResource();
}
QTCEXPORT(int,qtc_QResource_registerResource)(wchar_t* x1) {
QString tx1(from_method(x1));
QByteArray txa1(tx1.toAscii());
return (int)QResource::registerResource(tx1);
}
QTCEXPORT(int,qtc_QResource_unregisterResource)(wchar_t* x1) {
QString tx1(from_method(x1));
QByteArray txa1(tx1.toAscii());
return (int)QResource::unregisterResource(tx1);
}
QTCEXPORT(void,qtc_qsrand)(int x1) {
qsrand(x1);
}
QTCEXPORT(int,qtc_QObject_isNull)(void* x1) {
QObject*tx1 = *((QPointer<QObject>*)x1);
if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent()));
return (int) (tx1 == NULL);
}
QTCEXPORT(int,qtc_QDataStream_read_qint8)(void* x0) {
qint8 tqi8;
(*(QDataStream*)x0) >> tqi8;
return (int)tqi8;
}
QTCEXPORT(void,qtc_QDataStream_write_qint8)(void* x0, int x1) {
(*(QDataStream*)x0) << (qint8)x1;
}
QTCEXPORT(int,qtc_QDataStream_read_qint32)(void* x0) {
qint32 tqi32;
(*(QDataStream*)x0) >> tqi32;
return (int)tqi32;
}
QTCEXPORT(void,qtc_QDataStream_write_qint32)(void* x0, int x1) {
qint32 tqi32 = (qint32)x1;
(*(QDataStream*)x0) << tqi32;
}
QTCEXPORT(int,qtc_QDataStream_read_bool)(void* x0) {
bool tb;
(*(QDataStream*)x0) >> tb;
return (int)tb;
}
QTCEXPORT(void,qtc_QDataStream_write_bool)(void* x0, int x1) {
(*(QDataStream*)x0) << (bool)x1;
}
QTCEXPORT(void*,qtc_QDataStream_read_str)(void* x0) {
QString tqs;
(*(QDataStream*)x0) >> tqs;
QString * tqr = new QString(tqs);
return (void*) tqr;
}
QTCEXPORT(void,qtc_QDataStream_write_str)(void* x0, wchar_t* x1) {
QString tqs(from_method(x1));
(*(QDataStream*)x0) << tqs;
}
QTCEXPORT(void*,qtc_QDataStream_readRawData)(void* x0, int x1) {
QByteArray * tqba = new QByteArray(x1, '\0');
((QDataStream*)x0)->readRawData(tqba->data(), x1);
return (void*)(tqba);
}
QTCEXPORT(void*,qtc_QPolygonList)(int _len0, void* x0) {
QVector<QPoint> tqa1;
for (int tqai = 0; tqai < _len0; tqai+=2) {
QPoint tqp(((int*)x0)[tqai], ((int*)x0)[tqai + 1]);
tqa1.append(tqp);
}
QPolygon*tr = new QPolygon(tqa1);
return (void*) tr;
}
QTCEXPORT(void*,qtc_QPolygonFList)(int _len0, void* x0) {
QVector<QPointF> tqa1;
for (int tqai = 0; tqai < _len0; tqai+=2) {
QPointF tqp(((double*)x0)[tqai], ((double*)x0)[tqai + 1]);
tqa1.append(tqp);
}
QPolygonF*tr = new QPolygonF(tqa1);
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_GlobalColor)(long x0) {
QVariant*tr = new QVariant((Qt::GlobalColor)x0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_GlobalColor)(void* x0, long x1) {
((QVariant*)x0)->setValue<QColor>((Qt::GlobalColor)x1);
}
QTCEXPORT(void*,qtc_QVariantValue_QColor)(void* x0) {
QColor*tr = new QColor(((QVariant*)x0)->value<QColor>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QDate)(void* x0) {
QVariant*tr = new QVariant((const QDate&)(*(QDate*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QDate)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QDate>((const QDate&)(*(QDate*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QDate)(void* x0) {
QDate*tr = new QDate(((QVariant*)x0)->value<QDate>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toDate)(void* x0) {
QDate*tr = new QDate(((QVariant*)x0)->toDate());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QTime)(void* x0) {
QVariant*tr = new QVariant((const QTime&)(*(QTime*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QTime)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QTime>((const QTime&)(*(QTime*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QTime)(void* x0) {
QTime*tr = new QTime(((QVariant*)x0)->value<QTime>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toTime)(void* x0) {
QTime*tr = new QTime(((QVariant*)x0)->toTime());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QDateTime)(void* x0) {
QVariant*tr = new QVariant((const QDateTime&)(*(QDateTime*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QDateTime)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QDateTime>((const QDateTime&)(*(QDateTime*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QDateTime)(void* x0) {
QDateTime*tr = new QDateTime(((QVariant*)x0)->value<QDateTime>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toDateTime)(void* x0) {
QDateTime*tr = new QDateTime(((QVariant*)x0)->toDateTime());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QSize)(void* x0) {
QVariant*tr = new QVariant((const QSize&)(*(QSize*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QSize)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QSize>((const QSize&)(*(QSize*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QSize)(void* x0) {
QSize*tr = new QSize(((QVariant*)x0)->value<QSize>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toSize)(void* x0) {
QSize*tr = new QSize(((QVariant*)x0)->toSize());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QSize_qth)(int x0_w, int x0_h) {
QSize tx0(x0_w, x0_h);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QSize_qth)(void* x0, int x1_w, int x1_h) {
QSize tx1(x1_w, x1_h);
((QVariant*)x0)->setValue<QSize>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QSize_qth)(void* x0, int* _ret_w, int* _ret_h) {
QSize tx0 = ((QVariant*)x0)->value<QSize>();
*_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void,qtc_QVariant_toSize_qth)(void* x0, int* _ret_w, int* _ret_h) {
QSize tx0 = ((QVariant*)x0)->toSize();
*_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void*,qtc_QVariant_QSizeF)(void* x0) {
QVariant*tr = new QVariant((const QSizeF&)(*(QSizeF*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QSizeF)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QSizeF>((const QSizeF&)(*(QSizeF*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QSizeF)(void* x0) {
QSizeF*tr = new QSizeF(((QVariant*)x0)->value<QSizeF>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toSizeF)(void* x0) {
QSizeF*tr = new QSizeF(((QVariant*)x0)->toSizeF());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QSizeF_qth)(double x0_w, double x0_h) {
QSizeF tx0(x0_w, x0_h);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QSizeF_qth)(void* x0, double x1_w, double x1_h) {
QSizeF tx1(x1_w, x1_h);
((QVariant*)x0)->setValue<QSizeF>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QSizeF_qth)(void* x0, double* _ret_w, double* _ret_h) {
QSizeF tx0 = (((QVariant*)x0)->value<QSizeF>());
*_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void,qtc_QVariant_toSizeF_qth)(void* x0, double* _ret_w, double* _ret_h) {
QSizeF tx0 = ((QVariant*)x0)->toSizeF();
*_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void*,qtc_QVariant_QPoint)(void* x0) {
QVariant*tr = new QVariant((const QPoint&)(*(QPoint*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QPoint)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QPoint>((const QPoint&)(*(QPoint*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QPoint)(void* x0) {
QPoint*tr = new QPoint(((QVariant*)x0)->value<QPoint>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toPoint)(void* x0) {
QPoint*tr = new QPoint(((QVariant*)x0)->toPoint());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QPoint_qth)(int x0_x, int x0_y) {
QPoint tx0(x0_x, x0_y);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QPoint_qth)(void* x0, int x1_x, int x1_y) {
QPoint tx1(x1_x, x1_y);
((QVariant*)x0)->setValue<QPoint>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QPoint_qth)(void* x0, int* _ret_x, int* _ret_y) {
QPoint tx0 = (((QVariant*)x0)->value<QPoint>());
*_ret_x = tx0.x(); *_ret_y = tx0.y();
return;
}
QTCEXPORT(void,qtc_QVariant_toPoint_qth)(void* x0, int* _ret_x, int* _ret_y) {
QPoint tx0 = ((QVariant*)x0)->toPoint();
*_ret_x = tx0.x(); *_ret_y = tx0.y();
return;
}
QTCEXPORT(void*,qtc_QVariant_QPointF)(void* x0) {
QVariant*tr = new QVariant((const QPointF&)(*(QPointF*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QPointF)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QPointF>((const QPointF&)(*(QPointF*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QPointF)(void* x0) {
QPointF*tr = new QPointF(((QVariant*)x0)->value<QPointF>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toPointF)(void* x0) {
QPointF*tr = new QPointF(((QVariant*)x0)->toPointF());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QPointF_qth)(double x0_x, double x0_y) {
QPointF tx0(x0_x, x0_y);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QPointF_qth)(void* x0, double x1_x, double x1_y) {
QPointF tx1(x1_x, x1_y);
((QVariant*)x0)->setValue<QPointF>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QPointF_qth)(void* x0, double* _ret_x, double* _ret_y) {
QPointF tx0 = ((QVariant*)x0)->value<QPointF>();
*_ret_x = tx0.x(); *_ret_y = tx0.y();
return;
}
QTCEXPORT(void,qtc_QVariant_toPointF_qth)(void* x0, double* _ret_x, double* _ret_y) {
QPointF tx0 = ((QVariant*)x0)->toPointF();
*_ret_x = tx0.x(); *_ret_y = tx0.y();
return;
}
QTCEXPORT(void*,qtc_QVariant_QLine)(void* x0) {
QVariant*tr = new QVariant((const QLine&)(*(QLine*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QLine)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QLine>((const QLine&)(*(QLine*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QLine)(void* x0) {
QLine*tr = new QLine(((QVariant*)x0)->value<QLine>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toLine)(void* x0) {
QLine*tr = new QLine(((QVariant*)x0)->toLine());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QLine_qth)(int x0_x1, int x0_y1, int x0_x2, int x0_y2) {
QLine tx0(x0_x1, x0_y1, x0_x2, x0_y2);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QLine_qth)(void* x0, int x1_x1, int x1_y1, int x1_x2, int x1_y2) {
QLine tx1(x1_x1, x1_y1, x1_x2, x1_y2);
((QVariant*)x0)->setValue<QLine>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QLine_qth)(void* x0, int* _ret_x1, int* _ret_y1, int* _ret_x2, int* _ret_y2) {
QLine tx0 = ((QVariant*)x0)->value<QLine>();
*_ret_x1 = tx0.x1(); *_ret_y1 = tx0.y1(); *_ret_x2 = tx0.x2(); *_ret_y2 = tx0.y2();
return;
}
QTCEXPORT(void,qtc_QVariant_toLine_qth)(void* x0, int* _ret_x1, int* _ret_y1, int* _ret_x2, int* _ret_y2) {
QLine tx0 = ((QVariant*)x0)->toLine();
*_ret_x1 = tx0.x1(); *_ret_y1 = tx0.y1(); *_ret_x2 = tx0.x2(); *_ret_y2 = tx0.y2();
return;
}
QTCEXPORT(void*,qtc_QVariant_QLineF)(void* x0) {
QVariant*tr = new QVariant((const QLineF&)(*(QLineF*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QLineF)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QLineF>((const QLineF&)(*(QLineF*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QLineF)(void* x0) {
QLineF*tr = new QLineF(((QVariant*)x0)->value<QLineF>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toLineF)(void* x0) {
QLineF*tr = new QLineF(((QVariant*)x0)->toLineF());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QLineF_qth)(double x0_x1, double x0_y1, double x0_x2, double x0_y2) {
QLineF tx0(x0_x1, x0_y1, x0_x2, x0_y2);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QLineF_qth)(void* x0, double x1_x1, double x1_y1, double x1_x2, double x1_y2) {
QLineF tx1(x1_x1, x1_y1, x1_x2, x1_y2);
((QVariant*)x0)->setValue<QLineF>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QLineF_qth)(void* x0, double* _ret_x1, double* _ret_y1, double* _ret_x2, double* _ret_y2) {
QLineF tx0 = ((QVariant*)x0)->value<QLineF>();
*_ret_x1 = tx0.x1(); *_ret_y1 = tx0.y1(); *_ret_x2 = tx0.x2(); *_ret_y2 = tx0.y2();
return;
}
QTCEXPORT(void,qtc_QVariant_toLineF_qth)(void* x0, double* _ret_x1, double* _ret_y1, double* _ret_x2, double* _ret_y2) {
QLineF tx0 = ((QVariant*)x0)->toLineF();
*_ret_x1 = tx0.x1(); *_ret_y1 = tx0.y1(); *_ret_x2 = tx0.x2(); *_ret_y2 = tx0.y2();
return;
}
QTCEXPORT(void*,qtc_QVariant_QRect)(void* x0) {
QVariant*tr = new QVariant((const QRect&)(*(QRect*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QRect)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QRect>((const QRect&)(*(QRect*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QRect)(void* x0) {
QRect*tr = new QRect(((QVariant*)x0)->value<QRect>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toRect)(void* x0) {
QRect*tr = new QRect(((QVariant*)x0)->toRect());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QRect_qth)(int x0_x, int x0_y, int x0_w, int x0_h) {
QRect tx0(x0_x, x0_y, x0_w, x0_h);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QRect_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h) {
QRect tx1(x1_x, x1_y, x1_w, x1_h);
((QVariant*)x0)->setValue<QRect>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QRect_qth)(void* x0, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QRect tx0 = ((QVariant*)x0)->value<QRect>();
*_ret_x = tx0.x(); *_ret_y = tx0.y(); *_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void,qtc_QVariant_toRect_qth)(void* x0, int* _ret_x, int* _ret_y, int* _ret_w, int* _ret_h) {
QRect tx0 = ((QVariant*)x0)->toRect();
*_ret_x = tx0.x(); *_ret_y = tx0.y(); *_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void*,qtc_QVariant_QRectF)(void* x0) {
QVariant*tr = new QVariant((const QRectF&)(*(QRectF*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QRectF)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QRectF>((const QRectF&)(*(QRectF*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QRectF)(void* x0) {
QRectF*tr = new QRectF(((QVariant*)x0)->value<QRectF>());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_toRectF)(void* x0) {
QRectF*tr = new QRectF(((QVariant*)x0)->toRectF());
return (void*) tr;
}
QTCEXPORT(void*,qtc_QVariant_QRectF_qth)(double x0_x, double x0_y, double x0_w, double x0_h) {
QRectF tx0(x0_x, x0_y, x0_w, x0_h);
QVariant*tr = new QVariant(tx0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QRectF_qth)(void* x0, double x1_x, double x1_y, double x1_w, double x1_h) {
QRectF tx1(x1_x, x1_y, x1_w, x1_h);
((QVariant*)x0)->setValue<QRectF>(tx1);
}
QTCEXPORT(void,qtc_QVariantValue_QRectF_qth)(void* x0, double* _ret_x, double* _ret_y, double* _ret_w, double* _ret_h) {
QRectF tx0 = ((QVariant*)x0)->value<QRectF>();
*_ret_x = tx0.x(); *_ret_y = tx0.y(); *_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void,qtc_QVariant_toRectF_qth)(void* x0, double* _ret_x, double* _ret_y, double* _ret_w, double* _ret_h) {
QRectF tx0 = ((QVariant*)x0)->toRectF();
*_ret_x = tx0.x(); *_ret_y = tx0.y(); *_ret_w = tx0.width(); *_ret_h = tx0.height();
return;
}
QTCEXPORT(void*,qtc_QVariant_List)(int _len0, void* x0) {
QList<QVariant>tql0;
for (int i = 0; i < _len0; i++) {
tql0.append(*((QVariant*)((void**)x0)[i]));
}
QVariant*tr = new QVariant(tql0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_List)(void* x0, int _len1, void* x1) {
QList<QVariant>tql1;
for (int i = 0; i < _len1; i++) {
tql1.append(*((QVariant*)((void**)x1)[i]));
}
((QVariant*)x0)->setValue<QVariantList>(tql1);
}
QTCEXPORT(int,qtc_QVariantValue_List)(void* x0, void* _ref) {
QList<QVariant> tql = ((QVariant*)x0)->value<QVariantList>();
if (_ref != NULL) {
for (int i = 0; i < tql.size(); i++) {
QVariant * tr = new QVariant(tql.at(i));
((void**)_ref)[i] = (void*)tr;
}
}
return tql.size();
}
QTCEXPORT(int,qtc_QVariant_toList)(void* x0, void* _ref) {
QList<QVariant> tql = ((QVariant*)x0)->toList();
if (_ref != NULL) {
for (int i = 0; i < tql.size(); i++) {
QVariant * tr = new QVariant(tql.at(i));
((void**)_ref)[i] = (void*)tr;
}
}
return tql.size();
}
QTCEXPORT(void*,qtc_QVariant_QStringList)(int _len0, void* x0) {
QStringList tqsl0;
for (int i = 0; i < _len0; i++) {
tqsl0.append(from_method(((wchar_t**)x0)[i]));
}
QVariant*tr = new QVariant(tqsl0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QStringList)(void* x0, int _len1, void* x1) {
QStringList tqsl1;
for (int i = 0; i < _len1; i++) {
tqsl1.append(from_method(((wchar_t**)x1)[i]));
}
((QVariant*)x0)->setValue<QStringList>(tqsl1);
}
QTCEXPORT(int,qtc_QVariantValue_QStringList)(void* x0, void* _ref) {
QStringList tqsl = ((QVariant*)x0)->value<QStringList>();
if (_ref != NULL) {
for (int i = 0; i < tqsl.size(); i++) {
QString * tqs = new QString(tqsl.at(i));
((void**)_ref)[i] = (void*)tqs;
}
}
return tqsl.size();
}
QTCEXPORT(int,qtc_QVariant_toStringList)(void* x0, void* _ref) {
QStringList tqsl = ((QVariant*)x0)->toStringList();
if (_ref != NULL) {
for (int i = 0; i < tqsl.size(); i++) {
QString * tqs = new QString(tqsl.at(i));
((void**)_ref)[i] = (void*)tqs;
}
}
return tqsl.size();
}
QTCEXPORT(void*,qtc_QVariant_Int)(int x0) {
QVariant*tr = new QVariant(x0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_Int)(void* x0, int x1) {
((QVariant*)x0)->setValue<int>(x1);
}
QTCEXPORT(int,qtc_QVariantValue_Int)(void* x0) {
return ((QVariant*)x0)->value<int>();
}
QTCEXPORT(int,qtc_QVariant_toInt)(void* x0) {
return ((QVariant*)x0)->toInt();
}
QTCEXPORT(void*,qtc_QVariant_Bool)(int x0) {
QVariant*tr = new QVariant(((bool)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_Bool)(void* x0, int x1) {
((QVariant*)x0)->setValue<bool>(((bool)x1));
}
QTCEXPORT(int,qtc_QVariantValue_Bool)(void* x0) {
return (int) ((QVariant*)x0)->value<bool>();
}
QTCEXPORT(int,qtc_QVariant_toBool)(void* x0) {
return (int) ((QVariant*)x0)->toBool();
}
QTCEXPORT(void*,qtc_QVariant_Double)(double x0) {
QVariant*tr = new QVariant(x0);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_Double)(void* x0, double x1) {
((QVariant*)x0)->setValue<double>(x1);
}
QTCEXPORT(double,qtc_QVariantValue_Double)(void* x0) {
return ((QVariant*)x0)->value<double>();
}
QTCEXPORT(double,qtc_QVariant_toDouble)(void* x0) {
return ((QVariant*)x0)->toDouble();
}
QTCEXPORT(void*,qtc_QVariant_QString)(wchar_t* x0) {
QString tx1(from_method(x0));
QVariant*tr = new QVariant(tx1);
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QString)(void* x0, wchar_t* x1) {
QString tx1(from_method(x1));
((QVariant*)x0)->setValue<QString>(tx1);
}
QTCEXPORT(void*,qtc_QVariantValue_QString)(void* x0) {
QString * tq = new QString(((QVariant*)x0)->value<QString>());
return (void*) tq;
}
QTCEXPORT(void*,qtc_QVariant_toString)(void* x0) {
QString * tq = new QString(((QVariant*)x0)->toString());
return (void*) tq;
}
QTCEXPORT(void*,qtc_QVariant_QByteArray)(void* x0) {
QVariant*tr = new QVariant((const QByteArray&)(*(QByteArray*)x0));
return (void*) tr;
}
QTCEXPORT(void,qtc_QVariant_setValue_QByteArray)(void* x0, void* x1) {
((QVariant*)x0)->setValue<QByteArray>((const QByteArray&)(*(QByteArray*)x1));
}
QTCEXPORT(void*,qtc_QVariantValue_QByteArray)(void* x0) {
QByteArray * tq = new QByteArray(((QVariant*)x0)->value<QByteArray>());
return (void*) tq;
}
QTCEXPORT(void*,qtc_QVariant_toByteArray)(void* x0) {
QByteArray * tq = new QByteArray(((QVariant*)x0)->toByteArray());
return (void*) tq;
}
QTCEXPORT(long,qtc_QVariant_type)(void* x0) {
return (long) ((QVariant*)x0)->type();
}
QTCEXPORT(void*,qtc_QVariant_typeName)(void* x0) {
QString * tq = new QString(((QVariant*)x0)->typeName());
return (void*) tq;
}
QTCEXPORT(long,qtc_QVariant_nameToType)(wchar_t* x1) {
QString tx1(from_method(x1));
return (long) QVariant::nameToType(tx1.toUtf8().constData());
}
QTCEXPORT(void*,qtc_QVariant_typeToName)(long x1) {
QString * tq = new QString(QVariant::typeToName((QVariant::Type)x1));
return (void*) tq;
}
QTCEXPORT(int,qtc_QVariant_canConvert)(void* x0, long x1) {
return (int) ((QVariant*)x0)->canConvert((QVariant::Type)x1);
}
QTCEXPORT(int,qtc_QVariant_convert)(void* x0, long x1) {
return (int) ((QVariant*)x0)->convert((QVariant::Type)x1);
}
QTCEXPORT(void,qtc_QVariant_clear)(void* x0) {
((QVariant*)x0)->clear();
return;
}
QTCEXPORT(int,qtc_QVariant_isNull)(void* x0) {
return (int) ((QVariant*)x0)->isNull();
}
QTCEXPORT(int,qtc_QVariant_isValid)(void* x0) {
return (int) ((QVariant*)x0)->isValid();
}
QTCEXPORT(void*,qtc_QPointer)(void *x0) {
QPointer<QObject> * ttr = new QPointer<QObject>((QObject*)x0);
return (void *) ttr;
}
QTCEXPORT(void*,qtc_QPointer_data)(void *x0) {
QObject *ttr = *((QPointer<QObject>*)x0);
return (void *) ttr;
}
QTCEXPORT(int,qtc_QPolygonF_qpoints)(void *x0, double* _ret) {
int ts = ((QPolygonF*)x0)->size();
if (_ret != NULL) {
for (int i = 0; i < ts; i++) {
_ret[i * 2] = ((QPolygonF*)x0)->at(i).x();
_ret[(i * 2) + 1] = ((QPolygonF*)x0)->at(i).y();
}
}
return ts;
}
QTCEXPORT(int,qtc_QPolygon_qpoints)(void *x0, int* _ret) {
int ts = ((QPolygon*)x0)->size();
if (_ret != NULL) {
for (int i = 0; i < ts; i++) {
_ret[i * 2] = ((QPolygon*)x0)->at(i).x();
_ret[(i * 2) + 1] = ((QPolygon*)x0)->at(i).y();
}
}
return ts;
}
}
| 33.378173 | 182 | 0.676831 | keera-studios |
d1b3d4da3a4bae3d0ae068306d0c8d6e2dc1cfb8 | 1,331 | cpp | C++ | gameserver/test/main.cpp | shockerjue/Gameserver | 78faab152e1cb211d551a794ea4df5738cf99b04 | [
"Unlicense"
] | 31 | 2017-10-18T08:56:43.000Z | 2022-03-22T15:43:10.000Z | gameserver/test/main.cpp | shockerjue/Gameserver | 78faab152e1cb211d551a794ea4df5738cf99b04 | [
"Unlicense"
] | null | null | null | gameserver/test/main.cpp | shockerjue/Gameserver | 78faab152e1cb211d551a794ea4df5738cf99b04 | [
"Unlicense"
] | 14 | 2018-03-15T10:36:53.000Z | 2021-11-11T19:35:39.000Z | #include "./../src/msghandle/gameserver_msgheader.pb.h"
#include "./../../common/util/util.h"
#include "./../../common/msgdefine/msgheader.h"
#include "./../../common/network/network.h"
using namespace util;
using namespace msghandle;
using namespace gameserver_proto;
using namespace engine;
using namespace engine::network;
int main(int argc,const char* argv[]){
NetworkAddress address("127.0.0.1",4);
Network network(network::Protocol::TCP);
bool ret = network.Connect(address,8092);
if(!ret){
Log::Perror(__func__,"Connect fail!");
return -1;
}
LoginRequest login;
login.set_rid(9021);
login.set_key("ABCFARTQYT09879HJGJ^&**&()JKJI890");
string data;
login.SerializeToString(&data);
struct MessageHeader header;
header.msg_type = 10000;
header.msg_size = data.length();
char _data[sizeof(struct MessageHeader) + data.length()];
memcpy(_data,&header,sizeof(struct MessageHeader));
memcpy(_data + sizeof(struct MessageHeader),data.c_str(),data.length());
int len = network.Send(_data,sizeof(_data));
cout<<"Send sccuess len:"<<len<<" B"<<endl;
char buf[100] = {0};
len = network.Recv(buf,100);
string _recv = buf + sizeof(struct MessageHeader);
LoginResponse re_login;
re_login.ParseFromString(_recv);
cout<<"{status:"<<re_login.status()<<", msg:"<<re_login.msg()<<"}"<<endl;
return 0;
}
| 26.098039 | 74 | 0.709241 | shockerjue |
d1b5466adf001f4b32a8c3055cd9bbfb398ce3ca | 5,376 | cpp | C++ | src/wrappers/sockets/client_socket.cpp | ben-turner/s-torrent | f8ff818f2ce9c2bf76d2a108e1f32d3a601390e0 | [
"X11",
"BSD-2-Clause",
"MIT"
] | 20 | 2015-04-15T05:36:05.000Z | 2022-03-21T07:02:55.000Z | src/wrappers/sockets/client_socket.cpp | ben-turner/s-torrent | f8ff818f2ce9c2bf76d2a108e1f32d3a601390e0 | [
"X11",
"BSD-2-Clause",
"MIT"
] | null | null | null | src/wrappers/sockets/client_socket.cpp | ben-turner/s-torrent | f8ff818f2ce9c2bf76d2a108e1f32d3a601390e0 | [
"X11",
"BSD-2-Clause",
"MIT"
] | 6 | 2016-09-20T08:41:22.000Z | 2021-03-10T14:16:59.000Z | #include "client_socket.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <sstream>
#include <stdexcept>
namespace sockets
{
Client_socket::Client_socket ( std::string address, int port )
{
struct sockaddr_in server_address;
struct hostent* resolved_server;
// Create a socket on the internet using the tcp
socket_address = socket(AF_INET, SOCK_STREAM, 0);
if ( socket_address < 0 )
error ( "Client_socket : Couldn't open socket" );
// Resolve server
resolved_server = gethostbyname ( address.c_str () );
if ( resolved_server == NULL )
error ( "Client_socket : Host not found: \"" + address + "\"" );
// Empty server_address
bzero ( ( char* ) &server_address, sizeof ( server_address ) );
// Use the internet
server_address.sin_family = AF_INET;
// Use address of resolved server
bcopy ( ( char* ) resolved_server->h_addr, ( char* ) &server_address.sin_addr.s_addr, resolved_server->h_length );
// sin_port has to be in network byte order
server_address.sin_port = htons ( port );
// Enable socket address reuse
int yes = 1;
int success = setsockopt ( socket_address, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof ( int ) );
if ( success < 0 )
error ( "Client_socket : setsockopt failed" );
// server_address has to be converted to sockaddr* from sockadd_in
success = connect ( socket_address, ( struct sockaddr* ) &server_address, sizeof ( server_address ) );
if ( success < 0 )
error ( "Client_socket : Connecting failed");
}
Client_socket::Client_socket ( int socket_address ) :
socket_address ( socket_address )
{}
std::string Client_socket::read_line ( std::string linebreak )
{
// Read until we have at least one line
while ( next_lines.empty () )
{
// This might actually happen ( look at the test for an example )
if ( ends_with ( line_rest, linebreak ) )
{
// Remove the linebreak from the end
next_lines.push_back ( line_rest.substr ( 0, line_rest.find_last_of ( linebreak ) ) );
line_rest = "";
break;
}
char buffer [ 1024 ];
int success = read ( socket_address, buffer, sizeof ( buffer ) - 1 );
if ( success < 0 )
error ( "read_line : Reading from socket failed");
else if ( success == 0 )
error ( "read_line : Connection closed");
buffer [ success ] = '\0';
// Create actual string from vector
std::string data_string ( buffer, strlen ( buffer ) );
std::string line;
// Split lines at delimiter
while ( ( line = get_line ( data_string, linebreak ) ).size () > 0 )
{
// Apply line_rest ( if any )
line = line_rest + line;
line_rest.clear ();
// Save yourself the hassle of dealing with DOS linebreaks
next_lines.push_back ( line );
}
// If buffer_string doesn't end with a linebreak
if ( data_string.size () > 0 )
{
// Create a line_rest
line_rest += data_string;
}
}
// Return next line
while ( !next_lines.empty () && next_lines.front () == "" )
next_lines.pop_front ();
if ( !next_lines.empty () )
{
std::string line = next_lines.front ();
next_lines.pop_front ();
return line;
}
else
return read_line ();
}
void Client_socket::send ( std::string message, std::string linebreak )
{
message += linebreak;
int success = write ( socket_address, message.c_str (), message.size () );
if ( success < 0 )
error ( "send : Sending over socket failed");
}
void Client_socket::shutdown ()
{
int success = close ( socket_address );
if ( success < 0 )
error ( "shutdown : Shutting socket down failed" );
}
void Client_socket::error ( std::string message )
{
if ( errno != 0 )
throw std::runtime_error ( "Error in sockets::Client_socket::" + message + " ( " + strerror ( errno ) + " )" );
else
throw std::runtime_error ( "Error in sockets::Client_socket::" + message );
}
std::string Client_socket::get_line ( std::string& from, const std::string& delimiter )
{
size_t pos = from.find ( delimiter );
if ( pos != std::string::npos )
{
std::string return_string = from.substr ( 0, pos );
from = from.substr ( pos + delimiter.size () );
return return_string;
}
return "";
}
bool Client_socket::ends_with ( const std::string& target, const std::string& ending )
{
if ( target.length () >= ending.length () )
return ( 0 == target.compare ( target.length () - ending.length (), ending.length (), ending ) );
return false;
}
}
| 34.242038 | 123 | 0.549851 | ben-turner |
d1b6b396afc16bb80ba24924854f6d65ad014d1a | 4,144 | cpp | C++ | game/tile_instance.cpp | astrellon/Rouge | 088f55b331284238e807e0562b9cbbed6428c20f | [
"MIT"
] | null | null | null | game/tile_instance.cpp | astrellon/Rouge | 088f55b331284238e807e0562b9cbbed6428c20f | [
"MIT"
] | null | null | null | game/tile_instance.cpp | astrellon/Rouge | 088f55b331284238e807e0562b9cbbed6428c20f | [
"MIT"
] | null | null | null | #include "tile_instance.h"
#include <util/utils.h>
#include "tile.h"
#include "engine.h"
#include <lua/wrappers/lua_id_table.h>
namespace am {
namespace game {
const int TileInstance::LUA_ID = LUA_ID_TILEINSTANCE;
const char *TileInstance::LUA_TABLENAME = LUA_TABLE_TILEINSTANCE;
TileInstance::TileInstance() :
mTile(nullptr),
mBaseVariation(0),
mTransitionVariation(0),
mOrder(-1)
{
for (int i = 0; i < 8; i++)
{
mTileEdgeValues[i] = 0u;
}
}
TileInstance::TileInstance(Tile *tile) :
mTile(tile),
mBaseVariation(0),
mTransitionVariation(0),
mOrder(-1)
{
for (int i = 0; i < 8; i++)
{
mTileEdgeValues[i] = 0u;
}
}
TileInstance::~TileInstance()
{
}
Tile *TileInstance::getTile()
{
if (mTile)
{
return mTile;
}
return Tile::getDefaultTile();
}
const Tile *TileInstance::getTile() const
{
if (mTile)
{
return mTile;
}
return Tile::getDefaultTile();
}
void TileInstance::setTile(Tile *tile)
{
mTile = tile;
}
bool TileInstance::setTileName(const char *tileName)
{
return setTileName(std::string(tileName));
}
bool TileInstance::setTileName(const std::string &tileName)
{
int framePos = static_cast<int>(tileName.find_last_of(":"));
std::string tileNameUse;
int frameValue = 0;
if (framePos >= 0)
{
std::string name = tileName.substr(0, framePos);
std::string frame = tileName.substr(framePos + 1);
tileNameUse = name;
bool parseResult = util::Utils::fromString<int>(frameValue, frame);
if (!parseResult)
{
frameValue = 0;
}
}
else
{
tileNameUse = tileName;
}
Tile *tile = Engine::getEngine()->getTile(tileNameUse.c_str());
if (tile == nullptr)
{
return false;
}
setTile(tile);
setBaseVariation(frameValue);
return true;
}
void TileInstance::setBaseVariation(int frame)
{
mBaseVariation = frame;
}
int TileInstance::getBaseVariation() const
{
return mBaseVariation;
}
void TileInstance::randomiseVaritation()
{
gfx::Asset *asset = mTile ? mTile->getGraphicAsset() : nullptr;
if (!asset)
{
return;
}
if (asset->getFrameRate() <= 0.0f)
{
if (asset->isSubWindowAnimation())
{
setBaseVariation(util::Utils::rand(0, asset->getTotalSubWindows()));
}
else
{
setBaseVariation(util::Utils::rand(0, asset->getTotalTextures()));
}
}
else
{
setBaseVariation(0);
}
}
void TileInstance::setTransitionVariation(int frame)
{
mTransitionVariation = frame;
}
int TileInstance::getTransitionVariation() const
{
return mTransitionVariation;
}
bool TileInstance::hasEdgeValue() const
{
for (int i = 0; i < 8; i++)
{
if (mTileEdgeValues[i] != 0)
{
return true;
}
}
return false;
}
void TileInstance::clearTileEdges()
{
for (int i = 0; i < 8; i++)
{
mTileEdgeValues[i] = 0u;
}
}
void TileInstance::setTileEdgeValue(uint32_t index, uint8_t edgeValue)
{
if (index < 8)
{
mTileEdgeValues[index] = edgeValue;
}
}
uint8_t TileInstance::getTileEdgeValue(uint32_t index) const
{
if (index < 8)
{
return mTileEdgeValues[index];
}
return 0u;
}
void TileInstance::addTileType(TileType *tileType)
{
if (tileType != nullptr)
{
mTileTypes.push_back(tileType);
}
}
void TileInstance::removeTileType(TileType *tileType)
{
if (tileType == nullptr)
{
return;
}
for (size_t i = 0; i < mTileTypes.size(); i++)
{
if (mTileTypes[i].get() == tileType)
{
mTileTypes.erase(mTileTypes.begin() + i);
}
}
}
void TileInstance::removeAllTileTypes()
{
mTileTypes.clear();
}
bool TileInstance::hasTileType(TileType *tileType) const
{
if (tileType == nullptr)
{
return false;
}
for (size_t i = 0; i < mTileTypes.size(); i++)
{
if (mTileTypes[i].get() == tileType)
{
return true;
}
}
return false;
}
TileInstance::TileTypeList &TileInstance::getTileTypes()
{
return mTileTypes;
}
const TileInstance::TileTypeList &TileInstance::getTileTypes() const
{
return mTileTypes;
}
void TileInstance::setOrder(uint32_t order)
{
mOrder = order;
}
uint32_t TileInstance::getOrder() const
{
return mOrder;
}
}
}
| 17.785408 | 72 | 0.649855 | astrellon |
d1bebb1e78b9e0b5e41e4bb8dfa71674e68df33d | 2,194 | hpp | C++ | p5out/src/application/imageio.hpp | tinyalpha/PhysicsSimulation | a13f259862216d809b02aa4739e7692a9d66e2bc | [
"MIT"
] | 25 | 2016-11-14T23:23:53.000Z | 2020-12-17T08:29:41.000Z | p5out/src/application/imageio.hpp | tinyalpha/PhysicsSimulation | a13f259862216d809b02aa4739e7692a9d66e2bc | [
"MIT"
] | 1 | 2018-08-08T00:31:49.000Z | 2018-08-08T00:31:49.000Z | p5out/src/application/imageio.hpp | tinyalpha/PhysicsSimulation | a13f259862216d809b02aa4739e7692a9d66e2bc | [
"MIT"
] | 1 | 2020-03-22T12:04:52.000Z | 2020-03-22T12:04:52.000Z | /* LIBRARY: ImageIO Library v0.13
*
* FILE: imageio.hpp
*
* COPYRIGHT: Copyright (c) 2003-2004 Adrien Treuille
*
* AUTHORS: Adrien Treuille (treuille [AT] cs [DOT] washington [DOT] edu)
* Kristin Siu
*
* LICENSE: The ImageIO Library is supplied "AS IS". The Authors
* disclaim all warranties, expressed or implied,
* including, without limitation, the warranties of
* merchantability and of fitness for any purpose.
* The Authors assume no liability for direct, indirect,
* incidental, special, exemplary, or consequential
* damages, which may result from the use of the ImageIO
* Library, even if advised of the possibility of such
* damage.
*
* Permission is hereby granted to use, copy, modify,
* and distribute this source code, or portions hereof,
* for any purpose, without fee, for non-commercial
* purposes. All rights reserved for commercial uses of
* this source code.
*/
#ifndef _462_APPLICATION_IMAGEIO_HPP_
#define _462_APPLICATION_IMAGEIO_HPP_
#include <cstdlib>
namespace _462 {
// Sets tbe width and height to the appropriate values and mallocs
// a char *buffer loading up the values in row-major, RGBA format.
// The memory associated with the buffer can be deallocated with free().
// If there was an error reading file, then 0 is returned, and
// width = height are set to -1.
unsigned char* imageio_load_image( const char* filename, int *width, int *height );
// Saves image given by buffer with specicified width and height
// to the given file name, returns true on success, false otherwise.
// The image format is RGBA.
bool imageio_save_image( const char* filename, unsigned char* buffer, int width, int height );
// Writes the current opengl frame buffer to a specified file name.
// Returns true on succces, false otherwise.
bool imageio_save_screenshot( const char* filename, int width, int height );
// puts a default filename in name, up to len characters
void imageio_gen_name( char* filename, size_t len );
} /* _462 */
#endif /* _462_APPLICATION_IMAGEIO_HPP_ */
| 39.178571 | 94 | 0.692343 | tinyalpha |
d1c041790d599aa0d1b197136b45adbf63aa7b69 | 4,703 | cpp | C++ | src/pow.cpp | kevacoin-team/kevacoin | 7a6f5024cb8e2f0283c6e57b9f4439dcdf9a09e8 | [
"MIT"
] | null | null | null | src/pow.cpp | kevacoin-team/kevacoin | 7a6f5024cb8e2f0283c6e57b9f4439dcdf9a09e8 | [
"MIT"
] | null | null | null | src/pow.cpp | kevacoin-team/kevacoin | 7a6f5024cb8e2f0283c6e57b9f4439dcdf9a09e8 | [
"MIT"
] | null | null | null | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <pow.h>
#include <arith_uint256.h>
#include <chain.h>
#include <primitives/block.h>
#include <uint256.h>
extern void GetRandomXSeedParams(uint64_t& seedHeight, uint256& blockHash);
// Copy and modified from CalculateDogecoinNextWorkRequired (dogecoin.cpp)
unsigned int CalculateDigishieldNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
const int64_t retargetTimespan = params.nPowTargetTimespan;
const int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
int64_t nModulatedTimespan = nActualTimespan;
int64_t nMaxTimespan;
int64_t nMinTimespan;
// amplitude filter - thanks to daft27 for this code
nModulatedTimespan = retargetTimespan + (nModulatedTimespan - retargetTimespan) / 8;
nMinTimespan = retargetTimespan - (retargetTimespan / 4);
nMaxTimespan = retargetTimespan + (retargetTimespan / 2);
// Limit adjustment step
if (nModulatedTimespan < nMinTimespan)
nModulatedTimespan = nMinTimespan;
else if (nModulatedTimespan > nMaxTimespan)
nModulatedTimespan = nMaxTimespan;
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
arith_uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
bnNew *= nModulatedTimespan;
bnNew /= retargetTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
return bnNew.GetCompact();
}
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
assert(pindexLast != nullptr);
// Go back by what we want to be 14 days worth of blocks
// Kevacoin: This fixes an issue where a 51% attack can change difficulty at will.
// Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
int blockstogoback = params.DifficultyAdjustmentInterval()-1;
if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval())
blockstogoback = params.DifficultyAdjustmentInterval();
// Go back by what we want to be 14 days worth of blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < blockstogoback; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
return CalculateDigishieldNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
if (nActualTimespan < params.nPowTargetTimespan/4)
nActualTimespan = params.nPowTargetTimespan/4;
if (nActualTimespan > params.nPowTargetTimespan*4)
nActualTimespan = params.nPowTargetTimespan*4;
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
bnNew.SetCompact(pindexLast->nBits);
bnNew *= nActualTimespan;
bnNew /= params.nPowTargetTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return false;
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
return false;
return true;
}
bool CheckProofOfWork(const CBlock& block, unsigned int nBits, const Consensus::Params& params) {
uint64_t seedHeight = 0;
uint256 blockHash(0);
GetRandomXSeedParams(seedHeight, blockHash);
//return CheckProofOfWork(block.GetPoWHash(seedHeight, blockHash), nBits, params);
return true;
}
bool CheckProofOfWork(const CBlockHeader& block, unsigned int nBits, const Consensus::Params& params) {
uint64_t seedHeight = 0;
uint256 blockHash(0);
GetRandomXSeedParams(seedHeight, blockHash);
//return CheckProofOfWork(block.GetPoWHash(seedHeight, blockHash), nBits, params);
return true;
}
| 35.360902 | 137 | 0.732936 | kevacoin-team |
d1c7024bfc06fc71c2df0d891bce19a53d10da44 | 3,015 | cpp | C++ | apps/main.cpp | mpohl100/TheChase | 06a3ddd7b2a5dd5102f3b3288706bd6e658d0cd9 | [
"Apache-2.0"
] | null | null | null | apps/main.cpp | mpohl100/TheChase | 06a3ddd7b2a5dd5102f3b3288706bd6e658d0cd9 | [
"Apache-2.0"
] | null | null | null | apps/main.cpp | mpohl100/TheChase | 06a3ddd7b2a5dd5102f3b3288706bd6e658d0cd9 | [
"Apache-2.0"
] | null | null | null | #include <chase/TeamAnalysisPar.h>
#include <clara.hpp>
#include <iostream>
int main(int argc, char** argv)
{
using namespace clara;
std::string name;
bool help = false;
auto cli = Opt(name, "name")["-n"]["--name"]("name to greet") | Help(help);
auto result = cli.parse(Args(argc, argv));
if (!result) {
std::cerr << "Error in command line: " << result.errorMessage() << '\n';
exit(1);
}
if (help) {
std::cout << cli;
exit(0);
}
#if 0
chase::SimpleAnalysisOptions options;
options.dontPlayFinal = true;
options.nbGenerations = 500;
chase::simpleChaseAnalysis(options);
#else
std::vector<std::vector<double>> playerPercentages = {
{0.4, 0.7, 0.4, 0.4},
{0.4, 0.4, 0.7, 0.4},
{0.4, 0.4, 0.4, 0.7},
{0.6, 0.4, 0.4, 0.4},
{0.4, 0.6, 0.4, 0.4},
{0.4, 0.4, 0.6, 0.4},
{0.4, 0.4, 0.4, 0.6},
{0.5, 0.4, 0.4, 0.4},
{0.4, 0.5, 0.4, 0.4},
{0.4, 0.4, 0.5, 0.4},
{0.4, 0.4, 0.4, 0.5},
{0.7, 0.5, 0.5, 0.5},
{0.5, 0.7, 0.5, 0.5},
{0.5, 0.5, 0.7, 0.5},
{0.5, 0.5, 0.5, 0.7},
{0.6, 0.5, 0.5, 0.5},
{0.5, 0.6, 0.5, 0.5},
{0.5, 0.5, 0.6, 0.5},
{0.5, 0.5, 0.5, 0.6},
{0.7, 0.6, 0.6, 0.6},
{0.6, 0.7, 0.6, 0.6},
{0.6, 0.6, 0.7, 0.6},
{0.6, 0.6, 0.6, 0.7}};
for(const auto& playerPercentage : playerPercentages)
{
chase::TeamPlayerAnalysis analysis;
analysis.analysisRange.playerPercentages = playerPercentage;
analysis.analysisRange.chaserFactorParams = {{2.0, 5.0, 1.0}};
chase::teamPlayerAnalysisPar(analysis);
chase::dumpTeamPlayerResults(analysis, std::string("Team" + chase::toStringPath(playerPercentage) + ".csv"));
}
#endif
return 0;
}
| 44.338235 | 117 | 0.305804 | mpohl100 |
d1ca2ef06b7606a13b1247b19a65bd7d89f4b594 | 2,665 | cpp | C++ | src/gameobject_asteroid.cpp | liamst19/asteroids-study | 809e6573eb45800ba06ec8e03e7103815188a70b | [
"MIT"
] | null | null | null | src/gameobject_asteroid.cpp | liamst19/asteroids-study | 809e6573eb45800ba06ec8e03e7103815188a70b | [
"MIT"
] | null | null | null | src/gameobject_asteroid.cpp | liamst19/asteroids-study | 809e6573eb45800ba06ec8e03e7103815188a70b | [
"MIT"
] | null | null | null | /** gameobject_asteroid.h
*
*
*/
#include <vector>
#include <algorithm>
#include "math.h"
#include "game.h"
#include "gameobject_asteroid.h"
#include "component_physics.h"
#include "component_collision.h"
/** Constructor
*
*/
Asteroid::Asteroid(Game* game,
Vector2d position,
float rotation):
GameObject(game, position, rotation)
{
// Set Velocities
_physics.set_velocity(Vector2d(_game->rand(_rand_forward_velocity_min, _rand_forward_velocity_max),
_game->rand(_rand_forward_velocity_min, _rand_forward_velocity_max)));
_physics.set_angular_velocity(_game->rand(_rand_angular_velocity_min, _rand_angular_velocity_max));
// generate shape
float radius = _game->rand(_rand_radius_min, _rand_radius_max);
_draw.set_shape_active(make_shape_active(radius));
_draw.set_shape_destroyed(make_shape_destroyed(radius));
// prepare collision
_collision.set_radius(radius);
add_component(&_physics);
add_component(&_draw);
add_component(&_collision);
}
/** function: update()
*
*/
void Asteroid::update(double delta_time){
update_components(delta_time);
}
/** function: destroy()
*
*/
void Asteroid::destroy(){
_state = GameObject_State_Code::destroyed;
}
/** function: make_shape()
*
*/
std::vector<Vector2d> Asteroid::make_shape_active(float radius){
std::vector<Vector2d> shape;
int vertices = _game->rand(_rand_vertices_min, _rand_vertices_max);
std::vector<float> angles;
// Fill shape with random angles
for(int i = 0; i < vertices; ++i){
angles.push_back(_game->rand(_rand_angles_min, _rand_angles_max));
}
// Sort angles into shape
std::sort(angles.begin(), angles.end());
Vector2d bounds = _game->get_bounds();
// Draw shape from angles
for(auto angle: angles){
shape.push_back(Vector2d(
radius * Math::Sin(Math::ToRadians(angle)),
-1 * radius * Math::Cos(Math::ToRadians(angle))
));
}
return shape;
}
/** function: draw_shape_destroyed()
*
*/
std::vector<Vector2d> Asteroid::make_shape_destroyed(float radius){
std::vector<Vector2d> shape{
Vector2d(5, -3),
Vector2d(-5, 3),
Vector2d(8, -5),
Vector2d(-8, 5),
Vector2d(3, -1),
Vector2d(-4, 3),
};
return shape;
}
/** function: draw()
*
*/
std::vector<Vector2d> Asteroid::draw(){
return _draw.draw_shape(_physics.position(),
_physics.rotation());
} | 25.380952 | 106 | 0.620263 | liamst19 |
d1cada508aa3d1651678857da0ecddbc19d624fc | 2,104 | hpp | C++ | library/ATF/CNetSocket.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/CNetSocket.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/CNetSocket.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <CNetIndexList.hpp>
#include <CNetSocketVtbl.hpp>
#include <CNetTimer.hpp>
#include <_IP_CHECK_NODE.hpp>
#include <_SOCK_TYPE_PARAM.hpp>
#include <_socket.hpp>
#include <_total_count.hpp>
#include <sockaddr_in.hpp>
START_ATF_NAMESPACE
#pragma pack(push, 8)
struct CNetSocket
{
CNetSocketVtbl *vfptr;
unsigned __int64 m_sAccept;
void *m_AcceptEvent;
_socket *m_Socket;
void **m_Event;
_SOCK_TYPE_PARAM m_SockType;
_total_count m_TotalCount;
bool m_bSetSocket;
unsigned int m_dwSerialCounter;
int m_nIPCheckNodeNum;
_IP_CHECK_NODE *m_ndIPCheck;
unsigned int *m_dwIPCheckBufferList;
CNetIndexList m_listIPCheck;
CNetIndexList m_listIPCheck_Empty;
CNetTimer m_tmrListCheckerIPCheck;
public:
bool Accept_Client(unsigned int dwSocketIndex);
unsigned int Accept_Server();
CNetSocket();
void ctor_CNetSocket();
void CloseAll();
bool CloseSocket(unsigned int n);
int Connect(unsigned int n, struct sockaddr_in* pAddr);
void EmptySocketBuffer(unsigned int n);
unsigned int FindEmptySocket();
struct _socket* GetSocket(unsigned int dwIndex);
unsigned int GetSocketIPAddress(unsigned int dwIndex);
struct _SOCK_TYPE_PARAM* GetSocketType();
struct _total_count* GetTotalCount();
bool InitAcceptSocket(char* pszErrMsg);
void OnLoop();
bool PushIPCheckList(unsigned int dwIP);
bool Recv(unsigned int n, char* pBuf, int nBufMaxSize, int* pnRet);
void Release();
bool Send(unsigned int n, char* pBuf, int nSize, int* pnRet);
bool SetSocket(struct _SOCK_TYPE_PARAM* pType, char* pszErrMsg);
~CNetSocket();
void dtor_CNetSocket();
};
#pragma pack(pop)
static_assert(ATF::checkSize<CNetSocket, 488>(), "CNetSocket");
END_ATF_NAMESPACE
| 34.491803 | 108 | 0.677281 | lemkova |
d1ccd29a5e64983e562a2add75c39af476360f80 | 242 | cpp | C++ | c++11/tests/right_bracket_parse.cpp | queertypes/cplusplus-examples | c4f784cbc9e97220c0e25f7ea9f1121f63d194fe | [
"BSD-3-Clause"
] | null | null | null | c++11/tests/right_bracket_parse.cpp | queertypes/cplusplus-examples | c4f784cbc9e97220c0e25f7ea9f1121f63d194fe | [
"BSD-3-Clause"
] | null | null | null | c++11/tests/right_bracket_parse.cpp | queertypes/cplusplus-examples | c4f784cbc9e97220c0e25f7ea9f1121f63d194fe | [
"BSD-3-Clause"
] | null | null | null | #include <cstdio>
template <class T>
struct X {
};
int main()
{
// can your compiler handle this parse?
X<X<int>> *x{nullptr};
// output for the sake of silencing compiler warnings
printf("%p\n", static_cast<void *>(x));
return 0;
}
| 14.235294 | 54 | 0.652893 | queertypes |
d1d24e4857847c0be5fa20819c17367463c6698e | 21,177 | cpp | C++ | src/data_readers/data_reader_jag.cpp | forsyth2/lbann | 64fc0346f65353c2f7526a019da964914e539fb0 | [
"Apache-2.0"
] | null | null | null | src/data_readers/data_reader_jag.cpp | forsyth2/lbann | 64fc0346f65353c2f7526a019da964914e539fb0 | [
"Apache-2.0"
] | null | null | null | src/data_readers/data_reader_jag.cpp | forsyth2/lbann | 64fc0346f65353c2f7526a019da964914e539fb0 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <[email protected]>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 "lbann/utils/file_utils.hpp"
#include "lbann/utils/cnpy_utils.hpp"
#include "lbann/utils/image.hpp"
#include "lbann/data_readers/data_reader_jag.hpp"
#include <limits> // numeric_limits
#include <algorithm> // max_element
#include <numeric> // accumulate
#include <functional> // multiplies
#include <type_traits>// is_same
#include <opencv2/core.hpp>
namespace lbann {
data_reader_jag::data_reader_jag(bool shuffle)
: generic_data_reader(shuffle),
m_independent({Undefined}), m_dependent({Undefined}),
m_image_loaded(false), m_scalar_loaded(false),
m_input_loaded(false), m_num_samples(0u),
m_linearized_image_size(0u),
m_linearized_scalar_size(0u),
m_linearized_input_size(0u),
m_image_normalization(0u),
m_image_width(0u), m_image_height(0u),
m_img_min(std::numeric_limits<data_t>::max()),
m_img_max(std::numeric_limits<data_t>::min()) {
}
data_reader_jag::~data_reader_jag() {
}
void data_reader_jag::set_independent_variable_type(
const std::vector< std::vector<data_reader_jag::variable_t> >& independent) {
if (!independent.empty() && !m_independent.empty() && (m_independent[0] == Undefined)) {
m_independent.clear();
}
for (const auto& group: independent) {
for (const auto type: group) {
add_independent_variable_type(type);
}
}
}
void data_reader_jag::add_independent_variable_type(
const data_reader_jag::variable_t independent) {
if (!(independent == JAG_Image || independent == JAG_Scalar ||
independent == JAG_Input || independent == Undefined)) {
throw lbann_exception(std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: unrecognized variable type " + std::to_string(static_cast<int>(independent)));
}
m_independent.push_back(independent);
}
void data_reader_jag::set_dependent_variable_type(
const std::vector < std::vector<data_reader_jag::variable_t> >& dependent) {
if (!dependent.empty() && !m_dependent.empty() && (m_dependent[0] == Undefined)) {
m_dependent.clear();
}
for (const auto& group: dependent) {
for (const auto type: group) {
add_dependent_variable_type(type);
}
}
}
void data_reader_jag::add_dependent_variable_type(
const data_reader_jag::variable_t dependent) {
if (!(dependent == JAG_Image || dependent == JAG_Scalar ||
dependent == JAG_Input || dependent == Undefined)) {
throw lbann_exception(std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: unrecognized variable type " + std::to_string(static_cast<int>(dependent)));
}
m_dependent.push_back(dependent);
}
std::vector<data_reader_jag::variable_t> data_reader_jag::get_independent_variable_type() const {
return m_independent;
}
std::vector<data_reader_jag::variable_t> data_reader_jag::get_dependent_variable_type() const {
return m_dependent;
}
bool data_reader_jag::is_independent(const variable_t t) const {
for(const auto i: m_independent) {
if (i == t) return true;
}
return false;
}
bool data_reader_jag::is_dependent(const variable_t t) const {
for(const auto d: m_dependent) {
if (d == t) return true;
}
return false;
}
bool data_reader_jag::is_used(const variable_t t) const {
return is_independent(t) || is_dependent(t);
}
void data_reader_jag::set_normalization_mode(int mode) {
if ((mode < 0) || (2 < mode)) {
throw lbann_exception("data_reader_jag: invalid normalization mode " +
std::to_string(mode));
}
m_image_normalization = mode;
}
void data_reader_jag::set_image_dims(const int width, const int height) {
if ((width > 0) && (height > 0)) { // set and valid
m_image_width = width;
m_image_height = height;
} else if (!((width == 0) && (height == 0))) { // set but not valid
std::stringstream err;
err << __FILE__<<" "<<__LINE__
<< " :: data_reader_jag::set_image_dims() invalid image dims";
throw lbann_exception(err.str());
}
}
size_t data_reader_jag::get_num_samples() const {
return m_num_samples;
}
size_t data_reader_jag::get_linearized_image_size() const {
return m_linearized_image_size;
}
size_t data_reader_jag::get_linearized_scalar_size() const {
return m_linearized_scalar_size;
}
size_t data_reader_jag::get_linearized_input_size() const {
return m_linearized_input_size;
}
void data_reader_jag::set_linearized_image_size() {
if (!m_image_loaded) {
m_linearized_image_size = 0u;
m_image_width = 0u;
m_image_height = 0u;
} else {
m_linearized_image_size
= std::accumulate(m_images.shape.begin()+1, m_images.shape.end(),
1u, std::multiplies<size_t>());
if (m_linearized_image_size != static_cast<size_t>(m_image_width*m_image_height)) {
if ((m_image_width == 0u) && (m_image_height == 0u)) {
m_image_height = 1;
m_image_width = static_cast<int>(m_linearized_image_size);
} else {
std::stringstream err;
err << __FILE__<<" "<<__LINE__
<< " :: data_reader_jag::set_linearized_image_size() image size mismatch";
throw lbann_exception(err.str());
}
}
}
}
void data_reader_jag::set_linearized_scalar_size() {
if (!m_scalar_loaded) {
m_linearized_scalar_size = 0u;
} else {
m_linearized_scalar_size
= std::accumulate(m_scalars.shape.begin()+1, m_scalars.shape.end(),
1u, std::multiplies<size_t>());
}
}
void data_reader_jag::set_linearized_input_size() {
if (!m_input_loaded) {
m_linearized_input_size = 0u;
} else {
m_linearized_input_size
= std::accumulate(m_inputs.shape.begin()+1, m_inputs.shape.end(),
1u, std::multiplies<size_t>());
}
}
size_t data_reader_jag::get_linearized_size(const data_reader_jag::variable_t t) const {
switch (t) {
case JAG_Image:
return m_linearized_image_size;
case JAG_Scalar:
return m_linearized_scalar_size;
case JAG_Input:
return m_linearized_input_size;
default: { // includes Undefined case
throw lbann_exception(std::string("data_reader_jag::get_linearized_size() : ") +
"unknown or undefined variable type");
}
}
return 0u;
}
int data_reader_jag::get_linearized_data_size() const {
size_t sz = 0u;
for (const auto t: m_independent) {
if (t == Undefined) {
continue;
}
sz += get_linearized_size(t);
}
return static_cast<int>(sz);
}
int data_reader_jag::get_linearized_response_size() const {
size_t sz = 0u;
for (const auto t: m_dependent) {
if (t == Undefined) {
continue;
}
sz += get_linearized_size(t);
}
return static_cast<int>(sz);
}
std::vector<size_t> data_reader_jag::get_linearized_data_sizes() const {
std::vector<size_t> all_dim;
all_dim.reserve(m_independent.size());
for (const auto t: m_independent) {
if (t == Undefined) {
continue;
}
all_dim.push_back(get_linearized_size(t));
}
return all_dim;
}
std::vector<size_t> data_reader_jag::get_linearized_response_sizes() const {
std::vector<size_t> all_dim;
all_dim.reserve(m_dependent.size());
for (const auto t: m_dependent) {
if (t == Undefined) {
continue;
}
all_dim.push_back(get_linearized_size(t));
}
return all_dim;
}
const std::vector<int> data_reader_jag::get_dims(const data_reader_jag::variable_t t) const {
switch (t) {
case JAG_Image:
return {1, m_image_height, m_image_width};
//return {static_cast<int>(m_linearized_image_size)};
case JAG_Scalar:
return {static_cast<int>(m_linearized_scalar_size)};
case JAG_Input:
return {static_cast<int>(m_linearized_input_size)};
default: {
throw lbann_exception(std::string("data_reader_jag::get_dims() : ") +
"unknown or undefined variable type");
}
}
return {};
}
const std::vector<int> data_reader_jag::get_data_dims() const {
std::vector<int> all_dim;
for (const auto t: m_independent) {
if (t == Undefined) {
continue;
}
const std::vector<int> ld = get_dims(t);
all_dim.insert(all_dim.end(), ld.begin(), ld.end());
}
return all_dim;
}
void data_reader_jag::load() {
if (m_gan_labelling) {
m_num_labels=2;
}
if (is_master()) {
std::cout << "JAG load GAN m_gan_labelling : label_value "
<< m_gan_labelling <<" : " << m_gan_label_value << std::endl;
}
const std::string data_dir = add_delimiter(get_file_dir());
const std::string namestr = get_data_filename();
std::vector<std::string> file_names = get_tokens(namestr);
if (file_names.size() != 3u) {
throw lbann_exception(
std::string{} + __FILE__ + " " + std::to_string(__LINE__) +
" :: unexpected number of files " + std::to_string(file_names.size()));
}
for(auto& str : file_names) {
str = data_dir + str;
}
load(file_names[0], file_names[1], file_names[2], m_first_n);
size_t num_samples = get_num_samples();
if (m_first_n > 0) {
num_samples = (static_cast<size_t>(m_first_n) <= num_samples)?
static_cast<size_t>(m_first_n) : num_samples;
m_first_n = num_samples;
set_use_percent(1.0);
set_absolute_sample_count(0u);
}
// reset indices
m_shuffled_indices.clear();
m_shuffled_indices.resize(num_samples);
std::iota(m_shuffled_indices.begin(), m_shuffled_indices.end(), 0);
select_subset_of_data();
}
void data_reader_jag::load(const std::string image_file,
const std::string scalar_file,
const std::string input_file,
const size_t first_n) {
if ((m_independent.empty() || (m_independent[0] == Undefined)) &&
!m_dependent.empty() && (m_dependent[0] == Undefined)) {
throw lbann_exception("data_reader_jag: no type of variables to load is defined.");
}
if (is_used(JAG_Image) && !image_file.empty() && !check_if_file_exists(image_file)) {
throw lbann_exception("data_reader_jag: failed to load " + image_file);
}
if (is_used(JAG_Scalar) && !scalar_file.empty() && !check_if_file_exists(scalar_file)) {
throw lbann_exception("data_reader_jag: failed to load " + scalar_file);
}
if (is_used(JAG_Input) && !input_file.empty() && !check_if_file_exists(input_file)) {
throw lbann_exception("data_reader_jag: failed to load " + input_file);
}
m_num_samples = 0u;
// read in only those that will be used
if (is_used(JAG_Image) && !image_file.empty()) {
m_images = cnpy::npy_load(image_file);
if (first_n > 0u) { // to use only first_n samples
cnpy_utils::shrink_to_fit(m_images, first_n);
}
m_image_loaded = true;
set_linearized_image_size();
}
if (is_used(JAG_Scalar) && !scalar_file.empty()) {
m_scalars = cnpy::npy_load(scalar_file);
if (first_n > 0u) { // to use only first_n samples
cnpy_utils::shrink_to_fit(m_scalars, first_n);
}
m_scalar_loaded = true;
set_linearized_scalar_size();
}
if (is_used(JAG_Input) && !input_file.empty()) {
m_inputs = cnpy::npy_load(input_file);
if (first_n > 0u) { // to use only first_n samples
cnpy_utils::shrink_to_fit(m_inputs, first_n);
}
m_input_loaded = true;
set_linearized_input_size();
}
size_t num_samples = 0u;
bool ok = check_data(num_samples);
if (!ok) {
get_description();
throw lbann_exception("data_reader_jag: loaded data format not consistent");
}
m_num_samples = num_samples;
if (m_image_loaded) {
m_img_min = get_image_min();
m_img_max = get_image_max();
if (m_img_min == m_img_max) {
throw lbann_exception("data_reader_jag: no_variation in data");
}
normalize_image();
}
}
bool data_reader_jag::check_data(size_t& num_samples) const {
bool ok = true;
num_samples = 0u;
if (ok && m_image_loaded) {
ok = (m_linearized_image_size > 0u) && (m_images.word_size == sizeof(data_t));
if (!ok) {
std::cerr << "m_images.shape.size() = " << m_images.shape.size() << std::endl
<< "m_linearized_image_size = " << m_linearized_image_size << std::endl
<< "m_images.word_size = " << m_images.word_size << std::endl
<< "sizeof(data_t) = " << sizeof(data_t) << std::endl;
return false;
}
num_samples = m_images.shape[0];
}
if (ok && m_scalar_loaded) {
ok = (m_linearized_scalar_size > 0u) && (m_scalars.word_size == sizeof(scalar_t));
if (!ok) {
std::cerr << "m_scalars.shape.size() = " << m_scalars.shape.size() << std::endl
<< "m_linearized_scalar_size = " << m_linearized_scalar_size << std::endl
<< "m_scalars.word_size = " << m_scalars.word_size << std::endl
<< "sizeof(scalar_t) = " << sizeof(scalar_t) << std::endl;
return false;
}
if (num_samples > 0u) {
ok = ok && (num_samples == m_scalars.shape[0]);
} else {
num_samples = m_scalars.shape[0];
}
}
if (ok && m_input_loaded) {
ok = (m_linearized_input_size > 0u) && (m_inputs.word_size == sizeof(input_t));
if (!ok) {
std::cerr << "m_inputs.shape.size() = " << m_inputs.shape.size() << std::endl
<< "m_linearized_input_size = " << m_linearized_input_size << std::endl
<< "m_inputs.word_size = " << m_inputs.word_size << std::endl
<< "sizeof(input_t) = " << sizeof(input_t) << std::endl;
return false;
}
if (num_samples > 0u) {
ok = ok && (num_samples == m_inputs.shape[0]);
} else {
num_samples = m_inputs.shape[0];
}
}
if (!ok) {
num_samples = 0u;
} else {
if (is_used(JAG_Image)) {
ok = ok && m_image_loaded;
}
if (is_used(JAG_Scalar)) {
ok = ok && m_scalar_loaded;
}
if (is_used(JAG_Input)) {
ok = ok && m_input_loaded;
}
}
return ok;
}
std::string data_reader_jag::get_description() const {
using std::string;
using std::to_string;
string ret = string("data_reader_jag:\n")
+ " - images: " + cnpy_utils::show_shape(m_images) + "\n"
+ " - scalars: " + cnpy_utils::show_shape(m_scalars) + "\n"
+ " - inputs: " + cnpy_utils::show_shape(m_inputs) + "\n";
if (m_image_loaded) {
ret += " - min pixel value: " + to_string(m_img_min) + "\n"
+ " - max pixel value: " + to_string(m_img_max) + "\n"
+ " - image width " + to_string(m_image_width) + "\n"
+ " - image height " + to_string(m_image_height) + "\n"
+ " - image normalization: " + to_string(m_image_normalization) + "\n";
}
return ret;
}
void data_reader_jag::normalize_image() {
if (!m_image_loaded) {
return;
}
const int type_code = CV_MAKETYPE(cv::DataType<data_t>::depth, 1u);
if (m_image_normalization == 1) {
data_t* const ptr = get_image_ptr(0);
// Present the entire image data as a single image
// and normalize it once and for all
cv::Mat img(m_num_samples, m_linearized_image_size,
type_code, reinterpret_cast<void*>(ptr));
cv::normalize(img, img, 0.0, 1.0, cv::NORM_MINMAX);
} else if (m_image_normalization == 2) {
// normalize each image independently
for (size_t i=0u; i < m_num_samples; ++i) {
data_t* const ptr = get_image_ptr(i);
cv::Mat img(1, m_linearized_image_size,
type_code, reinterpret_cast<void*>(ptr));
cv::normalize(img, img, 0.0, 1.0, cv::NORM_MINMAX);
}
} else if (m_image_normalization != 0) {
throw lbann_exception("data_reader_jag: invalid normalization mode " +
std::to_string(m_image_normalization));
}
}
data_reader_jag::data_t* data_reader_jag::get_image_ptr(const size_t i) const {
return (m_image_loaded? cnpy_utils::data_ptr<data_t>(m_images, {i}) : nullptr);
}
data_reader_jag::data_t data_reader_jag::get_image_max() const {
if (!m_image_loaded) {
return std::numeric_limits<data_t>::min();
}
const data_t* ptr = get_image_ptr(0);
const size_t tot_num_pixels = m_images.shape[0]*m_linearized_image_size;
return *std::max_element(ptr, ptr + tot_num_pixels);
}
data_reader_jag::data_t data_reader_jag::get_image_min() const {
if (!m_image_loaded) {
return std::numeric_limits<data_t>::max();
}
const data_t* ptr = get_image_ptr(0);
const size_t tot_num_pixels = m_images.shape[0]*m_linearized_image_size;
return *std::min_element(ptr, ptr + tot_num_pixels);
}
data_reader_jag::scalar_t* data_reader_jag::get_scalar_ptr(const size_t i) const {
return (m_scalar_loaded? cnpy_utils::data_ptr<scalar_t>(m_scalars, {i}) : nullptr);
}
std::vector<DataType> data_reader_jag::get_scalar(const size_t i) const {
const scalar_t* const ptr = get_scalar_ptr(i);
if (ptr == nullptr) {
return {};
}
std::vector<DataType> ret(m_linearized_scalar_size);
for (size_t j = 0u; j < m_linearized_scalar_size; ++j) {
ret[j] = static_cast<DataType>(ptr[j]);
}
return ret;
}
data_reader_jag::input_t* data_reader_jag::get_input_ptr(const size_t i) const {
return (m_input_loaded? cnpy_utils::data_ptr<input_t>(m_inputs, {i}) : nullptr);
}
std::vector<DataType> data_reader_jag::get_input(const size_t i) const {
const input_t* const ptr = get_input_ptr(i);
if (ptr == nullptr) {
return {};
}
std::vector<DataType> ret(m_linearized_input_size);
for (size_t j = 0u; j < m_linearized_input_size; ++j) {
ret[j] = static_cast<DataType>(ptr[j]);
}
return ret;
}
std::vector<CPUMat>
data_reader_jag::create_datum_views(CPUMat& X, const std::vector<size_t>& sizes, const int mb_idx) const {
std::vector<CPUMat> X_v(sizes.size());
El::Int h = 0;
for(size_t i=0u; i < sizes.size(); ++i) {
const El::Int h_end = h + static_cast<El::Int>(sizes[i]);
El::View(X_v[i], X, El::IR(h, h_end), El::IR(mb_idx, mb_idx + 1));
h = h_end;
}
return X_v;
}
bool data_reader_jag::fetch(CPUMat& X, int data_id, int mb_idx,
const data_reader_jag::variable_t vt, const std::string tag) {
switch (vt) {
case JAG_Image: {
const data_t* ptr = get_image_ptr(data_id);
set_minibatch_item<data_t>(X, mb_idx, ptr, m_linearized_image_size);
break;
}
case JAG_Scalar: {
const scalar_t* ptr = get_scalar_ptr(data_id);
set_minibatch_item<scalar_t>(X, mb_idx, ptr, m_linearized_scalar_size);
break;
}
case JAG_Input: {
const input_t* ptr = get_input_ptr(data_id);
set_minibatch_item<input_t>(X, mb_idx, ptr, m_linearized_input_size);
break;
}
default: { // includes Undefined case
throw lbann_exception(std::string("data_reader_jag::fetch_") + tag +
"() : unknown or undefined variable type (" +
std::to_string(static_cast<int>(vt)) + ')');
}
}
return true;
}
bool data_reader_jag::fetch_datum(CPUMat& X, int data_id, int mb_idx) {
std::vector<size_t> sizes = get_linearized_data_sizes();
std::vector<CPUMat> X_v = create_datum_views(X, sizes, mb_idx);
bool ok = true;
for(size_t i = 0u; ok && (i < X_v.size()); ++i) {
ok = fetch(X_v[i], data_id, 0, m_independent[i], "datum");
}
return ok;
}
bool data_reader_jag::fetch_response(CPUMat& X, int data_id, int mb_idx) {
std::vector<size_t> sizes = get_linearized_response_sizes();
std::vector<CPUMat> X_v = create_datum_views(X, sizes, mb_idx);
bool ok = true;
for(size_t i = 0u; ok && (i < X_v.size()); ++i) {
ok = fetch(X_v[i], data_id, 0, m_dependent[i], "response");
}
return ok;
}
bool data_reader_jag::fetch_label(CPUMat& Y, int data_id, int mb_idx) {
if(m_gan_label_value) Y.Set(m_gan_label_value,mb_idx,1); //fake sample is set to 1; adversarial model
else { //fake sample (second half of minibatch is set to 0;discriminator model
//mb_idx < (m_mb_size/2) ? Y.Set(1,mb_idx,1) : Y.Set(m_gan_label_value,mb_idx,1);
mb_idx < (get_current_mini_batch_size()/2) ? Y.Set(1,mb_idx,1) : Y.Set(m_gan_label_value,mb_idx,1);
}
//Y.Set(m_gan_label_value, mb_idx, 1);
return true;
}
} // end of namespace lbann
| 32.88354 | 106 | 0.65727 | forsyth2 |
d1d3766a022f7d18781d9b3036b3993f6c158480 | 966 | cpp | C++ | HPC2/Parralel_bubblesort.cpp | vaibhav-k3/HPC-Assignments | bac3c3f9db813853bab0532c9a9689471c684653 | [
"MIT"
] | 1 | 2020-01-11T17:48:03.000Z | 2020-01-11T17:48:03.000Z | HPC2/Parralel_bubblesort.cpp | Gr3yH4t-H4cK3r/HPC-Assignments | bac3c3f9db813853bab0532c9a9689471c684653 | [
"MIT"
] | null | null | null | HPC2/Parralel_bubblesort.cpp | Gr3yH4t-H4cK3r/HPC-Assignments | bac3c3f9db813853bab0532c9a9689471c684653 | [
"MIT"
] | null | null | null | #include<iostream>
#include<omp.h>
#include<stdlib.h>
#define MAX 50
using namespace std ;
void disp( int* a )
{
for(int i = 0 ; i < MAX ; i++)
{
cout<<a[i]<<" " ;
}
cout<<"\n";
}
void bubblesort( int* a)
{ int temp = 0;
for(int i = 0 ; i < MAX ; i++)
{
for(int j = 0 ; j < MAX -1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j+1] ;
a[j+1] = a[j];
a[j] = temp ;
}
}
}
}
void oddeven_bubblesort(int* a)
{
for(int i = 0 ; i < MAX ; i++)
{
//odd phase
//#pragma omp parallel for
for(int j = 1 ; j < MAX-1 ; j+=2)
{
if(a[j] > a[j+1])
{
swap(a[j] , a[j+1]);
}
}
//even phase
//#pragma omp parallel for
for(int k = 0 ; k < MAX -1 ; k+=2)
{
if(a[k] > a[k+1])
{
swap(a[k] , a[k+1]);
}
}
}
}
int main()
{
int a[50];
for(int i = 0 ; i < MAX ; i++)
{
a[i] = rand()%1000;
}
cout<<" before sorting "<<endl;
disp(a);
oddeven_bubblesort(a);
cout<<"after sorting " <<endl;
disp(a);
}
| 14 | 36 | 0.461698 | vaibhav-k3 |
d1d954e5d399c4b7106942fb58fed05c74063373 | 4,330 | cpp | C++ | KeepCryingEngine/json_serializer.cpp | KeepCryingEngine/KeepCryingEngine | c2e3f89eb5c3d70916f97b7a04cfbab033553b04 | [
"MIT"
] | 1 | 2018-01-11T20:05:29.000Z | 2018-01-11T20:05:29.000Z | KeepCryingEngine/json_serializer.cpp | KeepCryingEngine/KeepCryingEngine | c2e3f89eb5c3d70916f97b7a04cfbab033553b04 | [
"MIT"
] | 28 | 2018-01-17T21:04:33.000Z | 2018-03-02T13:26:17.000Z | KeepCryingEngine/json_serializer.cpp | PereViader/KeepCryingEngine | c2e3f89eb5c3d70916f97b7a04cfbab033553b04 | [
"MIT"
] | 1 | 2020-01-12T02:28:04.000Z | 2020-01-12T02:28:04.000Z | #include "json_serializer.h"
using nlohmann::json;
using namespace std;
void to_json(nlohmann::json & j, const float2 & v)
{
j = json{ { "x", v.x },{ "y", v.y } };
}
void from_json(const nlohmann::json & j, float2 & v)
{
v.x = j.at("x").get<float>();
v.y = j.at("y").get<float>();
}
void to_json(json& j, const float3& v)
{
j = json{ { "x", v.x },{ "y", v.y },{ "z", v.z } };
}
void from_json(const json& j, float3& v)
{
v.x = j.at("x").get<float>();
v.y = j.at("y").get<float>();
v.z = j.at("z").get<float>();
}
void to_json(nlohmann::json& j, const float4& v)
{
j = json{ { "x", v.x },{ "y", v.y },{ "z", v.z },{ "w", v.w } };
}
void from_json(const nlohmann::json& j, float4& v)
{
v.x = j.at("x").get<float>();
v.y = j.at("y").get<float>();
v.z = j.at("z").get<float>();
v.w = j.at("w").get<float>();
}
void to_json(nlohmann::json& j, const Quat& v)
{
j = json{ { "x", v.x },{ "y", v.y },{ "z", v.z },{ "w", v.w } };
}
void from_json(const nlohmann::json& j, Quat& v)
{
v.x = j.at("x").get<float>();
v.y = j.at("y").get<float>();
v.z = j.at("z").get<float>();
v.w = j.at("w").get<float>();
}
void to_json(nlohmann::json& j, const Frustum& v)
{
nlohmann::json jsonPos;
to_json(jsonPos, v.pos);
nlohmann::json jsonUp;
to_json(jsonUp, v.up);
nlohmann::json jsonFront;
to_json(jsonFront, v.front);
j = json
{
{ "pos", jsonPos },
{ "type", v.type },
{ "up", jsonUp },
{ "front", jsonFront },
{ "verticalFov", v.verticalFov },
{ "horizontalFov", v.horizontalFov },
{ "farPlaneDistance", v.farPlaneDistance },
{ "nearPlaneDistance", v.nearPlaneDistance },
{ "orthographicWidth", v.orthographicWidth },
{ "orthographicHeight", v.orthographicHeight }
};
}
void from_json(const nlohmann::json& j, Frustum& v)
{
float3 pos;
from_json(j["pos"], pos);
float3 up;
from_json(j["up"], up);
float3 front;
from_json(j["front"], front);
v.pos = pos;
v.type = j["type"];
v.up = up;
v.front = front;
v.verticalFov = j["verticalFov"];
v.horizontalFov = j["horizontalFov"];
v.farPlaneDistance = j["farPlaneDistance"];
v.nearPlaneDistance = j["nearPlaneDistance"];
v.orthographicWidth = j["orthographicWidth"];
v.orthographicHeight = j["orthographicHeight"];
}
void to_json(nlohmann::json& j, const BASS_DX8_I3DL2REVERB& v)
{
j = json
{
{ "lRoom", v.lRoom },
{ "flRoomRolloffFactor", v.flRoomRolloffFactor },
{ "flDecayTime", v.flDecayTime },
{ "flDecayHFRatio", v.flDecayHFRatio },
{ "lReflections", v.lReflections },
{ "flReflectionsDelay", v.flReflectionsDelay },
{ "lReverb", v.lReverb },
{ "flReverbDelay", v.flReverbDelay },
{ "flDiffusion", v.flDiffusion },
{ "flDensity", v.flDensity },
{ "flHFReference", v.flHFReference }
};
}
void from_json(const nlohmann::json& j, BASS_DX8_I3DL2REVERB& v)
{
v.lRoom = j["lRoom"];
v.flRoomRolloffFactor = j["flRoomRolloffFactor"];
v.flDecayTime = j["flDecayTime"];
v.flDecayHFRatio = j["flDecayHFRatio"];
v.lReflections = j["lReflections"];
v.flReflectionsDelay = j["flReflectionsDelay"];
v.lReverb = j["lReverb"];
v.flReverbDelay = j["flReverbDelay"];
v.flDiffusion = j["flDiffusion"];
v.flDensity = j["flDensity"];
v.flHFReference = j["flHFReference"];
}
void to_json(nlohmann::json & j, const ENGINE_UUID & v)
{
j["id"] = v.id;
}
void from_json(const nlohmann::json & j, ENGINE_UUID & v)
{
v.id = j["id"];
}
void to_json(nlohmann::json & j, const TextureConfiguration & v)
{
j["anisotropicFilter"] = v.anisotropicFilter;
j["magFilterMode"] = v.magFilterMode;
j["minFilterMode"] = v.minFilterMode;
j["mipMap"] = v.mipMap;
j["textureType"] = v.textureType;
j["wrapModeS"] = v.wrapModeS;
j["wrapModeT"] = v.wrapModeT;
}
void from_json(const nlohmann::json & j, TextureConfiguration & v)
{
v.anisotropicFilter = j["anisotropicFilter"];
v.magFilterMode = j["magFilterMode"];
v.minFilterMode = j["minFilterMode"];
v.mipMap = j["mipMap"];
v.textureType = j["textureType"];
v.wrapModeS = j["wrapModeS"];
v.wrapModeT = j["wrapModeT"];
}
void to_json(nlohmann::json & j, const AudioClipIdentifier & v)
{
j["path"] = v.path.string();
j["audioType"] = v.audioType;
j["channelType"] = v.channelType;
}
void from_json(const nlohmann::json & j, AudioClipIdentifier & v)
{
v.path = j["path"].get<string>();
v.audioType = j["audioType"];
v.channelType = j["channelType"];
}
| 23.661202 | 66 | 0.631871 | KeepCryingEngine |
d1d9b8abca81320a7b03a1829f1f27462fe73566 | 13,654 | cpp | C++ | src/solver/conv_ocl_dir2D_bwdWrW_53.cpp | sabreshao/MIOpen | d0ae7a67430e77e30ab10066ff079327e53e1349 | [
"MIT"
] | null | null | null | src/solver/conv_ocl_dir2D_bwdWrW_53.cpp | sabreshao/MIOpen | d0ae7a67430e77e30ab10066ff079327e53e1349 | [
"MIT"
] | null | null | null | src/solver/conv_ocl_dir2D_bwdWrW_53.cpp | sabreshao/MIOpen | d0ae7a67430e77e30ab10066ff079327e53e1349 | [
"MIT"
] | null | null | null | /*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include "miopen/solver.hpp"
#include <miopen/env.hpp>
MIOPEN_DECLARE_ENV_VAR(MIOPEN_WORKAROUND_ISSUE_1007)
namespace miopen {
namespace solver {
bool ConvOclBwdWrW53::IsApplicable(const ConvolutionContext& params) const
{
// Cases when dy has negative padding are not supported (issue 918)
if(params.GetBackwardPad0() < 0 || params.GetBackwardPad1() < 0)
return false;
/// \todo Workaround for issue 1007, seems related to the next ones.
if(!miopen::IsDisabled(MIOPEN_WORKAROUND_ISSUE_1007{}) && params.kernel_size0 == 3 &&
(static_cast<double>(params.batch_sz) * params.out_height * params.out_width *
params.n_outputs * params.n_inputs) > 700000000)
return false;
/// \todo Workaround for some issues. Excludes some configs which covered by
/// the ConvOclBwdWrW2 solver. Found experimentally. Technically, this is a hack.
/// The kernel needs to be well understood and fixed.
if((params.kernel_size0 > 5) || (params.kernel_size0 == 5 && params.in_width >= 64))
return false;
/// \todo Workaround for issue #791. Found experimentally. Technically, this is a hack.
/// The kernel needs to be well understood and fixed.
if((params.kernel_size0 == 3 && params.pad0 == 0 && params.out_width >= 32))
return false;
return ((params.kernel_size0 >= 2 || params.kernel_size1 >= 2) &&
(params.kernel_stride1 == 1 && params.kernel_stride0 == 1));
}
ConvSolution ConvOclBwdWrW53::GetSolution(const ConvolutionContext& params) const
{
ConvSolution result;
size_t localMemSize = 64 * 1024;
const auto hw_wave_sz = 64;
const auto dev_local_mem_sz = localMemSize; // in bytes
// major parameters
// inpout are outputs
int wei_cstride = params.kernel_size0 * params.kernel_size1;
int wei_bstride = params.n_outputs * wei_cstride;
// number of batch iterations
result.n_stacks = 1;
result.n_stacks = std::min(params.batch_sz, result.n_stacks);
// defines how to proceed : 1 grouop per batch or with a loop over all batches
// loop over al batches make sense in 2 cases: a lot of small inputs/outputs or few batches
// param
int N_BATCH_LOOPS = (params.n_inputs * params.n_outputs <= 8 * 1024)
? 1
: (params.batch_sz <= 16 || params.in_width <= 32)
? (params.batch_sz / result.n_stacks)
: 4;
int n_batch_blks =
(params.batch_sz + N_BATCH_LOOPS * result.n_stacks - 1) / (N_BATCH_LOOPS * result.n_stacks);
result.out_pix_tile0 = params.kernel_size0;
result.out_pix_tile1 = params.kernel_size1;
result.in_tile1 = 1;
// span size
// param
result.in_tile0 = (params.in_width % 4 == 0) ? 4 : (params.in_width % 3 == 0)
? 3
: (params.in_width % 2 == 0) ? 2 : 1;
int n_spans = (params.in_width + result.in_tile0 - 1) / result.in_tile0;
// n of wavefronts per group
// param
int n_waves = ((result.out_pix_tile0 * result.out_pix_tile1) <= 16 && (params.in_width > 8))
? 4
: (params.in_width <= 16) ? 1 : 2;
int GRP_SZ = hw_wave_sz * n_waves;
result.n_out_pix_tiles = 1;
int n_out_stacks = std::min(params.n_inputs, std::max(1, GRP_SZ / n_spans));
// number of input maps per group
result.n_in_data_tiles =
(params.in_width <= 32 && (result.out_pix_tile0 * result.out_pix_tile1) <= 16) ? 4 : 1;
result.n_in_data_tiles = std::min(result.n_in_data_tiles, params.n_outputs);
static const int read_unit =
(params.out_width % 4 == 0) ? 4 : (params.out_width % 3 == 0)
? 3
: (params.out_width % 2 == 0) ? 2 : 1;
static const std::string READ_TYPE =
(read_unit == 1) ? "_FLOAT" : "_FLOAT" + std::to_string((read_unit));
// calculate number of input scans in the input block
// max LDS size is 8K
int in_lcl_width =
((params.in_width + read_unit - 1) / read_unit) * read_unit + 2 * params.pad0;
// number of input map blocks being process at once
// param
int in_n_vert_reads = (params.out_height > 32 && params.out_width <= 64 &&
(result.out_pix_tile0 * result.out_pix_tile1) <= 16)
? (params.out_height + 1) / 2
: params.out_height;
while(in_lcl_width * in_n_vert_reads * result.n_in_data_tiles >
(dev_local_mem_sz / (2 * ((params.in_data_type == "FP32") ? 4 : 2))))
{
in_n_vert_reads = (in_n_vert_reads + 1) / 2;
if(in_n_vert_reads < 2 && result.n_in_data_tiles >= 2)
{
in_n_vert_reads = params.in_height;
result.n_in_data_tiles /= 2;
}
else if(in_n_vert_reads < 2)
{
MIOPEN_LOG_E("Not enough local memory to run direct algorithm");
return ConvSolution(miopenStatusUnknownError);
}
}
int in_n_vert_read_loops = (params.in_height + in_n_vert_reads - 1) / in_n_vert_reads;
int ALIGNED_OUT_SCAN_LN = ((params.in_width + read_unit - 1) / read_unit); // image aligned scan
// select output mapping
int total_out_maps = result.n_out_pix_tiles * n_out_stacks;
total_out_maps = (total_out_maps > params.n_inputs) ? params.n_inputs : total_out_maps;
result.grp_tile0 = GRP_SZ;
result.grp_tile1 = 1;
int grp_tile2 = 1;
// utility parameters
int n_ut_waves = 4;
int UT_GRP_SZ0 = hw_wave_sz * n_ut_waves;
int ut_read_unit =
((wei_cstride / 4) * 4 == wei_cstride) ? 4 : ((wei_cstride / 2) * 2 == wei_cstride) ? 2 : 1;
std::string UT_READ_TYPE =
(ut_read_unit == 1) ? "_FLOAT" : "_FLOAT" + std::to_string((ut_read_unit));
if(!params.direction.IsBackwardWrW())
MIOPEN_THROW("!params.direction.IsBackwardWrW()");
// it's backward - inputs are outputs and vs versa
const auto comp_options =
std::string(" -DMLO_DIR_FORWARD=0") + std::string(" -DMLO_GRP_SZ=") +
std::to_string(GRP_SZ) + std::string(" -DMLO_GRP_SZ0=") + std::to_string(result.grp_tile0) +
std::string(" -DMLO_GRP_SZ1=") + std::to_string(result.grp_tile1) +
std::string(" -DMLO_GRP_SZ2=") + std::to_string(grp_tile2) +
std::string(" -DMLO_FILTER_SIZE0=") + std::to_string(params.kernel_size0) +
std::string(" -DMLO_FILTER_SIZE1=") + std::to_string(params.kernel_size1) +
std::string(" -DMLO_FILTER_PAD0=") + std::to_string(params.pad0) +
std::string(" -DMLO_FILTER_PAD1=") + std::to_string(params.pad1) +
std::string(" -DMLO_FILTER_STRIDE0=") + std::to_string(params.kernel_stride0) +
std::string(" -DMLO_FILTER_STRIDE1=") + std::to_string(params.kernel_stride1) +
std::string(" -DSTRIDE_W=") + std::to_string(params.kernel_stride0) +
std::string(" -DSTRIDE_H=") + std::to_string(params.kernel_stride1) +
std::string(" -DMLO_N_OUTPUTS=") + std::to_string(params.n_inputs) +
std::string(" -DMLO_N_INPUTS=") + std::to_string(params.n_outputs) +
std::string(" -DMLO_BATCH_SZ=") + std::to_string(params.batch_sz) +
std::string(" -DMLO_N_BATCH_LOOPS=") + std::to_string(N_BATCH_LOOPS) +
std::string(" -DMLO_OUT_BATCH_STRIDE=") + std::to_string(params.in_batch_stride) +
std::string(" -DMLO_OUT_CHANNEL_STRIDE=") + std::to_string(params.in_channel_stride) +
std::string(" -DMLO_OUT_STRIDE=") + std::to_string(params.in_stride) +
std::string(" -DMLO_IN_BATCH_STRIDE=") + std::to_string(params.out_batch_stride) +
std::string(" -DMLO_IN_CHANNEL_STRIDE=") + std::to_string(params.out_channel_stride) +
std::string(" -DMLO_IN_STRIDE=") + std::to_string(params.out_stride) +
std::string(" -DMLO_WEI_BATCH_STRIDE=") + std::to_string(wei_bstride) +
std::string(" -DMLO_WEI_CHANNEL_STRIDE=") + std::to_string(wei_cstride) +
std::string(" -DMLO_IN_WIDTH=") + std::to_string(params.out_width) +
std::string(" -DMLO_IN_HEIGHT=") + std::to_string(params.out_height) +
std::string(" -DMLO_OUT_WIDTH=") + std::to_string(params.in_width) +
std::string(" -DMLO_OUT_HEIGHT=") + std::to_string(params.in_height) +
std::string(" -DMLO_IN_TILE1=") + std::to_string(result.in_tile1) +
std::string(" -DMLO_IN_TILE0=") + std::to_string(result.in_tile0) +
std::string(" -DMLO_N_LCL_BATCHS=") +
std::to_string(result.n_stacks) // # of diff stacks (part of batch).
+ std::string(" -DMLO_N_LCL_OUT_MAPS=") +
std::to_string(result.n_out_pix_tiles) // # output pixel tiles per wk-item (ALU)
+ std::string(" -DMLO_N_LCL_IN_MAPS=") +
std::to_string(result.n_in_data_tiles) // total # of blocks of different inputs in LDS
+ std::string(" -DMLO_OUT_TILE0=") +
std::to_string(result.out_pix_tile0) // size of ouptput tile per wk-item (ALU)
+ std::string(" -DMLO_OUT_TILE1=") + std::to_string(result.out_pix_tile1) //
+ std::string(" -DMLO_OUT_STACKS=") + std::to_string(n_out_stacks) +
std::string(" -DMLO_N_WAVES=") + std::to_string(n_waves) +
std::string(" -DMLO_READ_TYPE=") + READ_TYPE + std::string(" -DMLO_READ_UNIT=") +
std::to_string(read_unit) + std::string(" -DMLO_ALIGNED_OUT_SCAN_LN=") +
std::to_string(ALIGNED_OUT_SCAN_LN) // image aligned scan
+ std::string(" -DMLO_HW_WAVE_SZ=") + std::to_string(hw_wave_sz) +
std::string(" -DMLO_LG2_PHYS_WAVE_SZ=") + std::to_string(mloLg2(hw_wave_sz)) +
std::string(" -DMLO_IN_EXTENT1=") + std::to_string(in_n_vert_reads) +
std::string(" -DMLO_IN_N_VERT_LOOPS=") + std::to_string(in_n_vert_read_loops)
+ std::string(" -DMLO_CONV_BIAS=") + std::to_string(params.bias)
+ std::string(" -DMLO_UT_READ_TYPE=") + UT_READ_TYPE + std::string(" -DMLO_UT_READ_UNIT=") +
std::to_string(ut_read_unit)
+ std::string(" -DMLO_UT_GRP_SZ0=") + std::to_string(UT_GRP_SZ0)
// + std::string(" -limit-vector-registers=64 ")
+ params.general_compile_options;
// wrt to W
{
KernelInfo kernel;
kernel.l_wk.push_back(result.grp_tile0);
kernel.l_wk.push_back(result.grp_tile1);
kernel.l_wk.push_back(grp_tile2);
// input is output
size_t gbl_wk0 =
GRP_SZ * ((params.n_outputs + result.n_in_data_tiles - 1) / result.n_in_data_tiles);
size_t gbl_wk1 = ((params.n_inputs + total_out_maps - 1) / total_out_maps);
size_t gbl_wk2 = n_batch_blks;
kernel.g_wk.push_back(gbl_wk0);
kernel.g_wk.push_back(gbl_wk1);
kernel.g_wk.push_back(gbl_wk2);
kernel.kernel_file =
(params.kernel_size0 == 5 && params.kernel_size1 == 5 && in_n_vert_read_loops == 1)
? "MIOpenConvBwdWrW_LxG_5x5.cl"
: "MIOpenConvBwdWrW_LxG_P53.cl";
kernel.kernel_name = "MIOpenCvBwdWrW";
kernel.comp_options = comp_options;
result.construction_params.push_back(kernel);
result.workspce_sz = 0;
}
// sum over batch
if(n_batch_blks > 1)
{
KernelInfo kernel;
kernel.kernel_file =
(params.kernel_size0 == 5 && params.kernel_size1 == 5 && in_n_vert_read_loops == 1)
? "MIOpenConvBwdWrW_LxG_5x5.cl"
: "MIOpenConvBwdWrW_LxG_P53.cl";
kernel.kernel_name = "MIOpenCvBwdWrW_rdc";
kernel.comp_options = comp_options;
kernel.l_wk.push_back(UT_GRP_SZ0);
kernel.l_wk.push_back(1);
kernel.l_wk.push_back(1);
int gbl_ut_wk0 = wei_bstride * params.n_inputs / ut_read_unit;
kernel.g_wk.push_back(gbl_ut_wk0);
kernel.g_wk.push_back(1);
kernel.g_wk.push_back(1);
int data_len = (params.out_data_type == "FP32" ? 4 : 8);
result.construction_params.push_back(kernel);
result.workspce_sz = wei_bstride * params.n_inputs * n_batch_blks * data_len;
}
return result;
}
} // namespace solver
} // namespace miopen
| 47.245675 | 100 | 0.625238 | sabreshao |
d1de3c9d15e584f0c2aaab8cbe10cb7f0c9eb496 | 536 | cpp | C++ | filip/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | filip/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | filip/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int a, b, tmpmod, tmpnum = 0;
cin >> a >> b;
for(int i = 0; i < 3; i++){
tmpmod = a%10;
a/=10;
tmpnum += tmpmod;
if(i < 2){
tmpnum*=10;}}
a = tmpnum; tmpnum = 0;
for(int i = 0; i < 3; i++){
tmpmod = b%10;
b/=10;
tmpnum += tmpmod;
if(i < 2){
tmpnum*=10;}}
b = tmpnum;
if(b>a){
cout << b << endl;
} else{
cout << a << endl;
}
return 0;
} | 18.482759 | 33 | 0.391791 | KalawelaLo |
d1e2c89b22dcdf969880423e8b18d25890fc146f | 7,454 | cpp | C++ | samples/Hello/third-party/fuzzylite/fuzzylite/src/term/Aggregated.cpp | okocsis/ios-cmake | ca61d83725bc5b1a755928f4592badbd9a8b37f4 | [
"BSD-3-Clause"
] | null | null | null | samples/Hello/third-party/fuzzylite/fuzzylite/src/term/Aggregated.cpp | okocsis/ios-cmake | ca61d83725bc5b1a755928f4592badbd9a8b37f4 | [
"BSD-3-Clause"
] | null | null | null | samples/Hello/third-party/fuzzylite/fuzzylite/src/term/Aggregated.cpp | okocsis/ios-cmake | ca61d83725bc5b1a755928f4592badbd9a8b37f4 | [
"BSD-3-Clause"
] | null | null | null | /*
fuzzylite (R), a fuzzy logic control library in C++.
Copyright (C) 2010-2017 FuzzyLite Limited. All rights reserved.
Author: Juan Rada-Vilela, Ph.D. <[email protected]>
This file is part of fuzzylite.
fuzzylite is free software: you can redistribute it and/or modify it under
the terms of the FuzzyLite License included with the software.
You should have received a copy of the FuzzyLite License along with
fuzzylite. If not, see <http://www.fuzzylite.com/license/>.
fuzzylite is a registered trademark of FuzzyLite Limited.
*/
#include "fl/term/Aggregated.h"
#include "fl/imex/FllExporter.h"
#include "fl/norm/s/Maximum.h"
namespace fl {
Aggregated::Aggregated(const std::string& name, scalar minimum, scalar maximum,
SNorm* aggregation)
: Term(name), _minimum(minimum), _maximum(maximum), _aggregation(aggregation) { }
Aggregated::Aggregated(const Aggregated& other) : Term(other) {
copyFrom(other);
}
Aggregated& Aggregated::operator=(const Aggregated& other) {
if (this != &other) {
clear();
_aggregation.reset(fl::null);
Term::operator=(other);
copyFrom(other);
}
return *this;
}
Aggregated::~Aggregated() { }
void Aggregated::copyFrom(const Aggregated& source) {
_minimum = source._minimum;
_maximum = source._maximum;
if (source._aggregation.get())
_aggregation.reset(source._aggregation->clone());
for (std::size_t i = 0; i < source._terms.size(); ++i) {
_terms.push_back(source._terms.at(i));
}
}
std::string Aggregated::className() const {
return "Aggregated";
}
Complexity Aggregated::complexity() const {
return complexityOfMembership();
}
Complexity Aggregated::complexityOfMembership() const {
Complexity result;
result.comparison(3);
if (_aggregation.get()) {
result += _aggregation->complexity().multiply(scalar(_terms.size()));
}
for (std::size_t i = 0; i < _terms.size(); ++i) {
result += _terms.at(i).complexity();
}
return result;
}
scalar Aggregated::membership(scalar x) const {
if (Op::isNaN(x)) return fl::nan;
if (not (_terms.empty() or _aggregation.get())) { //Exception for IntegralDefuzzifiers
throw Exception("[aggregation error] "
"aggregation operator needed to aggregate variable "
"<" + getName() + ">", FL_AT);
}
scalar mu = 0.0;
for (std::size_t i = 0; i < _terms.size(); ++i) {
mu = _aggregation->compute(mu, _terms.at(i).membership(x));
}
return mu;
}
Complexity Aggregated::complexityOfActivationDegree() const {
Complexity result;
result.comparison(2);
if (_aggregation.get()) {
result += _aggregation->complexity();
} else result.arithmetic(1);
result.multiply(scalar(_terms.size()));
return result;
}
scalar Aggregated::activationDegree(const Term* forTerm) const {
scalar result = 0.0;
for (std::size_t i = 0; i < _terms.size(); ++i) {
const Activated& activatedTerm = _terms.at(i);
if (activatedTerm.getTerm() == forTerm) {
if (_aggregation.get())
result = _aggregation->compute(result, activatedTerm.getDegree());
else
result += activatedTerm.getDegree(); //Default for WeightDefuzzifier
}
}
return result;
}
const Activated* Aggregated::highestActivatedTerm() const {
const Activated* maximumTerm = fl::null;
scalar maximumActivation = -fl::inf;
for (std::size_t i = 0; i < _terms.size(); ++i) {
const Activated& activated = _terms.at(i);
if (Op::isGt(activated.getDegree(), maximumActivation)) {
maximumActivation = activated.getDegree();
maximumTerm = &activated;
}
}
return maximumTerm;
}
std::string Aggregated::parameters() const {
FllExporter exporter;
std::ostringstream ss;
ss << exporter.toString(getAggregation());
ss << " " << Op::str(getMinimum()) << " " << Op::str(getMaximum()) << " ";
for (std::size_t i = 0; i < terms().size(); ++i) {
ss << " " << exporter.toString(&terms().at(i));
}
return ss.str();
}
void Aggregated::configure(const std::string& parameters) {
FL_IUNUSED(parameters);
}
Aggregated* Aggregated::clone() const {
return new Aggregated(*this);
}
std::string Aggregated::toString() const {
std::vector<std::string> aggregate;
for (std::size_t i = 0; i < terms().size(); ++i) {
aggregate.push_back(terms().at(i).toString());
}
FllExporter exporter;
std::ostringstream ss;
if (getAggregation()) {
ss << getName() << ": " << className() << " "
<< exporter.toString(getAggregation()) << "["
<< Op::join(aggregate, ",") << "]";
} else {
ss << getName() << ": " << className() << " " << "["
<< Op::join(aggregate, "+") << "]"; //\u2295: (+)
}
return ss.str();
}
void Aggregated::setMinimum(scalar minimum) {
this->_minimum = minimum;
}
scalar Aggregated::getMinimum() const {
return this->_minimum;
}
void Aggregated::setMaximum(scalar maximum) {
this->_maximum = maximum;
}
scalar Aggregated::getMaximum() const {
return this->_maximum;
}
void Aggregated::setRange(scalar minimum, scalar maximum) {
setMinimum(minimum);
setMaximum(maximum);
}
scalar Aggregated::range() const {
return getMaximum() - getMinimum();
}
void Aggregated::setAggregation(SNorm* aggregation) {
this->_aggregation.reset(aggregation);
}
SNorm* Aggregated::getAggregation() const {
return this->_aggregation.get();
}
/**
* Operations for std::vector _terms
*/
void Aggregated::addTerm(const Term* term, scalar degree, const TNorm* implication) {
_terms.push_back(Activated(term, degree, implication));
FL_DBG("Aggregating " << _terms.back().toString());
}
void Aggregated::addTerm(const Activated& term) {
_terms.push_back(term);
FL_DBG("Aggregating " << _terms.back().toString());
}
const Activated& Aggregated::removeTerm(std::size_t index) {
const Activated& term = _terms.at(index);
_terms.erase(_terms.begin() + index);
return term;
}
void Aggregated::clear() {
_terms.clear();
}
const Activated& Aggregated::getTerm(std::size_t index) const {
return _terms.at(index);
}
void Aggregated::setTerms(const std::vector<Activated>& terms) {
this->_terms = terms;
}
const std::vector<Activated>& Aggregated::terms() const {
return this->_terms;
}
std::vector<Activated>& Aggregated::terms() {
return this->_terms;
}
std::size_t Aggregated::numberOfTerms() const {
return _terms.size();
}
bool Aggregated::isEmpty() const {
return _terms.empty();
}
}
| 30.056452 | 94 | 0.57553 | okocsis |
d1e3f64fb002a9e33d28d841de937e2f73e025ad | 6,317 | cpp | C++ | src/dialog.cpp | nekoshota/teippi_PronogoMod | 590b59384118b4dc99800260356accf9d484eb63 | [
"MIT"
] | null | null | null | src/dialog.cpp | nekoshota/teippi_PronogoMod | 590b59384118b4dc99800260356accf9d484eb63 | [
"MIT"
] | null | null | null | src/dialog.cpp | nekoshota/teippi_PronogoMod | 590b59384118b4dc99800260356accf9d484eb63 | [
"MIT"
] | null | null | null | #include "dialog.h"
#include "offsets.h"
#include "unit.h"
#include "patchmanager.h"
#include "strings.h"
#include <stdio.h>
#include <vector>
Unit *ui_transported_units[8] = {0, 0, 0, 0, 0, 0, 0, 0};
void TransportStatus_UpdateDrawnValues()
{
Unit *transport = *bw::primary_selected;
int i = 0;
for (Unit *unit = transport->first_loaded; unit; unit = unit->next_loaded, i++)
{
ui_transported_units[i] = unit;
bw::ui_transported_unit_hps[i] = unit->hitpoints;
}
*bw::redraw_transport_ui = Ui_NeedsRedraw_Unk(); // ???
*bw::ui_hitpoints = transport->hitpoints;
*bw::ui_shields = transport->shields >> 8;
*bw::ui_energy = transport->energy;
}
int TransportStatus_DoesNeedRedraw()
{
Unit *transport = *bw::primary_selected;
if (*bw::redraw_transport_ui)
return true;
if (!*bw::is_replay && transport->player != *bw::local_player_id)
return GenericStatus_DoesNeedRedraw();
int i = 0;
for (Unit *unit = transport->first_loaded; unit; unit = unit->next_loaded, i++)
{
if (ui_transported_units[i] != unit)
return true;
if (bw::ui_transported_unit_hps[i] != unit->hitpoints)
return true;
}
return GenericStatus_DoesNeedRedraw();
}
void DrawStatusScreen_LoadedUnits()
{
REG_EAX(Dialog *, dlg);
Unit *transport = *bw::primary_selected;
Control *first_button = dlg->FindChild(StatusScreen::TransportLargeUnit);
Control *large_unit_button, *medium_unit_button, *small_unit_button;
int remaining_space = units_dat_space_provided[transport->unit_id];
if (remaining_space < 8)
{
large_unit_button = dlg->FindChild(StatusScreen::TransportLargeUnit4, first_button);
medium_unit_button = dlg->FindChild(StatusScreen::TransportMediumUnit4, large_unit_button);
small_unit_button = dlg->FindChild(StatusScreen::TransportSmallUnit4, medium_unit_button);
}
else
{
remaining_space = 8;
large_unit_button = first_button;
medium_unit_button = dlg->FindChild(StatusScreen::TransportMediumUnit, large_unit_button);
small_unit_button = dlg->FindChild(StatusScreen::TransportSmallUnit, medium_unit_button);
}
for (Control *ctrl = first_button; ctrl->id != StatusScreen::TransportSmallUnit + 8; ctrl = ctrl->next)
{
ctrl->val = 0;
}
for (Unit *unit = transport->first_loaded; unit; unit = unit->next_loaded)
{
int space = units_dat_space_required[unit->unit_id];
remaining_space -= space;
if (remaining_space < 0)
break;
Control *current_button;
switch (space)
{
case 1:
current_button = small_unit_button;
small_unit_button = small_unit_button->next;
break;
case 2:
current_button = medium_unit_button;
medium_unit_button = medium_unit_button->next;
small_unit_button = small_unit_button->next->next;
break;
case 4:
current_button = large_unit_button;
large_unit_button = large_unit_button->next;
medium_unit_button = medium_unit_button->next->next;
small_unit_button = small_unit_button->next->next->next->next;
break;
default:
current_button = 0;
break;
}
current_button->val = unit;
int border_id;
if (unit->flags & UnitStatus::Hallucination)
border_id = StatusScreen::SmallUnitBorderHallucination + ((space >> 1) * 2);
else if (units_dat_flags[unit->unit_id] & UnitFlags::Hero)
border_id = StatusScreen::SmallUnitBorderHero + ((space >> 1) * 2);
else if (unit->parasites)
border_id = StatusScreen::SmallUnitBorderParasite + ((space >> 1) * 2);
else
border_id = StatusScreen::SmallUnitBorder + ((space >> 1) * 2);
current_button->button_icon = border_id;
current_button->Show();
current_button->MarkDirty();
}
for (Control *ctrl = first_button; ctrl->id != StatusScreen::TransportSmallUnit + 8; ctrl = ctrl->next)
{
if (!ctrl->val)
ctrl->Hide();
}
}
static char ss_kills[0x20];
void StatusScreen_DrawKills()
{
REG_EBX(Dialog *, dlg);
Unit *unit = *bw::primary_selected;
int unit_id = unit->unit_id;
if (unit_id == Unit::Scourge || unit_id == Unit::InfestedTerran || unit->IsKnownHallucination() || (!unit->HasWayOfAttacking() && !unit->kills))
{
dlg->FindChild(StatusScreen::Kills)->Hide();
}
else
{
snprintf(ss_kills, sizeof ss_kills, "%s %d", (*bw::stat_txt_tbl)->GetTblString(String::Kills), unit->kills);
SetLabel(dlg, ss_kills, StatusScreen::Kills);
}
}
void Control::MarkDirty()
{
if (~flags & 0x1)
{
flags |= 0x1;
MarkControlDirty(this);
}
}
void Control::Show()
{
if (flags & 0x8)
return;
flags |= 0x8;
Event event;
event.ext_type = 0xd;
event.type = 0xe;
event.x = *bw::mouse_clickpos_x;
event.y = *bw::mouse_clickpos_y;
event.unk4 = 0;
if ((*EventHandler)(this, &event))
MarkDirty();
}
void Control::Hide()
{
if (~flags & 0x8)
return;
Event event;
event.ext_type = 0xe;
event.type = 0xe;
event.x = *bw::mouse_clickpos_x;
event.y = *bw::mouse_clickpos_y;
event.unk4 = 0;
if ((*EventHandler)(this, &event))
{
event.ext_type = 0x6;
(*EventHandler)(this, &event);
MarkDirty();
}
}
Control *Control::FindChild(int id, Control *search_beg) const
{
if (type == 0)
{
Dialog *dlg = (Dialog *)this;
return dlg->FindChild(id, search_beg);
}
else
return parent->FindChild(id, search_beg);
}
Control *Dialog::FindChild(int id, Control *search_beg) const
{
if (search_beg)
{
for (Control *ctrl = search_beg; ctrl; ctrl = ctrl->next)
{
if (ctrl->id == id)
return ctrl;
}
}
else
{
for (Control *ctrl = dialog.first_child; ctrl; ctrl = ctrl->next)
{
if (ctrl->id == id)
return ctrl;
}
}
return 0;
}
| 29.110599 | 148 | 0.602026 | nekoshota |
d1e4e0970858615269cefb0c00b85547e910b601 | 14,905 | cpp | C++ | src/ui/src/setup/simtab.cpp | Terebinth/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 117 | 2015-01-13T14:48:49.000Z | 2022-03-16T01:38:19.000Z | src/ui/src/setup/simtab.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 4 | 2015-05-01T13:09:53.000Z | 2017-07-22T09:11:06.000Z | src/ui/src/setup/simtab.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 78 | 2015-01-13T09:27:47.000Z | 2022-03-18T14:39:09.000Z | #include "falclib.h"
#include "chandler.h"
#include "userids.h"
#include "PlayerOp.h"
#include "sim/include/stdhdr.h"
#include "ui_setup.h"
#include "f4find.h"
//define presets for skill level list box (first set is ace, then veteran, etc...)
Preset Presets[] =
{
{FMAccurate, ATRealisticAV, WEAccurate, APNormal, ARRealistic, PDRealistic, 0},
{FMAccurate, ATRealistic, WEAccurate, APNormal, ARModerated, PDRealistic, SIM_UNLIMITED_CHAFF},
{FMAccurate, ATSimplified, WEEnhanced, APEnhanced, ARModerated, PDEnhanced, SIM_NO_BLACKOUT bitor SIM_UNLIMITED_CHAFF bitor SIM_NAMETAGS},
{FMSimplified, ATEasy, WEExaggerated, APEnhanced, ARSimplistic, PDEnhanced, SIM_NO_BLACKOUT bitor SIM_UNLIMITED_CHAFF bitor SIM_NAMETAGS bitor SIM_UNLIMITED_FUEL}, //need to put SIM_UNLIMITED_FUEL
{FMSimplified, ATEasy, WEExaggerated, APIntelligent, ARSimplistic, PDEnhanced, SIM_NO_BLACKOUT bitor SIM_UNLIMITED_AMMO bitor SIM_UNLIMITED_CHAFF bitor SIM_NAMETAGS bitor SIM_UNLIMITED_FUEL bitor SIM_NO_COLLISIONS},
//{FMSimplified,ATEasy,WEExaggerated,APIntelligent,ARSimplistic, PDSuper,SIM_NO_BLACKOUT|SIM_UNLIMITED_AMMO|SIM_UNLIMITED_CHAFF|SIM_NAMETAGS|SIM_UNLIMITED_FUEL|SIM_NO_COLLISIONS}, //back into these two after DEMO
};
extern C_Handler *gMainHandler;
/////////////
// Sim Tab
/////////////
int GetRealism(C_Window *win)
{
C_ListBox *listbox;
C_Button *button;
int realism = 100, maxrealism = 100;
if (win == NULL)
return 0;
listbox = (C_ListBox *)win->FindControl(SET_FLTMOD);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
listbox = (C_ListBox *)win->FindControl(SET_RADAR);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
listbox = (C_ListBox *)win->FindControl(SET_WEAPEFF);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
listbox = (C_ListBox *)win->FindControl(SET_AUTOPILOT);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
listbox = (C_ListBox *)win->FindControl(SET_PADLOCK);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
listbox = (C_ListBox *)win->FindControl(SET_REFUELING);
if (listbox not_eq NULL)
{
button = (C_Button *)listbox->GetItem(listbox->GetTextID());
if (button)
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_FUEL);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_CHAFFLARES);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_COLLISIONS);
if (button not_eq NULL)
{
if (button->GetState())
{
// Cobra - 03-08-05 Temp disabled due to unknown cause mid-air collisions
// realism -= button->GetUserNumber(0);
// if(maxrealism > button->GetUserNumber(1))
// maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_BLACKOUT);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_IDTAGS);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_WEATHER);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_BULLSEYE_CALLS);
if (button not_eq NULL)
{
if (button->GetState())
{
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
}
}
button = (C_Button *)win->FindControl(SET_INVULNERABILITY);
if (button not_eq NULL)
{
if (button->GetState())
{
//realism = 0;
realism -= button->GetUserNumber(0);
if (maxrealism > button->GetUserNumber(1))
maxrealism = button->GetUserNumber(1);
//realism *= 0.5f;
}
}
if (realism > maxrealism)
realism = maxrealism ;
if (realism < 0)
realism = 0;
return realism;
}//GetRealism
int SetRealism(C_Window *win)
{
C_Button *button;
C_EditBox *ebox;
C_ListBox *listbox;
int realism = 100, maxrealism = 100;
if (win == NULL)
return 0;
realism = GetRealism(win);
ebox = (C_EditBox *)win->FindControl(REALISM_READOUT);
if (ebox not_eq NULL)
{
if (realism > maxrealism)
realism = maxrealism ;
if (realism < 0)
realism = 0;
ebox->SetInteger(realism);
}
listbox = (C_ListBox *)win->FindControl(SET_SKILL);
if (listbox)
{
listbox->SetValue(RECRUIT_LEVEL);
for (int i = 0; i < NUM_LEVELS; i++)
{
button = (C_Button *)listbox->GetItem(ACE_LEVEL + i);
if (button)
{
if (realism > button->GetUserNumber(0))
{
listbox->SetValue(ACE_LEVEL + i);
break;
}
}
}
}
win->RefreshWindow();
return realism;
}//SetRealism
void SimControlCB(long, short hittype, C_Base *control)
{
if ((hittype not_eq C_TYPE_LMOUSEUP) and (hittype not_eq C_TYPE_SELECT))
return;
SetRealism(control->Parent_);
}
void SetSkillCB(long, short hittype, C_Base *control)
{
if (hittype not_eq C_TYPE_SELECT)
return;
int Index;
C_Button *button;
C_Window *win;
C_ListBox *lbox;
win = (C_Window *)control->Parent_;
Index = ((C_ListBox *)control)->GetTextID() - ACE_LEVEL;
lbox = (C_ListBox *)win->FindControl(SET_FLTMOD);
if (lbox not_eq NULL)
{
if (Presets[Index].FlightModel == FMAccurate)
lbox->SetValue(SET_FLTMOD_1);
else
lbox->SetValue(SET_FLTMOD_2);
}
lbox = (C_ListBox *)win->FindControl(SET_RADAR);
if (lbox not_eq NULL)
{
switch (Presets[Index].RadarMode)
{
// M.N. full realism mode added
case ATRealisticAV:
lbox->SetValue(SET_RADAR_0);
break;
case ATRealistic:
lbox->SetValue(SET_RADAR_1);
break;
case ATSimplified:
lbox->SetValue(SET_RADAR_2);
break;
case ATEasy:
lbox->SetValue(SET_RADAR_3);
break;
}
}
lbox = (C_ListBox *)win->FindControl(SET_WEAPEFF);
if (lbox not_eq NULL)
{
switch (Presets[Index].WeapEffects)
{
case WEAccurate:
lbox->SetValue(SET_WEAPEFF_1);
break;
case WEEnhanced:
lbox->SetValue(SET_WEAPEFF_2);
break;
case WEExaggerated:
lbox->SetValue(SET_WEAPEFF_3);
break;
}
}
lbox = (C_ListBox *)win->FindControl(SET_AUTOPILOT);
if (lbox not_eq NULL)
{
switch (Presets[Index].Autopilot)
{
case APNormal:
lbox->SetValue(SET_AUTO_1);
break;
case APEnhanced:
lbox->SetValue(SET_AUTO_2);
break;
case APIntelligent:
lbox->SetValue(SET_AUTO_3);
break;
}
}
lbox = (C_ListBox *)win->FindControl(SET_REFUELING);
if (lbox not_eq NULL)
{
switch (Presets[Index].RefuelingMode)
{
case ARRealistic:
lbox->SetValue(SET_REFUEL_1);
break;
case ARModerated:
lbox->SetValue(SET_REFUEL_2);
break;
case ARSimplistic:
lbox->SetValue(SET_REFUEL_3);
break;
}
}
lbox = (C_ListBox *)win->FindControl(SET_PADLOCK);
if (lbox not_eq NULL)
{
switch (Presets[Index].PadlockMode)
{
case PDDisabled:
lbox->SetValue(SET_PADLOCK_4);
break;
case PDRealistic:
lbox->SetValue(SET_PADLOCK_1);
break;
case PDEnhanced:
lbox->SetValue(SET_PADLOCK_2);
break;
//case PDSuper:
// lbox->SetValue(SET_PADLOCK_3);
// break;
}
}
button = (C_Button *)win->FindControl(SET_ORDNANCE);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_UNLIMITED_AMMO)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_FUEL);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_UNLIMITED_FUEL)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_CHAFFLARES);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_UNLIMITED_CHAFF)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_COLLISIONS);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_NO_COLLISIONS)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_BLACKOUT);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_NO_BLACKOUT)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_IDTAGS);
if (button not_eq NULL)
{
if (Presets[Index].flags bitand SIM_NAMETAGS)
button->SetState(C_STATE_1);
else
button->SetState(C_STATE_0);
button->Refresh();
}
button = (C_Button *)win->FindControl(SET_INVULNERABILITY); //should be SET_INVULNERABLITY
if (button not_eq NULL)
{
button->SetState(C_STATE_0);
button->Refresh();
}
SetRealism(win);
}//SetSkillCB
/*****************************************************************************/
// Retro 25Dec2003
//
// Callback for the radiosubtitle button. Constructs/Destroys the radiolabel
// object. This object is already constructed at startup when the corresponding
// playeroptions variable (subTitles) is set to true.
/*****************************************************************************/
#include "RadioSubTitle.h"
extern int g_nSubTitleTTL;
extern int g_nNumberOfSubTitles;
extern char g_strRadioflightCol[0x40]; // Retro 27Dec2003
extern char g_strRadiotoPackageCol[0x40]; // Retro 27Dec2003
extern char g_strRadioToFromPackageCol[0x40]; // Retro 27Dec2003
extern char g_strRadioTeamCol[0x40]; // Retro 27Dec2003
extern char g_strRadioProximityCol[0x40]; // Retro 27Dec2003
extern char g_strRadioWorldCol[0x40]; // Retro 27Dec2003
extern char g_strRadioTowerCol[0x40]; // Retro 27Dec2003
extern char g_strRadioStandardCol[0x40]; // Retro 27Dec2003
void SubTitleCB(long ID, short hittype, C_Base *control)
{
if (hittype not_eq C_TYPE_LMOUSEUP)
return;
if ((PlayerOptions.getSubtitles() == false) and ( not radioLabel)) // need to create a new object..
{
try
{
radioLabel = new RadioSubTitle(g_nNumberOfSubTitles, g_nSubTitleTTL);
radioLabel->SetChannelColours(g_strRadioflightCol, g_strRadiotoPackageCol, g_strRadioToFromPackageCol,
g_strRadioTeamCol, g_strRadioProximityCol, g_strRadioWorldCol,
g_strRadioTowerCol, g_strRadioStandardCol);
PlayerOptions.SetSubtitles(true);
control->SetState(C_STATE_1);
}
catch (RadioSubTitle::Init_Error)
{
delete(radioLabel);
radioLabel = 0;
PlayerOptions.SetSubtitles(false);
control->SetState(C_STATE_0);
};
}
else // need to delete the object..
{
delete(radioLabel);
radioLabel = 0;
PlayerOptions.SetSubtitles(false);
control->SetState(C_STATE_0);
}
}
// Retro 25Dec2003 ends..
| 25.478632 | 219 | 0.563033 | Terebinth |
d1e81c5d78f2dbf62a8d342b7ac492d9baeb9c1d | 743 | cc | C++ | examples/csv_example.cc | KaiminLai/tiny-machine-learning-system | e29625dfb513032b40712663b63f874e2ae6f924 | [
"MIT"
] | 1 | 2019-01-09T16:03:50.000Z | 2019-01-09T16:03:50.000Z | examples/csv_example.cc | KaiminLai/tiny-machine-learning-system | e29625dfb513032b40712663b63f874e2ae6f924 | [
"MIT"
] | null | null | null | examples/csv_example.cc | KaiminLai/tiny-machine-learning-system | e29625dfb513032b40712663b63f874e2ae6f924 | [
"MIT"
] | null | null | null | #include<iostream>
#include "../src/csv.h"
using namespace std;
using namespace Eigen;
using namespace csv;
int main(){
CSVReader csv("a.csv");
cout<<"rows:"<<csv.rows()<<endl;
cout<<"columns:"<<csv.cols()<<endl;
cout<<"size:"<<csv.size()[0]<<"*"<<csv.size()[1]<<endl;
cout<<"element mat(0,1):"<<csv.get_element(0,1)<<endl;
VectorXd r1 = csv.get_row(1);
VectorXd c1 = csv.get_col(1);
MatrixXd mat = csv.get_mat();
cout<<"row1:\n";
cout<<r1[0]<<" "<<r1[1]<<" "<<r1[2]<<endl;
cout<<"column1:\n";
cout<<c1[0]<<" "<<c1[1]<<endl;
cout<<"mat(0,0):"<<mat(0,0)<<endl;
CSVWriter csv1(mat);
csv1.write("b.csv");
CSVWriter csv2(c1);
csv2.write("c.csv");
CSVWriter csv3(r1);
csv3.write("d.csv");
return 0;
} | 26.535714 | 57 | 0.585464 | KaiminLai |
d1e83f652bf4efb0799fea2bcb282f8a1785db7b | 1,065 | cpp | C++ | tests/memPSGRand_bug57/src_pers/PersTest00_src.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 13 | 2015-02-26T22:46:18.000Z | 2020-03-24T11:53:06.000Z | tests/memPSGRand_bug57/src_pers/PersTest00_src.cpp | PacificBiosciences/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 5 | 2016-02-25T17:08:19.000Z | 2018-01-20T15:24:36.000Z | tests/memPSGRand_bug57/src_pers/PersTest00_src.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 12 | 2015-04-13T21:39:54.000Z | 2021-01-15T01:00:13.000Z | #include "Ht.h"
#include "PersTest00.h"
void CPersTest00::PersTest00() {
if (PR2_htValid) {
switch (PR2_htInst) {
case TEST00_ENTRY: {
HtContinue(TEST00_WR);
break;
}
case TEST00_WR: {
GW2_test00_0_src_u0_data[0][1].write_addr(10, 3);
GW2_test00_0_src_u0_data[0][1].test00_0_src_v4_data = ((int32_t)0x001fe79ea30a33c0LL);
HtContinue(TEST00_ST0);
break;
}
case TEST00_ST0: {
if (WriteMemBusy()) {
HtRetry();
break;
}
WriteMem_test00_0_src_v4_data(PR2_memAddr + 0, 10, 3, 0, 1, 1);
WriteMemPause(TEST00_LD0);
break;
}
case TEST00_LD0: {
if (ReadMemBusy()) {
HtRetry();
break;
}
ReadMem_test00_0_dst_v0_data(PR2_memAddr + 0);
ReadMemPause(TEST00_CHK);
break;
}
case TEST00_CHK: {
if ((int32_t)SR_test00_0_dst_v0_data != ((int32_t)0x001fe79ea30a33c0LL)) {
HtAssert(0, 0);
}
HtContinue(TEST00_RTN);
break;
}
case TEST00_RTN: {
if (SendReturnBusy_test00()) {
HtRetry();
break;
}
SendReturn_test00();
break;
}
default:
assert(0);
}
}
}
| 19.363636 | 89 | 0.644131 | TonyBrewer |
d1ee5a73707b1026aac20ab13aa7d49ea028856d | 11,818 | cpp | C++ | Localization/LocalAlign/src/ipc.cpp | wangarcher/examine | e04c923f0db397558ea765d7fbf1050fe4aec3dd | [
"MIT"
] | null | null | null | Localization/LocalAlign/src/ipc.cpp | wangarcher/examine | e04c923f0db397558ea765d7fbf1050fe4aec3dd | [
"MIT"
] | null | null | null | Localization/LocalAlign/src/ipc.cpp | wangarcher/examine | e04c923f0db397558ea765d7fbf1050fe4aec3dd | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <dbus/dbus.h>
#include <stdbool.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <errno.h>
#include "../include/ipc.h"
/*********************************** 组合导航定位模块进程间通信 ****************************/
/*************** 定位模块的IPC信号量 ***********************/
int INPosSemKey = 2463;
int INPosSemId;
/*************** 定位模块的IPC信号量 ***********************/
/*************** 定位模块的消息队列通信 ***********************/
int INPosMsgKey = 2464; //消息键
int INPosMsgId; //定义位置消息Id, 进程间消息队列共享
/*************** 定位模块的消息队列通信 ***********************/
/*************** 定位模块的共享内存通信 ***********************/
int INPosShmKey = 2465;
int INPosShmId; //获取共享内存(Odom Imu Gps + Pos)句柄
/*************** 定位模块的共享内存通信 ***********************/
/*********************************** 组合导航定位模块进程间通信 ******************************/
/*********************************** SLAM定位模块进程间通信 ****************************/
/*************** 定位模块的IPC信号量 ***********************/
int LocalizationPosSemKey = 2466;
int LocalizationPosSemId;
/*************** 定位模块的IPC信号量 ***********************/
/*************** 定位模块的消息队列通信 ***********************/
int LocalizationPosMsgId; //定义位置消息Id, 进程间消息队列共享
int LocalizationPosMsgKey = 2467; //消息键
/*************** 定位模块的消息队列通信 ***********************/
/*************** 定位模块的共享内存通信 ***********************/
int LocalizationPosShmKey = 2468;
int LocalizationPosShmId;
/*************** 定位模块的共享内存通信 ***********************/
/*********************************** SLAM定位模块进程间通信 ******************************/
/*********************************** 视觉模块进程间通信 ******************************/
/*************** 视觉模块的IPC信号量 ***********************/
int VisualOccPosSemKey = 2469;
int VisualOccPosSemId;
/*************** 视觉模块的IPC信号量 ***********************/
/*************** 视觉模块的消息队列通信 ***********************/
int VisualOccPosMsgKey = 2470; //消息键
int VisualOccPosMsgId; //定义位置消息Id, 进程间消息队列共享
/*************** 视觉模块的消息队列通信 ***********************/
/*************** 视觉模块的共享内存通信 ***********************/
int VisualOccPosShmKey = 2471;
int VisualOccPosShmId;
/*************** 视觉模块的共享内存通信 ***********************/
/*********************************** 视觉模块进程间通信 *****************************/
/*********************************** 雷达模块进程间通信 ******************************/
/*************** 雷达模块的IPC信号量 ***********************/
int LidarOccPosSemKey = 2472;
int LidarOccPosSemId;
/*************** 雷达模块的IPC信号量 ***********************/
/*************** 雷达模块的消息队列通信 ***********************/
int LidarOccPosMsgKey = 2473; //消息键
int LidarOccPosMsgId; //定义位置消息Id, 进程间消息队列共享
/*************** 雷达模块的消息队列通信 ***********************/
/*************** 雷达模块的共享内存通信 ***********************/
int LidarOccPosShmKey = 2474;
int LidarOccPosShmId;
/*************** 雷达模块的共享内存通信 ***********************/
/*********************************** 雷达模块进程间通信 *****************************/
void InitIPC()
{
InitSem(INPosSemId, INPosSemKey, 1, IPC_CREAT|0777);
MessageQueueInit(INPosMsgId, INPosMsgKey, IPC_CREAT|0777);
InitShareMemory(INPosShmId, INPosShmKey,4096, IPC_CREAT|0777);
InitSem(LocalizationPosSemId, LocalizationPosSemKey, 1, IPC_CREAT|0777);
MessageQueueInit(LocalizationPosMsgId, LocalizationPosMsgKey, IPC_CREAT|0777);
InitShareMemory(LocalizationPosShmId, LocalizationPosShmKey,4096, IPC_CREAT|0777);
InitSem(VisualOccPosSemId, VisualOccPosSemKey, 1, IPC_CREAT|0777);
MessageQueueInit(VisualOccPosMsgId, VisualOccPosMsgKey, IPC_CREAT|0777);
InitShareMemory(VisualOccPosShmId, VisualOccPosShmKey,4096, IPC_CREAT|0777);
InitSem(LidarOccPosSemId, LidarOccPosSemKey, 1, IPC_CREAT|0777);
MessageQueueInit(LidarOccPosMsgId, LidarOccPosMsgKey, IPC_CREAT|0777);
InitShareMemory(LidarOccPosShmId, LidarOccPosShmKey,4096, IPC_CREAT|0777);
}
/*************************************************************** 进程间的信号量通信 ***************************************************/
//(1)第一个参数key是长整型(唯一非零),系统建立IPC通讯 ( 消息队列、 信号量和 共享内存) 时必须指定一个ID值。
//通常情况下,该id值通过ftok函数得到,由内核变成标识符,要想让两个进程看到同一个信号集,只需设置key值不变就可以。
//(2)第二个参数nsem指定信号量集中需要的信号量数目
//(3)第三个参数flag是一组标志,当想要当信号量不存在时创建一个新的信号量,可以将flag设置为IPC_CREAT与文件权限做按位或操作。
//设置了IPC_CREAT标志后,即使给出的key是一个已有信号量的key,也不会产生错误。而IPC_CREAT | IPC_EXCL则可以创建一个新的,唯一的信号量,如果信号量已存在,返回一个错误。一般我们会还或上一个文件权限
int InitSem(int &semId, int key, int num, int cmd)
{
semun sem_union;
sem_union.val = 0;
semId = semget(key_t(key), num, cmd);//创建并打开 或者创建 打开拆开 用时打开
if(semId < 0)
{
perror("InitSem failed");
return -1;
}
//信号量存在则获取
else
{
std::cout << "InitSem Success" << std::endl;
return 0;
}
if (semctl(semId, 0, SETVAL, sem_union) == -1) //设置信号量的计数值为0
{
printf("error to open semaphore!\n");
return -1;
}
//设置信号量集合中的信号量(元素)的计数值
SetSem(semId,1);
return 0;
}
int CreatSem(int &semId, int key, int num, int cmd)
{
semId = semget(key_t(key), num, cmd);
if(semId < 0)
{
std::cout << "Creat Sem failed" << std::endl;
return -1;
}
else
{
std::cout << "Creat Sem failed" << std::endl;
return 0;
}
}
//设置信号量集合里面的信号量的计数值val
int SetSem(int semId,int val)
{
int ret = 0;
if(semId < 0)
{
return -1;
}
semun su;
su.val = val;
ret = semctl(semId,0,SETVAL,su);
return ret;
}
//获取信号量集合里面的信号量的计数值
int GetSem(int semId, int& val)
{
int ret = 0;
semun sem_union;
sem_union.val = 0;
if(semId < 0)
{
return -1;
}
ret = semctl(semId,0,GETVAL,sem_union);
val = sem_union.val;
return ret;
}
//struct sembuf{
// short sem_num; // 除非使用一组信号量,否则它为0
// short sem_op; // 信号量在一次操作中需要改变的数据,通常是两个数,
// 一个是-1,即P(等待)操作,
// 一个是+1,即V(发送信号)操作。
// short sem_flg; // 通常为SEM_UNDO,使操作系统跟踪信号,
// // 并在进程没有释放该信号量而终止时,操作系统释放信号量
//};
int P_sem(int semId, int semIndex)
{
struct sembuf s;
s.sem_num = semIndex;
s.sem_op = -1;
s.sem_flg = SEM_UNDO;
if(semop(semId,&s,1) < 0)
{
printf("op errno,%d: %s\n", errno, strerror(errno));
return -1;
}
}
int V_sem(int semId, int semIndex)
{
struct sembuf s;
s.sem_num = semIndex;
s.sem_op = 1;
s.sem_flg = SEM_UNDO;
if(semop(semId,&s,1) < 0)
{
printf("ov error,%d:%s\n",errno,strerror(errno));
return -1;
}
}
// union semun {
// int val;
// struct semid_ds *buf;
// unsigned short *arry;
// };
// SETVAL:用来把信号量初始化为一个已知的值。
// p 这个值通过union semun中的val成员设置,其作用是在信号量第一次使用前对它进行设置。
// IPC_RMID:用于删除一个已经无需继续使用的信号量标识符。
int DestorySem(int semId)
{
semun sem_union;
if (semctl(semId, 0, IPC_RMID, sem_union) == -1)
{
printf("err to delete semaphore!\n");
return -1;
}
}
/*************************************************************** 进程间的信号量通信 ***************************************************/
/*************************************************************** 进程间的消息队列通信 ***************************************************/
//msgflag:有两个选项IPC_CREAT和IPC_EXCL,
//单独使用IPC_CREAT,如果消息队列不存在则创建之,
//如果存在则打开返回;单独使用IPC_EXCL是没有意义的;
//两个同时使用,如果消息队列不存在则创建之,如果存在则出错返回。
int MessageQueueInit(int &msgId, int msgKey, int cmd)
{
//先检查消息队列是否存在
msgId = msgget(msgKey, cmd);
//不存在则创建
if(msgId < 0)
{
std::cout << "InitMsg failed" << std::endl;
return -1;
}
else
{
std::cout << "InitMsg Success(GetMsg)" << std::endl;
return 0;
}
}
int CreatMessageQueue(int &msgId, int msgKey, int cmd)
{
msgId = msgget(msgKey, cmd);
if(msgId < 0)
{
fprintf(stderr, "CreatMsg failed with error:%d\n", errno);
return -1;
}
else
{
std::cout << "CreatMsg successful" << std::endl;
return 0;
}
}
//msgid:由msgget函数返回的消息队列标识码
//msgp:指针指向准备发送的消息
//msgze:msgp指向的消息的长度(不包括消息类型的long int长整型)
//msgflg: 0:当消息队列满时,msgsnd将会阻塞,直到消息能写进消息队列
// IPC_NOWAIT:当消息队列已满的时候,msgsnd函数不等待立即返回
// IPC_NOERROR:若发送的消息大于size字节,则把该消息截断,截断部分将被丢弃,且不通知发送进程。
int SendMessageQueue(int msgId, void* dataAdress, int msgSize, int cmd)
{
if(-1 == msgsnd(msgId, dataAdress, msgSize, cmd)) //理解: 将数据地址(dataAdress)大小(msgSize)发送到消息队列
{
fprintf(stderr, "msgsnd failed: %d\n", errno);
return -1;
}
else
{
std::cout << "msgsnd successful" << std::endl;
return 0;
}
}
//int msgrcv(int msqid, void *ptr, size_t length, long type, int flag);
//type: 决定从队列中返回哪条消息:
// =0 返回消息队列中第一条消息
// >0 返回消息队列中等于mtype 类型的第一条消息。
// <0 返回mtype<=type 绝对值最小值的第一条消息。
//msgflg为0表示阻塞方式,设置 IPC_NOWAIT 表示非阻塞方式
int RcvMessageQueue(int msgId, void* dataAdress, int msgSize, int cmd)
{
if(-1 == msgrcv(msgId, dataAdress, msgSize, 0, cmd))
{
fprintf(stderr, "msgrcv failed with errno: %d", errno);
return -1;
}
else
{
std::cout << "msgrcv successful" << std::endl;
return 0;
}
}
//msqid:由msgget函数返回的消息队列标识码
//cmd:有三个可选的值,在此我们使用IPC_RMID
// IPC_STAT 把msqid_ds结构中的数据设置为消息队列的当前关联值
// IPC_SET 在进程有足够权限的前提下,把消息队列的当前关联值设置为msqid_ds数据结构中给出的值
// IPC_RMID 删除消息队列
int DestoryMessageQueue(int msgId)
{
if(msgctl(msgId, IPC_RMID, NULL) < 0)
{
perror("msgctl");
return -1;
}
return 0;
}
/*************************************************************** 进程间的消息队列通信 ***************************************************/
/*************************************************************** 进程间的内存共享通信 ***************************************************/
//key:共享内存名字,确保不同进程看到同一份IPC资源;
//其中key值的又由ftok函数创建。
//size:共享内存的大小,共享内存的创建是以页为单位的;
//页的大小是4096k(4kb)
//共享内存分别存放Odom Imu Gps Robot数据 请按照此顺序进行读取以及写入
int InitShareMemory(int &shmid, int key, int size, int cmd)
{
int pageSize = getpagesize();//获取系统页面的大小
if(size <= 0)
{
std::cout << "共享内存创建非法,请检查!" << std::endl;
return -1;
}
else if(size > pageSize)
{
std::cout << "创建共享内存段的大小超过页面的大小!" << std::endl;
return -1;
}
else
{
shmid = shmget(key, size, cmd);
if(shmid < 0)
{
std::cout << "InitShm failed" << std::endl;
return -1;
}
else
{
std::cout << "InitShm success" << std::endl;
return 0;
}
return 0;
}
}
int CreatShareMemory(int &shmid, key_t key, int size, int cmd)
{
shmid = shmget(key, size, IPC_CREAT | 0666);
if( shmid < 0)
{
perror("CreatShm failed");
return -1;
}
else
{
std::cout << "CreatShm successful" << std::endl;
return 0;
}
}
void* AttachShareMemory(int shmid)
{
void* shmaddr;
return shmaddr = (void *) shmat(shmid, NULL, 0);
}
void* WriteShareMemory(void* shmaddr, void* source, int size)
{
return memcpy(shmaddr, source, size);
}
void* ReadShareMemory(void* destion, void* shmaddr, int size)
{
return memcpy(destion, shmaddr, size);
}
int DisattachShareMemory(void* shmaddr)
{
return shmdt(shmaddr);
}
int DestoryShareMemory(int shmid)
{
return shmctl(shmid, IPC_RMID, NULL);
}
/*************************************************************** 进程间的内存共享通信 ***************************************************/
| 26.146018 | 129 | 0.519123 | wangarcher |
d1f277c362894330ad3b5b1c075802b4579ecd49 | 2,338 | cc | C++ | MassRecoCompare/src/Common.cc | NTUHEP-Tstar/TstarAnalysis | d3bcdf6f0fd19b9a34bbacb1052143856917bea7 | [
"MIT"
] | null | null | null | MassRecoCompare/src/Common.cc | NTUHEP-Tstar/TstarAnalysis | d3bcdf6f0fd19b9a34bbacb1052143856917bea7 | [
"MIT"
] | null | null | null | MassRecoCompare/src/Common.cc | NTUHEP-Tstar/TstarAnalysis | d3bcdf6f0fd19b9a34bbacb1052143856917bea7 | [
"MIT"
] | null | null | null | /*******************************************************************************
*
* Filename : Common.cc
* Description : Declaration of common global variables and functions
* Author : Yi-Mu "Enoch" Chen [ [email protected] ]
*
* Additional comments
*
*******************************************************************************/
#include "TstarAnalysis/MassRecoCompare/interface/Common.hpp"
#include <boost/algorithm/string.hpp>
using namespace std;
/*******************************************************************************
* Declaring global objects
*******************************************************************************/
TstarNamer reconamer( "MassRecoCompare" );
const Color_t Color_Sequence[5] = {
kBlue,
kRed,
kGreen,
kBlack,
kCyan
};
/*******************************************************************************
* Module naming functions
*******************************************************************************/
std::string
ProcessName(){ return "HitFitCompare"; }
/******************************************************************************/
std::string
LabelName( const std::string& modulename )
{
return boost::starts_with( modulename, "ChiSq" ) ?
"ChiSquareResult" : "HitFitResult";
}
/*******************************************************************************
* Common functions
*******************************************************************************/
const vector<tstar::Particle_Label> fitlabellist = {
tstar::lepb_label,
tstar::lepg_label,
tstar::hadw1_label,
tstar::hadw2_label,
tstar::hadb_label,
tstar::hadg_label
};
const vector<tstar::Particle_Label> truthlabellist = {
tstar::lepb_label,
tstar::lepg_label,
tstar::hadw1_label,
tstar::hadw2_label,
tstar::hadb_label,
tstar::hadg_label,
tstar::unknown_label
};
/******************************************************************************/
unsigned
NumCorrectAssign( const RecoResult& results )
{
unsigned ans = 0;
for( const auto x : fitlabellist ){
const auto y = results.GetParticle( x ).TypeFromTruth();
if( x == y ){ ans++; continue; }
if( x == tstar::hadw1_label && y == tstar::hadw2_label ){ ans++; continue; }
if( x == tstar::hadw2_label && y == tstar::hadw1_label ){ ans++; continue; }
}
return ans;
}
| 28.864198 | 80 | 0.44953 | NTUHEP-Tstar |
d1f359753752617b84bcfb358e508e6f557c25b5 | 1,475 | cpp | C++ | compiler/angkor/src/ADT/feature/HWCLayout.test.cpp | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | compiler/angkor/src/ADT/feature/HWCLayout.test.cpp | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | compiler/angkor/src/ADT/feature/HWCLayout.test.cpp | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "nncc/core/ADT/feature/HWCLayout.h"
#include <gtest/gtest.h>
using namespace nncc::core::ADT::feature;
TEST(ADT_FEATURE_HWC_LAYOUT, C_increase)
{
const uint32_t C = 4;
const uint32_t H = 3;
const uint32_t W = 6;
const Shape shape{C, H, W};
const HWCLayout l;
ASSERT_EQ(l.offset(shape, 1, 1, 1) + 1, l.offset(shape, 2, 1, 1));
}
TEST(ADT_FEATURE_HWC_LAYOUT, W_increase)
{
const uint32_t C = 4;
const uint32_t H = 3;
const uint32_t W = 6;
const Shape shape{C, H, W};
const HWCLayout l;
ASSERT_EQ(l.offset(shape, 1, 2, 1) + C, l.offset(shape, 1, 2, 2));
}
TEST(ADT_FEATURE_HWC_LAYOUT, H_increase)
{
const uint32_t C = 4;
const uint32_t H = 3;
const uint32_t W = 6;
const Shape shape{C, H, W};
const HWCLayout l;
ASSERT_EQ(l.offset(shape, 1, 1, 1) + W * C, l.offset(shape, 1, 2, 1));
}
| 25.431034 | 75 | 0.690169 | wateret |
d1f46989a9fba26159145429767fad72259179d2 | 1,184 | cpp | C++ | testkuplayer/tst_kuplayertest.cpp | listener/mikuplayer | 06b3fb9ffc13184086c5098cd50224c6c60d162f | [
"Unlicense"
] | 17 | 2015-09-13T02:06:27.000Z | 2017-09-22T06:39:26.000Z | testkuplayer/tst_kuplayertest.cpp | xiaosumay/kuplayer | 06b3fb9ffc13184086c5098cd50224c6c60d162f | [
"Unlicense"
] | null | null | null | testkuplayer/tst_kuplayertest.cpp | xiaosumay/kuplayer | 06b3fb9ffc13184086c5098cd50224c6c60d162f | [
"Unlicense"
] | 2 | 2015-10-26T01:54:54.000Z | 2016-01-16T08:24:45.000Z | /*
Copyright (C) 2015 MeiZhaorui(Mason) <[email protected]>
The File 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; either
version 2.1 of the License, or (at your option) any later version.
The File 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 Library; if not, see
<http://www.gnu.org/licenses/>.
*/
#include <QString>
#include <QtTest>
#include <QCoreApplication>
#include "../src/pyscript.h"
USR_NAMESPACE_KUPLAYER
class kuplayerTest : public QObject
{
Q_OBJECT
public:
kuplayerTest();
private Q_SLOTS:
void testgetShowList();
};
kuplayerTest::kuplayerTest()
{
}
void kuplayerTest::testgetShowList()
{
PyScript p;
QCOMPARE(true,p.getShowList());
}
QTEST_MAIN(kuplayerTest)
#include "tst_kuplayertest.moc"
| 24.163265 | 69 | 0.725507 | listener |
d1f63cd1080601f902d65f7eecdb178a63bb2fae | 11,599 | cpp | C++ | src/Scenario/DIALOGS/CustTree.cpp | privatosan/RayStorm | 17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa | [
"MIT"
] | 2 | 2016-04-03T23:57:54.000Z | 2019-12-05T17:50:37.000Z | src/Scenario/DIALOGS/CustTree.cpp | privatosan/RayStorm | 17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa | [
"MIT"
] | null | null | null | src/Scenario/DIALOGS/CustTree.cpp | privatosan/RayStorm | 17e27259a8a1d6b2fcfa16886c6e4cdd81be8cfa | [
"MIT"
] | 2 | 2015-06-20T19:22:47.000Z | 2021-11-15T15:22:14.000Z | // OwnrTree.cpp : implementation file
//
#include "typedefs.h"
#include "CustTree.h"
#include "object.h"
#include "sci.h"
#include "resource.h"
#include "BrowserView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define INSERT_TEXT ""
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl Construction
CCustomTreeCtrl::CCustomTreeCtrl()
{
m_bNoPaint = FALSE;
m_bLockPropertySelchanged = FALSE;
}
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl Public Interfaces
BOOL CCustomTreeCtrl::SetItemText(HTREEITEM hItem, LPCTSTR lpszItem)
{
CString cstr;
CRect crect;
cstr = lpszItem;
AddTextItem(hItem, cstr);
GetItemRect(hItem, &crect, FALSE);
InvalidateRect(&crect);
return TRUE;
}
CString CCustomTreeCtrl::GetItemText(HTREEITEM hItem)
{
CString cstr;
GetTextFromItem(hItem, cstr);
return cstr;
}
HTREEITEM CCustomTreeCtrl::InsertItem(LPTV_INSERTSTRUCT lpInsertStruct)
{
HTREEITEM hItem;
CString cstr;
cstr = lpInsertStruct->item.pszText;
lpInsertStruct->item.pszText = INSERT_TEXT;
hItem = CTreeCtrl::InsertItem(lpInsertStruct);
if (!hItem)
return NULL;
AddTextItem(hItem, cstr);
return hItem;
}
HTREEITEM CCustomTreeCtrl::InsertItem(UINT nMask, LPCTSTR lpszItem,
int nImage,
int nSelectedImage,
UINT nState,UINT nStateMask,
LPARAM lParam,
HTREEITEM hParent,
HTREEITEM hInsertAfter)
{
CString cstr;
HTREEITEM hItem;
hItem = CTreeCtrl::InsertItem(nMask, INSERT_TEXT, nImage,
nSelectedImage, nState,
nStateMask, lParam, hParent,
hInsertAfter);
if (!hItem)
return NULL;
cstr = lpszItem;
AddTextItem(hItem, cstr);
return hItem;
}
HTREEITEM CCustomTreeCtrl::InsertItem(LPCTSTR lpszItem, HTREEITEM hParent, HTREEITEM hInsertAfter)
{
CString cstr;
HTREEITEM hItem;
cstr = lpszItem;
hItem = CTreeCtrl::InsertItem(INSERT_TEXT, hParent,
hInsertAfter);
if (!hItem)
return NULL;
AddTextItem(hItem, cstr);
return hItem;
}
HTREEITEM CCustomTreeCtrl::InsertItem(LPCTSTR lpszItem, int nImage,
int nSelectedImage,
HTREEITEM hParent,
HTREEITEM hInsertAfter)
{
CString cstr;
HTREEITEM hItem;
cstr = lpszItem;
hItem = CTreeCtrl::InsertItem(INSERT_TEXT, nImage,nSelectedImage,
hParent, hInsertAfter);
if (!hItem)
return NULL;
AddTextItem(hItem, cstr);
return hItem;
}
BOOL CCustomTreeCtrl::GetItem(TV_ITEM* pItem)
{
BOOL bRet;
CString cstr;
bRet = CTreeCtrl::GetItem(pItem);
if (bRet)
{
GetTextFromItem(pItem->hItem, cstr);
strncpy(pItem->pszText, cstr, pItem->cchTextMax);
}
return bRet;
}
BOOL CCustomTreeCtrl::SetItem(TV_ITEM* pItem)
{
BOOL bRet;
CString cstr;
cstr = pItem->pszText;
pItem->pszText = INSERT_TEXT;
bRet = CTreeCtrl::SetItem(pItem);
if (bRet)
{
AddTextItem(pItem->hItem, cstr);
}
return bRet;
}
BOOL CCustomTreeCtrl::SetItem(HTREEITEM hItem, UINT nMask,
LPCTSTR lpszItem, int nImage,
int nSelectedImage, UINT nState,
UINT nStateMask, LPARAM lParam)
{
BOOL bRet;
bRet = CTreeCtrl::SetItem(hItem, nMask, INSERT_TEXT, nImage,
nSelectedImage, nState, nStateMask,
lParam);
if (bRet)
{
CString cstr;
cstr = lpszItem;
AddTextItem(hItem, cstr);
}
return TRUE;
}
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl Implementation Methods
HTREEITEM CCustomTreeCtrl::PtInField(POINT pt)
{
CRect crect;
HTREEITEM htreeitem;
htreeitem = GetFirstVisibleItem();
while (htreeitem)
{
GetItemRect(htreeitem, &crect, TRUE);
if (crect.PtInRect(pt))
break;
htreeitem = GetNextVisibleItem(htreeitem);
}
return htreeitem;
}
void CCustomTreeCtrl::AddTextItem(HTREEITEM hItem, CString &cstr)
{
m_cmapTextItems.SetAt(hItem, cstr);
}
void CCustomTreeCtrl::RemoveTextItem(HTREEITEM hItem)
{
m_cmapTextItems.RemoveKey(hItem);
}
BOOL CCustomTreeCtrl::GetTextFromItem(HTREEITEM hItem, CString &cstr)
{
return m_cmapTextItems.Lookup(hItem, cstr);
}
void CCustomTreeCtrl::SetItemWidth(HTREEITEM htreeitem, CDC &cdc,
DWORD dwWidth)
{
int nSpaceWidth, nSpaces;
CString cstr;
cdc.GetCharWidth(' ', ' ', &nSpaceWidth);
// I don't know when a space wouldn't have width, but I would
// hate to see a divide by zero error.
if (!nSpaceWidth)
return;
nSpaces = dwWidth / nSpaceWidth + ((dwWidth % nSpaceWidth)?1:0);
cstr = CTreeCtrl::GetItemText(htreeitem);
if (cstr.GetLength() != nSpaces)
{
CTreeCtrl::SetItemText(htreeitem, CString(' ', nSpaces));
}
}
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl Overidables
// This function should normally be overridden, however it is always
// nice to have a default implementation to fall back on
DWORD CCustomTreeCtrl::DrawItem(HTREEITEM htreeitem, CDC &cdc, CRect &rect, UINT nState)
{
CFont *oldFont;
CRect rectBack;
COLORREF oldCol;
OBJECT *object;
char *name;
rectBack = rect;
rectBack.right += 4;
cdc.FillSolidRect(&rectBack, GetSysColor(COLOR_WINDOW));
oldFont = cdc.SelectObject(GetFont());
object = (OBJECT*)(GetItemData(htreeitem));
if (object)
{
name = object->GetName();
if (object->selected)
oldCol = cdc.SetTextColor(RGB(255,0,0));
else
oldCol = cdc.SetTextColor(RGB(0,0,0));
cdc.DrawText(name, &rect, DT_VCENTER | DT_SINGLELINE);
cdc.SelectObject(oldFont);
cdc.SetTextColor(oldCol);
return cdc.GetTextExtent(name, strlen(name)).cx;
}
return 0;
}
BEGIN_MESSAGE_MAP(CCustomTreeCtrl, CTreeCtrl)
//{{AFX_MSG_MAP(CCustomTreeCtrl)
ON_NOTIFY_REFLECT(TVN_SELCHANGED, OnPropertySelchanged)
ON_NOTIFY_REFLECT(TVN_ITEMEXPANDED, OnItemExpanded)
ON_WM_PAINT()
ON_WM_RBUTTONDOWN()
ON_WM_ERASEBKGND()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////
// CCustomTreeCtrl message handlers
// To prevent flickering when using non default bkcolor
BOOL CCustomTreeCtrl::OnEraseBkgnd(CDC *)
{
return TRUE;
}
// Disable Tooltips
BOOL CCustomTreeCtrl::OnNotify(WPARAM wParam, LPARAM lParam,
LRESULT* pResult)
{
return TRUE;
}
/*************
* DESCRIPTION: set which to current selected object
* INPUT: system
* OUTPUT: -
*************/
void CCustomTreeCtrl::OnPropertySelchanged(LPNMHDR pNMHDR, LRESULT *lParam)
{
NM_TREEVIEW *pnmtv;
if (m_bLockPropertySelchanged)
return;
pnmtv = (NM_TREEVIEW*)pNMHDR;
OBJECT *which = (OBJECT*)GetItemData(pnmtv->itemNew.hItem);
if (which)
{
if (!(GetKeyState(VK_SHIFT) & 0xf000))
DeselectAll();
which->SelectObject();
// lock us to prevent recursive call
m_bLockPropertySelchanged = TRUE;
sciBrowserBuild();
m_bLockPropertySelchanged = FALSE;
sciRedraw();
}
}
void CCustomTreeCtrl::OnPaint()
{
HTREEITEM hTreeItem;
CRect rect, rectClip, rectClient, rectTemp;
CFont *pcfont, *pcfontOld;
CBitmap bitmap;
CDC memDC;
CRgn rgn;
CPaintDC dc(this);
UINT nState;
BOOL bFocus;
DWORD dwWidth;
// If we are flagged to ignore this pain message,
// then validate rect and return
if (m_bNoPaint)
{
m_bNoPaint = FALSE;
ValidateRect(NULL);
return;
}
// Create a memory DC compatible with the paint DC
memDC.CreateCompatibleDC(&dc);
dc.GetClipBox(&rectClip);
GetClientRect(&rectClient);
// Select a compatible bitmap into the memory DC
bitmap.CreateCompatibleBitmap(&dc, rectClient.Width(), rectClient.Height());
memDC.SelectObject(&bitmap);
// Set clip region to be same as that in paint DC
rgn.CreateRectRgnIndirect(&rectClip);
memDC.SelectClipRgn(&rgn);
rgn.DeleteObject();
// First let the control do its default drawing.
// Retrieve Invalid Rect for use throughout paint handler
ValidateRect(NULL);
// If we have focus, store this fact, but then turn it off
if (bFocus = GetFocus() == this)
{
// Make sure any paint message generated by
// SetFocus() does nothing
m_bNoPaint = TRUE;
::SetFocus(NULL);
// Make sure that or Invalid rect is the same as it
// was upon entering the paint handler
ValidateRect(NULL);
InvalidateRect(&rectClient);
// Set Paint Flag so that future paint handling will occur
m_bNoPaint = FALSE;
}
// Get that default drawing done... without a focus rect or
// selected area
CWnd::DefWindowProc(WM_PAINT, (WPARAM)memDC.m_hDC, 0);
// If we did have focus we will restore it now
if (bFocus)
{
m_bNoPaint = TRUE;
SetFocus();
m_bNoPaint = FALSE;
}
// We want a valid window rect now... SetFocus() may have
// invalidated some portion of the client
ValidateRect(NULL);
// As control we need to make sure we do our drawing in
// our parents font
pcfont = GetParent()->GetFont();
pcfontOld = memDC.SelectObject(pcfont);
// Now we will enumerate the visible items in the control
hTreeItem = GetFirstVisibleItem();
while (hTreeItem)
{
// Where is this item in the client
GetItemRect(hTreeItem, &rect, TRUE);
// Get the state of the current item to pass to the
// DrawItem() Function
nState = GetItemState(hTreeItem, ~0);
// Expand / limit the area of the item to the right
// edge of the client
rect.right = rectClient.right;
// If the item falls inside of our original
// invalid rect then redraw it
// by calling the overidable virtual function DrawItem()
if (rectTemp.IntersectRect(&rect, &rectClient))
{
dwWidth = DrawItem(hTreeItem, memDC, rect, nState);
SetItemWidth(hTreeItem, memDC, dwWidth);
}
// Continue through visible items
hTreeItem = GetNextVisibleItem(hTreeItem);
}
// We do this, because SetItemWidth actually changes
// the text of the items in the control and it
// may have flagged a repaint which we don't want to happen
ValidateRect(NULL);
dc.BitBlt(rectClip.left, rectClip.top, rectClip.Width(), rectClip.Height(), &memDC, rectClip.left, rectClip.top,SRCCOPY);
}
/*************
* DESCRIPTION: called if tree item is expanded or collapsed
* INPUT: system
* OUTPUT: -
*************/
void CCustomTreeCtrl::OnItemExpanded(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
OBJECT *object;
object = (OBJECT *)GetItemData(pNMTreeView->itemNew.hItem);
if (object)
{
if (pNMTreeView->action & TVE_COLLAPSE)
object->flags &= ~OBJECT_NODEOPEN;
if (pNMTreeView->action & TVE_EXPAND)
object->flags |= OBJECT_NODEOPEN;
}
*pResult = 0;
}
/*************
* DESCRIPTION: ON_WM_RBUTTONDOWN
* handles right mouse button click
* display pop up menu in browser menu
* INPUT: nFlags Specifies if various flags are set
* point coordinates of mouse cursor
* OUTPUT: -
*************/
void CCustomTreeCtrl::OnRButtonDown(UINT nFlags, CPoint point)
{
CMenu menu;
int resource;
HTREEITEM hItem;
UINT flags;
OBJECT *object;
hItem = HitTest(point, &flags);
if (hItem)
{
object = (OBJECT*)GetItemData(hItem);
resource = object->GetResourceID();
ClientToScreen(&point);
if (menu.LoadMenu(resource))
{
CMenu* pSubMenu = menu.GetSubMenu(0);
if (pSubMenu != NULL)
{
if (resource == IDR_POPUP_OBJECT)
{
if (object->external != EXTERNAL_NONE)
pSubMenu->EnableMenuItem(IDM_TOSCENE, MF_ENABLED);
else
pSubMenu->EnableMenuItem(IDM_TOSCENE, MF_GRAYED);
}
pSubMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, ((CBrowserView*)GetParent())->pCamView);
}
}
}
}
| 22.435203 | 122 | 0.677903 | privatosan |
060013ca6684d72925a5ed796ecf040827993dca | 20,470 | cpp | C++ | tools/OdometryViewer/main.cpp | jackiecx/rtabmap | e12b10b860a85872568180e11f5babd78bf266b0 | [
"BSD-3-Clause"
] | 1 | 2019-06-14T15:21:42.000Z | 2019-06-14T15:21:42.000Z | tools/OdometryViewer/main.cpp | jackiecx/rtabmap | e12b10b860a85872568180e11f5babd78bf266b0 | [
"BSD-3-Clause"
] | null | null | null | tools/OdometryViewer/main.cpp | jackiecx/rtabmap | e12b10b860a85872568180e11f5babd78bf266b0 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
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 Universite de Sherbrooke 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 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.
*/
#include <rtabmap/utilite/ULogger.h>
#include <rtabmap/utilite/UEventsManager.h>
#include <rtabmap/utilite/UFile.h>
#include <rtabmap/utilite/UConversion.h>
#include <rtabmap/core/Odometry.h>
#include <rtabmap/core/OdometryThread.h>
#include <rtabmap/gui/OdometryViewer.h>
#include <rtabmap/core/CameraThread.h>
#include <rtabmap/core/CameraRGBD.h>
#include <rtabmap/core/CameraStereo.h>
#include <rtabmap/core/DBReader.h>
#include <rtabmap/core/VWDictionary.h>
#include <QApplication>
#include <QPushButton>
#include <pcl/console/print.h>
void showUsage()
{
printf("\nUsage:\n"
"odometryViewer [options]\n"
"Options:\n"
" -driver # Driver number to use: 0=OpenNI-PCL, 1=OpenNI2, 2=Freenect, 3=OpenNI-CV, 4=OpenNI-CV-ASUS, 5=Freenect2, 6=dc1394, 7=FlyCapture2\n"
" -o # Odometry type (default 6): 0=SURF, 1=SIFT, 2=ORB, 3=FAST/FREAK, 4=FAST/BRIEF, 5=GFTT/FREAK, 6=GFTT/BRIEF, 7=BRISK\n"
" -nn # Nearest neighbor strategy (default 3): kNNFlannNaive=0, kNNFlannKdTree=1, kNNFlannLSH=2, kNNBruteForce=3, kNNBruteForceGPU=4\n"
" -nndr # Nearest neighbor distance ratio (default 0.7)\n"
" -flow Use optical flow odometry.\n"
" -icp Use ICP odometry\n"
" -mono Use Mono odometry\n"
"\n"
" -hz #.# Camera rate (default 0, 0 means as fast as the camera can)\n"
" -db \"input.db\" Use database instead of camera (recorded with rtabmap-dataRecorder)\n"
" -clouds # Maximum clouds shown (default 10, zero means inf)\n"
" -sec #.# Delay (seconds) before reading the database (if set)\n"
"\n"
" -in #.# Inliers maximum distance, features/ICP (default 0.01 m)\n"
" -max # Max features used for matching (default 0=inf)\n"
" -min # Minimum inliers to accept the transform (default 20)\n"
" -depth #.# Maximum features depth (default 5.0 m)\n"
" -i # RANSAC/ICP iterations (default 30)\n"
" -reset # Reset countdown (default 0 = disabled)\n"
" -gpu Use GPU\n"
" -lh # Local history (default 1000)\n"
"\n"
" -brief_bytes # BRIEF bytes (default 32)\n"
" -fast_thr # FAST threshold (default 30)\n"
"\n"
" -d # ICP decimation (default 4)\n"
" -v # ICP voxel size (default 0.005)\n"
" -s # ICP samples (default 0, not used if voxel is set.)\n"
" -cr #.# ICP correspondence ratio (default 0.7)\n"
" -p2p ICP point to point (default point to plane)"
"\n"
" -debug Log debug messages\n"
"\n"
"Examples:\n"
" odometryViewer -odom 0 -lh 5000 SURF example\n"
" odometryViewer -odom 1 -lh 10000 SIFT example\n"
" odometryViewer -odom 4 -nn 2 -lh 1000 FAST/BRIEF example\n"
" odometryViewer -odom 3 -nn 2 -lh 1000 FAST/FREAK example\n"
" odometryViewer -icp -in 0.05 -i 30 ICP example\n"
" odometryViewer -flow -in 0.02 Optical flow example\n");
exit(1);
}
int main (int argc, char * argv[])
{
ULogger::setType(ULogger::kTypeConsole);
ULogger::setLevel(ULogger::kInfo);
ULogger::setPrintTime(false);
ULogger::setPrintWhere(false);
// parse arguments
float rate = 0.0;
std::string inputDatabase;
int driver = 0;
int odomType = rtabmap::Parameters::defaultOdomFeatureType();
bool icp = false;
bool flow = false;
bool mono = false;
int nnType = rtabmap::Parameters::defaultOdomBowNNType();
float nndr = rtabmap::Parameters::defaultOdomBowNNDR();
float distance = rtabmap::Parameters::defaultOdomInlierDistance();
int maxWords = rtabmap::Parameters::defaultOdomMaxFeatures();
int minInliers = rtabmap::Parameters::defaultOdomMinInliers();
float maxDepth = rtabmap::Parameters::defaultOdomMaxDepth();
int iterations = rtabmap::Parameters::defaultOdomIterations();
int resetCountdown = rtabmap::Parameters::defaultOdomResetCountdown();
int decimation = 4;
float voxel = 0.005;
int samples = 10000;
float ratio = 0.7f;
int maxClouds = 10;
int briefBytes = rtabmap::Parameters::defaultBRIEFBytes();
int fastThr = rtabmap::Parameters::defaultFASTThreshold();
float sec = 0.0f;
bool gpu = false;
int localHistory = rtabmap::Parameters::defaultOdomBowLocalHistorySize();
bool p2p = false;
for(int i=1; i<argc; ++i)
{
if(strcmp(argv[i], "-driver") == 0)
{
++i;
if(i < argc)
{
driver = std::atoi(argv[i]);
if(driver < 0 || driver > 7)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-o") == 0)
{
++i;
if(i < argc)
{
odomType = std::atoi(argv[i]);
if(odomType < 0 || odomType > 6)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-nn") == 0)
{
++i;
if(i < argc)
{
nnType = std::atoi(argv[i]);
if(nnType < 0 || nnType > 4)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-nndr") == 0)
{
++i;
if(i < argc)
{
nndr = uStr2Float(argv[i]);
if(nndr < 0.0f)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-hz") == 0)
{
++i;
if(i < argc)
{
rate = uStr2Float(argv[i]);
if(rate < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-db") == 0)
{
++i;
if(i < argc)
{
inputDatabase = argv[i];
if(UFile::getExtension(inputDatabase).compare("db") != 0)
{
printf("Database path (%s) should end with \"db\" \n", inputDatabase.c_str());
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-clouds") == 0)
{
++i;
if(i < argc)
{
maxClouds = std::atoi(argv[i]);
if(maxClouds < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-sec") == 0)
{
++i;
if(i < argc)
{
sec = uStr2Float(argv[i]);
if(sec < 0.0f)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-in") == 0)
{
++i;
if(i < argc)
{
distance = uStr2Float(argv[i]);
if(distance <= 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-max") == 0)
{
++i;
if(i < argc)
{
maxWords = std::atoi(argv[i]);
if(maxWords < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-min") == 0)
{
++i;
if(i < argc)
{
minInliers = std::atoi(argv[i]);
if(minInliers < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-depth") == 0)
{
++i;
if(i < argc)
{
maxDepth = uStr2Float(argv[i]);
if(maxDepth < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-i") == 0)
{
++i;
if(i < argc)
{
iterations = std::atoi(argv[i]);
if(iterations <= 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-reset") == 0)
{
++i;
if(i < argc)
{
resetCountdown = std::atoi(argv[i]);
if(resetCountdown < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-d") == 0)
{
++i;
if(i < argc)
{
decimation = std::atoi(argv[i]);
if(decimation < 1)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-v") == 0)
{
++i;
if(i < argc)
{
voxel = uStr2Float(argv[i]);
if(voxel < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-s") == 0)
{
++i;
if(i < argc)
{
samples = std::atoi(argv[i]);
if(samples < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-cr") == 0)
{
++i;
if(i < argc)
{
ratio = uStr2Float(argv[i]);
if(ratio < 0.0f)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-gpu") == 0)
{
gpu = true;
continue;
}
if(strcmp(argv[i], "-lh") == 0)
{
++i;
if(i < argc)
{
localHistory = std::atoi(argv[i]);
if(localHistory < 0)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-brief_bytes") == 0)
{
++i;
if(i < argc)
{
briefBytes = std::atoi(argv[i]);
if(briefBytes < 1)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-fast_thr") == 0)
{
++i;
if(i < argc)
{
fastThr = std::atoi(argv[i]);
if(fastThr < 1)
{
showUsage();
}
}
else
{
showUsage();
}
continue;
}
if(strcmp(argv[i], "-icp") == 0)
{
icp = true;
continue;
}
if(strcmp(argv[i], "-flow") == 0)
{
flow = true;
continue;
}
if(strcmp(argv[i], "-mono") == 0)
{
mono = true;
continue;
}
if(strcmp(argv[i], "-p2p") == 0)
{
p2p = true;
continue;
}
if(strcmp(argv[i], "-debug") == 0)
{
ULogger::setLevel(ULogger::kDebug);
ULogger::setPrintTime(true);
ULogger::setPrintWhere(true);
continue;
}
printf("Unrecognized option : %s\n", argv[i]);
showUsage();
}
if(odomType > 1 && nnType == rtabmap::VWDictionary::kNNFlannKdTree)
{
UERROR("You set \"-o %d\" (binary descriptor), you must use \"-nn 2\" (any \"-nn\" other than kNNFlannKdTree)", odomType);
showUsage();
}
else if(odomType <= 1 && nnType == rtabmap::VWDictionary::kNNFlannLSH)
{
UERROR("You set \"-o %d\" (float descriptor), you must use \"-nn 1\" (any \"-nn\" other than kNNFlannLSH)", odomType);
showUsage();
}
if(inputDatabase.size())
{
UINFO("Using database input \"%s\"", inputDatabase.c_str());
}
else
{
UINFO("Using OpenNI camera");
}
std::string odomName;
if(odomType == 0)
{
odomName = "SURF";
}
else if(odomType == 1)
{
odomName = "SIFT";
}
else if(odomType == 2)
{
odomName = "ORB";
}
else if(odomType == 3)
{
odomName = "FAST+FREAK";
}
else if(odomType == 4)
{
odomName = "FAST+BRIEF";
}
else if(odomType == 5)
{
odomName = "GFTT+FREAK";
}
else if(odomType == 6)
{
odomName = "GFTT+BRIEF";
}
else if(odomType == 7)
{
odomName = "BRISK";
}
if(icp)
{
odomName= "ICP";
}
if(flow)
{
odomName= "Optical Flow";
}
std::string nnName;
if(nnType == 0)
{
nnName = "kNNFlannLinear";
}
else if(nnType == 1)
{
nnName = "kNNFlannKdTree";
}
else if(nnType == 2)
{
nnName= "kNNFlannLSH";
}
else if(nnType == 3)
{
nnName= "kNNBruteForce";
}
else if(nnType == 4)
{
nnName= "kNNBruteForceGPU";
}
UINFO("Odometry used = %s", odomName.c_str());
UINFO("Camera rate = %f Hz", rate);
UINFO("Maximum clouds shown = %d", maxClouds);
UINFO("Delay = %f s", sec);
UINFO("Max depth = %f", maxDepth);
UINFO("Reset odometry coutdown = %d", resetCountdown);
QApplication app(argc, argv);
rtabmap::Odometry * odom = 0;
rtabmap::ParametersMap parameters;
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomMaxDepth(), uNumber2Str(maxDepth)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomResetCountdown(), uNumber2Str(resetCountdown)));
if(!icp)
{
UINFO("Min inliers = %d", minInliers);
UINFO("Inlier maximum correspondences distance = %f", distance);
UINFO("RANSAC iterations = %d", iterations);
UINFO("Max features = %d", maxWords);
UINFO("GPU = %s", gpu?"true":"false");
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomInlierDistance(), uNumber2Str(distance)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomMinInliers(), uNumber2Str(minInliers)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomIterations(), uNumber2Str(iterations)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomMaxFeatures(), uNumber2Str(maxWords)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomFeatureType(), uNumber2Str(odomType)));
if(odomType == 0)
{
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kSURFGpuVersion(), uBool2Str(gpu)));
}
if(odomType == 2)
{
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kORBGpu(), uBool2Str(gpu)));
}
if(odomType == 3 || odomType == 4)
{
UINFO("FAST threshold = %d", fastThr);
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kFASTThreshold(), uNumber2Str(fastThr)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kFASTGpu(), uBool2Str(gpu)));
}
if(odomType == 4 || odomType == 6)
{
UINFO("BRIEF bytes = %d", briefBytes);
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kBRIEFBytes(), uNumber2Str(briefBytes)));
}
if(flow)
{
// Optical Flow
odom = new rtabmap::OdometryOpticalFlow(parameters);
}
else
{
//BOW
UINFO("Nearest neighbor = %s", nnName.c_str());
UINFO("Nearest neighbor ratio = %f", nndr);
UINFO("Local history = %d", localHistory);
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomBowNNType(), uNumber2Str(nnType)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomBowNNDR(), uNumber2Str(nndr)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomBowLocalHistorySize(), uNumber2Str(localHistory)));
if(mono)
{
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomPnPFlags(), uNumber2Str(0))); //CV_ITERATIVE
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomPnPReprojError(), "4.0"));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOdomIterations(), "100"));
odom = new rtabmap::OdometryMono(parameters);
}
else
{
odom = new rtabmap::OdometryBOW(parameters);
}
}
}
else if(icp) // ICP
{
UINFO("ICP maximum correspondences distance = %f", distance);
UINFO("ICP iterations = %d", iterations);
UINFO("Cloud decimation = %d", decimation);
UINFO("Cloud voxel size = %f", voxel);
UINFO("Cloud samples = %d", samples);
UINFO("Cloud correspondence ratio = %f", ratio);
UINFO("Cloud point to plane = %s", p2p?"false":"true");
odom = new rtabmap::OdometryICP(decimation, voxel, samples, distance, iterations, ratio, !p2p);
}
rtabmap::OdometryThread odomThread(odom);
rtabmap::OdometryViewer odomViewer(maxClouds, 2, 0.0, 50);
UEventsManager::addHandler(&odomThread);
UEventsManager::addHandler(&odomViewer);
odomViewer.setWindowTitle("Odometry view");
odomViewer.resize(1280, 480+QPushButton().minimumHeight());
if(inputDatabase.size())
{
rtabmap::DBReader camera(inputDatabase, rate, true);
if(camera.init())
{
odomThread.start();
if(sec > 0)
{
uSleep(sec*1000);
}
camera.start();
app.exec();
camera.join(true);
odomThread.join(true);
}
}
else
{
rtabmap::Camera * camera = 0;
rtabmap::Transform t=rtabmap::Transform(0,0,1,0, -1,0,0,0, 0,-1,0,0);
if(driver == 0)
{
camera = new rtabmap::CameraOpenni("", rate, t);
}
else if(driver == 1)
{
if(!rtabmap::CameraOpenNI2::available())
{
UERROR("Not built with OpenNI2 support...");
exit(-1);
}
camera = new rtabmap::CameraOpenNI2("", rate, t);
}
else if(driver == 2)
{
if(!rtabmap::CameraFreenect::available())
{
UERROR("Not built with Freenect support...");
exit(-1);
}
camera = new rtabmap::CameraFreenect(0, rate, t);
}
else if(driver == 3)
{
if(!rtabmap::CameraOpenNICV::available())
{
UERROR("Not built with OpenNI from OpenCV support...");
exit(-1);
}
camera = new rtabmap::CameraOpenNICV(false, rate, t);
}
else if(driver == 4)
{
if(!rtabmap::CameraOpenNICV::available())
{
UERROR("Not built with OpenNI from OpenCV support...");
exit(-1);
}
camera = new rtabmap::CameraOpenNICV(true, rate, t);
}
else if(driver == 5)
{
if(!rtabmap::CameraFreenect2::available())
{
UERROR("Not built with Freenect2 support...");
exit(-1);
}
camera = new rtabmap::CameraFreenect2(0, rtabmap::CameraFreenect2::kTypeRGBDepthSD, rate, t);
}
else if(driver == 6)
{
if(!rtabmap::CameraStereoDC1394::available())
{
UERROR("Not built with dc1394 support...");
exit(-1);
}
camera = new rtabmap::CameraStereoDC1394(rate, t);
}
else if(driver == 7)
{
if(!rtabmap::CameraStereoFlyCapture2::available())
{
UERROR("Not built with FlyCapture2/Triclops support...");
exit(-1);
}
camera = new rtabmap::CameraStereoFlyCapture2(rate, t);
}
else
{
UFATAL("Camera driver (%d) not found!", driver);
}
//pcl::console::setVerbosityLevel(pcl::console::L_DEBUG);
if(camera->init())
{
if(camera->isCalibrated())
{
rtabmap::CameraThread cameraThread(camera);
cameraThread.setColorOnly(true);
odomThread.start();
cameraThread.start();
odomViewer.exec();
cameraThread.join(true);
odomThread.join(true);
}
else
{
printf("The camera is not calibrated! You should calibrate the camera first.\n");
delete camera;
}
}
else
{
printf("Failed to initialize the camera! Please select another driver (see \"--help\").\n");
delete camera;
}
}
return 0;
}
| 24.51497 | 162 | 0.566097 | jackiecx |
06007cf5ea31140d74a080ecadaee399d74c1b7d | 418 | cpp | C++ | src/ganon-classify/main.cpp | mdehollander/ganon | 3a0b87fcda1f47455b4eefc6c47989b0c601f16f | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/ganon-classify/main.cpp | mdehollander/ganon | 3a0b87fcda1f47455b4eefc6c47989b0c601f16f | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/ganon-classify/main.cpp | mdehollander/ganon | 3a0b87fcda1f47455b4eefc6c47989b0c601f16f | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #include <ganon-classify/CommandLineParser.hpp>
#include <ganon-classify/GanonClassify.hpp>
#include <cstdlib>
#include <utility>
int main( int argc, char** argv )
{
if ( auto config = GanonClassify::CommandLineParser::parse( argc, argv ); config.has_value() )
{
return GanonClassify::run( std::move( config.value() ) ) ? EXIT_SUCCESS : EXIT_FAILURE;
}
return EXIT_FAILURE;
}
| 26.125 | 99 | 0.665072 | mdehollander |
06030ea4d9f1cf7b3c1d3dece9058db58eea34b4 | 930 | cpp | C++ | tests/sha3.cpp | calccrypto/Hashes | 4764d88bc71b4905141a208ab38f475cdc547f13 | [
"MIT"
] | 20 | 2016-01-10T13:53:41.000Z | 2022-01-28T02:09:07.000Z | tests/sha3.cpp | m0n0ph1/Hashes | 4764d88bc71b4905141a208ab38f475cdc547f13 | [
"MIT"
] | 1 | 2020-07-13T17:48:10.000Z | 2020-07-18T21:03:41.000Z | tests/sha3.cpp | m0n0ph1/Hashes | 4764d88bc71b4905141a208ab38f475cdc547f13 | [
"MIT"
] | 10 | 2017-05-15T16:25:59.000Z | 2022-02-03T15:31:11.000Z | #include <gtest/gtest.h>
#include "Hashes/SHA3.h"
#include "testvectors/sha/sha3.h"
TEST(SHA3, 224) {
EXPECT_EQ(SHA3 <224> ().blocksize(), (std::size_t) (1600 - 2 * 224));
EXPECT_EQ(SHA3 <224> ().digestsize(), (std::size_t) 224);
hash_test <SHA3 <224> > (SHA3_224_TEST_VECTORS);
}
TEST(SHA3, 256) {
EXPECT_EQ(SHA3 <256> ().blocksize(), (std::size_t) (1600 - 2 * 256));
EXPECT_EQ(SHA3 <256> ().digestsize(), (std::size_t) 256);
hash_test <SHA3 <256> > (SHA3_256_TEST_VECTORS);
}
TEST(SHA3, 384) {
EXPECT_EQ(SHA3 <384> ().blocksize(), (std::size_t) (1600 - 2 * 384));
EXPECT_EQ(SHA3 <384> ().digestsize(), (std::size_t) 384);
hash_test <SHA3 <384> > (SHA3_384_TEST_VECTORS);
}
TEST(SHA3, 512) {
EXPECT_EQ(SHA3 <512> ().blocksize(), (std::size_t) (1600 - 2 * 512));
EXPECT_EQ(SHA3 <512> ().digestsize(), (std::size_t) 512);
hash_test <SHA3 <512> > (SHA3_512_TEST_VECTORS);
}
| 31 | 74 | 0.617204 | calccrypto |
0605dd3228416c3c48a47a7a8707d3c5cb88e37f | 997 | cpp | C++ | dataset/test/modification/1466_all/24/transformation_1.cpp | Karina5005/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | 3 | 2022-02-15T00:29:39.000Z | 2022-03-15T08:36:44.000Z | dataset/test/modification/1466_all/24/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | dataset/test/modification/1466_all/24/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | #include <iomanip>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void iev_mv()
;
int main()
;
void r() {
int ky_fzo;
cin >> ky_fzo;
int kxt[ky_fzo];
map<int, int> keo;
{
int ow = 0;
if (5 > 3) cout << "new code";for ( ; ow < ky_fzo; )
/* 'for' inside */
{
cin >> kxt[ow];
ow++;
}}
sort(kxt, kxt + ky_fzo);
{
int xev = 1;
if (5 > 3) cout << "new code";for ( ; xev < ky_fzo; )
/* 'for' inside */
{
/* 'if' begin */
if (kxt[xev] <= kxt[xev - 1])
/* 'if' inside */
kxt[xev]++;
xev++;
}}
{
int vr_o = 0;
if (5 > 3) cout << "new code";for ( ; vr_o < ky_fzo; )
/* 'for' inside */
{
keo[kxt[vr_o]]++;
vr_o++;
}}
cout << keo.size() << endl;
}
int main() {
int wew = 1;
cin >> wew;
if (5 > 3) cout << "new code";for ( ; wew--; )
/* 'for' inside */
{
r();
}
return 0;
}
| 15.338462 | 59 | 0.408225 | Karina5005 |
060b83e07c1257e5b4098b32de1b9fe5ccf76a36 | 1,010 | cpp | C++ | modules/gin_metadata/gin_metadata.cpp | peterrudenko/Gin | 449c4c6b83fbec91070dc87d124c60a7d1f8c0a5 | [
"BSD-3-Clause"
] | null | null | null | modules/gin_metadata/gin_metadata.cpp | peterrudenko/Gin | 449c4c6b83fbec91070dc87d124c60a7d1f8c0a5 | [
"BSD-3-Clause"
] | null | null | null | modules/gin_metadata/gin_metadata.cpp | peterrudenko/Gin | 449c4c6b83fbec91070dc87d124c60a7d1f8c0a5 | [
"BSD-3-Clause"
] | null | null | null | /*==============================================================================
Copyright 2018 by Roland Rabien
For more information visit www.rabiensoftware.com
==============================================================================*/
// Your project must contain an AppConfig.h file with your project-specific settings in it,
// and your header search path must make it accessible to the module's files.
#include "AppConfig.h"
#ifdef _WIN32
#include <Windows.h>
#include <ctime>
#endif
//==============================================================================
#include "gin_metadata.h"
//==============================================================================
namespace gin
{
using namespace juce;
using juce::Rectangle;
using juce::MemoryBlock;
#include "metadata/libjpegpng.cpp"
#include "metadata/commentmetadata.cpp"
#include "metadata/exifmetadata.cpp"
#include "metadata/imagemetadata.cpp"
#include "metadata/iptcmetadata.cpp"
#include "metadata/xmpmetadata.cpp"
}
| 26.578947 | 91 | 0.526733 | peterrudenko |
060c5679378209dd375f26dfcd5fb005acb9cdb0 | 622 | cpp | C++ | CodeChef/Practice/GDOG.cpp | ysumit99/Compi-Coding | d0e96c4f024328b0bfb799fab927919dae367f7a | [
"MIT"
] | 1 | 2019-04-19T13:06:33.000Z | 2019-04-19T13:06:33.000Z | CodeChef/Practice/GDOG.cpp | ysumit99/Compi-Coding | d0e96c4f024328b0bfb799fab927919dae367f7a | [
"MIT"
] | null | null | null | CodeChef/Practice/GDOG.cpp | ysumit99/Compi-Coding | d0e96c4f024328b0bfb799fab927919dae367f7a | [
"MIT"
] | null | null | null | //https://www.codechef.com/problems/GDOG
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
#ifdef DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base ::sync_with_stdio(false);
cin.tie(0);
int t, n, k;
cin >> t;
while (t--)
{
cin >> n >> k;
int max = INT_MIN, temp;
for (int i = 1; i <= k; i++)
{
temp = n - (n / i) * i;
if (temp > max)
{
max = temp;
}
}
cout << max << endl;
}
return 0;
} | 16.368421 | 40 | 0.442122 | ysumit99 |
060d7013508e95574467d57a0846b6e1430e8552 | 282 | cc | C++ | Part-III/Ch13/13.1.1/13.5.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | 1 | 2021-09-23T13:13:12.000Z | 2021-09-23T13:13:12.000Z | Part-III/Ch13/13.1.1/13.5.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | null | null | null | Part-III/Ch13/13.1.1/13.5.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | null | null | null | #include <string>
class HasPtr
{
public:
HasPtr(const std::string &s = std::string())
: ps(new std::string(s)), i(0)
{}
HasPtr(const HasPtr &has_ptr)
: ps(new std::string(*(has_ptr.ps))), i(has_ptr.i)
{}
private:
std::string *ps;
int i;
}; | 16.588235 | 58 | 0.549645 | RingZEROtlf |
06117e726c94d35380790a0ef0f9360a84eef171 | 692 | cpp | C++ | q11727.cpp | abraxaslee/ACM-ICPC | d8db31a4a2a36258bfba42a806b02bbf3eceaf2b | [
"MIT"
] | 1 | 2018-03-19T05:18:49.000Z | 2018-03-19T05:18:49.000Z | q11727.cpp | abraxaslee/ACM-ICPC | d8db31a4a2a36258bfba42a806b02bbf3eceaf2b | [
"MIT"
] | null | null | null | q11727.cpp | abraxaslee/ACM-ICPC | d8db31a4a2a36258bfba42a806b02bbf3eceaf2b | [
"MIT"
] | null | null | null | //q11727.cpp - 2011/10/11
//accepted at 2011/10/11
//run time = 0.000
#include <stdio.h>
using namespace std;
int salary[3] = {};
int top = 0;
void sort(int inputNum){
int i;
for(i = top-1; i >= 0 && salary[i] > inputNum; i--){
salary[i+1] = salary[i];
}
i += 1;
salary[i] = inputNum;
top += 1;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("q11727.in", "r", stdin);
freopen("q11727.out", "w", stdout);
#endif
int caseNum, currentCase = 0, tmp;
scanf("%d", &caseNum);
while(caseNum-- > 0){
top = 0;
for(int j=0;j<3;j++){
scanf("%d", &tmp);
sort(tmp);
}
printf("Case %d: %d\n", ++currentCase, salary[1]);
}
return 0;
}
| 17.3 | 54 | 0.537572 | abraxaslee |
061303968b4bb3db66ec033910e2e33fc93fb898 | 73,441 | cpp | C++ | Core/burn/drv/dataeast/d_rohga.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 17 | 2018-05-24T05:20:45.000Z | 2021-12-24T07:27:22.000Z | Core/burn/drv/dataeast/d_rohga.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 6 | 2016-10-20T02:36:07.000Z | 2017-03-08T15:23:06.000Z | Core/burn/drv/dataeast/d_rohga.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 5 | 2019-01-21T00:45:00.000Z | 2021-07-20T08:34:22.000Z | // FB Alpha Rohga Armor Force / Wizard Fire / Nitro Ball / Schmeiser Robo driver module
// Based on MAME driver by Bryan McPhail
#include "tiles_generic.h"
#include "m68000_intf.h"
#include "h6280_intf.h"
#include "deco16ic.h"
#include "msm6295.h"
#include "burn_ym2151.h"
static UINT8 *AllMem;
static UINT8 *MemEnd;
static UINT8 *AllRam;
static UINT8 *RamEnd;
static UINT8 *Drv68KROM;
static UINT8 *DrvHucROM;
static UINT8 *DrvGfxROM0;
static UINT8 *DrvGfxROM1;
static UINT8 *DrvGfxROM2;
static UINT8 *DrvGfxROM3;
static UINT8 *DrvGfxROM4;
static UINT8 *DrvSndROM0;
static UINT8 *DrvSndROM1;
static UINT8 *Drv68KRAM;
static UINT8 *DrvHucRAM;
static UINT8 *DrvPalRAM;
static UINT8 *DrvPalBuf;
static UINT8 *DrvSprRAM;
static UINT8 *DrvSprRAM2;
static UINT8 *DrvSprBuf;
static UINT8 *DrvSprBuf2;
static UINT8 *DrvPrtRAM;
static UINT32 *DrvPalette;
static UINT8 DrvRecalc;
static UINT8 *flipscreen;
static UINT8 DrvJoy1[16];
static UINT8 DrvJoy2[16];
static UINT8 DrvJoy3[16];
static UINT8 DrvDips[3];
static UINT8 DrvReset;
static UINT16 DrvInputs[4];
static UINT16 *tempdraw[2];
static INT32 DrvOkiBank;
static struct BurnInputInfo RohgaInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvJoy2 + 0, "p1 coin" },
{"P1 Start", BIT_DIGITAL, DrvJoy1 + 7, "p1 start" },
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" },
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" },
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left" },
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right" },
{"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" },
{"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" },
{"P1 Button 3", BIT_DIGITAL, DrvJoy1 + 6, "p1 fire 3" },
{"P2 Coin", BIT_DIGITAL, DrvJoy2 + 1, "p2 coin" },
{"P2 Start", BIT_DIGITAL, DrvJoy1 + 15, "p2 start" },
{"P2 Up", BIT_DIGITAL, DrvJoy1 + 8, "p2 up" },
{"P2 Down", BIT_DIGITAL, DrvJoy1 + 9, "p2 down" },
{"P2 Left", BIT_DIGITAL, DrvJoy1 + 10, "p2 left" },
{"P2 Right", BIT_DIGITAL, DrvJoy1 + 11, "p2 right" },
{"P2 Button 1", BIT_DIGITAL, DrvJoy1 + 12, "p2 fire 1" },
{"P2 Button 2", BIT_DIGITAL, DrvJoy1 + 13, "p2 fire 2" },
{"P2 Button 3", BIT_DIGITAL, DrvJoy1 + 14, "p2 fire 3" },
{"Reset", BIT_DIGITAL, &DrvReset, "reset" },
{"Service", BIT_DIGITAL, DrvJoy2 + 2, "service" },
{"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" },
{"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" },
{"Dip C", BIT_DIPSWITCH, DrvDips + 2, "dip" },
};
STDINPUTINFO(Rohga)
static struct BurnInputInfo WizdfireInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvJoy2 + 0, "p1 coin" },
{"P1 Start", BIT_DIGITAL, DrvJoy1 + 7, "p1 start" },
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" },
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" },
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left" },
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right" },
{"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" },
{"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" },
{"P2 Coin", BIT_DIGITAL, DrvJoy2 + 1, "p2 coin" },
{"P2 Start", BIT_DIGITAL, DrvJoy1 + 15, "p2 start" },
{"P2 Up", BIT_DIGITAL, DrvJoy1 + 8, "p2 up" },
{"P2 Down", BIT_DIGITAL, DrvJoy1 + 9, "p2 down" },
{"P2 Left", BIT_DIGITAL, DrvJoy1 + 10, "p2 left" },
{"P2 Right", BIT_DIGITAL, DrvJoy1 + 11, "p2 right" },
{"P2 Button 1", BIT_DIGITAL, DrvJoy1 + 12, "p2 fire 1" },
{"P2 Button 2", BIT_DIGITAL, DrvJoy1 + 13, "p2 fire 2" },
{"Reset", BIT_DIGITAL, &DrvReset, "reset" },
{"Service", BIT_DIGITAL, DrvJoy2 + 2, "service" },
{"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" },
{"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" },
};
STDINPUTINFO(Wizdfire)
static struct BurnInputInfo NitrobalInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvJoy2 + 0, "p1 coin" },
{"P1 Start", BIT_DIGITAL, DrvJoy1 + 7, "p1 start" },
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" },
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" },
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left" },
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right" },
{"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" },
{"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" },
{"P2 Coin", BIT_DIGITAL, DrvJoy2 + 1, "p2 coin" },
{"P2 Start", BIT_DIGITAL, DrvJoy1 + 15, "p2 start" },
{"P2 Up", BIT_DIGITAL, DrvJoy1 + 8, "p2 up" },
{"P2 Down", BIT_DIGITAL, DrvJoy1 + 9, "p2 down" },
{"P2 Left", BIT_DIGITAL, DrvJoy1 + 10, "p2 left" },
{"P2 Right", BIT_DIGITAL, DrvJoy1 + 11, "p2 right" },
{"P2 Button 1", BIT_DIGITAL, DrvJoy1 + 12, "p2 fire 1" },
{"P2 Button 2", BIT_DIGITAL, DrvJoy1 + 13, "p2 fire 2" },
{"P3 Coin", BIT_DIGITAL, DrvJoy3 + 7, "p3 coin" },
{"P3 Up", BIT_DIGITAL, DrvJoy3 + 0, "p3 up" },
{"P3 Down", BIT_DIGITAL, DrvJoy3 + 1, "p3 down" },
{"P3 Left", BIT_DIGITAL, DrvJoy3 + 2, "p3 left" },
{"P3 Right", BIT_DIGITAL, DrvJoy3 + 3, "p3 right" },
{"P3 Button 1", BIT_DIGITAL, DrvJoy3 + 4, "p3 fire 1" },
{"P3 Button 2", BIT_DIGITAL, DrvJoy3 + 5, "p3 fire 2" },
{"Reset", BIT_DIGITAL, &DrvReset, "reset" },
{"Service", BIT_DIGITAL, DrvJoy2 + 2, "service" },
{"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" },
{"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" },
};
STDINPUTINFO(Nitrobal)
static struct BurnDIPInfo RohgaDIPList[]=
{
{0x14, 0xff, 0xff, 0xff, NULL },
{0x15, 0xff, 0xff, 0x7f, NULL },
{0x16, 0xff, 0xff, 0xff, NULL },
{0 , 0xfe, 0 , 8, "Coin A" },
{0x14, 0x01, 0x07, 0x00, "3 Coins 1 Credits" },
{0x14, 0x01, 0x07, 0x01, "2 Coins 1 Credits" },
{0x14, 0x01, 0x07, 0x07, "1 Coin 1 Credits" },
{0x14, 0x01, 0x07, 0x06, "1 Coin 2 Credits" },
{0x14, 0x01, 0x07, 0x05, "1 Coin 3 Credits" },
{0x14, 0x01, 0x07, 0x04, "1 Coin 4 Credits" },
{0x14, 0x01, 0x07, 0x03, "1 Coin 5 Credits" },
{0x14, 0x01, 0x07, 0x02, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 8, "Coin B" },
{0x14, 0x01, 0x38, 0x00, "3 Coins 1 Credits" },
{0x14, 0x01, 0x38, 0x08, "2 Coins 1 Credits" },
{0x14, 0x01, 0x38, 0x38, "1 Coin 1 Credits" },
{0x14, 0x01, 0x38, 0x30, "1 Coin 2 Credits" },
{0x14, 0x01, 0x38, 0x28, "1 Coin 3 Credits" },
{0x14, 0x01, 0x38, 0x20, "1 Coin 4 Credits" },
{0x14, 0x01, 0x38, 0x18, "1 Coin 5 Credits" },
{0x14, 0x01, 0x38, 0x10, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 2, "Flip Screen" },
{0x14, 0x01, 0x40, 0x40, "Off" },
{0x14, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "2 Credits to Start, 1 to Continue" },
{0x14, 0x01, 0x80, 0x80, "Off" },
{0x14, 0x01, 0x80, 0x00, "On" },
{0 , 0xfe, 0 , 4, "Player's Vitality" },
{0x15, 0x01, 0x30, 0x30, "Normal" },
{0x15, 0x01, 0x30, 0x20, "Low" },
{0x15, 0x01, 0x30, 0x10, "Lowest" },
{0x15, 0x01, 0x30, 0x00, "High" },
{0 , 0xfe, 0 , 2, "Allow Continue" },
{0x15, 0x01, 0x40, 0x40, "Off" },
{0x15, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x15, 0x01, 0x80, 0x80, "Off" },
{0x15, 0x01, 0x80, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Stage Clear Bonus" },
{0x16, 0x01, 0x01, 0x01, "Off" },
{0x16, 0x01, 0x01, 0x00, "On" },
{0 , 0xfe, 0 , 4, "Enemy's Vitality" },
{0x16, 0x01, 0x0c, 0x08, "Low" },
{0x16, 0x01, 0x0c, 0x0c, "Normal" },
{0x16, 0x01, 0x0c, 0x04, "High" },
{0x16, 0x01, 0x0c, 0x00, "Highest" },
{0 , 0xfe, 0 , 4, "Enemy Encounter Rate" },
{0x16, 0x01, 0x30, 0x20, "Low" },
{0x16, 0x01, 0x30, 0x30, "Normal" },
{0x16, 0x01, 0x30, 0x10, "High" },
{0x16, 0x01, 0x30, 0x00, "Highest" },
{0 , 0xfe, 0 , 4, "Enemy's Weapon Speed" },
{0x16, 0x01, 0xc0, 0x80, "Slow" },
{0x16, 0x01, 0xc0, 0xc0, "Normal" },
{0x16, 0x01, 0xc0, 0x40, "Fast" },
{0x16, 0x01, 0xc0, 0x00, "Fastest" },
};
STDDIPINFO(Rohga)
static struct BurnDIPInfo SchmeisrDIPList[]=
{
{0x14, 0xff, 0xff, 0xff, NULL },
{0x15, 0xff, 0xff, 0xff, NULL },
{0x16, 0xff, 0xff, 0xff, NULL },
{0 , 0xfe, 0 , 8, "Coin A" },
{0x14, 0x01, 0x07, 0x00, "3 Coins 1 Credits" },
{0x14, 0x01, 0x07, 0x01, "2 Coins 1 Credits" },
{0x14, 0x01, 0x07, 0x07, "1 Coin 1 Credits" },
{0x14, 0x01, 0x07, 0x06, "1 Coin 2 Credits" },
{0x14, 0x01, 0x07, 0x05, "1 Coin 3 Credits" },
{0x14, 0x01, 0x07, 0x04, "1 Coin 4 Credits" },
{0x14, 0x01, 0x07, 0x03, "1 Coin 5 Credits" },
{0x14, 0x01, 0x07, 0x02, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 8, "Coin B" },
{0x14, 0x01, 0x38, 0x00, "3 Coins 1 Credits" },
{0x14, 0x01, 0x38, 0x08, "2 Coins 1 Credits" },
{0x14, 0x01, 0x38, 0x38, "1 Coin 1 Credits" },
{0x14, 0x01, 0x38, 0x30, "1 Coin 2 Credits" },
{0x14, 0x01, 0x38, 0x28, "1 Coin 3 Credits" },
{0x14, 0x01, 0x38, 0x20, "1 Coin 4 Credits" },
{0x14, 0x01, 0x38, 0x18, "1 Coin 5 Credits" },
{0x14, 0x01, 0x38, 0x10, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 2, "Flip Screen" },
{0x14, 0x01, 0x40, 0x40, "Off" },
{0x14, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Service Mode" },
{0x14, 0x01, 0x80, 0x80, "Off" },
{0x14, 0x01, 0x80, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x15, 0x01, 0x04, 0x00, "Off" },
{0x15, 0x01, 0x04, 0x04, "On" },
{0 , 0xfe, 0 , 2, "Freeze Screen" },
{0x16, 0x01, 0x20, 0x20, "Off" },
{0x16, 0x01, 0x20, 0x00, "On" },
};
STDDIPINFO(Schmeisr)
static struct BurnDIPInfo WizdfireDIPList[]=
{
{0x12, 0xff, 0xff, 0xff, NULL },
{0x13, 0xff, 0xff, 0x7f, NULL },
{0 , 0xfe, 0 , 8, "Coin A" },
{0x12, 0x01, 0x07, 0x00, "3 Coins 1 Credits" },
{0x12, 0x01, 0x07, 0x01, "2 Coins 1 Credits" },
{0x12, 0x01, 0x07, 0x07, "1 Coin 1 Credits" },
{0x12, 0x01, 0x07, 0x06, "1 Coin 2 Credits" },
{0x12, 0x01, 0x07, 0x05, "1 Coin 3 Credits" },
{0x12, 0x01, 0x07, 0x04, "1 Coin 4 Credits" },
{0x12, 0x01, 0x07, 0x03, "1 Coin 5 Credits" },
{0x12, 0x01, 0x07, 0x02, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 8, "Coin B" },
{0x12, 0x01, 0x38, 0x00, "3 Coins 1 Credits" },
{0x12, 0x01, 0x38, 0x08, "2 Coins 1 Credits" },
{0x12, 0x01, 0x38, 0x38, "1 Coin 1 Credits" },
{0x12, 0x01, 0x38, 0x30, "1 Coin 2 Credits" },
{0x12, 0x01, 0x38, 0x28, "1 Coin 3 Credits" },
{0x12, 0x01, 0x38, 0x20, "1 Coin 4 Credits" },
{0x12, 0x01, 0x38, 0x18, "1 Coin 5 Credits" },
{0x12, 0x01, 0x38, 0x10, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 2, "Flip Screen" },
{0x12, 0x01, 0x40, 0x40, "Off" },
{0x12, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "2 Credits to Start, 1 to Continue" },
{0x12, 0x01, 0x80, 0x80, "Off" },
{0x12, 0x01, 0x80, 0x00, "On" },
{0 , 0xfe, 0 , 4, "Lives" },
{0x13, 0x01, 0x03, 0x00, "2" },
{0x13, 0x01, 0x03, 0x01, "3" },
{0x13, 0x01, 0x03, 0x03, "4" },
{0x13, 0x01, 0x03, 0x02, "5" },
{0 , 0xfe, 0 , 4, "Difficulty" },
{0x13, 0x01, 0x0c, 0x08, "Easy" },
{0x13, 0x01, 0x0c, 0x0c, "Normal" },
{0x13, 0x01, 0x0c, 0x04, "Hard" },
{0x13, 0x01, 0x0c, 0x00, "Hardest" },
{0 , 0xfe, 0 , 4, "Magic Gauge Speed" },
{0x13, 0x01, 0x30, 0x00, "Very Slow" },
{0x13, 0x01, 0x30, 0x10, "Slow" },
{0x13, 0x01, 0x30, 0x30, "Normal" },
{0x13, 0x01, 0x30, 0x20, "Fast" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x13, 0x01, 0x80, 0x80, "Off" },
{0x13, 0x01, 0x80, 0x00, "On" },
};
STDDIPINFO(Wizdfire)
static struct BurnDIPInfo NitrobalDIPList[]=
{
{0x19, 0xff, 0xff, 0xff, NULL },
{0x1a, 0xff, 0xff, 0x7f, NULL },
{0 , 0xfe, 0 , 8, "Coin A" },
{0x19, 0x01, 0x07, 0x00, "3 Coins 1 Credits" },
{0x19, 0x01, 0x07, 0x01, "2 Coins 1 Credits" },
{0x19, 0x01, 0x07, 0x07, "1 Coin 1 Credits" },
{0x19, 0x01, 0x07, 0x06, "1 Coin 2 Credits" },
{0x19, 0x01, 0x07, 0x05, "1 Coin 3 Credits" },
{0x19, 0x01, 0x07, 0x04, "1 Coin 4 Credits" },
{0x19, 0x01, 0x07, 0x03, "1 Coin 5 Credits" },
{0x19, 0x01, 0x07, 0x02, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 8, "Coin B" },
{0x19, 0x01, 0x38, 0x00, "3 Coins 1 Credits" },
{0x19, 0x01, 0x38, 0x08, "2 Coins 1 Credits" },
{0x19, 0x01, 0x38, 0x38, "1 Coin 1 Credits" },
{0x19, 0x01, 0x38, 0x30, "1 Coin 2 Credits" },
{0x19, 0x01, 0x38, 0x28, "1 Coin 3 Credits" },
{0x19, 0x01, 0x38, 0x20, "1 Coin 4 Credits" },
{0x19, 0x01, 0x38, 0x18, "1 Coin 5 Credits" },
{0x19, 0x01, 0x38, 0x10, "1 Coin 6 Credits" },
{0 , 0xfe, 0 , 2, "Flip Screen" },
{0x19, 0x01, 0x40, 0x40, "Off" },
{0x19, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "2 Credits to Start, 1 to Continue" },
{0x19, 0x01, 0x80, 0x80, "Off" },
{0x19, 0x01, 0x80, 0x00, "On" },
{0 , 0xfe, 0 , 4, "Lives" },
{0x1a, 0x01, 0x03, 0x01, "1" },
{0x1a, 0x01, 0x03, 0x00, "2" },
{0x1a, 0x01, 0x03, 0x03, "3" },
{0x1a, 0x01, 0x03, 0x02, "4" },
{0 , 0xfe, 0 , 4, "Difficulty?" },
{0x1a, 0x01, 0x0c, 0x08, "Easy" },
{0x1a, 0x01, 0x0c, 0x0c, "Normal" },
{0x1a, 0x01, 0x0c, 0x04, "Hard" },
{0x1a, 0x01, 0x0c, 0x00, "Hardest" },
{0 , 0xfe, 0 , 2, "Split Coin Chutes" },
{0x1a, 0x01, 0x10, 0x10, "Off" },
{0x1a, 0x01, 0x10, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Players" },
{0x1a, 0x01, 0x20, 0x20, "2" },
{0x1a, 0x01, 0x20, 0x00, "3" },
{0 , 0xfe, 0 , 2, "Shot Button to Start" },
{0x1a, 0x01, 0x40, 0x40, "Off" },
{0x1a, 0x01, 0x40, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x1a, 0x01, 0x80, 0x80, "Off" },
{0x1a, 0x01, 0x80, 0x00, "On" },
};
STDDIPINFO(Nitrobal)
void __fastcall rohga_main_write_word(UINT32 address, UINT16 data)
{
deco16_write_control_word(0, address, 0x200000, data)
deco16_write_control_word(1, address, 0x240000, data)
switch (address)
{
case 0x2800a8:
deco16_soundlatch = data & 0xff;
h6280SetIRQLine(0, H6280_IRQSTATUS_ACK);
return;
case 0x300000:
memcpy (DrvSprBuf2, DrvSprBuf, 0x800);
memcpy (DrvSprBuf, DrvSprRAM, 0x800);
return;
case 0x31000a:
memcpy (DrvPalBuf, DrvPalRAM, 0x2000);
return;
case 0x321100: // schmeisr
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return;
case 0x322000:
deco16_priority = data;
return;
}
if ((address & 0xffff000) == 0x280000) {
deco16_104_rohga_prot_w(address, data, 0xffff);
return;
}
}
void __fastcall rohga_main_write_byte(UINT32 address, UINT8 data)
{
switch (address)
{
case 0x2800a9:
deco16_soundlatch = data;
h6280SetIRQLine(0, H6280_IRQSTATUS_ACK);
return;
case 0x300000:
case 0x300001:
memcpy (DrvSprBuf2, DrvSprBuf, 0x800);
memcpy (DrvSprBuf, DrvSprRAM, 0x800);
return;
case 0x31000a:
case 0x31000b:
memcpy (DrvPalBuf, DrvPalRAM, 0x2000);
return;
case 0x321100: // schmeisr
case 0x321101:
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return;
case 0x322000:
case 0x322001:
deco16_priority = data;
return;
}
if ((address & 0xffff000) == 0x280000) {
deco16_104_rohga_prot_w(address, data, 0x00ff << ((address & 1) << 3));
return;
}
}
UINT16 __fastcall rohga_main_read_word(UINT32 address)
{
switch (address)
{
case 0x2c0000:
case 0x300000: // schmeisr
return DrvDips[2];
case 0x310002: // schmeisr
return (DrvInputs[1] & 0x07) | (deco16_vblank & 0x08);
case 0x321100:
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return 0;
}
if ((address & 0xffff000) == 0x280000) {
return deco16_104_rohga_prot_r(address);
}
return 0;
}
UINT8 __fastcall rohga_main_read_byte(UINT32 address)
{
switch (address)
{
case 0x2c0000:
case 0x2c0001:
case 0x300000: // schmeisr
case 0x300001:
return DrvDips[2];
case 0x310002: // schmeisr
case 0x310003:
return (DrvInputs[1] & 0x07) | (deco16_vblank & 0x08);
case 0x321100:
case 0x321101:
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return 0;
}
if ((address & 0xffff000) == 0x280000) {
return deco16_104_rohga_prot_r(address) >> ((~address & 1) << 3);
}
return 0;
}
void __fastcall wizdfire_main_write_word(UINT32 address, UINT16 data)
{
deco16_write_control_word(0, address, 0x300000, data)
deco16_write_control_word(1, address, 0x310000, data)
switch (address)
{
case 0x350000:
memcpy (DrvSprBuf, DrvSprRAM, 0x800);
return;
case 0x370000:
memcpy (DrvSprBuf2, DrvSprRAM2, 0x800);
return;
case 0x380008:
memcpy (DrvPalBuf, DrvPalRAM, 0x2000);
return;
case 0x320000:
deco16_priority = data;
return;
case 0x320004:
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return;
case 0xfe4150:
case 0xff4260: // nitrobal
case 0xff4a60:
deco16_soundlatch = data & 0xff;
h6280SetIRQLine(0, H6280_IRQSTATUS_ACK);
return;
}
if ((address & 0xffff000) == 0xfe4000) {
deco16_prot_ram[(address & 0x7ff)/2] = data;
return;
}
if ((address & 0xffff000) == 0xff4000) {
deco16_146_nitroball_prot_w(address, data, 0xffff);
return;
}
}
void __fastcall wizdfire_main_write_byte(UINT32 address, UINT8 data)
{
switch (address)
{
case 0x350000:
case 0x350001:
memcpy (DrvSprBuf, DrvSprRAM, 0x800);
return;
case 0x370000:
case 0x370001:
memcpy (DrvSprBuf2, DrvSprRAM2, 0x800);
return;
case 0x380008:
case 0x380009:
memcpy (DrvPalBuf, DrvPalRAM, 0x2000);
return;
case 0x320000:
case 0x320001:
deco16_priority = data;
return;
case 0x320004:
case 0x320005:
SekSetIRQLine(6, SEK_IRQSTATUS_NONE);
return;
case 0xfe4151:
case 0xff4261: // nitrobal
case 0xff4a61:
deco16_soundlatch = data;
h6280SetIRQLine(0, H6280_IRQSTATUS_ACK);
return;
}
if ((address & 0xffff000) == 0xfe4000) {
DrvPrtRAM[(address & 0x7ff)^1] = data;
return;
}
if ((address & 0xffff000) == 0xff4000) {
deco16_146_nitroball_prot_w(address, data, 0x00ff << ((address & 1) << 3));
return;
}
}
UINT16 __fastcall wizdfire_main_read_word(UINT32 address)
{
if (address == 0x320000) return DrvInputs[2];
if ((address & 0xffff800) == 0xfe4000) {
return deco16_104_prot_r(address);
}
if ((address & 0xffff000) == 0xff4000) {
return deco16_146_nitroball_prot_r(address);
}
return 0;
}
UINT8 __fastcall wizdfire_main_read_byte(UINT32 address)
{
if (address == 0x320000 || address == 0x320001) return DrvInputs[2] >> ((~address & 1) << 3);
if ((address & 0xffff800) == 0xfe4000) {
return deco16_104_prot_r(address) >> ((~address & 1) << 3);
}
if ((address & 0xffff000) == 0xff4000) {
return deco16_146_nitroball_prot_r(address) >> ((~address & 1) << 3);
}
return 0;
}
static void DrvYM2151WritePort(UINT32, UINT32 data)
{
if ((data & 0x01) != (UINT32)(DrvOkiBank & 0x01)) {
memcpy (DrvSndROM0, DrvSndROM0 + 0x40000 + ((data & 0x01) >> 0) * 0x40000, 0x40000);
}
if ((data & 0x02) != (UINT32)(DrvOkiBank & 0x02)) {
memcpy (DrvSndROM1, DrvSndROM1 + 0x40000 + ((data & 0x02) >> 1) * 0x40000, 0x40000);
}
DrvOkiBank = data;
}
static INT32 rohga_bank_callback( const INT32 bank )
{
return ((bank >> 4) & 0x3) << 12;
}
static INT32 DrvDoReset()
{
memset (AllRam, 0, RamEnd - AllRam);
SekOpen(0);
SekReset();
SekClose();
deco16SoundReset();
deco16Reset();
DrvOkiBank = -1;
DrvYM2151WritePort(0, 3);
return 0;
}
static INT32 MemIndex()
{
UINT8 *Next; Next = AllMem;
Drv68KROM = Next; Next += 0x200000;
DrvHucROM = Next; Next += 0x010000;
DrvGfxROM0 = Next; Next += 0x080000;
DrvGfxROM1 = Next; Next += 0x400000;
DrvGfxROM2 = Next; Next += 0x400000;
DrvGfxROM3 = Next; Next += 0x800000;
DrvGfxROM4 = Next; Next += 0x100000;
MSM6295ROM = Next;
DrvSndROM0 = Next; Next += 0x100000;
DrvSndROM1 = Next; Next += 0x0c0000;
tempdraw[0] = (UINT16*)Next; Next += 320 * 240 * sizeof(UINT16);
tempdraw[1] = (UINT16*)Next; Next += 320 * 240 * sizeof(UINT16);
DrvPalette = (UINT32*)Next; Next += 0x0800 * sizeof(UINT32);
AllRam = Next;
Drv68KRAM = Next; Next += 0x024000;
DrvHucRAM = Next; Next += 0x002000;
DrvSprRAM2 = Next; Next += 0x000800;
DrvSprRAM = Next; Next += 0x000800;
DrvSprBuf2 = Next; Next += 0x000800;
DrvSprBuf = Next; Next += 0x000800;
deco16_prot_ram = (UINT16*)Next;
DrvPrtRAM = Next; Next += 0x000800;
deco16_buffer_ram = (UINT16*)Next; Next += 0x000800;
DrvPalRAM = Next; Next += 0x002000;
DrvPalBuf = Next; Next += 0x002000;
flipscreen = Next; Next += 0x000001;
RamEnd = Next;
MemEnd = Next;
return 0;
}
static INT32 DrvSpriteDecode()
{
INT32 Plane[6] = { 0x400000*8+8, 0x400000*8, 0x200000*8+8, 0x200000*8, 8, 0 };
INT32 XOffs[16] = { 7,6,5,4,3,2,1,0, 32*8+7, 32*8+6, 32*8+5, 32*8+4, 32*8+3, 32*8+2, 32*8+1, 32*8+0 };
INT32 YOffs[16] = { 15*16, 14*16, 13*16, 12*16, 11*16, 10*16, 9*16, 8*16, 7*16, 6*16, 5*16, 4*16, 3*16, 2*16, 1*16, 0*16};
UINT8 *tmp = (UINT8*)BurnMalloc(0x600000);
if (tmp == NULL) {
return 1;
}
memcpy (tmp, DrvGfxROM3, 0x600000);
GfxDecode(0x8000, 6, 16, 16, Plane, XOffs, YOffs, 0x200, tmp, DrvGfxROM3);
BurnFree (tmp);
return 0;
}
static INT32 RohgaInit()
{
BurnSetRefreshRate(58.00);
AllMem = NULL;
MemIndex();
INT32 nLen = MemEnd - (UINT8 *)0;
if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
{
if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x100001, 2, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x100000, 3, 2)) return 1;
if (BurnLoadRom(DrvHucROM + 0x000000, 4, 1)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000000, 5, 2)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000001, 6, 2)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x000000, 7, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x080000, 8, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x000000, 9, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x100000, 10, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000000, 11, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x100000, 12, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200000, 13, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x300000, 14, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x400000, 15, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x500000, 16, 1)) return 1;
if (BurnLoadRom(DrvSndROM0 + 0x040000, 17, 1)) return 1;
if (BurnLoadRom(DrvSndROM1 + 0x040000, 18, 1)) return 1;
deco56_decrypt_gfx(DrvGfxROM0, 0x020000);
deco56_decrypt_gfx(DrvGfxROM1, 0x100000);
deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x020000, 1);
deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x100000, 0);
deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x200000, 0);
DrvSpriteDecode();
}
deco16Init(0, 0, 1);
deco16_set_graphics(DrvGfxROM0, 0x20000 * 2, DrvGfxROM1, 0x100000 * 2, DrvGfxROM2, 0x200000 * 2);
deco16_set_color_base(2, 512);
deco16_set_color_base(3, 768);
deco16_set_global_offsets(0, 8);
deco16_set_bank_callback(0, rohga_bank_callback);
deco16_set_bank_callback(1, rohga_bank_callback);
deco16_set_bank_callback(2, rohga_bank_callback);
deco16_set_bank_callback(3, rohga_bank_callback);
SekInit(0, 0x68000);
SekOpen(0);
SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM);
SekMapMemory(deco16_pf_ram[0], 0x3c0000, 0x3c1fff, SM_RAM);
SekMapMemory(deco16_pf_ram[1], 0x3c2000, 0x3c2fff, SM_RAM);
SekMapMemory(deco16_pf_ram[2], 0x3c4000, 0x3c4fff, SM_RAM);
SekMapMemory(deco16_pf_ram[3], 0x3c6000, 0x3c6fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[0], 0x3c8000, 0x3c8fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[0], 0x3c9000, 0x3c9fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[1], 0x3ca000, 0x3cafff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[1], 0x3cb000, 0x3cbfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x3cc000, 0x3ccfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x3cd000, 0x3cdfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x3ce000, 0x3cefff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x3cf000, 0x3cffff, SM_RAM);
SekMapMemory(DrvSprRAM, 0x3d0000, 0x3d07ff, SM_RAM);
SekMapMemory(DrvPalRAM, 0x3e0000, 0x3e1fff, SM_RAM);
SekMapMemory(Drv68KRAM, 0x3f0000, 0x3f3fff, SM_RAM);
SekSetWriteWordHandler(0, rohga_main_write_word);
SekSetWriteByteHandler(0, rohga_main_write_byte);
SekSetReadWordHandler(0, rohga_main_read_word);
SekSetReadByteHandler(0, rohga_main_read_byte);
SekClose();
deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.78, 1006875, 1.00, 2013750, 0.40);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.78, BURN_SND_ROUTE_LEFT);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.78, BURN_SND_ROUTE_RIGHT);
GenericTilesInit();
DrvDoReset();
return 0;
}
static INT32 WizdfireInit()
{
BurnSetRefreshRate(58.00);
AllMem = NULL;
MemIndex();
INT32 nLen = MemEnd - (UINT8 *)0;
if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
{
if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x040001, 2, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x040000, 3, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x080001, 4, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x080000, 5, 2)) return 1;
if (BurnLoadRom(DrvHucROM + 0x000000, 6, 1)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000000, 7, 2)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000001, 8, 2)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x000000, 9, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x100000, 10, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x000000, 11, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x080000, 12, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000000, 13, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000001, 14, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200000, 15, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200001, 16, 2)) return 1;
if (BurnLoadRom(DrvGfxROM4 + 0x000000, 17, 2)) return 1;
if (BurnLoadRom(DrvGfxROM4 + 0x000001, 18, 2)) return 1;
if (BurnLoadRom(DrvSndROM0 + 0x040000, 19, 1)) return 1;
if (BurnLoadRom(DrvSndROM1 + 0x040000, 20, 1)) return 1;
deco74_decrypt_gfx(DrvGfxROM0, 0x020000);
deco74_decrypt_gfx(DrvGfxROM1, 0x200000);
deco74_decrypt_gfx(DrvGfxROM2, 0x100000);
deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x020000, 1);
deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x200000, 0);
deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x100000, 0);
deco16_sprite_decode(DrvGfxROM3, 0x400000);
deco16_sprite_decode(DrvGfxROM4, 0x100000);
}
deco16Init(0, 0, 1);
deco16_set_graphics(DrvGfxROM0, 0x20000 * 2, DrvGfxROM1, 0x200000 * 2, DrvGfxROM2, 0x100000 * 2);
deco16_set_color_base(2, 512);
deco16_set_color_base(3, 768);
deco16_set_global_offsets(0, 8);
deco16_set_bank_callback(0, rohga_bank_callback);
deco16_set_bank_callback(1, rohga_bank_callback);
deco16_set_bank_callback(2, rohga_bank_callback);
deco16_set_bank_callback(3, rohga_bank_callback);
SekInit(0, 0x68000);
SekOpen(0);
SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM);
SekMapMemory(deco16_pf_ram[0], 0x200000, 0x200fff, SM_RAM);
SekMapMemory(deco16_pf_ram[1], 0x202000, 0x202fff, SM_RAM);
SekMapMemory(deco16_pf_ram[2], 0x208000, 0x208fff, SM_RAM);
SekMapMemory(deco16_pf_ram[3], 0x20a000, 0x20afff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x20c000, 0x20c7ff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x20e000, 0x20e7ff, SM_RAM);
SekMapMemory(DrvSprRAM, 0x340000, 0x3407ff, SM_RAM);
SekMapMemory(DrvSprRAM2, 0x360000, 0x3607ff, SM_RAM);
SekMapMemory(DrvPalRAM, 0x380000, 0x381fff, SM_RAM);
SekMapMemory(Drv68KRAM, 0xfdc000, 0xfe3fff, SM_RAM);
SekMapMemory(Drv68KRAM + 0x8000, 0xfe4800, 0xffffff, SM_RAM);
SekSetWriteWordHandler(0, wizdfire_main_write_word);
SekSetWriteByteHandler(0, wizdfire_main_write_byte);
SekSetReadWordHandler(0, wizdfire_main_read_word);
SekSetReadByteHandler(0, wizdfire_main_read_byte);
SekClose();
deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.80, 1006875, 1.00, 2013750, 0.40);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.80, BURN_SND_ROUTE_LEFT);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.80, BURN_SND_ROUTE_RIGHT);
GenericTilesInit();
DrvDoReset();
return 0;
}
static INT32 SchmeisrInit()
{
BurnSetRefreshRate(58.00);
AllMem = NULL;
MemIndex();
INT32 nLen = MemEnd - (UINT8 *)0;
if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
{
if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1;
if (BurnLoadRom(DrvHucROM + 0x000000, 2, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x000000, 3, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x080000, 4, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x000000, 5, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x100000, 6, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000000, 7, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x100000, 8, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200000, 9, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x300000, 10, 1)) return 1;
if (BurnLoadRom(DrvSndROM0 + 0x040000, 11, 1)) return 1;
if (BurnLoadRom(DrvSndROM1 + 0x040000, 12, 1)) return 1;
deco74_decrypt_gfx(DrvGfxROM1, 0x100000);
memcpy (DrvGfxROM0 + 0x000000, DrvGfxROM1 + 0x000000, 0x020000);
memcpy (DrvGfxROM0 + 0x020000, DrvGfxROM1 + 0x080000, 0x020000);
deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x040000, 1);
deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x100000, 0);
deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x200000, 0);
DrvSpriteDecode();
}
deco16Init(0, 0, 1);
deco16_set_graphics(DrvGfxROM0, 0x40000 * 2, DrvGfxROM1, 0x100000 * 2, DrvGfxROM2, 0x200000 * 2);
deco16_set_color_base(2, 512);
deco16_set_color_base(3, 768);
deco16_set_global_offsets(0, 8);
deco16_set_bank_callback(0, rohga_bank_callback);
deco16_set_bank_callback(1, rohga_bank_callback);
deco16_set_bank_callback(2, rohga_bank_callback);
deco16_set_bank_callback(3, rohga_bank_callback);
SekInit(0, 0x68000);
SekOpen(0);
SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM);
SekMapMemory(deco16_pf_ram[0], 0x3c0000, 0x3c1fff, SM_RAM);
SekMapMemory(deco16_pf_ram[1], 0x3c2000, 0x3c2fff, SM_RAM);
SekMapMemory(deco16_pf_ram[2], 0x3c4000, 0x3c4fff, SM_RAM);
SekMapMemory(deco16_pf_ram[3], 0x3c6000, 0x3c6fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[0], 0x3c8000, 0x3c8fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[0], 0x3c9000, 0x3c9fff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[1], 0x3ca000, 0x3cafff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[1], 0x3cb000, 0x3cbfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x3cc000, 0x3ccfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x3cd000, 0x3cdfff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x3ce000, 0x3cefff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x3cf000, 0x3cffff, SM_RAM);
SekMapMemory(DrvSprRAM, 0x3d0000, 0x3d07ff, SM_RAM);
SekMapMemory(DrvPalRAM, 0x3e0000, 0x3e1fff, SM_RAM);
SekMapMemory(DrvPalRAM, 0x3e2000, 0x3e3fff, SM_RAM);
SekMapMemory(Drv68KRAM, 0xff0000, 0xff7fff, SM_RAM);
SekSetWriteWordHandler(0, rohga_main_write_word);
SekSetWriteByteHandler(0, rohga_main_write_byte);
SekSetReadWordHandler(0, rohga_main_read_word);
SekSetReadByteHandler(0, rohga_main_read_byte);
SekClose();
deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.80, 1006875, 1.00, 2013750, 0.40);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.80, BURN_SND_ROUTE_LEFT);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.80, BURN_SND_ROUTE_RIGHT);
GenericTilesInit();
DrvDoReset();
return 0;
}
static INT32 NitrobalInit()
{
BurnSetRefreshRate(58.00);
AllMem = NULL;
MemIndex();
INT32 nLen = MemEnd - (UINT8 *)0;
if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
{
if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x040001, 2, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x040000, 3, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x080001, 4, 2)) return 1;
if (BurnLoadRom(Drv68KROM + 0x080000, 5, 2)) return 1;
if (BurnLoadRom(DrvHucROM + 0x000000, 6, 1)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000000, 7, 2)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000001, 8, 2)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x000000, 9, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x080000, 10, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x000000, 11, 1)) return 1;
if (BurnLoadRom(DrvGfxROM2 + 0x100000, 12, 1)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000000, 13, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x000001, 14, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200000, 15, 2)) return 1;
if (BurnLoadRom(DrvGfxROM3 + 0x200001, 16, 2)) return 1;
BurnByteswap(DrvGfxROM3, 0x400000);
if (BurnLoadRom(DrvGfxROM4 + 0x000000, 17, 2)) return 1;
if (BurnLoadRom(DrvGfxROM4 + 0x000001, 18, 2)) return 1;
BurnByteswap(DrvGfxROM4, 0x080000);
if (BurnLoadRom(DrvSndROM0 + 0x040000, 19, 1)) return 1;
if (BurnLoadRom(DrvSndROM1 + 0x040000, 20, 1)) return 1;
deco56_decrypt_gfx(DrvGfxROM0, 0x020000);
deco56_decrypt_gfx(DrvGfxROM1, 0x100000);
deco74_decrypt_gfx(DrvGfxROM2, 0x200000);
deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x020000, 1);
deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x100000, 0);
deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x200000, 0);
deco16_sprite_decode(DrvGfxROM3, 0x400000);
deco16_sprite_decode(DrvGfxROM4, 0x080000);
}
deco16Init(0, 0, 0);
deco16_set_graphics(DrvGfxROM0, 0x20000 * 2, DrvGfxROM1, 0x100000 * 2, DrvGfxROM2, 0x200000 * 2);
deco16_set_color_base(2, 512);
deco16_set_color_mask(2, 0);
deco16_set_color_base(3, 512);
deco16_set_color_mask(3, 0);
deco16_set_global_offsets(0, 8);
deco16_set_bank_callback(0, rohga_bank_callback);
deco16_set_bank_callback(1, rohga_bank_callback);
deco16_set_bank_callback(2, rohga_bank_callback);
deco16_set_bank_callback(3, rohga_bank_callback);
SekInit(0, 0x68000);
SekOpen(0);
SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM);
SekMapMemory(deco16_pf_ram[0], 0x200000, 0x200fff, SM_RAM);
SekMapMemory(deco16_pf_ram[0], 0x201000, 0x201fff, SM_RAM);
SekMapMemory(deco16_pf_ram[1], 0x202000, 0x2027ff, SM_RAM);
SekMapMemory(deco16_pf_ram[1], 0x202800, 0x202fff, SM_RAM);
SekMapMemory(deco16_pf_ram[2], 0x208000, 0x2087ff, SM_RAM);
SekMapMemory(deco16_pf_ram[2], 0x208800, 0x208fff, SM_RAM);
SekMapMemory(deco16_pf_ram[3], 0x20a000, 0x20a7ff, SM_RAM);
SekMapMemory(deco16_pf_ram[3], 0x20a800, 0x20afff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[0], 0x204000, 0x2047ff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[1], 0x206000, 0x2067ff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[2], 0x20c000, 0x20c7ff, SM_RAM);
SekMapMemory(deco16_pf_rowscroll[3], 0x20e000, 0x20e7ff, SM_RAM);
SekMapMemory(DrvSprRAM, 0x340000, 0x3407ff, SM_RAM);
SekMapMemory(DrvSprRAM2, 0x360000, 0x3607ff, SM_RAM);
SekMapMemory(DrvPalRAM, 0x380000, 0x381fff, SM_RAM);
SekMapMemory(Drv68KRAM, 0xfec000, 0xff3fff, SM_RAM);
SekMapMemory(Drv68KRAM + 0x8000, 0xff8000, 0xffffff, SM_RAM);
SekSetWriteWordHandler(0, wizdfire_main_write_word);
SekSetWriteByteHandler(0, wizdfire_main_write_byte);
SekSetReadWordHandler(0, wizdfire_main_read_word);
SekSetReadByteHandler(0, wizdfire_main_read_byte);
SekClose();
deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.80, 1006875, 1.00, 2013750, 0.40);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.80, BURN_SND_ROUTE_LEFT);
BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.80, BURN_SND_ROUTE_RIGHT);
GenericTilesInit();
DrvDoReset();
return 0;
}
static INT32 DrvExit()
{
GenericTilesExit();
deco16Exit();
SekExit();
deco16SoundExit();
BurnFree (AllMem);
return 0;
}
static void rohga_draw_sprites(UINT8 *ram, INT32 is_schmeisr)
{
UINT16 *spriteptr = (UINT16*)ram;
for (INT32 offs = 0x400 - 4; offs >= 0; offs -= 4)
{
INT32 inc, mult, pri = 0;
INT32 sprite = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 1]);
if (!sprite) continue;
INT32 x = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]);
switch (x & 0x6000)
{
case 0x0000: pri = 0; break;
case 0x4000: pri = 0xf0; break;
case 0x6000: pri = 0xf0 | 0xcc; break;
case 0x2000: pri = 0; break;
}
INT32 y = BURN_ENDIAN_SWAP_INT16(spriteptr[offs]);
if ((y & 0x1000) && (nCurrentFrame & 1)) continue; // flash
INT32 colour = (((x >> 9) & 0xf) << 6);
if (is_schmeisr) colour += ((x & 0x8000) >> 15) << 4;
INT32 fx = y & 0x2000;
INT32 fy = y & 0x4000;
INT32 multi = (1 << ((y & 0x0600) >> 9)) - 1;
x = x & 0x01ff;
y = y & 0x01ff;
if (x >= 320) x -= 512;
if (y >= 256) y -= 512;
sprite &= ~multi;
if (fy)
inc = -1;
else
{
sprite += multi;
inc = 1;
}
if (*flipscreen)
{
x = 304 - x;
y = 240 - y;
if (fx) fx = 0; else fx = 1;
if (fy) fy = 0; else fy = 1;
mult = -16;
}
else
mult = +16;
while (multi >= 0)
{
deco16_draw_prio_sprite(pTransDraw, DrvGfxROM3, (sprite - multi * inc) & 0x7fff, colour + 0x400, x, y + mult * multi, fx, fy, pri);
multi--;
}
}
}
static void wizdfire_draw_sprites(UINT8 *ram, UINT8 *gfx, INT32 coloff, INT32 mode, INT32 bank)
{
UINT16 *spriteptr = (UINT16*)ram;
for (INT32 offs = 0; offs < 0x400; offs += 4)
{
INT32 inc, mult, prio = 0, alpha = 0xff;
INT32 sprite = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 1]);
if (!sprite) continue;
INT32 x = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]);
switch (mode)
{
case 4:
if ((x & 0xc000) != 0xc000)
continue;
prio = 0x08;
break;
case 3:
if ((x & 0xc000) != 0x8000)
continue;
prio = 0x10;
break;
case 2:
if ((x & 0x8000) != 0x8000)
continue;
prio = 0x20;
break;
case 1:
case 0:
default:
if ((x & 0x8000) != 0)
continue;
prio = 0x40;
break;
}
INT32 y = BURN_ENDIAN_SWAP_INT16(spriteptr[offs]);
if ((y & 0x1000) && (nCurrentFrame & 1)) continue; // flash
INT32 colour = (x >> 9) & 0x1f;
if (bank == 4 && colour & 0x10)
{
alpha = 0x80;
colour &= 0xf;
}
INT32 fx = y & 0x2000;
INT32 fy = y & 0x4000;
INT32 multi = (1 << ((y & 0x0600) >> 9)) - 1;
x = x & 0x01ff;
y = y & 0x01ff;
if (x >= 320) x -= 512;
if (y >= 256) y -= 512;
sprite &= ~multi;
if (fy)
inc = -1;
else
{
sprite += multi;
inc = 1;
}
if (*flipscreen)
{
x = 304 - x;
y = 240 - y;
mult = -16;
} else {
mult = +16;
fx = !fx;
fy = !fy;
}
if (bank == 3) {
sprite &= 0x7fff;
} else {
sprite &= 0x0fff;
}
while (multi >= 0)
{
deco16_draw_prio_sprite(pTransDraw, gfx, sprite - multi * inc, (colour << 4) + coloff, x, y + mult * multi, fx, fy, -1);
#if 0
drawgfx_alpha(bitmap,cliprect,machine->gfx[bank],
sprite - multi * inc,
colour,
fx,fy,
x,y + mult * multi,
0,alpha);
#endif
multi--;
}
}
}
static void nitrobal_draw_sprites(UINT8 *ram, INT32 gfxbank, INT32 /*bpp*/)
{
// if (bpp != (nBurnBpp & 0x04)) return;
UINT16 *spriteptr = (UINT16*)ram;
INT32 offs = 0x3fc;
INT32 end = -4;
INT32 inc = -4;
UINT8 *gfx;
while (offs != end)
{
INT32 x, y, sprite, colour, fx, fy, w, h, sx, sy, x_mult, y_mult, tilemap_pri, sprite_pri, coloff;
INT32 alpha = 0xff;
sprite = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 3]);
if (!sprite)
{
offs += inc;
continue;
}
sx = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 1]);
h = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) & 0xf000) >> 12;
w = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) & 0x0f00) >> 8;
sy = BURN_ENDIAN_SWAP_INT16(spriteptr[offs]);
if ((sy & 0x2000) && (nCurrentFrame & 1))
{
offs += inc;
continue;
}
colour = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) >> 0) & 0x1f;
if (gfxbank == 3)
{
switch (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) & 0xe0)
{
case 0xc0: tilemap_pri = 8; break;
case 0x80: tilemap_pri = 32; break;
case 0x20: tilemap_pri = 32; break;
case 0x40: tilemap_pri = 8; break;
case 0xa0: tilemap_pri = 32; break;
case 0x00: tilemap_pri = 128; break;
default: tilemap_pri = 128; break;
}
sprite_pri = 1;
gfx = DrvGfxROM3;
coloff = 0x400;
}
else
{
if (deco16_priority)
tilemap_pri = 8;
else
tilemap_pri = 64;
sprite_pri = 2;
gfx = DrvGfxROM4;
coloff = 0x600;
if (colour & 0x10) {
alpha = 0x80;
colour &= 0x0f;
}
}
fx = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 0]) & 0x4000);
fy = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 0]) & 0x8000);
if (!*flipscreen)
{
if (fx) fx = 0; else fx = 1;
if (fy) fy = 0; else fy = 1;
sx = sx & 0x01ff;
sy = sy & 0x01ff;
if (sx > 0x180) sx = -(0x200 - sx);
if (sy > 0x180) sy = -(0x200 - sy);
if (fx) { x_mult = -16; sx += 16 * w; } else { x_mult = 16; sx -= 16; }
if (fy) { y_mult = -16; sy += 16 * h; } else { y_mult = 16; sy -= 16; }
}
else
{
sx = sx & 0x01ff;
sy = sy & 0x01ff;
if (sx & 0x100) sx = -(0x100 - (sx & 0xff));
if (sy & 0x100) sy = -(0x100 - (sy & 0xff));
sx = 304 - sx;
sy = 240 - sy;
if (sx >= 432) sx -= 512;
if (sy >= 384) sy -= 512;
if (fx) { x_mult = -16; sx += 16; } else { x_mult = 16; sx -= 16 * w; }
if (fy) { y_mult = -16; sy += 16; } else { y_mult = 16; sy -= 16 * h; }
}
if (gfxbank == 3) {
sprite &= 0x7fff;
} else {
sprite &= 0x0fff;
}
for (x = 0; x < w; x++)
{
for (y = 0; y < h; y++)
{
//if (!bpp) {
deco16_draw_prio_sprite(pTransDraw, gfx, sprite + y + h * x, (colour << 4) + coloff, sx + x_mult * (w-x), sy + y_mult * (h-y), fx, fy, tilemap_pri, sprite_pri);
//} else {
// deco16_draw_alphaprio_sprite(DrvPalette, gfx, sprite + y + h * x, (colour << 4) + coloff, sx + x_mult * (w-x), sy + y_mult * (h-y), fx, fy, tilemap_pri, sprite_pri, alpha);
//}
}
}
offs += inc;
}
}
static void draw_combined_playfield_step1()
{
UINT8 *tptr = deco16_pf_rowscroll[3];
deco16_pf_rowscroll[3] = deco16_pf_rowscroll[2];
deco16_draw_layer(2, tempdraw[0], 0x10000);
deco16_draw_layer(3, tempdraw[1], 0x10000);
deco16_pf_rowscroll[3] = tptr;
}
static void draw_combined_playfield(INT32 color, INT32 priority) // opaque
{
UINT16 *src0 = tempdraw[0];
UINT16 *src1 = tempdraw[1];
UINT16 *dest = pTransDraw;
UINT8 *prio = deco16_prio_map;
for (INT32 y = 0; y < nScreenHeight; y++) {
for (INT32 x = 0; x < nScreenWidth; x++) {
dest[x] = color | (src0[x] & 0x0f) | ((src1[x] & 0x0f) << 4);
prio[x] = priority;
}
src0 += nScreenWidth;
src1 += nScreenWidth;
dest += nScreenWidth;
prio += 512;
}
}
static void update_rohga(INT32 is_schmeisr)
{
// if (DrvRecalc) {
deco16_palette_recalculate(DrvPalette, DrvPalRAM);
DrvRecalc = 0;
// }
deco16_pf12_update();
deco16_pf34_update();
for (INT32 i = 0; i < nScreenWidth * nScreenHeight; i++) {
pTransDraw[i] = 0x300;
}
if ((deco16_priority & 0x03) == 0) {
draw_combined_playfield_step1();
}
deco16_clear_prio_map();
switch (deco16_priority & 3)
{
case 0:
if (deco16_priority & 4)
{
draw_combined_playfield(0x300, DECO16_LAYER_PRIORITY(3));
}
else
{
deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE | DECO16_LAYER_PRIORITY(0x01));
deco16_draw_layer(2, pTransDraw, DECO16_LAYER_PRIORITY(0x02));
}
deco16_draw_layer(1, pTransDraw, DECO16_LAYER_PRIORITY(0x04));
break;
case 1:
deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE | DECO16_LAYER_PRIORITY(0x01));
deco16_draw_layer(1, pTransDraw, DECO16_LAYER_PRIORITY(0x02));
deco16_draw_layer(2, pTransDraw, DECO16_LAYER_PRIORITY(0x04));
break;
case 2:
deco16_draw_layer(1, pTransDraw, DECO16_LAYER_OPAQUE | DECO16_LAYER_PRIORITY(0x01));
deco16_draw_layer(3, pTransDraw, DECO16_LAYER_PRIORITY(0x02));
deco16_draw_layer(2, pTransDraw, DECO16_LAYER_PRIORITY(0x04));
break;
}
if (nSpriteEnable & 1) rohga_draw_sprites(DrvSprBuf2, is_schmeisr);
deco16_draw_layer(0, pTransDraw, 0);
BurnTransferCopy(DrvPalette);
}
static INT32 RohgaDraw()
{
update_rohga(0);
return 0;
}
static INT32 SchmeisrDraw()
{
update_rohga(1);
return 0;
}
static INT32 WizdfireDraw()
{
// if (DrvRecalc) {
deco16_palette_recalculate(DrvPalette, DrvPalRAM);
DrvRecalc = 0;
// }
deco16_pf12_update();
deco16_pf34_update();
for (INT32 i = 0; i < nScreenWidth * nScreenHeight; i++) {
pTransDraw[i] = 0x200;
}
if (nBurnLayer & 1) deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE);
if (nSpriteEnable & 1) wizdfire_draw_sprites(DrvSprBuf, DrvGfxROM3, 0x400, 4, 3);
if (nBurnLayer & 2) deco16_draw_layer(1, pTransDraw, 0);
if (nSpriteEnable & 2) wizdfire_draw_sprites(DrvSprBuf, DrvGfxROM3, 0x400, 3, 3);
if ((deco16_priority & 0x1f) == 0x1f) {
if (nBurnLayer & 4) deco16_draw_layer(2, pTransDraw, 0); // tilemap draw alpha 0x80...
} else {
if (nBurnLayer & 4) deco16_draw_layer(2, pTransDraw, 0);
}
if (nSpriteEnable & 4) wizdfire_draw_sprites(DrvSprBuf, DrvGfxROM3, 0x400, 0, 3);
if (nSpriteEnable & 8) wizdfire_draw_sprites(DrvSprBuf2, DrvGfxROM4, 0x600, 2, 4);
if (nSpriteEnable & 16) wizdfire_draw_sprites(DrvSprBuf2, DrvGfxROM4, 0x600, 1, 4);
if (nBurnLayer & 8) deco16_draw_layer(0, pTransDraw, 0);
BurnTransferCopy(DrvPalette);
return 0;
}
static INT32 NitrobalDraw()
{
// if (DrvRecalc) {
deco16_palette_recalculate(DrvPalette, DrvPalRAM);
DrvRecalc = 0;
// }
deco16_pf12_update();
deco16_pf34_update();
for (INT32 i = 0; i < nScreenWidth * nScreenHeight; i++) {
pTransDraw[i] = 0x200;
}
draw_combined_playfield_step1();
deco16_clear_prio_map();
draw_combined_playfield(0x200, 0);
if (nBurnLayer & 1)deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE);
deco16_draw_layer(1, pTransDraw, 16);
nitrobal_draw_sprites(DrvSprBuf , 3, 0);
nitrobal_draw_sprites(DrvSprBuf2, 4, 0);
deco16_draw_layer(0, pTransDraw, DECO16_LAYER_PRIORITY(0xff));
BurnTransferCopy(DrvPalette);
// nitrobal_draw_sprites(DrvSprBuf , 3, 4);
// nitrobal_draw_sprites(DrvSprBuf2, 4, 4);
return 0;
}
static INT32 DrvFrame()
{
if (DrvReset) {
DrvDoReset();
}
{
deco16_prot_inputs = DrvInputs;
memset (DrvInputs, 0xff, 4 * sizeof(UINT16));
for (INT32 i = 0; i < 16; i++) {
DrvInputs[0] ^= (DrvJoy1[i] & 1) << i;
DrvInputs[1] ^= (DrvJoy2[i] & 1) << i;
DrvInputs[3] ^= (DrvJoy3[i] & 1) << i;
}
DrvInputs[2] = (DrvDips[1] << 8) | (DrvDips[0] << 0);
}
INT32 nInterleave = 256;
INT32 nSoundBufferPos = 0;
INT32 nCyclesTotal[2] = { 14000000 / 58, 2685000 / 58 };
INT32 nCyclesDone[2] = { 0, 0 };
h6280NewFrame();
SekOpen(0);
h6280Open(0);
deco16_vblank = 0;
for (INT32 i = 0; i < nInterleave; i++)
{
nCyclesDone[0] += SekRun(nCyclesTotal[0] / nInterleave);
nCyclesDone[1] += h6280Run(nCyclesTotal[1] / nInterleave);
if (i == 240) deco16_vblank = 0x08;
if (pBurnSoundOut) {
INT32 nSegmentLength = nBurnSoundLen / nInterleave;
INT16* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1);
deco16SoundUpdate(pSoundBuf, nSegmentLength);
nSoundBufferPos += nSegmentLength;
}
}
SekSetIRQLine(6, SEK_IRQSTATUS_ACK);
if (pBurnSoundOut) {
INT32 nSegmentLength = nBurnSoundLen - nSoundBufferPos;
INT16* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1);
if (nSegmentLength) {
deco16SoundUpdate(pSoundBuf, nSegmentLength);
}
}
h6280Close();
SekClose();
if (pBurnDraw) {
BurnDrvRedraw();
}
return 0;
}
static INT32 DrvScan(INT32 nAction, INT32 *pnMin)
{
struct BurnArea ba;
if (pnMin != NULL) {
*pnMin = 0x029722;
}
if (nAction & ACB_MEMORY_RAM) {
memset(&ba, 0, sizeof(ba));
ba.Data = AllRam;
ba.nLen = RamEnd-AllRam;
ba.szName = "All Ram";
BurnAcb(&ba);
}
if (nAction & ACB_DRIVER_DATA) {
SekScan(nAction);
deco16SoundScan(nAction, pnMin);
deco16Scan();
SCAN_VAR(DrvOkiBank);
INT32 bank = DrvOkiBank;
DrvOkiBank = -1;
DrvYM2151WritePort(0, bank);
}
return 0;
}
// Rohga Armor Force (Asia/Europe v5.0)
static struct BurnRomInfo rohgaRomDesc[] = {
{ "ht-00-1.2a", 0x040000, 0x1ed84a67, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "ht-03-1.2d", 0x040000, 0x84e7ebf6, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters
{ "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(rohga)
STD_ROM_FN(rohga)
struct BurnDriver BurnDrvRohga = {
"rohga", NULL, NULL, NULL, "1991",
"Rohga Armor Force (Asia/Europe v5.0)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, rohgaRomInfo, rohgaRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Rohga Armor Force (Asia/Europe v3.0 Set 1)
static struct BurnRomInfo rohga1RomDesc[] = {
{ "jd00.bin", 0x040000, 0xe046c77a, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jd03.bin", 0x040000, 0x2c5120b8, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters
{ "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(rohga1)
STD_ROM_FN(rohga1)
struct BurnDriver BurnDrvRohga1 = {
"rohga1", "rohga", NULL, NULL, "1991",
"Rohga Armor Force (Asia/Europe v3.0 Set 1)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, rohga1RomInfo, rohga1RomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Rohga Armor Force (Asia/Europe v3.0 Set 2)
static struct BurnRomInfo rohga2RomDesc[] = {
{ "hts-00-3.2a", 0x040000, 0x154f02ec, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "hts-03-3.2d", 0x040000, 0x5e69d3d8, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters
{ "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(rohga2)
STD_ROM_FN(rohga2)
struct BurnDriver BurnDrvRohga2 = {
"rohga2", "rohga", NULL, NULL, "1991",
"Rohga Armor Force (Asia/Europe v3.0 Set 2)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, rohga2RomInfo, rohga2RomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Rohga Armor Force (Hong Kong v3.0)
static struct BurnRomInfo rohgahRomDesc[] = {
{ "jd00-2.2a", 0x040000, 0xec70646a, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jd03-2.2d", 0x040000, 0x11d4c9a2, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters
{ "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(rohgah)
STD_ROM_FN(rohgah)
struct BurnDriver BurnDrvRohgah = {
"rohgah", "rohga", NULL, NULL, "1991",
"Rohga Armor Force (Hong Kong v3.0)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, rohgahRomInfo, rohgahRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Rohga Armor Force (US v1.0)
static struct BurnRomInfo rohgauRomDesc[] = {
{ "ha00.2a", 0x040000, 0xd8d13052, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "ha03.2d", 0x040000, 0x5f683bbf, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters
{ "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(rohgau)
STD_ROM_FN(rohgau)
struct BurnDriver BurnDrvRohgau = {
"rohgau", "rohga", NULL, NULL, "1991",
"Rohga Armor Force (US v1.0)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, rohgauRomInfo, rohgauRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Wolf Fang -Kuhga 2001- (Japan)
static struct BurnRomInfo wolffangRomDesc[] = {
{ "hw_00-1.2a", 0x040000, 0x69dc611e, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "hw_03-1.2d", 0x040000, 0xb66d9680, 1 | BRF_PRG | BRF_ESS }, // 1
{ "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2
{ "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3
{ "hw_04-.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code
{ "hw_01-.13a", 0x010000, 0xd9810ca4, 3 | BRF_GRA }, // 5 Characters
{ "hw_02-.14a", 0x010000, 0x2a27ac8e, 3 | BRF_GRA }, // 6
{ "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles
{ "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8
{ "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles
{ "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10
{ "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites
{ "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12
{ "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13
{ "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14
{ "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15
{ "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16
{ "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0
{ "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs
};
STD_ROM_PICK(wolffang)
STD_ROM_FN(wolffang)
struct BurnDriver BurnDrvWolffang = {
"wolffang", "rohga", NULL, NULL, "1991",
"Wolf Fang -Kuhga 2001- (Japan)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0,
NULL, wolffangRomInfo, wolffangRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo,
RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Wizard Fire (Over Sea v2.1)
static struct BurnRomInfo wizdfireRomDesc[] = {
{ "je-01.3d", 0x020000, 0xb6d62367, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "je-00.3a", 0x020000, 0xf33de278, 1 | BRF_PRG | BRF_ESS }, // 1
{ "je-03.5d", 0x020000, 0x5217d404, 1 | BRF_PRG | BRF_ESS }, // 2
{ "je-02.5a", 0x020000, 0x36a1ce28, 1 | BRF_PRG | BRF_ESS }, // 3
{ "mas13", 0x080000, 0x7e5256ce, 1 | BRF_PRG | BRF_ESS }, // 4
{ "mas12", 0x080000, 0x005bd499, 1 | BRF_PRG | BRF_ESS }, // 5
{ "je-06.20r", 0x010000, 0x79042546, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code
{ "je-04.10d", 0x010000, 0x73cba800, 3 | BRF_GRA }, // 7 Characters
{ "je-05.12d", 0x010000, 0x22e2c49d, 3 | BRF_GRA }, // 8
{ "mas00", 0x100000, 0x3d011034, 4 | BRF_GRA }, // 9 Foreground Tiles
{ "mas01", 0x100000, 0x6d0c9d0b, 4 | BRF_GRA }, // 10
{ "mas02", 0x080000, 0xaf00e620, 5 | BRF_GRA }, // 11 Background Tiles
{ "mas03", 0x080000, 0x2fe61ea2, 5 | BRF_GRA }, // 12
{ "mas04", 0x100000, 0x1e56953b, 6 | BRF_GRA }, // 13 Sprite Bank A
{ "mas05", 0x100000, 0x3826b8f8, 6 | BRF_GRA }, // 14
{ "mas06", 0x100000, 0x3b8bbd45, 6 | BRF_GRA }, // 15
{ "mas07", 0x100000, 0x31303769, 6 | BRF_GRA }, // 16
{ "mas08", 0x080000, 0xe224fb7a, 7 | BRF_GRA }, // 17 Sprite Bank B
{ "mas09", 0x080000, 0x5f6deb41, 7 | BRF_GRA }, // 18
{ "mas10", 0x080000, 0x6edc06a7, 8 | BRF_SND }, // 19 OKI M6295 Samples 0
{ "mas11", 0x080000, 0xc2f0a4f2, 9 | BRF_SND }, // 20 OKI M6295 Samples 1
{ "mb7122h.16l", 0x000400, 0x2bee57cc, 0 | BRF_OPT }, // 21 Unused PROMs
};
STD_ROM_PICK(wizdfire)
STD_ROM_FN(wizdfire)
struct BurnDriver BurnDrvWizdfire = {
"wizdfire", NULL, NULL, NULL, "1992",
"Wizard Fire (Over Sea v2.1)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT, 0,
NULL, wizdfireRomInfo, wizdfireRomName, NULL, NULL, WizdfireInputInfo, WizdfireDIPInfo,
WizdfireInit, DrvExit, DrvFrame, WizdfireDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Wizard Fire (US v1.1)
static struct BurnRomInfo wizdfireuRomDesc[] = {
{ "jf-01.3d", 0x020000, 0xbde42a41, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jf-00.3a", 0x020000, 0xbca3c995, 1 | BRF_PRG | BRF_ESS }, // 1
{ "jf-03.5d", 0x020000, 0x5217d404, 1 | BRF_PRG | BRF_ESS }, // 2
{ "jf-02.5a", 0x020000, 0x36a1ce28, 1 | BRF_PRG | BRF_ESS }, // 3
{ "mas13", 0x080000, 0x7e5256ce, 1 | BRF_PRG | BRF_ESS }, // 4
{ "mas12", 0x080000, 0x005bd499, 1 | BRF_PRG | BRF_ESS }, // 5
{ "jf-06.20r", 0x010000, 0x79042546, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code
{ "jf-04.10d", 0x010000, 0x73cba800, 3 | BRF_GRA }, // 7 Characters
{ "jf-05.12d", 0x010000, 0x22e2c49d, 3 | BRF_GRA }, // 8
{ "mas00", 0x100000, 0x3d011034, 4 | BRF_GRA }, // 9 Foreground Tiles
{ "mas01", 0x100000, 0x6d0c9d0b, 4 | BRF_GRA }, // 10
{ "mas02", 0x080000, 0xaf00e620, 5 | BRF_GRA }, // 11 Background Tiles
{ "mas03", 0x080000, 0x2fe61ea2, 5 | BRF_GRA }, // 12
{ "mas04", 0x100000, 0x1e56953b, 6 | BRF_GRA }, // 13 Sprite Bank A
{ "mas05", 0x100000, 0x3826b8f8, 6 | BRF_GRA }, // 14
{ "mas06", 0x100000, 0x3b8bbd45, 6 | BRF_GRA }, // 15
{ "mas07", 0x100000, 0x31303769, 6 | BRF_GRA }, // 16
{ "mas08", 0x080000, 0xe224fb7a, 7 | BRF_GRA }, // 17 Sprite Bank B
{ "mas09", 0x080000, 0x5f6deb41, 7 | BRF_GRA }, // 18
{ "mas10", 0x080000, 0x6edc06a7, 8 | BRF_SND }, // 19 OKI M6295 Samples 0
{ "mas11", 0x080000, 0xc2f0a4f2, 9 | BRF_SND }, // 20 OKI M6295 Samples 1
{ "mb7122h.16l", 0x000400, 0x2bee57cc, 0 | BRF_OPT }, // 21 Unused PROMs
};
STD_ROM_PICK(wizdfireu)
STD_ROM_FN(wizdfireu)
struct BurnDriver BurnDrvWizdfireu = {
"wizdfireu", "wizdfire", NULL, NULL, "1992",
"Wizard Fire (US v1.1)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT, 0,
NULL, wizdfireuRomInfo, wizdfireuRomName, NULL, NULL, WizdfireInputInfo, WizdfireDIPInfo,
WizdfireInit, DrvExit, DrvFrame, WizdfireDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Dark Seal 2 (Japan v2.1)
static struct BurnRomInfo darkseal2RomDesc[] = {
{ "jb-01-3.3d", 0x020000, 0x82308c01, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jb-00-3.3a", 0x020000, 0x1d38113a, 1 | BRF_PRG | BRF_ESS }, // 1
{ "jb-03.5d", 0x020000, 0x5217d404, 1 | BRF_PRG | BRF_ESS }, // 2
{ "jb-02.5a", 0x020000, 0x36a1ce28, 1 | BRF_PRG | BRF_ESS }, // 3
{ "mas13", 0x080000, 0x7e5256ce, 1 | BRF_PRG | BRF_ESS }, // 4
{ "mas12", 0x080000, 0x005bd499, 1 | BRF_PRG | BRF_ESS }, // 5
{ "jb-06.20r", 0x010000, 0x2066a1dd, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code
{ "jb-04.10d", 0x010000, 0x73cba800, 3 | BRF_GRA }, // 7 Characters
{ "jb-05.12d", 0x010000, 0x22e2c49d, 3 | BRF_GRA }, // 8
{ "mas00", 0x100000, 0x3d011034, 4 | BRF_GRA }, // 9 Foreground Tiles
{ "mas01", 0x100000, 0x6d0c9d0b, 4 | BRF_GRA }, // 10
{ "mas02", 0x080000, 0xaf00e620, 5 | BRF_GRA }, // 11 Background Tiles
{ "mas03", 0x080000, 0x2fe61ea2, 5 | BRF_GRA }, // 12
{ "mas04", 0x100000, 0x1e56953b, 6 | BRF_GRA }, // 13 Sprite Bank A
{ "mas05", 0x100000, 0x3826b8f8, 6 | BRF_GRA }, // 14
{ "mas06", 0x100000, 0x3b8bbd45, 6 | BRF_GRA }, // 15
{ "mas07", 0x100000, 0x31303769, 6 | BRF_GRA }, // 16
{ "mas08", 0x080000, 0xe224fb7a, 7 | BRF_GRA }, // 17 Sprite Bank B
{ "mas09", 0x080000, 0x5f6deb41, 7 | BRF_GRA }, // 18
{ "mas10", 0x080000, 0x6edc06a7, 8 | BRF_SND }, // 19 OKI M6295 Samples 0
{ "mas11", 0x080000, 0xc2f0a4f2, 9 | BRF_SND }, // 20 OKI M6295 Samples 1
{ "mb7122h.16l", 0x000400, 0x2bee57cc, 0 | BRF_OPT }, // 21 Unused PROMs
};
STD_ROM_PICK(darkseal2)
STD_ROM_FN(darkseal2)
struct BurnDriver BurnDrvDarkseal2 = {
"darkseal2", "wizdfire", NULL, NULL, "1992",
"Dark Seal 2 (Japan v2.1)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT, 0,
NULL, darkseal2RomInfo, darkseal2RomName, NULL, NULL, WizdfireInputInfo, WizdfireDIPInfo,
WizdfireInit, DrvExit, DrvFrame, WizdfireDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Schmeiser Robo (Japan)
static struct BurnRomInfo schmeisrRomDesc[] = {
{ "sr001j.8a", 0x080000, 0xed31f3ff, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "sr006j.8d", 0x080000, 0x9e9cfa5d, 1 | BRF_PRG | BRF_ESS }, // 1
{ "sr013.18p", 0x010000, 0x4ac00cbb, 2 | BRF_PRG | BRF_ESS }, // 2 Huc6280 Code
{ "sr002-74.9a", 0x080000, 0x97e15c7b, 3 | BRF_GRA }, // 3 Foreground Tiles
{ "sr003-74.11a", 0x080000, 0xea367971, 3 | BRF_GRA }, // 4
{ "sr007.17d", 0x100000, 0x886f80c7, 4 | BRF_GRA }, // 5 Background Tiles
{ "sr008.18d", 0x100000, 0xa74cbc90, 4 | BRF_GRA }, // 6
{ "sr004.19a", 0x100000, 0xe25434a1, 5 | BRF_GRA }, // 7 Sprites
{ "sr005.20a", 0x100000, 0x1630033b, 5 | BRF_GRA }, // 8
{ "sr009.19d", 0x100000, 0x7b9d982f, 5 | BRF_GRA }, // 9
{ "sr010.20d", 0x100000, 0x6e9e5352, 5 | BRF_GRA }, // 10
{ "sr012.15p", 0x080000, 0x38843d4d, 7 | BRF_SND }, // 12 OKI M6295 Samples 0
{ "sr011.14p", 0x080000, 0x81805616, 6 | BRF_SND }, // 11 OKI M6295 Samples 1
{ "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 13 Unused PROMs
};
STD_ROM_PICK(schmeisr)
STD_ROM_FN(schmeisr)
struct BurnDriver BurnDrvSchmeisr = {
"schmeisr", NULL, NULL, NULL, "1993",
"Schmeiser Robo (Japan)\0",NULL, "Hot B", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING, 2, HARDWARE_PREFIX_DATAEAST, GBF_VSFIGHT, 0,
NULL, schmeisrRomInfo, schmeisrRomName, NULL, NULL, RohgaInputInfo, SchmeisrDIPInfo,
SchmeisrInit, DrvExit, DrvFrame, SchmeisrDraw, DrvScan, &DrvRecalc, 0x800,
320, 240, 4, 3
};
// Nitro Ball (US)
static struct BurnRomInfo nitrobalRomDesc[] = {
{ "jl01-4.d3", 0x020000, 0x0414e409, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jl00-4.b3", 0x020000, 0xdd9e2bcc, 1 | BRF_PRG | BRF_ESS }, // 1
{ "jl03-4.d5", 0x020000, 0xea264ac5, 1 | BRF_PRG | BRF_ESS }, // 2
{ "jl02-4.b5", 0x020000, 0x74047997, 1 | BRF_PRG | BRF_ESS }, // 3
{ "jl05-2.d6", 0x040000, 0xb820fa20, 1 | BRF_PRG | BRF_ESS }, // 4
{ "jl04-2.b6", 0x040000, 0x1fd8995b, 1 | BRF_PRG | BRF_ESS }, // 5
{ "jl08.r20", 0x010000, 0x93d93fe1, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code
{ "jl06.d10", 0x010000, 0x91cf668e, 3 | BRF_GRA }, // 7 Characters
{ "jl07.d12", 0x010000, 0xe61d0e42, 3 | BRF_GRA }, // 8
{ "mav00.b10", 0x080000, 0x34785d97, 4 | BRF_GRA }, // 9 Foreground Tiles
{ "mav01.b12", 0x080000, 0x8b531b16, 4 | BRF_GRA }, // 10
{ "mav02.b16", 0x100000, 0x20723bf7, 5 | BRF_GRA }, // 11 Background Tiles
{ "mav03.e16", 0x100000, 0xef6195f0, 5 | BRF_GRA }, // 12
{ "mav05.e19", 0x100000, 0xd92d769c, 6 | BRF_GRA }, // 13 Sprite Bank A
{ "mav04.b19", 0x100000, 0x8ba48385, 6 | BRF_GRA }, // 14
{ "mav07.e20", 0x080000, 0x5fc10ccd, 6 | BRF_GRA }, // 15
{ "mav06.b20", 0x080000, 0xae6201a5, 6 | BRF_GRA }, // 16
{ "mav09.e23", 0x040000, 0x1ce7b51a, 7 | BRF_GRA }, // 17 Sprite Bank B
{ "mav08.b23", 0x040000, 0x64966576, 7 | BRF_GRA }, // 18
{ "mav10.r17", 0x080000, 0x8ad734b0, 8 | BRF_SND }, // 19 OKI M6295 Samples 0
{ "mav11.r19", 0x080000, 0xef513908, 9 | BRF_SND }, // 20 OKI M6295 Samples 1
{ "jn-00.17l", 0x000400, 0x6ac77b84, 0 | BRF_OPT }, // 21 Unused PROMs
};
STD_ROM_PICK(nitrobal)
STD_ROM_FN(nitrobal)
struct BurnDriver BurnDrvNitrobal = {
"nitrobal", NULL, NULL, NULL, "1992",
"Nitro Ball (US)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL, 3, HARDWARE_PREFIX_DATAEAST, GBF_SHOOT, 0,
NULL, nitrobalRomInfo, nitrobalRomName, NULL, NULL, NitrobalInputInfo, NitrobalDIPInfo,
NitrobalInit, DrvExit, DrvFrame, NitrobalDraw, DrvScan, &DrvRecalc, 0x800,
240, 320, 3, 4
};
// Gun Ball (Japan)
static struct BurnRomInfo gunballRomDesc[] = {
{ "jc01.3d", 0x020000, 0x61bfa998, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code
{ "jc00.3b", 0x020000, 0x73ba8f74, 1 | BRF_PRG | BRF_ESS }, // 1
{ "jc03.5d", 0x020000, 0x19231612, 1 | BRF_PRG | BRF_ESS }, // 2
{ "jc02.5b", 0x020000, 0xa254f34c, 1 | BRF_PRG | BRF_ESS }, // 3
{ "jc05-3.6d", 0x040000, 0xf750a709, 1 | BRF_PRG | BRF_ESS }, // 4
{ "jc04-3.6b", 0x040000, 0xad711767, 1 | BRF_PRG | BRF_ESS }, // 5
{ "jl08.r20", 0x010000, 0x93d93fe1, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code
{ "jl06.d10", 0x010000, 0x91cf668e, 3 | BRF_GRA }, // 7 Characters
{ "jl07.d12", 0x010000, 0xe61d0e42, 3 | BRF_GRA }, // 8
{ "mav00.b10", 0x080000, 0x34785d97, 4 | BRF_GRA }, // 9 Foreground Tiles
{ "mav01.b12", 0x080000, 0x8b531b16, 4 | BRF_GRA }, // 10
{ "mav02.b16", 0x100000, 0x20723bf7, 5 | BRF_GRA }, // 11 Background Tiles
{ "mav03.e16", 0x100000, 0xef6195f0, 5 | BRF_GRA }, // 12
{ "mav05.e19", 0x100000, 0xd92d769c, 6 | BRF_GRA }, // 13 Sprite Bank A
{ "mav04.b19", 0x100000, 0x8ba48385, 6 | BRF_GRA }, // 14
{ "mav07.e20", 0x080000, 0x5fc10ccd, 6 | BRF_GRA }, // 15
{ "mav06.b20", 0x080000, 0xae6201a5, 6 | BRF_GRA }, // 16
{ "mav09.e23", 0x040000, 0x1ce7b51a, 7 | BRF_GRA }, // 17 Sprite Bank B
{ "mav08.b23", 0x040000, 0x64966576, 7 | BRF_GRA }, // 18
{ "mav10.r17", 0x080000, 0x8ad734b0, 8 | BRF_SND }, // 19 OKI M6295 Samples 0
{ "mav11.r19", 0x080000, 0xef513908, 9 | BRF_SND }, // 20 OKI M6295 Samples 1
{ "jn-00.17l", 0x000400, 0x6ac77b84, 0 | BRF_OPT }, // 21 Unused PROMs
};
STD_ROM_PICK(gunball)
STD_ROM_FN(gunball)
struct BurnDriver BurnDrvGunball = {
"gunball", "nitrobal", NULL, NULL, "1992",
"Gun Ball (Japan)\0", NULL, "Data East Corporation", "DECO IC16",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL, 3, HARDWARE_PREFIX_DATAEAST, GBF_SHOOT, 0,
NULL, gunballRomInfo, gunballRomName, NULL, NULL, NitrobalInputInfo, NitrobalDIPInfo,
NitrobalInit, DrvExit, DrvFrame, NitrobalDraw, DrvScan, &DrvRecalc, 0x800,
240, 320, 3, 4
};
| 32.424283 | 179 | 0.634223 | atship |
061539070b92ba6ecf691a18d97789d12f62c4f4 | 2,868 | cpp | C++ | src/database/overlay/ftgl/src/FTGlyphContainer.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 2 | 2020-05-21T07:06:07.000Z | 2021-06-28T02:14:34.000Z | src/database/overlay/ftgl/src/FTGlyphContainer.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | null | null | null | src/database/overlay/ftgl/src/FTGlyphContainer.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 6 | 2016-03-21T19:53:18.000Z | 2021-06-08T18:06:03.000Z | /*
Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/#include "FTGlyphContainer.h"
#include "FTGlyph.h"
#include "FTFace.h"
#include "FTCharmap.h"
FTGlyphContainer::FTGlyphContainer( FTFace* f)
: face(f),
err(0)
{
glyphs.push_back( NULL);
charMap = new FTCharmap( face);
}
FTGlyphContainer::~FTGlyphContainer()
{
GlyphVector::iterator glyphIterator;
for( glyphIterator = glyphs.begin(); glyphIterator != glyphs.end(); ++glyphIterator)
{
delete *glyphIterator;
}
glyphs.clear();
delete charMap;
}
bool FTGlyphContainer::CharMap( FT_Encoding encoding)
{
bool result = charMap->CharMap( encoding);
err = charMap->Error();
return result;
}
unsigned int FTGlyphContainer::FontIndex( const unsigned int characterCode) const
{
return charMap->FontIndex( characterCode);
}
void FTGlyphContainer::Add( FTGlyph* tempGlyph, const unsigned int characterCode)
{
charMap->InsertIndex( characterCode, glyphs.size());
glyphs.push_back( tempGlyph);
}
const FTGlyph* const FTGlyphContainer::Glyph( const unsigned int characterCode) const
{
signed int index = charMap->GlyphListIndex( characterCode);
return glyphs[index];
}
FTBBox FTGlyphContainer::BBox( const unsigned int characterCode) const
{
return glyphs[charMap->GlyphListIndex( characterCode)]->BBox();
}
float FTGlyphContainer::Advance( const unsigned int characterCode, const unsigned int nextCharacterCode)
{
unsigned int left = charMap->FontIndex( characterCode);
unsigned int right = charMap->FontIndex( nextCharacterCode);
float width = face->KernAdvance( left, right).X();
width += glyphs[charMap->GlyphListIndex( characterCode)]->Advance().X();
return width;
}
FTPoint FTGlyphContainer::Render( const unsigned int characterCode, const unsigned int nextCharacterCode, FTPoint penPosition)
{
FTPoint kernAdvance, advance;
unsigned int left = charMap->FontIndex( characterCode);
unsigned int right = charMap->FontIndex( nextCharacterCode);
kernAdvance = face->KernAdvance( left, right);
if( !face->Error())
{
advance = glyphs[charMap->GlyphListIndex( characterCode)]->Render( penPosition);
}
kernAdvance += advance;
return kernAdvance;
}
| 26.803738 | 126 | 0.722803 | OpenXIP |
0620730f122eab6b1b96661bd5476e8c17504dc0 | 8,112 | hpp | C++ | src/ngraph/frontend/onnx_import/core/value_info.hpp | bergtholdt/ngraph | 55ca8bb15488ac7a567bb420ca32fcee25e60fe6 | [
"Apache-2.0"
] | null | null | null | src/ngraph/frontend/onnx_import/core/value_info.hpp | bergtholdt/ngraph | 55ca8bb15488ac7a567bb420ca32fcee25e60fe6 | [
"Apache-2.0"
] | null | null | null | src/ngraph/frontend/onnx_import/core/value_info.hpp | bergtholdt/ngraph | 55ca8bb15488ac7a567bb420ca32fcee25e60fe6 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include "ngraph/op/constant.hpp"
#include "ngraph/op/parameter_vector.hpp"
#include "ngraph/shape.hpp"
#include "ngraph/type/element_type.hpp"
#include <onnx/onnx.pb.h>
#include "node.hpp"
#include "tensor.hpp"
namespace ngraph
{
namespace onnx_import
{
namespace error
{
namespace value_info
{
struct unspecified_element_type : ngraph_error
{
unspecified_element_type()
: ngraph_error{"value info has no element type specified"}
{
}
};
struct unsupported_element_type : ngraph_error
{
explicit unsupported_element_type(onnx::TensorProto_DataType type)
: ngraph_error{"unsupported value info element type: " +
onnx::TensorProto_DataType_Name(type)}
{
}
};
}
}
class ValueInfo
{
public:
ValueInfo(ValueInfo&&) = default;
ValueInfo(const ValueInfo&) = default;
ValueInfo() = delete;
explicit ValueInfo(const onnx::ValueInfoProto& value_info_proto)
: m_value_info_proto{&value_info_proto}
{
if (value_info_proto.type().has_tensor_type())
{
for (const auto& dim : value_info_proto.type().tensor_type().shape().dim())
{
m_shape.emplace_back(static_cast<Shape::value_type>(dim.dim_value()));
}
}
}
ValueInfo& operator=(const ValueInfo&) = delete;
ValueInfo& operator=(ValueInfo&&) = delete;
const std::string& get_name() const { return m_value_info_proto->name(); }
const Shape& get_shape() const { return m_shape; }
const element::Type& get_element_type() const
{
if (!m_value_info_proto->type().tensor_type().has_elem_type())
{
throw error::value_info::unspecified_element_type{};
}
switch (m_value_info_proto->type().tensor_type().elem_type())
{
case onnx::TensorProto_DataType::TensorProto_DataType_BOOL: return element::boolean;
case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT:
case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT16: return element::f32;
case onnx::TensorProto_DataType::TensorProto_DataType_DOUBLE: return element::f64;
case onnx::TensorProto_DataType::TensorProto_DataType_INT8: return element::i8;
case onnx::TensorProto_DataType::TensorProto_DataType_INT16: return element::i16;
case onnx::TensorProto_DataType::TensorProto_DataType_INT32: return element::i32;
case onnx::TensorProto_DataType::TensorProto_DataType_INT64: return element::i64;
case onnx::TensorProto_DataType::TensorProto_DataType_UINT8: return element::u8;
case onnx::TensorProto_DataType::TensorProto_DataType_UINT16: return element::u16;
case onnx::TensorProto_DataType::TensorProto_DataType_UINT32: return element::u32;
case onnx::TensorProto_DataType::TensorProto_DataType_UINT64: return element::u64;
default:
throw error::value_info::unsupported_element_type{
m_value_info_proto->type().tensor_type().elem_type()};
}
}
std::shared_ptr<ngraph::Node>
get_ng_node(op::ParameterVector& parameters,
const std::map<std::string, Tensor>& initializers) const
{
const auto it = initializers.find(get_name());
if (it != std::end(initializers))
{
return get_ng_constant(it->second);
}
else
{
parameters.push_back(get_ng_parameter());
return parameters.back();
}
}
protected:
std::shared_ptr<op::Parameter> get_ng_parameter() const
{
return std::make_shared<op::Parameter>(get_element_type(), get_shape());
}
std::shared_ptr<op::Constant> get_ng_constant(const Tensor& tensor) const
{
switch (m_value_info_proto->type().tensor_type().elem_type())
{
case onnx::TensorProto_DataType::TensorProto_DataType_BOOL:
return make_ng_constant<bool>(element::boolean, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT:
case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT16:
return make_ng_constant<float>(element::f32, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_DOUBLE:
return make_ng_constant<double>(element::f64, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_INT8:
return make_ng_constant<int8_t>(element::i8, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_INT16:
return make_ng_constant<int16_t>(element::i16, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_INT32:
return make_ng_constant<int32_t>(element::i32, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_INT64:
return make_ng_constant<int64_t>(element::i64, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_UINT8:
return make_ng_constant<uint8_t>(element::u8, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_UINT16:
return make_ng_constant<uint16_t>(element::u16, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_UINT32:
return make_ng_constant<uint32_t>(element::u32, tensor);
case onnx::TensorProto_DataType::TensorProto_DataType_UINT64:
return make_ng_constant<uint64_t>(element::u64, tensor);
default:
throw error::value_info::unsupported_element_type{
m_value_info_proto->type().tensor_type().elem_type()};
}
}
template <typename T>
std::shared_ptr<op::Constant> make_ng_constant(const element::Type& type,
const Tensor& tensor) const
{
return std::make_shared<op::Constant>(type, m_shape, tensor.get_data<T>());
}
private:
const onnx::ValueInfoProto* m_value_info_proto;
Shape m_shape;
};
inline std::ostream& operator<<(std::ostream& outs, const ValueInfo& info)
{
return (outs << "<ValueInfo: " << info.get_name() << ">");
}
} // namespace onnx_import
} // namespace ngraph
| 45.066667 | 100 | 0.568047 | bergtholdt |
0620bd7b0f9c0b556ffb8af1fdee66019a3353cc | 9,794 | cpp | C++ | vehicle/OVMS.V3/components/vehicle_bmwi3/ecu_definitions/ecu_lim_code.cpp | qtwre/Open-Vehicle-Monitoring-System-3 | 0ebd21bdff06190c0909c29b215ab63f5792e7d6 | [
"MIT"
] | 322 | 2017-06-12T16:56:49.000Z | 2022-03-27T15:46:38.000Z | vehicle/OVMS.V3/components/vehicle_bmwi3/ecu_definitions/ecu_lim_code.cpp | qtwre/Open-Vehicle-Monitoring-System-3 | 0ebd21bdff06190c0909c29b215ab63f5792e7d6 | [
"MIT"
] | 426 | 2017-08-30T04:47:34.000Z | 2022-03-25T21:01:11.000Z | vehicle/OVMS.V3/components/vehicle_bmwi3/ecu_definitions/ecu_lim_code.cpp | qtwre/Open-Vehicle-Monitoring-System-3 | 0ebd21bdff06190c0909c29b215ab63f5792e7d6 | [
"MIT"
] | 194 | 2017-07-03T23:34:08.000Z | 2022-03-16T09:09:22.000Z |
//
// Warning: don't edit - generated by generate_ecu_code.pl processing ../dev/lim_i1.json: LIM 14: Charging interface module
// This generated code makes it easier to process CANBUS messages from the LIM ecu in a BMW i3
//
case I3_PID_LIM_STATUS_CALCVN: { // 0x2541
if (datalen < 20) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_STATUS_CALCVN", 20);
break;
}
unsigned long STAT_CVN_WERT = (RXBUF_UINT32(16));
// Read out CVN (here the CVN must be output as in mode $ 09 (PID $ 06)) / CVN auslesen (hier muss die CVN wie
// bei Mode $09 (PID $06) ausgegeben werden)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%lu%s\n", "LIM", "STATUS_CALCVN", "STAT_CVN_WERT", STAT_CVN_WERT, "\"HEX\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_LADESTECKDOSE_TEMPERATUR: { // 0xDB0F
if (datalen < 2) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_LADESTECKDOSE_TEMPERATUR", 2);
break;
}
float STAT_LADESTECKDOSE_TEMP_WERT = (RXBUF_UINT(0)/10.0f-40.0);
// Temperature of the DC charging connection in ° C (China) / Temperatur der DC-Ladeanschluss in °C (China)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "LIM", "LADESTECKDOSE_TEMPERATUR", "STAT_LADESTECKDOSE_TEMP_WERT", STAT_LADESTECKDOSE_TEMP_WERT, "\"°C\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_LADEBEREITSCHAFT_LIM: { // 0xDEF2
if (datalen < 1) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_LADEBEREITSCHAFT_LIM", 1);
break;
}
unsigned char STAT_LADEBEREITSCHAFT_LIM = (RXBUF_UCHAR(0));
// Ready to charge (HW line), (1 = yes, 0 = no) sent from LIM to SLE / Ladebereitschaft (HW-Leitung), (1 = ja, 0
// = nein) vom LIM an SLE gesendet
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADEBEREITSCHAFT_LIM", "STAT_LADEBEREITSCHAFT_LIM", STAT_LADEBEREITSCHAFT_LIM, "\"0/1\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_PROXIMITY: { // 0xDEF5
if (datalen < 2) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_PROXIMITY", 2);
break;
}
unsigned char STAT_STECKER_NR = (RXBUF_UCHAR(0));
// Condition of the plug / Zustand des Steckers
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PROXIMITY", "STAT_STECKER_NR", STAT_STECKER_NR, "\"0-n\"");
unsigned char STAT_STROMTRAGFAEHIGKEIT_WERT = (RXBUF_UCHAR(1));
// Current carrying capacity of the connected cable / Stromtragfähigkeit des angeschlossenen Kabels
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PROXIMITY", "STAT_STROMTRAGFAEHIGKEIT_WERT", STAT_STROMTRAGFAEHIGKEIT_WERT, "\"A\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_PILOTSIGNAL: { // 0xDEF6
if (datalen < 7) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_PILOTSIGNAL", 7);
break;
}
unsigned char STAT_PILOT_AKTIV = (RXBUF_UCHAR(0));
// State of the pilot signal (0 = not active, 1 = active) / Zustand des Pilotsignals (0 = nicht aktiv, 1 = aktiv)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_AKTIV", STAT_PILOT_AKTIV, "\"0/1\"");
unsigned char STAT_PILOT_PWM_DUTYCYCLE_WERT = (RXBUF_UCHAR(1));
// Pulse duty factor PWM pilot signal / Tastverhältnis PWM Pilotsignal
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_PWM_DUTYCYCLE_WERT", STAT_PILOT_PWM_DUTYCYCLE_WERT, "\"%\"");
unsigned char STAT_PILOT_CURRENT_WERT = (RXBUF_UCHAR(2));
// Current value calculated from the pilot signal / Errechneter Stromwert aus Pilotsignal
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_CURRENT_WERT", STAT_PILOT_CURRENT_WERT, "\"A\"");
unsigned char STAT_PILOT_LADEBEREIT = (RXBUF_UCHAR(3));
// Vehicle ready to charge state (0 = not ready to charge, 1 = ready to charge) / Zustand Ladebereitschaft
// Fahrzeug (0 = nicht ladebereit, 1 = ladebereit)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_LADEBEREIT", STAT_PILOT_LADEBEREIT, "\"0/1\"");
unsigned short STAT_PILOT_FREQUENZ_WERT = (RXBUF_UINT(4));
// Frequency of the pilot signal / Frequenz des Pilotsignals
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_FREQUENZ_WERT", STAT_PILOT_FREQUENZ_WERT, "\"Hz\"");
float STAT_PILOT_PEGEL_WERT = (RXBUF_UCHAR(6)/10.0f);
// Pilot signal level / Pegel des Pilotsignals
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_PEGEL_WERT", STAT_PILOT_PEGEL_WERT, "\"V\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_LADESCHNITTSTELLE_DC_TEPCO: { // 0xDEF7
if (datalen < 4) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_LADESCHNITTSTELLE_DC_TEPCO", 4);
break;
}
unsigned char STAT_CHARGE_CONTROL_1 = (RXBUF_UCHAR(0));
// Charge control status 1 line (0 = not active, 1 = active) / Zustand Charge control 1 Leitung (0 = nicht aktiv,
// 1 = aktiv)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_CHARGE_CONTROL_1", STAT_CHARGE_CONTROL_1, "\"0/1\"");
unsigned char STAT_CHARGE_CONTROL_2 = (RXBUF_UCHAR(1));
// Charge control status 2 line (0 = not active, 1 = active) / Zustand Charge control 2 Leitung (0 = nicht aktiv,
// 1 = aktiv)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_CHARGE_CONTROL_2", STAT_CHARGE_CONTROL_2, "\"0/1\"");
unsigned char STAT_CHARGE_PERMISSION = (RXBUF_UCHAR(2));
// Charge permission line status (0 = not active, 1 = active) / Zustand Charge Permission Leitung (0 = nicht
// aktiv, 1 = aktiv)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_CHARGE_PERMISSION", STAT_CHARGE_PERMISSION, "\"0/1\"");
unsigned char STAT_LADESTECKER = (RXBUF_UCHAR(3));
// State of charging plug (0 = not plugged in, 1 = plugged in) / Zustand Ladestecker (0 = nicht gesteckt, 1 =
// gesteckt)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_LADESTECKER", STAT_LADESTECKER, "\"0/1\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_DC_SCHUETZ_SCHALTER: { // 0xDEF8
if (datalen < 1) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_DC_SCHUETZ_SCHALTER", 1);
break;
}
unsigned char STAT_DC_SCHUETZ_SCHALTER = (RXBUF_UCHAR(0));
// Contactor switch status (DC charging) / Status Schützschalter (DC-Laden)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "DC_SCHUETZ_SCHALTER", "STAT_DC_SCHUETZ_SCHALTER", STAT_DC_SCHUETZ_SCHALTER, "\"0-n\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_DC_SCHUETZ_SPANNUNG_EINGANG: { // 0xDEF9
if (datalen < 3) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_DC_SCHUETZ_SPANNUNG_EINGANG", 3);
break;
}
unsigned short STAT_DC_SCHUETZ_SPANNUNG_EINGANG_WERT = (RXBUF_UINT(0));
// Voltage at the input of the relay box (contactors) for DC charging / Spannung am Eingang der Relaisbox
// (Schaltschütze) für DC-Laden
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "LIM", "DC_SCHUETZ_SPANNUNG_EINGANG", "STAT_DC_SCHUETZ_SPANNUNG_EINGANG_WERT", STAT_DC_SCHUETZ_SPANNUNG_EINGANG_WERT, "\"V\"");
unsigned char STAT_DC_SCHUETZ_SPANNUNG_NEGATIV = (RXBUF_UCHAR(2));
// Detection of a negative voltage (0 = no or positive voltage / 1 = negative voltage) / Erkennung einer
// negativen Spannung (0 = keine oder positive Spannung / 1 = negative Spannung)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "DC_SCHUETZ_SPANNUNG_EINGANG", "STAT_DC_SCHUETZ_SPANNUNG_NEGATIV", STAT_DC_SCHUETZ_SPANNUNG_NEGATIV, "\"0/1\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
case I3_PID_LIM_DC_PINABDECKUNG_COMBO: { // 0xDEFA
if (datalen < 1) {
ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_DC_PINABDECKUNG_COMBO", 1);
break;
}
unsigned char STAT_DC_PINABDECKUNG = (RXBUF_UCHAR(0));
// State of the DC pin cover for combo socket (0 = closed, 1 = open) / Zustand der DC Pinabdeckung bei
// Combo-Steckdose (0 = geschlossen, 1 = geöffnet)
ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "DC_PINABDECKUNG_COMBO", "STAT_DC_PINABDECKUNG", STAT_DC_PINABDECKUNG, "\"0/1\"");
// ========== Add your processing here ==========
hexdump(rxbuf, type, pid);
break;
}
| 48.97 | 183 | 0.620584 | qtwre |
0621aa73a23d5b4465d601edd464d7b63fdd5a36 | 3,494 | cpp | C++ | Code/Projects/Eldritch/src/Components/wbcompeldlight.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | Code/Projects/Eldritch/src/Components/wbcompeldlight.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | Code/Projects/Eldritch/src/Components/wbcompeldlight.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | #include "core.h"
#include "wbcompeldlight.h"
#include "wbcompeldtransform.h"
#include "wbevent.h"
#include "eldritchworld.h"
#include "idatastream.h"
#include "configmanager.h"
WBCompEldLight::WBCompEldLight()
: m_Radius(0.0f),
m_Color(),
m_HasAddedLight(false),
m_LightLocation(),
m_DeferAddLight(false) {}
WBCompEldLight::~WBCompEldLight() { RemoveLight(); }
/*virtual*/ void WBCompEldLight::InitializeFromDefinition(
const SimpleString& DefinitionName) {
Super::InitializeFromDefinition(DefinitionName);
MAKEHASH(DefinitionName);
STATICHASH(Radius);
m_Radius = ConfigManager::GetInheritedFloat(sRadius, 0.0f, sDefinitionName);
STATICHASH(ColorR);
m_Color.r = ConfigManager::GetInheritedFloat(sColorR, 0.0f, sDefinitionName);
STATICHASH(ColorG);
m_Color.g = ConfigManager::GetInheritedFloat(sColorG, 0.0f, sDefinitionName);
STATICHASH(ColorB);
m_Color.b = ConfigManager::GetInheritedFloat(sColorB, 0.0f, sDefinitionName);
m_Color.a = 1.0f;
STATICHASH(DeferAddLight);
m_DeferAddLight =
ConfigManager::GetInheritedBool(sDeferAddLight, false, sDefinitionName);
}
/*virtual*/ void WBCompEldLight::HandleEvent(const WBEvent& Event) {
XTRACE_FUNCTION;
Super::HandleEvent(Event);
STATIC_HASHED_STRING(OnMoved);
STATIC_HASHED_STRING(OnDestroyed);
STATIC_HASHED_STRING(AddLight);
STATIC_HASHED_STRING(RemoveLight);
const HashedString EventName = Event.GetEventName();
if (EventName == sOnMoved) {
if (m_DeferAddLight) {
// Do nothing
} else {
AddLight();
}
} else if (EventName == sAddLight) {
AddLight();
} else if (EventName == sOnDestroyed || EventName == sRemoveLight) {
RemoveLight();
}
}
void WBCompEldLight::AddLight() {
// I don't currently want to support dynamic light-emitting entities.
// So this event handles the first time a static entity's location is set.
// But if it moves again, that's a problem!
if (m_HasAddedLight) {
return;
}
WBCompEldTransform* pTransform =
GetEntity()->GetTransformComponent<WBCompEldTransform>();
DEVASSERT(pTransform);
m_LightLocation = pTransform->GetLocation();
m_HasAddedLight = GetWorld()->AddLightAt(m_LightLocation, m_Radius, m_Color);
}
void WBCompEldLight::RemoveLight() {
if (m_HasAddedLight) {
m_HasAddedLight = false;
if (GetWorld()) {
GetWorld()->RemoveLightAt(m_LightLocation);
}
}
}
#define VERSION_EMPTY 0
#define VERSION_LIGHT 1
#define VERSION_CURRENT 1
uint WBCompEldLight::GetSerializationSize() {
uint Size = 0;
Size += 4; // Version
Size += sizeof(bool); // m_HasAddedLight
Size += sizeof(Vector); // m_LightLocation
return Size;
}
void WBCompEldLight::Save(const IDataStream& Stream) {
Stream.WriteUInt32(VERSION_CURRENT);
Stream.WriteBool(m_HasAddedLight);
#ifdef __amigaos4__
Vector tmp(m_LightLocation);
littleBigEndian(&tmp.x);
littleBigEndian(&tmp.y);
littleBigEndian(&tmp.z);
Stream.Write(sizeof(Vector), &tmp);
#else
Stream.Write(sizeof(Vector), &m_LightLocation);
#endif
}
void WBCompEldLight::Load(const IDataStream& Stream) {
XTRACE_FUNCTION;
const uint Version = Stream.ReadUInt32();
if (Version >= VERSION_LIGHT) {
m_HasAddedLight = Stream.ReadBool();
Stream.Read(sizeof(Vector), &m_LightLocation);
#ifdef __amigaos4__
littleBigEndian(&m_LightLocation.x);
littleBigEndian(&m_LightLocation.y);
littleBigEndian(&m_LightLocation.z);
#endif
}
} | 25.881481 | 79 | 0.716943 | kas1e |
1646804752e4aa8d221bb3f28fc88fc8709acbb9 | 12,586 | cpp | C++ | main.cpp | erlog/laughing-couscous | ef5f3ec1e83d524ebad04fd6d62e5b39d95ec413 | [
"MIT",
"Ruby",
"Unlicense"
] | null | null | null | main.cpp | erlog/laughing-couscous | ef5f3ec1e83d524ebad04fd6d62e5b39d95ec413 | [
"MIT",
"Ruby",
"Unlicense"
] | null | null | null | main.cpp | erlog/laughing-couscous | ef5f3ec1e83d524ebad04fd6d62e5b39d95ec413 | [
"MIT",
"Ruby",
"Unlicense"
] | null | null | null | //Compile-time Flags
//#define MAC_COMPILE 0
//#define LINUX_COMPILE 1
#define MEMORY_LOGGING 0
#define DEBUG 1
#include "main.h"
int main() {
//INITIALIZATION- Failures here cause a hard exit
//Start Ruby
ruby_setup_environment(); //VALUE rb_update_func = rb_intern("ruby_update");
//Initialize State & Debug Memory Manager
Memory_Info mem_info = {0}; Global_State = &mem_info;
State* state = (State*)walloc(sizeof(State));
//Load global strings
String_DB _string_db;
state->Strings = &_string_db;
load_strings(state->Strings, "english");
wfree_string_db(state->Strings);
//Initialize game input
state->Input = (Game_Input*)walloc(sizeof(Game_Input));
clear_input(state->Input);
//Load global settings file
load_settings(state);
state->IsRunning = true; //Set this to false to exit after one frame
state->IsPaused = true; //Pause will be toggled when our window gains focus
//DEBUG: Initialize rand()
//TODO: remove this
time_t t;
srand((unsigned) time(&t));
//Initialize screen struct and buffer for taking screenshots
state->Screen = (Texture*)walloc(sizeof(Texture));
state->Screen->asset_path = str_lit("Flamerokz");
state->Screen->width = state->Settings.horizontal_resolution;
state->Screen->height = state->Settings.vertical_resolution;
state->Screen->bytes_per_pixel = 3;
state->Screen->pitch = state->Screen->width * state->Screen->bytes_per_pixel;
state->Screen->buffer_size = state->Screen->pitch * state->Screen->height;
state->Screen->buffer = (uint8_t*)walloc(state->Screen->buffer_size);
//Initialize SDL and OpenGL
SDL_Event event;
int error = SDL_Init(SDL_INIT_VIDEO); if(error != 0) {
message_log("SDL Init Error, Code", error); return 0;
}
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); //Use OpenGL 3.1
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
//TODO: implement fullscreen
SDL_Window* window = SDL_CreateWindow( state->Screen->asset_path,
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, state->Screen->width,
state->Screen->height, SDL_WINDOW_OPENGL);
if(window == NULL) {
message_log("Couldn't initialize-", "SDL OpenGL window"); return 0;
}
state->Window = window;
SDL_GLContext context = SDL_GL_CreateContext( window );
if(context == NULL) {
message_log("Couldn't get-", "OpenGL Context for window"); return 0;
}
if(state->Settings.vsync) { if(SDL_GL_SetSwapInterval(1) != 0) {
//late-swap tearing if the vsync call fails
SDL_GL_SetSwapInterval(-1);
} }
const uint8_t* SDL_KeyState = SDL_GetKeyboardState(NULL);
//GLEW
glewExperimental = GL_TRUE;
if(glewInit() != GLEW_OK) {
message_log("Couldn't initialize-", "GLEW"); return 0;
}
if(!GLEW_VERSION_2_1) {
message_log("OpenGL 2.1 not supported by GLEW", ""); return 0;
}
//Set up simple OpenGL environment for rendering
glPixelStorei(GL_PACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glMatrixMode( GL_PROJECTION ); glLoadIdentity();
glMatrixMode( GL_MODELVIEW ); glLoadIdentity();
glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE);
//glFrontFace(GL_CCW); //Default is CCW, counter-clockwise
//glDepthRange(1.0, -1.0); //change the handedness of the z axis
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//GAME INIT- Failures here may cause a proper smooth exit when necessary
//Construct Camera
state->Camera = (Scene_Camera*)walloc(sizeof(Scene_Camera));
state->Camera->physics = (Physics_Object*)walloc(sizeof(Physics_Object));
load_physics(state->Camera->physics);
state->Camera->projection = glm::perspective(glm::radians(45.0f),
(float)state->Screen->width/state->Screen->height, 0.1f, 100.0f);
//Construct screen-space camera for HUD elements
Scene_Camera screen_camera;
screen_camera.physics = (Physics_Object*)walloc(sizeof(Physics_Object));
load_physics(screen_camera.physics);
//TODO: figure out how to make this in semi-normalized coords that
//can be somewhat resolution-independent
screen_camera.projection = glm::ortho(0.0f, (float)state->Screen->width,
0.0f, (float)state->Screen->height);
//Load Objects
state->Debug_Cube = (Object*)walloc(sizeof(Object));
load_object(state->Debug_Cube, "cube", "blank", "blank_nm",
"blank_spec", "shader");
state->Debug_Sphere = (Object*)walloc(sizeof(Object));
load_object(state->Debug_Sphere, "sphere", "blank", "blank_nm",
"blank_spec", "flat_shaded");
state->Player = (Object*)walloc(sizeof(Object));
load_object(state->Player, "wedge", "cheese", "blank_nm_512",
"cheese_spec", "shader");
state->Player->model->color = rgb_to_vector(0xE7, 0xE0, 0x8B);
state->Player->physics->position = glm::vec3(0.0f, -1.0f, 0.0f);
glm::vec3 light_direction = glm::vec3(0.0f, -1.0f, -1.0f);
normalize(&light_direction);
//TODO: break this out into level loading code
state->ObjectCount = 3;
state->Objects = (Object*)walloc(sizeof(Object)*state->ObjectCount);
load_object(&state->Objects[0], "cube", "blank", "blank_nm",
"blank_spec", "flat");
state->Objects[0].physics->position = glm::vec3(-10.5f, 0.0f, 0.0f);
state->Objects[0].physics->rotation_vector = glm::vec3(1.0f, 1.0f, 0.0f);
state->Objects[0].light_direction = light_direction;
state->Objects[0].model->color = rgb_to_vector(0xE3, 0x1F, 0x1F);
load_object(&state->Objects[1], "african_head", "african_head", "african_head",
"african_head", "flat_shaded");
state->Objects[1].physics->position = glm::vec3(10.5f, 0.0f, 0.0f);
state->Objects[1].physics->rotation_vector = glm::vec3(0.0f, 1.0f, 0.0f);
state->Objects[1].light_direction = light_direction;
state->Objects[1].model->color = rgb_to_vector(0xE3, 0x78, 0x1F);
state->Objects[1].model->scale = glm::vec3(5.0f, 5.0f, 5.0f);
load_object(&state->Objects[2], "cone", "blank", "blank_nm",
"blank_spec", "flat_shaded");
state->Objects[2].physics->position = glm::vec3(-15.5f, 0.0f, 0.0f);
state->Objects[2].physics->rotation_vector = glm::vec3(0.0f, 0.0f, 1.0f);
state->Objects[2].light_direction = light_direction;
state->Objects[2].model->color = rgb_to_vector(0x19, 0xB5, 0x19);
state->Level = (Game_Level*)walloc(sizeof(Game_Level));
load_level(state->Level, "test_level");
//octree_print(&state->Level->octree->root);
Font test_font;
UChar* test_text = UChar_convert("#testing, unicode, 微研");
load_font(&test_font, "DroidSans");
//MAIN LOOP- Failures here may cause a proper smooth exit when necessary
message_log("Starting update loop.");
//TODO: figure out how to start my clock without eating the first frame
state->TimeDifference = 0;
state->LastUpdateTime = 0;
state->PauseStartTime = 0;
int passed_frames = 0;
while(state->IsRunning) {
update_time(state);
//Process keydown events
while(SDL_PollEvent(&event)) { switch(event.type) {
case SDL_WINDOWEVENT:
if(event.window.event == SDL_WINDOWEVENT_SHOWN) {
SDL_SetRelativeMouseMode(SDL_TRUE);
//eat first input to avoid movement jitter
SDL_GetRelativeMouseState(NULL, NULL);
toggle_pause(state);
} else if(event.window.event == SDL_WINDOWEVENT_HIDDEN) {
SDL_SetRelativeMouseMode(SDL_FALSE);
toggle_pause(state);
}
break;
case SDL_KEYDOWN:
handle_keyboard(state, event);
break;
case SDL_QUIT:
state->IsRunning = false;
break;
} }
if(state->IsPaused) { continue; }
poll_input(state, SDL_KeyState);
//TODO: is there a better way to control our framerate?
if( state->DeltaTimeMS > 30 ) {
process_input(state);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//TODO: unified camera system
//first person camera
#if 0
state->Camera->direction = glm::normalize(
glm::vec3(0.0f, 0.0f, -1.0f) * state->Camera->physics->quaternion);
state->Camera->view = glm::lookAt(state->Camera->physics->position,
state->Camera->direction + state->Camera->physics->position,
glm::vec3(0.0f, 1.0f, 0.0f));
state->Camera->physics->quaternion =
glm::quat_cast(state->Camera->view);
#endif
//3rd-person camera
#if 1
state->Camera->physics->position = state->Player->physics->position +
(glm::vec3(0.0f, 6.0f, 6.0f) * state->Camera->physics->quaternion);
state->Camera->view = glm::lookAt(state->Camera->physics->position,
state->Player->physics->position,
glm::vec3(0.0f, 1.0f, 0.0f));
#endif
//draw dynamic objects
for(int i = 0; i < state->ObjectCount; i++) {
//state->Objects[i].physics->angular_velocity = 30.0f;
//update_physics_object(state->Objects[i].physics, state->DeltaTimeS);
gl_draw_object(state->Camera, &state->Objects[i]);
}
//draw level
gl_draw_object(state->Camera, state->Level->geometry);
//octree_debug_draw(state->Level->octree, state);
//do player movement relative to the camera
state->Player->physics->quaternion = state->Camera->physics->quaternion;
state->Player->physics->time_remaining = state->DeltaTimeS;
physics_process_movement(state->Player->physics);
//TODO: make our collision detection not require this sanity check
if(state->Player->physics->moved) {
for(int reps = 0; reps < 25; reps ++) {
if(!process_collision(state->Level, state->Player->physics)) {
break;
}
}
}
//face model in direction of movement
physics_face_movement_direction(state->Player);
gl_draw_object(state->Camera, state->Player);
//draw bounding box
#if 1
state->Debug_Sphere->physics->position = state->Player->physics->position;
state->Debug_Sphere->model->scale = state->Player->physics->radii;
//state->Debug_Sphere->model->rotation = state->Player->model->rotation;
gl_toggle_wireframe(true);
gl_draw_object(state->Camera, state->Debug_Sphere);
gl_toggle_wireframe(false);
#endif
//draw test text
//TODO: make this an FPS counter
test_font.quad->physics->position = glm::vec3(0.0f, 8.0f, 0.0f);
gl_draw_text(&screen_camera, &test_font, test_text, 32.0f);
SDL_GL_SwapWindow(window);
state->LastUpdateTime = state->GameTime;
state->FrameCounter += 1;
//Spit out debug info
if(state->FrameCounter > 100) {
float fps = (float)state->FrameCounter;
fps /= (state->WallTime - state->LastFPSUpdateTime);
message_log("FPS-", fps*1000);
fps = (float)passed_frames;
fps /= (state->WallTime - state->LastFPSUpdateTime);
message_log("Loops spent idling per second-", fps*1000);
message_log("Memory in use-", mem_info.MemoryAllocated -
mem_info.MemoryFreed);
passed_frames = 0;
state->FrameCounter = 0;
state->LastFPSUpdateTime = state->WallTime;
}
clear_input(state->Input);
}
else { passed_frames++; }
}
take_screenshot(state);
wfree_font(&test_font);
wfree_camera(&screen_camera);
wfree(test_text);
wfree_state(state);
wfree(state);
ruby_cleanup(0);
printf("Leaked- %lu Bytes", mem_info.MemoryAllocated - mem_info.MemoryFreed);
SDL_Quit();
return 0;
}
| 39.454545 | 86 | 0.622199 | erlog |
164bf7629950c384ca4357f1bb52a8375321f6bd | 2,112 | cpp | C++ | Javelin/Tools/jasm/CodeSegmentSource.cpp | jthlim/JavelinPattern | 8add264f88ac620de109ddf797f7431779bbd9ea | [
"BSD-3-Clause"
] | 10 | 2016-04-06T01:24:00.000Z | 2021-11-16T10:16:51.000Z | Javelin/Tools/jasm/CodeSegmentSource.cpp | jthlim/JavelinPattern | 8add264f88ac620de109ddf797f7431779bbd9ea | [
"BSD-3-Clause"
] | 1 | 2016-05-06T05:38:58.000Z | 2016-05-09T16:42:43.000Z | Javelin/Tools/jasm/CodeSegmentSource.cpp | jthlim/JavelinPattern | 8add264f88ac620de109ddf797f7431779bbd9ea | [
"BSD-3-Clause"
] | null | null | null | //============================================================================
#include "Javelin/Tools/jasm/CodeSegmentSource.h"
//============================================================================
using namespace Javelin::Assembler;
//============================================================================
CodeSegmentSource::CodeSegmentSource(const CodeSegmentData &aData, int aIndent)
: data(aData), indent(aIndent)
{
}
int CodeSegmentSource::ReadByte()
{
if(index >= data.size()) return EOF;
const std::string& s = data[index].line;
if(offset >= s.size())
{
offset = 0;
++index;
return '\n';
}
return (uint8_t) s[offset++];
}
int CodeSegmentSource::PeekByte()
{
if(index >= data.size()) return EOF;
const std::string& s = data[index].line;
if(offset >= s.size()) return '\n';
return (uint8_t) s[offset];
}
void CodeSegmentSource::SkipByte()
{
if(index >= data.size()) return;
const std::string& s = data[index].line;
if(offset >= s.size())
{
offset = 0;
++index;
}
else
{
++offset;
}
}
//============================================================================
int CodeSegmentSource::GetCurrentLineNumber() const
{
if(data.size() == 0) return 0;
if(index >= data.size()) return data[index-1].lineNumber;
return data[index].lineNumber;
}
const std::string CodeSegmentSource::GetPreviousLine() const
{
if(data.size() == 0) return "";
if(index == 0) return data[0].line;
return data[index-1].line;
}
const std::string CodeSegmentSource::GetCurrentLine() const
{
if(data.size() == 0) return "";
if(index >= data.size()) return data[index-1].line;
return data[index].line;
}
int CodeSegmentSource::GetCurrentFileIndex() const
{
if(data.size() == 0) return 0;
if(index >= data.size()) return data[index-1].fileIndex;
return data[index].fileIndex;
}
bool CodeSegmentSource::GetCurrentLineIsPreprocessor() const
{
if(data.size() == 0) return false;
if(index >= data.size()) return data[index-1].isPreprocessor;
return data[index].isPreprocessor;
}
//============================================================================
| 22.231579 | 79 | 0.551136 | jthlim |
164fb7502e74fbb74baf2e56db0e25f829ea3ece | 10,317 | cpp | C++ | dotth/D3D11RHI.cpp | jaefunk/dotth | d93c69a1744c545606bec3ee0cdc8f46b5c19d36 | [
"MIT"
] | null | null | null | dotth/D3D11RHI.cpp | jaefunk/dotth | d93c69a1744c545606bec3ee0cdc8f46b5c19d36 | [
"MIT"
] | 8 | 2019-11-05T00:06:59.000Z | 2022-03-28T09:20:40.000Z | dotth/D3D11RHI.cpp | jaefunk/dotth | d93c69a1744c545606bec3ee0cdc8f46b5c19d36 | [
"MIT"
] | null | null | null | #include "D3D11RHI.h"
#include "D3D11Shader.h"
D3D11RHI::~D3D11RHI()
{
D3D11RHI::Instance()->_Device->Release();
D3D11RHI::Instance()->_Context->Release();;
D3D11RHI::Instance()->_SwapChain->Release();
D3D11RHI::Instance()->_BackBufferRTV->Release();
D3D11RHI::Instance()->_RasterizerStateSolid->Release();
D3D11RHI::Instance()->_SamplerState->Release();
D3D11RHI::Instance()->_DepthStencilView->Release();;
}
bool D3D11RHI::Initialize(HWND hwnd, unsigned int width, unsigned int height)
{
D3D11RHI::Instance()->_Width = width;
D3D11RHI::Instance()->_Height = height;
D3D11RHI::Instance()->_FeatureLevel = D3D_FEATURE_LEVEL_11_1;
UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
//createDeviceFlags |= D3D11_DEBUG;
#endif
if (FAILED(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE::D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, &D3D11RHI::Instance()->_FeatureLevel, 1, D3D11_SDK_VERSION, &D3D11RHI::Instance()->_Device, nullptr, &D3D11RHI::Instance()->_Context)))
{
return false;
}
IDXGIFactory* factory = nullptr;
if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory)))
{
return false;
}
const unsigned int RenderTargetWidth = width;
const unsigned int RenderTargetHeight = height;
DXGI_SWAP_CHAIN_DESC scd;
ZeroMemory(&scd, sizeof(scd));
scd.BufferCount = 1;
scd.BufferDesc.Width = RenderTargetWidth;
scd.BufferDesc.Height = RenderTargetHeight;
scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
scd.BufferDesc.RefreshRate.Numerator = 60;
scd.BufferDesc.RefreshRate.Denominator = 1;
scd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
scd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.OutputWindow = (HWND)hwnd;
scd.SampleDesc.Count = 1;
scd.SampleDesc.Quality = 0;
scd.Windowed = true;
scd.Flags = 0;
if (FAILED(factory->CreateSwapChain(D3D11RHI::Instance()->_Device, &scd, &D3D11RHI::Instance()->_SwapChain)))
{
return false;
}
ID3D11Texture2D* backbuffer = nullptr;
D3D11RHI::SwapChain()->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backbuffer));
D3D11RHI::Device()->CreateRenderTargetView(backbuffer, NULL, &D3D11RHI::Instance()->_BackBufferRTV);
backbuffer->Release();
D3D11_TEXTURE2D_DESC db;
ZeroMemory(&db, sizeof(db));
db.Width = RenderTargetWidth;
db.Height = RenderTargetHeight;
db.MipLevels = 1;
db.ArraySize = 1;
db.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
db.SampleDesc.Count = 1;
db.SampleDesc.Quality = 0;
db.Usage = D3D11_USAGE_DEFAULT;
db.BindFlags = D3D11_BIND_DEPTH_STENCIL;
db.CPUAccessFlags = 0;
db.MiscFlags = 0;
ID3D11Texture2D* depthstencilbuffer = nullptr;
D3D11RHI::Device()->CreateTexture2D(&db, NULL, &depthstencilbuffer);
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
D3D11RHI::Device()->CreateDepthStencilState(&depthStencilDesc, &D3D11RHI::Instance()->_DepthStencilState);
D3D11RHI::Context()->OMSetDepthStencilState(D3D11RHI::Instance()->_DepthStencilState, 1);
D3D11_DEPTH_STENCIL_VIEW_DESC dsvd;
ZeroMemory(&dsvd, sizeof(dsvd));
dsvd.Format = db.Format;
dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
dsvd.Texture2D.MipSlice = 0;
D3D11RHI::Device()->CreateDepthStencilView(depthstencilbuffer, &dsvd, &D3D11RHI::Instance()->_DepthStencilView);
depthstencilbuffer->Release();
D3D11RHI::Context()->OMSetRenderTargets(1, &D3D11RHI::Instance()->_BackBufferRTV, D3D11RHI::DepthStencilView());
D3D11_RASTERIZER_DESC rd;
ZeroMemory(&rd, sizeof(D3D11_RASTERIZER_DESC));
rd.AntialiasedLineEnable = false;
rd.CullMode = D3D11_CULL_BACK;
rd.DepthBias = 0;
rd.DepthBiasClamp = 0.0f;
rd.DepthClipEnable = true;
rd.FillMode = D3D11_FILL_SOLID;
rd.FrontCounterClockwise = false;
rd.MultisampleEnable = false;
rd.ScissorEnable = false;
rd.SlopeScaledDepthBias = 0.0f;
D3D11RHI::Device()->CreateRasterizerState(&rd, &D3D11RHI::Instance()->_RasterizerStateSolid);
D3D11RHI::Context()->RSSetState(D3D11RHI::Instance()->_RasterizerStateSolid);
D3D11_SAMPLER_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sd.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sd.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sd.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sd.ComparisonFunc = D3D11_COMPARISON_NEVER;
sd.MinLOD = 0;
sd.MaxLOD = D3D11_FLOAT32_MAX;
if (FAILED(D3D11RHI::Device()->CreateSamplerState(&sd, &D3D11RHI::Instance()->_SamplerState)))
{
return false;
}
D3D11_VIEWPORT viewport;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
viewport.Width = static_cast<float>(RenderTargetWidth);
viewport.Height = static_cast<float>(RenderTargetHeight);
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
D3D11RHI::Context()->RSSetViewports(1, &viewport);
D3D11RHI::Instance()->_DeferredBuffer = std::make_shared<D3D11DeferredBuffer>();
D3D11RHI::Instance()->_DeferredBuffer->Initialize(D3D11RHI::Device(), RenderTargetWidth, RenderTargetHeight);
D3D11RHI::Instance()->_OrthoRect = std::make_shared<D3D11OrthoRect>();
D3D11RHI::Instance()->_OrthoRect->Initialize(D3D11RHI::Device(), RenderTargetWidth, RenderTargetHeight);
D3D11RHI::Instance()->_Light = std::make_shared<D3D11Light>();
D3D11RHI::Instance()->_Light->Initialize(D3D11RHI::Device(), hwnd);
D3D11RHI::Instance()->_OrthoMatrix = XMMatrixOrthographicLH(static_cast<float>(D3D11RHI::Instance()->_Width), static_cast<float>(D3D11RHI::Instance()->_Height), 0.f, 1000.f);
return true;
}
void D3D11RHI::InitializeImGui(HWND hwnd, unsigned int width, unsigned int height)
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
//ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsDark();
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(D3D11RHI::Device(), D3D11RHI::Context());
}
void D3D11RHI::StandbyDeferred(void)
{
float clear_color_with_alpha[4] = { 0.f, 0.f, 0.f, 0.f };
D3D11RHI::DeferredBuffer()->SetRenderTargets(D3D11RHI::Context());
D3D11RHI::DeferredBuffer()->ClearRenderTargets(D3D11RHI::Context(), clear_color_with_alpha);
}
void D3D11RHI::Draw(void)
{
float clear_color_with_alpha[4] = { 0.f, 0.f, 0.f, 0.f };
D3D11RHI::Context()->OMSetRenderTargets(1, &D3D11RHI::Instance()->_BackBufferRTV, D3D11RHI::DepthStencilView());
D3D11RHI::Context()->ClearRenderTargetView(D3D11RHI::BackBuffer(), clear_color_with_alpha);
D3D11RHI::Context()->ClearDepthStencilView(D3D11RHI::DepthStencilView(), D3D11_CLEAR_DEPTH, 1.0f, 0);
D3D11RHI::Context()->OMSetDepthStencilState(D3D11RHI::DepthStencilState(), 0);
D3D11RHI::Instance()->_OrthoRect->Render(D3D11RHI::Context());
D3D11RHI::Instance()->_Light->Render(
D3D11RHI::Context(), 6,
XMMatrixIdentity(),
XMMatrixIdentity(),
D3D11RHI::Instance()->_OrthoMatrix,
D3D11RHI::DeferredBuffer()->GetShaderResourceView(0),
D3D11RHI::DeferredBuffer()->GetShaderResourceView(1),
XMFLOAT3(-1.f, -1.f, 1.f));
}
void D3D11RHI::BeginImGui(void)
{
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
}
void D3D11RHI::EndImGui(void)
{
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
}
void D3D11RHI::Present(void)
{
D3D11RHI::SwapChain()->Present(1, 0);
}
ID3D11Device* D3D11RHI::Device()
{
return D3D11RHI::Instance()->_Device;
}
ID3D11DeviceContext* D3D11RHI::Context()
{
return D3D11RHI::Instance()->_Context;
}
IDXGISwapChain* D3D11RHI::SwapChain()
{
return D3D11RHI::Instance()->_SwapChain;
}
ID3D11RenderTargetView* D3D11RHI::BackBuffer()
{
return D3D11RHI::Instance()->_BackBufferRTV;
}
ID3D11DepthStencilView* D3D11RHI::DepthStencilView()
{
return D3D11RHI::Instance()->_DepthStencilView;
}
ID3D11SamplerState* D3D11RHI::Sampler()
{
return D3D11RHI::Instance()->_SamplerState;
}
ID3D11DepthStencilState* D3D11RHI::DepthStencilState()
{
return D3D11RHI::Instance()->_DepthStencilState;
}
//
//ID3D11Buffer * D3D11RHI::CreateBuffer(const D3D11_BUFFER_DESC* desc, const D3D11_SUBRESOURCE_DATA* data)
//{
// ID3D11Buffer* buffer = nullptr;
// Device()->CreateBuffer(desc, data, &buffer);
// return buffer;
//}
//
//ID3D11VertexShader * D3D11RHI::CreateVertexShader(ID3DBlob * blob)
//{
// ID3D11VertexShader* shader = nullptr;
// Device()->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &shader);
// return shader;
//}
//
//ID3D11PixelShader * D3D11RHI::CreatePixelShader(ID3DBlob * blob)
//{
// ID3D11PixelShader* shader = nullptr;
// Device()->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &shader);
// return shader;
//}
//
//ID3D11InputLayout * D3D11RHI::CreateInputLayout(ID3DBlob * blob, D3D11_INPUT_ELEMENT_DESC * desc, unsigned int desc_size)
//{
// ID3D11InputLayout* layout = nullptr;
// Device()->CreateInputLayout(desc, desc_size, blob->GetBufferPointer(), blob->GetBufferSize(), &layout);
// return layout;
//}
//
//void D3D11RHI::BindVertexBuffer(ID3D11Buffer* buffer, unsigned int size, unsigned int offset)
//{
// D3D11RHI::Context()->IASetVertexBuffers(0, 1, &buffer, &size, &offset);
//
//}
//
//void D3D11RHI::BindIndexBuffer(ID3D11Buffer* buffer)
//{
// D3D11RHI::Context()->IASetIndexBuffer(buffer, DXGI_FORMAT_R32_UINT, 0);
//}
std::shared_ptr<D3D11DeferredBuffer> D3D11RHI::DeferredBuffer(void)
{
return D3D11RHI::Instance()->_DeferredBuffer;
}
void D3D11RHI::GetViewportSize(unsigned int& width, unsigned int& height)
{
width = D3D11RHI::Instance()->_Width;
height = D3D11RHI::Instance()->_Height;
} | 33.9375 | 245 | 0.765048 | jaefunk |
1650e602e330de0258ece84363a3c6137e7cfed6 | 4,886 | cpp | C++ | src/3rdparty/libnbtplusplus/src/tag_list.cpp | AgustinSRG/ImageToMapMC | fbff8017e87c30baaa0c9c2327bdd28846253646 | [
"MIT"
] | null | null | null | src/3rdparty/libnbtplusplus/src/tag_list.cpp | AgustinSRG/ImageToMapMC | fbff8017e87c30baaa0c9c2327bdd28846253646 | [
"MIT"
] | null | null | null | src/3rdparty/libnbtplusplus/src/tag_list.cpp | AgustinSRG/ImageToMapMC | fbff8017e87c30baaa0c9c2327bdd28846253646 | [
"MIT"
] | null | null | null | /*
* libnbt++ - A library for the Minecraft Named Binary Tag format.
* Copyright (C) 2013, 2015 ljfa-ag
*
* This file is part of libnbt++.
*
* libnbt++ 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, either version 3 of the License, or
* (at your option) any later version.
*
* libnbt++ 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 libnbt++. If not, see <http://www.gnu.org/licenses/>.
*/
#include "tag_list.h"
#include "nbt_tags.h"
#include "io/stream_reader.h"
#include "io/stream_writer.h"
#include <istream>
namespace nbt
{
tag_list::tag_list(std::initializer_list<int8_t> il) { init<tag_byte>(il); }
tag_list::tag_list(std::initializer_list<int16_t> il) { init<tag_short>(il); }
tag_list::tag_list(std::initializer_list<int32_t> il) { init<tag_int>(il); }
tag_list::tag_list(std::initializer_list<int64_t> il) { init<tag_long>(il); }
tag_list::tag_list(std::initializer_list<float> il) { init<tag_float>(il); }
tag_list::tag_list(std::initializer_list<double> il) { init<tag_double>(il); }
tag_list::tag_list(std::initializer_list<std::string> il) { init<tag_string>(il); }
tag_list::tag_list(std::initializer_list<tag_byte_array> il) { init<tag_byte_array>(il); }
tag_list::tag_list(std::initializer_list<tag_list> il) { init<tag_list>(il); }
tag_list::tag_list(std::initializer_list<tag_compound> il) { init<tag_compound>(il); }
tag_list::tag_list(std::initializer_list<tag_int_array> il) { init<tag_int_array>(il); }
tag_list::tag_list(std::initializer_list<tag_long_array> il) { init<tag_long_array>(il); }
tag_list::tag_list(std::initializer_list<value> init)
{
if(init.size() == 0)
el_type_ = tag_type::Null;
else
{
el_type_ = init.begin()->get_type();
for(const value& val: init)
{
if(!val || val.get_type() != el_type_)
throw std::invalid_argument("The values are not all the same type");
}
tags.assign(init.begin(), init.end());
}
}
value& tag_list::at(size_t i)
{
return tags.at(i);
}
const value& tag_list::at(size_t i) const
{
return tags.at(i);
}
void tag_list::set(size_t i, value&& val)
{
if(val.get_type() != el_type_)
throw std::invalid_argument("The tag type does not match the list's content type");
tags.at(i) = std::move(val);
}
void tag_list::push_back(value_initializer&& val)
{
if(!val) //don't allow null values
throw std::invalid_argument("The value must not be null");
if(el_type_ == tag_type::Null) //set content type if undetermined
el_type_ = val.get_type();
else if(el_type_ != val.get_type())
throw std::invalid_argument("The tag type does not match the list's content type");
tags.push_back(std::move(val));
}
void tag_list::reset(tag_type type)
{
clear();
el_type_ = type;
}
void tag_list::read_payload(io::stream_reader& reader)
{
tag_type lt = reader.read_type(true);
int32_t length;
reader.read_num(length);
if(length < 0)
reader.get_istr().setstate(std::ios::failbit);
if(!reader.get_istr())
throw io::input_error("Error reading length of tag_list");
if(lt != tag_type::End)
{
reset(lt);
tags.reserve(length);
for(int32_t i = 0; i < length; ++i)
tags.emplace_back(reader.read_payload(lt));
}
else
{
//In case of tag_end, ignore the length and leave the type undetermined
reset(tag_type::Null);
}
}
void tag_list::write_payload(io::stream_writer& writer) const
{
if(size() > io::stream_writer::max_array_len)
{
writer.get_ostr().setstate(std::ios::failbit);
throw std::length_error("List is too large for NBT");
}
writer.write_type(el_type_ != tag_type::Null
? el_type_
: tag_type::End);
writer.write_num(static_cast<int32_t>(size()));
for(const auto& val: tags)
{
//check if the value is of the correct type
if(val.get_type() != el_type_)
{
writer.get_ostr().setstate(std::ios::failbit);
throw std::logic_error("The tags in the list do not all match the content type");
}
writer.write_payload(val);
}
}
bool operator==(const tag_list& lhs, const tag_list& rhs)
{
return lhs.el_type_ == rhs.el_type_ && lhs.tags == rhs.tags;
}
bool operator!=(const tag_list& lhs, const tag_list& rhs)
{
return !(lhs == rhs);
}
}
| 32.144737 | 93 | 0.651658 | AgustinSRG |
1651082bd716f0a2a479444b9518d6853ee92edd | 1,030 | cpp | C++ | ycitoj/week1/a.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | 3 | 2022-03-30T14:14:57.000Z | 2022-03-31T04:30:32.000Z | ycitoj/week1/a.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | null | null | null | ycitoj/week1/a.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#define ll int64_t
#define endl "\n"
using namespace std;
void solve(){
int n;
cin >> n;
vector<int> vec1, vec2;
for (int i = 0; i < n; i++){
string str;
cin >> str;
vec1.push_back(str[str.size() - 1] - '0');
}
for (int i = 0; i < n; i++){
string str;
cin >> str;
vec2.push_back(str[str.size() - 1] - '0');
}
if (vec1[n - 1] == 1 || vec1[n - 1] == 2){
cout << "NO" << endl;
return;
}
for (int i = 0; i < n; i++){
if ((vec1[i] == 1 || vec1[i] == 2) && (vec2[i] == 3 || vec2[i] == 4))
continue;
else if ((vec2[i] == 1 || vec2[i] == 2) && (vec1[i] == 3 || vec1[i] == 4))
continue;
else{
cout << "NO" << endl;
return;
}
}
cout << "YES" << endl;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
//IO
int t;
cin >> t;
while (t--){
solve();
}
return 0;
}
| 19.433962 | 82 | 0.405825 | Zilanlann |
16516fc0b786ded2ab5ebcc4de3c9cd866b2eadf | 1,617 | hpp | C++ | Applications/Topper/plugins/Topper.Workbench/src/RootEntity.hpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | 2 | 2018-02-07T01:19:37.000Z | 2018-02-09T14:27:48.000Z | Applications/Topper/plugins/Topper.Workbench/src/RootEntity.hpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | null | null | null | Applications/Topper/plugins/Topper.Workbench/src/RootEntity.hpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | null | null | null | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Topper Trading Workbench
//
// Copyright (C) 2018 Hat Boy Software, Inc.
//
// @author Matthew Alan Gray - <[email protected]>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#pragma once
#include "Entity.hpp"
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Topper {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
class RootEntity
: public Entity
{
/// @name Types
/// @{
public:
/// @}
/// @name I_Cleanable implementation
/// @{
public:
void setDirty() const override;
/// @}
/// @name Entity implementation
/// @{
public:
const std::string& getType() const override;
const I_Entity& getRoot() const;
const Helmet::Workbench::I_Model& getParentModel() const override;
bool isVisible() override;
/// @}
/// @name RootEntity implementation
/// @{
public:
/// @}
/// @name 'Structors
/// @{
public:
RootEntity(Helmet::Workbench::I_Model& _parent,
const std::string& _name,
const std::string& _entityInfo);
virtual ~RootEntity();
/// @}
/// @name Member Variables
/// @{
private:
static const std::string sm_type;
Helmet::Workbench::I_Model& m_parent;
/// @}
}; // class RootEntity
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Topper
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| 24.876923 | 80 | 0.413729 | hatboysoftware |
1653357bb6b8dac9a58649f9020b6b74bbca2582 | 1,250 | cpp | C++ | test/result_type_test.cpp | ToruNiina/Boost.toml | 0d29d33834d29f476f2d1a0d9e2758660d3e8eb3 | [
"BSL-1.0"
] | 29 | 2018-06-01T14:40:07.000Z | 2022-01-24T12:57:09.000Z | test/result_type_test.cpp | ToruNiina/Boost.toml | 0d29d33834d29f476f2d1a0d9e2758660d3e8eb3 | [
"BSL-1.0"
] | 1 | 2019-12-07T22:33:37.000Z | 2019-12-09T19:49:50.000Z | test/result_type_test.cpp | ToruNiina/Boost.toml | 0d29d33834d29f476f2d1a0d9e2758660d3e8eb3 | [
"BSL-1.0"
] | 1 | 2020-07-13T20:57:48.000Z | 2020-07-13T20:57:48.000Z | #define BOOST_TEST_MODULE "result_type_test"
#include <boost/test/included/unit_test.hpp>
#include <toml/result.hpp>
#include <iostream>
#include <iomanip>
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_construction)
{
{
result<int, double> r(ok(42));
BOOST_CHECK(r);
BOOST_CHECK(r.is_ok());
BOOST_CHECK(!r.is_err());
}
{
result<int, double> r(err(3.14));
BOOST_CHECK(!r);
BOOST_CHECK(!r.is_ok());
BOOST_CHECK(r.is_err());
}
{
result<int, double> r = ok(42);
BOOST_CHECK(r);
BOOST_CHECK(r.is_ok());
BOOST_CHECK(!r.is_err());
}
{
result<int, double> r = err(3.14);
BOOST_CHECK(!r);
BOOST_CHECK(!r.is_ok());
BOOST_CHECK(r.is_err());
}
}
BOOST_AUTO_TEST_CASE(test_unwrap)
{
{
result<int, double> r(ok(42));
BOOST_CHECK_EQUAL(r.unwrap(), 42);
BOOST_CHECK_EQUAL(r.ok_or(54), 42);
BOOST_CHECK_EQUAL(r.err_or(2.71), 2.71);
}
{
result<int, double> r(err(3.14));
BOOST_CHECK_EQUAL(r.unwrap_err(), 3.14);
BOOST_CHECK_EQUAL(r.ok_or(54), 54);
BOOST_CHECK_EQUAL(r.err_or(2.71), 3.14);
}
}
| 23.584906 | 48 | 0.572 | ToruNiina |
1656afae5dae168349052cbd3ecc196efe8ca034 | 15,007 | cpp | C++ | src/tests/add-ons/kernel/file_systems/bfs/r5/Journal.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 4 | 2017-06-17T22:03:56.000Z | 2019-01-25T10:51:55.000Z | src/tests/add-ons/kernel/file_systems/bfs/r5/Journal.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | null | null | null | src/tests/add-ons/kernel/file_systems/bfs/r5/Journal.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 3 | 2018-12-17T13:07:38.000Z | 2021-09-08T13:07:31.000Z | /*
* Copyright 2001-2008, Axel Dörfler, [email protected]
* This file may be used under the terms of the MIT License.
*/
//! Transaction and logging
#include "Journal.h"
#include "Inode.h"
#include <Drivers.h>
#include <util/kernel_cpp.h>
struct run_array {
int32 count;
int32 max_runs;
block_run runs[0];
int32 CountRuns() const { return BFS_ENDIAN_TO_HOST_INT32(count); }
int32 MaxRuns() const { return BFS_ENDIAN_TO_HOST_INT32(max_runs); }
const block_run &RunAt(int32 i) const { return runs[i]; }
static int32 MaxRuns(int32 blockSize)
{ return (blockSize - sizeof(run_array)) / sizeof(block_run); }
};
class LogEntry : public DoublyLinkedListLinkImpl<LogEntry> {
public:
LogEntry(Journal *journal, uint32 logStart);
~LogEntry();
status_t InitCheck() const { return fArray != NULL ? B_OK : B_NO_MEMORY; }
uint32 Start() const { return fStart; }
uint32 Length() const { return fLength; }
Journal *GetJournal() { return fJournal; }
bool InsertBlock(off_t blockNumber);
bool NotifyBlocks(int32 count);
run_array *Array() const { return fArray; }
int32 CountRuns() const { return fArray->CountRuns(); }
int32 MaxRuns() const { return fArray->MaxRuns() - 1; }
// the -1 is an off-by-one error in Be's BFS implementation
const block_run &RunAt(int32 i) const { return fArray->RunAt(i); }
private:
Journal *fJournal;
uint32 fStart;
uint32 fLength;
uint32 fCachedBlocks;
run_array *fArray;
};
// #pragma mark -
LogEntry::LogEntry(Journal *journal, uint32 start)
:
fJournal(journal),
fStart(start),
fLength(1),
fCachedBlocks(0)
{
int32 blockSize = fJournal->GetVolume()->BlockSize();
fArray = (run_array *)malloc(blockSize);
if (fArray == NULL)
return;
memset(fArray, 0, blockSize);
fArray->max_runs = HOST_ENDIAN_TO_BFS_INT32(run_array::MaxRuns(blockSize));
}
LogEntry::~LogEntry()
{
free(fArray);
}
/** Adds the specified block into the array.
*/
bool
LogEntry::InsertBlock(off_t blockNumber)
{
// Be's BFS log replay routine can only deal with block_runs of size 1
// A pity, isn't it? Too sad we have to be compatible.
if (CountRuns() >= MaxRuns())
return false;
block_run run = fJournal->GetVolume()->ToBlockRun(blockNumber);
fArray->runs[CountRuns()] = run;
fArray->count = HOST_ENDIAN_TO_BFS_INT32(CountRuns() + 1);
fLength++;
fCachedBlocks++;
return true;
}
bool
LogEntry::NotifyBlocks(int32 count)
{
fCachedBlocks -= count;
return fCachedBlocks == 0;
}
// #pragma mark -
Journal::Journal(Volume *volume)
:
fVolume(volume),
fLock("bfs journal"),
fOwner(NULL),
fArray(volume->BlockSize()),
fLogSize(volume->Log().Length()),
fMaxTransactionSize(fLogSize / 4 - 5),
fUsed(0),
fTransactionsInEntry(0)
{
if (fMaxTransactionSize > fLogSize / 2)
fMaxTransactionSize = fLogSize / 2 - 5;
}
Journal::~Journal()
{
FlushLogAndBlocks();
}
status_t
Journal::InitCheck()
{
if (fVolume->LogStart() != fVolume->LogEnd()) {
if (fVolume->SuperBlock().flags != SUPER_BLOCK_DISK_DIRTY)
FATAL(("log_start and log_end differ, but disk is marked clean - trying to replay log...\n"));
return ReplayLog();
}
return B_OK;
}
status_t
Journal::_CheckRunArray(const run_array *array)
{
int32 maxRuns = run_array::MaxRuns(fVolume->BlockSize());
if (array->MaxRuns() != maxRuns
|| array->CountRuns() > maxRuns
|| array->CountRuns() <= 0) {
FATAL(("Log entry has broken header!\n"));
return B_ERROR;
}
for (int32 i = 0; i < array->CountRuns(); i++) {
if (fVolume->ValidateBlockRun(array->RunAt(i)) != B_OK)
return B_ERROR;
}
PRINT(("Log entry has %ld entries (%Ld)\n", array->CountRuns()));
return B_OK;
}
/** Replays an entry in the log.
* \a _start points to the entry in the log, and will be bumped to the next
* one if replaying succeeded.
*/
status_t
Journal::_ReplayRunArray(int32 *_start)
{
PRINT(("ReplayRunArray(start = %ld)\n", *_start));
off_t logOffset = fVolume->ToBlock(fVolume->Log());
off_t blockNumber = *_start % fLogSize;
int32 blockSize = fVolume->BlockSize();
int32 count = 1;
CachedBlock cachedArray(fVolume);
const run_array *array = (const run_array *)cachedArray.SetTo(logOffset + blockNumber);
if (array == NULL)
return B_IO_ERROR;
if (_CheckRunArray(array) < B_OK)
return B_BAD_DATA;
blockNumber = (blockNumber + 1) % fLogSize;
CachedBlock cached(fVolume);
for (int32 index = 0; index < array->CountRuns(); index++) {
const block_run &run = array->RunAt(index);
PRINT(("replay block run %lu:%u:%u in log at %Ld!\n", run.AllocationGroup(),
run.Start(), run.Length(), blockNumber));
off_t offset = fVolume->ToOffset(run);
for (int32 i = 0; i < run.Length(); i++) {
const uint8 *data = cached.SetTo(logOffset + blockNumber);
if (data == NULL)
RETURN_ERROR(B_IO_ERROR);
ssize_t written = write_pos(fVolume->Device(),
offset + (i * blockSize), data, blockSize);
if (written != blockSize)
RETURN_ERROR(B_IO_ERROR);
blockNumber = (blockNumber + 1) % fLogSize;
count++;
}
}
*_start += count;
return B_OK;
}
/** Replays all log entries - this will put the disk into a
* consistent and clean state, if it was not correctly unmounted
* before.
* This method is called by Journal::InitCheck() if the log start
* and end pointer don't match.
*/
status_t
Journal::ReplayLog()
{
INFORM(("Replay log, disk was not correctly unmounted...\n"));
int32 start = fVolume->LogStart();
int32 lastStart = -1;
while (true) {
// stop if the log is completely flushed
if (start == fVolume->LogEnd())
break;
if (start == lastStart) {
// strange, flushing the log hasn't changed the log_start pointer
return B_ERROR;
}
lastStart = start;
status_t status = _ReplayRunArray(&start);
if (status < B_OK) {
FATAL(("replaying log entry from %ld failed: %s\n", start, strerror(status)));
return B_ERROR;
}
start = start % fLogSize;
}
PRINT(("replaying worked fine!\n"));
fVolume->SuperBlock().log_start = HOST_ENDIAN_TO_BFS_INT64(fVolume->LogEnd());
fVolume->LogStart() = fVolume->LogEnd();
fVolume->SuperBlock().flags = HOST_ENDIAN_TO_BFS_INT32(SUPER_BLOCK_DISK_CLEAN);
return fVolume->WriteSuperBlock();
}
/** This is a callback function that is called by the cache, whenever
* a block is flushed to disk that was updated as part of a transaction.
* This is necessary to keep track of completed transactions, to be
* able to update the log start pointer.
*/
void
Journal::blockNotify(off_t blockNumber, size_t numBlocks, void *arg)
{
LogEntry *logEntry = (LogEntry *)arg;
if (!logEntry->NotifyBlocks(numBlocks)) {
// nothing to do yet...
return;
}
Journal *journal = logEntry->GetJournal();
disk_super_block &superBlock = journal->fVolume->SuperBlock();
bool update = false;
// Set log_start pointer if possible...
journal->fEntriesLock.Lock();
if (logEntry == journal->fEntries.First()) {
LogEntry *next = journal->fEntries.GetNext(logEntry);
if (next != NULL) {
int32 length = next->Start() - logEntry->Start();
superBlock.log_start = HOST_ENDIAN_TO_BFS_INT64((superBlock.LogStart() + length) % journal->fLogSize);
} else
superBlock.log_start = HOST_ENDIAN_TO_BFS_INT64(journal->fVolume->LogEnd());
update = true;
}
journal->fUsed -= logEntry->Length();
journal->fEntries.Remove(logEntry);
journal->fEntriesLock.Unlock();
free(logEntry);
// update the superblock, and change the disk's state, if necessary
if (update) {
journal->fVolume->LogStart() = superBlock.log_start;
if (superBlock.log_start == superBlock.log_end)
superBlock.flags = SUPER_BLOCK_DISK_CLEAN;
status_t status = journal->fVolume->WriteSuperBlock();
if (status != B_OK)
FATAL(("blockNotify: could not write back superblock: %s\n", strerror(status)));
}
}
status_t
Journal::WriteLogEntry()
{
fTransactionsInEntry = 0;
fHasChangedBlocks = false;
sorted_array *array = fArray.Array();
if (array == NULL || array->count == 0)
return B_OK;
// Make sure there is enough space in the log.
// If that fails for whatever reason, panic!
force_cache_flush(fVolume->Device(), false);
int32 tries = fLogSize / 2 + 1;
while (TransactionSize() > FreeLogBlocks() && tries-- > 0)
force_cache_flush(fVolume->Device(), true);
if (tries <= 0) {
fVolume->Panic();
return B_BAD_DATA;
}
int32 blockShift = fVolume->BlockShift();
off_t logOffset = fVolume->ToBlock(fVolume->Log()) << blockShift;
off_t logStart = fVolume->LogEnd();
off_t logPosition = logStart % fLogSize;
// Create log entries for the transaction
LogEntry *logEntry = NULL, *firstEntry = NULL, *lastAdded = NULL;
for (int32 i = 0; i < array->CountItems(); i++) {
retry:
if (logEntry == NULL) {
logEntry = new LogEntry(this, logStart);
if (logEntry == NULL)
return B_NO_MEMORY;
if (logEntry->InitCheck() != B_OK) {
delete logEntry;
return B_NO_MEMORY;
}
if (firstEntry == NULL)
firstEntry = logEntry;
logStart++;
}
if (!logEntry->InsertBlock(array->ValueAt(i))) {
// log entry is full - start a new one
fEntriesLock.Lock();
fEntries.Add(logEntry);
fEntriesLock.Unlock();
lastAdded = logEntry;
logEntry = NULL;
goto retry;
}
logStart++;
}
if (firstEntry == NULL)
return B_OK;
if (logEntry != lastAdded) {
fEntriesLock.Lock();
fEntries.Add(logEntry);
fEntriesLock.Unlock();
}
// Write log entries to disk
CachedBlock cached(fVolume);
fEntriesLock.Lock();
for (logEntry = firstEntry; logEntry != NULL; logEntry = fEntries.GetNext(logEntry)) {
// first write the log entry array
write_pos(fVolume->Device(), logOffset + (logPosition << blockShift),
logEntry->Array(), fVolume->BlockSize());
logPosition = (logPosition + 1) % fLogSize;
for (int32 i = 0; i < logEntry->CountRuns(); i++) {
uint8 *block = cached.SetTo(logEntry->RunAt(i));
if (block == NULL)
return B_IO_ERROR;
// write blocks
write_pos(fVolume->Device(), logOffset + (logPosition << blockShift),
block, fVolume->BlockSize());
logPosition = (logPosition + 1) % fLogSize;
}
}
fEntriesLock.Unlock();
fUsed += array->CountItems();
// Update the log end pointer in the superblock
fVolume->SuperBlock().flags = HOST_ENDIAN_TO_BFS_INT32(SUPER_BLOCK_DISK_DIRTY);
fVolume->SuperBlock().log_end = HOST_ENDIAN_TO_BFS_INT64(logPosition);
fVolume->LogEnd() = logPosition;
status_t status = fVolume->WriteSuperBlock();
// We need to flush the drives own cache here to ensure
// disk consistency.
// If that call fails, we can't do anything about it anyway
ioctl(fVolume->Device(), B_FLUSH_DRIVE_CACHE);
fEntriesLock.Lock();
logStart = firstEntry->Start();
for (logEntry = firstEntry; logEntry != NULL; logEntry = fEntries.GetNext(logEntry)) {
// Note: this only works this way as we only have block_runs of length 1
// We're reusing the fArray array, as we don't need it anymore, and
// it's guaranteed to be large enough for us, too
for (int32 i = 0; i < logEntry->CountRuns(); i++) {
array->values[i] = fVolume->ToBlock(logEntry->RunAt(i));
}
set_blocks_info(fVolume->Device(), &array->values[0],
logEntry->CountRuns(), blockNotify, logEntry);
}
fEntriesLock.Unlock();
fArray.MakeEmpty();
// If the log goes to the next round (the log is written as a
// circular buffer), all blocks will be flushed out which is
// possible because we don't have any locked blocks at this
// point.
if (logPosition < logStart)
fVolume->FlushDevice();
return status;
}
status_t
Journal::FlushLogAndBlocks()
{
status_t status = Lock((Transaction *)this);
if (status != B_OK)
return status;
// write the current log entry to disk
if (TransactionSize() != 0) {
status = WriteLogEntry();
if (status < B_OK)
FATAL(("writing current log entry failed: %s\n", strerror(status)));
}
status = fVolume->FlushDevice();
Unlock((Transaction *)this, true);
return status;
}
status_t
Journal::Lock(Transaction *owner)
{
if (owner == fOwner)
return B_OK;
status_t status = fLock.Lock();
if (status == B_OK)
fOwner = owner;
// if the last transaction is older than 2 secs, start a new one
if (fTransactionsInEntry != 0 && system_time() - fTimestamp > 2000000L)
WriteLogEntry();
return B_OK;
}
void
Journal::Unlock(Transaction *owner, bool success)
{
if (owner != fOwner)
return;
TransactionDone(success);
fTimestamp = system_time();
fOwner = NULL;
fLock.Unlock();
}
/** If there is a current transaction that the current thread has
* started, this function will give you access to it.
*/
Transaction *
Journal::CurrentTransaction()
{
if (fLock.LockWithTimeout(0) != B_OK)
return NULL;
Transaction *owner = fOwner;
fLock.Unlock();
return owner;
}
status_t
Journal::TransactionDone(bool success)
{
if (!success && fTransactionsInEntry == 0) {
// we can safely abort the transaction
sorted_array *array = fArray.Array();
if (array != NULL) {
// release the lock for all blocks in the array (we don't need
// to be notified when they are actually written to disk)
for (int32 i = 0; i < array->CountItems(); i++)
release_block(fVolume->Device(), array->ValueAt(i));
}
return B_OK;
}
// Up to a maximum size, we will just batch several
// transactions together to improve speed
if (TransactionSize() < fMaxTransactionSize) {
fTransactionsInEntry++;
fHasChangedBlocks = false;
return B_OK;
}
return WriteLogEntry();
}
status_t
Journal::LogBlocks(off_t blockNumber, const uint8 *buffer, size_t numBlocks)
{
// ToDo: that's for now - we should change the log file size here
if (TransactionSize() + numBlocks + 1 > fLogSize)
return B_DEVICE_FULL;
fHasChangedBlocks = true;
int32 blockSize = fVolume->BlockSize();
for (;numBlocks-- > 0; blockNumber++, buffer += blockSize) {
if (fArray.Find(blockNumber) >= 0) {
// The block is already in the log, so just update its data
// Note, this is only necessary if this method is called with a buffer
// different from the cached block buffer - which is unlikely but
// we'll make sure this way (costs one cache lookup, though).
status_t status = cached_write(fVolume->Device(), blockNumber, buffer, 1, blockSize);
if (status < B_OK)
return status;
continue;
}
// Insert the block into the transaction's array, and write the changes
// back into the locked cache buffer
fArray.Insert(blockNumber);
status_t status = cached_write_locked(fVolume->Device(), blockNumber, buffer, 1, blockSize);
if (status < B_OK)
return status;
}
// If necessary, flush the log, so that we have enough space for this transaction
if (TransactionSize() > FreeLogBlocks())
force_cache_flush(fVolume->Device(), true);
return B_OK;
}
// #pragma mark -
status_t
Transaction::Start(Volume *volume, off_t refBlock)
{
// has it already been started?
if (fJournal != NULL)
return B_OK;
fJournal = volume->GetJournal(refBlock);
if (fJournal != NULL && fJournal->Lock(this) == B_OK)
return B_OK;
fJournal = NULL;
return B_ERROR;
}
| 24.12701 | 105 | 0.690078 | axeld |
165b49d4c77dc5232759996289928184e64b5dd0 | 6,553 | cpp | C++ | src/TransportUtilities.cpp | tamara-schmitz/audacity | df42c72ecfa663cab028f7932c4063c79aee6b9d | [
"CC-BY-3.0"
] | 2 | 2022-01-17T08:27:47.000Z | 2022-02-08T15:54:42.000Z | src/TransportUtilities.cpp | tamara-schmitz/audacity | df42c72ecfa663cab028f7932c4063c79aee6b9d | [
"CC-BY-3.0"
] | 70 | 2021-07-18T18:11:53.000Z | 2021-12-05T20:22:15.000Z | src/TransportUtilities.cpp | tamara-schmitz/audacity | df42c72ecfa663cab028f7932c4063c79aee6b9d | [
"CC-BY-3.0"
] | 2 | 2021-09-08T18:12:22.000Z | 2021-12-24T16:39:47.000Z | /**********************************************************************
Audacity: A Digital Audio Editor
@file TransportUtilities.cpp
@brief implements some UI related to starting and stopping play and record
Paul Licameli split from TransportMenus.cpp
**********************************************************************/
#include "TransportUtilities.h"
#include <thread>
#include "AudioIO.h"
#include "commands/CommandContext.h"
#include "Project.h"
#include "ProjectAudioIO.h"
#include "ProjectAudioManager.h"
#include "ViewInfo.h"
#include "toolbars/ControlToolBar.h"
#include "widgets/ProgressDialog.h"
void TransportUtilities::PlayCurrentRegionAndWait(
const CommandContext &context,
bool newDefault,
bool cutpreview)
{
auto &project = context.project;
auto &projectAudioManager = ProjectAudioManager::Get(project);
const auto &playRegion = ViewInfo::Get(project).playRegion;
double t0 = playRegion.GetStart();
double t1 = playRegion.GetEnd();
projectAudioManager.PlayCurrentRegion(newDefault, cutpreview);
if (project.mBatchMode > 0 && t0 != t1 && !newDefault) {
wxYieldIfNeeded();
/* i18n-hint: This title appears on a dialog that indicates the progress
in doing something.*/
ProgressDialog progress(XO("Progress"), XO("Playing"), pdlgHideCancelButton);
auto gAudioIO = AudioIO::Get();
while (projectAudioManager.Playing()) {
ProgressResult result = progress.Update(gAudioIO->GetStreamTime() - t0, t1 - t0);
if (result != ProgressResult::Success) {
projectAudioManager.Stop();
if (result != ProgressResult::Stopped) {
context.Error(wxT("Playing interrupted"));
}
break;
}
using namespace std::chrono;
std::this_thread::sleep_for(100ms);
wxYieldIfNeeded();
}
projectAudioManager.Stop();
wxYieldIfNeeded();
}
}
void TransportUtilities::PlayPlayRegionAndWait(
const CommandContext &context,
const SelectedRegion &selectedRegion,
const AudioIOStartStreamOptions &options,
PlayMode mode)
{
auto &project = context.project;
auto &projectAudioManager = ProjectAudioManager::Get(project);
double t0 = selectedRegion.t0();
double t1 = selectedRegion.t1();
projectAudioManager.PlayPlayRegion(selectedRegion, options, mode);
if (project.mBatchMode > 0) {
wxYieldIfNeeded();
/* i18n-hint: This title appears on a dialog that indicates the progress
in doing something.*/
ProgressDialog progress(XO("Progress"), XO("Playing"), pdlgHideCancelButton);
auto gAudioIO = AudioIO::Get();
while (projectAudioManager.Playing()) {
ProgressResult result = progress.Update(gAudioIO->GetStreamTime() - t0, t1 - t0);
if (result != ProgressResult::Success) {
projectAudioManager.Stop();
if (result != ProgressResult::Stopped) {
context.Error(wxT("Playing interrupted"));
}
break;
}
using namespace std::chrono;
std::this_thread::sleep_for(100ms);
wxYieldIfNeeded();
}
projectAudioManager.Stop();
wxYieldIfNeeded();
}
}
void TransportUtilities::RecordAndWait(
const CommandContext &context, bool altAppearance)
{
auto &project = context.project;
auto &projectAudioManager = ProjectAudioManager::Get(project);
const auto &selectedRegion = ViewInfo::Get(project).selectedRegion;
double t0 = selectedRegion.t0();
double t1 = selectedRegion.t1();
projectAudioManager.OnRecord(altAppearance);
if (project.mBatchMode > 0 && t1 != t0) {
wxYieldIfNeeded();
/* i18n-hint: This title appears on a dialog that indicates the progress
in doing something.*/
ProgressDialog progress(XO("Progress"), XO("Recording"), pdlgHideCancelButton);
auto gAudioIO = AudioIO::Get();
while (projectAudioManager.Recording()) {
ProgressResult result = progress.Update(gAudioIO->GetStreamTime() - t0, t1 - t0);
if (result != ProgressResult::Success) {
projectAudioManager.Stop();
if (result != ProgressResult::Stopped) {
context.Error(wxT("Recording interrupted"));
}
break;
}
using namespace std::chrono;
std::this_thread::sleep_for(100ms);
wxYieldIfNeeded();
}
projectAudioManager.Stop();
wxYieldIfNeeded();
}
}
// Returns true if this project was stopped, otherwise false.
// (it may though have stopped another project playing)
bool TransportUtilities::DoStopPlaying(const CommandContext &context)
{
auto &project = context.project;
auto &projectAudioManager = ProjectAudioManager::Get(project);
auto gAudioIO = AudioIOBase::Get();
auto &toolbar = ControlToolBar::Get(project);
auto token = ProjectAudioIO::Get(project).GetAudioIOToken();
//If this project is playing, stop playing, make sure everything is unpaused.
if (gAudioIO->IsStreamActive(token)) {
toolbar.SetStop(); //Pushes stop down
projectAudioManager.Stop();
// Playing project was stopped. All done.
return true;
}
// This project isn't playing.
// If some other project is playing, stop playing it
if (gAudioIO->IsStreamActive()) {
//find out which project we need;
auto start = AllProjects{}.begin(), finish = AllProjects{}.end(),
iter = std::find_if(start, finish,
[&](const AllProjects::value_type &ptr) {
return gAudioIO->IsStreamActive(
ProjectAudioIO::Get(*ptr).GetAudioIOToken()); });
//stop playing the other project
if (iter != finish) {
auto otherProject = *iter;
auto &otherToolbar = ControlToolBar::Get(*otherProject);
auto &otherProjectAudioManager =
ProjectAudioManager::Get(*otherProject);
otherToolbar.SetStop(); //Pushes stop down
otherProjectAudioManager.Stop();
}
}
return false;
}
void TransportUtilities::DoStartPlaying(
const CommandContext &context, bool newDefault)
{
auto &project = context.project;
auto &projectAudioManager = ProjectAudioManager::Get(project);
auto gAudioIO = AudioIOBase::Get();
//play the front project
if (!gAudioIO->IsBusy()) {
//Otherwise, start playing (assuming audio I/O isn't busy)
// Will automatically set mLastPlayMode
PlayCurrentRegionAndWait(context, newDefault);
}
}
| 32.122549 | 90 | 0.647184 | tamara-schmitz |
165b62def89fd734df69b9cf20d42487fe28b944 | 1,367 | hpp | C++ | libraries/CMakeServerConnector/include/Messages/CodeModelResponse.hpp | Megaxela/HGEngineReloadedEditor | be79b6089985da1bf811be8a6d06ce25f71236b1 | [
"MIT"
] | null | null | null | libraries/CMakeServerConnector/include/Messages/CodeModelResponse.hpp | Megaxela/HGEngineReloadedEditor | be79b6089985da1bf811be8a6d06ce25f71236b1 | [
"MIT"
] | null | null | null | libraries/CMakeServerConnector/include/Messages/CodeModelResponse.hpp | Megaxela/HGEngineReloadedEditor | be79b6089985da1bf811be8a6d06ce25f71236b1 | [
"MIT"
] | 1 | 2020-03-12T04:39:14.000Z | 2020-03-12T04:39:14.000Z | #pragma once
#include <Messages/BasicMessage.hpp>
struct CodeModelResponse : public BasicMessage
{
struct IncludePath
{
std::string path;
};
struct FileGroup
{
std::string compileFlags;
std::vector<std::string> defines;
std::vector<IncludePath> includePaths;
bool isGenerated;
std::string language;
std::vector<std::string> sources;
};
struct Target
{
std::vector<std::string> artifacts;
std::string buildDirectory;
std::vector<FileGroup> fileGroups;
std::string fullName;
std::string linkerLanguage;
std::string name;
std::string sourceDirectory;
std::string type;
};
struct Project
{
std::string buildDirectory;
std::string name;
std::string sourceDirectory;
std::vector<Target> targets;
};
struct Configuration
{
std::string name;
std::vector<Project> projects;
};
std::vector<Configuration> configurations;
static void deserialize(const nlohmann::json& json, BasicMessage& msg);
};
namespace
{
Messages::Registrator<ComputeResponse> CodeModelResponseRegistrator(
"reply",
"codemodel",
Messages::Type::CodeModelResponse,
nullptr,
&CodeModelResponse::deserialize
);
}
| 20.402985 | 75 | 0.610095 | Megaxela |
1660a0319b91c38cbbe2376308e98f031ed515e7 | 1,789 | hpp | C++ | include/mummer/sparseSA_imp.hpp | bredelings/mummer | e084d9b32613ebb1841c60e47a11ff6b1928450a | [
"Artistic-2.0"
] | 284 | 2017-06-12T18:44:09.000Z | 2022-03-29T13:22:00.000Z | ext/mummer/sparseSA_imp.hpp | AT-CG/ChainX | 2b4c902a8981eceda17e72dc7409f744ad3a0bc3 | [
"Apache-2.0"
] | 167 | 2017-06-09T12:33:21.000Z | 2022-03-29T15:45:19.000Z | ext/mummer/sparseSA_imp.hpp | AT-CG/ChainX | 2b4c902a8981eceda17e72dc7409f744ad3a0bc3 | [
"Apache-2.0"
] | 114 | 2017-07-03T07:39:33.000Z | 2022-02-23T06:27:26.000Z | #ifndef __SPARSESA_IMP_H__
#define __SPARSESA_IMP_H__
#undef _OPENMP
#ifdef _OPENMP
#include <omp.h>
#endif
// Implementation of some sparseSA functions
namespace mummer {
namespace sparseSA_imp {
#ifndef _OPENMP
template<typename Map, typename Seq, typename Vec>
void computeLCP(Map& LCP, const Seq& S, const Vec& SA, const Vec& ISA, const long N, const long K) {
long h = 0;
for(long i = 0; i < N / K; ++i) {
const long m = ISA[i];
if(m > 0) {
const long bj = SA[m-1];
const long bi = i * K;
while(bi + h < N && bj + h < N && S[bi + h] == S[bj + h]) ++h;
LCP.set(m, h); //LCP[m] = h;
} else {
LCP.set(m, 0); // LCP[m]=0;
}
h = std::max(0L, h - K);
}
LCP.init();
}
#else // _OPENMP
template<typename Map, typename Seq, typename Vec>
void computeLCP(Map& LCP, const Seq& S, const Vec& SA, const Vec& ISA, const long N, const long K) {
// const long chunk = std::min((long)10000000, (long)(N / omp_get_num_threads()));
std::vector<typename Map::item_vector> Ms;
#pragma omp parallel
{
long h = 0;
typename Map::item_vector tM; // M array for this thread
#pragma omp for schedule(static)
for(long i = 0; i < N / K; ++i) {
const long m = ISA[i];
if(m > 0) {
const long bj = SA[m-1];
const long bi = i * K;
while(bi + h < N && bj + h < N && S[bi + h] == S[bj + h]) ++h;
LCP.set(m, h, tM); //LCP[m] = h;
} else {
LCP.set(m, 0); // LCP[m]=0;
}
h = std::max(0L, h - K);
}
std::sort(tM.begin(), tM.end(), Map::first_comp);
#pragma omp critical
Ms.push_back(std::move(tM));
}
LCP.init_merge(Ms);
}
#endif // _OPENMP
} // namespace sparseSA_imp
} // namespace mummer
#endif /* __SPARSESA_IMP_H__ */
| 24.847222 | 100 | 0.560089 | bredelings |
166e3174a74b9263cd87f863a89338c5b1432abc | 1,750 | cpp | C++ | test/fixture/fixture_string.cpp | engineer-legion/json | 7ef33477720e7c801e5636fae6f34d7fbf55bcf0 | [
"BSL-1.0"
] | null | null | null | test/fixture/fixture_string.cpp | engineer-legion/json | 7ef33477720e7c801e5636fae6f34d7fbf55bcf0 | [
"BSL-1.0"
] | null | null | null | test/fixture/fixture_string.cpp | engineer-legion/json | 7ef33477720e7c801e5636fae6f34d7fbf55bcf0 | [
"BSL-1.0"
] | null | null | null | /*
* fixture_string.cpp
*
* Created on: 01.02.2015
* Author: mike_gresens
*/
#include "fixture_string.hpp"
namespace json {
namespace fixture {
const fixture_base::entry_t
fixture_string::_empty =
{
string_t(),
"\"\""
};
const fixture_base::entry_t
fixture_string::_simple =
{
string_t("foo"),
"\"foo\""
};
const fixture_base::entry_t
fixture_string::_space =
{
string_t(" foo bar "),
"\" foo bar \""
};
const fixture_base::entry_t
fixture_string::_quote =
{
string_t("\"foo\"bar\""),
"\"\\\"foo\\\"bar\\\"\""
};
const fixture_base::entry_t
fixture_string::_backslash =
{
string_t("\\foo\\bar\\"),
"\"\\\\foo\\\\bar\\\\\""
};
const fixture_base::entry_t
fixture_string::_slash =
{
string_t("/foo/bar/"),
"\"\\/foo\\/bar\\/\""
};
const fixture_base::entry_t
fixture_string::_backspace =
{
string_t("\bfoo\bbar\b"),
"\"\\bfoo\\bbar\\b\""
};
const fixture_base::entry_t
fixture_string::_formfeed =
{
string_t("\ffoo\fbar\f"),
"\"\\ffoo\\fbar\\f\""
};
const fixture_base::entry_t
fixture_string::_newline =
{
string_t("\nfoo\nbar\n"),
"\"\\nfoo\\nbar\\n\""
};
const fixture_base::entry_t
fixture_string::_return =
{
string_t("\rfoo\rbar\r"),
"\"\\rfoo\\rbar\\r\""
};
const fixture_base::entry_t
fixture_string::_tab =
{
string_t("\tfoo\tbar\t"),
"\"\\tfoo\\tbar\\t\""
};
const fixture_base::entry_t
fixture_string::_unicode =
{
string_t("\u1234foo\u5555bar\u9876"),
"\"\\u1234foo\\u5555bar\\u9876\""
};
const string_t
fixture_string::_invalid1 =
{
"\"\\ufoo\""
};
const string_t
fixture_string::_invalid2 =
{
"\"\\u12\""
};
const string_t
fixture_string::_invalid3 =
{
"\"\n\""
};
const string_t
fixture_string::_invalid4 =
{
"\\"
};
const string_t
fixture_string::_invalid5 =
{
"\"foo"
};
}
}
| 13.565891 | 38 | 0.640571 | engineer-legion |
166e730bf761817bcbfa36419c4cd8ab3d433dd7 | 1,954 | cpp | C++ | graph-source-code/131-D/897677.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/131-D/897677.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/131-D/897677.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <bitset>
#include <algorithm>
#include <map>
#include <fstream>
#define pb push_back
#define MP make_pair
#define FOR(a,b) for((a)=0 ; (a)<(b) ; (a)++)
typedef long long ll;
using namespace std;
vector<int> table[3001];
vector<int> V;
int N;
bool used[3001];
bool cycle[3001];
int dis[3001];
int cur[3001];
void dfs(int from , int s, int depth){
int i,j;
for(i=0;i<table[s].size();i++){
int to = table[s][i];
if(to == from)continue;
if(used[to]){
for(j=0;j<depth;j++){
if(cur[j]==to){
for(;j<depth;j++)
cycle[cur[j]]=1;
break;
}
}
}else{
used[to] = 1;
cur[depth] = to;
dfs(s,to,depth+1);
}
}
}
void bfs(){
int i,j,k;
queue< pair<int,int> > Q;
for(i=1;i<=N;i++){
if(cycle[i])Q.push(MP(i,0));
}
while(!Q.empty()){
int s= Q.front().first;
int d = Q.front().second;
if(dis[s]==0)d = 0;
for(i=0;i<table[s].size();i++){
int to =table[s][i];
if(dis[to] > d + 1){
dis[to] = d+1;
Q.push(MP(to,d+1));
}
}
Q.pop();
}
return ;
}
int main(){
int i,j,k,M,P,l,m,n;
cin >> N;
int t1,t2;
for(i=0;i<N;i++){
cin >> t1>>t2;
table[t1].pb(t2);
table[t2].pb(t1);
}
cur[0] = 1;
used[1] = 1;
dfs(0,1,1);
for(i=1;i<=N;i++)
if(cycle[i]){
V.pb(i);
dis[i] = 0;
}else dis[i]=100000;
bfs();
for(i=1;i<N;i++){
cout<<dis[i]<<" ";
}
cout<<dis[N]<<endl;
}
| 20.568421 | 46 | 0.413511 | AmrARaouf |
166ec313684fcb5bcc2a8c021ddbaac8b1913b8f | 1,227 | hpp | C++ | source/quantum-script-extension-shell-version.hpp | g-stefan/quantum-script-extension-shell | 27e7885c6b74e518697f40536fa736c637d51981 | [
"MIT",
"Unlicense"
] | null | null | null | source/quantum-script-extension-shell-version.hpp | g-stefan/quantum-script-extension-shell | 27e7885c6b74e518697f40536fa736c637d51981 | [
"MIT",
"Unlicense"
] | null | null | null | source/quantum-script-extension-shell-version.hpp | g-stefan/quantum-script-extension-shell | 27e7885c6b74e518697f40536fa736c637d51981 | [
"MIT",
"Unlicense"
] | null | null | null | //
// Quantum Script Extension Shell
//
// Copyright (c) 2020-2021 Grigore Stefan <[email protected]>
// Created by Grigore Stefan <[email protected]>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#ifndef QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_HPP
#define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_HPP
#define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_ABCD 2,1,0,19
#define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_STR "2.1.0"
#define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_STR_BUILD "19"
#define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_STR_DATETIME "2021-08-09 17:38:06"
#ifndef XYO_RC
#ifndef QUANTUM_SCRIPT_EXTENSION_SHELL__EXPORT_HPP
#include "quantum-script-extension-shell--export.hpp"
#endif
namespace Quantum {
namespace Script {
namespace Extension {
namespace Shell {
namespace Version {
QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *version();
QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *build();
QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *versionWithBuild();
QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *datetime();
};
};
};
};
};
#endif
#endif
| 29.214286 | 89 | 0.731866 | g-stefan |
1673532033720107537b9e6c1e585a7bf75f89e5 | 2,046 | cpp | C++ | chp4_exercises.cpp | toddbrentlinger/Beginning-Cpp-Through-Game-Programming-Third-Edition | 16a53f70869920cec7230f4d2f3e2a0d1dcd43f4 | [
"MIT"
] | 10 | 2018-03-22T19:30:55.000Z | 2021-12-09T14:02:07.000Z | chp4_exercises.cpp | spellberry/Beginning-Cpp-Through-Game-Programming-Third-Edition | 16a53f70869920cec7230f4d2f3e2a0d1dcd43f4 | [
"MIT"
] | null | null | null | chp4_exercises.cpp | spellberry/Beginning-Cpp-Through-Game-Programming-Third-Edition | 16a53f70869920cec7230f4d2f3e2a0d1dcd43f4 | [
"MIT"
] | 8 | 2018-03-22T19:34:31.000Z | 2021-12-09T14:02:13.000Z | // Chapter 4 Exercises
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;
int main()
{
cout << "\tChapter43 Exercises\n\n";
// Question 1
vector<string> gameList;
vector<string>::iterator myIterator;
vector<string>::const_iterator iter;
cout << "Question 1\n";
cout << "Favorite Games List:\n\n";
cout << "Action Options:\n";
cout << "'List' - list all game titles\n";
cout << "'Add' - add a game title\n";
cout << "'Remove' - remove a game title\n";
cout << "'Quit' - quit the program\n";
string action;
string gameTitle;
// main loop
while (action != "QUIT")
{
cout << "\nAction: ";
cin >> action;
if (action == "LIST")
{
cout << "\nFavorite Game:\n";
for (iter = gameList.begin(); iter != gameList.end(); ++iter)
{
cout << *iter << endl;
}
}
else if (action == "ADD")
{
cout << "\nAdd Game: ";
cin >> gameTitle;
gameList.push_back(gameTitle);
cout << "\nFavorite Game:\n";
for (iter = gameList.begin(); iter < gameList.end(); ++iter)
{
cout << *iter << endl;
}
}
else if (action == "REMOVE")
{
cout << "\nRemove Game: ";
cin >> gameTitle;
myIterator = find(gameList.begin(), gameList.end(), gameTitle);
if (myIterator != gameList.end())
{
gameList.erase(myIterator);
cout << "\nFavorite Game:\n";
for (iter = gameList.begin(); iter < gameList.end(); ++iter)
{
cout << *iter << endl;
}
}
else
{
cout << "\nGame title not found. Try Again.";
}
}
}
// Question 2
cout << "Question 2\n\n";
vector<int> scores(5,0);
vector<int>::iterator myIter2;
vector<int>::const_iterator iter2;
// increment each score
for (myIter2 = scores.begin(); myIter2 != scores.end(); ++myIter2)
{
(*myIter2)++;
}
cout << "Scores:\n";
for (iter2 = scores.begin(); iter2 != scores.end(); ++iter2)
{
cout << *iter2 << endl;
}
return 0;
}
| 21.092784 | 68 | 0.554252 | toddbrentlinger |
16789454c84225a65d9c0b85cb45774fd255768e | 653 | cpp | C++ | cpp/ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp | mvshmakov/junk | d67b31d918772018f78c3b1ff43d2bfd72bc57c9 | [
"WTFPL"
] | null | null | null | cpp/ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp | mvshmakov/junk | d67b31d918772018f78c3b1ff43d2bfd72bc57c9 | [
"WTFPL"
] | 1 | 2022-03-02T09:56:38.000Z | 2022-03-02T09:56:38.000Z | cpp/ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp | mvshmakov/junk | d67b31d918772018f78c3b1ff43d2bfd72bc57c9 | [
"WTFPL"
] | null | null | null | // Массивы.cpp: главный файл проекта.
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
float a[10];
float proiz = 1.0;
int i, n, k = 0;
cout << "Vvedite elementi massiva cherez enter:" << endl;
for (i = 0; i < 10; i++)
{
cin >> a[i];
}
for (i = 0; i < 10; i++)
{
cout << a[i] << " ";
}
cout << "\nVvedite chislo N:" << endl;
cin >> n;
for (i = 0; i < 10; i++)
{
if (a[i] > n) { k++; proiz *= a[i]; };
}
cout << "Proizvedenie elementov massiva = " << proiz << endl;
cout << "Kol-vo elementov bolshih chisla = " << k << endl;
getch();
return 0;
}
| 19.205882 | 63 | 0.503828 | mvshmakov |
167c048ba3a7c1d7f245d8f97f304003c2dbad88 | 3,919 | hpp | C++ | include/zipper_iterator.hpp | aurelien-boch/cpp-ecs | cc3ac80a18909dfcc476d7cfe1f3c7cd67b19e57 | [
"MIT"
] | 5 | 2021-11-22T18:49:49.000Z | 2022-01-14T14:49:09.000Z | include/zipper_iterator.hpp | aurelien-boch/cpp-ecs | cc3ac80a18909dfcc476d7cfe1f3c7cd67b19e57 | [
"MIT"
] | null | null | null | include/zipper_iterator.hpp | aurelien-boch/cpp-ecs | cc3ac80a18909dfcc476d7cfe1f3c7cd67b19e57 | [
"MIT"
] | 1 | 2021-12-05T15:33:05.000Z | 2021-12-05T15:33:05.000Z | #ifndef ZIPPER_ITERATOR_HPP
#define ZIPPER_ITERATOR_HPP
#include <tuple>
#include <optional>
namespace ecs::containers
{
template<class ...T>
class zipper;
}
namespace ecs::iterators
{
/**
* @brief This class defines an iterator instantiated by the zipper class. it's intended to be used in a range based
* loop or a simple for.
* @tparam Containers This variadic template refers to the types to bind the iterator.
*/
template<class ...Containers>
class zipper_iterator
{
template<class Container>
using iterator_t = typename Container::iterator;
template<class Container>
using it_reference_t = decltype(std::declval<typename iterator_t<Container>::reference>().value());
public:
using value_type = std::tuple<it_reference_t<Containers>...>;
using reference = value_type &;
using pointer = void;
using difference_type = std::size_t;
using iterator_category = std::input_iterator_tag;
using iterator_tuple = std::tuple<iterator_t<Containers>...>;
friend ecs::containers::zipper<Containers ...>;
zipper_iterator(zipper_iterator const &z) noexcept :
_max(z._max),
_idx(z._idx),
_current(z._current)
{}
const zipper_iterator &operator++() //TODO fix this magic
{
if (_max == 0)
return (*this);
if (_idx == _max - 1) {
_incrAll(_seq);
_idx++;
}
else if (_idx < _max - 1)
do {
_incrAll(_seq);
_idx += 1;
} while (!_allSet(_seq) && _idx < _max - 1);
if (_idx == _max - 1 && !_allSet(_seq)) {
_incrAll(_seq);
_idx++;
}
return (*this);
}
zipper_iterator operator++(int)
{
zipper_iterator<Containers...> old = *this;
operator++();
return (old);
}
value_type operator*()
{
return (_toValue(_seq));
}
value_type operator->()
{
return (_toValue(_seq));
}
friend inline bool operator==(zipper_iterator const &lhs, zipper_iterator const &rhs)
{
return ((lhs._max - lhs._idx) == (rhs._max - rhs._idx));
}
friend inline bool operator!=(zipper_iterator const &lhs, zipper_iterator const &rhs)
{
return ((lhs._max - lhs._idx) != (rhs._max - rhs._idx));
}
private:
iterator_tuple _current;
std::size_t _max;
std::size_t _idx{};
static constexpr std::index_sequence_for<Containers ...> _seq{};
template<size_t ... Is>
void _incrAll(std::index_sequence<Is ...>)
{
((++std::get<Is>(_current)), ...);
}
template<size_t ... Is>
[[nodiscard]] bool _allSet(std::index_sequence<Is ...>)
{
return (((*std::get<Is>(_current)) != std::nullopt) && ...);
}
template<size_t ... Is>
[[nodiscard]] value_type _toValue(std::index_sequence<Is ...>)
{
return std::tie(std::get<Is>(_current)->value()...);
}
zipper_iterator(iterator_tuple const &it_tuple, std::size_t max) :
_current(it_tuple),
_max(max)
{
if (_max > 0 && !_allSet(_seq))
this->operator++();
}
};
}
#endif //ZIPPER_ITERATOR_HPP
| 29.916031 | 120 | 0.48048 | aurelien-boch |
1683c2842b9b795900eeae61538c906b57befea5 | 8,556 | hh | C++ | subprojects/libostd/ostd/vecmath.hh | Croydon/libcubescript | a6d80a33f40f2c959c8ac881d8f8056d3460b1f3 | [
"Zlib"
] | 1 | 2022-02-02T19:24:35.000Z | 2022-02-02T19:24:35.000Z | subprojects/libostd/ostd/vecmath.hh | Croydon/libcubescript | a6d80a33f40f2c959c8ac881d8f8056d3460b1f3 | [
"Zlib"
] | null | null | null | subprojects/libostd/ostd/vecmath.hh | Croydon/libcubescript | a6d80a33f40f2c959c8ac881d8f8056d3460b1f3 | [
"Zlib"
] | 1 | 2022-02-02T22:39:12.000Z | 2022-02-02T22:39:12.000Z | /* Vector math for libostd.
*
* This file is part of libostd. See COPYING.md for futher information.
*/
#ifndef OSTD_VECMATH_HH
#define OSTD_VECMATH_HH
#include <cstddef>
namespace ostd {
template<typename T>
struct vec2 {
union {
struct { T x, y; };
T value[2];
};
vec2(): x(0), y(0) {}
vec2(vec2 const &v): x(v.x), y(v.y) {}
vec2(T v): x(v), y(v) {}
vec2(T x, T y): x(x), y(y) {}
T &operator[](std::size_t idx) { return value[idx]; }
T operator[](std::size_t idx) const { return value[idx]; }
vec2 &add(T v) {
x += v; y += v;
return *this;
}
vec2 &add(vec2 const &o) {
x += o.x; y += o.y;
return *this;
}
vec2 &sub(T v) {
x -= v; y -= v;
return *this;
}
vec2 &sub(vec2 const &o) {
x -= o.x; y -= o.y;
return *this;
}
vec2 &mul(T v) {
x *= v; y *= v;
return *this;
}
vec2 &mul(vec2 const &o) {
x *= o.x; y *= o.y;
return *this;
}
vec2 &div(T v) {
x /= v; y /= v;
return *this;
}
vec2 &div(vec2 const &o) {
x /= o.x; y /= o.y;
return *this;
}
vec2 &neg() {
x = -x; y = -y;
return *this;
}
bool is_zero() const {
return (x == 0) && (y == 0);
}
T dot(vec2<T> const &o) const {
return (x * o.x) + (y * o.y);
}
};
template<typename T>
inline bool operator==(vec2<T> const &a, vec2<T> const &b) {
return (a.x == b.x) && (a.y == b.y);
}
template<typename T>
inline bool operator!=(vec2<T> const &a, vec2<T> const &b) {
return (a.x != b.x) || (a.y != b.y);
}
template<typename T>
inline vec2<T> operator+(vec2<T> const &a, vec2<T> const &b) {
return vec2<T>(a).add(b);
}
template<typename T>
inline vec2<T> operator+(vec2<T> const &a, T b) {
return vec2<T>(a).add(b);
}
template<typename T>
inline vec2<T> operator-(vec2<T> const &a, vec2<T> const &b) {
return vec2<T>(a).sub(b);
}
template<typename T>
inline vec2<T> operator-(vec2<T> const &a, T b) {
return vec2<T>(a).sub(b);
}
template<typename T>
inline vec2<T> operator*(vec2<T> const &a, vec2<T> const &b) {
return vec2<T>(a).mul(b);
}
template<typename T>
inline vec2<T> operator*(vec2<T> const &a, T b) {
return vec2<T>(a).mul(b);
}
template<typename T>
inline vec2<T> operator/(vec2<T> const &a, vec2<T> const &b) {
return vec2<T>(a).div(b);
}
template<typename T>
inline vec2<T> operator/(vec2<T> const &a, T b) {
return vec2<T>(a).div(b);
}
template<typename T>
inline vec2<T> operator-(vec2<T> const &a) {
return vec2<T>(a).neg();
}
using vec2f = vec2<float>;
using vec2d = vec2<double>;
using vec2b = vec2<unsigned char>;
using vec2i = vec2<int>;
template<typename T>
struct vec3 {
union {
struct { T x, y, z; };
struct { T r, g, b; };
T value[3];
};
vec3(): x(0), y(0), z(0) {}
vec3(vec3 const &v): x(v.x), y(v.y), z(v.z) {}
vec3(T v): x(v), y(v), z(v) {}
vec3(T x, T y, T z): x(x), y(y), z(z) {}
T &operator[](std::size_t idx) { return value[idx]; }
T operator[](std::size_t idx) const { return value[idx]; }
vec3 &add(T v) {
x += v; y += v; z += v;
return *this;
}
vec3 &add(vec3 const &o) {
x += o.x; y += o.y; z += o.z;
return *this;
}
vec3 &sub(T v) {
x -= v; y -= v; z -= v;
return *this;
}
vec3 &sub(vec3 const &o) {
x -= o.x; y -= o.y; z -= o.z;
return *this;
}
vec3 &mul(T v) {
x *= v; y *= v; z *= v;
return *this;
}
vec3 &mul(vec3 const &o) {
x *= o.x; y *= o.y; z *= o.z;
return *this;
}
vec3 &div(T v) {
x /= v; y /= v; z /= v;
return *this;
}
vec3 &div(vec3 const &o) {
x /= o.x; y /= o.y; z /= o.z;
return *this;
}
vec3 &neg() {
x = -x; y = -y; z = -z;
return *this;
}
bool is_zero() const {
return (x == 0) && (y == 0) && (z == 0);
}
T dot(vec3<T> const &o) const {
return (x * o.x) + (y * o.y) + (z * o.z);
}
};
template<typename T>
inline bool operator==(vec3<T> const &a, vec3<T> const &b) {
return (a.x == b.x) && (a.y == b.y) && (a.z == b.z);
}
template<typename T>
inline bool operator!=(vec3<T> const &a, vec3<T> const &b) {
return (a.x != b.x) || (a.y != b.y) || (a.z != b.z);
}
template<typename T>
inline vec3<T> operator+(vec3<T> const &a, vec3<T> const &b) {
return vec3<T>(a).add(b);
}
template<typename T>
inline vec3<T> operator+(vec3<T> const &a, T b) {
return vec3<T>(a).add(b);
}
template<typename T>
inline vec3<T> operator-(vec3<T> const &a, vec3<T> const &b) {
return vec3<T>(a).sub(b);
}
template<typename T>
inline vec3<T> operator-(vec3<T> const &a, T b) {
return vec3<T>(a).sub(b);
}
template<typename T>
inline vec3<T> operator*(vec3<T> const &a, vec3<T> const &b) {
return vec3<T>(a).mul(b);
}
template<typename T>
inline vec3<T> operator*(vec3<T> const &a, T b) {
return vec3<T>(a).mul(b);
}
template<typename T>
inline vec3<T> operator/(vec3<T> const &a, vec3<T> const &b) {
return vec3<T>(a).div(b);
}
template<typename T>
inline vec3<T> operator/(vec3<T> const &a, T b) {
return vec3<T>(a).div(b);
}
template<typename T>
inline vec3<T> operator-(vec3<T> const &a) {
return vec3<T>(a).neg();
}
using vec3f = vec3<float>;
using vec3d = vec3<double>;
using vec3b = vec3<unsigned char>;
using vec3i = vec3<int>;
template<typename T>
struct vec4 {
union {
struct { T x, y, z, w; };
struct { T r, g, b, a; };
T value[4];
};
vec4(): x(0), y(0), z(0), w(0) {}
vec4(vec4 const &v): x(v.x), y(v.y), z(v.z), w(v.w) {}
vec4(T v): x(v), y(v), z(v), w(v) {}
vec4(T x, T y, T z, T w): x(x), y(y), z(z), w(w) {}
T &operator[](std::size_t idx) { return value[idx]; }
T operator[](std::size_t idx) const { return value[idx]; }
vec4 &add(T v) {
x += v; y += v; z += v; w += v;
return *this;
}
vec4 &add(vec4 const &o) {
x += o.x; y += o.y; z += o.z; w += o.w;
return *this;
}
vec4 &sub(T v) {
x -= v; y -= v; z -= v; w -= v;
return *this;
}
vec4 &sub(vec4 const &o) {
x -= o.x; y -= o.y; z -= o.z; w -= o.w;
return *this;
}
vec4 &mul(T v) {
x *= v; y *= v; z *= v; w *= v;
return *this;
}
vec4 &mul(vec4 const &o) {
x *= o.x; y *= o.y; z *= o.z; w *= o.w;
return *this;
}
vec4 &div(T v) {
x /= v; y /= v; z /= v; w /= v;
return *this;
}
vec4 &div(vec4 const &o) {
x /= o.x; y /= o.y; z /= o.z; w /= o.w;
return *this;
}
vec4 &neg() {
x = -x; y = -y; z = -z; w = -w;
return *this;
}
bool is_zero() const {
return (x == 0) && (y == 0) && (z == 0) && (w == 0);
}
T dot(vec4<T> const &o) const {
return (x * o.x) + (y * o.y) + (z * o.z) + (w * o.w);
}
};
template<typename T>
inline bool operator==(vec4<T> const &a, vec4<T> const &b) {
return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w);
}
template<typename T>
inline bool operator!=(vec4<T> const &a, vec4<T> const &b) {
return (a.x != b.x) || (a.y != b.y) || (a.z != b.z) || (a.w != b.w);
}
template<typename T>
inline vec4<T> operator+(vec4<T> const &a, vec4<T> const &b) {
return vec4<T>(a).add(b);
}
template<typename T>
inline vec4<T> operator+(vec4<T> const &a, T b) {
return vec4<T>(a).add(b);
}
template<typename T>
inline vec4<T> operator-(vec4<T> const &a, vec4<T> const &b) {
return vec4<T>(a).sub(b);
}
template<typename T>
inline vec4<T> operator-(vec4<T> const &a, T b) {
return vec4<T>(a).sub(b);
}
template<typename T>
inline vec4<T> operator*(vec4<T> const &a, vec4<T> const &b) {
return vec4<T>(a).mul(b);
}
template<typename T>
inline vec4<T> operator*(vec4<T> const &a, T b) {
return vec4<T>(a).mul(b);
}
template<typename T>
inline vec4<T> operator/(vec4<T> const &a, vec4<T> const &b) {
return vec4<T>(a).div(b);
}
template<typename T>
inline vec4<T> operator/(vec4<T> const &a, T b) {
return vec4<T>(a).div(b);
}
template<typename T>
inline vec4<T> operator-(vec4<T> const &a) {
return vec4<T>(a).neg();
}
using vec4f = vec4<float>;
using vec4d = vec4<double>;
using vec4b = vec4<unsigned char>;
using vec4i = vec4<int>;
} /* namespace ostd */
#endif
| 21.770992 | 72 | 0.5 | Croydon |
1685e0a12d3375087aa27131a3d12d232e9e0e54 | 3,080 | hpp | C++ | include/gdrive/request.hpp | allenbo/libgdrive | a7838bcf55fbbc6cfb66209bb2db1fbe82758924 | [
"MIT"
] | 16 | 2015-05-04T01:05:12.000Z | 2022-03-13T05:25:34.000Z | include/gdrive/request.hpp | allenbo/libgdrive | a7838bcf55fbbc6cfb66209bb2db1fbe82758924 | [
"MIT"
] | 1 | 2019-07-28T19:28:49.000Z | 2021-05-14T14:08:57.000Z | include/gdrive/request.hpp | allenbo/libgdrive | a7838bcf55fbbc6cfb66209bb2db1fbe82758924 | [
"MIT"
] | 3 | 2019-12-06T17:48:44.000Z | 2021-12-07T02:07:29.000Z | #ifndef __GDRIVE_REQUEST_HPP__
#define __GDRIVE_REQUEST_HPP__
#include "gdrive/config.hpp"
#include "common/all.hpp"
#include <string>
#include <map>
#include <vector>
#include <curl/curl.h>
namespace GDRIVE {
enum RequestMethod {
RM_GET,
RM_POST,
RM_PUT,
RM_DELETE,
RM_PATCH
};
enum EncodeMethod {
EM_URL,
EM_JSON,
};
typedef std::map<std::string, std::string> RequestHeader;
typedef std::map<std::string, std::string> RequestQuery;
typedef size_t (*ReadFunction) (void*, size_t, size_t, void*);
class HttpResponse;
class HttpRequest;
class MemoryString {
public:
MemoryString(const char* str, int size)
:_str(str), _size(size), _pos(0) {}
static size_t read(void* ptr, size_t size, size_t nmemb, void* userp) {
MemoryString* self = (MemoryString*)userp;
if (self->_size - self->_pos == 0) return 0;
int length = self->_size - self->_pos > size * nmemb ? size * nmemb : self->_size - self->_pos;
memcpy(ptr, self->_str + self->_pos, length);
self->_pos += length;
return length;
}
private:
const char* _str;
int _size;
int _pos;
};
class HttpResponse {
CLASS_MAKE_LOGGER
public:
HttpResponse() { _header_map.clear(); }
static size_t curl_write_callback(void* content, size_t size, size_t nmemb, void* userp);
inline std::string content() const { return _content; };
inline std::string header() const { return _header; };
inline void clear() { _content = ""; _header = ""; _header_map.clear(); }
inline int status() const { return _status; }
inline void set_status(int status) { _status = status;}
std::string get_header(std::string field);
void _parse_header();
private:
std::string _content;
std::string _header;
int _status;
std::map<std::string, std::string> _header_map;
friend class HttpRequest;
};
class HttpRequest {
CLASS_MAKE_LOGGER
public:
HttpRequest(std::string uri, RequestMethod method);
HttpRequest(std::string uri, RequestMethod method, RequestHeader& header, std::string body);
void add_header(RequestHeader &header);
void add_header(std::string key, std::string value);
void add_query(RequestQuery& query);
void add_query(std::string key, std::string value);
inline void clear_header() { _header.clear();}
inline void clear_query() { _query.clear(); }
void clear();
void set_uri(std::string uri);
HttpResponse& request();
inline HttpResponse& response() { return _resp;}
~HttpRequest();
protected:
std::string _uri;
RequestMethod _method;
RequestHeader _header;
RequestQuery _query;
std::string _body;
HttpResponse _resp;
CURL *_handle;
ReadFunction _read_hook;
void* _read_context;
void _init_curl_handle();
curl_slist* _build_header();
};
}
#endif
| 28.785047 | 107 | 0.624026 | allenbo |
168f32aa163f3cb0144239a0773b3b4f4907215e | 467 | hpp | C++ | include/tadsf/utils.hpp | KanHarI/TADSF | 62b68fd07fa98964125198173e589aa7322541c2 | [
"MIT"
] | 1 | 2019-07-15T06:03:13.000Z | 2019-07-15T06:03:13.000Z | include/tadsf/utils.hpp | KanHarI/CTAD | 62b68fd07fa98964125198173e589aa7322541c2 | [
"MIT"
] | null | null | null | include/tadsf/utils.hpp | KanHarI/CTAD | 62b68fd07fa98964125198173e589aa7322541c2 | [
"MIT"
] | null | null | null | #ifndef GCD_HPP
#define GCD_HPP
namespace TADSF {
constexpr int gcd(int a, int b) {
if (a > b) {
a ^= b ^= a ^= b; // constexpr alternative to std::swap(a, b)
}
while (b%a) {
b %= a;
a ^= b ^= a ^= b;
}
return a;
}
constexpr int ctpow(int base, int exp) {
int acc = 1;
while(exp) {
if (exp%2) {
acc *= base;
}
exp >>= 1;
base <<= 1;
}
return acc;
}
}
#endif
| 14.59375 | 69 | 0.43469 | KanHarI |
1690be2a77320ca8a7bafcc0096038155d72d2da | 285 | hpp | C++ | modules/ui/include/glpp/ui/elements.hpp | lenamueller/glpp | f7d29e5924537fd405a5bb409d67e65efdde8d9e | [
"MIT"
] | 16 | 2019-12-10T19:44:17.000Z | 2022-01-04T03:16:19.000Z | modules/ui/include/glpp/ui/elements.hpp | lenamueller/glpp | f7d29e5924537fd405a5bb409d67e65efdde8d9e | [
"MIT"
] | null | null | null | modules/ui/include/glpp/ui/elements.hpp | lenamueller/glpp | f7d29e5924537fd405a5bb409d67e65efdde8d9e | [
"MIT"
] | 3 | 2021-06-04T21:56:55.000Z | 2022-03-03T06:47:56.000Z | #pragma once
#include "element/box.hpp"
#include "element/button.hpp"
#include "element/flow.hpp"
#include "element/frame.hpp"
#include "element/image.hpp"
#include "element/label.hpp"
#include "element/mouse_action.hpp"
#include "element/multiplex.hpp"
#include "element/widget.hpp"
| 23.75 | 35 | 0.764912 | lenamueller |
16928a8584e121e7bda41f661b7c227f299e8d38 | 1,016 | hpp | C++ | include/metal/map/erase_key.hpp | dpacbach/metal | 9cbc6472aad3a2eb20c24709c3f142df87d9c5d0 | [
"MIT"
] | null | null | null | include/metal/map/erase_key.hpp | dpacbach/metal | 9cbc6472aad3a2eb20c24709c3f142df87d9c5d0 | [
"MIT"
] | null | null | null | include/metal/map/erase_key.hpp | dpacbach/metal | 9cbc6472aad3a2eb20c24709c3f142df87d9c5d0 | [
"MIT"
] | null | null | null | #ifndef METAL_MAP_ERASE_KEY_HPP
#define METAL_MAP_ERASE_KEY_HPP
#include "../config.hpp"
#include "../list/erase.hpp"
#include "../map/order.hpp"
namespace metal {
/// \ingroup map
///
/// ### Description
/// Removes the entry associated with some key in a \map.
///
/// ### Usage
/// For any \map `m` and \value `k`
/// \code
/// using result = metal::erase_key<m, k>;
/// \endcode
///
/// \returns: \map
/// \semantics:
/// If `m` associates keys `k_1, ..., k, ..., k_n` to values
/// `v_1, ..., v, ..., v_n`, then
/// \code
/// using result = metal::map<
/// metal::pair<k_1, v_1>, ..., metal::pair<k_n, v_n>
/// >;
/// \endcode
///
/// ### Example
/// \snippet map.cpp erase_key
///
/// ### See Also
/// \see map, has_key, at_key, insert_key
template<typename seq, typename key>
using erase_key = metal::erase<seq, metal::order<seq, key>>;
}
#endif
| 25.4 | 69 | 0.50689 | dpacbach |
16998b1dd0d4a9fbbd934eb113ef6755e7658bba | 35,300 | cpp | C++ | data-server/src/range/watch_funcs.cpp | gengdaomi/sharkstore | 1b490176846d2da98ceca07a69b6c35646567a28 | [
"Apache-2.0"
] | 1 | 2021-08-11T02:31:52.000Z | 2021-08-11T02:31:52.000Z | data-server/src/range/watch_funcs.cpp | gengdaomi/sharkstore | 1b490176846d2da98ceca07a69b6c35646567a28 | [
"Apache-2.0"
] | null | null | null | data-server/src/range/watch_funcs.cpp | gengdaomi/sharkstore | 1b490176846d2da98ceca07a69b6c35646567a28 | [
"Apache-2.0"
] | null | null | null | #include "range.h"
#include "server/range_server.h"
#include "watch.h"
#include "monitor/statistics.h"
namespace sharkstore {
namespace dataserver {
namespace range {
Status Range::GetAndResp( watch::WatcherPtr pWatcher, const watchpb::WatchCreateRequest& req, const std::string &dbKey, const bool &prefix,
int64_t &version, watchpb::DsWatchResponse *dsResp) {
version = 0;
Status ret;
if(prefix) {
//use iterator
std::string dbKeyEnd{""};
dbKeyEnd.assign(dbKey);
if (0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) {
//to do set error message
FLOG_ERROR("GetAndResp:NextComparableBytes error.");
return Status(Status::kUnknown);
}
std::string hashKey("");
WatchUtil::GetHashKey(pWatcher, prefix, meta_.GetTableID(), &hashKey);
auto watcherServer = context_->WatchServer();
auto ws = watcherServer->GetWatcherSet_(hashKey);
auto result = ws->loadFromDb(store_.get(), watchpb::PUT, dbKey, dbKeyEnd, version, meta_.GetTableID(), dsResp);
if (result.first <= 0) {
delete dsResp;
dsResp = nullptr;
}
} else {
auto resp = dsResp->mutable_resp();
resp->set_watchid(pWatcher->GetWatcherId());
resp->set_code(static_cast<int>(ret.code()));
auto evt = resp->add_events();
std::string dbValue("");
ret = store_->Get(dbKey, &dbValue);
if (ret.ok()) {
evt->set_type(watchpb::PUT);
int64_t dbVersion(0);
std::string userValue("");
std::string ext("");
watch::Watcher::DecodeValue(&dbVersion, &userValue, &ext, dbValue);
auto userKv = new watchpb::WatchKeyValue;
for(auto userKey : req.kv().key()) {
userKv->add_key(userKey);
}
userKv->set_value(userValue);
userKv->set_version(dbVersion);
userKv->set_tableid(meta_.GetTableID());
version = dbVersion;
RANGE_LOG_INFO("GetAndResp ok, db_version: [%"
PRIu64
"]", dbVersion);
} else {
evt->set_type(watchpb::DELETE);
RANGE_LOG_INFO("GetAndResp code_: %s key:%s",
ret.ToString().c_str(), EncodeToHexString(dbKey).c_str());
}
}
return ret;
}
void Range::WatchGet(common::ProtoMessage *msg, watchpb::DsWatchRequest &req) {
errorpb::Error *err = nullptr;
auto btime = get_micro_second();
context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time);
auto ds_resp = new watchpb::DsWatchResponse;
auto header = ds_resp->mutable_header();
std::string dbKey{""};
std::string dbValue{""};
int64_t dbVersion{0};
auto prefix = req.req().prefix();
auto tmpKv = req.req().kv();
RANGE_LOG_DEBUG("WatchGet begin msgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id);
do {
if (!VerifyLeader(err)) {
break;
}
if( Status::kOk != WatchEncodeAndDecode::EncodeKv(funcpb::kFuncWatchGet, meta_.Get(), tmpKv, dbKey, dbValue, err) ) {
break;
}
FLOG_DEBUG("range[%" PRIu64 " %s-%s] WatchGet key:%s", id_, EncodeToHexString(meta_.GetStartKey()).c_str(),
EncodeToHexString(meta_.GetEndKey()).c_str(), EncodeToHexString(dbKey).c_str());
auto epoch = req.header().range_epoch();
bool in_range = KeyInRange(dbKey);
bool is_equal = EpochIsEqual(epoch);
if (!in_range) {
if (is_equal) {
err = KeyNotInRange(dbKey);
break;
}
}
} while (false);
//int16_t watchFlag{0};
if (err != nullptr) {
RANGE_LOG_WARN("WatchGet error: %s", err->message().c_str());
common::SetResponseHeader(req.header(), header, err);
context_->SocketSession()->Send(msg, ds_resp);
return;
}
//add watch if client version is not equal to ds side
auto clientVersion = req.req().startversion();
//to do add watch
auto watch_server = context_->WatchServer();
std::vector<watch::WatcherKey*> keys;
for (auto i = 0; i < tmpKv.key_size(); i++) {
keys.push_back(new watch::WatcherKey(tmpKv.key(i)));
}
watch::WatchType watchType = watch::WATCH_KEY;
if(prefix) {
watchType = watch::WATCH_PREFIX;
}
//int64_t expireTime = (req.req().longpull() > 0)?getticks() + req.req().longpull():msg->expire_time;
int64_t expireTime = (req.req().longpull() > 0)?get_micro_second() + req.req().longpull()*1000:msg->expire_time*1000;
auto w_ptr = std::make_shared<watch::Watcher>(watchType, meta_.GetTableID(), keys, clientVersion, expireTime, msg);
watch::WatchCode wcode;
if(prefix) {
//to do load data from memory
//std::string dbKeyEnd("");
//dbKeyEnd.assign(dbKey);
// if( 0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) {
// //to do set error message
// FLOG_ERROR("NextComparableBytes error.");
// return;
// }
auto hashKey = w_ptr->GetKeys();
std::string encode_key("");
w_ptr->EncodeKey(&encode_key, w_ptr->GetTableId(), w_ptr->GetKeys());
std::vector<watch::CEventBufferValue> vecUpdKeys;
auto retPair = eventBuffer->loadFromBuffer(encode_key, clientVersion, vecUpdKeys);
int32_t memCnt(retPair.first);
auto verScope = retPair.second;
RANGE_LOG_DEBUG("loadFromBuffer key:%s hit count[%" PRId32 "] version scope:%" PRId32 "---%" PRId32 " client_version:%" PRId64 ,
EncodeToHexString(encode_key).c_str(), memCnt, verScope.first, verScope.second, clientVersion);
if(memCnt > 0) {
auto resp = ds_resp->mutable_resp();
resp->set_code(Status::kOk);
resp->set_scope(watchpb::RESPONSE_PART);
for (auto j = 0; j < memCnt; j++) {
auto evt = resp->add_events();
for (decltype(vecUpdKeys[j].key().size()) k = 0; k < vecUpdKeys[j].key().size(); k++) {
evt->mutable_kv()->add_key(vecUpdKeys[j].key(k));
}
evt->mutable_kv()->set_value(vecUpdKeys[j].value());
evt->mutable_kv()->set_version(vecUpdKeys[j].version());
evt->set_type(vecUpdKeys[j].type());
}
w_ptr->Send(ds_resp);
return;
} else {
w_ptr->setBufferFlag(memCnt);
wcode = watch_server->AddPrefixWatcher(w_ptr, store_.get());
}
} else {
wcode = watch_server->AddKeyWatcher(w_ptr, store_.get());
}
if(watch::WATCH_OK == wcode) {
return;
} else if(watch::WATCH_WATCHER_NOT_NEED == wcode) {
auto btime = get_micro_second();
//to do get from db again
GetAndResp(w_ptr, req.req(), dbKey, prefix, dbVersion, ds_resp);
context_->Statistics()->PushTime(monitor::HistogramType::kQWait,
get_micro_second() - btime);
w_ptr->Send(ds_resp);
} else {
RANGE_LOG_ERROR("add watcher exception(%d).", static_cast<int>(wcode));
return;
}
return;
}
void Range::PureGet(common::ProtoMessage *msg, watchpb::DsKvWatchGetMultiRequest &req) {
errorpb::Error *err = nullptr;
auto btime = get_micro_second();
context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time);
auto ds_resp = new watchpb::DsKvWatchGetMultiResponse;
auto header = ds_resp->mutable_header();
//encode key and value
std::string dbKey{""};
std::string dbKeyEnd{""};
std::string dbValue("");
//int64_t version{0};
int64_t minVersion(0);
int64_t maxVersion(0);
auto prefix = req.prefix();
RANGE_LOG_DEBUG("PureGet beginmsgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id);
do {
if (!VerifyLeader(err)) {
break;
}
auto &key = req.kv().key();
if (key.empty()) {
RANGE_LOG_WARN("PureGet error: key empty");
err = KeyNotInRange("EmptyKey");
break;
}
//encode key
if( 0 != WatchEncodeAndDecode::EncodeKv(funcpb::kFuncWatchGet, meta_.Get(), req.kv(), dbKey, dbValue, err)) {
break;
}
RANGE_LOG_INFO("PureGet key before:%s after:%s", key[0].c_str(), EncodeToHexString(dbKey).c_str());
auto epoch = req.header().range_epoch();
bool in_range = KeyInRange(dbKey);
bool is_equal = EpochIsEqual(epoch);
if (!in_range) {
if (is_equal) {
err = KeyNotInRange(dbKey);
break;
}
}
auto resp = ds_resp;
auto btime = get_micro_second();
storage::Iterator *it = nullptr;
Status::Code code = Status::kOk;
if (prefix) {
dbKeyEnd.assign(dbKey);
if( 0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) {
//to do set error message
break;
}
RANGE_LOG_DEBUG("PureGet key scope %s---%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbKeyEnd).c_str());
//need to encode and decode
std::shared_ptr<storage::Iterator> iterator(store_->NewIterator(dbKey, dbKeyEnd));
uint32_t count{0};
for (int i = 0; iterator->Valid() ; ++i) {
count++;
auto kv = resp->add_kvs();
auto tmpDbKey = iterator.get()->key();
auto tmpDbValue = iterator.get()->value();
if(Status::kOk != WatchEncodeAndDecode::DecodeKv(funcpb::kFuncPureGet, meta_.GetTableID(), kv, tmpDbKey, tmpDbValue, err)) {
//break;
continue;
}
//to judge version after decoding value and spliting version from value
if (minVersion > kv->version()) {
minVersion = kv->version();
}
if(maxVersion < kv->version()) {
maxVersion = kv->version();
}
iterator->Next();
}
RANGE_LOG_DEBUG("PureGet ok:%d ", count);
code = Status::kOk;
} else {
auto ret = store_->Get(dbKey, &dbValue);
if(ret.ok()) {
//to do decode value version
RANGE_LOG_DEBUG("PureGet: dbKey:%s dbValue:%s ", EncodeToHexString(dbKey).c_str(),
EncodeToHexString(dbValue).c_str());
auto kv = resp->add_kvs();
/*
int64_t dbVersion(0);
std::string userValue("");
std::string extend("");
watch::Watcher::DecodeValue(&dbVersion, &userValue, &extend, dbValue);
*/
if (Status::kOk != WatchEncodeAndDecode::DecodeKv(funcpb::kFuncPureGet, meta_.GetTableID(), kv, dbKey, dbValue, err)) {
RANGE_LOG_WARN("DecodeKv fail. dbvalue:%s err:%s", EncodeToHexString(dbValue).c_str(),
err->message().c_str());
//break;
}
}
RANGE_LOG_DEBUG("PureGet code:%d msg:%s ", ret.code(), ret.ToString().data());
code = ret.code();
}
context_->Statistics()->PushTime(monitor::HistogramType::kQWait, get_micro_second() - btime);
resp->set_code(static_cast<int32_t>(code));
} while (false);
if (err != nullptr) {
RANGE_LOG_WARN("PureGet error: %s", err->message().c_str());
}
common::SetResponseHeader(req.header(), header, err);
context_->SocketSession()->Send(msg, ds_resp);
}
void Range::WatchPut(common::ProtoMessage *msg, watchpb::DsKvWatchPutRequest &req) {
errorpb::Error *err = nullptr;
std::string dbKey{""};
//auto dbValue{std::make_shared<std::string>("")};
//auto extPtr{std::make_shared<std::string>("")};
auto btime = get_micro_second();
context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time);
RANGE_LOG_DEBUG("WatchPut begin msgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id);
if (!CheckWriteable()) {
auto resp = new watchpb::DsKvWatchPutResponse;
resp->mutable_resp()->set_code(Status::kNoLeftSpace);
return SendError(msg, req.header(), resp, nullptr);
}
do {
if (!VerifyLeader(err)) {
break;
}
auto kv = req.mutable_req()->mutable_kv();
if (kv->key().empty()) {
RANGE_LOG_WARN("WatchPut error: key empty");
err = KeyNotInRange("-");
break;
}
RANGE_LOG_DEBUG("WatchPut key:%s value:%s", kv->key(0).c_str(), kv->value().c_str());
/*
//to do move to apply encode key
if( 0 != version_seq_->nextId(&version)) {
if (err == nullptr) {
err = new errorpb::Error;
}
err->set_message(version_seq_->getErrMsg());
break;
}
kv->set_version(version);
FLOG_DEBUG("range[%" PRIu64 "] WatchPut key-version[%" PRIu64 "]", meta_.id(), version);
if( Status::kOk != WatchCode::EncodeKv(funcpb::kFuncWatchPut, meta_, *kv, *dbKey, *dbValue, err) ) {
break;
}*/
std::vector<std::string*> vecUserKeys;
for ( auto i = 0 ; i < kv->key_size(); i++) {
vecUserKeys.emplace_back(kv->mutable_key(i));
}
watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), vecUserKeys);
auto epoch = req.header().range_epoch();
bool in_range = KeyInRange(dbKey);
bool is_equal = EpochIsEqual(epoch);
if (!in_range) {
if (is_equal) {
err = KeyNotInRange(dbKey);
} else {
err = StaleEpochError(epoch);
}
break;
}
/*
//increase key version
kv->set_version(version);
kv->clear_key();
kv->add_key(*dbKey);
kv->set_value(*dbValue);
*/
//raft propagate at first, propagate KV after encodding
if (!WatchPutSubmit(msg, req)) {
err = RaftFailError();
}
} while (false);
if (err != nullptr) {
RANGE_LOG_WARN("WatchPut error: %s", err->message().c_str());
auto resp = new watchpb::DsKvWatchPutResponse;
return SendError(msg, req.header(), resp, err);
}
}
void Range::WatchDel(common::ProtoMessage *msg, watchpb::DsKvWatchDeleteRequest &req) {
errorpb::Error *err = nullptr;
std::string dbKey{""};
//auto dbValue = std::make_shared<std::string>();
//auto extPtr = std::make_shared<std::string>();
auto btime = get_micro_second();
context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time);
RANGE_LOG_DEBUG("WatchDel begin, msgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id);
if (!CheckWriteable()) {
auto resp = new watchpb::DsKvWatchDeleteResponse;
resp->mutable_resp()->set_code(Status::kNoLeftSpace);
return SendError(msg, req.header(), resp, nullptr);
}
do {
if (!VerifyLeader(err)) {
break;
}
auto kv = req.mutable_req()->mutable_kv();
if (kv->key_size() < 1) {
RANGE_LOG_WARN("WatchDel error due to key is empty");
err = KeyNotInRange("EmptyKey");
break;
}
/*
if(Status::kOk != WatchCode::EncodeKv(funcpb::kFuncWatchDel, meta_, *kv, *dbKey, *dbValue, err)) {
break;
}*/
/*std::vector<std::string*> vecUserKeys;
for(auto itKey : kv->key()) {
vecUserKeys.emplace_back(&itKey);
}*/
std::vector<std::string*> vecUserKeys;
for ( auto i = 0 ; i < kv->key_size(); i++) {
vecUserKeys.emplace_back(kv->mutable_key(i));
}
watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), vecUserKeys);
auto epoch = req.header().range_epoch();
bool in_range = KeyInRange(dbKey);
bool is_equal = EpochIsEqual(epoch);
if (!in_range) {
if (is_equal) {
err = KeyNotInRange(dbKey);
} else {
err = StaleEpochError(epoch);
}
break;
}
/*
//set encoding value to request
kv->clear_key();
kv->add_key(*dbKey);
kv->set_value(*dbValue);
*/
/*to do move to apply
//to do consume version and will reply to client
int64_t version{0};
if( 0 != version_seq_->nextId(&version)) {
if (err == nullptr) {
err = new errorpb::Error;
}
err->set_message(version_seq_->getErrMsg());
break;
}
kv->set_version(version);
*/
if (!WatchDeleteSubmit(msg, req)) {
err = RaftFailError();
}
} while (false);
if (err != nullptr) {
RANGE_LOG_WARN("WatchDel error: %s", err->message().c_str());
auto resp = new watchpb::DsKvWatchDeleteResponse;
return SendError(msg, req.header(), resp, err);
}
}
bool Range::WatchPutSubmit(common::ProtoMessage *msg, watchpb::DsKvWatchPutRequest &req) {
auto &kv = req.req().kv();
if (is_leader_ && kv.key_size() > 0 ) {
auto ret = SubmitCmd(msg, req.header(), [&req](raft_cmdpb::Command &cmd) {
cmd.set_cmd_type(raft_cmdpb::CmdType::KvWatchPut);
cmd.set_allocated_kv_watch_put_req(req.release_req());
});
return ret.ok() ? true : false;
}
return false;
}
bool Range::WatchDeleteSubmit(common::ProtoMessage *msg,
watchpb::DsKvWatchDeleteRequest &req) {
auto &kv = req.req().kv();
if (is_leader_ && kv.key_size() > 0 ) {
auto ret = SubmitCmd(msg, req.header(), [&req](raft_cmdpb::Command &cmd) {
cmd.set_cmd_type(raft_cmdpb::CmdType::KvWatchDel);
cmd.set_allocated_kv_watch_del_req(req.release_req());
});
return ret.ok() ? true : false;
}
return false;
}
Status Range::ApplyWatchPut(const raft_cmdpb::Command &cmd, uint64_t raftIdx) {
Status ret;
errorpb::Error *err = nullptr;
//RANGE_LOG_DEBUG("ApplyWatchPut begin");
auto &req = cmd.kv_watch_put_req();
auto btime = get_micro_second();
watchpb::WatchKeyValue notifyKv;
notifyKv.CopyFrom(req.kv());
static int64_t version{0};
version = raftIdx;
//for test
if (0) {
static std::atomic<int64_t> test_version = {0};
test_version += 1;
////////////////////////////////////////////////////////////
version = test_version;
apply_index_=version;
///////////////////////////////////////////////////////////
}
notifyKv.set_version(version);
RANGE_LOG_DEBUG("ApplyWatchPut new version[%" PRIu64 "]", version);
int64_t beginTime(getticks());
std::string dbKey{""};
std::string dbValue{""};
if( Status::kOk != WatchEncodeAndDecode::EncodeKv(funcpb::kFuncWatchPut, meta_.Get(), notifyKv, dbKey, dbValue, err) ) {
//to do
// SendError()
FLOG_WARN("EncodeKv failed, key:%s ", notifyKv.key(0).c_str());
;
}
notifyKv.clear_key();
notifyKv.add_key(dbKey);
notifyKv.set_value(dbValue);
RANGE_LOG_DEBUG("ApplyWatchPut dbkey:%s dbvalue:%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbValue).c_str());
do {
if (!KeyInRange(dbKey, err)) {
FLOG_WARN("Apply WatchPut failed, key:%s not in range.", dbKey.data());
ret = std::move(Status(Status::kInvalidArgument, "key not in range", ""));
break;
}
//save to db
auto btime = get_micro_second();
ret = store_->Put(dbKey, dbValue);
context_->Statistics()->PushTime(monitor::HistogramType::kQWait,
get_micro_second() - btime);
if (!ret.ok()) {
FLOG_ERROR("ApplyWatchPut failed, code:%d, msg:%s", ret.code(),
ret.ToString().data());
break;
}
/*if(req.kv().key_size() > 1) {
//to do decode group key,ignore single key
auto value = std::make_shared<watch::CEventBufferValue>(notifyKv, watchpb::PUT);
if(value->key_size()) {
FLOG_DEBUG(">>>key is valid.");
}
if (!eventBuffer->enQueue(dbKey, value.get())) {
FLOG_ERROR("load delete event kv to buffer error.");
}
}
*/
if (cmd.cmd_id().node_id() == node_id_) {
auto len = static_cast<uint64_t>(req.kv().ByteSizeLong());
CheckSplit(len);
}
} while (false);
if (cmd.cmd_id().node_id() == node_id_) {
auto resp = new watchpb::DsKvWatchPutResponse;
resp->mutable_resp()->set_code(ret.code());
ReplySubmit(cmd, resp, err, btime);
//notify watcher
std::string errMsg("");
int32_t retCnt = WatchNotify(watchpb::PUT, req.kv(), version, errMsg);
if (retCnt < 0) {
FLOG_ERROR("WatchNotify-put failed, ret:%d, msg:%s", retCnt, errMsg.c_str());
} else {
FLOG_DEBUG("WatchNotify-put success, count:%d, msg:%s", retCnt, errMsg.c_str());
}
} else if (err != nullptr) {
delete err;
return ret;
}
int64_t endTime(getticks());
FLOG_DEBUG("ApplyWatchPut key[%s], take time:%" PRId64 " ms", EncodeToHexString(dbKey).c_str(), endTime - beginTime);
return ret;
}
Status Range::ApplyWatchDel(const raft_cmdpb::Command &cmd, uint64_t raftIdx) {
Status ret;
errorpb::Error *err = nullptr;
// RANGE_LOG_DEBUG("ApplyWatchDel begin");
auto &req = cmd.kv_watch_del_req();
auto btime = get_micro_second();
watchpb::WatchKeyValue notifyKv;
notifyKv.CopyFrom(req.kv());
auto prefix = req.prefix();
uint64_t version{0};
//version = getNextVersion(err);
version = raftIdx;
//for test
if (0) {
static std::atomic<int64_t> test_version = {1};
test_version += 1;
////////////////////////////////////////////////////////////
version = test_version;
apply_index_=version;
///////////////////////////////////////////////////////////
}
notifyKv.set_version(version);
RANGE_LOG_DEBUG("ApplyWatchDel new-version[%" PRIu64 "]", version);
std::string dbKey{""};
std::string dbValue{""};
std::vector<std::string*> userKeys;
for(auto i = 0; i < req.kv().key_size(); i++) {
userKeys.push_back(std::move(new std::string(req.kv().key(i))));
}
watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), userKeys);
for(auto it:userKeys) {
delete it;
}
if(!req.kv().value().empty()) {
std::string extend("");
watch::Watcher::EncodeValue(&dbValue, version, &req.kv().value(), &extend);
}
std::vector<std::string> delKeys;
if (!KeyInRange(dbKey, err)) {
FLOG_WARN("ApplyWatchDel failed, key:%s not in range.", dbKey.data());
}
if (err != nullptr) {
delete err;
return ret;
}
if(prefix) {
std::string dbKeyEnd(dbKey);
if (0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) {
//to do set error message
FLOG_ERROR("NextComparableBytes error, skip key:%s", EncodeToHexString(dbKey).c_str());
return Status(Status::kUnknown);
}
RANGE_LOG_DEBUG("ApplyWatchDel key scope %s---%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbKeyEnd).c_str());
std::shared_ptr<storage::Iterator> iterator(store_->NewIterator(dbKey, dbKeyEnd));
for (int i = 0; iterator->Valid(); ++i) {
delKeys.push_back(std::move(iterator->key()));
iterator->Next();
}
std::string first_key("");
std::string last_key("");
int64_t keySize = delKeys.size();
if (delKeys.size() > 0) {
first_key = delKeys[0];
last_key = delKeys[delKeys.size() - 1];
}
RANGE_LOG_DEBUG("BatchDelete afftected_keys:%" PRId64 " first_key:%s last_key:%s",
keySize, EncodeToHexString(first_key).c_str(), EncodeToHexString(last_key).c_str());
} else {
delKeys.push_back(dbKey);
}
// ret = store_->BatchDelete(delKeys);
// if (!ret.ok()) {
// FLOG_ERROR("BatchDelete failed, code:%d, msg:%s , key:%s", ret.code(),
// ret.ToString().c_str(), EncodeToHexString(dbKey).c_str());
// break;
// }
auto keySize(delKeys.size());
int64_t idx(0);
std::vector<std::string*> vecKeys;
for(auto it : delKeys) {
idx++;
FLOG_DEBUG("execute delte...[%" PRId64 "/%" PRIu64 "]", idx, keySize);
auto btime = get_micro_second();
ret = store_->Delete(it);
context_->Statistics()->PushTime(monitor::HistogramType::kQWait,
get_micro_second() - btime);
if (cmd.cmd_id().node_id() == node_id_ && delKeys[keySize-1] == it) {
//FLOG_DEBUG("Delete:%s del key:%s---last key:%s", ret.ToString().c_str(), EncodeToHexString(it).c_str(), EncodeToHexString(delKeys[keySize-1]).c_str());
auto resp = new watchpb::DsKvWatchDeleteResponse;
resp->mutable_resp()->set_code(ret.code());
ReplySubmit(cmd, resp, err, btime);
} else if (err != nullptr) {
delete err;
continue;
}
if (!ret.ok()) {
FLOG_ERROR("ApplyWatchDel failed, code:%d, msg:%s , key:%s", ret.code(),
ret.ToString().c_str(), EncodeToHexString(dbKey).c_str());
continue;
}
FLOG_DEBUG("store->Delete->ret.code:%s", ret.ToString().c_str());
if (cmd.cmd_id().node_id() == node_id_) {
notifyKv.clear_key();
vecKeys.clear();
watch::Watcher::DecodeKey(vecKeys, it);
for (auto key:vecKeys) {
notifyKv.add_key(*key);
}
for (auto key:vecKeys) {
delete key;
}
//notify watcher
int32_t retCnt(0);
std::string errMsg("");
retCnt = WatchNotify(watchpb::DELETE, notifyKv, version, errMsg, prefix);
if (retCnt < 0) {
FLOG_ERROR("WatchNotify-del failed, ret:%d, msg:%s", retCnt, errMsg.c_str());
} else {
FLOG_DEBUG("WatchNotify-del success, watch_count:%d, msg:%s", retCnt, errMsg.c_str());
}
}
}
if(prefix && cmd.cmd_id().node_id() == node_id_ && keySize == 0) {
auto resp = new watchpb::DsKvWatchDeleteResponse;
//Delete没有失败,统一返回ok
ret = Status(Status::kOk);
resp->mutable_resp()->set_code(ret.code());
ReplySubmit(cmd, resp, err, btime);
}
return ret;
}
int32_t Range::WatchNotify(const watchpb::EventType evtType, const watchpb::WatchKeyValue& kv, const int64_t &version, std::string &errMsg, bool prefix) {
if(kv.key_size() == 0) {
errMsg.assign("WatchNotify--key is empty.");
return -1;
}
std::vector<watch::WatcherPtr> vecNotifyWatcher;
std::vector<watch::WatcherPtr> vecPrefixNotifyWatcher;
//continue to get prefix key
std::vector<std::string *> decodeKeys;
std::string hashKey("");
std::string dbKey("");
bool hasPrefix(prefix);
if(!hasPrefix && kv.key_size() > 1) {
hasPrefix = true;
}
for(auto it : kv.key()) {
decodeKeys.emplace_back(std::move(new std::string(it)));
//only push the first key
break;
}
watch::Watcher::EncodeKey(&hashKey, meta_.GetTableID(), decodeKeys);
if(hasPrefix) {
int16_t tmpCnt{0};
for(auto it : kv.key()) {
++tmpCnt;
if(tmpCnt == 1) continue;
//to do skip the first element
decodeKeys.emplace_back(std::move(new std::string(it)));
}
watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), decodeKeys);
} else {
dbKey = hashKey;
}
for(auto it : decodeKeys) {
delete it;
}
FLOG_DEBUG("WatchNotify haskkey:%s key:%s version:%" PRId64, EncodeToHexString(hashKey).c_str(), EncodeToHexString(dbKey).c_str(), version);
if(hasPrefix) {
auto value = std::make_shared<watch::CEventBufferValue>(kv, evtType, version);
if (!eventBuffer->enQueue(hashKey, value.get())) {
FLOG_ERROR("load delete event kv to buffer error.");
}
}
auto dbValue = kv.value();
int64_t currDbVersion{version};
auto watch_server = context_->WatchServer();
watch_server->GetKeyWatchers(evtType, vecNotifyWatcher, hashKey, dbKey, currDbVersion);
//start to send user kv to client
int32_t watchCnt = vecNotifyWatcher.size();
FLOG_DEBUG("single key notify:%" PRId32 " key:%s", watchCnt, EncodeToHexString(dbKey).c_str());
for(auto i = 0; i < watchCnt; i++) {
auto dsResp = new watchpb::DsWatchResponse;
auto resp = dsResp->mutable_resp();
auto evt = resp->add_events();
evt->set_allocated_kv(new watchpb::WatchKeyValue(kv));
evt->mutable_kv()->set_version(currDbVersion);
evt->set_type(evtType);
SendNotify(vecNotifyWatcher[i], dsResp);
}
if(hasPrefix) {
//watch_server->GetPrefixWatchers(evtType, vecPrefixNotifyWatcher, hashKey, dbKey, currDbVersion);
watch_server->GetPrefixWatchers(evtType, vecPrefixNotifyWatcher, hashKey, hashKey, currDbVersion);
watchCnt = vecPrefixNotifyWatcher.size();
FLOG_DEBUG("prefix key notify:%" PRId32 " key:%s", watchCnt, EncodeToHexString(dbKey).c_str());
for( auto i = 0; i < watchCnt; i++) {
int64_t startVersion(vecPrefixNotifyWatcher[i]->getKeyVersion());
auto dsResp = new watchpb::DsWatchResponse;
std::vector<watch::CEventBufferValue> vecUpdKeys;
vecUpdKeys.clear();
auto retPair = eventBuffer->loadFromBuffer(hashKey, startVersion, vecUpdKeys);
int32_t memCnt(retPair.first);
auto verScope = retPair.second;
RANGE_LOG_DEBUG("loadFromBuffer key:%s hit count[%" PRId32 "] version scope:%" PRId32 "---%" PRId32 " client_version:%" PRId64 ,
EncodeToHexString(hashKey).c_str(), memCnt, verScope.first, verScope.second, startVersion);
if (0 == memCnt) {
FLOG_ERROR("doudbt no changing, notify %d/%"
PRId32
" key:%s", i+1, watchCnt, EncodeToHexString(dbKey).c_str());
delete dsResp;
dsResp = nullptr;
} else if (memCnt > 0) {
FLOG_DEBUG("notify %d/%"
PRId32
" loadFromBuffer key:%s hit count:%"
PRId32, i+1, watchCnt, EncodeToHexString(dbKey).c_str(), memCnt);
auto resp = dsResp->mutable_resp();
resp->set_code(Status::kOk);
resp->set_scope(watchpb::RESPONSE_PART);
for (auto j = 0; j < memCnt; j++) {
auto evt = resp->add_events();
for (decltype(vecUpdKeys[j].key().size()) k = 0; k < vecUpdKeys[j].key().size(); k++) {
evt->mutable_kv()->add_key(vecUpdKeys[j].key(k));
}
evt->mutable_kv()->set_value(vecUpdKeys[j].value());
evt->mutable_kv()->set_version(vecUpdKeys[j].version());
evt->set_type(vecUpdKeys[j].type());
}
} else {
//get all from db
FLOG_INFO("overlimit version in memory,get from db now. notify %d/%"
PRId32
" key:%s version:%"
PRId64,
i+1, watchCnt, EncodeToHexString(dbKey).c_str(), startVersion);
//use iterator
std::string dbKeyEnd{""};
dbKeyEnd.assign(dbKey);
if( 0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) {
//to do set error message
FLOG_ERROR("NextComparableBytes error.");
return -1;
}
//RANGE_LOG_DEBUG("WatchNotify key scope %s---%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbKeyEnd).c_str());
auto watcherServer = context_->WatchServer();
auto ws = watcherServer->GetWatcherSet_(hashKey);
auto result = ws->loadFromDb(store_.get(), evtType, dbKey, dbKeyEnd, startVersion, meta_.GetTableID(), dsResp);
if(result.first <= 0) {
delete dsResp;
dsResp = nullptr;
}
//scopeFlag = 1;
FLOG_DEBUG("notify %d/%" PRId32 " load from db, db-count:%" PRId32 " key:%s ", i+1, watchCnt, result.first, EncodeToHexString(dbKey).c_str());
}
if (hasPrefix && watchCnt > 0 && dsResp != nullptr) {
SendNotify(vecPrefixNotifyWatcher[i], dsResp, true);
}
}
}
return watchCnt;
}
int32_t Range::SendNotify( watch::WatcherPtr w, watchpb::DsWatchResponse *ds_resp, bool prefix)
{
auto watch_server = context_->WatchServer();
auto resp = ds_resp->mutable_resp();
auto w_id = w->GetWatcherId();
resp->set_watchid(w_id);
w->Send(ds_resp);
//delete watch
watch::WatchCode del_ret = watch::WATCH_OK;
if (!prefix && w->GetType() == watch::WATCH_KEY) {
del_ret = watch_server->DelKeyWatcher(w);
if (del_ret) {
RANGE_LOG_WARN(" DelKeyWatcher error, watch_id[%" PRId64 "]", w_id);
} else {
RANGE_LOG_WARN(" DelKeyWatcher execute end. watch_id:%" PRIu64, w_id);
}
}
if (prefix && w->GetType() == watch::WATCH_KEY) {
del_ret = watch_server->DelPrefixWatcher(w);
if (del_ret) {
RANGE_LOG_WARN(" DelPrefixWatcher error, watch_id[%" PRId64 "]", w_id);
} else {
RANGE_LOG_WARN(" DelPrefixWatcher execute end. watch_id:%" PRIu64, w_id);
}
}
return del_ret;
}
} // namespace range
} // namespace dataserver
} // namespace sharkstore
| 33.844679 | 165 | 0.552691 | gengdaomi |
169b99a6b5b80ca3f8b9d46b90c72b352720699a | 5,747 | cpp | C++ | src/trafficsim/Map.cpp | lutrarutra/trafsim | 05e87b263b48e39d63f699dcaa456f10ca61e9a4 | [
"Apache-2.0"
] | 12 | 2019-12-28T21:45:23.000Z | 2022-03-28T12:40:44.000Z | src/trafficsim/Map.cpp | lutrarutra/trafsim | 05e87b263b48e39d63f699dcaa456f10ca61e9a4 | [
"Apache-2.0"
] | null | null | null | src/trafficsim/Map.cpp | lutrarutra/trafsim | 05e87b263b48e39d63f699dcaa456f10ca61e9a4 | [
"Apache-2.0"
] | 1 | 2021-05-31T10:22:41.000Z | 2021-05-31T10:22:41.000Z | #include "Map.hpp"
#include <fstream>
#include <cfloat> // FLT_MAX
#include <iostream> // FLT_MAX
#include <memory>
#include "Rando.hpp"
#include "RoadTile.hpp"
namespace ts
{
Map::Map()
: grid_(120)
{
}
void Map::clearMap()
{
cars_.clear();
light_networks_.clear();
building_handlers_.clear();
current_network_id_ = 0;
current_building_id_ = 0;
grid_.init();
}
void Map::initDay()
{
for(unsigned int i = 0; i < grid_.getTotalTileCount(); ++i)
{
if(grid_.getTile(i)->getCategory() == TileCategory::RoadCategory)
{
grid_.getTile(i)->getNode()->resetCounter();
}
}
for (auto it = building_handlers_.begin(); it != building_handlers_.end(); ++it)
{
it->second->initDay();
}
}
void Map::update(const sf::Time &game_time, float delta_time)
{
// Move cars, and other things which are dependent on time
//cars, humans, trafficlights
if (!simulating_)
return;
for (auto ita = building_handlers_.begin(); ita != building_handlers_.end(); ++ita)
{
if (ita->second->update(game_time))
{
Rando r(building_handlers_.size());
int index = r.uniroll() - 1;
int i = 0;
const Tile *dest_tile;
for (auto itb = building_handlers_.begin(); itb != building_handlers_.end(); ++itb)
{
if (index == i)
{
dest_tile = itb->second->getClosestRoad();
break;
}
i++;
}
auto spawn_tile = ita->second->getClosestRoad();
if(dest_tile && spawn_tile)
addCar(spawn_tile, dest_tile);
}
}
for (auto &car : cars_)
car->update(game_time, delta_time, cars_, light_networks_);
removeFinishedCars();
for (auto ita = light_networks_.begin(); ita != light_networks_.end(); ++ita)
ita->second->update(delta_time);
}
void Map::addCar(const Tile *spawn_pos, const Tile *dest)
{
cars_.push_back(std::make_unique<Car>(Car(spawn_pos->getNode(), dest->getNode(), sf::Vector2f(50, 100))));
}
unsigned int Map::addBuilding(BuildingTile *building)
{
auto closest_road_node = closestRoadNode(building->getCenter());
if (closest_road_node)
building_handlers_.insert({current_building_id_, std::make_unique<BuildingHandler>(building, grid_.getTile(closest_road_node->getPos()), current_building_id_)});
else
building_handlers_.insert({current_building_id_, std::make_unique<BuildingHandler>(building, nullptr, current_building_id_)});
current_building_id_++;
return current_building_id_ - 1;
}
void Map::updateClosestRoads()
{
for (auto it = building_handlers_.begin(); it != building_handlers_.end(); ++it)
{
auto closest_road_node = closestRoadNode(it->second->getBuildingTile()->getCenter());
if(closest_road_node)
it->second->setClosestRoad(grid_.getTile(closest_road_node->getPos()));
}
}
void Map::addLight(TrafficLight *light, unsigned int handler_id)
{
if (light_networks_.find(handler_id) == light_networks_.end())
{
if (handler_id < UINT_MAX)
{
light_networks_.insert({handler_id, std::make_unique<TrafficLightNetwork>(handler_id)});
}
else
light_networks_.insert({0, std::make_unique<TrafficLightNetwork>(0)});
}
if (light_networks_.find(handler_id) != light_networks_.end())
light_networks_.at(handler_id)->addLight(light);
else
light_networks_.at(current_network_id_)->addLight(light);
}
void Map::newLightNetwork(TrafficLight *light)
{
current_network_id_++;
light_networks_.insert({current_network_id_, std::make_unique<TrafficLightNetwork>(current_network_id_)});
if (light)
{
light_networks_.at(light->getHandlerId())->removeLight(light, light->getPos());
light->setHandlerId(current_network_id_);
light_networks_.at(current_network_id_)->addLight(light);
}
}
void Map::removeBuilding(unsigned int id)
{
building_handlers_.erase(id);
}
void Map::removeLight(TrafficLight *light)
{
light_networks_.at(light->getHandlerId())->removeLight(light, light->getPos());
}
void Map::removeFinishedCars()
{
cars_.erase(std::remove_if(cars_.begin(), cars_.end(), [](const auto &car) -> bool { return car->isFinished(); }), cars_.end());
}
std::shared_ptr<Node> Map::closestRoadNode(const sf::Vector2f &pos)
{
std::shared_ptr<Node> closest = nullptr;
float closest_distance = FLT_MAX;
for (unsigned int i = 0; i < grid_.getTotalTileCount(); ++i)
{
if (grid_.getTile(i)->getCategory() == TileCategory::RoadCategory)
{
auto road_tile = static_cast<RoadTile *>(grid_.getTile(i));
if (road_tile->getType() == RoadType::StraightRoadType)
{
float dist = VectorMath::Distance(pos, grid_.getTile(i)->getCenter());
if (closest_distance > dist)
{
closest_distance = dist;
closest = grid_.getTile(i)->getNode();
}
}
}
}
return closest;
}
void Map::setSimulating(bool val)
{
if (simulating_ == val)
return;
simulating_ = val;
cars_.clear();
}
void Map::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
target.draw(grid_, states);
if (simulating_)
{
for (const auto &car : cars_)
target.draw(*car, states);
}
else
{
for (auto ita = light_networks_.begin(); ita != light_networks_.end(); ++ita)
target.draw(*ita->second, states);
}
}
} // namespace ts | 28.735 | 169 | 0.616844 | lutrarutra |
169dbf68a9d6144dc779b92ed295d8bfb87b4b92 | 12,371 | cpp | C++ | NativeCode/Plugin_Multiband.cpp | PStewart95/Unity | f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331 | [
"MIT"
] | null | null | null | NativeCode/Plugin_Multiband.cpp | PStewart95/Unity | f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331 | [
"MIT"
] | null | null | null | NativeCode/Plugin_Multiband.cpp | PStewart95/Unity | f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331 | [
"MIT"
] | null | null | null | #include "AudioPluginUtil.h"
namespace Multiband
{
enum Param
{
P_MasterGain,
P_LowFreq, P_HighFreq,
P_LowGain, P_MidGain, P_HighGain,
P_LowAttack, P_MidAttack, P_HighAttack,
P_LowRelease, P_MidRelease, P_HighRelease,
P_LowThreshold, P_MidThreshold, P_HighThreshold,
P_LowRatio, P_MidRatio, P_HighRatio,
P_LowKnee, P_MidKnee, P_HighKnee,
P_FilterOrder,
P_UseLogScale,
P_ShowSpectrum,
P_SpectrumDecay,
P_NUM
};
struct CompressorChannel
{
float env;
float atk;
float rel;
float thr;
float ratio;
float knee;
float reduction;
float exp1;
float exp2;
float GetTimeConstant(float accuracy, float numSamples)
{
/*
Derivation of time constant from transition length specified as numSamples and desired accuracy within which target is reached:
y(n) = y(n-1) + [x(n) - y(n-1)] * alpha
y(0) = 1, x(n) = 0 =>
y(1) = 1 + [0 - 1] * alpha = 1-alpha
y(2) = 1-alpha + [0 - (1-alpha)] * alpha = (1-alpha)*(1-alpha) = (1-alpha)^2
y(3) = (1-alpha)^2 + [0 - (1-alpha)^2] * alpha = (1-alpha) * (1-alpha)^2 = (1-alpha)^3
...
y(n) = (1-alpha)^n = 1-accuracy =>
1-alpha = (1-accuracy)^(1/n)
alpha = 1 - (1-accuracy)^(1/n)
*/
if (numSamples <= 0.0f)
return 1.0f;
return 1.0f - powf(1.0f - accuracy, 1.0f / numSamples);
}
void Setup(float _atk, float _rel, float _thr, float _ratio, float _knee)
{
thr = _thr;
ratio = _ratio;
knee = _knee;
float g = 0.05f * ((1.0f / ratio) - 1.0f);
exp1 = powf(10.0f, g * 0.25f / ((knee > 0.0f) ? knee : 1.0f));
exp2 = powf(10.0f, g);
atk = GetTimeConstant(0.99f, atk);
rel = GetTimeConstant(0.99f, rel);
}
inline float Process(float input)
{
float g = 1.0f;
float s = FastClip(input * input, 1.0e-11f, 100.0f);
float timeConst = (s > env) ? atk : rel;
env += (s - env) * timeConst + 1.0e-16f; // add small constant to always positive number to avoid denormal numbers
float sideChainLevel = 10.0f * log10f(env); // multiply by 10 (not 20) because duckEnvelope is RMS
float t = sideChainLevel - thr;
if (fabsf(t) < knee)
{
t += knee;
g = powf(exp1, t * t);
}
else if (t > 0.0f)
g = powf(exp2, t);
reduction = g;
return input * g;
}
};
const int MAXORDER = 4;
struct EffectData
{
struct Data
{
float p[P_NUM];
BiquadFilter bandsplit[8][MAXORDER][4];
BiquadFilter previewBandsplit[4];
CompressorChannel band[3][8];
Random random;
FFTAnalyzer analyzer;
};
union
{
Data data;
unsigned char pad[(sizeof(Data) + 15) & ~15]; // This entire structure must be a multiple of 16 bytes (and and instance 16 byte aligned) for PS3 SPU DMA requirements
};
};
int InternalRegisterEffectDefinition(UnityAudioEffectDefinition& definition)
{
static const char* bandname[] = { "Low", "Mid", "High" };
int numparams = P_NUM;
definition.paramdefs = new UnityAudioParameterDefinition[numparams];
RegisterParameter(definition, "MasterGain", "dB", -100.0f, 100.0f, 0.0f, 1.0f, 1.0f, P_MasterGain, "Overall gain");
RegisterParameter(definition, "LowFreq", "Hz", 0.01f, 24000.0f, 800.0f, 1.0f, 3.0f, P_LowFreq, "Low/Mid cross-over frequency");
RegisterParameter(definition, "HighFreq", "Hz", 0.01f, 24000.0f, 5000.0f, 1.0f, 3.0f, P_HighFreq, "Mid/High cross-over frequency");
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sGain", bandname[i]), "dB", -100.0f, 100.0f, 0.0f, 1.0f, 1.0f, P_LowGain + i, tmpstr(1, "%s band gain in dB", bandname[i]));
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sAttackTime", bandname[i]), "ms", 0.0f, 10.0f, 0.1f, 1000.0f, 4.0f, P_LowAttack + i, tmpstr(1, "%s band attack time in seconds", bandname[i]));
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sReleaseTime", bandname[i]), "ms", 0.0f, 10.0f, 0.5f, 1000.0f, 4.0f, P_LowRelease + i, tmpstr(1, "%s band release time in seconds", bandname[i]));
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sThreshold", bandname[i]), "dB", -50.0f, 0.0f, -10.0f, 1.0f, 1.0f, P_LowThreshold + i, tmpstr(1, "%s band compression level threshold time in dB", bandname[i]));
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sRatio", bandname[i]), "%", 1.0f, 30.0f, 1.0f, 100.0f, 1.0f, P_LowRatio + i, tmpstr(1, "%s band compression ratio time in percent", bandname[i]));
for (int i = 0; i < 3; i++)
RegisterParameter(definition, tmpstr(0, "%sKnee", bandname[i]), "dB", 0.0f, 40.0f, 10.0f, 1.0f, 1.0f, P_LowKnee + i, tmpstr(1, "%s band compression curve knee range in dB", bandname[i]));
RegisterParameter(definition, "FilterOrder", "", 1.0f, (float)MAXORDER, 1.0f, 1.0f, 1.0f, P_FilterOrder, "Filter order of cross-over filters");
RegisterParameter(definition, "UseLogScale", "", 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, P_UseLogScale, "Use logarithmic scale for plotting the filter curve frequency response and input/output spectra");
RegisterParameter(definition, "ShowSpectrum", "", 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, P_ShowSpectrum, "Overlay input spectrum (green) and output spectrum (red)");
RegisterParameter(definition, "SpectrumDecay", "dB/s", -50.0f, 0.0f, -10.0f, 1.0f, 1.0f, P_SpectrumDecay, "Hold time for overlaid spectra");
return numparams;
}
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK CreateCallback(UnityAudioEffectState* state)
{
EffectData* effectdata = new EffectData;
memset(effectdata, 0, sizeof(EffectData));
effectdata->data.analyzer.spectrumSize = 4096;
InitParametersFromDefinitions(InternalRegisterEffectDefinition, effectdata->data.p);
state->effectdata = effectdata;
return UNITY_AUDIODSP_OK;
}
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ReleaseCallback(UnityAudioEffectState* state)
{
EffectData::Data* data = &state->GetEffectData<EffectData>()->data;
data->analyzer.Cleanup();
delete data;
return UNITY_AUDIODSP_OK;
}
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK SetFloatParameterCallback(UnityAudioEffectState* state, int index, float value)
{
EffectData::Data* data = &state->GetEffectData<EffectData>()->data;
if (index >= P_NUM)
return UNITY_AUDIODSP_ERR_UNSUPPORTED;
data->p[index] = value;
return UNITY_AUDIODSP_OK;
}
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK GetFloatParameterCallback(UnityAudioEffectState* state, int index, float* value, char *valuestr)
{
EffectData::Data* data = &state->GetEffectData<EffectData>()->data;
if (value != NULL)
*value = data->p[index];
if (valuestr != NULL)
valuestr[0] = 0;
return UNITY_AUDIODSP_OK;
}
static void SetupFilterCoeffs(EffectData::Data* data, int samplerate, BiquadFilter* filter0, BiquadFilter* filter1, BiquadFilter* filter2, BiquadFilter* filter3)
{
const float qfactor = 0.707f;
filter0->SetupLowpass(data->p[P_LowFreq], samplerate, qfactor);
filter1->SetupHighpass(data->p[P_LowFreq], samplerate, qfactor);
filter2->SetupLowpass(data->p[P_HighFreq], samplerate, qfactor);
filter3->SetupHighpass(data->p[P_HighFreq], samplerate, qfactor);
}
int UNITY_AUDIODSP_CALLBACK GetFloatBufferCallback(UnityAudioEffectState* state, const char* name, float* buffer, int numsamples)
{
EffectData::Data* data = &state->GetEffectData<EffectData>()->data;
if (strcmp(name, "InputSpec") == 0)
data->analyzer.ReadBuffer(buffer, numsamples, true);
else if (strcmp(name, "OutputSpec") == 0)
data->analyzer.ReadBuffer(buffer, numsamples, false);
else if (strcmp(name, "LiveData") == 0)
{
buffer[0] = data->band[0][0].reduction;
buffer[1] = data->band[1][0].reduction;
buffer[2] = data->band[2][0].reduction;
buffer[3] = data->band[0][0].env;
buffer[4] = data->band[1][0].env;
buffer[5] = data->band[2][0].env;
}
else if (strcmp(name, "Coeffs") == 0)
{
SetupFilterCoeffs(data, state->samplerate, &data->previewBandsplit[0], &data->previewBandsplit[1], &data->previewBandsplit[2], &data->previewBandsplit[3]);
data->previewBandsplit[0].StoreCoeffs(buffer);
data->previewBandsplit[1].StoreCoeffs(buffer);
data->previewBandsplit[2].StoreCoeffs(buffer);
data->previewBandsplit[3].StoreCoeffs(buffer);
}
else
memset(buffer, 0, sizeof(float) * numsamples);
return UNITY_AUDIODSP_OK;
}
UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ProcessCallback(UnityAudioEffectState* state, float* inbuffer, float* outbuffer, unsigned int length, int inchannels, int outchannels)
{
EffectData::Data* data = &state->GetEffectData<EffectData>()->data;
const float sr = (float)state->samplerate;
float specDecay = powf(10.0f, 0.05f * data->p[P_SpectrumDecay] * length / sr);
bool calcSpectrum = (data->p[P_ShowSpectrum] >= 0.5f);
if (calcSpectrum)
data->analyzer.AnalyzeInput(inbuffer, inchannels, length, specDecay);
for (int i = 0; i < inchannels; i++)
{
data->band[0][i].Setup(data->p[P_LowAttack] * sr, data->p[P_LowRelease] * sr, data->p[P_LowThreshold], data->p[P_LowRatio], data->p[P_LowKnee]);
data->band[1][i].Setup(data->p[P_MidAttack] * sr, data->p[P_MidRelease] * sr, data->p[P_MidThreshold], data->p[P_MidRatio], data->p[P_MidKnee]);
data->band[2][i].Setup(data->p[P_HighAttack], data->p[P_HighRelease], data->p[P_HighThreshold], data->p[P_HighRatio], data->p[P_HighKnee]);
for (int k = 0; k < MAXORDER; k++)
SetupFilterCoeffs(data, state->samplerate, &data->bandsplit[i][k][0], &data->bandsplit[i][k][1], &data->bandsplit[i][k][2], &data->bandsplit[i][k][3]);
}
const float lowGainLin = powf(10.0f, (data->p[P_LowGain] + data->p[P_MasterGain]) * 0.05f);
const float midGainLin = powf(10.0f, (data->p[P_MidGain] + data->p[P_MasterGain]) * 0.05f);
const float highGainLin = powf(10.0f, (data->p[P_HighGain] + data->p[P_MasterGain]) * 0.05f);
const int order = (int)data->p[P_FilterOrder];
for (unsigned int n = 0; n < length; n++)
{
for (int i = 0; i < outchannels; i++)
{
float killdenormal = (float)(data->random.Get() & 255) * 1.0e-9f;
float input = inbuffer[n * inchannels + i] + killdenormal;
float lpf = input, bpf = input, hpf = input;
for (int k = 0; k < order; k++)
{
lpf = data->bandsplit[i][k][0].Process(lpf);
bpf = data->bandsplit[i][k][1].Process(bpf);
}
for (int k = 0; k < order; k++)
{
bpf = data->bandsplit[i][k][2].Process(bpf);
hpf = data->bandsplit[i][k][3].Process(hpf);
}
outbuffer[n * outchannels + i] =
data->band[0]->Process(lpf) * lowGainLin +
data->band[1]->Process(bpf) * midGainLin +
data->band[2]->Process(hpf) * highGainLin;
}
}
if (calcSpectrum)
data->analyzer.AnalyzeOutput(outbuffer, outchannels, length, specDecay);
return UNITY_AUDIODSP_OK;
}
}
| 47.217557 | 215 | 0.580955 | PStewart95 |
16a2cccb2154ef1e951a16cebc467407c7e64620 | 1,409 | cpp | C++ | PlayerLinkedList.cpp | nickcuenca/UNO-An-SFML-Experience | d43beb5ba659958f1fa596a47814379d612f86b7 | [
"MIT"
] | null | null | null | PlayerLinkedList.cpp | nickcuenca/UNO-An-SFML-Experience | d43beb5ba659958f1fa596a47814379d612f86b7 | [
"MIT"
] | null | null | null | PlayerLinkedList.cpp | nickcuenca/UNO-An-SFML-Experience | d43beb5ba659958f1fa596a47814379d612f86b7 | [
"MIT"
] | null | null | null | //
// Created by Nicolas Cuenca on 11/25/2020.
//
#include "PlayerLinkedList.h"
#include <iostream>
PlayerLinkedList::PlayerLinkedList(Player *first) {
this->first = first;
this->currentPlayer = first;
}
Player *PlayerLinkedList::getFirst() const {
return first;
}
Player *PlayerLinkedList::getCurrentPlayer() const {
return currentPlayer;
}
void PlayerLinkedList::setCurrentPlayer(Player *currentPlayer) {
PlayerLinkedList::currentPlayer = currentPlayer;
}
void PlayerLinkedList::reverseList() {
Player *prev = first;
Player *temp;
Player *curr = first->getNextPlayer();
bool visited = false;
while(!visited || prev != first){
temp = curr->getNextPlayer();
curr->setNextPlayer(prev);
prev = curr;
curr = temp;
visited = true;
}
}
void PlayerLinkedList::deletePlayers() {
Player *curr = first;
Player *next;
int count = 0;
bool visited = false;
while(curr != first || !visited ){
count++;
curr = curr->getNextPlayer();
visited = true;
}
int delete_until = 0;
while(delete_until < count){
std::cout << curr->getId() << std::endl;
next = curr->getNextPlayer();
delete curr;
curr = next;
delete_until++;
}
first = nullptr;
currentPlayer = nullptr;
}
| 22.725806 | 65 | 0.58907 | nickcuenca |
16b14d897675e03f2c39adc7e4d30e12f7b2c69c | 25,018 | hpp | C++ | xfinal/websokcet.hpp | maxbad/xfinal | 3e8ba689fc40b896bb2555aebf903672335b8b7b | [
"MIT"
] | 57 | 2019-05-14T09:55:14.000Z | 2022-03-17T07:08:55.000Z | xfinal/websokcet.hpp | maxbad/xfinal | 3e8ba689fc40b896bb2555aebf903672335b8b7b | [
"MIT"
] | 12 | 2019-05-18T02:34:48.000Z | 2021-06-29T15:30:41.000Z | xfinal/websokcet.hpp | maxbad/xfinal | 3e8ba689fc40b896bb2555aebf903672335b8b7b | [
"MIT"
] | 22 | 2019-06-15T10:09:33.000Z | 2022-01-18T09:24:25.000Z | #pragma once
#include <asio.hpp>
#include "http_handler.hpp"
#include <memory>
#include <functional>
#include <string>
#include "uuid.hpp"
#include <unordered_map>
#include "string_view.hpp"
#include "utils.hpp"
#include <memory>
#include "md5.hpp"
#include <queue>
#include <random>
#include <list>
#include "message_handler.hpp"
#include "any.hpp"
namespace xfinal {
struct frame_info {
frame_info() = default;
bool eof;
int opcode;
int mask;
std::uint64_t payload_length;
unsigned char mask_key[4];
};
class websockets;
class websocket;
template<typename T>
void close_ws(websocket& ws);
inline void close_ws_with_notification(websocket& ws);
class websocket_event final {
friend class websockets;
public:
websocket_event() = default;
public:
template<typename Function, typename...Args>
websocket_event& on(std::string const& event_name, Function&& function, Args&& ...args) {
event_call_back_.insert(std::make_pair(event_name, on_help<(sizeof...(Args))>(0, std::forward<Function>(function), std::forward<Args>(args)...)));
return *this;
}
void trigger(std::string const& event_name, websocket& ws) {
auto it = event_call_back_.find(event_name);
if (it != event_call_back_.end()) {
(it->second)(ws);
}
}
private:
template<std::size_t N, typename Function, typename...Args, typename U = typename std::enable_if<std::is_same<number_content<N>, number_content<0>>::value>::type>
auto on_help(int, Function && function, Args && ...args)->decltype(std::bind(std::forward<Function>(function), std::placeholders::_1)) {
return std::bind(std::forward<Function>(function), std::placeholders::_1);
}
template<std::size_t N, typename Function, typename...Args, typename U = typename std::enable_if<!std::is_same<number_content<N>, number_content<0>>::value>::type>
auto on_help(long, Function && function, Args && ...args)->decltype(std::bind(std::forward<Function>(function), std::forward<Args>(args)..., std::placeholders::_1)) {
return std::bind(std::forward<Function>(function), std::forward<Args>(args)..., std::placeholders::_1);
}
private:
std::unordered_map<std::string, std::function<void(websocket&)>> event_call_back_;
};
class websocket_event_map {
friend class websockets;
friend class websocket;
public:
void trigger(const std::string& url, std::string const& event_name, websocket& ws) {//只是读 多线程没有问题
auto it = events_.find(url);
if (it != events_.end()) {
it->second.trigger(event_name, ws);
}
else {
close_ws<void>(ws);
}
}
void add(nonstd::string_view uuid,std::weak_ptr<websocket> weak) {
std::unique_lock<std::mutex> lock(map_mutex_);
websockets_.insert(std::make_pair(uuid, weak.lock()));
}
void remove(nonstd::string_view uuid) {
std::unique_lock<std::mutex> lock(map_mutex_);
auto it = websockets_.find(uuid);
if (it != websockets_.end()) {
websockets_.erase(it);
}
}
~websocket_event_map() {
map_mutex_.lock();
auto copy_sockets = websockets_;
map_mutex_.unlock();
for (auto&& wsocket : copy_sockets) {
close_ws_with_notification(*wsocket.second);
}
}
private:
std::mutex map_mutex_;
std::unordered_map<std::string, websocket_event> events_;
std::unordered_map<nonstd::string_view, std::shared_ptr<websocket>> websockets_;
};
struct send_message {
std::shared_ptr<websocket> websocket_;
std::shared_ptr<std::queue<std::shared_ptr<std::string>>> message_queue;
std::shared_ptr<std::function<void(bool, std::error_code)>> write_callback;
};
inline void send_to_hub(send_message const&);
class websocket final :public std::enable_shared_from_this<websocket> {
friend class websocket_hub;
friend class connection;
template<typename T>
friend void close_ws(websocket& ws);
public:
websocket(websocket_event_map& web, std::string const& url) :websocket_event_manager(web), socket_uid_(uuids::uuid_system_generator{}().to_short_str()), url_(url){
}
public:
std::string const& uuid() {
return socket_uid_;
}
bool is_open() {
return socket_is_open_;
}
asio::ip::tcp::socket& socket() {
return *socket_;
}
std::map<std::string, std::string> key_params () const noexcept {
return decode_url_params_;
}
private:
void move_socket(std::unique_ptr<asio::ip::tcp::socket>&& socket) {
socket_ = std::move(socket);
socket = nullptr;
socket_is_open_ = true;
auto& io = static_cast<asio::io_service&>(socket_->get_executor().context());
wait_read_timer_ = std::move(std::unique_ptr<asio::steady_timer>(new asio::steady_timer(io)));
wait_write_timer_ = std::move(std::unique_ptr<asio::steady_timer>(new asio::steady_timer(io)));
websocket_event_manager.trigger(url_, "open", *this);
start_read();
}
private:
void start_read() {
read_pos_ = 0;
std::memset(frame, 0, sizeof(frame));
std::memset(&frame_info_, 0, sizeof(frame_info_));
auto handler = this->shared_from_this();
start_read_timeout(); //开始开启空连接超时 从当前时间算起
socket_->async_read_some(asio::buffer(&frame[read_pos_], 2), [handler,this](std::error_code const& ec, std::size_t read_size) {
if (ec) {
handler->close();
return;
}
cancel_read_time();
handler->frame_parser();
});
}
public:
nonstd::string_view messages() const {
return message_;
}
unsigned char message_code() const {
return message_opcode;
}
public:
//void write(std::string const& message, unsigned char opcode) {
// auto message_size = message.size();
// auto offset = 0;
// if (message_size < 126) {
// unsigned char frame_head = 128;
// frame_head = frame_head | opcode;
// unsigned char c2 = 0;
// c2 = c2 | ((unsigned char)message_size);
// std::string a_frame;
// a_frame.push_back(frame_head);
// a_frame.push_back(c2);
// a_frame.append(message);
// write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame))));
// }
// else if (message_size >= 126) {
// auto counts = message_size / frame_data_size_;
// if ((message_size % frame_data_size_) != 0) {
// counts++;
// }
// std::size_t read_pos = 0;
// for (std::size_t i = 0; i < counts; ++i) {
// std::int64_t left_size = std::int64_t(message_size) - std::int64_t(frame_data_size_);
// unsigned short write_data_size = (unsigned short)frame_data_size_;
// unsigned char frame_head = 0;
// std::string a_frame;
// if (left_size <= 0) {
// frame_head = 128;
// write_data_size = (unsigned short)message_size;
// //frame_head = frame_head | opcode;
// }
// if (i == 0) {
// frame_head = frame_head | opcode;
// }
// a_frame.push_back(frame_head);
// unsigned char c2 = 0;
// if (write_data_size >= 126) {
// unsigned char tmp_c = 126;
// c2 = c2 | tmp_c;
// a_frame.push_back(c2);
// auto data_length = l_to_netendian(write_data_size);
// a_frame.append(data_length);
// }
// else if (write_data_size < 126) {
// unsigned char tmp_c = (unsigned char)write_data_size;
// c2 = c2 | tmp_c;
// a_frame.push_back(c2);
// }
// a_frame.append(std::string(&message[read_pos], write_data_size));
// read_pos += write_data_size;
// message_size = (std::size_t)left_size;
// write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame))));
// }
// }
// write_frame();
//}
void write(std::string const& message, unsigned char opcode, std::function<void(bool, std::error_code)> const& call_back) {
auto message_size = message.size();
if (message_size == 0) {
return;
}
auto offset = 0;
//std::shared_ptr<std::string> write_data(new std::string());
std::shared_ptr<std::queue<std::shared_ptr<std::string>>> write_queue{ new std::queue<std::shared_ptr<std::string>> {} };
if (message_size < 126) {
unsigned char frame_head = 128;
frame_head = frame_head | opcode;
unsigned char c2 = 0;
c2 = c2 | ((unsigned char)message_size);
std::shared_ptr<std::string> a_frame{new std::string()};
a_frame->push_back(frame_head);
a_frame->push_back(c2);
a_frame->append(message);
write_queue->emplace(a_frame);
//write_data->append(a_frame);
/*write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame))));*/
}
else if (message_size >= 126) {
auto counts = message_size / frame_data_size_;
if ((message_size % frame_data_size_) != 0) {
counts++;
}
std::size_t read_pos = 0;
for (std::size_t i = 0; i < counts; ++i) {
std::int64_t left_size = std::int64_t(message_size) - std::int64_t(frame_data_size_);
unsigned short write_data_size = (unsigned short)frame_data_size_;
unsigned char frame_head = 0;
std::shared_ptr<std::string> a_frame{ new std::string() };
if (left_size <= 0) {
frame_head = 128;
write_data_size = (unsigned short)message_size;
//frame_head = frame_head | opcode;
}
if (i == 0) {
frame_head = frame_head | opcode;
}
a_frame->push_back(frame_head);
unsigned char c2 = 0;
if (write_data_size >= 126) {
unsigned char tmp_c = 126;
c2 = c2 | tmp_c;
a_frame->push_back(c2);
auto data_length = l_to_netendian(write_data_size);
a_frame->append(data_length);
}
else if (write_data_size < 126) {
unsigned char tmp_c = (unsigned char)write_data_size;
c2 = c2 | tmp_c;
a_frame->push_back(c2);
}
a_frame->append(std::string(&message[read_pos], write_data_size));
read_pos += write_data_size;
message_size = (std::size_t)left_size;
write_queue->emplace(a_frame);
//write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame))));
//write_data->append(a_frame);
}
}
/*write_frame();*/
send_message send_msg = { this->shared_from_this() ,write_queue,std::shared_ptr<std::function<void(bool,std::error_code)>>(new std::function<void(bool,std::error_code)>{call_back}) };
send_to_hub(send_msg);
}
public:
void write_string(std::string const& message,std::function<void(bool,std::error_code)> const& call_back = nullptr) {
write(message, 1, call_back);
}
void write_binary(std::string const& message, std::function<void(bool, std::error_code)> const& call_back = nullptr) {
write(message, 2, call_back);
}
template<typename T>
void set_user_data(std::string const& key,std::shared_ptr<T> const& value){
user_data_.emplace(key, value);
}
template<typename T>
T get_user_data(std::string const& key) {
auto it = user_data_.find(key);
if (it != user_data_.end()) {
return nonstd::any_cast<T>(it->second);
}
return nullptr;//error
}
private:
//void write_frame() {
// if (write_frame_queue_.empty()) {
// return;
// }
// while (!write_frame_queue_.empty()) {
// reset_time();
// auto frame = std::move(write_frame_queue_.front());
// write_frame_queue_.pop();
// asio::const_buffer buffers(frame->data(), frame->size());
// std::error_code ingore_ec;
// asio::write(*socket_, buffers, ingore_ec);
// if (ingore_ec) {
// auto clear = std::queue<std::unique_ptr<std::string>>{};
// write_frame_queue_.swap(clear);
// break;
// }
// }
// // asio::async_write(*socket_,buffers, [frame = std::move(frame),handler = this->shared_from_this()](std::error_code const& ec,std::size_t size) {
// // if (ec) {
// // return;
// // }
// // handler->write_frame();
// // });
//}
public:
void start_read_timeout() {
wait_read_timer_->expires_from_now(std::chrono::seconds(wait_read_time_));
auto handler = this->shared_from_this();
wait_read_timer_->async_wait([handler,this](std::error_code const& ec) {
if (ec) {
return;
}
std::stringstream ss;
ss << "websocket id: "<< socket_uid_<< " read no data during " << wait_read_time_ << " seconds";
utils::messageCenter::get().trigger_message(ss.str());
handler->close();
});
}
void cancel_read_time() {
std::error_code ignore;
wait_read_timer_->cancel(ignore);
}
void start_write_timeout() {
wait_write_timer_->expires_from_now(std::chrono::seconds(wait_write_time_));
auto handler = this->shared_from_this();
wait_write_timer_->async_wait([handler,this](std::error_code const& ec) {
if (ec) {
return;
}
std::stringstream ss;
ss << "websocket id: " << socket_uid_ << " couldn't write data during " << wait_write_time_ << " seconds";
utils::messageCenter::get().trigger_message(ss.str());
handler->close();
});
}
void cancel_write_time() {
std::error_code ignore;
wait_write_timer_->cancel(ignore);
}
void ping() {
//ping_pong_timer_->expires_from_now(std::chrono::seconds(ping_pong_time_));
//ping_pong_timer_->async_wait([handler = this->shared_from_this()](std::error_code const& ec) {
// if (ec) {
// return;
// }
// handler->write("", 9);
// handler->reset_time();
// handler->ping();
//});
}
private:
void frame_parser() {
read_pos_ += 2;
unsigned char c = frame[0];
frame_info_.eof = c >> 7;
frame_info_.opcode = c & 15;
if (frame_info_.opcode) {
message_opcode = (unsigned char)frame_info_.opcode;
}
if (frame_info_.opcode == 8) { //关闭连接
close();
return;
}
if (frame_info_.opcode == 9) { //ping
write("", 10,nullptr); //回应客户端心跳
return;
}
if (frame_info_.opcode == 10) { //pong
cancel_read_time();
return;
}
unsigned char c2 = frame[1];
frame_info_.mask = c2 >> 7;
if (frame_info_.mask != 1) { //mask 必须是1
close();
return;
}
c2 = c2 & 127;
if (c2 < 126) { //数据的长度为当前值
frame_info_.payload_length = c2;
handle_payload_length(0);
}
else if (c2 == 126) { //后续2个字节 unsigned
auto handler = this->shared_from_this();
start_read_timeout();
asio::async_read(*socket_, asio::buffer(&frame[read_pos_], 2), [handler,this](std::error_code const& ec, std::size_t read_size) {
if (ec) {
handler->close();
return;
}
cancel_read_time();
handler->handle_payload_length(2);
});
}
else if (c2 == 127) { //后续8个字节 unsigned
auto handler = this->shared_from_this();
start_read_timeout();
asio::async_read(*socket_, asio::buffer(&frame[read_pos_], 8), [handler,this](std::error_code const& ec, std::size_t read_size) {
if (ec) {
handler->close();
return;
}
cancel_read_time();
handler->handle_payload_length(8);
});
}
}
void handle_payload_length(std::size_t read_size) { //if length >126
if (read_size == 2) {
unsigned short tmp = 0;
netendian_to_l(tmp, &(frame[read_pos_]));
frame_info_.payload_length = tmp;
}
else if (read_size == 8) {
std::uint64_t tmp = 0;
netendian_to_l(tmp, &(frame[read_pos_]));
frame_info_.payload_length = tmp;
}
if (frame_info_.mask == 1) { //应该必须等于1
auto handler = this->shared_from_this();
start_read_timeout();
asio::async_read(*socket_, asio::buffer(&frame_info_.mask_key[0], 4), [handler,this](std::error_code const& ec, std::size_t read_size) {
if (ec) {
handler->close();
return;
}
cancel_read_time();
handler->read_data();
});
}
}
void read_data() {
if (frame_info_.payload_length == 0) { //没有数据需要读取
if (frame_info_.eof) {
message_ = std::string();
buffers_.resize(0);
data_current_pos_ = 0;
//数据帧都处理完整 回调
websocket_event_manager.trigger(url_, "message", *this);
}
start_read();
return;
}
expand_buffer(frame_info_.payload_length);
auto handler = this->shared_from_this();
start_read_timeout();
asio::async_read(*socket_, asio::buffer(&buffers_[data_current_pos_], (std::size_t)frame_info_.payload_length), [handler,this](std::error_code const& ec, std::size_t read_size) {
if (ec) {
handler->close();
return;
}
cancel_read_time();
handler->set_current_pos(read_size);
handler->decode_data(read_size);
});
}
void decode_data(std::size_t use_size) {
unsigned char* iter = &(buffers_[data_current_pos_ - use_size]);
for (std::size_t i = 0; i < use_size; ++i) {
auto j = i % 4;
auto mask_key = frame_info_.mask_key[j];
*iter = (*iter) ^ mask_key;
++iter;
}
if (frame_info_.eof) {
message_ = std::string(buffers_.begin(), buffers_.begin() + data_current_pos_);
buffers_.resize(0);
data_current_pos_ = 0;
//数据帧都处理完整 回调
websocket_event_manager.trigger(url_, "message", *this);
}
start_read();
}
void set_current_pos(std::size_t size) {
data_current_pos_ += size;
}
std::size_t left_buffer_size() {
return buffers_.size() - data_current_pos_;
}
void expand_buffer(std::uint64_t need_size) {
auto left_size = left_buffer_size();
if (need_size > left_buffer_size()) {
auto total_size = buffers_.size() + (need_size - left_size);
buffers_.resize((std::size_t)total_size);
}
}
public:
void set_check_alive_time(std::time_t seconds) {
wait_read_time_ = seconds;
}
void set_frame_data_size(std::size_t size) {
frame_data_size_ = size;
}
void set_check_write_alive_time(std::time_t seconds) {
wait_write_time_ = seconds;
}
public:
void close() {
if (socket_is_open_) {
std::error_code ec;
socket_->shutdown(asio::ip::tcp::socket::shutdown_both, ec);
std::error_code ec0;
socket_->close(ec0);
socket_is_open_ = false;
is_writing_ = false;
cancel_read_time();
cancel_write_time();
//ping_pong_timer_->cancel();
websocket_event_manager.trigger(url_, "close", *this); //关闭事件
websocket_event_manager.remove(nonstd::string_view(socket_uid_.data(), socket_uid_.size()));
}
}
void shutdown() {
null_close();
}
private:
void null_close() { //无路由的空连接需要关闭
std::error_code ec;
socket_->shutdown(asio::ip::tcp::socket::shutdown_both, ec);
std::error_code ec0;
socket_->close(ec0);
socket_is_open_ = false;
is_writing_ = false;
cancel_read_time();
cancel_write_time();
//ping_pong_timer_->cancel();
websocket_event_manager.remove(nonstd::string_view(socket_uid_.data(), socket_uid_.size()));
}
private:
std::unique_ptr<asio::ip::tcp::socket> socket_;
websocket_event_map& websocket_event_manager;
std::string socket_uid_;
std::vector<unsigned char> buffers_;
unsigned char frame[10] = {0};
frame_info frame_info_;
std::size_t read_pos_ = 0;
std::size_t data_current_pos_ = 0;
std::string message_;
std::string const url_;
//std::queue<std::unique_ptr<std::string>> write_frame_queue_;
std::size_t frame_data_size_ = 65535;//256
//std::time_t ping_pong_time_ = 30 * 60 * 60;
std::time_t wait_read_time_ = 30 * 60;
std::time_t wait_write_time_ = 30 * 60;
std::unique_ptr<asio::steady_timer> wait_read_timer_;
std::unique_ptr<asio::steady_timer> wait_write_timer_;
//std::unique_ptr<asio::steady_timer> ping_pong_timer_;
unsigned char message_opcode = 0;
std::atomic_bool socket_is_open_{ false };
std::atomic_bool is_writing_{ false };
std::map<std::string, nonstd::any> user_data_;
std::map<std::string, std::string> decode_url_params_;
};
class websocket_hub {
friend class http_router;
public:
static websocket_hub& get() {
static websocket_hub instance;
return instance;
}
public:
void add(send_message const& message) {
std::unique_lock<std::mutex> lock(list_mutex_);
message_list_.emplace_back(message);
lock.unlock();
condtion_.notify_all();
}
private:
void write_ok(std::shared_ptr<websocket> const& websocket) const {
websocket->is_writing_ = false;
}
void close_socket(std::shared_ptr<websocket> const& websocket) const {
websocket->close();
}
private:
void write_frame(std::shared_ptr<websocket> const& websocket, std::shared_ptr<std::queue<std::shared_ptr<std::string>>> const& frame_queue, std::shared_ptr<std::function<void(bool, std::error_code)>> const& call_back) const {
if (frame_queue->empty() || !websocket->is_open()) {
write_ok(websocket);
if (call_back != nullptr && *call_back != nullptr) {
(*call_back)(true, std::error_code{});
}
return;
}
auto a_frame = frame_queue->front();
frame_queue->pop();
auto buff = asio::buffer(a_frame->data(), a_frame->size());
websocket->start_write_timeout();
asio::async_write(*websocket->socket_, buff, [websocket, a_frame, frame_queue, this, call_back](std::error_code const& ec, std::size_t size) {
websocket->cancel_write_time();
if (ec) {
close_socket(websocket);
if (call_back != nullptr && *call_back != nullptr) {
(*call_back)(false, ec);
}
return;
}
write_frame(websocket, frame_queue, call_back);
});
}
private:
void send() {
while (true) {
std::unique_lock<std::mutex> lock(list_mutex_);
condtion_.wait(lock, [this]() {
return message_list_.empty() == false;
});
if (end_thread_ == true) {
return;
}
auto one = message_list_.front();
message_list_.pop_front();
auto websocket = one.websocket_;
auto message = one.message_queue;
auto write_callback = one.write_callback;
if (websocket->socket_is_open_ == true && websocket->is_writing_ == false) {
websocket->is_writing_ = true;
write_frame(websocket, message, write_callback);
}
else if (websocket->socket_is_open_ == true && websocket->is_writing_ == true) {
message_list_.push_back(one);
}
}
}
private:
websocket_hub() = default;
private:
std::mutex list_mutex_;
std::condition_variable condtion_;
std::list<send_message> message_list_;
std::atomic_bool end_thread_{ false };
};
inline void send_to_hub(send_message const& message) {
websocket_hub::get().add(message);
}
template<typename T>
void close_ws(websocket& ws)
{
ws.null_close();
}
void close_ws_with_notification(websocket& ws) {
ws.close();
}
class websockets final :private nocopyable
{
friend class connection;
public:
using event_reg_func = std::function<void(websocket&)>;
public:
std::shared_ptr<websocket> start_webscoket(std::string const& url) { //有多线程竞争
auto ws = std::make_shared<websocket>(websocket_event_map_, url);
ws->set_check_alive_time(websocket_check_read_alive_time_);
ws->set_check_write_alive_time(websocket_check_write_time_);
ws->set_frame_data_size(frame_data_size_);
auto& uuid = ws->uuid();
websocket_event_map_.add(nonstd::string_view{ uuid.data(),uuid.size() }, ws);
return ws;
}
void add_event(std::string const& url, websocket_event const& websocket_event_) {//注册事件 没有多线程竞争
websocket_event_map_.events_.insert(std::make_pair(url, websocket_event_));
}
public:
void set_check_read_alive_time(std::time_t seconds) {
if (seconds <= 0) {
return;
}
websocket_check_read_alive_time_ = seconds;
}
std::time_t get_check_read_alive_time() {
return websocket_check_read_alive_time_;
}
void set_check_write_alive_time(std::time_t seconds) {
if (seconds <= 0) {
return;
}
websocket_check_write_time_ = seconds;
}
std::time_t get_check_write_alive_time() {
return websocket_check_write_time_;
}
void set_frame_data_size(std::size_t size) {
if (size <= 0) {
return;
}
frame_data_size_ = size;
}
std::size_t get_frame_data_size() {
return frame_data_size_;
}
private:
bool is_websocket(request& req) {
using namespace nonstd::string_view_literals;
if (req.method() != "GET"_sv) {
return false;
}
auto connection = req.header("connection");
if (connection.empty() && to_lower(view2str(connection)) != "upgrade") {
return false;
}
auto upgrade = req.header("upgrade");
if (upgrade.empty() && to_lower(view2str(upgrade)) != "websocket") {
return false;
}
auto sec_webSocket_key = req.header("Sec-WebSocket-Key");
if (sec_webSocket_key.empty()) {
return false;
}
auto sec_websocket_version = req.header("Sec-WebSocket-Version");
if (sec_websocket_version.empty()) {
return false;
}
sec_webSocket_key_ = sec_webSocket_key;
sec_websocket_version_ = sec_websocket_version;
return true;
}
void update_to_websocket(response& res) {
res.add_header("Connection", "Upgrade");
res.add_header("Upgrade", "websocket");
auto str = view2str(sec_webSocket_key_) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
auto result = to_base64(to_sha1(str));
res.add_header("Sec-WebSocket-Accept", result);
res.add_header("Sec-WebSocket-Version", view2str(sec_websocket_version_));
res.write_state(http_status::switching_protocols);
}
private:
nonstd::string_view sec_webSocket_key_;
nonstd::string_view sec_websocket_version_;
websocket_event_map websocket_event_map_;
std::time_t websocket_check_read_alive_time_ = 30*60;
std::time_t websocket_check_write_time_ = 30 * 60;
std::size_t frame_data_size_ = 65535;
};
}
| 32.448768 | 227 | 0.668159 | maxbad |
16b1e4f65ab640f5853a1f2350b8fc4edc13ca4c | 11,145 | cpp | C++ | data/602.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/602.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/602.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | int iN, aW, N/*hA*/
,AK8,
Vi0 ,
QCmew, bs,iio1,El
, A3
, bZV
,
BTJ61W
,cAgH2,uL
,
VWN,lsQZ/*K4*/ , nKtYm,/*7R9d*/
HRZ
,tBMY,
ohG
,
cgGKP,xbFv, BBi
, gR ,//j9l
Ek, OD1 ,S6A//Ma
, tvG,Gy, b , tylWc
,/*g*/ wby,gUK,BMc ,
r3,zHKSm ,jL ,Jivf ,
Zcr ,ehp
,LG,
Ue,fly;void f_f0()//vtg
{int n5kter ; volatile int
UuR , fc4IA, vSA
,
HGn ,
//
dTr ,
IQ5, taB ;{volatile int J,FPq, Q
, b9qB
,
OC
, Bu/*a*/;if
/*A*/(
true )
fly=
Bu
+ J
+ FPq/*Yyad*/+
Q +
b9qB+OC
;else
{
int D3//N8i
; volatile int dBTo//
,Xf0
,SaN
,
Dw;return ;//W
{ {{} {
}
}} {volatile int I, Ry; {}
iN =
Ry + I
;/*c*/}for (int /*y*/
i=1;
i< 1 ;++i
){volatile int
CP2
, BX,Zpg,VgFCPuF, eT //Udf
,XJNti; /*eR6*/aW=XJNti //G
+
CP2 +BX
;for(int i=1
;
i<2 ;++i )N =
Zpg+
VgFCPuF
+eT
;
} D3= Dw + dBTo + Xf0 +SaN;/*5*/{{ return ; }}}; if /*iAd*/(true){
volatile int Xs ,T,
P9la
,O ;if(
true) for(int
i=1
;
i< 3;++i)/*t*/{int PAi;volatile int
QHf6,P5x,
qF;PAi= qF+//
QHf6+
P5x
//J
;{volatile int cUVO,qM;
AK8=/*N0P*/ qM +
cUVO ;}for (int i=1;i<4;++i) return ;
{ } }
else{
volatile int fjlLC /*pI*/, TX ; Vi0=TX +fjlLC//DAUF
;
}; {{ }}QCmew
=O
+Xs
+
T +P9la;}else
{int s;
volatile int df,
V
,
Lwiv
,CBu ;
s=CBu
+ df + V
+Lwiv ;for
(int i=1
; //YZ
i< 5;++i)/*1*/return//YK
;{int o7 ; volatile int K //Kg
, jX;; o7 = /*RGu*/jX + K ; } }
}n5kter=taB
+UuR
+fc4IA +
vSA
+HGn+dTr+IQ5 ; return
; for (int
i=1;
i<6
;++i )for (int i=1;i< //ci
7 ;++i
){ volatile int
JO1f,IXqn6, Lu ,oRMf, BYJG;; if//Q4G
( true
)return ;
else bs =BYJG+
JO1f//cw
+
IXqn6+
Lu+oRMf ;
{ { { {
}{}}};//231S
} return
;{
for
(int i=1 ;i<
8
;++i) return ;
{
{//GS
;
} }
{return ;;
{ {
}}} {/**/;return/*x*/ ;
} }{int i8O;volatile int CCFF,ft6S9,fDzsV//x
,uaPIH; return//ZA
;
return ; i8O =uaPIH
+CCFF + ft6S9//j
//Xq
+fDzsV ; } } /*0aG*/
return ;}void f_f1 (){volatile int
Wzx
,
erI5J ,bCD
,
LX/*J*/ ,C , u, Mu ; { { volatile int
/*n*/ U8GU ,
gj
,
h,uC ;
;iio1= uC+ U8GU+gj+
h ; {
{ };for (int
i=1;i<9
;++i )
{ }
} } ; return ;} for(int i=1 /*dwW76*/;i< 10 ;++i
)
{ int/*Y*/ D7
;//29P
volatile int Do ,
DVd ,
TB,/*fBpR*///
/*VF*/ VJB,
cxtax ,deh , VT//M3
,B
,
Qq80
; if(
true)
if(true
)
D7 =Qq80
+ Do +
DVd +TB + VJB ; else{volatile int hBr,
Ry2 ,
hmC3
,M ;/*X*/{return ;}El=M
+
hBr+/*h7pI*/Ry2 +
hmC3;
//5jxQ
{{{}}for(int i=1 ; i<11 ;++i
){
{ }}
} ;
}else A3 /*S*/= cxtax+ deh+ VT/**//*Ao*/+
B
;
{ { return ;
{
;}{
{ };{//Csa
} }} { ;//j
}
}return/**/ ;/*Hzi*/ if
( true) /*4O*/return ; else
{
return ; return ;{{
{
}/**/}{/*8bX*/for(int
i=1/*K1*/ ;i<
12;++i) for (int
i=1
; i<13 ;++i)return ;
} { }
}return ;}}
for(int i=1 ; i<
14 ;++i ) { int tL ; volatile int//Yys
NvW
,a/**/ ,
iIPf , VY
,p ,//dkiH
Oc ;/*FZRx*/ {
volatile int/*1L*/ IhM
,
wcEy ,A3a
, gjjl
; ; bZV
= gjjl+
IhM+
wcEy +
A3a ; {
int xeolf;volatile int Y ,DdPJDs,cfl//w
,PvoQG/*yU*/;
{};return ;xeolf=
PvoQG+
Y+
DdPJDs
//D8P
+ cfl ;
}
} tL/*U*/=Oc
/*tR*/+NvW +a
+ iIPf+
//6y16
VY+p;if/*N5CI*/(/*s2gki*/true )
{ int
rS ;
volatile int
fi4,RGBPw8, re18
, cxD
;rS =
cxD + fi4
+ RGBPw8+ re18;{
return//xlF
;}} else{ /*iBU4HzeB*/{for
(int i=1;/*r5j*/i<
15 ;++i) {}{}}for(int i=1; i<16 ;++i//NFzwR
)
{ {volatile int cr
;
for (int i=1;
i< 17 ;++i )//qfW
/*2I*/{
} BTJ61W=cr
; }
;{ { }
} }{ { /*xTS*/{
}if(
true );else{ //rjg
} }} }{
volatile int lI,iRj
,Qr ,/*8D*/ VctV ;{int
IE1IB ; volatile int
eurp,j,
gx3,
u5O7B ;/*e*/
for(int i=1 ;i<
18 ;++i )if(
true) cAgH2= u5O7B+ eurp; else//7
{ }//Jo
if(
true //h2tyM
)IE1IB=
j+gx3 ;else if (true/*9*/)for
(int i=1
; i< 19;++i )
{
}/*UYP*/ else{ { //aU
}for
(int i=1 ; i<20;++i
) ;
} {/*g*/{//Hh
}}} for(int
i=1
;i<21 ;++i)/*ao*/if (true/*SN*/
)uL = VctV/*UaJc*/
+ lI
+iRj+Qr ;else{ { { for (int i=1 ;/*T*//*i*/i<22
;++i )
;}}
}//T
}}
{;{{{ {
}} }
;
} { int ln123 ;volatile int//q
oaq0
,KX
,ORYNf,W ;
for(int
i=1; i<
23 /*qW7*/;++i )
{int vo ;volatile int n ,FIFGT2;for //Amt
(int
i=1; i<24
;++i){}//RYo
vo
= FIFGT2//h
+n ;}ln123
=W+ oaq0+//w7
KX+
ORYNf
;} {return ;
;//q
}{/*wzy6*/ {int TU;
volatile int g2,//Lf1q
BE ,//H
qiH,j4,je8n ;for
(int i=1;//BUy
i< 25 ;++i
//GT
)
{ }//
TU= je8n+
g2
+
BE +qiH + /*PrLU*/ j4
; }return
;{{
volatile int/*qR1*/
DK
;VWN =
DK; }}
if( true){
{ for
(int i=1 ; i<26
;++i
)
{ volatile int kO ;lsQZ=kO
;return ;} }} else{if(
true
)
{ }else//Yh
{
}//WN2u
{}}//g
;
} }
nKtYm=Mu +Wzx+erI5J +bCD +LX+C+u ;{int WGbb;
volatile int VRFK,WS ,//t
xc
,GFx, Dtcq ;WGbb//YIz
//fZ
=//B
Dtcq
+VRFK//
+WS//Qh
+ xc+GFx ;
return ;/*E3t*/
return ; { volatile int RrX,//iQt
LIqLnz, Yf
;
for(int i=1;
i< 27 ;++i)HRZ =Yf+ RrX +LIqLnz ;;if( true)for(int i=1 ;
i<
28;++i)
{
return ; return ; }else ;}
{ /*uj5*/ { return ;} {volatile int A
, c5/*m*/;if(
true) if
( true
){
{}} else tBMY=c5 +
A /*E*/
;else{ }for
(int
i=1 ; i<
29;++i/*vk*/)
;/*r*/
;};
}{ int
Pd;
volatile int
//JZ
M5bGt ,kDR18U, /*fGp*/
kVH , /*Vl*/ TG
, yla, eAZ;{ { ;} {
int
g38
;volatile int mLYH
,z9B
;
;for(int i=1;
i<30;++i ) if(
true//ID
)/*f4Wr*/if ( true)
{} else
for (int
i=1;i<31 ;++i
)
g38= z9B//6
//
+ mLYH/*5n*/
;
else//
{
}}{ {}{} }}if
(true
) Pd=eAZ+ M5bGt+ kDR18U
;
else
ohG
=kVH +
TG + yla ;} } return ; return ;
}void f_f2() {int
ggsq ;//IPv
volatile int iW8 ,
fC ,
lF9 ,//HZ
ZgT ,ACJ
,
lt3lf//
,id , spd,
BaV4
, Gk ,//62eyaw
gOp, U,
ibD
;
/*0cC*/if (true
/*U7*/) ; else
;cgGKP
=ibD
+
iW8 + fC+ lF9+ZgT + ACJ;ggsq =
lt3lf+//kF
id + spd /*W*/+
BaV4 + Gk +gOp
+U ;;
{{int wV3A
;
volatile int v
,tw
,
Qv1Gj,N6u0
,//p4prhZ
WyD/*g*//*XYc*/; wV3A=WyD +v
+tw +//BAux2
Qv1Gj + N6u0 ;{volatile int IxZX , JPtW,/**/mo
; xbFv
=
mo +IxZX+
JPtW
;
for
(int
i=1
;
//Y24
i<32
;++i
)
{ }if(true)
return ; else for(int i=1;i< 33
;++i) {}} {
{}}
} { ;
{/*GQR*/ return
;
/*E8qy*/ } }{ volatile int /**/ Xq /*6gq7*/
,cG,S ,
tHty;
BBi=/*bxDQ*///rRPPt
tHty
+Xq+
cG
+S ;;for//Rg2nZ
(int
i=1;i<34;++i ){ ;
{
}
{
{}
}}} }return/*MXq*/ ;
} int main() { {volatile int uI , eC
,Up,K0R2
,//UWUM
EPCm//u8p
;{
volatile int WThA
,
bBC ,X21
;for (int //ec
i=1 ;
i<
35 ;++i )/*Q8b*//*c*/if
(true) {/*dv*/int CFl;volatile int Hl
,/**/ wDq ;
CFl//XK5
= wDq/*n*/ +
Hl; }else{ {
} {
int
Njh ;volatile int l3W
;
for(int i=1 ; i<36/*dSj*/;++i ) if(true
){
{}for
(int i=1 ;
i< 37 ;++i
)/*rV*/{
}}//N
else for (int i=1 ;
i<
//wG
38
;++i ){}Njh= l3W
;return 1459539307; }} if (true)//zd
{ {{ }{ ; }}} else
gR
= X21 + WThA+bBC ;
;
}if ( true/**/) { return 450129796
; { int iJGW4
;volatile int EIi
,
CELl ,
cH3t, ebh ,mHL,//S
lgbJF ; for
(int
i=1 ;
i<39 ;++i)Ek= lgbJF +/*qD*/EIi+ CELl;
iJGW4 =cH3t
+ebh +mHL/**/;}{ volatile int Ekwc
, q;
{{} return//WUCIv
77365647;
//fCo
} OD1=q+//8
Ekwc; }{/*IGp*/{
; }} if //ROoq
(/*7*/ true )for (int i=1 ;//2
i<
40//6cY
;++i
)
return 966886858
;
else return 61553154 ;{{{
}{
return 254619342
;}}}for(int
i=1; i< 41/*PK1Hs*/;++i
) ;} else{
int
h5di/*Ti*/;volatile int ka//FF
,Zc8R /*68PHtN*/,XGro; {volatile int
GJ2,tbnaB//Bf
;
S6A= tbnaB+
/*gVNJv*/GJ2
;//Ko
if(true/*pGa6*//*W*/
); else{return 1301871030
;
}
} /*ZVe*/for (int
/*7O*/i=1;i<
42 ;++i//v
)if(true/*CKR*/ )
if(true )h5di=XGro
+/*o*/ka
+Zc8R
;
else return 501854691 ;else /*BaNt*/{for //
(int /*S*/i=1;i<
43;++i ){if ( true) return //cq
834040775/*94OMC*/; else{
{}} { { if(
true){} else {
}} }/*dTu*/ } { ; ;
}//F
}; /*X*/}
tvG =EPCm+ uI+ eC +Up +
/*Q*/K0R2;; }return 493153421
;
{ { {/*oIE*/{
if(true){ } else //pmx
{
}/*OfV*/ //2W
}{ ; } }
//t
for//Pfe
(int i=1
;i<44/*M*/;++i
) { volatile int qC2 ,X7, jYR
, sm ,F9VH/*Tp*/
;Gy
= F9VH+qC2
; { {
}
;
}
b =
X7+jYR+ sm/*YqhC*/;/*qV*/}
{
{
{}
}
{ }} ;
} /*Im*/{{volatile int tws, Uf,PrHRv;{{}/*g*/}
;
tylWc=PrHRv + tws
+/*Gycm*/Uf; } {
;
if(true )//D48
{ int
QB;//Aw
volatile int eL3,
Xp;
return 1486057255;
{//
} { }
return
724636532 ; QB =Xp
+ eL3; } else
{
volatile int dp/*LW*/ , GjQWFe/*Qp*/
;wby=
GjQWFe+dp
; }}return 1870620381 ;
}
if (true){ for
(int i=1 ;i<45
;++i
) //h
;{
{/*TD*/ {return 307491052 ;/*SoA*/} } {
} } for
(int
i=1
;i<46;++i
)
{
{
}
{ volatile int d
,FW ;
gUK
=FW
+
d ;
{
int OJD;
volatile int
c
;
; if (true
){} else for(int i=1 ; i<
47
;++i//cAs
)
OJD =c
;}}}if(true)if (
true )
{int keT ;volatile int uJ,
//9e
hw,x,xm ;
{{} } { ;//JwS
{{}; } }for(int //L
i=1 ; i<48
;++i)/*S*/keT=xm+/*jt*/ uJ+hw
+x
;
{volatile int Czf//9CtW
,
//J
PQJ
;
BMc=PQJ
+ Czf
; }}else {
volatile int nC5 ,
l
,UXFnU ;
if
(true) {int xNS;volatile int q3 , tlG,
DRX;xNS
= DRX
+q3 +tlG/*2V*/
;
}
else {;
}r3
//dL
= UXFnU +nC5+ l ;
}else
for (int i=1 ;i< 49 ;++i ){{ }
{volatile int vDrLW,Ag//T
, Lmf ;zHKSm=Lmf +vDrLW +Ag
;
}}}//6A
else { for /*3r8*/(int i=1/*d*/;i< 50;++i )
{ for
(int i=1
; i< 51 ;++i );} return 26605759
;{if/**/
(
true
){ int D6S ;volatile int s2J, Nd; D6S =
Nd+ s2J ;/*eRQ4*/} else {
{}} {}
/*QSFr*/{/*pf*/{
}//OSkg
/*V3H*/}}} } {int irM6
; volatile int
QO
,
vLi3 ,TwH,
w, dMZ7o/*mN0*/;
{ {//KvK
int//
WL ;
volatile int
tAl,cT, bTy;
{{} return 1839056157;}
{ /**/}WL = bTy
+tAl +cT ;}for(int i=1
; i<52 ;++i ) { {} //eI
{for(int
i=1 ;
i< 53 ;++i){ for(int
/*D*/i=1
; i<
54
;++i)
{}
} for
(int /*bR*/i=1 ; i<55;++i //9y
/**/)
{}
}} {
//N3j
if( true) {}/*JT*/ else{ }
return 699596162
;{ volatile int //Ot
qTjy/**/,S9v ,FsT , lh;
jL
= lh
+qTjy ; if
(true){/*vZ*/}
else for (int i=1 ;
i<
56;++i
) Jivf//g3qjW
=S9v + FsT
;
}{
{}{
}} }}; irM6
= dMZ7o +
QO+ vLi3+TwH+ w
; }
{int R ;/*63*/volatile int Z ,/*z8*/
b9G,wR0
, kV, Gg9O
;
/**/if(
/*UaN*/ true) {volatile int jpR /**/ ,CqK,
PMxc,/*ncX*/ Ow ;
{ { {for (int
i=1;
i<
57 ;++i){ } }} {
if( true)
{}
else {}
}}
Zcr=Ow
+
jpR +
CqK + PMxc
; } else for (int i=1;i<58;++i )R //a
= Gg9O +Z
+
b9G +
wR0
//ZYO
+kV ; {{ ;} //c0
for(int i=1;i<
59
;++i )
{ for
(int /*DS*/i=1 ;
i<
//m
60 ;++i
);
;//MM
}}//
for(int i=1 ;i< 61/**/;++i
);
{ if (
true)for//G6
(int i=1;
i<
62;++i
/*Vt*/) {{int aP7
;volatile int yXuqh ,fg3;
{ }
; {
{} }aP7
= fg3+yXuqh; }{if/*cddz*/ (
true); else for //M6vE
(int
i=1 ;i<
63;++i
){{ }}
} }else //I
{ volatile int upr
,vx,
n7w
/*PfXG*/ ,
eve,r ;if(true
)if
( //V
true
) {{} }
else ehp=
r+
upr +
vx ; else LG
=
n7w+eve ;{}}
if ( true)/*2mtV*/{ {
return
1669666163 ;
//ZSt
} } else
{ volatile int ZO,
SLUs ;/*asJ*/
//
if
( true
)Ue
//vB
=SLUs+ ZO; else if (true//uI
);
else ;}};if (true) {for(int
i=1 ;i< 64 ;++i) {return
231352685 //2
;//rj0sm
}//q
{
{/*4*/
}
}}else return 1008721898 ; }
} | 11.012846 | 74 | 0.468282 | TianyiChen |
16be2152cdfa7abcabc12b5ec3e507c6d0cd22ec | 15 | cpp | C++ | engine/src/id.cpp | unyankee/OutterSpace | a0746dd8d32b33be36f6972ace53f7b71f09d470 | [
"MIT"
] | null | null | null | engine/src/id.cpp | unyankee/OutterSpace | a0746dd8d32b33be36f6972ace53f7b71f09d470 | [
"MIT"
] | null | null | null | engine/src/id.cpp | unyankee/OutterSpace | a0746dd8d32b33be36f6972ace53f7b71f09d470 | [
"MIT"
] | null | null | null | #include <id.h> | 15 | 15 | 0.666667 | unyankee |
16bf11743144e64c08f049815176ed52f37aa485 | 2,801 | cc | C++ | code/render/graphics/globallightentity.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/render/graphics/globallightentity.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/render/graphics/globallightentity.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
// globallightentity.cc
// (C) 2007 Radon Labs GmbH
// (C) 2013-2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "graphics/globallightentity.h"
#include "lighting/shadowserver.h"
#include "lighting/lightserver.h"
namespace Graphics
{
__ImplementClass(Graphics::GlobalLightEntity, 'GLBE', Graphics::AbstractLightEntity);
using namespace Math;
using namespace Messaging;
using namespace Lighting;
//------------------------------------------------------------------------------
/**
*/
GlobalLightEntity::GlobalLightEntity() :
backLightColor(0.0f, 0.0f, 0.0f, 0.0f),
ambientLightColor(0.0f, 0.0f, 0.0f, 0.0f),
lightDir(0.0f, 0.0f, -1.0f),
backLightOffset(0.3)
{
this->SetLightType(LightType::Global);
this->SetAlwaysVisible(true);
}
//------------------------------------------------------------------------------
/**
*/
ClipStatus::Type
GlobalLightEntity::ComputeClipStatus(const Math::bbox& box)
{
// since we are essentially a directional light, everything is visible,
// we depend on the visibility detection code in the Cell class to
// only create light links for objects that are actually visible
return ClipStatus::Inside;
}
//------------------------------------------------------------------------------
/**
*/
void
GlobalLightEntity::OnTransformChanged()
{
AbstractLightEntity::OnTransformChanged();
// if the light transforms then all shadows must be updated
this->castShadowsThisFrame = this->castShadows;
// extract the light's direction from the transformation matrix
this->lightDir = float4::normalize(this->transform.getrow2());
// calculate shadow transform by doing a simple lookat
this->shadowTransform = matrix44::lookatrh(point(0,0,0), this->lightDir, vector::upvec());
// extend shadow casting frustum so that the global light resolves everything within the shadow casting range
this->transform.set_xaxis(float4::normalize(this->transform.get_xaxis()) * 1000000.0f);
this->transform.set_yaxis(float4::normalize(this->transform.get_yaxis()) * 1000000.0f);
this->transform.set_zaxis(float4::normalize(this->transform.get_zaxis()) * 1000000.0f);
}
//------------------------------------------------------------------------------
/**
*/
void
GlobalLightEntity::OnRenderDebug()
{
// TODO: render shadow frustum?
}
//------------------------------------------------------------------------------
/**
Handle a message, override this method accordingly in subclasses!
*/
void
GlobalLightEntity::HandleMessage(const Ptr<Message>& msg)
{
__Dispatch(GlobalLightEntity, this, msg);
}
} // namespace Graphics
| 31.829545 | 113 | 0.586219 | gscept |
16bfe033e69ed0ed010d0295a66779979ccf8ca1 | 12,795 | cpp | C++ | Chikara/Main.cpp | Chrono-byte/Chikara | 14801ff7de5f40201c542153f1021be9968074ff | [
"Apache-2.0"
] | 11 | 2020-05-25T06:03:57.000Z | 2021-08-12T16:34:11.000Z | Chikara/Main.cpp | Chrono-byte/Chikara | 14801ff7de5f40201c542153f1021be9968074ff | [
"Apache-2.0"
] | 6 | 2020-08-04T04:06:21.000Z | 2022-02-07T02:46:13.000Z | Chikara/Main.cpp | Chrono-byte/Chikara | 14801ff7de5f40201c542153f1021be9968074ff | [
"Apache-2.0"
] | 1 | 2020-09-22T19:16:59.000Z | 2020-09-22T19:16:59.000Z | #include "Main.h"
#include "KDMAPI.h"
#include "OmniMIDI.h"
#include "Config.h"
#include "Utils.h"
#include "Platform.h"
#include <inttypes.h>
#include <fmt/locale.h>
#include <fmt/format.h>
// msvc complains about narrowing conversion with bin2c
#pragma warning(push)
#pragma warning(disable : 4838)
#pragma warning(disable : 4309)
#include "Shaders/notes_f.h"
#include "Shaders/notes_v.h"
#include "Shaders/notes_g.h"
#pragma warning(pop)
Renderer r;
GlobalTime* gtime;
Midi* midi;
MidiTrack* trk;
Vertex instanced_quad[]
{
{ {0,1}, {0,1} },
{ {1,1}, {1,1} },
{ {1,0}, {1,0} },
{ {0,0}, {0,0} },
};
uint32_t instanced_quad_indis[] = {
0, 1, 2,
2, 3, 0,
};
void Main::run(int argc, wchar_t** argv)
{
std::wstring filename;
if(argc < 2) {
filename = Platform::OpenMIDIFileDialog();
if(filename.empty())
return;
}
else {
filename = argv[1];
}
auto config_path = Config::GetConfigPath();
Config::GetConfig().Load(config_path);
InitializeKDMAPIStream();
SetConsoleOutputCP(65001); // utf-8
fmt::print("Loading {}\n", Utils::wstringToUtf8(Utils::GetFileName(filename)));
#ifdef RELEASE
try
{
std::cout << "RPC Enabled: " << Config::GetConfig().discord_rpc << std::endl;
if(Config::GetConfig().discord_rpc) Utils::InitDiscord();
}
catch(const std::exception& e)
{
std::cout << "RPC Enabled: 0 (Discord Not Installed)" << std::endl;
Config::GetConfig().discord_rpc = false;
}
#else
std::cout << "RPC Enabled: 0 (Chikara is compiled as debug)" << std::endl;
#endif
try
{
if(Config::GetConfig().loader_buffer < 0)
{
Config::GetConfig().loader_buffer = 0;
Config::GetConfig().Save();
}
}
catch(const std::exception& e)
{
//Config didn't exist, expecting it to just be 10;
}
wchar_t* filename_temp = _wcsdup(filename.c_str());
midi = new Midi(filename_temp);
r.note_event_buffer = midi->note_event_buffer;
r.midi_renderer_time = &midi->renderer_time;
r.note_stacks.resize(midi->track_count * 16);
r.note_count = &midi->note_count;
r.notes_played = &midi->notes_played;
r.song_len = midi->song_len;
r.marker = &midi->marker;
r.colors = midi->colors;
r.createColors();
midi->colors.clear(); //free up the colors array in color since we no longer need it
// playback thread spawned in mainLoop to ensure it's synced with render
//printf(file_name);
midi->SpawnLoaderThread();
initWindow(filename); //Setup everything for the window
initVulkan(); //Setup everything for Vulkan
gt = new GlobalTime(Config::GetConfig().start_delay, midi->note_count, filename);
gtime = gt;
mainLoop(filename); //The main loop for the application
cleanup(); //Cleanup everything because we closed the application
free(filename_temp);
}
std::wstring midi_file_name;
long long start_time;
long long end_time;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
exit(1);
if(key == GLFW_KEY_SPACE && action == GLFW_PRESS)
{
r.paused = !r.paused;
r.paused ? gtime->pause() : gtime->resume();
}
if(key == GLFW_KEY_RIGHT && action == GLFW_PRESS && mods != GLFW_MOD_SHIFT)
gtime->skipForward(1);
if(key == GLFW_KEY_RIGHT && action == GLFW_PRESS && mods == GLFW_MOD_SHIFT)
gtime->skipForward(5);
}
void Main::initWindow(std::wstring midi)
{
midi_file_name = midi;
glfwInit(); //Init glfw
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); //Set the glfw api to GLFW_NO_API because we are using Vulkan
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); //Change the ability to resize the window
if(Config::GetConfig().transparent)
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE); //Window Transparancy
auto filename = Utils::wstringToUtf8(Utils::GetFileName(midi));
int count;
int monitorX, monitorY;
GLFWmonitor** monitors = glfwGetMonitors(&count);
glfwGetMonitorPos(monitors[0], &monitorX, &monitorY);
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
if(Config::GetConfig().fullscreen)
{
r.window = glfwCreateWindow(mode->width, mode->height, std::string("Chikara | " + filename).c_str(), glfwGetPrimaryMonitor(), nullptr); //Now we create the window
r.window_width = mode->width;
r.window_height = mode->height;
}
else {
r.window = glfwCreateWindow(default_width, default_height, std::string("Chikara | " + filename).c_str(), nullptr, nullptr); //Now we create the window
glfwSetWindowPos(r.window, monitorX + (mode->width - default_width) / 2, monitorY + (mode->height - default_height) / 2);
}
glfwSetWindowUserPointer(r.window, &r);
glfwSetFramebufferSizeCallback(r.window, r.framebufferResizeCallback);
glfwSetKeyCallback(r.window, key_callback);
}
void Main::initVulkan()
{
r.createInstance(); //Create the Vulkan Instance
r.setupDebugMessenger();
r.createSurface();
r.setupDevice(); //Pick the physical device
r.createLogicalDevice(); //Create the logical device to use
r.createSwapChain();
r.createImageViews();
r.createRenderPass(&r.note_render_pass, true, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
r.createRenderPass(&r.additional_note_render_pass, true, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
r.createDescriptorSetLayout();
r.createGraphicsPipeline(notes_v, notes_v_length, notes_f, notes_f_length, notes_g, notes_g_length, r.note_render_pass, &r.note_pipeline_layout, &r.note_pipeline);
r.createRenderPass(&r.imgui_render_pass, false, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
r.createPipelineCache();
r.createCommandPool(&r.cmd_pool, 0);
r.createCommandPool(&r.imgui_cmd_pool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT);
r.createDepthResources();
r.createFramebuffers();
r.createImGuiFramebuffers();
//r.createTextureImage();
//r.createTextureImageView();
//r.createTextureSampler();
//r.createVertexBuffer(instanced_quad, 4, r.note_vertex_buffer, r.note_vertex_buffer_mem);
//r.createInstanceBuffer(sizeof(InstanceData) * MAX_NOTES, r.note_instance_buffer, r.note_instance_buffer_mem);
//r.createIndexBuffer(instanced_quad_indis, 6, r.note_index_buffer, r.note_index_buffer_mem);
r.createNoteDataBuffer(sizeof(NoteData) * MAX_NOTES, r.note_buffer, r.note_buffer_mem);
r.createUniformBuffers(r.uniform_buffers, r.uniform_buffers_mem);
r.createDescriptorPool();
r.createImGuiDescriptorPool();
r.createDescriptorSets();
r.createCommandBuffers();
r.createImGuiCommandBuffers();
r.createSyncObjects();
r.initImGui();
r.PrepareKeyboard();
}
auto timer = std::chrono::steady_clock();
auto last_time = timer.now();
uint64_t frame_counter = 0;
uint64_t fps = 0;
void Main::mainLoop(std::wstring midi_name)
{
midi->SpawnPlaybackThread(gt, Config::GetConfig().start_delay);
/*
char buffer[256];
sprintf(buffer, "Note Count: %s", fmt::format(std::locale(""), "{:n}", midi->note_count));
*/
#ifdef RELEASE
if(Config::GetConfig().discord_rpc && midi) {
auto rpc_text = fmt::format(std::locale(""), "Note Count: {:n}", midi->note_count);
Utils::UpdatePresence(rpc_text.c_str(), "Playing: ", Utils::wstringToUtf8(Utils::GetFileName(midi_name)));
}
#endif
while(!glfwWindowShouldClose(r.window))
{
r.pre_time = Config::GetConfig().note_speed;
//float time;
//auto current_time = std::chrono::high_resolution_clock::now();
//time = std::chrono::duration<float, std::chrono::seconds::period>(current_time - start_time).count();
r.midi_renderer_time->store(gt->getTime() + r.pre_time);
glfwPollEvents();
r.drawFrame(gt);
}
vkDeviceWaitIdle(r.device);
TerminateKDMAPIStream();
}
#pragma region Recreating the swap chain
void Main::cleanupSwapChain()
{
vkDestroyImageView(r.device, r.depth_img_view, nullptr);
vkDestroyImage(r.device, r.depth_img, nullptr);
vkFreeMemory(r.device, r.depth_img_mem, nullptr);
for(size_t i = 0; i < r.swap_chain_framebuffers.size(); i++)
vkDestroyFramebuffer(r.device, r.swap_chain_framebuffers[i], nullptr);
for(size_t i = 0; i < r.imgui_swap_chain_framebuffers.size(); i++)
vkDestroyFramebuffer(r.device, r.imgui_swap_chain_framebuffers[i], nullptr);
vkFreeCommandBuffers(r.device, r.cmd_pool, static_cast<uint32_t>(r.cmd_buffers.size()), r.cmd_buffers.data());
vkFreeCommandBuffers(r.device, r.imgui_cmd_pool, static_cast<uint32_t>(r.imgui_cmd_buffers.size()), r.imgui_cmd_buffers.data());
vkDestroyPipeline(r.device, r.note_pipeline, nullptr);
vkDestroyPipelineLayout(r.device, r.note_pipeline_layout, nullptr);
vkDestroyRenderPass(r.device, r.note_render_pass, nullptr);
vkDestroyRenderPass(r.device, r.additional_note_render_pass, nullptr);
vkDestroyRenderPass(r.device, r.imgui_render_pass, nullptr);
for(size_t i = 0; i < r.swap_chain_img_views.size(); i++)
{
vkDestroyImageView(r.device, r.swap_chain_img_views[i], nullptr);
}
vkDestroySwapchainKHR(r.device, r.swap_chain, nullptr);
for(size_t i = 0; i < r.swap_chain_imgs.size(); i++)
{
vkDestroyBuffer(r.device, r.uniform_buffers[i], nullptr);
vkFreeMemory(r.device, r.uniform_buffers_mem[i], nullptr);
}
vkDestroyDescriptorPool(r.device, r.descriptor_pool, nullptr);
vkDestroyDescriptorPool(r.device, r.imgui_descriptor_pool, nullptr);
}
void Main::recreateSwapChain()
{
int width = 0, height = 0;
glfwGetFramebufferSize(r.window, &width, &height);
while(width == 0 || height == 0)
{
glfwGetFramebufferSize(r.window, &width, &height);
glfwWaitEvents();
}
r.window_width = width;
r.window_height = height;
vkDeviceWaitIdle(r.device);
r.destroyImGui();
cleanupSwapChain();
r.createSwapChain();
r.createImageViews();
r.createRenderPass(&r.note_render_pass, true, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
r.createRenderPass(&r.additional_note_render_pass, true, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
r.createGraphicsPipeline(notes_v, notes_v_length, notes_f, notes_f_length, notes_g, notes_g_length, r.note_render_pass, &r.note_pipeline_layout, &r.note_pipeline);
r.createRenderPass(&r.imgui_render_pass, false, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
r.createDepthResources();
r.createFramebuffers();
r.createImGuiFramebuffers();
r.createUniformBuffers(r.uniform_buffers, r.uniform_buffers_mem);
r.createDescriptorPool();
r.createImGuiDescriptorPool();
r.createDescriptorSets();
r.createCommandBuffers();
r.createImGuiCommandBuffers();
r.initImGui();
r.PrepareKeyboard();
}
#pragma endregion
#pragma region Cleanup
void Main::cleanup()
{
if(enable_validation_layers)
{
r.DestroyDebugUtilsMessengerEXT(r.inst, r.debug_msg, nullptr);
}
r.destroyImGui();
cleanupSwapChain();
//vkDestroySampler(r.device, r.tex_sampler, nullptr);
vkDestroyImageView(r.device, r.tex_img_view, nullptr);
vkDestroyImage(r.device, r.tex_img, nullptr);
vkFreeMemory(r.device, r.tex_img_mem, nullptr);
vkDestroyDescriptorSetLayout(r.device, r.descriptor_set_layout, nullptr);
vkDestroyBuffer(r.device, r.note_buffer, nullptr);
vkFreeMemory(r.device, r.note_buffer_mem, nullptr);
for(size_t i = 0; i < max_frames_in_flight; i++)
{
vkDestroySemaphore(r.device, r.render_fin_semaphore[i], nullptr);
vkDestroySemaphore(r.device, r.img_available_semaphore[i], nullptr);
vkDestroyFence(r.device, r.in_flight_fences[i], nullptr);
}
vkDestroyCommandPool(r.device, r.cmd_pool, nullptr);
vkDestroyCommandPool(r.device, r.imgui_cmd_pool, nullptr);
vkDestroyPipelineCache(r.device, r.pipeline_cache, nullptr);
vkDestroyDevice(r.device, nullptr);
vkDestroySurfaceKHR(r.inst, r.surface, nullptr);
vkDestroyInstance(r.inst, nullptr);
glfwDestroyWindow(r.window);
glfwTerminate(); //Now we terminate
#ifdef RELEASE
Utils::DestroyDiscord();
#endif
}
#pragma endregion
int wmain(int argc, wchar_t** argv)
{
Main app; //Get the main class and call it app
try
{
app.run(argc, argv); //Startup the application
}
catch(const std::exception& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE; //Something broke...
}
return EXIT_SUCCESS;
} | 33.849206 | 170 | 0.733255 | Chrono-byte |
16cacb7673707af23c92c9853e93c16ce0e93ddd | 5,874 | cpp | C++ | src/Htfe/HtfeFile.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 13 | 2015-02-26T22:46:18.000Z | 2020-03-24T11:53:06.000Z | src/Htfe/HtfeFile.cpp | PacificBiosciences/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 5 | 2016-02-25T17:08:19.000Z | 2018-01-20T15:24:36.000Z | src/Htfe/HtfeFile.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 12 | 2015-04-13T21:39:54.000Z | 2021-01-15T01:00:13.000Z | /* Copyright (c) 2015 Convey Computer Corporation
*
* This file is part of the OpenHT toolset located at:
*
* https://github.com/TonyBrewer/OpenHT
*
* Use and distribution licensed under the BSD 3-clause license.
* See the LICENSE file for the complete license text.
*/
// HtFile.cpp: implementation of the CHtFile class.
//
//////////////////////////////////////////////////////////////////////
#include "Htfe.h"
#include "HtfeErrorMsg.h"
#include "HtfeFile.h"
#ifndef _MSC_VER
#include <sys/types.h>
#include <unistd.h>
#define _lseek lseek
#define _read read
#define _unlink unlink
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CHtFile::CHtFile()
{
m_indentLevel = 0;
m_bNewLine = false;
m_bDoNotSplitLine = false;
m_dstFp = 0;
m_lineCol = 0;
m_lineNum = 1;
m_maxLineCol = 70;
m_bLineBuffering = false;
m_lineListIdx = 0;
m_bVarInit = false;
m_bInTask = false;
}
bool
CHtFile::Open(const string &outputFileName, char *pMode)
{
m_fileName = outputFileName;
m_dstFp = fopen(outputFileName.c_str(), pMode);
int lastSlash = outputFileName.find_last_of("/\\");
if (lastSlash > 0)
m_folder = outputFileName.substr(0,lastSlash);
else
m_folder = ".";
return m_dstFp != 0;
}
void CHtFile::Close() {
Assert(m_dstFp);
fclose(m_dstFp);
m_dstFp = 0;
}
void CHtFile::Delete() {
if (m_dstFp) {
fclose(m_dstFp);
_unlink(m_fileName.c_str());
}
m_dstFp = 0;
}
void
CHtFile::Dup(int srcFd, int startOffset, int endOffset)
{
int origOffset = _lseek(srcFd, 0, SEEK_CUR);
_lseek(srcFd, startOffset, SEEK_SET);
char buffer[4096];
for (int offset = startOffset; offset < endOffset; ) {
int readSize = endOffset - offset;
if (readSize > 4096)
readSize = 4096;
int readBytes = _read(srcFd, buffer, readSize);
if (readBytes <= 0)
break;
fwrite(buffer, 1, readBytes, m_dstFp);
offset += readBytes;
}
_lseek(srcFd, origOffset, SEEK_SET);
}
void CHtFile::PrintVarInit(const char *format, ...)
{
int savedIndentLevel = GetIndentLevel();
SetIndentLevel(m_varInitIndentLevel);
m_bVarInit = true;
va_list marker;
va_start(marker, format); /* Initialize variable arguments. */
Print_(format, marker);
m_bVarInit = false;
SetIndentLevel(savedIndentLevel);
}
int CHtFile::Print(const char *format, ...)
{
va_list marker;
va_start(marker, format); /* Initialize variable arguments. */
return Print_(format, marker);
}
int CHtFile::Print_(const char *format, va_list marker)
{
if (m_indentLevel == -1) {
int r = vfprintf(m_dstFp, format, marker);
for (const char *pCh = format; *pCh; pCh += 1)
if (*pCh == '\n')
m_lineNum += 1;
return r;
} else {
char buf[4096];
int r = vsprintf(buf, format, marker);
// a newline in the input forces a new line in the output
// the formated string can be split where a space exists or at the boundary
bool bEol = false;
char *pStrStart = buf;
for (;;) {
if (m_bNewLine) {
int level = m_indentLevel;
for (int i = 0; i < level; i += 1)
Putc(' ');
m_lineCol = m_indentLevel;
m_bNewLine = false;
}
// find next string terminated by a ' ', '\t', '\n' or '\0'
char *pStrEnd = pStrStart;
if (pStrStart[0] == '/' && pStrStart[1] == '/') {
// comments must be handled together to avoid wrapping to a newline
while (*pStrEnd != '\n' && *pStrEnd != '\r' && *pStrEnd != '\0')
pStrEnd++;
} else {
while (*pStrEnd != ' ' && *pStrEnd != '\t' && *pStrEnd != '\n' && *pStrEnd != '\r' && *pStrEnd != '\0')
pStrEnd++;
}
m_bNewLine = *pStrEnd == '\n' || *pStrEnd == '\r';
bEol = *pStrEnd == '\0';
bool bSpace = *pStrEnd == ' ';
bool bTab = *pStrEnd == '\t';
*pStrEnd = '\0';
// check if string can fit in current line
int strLen = strlen(pStrStart);
if (!m_bDoNotSplitLine && m_indentLevel < m_lineCol && m_lineCol + strLen > m_maxLineCol) {
// string does not fit, start new line
Putc('\n');
m_lineNum += 1;
for (int i = 0; i < m_indentLevel+1; i += 1)
Putc(' ');
m_lineCol = m_indentLevel+1;
}
if (strLen > 0)
Puts(pStrStart);
m_lineCol += strLen;
if (!m_bNewLine && bSpace) Putc(' ');
if (!m_bNewLine && bTab) Putc('\t');
pStrStart = pStrEnd+1;
if (m_bNewLine) {
Putc('\n');
m_lineNum += 1;
}
while (!bEol && *pStrStart == '\n') {
pStrStart += 1;
Putc('\n');
m_lineNum += 1;
}
if (bEol || *pStrStart == '\0') {
m_bDoNotSplitLine = false;
return r;
}
}
}
}
void CHtFile::Putc(char ch)
{
if (m_bVarInit) {
m_varInitBuffer += ch;
if (ch == '\n') {
m_varInitLineList.push_back(m_varInitBuffer);
m_varInitBuffer.clear();
}
} else if (m_bLineBuffering) {
m_lineBuffer += ch;
if (ch == '\n') {
m_lineList[m_lineListIdx].push_back(m_lineBuffer);
m_lineBuffer.clear();
}
} else
fputc(ch, m_dstFp);
}
void CHtFile::Puts(char * pStr)
{
if (m_bVarInit)
m_varInitBuffer += pStr;
else if (m_bLineBuffering)
m_lineBuffer += pStr;
else
fputs(pStr, m_dstFp);
}
void CHtFile::FlushLineBuffer()
{
for (size_t i = 0; i < m_lineList[m_lineListIdx].size(); i += 1)
fputs(m_lineList[m_lineListIdx][i].c_str(), m_dstFp);
m_lineList[m_lineListIdx].clear();
}
void CHtFile::VarInitClose()
{
if (m_bInTask) {
// first insert task's temp var declarations
m_lineList[m_varInitListIdx].insert(m_lineList[m_varInitListIdx].begin() + m_varInitLineIdx,
m_lineList[2].begin(), m_lineList[2].end());
m_varInitLineIdx += m_lineList[2].size();
m_lineList[2].clear();
// SetLineBuffer(0);
}
m_lineList[m_varInitListIdx].insert(m_lineList[m_varInitListIdx].begin() + m_varInitLineIdx,
m_varInitLineList.begin(), m_varInitLineList.end());
m_varInitLineList.clear();
}
| 23.217391 | 107 | 0.617637 | TonyBrewer |
16cc18d3f91a15da1a0a85da670a20ce14f8fb68 | 2,668 | cpp | C++ | speedcc/stage/SCBehaviorSystem.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | 7 | 2018-03-10T02:01:49.000Z | 2021-09-14T15:42:10.000Z | speedcc/stage/SCBehaviorSystem.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | null | null | null | speedcc/stage/SCBehaviorSystem.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | 1 | 2018-03-10T02:01:58.000Z | 2018-03-10T02:01:58.000Z | /****************************************************************************
Copyright (c) 2017-2020 Kevin Wu (Wu Feng)
github: http://github.com/kevinwu1024
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
http://opensource.org/licenses/MIT
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "SCBehaviorSystem.h"
#include "../cocos/SCViewController.h"
#include "../system/SCSystem.h"
NAMESPACE_SPEEDCC_BEGIN
///--------- SCBehaviorPurchase
SCBehaviorPurchase::SCBehaviorPurchase(const int nFeatureID,SCStore::ResultFunc_t resultFunc)
:_nFeatureID(nFeatureID)
{
this->setResultFunc(resultFunc);
}
SCBehaviorPurchase::~SCBehaviorPurchase()
{
SCStore::getInstance()->setPurchaseResultFunc(nullptr);
}
void SCBehaviorPurchase::setResultFunc(const SCStore::ResultFunc_t& func)
{
_resultFunc = [func](int nFeatureID,SCStore::EResultType result,void* pInfo)
{
auto ptrCtrl = SCViewNav()->getCurrentController();
ptrCtrl->showBlackMask(false);
ptrCtrl->setTouchAcceptable(true);
if(func!=nullptr)
{
func(nFeatureID,result,pInfo);
}
};
}
void SCBehaviorPurchase::execute(const SCDictionary& par)
{
auto ptrCtrl = SCViewNav()->getCurrentController();
ptrCtrl->showBlackMask(true);
ptrCtrl->setTouchAcceptable(false);
SCStore::getInstance()->purchaseFeature(_nFeatureID,_resultFunc);
}
///---------- SCBehaviorRequestProduct
SCBehaviorRequestProduct::~SCBehaviorRequestProduct()
{
SCStore::getInstance()->setRequestProductResultFunc(nullptr);
}
void SCBehaviorRequestProduct::execute(const SCDictionary& par)
{
SCStore::getInstance()->requestProductInfo(_resultFunc);
}
///----------- SCBehaviorRestorePurchased
SCBehaviorRestorePurchased::~SCBehaviorRestorePurchased()
{
SCStore::getInstance()->setRestoreResultFunc(nullptr);
}
void SCBehaviorRestorePurchased::execute(const SCDictionary& par)
{
SCStore::getInstance()->restorePurchased(_resultFunc);
}
NAMESPACE_SPEEDCC_END
| 30.318182 | 93 | 0.687781 | kevinwu1024 |
16cdf32d98a37fa69ba5632fad2824d1ca1bda5f | 846 | cpp | C++ | Blake2/Blake2/ParallelUtils.cpp | Steppenwolfe65/Blake2 | 9444e194323f98bb797816bc774d202276d17243 | [
"Intel",
"MIT"
] | 1 | 2016-11-09T05:34:58.000Z | 2016-11-09T05:34:58.000Z | Blake2/Blake2/ParallelUtils.cpp | Steppenwolfe65/Blake2 | 9444e194323f98bb797816bc774d202276d17243 | [
"Intel",
"MIT"
] | null | null | null | Blake2/Blake2/ParallelUtils.cpp | Steppenwolfe65/Blake2 | 9444e194323f98bb797816bc774d202276d17243 | [
"Intel",
"MIT"
] | null | null | null | #include "ParallelUtils.h"
#include <functional>
#if defined(_OPENMP)
# include <omp.h>
#else
# include <future>
#endif
NAMESPACE_UTILITY
size_t ParallelUtils::ProcessorCount()
{
#if defined(_OPENMP)
return static_cast<size_t>(omp_get_num_procs());
#else
return static_cast<size_t>(std::thread::hardware_concurrency());
#endif
}
void ParallelUtils::ParallelFor(size_t From, size_t To, const std::function<void(size_t)> &F)
{
#if defined(_OPENMP)
#pragma omp parallel num_threads((int)To)
{
size_t i = (size_t)omp_get_thread_num();
F(i);
}
#else
std::vector<std::future<void>> futures;
for (size_t i = From; i < To; ++i)
{
auto fut = std::async([i, F]()
{
F(i);
});
futures.push_back(std::move(fut));
}
for (size_t i = 0; i < futures.size(); ++i)
futures[i].wait();
futures.clear();
#endif
}
NAMESPACE_UTILITYEND | 17.625 | 93 | 0.683215 | Steppenwolfe65 |
16cf20038e00882772a14e9a2dd81ee4ae1c0b1a | 4,746 | cpp | C++ | Dicom/dicom/data/AS.cpp | drleq/CppDicom | e320fad8414fabfb51c5eb80964f8b6def578247 | [
"MIT"
] | null | null | null | Dicom/dicom/data/AS.cpp | drleq/CppDicom | e320fad8414fabfb51c5eb80964f8b6def578247 | [
"MIT"
] | null | null | null | Dicom/dicom/data/AS.cpp | drleq/CppDicom | e320fad8414fabfb51c5eb80964f8b6def578247 | [
"MIT"
] | null | null | null | #include "dicom_pch.h"
#include "dicom/data/AS.h"
#include <sstream>
#include <iomanip>
#include "dicom/data/detail/atoi.h"
namespace {
using namespace dicom::data;
[[nodiscard]] AS::UnitType char_to_units(char c) {
switch (c) {
case 'D': return AS::Days;
case 'W': return AS::Weeks;
case 'M': return AS::Months;
case 'Y': return AS::Years;
default: return AS::UnitType(-1);
}
}
[[nodiscard]] char units_to_char(AS::UnitType units) {
switch (units) {
case AS::Days: return 'D';
case AS::Weeks: return 'W';
case AS::Months: return 'M';
case AS::Years: return 'Y';
default: return 'X'; // Something purposefully invalid
}
}
}
namespace dicom::data {
AS::AS()
: AS(std::string())
{}
//--------------------------------------------------------------------------------------------------------
AS::AS(const char* value)
: AS(std::string(value))
{}
//--------------------------------------------------------------------------------------------------------
AS::AS(const std::string_view& value)
: AS(std::string(value))
{}
//--------------------------------------------------------------------------------------------------------
AS::AS(std::string&& value)
: VR(VRType::AS),
m_value(std::forward<std::string>(value))
{}
//--------------------------------------------------------------------------------------------------------
AS::AS(int32_t age, UnitType units)
: VR(VRType::AS)
{
std::ostringstream ss;
ss << std::setw(3) << std::setfill('0') << age
<< std::setw(0) << units_to_char(units);
m_value = ss.str();
}
//--------------------------------------------------------------------------------------------------------
AS::AS(const AS& other) = default;
AS::AS(AS&& other) = default;
AS& AS::operator = (const AS& other) = default;
AS& AS::operator = (AS&& other) = default;
//--------------------------------------------------------------------------------------------------------
AS::~AS() = default;
//--------------------------------------------------------------------------------------------------------
ValidityType AS::Validate() const {
/*** Essential checks ***/
// Value is always 4 characters long
if (m_value.size() != 4) { return ValidityType::Invalid; }
// Value must have numeric digits for the first three characters
if (!std::all_of(m_value.begin(), m_value.begin() + 3, isdigit)) { return ValidityType::Invalid; }
// Value must have a unit character at the end
if (char_to_units(m_value[3]) == -1) { return ValidityType::Invalid; }
return ValidityType::Valid;
}
//--------------------------------------------------------------------------------------------------------
int32_t AS::Age() const {
AssertValidated();
return detail::unchecked_atoi<int32_t>(m_value.c_str());
}
//--------------------------------------------------------------------------------------------------------
AS::UnitType AS::Units() const {
AssertValidated();
return char_to_units(m_value[3]);
}
//--------------------------------------------------------------------------------------------------------
int32_t AS::Compare(const VR* other) const {
auto result = VR::Compare(other);
if (result) { return result; }
auto typed = static_cast<const AS*>(other);
if (Validity() == ValidityType::Invalid || typed->Validity() == ValidityType::Invalid) {
return m_value.compare(typed->m_value);
}
int32_t diff = Units() - typed->Units();
if (diff != 0) { return diff; }
diff = Age() - typed->Age();
return diff;
}
//--------------------------------------------------------------------------------------------------------
bool AS::operator == (const VR* other) const {
if (VR::Compare(other) != 0) { return false; }
auto typed = static_cast<const AS*>(other);
return (m_value == typed->m_value);
}
//--------------------------------------------------------------------------------------------------------
bool AS::operator != (const VR* other) const {
if (VR::Compare(other) != 0) { return true; }
auto typed = static_cast<const AS*>(other);
return (m_value != typed->m_value);
}
} | 32.067568 | 111 | 0.379899 | drleq |
16d11e28f268c65b7aef8efe1f731e87f602a2d0 | 806 | cpp | C++ | codeforces/gym/2016 ACM Amman Collegiate Programming Contest/b.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | 4 | 2020-10-05T19:24:10.000Z | 2021-07-15T00:45:43.000Z | codeforces/gym/2016 ACM Amman Collegiate Programming Contest/b.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | codeforces/gym/2016 ACM Amman Collegiate Programming Contest/b.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | #include <cpplib/stdinc.hpp>
int32_t main(){
desync();
int t;
cin >> t;
vi pali = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
map<int, int> ipal;
ipal[2] = 1;
ipal[3] = 7;
ipal[4] = 4;
ipal[5] = 5;
ipal[6] = 9;
ipal[7] = 8;
while(t--){
int n;
cin >> n;
string num;
cin >> num;
int pals = 0;
for(char c:num)
pals += pali[c-'0'];
for(int i=0; i<n; ++i){
int l = (n-i-1)*2, r = (n-i-1)*7;
for(int d=9; d>=0; --d){
int aft = pals - pali[d];
if(aft >= l and aft <= r){
pals -= pali[d];
cout << d;
break;
}
}
}
cout << endl;
}
return 0;
}
| 21.210526 | 45 | 0.331266 | tysm |
16d1e27ce68b98c221d0b8cec84b21c8674c94ac | 1,568 | cpp | C++ | src/kv/File.cpp | kushview/decibels | db7298fe4c1ca25a5eb0ddf5b5e481a52fa67aff | [
"0BSD"
] | 3 | 2020-11-14T05:51:35.000Z | 2021-01-18T03:47:55.000Z | src/kv/File.cpp | kushview/lua-rt | db7298fe4c1ca25a5eb0ddf5b5e481a52fa67aff | [
"0BSD"
] | 2 | 2021-02-24T16:44:03.000Z | 2021-02-24T17:28:58.000Z | src/kv/File.cpp | kushview/lua-kv | db7298fe4c1ca25a5eb0ddf5b5e481a52fa67aff | [
"0BSD"
] | null | null | null | /// A file or directory on your system.
// @classmod kv.File
// @pragma nostrip
#include "lua-kv.hpp"
#include LKV_JUCE_HEADER
#define LKV_TYPE_NAME_FILE "File"
using namespace juce;
LKV_EXPORT
int luaopen_kv_File (lua_State* L) {
sol::state_view lua (L);
auto t = lua.create_table();
t.new_usertype<File> (LKV_TYPE_NAME_FILE, sol::no_constructor,
sol::call_constructor, sol::factories (
/// Non-existent file
// @function File.__call
// @within Metamethods
[]() { return File(); },
/// File from absolute path
// @string abspath Absolute file path.
// @function File.__call
// @within Metamethods
// @usage
// local f = kv.File ("/path/to/file/or/dir")
// -- do something with file
[](const char* path) { return File (String::fromUTF8 (path)); }
),
/// File name with extension (string)(readonly).
// @class field
// @name File.name
// @within Attributes
"name", sol::readonly_property ([](File& self) {
return self.getFileName().toStdString();
}),
/// Absolute file path (string)(readonly).
// @class field
// @name File.path
// @within Attributes
"path", sol::readonly_property ([](File& self) {
return self.getFullPathName().toStdString();
})
);
auto M = t.get<sol::table> (LKV_TYPE_NAME_FILE);
t.clear();
sol::stack::push (L, M);
return 1;
}
| 29.037037 | 75 | 0.552934 | kushview |
16d21cfa513614ef99c27e015c5d3c98e305788b | 5,565 | cc | C++ | dcmdata/tests/tvrdatim.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 10 | 2016-07-03T12:16:58.000Z | 2021-12-18T06:15:50.000Z | dcmdata/tests/tvrdatim.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 1 | 2020-04-30T07:55:55.000Z | 2020-04-30T07:55:55.000Z | dcmdata/tests/tvrdatim.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 9 | 2017-02-09T02:16:39.000Z | 2021-01-06T02:49:24.000Z | /*
*
* Copyright (C) 2002-2013, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Joerg Riesmeier
*
* Purpose: test program for classes DcmDate, DcmTime and DcmDateTime
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/ofstd/oftest.h"
#include "dcmtk/dcmdata/dcvrda.h"
#include "dcmtk/dcmdata/dcvrtm.h"
#include "dcmtk/dcmdata/dcvrdt.h"
#include "dcmtk/dcmdata/dcdeftag.h"
#define CHECK_EQUAL(string) do { \
strstream << OFStringStream_ends; \
OFSTRINGSTREAM_GETOFSTRING(strstream, res); \
OFCHECK_EQUAL(res, string); \
strstream.clear(); \
strstream.str(""); \
} while (0)
#define CHECK_STREAM_EQUAL(val, string) do { \
strstream << val; \
CHECK_EQUAL(string); \
strstream.clear(); \
strstream.str(""); \
} while(0)
OFTEST(dcmdata_dateTime)
{
double timeZone;
OFDate dateVal;
OFTime timeVal;
OFDateTime dateTime;
OFString string;
DcmDate dcmDate(DCM_StudyDate);
DcmTime dcmTime(DCM_StudyTime);
DcmDateTime dcmDateTime(DCM_DateTime);
OFOStringStream strstream;
// Determine the local time zone, needed because setOFTime loses the timezone
timeVal.setCurrentTime();
const double localTimeZone = timeVal.getTimeZone();
OFDate curDateVal(2011, 5, 9);
OFTime curTimeVal(10, 35, 20, localTimeZone);
OFDateTime curDateTimeVal(curDateVal, curTimeVal);
dcmDate.setOFDate(curDateVal);
dcmDate.print(strstream);
CHECK_EQUAL("(0008,0020) DA [20110509] # 8, 1 StudyDate\n");
OFCHECK(dcmDate.getOFDate(dateVal).good());
OFCHECK_EQUAL(dateVal, curDateVal);
dcmTime.setOFTime(curTimeVal);
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [103520] # 6, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
OFCHECK_EQUAL(timeVal, curTimeVal);
dcmDateTime.setOFDateTime(curDateTimeVal);
dcmDateTime.print(strstream);
CHECK_EQUAL("(0040,a120) DT [20110509103520] # 14, 1 DateTime\n");
OFCHECK(dcmDateTime.getOFDateTime(dateTime).good());
OFCHECK_EQUAL(dateTime, curDateTimeVal);
OFCHECK(dateTime.getISOFormattedDateTime(string, OFTrue /*seconds*/, OFTrue /*fraction*/, OFFalse /*timeZone*/, OFFalse /*delimiter*/));
OFCHECK_EQUAL(string, "20110509103520.000000");
dcmTime.putString("12");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [12] # 2, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
CHECK_STREAM_EQUAL(timeVal, "12:00:00");
dcmTime.putString("1203");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [1203] # 4, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
CHECK_STREAM_EQUAL(timeVal, "12:03:00");
dcmTime.putString("120315");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [120315] # 6, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
CHECK_STREAM_EQUAL(timeVal, "12:03:15");
dcmTime.putString("120301.99");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [120301.99] # 10, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
timeVal.getISOFormattedTime(string, OFTrue /*seconds*/, OFTrue /*fraction*/, OFFalse /*timeZone*/);
OFCHECK_EQUAL(string, "12:03:01.990000");
dcmTime.putString("12:03");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [12:03] # 6, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
CHECK_STREAM_EQUAL(timeVal, "12:03:00");
dcmTime.putString("12:03:15");
dcmTime.print(strstream);
CHECK_EQUAL("(0008,0030) TM [12:03:15] # 8, 1 StudyTime\n");
OFCHECK(dcmTime.getOFTime(timeVal).good());
CHECK_STREAM_EQUAL(timeVal, "12:03:15");
OFCHECK(DcmTime::getTimeZoneFromString("+0030", timeZone).good());
OFCHECK_EQUAL(timeZone, 0.5);
OFCHECK(DcmTime::getTimeZoneFromString("+1130", timeZone).good());
OFCHECK_EQUAL(timeZone, 11.5);
OFCHECK(DcmTime::getTimeZoneFromString("-0100", timeZone).good());
OFCHECK_EQUAL(timeZone, -1);
OFCHECK(DcmTime::getTimeZoneFromString("-0530", timeZone).good());
OFCHECK_EQUAL(timeZone, -5.5);
OFCHECK(DcmTime::getTimeZoneFromString("01130", timeZone).bad());
OFCHECK(DcmTime::getTimeZoneFromString("+100", timeZone).bad());
OFCHECK(DcmTime::getTimeZoneFromString("UTC+1", timeZone).bad());
dcmDateTime.putString("200204101203+0500");
dcmDateTime.print(strstream);
CHECK_EQUAL("(0040,a120) DT [200204101203+0500] # 18, 1 DateTime\n");
OFCHECK(dcmDateTime.getOFDateTime(dateTime).good());
CHECK_STREAM_EQUAL(dateTime, "2002-04-10 12:03:00");
dcmDateTime.putString("20020410");
dcmDateTime.print(strstream);
CHECK_EQUAL("(0040,a120) DT [20020410] # 8, 1 DateTime\n");
OFCHECK(dcmDateTime.getOFDateTime(dateTime).good());
dateTime.getISOFormattedDateTime(string, OFTrue /*seconds*/, OFFalse /*fraction*/, OFFalse /*timeZone*/);
OFCHECK_EQUAL(string, "2002-04-10 00:00:00");
}
| 38.37931 | 140 | 0.647978 | trice-imaging |
16d3368bb7c27f39a0da056372a016210b6ccbe8 | 1,225 | cpp | C++ | DigitalTriangle/DigitalTriangle11.cpp | nananjy/DynamicPlanning | 03c96c6dca92f5b3c82fceb5e061e93c1d22edfd | [
"Apache-2.0"
] | 1 | 2017-12-28T13:46:35.000Z | 2017-12-28T13:46:35.000Z | DigitalTriangle/DigitalTriangle11.cpp | nananjy/DynamicPlanning | 03c96c6dca92f5b3c82fceb5e061e93c1d22edfd | [
"Apache-2.0"
] | null | null | null | DigitalTriangle/DigitalTriangle11.cpp | nananjy/DynamicPlanning | 03c96c6dca92f5b3c82fceb5e061e93c1d22edfd | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
/**
* 利用动态规划思想求解数字三角形(POJ 1163), 题目来源IOI 1994
* 将一个问题分解为子问题递归求解,并且将中间结果保存以避免重复计算的办法
* 1.问题具有最优子结构性质(问题的最优解所包含的子问题的解也是最优的)
* 2.无后效性(当前若干个状态值一旦确定,此后过程的演变就只和这若干个状态值有关,与之前采取哪种方式演变到若干个状态无关)
* 问题描述:求出累加和最大的最佳路径上的数字之和,
* 路径上每一步只能从一个数走到下一层和它最近的左边的数或右边的数。
* @author 作者名
*/
#define MAX_NUM 100
int d[MAX_NUM + 10][MAX_NUM + 10];//存放待计算的数字三角形
int N;//存放行数
int maxSum[MAX_NUM + 10][MAX_NUM + 10];//存放当前数字到底边的最佳路径之和
/**
* 计算路径和
* @r 数字三角形的行
* @j 数字三角形的列
* @return 从第i行第j列的数字到底边的最佳路径和
*/
int MaxSum(int r, int j)
{
if(r == N)
return d[r][j];//底边数字的路径和即为数字本身
if(maxSum[r+1][j] == -1)//如果MaxSum(r+1, j)没有计算过
maxSum[r+1][j] = MaxSum(r+1, j);
if(maxSum[r+1][j+1] == -1)//如果MaxSum(r+1, j+1)没有计算过
maxSum[r+1][j+1] = MaxSum(r+1, j+1);
if(maxSum[r+1][j] > maxSum[r+1][j+1])
return maxSum[r+1][j] + d[r][j];
return maxSum[r+1][j+1] + d[r][j];//返回当前数字到底边的最佳路径和
}
/**
* 输入数字三角形
*/
int main()
{
scanf("%d", &N);//输入行数
//将maxSum全部置成-1, 表示开始所有的MaxSum(r, j)都没有计算过
memset(maxSum, -1, sizeof(maxSum));
for(int i = 1; i <= N; i++)
for(int j = 1; j <= i; j++)
scanf("%d", &d[i][j]);//输入数字三角形
printf("%d", MaxSum(1, 1));//输出最佳路径和
return 0;
}
| 23.113208 | 63 | 0.64 | nananjy |
16e177a8e343d2d71049506dbc4124d2301bdff0 | 882 | cpp | C++ | jianzhioffer/33verifyPostorder.cpp | wanghengg/LeetCode | 4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79 | [
"Apache-2.0"
] | null | null | null | jianzhioffer/33verifyPostorder.cpp | wanghengg/LeetCode | 4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79 | [
"Apache-2.0"
] | null | null | null | jianzhioffer/33verifyPostorder.cpp | wanghengg/LeetCode | 4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool verify(vector<int>& postorder, int left, int right) {
if (left >= right) return true;
int root = postorder[right];
int index = right-1;
while (index >= 0 && postorder[index] > root) {
--index;
}
int mid = index;
while (index >= 0) {
if (postorder[index] > root) {
return false;
} else {
--index;
}
}
return verify(postorder, left, mid) && verify(postorder, mid + 1, right - 1);
}
bool verifyPostorder(vector<int>& postorder) {
return verify(postorder, 0, postorder.size()-1);
}
};
int main() {
vector<int> postorder{5,4,3,2,1};
Solution solution;
cout << solution.verifyPostorder(postorder) << endl;
return 0;
} | 25.941176 | 85 | 0.528345 | wanghengg |
16e2ac8bd50e36687a24da8a1e931ab99745b161 | 596 | cc | C++ | aircrafting/Game.cc | SametSisartenep/game-dev | 8779ea5845784e1ab1cea5bc5c29e46463aef731 | [
"MIT"
] | 1 | 2015-11-08T11:17:50.000Z | 2015-11-08T11:17:50.000Z | aircrafting/Game.cc | SametSisartenep/game-dev | 8779ea5845784e1ab1cea5bc5c29e46463aef731 | [
"MIT"
] | null | null | null | aircrafting/Game.cc | SametSisartenep/game-dev | 8779ea5845784e1ab1cea5bc5c29e46463aef731 | [
"MIT"
] | null | null | null | #include "Game.h"
Game::Game()
: mWindow(sf::VideoMode(640, 480), "SFML Application")
, mPlayer()
{
mPlayer.setRadius(40.f);
mPlayer.setPosition(100.f, 100.f);
mPlayer.setFillColor(sf::Color::Cyan);
}
void Game::run() {
while (mWindow.isOpen()) {
processEvents();
update();
render();
}
}
void Game::processEvents() {
sf::Event event;
while (mWindow.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
mWindow.close();
}
}
}
void Game::update() {
}
void Game::render() {
mWindow.clear();
mWindow.draw(mPlayer);
mWindow.display();
}
| 15.684211 | 56 | 0.607383 | SametSisartenep |
16e922742d90d8d2f191cbb16da1ad360e15706e | 2,416 | cpp | C++ | Demos/UnitTests/src/Sort.cpp | gammaker/Intra | aed1647cd2cf1781ab0976c2809533d0f347e87e | [
"MIT"
] | 8 | 2017-05-22T12:55:40.000Z | 2018-11-11T22:36:56.000Z | Demos/UnitTests/src/Sort.cpp | gammaker/Intra | aed1647cd2cf1781ab0976c2809533d0f347e87e | [
"MIT"
] | 1 | 2020-03-14T11:26:17.000Z | 2020-03-14T12:31:11.000Z | Demos/UnitTests/src/Sort.cpp | devoln/Intra | aed1647cd2cf1781ab0976c2809533d0f347e87e | [
"MIT"
] | 1 | 2017-10-12T10:03:56.000Z | 2017-10-12T10:03:56.000Z | #include "Cpp/Warnings.h"
INTRA_PUSH_DISABLE_REDUNDANT_WARNINGS
#include "Sort.h"
#include "Range/Sort.hh"
#include "Container/Sequential/Array.h"
#include "IO/FormattedWriter.h"
#include "Utils/Debug.h"
INTRA_PUSH_DISABLE_ALL_WARNINGS
#include <algorithm>
INTRA_WARNING_POP
using namespace Intra;
static const short arrayForSortTesting[] = {
2, 4234, -9788, 23, 5, 245, 2, 24, 5, -9890,
2, 5, 4552, 54, 3, -932, 123, 342, 24321, -234
};
void TestSort(IO::FormattedWriter& output)
{
Array<short> arrUnsorted = arrayForSortTesting;
output.PrintLine("Not sorted array: ", arrUnsorted);
Array<short> arrStdSort = arrUnsorted;
std::sort(arrStdSort.begin(), arrStdSort.end());
output.PrintLine("std::sort'ed array: ", arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrStdSort), arrStdSort);
Array<short> arrInsertion = arrUnsorted;
Range::InsertionSort(arrInsertion);
output.PrintLine("InsertionSort'ed array: ", arrInsertion);
INTRA_ASSERT_EQUALS(arrInsertion, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrInsertion), arrInsertion);
Array<short> arrShell = arrUnsorted;
Range::ShellSort(arrShell);
output.PrintLine("ShellSort'ed array: ", arrShell);
INTRA_ASSERT_EQUALS(arrShell, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrShell), arrShell);
Array<short> arrQuick = arrUnsorted;
Range::QuickSort(arrQuick);
output.PrintLine("QuickSort'ed array: ", arrQuick);
INTRA_ASSERT_EQUALS(arrQuick, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrQuick), arrQuick);
Array<short> arrRadix = arrUnsorted;
Range::RadixSort(arrRadix.AsRange());
output.PrintLine("RadixSort'ed array: ", arrRadix);
INTRA_ASSERT_EQUALS(arrRadix, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrRadix), arrRadix);
Array<short> arrMerge = arrUnsorted;
Range::MergeSort(arrMerge);
output.PrintLine("MergeSort'ed array: ", arrMerge);
INTRA_ASSERT_EQUALS(arrMerge, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrMerge), arrMerge);
Array<short> arrHeap = arrUnsorted;
Range::HeapSort(arrHeap);
output.PrintLine("HeapSort'ed array: ", arrHeap);
INTRA_ASSERT_EQUALS(arrHeap, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrHeap), arrHeap);
Array<short> arrSelection = arrUnsorted;
Range::SelectionSort(arrSelection);
output.PrintLine("SelectionSort'ed array: ", arrSelection);
INTRA_ASSERT_EQUALS(arrSelection, arrStdSort);
INTRA_ASSERT1(Range::IsSorted(arrSelection), arrSelection);
}
INTRA_WARNING_POP
| 31.376623 | 60 | 0.768626 | gammaker |
16eb73148836c6c033158610a65de3b2daf19c4b | 1,148 | hpp | C++ | src/wavefile.hpp | ushitora-anqou/cables | edafc749bfd010e367838c193183b80953f60000 | [
"MIT"
] | 2 | 2021-02-15T08:11:00.000Z | 2021-11-14T17:09:37.000Z | src/wavefile.hpp | ushitora-anqou/cables | edafc749bfd010e367838c193183b80953f60000 | [
"MIT"
] | null | null | null | src/wavefile.hpp | ushitora-anqou/cables | edafc749bfd010e367838c193183b80953f60000 | [
"MIT"
] | null | null | null | #pragma once
#ifndef ___WAVEFILE_HPP___
#define ___WAVEFILE_HPP___
#include "pcmwave.hpp"
#include <cstdint>
#include <fstream>
#include <string>
// リニアPCM専用
struct PCMWaveFileHeader
{
std::uint8_t riffID[4];
std::uint32_t size;
std::uint8_t waveID[4];
std::uint8_t fmtID[4];
std::uint32_t fmtSize;
std::uint16_t format;
std::uint16_t channel;
std::uint32_t sampleRate;
std::uint32_t bytePerSec;
std::uint16_t blockSize;
std::uint16_t bitPerSample;
std::uint8_t dataID[4];
std::uint32_t dataSize;
PCMWaveFileHeader(){}
PCMWaveFileHeader(int) :
riffID{'R', 'I', 'F', 'F'},
waveID{'W', 'A', 'V', 'E'},
fmtID{'f', 'm', 't', ' '},
fmtSize(16), format(1),
dataID{'d', 'a', 't', 'a'}
{}
};
class WaveInFile
{
private:
std::ifstream ifs_;
public:
WaveInFile(const std::string& filename);
~WaveInFile(){}
bool isEOF() const;
PCMWave read();
};
class WaveOutFile
{
private:
std::ofstream ofs_;
public:
WaveOutFile(const std::string& filename);
~WaveOutFile();
void write(const PCMWave& wave);
};
#endif
| 17.9375 | 45 | 0.614111 | ushitora-anqou |
16ec96b7b56a3862a4bc1131d8646d4625a21025 | 2,653 | cc | C++ | src/core/ext/filters/client_channel/server_address.cc | inteos/grpc | fb8e4556c250bbcc523b55e6ebe69cb2b3d95998 | [
"Apache-2.0"
] | 4 | 2020-08-11T10:00:16.000Z | 2021-10-08T15:17:25.000Z | src/core/ext/filters/client_channel/server_address.cc | inteos/grpc | fb8e4556c250bbcc523b55e6ebe69cb2b3d95998 | [
"Apache-2.0"
] | 1 | 2020-05-12T16:17:30.000Z | 2020-05-12T16:17:30.000Z | src/core/ext/filters/client_channel/server_address.cc | inteos/grpc | fb8e4556c250bbcc523b55e6ebe69cb2b3d95998 | [
"Apache-2.0"
] | 3 | 2020-08-16T12:11:56.000Z | 2021-11-06T02:45:04.000Z | /*
*
* Copyright 2018 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/ext/filters/client_channel/server_address.h"
namespace grpc_core {
//
// ServerAddress
//
ServerAddress::ServerAddress(
const grpc_resolved_address& address, grpc_channel_args* args,
std::map<const char*, std::unique_ptr<AttributeInterface>> attributes)
: address_(address), args_(args), attributes_(std::move(attributes)) {}
ServerAddress::ServerAddress(
const void* address, size_t address_len, grpc_channel_args* args,
std::map<const char*, std::unique_ptr<AttributeInterface>> attributes)
: args_(args), attributes_(std::move(attributes)) {
memcpy(address_.addr, address, address_len);
address_.len = static_cast<socklen_t>(address_len);
}
namespace {
int CompareAttributes(
const std::map<const char*,
std::unique_ptr<ServerAddress::AttributeInterface>>&
attributes1,
const std::map<const char*,
std::unique_ptr<ServerAddress::AttributeInterface>>&
attributes2) {
auto it2 = attributes2.begin();
for (auto it1 = attributes1.begin(); it1 != attributes1.end(); ++it1) {
// attributes2 has fewer elements than attributes1
if (it2 == attributes2.end()) return -1;
// compare keys
int retval = strcmp(it1->first, it2->first);
if (retval != 0) return retval;
// compare values
retval = it1->second->Cmp(it2->second.get());
if (retval != 0) return retval;
++it2;
}
// attributes1 has fewer elements than attributes2
if (it2 != attributes2.end()) return 1;
// equal
return 0;
}
} // namespace
int ServerAddress::Cmp(const ServerAddress& other) const {
if (address_.len > other.address_.len) return 1;
if (address_.len < other.address_.len) return -1;
int retval = memcmp(address_.addr, other.address_.addr, address_.len);
if (retval != 0) return retval;
retval = grpc_channel_args_compare(args_, other.args_);
if (retval != 0) return retval;
return CompareAttributes(attributes_, other.attributes_);
}
} // namespace grpc_core
| 32.353659 | 75 | 0.701093 | inteos |
16ef5617204523102bd98f68ff37ffc01c208f77 | 1,091 | cpp | C++ | D.cpp | ebaty/Typical-DP-Contest | eae2f3547df020dbdb66e3314dbae44c9c51fe89 | [
"MIT"
] | null | null | null | D.cpp | ebaty/Typical-DP-Contest | eae2f3547df020dbdb66e3314dbae44c9c51fe89 | [
"MIT"
] | null | null | null | D.cpp | ebaty/Typical-DP-Contest | eae2f3547df020dbdb66e3314dbae44c9c51fe89 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <sstream>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
using namespace std;
typedef long long ll;
double dp[101][70][40][30];
int main() {
ll N, D;
cin >> N >> D;
int I = 0, J = 0, K = 0;
memset(dp, 0.0, sizeof(dp));
while ( D % 2 == 0 ) {
I++;
D /= 2;
}
while ( D % 3 == 0 ) {
J++;
D /= 3;
}
while ( D % 5 == 0 ) {
K++;
D /= 5;
}
if ( D != 1 ) {
cout << "0.0" << endl;
return 0;
}
dp[0][0][0][0] = 1.0;
REP(n, N) REP(i, I+1) REP(j, J+1) REP(k, K+1) {
double p = dp[n][i][j][k] / 6.0;
int i1 = min(i+1, I);
int i2 = min(i+2, I);
int j1 = min(j+1, J);
int k1 = min(k+1, K);
dp[n+1][i][j][k] += p;
dp[n+1][i1][j][k] += p;
dp[n+1][i][j1][k] += p;
dp[n+1][i2][j][k] += p;
dp[n+1][i][j][k1] += p;
dp[n+1][i1][j1][k] += p;
}
printf("%0.6lf\n", dp[N][I][J][K]);
return 0;
}
| 17.046875 | 49 | 0.447296 | ebaty |
a8480fced0de3740bbe0f324752916d5f212e78c | 1,057 | hpp | C++ | include/Menu.hpp | Kiloris/Complot_Game | 81247c6c13d7921a9cc01b765ab3a4a5924c2391 | [
"MIT"
] | null | null | null | include/Menu.hpp | Kiloris/Complot_Game | 81247c6c13d7921a9cc01b765ab3a4a5924c2391 | [
"MIT"
] | null | null | null | include/Menu.hpp | Kiloris/Complot_Game | 81247c6c13d7921a9cc01b765ab3a4a5924c2391 | [
"MIT"
] | null | null | null | /*
** COMPLOT PROJECT
** AUTHOR:
** Zacharie ABIDAT
*/
#ifndef MENU_HPP_
#define MENU_HPP_
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Graphics/Font.hpp>
#include "Button.hpp"
#include "Square.hpp"
#include <iostream>
#include <cstdlib>
class Menu {
public:
Menu(sf::RenderWindow *);
~Menu();
void draw();
void event_clicked();
void event_pressed();
void clicked_settings();
void clicked_menu();
void pressed_settings();
void pressed_menu();
bool get_verif();
void set_verif(bool);
protected:
private:
sf::RenderWindow *app;
sf::Texture bg_texture;
sf::Sprite bg_sprite;
Button *play_button;
Button *multi_button;
Button *settings_button;
Button *exit_button;
Button *low_sound_button;
Button *high_sound_button;
Button *menu_button;
std::vector<Square *> list_square;
bool settings;
bool verif;
};
#endif /* !MENU_HPP_ */
| 21.571429 | 42 | 0.603595 | Kiloris |
a8495da44209d7d618d0294d61afbbf6915e786f | 14,009 | hpp | C++ | api-cpp/include/dfx/api/MeasurementStreamAPI.hpp | nuralogix/dfx-api-client-cpp | 6b45307ddf4b0036c107eebd7e8915f6c501c3b0 | [
"MIT"
] | null | null | null | api-cpp/include/dfx/api/MeasurementStreamAPI.hpp | nuralogix/dfx-api-client-cpp | 6b45307ddf4b0036c107eebd7e8915f6c501c3b0 | [
"MIT"
] | null | null | null | api-cpp/include/dfx/api/MeasurementStreamAPI.hpp | nuralogix/dfx-api-client-cpp | 6b45307ddf4b0036c107eebd7e8915f6c501c3b0 | [
"MIT"
] | null | null | null | // Copyright (c) Nuralogix. All rights reserved. Licensed under the MIT license.
// See LICENSE.txt in the project root for license information.
#pragma once
#ifndef DFX_API_CLOUD_MEASUREMENT_STREAM_API_H
#define DFX_API_CLOUD_MEASUREMENT_STREAM_API_H
#include "dfx/api/CloudAPI_Export.hpp"
#include "dfx/api/CloudConfig.hpp"
#include "dfx/api/CloudStatus.hpp"
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <map>
#include <mutex>
#include <string>
#include <vector>
namespace dfx::api
{
class CloudAPI;
/**
* @brief MeasurementResult is the message type of result data from the server.
*/
struct DFXCLOUD_EXPORT MeasurementResult
{
uint64_t chunkOrder; ///< The Chunk Order
std::string faceID; ///< The Face ID
std::map<std::string, std::vector<float>> signalData;
int64_t frameEndTimestampMS;
int64_t timestampMS;
};
struct DFXCLOUD_EXPORT MeasurementMetric
{
float uploadRate;
};
struct DFXCLOUD_EXPORT MeasurementWarning
{
int warningCode;
std::string warningMessage;
int64_t timestampMS;
};
/**
* @brief Asynchronous callback signature to receive a Measurement ID.
*
* Provides the Measurement ID being used from this Measurement instance.
*/
typedef std::function<void(const std::string& measurementID)> MeasurementIDCallback;
/**
* @brief Asynchronous callback signature to receive Measurement results.
*
* Provides the actual measurement results from the server for individual
* signals like heart rate, or signal-to-noise ratio.
*/
typedef std::function<void(const MeasurementResult& result)> MeasurementResultCallback;
/**
* @brief Asynchronous callback signature to receive Measurement metrics.
*
* Provides diagnostic information on the connection speed.
*/
typedef std::function<void(const MeasurementMetric& result)> MeasurementMetricCallback;
/**
* @brief Asynchronous callback signature to receive Measurement warnings.
*
* The warning Callback is used on gRPC streams to provide warning notifications when
* a signal can't be provided because a criteria has not been met. The connection has not been
* terminated and the server will continue to attempt to process but it is advice that would
* improve the signals being provided.
*/
typedef std::function<void(const MeasurementWarning& warning)> MeasurementWarningCallback;
/**
* @brief Measurement is used to send payload chunks to the DFX Server and get back results.
*
* The sendChunk operation is used to provide the server with payload chunks which the
* server will process and reply with result data. Because of the latency involved in
* the network communication, uploading, processing and result return this class has
* been designed to work on a background thread and offers two forms of use.
*
* If you prefer asynchronous results, you can register callbacks of the message
* types you are interested in and you will be called immediately when there are
* results. The callback itself needs to be thread-safe. If there are any queued
* messages, those will be delivered the instant a callback is registered and the
* queue will be cleared.
*
* If you prefer synchronous results, you can poll the Measurement for results
* using the getResult (and associated signatures) with an optional timeout. If
* you provide no timeout, it will wait until a response is received which might
* be when the underlying connection itself dies.
*/
class DFXCLOUD_EXPORT MeasurementStreamAPI
{
public:
enum class CreateProperty
{
UserProfileID,
DeviceVersion,
Notes,
Mode, ///< For streaming set Mode="STREAMING"
PartnerID,
Resolution ///< Resolution=0 averages results (default), Resolution=100 is non-averaged
};
/**
* @brief MeasurementStreamAPI constructor.
*/
MeasurementStreamAPI();
/**
* @brief Measurement destructor.
*/
virtual ~MeasurementStreamAPI();
/**
* @brief Setup the stream.
*
* @param config
* @param studyID
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus setupStream(const CloudConfig& config,
const std::string& studyID,
const std::map<CreateProperty, std::string>& createProperties = {});
/**
* @brief Asynchronously send a payload chunk to the server for processing.
*
* @param config the connection configuration to use when sending the chunk.
* @param chunk the payload chunk of bytes obtained from DFX SDK.
* @param isLastChunk flag indicating if this is the last chunk for proper measurement completion.
* @return status of the measurement connection, CLOUD_OK on SUCCESS
*/
virtual CloudStatus sendChunk(const CloudConfig& config, const std::vector<uint8_t>& chunk, bool isLastChunk);
/**
* @brief Waits for the measurement connection to close ensuring that all results
* have been properly received.
*
* In order for the server to properly close the connection when it has completed
* processing all the chunks, the last chunk needs to be flagged on the sendChunk
* call or this wait for completion may wait a very long time.
*
* @param config the connection configuration to use when waiting.
* @param timeoutMillis the amount of time to wait for completion, zero is wait forever.
* @return status of the measurement connection at close, CLOUD_OK on SUCCESS
*/
virtual CloudStatus waitForCompletion(const CloudConfig& config, int32_t timeoutMillis = 0);
/**
* @brief cancel will inform the server that the Measurement should be terminated.
*
* This will notify the server of the intent to cancel but leave all internal
* state setup to receive any final messages the server might wish to deliver.
*
* @param config the connection configuration to use when cancelling.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus cancel(const CloudConfig& config);
/**
* @brief Resets this measurement back so another stream can be setup.
*
* The current measurement will be cancelled and the state immediately cleared
* so any undelivered messages would be lost, but the instance will be
* able to perform another setupStream() without having to be entirely
* recreated.
*
* @param config the connection configuration to use when cancelling.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus reset(const CloudConfig& config);
/**
* @brief Register an asynchronous callback for receiving the Measurement ID.
*
* @param callback the callback to invoke when a Measurement ID is available.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus setMeasurementIDCallback(const MeasurementIDCallback& callback);
/**
* @brief Register an asynchronous callback for receiving results.
*
* @param callback the callback to invoke when a result is available.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus setResultCallback(const MeasurementResultCallback& callback);
/**
* @brief Register an asynchronous callback for receiving metrics.
*
* @param callback the callback to invoke when a metric is available.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus setMetricCallback(const MeasurementMetricCallback& callback);
/**
* @brief Register an asynchronous callback for receiving warnings.
*
* @param callback the callback to invoke when a warning message is available.
* @return status of operation, CLOUD_OK on SUCCESS
*/
virtual CloudStatus setWarningCallback(const MeasurementWarningCallback& callback);
/**
* @brief Synchronously poll for a Measurement ID until timeout expires or connection
* dies.
*
* @param measurementID the measurement ID if the CloudStatus is CLOUD_OK.
* @param timeoutMillis the amount of time to wait for value, zero is wait forever.
* @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if
* measurement has been terminated.
*/
virtual CloudStatus getMeasurementID(std::string& measurementID, int32_t timeoutMillis = 0);
/**
* @brief Synchronously poll for a Measurement Result until timeout expires or
* connection dies.
*
* @param result a measurement result if the CloudStatus is CLOUD_OK.
* @param timeoutMillis the amount of time to wait for value, zero is wait forever.
* @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if
* measurement has been terminated.
*/
virtual CloudStatus getResult(MeasurementResult& result, int32_t timeoutMillis = 0);
/**
* @brief Synchronously poll for a Measurement Metric until timeout expires or
* connection dies.
*
* @param result a measurement metric if the CloudStatus is CLOUD_OK.
* @param timeoutMillis the amount of time to wait for value, zero is wait forever.
* @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if
* measurement has been terminated.
*/
virtual CloudStatus getMetric(MeasurementMetric& metric, int32_t timeoutMillis = 0);
/**
* @brief Synchronously poll for a Measurement Warning until timeout expires or
* connection dies.
*
* @param result a measurement warning if the CloudStatus is CLOUD_OK.
* @param timeoutMillis the amount of time to wait for value, zero is wait forever.
* @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if
* measurement has been terminated.
*/
virtual CloudStatus getWarning(MeasurementWarning& warning, int32_t timeoutMillis = 0);
protected:
/**
* @brief handleMeasurementID is called by derived implementations when they
* receive a measurement ID.
*
* @param measurementID the measurementID received.
* @return status of operation, CLOUD_OK on SUCCESS
*/
CloudStatus handleMeasurementID(const std::string& measurementID);
/**
* @brief handleResult is called by derived implementations when they
* receive a measurement result.
*
* @param result the measurement result received.
* @return status of operation, CLOUD_OK on SUCCESS
*/
CloudStatus handleResult(const MeasurementResult& result);
/**
* @brief handleMetric is called by derived implementations when they
* receive a measurement metric.
*
* @param metric the measurement metric received.
* @return status of operation, CLOUD_OK on SUCCESS
*/
CloudStatus handleMetric(const MeasurementMetric& metric);
/**
* @brief handleWarning is called by derived implementations when they
* receive a measurement warning.
*
* @param warning the measurement warning received.
* @return status of operation, CLOUD_OK on SUCCESS
*/
CloudStatus handleWarning(const MeasurementWarning& warning);
/**
* @brief isMeasurementClosed is called by derived implementations when
* they are interested if the measurement has been closed.
*
* @param status of the closed connection, if it is closed.
* @return true if the connection has been closed, false if it still active.
*/
bool isMeasurementClosed(CloudStatus& status);
/**
* @brief closeMeasurement is called by derived implementations when
* they need to ensure the measurement is closed, either the connection
* has died or the measurement has processed it's last chunk.
*
* @param status of the closed connection that the derived implementation would like to use.
* @return status of the closed connection that was used.
*/
CloudStatus closeMeasurement(const CloudStatus& status);
private:
std::shared_ptr<CloudAPI> cloudAPI;
/**
* @brief waitForQueuedData is an internal method which holds the implementation for how
* all the various message types are handled when a get request is performed.
*
* @tparam T the message type.
* @param condition the condition variable protecting the message type.
* @param timeoutMillis the number of milliseconds, or zero for infinite that should be waited.
* @param queue the queue for message type holding any queued values.
* @param result the value obtained after waiting.
* @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error if connection
* has been closed.
*/
template <typename T>
CloudStatus
waitForQueuedData(std::condition_variable& condition, int32_t timeoutMillis, std::deque<T>& queue, T& result);
template <typename T, typename F>
CloudStatus setCallbackVariable(F& variableCallback, std::deque<T>& queue, const F& callback);
template <typename T, typename F>
CloudStatus handle(std::condition_variable& condition, std::deque<T>& queue, const F& callback, const T& result);
std::mutex measurementMutex;
std::condition_variable cvWaitForCompletion;
bool measurementClosed;
CloudStatus measurementStatus;
MeasurementIDCallback measurementIDCallback;
std::condition_variable cvWaitForMeasurementID;
std::deque<std::string> measurementIDs;
MeasurementResultCallback resultCallback;
std::condition_variable cvWaitForResults;
std::deque<MeasurementResult> measurementResults;
MeasurementMetricCallback metricCallback;
std::condition_variable cvWaitForMetrics;
std::deque<MeasurementMetric> measurementMetrics;
MeasurementWarningCallback warningCallback;
std::condition_variable cvWaitForWarnings;
std::deque<MeasurementWarning> measurementWarnings;
};
} // namespace dfx::api
#endif // DFX_API_CLOUD_MEASUREMENT_STREAM_API_H
| 38.486264 | 117 | 0.721964 | nuralogix |
a84f2912ec22baefc073957b9f3873639de6dac9 | 639 | cpp | C++ | Scripts/BossBehaviourScript/BossStateIdle.cpp | solidajenjo/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 10 | 2019-02-25T11:36:23.000Z | 2021-11-03T22:51:30.000Z | Scripts/BossBehaviourScript/BossStateIdle.cpp | solidajenjo/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 146 | 2019-02-05T13:57:33.000Z | 2019-11-07T16:21:31.000Z | Scripts/BossBehaviourScript/BossStateIdle.cpp | FractalPuppy/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 3 | 2019-11-17T20:49:12.000Z | 2020-04-19T17:28:28.000Z | #include "BossStateIdle.h"
#include "BossBehaviourScript.h"
#include "EnemyControllerScript/EnemyControllerScript.h"
#include "ComponentAnimation.h"
BossStateIdle::BossStateIdle(BossBehaviourScript* AIBoss)
{
boss = AIBoss;
trigger = "Idle";
}
BossStateIdle::~BossStateIdle()
{
}
void BossStateIdle::HandleIA()
{
if (timer > (duration + baseDuration))
{
boss->currentState = (BossState*)boss->precast;
}
}
void BossStateIdle::Update()
{
boss->enemyController->LookAt2D(boss->playerPosition);
}
void BossStateIdle::Enter()
{
duration = (std::rand() % 100) / 100.f;
boss->anim->SendTriggerToStateMachine(trigger.c_str());
}
| 17.75 | 57 | 0.730829 | solidajenjo |
a850704010729c2f191254bdf87149b994e49e75 | 205 | cpp | C++ | 02Fundamental Data Types/04staticCast.cpp | CedarChennn/myC | b4de17f332788e3e578d304f2a690d2c9a07c004 | [
"Apache-2.0"
] | 2 | 2021-01-13T08:55:41.000Z | 2021-04-23T15:14:05.000Z | 02Fundamental Data Types/04staticCast.cpp | CedarChennn/myC | b4de17f332788e3e578d304f2a690d2c9a07c004 | [
"Apache-2.0"
] | null | null | null | 02Fundamental Data Types/04staticCast.cpp | CedarChennn/myC | b4de17f332788e3e578d304f2a690d2c9a07c004 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
int main()
{
char ch{'a'};
std::cout<<ch<<'\n';
std::cout<<static_cast<int>(ch)<<'\n';
std::cout<<ch<<'\n';
std::cout<<static_cast<int>(45)<<'\n';
return 0;
} | 18.636364 | 43 | 0.507317 | CedarChennn |
a8575b98f518033b6731753bc63e967aef4ef02f | 6,434 | hpp | C++ | include/RSG/Tuple.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/RSG/Tuple.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/RSG/Tuple.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: RSG
namespace RSG {
// Forward declaring type: Tuple`2<T1, T2>
template<typename T1, typename T2>
class Tuple_2;
// Forward declaring type: Tuple`3<T1, T2, T3>
template<typename T1, typename T2, typename T3>
class Tuple_3;
// Forward declaring type: Tuple`4<T1, T2, T3, T4>
template<typename T1, typename T2, typename T3, typename T4>
class Tuple_4;
}
// Completed forward declares
// Type namespace: RSG
namespace RSG {
// Forward declaring type: Tuple
class Tuple;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::RSG::Tuple);
DEFINE_IL2CPP_ARG_TYPE(::RSG::Tuple*, "RSG", "Tuple");
// Type namespace: RSG
namespace RSG {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: RSG.Tuple
// [TokenAttribute] Offset: FFFFFFFF
class Tuple : public ::Il2CppObject {
public:
// public System.Void .ctor()
// Offset: 0xA2E734
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static Tuple* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::RSG::Tuple::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<Tuple*, creationType>()));
}
// static public RSG.Tuple`2<T1,T2> Create(T1 item1, T2 item2)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T1, class T2>
static ::RSG::Tuple_2<T1, T2>* Create(T1 item1, T2 item2) {
static auto ___internal__logger = ::Logger::get().WithContext("::RSG::Tuple::Create");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("RSG", "Tuple", "Create", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item1), ::il2cpp_utils::ExtractType(item2)})));
static auto* ___generic__method = THROW_UNLESS((::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get()})));
return ::il2cpp_utils::RunMethodRethrow<::RSG::Tuple_2<T1, T2>*, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, item1, item2);
}
// static public RSG.Tuple`3<T1,T2,T3> Create(T1 item1, T2 item2, T3 item3)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T1, class T2, class T3>
static ::RSG::Tuple_3<T1, T2, T3>* Create(T1 item1, T2 item2, T3 item3) {
static auto ___internal__logger = ::Logger::get().WithContext("::RSG::Tuple::Create");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("RSG", "Tuple", "Create", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T3>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item1), ::il2cpp_utils::ExtractType(item2), ::il2cpp_utils::ExtractType(item3)})));
static auto* ___generic__method = THROW_UNLESS((::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T3>::get()})));
return ::il2cpp_utils::RunMethodRethrow<::RSG::Tuple_3<T1, T2, T3>*, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, item1, item2, item3);
}
// static public RSG.Tuple`4<T1,T2,T3,T4> Create(T1 item1, T2 item2, T3 item3, T4 item4)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T1, class T2, class T3, class T4>
static ::RSG::Tuple_4<T1, T2, T3, T4>* Create(T1 item1, T2 item2, T3 item3, T4 item4) {
static auto ___internal__logger = ::Logger::get().WithContext("::RSG::Tuple::Create");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("RSG", "Tuple", "Create", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T3>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T4>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item1), ::il2cpp_utils::ExtractType(item2), ::il2cpp_utils::ExtractType(item3), ::il2cpp_utils::ExtractType(item4)})));
static auto* ___generic__method = THROW_UNLESS((::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T3>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T4>::get()})));
return ::il2cpp_utils::RunMethodRethrow<::RSG::Tuple_4<T1, T2, T3, T4>*, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, item1, item2, item3, item4);
}
}; // RSG.Tuple
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: RSG::Tuple::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: RSG::Tuple::Create
// Il2CppName: Create
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: RSG::Tuple::Create
// Il2CppName: Create
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: RSG::Tuple::Create
// Il2CppName: Create
// Cannot write MetadataGetter for generic methods!
| 68.446809 | 583 | 0.727541 | v0idp |
a857926d1990db6a4478b7d1508a558a9b5e8134 | 2,016 | cpp | C++ | Genesis3D/v120/OpenSource/Tools/mkactor/AStudio/StdAfx.cpp | dumpinfo/WinMasterGame | 59d300ec77c46fec2a821b4cfa095af0c21e434c | [
"Unlicense"
] | null | null | null | Genesis3D/v120/OpenSource/Tools/mkactor/AStudio/StdAfx.cpp | dumpinfo/WinMasterGame | 59d300ec77c46fec2a821b4cfa095af0c21e434c | [
"Unlicense"
] | null | null | null | Genesis3D/v120/OpenSource/Tools/mkactor/AStudio/StdAfx.cpp | dumpinfo/WinMasterGame | 59d300ec77c46fec2a821b4cfa095af0c21e434c | [
"Unlicense"
] | null | null | null | /****************************************************************************************/
/* STDAFX.CPP */
/* */
/* Author: Jim Mischel */
/* Description: Standard MFC includes. */
/* */
/* The contents of this file are subject to the Genesis3D Public License */
/* Version 1.01 (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.genesis3d.com */
/* */
/* Software distributed under the License is distributed on an "AS IS" */
/* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See */
/* the License for the specific language governing rights and limitations */
/* under the License. */
/* */
/* The Original Code is Genesis3D, released March 25, 1999. */
/*Genesis3D Version 1.1 released November 15, 1999 */
/* Copyright (C) 1999 WildTangent, Inc. All Rights Reserved */
/* */
/****************************************************************************************/
// stdafx.cpp : source file that includes just the standard includes
// AStudio.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| 72 | 91 | 0.34871 | dumpinfo |
a85a9f40340d7abe6ff59b27922e0a85144e3d32 | 1,942 | cpp | C++ | descartes_trajectory/src/axial_symmetric_pt.cpp | shaun-edwards/descartes | 75baae4ceccf328ec2315d7fdbc247006949251c | [
"Apache-2.0"
] | null | null | null | descartes_trajectory/src/axial_symmetric_pt.cpp | shaun-edwards/descartes | 75baae4ceccf328ec2315d7fdbc247006949251c | [
"Apache-2.0"
] | 1 | 2016-11-03T18:42:03.000Z | 2016-11-03T18:47:20.000Z | descartes_trajectory/src/axial_symmetric_pt.cpp | shaun-edwards/descartes | 75baae4ceccf328ec2315d7fdbc247006949251c | [
"Apache-2.0"
] | null | null | null | #include "descartes_trajectory/axial_symmetric_pt.h"
using descartes_trajectory::TolerancedFrame;
using descartes_trajectory::AxialSymmetricPt;
using namespace descartes_core::utils;
static TolerancedFrame makeRotationalAxis(AxialSymmetricPt::FreeAxis axis)
{
using namespace descartes_trajectory;
Eigen::Affine3d rot = Eigen::Affine3d::Identity();
PositionTolerance pos_tol = ToleranceBase::zeroTolerance<PositionTolerance>(0,0,0);
OrientationTolerance orient_tol = ToleranceBase::createSymmetric<OrientationTolerance>(0.0, 0.0, 0.0,
((axis == AxialSymmetricPt::X_AXIS) ? 2*M_PI : 0.0),
((axis == AxialSymmetricPt::Y_AXIS) ? 2*M_PI : 0.0),
((axis == AxialSymmetricPt::Z_AXIS) ? 2*M_PI : 0.0));
return TolerancedFrame(rot, pos_tol, orient_tol);
}
namespace descartes_trajectory
{
AxialSymmetricPt::AxialSymmetricPt(double x, double y, double z, double rx, double ry, double rz,
double orient_increment, FreeAxis axis) :
CartTrajectoryPt(toFrame(x, y, z, rx, ry, rz, EulerConventions::XYZ),
makeRotationalAxis(axis),
Eigen::Affine3d::Identity(),
Eigen::Affine3d::Identity(),
0.0, // The position discretization
orient_increment) // Orientation discretization (starting at -2Pi and marching to 2Pi)
{
}
AxialSymmetricPt::AxialSymmetricPt(const Eigen::Affine3d& pose, double orient_increment, FreeAxis axis) :
CartTrajectoryPt(pose,
makeRotationalAxis(axis),
Eigen::Affine3d::Identity(),
Eigen::Affine3d::Identity(),
0.0, // The position discretization
orient_increment) // Orientation discretization (starting at -2Pi and marching to 2Pi)
{
}
} // end of namespace descartes_trajectory
| 41.319149 | 105 | 0.642122 | shaun-edwards |
a85d331d28dd0db9296751972ce0424c91ec1c51 | 1,498 | cxx | C++ | cgv/reflect/reflect_enum.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 11 | 2017-09-30T12:21:55.000Z | 2021-04-29T21:31:57.000Z | cgv/reflect/reflect_enum.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 2 | 2017-07-11T11:20:08.000Z | 2018-03-27T12:09:02.000Z | cgv/reflect/reflect_enum.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 24 | 2018-03-27T11:46:16.000Z | 2021-05-01T20:28:34.000Z | #include "reflect_enum.h"
#include <cgv/utils/convert.h>
#include <cgv/utils/scan_enum.h>
namespace cgv {
namespace reflect {
void abst_enum_reflection_traits::parse_declarations()
{
cgv::utils::parse_enum_declarations(declarations(), ref_names(), ref_values());
}
bool abst_enum_reflection_traits::has_string_conversions() const
{
return true;
}
bool abst_enum_reflection_traits::set_from_string(void* member_ptr, const std::string& str_val)
{
unsigned i = cgv::utils::find_enum_index(str_val, ref_names());
if (i == -1)
return false;
*static_cast<int*>(member_ptr) = ref_values()[i];
return true;
}
void abst_enum_reflection_traits::get_to_string(const void* member_ptr, std::string& str_val)
{
unsigned i = cgv::utils::find_enum_index(*static_cast<const int*>(member_ptr), ref_values());
if (i != -1)
str_val = to_string(ref_names()[i]);
else
str_val = "UNDEF";
}
bool abst_enum_reflection_traits::has_enum_interface() const
{
return true;
}
unsigned abst_enum_reflection_traits::get_nr_enum_items() const
{
return (unsigned) const_cast<abst_enum_reflection_traits*>(this)->ref_values().size();
}
std::string abst_enum_reflection_traits::get_enum_name(unsigned i) const
{
return to_string(const_cast<abst_enum_reflection_traits*>(this)->ref_names()[i]);
}
int abst_enum_reflection_traits::get_enum_value(unsigned i) const
{
return const_cast<abst_enum_reflection_traits*>(this)->ref_values()[i];
}
}
}
| 26.75 | 97 | 0.730975 | MarioHenze |
a85dc5bf5b4cb76bf77a0750e0662cb67b65b4ff | 7,478 | cpp | C++ | worker/src/Channel/ChannelSocket.cpp | kcking/mediasoup | f385349d0f06fe14a4e38d50f0212b48d588fa32 | [
"ISC"
] | 29 | 2020-09-27T12:14:18.000Z | 2022-02-28T15:58:03.000Z | worker/src/Channel/ChannelSocket.cpp | kcking/mediasoup | f385349d0f06fe14a4e38d50f0212b48d588fa32 | [
"ISC"
] | 10 | 2021-10-10T14:04:01.000Z | 2022-03-21T09:39:14.000Z | worker/src/Channel/ChannelSocket.cpp | kcking/mediasoup | f385349d0f06fe14a4e38d50f0212b48d588fa32 | [
"ISC"
] | 7 | 2021-01-12T03:07:14.000Z | 2021-08-23T14:43:32.000Z | #define MS_CLASS "Channel::ChannelSocket"
// #define MS_LOG_DEV_LEVEL 3
#include "Channel/ChannelSocket.hpp"
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include <cmath> // std::ceil()
#include <cstdio> // sprintf()
#include <cstring> // std::memcpy(), std::memmove()
namespace Channel
{
/* Static methods for UV callbacks. */
inline static void onAsync(uv_handle_t* handle)
{
while (static_cast<ChannelSocket*>(handle->data)->CallbackRead())
{
// Read while there are new messages.
}
}
inline static void onClose(uv_handle_t* handle)
{
delete handle;
}
// Binary length for a 4194304 bytes payload.
static constexpr size_t MessageMaxLen{ 4194308 };
static constexpr size_t PayloadMaxLen{ 4194304 };
/* Instance methods. */
ChannelSocket::ChannelSocket(int consumerFd, int producerFd)
: consumerSocket(new ConsumerSocket(consumerFd, MessageMaxLen, this)),
producerSocket(new ProducerSocket(producerFd, MessageMaxLen)),
writeBuffer(static_cast<uint8_t*>(std::malloc(MessageMaxLen)))
{
MS_TRACE_STD();
}
ChannelSocket::ChannelSocket(
ChannelReadFn channelReadFn,
ChannelReadCtx channelReadCtx,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx)
: channelReadFn(channelReadFn), channelReadCtx(channelReadCtx), channelWriteFn(channelWriteFn),
channelWriteCtx(channelWriteCtx)
{
MS_TRACE_STD();
int err;
this->uvReadHandle = new uv_async_t;
this->uvReadHandle->data = static_cast<void*>(this);
err =
uv_async_init(DepLibUV::GetLoop(), this->uvReadHandle, reinterpret_cast<uv_async_cb>(onAsync));
if (err != 0)
{
delete this->uvReadHandle;
this->uvReadHandle = nullptr;
MS_THROW_ERROR_STD("uv_async_init() failed: %s", uv_strerror(err));
}
err = uv_async_send(this->uvReadHandle);
if (err != 0)
{
delete this->uvReadHandle;
this->uvReadHandle = nullptr;
MS_THROW_ERROR_STD("uv_async_send() failed: %s", uv_strerror(err));
}
}
ChannelSocket::~ChannelSocket()
{
MS_TRACE_STD();
std::free(this->writeBuffer);
if (!this->closed)
Close();
delete this->consumerSocket;
delete this->producerSocket;
}
void ChannelSocket::Close()
{
MS_TRACE_STD();
if (this->closed)
return;
this->closed = true;
if (this->uvReadHandle)
{
uv_close(reinterpret_cast<uv_handle_t*>(this->uvReadHandle), static_cast<uv_close_cb>(onClose));
}
if (this->consumerSocket)
{
this->consumerSocket->Close();
}
if (this->producerSocket)
{
this->producerSocket->Close();
}
}
void ChannelSocket::SetListener(Listener* listener)
{
MS_TRACE_STD();
this->listener = listener;
}
void ChannelSocket::Send(json& jsonMessage)
{
MS_TRACE_STD();
if (this->closed)
return;
std::string message = jsonMessage.dump();
if (message.length() > PayloadMaxLen)
{
MS_ERROR_STD("message too big");
return;
}
SendImpl(
reinterpret_cast<const uint8_t*>(message.c_str()), static_cast<uint32_t>(message.length()));
}
void ChannelSocket::SendLog(const char* message, uint32_t messageLen)
{
MS_TRACE_STD();
if (this->closed)
return;
if (messageLen > PayloadMaxLen)
{
MS_ERROR_STD("message too big");
return;
}
SendImpl(reinterpret_cast<const uint8_t*>(message), messageLen);
}
bool ChannelSocket::CallbackRead()
{
MS_TRACE_STD();
if (this->closed)
return false;
uint8_t* message{ nullptr };
uint32_t messageLen;
size_t messageCtx;
auto free = this->channelReadFn(
&message, &messageLen, &messageCtx, this->uvReadHandle, this->channelReadCtx);
if (free)
{
try
{
json jsonMessage = json::parse(message, message + static_cast<size_t>(messageLen));
auto* request = new Channel::ChannelRequest(this, jsonMessage);
// Notify the listener.
try
{
this->listener->OnChannelRequest(this, request);
}
catch (const MediaSoupTypeError& error)
{
request->TypeError(error.what());
}
catch (const MediaSoupError& error)
{
request->Error(error.what());
}
// Delete the Request.
delete request;
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR_STD("discarding wrong Channel request");
}
free(message, messageLen, messageCtx);
}
return free != nullptr;
}
inline void ChannelSocket::SendImpl(const uint8_t* payload, uint32_t payloadLen)
{
MS_TRACE_STD();
// Write using function call if provided.
if (this->channelWriteFn)
{
this->channelWriteFn(payload, payloadLen, this->channelWriteCtx);
}
else
{
std::memcpy(this->writeBuffer, &payloadLen, sizeof(uint32_t));
if (payloadLen != 0)
{
std::memcpy(this->writeBuffer + sizeof(uint32_t), payload, payloadLen);
}
size_t len = sizeof(uint32_t) + payloadLen;
this->producerSocket->Write(this->writeBuffer, len);
}
}
void ChannelSocket::OnConsumerSocketMessage(ConsumerSocket* /*consumerSocket*/, char* msg, size_t msgLen)
{
MS_TRACE_STD();
try
{
json jsonMessage = json::parse(msg, msg + msgLen);
auto* request = new Channel::ChannelRequest(this, jsonMessage);
// Notify the listener.
try
{
this->listener->OnChannelRequest(this, request);
}
catch (const MediaSoupTypeError& error)
{
request->TypeError(error.what());
}
catch (const MediaSoupError& error)
{
request->Error(error.what());
}
// Delete the Request.
delete request;
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR_STD("discarding wrong Channel request");
}
}
void ChannelSocket::OnConsumerSocketClosed(ConsumerSocket* /*consumerSocket*/)
{
MS_TRACE_STD();
this->listener->OnChannelClosed(this);
}
ConsumerSocket::ConsumerSocket(int fd, size_t bufferSize, Listener* listener)
: ::UnixStreamSocket(fd, bufferSize, ::UnixStreamSocket::Role::CONSUMER), listener(listener)
{
MS_TRACE_STD();
}
void ConsumerSocket::UserOnUnixStreamRead()
{
MS_TRACE_STD();
size_t msgStart{ 0 };
// Be ready to parse more than a single message in a single chunk.
while (true)
{
if (IsClosed())
return;
size_t readLen = this->bufferDataLen - msgStart;
if (readLen < sizeof(uint32_t))
{
// Incomplete data.
break;
}
uint32_t msgLen;
// Read message length.
std::memcpy(&msgLen, this->buffer + msgStart, sizeof(uint32_t));
if (readLen < sizeof(uint32_t) + static_cast<size_t>(msgLen))
{
// Incomplete data.
break;
}
this->listener->OnConsumerSocketMessage(
this,
reinterpret_cast<char*>(this->buffer + msgStart + sizeof(uint32_t)),
static_cast<size_t>(msgLen));
msgStart += sizeof(uint32_t) + static_cast<size_t>(msgLen);
}
if (msgStart != 0)
{
this->bufferDataLen = this->bufferDataLen - msgStart;
if (this->bufferDataLen != 0)
{
std::memmove(this->buffer, this->buffer + msgStart, this->bufferDataLen);
}
}
}
void ConsumerSocket::UserOnUnixStreamSocketClosed()
{
MS_TRACE_STD();
// Notify the listener.
this->listener->OnConsumerSocketClosed(this);
}
ProducerSocket::ProducerSocket(int fd, size_t bufferSize)
: ::UnixStreamSocket(fd, bufferSize, ::UnixStreamSocket::Role::PRODUCER)
{
MS_TRACE_STD();
}
} // namespace Channel
| 21.426934 | 106 | 0.681733 | kcking |
a8634c0220e2b4ba4d6cd9458efbeef840cd96e3 | 3,171 | cpp | C++ | code/cheonsa/cheonsa__types_vector32x3.cpp | Olaedaria/cheonsa | cf366a5869a4bf0872a0d8dc6a01a68118cfc92e | [
"Unlicense"
] | null | null | null | code/cheonsa/cheonsa__types_vector32x3.cpp | Olaedaria/cheonsa | cf366a5869a4bf0872a0d8dc6a01a68118cfc92e | [
"Unlicense"
] | null | null | null | code/cheonsa/cheonsa__types_vector32x3.cpp | Olaedaria/cheonsa | cf366a5869a4bf0872a0d8dc6a01a68118cfc92e | [
"Unlicense"
] | null | null | null | #include "cheonsa__types_vector32x3.h"
#include "cheonsa__types_vector64x3.h"
#include <cassert>
namespace cheonsa
{
vector32x3_c::vector32x3_c()
: a( 0.0f )
, b( 0.0f )
, c( 0.0f )
{
}
vector32x3_c::vector32x3_c( float32_c const a, float32_c const b, float32_c const c )
: a( a )
, b( b )
, c( c )
{
}
vector32x3_c::vector32x3_c( float32_c const * values )
: a( values[ 0 ] )
, b( values[ 1 ] )
, c( values[ 2 ] )
{
}
vector32x3_c::vector32x3_c( vector64x3_c const & other )
: a( static_cast< float32_c >( other.a ) )
, b( static_cast< float32_c >( other.b ) )
, c( static_cast< float32_c >( other.c ) )
{
}
float32_c & vector32x3_c::get_element_at_index( sint32_c index )
{
assert( index >= 0 && index < 3 );
return reinterpret_cast< float32_c * >( this )[ index ];
}
float32_c const & vector32x3_c::get_element_at_index( sint32_c index ) const
{
assert( index >= 0 && index < 3 );
return reinterpret_cast< float32_c const * >( this )[ index ];
}
float32_c vector32x3_c::get_largest_element() const
{
float32_c result = a > b ? a : b;
result = c > result ? c : result;
return result;
}
vector32x3_c & vector32x3_c::operator *= ( float32_c b )
{
this->a *= b;
this->b *= b;
this->c *= b;
return * this;
}
vector32x3_c & vector32x3_c::operator /= ( float32_c b )
{
this->a /= b;
this->b /= b;
this->c /= b;
return * this;
}
vector32x3_c & vector32x3_c::operator += ( vector32x3_c const & b )
{
this->a += b.a;
this->b += b.b;
this->c += b.c;
return * this;
}
vector32x3_c & vector32x3_c::operator -= ( vector32x3_c const & b )
{
this->a -= b.a;
this->b -= b.b;
this->c -= b.c;
return * this;
}
vector32x3_c & vector32x3_c::operator *= ( vector32x3_c const & b )
{
this->a *= b.a;
this->b *= b.b;
this->c *= b.c;
return * this;
}
vector32x3_c & vector32x3_c::operator /= ( vector32x3_c const & b )
{
this->a /= b.a;
this->b /= b.b;
this->c /= b.c;
return * this;
}
boolean_c operator == ( vector32x3_c const & a, vector32x3_c const & b )
{
return ( a.a == b.a ) && ( a.b == b.b ) && ( a.c == b.c );
}
boolean_c operator != ( vector32x3_c const & a, vector32x3_c const & b )
{
return ( a.a != b.a ) || ( a.b != b.b ) || ( a.c != b.c );
}
vector32x3_c operator - ( vector32x3_c const & a )
{
return vector32x3_c( -a.a, -a.b, -a.c );
}
vector32x3_c operator * ( vector32x3_c a, float32_c b )
{
return a *= b;
}
vector32x3_c operator / ( vector32x3_c a, float32_c b )
{
return a /= b;
}
vector32x3_c operator + ( vector32x3_c a, vector32x3_c const & b )
{
return a += b;
}
vector32x3_c operator - ( vector32x3_c a, vector32x3_c const & b )
{
return a -= b;
}
vector32x3_c operator * ( vector32x3_c a, vector32x3_c const & b )
{
return a *= b;
}
vector32x3_c operator / ( vector32x3_c a, vector32x3_c const & b )
{
return a /= b;
}
vector64x3_c operator * ( vector32x3_c a, float64_c b )
{
return vector64x3_c( a.a * b, a.b * b, a.c * b );
}
vector64x3_c operator * ( vector32x3_c a, vector64x3_c const & b )
{
return vector64x3_c( a.a * b.a, a.b * b.b, a.c * b.c );
}
}
| 19.943396 | 86 | 0.597288 | Olaedaria |
a863ed98d0ee2dd3567f2c52b3b18ed0d8fdab81 | 857 | hpp | C++ | libs/fnd/algorithm/include/bksge/fnd/algorithm/detail/nth_element.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/algorithm/include/bksge/fnd/algorithm/detail/nth_element.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/algorithm/include/bksge/fnd/algorithm/detail/nth_element.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file nth_element.hpp
*
* @brief nth_element の実装
*
* @author myoukaku
*/
#ifndef BKSGE_FND_ALGORITHM_DETAIL_NTH_ELEMENT_HPP
#define BKSGE_FND_ALGORITHM_DETAIL_NTH_ELEMENT_HPP
#include <bksge/fnd/algorithm/detail/introselect.hpp>
#include <bksge/fnd/algorithm/detail/lg.hpp>
#include <bksge/fnd/config.hpp>
namespace bksge
{
namespace detail
{
template <typename RandomAccessIterator, typename Compare>
inline BKSGE_CXX14_CONSTEXPR void
nth_element(
RandomAccessIterator first,
RandomAccessIterator nth,
RandomAccessIterator last,
Compare comp)
{
if (first == last || nth == last)
{
return;
}
bksge::detail::introselect(
first, nth, last, bksge::detail::lg(last - first) * 2, comp);
}
} // namespace detail
} // namespace bksge
#endif // BKSGE_FND_ALGORITHM_DETAIL_NTH_ELEMENT_HPP
| 19.477273 | 64 | 0.718786 | myoukaku |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.