parent
2b8a658071
commit
19bf17c110
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,224 @@ |
||||
#pragma once |
||||
|
||||
#ifdef WIN32 |
||||
#include <windows.h> |
||||
#include <xinput.h> |
||||
|
||||
typedef DWORD(WINAPI XInputGetState_t)(DWORD dwUserIndex, XINPUT_STATE* pState); |
||||
static XInputGetState_t* XInputStateGet; |
||||
|
||||
typedef DWORD(WINAPI XInputSetState_t)(DWORD dwUserIndex, XINPUT_VIBRATION* pVibration); |
||||
static XInputSetState_t* XInputStateSet; |
||||
#endif |
||||
|
||||
#define C_BUTTON_COUNT 14 |
||||
enum CButton |
||||
{ |
||||
UP, |
||||
DOWN, |
||||
LEFT, |
||||
RIGHT, |
||||
START, |
||||
BACK, |
||||
A, |
||||
B, |
||||
X, |
||||
Y, |
||||
LEFT_SHOULDER, |
||||
RIGHT_SHOULDER, |
||||
LEFT_THUMB, |
||||
RIGHT_THUMB |
||||
}; |
||||
|
||||
struct CBState |
||||
{ |
||||
bool bPressed = false; |
||||
bool bReleased = false; |
||||
bool bHeld = false; |
||||
}; |
||||
|
||||
class ControllerManager |
||||
{ |
||||
private: |
||||
bool buttonState[C_BUTTON_COUNT]; |
||||
bool lastButtonState[C_BUTTON_COUNT]; |
||||
|
||||
// Trigger values are in the range of 0 to 1, where 0 is fully
|
||||
// released and 1 is fully pressed.
|
||||
float triggerLeft = 0; |
||||
float triggerRight = 0; |
||||
|
||||
// Stick values are in the range of -1 to 1. For X values, -1 is
|
||||
// all the way to the left while +1 is all the way to the right.
|
||||
float leftStickX = 0; |
||||
float leftStickY = 0; |
||||
float rightStickX = 0; |
||||
float rightStickY = 0; |
||||
|
||||
// Whether or not the controller is plugged in.
|
||||
bool pluggedIn = true; |
||||
|
||||
bool vibrating = false; |
||||
float vibrateTime = 0; |
||||
float vibrateCounter = 0; |
||||
|
||||
public: |
||||
bool Initialize(); |
||||
void Update(float dt); |
||||
|
||||
void Vibrate(short amt, int timeMs); |
||||
|
||||
CBState GetButton(CButton button); |
||||
|
||||
float GetLeftTrigger() { return triggerLeft; } |
||||
float GetRightTrigger() { return triggerRight; } |
||||
|
||||
float GetLeftStickX() { return leftStickX; } |
||||
float GetLeftStickY() { return leftStickY; } |
||||
|
||||
float GetRightStickX() { return rightStickX; } |
||||
float GetRightStickY() { return rightStickY; } |
||||
|
||||
bool IsVibrating() { return vibrating; } |
||||
bool IsPluggedIn() { return pluggedIn; } |
||||
|
||||
private: |
||||
float NormalizeStickValue(short value); |
||||
}; |
||||
|
||||
bool ControllerManager::Initialize() |
||||
{ |
||||
#ifdef WIN32 |
||||
// TODO: Should we check for version 9.1.0 if we fail to find 1.4?
|
||||
HMODULE lib = LoadLibraryA("xinput1_4.dll"); |
||||
|
||||
if (!lib) return false; |
||||
|
||||
XInputStateGet = (XInputGetState_t*)GetProcAddress(lib, "XInputGetState"); |
||||
XInputStateSet = (XInputSetState_t*)GetProcAddress(lib, "XInputSetState"); |
||||
#endif |
||||
|
||||
return true; |
||||
} |
||||
|
||||
float ControllerManager::NormalizeStickValue(short value) |
||||
{ |
||||
// The value we are given is in the range -32768 to 32767 with some deadzone around zero.
|
||||
// We will assume all values in this dead zone to be a reading of zero (the stick is not moved).
|
||||
if (value > -7000 && value < 7000) return 0; |
||||
|
||||
// Otherwise, we are going to normalize the value.
|
||||
return ((value + 32768.0f) / (32768.0f + 32767.0f) * 2) - 1; |
||||
} |
||||
|
||||
void ControllerManager::Vibrate(short amt, int timeMs) |
||||
{ |
||||
// If we are already vibrating, just ignore this, unless they say zero, in which case we will let them stop it.
|
||||
if (vibrating && amt != 0) return; |
||||
|
||||
// Only start the timer if we are actually vibrating.
|
||||
if (amt != 0) |
||||
{ |
||||
vibrateTime = timeMs / 1000.0f; |
||||
vibrating = true; |
||||
} |
||||
#ifdef WIN32 |
||||
XINPUT_VIBRATION info = |
||||
{ |
||||
amt, |
||||
amt |
||||
}; |
||||
XInputStateSet(0, &info); |
||||
#endif |
||||
} |
||||
|
||||
CBState ControllerManager::GetButton(CButton button) |
||||
{ |
||||
return |
||||
{ |
||||
!lastButtonState[button] && buttonState[button], |
||||
lastButtonState[button] && !buttonState[button], |
||||
lastButtonState[button] && buttonState[button] |
||||
}; |
||||
} |
||||
|
||||
void ControllerManager::Update(float dt) |
||||
{ |
||||
#ifdef WIN32 |
||||
if (vibrating) |
||||
{ |
||||
vibrateCounter += dt; |
||||
if (vibrateCounter >= vibrateTime) |
||||
{ |
||||
XINPUT_VIBRATION info = |
||||
{ |
||||
0, 0 |
||||
}; |
||||
XInputStateSet(0, &info); |
||||
|
||||
vibrating = false; |
||||
vibrateCounter = 0; |
||||
vibrateTime = 0; |
||||
} |
||||
} |
||||
|
||||
for (int i = 0; i < C_BUTTON_COUNT; i++) |
||||
{ |
||||
lastButtonState[i] = buttonState[i]; |
||||
} |
||||
|
||||
XINPUT_STATE state; |
||||
|
||||
// Try and get the first controller. For now we will only support a single one.
|
||||
DWORD res = XInputStateGet(0, &state); |
||||
|
||||
// If the controller is plugged in, handle input.
|
||||
if (res == ERROR_SUCCESS) |
||||
{ |
||||
XINPUT_GAMEPAD* pad = &state.Gamepad; |
||||
|
||||
buttonState[UP] = (pad->wButtons & XINPUT_GAMEPAD_DPAD_UP); |
||||
buttonState[DOWN] = (pad->wButtons & XINPUT_GAMEPAD_DPAD_DOWN); |
||||
buttonState[LEFT] = (pad->wButtons & XINPUT_GAMEPAD_DPAD_LEFT); |
||||
buttonState[RIGHT] = (pad->wButtons & XINPUT_GAMEPAD_DPAD_RIGHT); |
||||
buttonState[START] = (pad->wButtons & XINPUT_GAMEPAD_START); |
||||
buttonState[BACK] = (pad->wButtons & XINPUT_GAMEPAD_BACK); |
||||
buttonState[LEFT_SHOULDER] = (pad->wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER); |
||||
buttonState[RIGHT_SHOULDER] = (pad->wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER); |
||||
buttonState[LEFT_THUMB] = (pad->wButtons & XINPUT_GAMEPAD_LEFT_THUMB); |
||||
buttonState[RIGHT_THUMB] = (pad->wButtons & XINPUT_GAMEPAD_RIGHT_THUMB); |
||||
buttonState[A] = (pad->wButtons & XINPUT_GAMEPAD_A); |
||||
buttonState[B] = (pad->wButtons & XINPUT_GAMEPAD_B); |
||||
buttonState[X] = (pad->wButtons & XINPUT_GAMEPAD_X); |
||||
buttonState[Y] = (pad->wButtons & XINPUT_GAMEPAD_Y); |
||||
|
||||
triggerLeft = pad->bLeftTrigger / 255.0f; |
||||
triggerRight = pad->bRightTrigger / 255.0f; |
||||
leftStickX = NormalizeStickValue(pad->sThumbLX); |
||||
leftStickY = NormalizeStickValue(pad->sThumbLY); |
||||
rightStickX = NormalizeStickValue(pad->sThumbRX); |
||||
rightStickY = NormalizeStickValue(pad->sThumbRY); |
||||
|
||||
if (!pluggedIn) |
||||
{ |
||||
pluggedIn = true; |
||||
// Send callback.
|
||||
// printf("Plugged in.\n");
|
||||
} |
||||
} |
||||
else |
||||
{ |
||||
if (pluggedIn) |
||||
{ |
||||
pluggedIn = false; |
||||
// Send callback.
|
||||
// printf("Unplugged.\n");
|
||||
} |
||||
} |
||||
#else |
||||
for (int i = 0; i < C_BUTTON_COUNT; i++) |
||||
{ |
||||
lastButtonState[i] = buttonState[i] = false; |
||||
} |
||||
#endif |
||||
} |
@ -0,0 +1,42 @@ |
||||
License (OLC-3) |
||||
~~~~~~~~~~~~~~~ |
||||
|
||||
Copyright 2018 - 2019 OneLoneCoder.com |
||||
|
||||
Redistribution and use in source and binary forms, with or without |
||||
modification, are permitted provided that the following conditions |
||||
are met: |
||||
|
||||
1. Redistributions or derivations of source code must retain the above |
||||
copyright notice, this list of conditions and the following disclaimer. |
||||
|
||||
2. Redistributions or derivative works in binary form must reproduce |
||||
the above copyright notice. This list of conditions and the following |
||||
disclaimer must be reproduced in the documentation and/or other |
||||
materials provided with the distribution. |
||||
|
||||
3. Neither the name of the copyright holder 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. |
||||
|
||||
Links |
||||
~~~~~ |
||||
YouTube: https://www.youtube.com/javidx9 |
||||
Discord: https://discord.gg/WhwHUMV |
||||
Twitter: https://www.twitter.com/javidx9 |
||||
Twitch: https://www.twitch.tv/javidx9 |
||||
GitHub: https://www.github.com/onelonecoder |
||||
Homepage: https://www.onelonecoder.com |
||||
Patreon: https://www.patreon.com/javidx9 |
@ -0,0 +1,313 @@ |
||||
/*
|
||||
olcPGEX_Graphics2D.h |
||||
|
||||
+-------------------------------------------------------------+ |
||||
| OneLoneCoder Pixel Game Engine Extension | |
||||
| Advanced 2D Rendering - v0.4 | |
||||
+-------------------------------------------------------------+ |
||||
|
||||
What is this? |
||||
~~~~~~~~~~~~~ |
||||
This is an extension to the olcPixelGameEngine, which provides |
||||
advanced olc::Sprite manipulation and drawing routines. To use |
||||
it, simply include this header file. |
||||
|
||||
License (OLC-3) |
||||
~~~~~~~~~~~~~~~ |
||||
|
||||
Copyright 2018 - 2019 OneLoneCoder.com |
||||
|
||||
Redistribution and use in source and binary forms, with or without |
||||
modification, are permitted provided that the following conditions |
||||
are met: |
||||
|
||||
1. Redistributions or derivations of source code must retain the above |
||||
copyright notice, this list of conditions and the following disclaimer. |
||||
|
||||
2. Redistributions or derivative works in binary form must reproduce |
||||
the above copyright notice. This list of conditions and the following |
||||
disclaimer must be reproduced in the documentation and/or other |
||||
materials provided with the distribution. |
||||
|
||||
3. Neither the name of the copyright holder 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. |
||||
|
||||
Links |
||||
~~~~~ |
||||
YouTube: https://www.youtube.com/javidx9
|
||||
Discord: https://discord.gg/WhwHUMV
|
||||
Twitter: https://www.twitter.com/javidx9
|
||||
Twitch: https://www.twitch.tv/javidx9
|
||||
GitHub: https://www.github.com/onelonecoder
|
||||
Homepage: https://www.onelonecoder.com
|
||||
|
||||
Author |
||||
~~~~~~ |
||||
David Barr, aka javidx9, ©OneLoneCoder 2019 |
||||
*/ |
||||
|
||||
/*
|
||||
Matrices stored as [Column][Row] (i.e. x, y) |
||||
|
||||
|C0R0 C1R0 C2R0| | x | | x'| |
||||
|C0R1 C1R1 C2R1| * | y | = | y'| |
||||
|C0R2 C1R2 C2R2| |1.0| | - | |
||||
*/ |
||||
|
||||
|
||||
|
||||
#ifndef OLC_PGEX_GFX2D |
||||
#define OLC_PGEX_GFX2D |
||||
|
||||
#include <algorithm> |
||||
#undef min |
||||
#undef max |
||||
|
||||
namespace olc |
||||
{ |
||||
// Container class for Advanced 2D Drawing functions
|
||||
class GFX2D : public olc::PGEX |
||||
{ |
||||
// A representation of an affine transform, used to rotate, scale, offset & shear space
|
||||
public: |
||||
class Transform2D |
||||
{ |
||||
public: |
||||
Transform2D(); |
||||
|
||||
public: |
||||
// Set this transformation to unity
|
||||
void Reset(); |
||||
// Append a rotation of fTheta radians to this transform
|
||||
void Rotate(float fTheta); |
||||
// Append a translation (ox, oy) to this transform
|
||||
void Translate(float ox, float oy); |
||||
// Append a scaling operation (sx, sy) to this transform
|
||||
void Scale(float sx, float sy); |
||||
// Append a shear operation (sx, sy) to this transform
|
||||
void Shear(float sx, float sy); |
||||
|
||||
void Perspective(float ox, float oy); |
||||
// Calculate the Forward Transformation of the coordinate (in_x, in_y) -> (out_x, out_y)
|
||||
void Forward(float in_x, float in_y, float &out_x, float &out_y); |
||||
// Calculate the Inverse Transformation of the coordinate (in_x, in_y) -> (out_x, out_y)
|
||||
void Backward(float in_x, float in_y, float &out_x, float &out_y); |
||||
// Regenerate the Inverse Transformation
|
||||
void Invert(); |
||||
|
||||
private: |
||||
void Multiply(); |
||||
float matrix[4][3][3]; |
||||
int nTargetMatrix; |
||||
int nSourceMatrix; |
||||
bool bDirty; |
||||
}; |
||||
|
||||
public: |
||||
// Draws a sprite with the transform applied
|
||||
static void DrawSprite(olc::Sprite *sprite, olc::GFX2D::Transform2D &transform); |
||||
}; |
||||
} |
||||
|
||||
|
||||
#ifdef OLC_PGE_GRAPHICS2D |
||||
#undef OLC_PGE_GRAPHICS2D |
||||
|
||||
namespace olc |
||||
{ |
||||
void GFX2D::DrawSprite(olc::Sprite *sprite, olc::GFX2D::Transform2D &transform) |
||||
{ |
||||
if (sprite == nullptr) |
||||
return; |
||||
|
||||
// Work out bounding rectangle of sprite
|
||||
float ex, ey; |
||||
float sx, sy;
|
||||
float px, py; |
||||
|
||||
transform.Forward(0.0f, 0.0f, sx, sy); |
||||
px = sx; py = sy; |
||||
sx = std::min(sx, px); sy = std::min(sy, py); |
||||
ex = std::max(ex, px); ey = std::max(ey, py); |
||||
|
||||
transform.Forward((float)sprite->width, (float)sprite->height, px, py); |
||||
sx = std::min(sx, px); sy = std::min(sy, py); |
||||
ex = std::max(ex, px); ey = std::max(ey, py); |
||||
|
||||
transform.Forward(0.0f, (float)sprite->height, px, py); |
||||
sx = std::min(sx, px); sy = std::min(sy, py); |
||||
ex = std::max(ex, px); ey = std::max(ey, py); |
||||
|
||||
transform.Forward((float)sprite->width, 0.0f, px, py); |
||||
sx = std::min(sx, px); sy = std::min(sy, py); |
||||
ex = std::max(ex, px); ey = std::max(ey, py); |
||||
|
||||
// Perform inversion of transform if required
|
||||
transform.Invert(); |
||||
|
||||
if (ex < sx)
|
||||
std::swap(ex, sx); |
||||
if (ey < sy)
|
||||
std::swap(ey, sy); |
||||
|
||||
// Iterate through render space, and sample Sprite from suitable texel location
|
||||
for (float i = sx; i < ex; i++) |
||||
{ |
||||
for (float j = sy; j < ey; j++) |
||||
{ |
||||
float ox, oy; |
||||
transform.Backward(i, j, ox, oy); |
||||
pge->Draw((int32_t)i, (int32_t)j, sprite->GetPixel((int32_t)(ox+0.5f), (int32_t)(oy+0.5f))); |
||||
} |
||||
} |
||||
} |
||||
|
||||
olc::GFX2D::Transform2D::Transform2D() |
||||
{ |
||||
Reset(); |
||||
} |
||||
|
||||
void olc::GFX2D::Transform2D::Reset() |
||||
{ |
||||
nTargetMatrix = 0; |
||||
nSourceMatrix = 1; |
||||
bDirty = true; |
||||
|
||||
// Columns Then Rows
|
||||
|
||||
// Matrices 0 & 1 are used as swaps in Transform accumulation
|
||||
matrix[0][0][0] = 1.0f; matrix[0][1][0] = 0.0f; matrix[0][2][0] = 0.0f; |
||||
matrix[0][0][1] = 0.0f; matrix[0][1][1] = 1.0f; matrix[0][2][1] = 0.0f; |
||||
matrix[0][0][2] = 0.0f; matrix[0][1][2] = 0.0f; matrix[0][2][2] = 1.0f; |
||||
|
||||
matrix[1][0][0] = 1.0f; matrix[1][1][0] = 0.0f; matrix[1][2][0] = 0.0f; |
||||
matrix[1][0][1] = 0.0f; matrix[1][1][1] = 1.0f; matrix[1][2][1] = 0.0f; |
||||
matrix[1][0][2] = 0.0f; matrix[1][1][2] = 0.0f; matrix[1][2][2] = 1.0f; |
||||
|
||||
// Matrix 2 is a cache matrix to hold the immediate transform operation
|
||||
// Matrix 3 is a cache matrix to hold the inverted transform
|
||||
} |
||||
|
||||
void olc::GFX2D::Transform2D::Multiply() |
||||
{ |
||||
for (int c = 0; c < 3; c++) |
||||
{ |
||||
for (int r = 0; r < 3; r++) |
||||
{ |
||||
matrix[nTargetMatrix][c][r] = matrix[2][0][r] * matrix[nSourceMatrix][c][0] + |
||||
matrix[2][1][r] * matrix[nSourceMatrix][c][1] + |
||||
matrix[2][2][r] * matrix[nSourceMatrix][c][2]; |
||||
} |
||||
} |
||||
|
||||
std::swap(nTargetMatrix, nSourceMatrix); |
||||
bDirty = true; // Any transform multiply dirties the inversion
|
||||
} |
||||
|
||||
void olc::GFX2D::Transform2D::Rotate(float fTheta) |
||||
{
|
||||
// Construct Rotation Matrix
|
||||
matrix[2][0][0] = cosf(fTheta); matrix[2][1][0] = sinf(fTheta); matrix[2][2][0] = 0.0f; |
||||
matrix[2][0][1] = -sinf(fTheta); matrix[2][1][1] = cosf(fTheta); matrix[2][2][1] = 0.0f; |
||||
matrix[2][0][2] = 0.0f; matrix[2][1][2] = 0.0f; matrix[2][2][2] = 1.0f; |
||||
Multiply();
|
||||
} |
||||
|
||||
void olc::GFX2D::Transform2D::Scale(float sx, float sy) |
||||
{ |
||||
// Construct Scale Matrix
|
||||
matrix[2][0][0] = sx; matrix[2][1][0] = 0.0f; matrix[2][2][0] = 0.0f; |
||||
matrix[2][0][1] = 0.0f; matrix[2][1][1] = sy; matrix[2][2][1] = 0.0f; |
||||
matrix[2][0][2] = 0.0f; matrix[2][1][2] = 0.0f; matrix[2][2][2] = 1.0f; |
||||
Multiply(); |
||||
} |
||||
|
||||
void olc::GFX2D::Transform2D::Shear(float sx, float sy) |
||||
{ |
||||
// Construct Shear Matrix
|
||||
matrix[2][0][0] = 1.0f; matrix[2][1][0] = sx; matrix[2][2][0] = 0.0f; |
||||
matrix[2][0][1] = sy; matrix[2][1][1] = 1.0f; matrix[2][2][1] = 0.0f; |
||||
matrix[2][0][2] = 0.0f; matrix[2][1][2] = 0.0f; matrix[2][2][2] = 1.0f; |
||||
Multiply(); |
||||
} |
||||
|
||||
void olc::GFX2D::Transform2D::Translate(float ox, float oy) |
||||
{ |
||||
// Construct Translate Matrix
|
||||
matrix[2][0][0] = 1.0f; matrix[2][1][0] = 0.0f; matrix[2][2][0] = ox; |
||||
matrix[2][0][1] = 0.0f; matrix[2][1][1] = 1.0f; matrix[2][2][1] = oy; |
||||
matrix[2][0][2] = 0.0f; matrix[2][1][2] = 0.0f; matrix[2][2][2] = 1.0f; |
||||
Multiply(); |
||||
} |
||||
|
||||
void olc::GFX2D::Transform2D::Perspective(float ox, float oy) |
||||
{ |
||||
// Construct Translate Matrix
|
||||
matrix[2][0][0] = 1.0f; matrix[2][1][0] = 0.0f; matrix[2][2][0] = 0.0f; |
||||
matrix[2][0][1] = 0.0f; matrix[2][1][1] = 1.0f; matrix[2][2][1] = 0.0f; |
||||
matrix[2][0][2] = ox; matrix[2][1][2] = oy; matrix[2][2][2] = 1.0f; |
||||
Multiply(); |
||||
} |
||||
|
||||
void olc::GFX2D::Transform2D::Forward(float in_x, float in_y, float &out_x, float &out_y) |
||||
{ |
||||
out_x = in_x * matrix[nSourceMatrix][0][0] + in_y * matrix[nSourceMatrix][1][0] + matrix[nSourceMatrix][2][0]; |
||||
out_y = in_x * matrix[nSourceMatrix][0][1] + in_y * matrix[nSourceMatrix][1][1] + matrix[nSourceMatrix][2][1]; |
||||
float out_z = in_x * matrix[nSourceMatrix][0][2] + in_y * matrix[nSourceMatrix][1][2] + matrix[nSourceMatrix][2][2]; |
||||
if (out_z != 0) |
||||
{ |
||||
out_x /= out_z; |
||||
out_y /= out_z; |
||||
} |
||||
}
|
||||
|
||||
void olc::GFX2D::Transform2D::Backward(float in_x, float in_y, float &out_x, float &out_y) |
||||
{ |
||||
out_x = in_x * matrix[3][0][0] + in_y * matrix[3][1][0] + matrix[3][2][0]; |
||||
out_y = in_x * matrix[3][0][1] + in_y * matrix[3][1][1] + matrix[3][2][1]; |
||||
float out_z = in_x * matrix[3][0][2] + in_y * matrix[3][1][2] + matrix[3][2][2]; |
||||
if (out_z != 0) |
||||
{ |
||||
out_x /= out_z; |
||||
out_y /= out_z; |
||||
} |
||||
} |
||||
|
||||
void olc::GFX2D::Transform2D::Invert() |
||||
{ |
||||
if (bDirty) // Obviously costly so only do if needed
|
||||
{
|
||||
float det = matrix[nSourceMatrix][0][0] * (matrix[nSourceMatrix][1][1] * matrix[nSourceMatrix][2][2] - matrix[nSourceMatrix][1][2] * matrix[nSourceMatrix][2][1]) - |
||||
matrix[nSourceMatrix][1][0] * (matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][2][2] - matrix[nSourceMatrix][2][1] * matrix[nSourceMatrix][0][2]) + |
||||
matrix[nSourceMatrix][2][0] * (matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][1][2] - matrix[nSourceMatrix][1][1] * matrix[nSourceMatrix][0][2]); |
||||
|
||||
float idet = 1.0f / det; |
||||
matrix[3][0][0] = (matrix[nSourceMatrix][1][1] * matrix[nSourceMatrix][2][2] - matrix[nSourceMatrix][1][2] * matrix[nSourceMatrix][2][1]) * idet; |
||||
matrix[3][1][0] = (matrix[nSourceMatrix][2][0] * matrix[nSourceMatrix][1][2] - matrix[nSourceMatrix][1][0] * matrix[nSourceMatrix][2][2]) * idet; |
||||
matrix[3][2][0] = (matrix[nSourceMatrix][1][0] * matrix[nSourceMatrix][2][1] - matrix[nSourceMatrix][2][0] * matrix[nSourceMatrix][1][1]) * idet; |
||||
matrix[3][0][1] = (matrix[nSourceMatrix][2][1] * matrix[nSourceMatrix][0][2] - matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][2][2]) * idet; |
||||
matrix[3][1][1] = (matrix[nSourceMatrix][0][0] * matrix[nSourceMatrix][2][2] - matrix[nSourceMatrix][2][0] * matrix[nSourceMatrix][0][2]) * idet; |
||||
matrix[3][2][1] = (matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][2][0] - matrix[nSourceMatrix][0][0] * matrix[nSourceMatrix][2][1]) * idet; |
||||
matrix[3][0][2] = (matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][1][2] - matrix[nSourceMatrix][0][2] * matrix[nSourceMatrix][1][1]) * idet; |
||||
matrix[3][1][2] = (matrix[nSourceMatrix][0][2] * matrix[nSourceMatrix][1][0] - matrix[nSourceMatrix][0][0] * matrix[nSourceMatrix][1][2]) * idet; |
||||
matrix[3][2][2] = (matrix[nSourceMatrix][0][0] * matrix[nSourceMatrix][1][1] - matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][1][0]) * idet; |
||||
bDirty = false; |
||||
}
|
||||
} |
||||
} |
||||
|
||||
#endif |
||||
#endif |
@ -0,0 +1,906 @@ |
||||
/*
|
||||
olcPGEX_Sound.h |
||||
|
||||
+-------------------------------------------------------------+ |
||||
| OneLoneCoder Pixel Game Engine Extension | |
||||
| Sound - v0.4 | |
||||
+-------------------------------------------------------------+ |
||||
|
||||
What is this? |
||||
~~~~~~~~~~~~~ |
||||
This is an extension to the olcPixelGameEngine, which provides |
||||
sound generation and wave playing routines. |
||||
|
||||
Special Thanks: |
||||
~~~~~~~~~~~~~~~
|
||||
Slavka - For entire non-windows system back end! |
||||
Gorbit99 - Testing, Bug Fixes |
||||
Cyberdroid - Testing, Bug Fixes |
||||
Dragoneye - Testing |
||||
Puol - Testing |
||||
|
||||
License (OLC-3) |
||||
~~~~~~~~~~~~~~~ |
||||
|
||||
Copyright 2018 - 2019 OneLoneCoder.com |
||||
|
||||
Redistribution and use in source and binary forms, with or without |
||||
modification, are permitted provided that the following conditions |
||||
are met: |
||||
|
||||
1. Redistributions or derivations of source code must retain the above |
||||
copyright notice, this list of conditions and the following disclaimer. |
||||
|
||||
2. Redistributions or derivative works in binary form must reproduce |
||||
the above copyright notice. This list of conditions and the following |
||||
disclaimer must be reproduced in the documentation and/or other |
||||
materials provided with the distribution. |
||||
|
||||
3. Neither the name of the copyright holder 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. |
||||
|
||||
Links |
||||
~~~~~ |
||||
YouTube: https://www.youtube.com/javidx9
|
||||
Discord: https://discord.gg/WhwHUMV
|
||||
Twitter: https://www.twitter.com/javidx9
|
||||
Twitch: https://www.twitch.tv/javidx9
|
||||
GitHub: https://www.github.com/onelonecoder
|
||||
Homepage: https://www.onelonecoder.com
|
||||
Patreon: https://www.patreon.com/javidx9
|
||||
|
||||
Author |
||||
~~~~~~ |
||||
David Barr, aka javidx9, ©OneLoneCoder 2019 |
||||
*/ |
||||
|
||||
|
||||
#ifndef OLC_PGEX_SOUND_H |
||||
#define OLC_PGEX_SOUND_H |
||||
|
||||
#include <istream> |
||||
#include <cstring> |
||||
#include <climits> |
||||
|
||||
#include <algorithm> |
||||
#undef min |
||||
#undef max |
||||
|
||||
// Choose a default sound backend
|
||||
#if !defined(USE_ALSA) && !defined(USE_OPENAL) && !defined(USE_WINDOWS) |
||||
#ifdef __linux__ |
||||
#define USE_ALSA |
||||
#endif |
||||
|
||||
#ifdef __EMSCRIPTEN__ |
||||
#define USE_OPENAL |
||||
#endif |
||||
|
||||
#ifdef _WIN32 |
||||
#define USE_WINDOWS |
||||
#endif |
||||
|
||||
#endif |
||||
|
||||
#ifdef USE_ALSA |
||||
#define ALSA_PCM_NEW_HW_PARAMS_API |
||||
#include <alsa/asoundlib.h> |
||||
#endif |
||||
|
||||
#ifdef USE_OPENAL |
||||
#include <AL/al.h> |
||||
#include <AL/alc.h> |
||||
#include <queue> |
||||
#endif |
||||
|
||||
#pragma pack(push, 1) |
||||
typedef struct { |
||||
uint16_t wFormatTag; |
||||
uint16_t nChannels; |
||||
uint32_t nSamplesPerSec; |
||||
uint32_t nAvgBytesPerSec; |
||||
uint16_t nBlockAlign; |
||||
uint16_t wBitsPerSample; |
||||
uint16_t cbSize; |
||||
} OLC_WAVEFORMATEX; |
||||
#pragma pack(pop) |
||||
|
||||
namespace olc |
||||
{ |
||||
// Container class for Advanced 2D Drawing functions
|
||||
class SOUND : public olc::PGEX |
||||
{ |
||||
// A representation of an affine transform, used to rotate, scale, offset & shear space
|
||||
public: |
||||
class AudioSample |
||||
{ |
||||
public: |
||||
AudioSample(); |
||||
AudioSample(std::string sWavFile, olc::ResourcePack *pack = nullptr); |
||||
olc::rcode LoadFromFile(std::string sWavFile, olc::ResourcePack *pack = nullptr); |
||||
|
||||
public: |
||||
OLC_WAVEFORMATEX wavHeader; |
||||
float *fSample = nullptr; |
||||
long nSamples = 0; |
||||
int nChannels = 0; |
||||
bool bSampleValid = false; |
||||
}; |
||||
|
||||
struct sCurrentlyPlayingSample |
||||
{ |
||||
int nAudioSampleID = 0; |
||||
long nSamplePosition = 0; |
||||
bool bFinished = false; |
||||
bool bLoop = false; |
||||
bool bFlagForStop = false; |
||||
}; |
||||
|
||||
static std::list<sCurrentlyPlayingSample> listActiveSamples; |
||||
|
||||
public: |
||||
static bool InitialiseAudio(unsigned int nSampleRate = 44100, unsigned int nChannels = 1, unsigned int nBlocks = 8, unsigned int nBlockSamples = 512); |
||||
static bool DestroyAudio(); |
||||
static void SetUserSynthFunction(std::function<float(int, float, float)> func); |
||||
static void SetUserFilterFunction(std::function<float(int, float, float)> func); |
||||
|
||||
public: |
||||
static int LoadAudioSample(std::string sWavFile, olc::ResourcePack *pack = nullptr); |
||||
static void PlaySample(int id, bool bLoop = false); |
||||
static void StopSample(int id); |
||||
static void StopAll(); |
||||
static float GetMixerOutput(int nChannel, float fGlobalTime, float fTimeStep); |
||||
|
||||
|
||||
private: |
||||
#ifdef USE_WINDOWS // Windows specific sound management
|
||||
static void CALLBACK waveOutProc(HWAVEOUT hWaveOut, UINT uMsg, DWORD dwParam1, DWORD dwParam2); |
||||
static unsigned int m_nSampleRate; |
||||
static unsigned int m_nChannels; |
||||
static unsigned int m_nBlockCount; |
||||
static unsigned int m_nBlockSamples; |
||||
static unsigned int m_nBlockCurrent; |
||||
static short* m_pBlockMemory; |
||||
static WAVEHDR *m_pWaveHeaders; |
||||
static HWAVEOUT m_hwDevice; |
||||
static std::atomic<unsigned int> m_nBlockFree; |
||||
static std::condition_variable m_cvBlockNotZero; |
||||
static std::mutex m_muxBlockNotZero; |
||||
#endif |
||||
|
||||
#ifdef USE_ALSA |
||||
static snd_pcm_t *m_pPCM; |
||||
static unsigned int m_nSampleRate; |
||||
static unsigned int m_nChannels; |
||||
static unsigned int m_nBlockSamples; |
||||
static short* m_pBlockMemory; |
||||
#endif |
||||
|
||||
#ifdef USE_OPENAL |
||||
static std::queue<ALuint> m_qAvailableBuffers; |
||||
static ALuint *m_pBuffers; |
||||
static ALuint m_nSource; |
||||
static ALCdevice *m_pDevice; |
||||
static ALCcontext *m_pContext; |
||||
static unsigned int m_nSampleRate; |
||||
static unsigned int m_nChannels; |
||||
static unsigned int m_nBlockCount; |
||||
static unsigned int m_nBlockSamples; |
||||
static short* m_pBlockMemory; |
||||
#endif |
||||
|
||||
static void AudioThread(); |
||||
static std::thread m_AudioThread; |
||||
static std::atomic<bool> m_bAudioThreadActive; |
||||
static std::atomic<float> m_fGlobalTime; |
||||
static std::function<float(int, float, float)> funcUserSynth; |
||||
static std::function<float(int, float, float)> funcUserFilter; |
||||
}; |
||||
} |
||||
|
||||
|
||||
// Implementation, platform-independent
|
||||
|
||||
#ifdef OLC_PGEX_SOUND |
||||
#undef OLC_PGEX_SOUND |
||||
|
||||
namespace olc |
||||
{ |
||||
SOUND::AudioSample::AudioSample() |
||||
{ } |
||||
|
||||
SOUND::AudioSample::AudioSample(std::string sWavFile, olc::ResourcePack *pack) |
||||
{ |
||||
LoadFromFile(sWavFile, pack); |
||||
} |
||||
|
||||
olc::rcode SOUND::AudioSample::LoadFromFile(std::string sWavFile, olc::ResourcePack *pack) |
||||
{ |
||||
auto ReadWave = [&](std::istream &is) |
||||
{ |
||||
char dump[4]; |
||||
is.read(dump, sizeof(char) * 4); // Read "RIFF"
|
||||
if (strncmp(dump, "RIFF", 4) != 0) return olc::FAIL; |
||||
is.read(dump, sizeof(char) * 4); // Not Interested
|
||||
is.read(dump, sizeof(char) * 4); // Read "WAVE"
|
||||
if (strncmp(dump, "WAVE", 4) != 0) return olc::FAIL; |
||||
|
||||
// Read Wave description chunk
|
||||
is.read(dump, sizeof(char) * 4); // Read "fmt "
|
||||
unsigned int nHeaderSize = 0; |
||||
is.read((char*)&nHeaderSize, sizeof(unsigned int)); // Not Interested
|
||||
is.read((char*)&wavHeader, nHeaderSize);// sizeof(WAVEFORMATEX)); // Read Wave Format Structure chunk
|
||||
// Note the -2, because the structure has 2 bytes to indicate its own size
|
||||
// which are not in the wav file
|
||||
|
||||
// Just check if wave format is compatible with olcPGE
|
||||
if (wavHeader.wBitsPerSample != 16 || wavHeader.nSamplesPerSec != 44100) |
||||
return olc::FAIL; |
||||
|
||||
// Search for audio data chunk
|
||||
uint32_t nChunksize = 0; |
||||
is.read(dump, sizeof(char) * 4); // Read chunk header
|
||||
is.read((char*)&nChunksize, sizeof(uint32_t)); // Read chunk size
|
||||
while (strncmp(dump, "data", 4) != 0) |
||||
{ |
||||
// Not audio data, so just skip it
|
||||
//std::fseek(f, nChunksize, SEEK_CUR);
|
||||
is.seekg(nChunksize, std::istream::cur); |
||||
is.read(dump, sizeof(char) * 4); |
||||
is.read((char*)&nChunksize, sizeof(uint32_t)); |
||||
} |
||||
|
||||
// Finally got to data, so read it all in and convert to float samples
|
||||
nSamples = nChunksize / (wavHeader.nChannels * (wavHeader.wBitsPerSample >> 3)); |
||||
nChannels = wavHeader.nChannels; |
||||
|
||||
// Create floating point buffer to hold audio sample
|
||||
fSample = new float[nSamples * nChannels]; |
||||
float *pSample = fSample; |
||||
|
||||
// Read in audio data and normalise
|
||||
for (long i = 0; i < nSamples; i++) |
||||
{ |
||||
for (int c = 0; c < nChannels; c++) |
||||
{ |
||||
short s = 0; |
||||
if (!is.eof()) |
||||
{ |
||||
is.read((char*)&s, sizeof(short)); |
||||
|
||||
*pSample = (float)s / (float)(SHRT_MAX); |
||||
pSample++; |
||||
} |
||||
} |
||||
} |
||||
|
||||
// All done, flag sound as valid
|
||||
bSampleValid = true; |
||||
return olc::OK; |
||||
}; |
||||
|
||||
if (pack != nullptr) |
||||
{ |
||||
olc::ResourcePack::sEntry entry = pack->GetStreamBuffer(sWavFile); |
||||
std::istream is(&entry); |
||||
return ReadWave(is); |
||||
} |
||||
else |
||||
{ |
||||
// Read from file
|
||||
std::ifstream ifs(sWavFile, std::ifstream::binary); |
||||
if (ifs.is_open()) |
||||
{ |
||||
return ReadWave(ifs); |
||||
} |
||||
else |
||||
return olc::FAIL; |
||||
} |
||||
} |
||||
|
||||
// This vector holds all loaded sound samples in memory
|
||||
std::vector<olc::SOUND::AudioSample> vecAudioSamples; |
||||
|
||||
// This structure represents a sound that is currently playing. It only
|
||||
// holds the sound ID and where this instance of it is up to for its
|
||||
// current playback
|
||||
|
||||
void SOUND::SetUserSynthFunction(std::function<float(int, float, float)> func) |
||||
{ |
||||
funcUserSynth = func; |
||||
} |
||||
|
||||
void SOUND::SetUserFilterFunction(std::function<float(int, float, float)> func) |
||||
{ |
||||
funcUserFilter = func; |
||||
} |
||||
|
||||
// Load a 16-bit WAVE file @ 44100Hz ONLY into memory. A sample ID
|
||||
// number is returned if successful, otherwise -1
|
||||
int SOUND::LoadAudioSample(std::string sWavFile, olc::ResourcePack *pack) |
||||
{ |
||||
|
||||
olc::SOUND::AudioSample a(sWavFile, pack); |
||||
if (a.bSampleValid) |
||||
{ |
||||
vecAudioSamples.push_back(a); |
||||
return (unsigned int)vecAudioSamples.size(); |
||||
} |
||||
else |
||||
return -1; |
||||
} |
||||
|
||||
// Add sample 'id' to the mixers sounds to play list
|
||||
void SOUND::PlaySample(int id, bool bLoop) |
||||
{ |
||||
olc::SOUND::sCurrentlyPlayingSample a; |
||||
a.nAudioSampleID = id; |
||||
a.nSamplePosition = 0; |
||||
a.bFinished = false; |
||||
a.bFlagForStop = false; |
||||
a.bLoop = bLoop; |
||||
SOUND::listActiveSamples.push_back(a); |
||||
} |
||||
|
||||
void SOUND::StopSample(int id) |
||||
{ |
||||
// Find first occurence of sample id
|
||||
auto s = std::find_if(listActiveSamples.begin(), listActiveSamples.end(), [&](const olc::SOUND::sCurrentlyPlayingSample &s) { return s.nAudioSampleID == id; }); |
||||
if (s != listActiveSamples.end()) |
||||
s->bFlagForStop = true; |
||||
} |
||||
|
||||
void SOUND::StopAll() |
||||
{ |
||||
for (auto &s : listActiveSamples) |
||||
{ |
||||
s.bFlagForStop = true; |
||||
} |
||||
} |
||||
|
||||
float SOUND::GetMixerOutput(int nChannel, float fGlobalTime, float fTimeStep) |
||||
{ |
||||
// Accumulate sample for this channel
|
||||
float fMixerSample = 0.0f; |
||||
|
||||
for (auto &s : listActiveSamples) |
||||
{ |
||||
if (m_bAudioThreadActive) |
||||
{ |
||||
if (s.bFlagForStop) |
||||
{ |
||||
s.bLoop = false; |
||||
s.bFinished = true; |
||||
} |
||||
else |
||||
{ |
||||
// Calculate sample position
|
||||
s.nSamplePosition += roundf((float)vecAudioSamples[s.nAudioSampleID - 1].wavHeader.nSamplesPerSec * fTimeStep); |
||||
|
||||
// If sample position is valid add to the mix
|
||||
if (s.nSamplePosition < vecAudioSamples[s.nAudioSampleID - 1].nSamples) |
||||
fMixerSample += vecAudioSamples[s.nAudioSampleID - 1].fSample[(s.nSamplePosition * vecAudioSamples[s.nAudioSampleID - 1].nChannels) + nChannel]; |
||||
else |
||||
{ |
||||
if (s.bLoop) |
||||
{ |
||||
s.nSamplePosition = 0; |
||||
} |
||||
else |
||||
s.bFinished = true; // Else sound has completed
|
||||
} |
||||
} |
||||
} |
||||
else |
||||
return 0.0f; |
||||
} |
||||
|
||||
// If sounds have completed then remove them
|
||||
listActiveSamples.remove_if([](const sCurrentlyPlayingSample &s) {return s.bFinished; }); |
||||
|
||||
// The users application might be generating sound, so grab that if it exists
|
||||
if (funcUserSynth != nullptr) |
||||
fMixerSample += funcUserSynth(nChannel, fGlobalTime, fTimeStep); |
||||
|
||||
// Return the sample via an optional user override to filter the sound
|
||||
if (funcUserFilter != nullptr) |
||||
return funcUserFilter(nChannel, fGlobalTime, fMixerSample); |
||||
else |
||||
return fMixerSample; |
||||
} |
||||
|
||||
std::thread SOUND::m_AudioThread; |
||||
std::atomic<bool> SOUND::m_bAudioThreadActive{ false }; |
||||
std::atomic<float> SOUND::m_fGlobalTime{ 0.0f }; |
||||
std::list<SOUND::sCurrentlyPlayingSample> SOUND::listActiveSamples; |
||||
std::function<float(int, float, float)> SOUND::funcUserSynth = nullptr; |
||||
std::function<float(int, float, float)> SOUND::funcUserFilter = nullptr; |
||||
} |
||||
|
||||
// Implementation, Windows-specific
|
||||
#ifdef USE_WINDOWS |
||||
#pragma comment(lib, "winmm.lib") |
||||
|
||||
namespace olc |
||||
{ |
||||
bool SOUND::InitialiseAudio(unsigned int nSampleRate, unsigned int nChannels, unsigned int nBlocks, unsigned int nBlockSamples) |
||||
{ |
||||
// Initialise Sound Engine
|
||||
m_bAudioThreadActive = false; |
||||
m_nSampleRate = nSampleRate; |
||||
m_nChannels = nChannels; |
||||
m_nBlockCount = nBlocks; |
||||
m_nBlockSamples = nBlockSamples; |
||||
m_nBlockFree = m_nBlockCount; |
||||
m_nBlockCurrent = 0; |
||||
m_pBlockMemory = nullptr; |
||||
m_pWaveHeaders = nullptr; |
||||
|
||||
// Device is available
|
||||
WAVEFORMATEX waveFormat; |
||||
waveFormat.wFormatTag = WAVE_FORMAT_PCM; |
||||
waveFormat.nSamplesPerSec = m_nSampleRate; |
||||
waveFormat.wBitsPerSample = sizeof(short) * 8; |
||||
waveFormat.nChannels = m_nChannels; |
||||
waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels; |
||||
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign; |
||||
waveFormat.cbSize = 0; |
||||
|
||||
listActiveSamples.clear(); |
||||
|
||||
// Open Device if valid
|
||||
if (waveOutOpen(&m_hwDevice, WAVE_MAPPER, &waveFormat, (DWORD_PTR)SOUND::waveOutProc, (DWORD_PTR)0, CALLBACK_FUNCTION) != S_OK) |
||||
return DestroyAudio(); |
||||
|
||||
// Allocate Wave|Block Memory
|
||||
m_pBlockMemory = new short[m_nBlockCount * m_nBlockSamples]; |
||||
if (m_pBlockMemory == nullptr) |
||||
return DestroyAudio(); |
||||
ZeroMemory(m_pBlockMemory, sizeof(short) * m_nBlockCount * m_nBlockSamples); |
||||
|
||||
m_pWaveHeaders = new WAVEHDR[m_nBlockCount]; |
||||
if (m_pWaveHeaders == nullptr) |
||||
return DestroyAudio(); |
||||
ZeroMemory(m_pWaveHeaders, sizeof(WAVEHDR) * m_nBlockCount); |
||||
|
||||
// Link headers to block memory
|
||||
for (unsigned int n = 0; n < m_nBlockCount; n++) |
||||
{ |
||||
m_pWaveHeaders[n].dwBufferLength = m_nBlockSamples * sizeof(short); |
||||
m_pWaveHeaders[n].lpData = (LPSTR)(m_pBlockMemory + (n * m_nBlockSamples)); |
||||
} |
||||
|
||||
m_bAudioThreadActive = true; |
||||
m_AudioThread = std::thread(&SOUND::AudioThread); |
||||
|
||||
// Start the ball rolling with the sound delivery thread
|
||||
std::unique_lock<std::mutex> lm(m_muxBlockNotZero); |
||||
m_cvBlockNotZero.notify_one(); |
||||
return true; |
||||
} |
||||
|
||||
// Stop and clean up audio system
|
||||
bool SOUND::DestroyAudio() |
||||
{ |
||||
m_bAudioThreadActive = false; |
||||
if(m_AudioThread.joinable()) |
||||
m_AudioThread.join(); |
||||
return false; |
||||
} |
||||
|
||||
// Handler for soundcard request for more data
|
||||
void CALLBACK SOUND::waveOutProc(HWAVEOUT hWaveOut, UINT uMsg, DWORD dwParam1, DWORD dwParam2) |
||||
{ |
||||
if (uMsg != WOM_DONE) return; |
||||
m_nBlockFree++; |
||||
std::unique_lock<std::mutex> lm(m_muxBlockNotZero); |
||||
m_cvBlockNotZero.notify_one(); |
||||
} |
||||
|
||||
// Audio thread. This loop responds to requests from the soundcard to fill 'blocks'
|
||||
// with audio data. If no requests are available it goes dormant until the sound
|
||||
// card is ready for more data. The block is fille by the "user" in some manner
|
||||
// and then issued to the soundcard.
|
||||
void SOUND::AudioThread() |
||||
{ |
||||
m_fGlobalTime = 0.0f; |
||||
static float fTimeStep = 1.0f / (float)m_nSampleRate; |
||||
|
||||
// Goofy hack to get maximum integer for a type at run-time
|
||||
short nMaxSample = (short)pow(2, (sizeof(short) * 8) - 1) - 1; |
||||
float fMaxSample = (float)nMaxSample; |
||||
short nPreviousSample = 0; |
||||
|
||||
auto tp1 = std::chrono::system_clock::now(); |
||||
auto tp2 = std::chrono::system_clock::now(); |
||||
|
||||
while (m_bAudioThreadActive) |
||||
{ |
||||
// Wait for block to become available
|
||||
if (m_nBlockFree == 0) |
||||
{ |
||||
std::unique_lock<std::mutex> lm(m_muxBlockNotZero); |
||||
while (m_nBlockFree == 0) // sometimes, Windows signals incorrectly
|
||||
m_cvBlockNotZero.wait(lm); |
||||
} |
||||
|
||||
// Block is here, so use it
|
||||
m_nBlockFree--; |
||||
|
||||
// Prepare block for processing
|
||||
if (m_pWaveHeaders[m_nBlockCurrent].dwFlags & WHDR_PREPARED) |
||||
waveOutUnprepareHeader(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR)); |
||||
|
||||
short nNewSample = 0; |
||||
int nCurrentBlock = m_nBlockCurrent * m_nBlockSamples; |
||||
|
||||
auto clip = [](float fSample, float fMax) |
||||
{ |
||||
if (fSample >= 0.0) |
||||
return fmin(fSample, fMax); |
||||
else |
||||
return fmax(fSample, -fMax); |
||||
}; |
||||
|
||||
tp2 = std::chrono::system_clock::now(); |
||||
std::chrono::duration<float> elapsedTime = tp2 - tp1; |
||||
tp1 = tp2; |
||||
|
||||
// Our time per frame coefficient
|
||||
float fElapsedTime = elapsedTime.count(); |
||||
|
||||
for (unsigned int n = 0; n < m_nBlockSamples; n += m_nChannels) |
||||
{ |
||||
// User Process
|
||||
for (unsigned int c = 0; c < m_nChannels; c++) |
||||
{ |
||||
nNewSample = (short)(clip(GetMixerOutput(c, m_fGlobalTime + fTimeStep * (float)n, fTimeStep), 1.0) * fMaxSample); |
||||
m_pBlockMemory[nCurrentBlock + n + c] = nNewSample; |
||||
nPreviousSample = nNewSample; |
||||
}
|
||||
} |
||||
|
||||
m_fGlobalTime = m_fGlobalTime + fTimeStep * (float)m_nBlockSamples; |
||||
|
||||
// Send block to sound device
|
||||
waveOutPrepareHeader(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR)); |
||||
waveOutWrite(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR)); |
||||
m_nBlockCurrent++; |
||||
m_nBlockCurrent %= m_nBlockCount; |
||||
} |
||||
} |
||||
|
||||
unsigned int SOUND::m_nSampleRate = 0; |
||||
unsigned int SOUND::m_nChannels = 0; |
||||
unsigned int SOUND::m_nBlockCount = 0; |
||||
unsigned int SOUND::m_nBlockSamples = 0; |
||||
unsigned int SOUND::m_nBlockCurrent = 0; |
||||
short* SOUND::m_pBlockMemory = nullptr; |
||||
WAVEHDR *SOUND::m_pWaveHeaders = nullptr; |
||||
HWAVEOUT SOUND::m_hwDevice; |
||||
std::atomic<unsigned int> SOUND::m_nBlockFree = 0; |
||||
std::condition_variable SOUND::m_cvBlockNotZero; |
||||
std::mutex SOUND::m_muxBlockNotZero; |
||||
} |
||||
|
||||
#elif defined(USE_ALSA) |
||||
|
||||
namespace olc |
||||
{ |
||||
bool SOUND::InitialiseAudio(unsigned int nSampleRate, unsigned int nChannels, unsigned int nBlocks, unsigned int nBlockSamples) |
||||
{ |
||||
// Initialise Sound Engine
|
||||
m_bAudioThreadActive = false; |
||||
m_nSampleRate = nSampleRate; |
||||
m_nChannels = nChannels; |
||||
m_nBlockSamples = nBlockSamples; |
||||
m_pBlockMemory = nullptr; |
||||
|
||||
// Open PCM stream
|
||||
int rc = snd_pcm_open(&m_pPCM, "default", SND_PCM_STREAM_PLAYBACK, 0); |
||||
if (rc < 0) |
||||
return DestroyAudio(); |
||||
|
||||
|
||||
// Prepare the parameter structure and set default parameters
|
||||
snd_pcm_hw_params_t *params; |
||||
snd_pcm_hw_params_alloca(¶ms); |
||||
snd_pcm_hw_params_any(m_pPCM, params); |
||||
|
||||
// Set other parameters
|
||||
snd_pcm_hw_params_set_access(m_pPCM, params, SND_PCM_ACCESS_RW_INTERLEAVED); |
||||
snd_pcm_hw_params_set_format(m_pPCM, params, SND_PCM_FORMAT_S16_LE); |
||||
snd_pcm_hw_params_set_rate(m_pPCM, params, m_nSampleRate, 0); |
||||
snd_pcm_hw_params_set_channels(m_pPCM, params, m_nChannels); |
||||
snd_pcm_hw_params_set_period_size(m_pPCM, params, m_nBlockSamples, 0); |
||||
snd_pcm_hw_params_set_periods(m_pPCM, params, nBlocks, 0); |
||||
|
||||
// Save these parameters
|
||||
rc = snd_pcm_hw_params(m_pPCM, params); |
||||
if (rc < 0) |
||||
return DestroyAudio(); |
||||
|
||||
listActiveSamples.clear(); |
||||
|
||||
// Allocate Wave|Block Memory
|
||||
m_pBlockMemory = new short[m_nBlockSamples]; |
||||
if (m_pBlockMemory == nullptr) |
||||
return DestroyAudio(); |
||||
std::fill(m_pBlockMemory, m_pBlockMemory + m_nBlockSamples, 0); |
||||
|
||||
// Unsure if really needed, helped prevent underrun on my setup
|
||||
snd_pcm_start(m_pPCM); |
||||
for (unsigned int i = 0; i < nBlocks; i++) |
||||
rc = snd_pcm_writei(m_pPCM, m_pBlockMemory, 512); |
||||
|
||||
snd_pcm_start(m_pPCM); |
||||
m_bAudioThreadActive = true; |
||||
m_AudioThread = std::thread(&SOUND::AudioThread); |
||||
|
||||
return true; |
||||
} |
||||
|
||||
// Stop and clean up audio system
|
||||
bool SOUND::DestroyAudio() |
||||
{ |
||||
m_bAudioThreadActive = false; |
||||
if(m_AudioThread.joinable()) |
||||
m_AudioThread.join(); |
||||
snd_pcm_drain(m_pPCM); |
||||
snd_pcm_close(m_pPCM); |
||||
return false; |
||||
} |
||||
|
||||
|
||||
// Audio thread. This loop responds to requests from the soundcard to fill 'blocks'
|
||||
// with audio data. If no requests are available it goes dormant until the sound
|
||||
// card is ready for more data. The block is fille by the "user" in some manner
|
||||
// and then issued to the soundcard.
|
||||
void SOUND::AudioThread() |
||||
{ |
||||
m_fGlobalTime = 0.0f; |
||||
static float fTimeStep = 1.0f / (float)m_nSampleRate; |
||||
|
||||
// Goofy hack to get maximum integer for a type at run-time
|
||||
short nMaxSample = (short)pow(2, (sizeof(short) * 8) - 1) - 1; |
||||
float fMaxSample = (float)nMaxSample; |
||||
short nPreviousSample = 0; |
||||
|
||||
while (m_bAudioThreadActive) |
||||
{ |
||||
short nNewSample = 0; |
||||
|
||||
auto clip = [](float fSample, float fMax) |
||||
{ |
||||
if (fSample >= 0.0) |
||||
return fmin(fSample, fMax); |
||||
else |
||||
return fmax(fSample, -fMax); |
||||
}; |
||||
|
||||
for (unsigned int n = 0; n < m_nBlockSamples; n += m_nChannels) |
||||
{ |
||||
// User Process
|
||||
for (unsigned int c = 0; c < m_nChannels; c++) |
||||
{ |
||||
nNewSample = (short)(GetMixerOutput(c, m_fGlobalTime + fTimeStep * (float)n, fTimeStep), 1.0) * fMaxSample; |
||||
m_pBlockMemory[n + c] = nNewSample; |
||||
nPreviousSample = nNewSample; |
||||
}
|
||||
} |
||||
|
||||
m_fGlobalTime = m_fGlobalTime + fTimeStep * (float)m_nBlockSamples; |
||||
|
||||
// Send block to sound device
|
||||
snd_pcm_uframes_t nLeft = m_nBlockSamples; |
||||
short *pBlockPos = m_pBlockMemory; |
||||
while (nLeft > 0) |
||||
{ |
||||
int rc = snd_pcm_writei(m_pPCM, pBlockPos, nLeft); |
||||
if (rc > 0) |
||||
{ |
||||
pBlockPos += rc * m_nChannels; |
||||
nLeft -= rc; |
||||
} |
||||
if (rc == -EAGAIN) continue; |
||||
if (rc == -EPIPE) // an underrun occured, prepare the device for more data
|
||||
snd_pcm_prepare(m_pPCM); |
||||
} |
||||
} |
||||
} |
||||
|
||||
snd_pcm_t* SOUND::m_pPCM = nullptr; |
||||
unsigned int SOUND::m_nSampleRate = 0; |
||||
unsigned int SOUND::m_nChannels = 0; |
||||
unsigned int SOUND::m_nBlockSamples = 0; |
||||
short* SOUND::m_pBlockMemory = nullptr; |
||||
} |
||||
|
||||
#elif defined(USE_OPENAL) |
||||
|
||||
namespace olc |
||||
{ |
||||
bool SOUND::InitialiseAudio(unsigned int nSampleRate, unsigned int nChannels, unsigned int nBlocks, unsigned int nBlockSamples) |
||||
{ |
||||
// Initialise Sound Engine
|
||||
m_bAudioThreadActive = false; |
||||
m_nSampleRate = nSampleRate; |
||||
m_nChannels = nChannels; |
||||
m_nBlockCount = nBlocks; |
||||
m_nBlockSamples = nBlockSamples; |
||||
m_pBlockMemory = nullptr; |
||||
|
||||
// Open the device and create the context
|
||||
m_pDevice = alcOpenDevice(NULL); |
||||
if (m_pDevice) |
||||
{ |
||||
m_pContext = alcCreateContext(m_pDevice, NULL); |
||||
alcMakeContextCurrent(m_pContext); |
||||
} |
||||
else |
||||
return DestroyAudio(); |
||||
|
||||
// Allocate memory for sound data
|
||||
alGetError(); |
||||
m_pBuffers = new ALuint[m_nBlockCount]; |
||||
alGenBuffers(m_nBlockCount, m_pBuffers); |
||||
alGenSources(1, &m_nSource); |
||||
|
||||
for (unsigned int i = 0; i < m_nBlockCount; i++) |
||||
m_qAvailableBuffers.push(m_pBuffers[i]); |
||||
|
||||
listActiveSamples.clear(); |
||||
|
||||
// Allocate Wave|Block Memory
|
||||
m_pBlockMemory = new short[m_nBlockSamples]; |
||||
if (m_pBlockMemory == nullptr) |
||||
return DestroyAudio(); |
||||
std::fill(m_pBlockMemory, m_pBlockMemory + m_nBlockSamples, 0); |
||||
|
||||
m_bAudioThreadActive = true; |
||||
m_AudioThread = std::thread(&SOUND::AudioThread); |
||||
return true; |
||||
} |
||||
|
||||
// Stop and clean up audio system
|
||||
bool SOUND::DestroyAudio() |
||||
{ |
||||
m_bAudioThreadActive = false; |
||||
if(m_AudioThread.joinable()) |
||||
m_AudioThread.join(); |
||||
|
||||
alDeleteBuffers(m_nBlockCount, m_pBuffers); |
||||
delete[] m_pBuffers; |
||||
alDeleteSources(1, &m_nSource); |
||||
|
||||
alcMakeContextCurrent(NULL); |
||||
alcDestroyContext(m_pContext); |
||||
alcCloseDevice(m_pDevice); |
||||
return false; |
||||
} |
||||
|
||||
|
||||
// Audio thread. This loop responds to requests from the soundcard to fill 'blocks'
|
||||
// with audio data. If no requests are available it goes dormant until the sound
|
||||
// card is ready for more data. The block is fille by the "user" in some manner
|
||||
// and then issued to the soundcard.
|
||||
void SOUND::AudioThread() |
||||
{ |
||||
m_fGlobalTime = 0.0f; |
||||
static float fTimeStep = 1.0f / (float)m_nSampleRate; |
||||
|
||||
// Goofy hack to get maximum integer for a type at run-time
|
||||
short nMaxSample = (short)pow(2, (sizeof(short) * 8) - 1) - 1; |
||||
float fMaxSample = (float)nMaxSample; |
||||
short nPreviousSample = 0; |
||||
|
||||
std::vector<ALuint> vProcessed; |
||||
|
||||
while (m_bAudioThreadActive) |
||||
{ |
||||
ALint nState, nProcessed; |
||||
alGetSourcei(m_nSource, AL_SOURCE_STATE, &nState); |
||||
alGetSourcei(m_nSource, AL_BUFFERS_PROCESSED, &nProcessed); |
||||
|
||||
// Add processed buffers to our queue
|
||||
vProcessed.resize(nProcessed); |
||||
alSourceUnqueueBuffers(m_nSource, nProcessed, vProcessed.data()); |
||||
for (ALint nBuf : vProcessed) m_qAvailableBuffers.push(nBuf); |
||||
|
||||
// Wait until there is a free buffer (ewww)
|
||||
if (m_qAvailableBuffers.empty()) continue; |
||||
|
||||
short nNewSample = 0; |
||||
|
||||
auto clip = [](float fSample, float fMax) |
||||
{ |
||||
if (fSample >= 0.0) |
||||
return fmin(fSample, fMax); |
||||
else |
||||
return fmax(fSample, -fMax); |
||||
}; |
||||
|
||||
for (unsigned int n = 0; n < m_nBlockSamples; n += m_nChannels) |
||||
{ |
||||
// User Process
|
||||
for (unsigned int c = 0; c < m_nChannels; c++) |
||||
{ |
||||
nNewSample = (short)(clip(GetMixerOutput(c, m_fGlobalTime, fTimeStep), 1.0) * fMaxSample); |
||||
m_pBlockMemory[n + c] = nNewSample; |
||||
nPreviousSample = nNewSample; |
||||
} |
||||
|
||||
m_fGlobalTime = m_fGlobalTime + fTimeStep; |
||||
} |
||||
|
||||
// Fill OpenAL data buffer
|
||||
alBufferData( |
||||
m_qAvailableBuffers.front(), |
||||
m_nChannels == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16, |
||||
m_pBlockMemory, |
||||
2 * m_nBlockSamples, |
||||
m_nSampleRate |
||||
); |
||||
// Add it to the OpenAL queue
|
||||
alSourceQueueBuffers(m_nSource, 1, &m_qAvailableBuffers.front()); |
||||
// Remove it from ours
|
||||
m_qAvailableBuffers.pop(); |
||||
|
||||
// If it's not playing for some reason, change that
|
||||
if (nState != AL_PLAYING) |
||||
alSourcePlay(m_nSource); |
||||
} |
||||
} |
||||
|
||||
std::queue<ALuint> SOUND::m_qAvailableBuffers; |
||||
ALuint *SOUND::m_pBuffers = nullptr; |
||||
ALuint SOUND::m_nSource = 0; |
||||
ALCdevice *SOUND::m_pDevice = nullptr; |
||||
ALCcontext *SOUND::m_pContext = nullptr; |
||||
unsigned int SOUND::m_nSampleRate = 0; |
||||
unsigned int SOUND::m_nChannels = 0; |
||||
unsigned int SOUND::m_nBlockCount = 0; |
||||
unsigned int SOUND::m_nBlockSamples = 0; |
||||
short* SOUND::m_pBlockMemory = nullptr; |
||||
} |
||||
|
||||
#else // Some other platform
|
||||
|
||||
namespace olc |
||||
{ |
||||
bool SOUND::InitialiseAudio(unsigned int nSampleRate, unsigned int nChannels, unsigned int nBlocks, unsigned int nBlockSamples) |
||||
{ |
||||
return true; |
||||
} |
||||
|
||||
// Stop and clean up audio system
|
||||
bool SOUND::DestroyAudio() |
||||
{ |
||||
return false; |
||||
} |
||||
|
||||
|
||||
// Audio thread. This loop responds to requests from the soundcard to fill 'blocks'
|
||||
// with audio data. If no requests are available it goes dormant until the sound
|
||||
// card is ready for more data. The block is fille by the "user" in some manner
|
||||
// and then issued to the soundcard.
|
||||
void SOUND::AudioThread() |
||||
{ } |
||||
} |
||||
|
||||
#endif |
||||
#endif |
||||
#endif // OLC_PGEX_SOUND
|
@ -0,0 +1,381 @@ |
||||
#pragma once |
||||
#include "olcPixelGameEngine.h" |
||||
|
||||
#include <algorithm> |
||||
#undef min |
||||
#undef max |
||||
|
||||
namespace olc |
||||
{ |
||||
|
||||
class TILE : public olc::PGEX |
||||
{ |
||||
|
||||
public: |
||||
|
||||
|
||||
struct Edge |
||||
{ |
||||
float sx, sy; |
||||
float ex, ey; |
||||
}; |
||||
|
||||
public: |
||||
class Atlas |
||||
{ |
||||
public: |
||||
Atlas(); |
||||
void Create(olc::Sprite *tileSheet); |
||||
olc::rcode LoadFromFile(std::string filename); |
||||
olc::rcode SaveToFile(std::string filename); |
||||
|
||||
public: |
||||
olc::Sprite *sprTileSheet; |
||||
std::vector<std::tuple<int32_t, int32_t, int32_t, int32_t>> location; |
||||
}; |
||||
|
||||
public: |
||||
|
||||
template <class T> |
||||
class Layer |
||||
{ |
||||
public: |
||||
Layer(); |
||||
void Create(int32_t w, int32_t h, int32_t tw, int32_t th); |
||||
olc::rcode LoadFromFile(std::string filename); |
||||
olc::rcode SaveToFile(std::string filename); |
||||
T* GetTile(int32_t x, int32_t y); |
||||
|
||||
public: |
||||
int32_t nLayerWidth; |
||||
int32_t nLayerHeight; |
||||
int32_t nTileWidth; |
||||
int32_t nTileHeight; |
||||
|
||||
private: |
||||
T *pTiles; |
||||
|
||||
}; |
||||
|
||||
class BasicTile |
||||
{ |
||||
public: |
||||
BasicTile(); |
||||
|
||||
public: |
||||
int32_t id; |
||||
bool exist; |
||||
|
||||
int edge_id[4]; |
||||
bool edge_exist[4]; |
||||
}; |
||||
|
||||
public: |
||||
template<typename T> |
||||
static void DrawLayer(olc::TILE::Layer<T> &layer, olc::TILE::Atlas &atlas, float cam_x, float cam_y, int tiles_x, int tiles_y, int nScale = 1); |
||||
|
||||
template<typename T> |
||||
static olc::Pixel GetLayerPixel(olc::TILE::Layer<T> &layer, olc::TILE::Atlas &atlas, float x, float y); |
||||
|
||||
template<typename T> |
||||
static std::vector<olc::TILE::Edge> ExtractEdgesFromLayer(olc::TILE::Layer<T> &layer, int sx, int sy, int width, int height); |
||||
|
||||
}; |
||||
} |
||||
|
||||
|
||||
|
||||
|
||||
namespace olc |
||||
{ |
||||
TILE::BasicTile::BasicTile() |
||||
{ |
||||
exist = false; |
||||
id = 0; |
||||
|
||||
for (int i = 0; i < 4; i++) |
||||
{ |
||||
edge_exist[i] = false; |
||||
edge_id[i] = 0; |
||||
} |
||||
} |
||||
|
||||
template <class T> |
||||
TILE::Layer<T>::Layer() |
||||
{ |
||||
|
||||
} |
||||
|
||||
|
||||
|
||||
template <class T> |
||||
void TILE::Layer<T>::Create(int32_t w, int32_t h, int32_t tw, int32_t th) |
||||
{ |
||||
nLayerWidth = w; |
||||
nLayerHeight = h; |
||||
nTileWidth = tw; |
||||
nTileHeight = th; |
||||
|
||||
pTiles = new T[nLayerWidth * nLayerHeight]; |
||||
for (int i = 0; i < nLayerWidth*nLayerHeight; i++) |
||||
{ |
||||
pTiles[i].id = 0; |
||||
} |
||||
} |
||||
|
||||
template <class T> |
||||
olc::rcode TILE::Layer<T>::LoadFromFile(std::string filename) |
||||
{ |
||||
return olc::FAIL; |
||||
} |
||||
|
||||
template <class T> |
||||
olc::rcode TILE::Layer<T>::SaveToFile(std::string filename) |
||||
{ |
||||
return olc::FAIL; |
||||
} |
||||
|
||||
template <class T> |
||||
T* TILE::Layer<T>::GetTile(int32_t x, int32_t y) |
||||
{ |
||||
if (x < 0 || x >= nLayerWidth || y < 0 || y >= nLayerHeight) |
||||
return nullptr; |
||||
else |
||||
return &pTiles[y*nLayerWidth + x]; |
||||
} |
||||
|
||||
template<typename T> |
||||
void TILE::DrawLayer(olc::TILE::Layer<T> &layer, olc::TILE::Atlas &atlas, float cam_x, float cam_y, int32_t tiles_x, int32_t tiles_y, int nScale) |
||||
{ |
||||
float fOffsetX = cam_x - (int)cam_x; |
||||
float fOffsetY = cam_y - (int)cam_y; |
||||
|
||||
for (int32_t x = 0; x < tiles_x; x++) |
||||
{ |
||||
for (int32_t y = 0; y < tiles_y; y++) |
||||
{ |
||||
olc::TILE::BasicTile *t = layer.GetTile(x + (int)cam_x, y + (int)cam_y); |
||||
if (t != nullptr && t->exist) |
||||
{ |
||||
float fx = (int)(((float)x - fOffsetX) * (float)(layer.nTileWidth)); |
||||
float fy = (int)(((float)y - fOffsetY) * (float)(layer.nTileHeight)); |
||||
|
||||
pge->DrawPartialSprite( |
||||
fx + 0.5f - (fx < 0.0f), |
||||
fy + 0.5f - (fy < 0.0f), |
||||
atlas.sprTileSheet, |
||||
std::get<0>(atlas.location[t->id]), |
||||
std::get<1>(atlas.location[t->id]), |
||||
std::get<2>(atlas.location[t->id]), |
||||
std::get<3>(atlas.location[t->id]),
|
||||
nScale);
|
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
template<typename T> |
||||
olc::Pixel TILE::GetLayerPixel(olc::TILE::Layer<T> &layer, olc::TILE::Atlas &atlas, float x, float y) |
||||
{ |
||||
olc::TILE::BasicTile *t = layer.GetTile((int32_t)x, (int32_t)y); |
||||
if (t != nullptr) |
||||
{ |
||||
float fOffsetX = x - (int)x; |
||||
float fOffsetY = y - (int)y; |
||||
return atlas.sprTileSheet->GetPixel(std::get<0>(atlas.location[t->id]) + fOffsetX * std::get<2>(atlas.location[t->id]), |
||||
std::get<1>(atlas.location[t->id]) + fOffsetX * std::get<3>(atlas.location[t->id])); |
||||
} |
||||
else |
||||
return olc::BLANK; |
||||
} |
||||
|
||||
template<typename T> |
||||
std::vector<olc::TILE::Edge> TILE::ExtractEdgesFromLayer(olc::TILE::Layer<T> &layer, int sx, int sy, int width, int height) |
||||
{ |
||||
enum |
||||
{ |
||||
NORTH = 0, |
||||
EAST = 1, |
||||
SOUTH = 2, |
||||
WEST = 3 |
||||
}; |
||||
|
||||
std::vector<olc::TILE::Edge> vecEdges; |
||||
|
||||
for (int x = -1; x < width + 1; x++) |
||||
for (int y = -1; y < height + 1; y++) |
||||
for (int j = 0; j < 4; j++) |
||||
{ |
||||
if ((x + sx) >= 0 && (y + sy) >= 0 && (x + sx) < (layer.nLayerWidth - 1) && (y + sy) < (layer.nLayerHeight - 1)) |
||||
{ |
||||
layer.GetTile(x + sx, y + sy)->edge_exist[j] = false; |
||||
layer.GetTile(x + sx, y + sy)->edge_id[j] = 0; |
||||
} |
||||
} |
||||
|
||||
// Add boundary edges
|
||||
vecEdges.push_back({ (float)(sx)* layer.nTileWidth, (float)(sy)*layer.nTileHeight, (float)(sx + width)*layer.nTileWidth, (float)(sy)*layer.nTileHeight }); |
||||
vecEdges.push_back({ (float)(sx + width)* layer.nTileWidth, (float)(sy)*layer.nTileHeight, (float)(sx + width)*layer.nTileWidth, (float)(sy + height)*layer.nTileHeight }); |
||||
vecEdges.push_back({ (float)(sx + width)* layer.nTileWidth, (float)(sy + height)*layer.nTileHeight, (float)(sx)*layer.nTileWidth, (float)(sy + height)*layer.nTileHeight }); |
||||
vecEdges.push_back({ (float)(sx)* layer.nTileWidth, (float)(sy + height)*layer.nTileHeight, (float)(sx)*layer.nTileWidth, (float)(sy)*layer.nTileHeight }); |
||||
|
||||
|
||||
// Iterate through region from top left to bottom right
|
||||
for (int x = 0; x < width; x++) |
||||
for (int y = 0; y < height; y++) |
||||
{ |
||||
T* i = layer.GetTile(x + sx, y + sy); //This
|
||||
T* n = layer.GetTile(x + sx, y + sy - 1); |
||||
T* s = layer.GetTile(x + sx, y + sy + 1); |
||||
T* w = layer.GetTile(x + sx - 1, y + sy); |
||||
T* e = layer.GetTile(x + sx + 1, y + sy); |
||||
|
||||
// If this cell exists, check if it needs edges
|
||||
if (i->exist) |
||||
{ |
||||
// If this cell has no western neighbour, it needs a western edge
|
||||
if (w && !w->exist) |
||||
{ |
||||
// It can either extend it from its northern neighbour if they have
|
||||
// one, or It can start a new one.
|
||||
if (n && n->edge_exist[WEST]) |
||||
{ |
||||
// Northern neighbour has a western edge, so grow it downwards
|
||||
vecEdges[n->edge_id[WEST]].ey += layer.nTileHeight; |
||||
i->edge_id[WEST] = n->edge_id[WEST]; |
||||
i->edge_exist[WEST] = true; |
||||
} |
||||
else |
||||
{ |
||||
// Northern neighbour does not have one, so create one
|
||||
olc::TILE::Edge edge; |
||||
edge.sx = (sx + x) * layer.nTileWidth; edge.sy = (sy + y) * layer.nTileHeight; |
||||
edge.ex = edge.sx; edge.ey = edge.sy + layer.nTileHeight; |
||||
|
||||
// Add edge to Polygon Pool
|
||||
int edge_id = vecEdges.size(); |
||||
vecEdges.push_back(edge); |
||||
|
||||
// Update tile information with edge information
|
||||
i->edge_id[WEST] = edge_id; |
||||
i->edge_exist[WEST] = true; |
||||
} |
||||
} |
||||
|
||||
|
||||
// If this cell dont have an eastern neignbour, It needs a eastern edge
|
||||
if (e && !e->exist) |
||||
{ |
||||
// It can either extend it from its northern neighbour if they have
|
||||
// one, or It can start a new one.
|
||||
if (n && n->edge_exist[EAST]) |
||||
{ |
||||
// Northern neighbour has one, so grow it downwards
|
||||
vecEdges[n->edge_id[EAST]].ey += layer.nTileHeight; |
||||
i->edge_id[EAST] = n->edge_id[EAST]; |
||||
i->edge_exist[EAST] = true; |
||||
} |
||||
else |
||||
{ |
||||
// Northern neighbour does not have one, so create one
|
||||
olc::TILE::Edge edge; |
||||
edge.sx = (sx + x + 1) * layer.nTileWidth; edge.sy = (sy + y) * layer.nTileHeight; |
||||
edge.ex = edge.sx; edge.ey = edge.sy + layer.nTileHeight; |
||||
|
||||
// Add edge to Polygon Pool
|
||||
int edge_id = vecEdges.size(); |
||||
vecEdges.push_back(edge); |
||||
|
||||
// Update tile information with edge information
|
||||
i->edge_id[EAST] = edge_id; |
||||
i->edge_exist[EAST] = true; |
||||
} |
||||
} |
||||
|
||||
// If this cell doesnt have a northern neignbour, It needs a northern edge
|
||||
if (n && !n->exist) |
||||
{ |
||||
// It can either extend it from its western neighbour if they have
|
||||
// one, or It can start a new one.
|
||||
if (w && w->edge_exist[NORTH]) |
||||
{ |
||||
// Western neighbour has one, so grow it eastwards
|
||||
vecEdges[w->edge_id[NORTH]].ex += layer.nTileWidth; |
||||
i->edge_id[NORTH] = w->edge_id[NORTH]; |
||||
i->edge_exist[NORTH] = true; |
||||
} |
||||
else |
||||
{ |
||||
// Western neighbour does not have one, so create one
|
||||
olc::TILE::Edge edge; |
||||
edge.sx = (sx + x) * layer.nTileWidth; edge.sy = (sy + y) * layer.nTileHeight; |
||||
edge.ex = edge.sx + layer.nTileWidth; edge.ey = edge.sy; |
||||
|
||||
// Add edge to Polygon Pool
|
||||
int edge_id = vecEdges.size(); |
||||
vecEdges.push_back(edge); |
||||
|
||||
// Update tile information with edge information
|
||||
i->edge_id[NORTH] = edge_id; |
||||
i->edge_exist[NORTH] = true; |
||||
} |
||||
} |
||||
|
||||
// If this cell doesnt have a southern neignbour, It needs a southern edge
|
||||
if (s && !s->exist) |
||||
{ |
||||
// It can either extend it from its western neighbour if they have
|
||||
// one, or It can start a new one.
|
||||
if (w && w->edge_exist[SOUTH]) |
||||
{ |
||||
// Western neighbour has one, so grow it eastwards
|
||||
vecEdges[w->edge_id[SOUTH]].ex += layer.nTileWidth; |
||||
i->edge_id[SOUTH] = w->edge_id[SOUTH]; |
||||
i->edge_exist[SOUTH] = true; |
||||
} |
||||
else |
||||
{ |
||||
// Western neighbour does not have one, so I need to create one
|
||||
olc::TILE::Edge edge; |
||||
edge.sx = (sx + x) * layer.nTileWidth; edge.sy = (sy + y + 1) * layer.nTileHeight; |
||||
edge.ex = edge.sx + layer.nTileWidth; edge.ey = edge.sy; |
||||
|
||||
// Add edge to Polygon Pool
|
||||
int edge_id = vecEdges.size(); |
||||
vecEdges.push_back(edge); |
||||
|
||||
// Update tile information with edge information
|
||||
i->edge_id[SOUTH] = edge_id; |
||||
i->edge_exist[SOUTH] = true; |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
return vecEdges; |
||||
} |
||||
|
||||
|
||||
|
||||
TILE::Atlas::Atlas() |
||||
{ |
||||
} |
||||
|
||||
void TILE::Atlas::Create(olc::Sprite *tileSheet) |
||||
{ |
||||
sprTileSheet = tileSheet; |
||||
location.clear(); |
||||
|
||||
} |
||||
|
||||
olc::rcode TILE::Atlas::LoadFromFile(std::string filename) |
||||
{ |
||||
return olc::FAIL; |
||||
} |
||||
|
||||
olc::rcode TILE::Atlas::SaveToFile(std::string filename) |
||||
{ |
||||
return olc::FAIL; |
||||
} |
||||
|
||||
} |
File diff suppressed because it is too large
Load Diff
Loading…
Reference in new issue