Initial Commit / Linux Combined Proof of Concept example

This commit is contained in:
John McCardle 2023-02-23 19:37:13 -05:00
commit d0d2eae762
935 changed files with 155947 additions and 0 deletions

View file

@ -0,0 +1,32 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#include "libtcod/libtcod.h"

View file

@ -0,0 +1,32 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#include "libtcod.h"

View file

@ -0,0 +1,87 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_BRESENHAM_H
#define _TCOD_BRESENHAM_H
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief A callback to be passed to TCOD_line
*
* The points given to the callback include both the starting and ending
* positions.
*
* \param x
* \param y
* \return As long as this callback returns true it will be called with the
* next x,y point on the line.
*/
typedef bool (*TCOD_line_listener_t)(int x, int y);
TCODLIB_API TCOD_DEPRECATED("This function is not reentrant. Use TCOD_line_init_mt instead.") void TCOD_line_init(
int xFrom, int yFrom, int xTo, int yTo);
/** advance one step. returns true if we reach destination */
TCODLIB_API TCOD_DEPRECATED("This function is not reentrant.") bool TCOD_line_step(
int* __restrict xCur, int* __restrict yCur);
/* atomic callback function. Stops when the callback returns false */
TCODLIB_API bool TCOD_line(int xFrom, int yFrom, int xTo, int yTo, TCOD_line_listener_t listener);
/**
* \brief A struct used for computing a bresenham line.
*/
typedef struct {
int stepx;
int stepy;
int e;
int deltax;
int deltay;
int origx;
int origy;
int destx;
int desty;
} TCOD_bresenham_data_t;
TCODLIB_API void TCOD_line_init_mt(int xFrom, int yFrom, int xTo, int yTo, TCOD_bresenham_data_t* data);
TCODLIB_API bool TCOD_line_step_mt(int* __restrict xCur, int* __restrict yCur, TCOD_bresenham_data_t* __restrict data);
TCOD_DEPRECATED("Use TCOD_line instead.")
TCODLIB_API bool TCOD_line_mt(
int xFrom, int yFrom, int xTo, int yTo, TCOD_line_listener_t listener, TCOD_bresenham_data_t* data);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // _TCOD_BRESENHAM_H

View file

@ -0,0 +1,386 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_BRESENHAM_HPP
#define _TCOD_BRESENHAM_HPP
#include <array>
#include <functional>
#include <iterator>
#include <vector>
#include "bresenham.h"
// clang-format off
class TCODLIB_API TCODLineListener {
public :
virtual bool putPoint(int x,int y) = 0;
virtual ~TCODLineListener() {}
};
class TCODLIB_API TCODLine {
public :
/**
@PageName line
@PageCategory Base toolkits
@PageTitle Line drawing toolkit
@PageDesc This toolkit is a very simple and lightweight implementation of the bresenham line drawing algorithm. It allows you to follow straight paths on your map very easily.
@FuncTitle Initializing the line
@FuncDesc First, you have to initialize the toolkit with your starting and ending coordinates.
@Cpp static void TCODLine::init (int xFrom, int yFrom, int xTo, int yTo)
@C void TCOD_line_init (int xFrom, int yFrom, int xTo, int yTo)
@Py line_init (xFrom, yFrom, xTo, yTo)
@C# static void TCODLine::init(int xFrom, int yFrom, int xTo, int yTo)
@Lua tcod.line.init(xFrom,yFrom, xTo,yTo)
@Param xFrom,yFrom Coordinates of the line's starting point.
@Param xTo,yTo Coordinates of the line's ending point.
*/
static void init(int xFrom, int yFrom, int xTo, int yTo);
/**
@PageName line
@FuncTitle Walking the line
@FuncDesc You can then step through each cell with this function. It returns true when you reach the line's ending point.
@Cpp static bool TCODLine::step (int * xCur, int * yCur)
@C bool TCOD_line_step (int * xCur, int * yCur)
@Py line_step () # returns x,y or None,None if finished
@C# static bool TCODLine::step(ref int xCur, ref int yCur)
@Lua tcod.line.step(x,y) -- returns lineEnd,x,y
@Param xCur,yCur the coordinates of the next cell on the line are stored here when the function returns
@CppEx
// Going from point 5,8 to point 13,4
int x = 5, y = 8;
TCODLine::init(x,y,13,4);
do {
// update cell x,y
} while (!TCODLine::step(&x,&y));
@CEx
int x = 5, y = 8;
TCOD_line_init(x,y,13,4);
do {
// update cell x,y
} while (!TCOD_line_step(&x,&y));
@PyEx
libtcod.line_init(5,8,13,4)
# update cell 5,8
x,y=libtcod.line_step()
while (not x is None) :
# update cell x,y
x,y=libtcod.line_step()
@LuaEx
x=5
y=8
tcod.line.init(x,y,13,4)
repeat
-- update cell x,y
lineEnd,x,y = tcod.line.step(x,y)
until lineEnd
*/
static bool step(int *xCur, int *yCur);
/**
@PageName line
@FuncTitle Callback-based function
@FuncDesc The function returns false if the line has been interrupted by the callback (it returned false before the last point).
@Cpp
class TCODLIB_API TCODLineListener {
virtual bool putPoint (int x, int y) = 0;
};
static bool TCODLine::line (int xFrom, int yFrom, int xTo, int yTo, TCODLineListener * listener)
@C
typedef bool (*TCOD_line_listener_t) (int x, int y);
bool TCOD_line(int xFrom, int yFrom, int xTo, int yTo, TCOD_line_listener_t listener)
@Py
def line_listener(x,y) : # ...
line(xFrom, yFrom, xTo, yTo, listener)
@C# static bool line(int xFrom, int yFrom, int xTo, int yTo, TCODLineListener listener)
@Param xFrom,yFrom Coordinates of the line's starting point.
@Param xTo,yTo Coordinates of the line's ending point.
@Param listener Callback called for each line's point. The function stops if the callback returns false.
@CppEx // Going from point 5,8 to point 13,4
class MyLineListener : public TCODLineListener {
public:
bool putPoint (int x,int y) {
printf ("%d %d\n",x,y);
return true;
}
};
MyLineListener myListener;
TCODLine::line(5,8,13,4,&myListener);
@CEx bool my_listener(int x,int y) {
printf ("%d %d\n",x,y);
return true;
}
TCOD_line_line(5,8,13,4,my_listener);
@PyEx def my_listener(x,y):
print x,y
return True
libtcod.line_line(5,8,13,4,my_listener)
*/
static bool line(int xFrom, int yFrom, int xTo, int yTo, TCODLineListener *listener);
};
// clang-format on
namespace tcod {
/**
Encapsulates a Bresenham line drawing algorithm.
\rst
.. versionadded:: 1.17
\endrst
*/
class BresenhamLine {
public:
using Point2 = std::array<int, 2>;
using iterator_category = std::random_access_iterator_tag;
using value_type = Point2;
using difference_type = int;
using pointer = void;
using reference = value_type;
/**
Construct a new Bresenham line from `begin` to `end`.
Iterating over this instance will include both endpoints.
*/
explicit BresenhamLine(Point2 begin, Point2 end) noexcept
: origin_{begin},
dest_{end},
index_{0},
index_end_{get_delta_x() + 1},
cursor_{0, 0},
y_error_{-get_delta_x() / 2} {}
/**
Construct a new Bresenham line with a manually given error value.
*/
explicit BresenhamLine(Point2 begin, Point2 end, int error) noexcept
: origin_{begin},
dest_{end},
index_{0},
index_end_{get_delta_x() + 1},
cursor_{0, 0},
y_error_{error > 0 ? error % get_delta_x() - get_delta_x() : error % get_delta_x()} {}
inline BresenhamLine& operator++() noexcept {
++index_;
return *this;
}
inline BresenhamLine operator++(int) noexcept {
auto tmp = *this;
++(*this);
return tmp;
}
inline BresenhamLine& operator--() noexcept {
--index_;
return *this;
}
inline BresenhamLine operator--(int) noexcept {
auto tmp = *this;
--(*this);
return tmp;
}
/**
Return the world position of the Bresenham at the index relative to the current index.
BresenhamLine is not restricted by any bounds so you can freely give a index past the end or before zero.
The internal state must always seek to the position being indexed, this will affect performance depending on if
successive indexes are close together or far apart.
*/
inline value_type operator[](int index) noexcept { return bresenham_get(index_ + index); }
/**
Return the world position of the Bresenham at the current index.
*/
inline value_type operator*() noexcept { return (*this)[0]; }
inline constexpr bool operator==(const BresenhamLine& rhs) const noexcept { return index_ == rhs.index_; }
inline constexpr bool operator!=(const BresenhamLine& rhs) const noexcept { return !(*this == rhs); }
inline constexpr difference_type operator-(const BresenhamLine& rhs) const noexcept { return index_ - rhs.index_; }
/**
Return a new version of this BresenhamLine with an adjusted range.
`shift_begin` and `shift_end` change the beginning and ending of the line
when iterators over.
Example::
// Remove the endpoints of a bresenham line.
auto line = tcod::BresenhamLine(from, to).adjust_range(1, -1);
*/
inline BresenhamLine adjust_range(int shift_begin, int shift_end) const noexcept {
BresenhamLine new_data{*this};
new_data.index_ += shift_begin;
new_data.index_end_ += shift_end;
new_data.index_end_ = std::max(new_data.index_, new_data.index_end_);
return new_data;
}
/**
Remove the staring endpoint of a line.
Example::
for (auto&& [x, y] : tcod::BresenhamLine(from, to).without_start()) {
// All positions excluding `from`.
}
*/
inline BresenhamLine without_start() const noexcept { return adjust_range(1, 0); }
/**
Remove the final endpoint of a line.
Example::
for (auto&& [x, y] : tcod::BresenhamLine(from, to).without_end()) {
// All positions excluding `to`.
}
*/
inline BresenhamLine without_end() const noexcept { return adjust_range(0, -1); }
/**
Remove both endpoints of a line.
Example::
for (auto&& [x, y] : tcod::BresenhamLine(from, to).without_endpoints()) {
// All positions between and excluding `from` and `to`.
}
*/
inline BresenhamLine without_endpoints() const noexcept { return adjust_range(1, -1); }
/**
Return the beginning iterator, which is a copy of the current object.
*/
inline BresenhamLine begin() const noexcept { return {*this}; }
/**
Return the past-the-end iterator.
*/
inline BresenhamLine end() const noexcept {
return BresenhamLine{origin_, dest_, index_end_, index_end_, cursor_, y_error_};
}
private:
/**
Transform matrix to convert from normalized state cursor to the real world coordinates.
*/
struct Matrix {
/**
Convert a state cursor vector to the a world vector.
*/
inline Point2 transform(const Point2& cursor) const noexcept {
return {ax + cursor.at(0) * xx + cursor.at(1) * yx, ay + cursor.at(0) * xy + cursor.at(1) * yy};
}
int ax; // Affine transformation on X.
int ay; // Affine transformation on Y.
int_fast8_t xx; // Index to world X.
int_fast8_t xy; // Index to world Y.
int_fast8_t yx; // Cursor Y to world X.
int_fast8_t yy; // Cursor Y to world Y.
};
/**
Return a Matrix that converts a normalized cursor to the correct octant.
*/
inline Matrix get_matrix() const noexcept { return get_matrix(origin_, dest_); }
static Matrix get_matrix(const Point2& origin, const Point2& dest) noexcept {
const int delta_x = dest.at(0) - origin.at(0);
const int delta_y = dest.at(1) - origin.at(1);
Matrix matrix{
origin.at(0),
origin.at(1),
1,
0,
0,
1,
};
if (delta_x < 0) matrix.xx = -1;
if (delta_y < 0) matrix.yy = -1;
if (std::abs(delta_y) > std::abs(delta_x)) {
std::swap(matrix.xx, matrix.yx);
std::swap(matrix.xy, matrix.yy);
}
return matrix;
}
explicit BresenhamLine(Point2 begin, Point2 end, int index_begin, int index_end, Point2 cursor, int error) noexcept
: origin_{begin}, dest_{end}, index_{index_begin}, index_end_{index_end}, cursor_{cursor}, y_error_{error} {}
/**
Return the normalized delta vector.
The first axis is always the longest. All values are non-negative.
*/
inline Point2 get_normalized_delta() const noexcept { return get_normalized_delta(origin_, dest_); }
static Point2 get_normalized_delta(const Point2& origin, const Point2& dest) noexcept {
return std::abs(dest.at(0) - origin.at(0)) > std::abs(dest.at(1) - origin.at(1))
? Point2{std::abs(dest.at(0) - origin.at(0)), std::abs(dest.at(1) - origin.at(1))}
: Point2{std::abs(dest.at(1) - origin.at(1)), std::abs(dest.at(0) - origin.at(0))};
}
/**
Return the normalized delta X value.
This is the value of the longest delta axis as a positive integer and is often used to determine the line length.
*/
inline int get_delta_x() const noexcept { return get_normalized_delta().at(0); }
/**
Advance one step using the Bresenham algorithm.
*/
inline BresenhamLine& bresenham_next() {
const Point2 delta = get_normalized_delta();
y_error_ += delta.at(1);
if (y_error_ > 0) {
++cursor_.at(1);
y_error_ -= delta.at(0);
};
++cursor_.at(0);
return *this;
}
/**
Inverse Bresenham algorithm. Takes one step backwards.
*/
inline BresenhamLine& bresenham_prev() {
const Point2 delta = get_normalized_delta();
y_error_ -= delta.at(1);
if (y_error_ <= -delta.at(0)) {
--cursor_.at(1);
y_error_ += delta.at(0);
};
--cursor_.at(0);
return *this;
}
/**
Seek to the given index and return the world position of the cursor.
*/
inline Point2 bresenham_get(int index) {
while (cursor_.at(0) < index) bresenham_next();
while (cursor_.at(0) > index) bresenham_prev();
return get_matrix().transform(cursor_);
}
Point2 origin_; // Starting point.
Point2 dest_; // Ending point.
int index_; // The starting index returned by `begin`.
int index_end_; // The past-the-end index returned by `end`.
Point2 cursor_; // Normalized Bresenham low-slope position. First axis acts as the current index.
int y_error_; // Fractional difference between Y indexes. Is always `-delta[0] < err <= 0`.
};
} // namespace tcod
#endif

View file

@ -0,0 +1,76 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_BSP_H
#define _TCOD_BSP_H
#include "mersenne_types.h"
#include "portability.h"
#include "tree.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
TCOD_tree_t tree; /* pseudo oop : bsp inherit tree */
int x, y, w, h; /* node position & size */
int position; /* position of splitting */
uint8_t level; /* level in the tree */
bool horizontal; /* horizontal splitting ? */
} TCOD_bsp_t;
typedef bool (*TCOD_bsp_callback_t)(TCOD_bsp_t* node, void* userData);
TCODLIB_API TCOD_bsp_t* TCOD_bsp_new(void);
TCODLIB_API TCOD_bsp_t* TCOD_bsp_new_with_size(int x, int y, int w, int h);
TCODLIB_API void TCOD_bsp_delete(TCOD_bsp_t* node);
TCODLIB_API TCOD_bsp_t* TCOD_bsp_left(TCOD_bsp_t* node);
TCODLIB_API TCOD_bsp_t* TCOD_bsp_right(TCOD_bsp_t* node);
TCODLIB_API TCOD_bsp_t* TCOD_bsp_father(TCOD_bsp_t* node);
TCODLIB_API bool TCOD_bsp_is_leaf(TCOD_bsp_t* node);
TCODLIB_API bool TCOD_bsp_traverse_pre_order(TCOD_bsp_t* node, TCOD_bsp_callback_t listener, void* userData);
TCODLIB_API bool TCOD_bsp_traverse_in_order(TCOD_bsp_t* node, TCOD_bsp_callback_t listener, void* userData);
TCODLIB_API bool TCOD_bsp_traverse_post_order(TCOD_bsp_t* node, TCOD_bsp_callback_t listener, void* userData);
TCODLIB_API bool TCOD_bsp_traverse_level_order(TCOD_bsp_t* node, TCOD_bsp_callback_t listener, void* userData);
TCODLIB_API bool TCOD_bsp_traverse_inverted_level_order(TCOD_bsp_t* node, TCOD_bsp_callback_t listener, void* userData);
TCODLIB_API bool TCOD_bsp_contains(TCOD_bsp_t* node, int x, int y);
TCODLIB_API TCOD_bsp_t* TCOD_bsp_find_node(TCOD_bsp_t* node, int x, int y);
TCODLIB_API void TCOD_bsp_resize(TCOD_bsp_t* node, int x, int y, int w, int h);
TCODLIB_API void TCOD_bsp_split_once(TCOD_bsp_t* node, bool horizontal, int position);
TCODLIB_API void TCOD_bsp_split_recursive(
TCOD_bsp_t* node, TCOD_Random* randomizer, int nb, int minHSize, int minVSize, float maxHRatio, float maxVRatio);
TCODLIB_API void TCOD_bsp_remove_sons(TCOD_bsp_t* node);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,428 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
#ifndef _TCOD_BSP_HPP
#define _TCOD_BSP_HPP
#include <utility>
#include "bsp.h"
#include "list.hpp"
#include "mersenne.hpp"
#include "tree.hpp"
class TCODBsp;
class TCODLIB_API ITCODBspCallback {
public :
virtual ~ITCODBspCallback() {}
virtual bool visitNode(TCODBsp *node, void *userData) = 0;
};
/**
@PageName bsp
@PageCategory Roguelike toolkits
@PageTitle BSP toolkit
@PageDesc This toolkit allows one to create and manipulate 2D Binary Space Partition trees. They can be used to split a rectangular region into non overlapping sub-regions.
*/
class TCODLIB_API TCODBsp : public TCODTree {
public :
int x,y,w,h; //
int position; // position of splitting
bool horizontal; // horizontal splitting ?
uint8_t level; // level in the tree
/**
@PageName bsp_init
@PageFather bsp
@PageTitle Creating a BSP tree
@FuncTitle Creating the root node
@FuncDesc First, you have to create the root node of the tree. This node encompasses the whole rectangular region.
@Cpp TCODBsp::TCODBsp(int x,int y,int w, int h)
@C TCOD_bsp_t *TCOD_bsp_new_with_size(int x,int y,int w, int h)
@Py bsp_new_with_size(x,y,w, h)
@C# TCODBsp::TCODBsp(int x, int y, int w, int h)
@Param x,y,w,h Top left corner position and size of the rectangular region covered by the BSP tree.
@CppEx TCODBsp *myBSP = new TCODBsp(0,0,50,50);
@CEx TCOD_bsp_t *my_bsp=TCOD_bsp_new_with_size(0,0,50,50);
@PyEx my_bsp=libtcod.bsp_new_with_size(0,0,50,50)
*/
TCODBsp() : level(0) {}
TCODBsp(int x,int y,int w, int h) : x(x),y(y),w(w),h(h),level(0) {}
TCODBsp(const TCODBsp&) = delete;
TCODBsp& operator=(const TCODBsp&) = delete;
TCODBsp(TCODBsp&& rhs) noexcept { (*this) = std::move(rhs); };
TCODBsp& operator=(TCODBsp&& rhs) noexcept {
std::swap(next, rhs.next);
std::swap(father, rhs.father);
std::swap(sons, rhs.sons);
return *this;
};
/**
@PageName bsp_init
@FuncTitle Deleting a part of the tree
@FuncDesc You can delete a part of the tree, releasing resources for all sub nodes with :
@Cpp void TCODBsp::removeSons()
@C void TCOD_bsp_remove_sons(TCOD_bsp_t *node)
@Py bsp_remove_sons(node)
@C# TCODBsp::removeSons()
@Param node In the C version, the node reference.
@CppEx
TCODBsp *myBSP = new TCODBsp(0,0,50,50);
// create a tree
myBSP->splitRecursive(NULL,4,5,5,1.5f,1.5f);
// clear it (keep only the root)
myBSP->removeSons();
// and rebuild another random tree
myBSP->splitRecursive(NULL,4,5,5,1.5f,1.5f);
@CEx
TCOD_bsp_t *my_bsp=TCOD_bsp_new_with_size(0,0,50,50);
TCOD_bsp_split_recursive(my_bsp,NULL,4,5,5,1.5f,1.5f);
TCOD_bsp_remove_sons(my_bsp);
TCOD_bsp_split_recursive(my_bsp,NULL,4,5,5,1.5f,1.5f);
@PyEx
my_bsp=libtcod.bsp_new_with_size(0,0,50,50)
libtcod.bsp_split_recursive(my_bsp,0,4,5,5,1.5,1.5)
libtcod.bsp_remove_sons(my_bsp)
libtcod.bsp_split_recursive(my_bsp,0,4,5,5,1.5,1.5)
*/
void removeSons();
/**
@PageName bsp_init
@FuncTitle deleting the tree
@FuncDesc You can also completely delete the tree, including the root node to release every resource used :
@Cpp void TCODBsp::~TCODBsp()
@C void TCOD_bsp_delete(TCOD_bsp_t *node)
@Py bsp_delete(node)
@C# void TCODBsp::Dispose()
@Param node In the C version, the node reference.
@CppEx
TCODBsp *myBSP = new TCODBsp(0,0,50,50);
// create a tree
myBSP->splitRecursive(NULL,4,5,5,1.5f,1.5f);
// use the tree ...
// delete the tree
delete myBSP;
@CEx
TCOD_bsp_t *my_bsp=TCOD_bsp_new_with_size(0,0,50,50);
TCOD_bsp_split_recursive(my_bsp,NULL,4,5,5,1.5f,1.5f);
// use the tree ...
TCOD_bsp_delete(my_bsp);
@PyEx
my_bsp=libtcod.bsp_new_with_size(0,0,50,50)
libtcod.bsp_split_recursive(my_bsp,0,4,5,5,1.5,1.5)
# use the tree ...
libtcod.bsp_delete(my_bsp)
*/
virtual ~TCODBsp();
/**
@PageName bsp_split
@PageFather bsp
@PageTitle Splitting the tree
@FuncTitle Splitting a node once
@FuncDesc Once you have the root node, you can split it into two smaller non-overlapping nodes.
@Cpp void TCODBsp::splitOnce(bool horizontal, int position)
@C void TCOD_bsp_split_once(TCOD_bsp_t *node, bool horizontal, int position)
@Py bsp_split_once(node, horizontal, position)
@C# void TCODBsp::splitOnce(bool horizontal, int position)
@Param node In the C version, the root node created with TCOD_bsp_new_with_size, or a node obtained by splitting.
@Param horizontal If true, the node will be split horizontally, else, vertically.
@Param position Coordinate of the splitting position.
If horizontal is true, x <= position < x+w
Else, y <= position < y+h
@CppEx
TCODBsp *myBSP = new TCODBsp(0,0,50,50);
myBSP->splitOnce(true,20); // horizontal split into two nodes : (0,0,50,20) and (0,20,50,30)
@CEx
TCOD_bsp_t *my_bsp=TCOD_bsp_new_with_size(0,0,50,50);
TCOD_bsp_split_once(my_bsp,false,20); // vertical split into two nodes : (0,0,20,50) and (20,0,30,50)
@PyEx
my_bsp=libtcod.bsp_new_with_size(0,0,50,50)
libtcod.bsp_split_once(my_bsp,False,20) # vertical split into two nodes : (0,0,20,50) and (20,0,30,50)
*/
void splitOnce(bool horizontal, int position);
/**
@PageName bsp_split
@FuncTitle Recursively splitting a node
@FuncDesc You can also recursively split the bsp. At each step, a random orientation (horizontal/vertical) and position are chosen :
@Cpp void TCODBsp::splitRecursive(TCODRandom *randomizer, int nb, int minHSize, int minVSize, float maxHRatio, float maxVRatio);
@C void TCOD_bsp_split_recursive(TCOD_bsp_t *node, TCOD_random_t randomizer, int nb, int minHSize, int minVSize, float maxHRatio, float maxVRatio)
@Py bsp_split_recursive(node, randomizer, nb, minHSize, minVSize, maxHRatio, maxVRatio)
@C# void TCODBsp::splitRecursive(TCODRandom randomizer, int nb, int minHSize, int minVSize, float maxHRatio, float maxVRatio)
@Param node In the C version, the root node created with TCOD_bsp_new_with_size, or a node obtained by splitting.
@Param randomizer The random number generator to use. Use NULL for the default one.
@Param nb Number of recursion levels.
@Param minHSize, minVSize minimum values of w and h for a node. A node is split only if the resulting sub-nodes are bigger than minHSize x minVSize
@Param maxHRatio, maxVRation maximum values of w/h and h/w for a node. If a node does not conform, the splitting orientation is forced to reduce either the w/h or the h/w ratio. Use values near 1.0 to promote square nodes.
@CppEx
// Do a 4 levels BSP tree (the region is split into a maximum of 2*2*2*2 sub-regions).
TCODBsp *myBSP = new TCODBsp(0,0,50,50);
myBSP->splitRecursive(NULL,4,5,5,1.5f,1.5f);
@CEx
TCOD_bsp_t *my_bsp=TCOD_bsp_new_with_size(0,0,50,50);
TCOD_bsp_split_recursive(my_bsp,NULL,4,5,5,1.5f,1.5f);
@PyEx
my_bsp=libtcod.bsp_new_with_size(0,0,50,50)
libtcod.bsp_split_recursive(my_bsp,0,4,5,5,1.5,1.5)
*/
void splitRecursive(TCODRandom *randomizer, int nb, int minHSize, int minVSize, float maxHRatio, float maxVRatio);
/**
@PageName bsp_resize
@PageTitle Resizing a tree
@PageFather bsp
@FuncDesc This operation resets the size of the tree nodes without changing the splitting data (orientation/position). It should be called with the initial region size or a bigger size, else some splitting position may be out of the region.
You can use it if you changed the nodes size and position while using the BSP tree, which happens typically when you use the tree to build a dungeon. You create rooms inside the tree leafs, then shrink the leaf to fit the room size. Calling resize on the root node with the original region size allows you to reset all nodes to their original size.
@Cpp void TCODBsp::resize(int x,int y, int w, int h)
@C void TCOD_bsp_resize(TCOD_bsp_t *node, int x,int y, int w, int h)
@Py bsp_resize(node, x,y, w, h)
@C# void TCODBsp::resize(int x, int y, int w, int h)
@Param node In the C version, the root node created with TCOD_bsp_new_with_size, or a node obtained by splitting.
@Param x,y,w,h New position and size of the node. The original rectangular area covered by the node should be included in the new one to ensure that every splitting edge stay inside its node.
@CppEx
// We create a BSP, do some processing that will modify the x,y,w,h fields of the tree nodes, then reset all the nodes to their original size.
TCODBsp *myBSP = new TCODBsp(0,0,50,50);
myBSP->splitRecursive(NULL,4,5,5,1.5f,1.5f);
// ... do something with the tree here
myBSP->resize(0,0,50,50);
@CEx
TCOD_bsp_t *my_bsp=TCOD_bsp_new_with_size(0,0,50,50);
TCOD_bsp_split_recursive(my_bsp,NULL,4,5,5,1.5f,1.5f);
// ... do something with the tree here
TCOD_bsp_resize(my_bsp,0,0,50,50);
@PyEx
my_bsp=libtcod.bsp_new_with_size(0,0,50,50)
libtcod.bsp_split_recursive(my_bsp,0,4,5,5,1.5,1.5)
# ... do something with the tree here
libtcod.bsp_resize(my_bsp,0,0,50,50)
*/
void resize(int x,int y, int w, int h);
/**
@PageName bsp_read
@PageFather bsp
@PageTitle Reading information from the tree
@FuncDesc Once you have built a BSP tree, you can retrieve information from any node. The node gives you free access to its fields :
@Cpp
class TCODBsp {
public :
int x,y,w,h; //
int position; // position of splitting
bool horizontal; // horizontal splitting ?
uint8_t level; // level in the tree
...
}
@C
typedef struct {
int x,y,w,h;
int position;
bool horizontal;
uint8_t level;
...
} TCOD_bsp_t;
@C#
class TCODBsp
{
public int x { get; set; }
public int y { get; set; }
public int h { get; set; }
public int w { get; set; }
public int position { get; set; }
public bool horizontal { get; set; }
public byte level { get; set; }
}
@Param x,y,w,h Rectangular region covered by this node.
@Param position If this node is not a leaf, splitting position.
@Param horizontal If this node is not a leaf, splitting orientation.
@Param level Level in the BSP tree (0 for the root, 1 for the root's sons, ...).
*/
/**
@PageName bsp_read
@FuncTitle Navigate in the tree
@FuncDesc You can navigate from a node to its sons or its parent using one of those functions. Each function returns NULL if the corresponding node does not exists (if the node is not split for getLeft and getRight, and if the node is the root node for getFather).
@Cpp
TCODBsp *TCODBsp::getLeft() const
TCODBsp *TCODBsp::getRight() const
TCODBsp *TCODBsp::getFather() const
@C
TCOD_bsp_t * TCOD_bsp_left(TCOD_bsp_t *node)
TCOD_bsp_t * TCOD_bsp_right(TCOD_bsp_t *node)
TCOD_bsp_t * TCOD_bsp_father(TCOD_bsp_t *node)
@Py
bsp_left(node)
bsp_right(node)
bsp_father(node)
@C#
TCODBsp TCODBsp::getLeft()
TCODBsp TCODBsp::getRight()
TCODBsp TCODBsp::getFather()
@Param node In the C version, the node reference.
*/
TCODBsp *getLeft() const {
return static_cast<TCODBsp*>(sons);
}
TCODBsp *getRight() const {
return sons ? static_cast<TCODBsp*>(sons->next) : NULL;
}
TCODBsp *getFather() const {
return static_cast<TCODBsp*>(father);
}
/**
@PageName bsp_read
@FuncTitle Checking if a node is a leaf
@FuncDesc You can know if a node is a leaf (not split, no sons) with this function :
@Cpp bool TCODBsp::isLeaf() const
@C bool TCOD_bsp_is_leaf(TCOD_bsp_t *node)
@Py bsp_is_leaf(node)
@C# bool TCODBsp::isLeaf()
*/
bool isLeaf() const { return sons == NULL ; }
/**
@PageName bsp_read
@FuncTitle Check if a cell is inside a node
@FuncDesc You can check if a map cell is inside a node.
@Cpp bool TCODBsp::contains(int cx, int cy) const
@C bool TCOD_bsp_contains(TCOD_bsp_t *node, int cx, int cy)
@Py bsp_contains(node, cx, cy)
@C# bool TCODBsp::contains(int x, int y)
@Param node In the C version, the node reference.
@Param cx,cy Map cell coordinates.
*/
bool contains(int x, int y) const;
/**
@PageName bsp_read
@FuncTitle Getting the node containing a cell
@FuncDesc You can search the tree for the smallest node containing a map cell. If the cell is outside the tree, the function returns NULL :
@Cpp TCODBsp *TCODBsp::findNode(int cx, int cy)
@C TCOD_bsp_t * TCOD_bsp_find_node(TCOD_bsp_t *node, int cx, int cy)
@Py bsp_find_node(node, cx, cy)
@C# TCODBsp TCODBsp::findNode(int x, int y)
@Param node In the C version, the node reference.
@Param cx,cy Map cell coordinates.
*/
TCODBsp *findNode(int x, int y);
/**
@PageName bsp_traverse
@PageFather bsp
@PageTitle Traversing the tree
@FuncDesc You can scan all the nodes of the tree and have a custom function called back for each node.
Each traversal function returns false if the traversal has been interrupted (a callback returned false).
* Pre-order : the callback is called for the current node, then for the left son, then for the right son.
* In-order : the callback is called for the left son, then for current node, then for the right son.
* Post-order : the callback is called for the left son, then for the right son, then for the current node.
* Level-order : the callback is called for the nodes level by level, from left to right.
* Inverted level-order : the callback is called in the exact inverse order as Level-order.
<table class="param">
<tbody><tr><th>Pre order</th><th>In order</th><th>Post order</th><th>Level order</th><th>Inverted level<br>order</th></tr>
<tr><td><img src="bsp_preorder.png"></td><td><img src="bsp_inorder.png"></td><td><img src="bsp_postorder.png"></td><td><img src="bsp_levelorder.png"></td><td><img src="bsp_invlevelorder.png"></td></tr>
</tbody></table>
@Cpp
class ITCODBspCallback {
public :
virtual bool visitNode(TCODBsp *node, void *userData) = 0;
};
bool TCODBsp::traversePreOrder(ITCODBspCallback *callback, void *userData)
bool TCODBsp::traverseInOrder(ITCODBspCallback *callback, void *userData)
bool TCODBsp::traversePostOrder(ITCODBspCallback *callback, void *userData)
bool TCODBsp::traverseLevelOrder(ITCODBspCallback *callback, void *userData)
bool TCODBsp::traverseInvertedLevelOrder(ITCODBspCallback *callback, void *userData)
@C
typedef bool (*TCOD_bsp_callback_t)(TCOD_bsp_t *node, void *userData)
bool TCOD_bsp_traverse_pre_order(TCOD_bsp_t *node, TCOD_bsp_callback_t callback, void *userData)
bool TCOD_bsp_traverse_in_order(TCOD_bsp_t *node, TCOD_bsp_callback_t callback, void *userData)
bool TCOD_bsp_traverse_post_order(TCOD_bsp_t *node, TCOD_bsp_callback_t callback, void *userData)
bool TCOD_bsp_traverse_level_order(TCOD_bsp_t *node, TCOD_bsp_callback_t callback, void *userData)
bool TCOD_bsp_traverse_inverted_level_order(TCOD_bsp_t *node, TCOD_bsp_callback_t callback, void *userData)
@Py
def bsp_callback(node, userData) : # ...
bsp_traverse_pre_order(node, callback, userData=0)
bsp_traverse_in_order(node, callback, userData=0)
bsp_traverse_post_order(node, callback, userData=0)
bsp_traverse_level_order(node, callback, userData=0)
bsp_traverse_inverted_level_order(node, callback, userData=0)
@C#
bool TCODBsp::traversePreOrder(ITCODBspCallback callback)
bool TCODBsp::traverseInOrder(ITCODBspCallback callback)
bool TCODBsp::traversePostOrder(ITCODBspCallback callback)
bool TCODBsp::traverseLevelOrder(ITCODBspCallback callback)
bool TCODBsp::traverseInvertedLevelOrder(ITCODBspCallback callback)
@Param node In the C version, the node reference (generally, the root node).
@Param callback The function to call for each node.
It receives the current node and the custom data as parameters
If it returns false, the traversal is interrupted.
@Param userData Custom data to pass to the callback.
@CppEx
class MyCallback : public ITCODBspCallback {
public :
bool visitNode(TCODBsp *node, void *userData) {
printf("node pos %dx%d size %dx%d level %d\n",node->x,node->y,node->w,node->h,node->level);
return true;
}
};
myBSP->traversePostOrder(new MyListener(),NULL);
@CEx
bool my_callback(TCOD_bsp_t *node, void *userData) {
printf("node pos %dx%d size %dx%d level %d\n",node->x,node->y,node->w,node->h,node->level);
return true;
}
TCOD_bsp_traverse_post_order(my_bsp,my_callback,NULL);
@PyEx
def my_callback(node, userData) :
print "node pos %dx%d size %dx%d level %d"%(node.x,node.y,node.w,node.h,node.level))
return True
libtcod.bsp_traverse_post_order(my_bsp,my_callback)
*/
bool traversePreOrder(ITCODBspCallback *listener, void *userData);
bool traverseInOrder(ITCODBspCallback *listener, void *userData);
bool traversePostOrder(ITCODBspCallback *listener, void *userData);
bool traverseLevelOrder(ITCODBspCallback *listener, void *userData);
bool traverseInvertedLevelOrder(ITCODBspCallback *listener, void *userData);
protected :
TCODBsp(TCODBsp *father, bool left);
};
#endif

View file

@ -0,0 +1,536 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_COLOR_H
#define _TCOD_COLOR_H
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
#include <istream>
#include <ostream>
#include <stdexcept>
#endif // __cplusplus
#include "config.h"
/**
A 3-channel RGB color struct.
*/
struct TCOD_ColorRGB {
#ifdef __cplusplus
constexpr bool operator==(const TCOD_ColorRGB& rhs) const noexcept { return r == rhs.r && g == rhs.g && b == rhs.b; }
constexpr bool operator!=(const TCOD_ColorRGB& rhs) const noexcept { return !(*this == rhs); }
friend std::ostream& operator<<(std::ostream& out, const TCOD_ColorRGB& rgb) {
return out << '{' << static_cast<int>(rgb.r) << ", " << static_cast<int>(rgb.g) << ", " << static_cast<int>(rgb.b)
<< '}';
}
friend std::istream& operator>>(std::istream& in, TCOD_ColorRGB& rgb) {
in >> std::ws;
char ch;
in >> ch;
if (ch != '{') throw std::runtime_error("Expected missing '{'.");
int channel;
in >> channel;
rgb.r = static_cast<uint8_t>(channel);
in >> ch;
if (ch != ',') throw std::runtime_error("Expected missing ',' delimiter.");
in >> channel;
rgb.g = static_cast<uint8_t>(channel);
in >> ch;
if (ch != ',') throw std::runtime_error("Expected missing ',' delimiter.");
in >> channel;
rgb.b = static_cast<uint8_t>(channel);
in >> ch;
if (ch != '}') throw std::runtime_error("Expected missing '}'.");
return in;
}
template <class Archive>
void serialize(Archive& archive) {
archive(r, g, b);
}
#endif // __cplusplus
uint8_t r;
uint8_t g;
uint8_t b;
};
typedef struct TCOD_ColorRGB TCOD_color_t;
typedef struct TCOD_ColorRGB TCOD_ColorRGB;
/**
A 4-channel RGBA color struct.
*/
struct TCOD_ColorRGBA {
#ifdef __cplusplus
constexpr bool operator==(const TCOD_ColorRGBA& rhs) const noexcept {
return r == rhs.r && g == rhs.g && b == rhs.b && a == rhs.a;
}
constexpr bool operator!=(const TCOD_ColorRGBA& rhs) const noexcept { return !(*this == rhs); }
constexpr TCOD_ColorRGBA& operator=(const TCOD_ColorRGB& rhs) {
return (*this) = TCOD_ColorRGBA{rhs.r, rhs.g, rhs.b, 255};
}
friend std::ostream& operator<<(std::ostream& out, const TCOD_ColorRGBA& rgba) {
return out << '{' << static_cast<int>(rgba.r) << ", " << static_cast<int>(rgba.g) << ", "
<< static_cast<int>(rgba.b) << ", " << static_cast<int>(rgba.a) << '}';
}
friend std::istream& operator>>(std::istream& in, TCOD_ColorRGBA& rgba) {
in >> std::ws;
char ch;
in >> ch;
if (ch != '{') throw std::runtime_error("Expected missing '{'.");
int channel;
in >> channel;
rgba.r = static_cast<uint8_t>(channel);
in >> ch;
if (ch != ',') throw std::runtime_error("Expected missing ',' delimiter.");
in >> channel;
rgba.g = static_cast<uint8_t>(channel);
in >> ch;
if (ch != ',') throw std::runtime_error("Expected missing ',' delimiter.");
in >> channel;
rgba.b = static_cast<uint8_t>(channel);
in >> ch;
if (ch == '}') {
rgba.a = 255;
return in;
}
if (ch != ',') throw std::runtime_error("Expected missing ',' delimiter.");
in >> channel;
rgba.a = static_cast<uint8_t>(channel);
in >> ch;
if (ch != '}') throw std::runtime_error("Expected missing '}'.");
return in;
}
template <class Archive>
void serialize(Archive& archive) {
archive(r, g, b, a);
}
#endif // __cplusplus
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
};
typedef struct TCOD_ColorRGBA TCOD_ColorRGBA;
#ifdef __cplusplus
extern "C" {
#endif
/* constructors */
TCODLIB_API TCOD_color_t TCOD_color_RGB(uint8_t r, uint8_t g, uint8_t b);
TCODLIB_API TCOD_color_t TCOD_color_HSV(float hue, float saturation, float value);
/* basic operations */
TCODLIB_API bool TCOD_color_equals(TCOD_color_t c1, TCOD_color_t c2);
TCODLIB_API TCOD_color_t TCOD_color_add(TCOD_color_t c1, TCOD_color_t c2);
TCODLIB_API TCOD_color_t TCOD_color_subtract(TCOD_color_t c1, TCOD_color_t c2);
TCODLIB_API TCOD_color_t TCOD_color_multiply(TCOD_color_t c1, TCOD_color_t c2);
TCODLIB_API TCOD_color_t TCOD_color_multiply_scalar(TCOD_color_t c1, float value);
TCODLIB_API TCOD_color_t TCOD_color_lerp(TCOD_color_t c1, TCOD_color_t c2, float coef);
/**
* Blend `src` into `dst` as an alpha blending operation.
* \rst
* .. versionadded:: 1.16
* \endrst
*/
void TCOD_color_alpha_blend(TCOD_ColorRGBA* dst, const TCOD_ColorRGBA* src);
/* HSV transformations */
TCODLIB_API void TCOD_color_set_HSV(TCOD_color_t* color, float hue, float saturation, float value);
TCODLIB_API void TCOD_color_get_HSV(TCOD_color_t color, float* hue, float* saturation, float* value);
TCODLIB_API float TCOD_color_get_hue(TCOD_color_t color);
TCODLIB_API void TCOD_color_set_hue(TCOD_color_t* color, float hue);
TCODLIB_API float TCOD_color_get_saturation(TCOD_color_t color);
TCODLIB_API void TCOD_color_set_saturation(TCOD_color_t* color, float saturation);
TCODLIB_API float TCOD_color_get_value(TCOD_color_t color);
TCODLIB_API void TCOD_color_set_value(TCOD_color_t* color, float value);
TCODLIB_API void TCOD_color_shift_hue(TCOD_color_t* color, float shift);
TCODLIB_API void TCOD_color_scale_HSV(TCOD_color_t* color, float saturation_coef, float value_coef);
/* color map */
TCODLIB_API void TCOD_color_gen_map(TCOD_color_t* map, int nb_key, const TCOD_color_t* key_color, const int* key_index);
/// @cond INTERNAL
/***************************************************************************
@brief Color names.
\rst
.. deprecated:: 1.23
\endrst
*/
enum {
TCOD_COLOR_RED TCOD_DEPRECATED_ENUM,
TCOD_COLOR_FLAME TCOD_DEPRECATED_ENUM,
TCOD_COLOR_ORANGE TCOD_DEPRECATED_ENUM,
TCOD_COLOR_AMBER TCOD_DEPRECATED_ENUM,
TCOD_COLOR_YELLOW TCOD_DEPRECATED_ENUM,
TCOD_COLOR_LIME TCOD_DEPRECATED_ENUM,
TCOD_COLOR_CHARTREUSE TCOD_DEPRECATED_ENUM,
TCOD_COLOR_GREEN TCOD_DEPRECATED_ENUM,
TCOD_COLOR_SEA TCOD_DEPRECATED_ENUM,
TCOD_COLOR_TURQUOISE TCOD_DEPRECATED_ENUM,
TCOD_COLOR_CYAN TCOD_DEPRECATED_ENUM,
TCOD_COLOR_SKY TCOD_DEPRECATED_ENUM,
TCOD_COLOR_AZURE TCOD_DEPRECATED_ENUM,
TCOD_COLOR_BLUE TCOD_DEPRECATED_ENUM,
TCOD_COLOR_HAN TCOD_DEPRECATED_ENUM,
TCOD_COLOR_VIOLET TCOD_DEPRECATED_ENUM,
TCOD_COLOR_PURPLE TCOD_DEPRECATED_ENUM,
TCOD_COLOR_FUCHSIA TCOD_DEPRECATED_ENUM,
TCOD_COLOR_MAGENTA TCOD_DEPRECATED_ENUM,
TCOD_COLOR_PINK TCOD_DEPRECATED_ENUM,
TCOD_COLOR_CRIMSON TCOD_DEPRECATED_ENUM,
TCOD_COLOR_NB
};
#if defined(_MSC_VER) && !defined(__clang__)
#pragma deprecated(TCOD_COLOR_RED)
#pragma deprecated(TCOD_COLOR_FLAME)
#pragma deprecated(TCOD_COLOR_ORANGE)
#pragma deprecated(TCOD_COLOR_AMBER)
#pragma deprecated(TCOD_COLOR_YELLOW)
#pragma deprecated(TCOD_COLOR_LIME)
#pragma deprecated(TCOD_COLOR_CHARTREUSE)
#pragma deprecated(TCOD_COLOR_GREEN)
#pragma deprecated(TCOD_COLOR_SEA)
#pragma deprecated(TCOD_COLOR_TURQUOISE)
#pragma deprecated(TCOD_COLOR_CYAN)
#pragma deprecated(TCOD_COLOR_SKY)
#pragma deprecated(TCOD_COLOR_AZURE)
#pragma deprecated(TCOD_COLOR_BLUE)
#pragma deprecated(TCOD_COLOR_HAN)
#pragma deprecated(TCOD_COLOR_VIOLET)
#pragma deprecated(TCOD_COLOR_PURPLE)
#pragma deprecated(TCOD_COLOR_FUCHSIA)
#pragma deprecated(TCOD_COLOR_MAGENTA)
#pragma deprecated(TCOD_COLOR_PINK)
#pragma deprecated(TCOD_COLOR_CRIMSON)
#endif // _MSC_VER
/***************************************************************************
@brief Color levels
\rst
.. deprecated:: 1.23
\endrst
*/
enum {
TCOD_COLOR_DESATURATED TCOD_DEPRECATED_ENUM,
TCOD_COLOR_LIGHTEST TCOD_DEPRECATED_ENUM,
TCOD_COLOR_LIGHTER TCOD_DEPRECATED_ENUM,
TCOD_COLOR_LIGHT TCOD_DEPRECATED_ENUM,
TCOD_COLOR_NORMAL TCOD_DEPRECATED_ENUM,
TCOD_COLOR_DARK TCOD_DEPRECATED_ENUM,
TCOD_COLOR_DARKER TCOD_DEPRECATED_ENUM,
TCOD_COLOR_DARKEST TCOD_DEPRECATED_ENUM,
TCOD_COLOR_LEVELS
};
#if defined(_MSC_VER) && !defined(__clang__)
#pragma deprecated(TCOD_COLOR_DESATURATED)
#pragma deprecated(TCOD_COLOR_LIGHTEST)
#pragma deprecated(TCOD_COLOR_LIGHTER)
#pragma deprecated(TCOD_COLOR_LIGHT)
#pragma deprecated(TCOD_COLOR_NORMAL)
#pragma deprecated(TCOD_COLOR_DARK)
#pragma deprecated(TCOD_COLOR_DARKER)
#pragma deprecated(TCOD_COLOR_DARKEST)
#endif // _MSC_VER
/* color array */
extern TCODLIB_API const TCOD_color_t TCOD_colors[TCOD_COLOR_NB][TCOD_COLOR_LEVELS];
/* grey levels */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 0, 0}") extern TCODLIB_API const TCOD_color_t TCOD_black;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){31, 31, 31}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_grey;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 63, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darker_grey;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){95, 95, 95}") extern TCODLIB_API const TCOD_color_t TCOD_dark_grey;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 127, 127}") extern TCODLIB_API const TCOD_color_t TCOD_grey;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){159, 159, 159}") extern TCODLIB_API const TCOD_color_t TCOD_light_grey;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 191, 191}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_grey;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){223, 223, 223}") extern TCODLIB_API const TCOD_color_t TCOD_lightest_grey;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){31, 31, 31}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_gray;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 63, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darker_gray;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){95, 95, 95}") extern TCODLIB_API const TCOD_color_t TCOD_dark_gray;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 127, 127}") extern TCODLIB_API const TCOD_color_t TCOD_gray;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){159, 159, 159}") extern TCODLIB_API const TCOD_color_t TCOD_light_gray;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 191, 191}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_gray;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){223, 223, 223}") extern TCODLIB_API const TCOD_color_t TCOD_lightest_gray;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 255, 255}") extern TCODLIB_API const TCOD_color_t TCOD_white;
/* sepia */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){31, 24, 15}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_sepia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 50, 31}") extern TCODLIB_API const TCOD_color_t TCOD_darker_sepia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){94, 75, 47}") extern TCODLIB_API const TCOD_color_t TCOD_dark_sepia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 101, 63}") extern TCODLIB_API const TCOD_color_t TCOD_sepia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){158, 134, 100}") extern TCODLIB_API const TCOD_color_t TCOD_light_sepia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 171, 143}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_sepia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){222, 211, 195}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_sepia;
/* standard colors */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 0, 0}") extern TCODLIB_API const TCOD_color_t TCOD_red;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 63, 0}") extern TCODLIB_API const TCOD_color_t TCOD_flame;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 127, 0}") extern TCODLIB_API const TCOD_color_t TCOD_orange;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 191, 0}") extern TCODLIB_API const TCOD_color_t TCOD_amber;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 255, 0}") extern TCODLIB_API const TCOD_color_t TCOD_yellow;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 255, 0}") extern TCODLIB_API const TCOD_color_t TCOD_lime;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 255, 0}") extern TCODLIB_API const TCOD_color_t TCOD_chartreuse;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 255, 0}") extern TCODLIB_API const TCOD_color_t TCOD_green;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 255, 127}") extern TCODLIB_API const TCOD_color_t TCOD_sea;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 255, 191}") extern TCODLIB_API const TCOD_color_t TCOD_turquoise;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 255, 255}") extern TCODLIB_API const TCOD_color_t TCOD_cyan;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 191, 255}") extern TCODLIB_API const TCOD_color_t TCOD_sky;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 127, 255}") extern TCODLIB_API const TCOD_color_t TCOD_azure;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 0, 255}") extern TCODLIB_API const TCOD_color_t TCOD_blue;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 0, 255}") extern TCODLIB_API const TCOD_color_t TCOD_han;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 0, 255}") extern TCODLIB_API const TCOD_color_t TCOD_violet;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 0, 255}") extern TCODLIB_API const TCOD_color_t TCOD_purple;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 0, 255}") extern TCODLIB_API const TCOD_color_t TCOD_fuchsia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 0, 191}") extern TCODLIB_API const TCOD_color_t TCOD_magenta;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 0, 127}") extern TCODLIB_API const TCOD_color_t TCOD_pink;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 0, 63}") extern TCODLIB_API const TCOD_color_t TCOD_crimson;
/* dark colors */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 0, 0}") extern TCODLIB_API const TCOD_color_t TCOD_dark_red;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 47, 0}") extern TCODLIB_API const TCOD_color_t TCOD_dark_flame;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 95, 0}") extern TCODLIB_API const TCOD_color_t TCOD_dark_orange;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 143, 0}") extern TCODLIB_API const TCOD_color_t TCOD_dark_amber;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 191, 0}") extern TCODLIB_API const TCOD_color_t TCOD_dark_yellow;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){143, 191, 0}") extern TCODLIB_API const TCOD_color_t TCOD_dark_lime;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){95, 191, 0}") extern TCODLIB_API const TCOD_color_t TCOD_dark_chartreuse;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 191, 0}") extern TCODLIB_API const TCOD_color_t TCOD_dark_green;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 191, 95}") extern TCODLIB_API const TCOD_color_t TCOD_dark_sea;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 191, 143}") extern TCODLIB_API const TCOD_color_t TCOD_dark_turquoise;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 191, 191}") extern TCODLIB_API const TCOD_color_t TCOD_dark_cyan;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 143, 191}") extern TCODLIB_API const TCOD_color_t TCOD_dark_sky;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 95, 191}") extern TCODLIB_API const TCOD_color_t TCOD_dark_azure;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 0, 191}") extern TCODLIB_API const TCOD_color_t TCOD_dark_blue;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){47, 0, 191}") extern TCODLIB_API const TCOD_color_t TCOD_dark_han;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){95, 0, 191}") extern TCODLIB_API const TCOD_color_t TCOD_dark_violet;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){143, 0, 191}") extern TCODLIB_API const TCOD_color_t TCOD_dark_purple;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 0, 191}") extern TCODLIB_API const TCOD_color_t TCOD_dark_fuchsia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 0, 143}") extern TCODLIB_API const TCOD_color_t TCOD_dark_magenta;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 0, 95}") extern TCODLIB_API const TCOD_color_t TCOD_dark_pink;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 0, 47}") extern TCODLIB_API const TCOD_color_t TCOD_dark_crimson;
/* darker colors */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 0, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darker_red;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 31, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darker_flame;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 63, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darker_orange;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 95, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darker_amber;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 127, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darker_yellow;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){95, 127, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darker_lime;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 127, 0}")
extern TCODLIB_API const TCOD_color_t TCOD_darker_chartreuse;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 127, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darker_green;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 127, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darker_sea;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 127, 95}") extern TCODLIB_API const TCOD_color_t TCOD_darker_turquoise;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 127, 127}") extern TCODLIB_API const TCOD_color_t TCOD_darker_cyan;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 95, 127}") extern TCODLIB_API const TCOD_color_t TCOD_darker_sky;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 63, 127}") extern TCODLIB_API const TCOD_color_t TCOD_darker_azure;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 0, 127}") extern TCODLIB_API const TCOD_color_t TCOD_darker_blue;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){31, 0, 127}") extern TCODLIB_API const TCOD_color_t TCOD_darker_han;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 0, 127}") extern TCODLIB_API const TCOD_color_t TCOD_darker_violet;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){95, 0, 127}") extern TCODLIB_API const TCOD_color_t TCOD_darker_purple;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 0, 127}") extern TCODLIB_API const TCOD_color_t TCOD_darker_fuchsia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 0, 95}") extern TCODLIB_API const TCOD_color_t TCOD_darker_magenta;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 0, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darker_pink;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 0, 31}") extern TCODLIB_API const TCOD_color_t TCOD_darker_crimson;
/* darkest colors */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 0, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_red;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 15, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_flame;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 31, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_orange;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 47, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_amber;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 63, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_yellow;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){47, 63, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_lime;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){31, 63, 0}")
extern TCODLIB_API const TCOD_color_t TCOD_darkest_chartreuse;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 63, 0}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_green;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 63, 31}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_sea;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 63, 47}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_turquoise;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 63, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_cyan;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 47, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_sky;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 31, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_azure;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){0, 0, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_blue;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){15, 0, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_han;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){31, 0, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_violet;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){47, 0, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_purple;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 0, 63}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_fuchsia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 0, 47}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_magenta;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 0, 31}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_pink;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 0, 15}") extern TCODLIB_API const TCOD_color_t TCOD_darkest_crimson;
/* light colors */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 63, 63}") extern TCODLIB_API const TCOD_color_t TCOD_light_red;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 111, 63}") extern TCODLIB_API const TCOD_color_t TCOD_light_flame;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 159, 63}") extern TCODLIB_API const TCOD_color_t TCOD_light_orange;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 207, 63}") extern TCODLIB_API const TCOD_color_t TCOD_light_amber;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 255, 63}") extern TCODLIB_API const TCOD_color_t TCOD_light_yellow;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){207, 255, 63}") extern TCODLIB_API const TCOD_color_t TCOD_light_lime;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){159, 255, 63}")
extern TCODLIB_API const TCOD_color_t TCOD_light_chartreuse;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 255, 63}") extern TCODLIB_API const TCOD_color_t TCOD_light_green;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 255, 159}") extern TCODLIB_API const TCOD_color_t TCOD_light_sea;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 255, 207}")
extern TCODLIB_API const TCOD_color_t TCOD_light_turquoise;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 255, 255}") extern TCODLIB_API const TCOD_color_t TCOD_light_cyan;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 207, 255}") extern TCODLIB_API const TCOD_color_t TCOD_light_sky;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 159, 255}") extern TCODLIB_API const TCOD_color_t TCOD_light_azure;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 63, 255}") extern TCODLIB_API const TCOD_color_t TCOD_light_blue;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){111, 63, 255}") extern TCODLIB_API const TCOD_color_t TCOD_light_han;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){159, 63, 255}") extern TCODLIB_API const TCOD_color_t TCOD_light_violet;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){207, 63, 255}") extern TCODLIB_API const TCOD_color_t TCOD_light_purple;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 63, 255}") extern TCODLIB_API const TCOD_color_t TCOD_light_fuchsia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 63, 207}") extern TCODLIB_API const TCOD_color_t TCOD_light_magenta;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 63, 159}") extern TCODLIB_API const TCOD_color_t TCOD_light_pink;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 63, 111}") extern TCODLIB_API const TCOD_color_t TCOD_light_crimson;
/* lighter colors */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 127, 127}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_red;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 159, 127}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_flame;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 191, 127}")
extern TCODLIB_API const TCOD_color_t TCOD_lighter_orange;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 223, 127}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_amber;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 255, 127}")
extern TCODLIB_API const TCOD_color_t TCOD_lighter_yellow;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){223, 255, 127}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_lime;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 255, 127}")
extern TCODLIB_API const TCOD_color_t TCOD_lighter_chartreuse;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 255, 127}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_green;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 255, 191}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_sea;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 255, 223}")
extern TCODLIB_API const TCOD_color_t TCOD_lighter_turquoise;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 255, 255}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_cyan;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 223, 255}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_sky;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 191, 255}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_azure;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 127, 255}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_blue;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){159, 127, 255}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_han;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 127, 255}")
extern TCODLIB_API const TCOD_color_t TCOD_lighter_violet;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){223, 127, 255}")
extern TCODLIB_API const TCOD_color_t TCOD_lighter_purple;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 127, 255}")
extern TCODLIB_API const TCOD_color_t TCOD_lighter_fuchsia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 127, 223}")
extern TCODLIB_API const TCOD_color_t TCOD_lighter_magenta;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 127, 191}") extern TCODLIB_API const TCOD_color_t TCOD_lighter_pink;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 127, 159}")
extern TCODLIB_API const TCOD_color_t TCOD_lighter_crimson;
/* lightest colors */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 191, 191}") extern TCODLIB_API const TCOD_color_t TCOD_lightest_red;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 207, 191}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_flame;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 223, 191}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_orange;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 239, 191}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_amber;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 255, 191}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_yellow;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){239, 255, 191}") extern TCODLIB_API const TCOD_color_t TCOD_lightest_lime;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){223, 255, 191}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_chartreuse;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 255, 191}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_green;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 255, 223}") extern TCODLIB_API const TCOD_color_t TCOD_lightest_sea;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 255, 239}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_turquoise;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 255, 255}") extern TCODLIB_API const TCOD_color_t TCOD_lightest_cyan;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 239, 255}") extern TCODLIB_API const TCOD_color_t TCOD_lightest_sky;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 223, 255}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_azure;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 191, 255}") extern TCODLIB_API const TCOD_color_t TCOD_lightest_blue;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){207, 191, 255}") extern TCODLIB_API const TCOD_color_t TCOD_lightest_han;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){223, 191, 255}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_violet;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){239, 191, 255}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_purple;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 191, 255}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_fuchsia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 191, 239}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_magenta;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 191, 223}") extern TCODLIB_API const TCOD_color_t TCOD_lightest_pink;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 191, 207}")
extern TCODLIB_API const TCOD_color_t TCOD_lightest_crimson;
/* desaturated */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 63, 63}") extern TCODLIB_API const TCOD_color_t TCOD_desaturated_red;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 79, 63}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_flame;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 95, 63}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_orange;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 111, 63}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_amber;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 127, 63}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_yellow;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){111, 127, 63}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_lime;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){95, 127, 63}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_chartreuse;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 127, 63}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_green;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 127, 95}") extern TCODLIB_API const TCOD_color_t TCOD_desaturated_sea;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 127, 111}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_turquoise;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 127, 127}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_cyan;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 111, 127}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_sky;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 95, 127}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_azure;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){63, 63, 127}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_blue;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){79, 63, 127}") extern TCODLIB_API const TCOD_color_t TCOD_desaturated_han;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){95, 63, 127}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_violet;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){111, 63, 127}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_purple;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 63, 127}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_fuchsia;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 63, 111}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_magenta;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 63, 95}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_pink;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){127, 63, 79}")
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_crimson;
/* metallic */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){191, 151, 96}") extern TCODLIB_API const TCOD_color_t TCOD_brass;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){197, 136, 124}") extern TCODLIB_API const TCOD_color_t TCOD_copper;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){229, 191, 0}") extern TCODLIB_API const TCOD_color_t TCOD_gold;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){203, 203, 203}") extern TCODLIB_API const TCOD_color_t TCOD_silver;
/* miscellaneous */
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){172, 255, 175}") extern TCODLIB_API const TCOD_color_t TCOD_celadon;
TCOD_DEPRECATED("Replace with (TCOD_ColorRGB){255, 159, 127}") extern TCODLIB_API const TCOD_color_t TCOD_peach;
/// @endcond
#ifdef __cplusplus
} // extern "C"
#endif
#endif

View file

@ -0,0 +1,807 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_COLOR_HPP
#define _TCOD_COLOR_HPP
#include <algorithm>
#include "color.h"
#include "utility.h"
namespace tcod {
/***************************************************************************
@brief A C++ RGB color, used to handle conversions between color types.
\rst
.. versionadded:: 1.19
\endrst
*/
struct ColorRGB : public TCOD_ColorRGB {
public:
/***************************************************************************
@brief Default construct a black ColorRGB object. RGB values are zero.
*/
constexpr ColorRGB() noexcept : ColorRGB{0, 0, 0} {}
/***************************************************************************
@brief Construct a ColorRGB object with the provided color.
*/
constexpr ColorRGB(uint8_t red, uint8_t green, uint8_t blue) noexcept : TCOD_ColorRGB{red, green, blue} {}
/***************************************************************************
@brief Construct a ColorRGB object from an TCOD_ColorRGB struct.
*/
explicit constexpr ColorRGB(const TCOD_ColorRGB& rhs) noexcept : TCOD_ColorRGB{rhs} {}
/***************************************************************************
@brief Construct a ColorRGB object from an RGBA color, truncating the alpha.
*/
explicit constexpr ColorRGB(const TCOD_ColorRGBA& rhs) noexcept : ColorRGB{rhs.r, rhs.g, rhs.b} {}
/***************************************************************************
@brief Allow implicit casts to RGBA colors, where alpha=255 is implied.
*/
[[nodiscard]] constexpr operator const TCOD_ColorRGBA() const noexcept { return TCOD_ColorRGBA{r, g, b, 255}; }
/***************************************************************************
@brief Allow explicit casts to a TCOD_ColorRGB pointer.
*/
[[nodiscard]] constexpr explicit operator TCOD_ColorRGB*() noexcept { return this; }
/***************************************************************************
@brief Allow explicit casts to a const TCOD_ColorRGB pointer.
*/
[[nodiscard]] constexpr explicit operator const TCOD_ColorRGB*() const noexcept { return this; }
};
/***************************************************************************
@brief A C++ RGBA color, used to handle conversions between color types.
\rst
.. versionadded:: 1.19
\endrst
*/
struct ColorRGBA : public TCOD_ColorRGBA {
public:
/***************************************************************************
@brief Default construct a black ColorRGBA object. RGB values are zero, alpha is 255.
*/
constexpr ColorRGBA() noexcept : ColorRGBA{0, 0, 0, 255} {}
/***************************************************************************
@brief Construct a ColorRGBA object with the provided color and alpha.
*/
constexpr ColorRGBA(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = 255) noexcept
: TCOD_ColorRGBA{red, green, blue, alpha} {}
/***************************************************************************
@brief Construct a ColorRGBA object by adding an alpha channel to an RGB object.
*/
explicit constexpr ColorRGBA(const TCOD_ColorRGB& rhs, uint8_t alpha = 255) noexcept
: TCOD_ColorRGBA{rhs.r, rhs.b, rhs.b, alpha} {}
/***************************************************************************
@brief Construct a ColorRGBA object from an TCOD_ColorRGBA struct.
*/
explicit constexpr ColorRGBA(const TCOD_ColorRGBA& rhs) noexcept : TCOD_ColorRGBA{rhs} {}
/***************************************************************************
@brief Allow explicit conversions to a TCOD_ColorRGB struct.
*/
[[nodiscard]] constexpr explicit operator TCOD_ColorRGB() const noexcept { return TCOD_ColorRGB{r, g, b}; };
/***************************************************************************
@brief Allow explicit conversions to a TCOD_ColorRGBA pointer.
*/
[[nodiscard]] constexpr explicit operator TCOD_ColorRGBA*() noexcept { return this; }
/***************************************************************************
@brief Allow explicit conversions to a const TCOD_ColorRGBA pointer.
*/
[[nodiscard]] constexpr explicit operator const TCOD_ColorRGBA*() const noexcept { return this; }
};
} // namespace tcod
// clang-format off
// color constants uses to generate @ColorTable
/**
@ColorCategory STANDARD COLORS
@Color red 255,0,0
@Color flame 255,63,0
@Color orange 255,127,0
@Color amber 255,191,0
@Color yellow 255,255,0,
@Color lime 191,255,0
@Color chartreuse 127,255,0
@Color green 0,255,0
@Color sea 0,255,127
@Color turquoise 0,255,191
@Color cyan 0,255,255
@Color sky 0,191,255
@Color azure 0,127,255
@Color blue 0,0,255
@Color han 63,0,255
@Color violet 127,0,255
@Color purple 191,0,255
@Color fuchsia 255,0,255
@Color magenta 255,0,191
@Color pink 255,0,127
@Color crimson 255,0,63
@ColorCategory METALLIC COLORS
@Color brass 191,151,96
@Color copper 196,136,124
@Color gold 229,191,0
@Color silver 203,203,203
@ColorCategory MISCELLANEOUS COLORS
@Color celadon 172,255,175
@Color peach 255,159,127
@ColorCategory GREYSCALE & SEPIA
@Color grey 127,127,127
@Color sepia 127,101,63
@ColorCategory BLACK AND WHITE
@Color black 0,0,0
@Color white 255,255,255
*/
/**
@PageName color
@PageCategory Core
@PageTitle Colors
@PageDesc The Doryen library uses 32bits colors. Thus, your OS desktop must use 32bits colors.
A color is defined by its red, green and blue component between 0 and 255.
You can use the following predefined colors (hover over a color to see its full name and R,G,B values):
@ColorTable
@CppEx
TCODColor::desaturatedRed
TCODColor::lightestRed
TCODColor::lighterRed
TCODColor::lightRed
TCODColor::red
TCODColor::darkRed
TCODColor::darkerRed
TCODColor::darkestRed
@CEx
TCOD_desaturated_red
TCOD_lightest_red
TCOD_lighter_red
TCOD_light_red
TCOD_red
TCOD_dark_red
TCOD_darker_red
TCOD_darkest_red
@PyEx
libtcod.desaturated_red
libtcod.lightest_red
libtcod.lighter_red
libtcod.light_red
libtcod.red
libtcod.dark_red
libtcod.darker_red
libtcod.darkest_red
@C#Ex
TCODColor::desaturatedRed
TCODColor::lightestRed
TCODColor::lighterRed
TCODColor::lightRed
TCODColor::red
TCODColor::darkRed
TCODColor::darkerRed
TCODColor::darkestRed
@LuaEx
tcod.color.desaturatedRed
tcod.color.lightestRed
tcod.color.lighterRed
tcod.color.lightRed
tcod.color.red
tcod.color.darkRed
tcod.color.darkerRed
tcod.color.darkestRed
*/
class TCODLIB_API TCODColor {
public :
uint8_t r,g,b;
constexpr TCODColor() : r{0}, g{0}, b{0} {}
/**
@PageName color
@FuncTitle Create your own colors
@FuncDesc You can create your own colours using a set of constructors, both for RGB and HSV values.
@CppEx
TCODColor myColor(24,64,255); //RGB
TCODColor myOtherColor(321.0f,0.7f,1.0f); //HSV
@CEx
TCOD_color_t my_color={24,64,255}; <span>/</span>* RGB *<span>/</span>
TCOD_color_t my_other_color = TCOD_color_RGB(24,64,255); <span>/</span>* RGB too *<span>/</span>
TCOD_color_t my_yet_another_color = TCOD_color_HSV(321.0f,0.7f,1.0f); <span>/</span>* HSV *<span>/</span>
@PyEx my_color=libtcod.Color(24,64,255)
@C#Ex TCODColor myColor = new TCODColor(24,64,255); //RGB
TCODColor myColor = new TCODColor(321.0f,0.7f,1.0f); //HSV
@LuaEx myColor = tcod.Color(24,24,255)
*/
constexpr TCODColor(uint8_t r_, uint8_t g_, uint8_t b_)
: r{r_}, g{g_}, b{b_}
{}
constexpr TCODColor(int r_, int g_, int b_)
: r{static_cast<uint8_t>(r_)}, g{static_cast<uint8_t>(g_)}, b{static_cast<uint8_t>(b_)}
{}
constexpr TCODColor(const TCOD_color_t &col): r{col.r}, g{col.g}, b{col.b} {} // Notice: not explicit!
TCODColor(float h, float s, float v);
/**
@PageName color
@FuncTitle Compare two colors
@CppEx
if (myColor == TCODColor::yellow) { ... }
if (myColor != TCODColor::white) { ... }
@CEx
if (TCOD_color_equals(my_color,TCOD_yellow)) { ... }
if (!TCOD_color_equals(my_color,TCOD_white)) { ... }
@PyEx
if my_color == libtcod.yellow : ...
if my_color != libtcod.white : ...
@C#Ex
if (myColor.Equal(TCODColor.yellow)) { ... }
if (myColor.NotEqual(TCODColor.white)) { ... }
@LuaEx
if myColor == tcod.color.yellow then ... end
*/
bool operator == (const TCODColor& c) const
{
return (c.r == r && c.g == g && c.b == b);
}
bool operator != (const TCODColor& c) const
{
return !(*this == c);
}
/**
@PageName color
@FuncTitle Multiply two colors
@FuncDesc c1 = c2 * c3 =>
c1.r = c2.r * c3.r / 255
c1.g = c2.g * c3.g / 255
c1.b = c2.b * c3.b / 255
darkishRed = darkGrey * red
<table><tr><td style="background-color: rgb(96, 0, 0); width: 60px; height: 30px;"></td><td style="background-color: rgb(96, 96, 96); width: 60px;"></td><td style="background-color: rgb(255, 0, 0); width: 60px;"></td></tr></table>
@CppEx TCODColor myDarkishRed = TCODColor::darkGrey * TCODColor::lightRed;
@CEx TCOD_color_t my_darkish_red = TCOD_color_multiply(TCOD_dark_grey, TCOD_light_red);
@PyEx my_darkish_red = libtcod.dark_grey * libtcod.light_red
@C#Ex TCODColor myDarkishRed = TCODColor.darkGrey.Multiply(TCODColor.lightRed);
@LuaEx myDarkishRed = tcod.color.darkGrey * tcod.color.lightRed
*/
TCODColor operator*(const TCODColor& rhs) const
{
return TCODColor(*this, rhs, [](int c1, int c2){ return c1 * c2 / 255; });
}
/**
@PageName color
@FuncTitle Multiply a color by a float
@FuncDesc c1 = c2 * v =>
c1.r = CLAMP(0, 255, c2.r * v)
c1.g = CLAMP(0, 255, c2.g * v)
c1.b = CLAMP(0, 255, c2.b * v)
darkishRed = red * 0.5
<table><tr><td style="background-color: rgb(128, 0, 0); width: 60px; height: 30px;"></td><td style="background-color: rgb(255, 0, 0); width: 60px;"></td><td style="width: 60px;"></td></tr></table>
</tbody>
@CppEx TCODColor myDarkishRed = TCODColor::lightRed * 0.5f;
@CEx TCOD_color_t my_darkish_red = TCOD_color_multiply_scalar(TCOD_light_red, 0.5f);
@PyEx myDarkishRed = libtcod.light_red * 0.5
@C#Ex TCODColor myDarkishRed = TCODColor.lightRed.Multiply(0.5f);
@LuaEx myDarkishRed = tcod.color.lightRed * 0.5
*/
TCODColor operator*(float value) const
{
return TCODColor(*this, [=](int c){ return static_cast<int>(c * value); });
}
/**
@PageName color
@FuncTitle Adding two colors
@FuncDesc c1 = c1 + c2 => c1.r = MIN(255, c1.r + c2.r)
c1.g = MIN(255, c1.g + c2.g)
c1.b = MIN(255, c1.b + c2.b)
lightishRed = red + darkGrey
<table><tr><td style="background-color: rgb(255, 128, 128); width: 60px; height: 30px;"></td><td style="background-color: rgb(255, 0, 0); width: 60px;"></td><td style="background-color: rgb(128, 128, 128); width: 60px;"></td></tr></table>
@CppEx TCODColor myLightishRed = TCODColor::red + TCODColor::darkGrey
@CEx TCOD_color_t my_lightish_red = TCOD_color_add(TCOD_red, TCOD_dark_grey);
@PyEx myLightishRed = libtcod.red + libtcod.dark_grey
@C#Ex TCODColor myLightishRed = TCODColor.red.Plus(TCODColor.darkGrey)
@LuaEx myLightishRed = tcod.color.red + tcod.color.darkGrey
*/
TCODColor operator+(const TCODColor & rhs) const
{
return TCODColor(*this, rhs, [](int c1, int c2){ return c1 + c2; });
}
/**
@PageName color
@FuncTitle Subtract two colors
@FuncDesc c1 = c1 - c2 => c1.r = MAX(0, c1.r - c2.r)
c1.g = MAX(0, c1.g - c2.g)
c1.b = MAX(0, c1.b - c2.b)
redish = red - darkGrey
<table><tr><td style="background-color: rgb(127, 0, 0); width: 60px; height: 30px;"></td><td style="background-color: rgb(255, 0, 0); width: 60px;"></td><td style="background-color: rgb(128, 128, 128); width: 60px;"></td></tr></table>
@CppEx TCODColor myRedish = TCODColor::red - TCODColor::darkGrey
@CEx TCOD_color_t my_redish = TCOD_color_subtract(TCOD_red, TCOD_dark_grey);
@PyEx myRedish = libtcod.red - libtcod.dark_grey
@C#Ex TCODColor myRedish = TCODColor.red.Minus(TCODColor.darkGrey)
@LuaEx myRedish = tcod.color.red - tcod.color.darkGrey
*/
TCODColor operator-(const TCODColor& rhs) const
{
return TCODColor(*this, rhs, [](int c1, int c2){ return c1 - c2; });
}
/**
@PageName color
@FuncTitle Interpolate between two colors
@FuncDesc c1 = lerp (c2, c3, coef) => c1.r = c2.r + (c3.r - c2.r ) * coef
c1.g = c2.g + (c3.g - c2.g ) * coef
c1.b = c2.b + (c3.b - c2.b ) * coef
coef should be between 0.0 and 1.0 but you can as well use other values
<table><tr><td style="background-color: rgb(96, 96, 96); color: rgb(255, 255, 255);" align="center">coef == 0.0f</td><td style="background-color: rgb(96, 96, 96); width: 60px;"></td><td style="background-color: rgb(255, 0, 0); width: 60px;"></td></tr>
<tr><td style="background-color: rgb(135, 72, 72); color: rgb(255, 255, 255);" align="center">coef == 0.25f</td><td style="background-color: rgb(96, 96, 96); width: 60px;"></td><td style="background-color: rgb(255, 0, 0); width: 60px;"></td></tr>
<tr><td style="background-color: rgb(175, 48, 48); color: rgb(255, 255, 255);" align="center">coef == 0.5f</td><td style="background-color: rgb(96, 96, 96); width: 60px;"></td><td style="background-color: rgb(255, 0, 0); width: 60px;"></td></tr>
<tr><td style="background-color: rgb(215, 24, 24); color: rgb(255, 255, 255);" align="center">coef == 0.75f</td><td style="background-color: rgb(96, 96, 96); width: 60px;"></td><td style="background-color: rgb(255, 0, 0); width: 60px;"></td></tr>
<tr><td style="background-color: rgb(255, 0, 0); color: rgb(255, 255, 255);" align="center">coef == 1.0f</td><td style="background-color: rgb(96, 96, 96); width: 60px;"></td><td style="background-color: rgb(255, 0, 0); width: 60px;"></td></tr></table>
@CppEx TCODColor myColor = TCODColor::lerp ( TCODColor::darkGrey, TCODColor::lightRed,coef );
@CEx TCOD_color_t my_color = TCOD_color_lerp ( TCOD_dark_grey, TCOD_light_red,coef);
@PyEx my_color = libtcod.color_lerp ( libtcod.dark_grey, libtcod.light_red,coef)
@C#Ex TCODColor myColor = TCODColor.Interpolate( TCODColor.darkGrey, TCODColor.lightRed, coef );
@LuaEx myColor = tcod.color.Interpolate( tcod.color.darkGrey, tcod.color.lightRed, coef )
*/
static TCODColor lerp(const TCODColor &c1, const TCODColor &c2, float coef)
{
return TCODColor(c1, c2, [=](int c, int d){ return c + (d - c) * coef; });
}
/**
@PageName color
@FuncTitle Define a color by its hue, saturation and value
@FuncDesc After this function is called, the r,g,b fields of the color are calculated according to the h,s,v parameters.
@Cpp void TCODColor::setHSV(float h, float s, float v)
@C void TCOD_color_set_HSV(TCOD_color_t *c,float h, float s, float v)
@Py color_set_hsv(c,h,s,v)
@C# void TCODColor::setHSV(float h, float s, float v)
@Lua Color:setHSV( h, s ,v )
@Param c In the C and Python versions, the color to modify
@Param h,s,v Color components in the HSV space
0.0 <= h < 360.0
0.0 <= s <= 1.0
0.0 <= v <= 1.0
*/
void setHSV(float h, float s, float v);
/**
@PageName color
@FuncTitle Define a color's hue, saturation or lightness
@FuncDesc These functions set only a single component in the HSV color space.
@Cpp
void TCODColor::setHue (float h)
void TCODColor::setSaturation (float s)
void TCODColor::setValue (float v)
@C
void TCOD_color_set_hue (TCOD_color_t *c, float h)
void TCOD_color_set_saturation (TCOD_color_t *c, float s)
void TCOD_color_set_value (TCOD_color_t *c, float v)
@Lua
Color:setHue(h)
Color:setSaturation(s)
Color:setValue(v)
@Param h,s,v Color components in the HSV space
@Param c In the C and Python versions, the color to modify
*/
void setHue (float h);
void setSaturation (float s);
void setValue (float v);
/**
@PageName color
@FuncTitle Get a color hue, saturation and value components
@Cpp void TCODColor::getHSV(float *h, float *s, float *v) const
@C void TCOD_color_get_HSV(TCOD_color_t c,float * h, float * s, float * v)
@Py color_get_HSV(c) # returns [h,s,v]
@C# void TCODColor::getHSV(out float h, out float s, out float v)
@Lua Color:getHSV() -- returns h,s,v
@Param c In the C and Python versions, the TCOD_color_t from which to read.
@Param h,s,v Color components in the HSV space
0.0 <= h < 360.0
0.0 <= s <= 1.0
0.0 <= v <= 1.0
*/
void getHSV(float *h, float *s, float *v) const;
/**
@PageName color
@FuncTitle Get a color's hue, saturation or value
@FuncDesc Should you need to extract only one of the HSV components, these functions are what you should call. Note that if you need all three values, it's way less burdensome for the CPU to call TCODColor::getHSV().
@Cpp
float TCODColor::getHue ()
float TCODColor::getSaturation ()
float TCODColor::getValue ()
@C
float TCOD_color_get_hue (TCOD_color_t c)
float TCOD_color_get_saturation (TCOD_color_t c)
float TCOD_color_get_value (TCOD_color_t c)
@Lua
Color:getHue()
Color:getSaturation()
Color:getValue()
@C#
float TCODColor::getHue()
float TCODColor::getSaturation()
float TCODColor::getValue()
@Param c the TCOD_color_t from which to read
*/
float getHue ();
float getSaturation ();
float getValue ();
/**
@PageName color
@FuncTitle Shift a color's hue up or down
@FuncDesc The hue shift value is the number of grades the color's hue will be shifted. The value can be negative for shift left, or positive for shift right.
Resulting values H < 0 and H >= 360 are handled automatically.
@Cpp void TCODColor::shiftHue (float hshift)
@C void TCOD_color_shift_hue (TCOD_color_t *c, float hshift)
@C# TCODColor::shiftHue(float hshift)
@Lua Color:shiftHue(hshift)
@Param c The color to modify
@Param hshift The hue shift value
*/
void shiftHue (float hshift);
/**
@PageName color
@FuncTitle Scale a color's saturation and value
@Cpp void TCODColor::scaleHSV (float sscale, float vscale)
@C void TCOD_color_scale_HSV (TCOD_color_t *c, float scoef, float vcoef)
@Py color_scale_HSV(c, scoef, vcoef)
@C# TCODColor::scaleHSV (float sscale, float vscale)
@Lua Color:scaleHSV(sscale,vscale)
@Param c The color to modify
@Param sscale saturation multiplier (1.0f for no change)
@Param vscale value multiplier (1.0f for no change)
*/
void scaleHSV (float sscale, float vscale);
/**
@PageName color
@FuncTitle Generate a smooth color map
@FuncDesc You can define a color map from an array of color keys. Colors will be interpolated between the keys.
0 -> black
4 -> red
8 -> white
Result :
<table>
<tbody><tr><td class="code"><pre>map[0]</pre></td><td style="background-color: rgb(0, 0, 0); color: rgb(255, 255, 255); width: 50px;" align="center">&nbsp;</td><td>black</td></tr>
<tr><td class="code"><pre>map[1]</pre></td><td style="background-color: rgb(63, 0, 0); color: rgb(255, 255, 255); width: 50px;" align="center">&nbsp;</td></tr>
<tr><td class="code"><pre>map[2]</pre></td><td style="background-color: rgb(127, 0, 0); color: rgb(255, 255, 255); width: 50px;" align="center">&nbsp;</td></tr>
<tr><td class="code"><pre>map[3]</pre></td><td style="background-color: rgb(191, 0, 0); color: rgb(255, 255, 255); width: 50px;" align="center">&nbsp;</td></tr>
<tr><td class="code"><pre>map[4]</pre></td><td style="background-color: rgb(255, 0, 0); color: rgb(255, 255, 255); width: 50px;" align="center">&nbsp;</td><td>red</td></tr>
<tr><td class="code"><pre>map[5]</pre></td><td style="background-color: rgb(255, 63, 63); color: rgb(255, 255, 255); width: 50px;" align="center">&nbsp;</td></tr>
<tr><td class="code"><pre>map[6]</pre></td><td style="background-color: rgb(255, 127, 127); color: rgb(255, 255, 255); width: 50px;" align="center">&nbsp;</td></tr>
<tr><td class="code"><pre>map[7]</pre></td><td style="background-color: rgb(255, 191, 191); color: rgb(255, 255, 255); width: 50px;" align="center">&nbsp;</td></tr>
<tr><td class="code"><pre>map[8]</pre></td><td style="background-color: rgb(255, 255, 255); color: rgb(255, 255, 255); width: 50px;" align="center">&nbsp;</td><td>white</td></tr>
</tbody></table>
@Cpp static void genMap(TCODColor *map, int nbKey, TCODColor const *keyColor, int const *keyIndex)
@C void TCOD_gen_map(TCOD_color_t *map, int nb_key, TCOD_color_t const *key_color, int const *key_index)
@Py color_gen_map(keyColor,keyIndex) # returns an array of colors
@Param map An array of colors to be filled by the function.
@Param nbKey Number of color keys
@Param keyColor Array of nbKey colors containing the color of each key
@Param keyIndex Array of nbKey integers containing the index of each key.
If you want to fill the map array, keyIndex[0] must be 0 and keyIndex[nbKey-1] is the number of elements in map minus 1 but you can also use the function to fill only a part of the map array.
@CppEx
int idx[] = { 0, 4, 8 }; // indexes of the keys
TCODColor col[] = { TCODColor( 0,0,0 ), TCODColor(255,0,0), TCODColor(255,255,255) }; // colors : black, red, white
TCODColor map[9];
TCODColor::genMap(map,3,col,idx);
@CEx
int idx[] = { 0, 4, 8 }; // indexes of the keys
TCOD_color_t col[] = { { 0,0,0 }, {255,0,0}, {255,255,255} }; // colors : black, red, white
TCOD_color_t map[9];
TCOD_color_gen_map(map,3,col,idx);
@PyEx
idx = [ 0, 4, 8 ] # indexes of the keys
col = [ libtcod.Color( 0,0,0 ), libtcod.Color( 255,0,0 ), libtcod.Color(255,255,255) ] # colors : black, red, white
map=libtcod.color_gen_map(col,idx)
*/
static void genMap(TCODColor *map, int nbKey, TCODColor const *keyColor, int const *keyIndex);
// clang-format on
/***************************************************************************
@brief Allow explicit conversions to TCOD_ColorRGB.
\rst
.. versionadded:: 1.19
\endrst
*/
[[nodiscard]] constexpr explicit operator TCOD_ColorRGB() const noexcept { return {r, g, b}; }
/***************************************************************************
@brief Allow explicit conversions to TCOD_ColorRGBA.
\rst
.. versionadded:: 1.19
\endrst
*/
[[nodiscard]] constexpr explicit operator TCOD_ColorRGBA() const noexcept { return {r, g, b, 255}; }
/***************************************************************************
@brief Allow explicit conversions to tcod::ColorRGB.
\rst
.. versionadded:: 1.19
\endrst
*/
[[nodiscard]] constexpr explicit operator tcod::ColorRGB() const noexcept { return {r, g, b}; };
/***************************************************************************
@brief Allow explicit conversions to tcod::ColorRGBA.
\rst
.. versionadded:: 1.19
\endrst
*/
[[nodiscard]] constexpr explicit operator tcod::ColorRGBA() const noexcept { return {r, g, b, 255}; };
/// @cond INTERNAL
// color array
static const TCODColor colors [[deprecated]][TCOD_COLOR_NB][TCOD_COLOR_LEVELS];
// grey levels
static const TCODColor black [[deprecated("Replace with tcod::ColorRGB{0, 0, 0}")]];
static const TCODColor darkestGrey [[deprecated("Replace with tcod::ColorRGB{31, 31, 31}")]];
static const TCODColor darkerGrey [[deprecated("Replace with tcod::ColorRGB{63, 63, 63}")]];
static const TCODColor darkGrey [[deprecated("Replace with tcod::ColorRGB{95, 95, 95}")]];
static const TCODColor grey [[deprecated("Replace with tcod::ColorRGB{127, 127, 127}")]];
static const TCODColor lightGrey [[deprecated("Replace with tcod::ColorRGB{159, 159, 159}")]];
static const TCODColor lighterGrey [[deprecated("Replace with tcod::ColorRGB{191, 191, 191}")]];
static const TCODColor lightestGrey [[deprecated("Replace with tcod::ColorRGB{223, 223, 223}")]];
static const TCODColor white [[deprecated("Replace with tcod::ColorRGB{255, 255, 255}")]];
// sepia
static const TCODColor darkestSepia [[deprecated("Replace with tcod::ColorRGB{31, 24, 15}")]];
static const TCODColor darkerSepia [[deprecated("Replace with tcod::ColorRGB{63, 50, 31}")]];
static const TCODColor darkSepia [[deprecated("Replace with tcod::ColorRGB{94, 75, 47}")]];
static const TCODColor sepia [[deprecated("Replace with tcod::ColorRGB{127, 101, 63}")]];
static const TCODColor lightSepia [[deprecated("Replace with tcod::ColorRGB{158, 134, 100}")]];
static const TCODColor lighterSepia [[deprecated("Replace with tcod::ColorRGB{191, 171, 143}")]];
static const TCODColor lightestSepia [[deprecated("Replace with tcod::ColorRGB{222, 211, 195}")]];
// standard colors
static const TCODColor red [[deprecated("Replace with tcod::ColorRGB{255, 0, 0}")]];
static const TCODColor flame [[deprecated("Replace with tcod::ColorRGB{255, 63, 0}")]];
static const TCODColor orange [[deprecated("Replace with tcod::ColorRGB{255, 127, 0}")]];
static const TCODColor amber [[deprecated("Replace with tcod::ColorRGB{255, 191, 0}")]];
static const TCODColor yellow [[deprecated("Replace with tcod::ColorRGB{255, 255, 0}")]];
static const TCODColor lime [[deprecated("Replace with tcod::ColorRGB{191, 255, 0}")]];
static const TCODColor chartreuse [[deprecated("Replace with tcod::ColorRGB{127, 255, 0}")]];
static const TCODColor green [[deprecated("Replace with tcod::ColorRGB{0, 255, 0}")]];
static const TCODColor sea [[deprecated("Replace with tcod::ColorRGB{0, 255, 127}")]];
static const TCODColor turquoise [[deprecated("Replace with tcod::ColorRGB{0, 255, 191}")]];
static const TCODColor cyan [[deprecated("Replace with tcod::ColorRGB{0, 255, 255}")]];
static const TCODColor sky [[deprecated("Replace with tcod::ColorRGB{0, 191, 255}")]];
static const TCODColor azure [[deprecated("Replace with tcod::ColorRGB{0, 127, 255}")]];
static const TCODColor blue [[deprecated("Replace with tcod::ColorRGB{0, 0, 255}")]];
static const TCODColor han [[deprecated("Replace with tcod::ColorRGB{63, 0, 255}")]];
static const TCODColor violet [[deprecated("Replace with tcod::ColorRGB{127, 0, 255}")]];
static const TCODColor purple [[deprecated("Replace with tcod::ColorRGB{191, 0, 255}")]];
static const TCODColor fuchsia [[deprecated("Replace with tcod::ColorRGB{255, 0, 255}")]];
static const TCODColor magenta [[deprecated("Replace with tcod::ColorRGB{255, 0, 191}")]];
static const TCODColor pink [[deprecated("Replace with tcod::ColorRGB{255, 0, 127}")]];
static const TCODColor crimson [[deprecated("Replace with tcod::ColorRGB{255, 0, 63}")]];
// dark colors
static const TCODColor darkRed [[deprecated("Replace with tcod::ColorRGB{191, 0, 0}")]];
static const TCODColor darkFlame [[deprecated("Replace with tcod::ColorRGB{191, 47, 0}")]];
static const TCODColor darkOrange [[deprecated("Replace with tcod::ColorRGB{191, 95, 0}")]];
static const TCODColor darkAmber [[deprecated("Replace with tcod::ColorRGB{191, 143, 0}")]];
static const TCODColor darkYellow [[deprecated("Replace with tcod::ColorRGB{191, 191, 0}")]];
static const TCODColor darkLime [[deprecated("Replace with tcod::ColorRGB{143, 191, 0}")]];
static const TCODColor darkChartreuse [[deprecated("Replace with tcod::ColorRGB{95, 191, 0}")]];
static const TCODColor darkGreen [[deprecated("Replace with tcod::ColorRGB{0, 191, 0}")]];
static const TCODColor darkSea [[deprecated("Replace with tcod::ColorRGB{0, 191, 95}")]];
static const TCODColor darkTurquoise [[deprecated("Replace with tcod::ColorRGB{0, 191, 143}")]];
static const TCODColor darkCyan [[deprecated("Replace with tcod::ColorRGB{0, 191, 191}")]];
static const TCODColor darkSky [[deprecated("Replace with tcod::ColorRGB{0, 143, 191}")]];
static const TCODColor darkAzure [[deprecated("Replace with tcod::ColorRGB{0, 95, 191}")]];
static const TCODColor darkBlue [[deprecated("Replace with tcod::ColorRGB{0, 0, 191}")]];
static const TCODColor darkHan [[deprecated("Replace with tcod::ColorRGB{47, 0, 191}")]];
static const TCODColor darkViolet [[deprecated("Replace with tcod::ColorRGB{95, 0, 191}")]];
static const TCODColor darkPurple [[deprecated("Replace with tcod::ColorRGB{143, 0, 191}")]];
static const TCODColor darkFuchsia [[deprecated("Replace with tcod::ColorRGB{191, 0, 191}")]];
static const TCODColor darkMagenta [[deprecated("Replace with tcod::ColorRGB{191, 0, 143}")]];
static const TCODColor darkPink [[deprecated("Replace with tcod::ColorRGB{191, 0, 95}")]];
static const TCODColor darkCrimson [[deprecated("Replace with tcod::ColorRGB{191, 0, 47}")]];
// darker colors
static const TCODColor darkerRed [[deprecated("Replace with tcod::ColorRGB{127, 0, 0}")]];
static const TCODColor darkerFlame [[deprecated("Replace with tcod::ColorRGB{127, 31, 0}")]];
static const TCODColor darkerOrange [[deprecated("Replace with tcod::ColorRGB{127, 63, 0}")]];
static const TCODColor darkerAmber [[deprecated("Replace with tcod::ColorRGB{127, 95, 0}")]];
static const TCODColor darkerYellow [[deprecated("Replace with tcod::ColorRGB{127, 127, 0}")]];
static const TCODColor darkerLime [[deprecated("Replace with tcod::ColorRGB{95, 127, 0}")]];
static const TCODColor darkerChartreuse [[deprecated("Replace with tcod::ColorRGB{63, 127, 0}")]];
static const TCODColor darkerGreen [[deprecated("Replace with tcod::ColorRGB{0, 127, 0}")]];
static const TCODColor darkerSea [[deprecated("Replace with tcod::ColorRGB{0, 127, 63}")]];
static const TCODColor darkerTurquoise [[deprecated("Replace with tcod::ColorRGB{0, 127, 95}")]];
static const TCODColor darkerCyan [[deprecated("Replace with tcod::ColorRGB{0, 127, 127}")]];
static const TCODColor darkerSky [[deprecated("Replace with tcod::ColorRGB{0, 95, 127}")]];
static const TCODColor darkerAzure [[deprecated("Replace with tcod::ColorRGB{0, 63, 127}")]];
static const TCODColor darkerBlue [[deprecated("Replace with tcod::ColorRGB{0, 0, 127}")]];
static const TCODColor darkerHan [[deprecated("Replace with tcod::ColorRGB{31, 0, 127}")]];
static const TCODColor darkerViolet [[deprecated("Replace with tcod::ColorRGB{63, 0, 127}")]];
static const TCODColor darkerPurple [[deprecated("Replace with tcod::ColorRGB{95, 0, 127}")]];
static const TCODColor darkerFuchsia [[deprecated("Replace with tcod::ColorRGB{127, 0, 127}")]];
static const TCODColor darkerMagenta [[deprecated("Replace with tcod::ColorRGB{127, 0, 95}")]];
static const TCODColor darkerPink [[deprecated("Replace with tcod::ColorRGB{127, 0, 63}")]];
static const TCODColor darkerCrimson [[deprecated("Replace with tcod::ColorRGB{127, 0, 31}")]];
// darkest colors
static const TCODColor darkestRed [[deprecated("Replace with tcod::ColorRGB{63, 0, 0}")]];
static const TCODColor darkestFlame [[deprecated("Replace with tcod::ColorRGB{63, 15, 0}")]];
static const TCODColor darkestOrange [[deprecated("Replace with tcod::ColorRGB{63, 31, 0}")]];
static const TCODColor darkestAmber [[deprecated("Replace with tcod::ColorRGB{63, 47, 0}")]];
static const TCODColor darkestYellow [[deprecated("Replace with tcod::ColorRGB{63, 63, 0}")]];
static const TCODColor darkestLime [[deprecated("Replace with tcod::ColorRGB{47, 63, 0}")]];
static const TCODColor darkestChartreuse [[deprecated("Replace with tcod::ColorRGB{31, 63, 0}")]];
static const TCODColor darkestGreen [[deprecated("Replace with tcod::ColorRGB{0, 63, 0}")]];
static const TCODColor darkestSea [[deprecated("Replace with tcod::ColorRGB{0, 63, 31}")]];
static const TCODColor darkestTurquoise [[deprecated("Replace with tcod::ColorRGB{0, 63, 47}")]];
static const TCODColor darkestCyan [[deprecated("Replace with tcod::ColorRGB{0, 63, 63}")]];
static const TCODColor darkestSky [[deprecated("Replace with tcod::ColorRGB{0, 47, 63}")]];
static const TCODColor darkestAzure [[deprecated("Replace with tcod::ColorRGB{0, 31, 63}")]];
static const TCODColor darkestBlue [[deprecated("Replace with tcod::ColorRGB{0, 0, 63}")]];
static const TCODColor darkestHan [[deprecated("Replace with tcod::ColorRGB{15, 0, 63}")]];
static const TCODColor darkestViolet [[deprecated("Replace with tcod::ColorRGB{31, 0, 63}")]];
static const TCODColor darkestPurple [[deprecated("Replace with tcod::ColorRGB{47, 0, 63}")]];
static const TCODColor darkestFuchsia [[deprecated("Replace with tcod::ColorRGB{63, 0, 63}")]];
static const TCODColor darkestMagenta [[deprecated("Replace with tcod::ColorRGB{63, 0, 47}")]];
static const TCODColor darkestPink [[deprecated("Replace with tcod::ColorRGB{63, 0, 31}")]];
static const TCODColor darkestCrimson [[deprecated("Replace with tcod::ColorRGB{63, 0, 15}")]];
// light colors
static const TCODColor lightRed [[deprecated("Replace with tcod::ColorRGB{255, 63, 63}")]];
static const TCODColor lightFlame [[deprecated("Replace with tcod::ColorRGB{255, 111, 63}")]];
static const TCODColor lightOrange [[deprecated("Replace with tcod::ColorRGB{255, 159, 63}")]];
static const TCODColor lightAmber [[deprecated("Replace with tcod::ColorRGB{255, 207, 63}")]];
static const TCODColor lightYellow [[deprecated("Replace with tcod::ColorRGB{255, 255, 63}")]];
static const TCODColor lightLime [[deprecated("Replace with tcod::ColorRGB{207, 255, 63}")]];
static const TCODColor lightChartreuse [[deprecated("Replace with tcod::ColorRGB{159, 255, 63}")]];
static const TCODColor lightGreen [[deprecated("Replace with tcod::ColorRGB{63, 255, 63}")]];
static const TCODColor lightSea [[deprecated("Replace with tcod::ColorRGB{63, 255, 159}")]];
static const TCODColor lightTurquoise [[deprecated("Replace with tcod::ColorRGB{63, 255, 207}")]];
static const TCODColor lightCyan [[deprecated("Replace with tcod::ColorRGB{63, 255, 255}")]];
static const TCODColor lightSky [[deprecated("Replace with tcod::ColorRGB{63, 207, 255}")]];
static const TCODColor lightAzure [[deprecated("Replace with tcod::ColorRGB{63, 159, 255}")]];
static const TCODColor lightBlue [[deprecated("Replace with tcod::ColorRGB{63, 63, 255}")]];
static const TCODColor lightHan [[deprecated("Replace with tcod::ColorRGB{111, 63, 255}")]];
static const TCODColor lightViolet [[deprecated("Replace with tcod::ColorRGB{159, 63, 255}")]];
static const TCODColor lightPurple [[deprecated("Replace with tcod::ColorRGB{207, 63, 255}")]];
static const TCODColor lightFuchsia [[deprecated("Replace with tcod::ColorRGB{255, 63, 255}")]];
static const TCODColor lightMagenta [[deprecated("Replace with tcod::ColorRGB{255, 63, 207}")]];
static const TCODColor lightPink [[deprecated("Replace with tcod::ColorRGB{255, 63, 159}")]];
static const TCODColor lightCrimson [[deprecated("Replace with tcod::ColorRGB{255, 63, 111}")]];
// lighter colors
static const TCODColor lighterRed [[deprecated("Replace with tcod::ColorRGB{255, 127, 127}")]];
static const TCODColor lighterFlame [[deprecated("Replace with tcod::ColorRGB{255, 159, 127}")]];
static const TCODColor lighterOrange [[deprecated("Replace with tcod::ColorRGB{255, 191, 127}")]];
static const TCODColor lighterAmber [[deprecated("Replace with tcod::ColorRGB{255, 223, 127}")]];
static const TCODColor lighterYellow [[deprecated("Replace with tcod::ColorRGB{255, 255, 127}")]];
static const TCODColor lighterLime [[deprecated("Replace with tcod::ColorRGB{223, 255, 127}")]];
static const TCODColor lighterChartreuse [[deprecated("Replace with tcod::ColorRGB{191, 255, 127}")]];
static const TCODColor lighterGreen [[deprecated("Replace with tcod::ColorRGB{127, 255, 127}")]];
static const TCODColor lighterSea [[deprecated("Replace with tcod::ColorRGB{127, 255, 191}")]];
static const TCODColor lighterTurquoise [[deprecated("Replace with tcod::ColorRGB{127, 255, 223}")]];
static const TCODColor lighterCyan [[deprecated("Replace with tcod::ColorRGB{127, 255, 255}")]];
static const TCODColor lighterSky [[deprecated("Replace with tcod::ColorRGB{127, 223, 255}")]];
static const TCODColor lighterAzure [[deprecated("Replace with tcod::ColorRGB{127, 191, 255}")]];
static const TCODColor lighterBlue [[deprecated("Replace with tcod::ColorRGB{127, 127, 255}")]];
static const TCODColor lighterHan [[deprecated("Replace with tcod::ColorRGB{159, 127, 255}")]];
static const TCODColor lighterViolet [[deprecated("Replace with tcod::ColorRGB{191, 127, 255}")]];
static const TCODColor lighterPurple [[deprecated("Replace with tcod::ColorRGB{223, 127, 255}")]];
static const TCODColor lighterFuchsia [[deprecated("Replace with tcod::ColorRGB{255, 127, 255}")]];
static const TCODColor lighterMagenta [[deprecated("Replace with tcod::ColorRGB{255, 127, 223}")]];
static const TCODColor lighterPink [[deprecated("Replace with tcod::ColorRGB{255, 127, 191}")]];
static const TCODColor lighterCrimson [[deprecated("Replace with tcod::ColorRGB{255, 127, 159}")]];
// lightest colors
static const TCODColor lightestRed [[deprecated("Replace with tcod::ColorRGB{255, 191, 191}")]];
static const TCODColor lightestFlame [[deprecated("Replace with tcod::ColorRGB{255, 207, 191}")]];
static const TCODColor lightestOrange [[deprecated("Replace with tcod::ColorRGB{255, 223, 191}")]];
static const TCODColor lightestAmber [[deprecated("Replace with tcod::ColorRGB{255, 239, 191}")]];
static const TCODColor lightestYellow [[deprecated("Replace with tcod::ColorRGB{255, 255, 191}")]];
static const TCODColor lightestLime [[deprecated("Replace with tcod::ColorRGB{239, 255, 191}")]];
static const TCODColor lightestChartreuse [[deprecated("Replace with tcod::ColorRGB{223, 255, 191}")]];
static const TCODColor lightestGreen [[deprecated("Replace with tcod::ColorRGB{191, 255, 191}")]];
static const TCODColor lightestSea [[deprecated("Replace with tcod::ColorRGB{191, 255, 223}")]];
static const TCODColor lightestTurquoise [[deprecated("Replace with tcod::ColorRGB{191, 255, 239}")]];
static const TCODColor lightestCyan [[deprecated("Replace with tcod::ColorRGB{191, 255, 255}")]];
static const TCODColor lightestSky [[deprecated("Replace with tcod::ColorRGB{191, 239, 255}")]];
static const TCODColor lightestAzure [[deprecated("Replace with tcod::ColorRGB{191, 223, 255}")]];
static const TCODColor lightestBlue [[deprecated("Replace with tcod::ColorRGB{191, 191, 255}")]];
static const TCODColor lightestHan [[deprecated("Replace with tcod::ColorRGB{207, 191, 255}")]];
static const TCODColor lightestViolet [[deprecated("Replace with tcod::ColorRGB{223, 191, 255}")]];
static const TCODColor lightestPurple [[deprecated("Replace with tcod::ColorRGB{239, 191, 255}")]];
static const TCODColor lightestFuchsia [[deprecated("Replace with tcod::ColorRGB{255, 191, 255}")]];
static const TCODColor lightestMagenta [[deprecated("Replace with tcod::ColorRGB{255, 191, 239}")]];
static const TCODColor lightestPink [[deprecated("Replace with tcod::ColorRGB{255, 191, 223}")]];
static const TCODColor lightestCrimson [[deprecated("Replace with tcod::ColorRGB{255, 191, 207}")]];
// desaturated colors
static const TCODColor desaturatedRed [[deprecated("Replace with tcod::ColorRGB{127, 63, 63}")]];
static const TCODColor desaturatedFlame [[deprecated("Replace with tcod::ColorRGB{127, 79, 63}")]];
static const TCODColor desaturatedOrange [[deprecated("Replace with tcod::ColorRGB{127, 95, 63}")]];
static const TCODColor desaturatedAmber [[deprecated("Replace with tcod::ColorRGB{127, 111, 63}")]];
static const TCODColor desaturatedYellow [[deprecated("Replace with tcod::ColorRGB{127, 127, 63}")]];
static const TCODColor desaturatedLime [[deprecated("Replace with tcod::ColorRGB{111, 127, 63}")]];
static const TCODColor desaturatedChartreuse [[deprecated("Replace with tcod::ColorRGB{95, 127, 63}")]];
static const TCODColor desaturatedGreen [[deprecated("Replace with tcod::ColorRGB{63, 127, 63}")]];
static const TCODColor desaturatedSea [[deprecated("Replace with tcod::ColorRGB{63, 127, 95}")]];
static const TCODColor desaturatedTurquoise [[deprecated("Replace with tcod::ColorRGB{63, 127, 111}")]];
static const TCODColor desaturatedCyan [[deprecated("Replace with tcod::ColorRGB{63, 127, 127}")]];
static const TCODColor desaturatedSky [[deprecated("Replace with tcod::ColorRGB{63, 111, 127}")]];
static const TCODColor desaturatedAzure [[deprecated("Replace with tcod::ColorRGB{63, 95, 127}")]];
static const TCODColor desaturatedBlue [[deprecated("Replace with tcod::ColorRGB{63, 63, 127}")]];
static const TCODColor desaturatedHan [[deprecated("Replace with tcod::ColorRGB{79, 63, 127}")]];
static const TCODColor desaturatedViolet [[deprecated("Replace with tcod::ColorRGB{95, 63, 127}")]];
static const TCODColor desaturatedPurple [[deprecated("Replace with tcod::ColorRGB{111, 63, 127}")]];
static const TCODColor desaturatedFuchsia [[deprecated("Replace with tcod::ColorRGB{127, 63, 127}")]];
static const TCODColor desaturatedMagenta [[deprecated("Replace with tcod::ColorRGB{127, 63, 111}")]];
static const TCODColor desaturatedPink [[deprecated("Replace with tcod::ColorRGB{127, 63, 95}")]];
static const TCODColor desaturatedCrimson [[deprecated("Replace with tcod::ColorRGB{127, 63, 79}")]];
// metallic
static const TCODColor brass [[deprecated("Replace with tcod::ColorRGB{191, 151, 96}")]];
static const TCODColor copper [[deprecated("Replace with tcod::ColorRGB{197, 136, 124}")]];
static const TCODColor gold [[deprecated("Replace with tcod::ColorRGB{229, 191, 0}")]];
static const TCODColor silver [[deprecated("Replace with tcod::ColorRGB{203, 203, 203}")]];
// miscellaneous
static const TCODColor celadon [[deprecated("Replace with tcod::ColorRGB{172, 255, 175}")]];
static const TCODColor peach [[deprecated("Replace with tcod::ColorRGB{255, 159, 127}")]];
/// @endcond
private:
/**
* Return a color transformed by a lambda.
*/
template <typename F>
TCODColor(const TCODColor& color, const F& lambda)
: r{clamp_(lambda(color.r))}, g{clamp_(lambda(color.g))}, b{clamp_(lambda(color.b))} {}
/**
* Return a color from two colors combined using a lambda.
*/
template <typename F>
TCODColor(const TCODColor& color1, const TCODColor& color2, const F& lambda)
: r{clamp_(lambda(color1.r, color2.r))},
g{clamp_(lambda(color1.g, color2.g))},
b{clamp_(lambda(color1.b, color2.b))} {}
/**
* Return a color value clamped between 0 to 255.
*/
template <typename T>
static constexpr uint8_t clamp_(const T& value) noexcept {
return static_cast<uint8_t>(std::max<T>(0, std::min<T>(value, 255)));
}
};
TCODLIB_API TCODColor operator*(float value, const TCODColor& c);
#endif // _TCOD_COLOR_HPP

View file

@ -0,0 +1,125 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_CONFIG_H_
#define LIBTCOD_CONFIG_H_
/* DLL export */
#ifndef TCODLIB_API
#ifdef LIBTCOD_STATIC
#define TCODLIB_API
#elif defined _WIN32 || defined __CYGWIN__ || defined __MINGW32__
#ifdef LIBTCOD_EXPORTS
#ifdef __GNUC__
#define TCODLIB_API __attribute__((dllexport))
#else
#define TCODLIB_API __declspec(dllexport)
#endif // __GNUC__
#else
#ifdef __GNUC__
#define TCODLIB_API __attribute__((dllimport))
#else
#define TCODLIB_API __declspec(dllimport)
#endif // __GNUC__
#endif // LIBTCOD_EXPORTS
#elif __GNUC__ >= 4
#define TCODLIB_API __attribute__((visibility("default")))
#else
#define TCODLIB_API
#endif
#endif // TCODLIB_API
#ifndef TCODLIB_CAPI
#ifdef __cplusplus
#define TCODLIB_CAPI extern "C" TCODLIB_API
#else
#define TCODLIB_CAPI TCODLIB_API
#endif // __cplusplus
#endif // TCODLIB_CAPI
// Publicly visible symbols and functions.
#define TCOD_PUBLIC TCODLIB_API
// Private hidden symbols.
#if __GNUC__ >= 4
#define TCOD_PRIVATE __attribute__((visibility("hidden")))
#else
#define TCOD_PRIVATE
#endif // __GNUC__ >= 4
// Cross platform deprecation.
#ifdef TCOD_IGNORE_DEPRECATED
#define TCOD_DEPRECATED(msg)
#define TCOD_DEPRECATED_NOMESSAGE
#define TCOD_DEPRECATED_ENUM
#elif defined(__cplusplus) && __cplusplus >= 201402L && !defined(__clang__)
#define TCOD_DEPRECATED(msg) [[deprecated(msg)]]
#define TCOD_DEPRECATED_NOMESSAGE [[deprecated]]
#define TCOD_DEPRECATED_ENUM [[deprecated]]
#elif defined(_MSC_VER)
#define TCOD_DEPRECATED(msg) __declspec(deprecated(msg))
#define TCOD_DEPRECATED_NOMESSAGE __declspec(deprecated)
#define TCOD_DEPRECATED_ENUM
#elif defined(__GNUC__)
#define TCOD_DEPRECATED(msg) __attribute__((deprecated(msg)))
#define TCOD_DEPRECATED_NOMESSAGE __attribute__((deprecated))
#define TCOD_DEPRECATED_ENUM __attribute__((deprecated))
#else
#define TCOD_DEPRECATED(msg)
#define TCOD_DEPRECATED_NOMESSAGE
#define TCOD_DEPRECATED_ENUM
#endif
#ifdef __GNUC__
// Tells GCC the these functions are printf-like.
#define TCODLIB_PRINTF(str_index, first_arg) __attribute__((format(printf, str_index, first_arg)))
#else
#define TCODLIB_PRINTF(str_index, first_arg)
#endif
#define TCODLIB_FORMAT TCODLIB_PRINTF
#if defined(__cplusplus) && __cplusplus >= 201703L && !defined(__clang__)
#define TCOD_NODISCARD [[nodiscard]]
#elif defined(_MSC_VER)
#define TCOD_NODISCARD
#elif defined(__GNUC__)
#define TCOD_NODISCARD __attribute__((warn_unused_result))
#else
#define TCOD_NODISCARD
#endif
#ifndef TCOD_FALLBACK_FONT_SIZE
// The default height of the fallback font size in pixels.
#define TCOD_FALLBACK_FONT_SIZE 16
#endif // TCOD_FALLBACK_FONT_SIZE
#endif // LIBTCOD_CONFIG_H_

View file

@ -0,0 +1,464 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_CONSOLE_H_
#define TCOD_CONSOLE_H_
#include <stdbool.h>
#ifdef __cplusplus
#include <algorithm>
#include <array>
#include <memory>
#include <optional>
#include <stdexcept>
#include <utility>
#include "error.hpp"
#endif // __cplusplus
#include "color.h"
#include "config.h"
#include "error.h"
#include "tileset.h"
/**
* \enum TCOD_bkgnd_flag_t
*
* Background color blend modes.
*/
typedef enum {
TCOD_BKGND_NONE,
TCOD_BKGND_SET,
TCOD_BKGND_MULTIPLY,
TCOD_BKGND_LIGHTEN,
TCOD_BKGND_DARKEN,
TCOD_BKGND_SCREEN,
TCOD_BKGND_COLOR_DODGE,
TCOD_BKGND_COLOR_BURN,
TCOD_BKGND_ADD,
TCOD_BKGND_ADDA,
TCOD_BKGND_BURN,
TCOD_BKGND_OVERLAY,
TCOD_BKGND_ALPH,
TCOD_BKGND_DEFAULT
} TCOD_bkgnd_flag_t;
/**
* \enum TCOD_alignment_t
*
* Print justification options.
*/
typedef enum { TCOD_LEFT, TCOD_RIGHT, TCOD_CENTER } TCOD_alignment_t;
/***************************************************************************
@brief The raw data for a single TCOD_Console tile.
\rst
.. versionadded:: 1.19
\endrst
*/
typedef struct TCOD_ConsoleTile {
#ifdef __cplusplus
bool operator==(const TCOD_ConsoleTile& rhs) const noexcept { return ch == rhs.ch && fg == rhs.fg && bg == rhs.bg; }
bool operator!=(const TCOD_ConsoleTile& rhs) const noexcept { return !(*this == rhs); }
#endif // __cplusplus
/***************************************************************************
@brief The Unicode codepoint for this tile.
*/
int ch;
/***************************************************************************
@brief The tile glyph color, rendered on top of the background.
*/
TCOD_ColorRGBA fg;
/***************************************************************************
@brief The tile background color, rendered behind the glyph.
*/
TCOD_ColorRGBA bg;
} TCOD_ConsoleTile;
/***************************************************************************
@brief A libtcod console containing a grid of tiles with `{ch, fg, bg}` information.
@details In C++ this struct has several convience methods to make working with consoles easier.
Note that all tile references are to TCOD_ConsoleTile structs and will include an alpha channel.
For C++ code examples see `tcod::Console`.
\rst
.. versionadded:: 1.19
\endrst
*/
struct TCOD_Console {
#ifdef __cplusplus
/***************************************************************************
@brief Return a pointer to the beginning of this consoles tile data.
*/
[[nodiscard]] auto begin() noexcept -> TCOD_ConsoleTile* { return tiles; }
/***************************************************************************
@brief Return a const pointer to the beginning of this consoles tile data.
*/
[[nodiscard]] auto begin() const noexcept -> const TCOD_ConsoleTile* { return tiles; }
/***************************************************************************
@brief Return a pointer to the end of this consoles tile data.
*/
[[nodiscard]] auto end() noexcept -> TCOD_ConsoleTile* { return tiles + elements; }
/***************************************************************************
@brief Return a const pointer to the end of this consoles tile data.
*/
[[nodiscard]] auto end() const noexcept -> const TCOD_ConsoleTile* { return tiles + elements; }
/***************************************************************************
@brief Clear a console by setting all tiles to the provided TCOD_ConsoleTile object.
@param tile A TCOD_ConsoleTile reference which will be used to clear the console.
*/
void clear(const TCOD_ConsoleTile& tile = {0x20, {255, 255, 255, 255}, {0, 0, 0, 255}}) noexcept {
for (auto& it : *this) it = tile;
}
/***************************************************************************
@brief Return a reference to the tile at `xy`.
*/
[[nodiscard]] auto operator[](const std::array<int, 2>& xy) noexcept -> TCOD_ConsoleTile& {
return tiles[get_index(xy)];
}
/***************************************************************************
@brief Return a constant reference to the tile at `xy`.
*/
[[nodiscard]] auto operator[](const std::array<int, 2>& xy) const noexcept -> const TCOD_ConsoleTile& {
return tiles[get_index(xy)];
}
/***************************************************************************
@brief Return a reference to the tile at `xy`.
@throws std::out_of_range if the index is out-of-bounds
*/
[[nodiscard]] auto at(const std::array<int, 2>& xy) -> TCOD_ConsoleTile& { return tiles[bounds_check(xy)]; }
/***************************************************************************
@brief Return a constant reference to the tile at `xy`.
@throws std::out_of_range if the index is out-of-bounds
*/
[[nodiscard]] auto at(const std::array<int, 2>& xy) const -> const TCOD_ConsoleTile& {
return tiles[bounds_check(xy)];
}
/***************************************************************************
@brief Return a reference to the tile at `x`,`y`.
@throws std::out_of_range if the index is out-of-bounds
*/
[[nodiscard]] auto at(int x, int y) -> TCOD_ConsoleTile& { return at({x, y}); }
/***************************************************************************
@brief Return a constant reference to the tile at `x`,`y`.
@throws std::out_of_range if the index is out-of-bounds
*/
[[nodiscard]] auto at(int x, int y) const -> const TCOD_ConsoleTile& { return at({x, y}); }
/***************************************************************************
@brief Convert `xy` into a 1-dimensional index. Out-of-bounds indexes are undefined.
@details This index is normally used to index the tiles attribute.
*/
[[nodiscard]] int get_index(const std::array<int, 2>& xy) const noexcept { return w * xy[1] + xy[0]; }
/***************************************************************************
@brief Return true if `xy` are within the bounds of this console.
*/
[[nodiscard]] bool in_bounds(const std::array<int, 2>& xy) const noexcept {
return 0 <= xy[0] && xy[0] < w && 0 <= xy[1] && xy[1] < h;
}
private:
/***************************************************************************
@brief Checks if `xy` is in bounds then return an in-bounds index.
@throws std::out_of_range if `xy` is out-of-bounds
*/
int bounds_check(const std::array<int, 2>& xy) const {
if (!in_bounds(xy)) {
throw std::out_of_range(
std::string("Out of bounds lookup {") + std::to_string(xy[0]) + ", " + std::to_string(xy[1]) +
"} on console of shape {" + std::to_string(w) + ", " + std::to_string(h) + "}.");
}
return get_index(xy);
}
public:
#endif // __cplusplus
/** Console width and height in tiles. */
int w, h;
/** A contiguous array of console tiles. */
TCOD_ConsoleTile* __restrict tiles;
/** Default background operator for print & print_rect functions. */
TCOD_bkgnd_flag_t bkgnd_flag;
/** Default alignment for print & print_rect functions. */
TCOD_alignment_t alignment;
/** Foreground (text) and background colors. */
TCOD_color_t fore, back;
/** True if a key color is being used. */
bool has_key_color;
/** The current key color for this console. */
TCOD_color_t key_color;
/**
@brief The total length of the tiles array. Same as `w * h`.
\rst
.. versionadded:: 1.16
\endrst
*/
int elements;
/**
@brief A userdata attribute which can be repurposed.
\rst
.. versionadded:: 1.16
\endrst
*/
void* userdata;
/** Internal use. */
void (*on_delete)(struct TCOD_Console* self);
};
typedef struct TCOD_Console TCOD_Console;
typedef struct TCOD_Console* TCOD_console_t;
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
* Return a new console with a specific number of columns and rows.
*
* \param w Number of columns.
* \param h Number of columns.
* \return A pointer to the new console, or NULL on error.
*/
TCOD_PUBLIC TCOD_NODISCARD TCOD_Console* TCOD_console_new(int w, int h);
/**
* Return the width of a console.
*/
TCOD_PUBLIC TCOD_NODISCARD int TCOD_console_get_width(const TCOD_Console* con);
/**
* Return the height of a console.
*/
TCOD_PUBLIC TCOD_NODISCARD int TCOD_console_get_height(const TCOD_Console* con);
TCOD_PUBLIC void TCOD_console_set_key_color(TCOD_Console* con, TCOD_color_t col);
/**
* Blit from one console to another.
*
* \param src Pointer to the source console.
* \param xSrc The left region of the source console to blit from.
* \param ySrc The top region of the source console to blit from.
* \param wSrc The width of the region to blit from.
* If 0 then it will fill to the maximum width.
* \param hSrc The height of the region to blit from.
* If 0 then it will fill to the maximum height.
* \param dst Pointer to the destination console.
* \param xDst The left corner to blit onto the destination console.
* \param yDst The top corner to blit onto the destination console.
* \param foreground_alpha Foreground blending alpha.
* \param background_alpha Background blending alpha.
*
* If the source console has a key color, this function will use it.
* \rst
* .. versionchanged:: 1.16
* Blits can now handle per-cell alpha transparency.
* \endrst
*/
TCOD_PUBLIC void TCOD_console_blit(
const TCOD_Console* __restrict src,
int xSrc,
int ySrc,
int wSrc,
int hSrc,
TCOD_Console* __restrict dst,
int xDst,
int yDst,
float foreground_alpha,
float background_alpha);
TCOD_PUBLIC void TCOD_console_blit_key_color(
const TCOD_Console* __restrict src,
int xSrc,
int ySrc,
int wSrc,
int hSrc,
TCOD_Console* __restrict dst,
int xDst,
int yDst,
float foreground_alpha,
float background_alpha,
const TCOD_color_t* key_color);
/**
* Delete a console.
*
* \param console A console pointer.
*
* If the console being deleted is the root console, then the display will be
* uninitialized.
*/
TCOD_PUBLIC void TCOD_console_delete(TCOD_Console* console);
TCOD_DEPRECATED("Console defaults have been deprecated.")
TCOD_PUBLIC void TCOD_console_set_default_background(TCOD_Console* con, TCOD_color_t col);
TCOD_DEPRECATED("Console defaults have been deprecated.")
TCOD_PUBLIC void TCOD_console_set_default_foreground(TCOD_Console* con, TCOD_color_t col);
/**
* Clear a console to its default colors and the space character code.
*/
TCOD_PUBLIC void TCOD_console_clear(TCOD_Console* con);
/**
* Blend a background color onto a console tile.
*
* \param con A console pointer.
* \param x The X coordinate, the left-most position being 0.
* \param y The Y coordinate, the top-most position being 0.
* \param col The background color to blend.
* \param flag The blend mode to use.
*/
TCOD_PUBLIC void TCOD_console_set_char_background(
TCOD_Console* con, int x, int y, TCOD_color_t col, TCOD_bkgnd_flag_t flag);
/**
* Change the foreground color of a console tile.
*
* \param con A console pointer.
* \param x The X coordinate, the left-most position being 0.
* \param y The Y coordinate, the top-most position being 0.
* \param col The foreground color to set.
*/
TCOD_PUBLIC void TCOD_console_set_char_foreground(TCOD_Console* con, int x, int y, TCOD_color_t col);
/**
* Change a character on a console tile, without changing its colors.
*
* \param con A console pointer.
* \param x The X coordinate, the left-most position being 0.
* \param y The Y coordinate, the top-most position being 0.
* \param c The character code to set.
*/
TCOD_PUBLIC void TCOD_console_set_char(TCOD_Console* con, int x, int y, int c);
/**
* Draw a character on a console using the default colors.
*
* \param con A console pointer.
* \param x The X coordinate, the left-most position being 0.
* \param y The Y coordinate, the top-most position being 0.
* \param c The character code to place.
* \param flag A TCOD_bkgnd_flag_t flag.
*/
TCOD_PUBLIC void TCOD_console_put_char(TCOD_Console* con, int x, int y, int c, TCOD_bkgnd_flag_t flag);
/**
* Draw a character on the console with the given colors.
*
* \param con A console pointer.
* \param x The X coordinate, the left-most position being 0.
* \param y The Y coordinate, the top-most position being 0.
* \param c The character code to place.
* \param fore The foreground color.
* \param back The background color. This color will not be blended.
*/
TCOD_PUBLIC void TCOD_console_put_char_ex(TCOD_Console* con, int x, int y, int c, TCOD_color_t fore, TCOD_color_t back);
/**
* Set a consoles default background flag.
*
* \param con A console pointer.
* \param flag One of `TCOD_bkgnd_flag_t`.
*/
TCOD_DEPRECATED("Console defaults have been deprecated.")
TCOD_PUBLIC void TCOD_console_set_background_flag(TCOD_Console* con, TCOD_bkgnd_flag_t flag);
/**
* Return a consoles default background flag.
*/
TCOD_DEPRECATED("Console defaults have been deprecated.")
TCOD_PUBLIC TCOD_NODISCARD TCOD_bkgnd_flag_t TCOD_console_get_background_flag(TCOD_Console* con);
/**
* Set a consoles default alignment.
*
* \param con A console pointer.
* \param alignment One of TCOD_alignment_t
*/
TCOD_DEPRECATED("Console defaults have been deprecated.")
TCOD_PUBLIC void TCOD_console_set_alignment(TCOD_Console* con, TCOD_alignment_t alignment);
/**
* Return a consoles default alignment.
*/
TCOD_DEPRECATED("Console defaults have been deprecated.")
TCOD_PUBLIC TCOD_NODISCARD TCOD_alignment_t TCOD_console_get_alignment(TCOD_Console* con);
TCOD_DEPRECATED("Console defaults have been deprecated.")
TCOD_PUBLIC TCOD_NODISCARD TCOD_color_t TCOD_console_get_default_background(TCOD_Console* con);
TCOD_DEPRECATED("Console defaults have been deprecated.")
TCOD_PUBLIC TCOD_NODISCARD TCOD_color_t TCOD_console_get_default_foreground(TCOD_Console* con);
/**
* Return the background color of a console at x,y
*
* \param con A console pointer.
* \param x The X coordinate, the left-most position being 0.
* \param y The Y coordinate, the top-most position being 0.
* \return A TCOD_color_t struct with a copy of the background color.
*/
TCOD_PUBLIC TCOD_NODISCARD TCOD_color_t TCOD_console_get_char_background(const TCOD_Console* con, int x, int y);
/**
* Return the foreground color of a console at x,y
*
* \param con A console pointer.
* \param x The X coordinate, the left-most position being 0.
* \param y The Y coordinate, the top-most position being 0.
* \return A TCOD_color_t struct with a copy of the foreground color.
*/
TCOD_PUBLIC TCOD_NODISCARD TCOD_color_t TCOD_console_get_char_foreground(const TCOD_Console* con, int x, int y);
/**
* Return a character code of a console at x,y
*
* \param con A console pointer.
* \param x The X coordinate, the left-most position being 0.
* \param y The Y coordinate, the top-most position being 0.
* \return The character code.
*/
TCOD_PUBLIC TCOD_NODISCARD int TCOD_console_get_char(const TCOD_Console* con, int x, int y);
/**
Fade the color of the display.
\param val Where at 255 colors are normal and at 0 colors are completely
faded.
\param fade_color Color to fade towards.
\rst
.. deprecated:: 1.19
This function will not work with libtcod contexts.
\endrst
*/
TCOD_DEPRECATED("This function does not support contexts.")
TCOD_PUBLIC
void TCOD_console_set_fade(uint8_t val, TCOD_color_t fade_color);
/**
* Return the fade value.
*
* \return At 255 colors are normal and at 0 colors are completely faded.
*/
TCOD_PUBLIC TCOD_NODISCARD uint8_t TCOD_console_get_fade(void);
/**
* Return the fade color.
*
* \return The current fading color.
*/
TCOD_PUBLIC TCOD_NODISCARD TCOD_color_t TCOD_console_get_fading_color(void);
void TCOD_console_resize_(TCOD_Console* console, int width, int height);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // TCOD_CONSOLE_H_

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,226 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_CONSOLE_DRAWING_H_
#define TCOD_CONSOLE_DRAWING_H_
#ifdef __cplusplus
#include <array>
#include <optional>
#endif // __cplusplus
#include "config.h"
#include "console_types.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
* Draw a rectangle onto a console.
*
* \param con A console pointer.
* \param x The starting region, the left-most position being 0.
* \param y The starting region, the top-most position being 0.
* \param rw The width of the rectangle.
* \param rh The height of the rectangle.
* \param clear If true the drawing region will be filled with spaces.
* \param flag The blending flag to use.
*/
TCOD_PUBLIC void TCOD_console_rect(TCOD_Console* con, int x, int y, int rw, int rh, bool clear, TCOD_bkgnd_flag_t flag);
/**
* Draw a horizontal line using the default colors.
*
* \param con A console pointer.
* \param x The starting X coordinate, the left-most position being 0.
* \param y The starting Y coordinate, the top-most position being 0.
* \param l The width of the line.
* \param flag The blending flag.
*
* This function makes assumptions about the fonts character encoding.
* It will fail if the font encoding is not `cp437`.
*/
TCOD_PUBLIC void TCOD_console_hline(TCOD_Console* con, int x, int y, int l, TCOD_bkgnd_flag_t flag);
/**
* Draw a vertical line using the default colors.
*
* \param con A console pointer.
* \param x The starting X coordinate, the left-most position being 0.
* \param y The starting Y coordinate, the top-most position being 0.
* \param l The height of the line.
* \param flag The blending flag.
*
* This function makes assumptions about the fonts character encoding.
* It will fail if the font encoding is not `cp437`.
*/
TCOD_PUBLIC void TCOD_console_vline(TCOD_Console* con, int x, int y, int l, TCOD_bkgnd_flag_t flag);
// Next functions are provisional unless given an added version.
/**
* Place a single tile on a `console` at `x`,`y`.
*
* If `ch` is 0 then the character code will not be updated.
*
* If `fg`,`bg` is NULL then their respective colors will not be updated.
*/
TCOD_PUBLIC void TCOD_console_put_rgb(
TCOD_Console* __restrict console,
int x,
int y,
int ch,
const TCOD_color_t* fg,
const TCOD_color_t* bg,
TCOD_bkgnd_flag_t flag);
/**
* Draw a rectangle on a `console` with a shape of `x`,`y`,`width`,`height`.
*
* If `ch` is 0 then the character code will not be updated.
*
* If `fg`,`bg` is NULL then their respective colors will not be updated.
*/
TCOD_PUBLIC TCOD_Error TCOD_console_draw_rect_rgb(
TCOD_Console* __restrict console,
int x,
int y,
int width,
int height,
int ch,
const TCOD_color_t* fg,
const TCOD_color_t* bg,
TCOD_bkgnd_flag_t flag);
/**
Draw a decorated frame onto `console` with the shape of `x`, `y`, `width`, `height`.
`decoration[9]` is an optional array of Unicode codepoints.
If left as NULL then a single-pipe decoration is used by default.
If `decoration[9]` is given the codepoints are used for the edges, corners, and fill of the frame in this order:
0 1 2
3 4 5
6 7 8
If `fg` or `bg` is NULL then their respective colors will not be updated.
If `clear` is true then the inner area of the frame is filled with the inner decoration, which is typically space.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_console_draw_frame_rgb(
struct TCOD_Console* __restrict con,
int x,
int y,
int width,
int height,
const int* __restrict decoration,
const TCOD_ColorRGB* __restrict fg,
const TCOD_ColorRGB* __restrict bg,
TCOD_bkgnd_flag_t flag,
bool clear);
#ifdef __cplusplus
} // extern "C"
namespace tcod {
/***************************************************************************
@brief Fill a region with the given graphic.
@param console A reference to a TCOD_Console.
@param rect An `{x, y, width, height}` rectangle, starting from the upper-left-most tile as zero.
@param ch The character to draw. If zero then the characters in the drawing region will not be changed.
@param fg The foreground color. The printed text is set to this color.
If std::nullopt then the foreground will be left unchanged, inheriting the previous value of the tile.
@param bg The background color. The background tile under the printed text is set to this color.
If std::nullopt then the background will be left unchanged.
@param flag The background blending flag.
@code{.cpp}
auto console = tcod::Console{80, 50};
// Draw a red background without replacing any foreground glyphs/colors.
tcod::draw_rect(console, {2, 2, 24, 24}, 0, std::nullopt, tcod::ColorRGB{255, 0, 0});
// Draw a horizontal bar.
tcod::draw_rect(console, {8, 8, 16, 1}, '-', {{255, 255, 255}}, std::nullopt);
@endcode
\rst
.. versionadded:: 1.19
\endrst
*/
inline void draw_rect(
TCOD_Console& console,
const std::array<int, 4>& rect,
int ch,
std::optional<TCOD_ColorRGB> fg,
std::optional<TCOD_ColorRGB> bg,
TCOD_bkgnd_flag_t flag = TCOD_BKGND_SET) {
const TCOD_ColorRGB* fg_ptr = fg ? &fg.value() : nullptr;
const TCOD_ColorRGB* bg_ptr = bg ? &bg.value() : nullptr;
tcod::check_throw_error(
TCOD_console_draw_rect_rgb(&console, rect.at(0), rect.at(1), rect.at(2), rect.at(3), ch, fg_ptr, bg_ptr, flag));
}
/***************************************************************************
@brief Draw a decorative frame.
@param console A reference to a TCOD_Console.
@param rect An `{x, y, width, height}` rectangle, starting from the upper-left-most tile as zero.
@param decoration The codepoints to use for the frame in row-major order.
@param fg The foreground color. The printed text is set to this color.
If std::nullopt then the foreground will be left unchanged, inheriting the previous value of the tile.
@param bg The background color. The background tile under the printed text is set to this color.
If std::nullopt then the background will be left unchanged.
@param flag The background blending flag.
@param clear If true then the center area will be cleared with the center decoration.
`decoration` is given the codepoints to be used for the edges, corners, and fill of the frame in this order:
0 1 2
3 4 5
6 7 8
@code{.cpp}
auto console = tcod::Console{80, 50};
static constexpr std::array<int, 9> LEGEND = {'0', '1', '2', '3', '4', '5', '6', '7', '8'};
tcod::draw_frame(console, {0, 0, 3, 3}, LEGEND, {{255, 255, 255}}, {{0, 0, 0}});
@endcode
\rst
.. versionadded:: 1.19
\endrst
*/
inline void draw_frame(
TCOD_Console& console,
const std::array<int, 4>& rect,
const std::array<int, 9>& decoration,
std::optional<TCOD_ColorRGB> fg,
std::optional<TCOD_ColorRGB> bg,
TCOD_bkgnd_flag_t flag = TCOD_BKGND_SET,
bool clear = true) {
const TCOD_ColorRGB* fg_ptr = fg ? &fg.value() : nullptr;
const TCOD_ColorRGB* bg_ptr = bg ? &bg.value() : nullptr;
tcod::check_throw_error(TCOD_console_draw_frame_rgb(
&console, rect.at(0), rect.at(1), rect.at(2), rect.at(3), decoration.data(), fg_ptr, bg_ptr, flag, clear));
}
} // namespace tcod
#endif // __cplusplus
#endif // TCOD_CONSOLE_DRAWING_H_

View file

@ -0,0 +1,161 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_CONSOLE_ETC_H_
#define TCOD_CONSOLE_ETC_H_
#include <stdbool.h>
#ifndef NO_UNICODE
#include <wchar.h>
#endif
#include "color.h"
#include "config.h"
#include "console.h"
#include "console_types.h"
#include "context.h"
#include "error.h"
#include "image.h"
#include "list.h"
#ifdef __cplusplus
extern "C" {
#endif
#define TCOD_BKGND_ALPHA(alpha) ((TCOD_bkgnd_flag_t)(TCOD_BKGND_ALPH | (((uint8_t)(alpha * 255)) << 8)))
#define TCOD_BKGND_ADDALPHA(alpha) ((TCOD_bkgnd_flag_t)(TCOD_BKGND_ADDA | (((uint8_t)(alpha * 255)) << 8)))
TCOD_DEPRECATED(
"This function is not compatible with contexts. Consider using tcod::load_tilesheet or TCOD_tileset_load instead."
" https://libtcod.readthedocs.io/en/latest/upgrading.html")
TCODLIB_API TCOD_Error
TCOD_console_set_custom_font(const char* fontFile, int flags, int nb_char_horiz, int nb_char_vertic);
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCODLIB_API void TCOD_console_map_ascii_code_to_font(int asciiCode, int fontCharX, int fontCharY);
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCODLIB_API void TCOD_console_map_ascii_codes_to_font(int asciiCode, int nbCodes, int fontCharX, int fontCharY);
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCODLIB_API void TCOD_console_map_string_to_font(const char* s, int fontCharX, int fontCharY);
#ifndef NO_UNICODE
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCODLIB_API void TCOD_console_map_string_to_font_utf(const wchar_t* s, int fontCharX, int fontCharY);
#endif
TCOD_DEPRECATED("This function does nothing.")
TCODLIB_API void TCOD_console_set_dirty(int x, int y, int w, int h);
/**
Render and present a console with optional viewport options.
`console` is the console to render.
`viewport` is optional.
Returns a negative values on error. See `TCOD_get_error`.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_console_flush_ex(TCOD_Console* console, struct TCOD_ViewportOptions* viewport);
/**
* Render and present the root console to the active display.
*/
TCOD_PUBLIC TCOD_Error TCOD_console_flush(void);
/**
Return True if the libtcod keycode is held.
\rst
.. deprecated:: 1.16
You should instead use SDL_GetKeyboardState to check if keys are held.
\endrst
*/
TCOD_DEPRECATED("Use SDL to check the keyboard state.")
TCODLIB_API bool TCOD_console_is_key_pressed(TCOD_keycode_t key);
/* ASCII paint file support */
TCODLIB_API TCOD_console_t TCOD_console_from_file(const char* filename);
TCODLIB_API bool TCOD_console_load_asc(TCOD_console_t con, const char* filename);
TCODLIB_API bool TCOD_console_load_apf(TCOD_console_t con, const char* filename);
TCODLIB_API bool TCOD_console_save_asc(TCOD_console_t con, const char* filename);
TCODLIB_API bool TCOD_console_save_apf(TCOD_console_t con, const char* filename);
#ifndef NO_SDL
/**
Return immediately with a recently pressed key.
\param flags A TCOD_event_t bit-field, for example: `TCOD_EVENT_KEY_PRESS`
\return A TCOD_key_t struct with a recently pressed key.
If no event exists then the `vk` attribute will be `TCODK_NONE`
*/
TCOD_DEPRECATED("This API is deprecated, use SDL_PollEvent instead.")
TCODLIB_API TCOD_key_t TCOD_console_check_for_keypress(int flags);
/**
Wait for a key press event, then return it.
\param flush If 1 then the event queue will be cleared before waiting for
the next event. This should always be 0.
\return A TCOD_key_t struct with the most recent key data.
Do not solve input lag issues by arbitrarily dropping events!
*/
TCOD_DEPRECATED("This API is deprecated, use SDL_WaitEvent instead.")
TCODLIB_API TCOD_key_t TCOD_console_wait_for_keypress(bool flush);
TCOD_DEPRECATED("This function does not support contexts. Consider using `TCOD_console_credits_render_ex`.")
TCODLIB_API void TCOD_console_credits(void);
TCOD_DEPRECATED("This function does not support contexts.")
TCODLIB_API void TCOD_console_credits_reset(void);
TCOD_DEPRECATED("This function does not support contexts. Consider using `TCOD_console_credits_render_ex`.")
TCODLIB_API bool TCOD_console_credits_render(int x, int y, bool alpha);
/*****************************************************************************
@brief Render a libtcod credit animation to a console.
@param console The console to render to.
@param x
@param y
@param alpha
@param delta_time Delta time in seconds.
@return Returns true once the credits animation has ended.
\rst
.. versionadded:: 1.19
\endrst
*/
TCODLIB_API bool TCOD_console_credits_render_ex(TCOD_Console* console, int x, int y, bool alpha, float delta_time);
TCOD_DEPRECATED("This function is a stub and will do nothing.")
TCODLIB_API void TCOD_console_set_keyboard_repeat(int initial_delay, int interval);
TCOD_DEPRECATED("This function is a stub and will do nothing.")
TCODLIB_API void TCOD_console_disable_keyboard_repeat(void);
#endif // NO_SDL
#ifdef __cplusplus
} // extern "C"
#endif
#endif // TCOD_CONSOLE_ETC_H_

View file

@ -0,0 +1,223 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_CONSOLE_INIT_H_
#define LIBTCOD_CONSOLE_INIT_H_
#include "config.h"
#include "console.h"
#include "console_types.h"
#include "context.h"
#include "error.h"
#include "tileset.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
struct SDL_Rect;
struct SDL_Window;
struct SDL_Renderer;
#ifndef NO_SDL
/**
* \brief Initialize the libtcod graphical engine.
*
* \param w The width in tiles.
* \param h The height in tiles.
* \param title The title for the window.
* \param fullscreen Fullscreen option.
* \param renderer Which renderer to use when rendering the console.
*
* You may want to call TCOD_console_set_custom_font BEFORE calling this
* function. By default this function loads libtcod's `terminal.png` image
* from the working directory.
*
* Afterwards TCOD_quit must be called before the program exits.
*
* Returns 0 on success, or -1 on an error, you can check the error with
* TCOD_sys_get_error()
*
* `renderer` and vsync settings can be overridden by the `TCOD_RENDERER` or
* `TCOD_VSYNC` environment variables.
*
* Valid case-sensitive options for `TCOD_RENDERER` are:
* - sdl
* - opengl
* - glsl
* - sdl2
* - opengl2
*
* Valid options for `TCOD_VSYNC` are `0` or `1`.
*
* \rst
* .. versionchanged:: 1.12
* Now returns -1 on error instead of crashing.
*
* .. versionchanged:: 1.13
* Added the `TCOD_RENDERER` and `TCOD_VSYNC` overrides.
* \endrst
*/
TCOD_DEPRECATED(
"This way of initializing libtcod is deprecated. See the documentation for how to use TCOD_context_new.")
TCOD_PUBLIC TCOD_NODISCARD TCOD_Error
TCOD_console_init_root(int w, int h, const char* title, bool fullscreen, TCOD_renderer_t renderer);
TCOD_DEPRECATED(
"This way of initializing libtcod is deprecated. See the documentation for how to use TCOD_context_new.")
TCOD_PUBLIC TCOD_NODISCARD TCOD_Error
TCOD_console_init_root_(int w, int h, const char* title, bool fullscreen, TCOD_renderer_t renderer, bool vsync);
/**
* Change the title string of the active window.
*
* \param title A utf8 string.
*/
TCOD_DEPRECATED("This function is not compatible with contexts. Use SDL_SetWindowTitle to change the window title.")
TCOD_PUBLIC void TCOD_console_set_window_title(const char* title);
/**
* Set the display to be full-screen or windowed.
*
* \param fullscreen If true the display will go full-screen.
*/
TCOD_DEPRECATED(
"This function is not compatible with contexts. Use SDL_SetWindowFullscreen to set the fullscreen state.")
TCOD_PUBLIC void TCOD_console_set_fullscreen(bool fullscreen);
/**
* Return true if the display is full-screen.
*/
TCOD_DEPRECATED("This function is not compatible with contexts. Use SDL_GetWindowFlags to check this.")
TCOD_PUBLIC bool TCOD_console_is_fullscreen(void);
/**
* Return true if the window has mouse focus.
*/
TCOD_DEPRECATED("This function is not compatible with contexts. Use SDL_GetWindowFlags to check this.")
TCOD_PUBLIC bool TCOD_console_has_mouse_focus(void);
/**
* Return true if the window has keyboard focus.
*
* \verbatim embed:rst:leading-asterisk
* .. versionchanged: 1.7
* This function was previously broken. It now keeps track of keyboard
* focus.
* \endverbatim
*/
TCOD_DEPRECATED("This function is not compatible with contexts. Use SDL_GetWindowFlags to check this.")
TCOD_PUBLIC bool TCOD_console_is_active(void);
/**
* Return true if the window is closing.
*/
TCOD_DEPRECATED("This function is not compatible with contexts. Use SDL for events and check for SDL_QUIT.")
TCOD_PUBLIC bool TCOD_console_is_window_closed(void);
/**
* Return an SDL_Window pointer if one is in use, returns NULL otherwise.
* \rst
* .. versionadded:: 1.11
* \endrst
*/
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCOD_PUBLIC struct SDL_Window* TCOD_sys_get_sdl_window(void);
/**
* Return an SDL_Renderer pointer if one is in use, returns NULL otherwise.
* \rst
* .. versionadded:: 1.11
* \endrst
*/
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCOD_PUBLIC struct SDL_Renderer* TCOD_sys_get_sdl_renderer(void);
/**
* Render a console over the display.
* \rst
* `console` can be any size, the active render will try to scale it to fit
* the screen.
*
* The function will only work for the SDL2/OPENGL2 renderers.
*
* Unlike :any:`TCOD_console_flush` this will not present the display.
* You will need to do that manually, likely with the SDL API.
*
* Returns 0 on success, or a negative number on a failure such as the
* incorrect renderer being active.
*
* .. versionadded:: 1.11
*
* .. seealso::
* :any:`TCOD_sys_get_sdl_window` :any:`TCOD_sys_get_sdl_renderer`
* \endrst
*/
#endif // NO_SDL
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCOD_PUBLIC int TCOD_sys_accumulate_console(const TCOD_Console* console);
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCOD_PUBLIC int TCOD_sys_accumulate_console_(const TCOD_Console* console, const struct SDL_Rect* viewport);
/***************************************************************************
@brief Return the context being used internally by the old API.
@return A TCOD_Context pointer, or NULL if the global internals were not initialzed.
This function can be useful to progressively upgrade older code to use the newer API.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_PUBLIC TCOD_Context* TCOD_sys_get_internal_context(void);
/***************************************************************************
@brief Return a pointer to the "root console" used internally by the old API.
This is useful for functions which take a console parameter but won't accept NULL.
@return A pointer to TCOD_Console, or NULL if it doesn't exist.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_PUBLIC TCOD_Console* TCOD_sys_get_internal_console(void);
/***************************************************************************
@brief Shutdown libtcod. This must be called before your program exits.
\rst
.. versionadded:: 1.8
\endrst
*/
TCOD_PUBLIC void TCOD_quit(void);
#ifdef __cplusplus
} // extern "C"
namespace tcod {
namespace console {
[[deprecated(
"This way of initializing libtcod is deprecated. See the documentation for how to use "
"tcod::new_context.")]] TCOD_PUBLIC void
init_root(int w, int h, const std::string& title, bool fullscreen, TCOD_renderer_t renderer);
[[deprecated(
"This way of initializing libtcod is deprecated. See the documentation for how to use "
"tcod::new_context.")]] TCOD_PUBLIC void
init_root(int w, int h, const std::string& title, bool fullscreen, TCOD_renderer_t renderer, bool vsync);
} // namespace console
} // namespace tcod
#endif // __cplusplus
#endif // LIBTCOD_CONSOLE_INIT_H_

View file

@ -0,0 +1,554 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_CONSOLE_PRINTING_H_
#define TCOD_CONSOLE_PRINTING_H_
#include <stdarg.h>
#include <stdbool.h>
#ifndef NO_UNICODE
#include <wchar.h>
#endif
#include "config.h"
#include "console_types.h"
#include "error.h"
#ifdef __cplusplus
extern "C" {
#endif
/// @defgroup PrintEASCII
/// @{
/***************************************************************************
@brief Print a string on a console, using default colors and alignment.
@param con A console pointer.
@param x The starting X coordinate, the left-most position being 0.
@param y The starting Y coordinate, the top-most position being 0.
@param fmt A format string as if passed to printf.
@param ... Variadic arguments as if passed to printf.
*/
TCOD_DEPRECATED("Use TCOD_console_printf instead.")
TCODLIB_API void TCOD_console_print(TCOD_Console* con, int x, int y, const char* fmt, ...);
/***************************************************************************
@brief Print an EASCII string on a console, using default colors.
@param con A console pointer.
@param x The starting X coordinate, the left-most position being 0.
@param y The starting Y coordinate, the top-most position being 0.
@param flag The blending flag.
@param alignment The font alignment to use.
@param fmt A format string as if passed to printf.
@param ... Variadic arguments as if passed to printf.
*/
TCOD_DEPRECATED("Use TCOD_console_printf_ex instead.")
TCODLIB_API void TCOD_console_print_ex(
TCOD_Console* con, int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char* fmt, ...);
/***************************************************************************
@brief Print an EASCII string on a console constrained to a rectangle, using default colors and alignment.
@param con A console pointer.
@param x The starting X coordinate, the left-most position being 0.
@param y The starting Y coordinate, the top-most position being 0.
@param w The width of the region.
If 0 then the maximum width will be used.
@param h The height of the region.
If 0 then the maximum height will be used.
@param fmt A format string as if passed to printf.
@param ... Variadic arguments as if passed to printf.
@return The number of lines actually printed.
*/
TCOD_DEPRECATED("Use TCOD_console_printf_rect instead.")
TCODLIB_API int TCOD_console_print_rect(TCOD_Console* con, int x, int y, int w, int h, const char* fmt, ...);
/***************************************************************************
@brief Print an EASCII string on a console constrained to a rectangle, using default colors.
@param con A console pointer.
@param x The starting X coordinate, the left-most position being 0.
@param y The starting Y coordinate, the top-most position being 0.
@param w The width of the region.
If 0 then the maximum width will be used.
@param h The height of the region.
If 0 then the maximum height will be used.
@param flag The blending flag.
@param alignment The font alignment to use.
@param fmt A format string as if passed to printf.
@param ... Variadic arguments as if passed to printf.
@return The number of lines actually printed.
*/
TCOD_DEPRECATED("Use TCOD_console_printf_rect_ex instead.")
TCODLIB_API int TCOD_console_print_rect_ex(
TCOD_Console* con,
int x,
int y,
int w,
int h,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment,
const char* fmt,
...);
/***************************************************************************
@brief Print a titled, framed region on a console, using default colors and alignment.
@param con A console pointer.
@param x The starting X coordinate, the left-most position being 0.
@param y The starting Y coordinate, the top-most position being 0.
@param w The width of the frame.
@param h The height of the frame.
@param empty If true the characters inside of the frame will be cleared
with spaces.
@param flag The blending flag.
@param fmt A format string as if passed to printf.
@param ... Variadic arguments as if passed to printf.
This function makes assumptions about the fonts character encoding and may draw garbage with some tilesets.
\rst
.. deprecated:: 1.19
This function is not using Unicode frame characters and has been deprecated.
\endrst
*/
TCOD_DEPRECATED("Use TCOD_console_printf_frame instead.")
TCODLIB_API void TCOD_console_print_frame(
TCOD_console_t con, int x, int y, int w, int h, bool empty, TCOD_bkgnd_flag_t flag, const char* fmt, ...);
/***************************************************************************
@brief Return the number of lines that would be printed by an EASCII string.
@param con A console pointer.
@param x The starting X coordinate, the left-most position being 0.
@param y The starting Y coordinate, the top-most position being 0.
@param w The width of the region.
If 0 then the maximum width will be used.
@param h The height of the region.
If 0 then the maximum height will be used.
@param fmt A format string as if passed to printf.
@param ... Variadic arguments as if passed to printf.
@return The number of lines that would have been printed.
*/
TCOD_DEPRECATED("Use TCOD_console_get_height_rect_fmt instead.")
TCODLIB_API int TCOD_console_get_height_rect(TCOD_Console* con, int x, int y, int w, int h, const char* fmt, ...);
/// @}
#ifndef NO_UNICODE
/// @defgroup PrintWide
/// @{
/***************************************************************************
\rst
.. deprecated:: 1.8
Use :any:`TCOD_console_printf` instead.
\endrst
*/
TCOD_DEPRECATED("Use TCOD_console_printf instead.")
TCODLIB_API void TCOD_console_print_utf(TCOD_Console* con, int x, int y, const wchar_t* fmt, ...);
/***************************************************************************
\rst
.. deprecated:: 1.8
Use :any:`TCOD_console_printf_ex` instead.
\endrst
*/
TCOD_DEPRECATED("Use TCOD_console_printf_ex instead.")
TCODLIB_API void TCOD_console_print_ex_utf(
TCOD_Console* con, int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t* fmt, ...);
/***************************************************************************
\rst
.. deprecated:: 1.8
Use :any:`TCOD_console_printf_rect` instead.
\endrst
*/
TCOD_DEPRECATED("Use TCOD_console_printf_rect instead.")
TCODLIB_API int TCOD_console_print_rect_utf(TCOD_Console* con, int x, int y, int w, int h, const wchar_t* fmt, ...);
/***************************************************************************
\rst
.. deprecated:: 1.8
Use :any:`TCOD_console_printf_rect_ex` instead.
\endrst
*/
TCOD_DEPRECATED("Use TCOD_console_printf_rect_ex instead.")
TCODLIB_API int TCOD_console_print_rect_ex_utf(
TCOD_Console* con,
int x,
int y,
int w,
int h,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment,
const wchar_t* fmt,
...);
/***************************************************************************
\rst
.. deprecated:: 1.8
\endrst
*/
TCOD_DEPRECATED("Use TCOD_console_get_height_rect_fmt instead.")
TCODLIB_API int TCOD_console_get_height_rect_utf(
TCOD_Console* con, int x, int y, int w, int h, const wchar_t* fmt, ...);
/// @}
#endif
typedef enum {
TCOD_COLCTRL_1 = 1,
TCOD_COLCTRL_2,
TCOD_COLCTRL_3,
TCOD_COLCTRL_4,
TCOD_COLCTRL_5,
TCOD_COLCTRL_NUMBER = 5,
TCOD_COLCTRL_FORE_RGB,
TCOD_COLCTRL_BACK_RGB,
TCOD_COLCTRL_STOP
} TCOD_colctrl_t;
TCODLIB_API void TCOD_console_set_color_control(TCOD_colctrl_t con, TCOD_color_t fore, TCOD_color_t back);
/* UTF-8 functions */
#ifndef TCOD_NO_UNICODE
/**
Format and print a UTF-8 string to a console.
\rst
.. versionadded:: 1.8
.. versionchanged:: 1.16
Now returns a negative error code on failure.
\endrst
*/
TCODLIB_API TCODLIB_FORMAT(4, 5) TCOD_Error
TCOD_console_printf(TCOD_Console* __restrict con, int x, int y, const char* __restrict fmt, ...);
/**
Format and print a UTF-8 string to a console.
\rst
.. versionadded:: 1.8
.. versionchanged:: 1.16
Now returns a negative error code on failure.
\endrst
*/
TCODLIB_API TCODLIB_FORMAT(6, 7) TCOD_Error TCOD_console_printf_ex(
TCOD_Console* __restrict con,
int x,
int y,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment,
const char* __restrict fmt,
...);
/**
Format and print a UTF-8 string to a console.
\rst
.. versionadded:: 1.8
.. versionchanged:: 1.16
Now returns a negative error code on failure.
\endrst
*/
TCODLIB_API TCODLIB_FORMAT(6, 7) int TCOD_console_printf_rect(
TCOD_Console* __restrict con, int x, int y, int w, int h, const char* __restrict fmt, ...);
/**
Format and print a UTF-8 string to a console.
\rst
.. versionadded:: 1.8
.. versionchanged:: 1.16
Now returns a negative error code on failure.
\endrst
*/
TCODLIB_API TCODLIB_FORMAT(8, 9) int TCOD_console_printf_rect_ex(
TCOD_Console* __restrict con,
int x,
int y,
int w,
int h,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment,
const char* __restrict fmt,
...);
/**
Print a framed and optionally titled region to a console, using default
colors and alignment.
This function uses Unicode box-drawing characters and a UTF-8 formatted
string.
\rst
.. versionadded:: 1.8
.. versionchanged:: 1.16
Now returns a negative error code on failure.
\endrst
*/
TCODLIB_API TCODLIB_FORMAT(8, 9) TCOD_Error TCOD_console_printf_frame(
TCOD_Console* __restrict con,
int x,
int y,
int w,
int h,
int empty,
TCOD_bkgnd_flag_t flag,
const char* __restrict fmt,
...);
/**
Return the number of lines that would be printed by this formatted string.
\rst
.. versionadded:: 1.8
.. versionchanged:: 1.16
Now returns a negative error code on failure.
\endrst
*/
TCODLIB_API TCODLIB_FORMAT(6, 7) int TCOD_console_get_height_rect_fmt(
TCOD_Console* __restrict con, int x, int y, int w, int h, const char* __restrict fmt, ...);
/**
@brief Print a string of a specified length to a console.
@param console A pointer to a TCOD_Console.
@param x The starting X position, starting from the left-most tile as zero.
@param y The starting Y position, starting from the upper-most tile as zero.
@param n The length of the string buffer `str[n]` in bytes.
@param str The text to print. This string can contain libtcod color codes.
@param fg The foreground color. The printed text is set to this color.
If NULL then the foreground will be left unchanged, inheriting the previous value of the tile.
@param bg The background color. The background tile under the printed text is set to this color.
If NULL then the background will be left unchanged.
@param flag The background blending flag. If unsure then use `TCOD_BKGND_SET`.
@param alignment The text justification. This is one of `TCOD_alignment_t` and is normally `TCOD_LEFT`.
@return TCOD_Error Any problems such as malformed UTF-8 will return a negative error code.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_console_printn(
TCOD_Console* __restrict console,
int x,
int y,
size_t n,
const char* __restrict str,
const TCOD_ColorRGB* __restrict fg,
const TCOD_ColorRGB* __restrict bg,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment);
/**
@brief Print a string of a specified length in a bounding box to a console.
@param console A pointer to a TCOD_Console.
@param x The starting X position, starting from the left-most tile as zero.
@param y The starting Y position, starting from the upper-most tile as zero.
@param width The maximum width of the bounding region in tiles.
@param height The maximum height of the bounding region in tiles.
@param n The length of the string buffer `str[n]` in bytes.
@param str The text to print. This string can contain libtcod color codes.
@param fg The foreground color. The printed text is set to this color.
If NULL then the foreground will be left unchanged, inheriting the previous value of the tile.
@param bg The background color. The background tile under the printed text is set to this color.
If NULL then the background will be left unchanged.
@param flag The background blending flag. If unsure then use `TCOD_BKGND_SET`.
@param alignment The text justification. This is one of `TCOD_alignment_t` and is normally `TCOD_LEFT`.
@return int The height of the printed text, or a negative error code on failure.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_PUBLIC int TCOD_console_printn_rect(
TCOD_Console* __restrict console,
int x,
int y,
int width,
int height,
size_t n,
const char* __restrict str,
const TCOD_ColorRGB* __restrict fg,
const TCOD_ColorRGB* __restrict bg,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment);
/**
@brief Return the height of the word-wrapped text with the given parameters.
@param console A pointer to a TCOD_Console.
@param x The starting X position, starting from the left-most tile as zero.
@param y The starting Y position, starting from the upper-most tile as zero.
@param width The maximum width of the bounding region in tiles.
@param height The maximum height of the bounding region in tiles.
@param n The length of the string buffer `str[n]` in bytes.
@param str The text to print. This string can contain libtcod color codes.
@return int The height of the word-wrapped text as if it were printed, or a negative error code on failure.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_PUBLIC int TCOD_console_get_height_rect_n(
TCOD_Console* __restrict console, int x, int y, int width, int height, size_t n, const char* __restrict str);
/**
@brief Return the height of the word-wrapped text with the given width.
@param width The maximum width of the bounding region in tiles.
@param n The length of the string buffer `str[n]` in bytes.
@param str The text to print. This string can contain libtcod color codes.
@return int The height of the word-wrapped text as if it were printed, or a negative error code on failure.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_PUBLIC int TCOD_console_get_height_rect_wn(int width, size_t n, const char* __restrict str);
// Deprecated function.
TCOD_PUBLIC TCOD_Error TCOD_console_printn_frame(
TCOD_Console* __restrict console,
int x,
int y,
int width,
int height,
size_t n,
const char* __restrict title,
const TCOD_ColorRGB* __restrict fg,
const TCOD_ColorRGB* __restrict bg,
TCOD_bkgnd_flag_t flag,
bool clear);
/*****************************************************************************
@brief Print a formatted string using a va_list.
@param console A pointer to a TCOD_Console.
@param x The starting X position, starting from the left-most tile as zero.
@param y The starting Y position, starting from the upper-most tile as zero.
@param fg The foreground color. The printed text is set to this color.
If NULL then the foreground will be left unchanged, inheriting the previous value of the tile.
@param bg The background color. The background tile under the printed text is set to this color.
If NULL then the background will be left unchanged.
@param flag The background blending flag. If unsure then use `TCOD_BKGND_SET`.
@param alignment The text justification. This is one of `TCOD_alignment_t` and is normally `TCOD_LEFT`.
@param fmt The format string for a vprintf-like function.
@param args The arguments for the formatted string.
@return TCOD_Error Any problems such as malformed UTF-8 will return a negative error code.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_console_vprintf(
TCOD_Console* __restrict console,
int x,
int y,
const TCOD_color_t* __restrict fg,
const TCOD_color_t* __restrict bg,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment,
const char* __restrict fmt,
va_list args);
/*****************************************************************************
@brief Print a formatted string using a va_list within a bounding box.
@param console A pointer to a TCOD_Console.
@param x The starting X position, starting from the left-most tile as zero.
@param y The starting Y position, starting from the upper-most tile as zero.
@param width The maximum width of the bounding region in tiles.
@param height The maximum height of the bounding region in tiles.
@param fg The foreground color. The printed text is set to this color.
If NULL then the foreground will be left unchanged, inheriting the previous value of the tile.
@param bg The background color. The background tile under the printed text is set to this color.
If NULL then the background will be left unchanged.
@param flag The background blending flag. If unsure then use `TCOD_BKGND_SET`.
@param alignment The text justification. This is one of `TCOD_alignment_t` and is normally `TCOD_LEFT`.
@param fmt The format string for a vprintf-like function.
@param args The arguments for the formatted string.
@return TCOD_PUBLIC
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_PUBLIC int TCOD_console_vprintf_rect(
TCOD_Console* __restrict console,
int x,
int y,
int width,
int height,
const TCOD_color_t* __restrict fg,
const TCOD_color_t* __restrict bg,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t alignment,
const char* fmt,
va_list args);
/*****************************************************************************
@brief Information about a string to be printed
*/
typedef struct TCOD_PrintParamsRGB {
int x; // The starting X coordinate, the left-most position being 0.
int y; // The starting Y coordinate, the top-most position being 0.
int width; // Width of the bounding rectangle. Will be unbound if set to 0
int height; // Height of the bounding rectangle. Will be unbound if set to 0
const TCOD_ColorRGB* __restrict fg; // An optional foreground color of the string
const TCOD_ColorRGB* __restrict bg; // An optional background color of the string
TCOD_bkgnd_flag_t flag; // The background blending flag. The default of `TCOD_BKGND_NONE` implies `TCOD_BKGND_SET`.
TCOD_alignment_t alignment; // The text justification. Defaults to `TCOD_LEFT`.
} TCOD_PrintParamsRGB;
/*****************************************************************************
@brief Prints a formatted string to the console.
@param console A pointer to a TCOD_Console.
@param params Information about how the string should be printed
@param fmt The format string for a vprintf-like function.
@param args The arguments for the formatted string.
@return An error code if less than 0
\rst
.. versionadded:: 1.23
\endrst
*/
TCOD_PUBLIC TCODLIB_FORMAT(3, 4) int TCOD_printf_rgb(
TCOD_Console* __restrict console, TCOD_PrintParamsRGB params, const char* __restrict fmt, ...);
/*****************************************************************************
@brief Prints n-bytes of a string string to the console.
@param console A pointer to a TCOD_Console.
@param params Information about how the string should be printed
@param str The string to be read from.
@param n Length of string in bytes
@return An error code if less than 0
\rst
.. versionadded:: 1.23
\endrst
*/
TCOD_PUBLIC int TCOD_printn_rgb(
TCOD_Console* __restrict console, TCOD_PrintParamsRGB params, int n, const char* __restrict str);
/*****************************************************************************
@brief Prints a formatted string using va_list
@param console A pointer to a TCOD_Console.
@param params Information about how the string should be printed
@param fmt The format string for a vprintf-like function
@param args The arguments for the format string
@return An error code if less than 0
\rst
.. versionadded:: 1.23
\endrst
*/
TCOD_PUBLIC int TCOD_vprintf_rgb(
TCOD_Console* __restrict console, TCOD_PrintParamsRGB params, const char* __restrict fmt, va_list args);
#endif // TCOD_NO_UNICODE
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif /* TCOD_CONSOLE_PRINTING_H_ */

View file

@ -0,0 +1,198 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_CONSOLE_PRINTING_HPP_
#define TCOD_CONSOLE_PRINTING_HPP_
#include <stdio.h>
#include <array>
#include <cstdarg>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include "console_printing.h"
namespace tcod {
#ifndef TCOD_NO_UNICODE
/*****************************************************************************
@brief Print a string to a console.
@param console A reference to a TCOD_Console.
@param xy The starting `{x, y}` position, starting from the upper-left-most tile as zero.
@param str The text to print. This string can contain libtcod color codes.
@param fg The foreground color. The printed text is set to this color.
If std::nullopt then the foreground will be left unchanged, inheriting the previous value of the tile.
@param bg The background color. The background tile under the printed text is set to this color.
If std::nullopt then the background will be left unchanged.
@param alignment The text justification.
@param flag The background blending flag.
@code{.cpp}
auto console = tcod::Console{80, 50};
tcod::print(console, {0, 0}, "Hello World", {{255, 255, 255}}, {{0, 0, 0}});
@endcode
\rst
.. versionadded:: 1.19
\endrst
*/
inline void print(
TCOD_Console& console,
const std::array<int, 2>& xy,
std::string_view str,
std::optional<TCOD_ColorRGB> fg,
std::optional<TCOD_ColorRGB> bg,
TCOD_alignment_t alignment = TCOD_LEFT,
TCOD_bkgnd_flag_t flag = TCOD_BKGND_SET) {
const TCOD_ColorRGB* fg_ptr = fg ? &fg.value() : nullptr;
const TCOD_ColorRGB* bg_ptr = bg ? &bg.value() : nullptr;
check_throw_error(
TCOD_console_printn(&console, xy.at(0), xy.at(1), str.size(), str.data(), fg_ptr, bg_ptr, flag, alignment));
}
/*****************************************************************************
@brief Print a string to a console constrained to a bounding box.
@param console A reference to a TCOD_Console.
@param rect An `{x, y, width, height}` rectangle, starting from the upper-left-most tile as zero.
A width or height of zero will leave that axis unconstrained.
@param str The text to print. This string can contain libtcod color codes.
@param fg The foreground color. The printed text is set to this color.
If std::nullopt then the foreground will be left unchanged, inheriting the previous value of the tile.
@param bg The background color. The background tile under the printed text is set to this color.
If std::nullopt then the background will be left unchanged.
@param alignment The text justification.
@param flag The background blending flag.
@return int The height of the printed output.
@code{.cpp}
auto console = tcod::Console{80, 50};
static constexpr auto TEAL = tcod::ColorRGB{0, 255, 255};
// Print "Hello World" centered along the top row, ignoring the background color.
tcod::print(console, {0, 0, console->w, 1}, "Hello World", TEAL, std::nullopt, TCOD_CENTER);
@endcode
\rst
.. versionadded:: 1.19
\endrst
*/
inline int print_rect(
TCOD_Console& console,
const std::array<int, 4>& rect,
std::string_view str,
std::optional<TCOD_ColorRGB> fg,
std::optional<TCOD_ColorRGB> bg,
TCOD_alignment_t alignment = TCOD_LEFT,
TCOD_bkgnd_flag_t flag = TCOD_BKGND_SET) {
return check_throw_error(TCOD_console_printn_rect(
&console,
rect.at(0),
rect.at(1),
rect.at(2),
rect.at(3),
str.size(),
str.data(),
fg ? &fg.value() : nullptr,
bg ? &bg.value() : nullptr,
flag,
alignment));
}
/*****************************************************************************
@brief Return the height of the word-wrapped text with the given width.
@param width The maximum width of the bounding region in tiles.
@param str The text to print. This string can contain libtcod color codes.
@return int The height of the text as if it were printed.
@code{.cpp}
auto console = tcod::Console{80, 50};
int y = console->h; // Start Y at the bottom of this console.
const int width = 6;
y -= tcod::get_height_rect("Long text example", width); // Move y up by the height of this text.
tcod::print(console, {0, y, width, 0}, "Long text example", std::nullopt, std::nullopt);
@endcode
\rst
.. versionadded:: 1.19
\endrst
*/
inline int get_height_rect(int width, std::string_view str) {
return check_throw_error(TCOD_console_get_height_rect_wn(width, str.size(), str.data()));
}
[[deprecated("It is recommended that you print your own banners for frames.")]] inline void print_frame(
struct TCOD_Console& console,
const std::array<int, 4>& rect,
std::string_view title,
const TCOD_ColorRGB* fg,
const TCOD_ColorRGB* bg,
TCOD_bkgnd_flag_t flag = TCOD_BKGND_SET,
bool clear = true) {
check_throw_error(TCOD_console_printn_frame(
&console, rect.at(0), rect.at(1), rect.at(2), rect.at(3), title.size(), title.data(), fg, bg, flag, clear));
}
#endif // TCOD_NO_UNICODE
/*****************************************************************************
@brief Return a formatted string as a std::string object.
This is a convience function for code using printf-like formatted strings.
Newer more modern code might want to use [the fmt library](https://fmt.dev/latest/index.html) instead.
@tparam T Parameter packed arguments.
@param format A printf-like format string.
@param args Any printf-like arguments.
@return A std::string object with the resulting output.
@details
[fmt::sprintf](https://fmt.dev/latest/api.html#_CPPv4I0Dp0EN3fmt7sprintfENSt12basic_stringI4CharEERK1SDpRK1T)
is a faster and safer alternative to this function.
@code{.cpp}
auto console = tcod::Console{80, 50};
// Use tcod::stringf to encapsulate printf-like parameters.
tcod::print(console, {0, 0}, tcod::stringf("%s %s", "Hello", "World"), nullptr, nullptr);
@endcode
\rst
.. versionadded:: 1.19
\endrst
*/
template <typename... T>
inline std::string stringf(const char* format, T... args) {
const int str_length = snprintf(nullptr, 0, format, args...);
if (str_length < 0) throw std::runtime_error("Failed to format string.");
std::string out(str_length, '\0');
snprintf(&out[0], str_length + 1, format, args...);
return out;
}
} // namespace tcod
#endif // TCOD_CONSOLE_PRINTING_HPP_

View file

@ -0,0 +1,189 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_CONSOLE_REXPAINT_H_
#define TCOD_CONSOLE_REXPAINT_H_
#ifndef TCOD_NO_ZLIB
#ifdef __cplusplus
#include <string>
#include <vector>
#endif // __cplusplus
#include "config.h"
#include "console_types.h"
#include "list.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
\brief Return a new console loaded from a REXPaint ``.xp`` file.
\param [in] filename A path to the REXPaint file.
\return A new TCOD_console_t object. New consoles will need
to be deleted with a call to :any:`TCOD_console_delete`.
Returns NULL on an error.
*/
TCODLIB_API TCOD_console_t TCOD_console_from_xp(const char* filename);
/**
\brief Update a console from a REXPaint ``.xp`` file.
\param [out] con A console instance to update from the REXPaint file.
\param [in] filename A path to the REXPaint file.
In C++, you can pass the filepath directly to the :any:`TCODConsole`
constructor to load a REXPaint file.
*/
TCODLIB_API bool TCOD_console_load_xp(TCOD_Console* con, const char* filename);
/**
\brief Save a console as a REXPaint ``.xp`` file.
\param [in] con The console instance to save.
\param [in] filename The filepath to save to.
\param [in] compress_level A zlib compression level, from 0 to 9.
1=fast, 6=balanced, 9=slowest, 0=uncompressed.
\return ``true`` when the file is saved successfully, or ``false`` when an
issue is detected.
The REXPaint format can support a 1:1 copy of a libtcod console.
*/
TCODLIB_API bool TCOD_console_save_xp(const TCOD_Console* con, const char* filename, int compress_level);
/**
\brief Return a list of consoles from a REXPaint file.
\param [in] filename A path to the REXPaint file.
\return Returns a TCOD_list_t of TCOD_console_t objects. Or NULL on an
error. You will need to delete this list and each console individually.
This function can load a REXPaint file with variable layer shapes,
which would cause issues for a function like TCOD_console_list_from_xp.
\rst
.. deprecated:: 1.20
TCOD_list_t is deprecated, use TCOD_load_xp instead.
\endrst
*/
TCOD_DEPRECATED("TCOD_list_t is deprecated, use TCOD_load_xp instead.")
TCODLIB_API TCOD_list_t TCOD_console_list_from_xp(const char* filename);
/**
\brief Save a list of consoles to a REXPaint file.
\param [in] console_list A TCOD_list_t of TCOD_console_t objects.
\param [in] filename Path to save to.
\param [in] compress_level zlib compression level.
\return true on success, false on a failure such as not being able to write
to the path provided.
This function can save any number of layers with multiple
different sizes.
The REXPaint tool only supports files with up to 9 layers where
all layers are the same size.
\rst
.. deprecated:: 1.20
TCOD_list_t is deprecated, use TCOD_save_xp instead.
\endrst
*/
TCOD_DEPRECATED("TCOD_list_t is deprecated, use TCOD_save_xp instead.")
TCODLIB_API bool TCOD_console_list_save_xp(TCOD_list_t console_list, const char* filename, int compress_level);
/**
@brief Load an array of consoles from a REXPaint file in memory.
You can call this function with `n_out=0` and `out=NULL` to get the number of consoles in the file.
@param n_data The length of the input `data` buffer.
@param data The buffer where the REXPaint file is held.
@param n_out The length of the output console `out` array. Can be zero.
@param out The array to fill with loaded consoles.
@return Returns the number of consoles held by the file. Returns a negative error code on error.
\rst
.. versionadded:: 1.18
\endrst
*/
TCODLIB_API int TCOD_load_xp_from_memory(int n_data, const unsigned char* data, int n_out, TCOD_Console** out);
/**
@brief Save an array of consoles to a REXPaint file in memory.
Partially initialized consoles are released on failures.
@param n_consoles The length of the input `consoles` array.
@param consoles An array of tcod consoles, can not be NULL.
@param n_out The size of the `out` buffer, if this is zero then upper bound to be returned.
@param out A pointer to an output buffer, can be NULL.
@param compression_level A compression level for the zlib library.
@return If `out=NULL` then returns the upper bound of the buffer size needed.
Otherwise this returns the number of bytes actually filled.
On an error a negative error code is returned.
\rst
.. versionadded:: 1.18
\endrst
*/
TCODLIB_API int TCOD_save_xp_to_memory(
int n_consoles, const TCOD_Console* const* consoles, int n_out, unsigned char* out, int compression_level);
/**
@brief Load an array of consoles from a REXPaint file.
@param path The path to the REXPaint file, can not be NULL.
@param n The size of the `out` array. Can be zero.
@param out The array to fill with loaded consoles.
@return Returns the number of consoles held by the file. Returns a negative error code on error.
\rst
.. versionadded:: 1.18
\endrst
*/
TCODLIB_API int TCOD_load_xp(const char* path, int n, TCOD_Console** out);
/**
@brief Save an array of consoles to a REXPaint file.
Partially initialized consoles are released on failures.
@param n The number of consoles in the `consoles` array.
@param consoles An array of consoles.
@param path The path write the REXPaint file, can not be NULL.
@param compress_level A compression level for the zlib library.
@return Returns an error code on failure.
\rst
.. versionadded:: 1.18
\endrst
*/
TCODLIB_API TCOD_Error TCOD_save_xp(int n, const TCOD_Console* const* consoles, const char* path, int compress_level);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // TCOD_NO_ZLIB
#endif // TCOD_CONSOLE_REXPAINT_H_

View file

@ -0,0 +1,78 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_CONSOLE_REXPAINT_HPP_
#define TCOD_CONSOLE_REXPAINT_HPP_
#ifndef TCOD_NO_ZLIB
#include <filesystem>
#include <vector>
#include "console_rexpaint.h"
#include "console_types.hpp"
namespace tcod {
/**
@brief Load an array of consoles from a REXPaint file.
@param path The path to the REXPaint file to load.
@return Returns a vector of consoles.
\rst
.. versionadded:: 1.18
\endrst
*/
inline std::vector<tcod::ConsolePtr> load_xp(const std::filesystem::path& path) {
const auto path_str = path.string();
int layer_count = tcod::check_throw_error(TCOD_load_xp(path_str.c_str(), 0, nullptr));
std::vector<TCOD_Console*> tmp(layer_count, nullptr);
tcod::check_throw_error(TCOD_load_xp(path_str.c_str(), layer_count, &tmp[0]));
return std::vector<tcod::ConsolePtr>(tmp.begin(), tmp.end());
}
/**
@brief Save an array of consoles to a REXPaint file.
@param consoles A vector of consoles to save.
@param path The path to write the REXPaint file to.
@param compress_level A compression level for the zlib library.
\rst
.. versionadded:: 1.18
\endrst
*/
inline void save_xp(
const std::vector<const TCOD_Console*>& consoles, const std::filesystem::path& path, int compress_level = 9) {
tcod::check_throw_error(
TCOD_save_xp(static_cast<int>(consoles.size()), consoles.data(), path.string().c_str(), compress_level));
}
} // namespace tcod
#endif // TCOD_NO_ZLIB
#endif // TCOD_CONSOLE_REXPAINT_HPP_

View file

@ -0,0 +1,419 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_CONSOLE_TYPES_H_
#define TCOD_CONSOLE_TYPES_H_
#include "color.h"
#include "config.h"
#include "console.h"
typedef enum {
TCODK_NONE,
TCODK_ESCAPE,
TCODK_BACKSPACE,
TCODK_TAB,
TCODK_ENTER,
TCODK_SHIFT,
TCODK_CONTROL,
TCODK_ALT,
TCODK_PAUSE,
TCODK_CAPSLOCK,
TCODK_PAGEUP,
TCODK_PAGEDOWN,
TCODK_END,
TCODK_HOME,
TCODK_UP,
TCODK_LEFT,
TCODK_RIGHT,
TCODK_DOWN,
TCODK_PRINTSCREEN,
TCODK_INSERT,
TCODK_DELETE,
TCODK_LWIN,
TCODK_RWIN,
TCODK_APPS,
TCODK_0,
TCODK_1,
TCODK_2,
TCODK_3,
TCODK_4,
TCODK_5,
TCODK_6,
TCODK_7,
TCODK_8,
TCODK_9,
TCODK_KP0,
TCODK_KP1,
TCODK_KP2,
TCODK_KP3,
TCODK_KP4,
TCODK_KP5,
TCODK_KP6,
TCODK_KP7,
TCODK_KP8,
TCODK_KP9,
TCODK_KPADD,
TCODK_KPSUB,
TCODK_KPDIV,
TCODK_KPMUL,
TCODK_KPDEC,
TCODK_KPENTER,
TCODK_F1,
TCODK_F2,
TCODK_F3,
TCODK_F4,
TCODK_F5,
TCODK_F6,
TCODK_F7,
TCODK_F8,
TCODK_F9,
TCODK_F10,
TCODK_F11,
TCODK_F12,
TCODK_NUMLOCK,
TCODK_SCROLLLOCK,
TCODK_SPACE,
TCODK_CHAR,
TCODK_TEXT
} TCOD_keycode_t;
#define TCOD_KEY_TEXT_SIZE 32
/* key data : special code or character or text */
typedef struct {
TCOD_keycode_t vk; /* key code */
char c; /* character if vk == TCODK_CHAR else 0 */
char text[TCOD_KEY_TEXT_SIZE]; /* text if vk == TCODK_TEXT else text[0] == '\0' */
bool pressed; /* does this correspond to a key press or key release event ? */
bool lalt;
bool lctrl;
bool lmeta;
bool ralt;
bool rctrl;
bool rmeta;
bool shift;
} TCOD_key_t;
typedef enum TCOD_chars_t {
/* single walls */
TCOD_CHAR_HLINE TCOD_DEPRECATED_ENUM = 196,
TCOD_CHAR_VLINE TCOD_DEPRECATED_ENUM = 179,
TCOD_CHAR_NE TCOD_DEPRECATED_ENUM = 191,
TCOD_CHAR_NW TCOD_DEPRECATED_ENUM = 218,
TCOD_CHAR_SE TCOD_DEPRECATED_ENUM = 217,
TCOD_CHAR_SW TCOD_DEPRECATED_ENUM = 192,
TCOD_CHAR_TEEW TCOD_DEPRECATED_ENUM = 180,
TCOD_CHAR_TEEE TCOD_DEPRECATED_ENUM = 195,
TCOD_CHAR_TEEN TCOD_DEPRECATED_ENUM = 193,
TCOD_CHAR_TEES TCOD_DEPRECATED_ENUM = 194,
TCOD_CHAR_CROSS TCOD_DEPRECATED_ENUM = 197,
/* double walls */
TCOD_CHAR_DHLINE TCOD_DEPRECATED_ENUM = 205,
TCOD_CHAR_DVLINE TCOD_DEPRECATED_ENUM = 186,
TCOD_CHAR_DNE TCOD_DEPRECATED_ENUM = 187,
TCOD_CHAR_DNW TCOD_DEPRECATED_ENUM = 201,
TCOD_CHAR_DSE TCOD_DEPRECATED_ENUM = 188,
TCOD_CHAR_DSW TCOD_DEPRECATED_ENUM = 200,
TCOD_CHAR_DTEEW TCOD_DEPRECATED_ENUM = 185,
TCOD_CHAR_DTEEE TCOD_DEPRECATED_ENUM = 204,
TCOD_CHAR_DTEEN TCOD_DEPRECATED_ENUM = 202,
TCOD_CHAR_DTEES TCOD_DEPRECATED_ENUM = 203,
TCOD_CHAR_DCROSS TCOD_DEPRECATED_ENUM = 206,
/* blocks */
TCOD_CHAR_BLOCK1 TCOD_DEPRECATED_ENUM = 176,
TCOD_CHAR_BLOCK2 TCOD_DEPRECATED_ENUM = 177,
TCOD_CHAR_BLOCK3 TCOD_DEPRECATED_ENUM = 178,
/* arrows */
TCOD_CHAR_ARROW_N TCOD_DEPRECATED_ENUM = 24,
TCOD_CHAR_ARROW_S TCOD_DEPRECATED_ENUM = 25,
TCOD_CHAR_ARROW_E TCOD_DEPRECATED_ENUM = 26,
TCOD_CHAR_ARROW_W TCOD_DEPRECATED_ENUM = 27,
/* arrows without tail */
TCOD_CHAR_ARROW2_N TCOD_DEPRECATED_ENUM = 30,
TCOD_CHAR_ARROW2_S TCOD_DEPRECATED_ENUM = 31,
TCOD_CHAR_ARROW2_E TCOD_DEPRECATED_ENUM = 16,
TCOD_CHAR_ARROW2_W TCOD_DEPRECATED_ENUM = 17,
/* double arrows */
TCOD_CHAR_DARROW_H TCOD_DEPRECATED_ENUM = 29,
TCOD_CHAR_DARROW_V TCOD_DEPRECATED_ENUM = 18,
/* GUI stuff */
TCOD_CHAR_CHECKBOX_UNSET TCOD_DEPRECATED_ENUM = 224,
TCOD_CHAR_CHECKBOX_SET TCOD_DEPRECATED_ENUM = 225,
TCOD_CHAR_RADIO_UNSET TCOD_DEPRECATED_ENUM = 9,
TCOD_CHAR_RADIO_SET TCOD_DEPRECATED_ENUM = 10,
/* sub-pixel resolution kit */
TCOD_CHAR_SUBP_NW TCOD_DEPRECATED_ENUM = 226,
TCOD_CHAR_SUBP_NE TCOD_DEPRECATED_ENUM = 227,
TCOD_CHAR_SUBP_N TCOD_DEPRECATED_ENUM = 228,
TCOD_CHAR_SUBP_SE TCOD_DEPRECATED_ENUM = 229,
TCOD_CHAR_SUBP_DIAG TCOD_DEPRECATED_ENUM = 230,
TCOD_CHAR_SUBP_E TCOD_DEPRECATED_ENUM = 231,
TCOD_CHAR_SUBP_SW TCOD_DEPRECATED_ENUM = 232,
/* miscellaneous */
TCOD_CHAR_SMILIE TCOD_DEPRECATED_ENUM = 1,
TCOD_CHAR_SMILIE_INV TCOD_DEPRECATED_ENUM = 2,
TCOD_CHAR_HEART TCOD_DEPRECATED_ENUM = 3,
TCOD_CHAR_DIAMOND TCOD_DEPRECATED_ENUM = 4,
TCOD_CHAR_CLUB TCOD_DEPRECATED_ENUM = 5,
TCOD_CHAR_SPADE TCOD_DEPRECATED_ENUM = 6,
TCOD_CHAR_BULLET TCOD_DEPRECATED_ENUM = 7,
TCOD_CHAR_BULLET_INV TCOD_DEPRECATED_ENUM = 8,
TCOD_CHAR_MALE TCOD_DEPRECATED_ENUM = 11,
TCOD_CHAR_FEMALE TCOD_DEPRECATED_ENUM = 12,
TCOD_CHAR_NOTE TCOD_DEPRECATED_ENUM = 13,
TCOD_CHAR_NOTE_DOUBLE TCOD_DEPRECATED_ENUM = 14,
TCOD_CHAR_LIGHT TCOD_DEPRECATED_ENUM = 15,
TCOD_CHAR_EXCLAM_DOUBLE TCOD_DEPRECATED_ENUM = 19,
TCOD_CHAR_PILCROW TCOD_DEPRECATED_ENUM = 20,
TCOD_CHAR_SECTION TCOD_DEPRECATED_ENUM = 21,
TCOD_CHAR_POUND TCOD_DEPRECATED_ENUM = 156,
TCOD_CHAR_MULTIPLICATION TCOD_DEPRECATED_ENUM = 158,
TCOD_CHAR_FUNCTION TCOD_DEPRECATED_ENUM = 159,
TCOD_CHAR_RESERVED TCOD_DEPRECATED_ENUM = 169,
TCOD_CHAR_HALF TCOD_DEPRECATED_ENUM = 171,
TCOD_CHAR_ONE_QUARTER TCOD_DEPRECATED_ENUM = 172,
TCOD_CHAR_COPYRIGHT TCOD_DEPRECATED_ENUM = 184,
TCOD_CHAR_CENT TCOD_DEPRECATED_ENUM = 189,
TCOD_CHAR_YEN TCOD_DEPRECATED_ENUM = 190,
TCOD_CHAR_CURRENCY TCOD_DEPRECATED_ENUM = 207,
TCOD_CHAR_THREE_QUARTERS TCOD_DEPRECATED_ENUM = 243,
TCOD_CHAR_DIVISION TCOD_DEPRECATED_ENUM = 246,
TCOD_CHAR_GRADE TCOD_DEPRECATED_ENUM = 248,
TCOD_CHAR_UMLAUT TCOD_DEPRECATED_ENUM = 249,
TCOD_CHAR_POW1 TCOD_DEPRECATED_ENUM = 251,
TCOD_CHAR_POW3 TCOD_DEPRECATED_ENUM = 252,
TCOD_CHAR_POW2 TCOD_DEPRECATED_ENUM = 253,
TCOD_CHAR_BULLET_SQUARE TCOD_DEPRECATED_ENUM = 254,
/* diacritics */
} TCOD_chars_t TCOD_DEPRECATED_ENUM;
#if defined(_MSC_VER) && !defined(__clang__)
#pragma deprecated(TCOD_CHAR_HLINE)
#pragma deprecated(TCOD_CHAR_VLINE)
#pragma deprecated(TCOD_CHAR_NE)
#pragma deprecated(TCOD_CHAR_NW)
#pragma deprecated(TCOD_CHAR_SE)
#pragma deprecated(TCOD_CHAR_SW)
#pragma deprecated(TCOD_CHAR_TEEW)
#pragma deprecated(TCOD_CHAR_TEEE)
#pragma deprecated(TCOD_CHAR_TEEN)
#pragma deprecated(TCOD_CHAR_TEES)
#pragma deprecated(TCOD_CHAR_CROSS)
#pragma deprecated(TCOD_CHAR_DHLINE)
#pragma deprecated(TCOD_CHAR_DVLINE)
#pragma deprecated(TCOD_CHAR_DNE)
#pragma deprecated(TCOD_CHAR_DNW)
#pragma deprecated(TCOD_CHAR_DSE)
#pragma deprecated(TCOD_CHAR_DSW)
#pragma deprecated(TCOD_CHAR_DTEEW)
#pragma deprecated(TCOD_CHAR_DTEEE)
#pragma deprecated(TCOD_CHAR_DTEEN)
#pragma deprecated(TCOD_CHAR_DTEES)
#pragma deprecated(TCOD_CHAR_DCROSS)
#pragma deprecated(TCOD_CHAR_BLOCK1)
#pragma deprecated(TCOD_CHAR_BLOCK2)
#pragma deprecated(TCOD_CHAR_BLOCK3)
#pragma deprecated(TCOD_CHAR_ARROW_N)
#pragma deprecated(TCOD_CHAR_ARROW_S)
#pragma deprecated(TCOD_CHAR_ARROW_E)
#pragma deprecated(TCOD_CHAR_ARROW_W)
#pragma deprecated(TCOD_CHAR_ARROW2_N)
#pragma deprecated(TCOD_CHAR_ARROW2_S)
#pragma deprecated(TCOD_CHAR_ARROW2_E)
#pragma deprecated(TCOD_CHAR_ARROW2_W)
#pragma deprecated(TCOD_CHAR_DARROW_H)
#pragma deprecated(TCOD_CHAR_DARROW_V)
#pragma deprecated(TCOD_CHAR_CHECKBOX_UNSET)
#pragma deprecated(TCOD_CHAR_CHECKBOX_SET)
#pragma deprecated(TCOD_CHAR_RADIO_UNSET)
#pragma deprecated(TCOD_CHAR_RADIO_SET)
#pragma deprecated(TCOD_CHAR_SUBP_NW)
#pragma deprecated(TCOD_CHAR_SUBP_NE)
#pragma deprecated(TCOD_CHAR_SUBP_N)
#pragma deprecated(TCOD_CHAR_SUBP_SE)
#pragma deprecated(TCOD_CHAR_SUBP_DIAG)
#pragma deprecated(TCOD_CHAR_SUBP_E)
#pragma deprecated(TCOD_CHAR_SUBP_SW)
#pragma deprecated(TCOD_CHAR_SMILIE)
#pragma deprecated(TCOD_CHAR_SMILIE_INV)
#pragma deprecated(TCOD_CHAR_HEART)
#pragma deprecated(TCOD_CHAR_DIAMOND)
#pragma deprecated(TCOD_CHAR_CLUB)
#pragma deprecated(TCOD_CHAR_SPADE)
#pragma deprecated(TCOD_CHAR_BULLET)
#pragma deprecated(TCOD_CHAR_BULLET_INV)
#pragma deprecated(TCOD_CHAR_MALE)
#pragma deprecated(TCOD_CHAR_FEMALE)
#pragma deprecated(TCOD_CHAR_NOTE)
#pragma deprecated(TCOD_CHAR_NOTE_DOUBLE)
#pragma deprecated(TCOD_CHAR_LIGHT)
#pragma deprecated(TCOD_CHAR_EXCLAM_DOUBLE)
#pragma deprecated(TCOD_CHAR_PILCROW)
#pragma deprecated(TCOD_CHAR_SECTION)
#pragma deprecated(TCOD_CHAR_POUND)
#pragma deprecated(TCOD_CHAR_MULTIPLICATION)
#pragma deprecated(TCOD_CHAR_FUNCTION)
#pragma deprecated(TCOD_CHAR_RESERVED)
#pragma deprecated(TCOD_CHAR_HALF)
#pragma deprecated(TCOD_CHAR_ONE_QUARTER)
#pragma deprecated(TCOD_CHAR_COPYRIGHT)
#pragma deprecated(TCOD_CHAR_CENT)
#pragma deprecated(TCOD_CHAR_YEN)
#pragma deprecated(TCOD_CHAR_CURRENCY)
#pragma deprecated(TCOD_CHAR_THREE_QUARTERS)
#pragma deprecated(TCOD_CHAR_DIVISION)
#pragma deprecated(TCOD_CHAR_GRADE)
#pragma deprecated(TCOD_CHAR_UMLAUT)
#pragma deprecated(TCOD_CHAR_POW1)
#pragma deprecated(TCOD_CHAR_POW3)
#pragma deprecated(TCOD_CHAR_POW2)
#pragma deprecated(TCOD_CHAR_BULLET_SQUARE)
#endif // _MSC_VER
typedef enum {
TCOD_KEY_PRESSED = 1,
TCOD_KEY_RELEASED = 2,
} TCOD_key_status_t;
/**
* These font flags can be OR'd together into a bit-field and passed to
* TCOD_console_set_custom_font
*/
typedef enum {
/** Tiles are arranged in column-major order.
*
* 0 3 6
* 1 4 7
* 2 5 8
*/
TCOD_FONT_LAYOUT_ASCII_INCOL = 1,
/** Tiles are arranged in row-major order.
*
* 0 1 2
* 3 4 5
* 6 7 8
*/
TCOD_FONT_LAYOUT_ASCII_INROW = 2,
/** Converts all tiles into a monochrome gradient. */
TCOD_FONT_TYPE_GREYSCALE = 4,
TCOD_FONT_TYPE_GRAYSCALE = 4,
/** A unique layout used by some of libtcod's fonts. */
TCOD_FONT_LAYOUT_TCOD = 8,
/**
* Decode a code page 437 tileset into Unicode code-points.
* \rst
* .. versionadded:: 1.10
* \endrst
*/
TCOD_FONT_LAYOUT_CP437 = 16,
} TCOD_font_flags_t;
/***************************************************************************
@brief Libtcod rendering modes.
*/
typedef enum TCOD_renderer_t {
/***************************************************************************
@brief Alias for TCOD_RENDERER_OPENGL2.
*/
TCOD_RENDERER_GLSL,
/***************************************************************************
An OpenGL 1.1 implementation.
Performs worse than TCOD_RENDERER_GLSL without many benefits.
\rst
.. deprecated:: 1.23
This renderer has been removed.
\endrst
*/
TCOD_RENDERER_OPENGL,
/***************************************************************************
A software based renderer.
The font file is loaded into RAM instead of VRAM in this implementation.
\rst
.. deprecated:: 1.23
This renderer has been removed.
\endrst
*/
TCOD_RENDERER_SDL,
/***************************************************************************
A new SDL2 renderer. Allows the window to be resized.
You may set `SDL_HINT_RENDER_SCALE_QUALITY` to determine the tileset
upscaling filter. Either nearest or linear. The hint will only take
effect if it's set before this renderer is created.
\rst
.. versionadded:: 1.8
\endrst
*/
TCOD_RENDERER_SDL2,
/***************************************************************************
A new OpenGL 2.0 core renderer. Allows the window to be resized.
You may set `SDL_HINT_RENDER_SCALE_QUALITY` to determine the tileset
upscaling filter. Either nearest or linear. The hint will take effect
on the next frame.
\rst
.. versionadded:: 1.9
.. versionchanged:: 1.11
This renderer now uses OpenGL 2.0 instead of 2.1.
.. versionchanged:: 1.16
Now checks the `SDL_HINT_RENDER_SCALE_QUALITY` hint.
.. deprecated:: 1.23
This renderer has been removed.
\endrst
*/
TCOD_RENDERER_OPENGL2,
/***************************************************************************
@brief A renderer targeting modern XTerm terminals with 24-bit color support.
This is an experimental renderer with partial support for XTerm and SSH.
This will work best on those terminals.
Terminal inputs and events will be passed to SDL's event system.
There is poor support for ANSI escapes on Windows 10.
It is not recommended to use this renderer on Windows.
\rst
.. versionadded:: 1.20
\endrst
*/
TCOD_RENDERER_XTERM,
TCOD_NB_RENDERERS,
} TCOD_renderer_t;
#endif // TCOD_CONSOLE_TYPES_H_

View file

@ -0,0 +1,294 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_CONSOLE_TYPES_HPP_
#define TCOD_CONSOLE_TYPES_HPP_
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include "console.h"
namespace tcod {
struct ConsoleDeleter {
void operator()(TCOD_Console* console) const { TCOD_console_delete(console); }
};
/***************************************************************************
@brief A unique pointer to a TCOD_Console.
\rst
.. versionadded:: 1.19
\endrst
*/
typedef std::unique_ptr<struct TCOD_Console, ConsoleDeleter> ConsolePtr;
/***************************************************************************
@brief A managed libtcod console containing a grid of tiles with `{ch, fg, bg}` information.
@details Note that all tile references are to TCOD_ConsoleTile structs and will include an alpha channel.
@code{.cpp}
auto console = tcod::Console{80, 50};
console.at({1, 1}).ch = '@'; // Bounds-checked references to a tile.
console[{1, 1}].bg = {0, 0, 255, 255}; // Access a tile without bounds checking, colors are RGBA.
if (console.in_bounds({100, 100})) {} // Test if an index is in bounds.
for (auto& tile : console) tile.fg = {255, 255, 0, 255}; // Iterate over all tiles on a console.
for (auto& tile : console) tile = {0x20, {255, 255, 255, 255}, {0, 0, 0, 255}}; // Same as clearing all tiles.
for (int y = 0; y < console.get_height(); ++y) {
for (int x = 0; x < console.get_width(); ++x) {
auto& tile = console.at({x, y}); // Iterate over the coordinates of a console.
}
}
@endcode
\rst
.. versionadded:: 1.19
\endrst
*/
class Console {
public:
/***************************************************************************
@brief Default initializer.
*/
Console() : Console{0, 0} {}
/***************************************************************************
@brief Create a new Console with the given size.
@param width The number of columns in the new console.
@param height The number of rows in the new console.
*/
explicit Console(int width, int height) : console_(TCOD_console_new(width, height)) {
if (!console_) throw std::runtime_error(TCOD_get_error());
}
/***************************************************************************
@brief Create a new Console with the given size.
@param size The new console size of `{width, height}`.
*/
explicit Console(const std::array<int, 2>& size) : Console{size[0], size[1]} {}
/***************************************************************************
@brief Clone the shape and tile data of a Console.
*/
explicit Console(const Console& other) : Console{other.console_->w, other.console_->h} {
std::copy(other.console_->begin(), other.console_->end(), console_->begin());
}
/***************************************************************************
@brief Pass ownership of a ConsolePtr to a new Console.
@param ptr A `tcod::ConsolePtr`, must not be nullptr.
*/
explicit Console(ConsolePtr ptr) : console_{std::move(ptr)} {
if (!console_) throw std::invalid_argument("Pointer must not be nullptr.");
}
/***************************************************************************
@brief Takes ownership of a raw TCOD_Console pointer.
@param ptr A pointer which will now be managed by this Console object. Must not be nullptr.
*/
explicit Console(TCOD_Console* ptr) : console_{ptr} {
if (!console_) throw std::invalid_argument("TCOD_Console pointer must not be nullptr.");
}
/***************************************************************************
@brief Copy the shape and tile data of another console.
*/
Console& operator=(const Console& rhs) {
if (console_->w != rhs.console_->w || console_->h != rhs.console_->h) {
*this = Console{{rhs.console_->w, rhs.console_->h}};
}
std::copy(rhs.console_->begin(), rhs.console_->end(), console_->begin());
return *this;
}
/***************************************************************************
@brief Standard move constructor.
*/
Console(Console&&) noexcept = default;
/***************************************************************************
@brief Standard move assignment.
*/
Console& operator=(Console&& rhs) noexcept {
swap(*this, rhs);
return *this;
}
/***************************************************************************
@brief Standard destructor.
*/
~Console() noexcept = default;
/***************************************************************************
@brief Swap two console objects.
*/
friend void swap(Console& lhs, Console& rhs) noexcept {
using std::swap;
swap(lhs.console_, rhs.console_);
}
/***************************************************************************
@brief Allow implicit conversions to a TCOD_Console reference.
*/
[[nodiscard]] operator TCOD_Console&() { return *console_; }
/***************************************************************************
@brief Allow implicit conversions to a const TCOD_Console reference.
*/
[[nodiscard]] operator const TCOD_Console&() const { return *console_; }
/***************************************************************************
@brief Return a pointer to the internal TCOD_Console struct.
*/
[[nodiscard]] auto get() noexcept -> TCOD_Console* { return console_.get(); }
/***************************************************************************
@brief Return a const pointer to the internal TCOD_Console struct.
*/
[[nodiscard]] auto get() const noexcept -> const TCOD_Console* { return console_.get(); }
/***************************************************************************
@brief Release ownership of this Console's `TCOD_Console*` and return the pointer.
Using this Console afterwards is undefined.
*/
auto release() noexcept -> TCOD_Console* { return console_.release(); }
/***************************************************************************
@brief Return a pointer to the beginning of this consoles tile data.
*/
[[nodiscard]] auto begin() noexcept -> TCOD_ConsoleTile* { return console_->tiles; }
/***************************************************************************
@brief Return a const pointer to the beginning of this consoles tile data.
*/
[[nodiscard]] auto begin() const noexcept -> const TCOD_ConsoleTile* { return console_->tiles; }
/***************************************************************************
@brief Return a pointer to the end of this consoles tile data.
*/
[[nodiscard]] auto end() noexcept -> TCOD_ConsoleTile* { return console_->tiles + console_->elements; }
/***************************************************************************
@brief Return a const pointer to the end of this consoles tile data.
*/
[[nodiscard]] auto end() const noexcept -> const TCOD_ConsoleTile* { return console_->tiles + console_->elements; }
/***************************************************************************
@brief Return the width of this console.
*/
[[nodiscard]] auto get_width() const noexcept -> int { return console_->w; }
/***************************************************************************
@brief Return the height of this console.
*/
[[nodiscard]] auto get_height() const noexcept -> int { return console_->h; }
/***************************************************************************
@brief Return the `{width, height}` shape of this console as a `std::array<int, 2>`.
@details
@code{.cpp}
auto console = tcod::Console{80, 50};
auto same_size = tcod::Console{console.get_shape()} // New console with the same shape of the previous one.
@endcode
*/
[[nodiscard]] auto get_shape() const noexcept -> std::array<int, 2> { return {console_->w, console_->h}; }
/***************************************************************************
@brief Clear a console by setting all tiles to the provided TCOD_ConsoleTile object.
@param tile A TCOD_ConsoleTile reference which will be used to clear the console.
@details
@code{.cpp}
// New consoles start already cleared with the space character, a white foreground, and a black background.
auto console = tcod::Console{80, 50};
console.clear() // Clear with the above mentioned defaults.
console.clear({0x20, {255, 255, 255, 255}, {0, 0, 0, 255}}); // Same as the above.
console.clear({0x20, tcod::ColorRGB{255, 255, 255}, tcod::ColorRGB{0, 0, 0}}) // Also same as the above.
@endcode
*/
void clear(const TCOD_ConsoleTile& tile = {0x20, {255, 255, 255, 255}, {0, 0, 0, 255}}) noexcept {
for (auto& it : *this) it = tile;
}
/***************************************************************************
@brief Return a reference to the tile at `xy`.
*/
[[nodiscard]] auto operator[](const std::array<int, 2>& xy) noexcept -> TCOD_ConsoleTile& {
return console_->tiles[get_index(xy)];
}
/***************************************************************************
@brief Return a constant reference to the tile at `xy`.
*/
[[nodiscard]] auto operator[](const std::array<int, 2>& xy) const noexcept -> const TCOD_ConsoleTile& {
return console_->tiles[get_index(xy)];
}
/***************************************************************************
@brief Return a reference to the tile at `xy`.
@throws std::out_of_range if the index is out-of-bounds
*/
[[nodiscard]] auto at(const std::array<int, 2>& xy) -> TCOD_ConsoleTile& { return console_->tiles[bounds_check(xy)]; }
/***************************************************************************
@brief Return a constant reference to the tile at `xy`.
@throws std::out_of_range if the index is out-of-bounds
*/
[[nodiscard]] auto at(const std::array<int, 2>& xy) const -> const TCOD_ConsoleTile& {
return console_->tiles[bounds_check(xy)];
}
/***************************************************************************
@brief Return a reference to the tile at `x`,`y`.
@throws std::out_of_range if the index is out-of-bounds
*/
[[nodiscard]] auto at(int x, int y) -> TCOD_ConsoleTile& { return at({x, y}); }
/***************************************************************************
@brief Return a constant reference to the tile at `x`,`y`.
@throws std::out_of_range if the index is out-of-bounds
*/
[[nodiscard]] auto at(int x, int y) const -> const TCOD_ConsoleTile& { return at({x, y}); }
/***************************************************************************
@brief Return true if `xy` are within the bounds of this console.
*/
[[nodiscard]] bool in_bounds(const std::array<int, 2>& xy) const noexcept { return console_->in_bounds(xy); }
private:
/***************************************************************************
@brief Checks if `xy` is in bounds then return an in-bounds index.
@throws std::out_of_range if `xy` is out-of-bounds
*/
auto bounds_check(const std::array<int, 2>& xy) const -> int {
if (!in_bounds(xy)) {
throw std::out_of_range(
std::string("Out of bounds lookup {") + std::to_string(xy[0]) + ", " + std::to_string(xy[1]) +
"} on console of shape {" + std::to_string(console_->w) + ", " + std::to_string(console_->h) + "}.");
}
return get_index(xy);
}
/***************************************************************************
@brief Convert `xy` into a 1-dimensional index.
@details This index is normally used to index the tiles attribute.
*/
[[nodiscard]] auto get_index(const std::array<int, 2>& xy) const noexcept -> int {
return console_->w * xy[1] + xy[0];
}
ConsolePtr console_ = nullptr; // The owned TCOD_Console pointer.
};
} // namespace tcod
#endif // TCOD_CONSOLE_TYPES_HPP_

View file

@ -0,0 +1,587 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_CONTEXT_H_
#define LIBTCOD_CONTEXT_H_
#ifdef __cplusplus
#include <algorithm>
#include <array>
#include <memory>
#include <stdexcept>
#include "console_types.hpp"
#include "error.hpp"
#endif // __cplusplus
#include "config.h"
#include "console.h"
#include "context_viewport.h"
#include "error.h"
#include "tileset.h"
struct SDL_Window;
struct SDL_Renderer;
struct SDL_Rect;
union SDL_Event;
struct TCOD_Context; // Defined in this header later.
typedef struct TCOD_Context TCOD_Context;
/**
A struct of parameters used to create a new context with `TCOD_context_new`.
\rst
.. versionadded:: 1.19
\endrst
*/
typedef struct TCOD_ContextParams {
/**
Must be `TCOD_COMPILEDVERSION`.
*/
int tcod_version;
/**
`window_x` and `window_y` are the starting position of the window.
These are SDL parameters so values like `SDL_WINDOWPOS_UNDEFINED` and
`SDL_WINDOWPOS_CENTERED` are acceptable.
Values of zero will be converted to `SDL_WINDOWPOS_UNDEFINED` unless
`window_xy_defined` is true.
*/
int window_x, window_y;
/**
`pixel_width` and `pixel_height` are the desired size of the window in pixels.
If these are zero then they'll be derived from `columns`, `rows`, and the `tileset`.
*/
int pixel_width, pixel_height;
/**
`columns` and `rows` are the desired size of the terminal window.
Usually you'll set either these or the pixel resolution.
If you are setting these values from a TCOD_Console then you should set the console attribute instead.
*/
int columns, rows;
/**
`renderer_type` is one of the `TCOD_renderer_t` values.
*/
int renderer_type;
/**
`tileset` is an optional pointer to a tileset object.
If this is NULL then a platform specific fallback tileset will be used.
This fallback is known to be unreliable, but it should work well enough
for prototyping code.
*/
TCOD_Tileset* tileset;
/**
If `vsync` is true, then vertical sync will be enabled whenever possible.
A value of true is recommended.
*/
int vsync;
/**
`sdl_window_flags` is a bitfield of SDL_WindowFlags flags.
For a window, a value of ``SDL_WINDOW_RESIZABLE`` is recommended.
For fullscreen, a value of
``SDL_WINDOW_RESIZABLE | SDL_WINDOW_FULLSCREEN_DESKTOP`` is recommended.
You should avoid the ``SDL_WINDOW_FULLSCREEN`` flag whenever possible.
*/
int sdl_window_flags;
/**
`window_title` will be the title of the opened window.
If not set then `argv[0]` will be used if available.
*/
const char* window_title;
/**
The number of items in `argv`.
*/
int argc;
/**
`argc` and `argv` are optional CLI parameters.
You can pass `0` and `NULL` respectfully to ignore them.
If unsure then you should pass the `argc` and `argv` arguments from your
`main` function.
*/
const char* const* argv;
/**
If user attention is required for the given CLI parameters then
`cli_output` will be called with `cli_userdata` and an error or help
message.
If `cli_output` is NULL then it will print the message to stdout and
terminate the program. If `cli_output` returns normally then
TCOD_E_REQUIRES_ATTENTION will be returned from `TCOD_context_new`.
*/
void (*cli_output)(void* userdata, const char* output);
/**
This is passed to the `userdata` parameter of `cli_output` if called.
*/
void* cli_userdata;
/**
If this is false then `window_x`/`window_y` parameters of zero are
assumed to be undefined and will be changed to `SDL_WINDOWPOS_UNDEFINED`.
*/
bool window_xy_defined;
/***************************************************************************
@brief A console to be used as a reference for the desired window size.
This can set as an alternative to the columns and rows attributes.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_Console* console;
} TCOD_ContextParams;
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
* Delete a rendering context.
* \rst
* .. versionadded:: 1.16
* \endrst
*/
TCOD_PUBLIC void TCOD_context_delete(struct TCOD_Context* renderer);
/**
* Create an uninitialized rendering context.
*
* Used internally.
*/
TCOD_NODISCARD struct TCOD_Context* TCOD_context_new_(void);
/**
Present a console to the screen, using a rendering context.
`console` is the console to present, the console can be any size.
`viewport` is the optional viewport options to use.
This will affect the scaling of the console with the current context.
This can be NULL to use the default options, which are to stretch the
console to fit the screen.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_context_present(
struct TCOD_Context* context, const struct TCOD_Console* console, const struct TCOD_ViewportOptions* viewport);
/**
Convert the screen coordinates to tile coordinates for this context.
`x` and `y` are the pointers to the screen coordinates, these will be
converted to tile coordinates after the call to this function.
The parameters given to the last call to `TCOD_context_present` will
determine where the tiles are for this call.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_context_screen_pixel_to_tile_d(struct TCOD_Context* context, double* x, double* y);
/**
Convert the screen coordinates to integer tile coordinates for this context.
Save as `TCOD_context_screen_pixel_to_tile` but the inputs and results are
integers. This is useful if you don't need sub-tile coordinates.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_context_screen_pixel_to_tile_i(struct TCOD_Context* context, int* x, int* y);
/**
Convert the pixel coordinates of SDL mouse events to the tile coordinates of the current context.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_context_convert_event_coordinates(struct TCOD_Context* context, union SDL_Event* event);
/**
Save the last presented console to a PNG file.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_context_save_screenshot(struct TCOD_Context* context, const char* filename);
/**
Return a pointer the SDL_Window for this context if it uses one.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC struct SDL_Window* TCOD_context_get_sdl_window(struct TCOD_Context* context);
/**
Return a pointer the SDL_Renderer for this context if it uses one.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC struct SDL_Renderer* TCOD_context_get_sdl_renderer(struct TCOD_Context* context);
/**
Change the active tileset for this context.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_context_change_tileset(struct TCOD_Context* self, TCOD_Tileset* tileset);
/**
Return the `TCOD_renderer_t` renderer type for this context.
Returns a negative number on error, such as `context` being NULL.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC int TCOD_context_get_renderer_type(struct TCOD_Context* context);
/**
Set `columns` and `rows` to the recommended console size for this context.
`magnification` determines the apparent size of the tiles on the output.
Values of 0.0f or lower will default to 1.0f.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_context_recommended_console_size(
struct TCOD_Context* context, float magnification, int* __restrict columns, int* __restrict rows);
/***************************************************************************
@brief Fill `out_pixels` with a screen capture.
@param context A non-NULL TCOD_Context object.
@param out_pixels If NULL then width and height are filled with the output dimensions.
If not NULL then width and height are verified and the capture will be written out.
@param width Pointer to fill with the expected image width.
@param height Pointer to fill with the expected image height.
@return A negative error value is returned on errors, otherwise returns TCOD_E_OK.
\rst
.. versionadded:: 1.22
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_context_screen_capture(
struct TCOD_Context* __restrict context,
TCOD_ColorRGBA* __restrict out_pixels,
int* __restrict width,
int* __restrict height);
/***************************************************************************
@brief Allocate and return a screen capture. The returned array must be freed with `free()`.
@param context A non-NULL TCOD_Context object.
@param width Pointer to fill with the allocated image width.
@param height Pointer to fill with the allocated image height.
@return An allocated array of RGBA pixels which must be manually freed.
\rst
.. versionadded:: 1.22
\endrst
*/
TCOD_NODISCARD
TCOD_PUBLIC TCOD_ColorRGBA* TCOD_context_screen_capture_alloc(
struct TCOD_Context* __restrict context, int* __restrict width, int* __restrict height);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
/**
A rendering context for libtcod.
\rst
.. versionadded:: 1.16
\endrst
*/
struct TCOD_Context {
#ifdef __cplusplus
/**
Return the TCOD_renderer_t value of this context which may be different
than the one requested.
*/
[[deprecated(
"TCOD_Context methods have been moved to tcod::Context,"
" use `auto context = tcod::Context(params);` to make a tcod context for C++.")]] auto
get_renderer_type() noexcept -> int {
return TCOD_context_get_renderer_type(this);
}
/***************************************************************************
@brief Present a console to the display with the provided viewport options.
@param console The TCOD_Console to render. This console can be any size.
@param viewport The viewport options, which can change the way the console is scaled.
\rst
.. deprecated:: 1.21
Replace ``tcod::new_console(params)`` with ``tcod::Context(params)`` to get a C++ context.
\endrst
*/
[[deprecated(
"TCOD_Context methods have been moved to tcod::Context,"
" use `auto context = tcod::Context(params);` to make a tcod context for C++.")]] void
present(const TCOD_Console& console, const TCOD_ViewportOptions& viewport) {
tcod::check_throw_error(TCOD_context_present(this, &console, &viewport));
}
/***************************************************************************
@brief Present a console to the display.
@param console The TCOD_Console to render. This console can be any size and will be stretched to fit the window.
\rst
.. deprecated:: 1.21
Replace ``tcod::new_console(params)`` with ``tcod::Context(params)`` to get a C++ context.
\endrst
*/
[[deprecated(
"TCOD_Context methods have been moved to tcod::Context,"
" use `auto context = tcod::Context(params);` to make a tcod context for C++.")]] void
present(const TCOD_Console& console) {
tcod::check_throw_error(TCOD_context_present(this, &console, nullptr));
}
/***************************************************************************
@brief Return a non-owning pointer to the SDL_Window used by this context.
@return A ``struct SDL_Window*`` pointer. This will be nullptr if this context does not use an SDL window.
\rst
.. deprecated:: 1.21
Replace ``tcod::new_console(params)`` with ``tcod::Context(params)`` to get a C++ context.
\endrst
*/
[[deprecated(
"TCOD_Context methods have been moved to tcod::Context,"
" use `auto context = tcod::Context(params);` to make a tcod context for C++.")]] auto
get_sdl_window() noexcept -> struct SDL_Window* {
return TCOD_context_get_sdl_window(this);
}
/***************************************************************************
@brief Return a non-owning pointer to the SDL_Renderer used by this context.
@return A ``struct SDL_Renderer*`` pointer. This will be nullptr if this context does not use SDL's renderer.
\rst
.. deprecated:: 1.21
Replace ``tcod::new_console(params)`` with ``tcod::Context(params)`` to get a C++ context.
\endrst
*/
[[deprecated(
"TCOD_Context methods have been moved to tcod::Context,"
" use `auto context = tcod::Context(params);` to make a tcod context for C++.")]] auto
get_sdl_renderer() noexcept -> struct SDL_Renderer* {
return TCOD_context_get_sdl_renderer(this);
}
/**
Convert pixel coordinates to this contexts integer tile coordinates.
\rst
.. deprecated:: 1.21
Replace ``tcod::new_console(params)`` with ``tcod::Context(params)`` to get a C++ context.
\endrst
*/
[[deprecated(
"TCOD_Context methods have been moved to tcod::Context,"
" use `auto context = tcod::Context(params);` to make a tcod context for C++.")]] auto
pixel_to_tile_coordinates(const std::array<int, 2>& xy) -> std::array<int, 2> {
std::array<int, 2> out{xy[0], xy[1]};
tcod::check_throw_error(TCOD_context_screen_pixel_to_tile_i(this, &out[0], &out[1]));
return out;
}
/**
Convert pixel coordinates to this contexts sub-tile coordinates.
\rst
.. deprecated:: 1.21
Replace ``tcod::new_console(params)`` with ``tcod::Context(params)`` to get a C++ context.
\endrst
*/
[[deprecated(
"TCOD_Context methods have been moved to tcod::Context,"
" use `auto context = tcod::Context(params);` to make a tcod context for C++.")]] auto
pixel_to_tile_coordinates(const std::array<double, 2>& xy) -> std::array<double, 2> {
std::array<double, 2> out{xy[0], xy[1]};
tcod::check_throw_error(TCOD_context_screen_pixel_to_tile_d(this, &out[0], &out[1]));
return out;
}
/***************************************************************************
@brief Convert the pixel coordinates of SDL mouse events to the tile coordinates of the current context.
@param event Any SDL_Event event.
If the event type is compatible then its coordinates will be converted into tile coordinates.
\rst
.. versionadded:: 1.19
.. deprecated:: 1.21
Replace ``tcod::new_console(params)`` with ``tcod::Context(params)`` to get a C++ context.
\endrst
*/
[[deprecated(
"TCOD_Context methods have been moved to tcod::Context,"
" use `auto context = tcod::Context(params);` to make a tcod context for C++.")]] void
convert_event_coordinates(SDL_Event& event) {
tcod::check_throw_error(TCOD_context_convert_event_coordinates(this, &event));
}
/***************************************************************************
@brief Save a screenshot to `filepath`.
@param filepath The file path to save the screenshot at.
If nullptr then a unique file name will be generated.
\rst
.. deprecated:: 1.21
Replace ``tcod::new_console(params)`` with ``tcod::Context(params)`` to get a C++ context.
\endrst
*/
[[deprecated(
"TCOD_Context methods have been moved to tcod::Context,"
" use `auto context = tcod::Context(params);` to make a tcod context for C++.")]] void
save_screenshot(const char* filepath) {
tcod::check_throw_error(TCOD_context_save_screenshot(this, filepath));
}
/***************************************************************************
@brief Save a screenshot to `filepath`.
@param filepath The file path to save the screenshot at.
\rst
.. deprecated:: 1.21
Replace ``tcod::new_console(params)`` with ``tcod::Context(params)`` to get a C++ context.
\endrst
*/
[[deprecated(
"TCOD_Context methods have been moved to tcod::Context,"
" use `auto context = tcod::Context(params);` to make a tcod context for C++.")]] void
save_screenshot(const std::string& filepath) {
tcod::check_throw_error(TCOD_context_save_screenshot(this, filepath.c_str()));
}
/***************************************************************************
@brief Return a new console with a size automatically determined by the context.
@param min_columns The minimum width to use for the new console, in tiles.
@param min_rows The minimum height to use for the new console, in tiles.
@param magnification Determines the apparent size of the tiles that will be rendered by a console created with
the output values.
A `magnification` larger then 1.0f will output smaller console parameters, which will show as larger tiles when
presented.
Only values larger than zero are allowed.
@return Returns a tcod::Console of a dynamic size.
\rst
.. deprecated:: 1.21
Replace ``tcod::new_console(params)`` with ``tcod::Context(params)`` to get a C++ context.
\endrst
*/
auto new_console(int min_columns = 1, int min_rows = 1, float magnification = 1.0f) -> tcod::Console {
int columns;
int rows;
if (magnification <= 0.0f) {
throw std::invalid_argument(
std::string("Magnification must be greater than zero. Got ") + std::to_string(magnification));
}
tcod::check_throw_error(TCOD_context_recommended_console_size(this, magnification, &columns, &rows));
return tcod::Console{std::max(columns, min_columns), std::max(rows, min_rows)};
}
#endif // __cplusplus
// All remaining members are private.
/**
The TCOD_renderer_t value of this context.
*/
int type;
/**
A pointer to this contexts unique data.
*/
void* __restrict contextdata_;
// Context C callback are prefixed with 'c_', always check if see if these are NULL.
/**
Called when this context is deleted.
*/
void (*c_destructor_)(struct TCOD_Context* __restrict self);
/**
Called to present a console to a contexts display.
`console` must not be NULL.
`viewport` may be NULL.
*/
TCOD_Error (*c_present_)(
struct TCOD_Context* __restrict self,
const struct TCOD_Console* __restrict console,
const struct TCOD_ViewportOptions* __restrict viewport);
/**
Convert pixel coordinates to the contexts tile coordinates.
*/
void (*c_pixel_to_tile_)(struct TCOD_Context* __restrict self, double* __restrict x, double* __restrict y);
/**
Ask this context to save a screenshot.
*/
TCOD_Error (*c_save_screenshot_)(struct TCOD_Context* __restrict self, const char* __restrict filename);
/**
Return this contexts SDL_Window, if any.
*/
struct SDL_Window* (*c_get_sdl_window_)(struct TCOD_Context* __restrict self);
/**
Return this contexts SDL_Renderer, if any.
*/
struct SDL_Renderer* (*c_get_sdl_renderer_)(struct TCOD_Context* __restrict self);
/**
Draw a console without flipping the display.
This method of drawing is deprecated.
*/
TCOD_Error (*c_accumulate_)(
struct TCOD_Context* __restrict self,
const struct TCOD_Console* __restrict console,
const struct TCOD_ViewportOptions* __restrict viewport);
/**
Change the tileset used by this context.
*/
TCOD_Error (*c_set_tileset_)(struct TCOD_Context* __restrict self, TCOD_Tileset* __restrict tileset);
/**
Output the recommended console size to `columns` and `rows`.
`magnification` determines the apparent size of tiles,
but might be ignored.
*/
TCOD_Error (*c_recommended_console_size_)(
struct TCOD_Context* __restrict self, float magnification, int* __restrict columns, int* __restrict rows);
/***************************************************************************
Fill `out_pixels` with a screen capture.
`width` and `height` will not be NULL.
`width` and `height` will be filled with the dimensions of the output if `out_pixels` is NULL.
If `out_pixels` is not NULL then `width` and `height` are verified before writing to `out_pixels`,
if verification fails then TCOD_E_INVALID_ARGUMENT must be returned.
*/
TCOD_Error (*c_screen_capture_)(
struct TCOD_Context* __restrict self,
TCOD_ColorRGBA* __restrict out_pixels,
int* __restrict width,
int* __restrict height);
};
#ifdef __cplusplus
namespace tcod {
struct ContextDeleter {
void operator()(TCOD_Context* console) const { TCOD_context_delete(console); }
};
typedef std::unique_ptr<TCOD_Context, ContextDeleter> ContextPtr;
typedef std::shared_ptr<TCOD_Context> ContextSharedPtr;
} // namespace tcod
#endif // __cplusplus
#endif // LIBTCOD_CONTEXT_H_

View file

@ -0,0 +1,295 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_CONTEXT_HPP_
#define LIBTCOD_CONTEXT_HPP_
#include <array>
#include <filesystem>
#include <stdexcept>
#include "config.h"
#include "console.h"
#include "context.h"
#include "context_init.h"
#include "context_viewport.h"
#include "error.hpp"
#include "tileset.hpp"
namespace tcod {
/***************************************************************************
@brief A C++ managed tcod context.
@details
\rst
See :ref:`getting-started` for complete examples of how to setup libtcod projects.
\endrst
@code{.cpp}
// The absolute minimum needed to create a new context in C++.
int main(int argc, char* argv[]) {
auto params = TCOD_ContextParams{};
params.tcod_version = TCOD_COMPILEDVERSION;
auto context = tcod::Context(params);
}
@endcode
\rst
.. versionadded:: 1.21
\endrst
*/
class Context {
public:
Context() = default;
/***************************************************************************
@brief Construct a new Context object using the provided parameters.
Requires SDL support enabled, otherwise this will throw.
*/
explicit Context(const TCOD_ContextParams& params) {
#ifndef NO_SDL
struct TCOD_Context* context = nullptr;
check_throw_error(TCOD_context_new(&params, &context));
context_ = ContextPtr{context};
#else
throw std::logic_error("Libtcod not compiled with SDL support, so it can not create its own context.");
#endif // NO_SDL
};
/// Take ownsership of a smart pointer to TCOD_Context.
explicit Context(ContextPtr&& ptr) : context_{std::move(ptr)} {}
/// Take ownsership of a raw TCOD_Context pointer.
explicit Context(TCOD_Context* ptr) : context_{ptr} {}
// Copy disabled, move allowed.
Context(const Context&) = delete;
Context& operator=(const Context&) = delete;
Context(Context&&) = default;
Context& operator=(Context&&) = default;
/***************************************************************************
@brief Return the TCOD_renderer_t value of this context which may be different than the one requested.
*/
[[nodiscard]] auto get_renderer_type() noexcept -> TCOD_renderer_t {
return static_cast<TCOD_renderer_t>(TCOD_context_get_renderer_type(context_.get()));
}
/***************************************************************************
@brief Present a console to the display with the provided viewport options.
@param console The TCOD_Console to render. This console can be any size.
@param viewport The viewport options, which can change the way the console is scaled.
@details
@code{.cpp}
// tcod::Context context;
while (1) {
auto console = context.new_console(); // This can be done as an alternative to clearing the console.
tcod::print(console, {0, 0}, "Hello world", nullptr, nullptr);
auto viewport_options = TCOD_ViewportOptions{}
viewport_options.tcod_version = TCOD_COMPILEDVERSION;
viewport_options.keep_aspect = true; // Adds letterboxing to keep aspect.
viewport_options.integer_scaling = true; // Prevent scaling artifacts with pixelated or low-res glyphs.
viewport_options.clear_color = {0, 0, 0, 255};
viewport_options.align_x = 0.5f;
viewport_options.align_y = 0.5f;
context.present(console, viewport_options);
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) std::exit(EXIT_SUCCESS);
}
}
@endcode
*/
void present(const TCOD_Console& console, const TCOD_ViewportOptions& viewport) {
tcod::check_throw_error(TCOD_context_present(context_.get(), &console, &viewport));
}
/***************************************************************************
@brief Present a console to the display.
@param console The TCOD_Console to render. This console can be any size and will be stretched to fit the window.
*/
void present(const TCOD_Console& console) {
tcod::check_throw_error(TCOD_context_present(context_.get(), &console, nullptr));
}
/***************************************************************************
@brief Return a non-owning pointer to the SDL_Window used by this context.
@return A ``struct SDL_Window*`` pointer. This will be nullptr if this context does not use an SDL window.
@details
@code{.cpp}
// tcod::Context context;
if (SDL_Window* sdl_window = context.get_sdl_window(); sdl_window) {
// Do anything with an SDL window, for example:
uint32_t flags = SDL_GetWindowFlags(sdl_window);
}
@endcode
*/
[[nodiscard]] auto get_sdl_window() noexcept -> struct SDL_Window* {
return TCOD_context_get_sdl_window(context_.get());
}
/***************************************************************************
@brief Return a non-owning pointer to the SDL_Renderer used by this context.
@return A ``struct SDL_Renderer*`` pointer. This will be nullptr if this context does not use SDL's renderer.
@details
@code{.cpp}
// tcod::Context context;
if (SDL_Renderer* sdl_renderer = context.get_sdl_renderer(); sdl_renderer) {
// Do anything with an SDL renderer, for example:
SDL_SetRenderDrawColor(sdl_renderer, 0, 0, 0, 255);
SDL_RenderClear(sdl_renderer);
SDL_RenderPresent(sdl_renderer);
}
@endcode
*/
[[nodiscard]] auto get_sdl_renderer() noexcept -> struct SDL_Renderer* {
return TCOD_context_get_sdl_renderer(context_.get());
}
/***************************************************************************
@brief Convert pixel coordinates to this contexts integer tile coordinates.
*/
[[nodiscard]] auto pixel_to_tile_coordinates(const std::array<int, 2>& xy) -> std::array<int, 2> {
std::array<int, 2> out{xy[0], xy[1]};
tcod::check_throw_error(TCOD_context_screen_pixel_to_tile_i(context_.get(), &out[0], &out[1]));
return out;
}
/***************************************************************************
@brief Convert pixel coordinates to this contexts sub-tile coordinates.
*/
[[nodiscard]] auto pixel_to_tile_coordinates(const std::array<double, 2>& xy) -> std::array<double, 2> {
std::array<double, 2> out{xy[0], xy[1]};
tcod::check_throw_error(TCOD_context_screen_pixel_to_tile_d(context_.get(), &out[0], &out[1]));
return out;
}
/***************************************************************************
@brief Convert the pixel coordinates of SDL mouse events to the tile coordinates of the current context.
@param event Any SDL_Event event.
If the event type is compatible then its coordinates will be converted into tile coordinates.
@details
@code{.cpp}
// tcod::Context context;
while (1) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
SDL_Event event_tile = event; // A copy of `event` using tile coordinates.
context.convert_event_coordinates(event_tile);
switch (event.type) {
case SDL_QUIT:
std::exit(EXIT_SUCCESS);
case SDL_MOUSEMOTION:
event.motion.xrel; // Relative motion in pixels.
event_tile.motion.xrel; // Relative motion in tiles.
break;
}
}
}
@endcode
\rst
.. versionadded:: 1.19
\endrst
*/
void convert_event_coordinates(SDL_Event& event) {
tcod::check_throw_error(TCOD_context_convert_event_coordinates(context_.get(), &event));
}
/***************************************************************************
@brief Save a screenshot to `path`.
@param path The file path to save the screenshot to.
*/
void save_screenshot(const std::filesystem::path& path) {
tcod::check_throw_error(TCOD_context_save_screenshot(context_.get(), path.string().c_str()));
}
/***************************************************************************
@brief Save a screenshot with a unique filename in the working directly.
*/
void save_screenshot() { tcod::check_throw_error(TCOD_context_save_screenshot(context_.get(), nullptr)); }
/***************************************************************************
@brief Return a new console with a size automatically determined by the context.
@param min_columns The minimum width to use for the new console, in tiles.
@param min_rows The minimum height to use for the new console, in tiles.
@param magnification Determines the apparent size of the tiles that will be rendered by a console created with
the output values.
A `magnification` larger then 1.0f will output smaller console parameters, which will show as larger tiles when
presented.
Only values larger than zero are allowed.
@return Returns a tcod::Console of a dynamic size.
@details
@code{.cpp}
// tcod::Context context;
while (1) {
auto console = context.new_console(); // Can be an alternative to clearing the console.
tcod::print(console, {0, 0}, "Hello world", std::nullopt, std::nullopt);
context.present(console);
SDL_Event event;
while (SDL_PollEvent(&event)) { // SDL_PollEvent may resize the window.
if (event.type == SDL_QUIT) std::exit(EXIT_SUCCESS);
}
}
@endcode
*/
[[nodiscard]] auto new_console(int min_columns = 1, int min_rows = 1, float magnification = 1.0f) -> tcod::Console {
int columns;
int rows;
if (magnification <= 0.0f) {
throw std::invalid_argument(
std::string("Magnification must be greater than zero. Got ") + std::to_string(magnification));
}
tcod::check_throw_error(TCOD_context_recommended_console_size(context_.get(), magnification, &columns, &rows));
return tcod::Console{std::max(columns, min_columns), std::max(rows, min_rows)};
}
/***************************************************************************
@brief Replace this contexts tileset with a different one.
*/
auto change_tileset(tcod::Tileset& new_tileset) -> void {
check_throw_error(TCOD_context_change_tileset(context_.get(), new_tileset.get()));
}
/***************************************************************************
@brief Access the context pointer. Modifying this pointer may make the class invalid.
*/
[[nodiscard]] auto get_ptr() noexcept -> ContextPtr& { return context_; }
/***************************************************************************
@brief Access the const context pointer.
*/
[[nodiscard]] auto get_ptr() const noexcept -> const ContextPtr& { return context_; }
/***************************************************************************
@brief Close and delete the objects managed by this context. This object will no longer be valid unless reset.
*/
auto close() -> void { *this = Context(); }
private:
ContextPtr context_ = nullptr;
};
} // namespace tcod
#endif // LIBTCOD_CONTEXT_HPP_

View file

@ -0,0 +1,97 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_CONTEXT_INIT_H_
#define LIBTCOD_CONTEXT_INIT_H_
#include <stdbool.h>
#include "config.h"
#include "context.h"
#include "error.h"
#ifndef NO_SDL
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
Create a new context with the given parameters.
`params` is a non-NULL pointer to a TCOD_ContextParams struct.
See its documentation for info on the parameters.
`out` is the output for the `TCOD_Context`, must not be NULL.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_NODISCARD TCOD_Error TCOD_context_new(const TCOD_ContextParams* params, TCOD_Context** out);
#ifdef __cplusplus
} // extern "C"
namespace tcod {
/**
@brief Initialize and return a new libtcod context. Also returns an error code for non-critical issues.
@param params Options to configure the new context with.
@param out_code Will be set to an error code on non-critical issues.
@return ContextPtr A pointer to the new context.
For critical issues an exception is thrown as usual.
Non-critical issues are things such as being unable to create a desired renderer and using to a fallback instead.
\rst
.. versionadded:: 1.19
\endrst
*/
[[deprecated("This function has been replaced by `auto context = tcod::Context(params);`")]] TCOD_NODISCARD inline auto
new_context(const TCOD_ContextParams& params, TCOD_Error& out_code) -> ContextPtr {
struct TCOD_Context* context = nullptr;
out_code = check_throw_error(TCOD_context_new(&params, &context));
return ContextPtr{context};
}
/**
@brief Initialize and return a new libtcod context.
@param params Options to configure the new context with.
@return ContextPtr A pointer to the new context.
\rst
.. versionadded:: 1.19
\endrst
*/
[[deprecated("This function has been replaced by `auto context = tcod::Context(params);`")]] TCOD_NODISCARD inline auto
new_context(const TCOD_ContextParams& params) -> ContextPtr {
struct TCOD_Context* context = nullptr;
check_throw_error(TCOD_context_new(&params, &context));
return ContextPtr{context};
}
} // namespace tcod
#endif // __cplusplus
#endif // NO_SDL
#endif // LIBTCOD_CONTEXT_INIT_H_

View file

@ -0,0 +1,107 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_CONTEXT_VIEWPORT_H_
#define LIBTCOD_CONTEXT_VIEWPORT_H_
#include <stdbool.h>
#include "color.h"
/**
Viewport options for the rendering context.
\rst
.. versionadded:: 1.16
\endrst
*/
struct TCOD_ViewportOptions {
/**
Must be set to `TCOD_COMPILEDVERSION`.
*/
int tcod_version;
/**
If true then the aspect ratio will be kept square when the console is
scaled. The view will be letter-boxed.
If false the console will be stretched to fill the screen.
Set this is true if your tileset is deigned for square pixels.
*/
bool keep_aspect;
/**
If true then console scaling will be fixed to integer increments.
Has no effect if the console must be scaled down.
*/
bool integer_scaling;
/**
The color to clear the screen with before rendering the console.
*/
TCOD_ColorRGBA clear_color;
/**
Alignment of the console when it is letter-boxed: 0.0f renders the
console in the upper-left corner, and 1.0f in the lower-right.
Values of 0.5f will center the console.
Values outside of the range 0.0f to 1.0f are clamped.
*/
float align_x;
float align_y;
};
typedef struct TCOD_ViewportOptions TCOD_ViewportOptions;
/**
Default viewport options if none are provided.
*/
extern const struct TCOD_ViewportOptions TCOD_VIEWPORT_DEFAULT_;
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
Allocate a new viewport options struct.
You should not allocate this struct manually since the size of it may change
between versions.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_NODISCARD TCOD_ViewportOptions* TCOD_viewport_new(void);
/**
Delete a viewport.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC void TCOD_viewport_delete(TCOD_ViewportOptions* viewport);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // LIBTCOD_CONTEXT_VIEWPORT_H_

View file

@ -0,0 +1,132 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_ERROR_H_
#define LIBTCOD_ERROR_H_
#include "config.h"
#include "version.h"
/**
* An enum of libtcod error codes.
*
* On values other than `TCOD_E_OK` you can use `TCOD_get_error()` to learn
* more information.
* \rst
* .. versionadded:: 1.16
* \endrst
*/
typedef enum TCOD_Error {
/**
* The function completed successfully without issues.
*
* A function is successful when `(err >= 0)`. Positive values may be used
* for warnings, or for other outputs.
*/
TCOD_E_OK = 0,
/**
* The error code for generic runtime errors.
*
* The returned code my be changed in the future to something more specific.
* Use `(err < 0)` to check if the value is an error.
*/
TCOD_E_ERROR = -1,
/**
* The function failed because a given input argument was invalid.
*/
TCOD_E_INVALID_ARGUMENT = -2,
/**
* The function failed because it was unable to allocate enough memory.
*/
TCOD_E_OUT_OF_MEMORY = -3,
/**
This function needs additional attention, but is otherwise functioning
correctly. See its documentation.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_E_REQUIRES_ATTENTION = -4,
/**
* The function completed, but a minor issue was detected.
*/
TCOD_E_WARN = 1,
} TCOD_Error;
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/***************************************************************************
@brief Return the last error message. If there is no error then the string will have a length of zero.
\rst
.. versionadded:: 1.12
\endrst
*/
TCOD_NODISCARD
TCODLIB_API const char* TCOD_get_error(void);
/***************************************************************************
@brief Set an error message and return TCOD_E_ERROR.
\rst
.. versionadded:: 1.12
\endrst
*/
TCODLIB_API TCOD_Error TCOD_set_error(const char* msg);
/**
* Set an error message and return TCOD_E_ERROR.
* \rst
* .. versionadded:: 1.16
* \endrst
*/
TCODLIB_FORMAT(1, 2)
TCODLIB_API TCOD_Error TCOD_set_errorf(const char* fmt, ...);
/**
* Clear a current existing error message.
* \rst
* .. versionadded:: 1.16
* \endrst
*/
TCODLIB_API void TCOD_clear_error(void);
/**
* Set an error with version, file, and line info added to the output.
*
* Used internally.
*/
#define TCOD_set_errorv(msg) TCOD_set_errorf("%s:%i\n%s", TCOD_STRVERSIONNAME " " __FILE__, __LINE__, (msg))
/**
* Format an error with version, file, and line info added to the output.
*
* Used internally.
*/
#define TCOD_set_errorvf(fmt, ...) \
TCOD_set_errorf("%s:%i\n" fmt, TCOD_STRVERSIONNAME " " __FILE__, __LINE__, __VA_ARGS__)
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // LIBTCOD_ERROR_H_

View file

@ -0,0 +1,81 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_ERROR_HPP_
#define LIBTCOD_ERROR_HPP_
#include <exception>
#include <filesystem>
#include <stdexcept>
#include <string>
#include "error.h"
namespace tcod {
/**
* Set an error message and return a relevant error code, usually -1.
*
* Used internally.
*/
inline TCOD_Error set_error(const std::string& msg) { return TCOD_set_errorv(msg.c_str()); }
inline TCOD_Error set_error(const std::exception& e) { return TCOD_set_errorv(e.what()); }
/**
* Check and throw error messages.
*
* Used internally.
*/
inline int check_throw_error(int error) {
if (error >= 0) {
return error;
}
std::string error_msg = TCOD_get_error();
switch (error) {
case TCOD_E_ERROR:
default:
throw std::runtime_error(error_msg);
break;
case TCOD_E_INVALID_ARGUMENT:
throw std::invalid_argument(error_msg);
break;
}
}
inline TCOD_Error check_throw_error(TCOD_Error error) {
return static_cast<TCOD_Error>(check_throw_error(static_cast<int>(error)));
}
/**
* @brief Throw an exception if the given path does not exist. Used internally.
*/
inline void check_path(const std::filesystem::path& path) {
if (!std::filesystem::exists(path)) {
throw std::runtime_error(std::string("File not found:\n") + std::filesystem::absolute(path).string());
}
}
} // namespace tcod
#endif // LIBTCOD_ERROR_HPP_

View file

@ -0,0 +1,129 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_FOV_H
#define _TCOD_FOV_H
#include <stdbool.h>
#ifdef __cplusplus
#include <memory>
#endif // __cplusplus
#include "config.h"
#include "error.h"
#include "fov_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
Return a new TCOD_Map with `width` and `height`.
*/
TCOD_PUBLIC TCOD_Map* TCOD_map_new(int width, int height);
/**
Set all cell values on `map` to the given parameters.
This call also zeroes out the field-of-view attribute.
*/
TCOD_PUBLIC void TCOD_map_clear(TCOD_Map* map, bool transparent, bool walkable);
/**
Clone map data from `source` to `dest`.
`dest` will be resized to match `source` if necessary.
*/
TCOD_PUBLIC TCOD_Error TCOD_map_copy(const TCOD_Map* __restrict source, TCOD_Map* __restrict dest);
/**
Change the properties of a single cell.
*/
TCOD_PUBLIC void TCOD_map_set_properties(TCOD_Map* map, int x, int y, bool is_transparent, bool is_walkable);
/**
Free a TCOD_Map object.
*/
TCOD_PUBLIC void TCOD_map_delete(TCOD_Map* map);
/**
Calculate the field-of-view.
\rst
`pov_x` and `pov_y` are the used as the field-of-view source.
These coordinates must be within the map.
`max_radius` is the maximum distance for the field-of-view algorithm.
If `light_walls` is false then only transparent cells will be touched by
the field-of-view.
`algo` is one of the :any:`TCOD_fov_algorithm_t` algorithms.
After this call you may check if a cell is within the field-of-view by
calling :any:`TCOD_map_is_in_fov`.
Returns an error code on failure. See :any:`TCOD_get_error` for details.
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_map_compute_fov(
TCOD_Map* __restrict map, int pov_x, int pov_y, int max_radius, bool light_walls, TCOD_fov_algorithm_t algo);
/**
Return true if this cell was touched by the current field-of-view.
*/
TCOD_PUBLIC bool TCOD_map_is_in_fov(const TCOD_Map* map, int x, int y);
/**
Set the fov flag on a specific cell.
*/
TCOD_PUBLIC void TCOD_map_set_in_fov(TCOD_Map* map, int x, int y, bool fov);
/**
Return true if this cell is transparent.
*/
TCOD_PUBLIC bool TCOD_map_is_transparent(const TCOD_Map* map, int x, int y);
/**
Return true if this cell is walkable.
*/
TCOD_PUBLIC bool TCOD_map_is_walkable(TCOD_Map* map, int x, int y);
/**
Return the width of `map`.
*/
TCOD_PUBLIC int TCOD_map_get_width(const TCOD_Map* map);
/**
Return the height of `map`.
*/
TCOD_PUBLIC int TCOD_map_get_height(const TCOD_Map* map);
/**
Return the total number of cells in `map`.
*/
TCOD_PUBLIC int TCOD_map_get_nb_cells(const TCOD_Map* map);
#ifdef __cplusplus
} // extern "C"
namespace tcod {
struct MapDeleter_ {
void operator()(TCOD_Map* map) const { TCOD_map_delete(map); }
};
typedef std::unique_ptr<struct TCOD_Map, MapDeleter_> MapPtr_;
} // namespace tcod
#endif // __cplusplus
#endif // _TCOD_FOV_H

View file

@ -0,0 +1,271 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
#ifndef _TCOD_FOV_HPP
#define _TCOD_FOV_HPP
#include <utility>
#include "fov.h"
class TCODPath;
/**
@PageName fov
@PageCategory Roguelike toolkits
@PageTitle Field of view
@PageDesc This toolkit allows one to easily calculate the potential visible set of map cells from the player position.
A cell is potentially visible if the line of sight from the player to the cell in unobstructed.
*/
class TCODLIB_API TCODMap {
public :
/**
@PageName fov_init
@PageFather fov
@PageTitle Building the map
@FuncTitle Creating the map object
@FuncDesc First, you have to allocate a map of the same size as your dungeon.
@Cpp TCODMap::TCODMap (int width, int height)
@C TCOD_map_t TCOD_map_new (int width, int height)
@Py map_new (width, height)
@C# TCODMap::TCODMap(int width, int height)
@Param width, height The size of the map (in map cells).
*/
TCODMap(int width, int height);
TCODMap(const TCODMap&) = delete;
TCODMap& operator=(const TCODMap&) = delete;
TCODMap(TCODMap&& rhs) noexcept { std::swap(data, rhs.data); };
TCODMap& operator=(TCODMap&& rhs) noexcept {
std::swap(data, rhs.data);
return *this;
};
/**
@PageName fov_init
@PageFather fov
@FuncTitle Defining the cell properties
@FuncDesc Then, build your dungeon by defining which cells let the light pass (by default, all cells block the light) and which cells are walkable (by default, all cells are not-walkable).
@Cpp void TCODMap::setProperties (int x, int y, bool isTransparent, bool isWalkable)
@C void TCOD_map_set_properties (TCOD_map_t map, int x, int y, bool is_transparent, bool is_walkable)
@Py map_set_properties (map, x, y, is_transparent, is_walkable)
@C# void TCODMap::setProperties (int x, int y, bool isTransparent, bool isWalkable)
@Param map In the C version, the map handler returned by the TCOD_map_new function.
@Param x, y Coordinate of the cell that we want to update.
@Param isTransparent If true, this cell will let the light pass else it will block the light.
@Param isWalkable If true, creatures can walk true this cell (it is not a wall).
*/
void setProperties(int x,int y, bool isTransparent, bool isWalkable);
/**
@PageName fov_init
@PageFather fov
@FuncTitle Clearing the map
@FuncDesc You can clear an existing map (setting all cells to the chosen walkable/transparent values) with:
@Cpp void TCODMap::clear (bool transparent = false, bool walkable = false)
@C void TCOD_map_clear (TCOD_map_t map, bool transparent, bool walkable)
@Py map_clear (map, transparent = False, walkable = False)
@C#
void TCODMap::clear()
void TCODMap::clear(bool transparent)
void TCODMap::clear(bool transparent, bool walkable)
@Param map In the C version, the map handler returned by the TCOD_map_new function.
@Param walkable Whether the cells should be walkable.
@Param transparent Whether the cells should be transparent.
*/
void clear(bool transparent=false, bool walkable=false);
/**
@PageName fov_init
@PageFather fov
@FuncTitle Copying a map
@FuncDesc You can copy an existing map into another. You have to allocate the destination map first.
@Cpp void TCODMap::copy (const TCODMap * source)
@C void TCOD_map_copy (TCOD_map_t source, TCOD_map_t dest)
@Py map_copy (source, dest)
@C# void TCODMap::copy (TCODMap source)
@Param source The map containing the source data.
@Param dest In C and Python version, the map where data is copied.
@CppEx
TCODMap * map = new TCODMap(50,50); // allocate the map
map->setProperties(10,10,true,true); // set a cell as 'empty'
TCODMap * map2 = new TCODMap(10,10); // allocate another map
map2->copy(map); // copy map data into map2, reallocating it to 50x50
@CEx
TCOD_map_t map = TCOD_map_new(50,50);
TCOD_map_t map2 = TCOD_map_new(10,10);
TCOD_map_set_properties(map,10,10,true,true);
TCOD_map_copy(map,map2);
@PyEx
map = libtcod.map_new(50,50)
map2 = libtcod.map_new(10,10)
libtcod.map_set_properties(map,10,10,True,True)
libtcod.map_copy(map,map2)
*/
void copy (const TCODMap *source);
/**
@PageName fov_compute
@PageTitle Computing the field of view
@PageFather fov
@FuncDesc Once your map is allocated and empty cells have been defined, you can calculate the field of view with :
<div class="code"><pre>typedef enum { FOV_BASIC,
FOV_DIAMOND,
FOV_SHADOW,
FOV_PERMISSIVE_0,FOV_PERMISSIVE_1,FOV_PERMISSIVE_2,FOV_PERMISSIVE_3,
FOV_PERMISSIVE_4,FOV_PERMISSIVE_5,FOV_PERMISSIVE_6,FOV_PERMISSIVE_7,FOV_PERMISSIVE_8,
FOV_RESTRICTIVE,
NB_FOV_ALGORITHMS } TCOD_fov_algorithm_t;
</pre></div>
* FOV_BASIC : classic libtcod fov algorithm (ray casted from the player to all the cells on the submap perimeter)
* FOV_DIAMOND : based on <a href="http://www.geocities.com/temerra/los_rays.html">this</a> algorithm
* FOV_SHADOW : based on <a href="http://roguebasin.roguelikedevelopment.org/index.php?title=FOV_using_recursive_shadowcasting">this</a> algorithm
* FOV_PERMISSIVE_x : based on <a href="http://roguebasin.roguelikedevelopment.org/index.php?title=Precise_Permissive_Field_of_View">this</a> algorithm
Permissive has a variable permissiveness parameter. You can either use the constants FOV_PERMISSIVE_x, x between 0 (the less permissive) and 8 (the more permissive), or using the macro FOV_PERMISSIVE(x).
* FOV_RESTRICTIVE : Mingos' Restrictive Precise Angle Shadowcasting (MRPAS). Original implementation <a href="http://umbrarumregnum.110mb.com/download/mrpas">here</a>. Comparison of the algorithms :
Check <a href="http://roguecentral.org/libtcod/fov/fov.pdf">this</a>.
@Cpp void TCODMap::computeFov(int playerX,int playerY, int maxRadius=0,bool light_walls = true, TCOD_fov_algorithm_t algo = FOV_BASIC)
@C void TCOD_map_compute_fov(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls, TCOD_fov_algorithm_t algo)
@Py map_compute_fov(map, player_x, player_y, max_radius=0, light_walls=True, algo=FOV_BASIC )
@C#
void TCODMap::computeFov(int playerX, int playerY)
void TCODMap::computeFov(int playerX, int playerY, int maxRadius)
void TCODMap::computeFov(int playerX, int playerY, int maxRadius,bool light_walls)
void TCODMap::computeFov(int playerX, int playerY, int maxRadius,bool light_walls, TCODFOVTypes algo)
@Param map In the C version, the map handler returned by the TCOD_map_new function.
@Param player_x,player_y Position of the player in the map.
0 <= player_x < map width.
0 <= player_y < map height.
@Param maxRadius If > 0, the fov is only computed up to maxRadius cells away from the player. Else, the range is unlimited.
@Param light_walls Whether the wall cells near ground cells in fov must be in fov too.
@Param algo FOV algorithm to use.
@CppEx
TCODMap *map = new TCODMap(50,50); // allocate the map
map->setProperties(10,10,true,true); // set a cell as 'empty'
map->computeFov(10,10); // calculate fov from the cell 10x10 (basic raycasting, unlimited range, walls lighting on)
@CEx
TCOD_map_t map = TCOD_map_new(50,50);
TCOD_map_set_properties(map,10,10,true,true);
TCOD_map_compute_fov(map,10,10,0,true,FOV_SHADOW); // using shadow casting
@PyEx
map = libtcod.map_new(50,50)
libtcod.map_set_properties(map,10,10,True,True)
libtcod.map_compute_fov(map,10,10,0,True,libtcod.FOV_PERMISSIVE(2))
*/
void computeFov(int playerX,int playerY, int maxRadius = 0,bool light_walls = true, TCOD_fov_algorithm_t algo = FOV_BASIC);
/**
@PageName fov_get
@PageFather fov
@PageTitle Reading fov information
@FuncTitle Checking if a cell is in fov
@FuncDesc Once your computed the field of view, you can know if a cell is visible with :
@Cpp bool TCODMap::isInFov(int x, int y) const
@C bool TCOD_map_is_in_fov(TCOD_map_t map, int x, int y)
@Py map_is_in_fov(map, x, y)
@C# bool TCODMap::isInFov(int x, int y)
@Param map In the C version, the map handler returned by the TCOD_map_new function.
@Param x,y Coordinates of the cell we want to check.
0 <= x < map width.
0 <= y < map height.
@CppEx
TCODMap *map = new TCODMap(50,50); // allocate the map
map->setProperties(10,10,true,true); // set a cell as 'empty'
map->computeFov(10,10); // calculate fov from the cell 10x10
bool visible=map->isInFov(10,10); // is the cell 10x10 visible ?
@CEx
TCOD_map_t map = TCOD_map_new(50,50);
TCOD_map_set_properties(map,10,10,true,true);
TCOD_map_compute_fov(map,10,10);
bool visible = TCOD_map_is_in_fov(map,10,10);
@PyEx
map = libtcod.map_new(50,50)
libtcod.map_set_properties(map,10,10,True,True)
libtcod.map_compute_fov(map,10,10)
visible = libtcod.map_is_in_fov(map,10,10)
*/
bool isInFov(int x,int y) const;
/**
@PageName fov_get
@FuncTitle Checking a cell transparency/walkability
@FuncDesc You can also retrieve transparent/walkable information with :
@Cpp
bool TCODMap::isTransparent(int x, int y) const
bool TCODMap::isWalkable(int x, int y) const
@C
bool TCOD_map_is_transparent(TCOD_map_t map, int x, int y)
bool TCOD_map_is_walkable(TCOD_map_t map, int x, int y)
@Py
map_is_transparent(map, x, y)
map_is_walkable(map, x, y)
@C#
bool TCODMap::isTransparent(int x, int y)
bool TCODMap::isWalkable(int x, int y)
@Param map In the C version, the map handler returned by the TCOD_map_new function.
@Param x,y Coordinates of the cell we want to check.
0 <= x < map width.
0 <= y < map height.
*/
bool isTransparent(int x, int y) const;
bool isWalkable(int x, int y) const;
/**
@PageName fov_get
@FuncTitle Getting the map size
@FuncDesc You can retrieve the map size with :
@Cpp
int TCODMap::getWidth() const
int TCODMap::getHeight() const
@C
int TCOD_map_get_width(TCOD_map_t map)
int TCOD_map_get_height(TCOD_map_t map)
@Py
map_get_width(map)
map_get_height(map)
@C#
int TCODMap::getWidth()
int TCODMap::getHeight()
@Param map In the C version, the map handler returned by the TCOD_map_new function.
*/
int getWidth() const;
int getHeight() const;
virtual ~TCODMap();
void setInFov(int x,int y, bool fov);
int getNbCells() const;
friend class TCODLIB_API TCODPath;
friend class TCODLIB_API TCODDijkstra;
// protected :
TCOD_map_t data;
};
#endif

View file

@ -0,0 +1,109 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_FOV_TYPES_H_
#define TCOD_FOV_TYPES_H_
#include "portability.h"
/**
* Private map cell struct.
*/
struct TCOD_MapCell {
bool transparent;
bool walkable;
bool fov;
};
/**
* Private map struct.
*/
typedef struct TCOD_Map {
int width;
int height;
int nbcells;
struct TCOD_MapCell* __restrict cells;
} TCOD_Map;
typedef TCOD_Map* TCOD_map_t;
/**
\rst
Field-of-view options for :any:`TCOD_map_compute_fov`.
\endrst
*/
typedef enum {
/**
Trace multiple Bresenham lines along the perimeter.
Based on: http://www.roguebasin.com/index.php?title=Ray_casting
*/
FOV_BASIC,
/**
Cast Bresenham line shadows on a per-tile basis.
Based on: http://www.oocities.org/temerra/los_rays.html
*/
FOV_DIAMOND,
/**
Recursive Shadowcast.
Based on: http://www.roguebasin.com/index.php?title=FOV_using_recursive_shadowcasting
*/
FOV_SHADOW,
/**
Precise Permissive Field of View.
Based on: http://www.roguebasin.com/index.php?title=Precise_Permissive_Field_of_View
*/
FOV_PERMISSIVE_0,
FOV_PERMISSIVE_1,
FOV_PERMISSIVE_2,
FOV_PERMISSIVE_3,
FOV_PERMISSIVE_4,
FOV_PERMISSIVE_5,
FOV_PERMISSIVE_6,
FOV_PERMISSIVE_7,
FOV_PERMISSIVE_8,
/**
Mingos' Restrictive Precise Angle Shadowcasting (contribution by Mingos)
Based on: http://www.roguebasin.com/index.php?title=Restrictive_Precise_Angle_Shadowcasting
*/
FOV_RESTRICTIVE,
/**
Symmetric Shadowcast.
Based on: https://www.albertford.com/shadowcasting/
\rst
.. versionadded :: 1.16
\endrst
*/
FOV_SYMMETRIC_SHADOWCAST,
NB_FOV_ALGORITHMS
} TCOD_fov_algorithm_t;
#define FOV_PERMISSIVE(x) ((TCOD_fov_algorithm_t)(FOV_PERMISSIVE_0 + (x)))
#endif /* TCOD_FOV_TYPES_H_ */

View file

@ -0,0 +1,63 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_GLOBALS_H_
#define LIBTCOD_GLOBALS_H_
#include "config.h"
#include "tileset.h"
/**
Return the default tileset, may be NULL.
A non-NULL return value is a new reference to the global tileset.
When you are done you will need to call `TCOD_tileset_delete` on this
pointer.
This function is provisional, the API may change in the future.
\rst
.. versionadded:: 1.19
\endrst
*/
TCODLIB_CAPI TCOD_Tileset* TCOD_get_default_tileset(void);
/**
Set the default tileset and update the default display to use it.
This will keep alive a reference to the given tileset. If you no longer
need the pointer then you should call `TCOD_tileset_delete` on it after
this function.
This function is provisional, the API may change in the future.
\rst
.. versionadded:: 1.19
\endrst
*/
TCODLIB_CAPI void TCOD_set_default_tileset(TCOD_Tileset* tileset);
#endif // LIBTCOD_GLOBALS_H_

View file

@ -0,0 +1,65 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_BUTTON_HPP
#define TCOD_GUI_BUTTON_HPP
#ifndef TCOD_NO_UNICODE
#include "widget.hpp"
class TCODLIB_GUI_API Button : public Widget {
public:
Button(const char* label, const char* tip, widget_callback_t cbk, void* userData = NULL);
Button(
int x,
int y,
int width,
int height,
const char* label,
const char* tip,
widget_callback_t cbk,
void* userData = NULL);
virtual ~Button();
void render();
void setLabel(const char* newLabel);
void computeSize();
inline bool isPressed() { return pressed; }
protected:
bool pressed;
char* label;
widget_callback_t cbk;
void onButtonPress();
void onButtonRelease();
void onButtonClick();
void expand(int width, int height);
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_BUTTON_HPP */

View file

@ -0,0 +1,51 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_CONTAINER_HPP
#define TCOD_GUI_CONTAINER_HPP
#ifndef TCOD_NO_UNICODE
#include "widget.hpp"
class TCODLIB_GUI_API Container : public Widget {
public:
Container(int x, int y, int w, int h) : Widget(x, y, w, h) {}
virtual ~Container();
void addWidget(Widget* wid);
void removeWidget(Widget* wid);
void setVisible(bool val);
void render();
void clear();
void update(const TCOD_key_t k);
protected:
TCODList<Widget*> content; // Can't be fixed without breaking the ABI.
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_CONTAINER_HPP */

View file

@ -0,0 +1,62 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_FLATLIST_HPP
#define TCOD_GUI_FLATLIST_HPP
#ifndef TCOD_NO_UNICODE
#include "textbox.hpp"
class TCODLIB_GUI_API FlatList : public TextBox {
public:
FlatList(int x, int y, int w, const char** list, const char* label, const char* tip = NULL);
virtual ~FlatList();
void render();
void update(const TCOD_key_t k);
void setCallback(void (*cbk_)(Widget* wid, const char* val, void* data), void* data_) {
this->cbk = cbk_;
this->data = data_;
}
void setValue(const char* value);
void setList(const char** list);
protected:
const char** value;
const char** list;
bool onLeftArrow;
bool onRightArrow;
void (*cbk)(Widget* wid, const char* val, void* data);
void* data;
void valueToText();
void textToValue();
void onButtonClick();
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_FLATLIST_HPP */

View file

@ -0,0 +1,51 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _GUI_HPP
#define _GUI_HPP
#include "../libtcod.hpp"
#include "button.hpp"
#include "container.hpp"
#include "flatlist.hpp"
#include "hbox.hpp"
#include "image.hpp"
#include "label.hpp"
#include "radiobutton.hpp"
#include "slider.hpp"
#include "statusbar.hpp"
#include "textbox.hpp"
#include "togglebutton.hpp"
#include "toolbar.hpp"
#include "vbox.hpp"
#include "widget.hpp"
#endif

View file

@ -0,0 +1,40 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_PORTABILITY_HPP
#define TCOD_GUI_PORTABILITY_HPP
#include "../portability.h"
// DLL export
#define TCODLIB_GUI_API TCODLIB_API
#endif /* TCOD_GUI_PORTABILITY_HPP */

View file

@ -0,0 +1,42 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_HBOX_HPP
#define TCOD_GUI_HBOX_HPP
#ifndef TCOD_NO_UNICODE
#include "vbox.hpp"
class TCODLIB_GUI_API HBox : public VBox {
public:
HBox(int x, int y, int padding);
void computeSize();
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_HBOX_HPP */

View file

@ -0,0 +1,47 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_IMAGE_HPP
#define TCOD_GUI_IMAGE_HPP
#include "widget.hpp"
class TCODLIB_GUI_API Image : public Widget {
public:
Image(int x, int y, int w, int h, const char* tip = NULL);
virtual ~Image();
void setBackgroundColor(const TCODColor col);
void render();
protected:
void expand(int width, int height);
TCODColor back;
};
#endif /* TCOD_GUI_IMAGE_HPP */

View file

@ -0,0 +1,49 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_LABEL_HPP
#define TCOD_GUI_LABEL_HPP
#ifndef TCOD_NO_UNICODE
#include "widget.hpp"
class TCODLIB_GUI_API Label : public Widget {
public:
Label(int x, int y, const char* label, const char* tip = NULL);
void render();
void computeSize();
void setValue(const char* label_) { this->label = label_; }
protected:
const char* label;
void expand(int width, int height);
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_LABEL_HPP */

View file

@ -0,0 +1,66 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_RADIOBUTTON_HPP
#define TCOD_GUI_RADIOBUTTON_HPP
#ifndef TCOD_NO_UNICODE
#include "button.hpp"
class TCODLIB_GUI_API RadioButton : public Button {
public:
RadioButton(const char* label, const char* tip, widget_callback_t cbk, void* userData = NULL)
: Button(label, tip, cbk, userData), group(defaultGroup) {}
RadioButton(
int x,
int y,
int width,
int height,
const char* label,
const char* tip,
widget_callback_t cbk,
void* userData = NULL)
: Button(x, y, width, height, label, tip, cbk, userData), group(defaultGroup) {}
void setGroup(int group_) { this->group = group_; }
void render();
void select();
void unSelect();
static void unSelectGroup(int group);
static void setDefaultGroup(int group) { defaultGroup = group; }
protected:
static int defaultGroup;
int group;
static RadioButton* groupSelect[512];
void onButtonClick();
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_RADIOBUTTON_HPP */

View file

@ -0,0 +1,71 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_SLIDER_HPP
#define TCOD_GUI_SLIDER_HPP
#ifndef TCOD_NO_UNICODE
#include "textbox.hpp"
class TCODLIB_GUI_API Slider : public TextBox {
public:
Slider(int x, int y, int w, float min, float max, const char* label, const char* tip = NULL);
virtual ~Slider();
void render();
void update(const TCOD_key_t k);
void setMinMax(float min_, float max_) {
this->min = min_;
this->max = max_;
}
void setCallback(void (*cbk_)(Widget* wid, float val, void* data), void* data_) {
this->cbk = cbk_;
this->data = data_;
}
void setFormat(const char* fmt);
void setValue(float value);
void setSensitivity(float sensitivity_) { this->sensitivity = sensitivity_; }
protected:
float min, max, value, sensitivity;
bool onArrows;
bool drag;
int drag_x;
int drag_y;
float dragValue;
char* fmt;
void (*cbk)(Widget* wid, float val, void* data);
void* data;
void valueToText();
void textToValue();
void onButtonPress();
void onButtonRelease();
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_SLIDER_HPP */

View file

@ -0,0 +1,42 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_STATUSBAR_HPP
#define TCOD_GUI_STATUSBAR_HPP
#ifndef TCOD_NO_UNICODE
#include "widget.hpp"
class TCODLIB_GUI_API StatusBar : public Widget {
public:
StatusBar(int x, int y, int w, int h) : Widget(x, y, w, h) {}
void render();
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_STATUSBAR_HPP */

View file

@ -0,0 +1,64 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_TEXTBOX_HPP
#define TCOD_GUI_TEXTBOX_HPP
#ifndef TCOD_NO_UNICODE
#include "widget.hpp"
class TCODLIB_GUI_API TextBox : public Widget {
public:
TextBox(int x, int y, int w, int max_width, const char* label, const char* value, const char* tip = NULL);
virtual ~TextBox();
void render();
void update(const TCOD_key_t k);
void setText(const char* txt);
const char* getValue() { return txt; }
void setCallback(void (*cbk)(Widget* wid, char* val, void* data), void* data_) {
text_callback = cbk;
this->data = data_;
}
static void setBlinkingDelay(float delay) { blinkingDelay = delay; }
protected:
static float blinkingDelay;
char* label;
char* txt;
float blink;
int pos, offset;
int box_x, box_width, max_width;
bool insert;
void (*text_callback)(Widget* wid, char* val, void* data);
void* data;
void onButtonClick();
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_TEXTBOX_HPP */

View file

@ -0,0 +1,60 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_TOGGLEBUTTON_HPP
#define TCOD_GUI_TOGGLEBUTTON_HPP
#ifndef TCOD_NO_UNICODE
#include "button.hpp"
class TCODLIB_GUI_API ToggleButton : public Button {
public:
ToggleButton(const char* label, const char* tip, widget_callback_t cbk, void* userData = NULL)
: Button(label, tip, cbk, userData) {}
ToggleButton(
int x,
int y,
int width,
int height,
const char* label,
const char* tip,
widget_callback_t cbk,
void* userData = NULL)
: Button(x, y, width, height, label, tip, cbk, userData) {}
void render();
bool isPressed() { return pressed; }
void setPressed(bool val) { pressed = val; }
protected:
void onButtonPress();
void onButtonRelease();
void onButtonClick();
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_TOGGLEBUTTON_HPP */

View file

@ -0,0 +1,51 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_TOOLBAR_HPP
#define TCOD_GUI_TOOLBAR_HPP
#ifndef TCOD_NO_UNICODE
#include "container.hpp"
class TCODLIB_GUI_API ToolBar : public Container {
public:
ToolBar(int x, int y, const char* name, const char* tip = NULL);
ToolBar(int x, int y, int w, const char* name, const char* tip = NULL);
~ToolBar();
void render();
void setName(const char* name);
void addSeparator(const char* txt, const char* tip = NULL);
void computeSize();
protected:
char* name;
int fixedWidth;
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_TOOLBAR_HPP */

View file

@ -0,0 +1,45 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_VBOX_HPP
#define TCOD_GUI_VBOX_HPP
#ifndef TCOD_NO_UNICODE
#include "container.hpp"
class TCODLIB_GUI_API VBox : public Container {
public:
VBox(int x, int y, int padding) : Container(x, y, 0, 0), padding(padding) {}
void computeSize();
protected:
int padding;
};
#endif // TCOD_NO_UNICODE
#endif /* TCOD_GUI_VBOX_HPP */

View file

@ -0,0 +1,91 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_GUI_WIDGET_HPP
#define TCOD_GUI_WIDGET_HPP
#include "../color.hpp"
#include "../console.hpp"
#include "../list.hpp"
#include "../mouse.hpp"
#include "gui_portability.hpp"
class TCODLIB_GUI_API Widget {
public:
int x, y, w, h;
void* userData;
static Widget* focus;
static Widget* keyboardFocus;
Widget();
Widget(int x, int y);
Widget(int x, int y, int w, int h);
virtual ~Widget();
virtual void render() {}
virtual void update(const TCOD_key_t k);
void move(int x, int y);
void setTip(const char* tip);
virtual void setVisible(bool val) { visible = val; }
bool isVisible() { return visible; }
virtual void computeSize() {}
static void setBackgroundColor(const TCODColor col, const TCODColor colFocus);
static void setForegroundColor(const TCODColor col, const TCODColor colFocus);
static void setConsole(TCODConsole* con);
static void updateWidgets(const TCOD_key_t k, const TCOD_mouse_t mouse);
static void renderWidgets();
static TCOD_mouse_t mouse;
static TCODColor fore;
virtual void expand(int, int) {} // parameters: width, height
protected:
friend class StatusBar;
friend class ToolBar;
friend class VBox;
friend class HBox;
virtual void onMouseIn() {}
virtual void onMouseOut() {}
virtual void onButtonPress() {}
virtual void onButtonRelease() {}
virtual void onButtonClick() {}
static void updateWidgetsIntern(const TCOD_key_t k);
static float elapsed;
static TCODColor back;
static TCODColor backFocus;
static TCODColor foreFocus;
static TCODConsole* con;
static TCODList<Widget*> widgets;
char* tip;
bool mouseIn : 1;
bool mouseL : 1;
bool visible : 1;
};
typedef void (*widget_callback_t)(Widget* w, void* userData);
#endif /* TCOD_GUI_WIDGET_HPP */

View file

@ -0,0 +1,64 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_HEAPQ_H
#define TCOD_HEAPQ_H
#include <stdbool.h>
#include <stddef.h>
#include "config.h"
struct TCOD_Heap {
unsigned char* __restrict heap;
int size; // The current number of elements in heap.
int capacity; // The current capacity of heap.
size_t node_size; // The full size of each node in bytes.
size_t data_size; // The size of a nodes user data section in bytes.
size_t data_offset; // The offset of the user data section.
int priority_type; // Should be -4.
};
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
TCOD_PUBLIC int TCOD_heap_init(struct TCOD_Heap* heap, size_t data_size);
TCOD_PUBLIC void TCOD_heap_uninit(struct TCOD_Heap* heap);
TCOD_PUBLIC void TCOD_heap_clear(struct TCOD_Heap* heap);
TCOD_PUBLIC int TCOD_minheap_push(struct TCOD_Heap* __restrict minheap, int priority, const void* __restrict data);
TCOD_PUBLIC void TCOD_minheap_pop(struct TCOD_Heap* __restrict minheap, void* __restrict out);
TCOD_PUBLIC void TCOD_minheap_heapify(struct TCOD_Heap* minheap);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // TCOD_HEAPQ_H

View file

@ -0,0 +1,115 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_HEIGHTMAP_H
#define _TCOD_HEIGHTMAP_H
#include "mersenne_types.h"
#include "noise.h"
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int w, h;
float* __restrict values;
} TCOD_heightmap_t;
TCODLIB_API TCOD_heightmap_t* TCOD_heightmap_new(int w, int h);
TCODLIB_API void TCOD_heightmap_delete(TCOD_heightmap_t* hm);
TCODLIB_API float TCOD_heightmap_get_value(const TCOD_heightmap_t* hm, int x, int y);
TCODLIB_API float TCOD_heightmap_get_interpolated_value(const TCOD_heightmap_t* hm, float x, float y);
TCODLIB_API void TCOD_heightmap_set_value(TCOD_heightmap_t* hm, int x, int y, float value);
TCODLIB_API float TCOD_heightmap_get_slope(const TCOD_heightmap_t* hm, int x, int y);
TCODLIB_API void TCOD_heightmap_get_normal(const TCOD_heightmap_t* hm, float x, float y, float n[3], float waterLevel);
TCODLIB_API int TCOD_heightmap_count_cells(const TCOD_heightmap_t* hm, float min, float max);
TCODLIB_API bool TCOD_heightmap_has_land_on_border(const TCOD_heightmap_t* hm, float waterLevel);
TCODLIB_API void TCOD_heightmap_get_minmax(const TCOD_heightmap_t* hm, float* min, float* max);
TCODLIB_API void TCOD_heightmap_copy(const TCOD_heightmap_t* hm_source, TCOD_heightmap_t* hm_dest);
TCODLIB_API void TCOD_heightmap_add(TCOD_heightmap_t* hm, float value);
TCODLIB_API void TCOD_heightmap_scale(TCOD_heightmap_t* hm, float value);
TCODLIB_API void TCOD_heightmap_clamp(TCOD_heightmap_t* hm, float min, float max);
TCODLIB_API void TCOD_heightmap_normalize(TCOD_heightmap_t* hm, float min, float max);
TCODLIB_API void TCOD_heightmap_clear(TCOD_heightmap_t* hm);
TCODLIB_API void TCOD_heightmap_lerp_hm(
const TCOD_heightmap_t* hm1, const TCOD_heightmap_t* hm2, TCOD_heightmap_t* out, float coef);
TCODLIB_API void TCOD_heightmap_add_hm(const TCOD_heightmap_t* hm1, const TCOD_heightmap_t* hm2, TCOD_heightmap_t* out);
TCODLIB_API void TCOD_heightmap_multiply_hm(
const TCOD_heightmap_t* hm1, const TCOD_heightmap_t* hm2, TCOD_heightmap_t* out);
TCODLIB_API void TCOD_heightmap_add_hill(TCOD_heightmap_t* hm, float hx, float hy, float h_radius, float h_height);
TCODLIB_API void TCOD_heightmap_dig_hill(TCOD_heightmap_t* hm, float hx, float hy, float h_radius, float h_height);
TCODLIB_API void TCOD_heightmap_dig_bezier(
TCOD_heightmap_t* hm, int px[4], int py[4], float startRadius, float startDepth, float endRadius, float endDepth);
TCODLIB_API void TCOD_heightmap_rain_erosion(
TCOD_heightmap_t* hm, int nbDrops, float erosionCoef, float sedimentationCoef, TCOD_Random* rnd);
/* TCODLIB_API void TCOD_heightmap_heat_erosion(TCOD_heightmap_t *hm, int nbPass,float minSlope,float erosionCoef,float
* sedimentationCoef,TCOD_Random* rnd); */
TCODLIB_API void TCOD_heightmap_kernel_transform(
TCOD_heightmap_t* hm,
int kernel_size,
const int* dx,
const int* dy,
const float* weight,
float minLevel,
float maxLevel);
TCODLIB_API void TCOD_heightmap_add_voronoi(
TCOD_heightmap_t* hm, int nbPoints, int nbCoef, const float* coef, TCOD_Random* rnd);
TCODLIB_API void TCOD_heightmap_mid_point_displacement(TCOD_heightmap_t* hm, TCOD_Random* rnd, float roughness);
TCODLIB_API void TCOD_heightmap_add_fbm(
TCOD_heightmap_t* hm,
TCOD_noise_t noise,
float mul_x,
float mul_y,
float add_x,
float add_y,
float octaves,
float delta,
float scale);
TCODLIB_API void TCOD_heightmap_scale_fbm(
TCOD_heightmap_t* hm,
TCOD_noise_t noise,
float mul_x,
float mul_y,
float add_x,
float add_y,
float octaves,
float delta,
float scale);
TCOD_DEPRECATED("This function does nothing and will be removed.")
TCODLIB_API void TCOD_heightmap_islandify(TCOD_heightmap_t* hm, float seaLevel, TCOD_Random* rnd);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,508 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
#ifndef _TCOD_HEIGHTMAP_HPP
#define _TCOD_HEIGHTMAP_HPP
#include "heightmap.h"
#include "noise.hpp"
/**
@PageName heightmap
@PageCategory Roguelike toolkits
@PageTitle Heightmap toolkit
@PageDesc This toolkit allows one to create a 2D grid of float values using various algorithms.
The code using the heightmap toolkit can be automatically generated with the heightmap tool (hmtool) included in the libtcod package.
*/
class TCODLIB_API TCODHeightMap {
public :
int w,h;
float *values;
/**
@PageName heightmap_init
@PageFather heightmap
@PageTitle Creating a heightmap
@FuncTitle Creating an empty map
@FuncDesc As with other modules, you have to create a heightmap object first :
Note that whereas most other modules use opaque structs, the TCOD_heightmap_t fields can be freely accessed. Thus, the TCOD_heightmap_new function returns a TCOD_heightmap_t pointer, not a TCOD_heightmap_t. The w and h fields should not be modified after the heightmap creation. The newly created heightmap is filled with 0.0 values.
@Cpp TCODHeightMap::TCODHeightMap(int w, int h)
@C
typedef struct {
int w,h;
float *values;
} TCOD_heightmap_t;
TCOD_heightmap_t *TCOD_heightmap_new(int w,int h)
@Py heightmap_new(w,h)
@C# TCODHeightMap::TCODHeightMap(int w, int h)
@Param w,h The width and height of the heightmap.
@CppEx TCODHeightMap myMap(50,50);
@CEx TCOD_heightmap_t *my_map=TCOD_heightmap_new(50,50);
@PyEx
map=libtcod.heightmap_new(50,50)
print map.w, map.h
*/
TCODHeightMap(int width, int height);
/**
@PageName heightmap_init
@FuncTitle Destroying a heightmap
@FuncDesc To release the resources used by a heightmap, destroy it with :
@Cpp TCODHeightMap::~TCODHeightMap()
@C void TCOD_heightmap_delete(TCOD_heightmap_t *hm)
@Py heightmap_delete(hm)
@C# void TCODHeightMap::Dispose()
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
*/
virtual ~TCODHeightMap();
/**
@PageName heightmap_base
@PageFather heightmap
@PageTitle Basic operations
@PageDesc Those are simple operations applied either on a single map cell or on every map cell.
@FuncTitle Setting a cell value
@FuncDesc Once the heightmap has been created, you can do some basic operations on the values inside it.
You can set a single value :
@Cpp void TCODHeightMap::setValue(int x, int y, float v)
@C void TCOD_heightmap_set_value(TCOD_heightmap_t *hm, int x, int y, float value)
@Py heightmap_set_value(hm, x, y, value)
@C# void TCODHeightMap::setValue(int x, int y, float v)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param x,y Coordinates of the cells to modify inside the map.
0 <= x < map width
0 <= y < map height
@Param value The new value of the map cell.
*/
inline void setValue(int x, int y, float v) {
values[x+y*w]=v;
}
/**
@PageName heightmap_base
@FuncTitle Adding a float value to all cells
@Cpp void TCODHeightMap::add(float value)
@C void TCOD_heightmap_add(TCOD_heightmap_t *hm, float value)
@Py heightmap_add(hm, value)
@C# void TCODHeightMap::add(float value)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param value Value to add to every cell.
*/
void add(float f);
/**
@PageName heightmap_base
@FuncTitle Multiplying all values by a float
@Cpp void TCODHeightMap::scale(float value)
@C void TCOD_heightmap_scale(TCOD_heightmap_t *hm, float value)
@Py heightmap_scale(hm, value)
@C# void TCODHeightMap::scale(float value)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param value Every cell's value is multiplied by this value.
*/
void scale(float f);
/**
@PageName heightmap_base
@FuncTitle Resetting all values to 0.0
@Cpp void TCODHeightMap::clear()
@C void TCOD_heightmap_clear(TCOD_heightmap_t *hm)
@Py heightmap_clear(hm)
@C# void TCODHeightMap::clear()
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
*/
void clear(); // resets all values to 0.0
/**
@PageName heightmap_base
@FuncTitle Clamping all values
@Cpp void TCODHeightMap::clamp(float min, float max)
@C void TCOD_heightmap_clamp(TCOD_heightmap_t *hm, float min, float max)
@Py heightmap_clamp(hm, mi, ma)
@C# void TCODHeightMap::clamp(float min, float max)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param min,max Every cell value is clamped between min and max.
min < max
*/
void clamp(float min, float max);
/**
@PageName heightmap_base
@FuncTitle Copying values from another heightmap
@Cpp void TCODHeightMap::copy(const TCODHeightMap *source)
@C void TCOD_heightmap_copy(const TCOD_heightmap_t *source,TCOD_heightmap_t *dest)
@Py heightmap_copy(source,dest)
@C# void TCODHeightMap::copy(TCODHeightMap source)
@Param source Each cell value from the source heightmap is copied in the destination (this for C++) heightmap.
The source and destination heightmap must have the same width and height.
@Param dest In the C and Python versions, the address of the destination heightmap.
*/
void copy(const TCODHeightMap *source);
/**
@PageName heightmap_base
@FuncTitle Normalizing values
@Cpp void TCODHeightMap::normalize(float min=0.0f, float max=1.0f)
@C void TCOD_heightmap_normalize(TCOD_heightmap_t *hm, float min, float max)
@Py heightmap_normalize(hm, mi=0.0, ma=1.0)
@C#
void TCODHeightMap::normalize()
void TCODHeightMap::normalize(float min)
void TCODHeightMap::normalize(float min, float max)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param min,max The whole heightmap is translated and scaled so that the lowest cell value becomes min and the highest cell value becomes max
min < max
*/
void normalize(float newMin=0.0f, float newMax=1.0f); // scales the values to the range [newMin;newMax]
/**
@PageName heightmap_base
@FuncTitle Doing a lerp operation between two heightmaps
@Cpp void TCODHeightMap::lerp(const TCODHeightMap *a, const TCODHeightMap *b,float coef)
@C void TCOD_heightmap_lerp_hm(const TCOD_heightmap_t *a, const TCOD_heightmap_t *b, TCOD_heightmap_t *res, float coef)
@Py heightmap_lerp_hm(a, b, res, coef)
@C# void TCODHeightMap::lerp(TCODHeightMap a, TCODHeightMap b, float coef)
@Param a First heightmap in the lerp operation.
@Param b Second heightmap in the lerp operation.
@Param coef lerp coefficient.
For each cell in the destination map (this for C++), value = a.value + (b.value - a.value) * coef
@Param res In the C and Python versions, the address of the destination heightmap.
*/
void lerp(const TCODHeightMap *a, const TCODHeightMap *b,float coef);
/**
@PageName heightmap_base
@FuncTitle Adding two heightmaps
@Cpp void TCODHeightMap::add(const TCODHeightMap *a, const TCODHeightMap *b)
@C void TCOD_heightmap_add_hm(const TCOD_heightmap_t *a, const TCOD_heightmap_t *b, TCOD_heightmap_t *res)
@Py heightmap_add_hm(a, b, res)
@C# void TCODHeightMap::add(TCODHeightMap a, TCODHeightMap b)
@Param a First heightmap.
@Param b Second heightmap. For each cell in the destination map (this for C++), value = a.value + b.value
@Param res In the C and Python versions, the address of the destination heightmap.
*/
void add(const TCODHeightMap *a, const TCODHeightMap *b);
/**
@PageName heightmap_base
@FuncTitle Multiplying two heightmaps
@Cpp void TCODHeightMap::multiply(const TCODHeightMap *a, const TCODHeightMap *b)
@C void TCOD_heightmap_multiply_hm(const TCOD_heightmap_t *a, const TCOD_heightmap_t *b, TCOD_heightmap_t *res)
@Py heightmap_multiply_hm(a, b, res)
@C# void TCODHeightMap::multiply(TCODHeightMap a, TCODHeightMap b)
@Param a First heightmap.
@Param b Second heightmap. For each cell in the destination map (this for C++), value = a.value * b.value
@Param res In the C and Python versions, the address of the destination heightmap.
*/
void multiply(const TCODHeightMap *a, const TCODHeightMap *b);
/**
@PageName heightmap_modify
@PageFather heightmap
@PageTitle Modifying the heightmap
@PageDesc Those are advanced operations involving several or all map cells.
@FuncTitle Add hills
@FuncDesc This function adds a hill (a half spheroid) at given position.
@Cpp void TCODHeightMap::addHill(float x, float y, float radius, float height)
@C void TCOD_heightmap_add_hill(TCOD_heightmap_t *hm, float x, float y, float radius, float height)
@Py heightmap_add_hill(hm, x, y, radius, height)
@C# void TCODHeightMap::addHill(float x, float y, float radius, float height)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param x,y Coordinates of the center of the hill.
0 <= x < map width
0 <= y < map height
@Param radius The hill radius.
@Param height The hill height. If height == radius or -radius, the hill is a half-sphere.
*/
void addHill(float x, float y, float radius, float height); // adds a hill (half sphere) at given position
/**
@PageName heightmap_modify
@FuncTitle Dig hills
@FuncDesc This function takes the highest value (if height > 0) or the lowest (if height < 0) between the map and the hill.
It's main goal is to carve things in maps (like rivers) by digging hills along a curve.
@Cpp void TCODHeightMap::digHill(float hx, float hy, float h_radius, float height)
@C void TCOD_heightmap_dig_hill(TCOD_heightmap_t *hm, float x, float y, float radius, float height)
@Py heightmap_dig_hill(hm, x, y, radius, height)
@C# void TCODHeightMap::digHill(float hx, float hy, float h_radius, float height)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param x,y Coordinates of the center of the hill.
0 <= x < map width
0 <= y < map height
@Param radius The hill radius.
@Param height The hill height. Can be < 0 or > 0
*/
void digHill(float hx, float hy, float h_radius, float height);
/**
@PageName heightmap_modify
@FuncTitle Simulate rain erosion
@FuncDesc This function simulates the effect of rain drops on the terrain, resulting in erosion patterns.
@Cpp void TCODHeightMap::rainErosion(int nbDrops,float erosionCoef,float sedimentationCoef,TCODRandom *rnd)
@C void TCOD_heightmap_rain_erosion(TCOD_heightmap_t *hm, int nbDrops,float erosionCoef,float sedimentationCoef,TCOD_random_t rnd)
@Py heightmap_rain_erosion(hm, nbDrops,erosionCoef,sedimentationCoef,rnd=0)
@C# void TCODHeightMap::rainErosion(int nbDrops, float erosionCoef, float sedimentationCoef, TCODRandom rnd)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param nbDrops Number of rain drops to simulate. Should be at least width * height.
@Param erosionCoef Amount of ground eroded on the drop's path.
@Param sedimentationCoef Amount of ground deposited when the drops stops to flow
@Param rnd RNG to use, NULL for default generator.
*/
void rainErosion(int nbDrops,float erosionCoef,float sedimentationCoef,TCODRandom *rnd);
/**
@PageName heightmap_modify
@FuncTitle Do a generic transformation
@FuncDesc This function allows you to apply a generic transformation on the map, so that each resulting cell value is the weighted sum of several neighbour cells. This can be used to smooth/sharpen the map. See examples below for a simple horizontal smoothing kernel : replace value(x,y) with 0.33*value(x-1,y) + 0.33*value(x,y) + 0.33*value(x+1,y).To do this, you need a kernel of size 3 (the sum involves 3 surrounding cells). The dx,dy array will contain :
dx=-1,dy = 0 for cell x-1,y
dx=1,dy=0 for cell x+1,y
dx=0,dy=0 for current cell (x,y)
The weight array will contain 0.33 for each cell.
@Cpp void TCODHeightMap::kernelTransform(int kernelSize, int *dx, int *dy, float *weight, float minLevel,float maxLevel)
@C void TCOD_heightmap_kernel_transform(TCOD_heightmap_t *hm, int kernel_size, int *dx, int *dy, float *weight, float minLevel,float maxLevel)
@Py heightmap_kernel_transform(hm, kernel_size, dx, dy, weight, minLevel,maxLevel)
@C# void TCODHeightMap::kernelTransform(int kernelSize, int[] dx, int[] dy, float[] weight, float minLevel, float maxLevel)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
kernelSize Number of neighbour cells involved.
@Param dx,dy Array of kernelSize cells coordinates. The coordinates are relative to the current cell (0,0) is current cell, (-1,0) is west cell, (0,-1) is north cell, (1,0) is east cell, (0,1) is south cell, ...
@Param weight Array of kernelSize cells weight. The value of each neighbour cell is scaled by its corresponding weight
@Param minLevel The transformation is only applied to cells which value is >= minLevel.
@Param maxLevel The transformation is only applied to cells which value is <= maxLevel.
@CEx
int dx [] = {-1,1,0};
int dy[] = {0,0,0};
float weight[] = {0.33f,0.33f,0.33f};
TCOD_heightMap_kernel_transform(heightmap,3,dx,dy,weight,0.0f,1.0f);
@CppEx
int dx [] = {-1,1,0};
int dy[] = {0,0,0};
float weight[] = {0.33f,0.33f,0.33f};
heightmap->kernelTransform(heightmap,3,dx,dy,weight,0.0f,1.0f);
*/
void kernelTransform(int kernelSize, const int *dx, const int *dy, const float *weight, float minLevel,float maxLevel);
/**
@PageName heightmap_modify
@FuncTitle Add a Voronoi diagram
@FuncDesc This function adds values from a Voronoi diagram to the map.
@Cpp void TCODHeightMap::addVoronoi(int nbPoints, int nbCoef, float *coef,TCODRandom *rnd)
@C void TCOD_heightmap_add_voronoi(TCOD_heightmap_t *hm, int nbPoints, int nbCoef, float *coef,TCOD_random_t rnd)
@Py heightmap_add_voronoi(hm, nbPoints, nbCoef, coef,rnd=0)
@C# void TCODHeightMap::addVoronoi(int nbPoints, int nbCoef, float[] coef, TCODRandom rnd)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param nbPoints Number of Voronoi sites.
@Param nbCoef The diagram value is calculated from the nbCoef closest sites.
@Param coef The distance to each site is scaled by the corresponding coef.
Closest site : coef[0], second closest site : coef[1], ...
@Param rnd RNG to use, NULL for default generator.
*/
void addVoronoi(int nbPoints, int nbCoef, const float *coef,TCODRandom *rnd);
/**
@PageName heightmap_modify
@FuncTitle Add a fbm
This function adds values from a simplex fbm function to the map.
@Cpp void TCODHeightMap::addFbm(TCODNoise *noise,float mul_x, float mul_y, float add_x, float add_y, float octaves, float delta, float scale)
@C void TCOD_heightmap_add_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mul_x, float mul_y, float add_x, float add_y, float octaves, float delta, float scale)
@Py heightmap_add_fbm(hm, noise,mul_x, mul_y, add_x, add_y, octaves, delta, scale)
@C# void TCODHeightMap::addFbm(TCODNoise noise, float mul_x, float mul_y, float add_x, float add_y, float octaves, float delta, float scale)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param noise The 2D noise to use.
@Param mul_x, mul_y / add_x, add_y The noise coordinate for map cell (x,y) are (x + add_x)*mul_x / width , (y + add_y)*mul_y / height.
Those values allow you to scale and translate the noise function over the heightmap.
@Param octaves Number of octaves in the fbm sum.
@Param delta / scale The value added to the heightmap is delta + noise * scale.
@Param noise is between -1.0 and 1.0
*/
void addFbm(TCODNoise *noise,float mul_x, float mul_y, float add_x, float add_y, float octaves, float delta, float scale);
/**
@PageName heightmap_modify
@FuncTitle Scale with a fbm
@FuncDesc This function works exactly as the previous one, but it multiplies the resulting value instead of adding it to the heightmap.
@Cpp void TCODHeightMap::scaleFbm(TCODNoise *noise,float mul_x, float mul_y, float add_x, float add_y, float octaves, float delta, float scale)
@C void TCOD_heightmap_scale_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mul_x, float mul_y, float add_x, float add_y, float octaves, float delta, float scale)
@Py heightmap_scale_fbm(hm, noise,mul_x, mul_y, add_x, add_y, octaves, delta, scale)
@C# void TCODHeightMap::scaleFbm(TCODNoise noise, float mul_x, float mul_y, float add_x, float add_y, float octaves, float delta, float scale)
*/
void scaleFbm(TCODNoise *noise,float mul_x, float mul_y, float add_x, float add_y, float octaves, float delta, float scale);
/**
@PageName heightmap_modify
@FuncTitle Dig along a Bezier curve
@FuncDesc This function carve a path along a cubic Bezier curve using the digHill function.
Could be used for roads/rivers/...
Both radius and depth can vary linearly along the path.
@Cpp void TCODHeightMap::digBezier(int px[4], int py[4], float startRadius, float startDepth, float endRadius, float endDepth)
@C void TCOD_heightmap_dig_bezier(TCOD_heightmap_t *hm, int px[4], int py[4], float startRadius, float startDepth, float endRadius, float endDepth)
@Py heightmap_dig_bezier(hm, px, py, startRadius, startDepth, endRadius, endDepth)
@C# void TCODHeightMap::digBezier(int[] px, int[] py, float startRadius, float startDepth, float endRadius, float endDepth)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param px,py The coordinates of the 4 Bezier control points.
@Param startRadius The path radius in map cells at point P0. Might be < 1.0
@Param startDepth The path depth at point P0.
@Param endRadius The path radius in map cells at point P3. Might be < 1.0
@Param endDepth The path depth at point P3.
*/
void digBezier(int px[4], int py[4], float startRadius, float startDepth, float endRadius, float endDepth);
/**
@PageName heightmap_read
@PageFather heightmap
@PageTitle Reading data from the heightmap
@PageDesc Those functions return raw or computed information about the heightmap.
@FuncTitle Get the value of a cell
@FuncDesc This function returns the height value of a map cell.
@Cpp float TCODHeightMap::getValue(int x, int y) const
@C float TCOD_heightmap_get_value(const TCOD_heightmap_t *hm, int x, int y)
@Py heightmap_get_value(hm, x, y)
@C# float TCODHeightMap::getValue(int x, int y)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param x,y Coordinates of the map cell.
0 <= x < map width
0 <= y < map height
*/
inline float getValue(int x, int y) const {
return values[x+y*w];
}
/**
@PageName heightmap_read
@FuncTitle Interpolate the height
@FuncDesc This function returns the interpolated height at non integer coordinates.
@Cpp float TCODHeightMap::getInterpolatedValue(float x, float y) const
@C float TCOD_heightmap_get_interpolated_value(const TCOD_heightmap_t *hm, float x, float y)
@Py heightmap_get_interpolated_value(hm, x, y)
@C# float TCODHeightMap::getInterpolatedValue(float x, float y)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param x,y Coordinates of the map cell.
0 <= x < map width
0 <= y < map height
*/
float getInterpolatedValue(float x, float y) const;
/**
@PageName heightmap_read
@FuncTitle Get the map slope
@FuncDesc This function returns the slope between 0 and PI/2 at given coordinates.
@Cpp float TCODHeightMap::getSlope(int x, int y) const
@C float TCOD_heightmap_get_slope(const TCOD_heightmap_t *hm, int x, int y)
@Py heightmap_get_slope(hm, x, y)
@C# float TCODHeightMap::getSlope(int x, int y)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param x,y Coordinates of the map cell.
0 <= x < map width
0 <= y < map height
*/
float getSlope(int x, int y) const; // returns the slope in radian between 0 and PI/2
/**
@PageName heightmap_read
@FuncTitle Get the map normal
@FuncDesc This function returns the map normal at given coordinates.
@Cpp void TCODHeightMap::getNormal(float x, float y,float n[3], float waterLevel=0.0f) const
@C void TCOD_heightmap_get_normal(const TCOD_heightmap_t *hm, float x, float y, float n[3], float waterLevel)
@Py heightmap_get_normal(hm, x, y, waterLevel) # returns nx,ny,nz
@C# void TCODHeightMap::getNormal(float x, float y, float[] n, float waterLevel)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param x,y Coordinates of the map cell.
0 <= x < map width
0 <= y < map height
@Param n The function stores the normalized normal vector in this array.
@Param waterLevel The map height is clamped at waterLevel so that the sea is flat.
*/
void getNormal(float x, float y,float n[3], float waterLevel=0.0f) const; // returns the surface normal or (0,0,1) if beyond water level.
/**
@PageName heightmap_read
@FuncTitle Count the map cells inside a height range
@FuncDesc This function returns the number of map cells which value is between min and max.
@Cpp int TCODHeightMap::countCells(float min,float max) const
@C int TCOD_heightmap_count_cells(const TCOD_heightmap_t *hm, float min, float max)
@Py heightmap_count_cells(hm, min, max)
@C# int TCODHeightMap::countCells(float min, float max)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param min,max Only cells which value is >=min and <= max are counted.
*/
int countCells(float min,float max) const;
/**
@PageName heightmap_read
@FuncTitle Check if the map is an island
@FuncDesc This function checks if the cells on the map border are below a certain height.
@Cpp bool TCODHeightMap::hasLandOnBorder(float waterLevel) const
@C bool TCOD_heightmap_has_land_on_border(const TCOD_heightmap_t *hm, float waterLevel)
@Py heightmap_has_land_on_border(hm, waterLevel)
@C# bool TCODHeightMap::hasLandOnBorder(float waterLevel)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param waterLevel Return true only if no border cell is > waterLevel.
*/
bool hasLandOnBorder(float waterLevel) const;
/**
@PageName heightmap_read
@FuncTitle Get the map min and max values
@FuncDesc This function calculates the min and max of all values inside the map.
@Cpp void TCODHeightMap::getMinMax(float *min, float *max) const
@C void TCOD_heightmap_get_minmax(const TCOD_heightmap_t *hm, float *min, float *max)
@Py heightmap_get_minmax(hm) # returns min,max
@C# void TCODHeightMap::getMinMax(out float min, out float max)
@Param hm In the C version, the address of the heightmap struct returned by the creation function.
@Param min, max The min and max values are returned in these variables.
*/
void getMinMax(float *min, float *max) const;
// void heatErosion(int nbPass,float minSlope,float erosionCoef,float sedimentationCoef,TCODRandom *rnd);
/**
@PageName heightmap_modify
@FuncTitle Generate a map with mid-point displacement
@FuncDesc This algorithm generates a realistic fractal heightmap using the <a href="http://en.wikipedia.org/wiki/Diamond-square_algorithm">diamond-square</a> (or random midpoint displacement) algorithm.
The roughness range should be comprised between 0.4 and 0.6. The image below show the same map with roughness varying from 0.4 to 0.6.
<img src="midpoint.png" />
It's also a good habit to normalize the map after using this algorithm to avoid unexpected heights.
@Cpp void TCODHeightMap::midPointDisplacement(TCODRandom *rng=NULL,float roughness=0.45f)
@C void TCOD_heightmap_mid_point_displacement(TCOD_heightmap_t *hm, TCOD_random_t rnd, float roughness)
@Py heightmap_mid_point_displacement(hm, rng, roughness)
@Param hm In the C and Python version, the address of the heightmap struct returned by the creation function.
@Param rng Random number generation to use, or NULL/0 to use the default one.
@Param roughness Map roughness.
*/
void midPointDisplacement(TCODRandom *rnd = NULL, float roughness=0.45f);
void islandify(float seaLevel,TCODRandom *rnd); // lowers the terrain near the heightmap borders
// TODO : checks island connectivity with floodfill
private :
// void setMPDHeight(TCODRandom *rnd,int x,int y, float z, float offset);
// void setMDPHeightSquare(TCODRandom *rnd,int x, int y, int initsz, int sz,float offset);
};
#endif

View file

@ -0,0 +1,122 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_IMAGE_H
#define _TCOD_IMAGE_H
#include "color.h"
#include "console_types.h"
#include "error.h"
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
struct TCOD_mipmap_ {
int width, height;
float fwidth, fheight;
TCOD_ColorRGB* __restrict buf;
bool dirty;
};
typedef struct TCOD_Image {
int nb_mipmaps;
struct TCOD_mipmap_* __restrict mipmaps;
TCOD_ColorRGB key_color;
bool has_key_color;
} TCOD_Image;
typedef TCOD_Image* TCOD_image_t;
TCODLIB_API TCOD_Image* TCOD_image_new(int width, int height);
/**
* Return a new image rendered from a console.
*
* This effectively returns a screenshot of the console.
*/
TCODLIB_API TCOD_Image* TCOD_image_from_console(const TCOD_Console* console);
/**
* Same as TCOD_image_from_console, but with an existing image.
*/
TCODLIB_API void TCOD_image_refresh_console(TCOD_Image* image, const TCOD_Console* console);
TCODLIB_API void TCOD_image_clear(TCOD_Image* image, TCOD_color_t color);
TCODLIB_API void TCOD_image_invert(TCOD_Image* image);
TCODLIB_API void TCOD_image_hflip(TCOD_Image* image);
TCODLIB_API void TCOD_image_rotate90(TCOD_Image* image, int numRotations);
TCODLIB_API void TCOD_image_vflip(TCOD_Image* image);
TCODLIB_API void TCOD_image_scale(TCOD_Image* image, int new_w, int new_h);
#ifndef NO_SDL
TCODLIB_API TCOD_Image* TCOD_image_load(const char* filename);
/**
Save an image to a PNG or BMP file.
Returns a negative error code on failure. Check TCOD_get_error for details.
\rst
.. versionchanged:: 1.16
Now returns TCOD_Error.
\endrst
*/
TCODLIB_API TCOD_Error TCOD_image_save(const TCOD_Image* image, const char* filename);
#endif // NO_SDL
TCODLIB_API void TCOD_image_get_size(const TCOD_Image* image, int* w, int* h);
TCODLIB_API TCOD_color_t TCOD_image_get_pixel(const TCOD_Image* image, int x, int y);
TCODLIB_API int TCOD_image_get_alpha(const TCOD_Image* image, int x, int y);
/**
* Return a mipmapped pixel of image.
*
* Mipmaps are updated when you call this, so it can't be called from multiple
* threads.
*/
TCODLIB_API TCOD_color_t TCOD_image_get_mipmap_pixel(TCOD_Image* image, float x0, float y0, float x1, float y1);
TCODLIB_API void TCOD_image_put_pixel(TCOD_Image* image, int x, int y, TCOD_color_t col);
TCODLIB_API void TCOD_image_blit(
TCOD_Image* image,
TCOD_console_t console,
float x,
float y,
TCOD_bkgnd_flag_t bkgnd_flag,
float scale_x,
float scale_y,
float angle);
TCODLIB_API void TCOD_image_blit_rect(
TCOD_Image* image, TCOD_console_t console, int x, int y, int w, int h, TCOD_bkgnd_flag_t bkgnd_flag);
TCODLIB_API void TCOD_image_blit_2x(
const TCOD_Image* __restrict image, TCOD_Console* __restrict dest, int dx, int dy, int sx, int sy, int w, int h);
TCODLIB_API void TCOD_image_delete(TCOD_Image* image);
TCODLIB_API void TCOD_image_set_key_color(TCOD_Image* image, TCOD_color_t key_color);
TCODLIB_API bool TCOD_image_is_pixel_transparent(const TCOD_Image* image, int x, int y);
#ifdef __cplusplus
}
namespace tcod {} // namespace tcod
#endif // __cplusplus
#endif /* _TCOD_IMAGE_H */

View file

@ -0,0 +1,560 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
#ifndef _TCOD_IMAGE_HPP
#define _TCOD_IMAGE_HPP
#include "color.hpp"
#include "console.hpp"
#include "image.h"
#include "matrix.hpp"
class TCODConsole;
class TCODLIB_API TCODImage {
public :
/**
@PageName image
@PageTitle Image toolkit
@PageCategory Base toolkits
@PageDesc This toolkit contains some image manipulation utilities.
*/
/// @brief Default constructs an image. This will be in a partially invalid state until assigned a real image.
TCODImage() noexcept = default;
/**
@PageName image_create
@PageTitle Creating an image
@PageFather image
@FuncTitle Creating an empty image
@FuncDesc You can create an image of any size, filled with black with this function.
@Cpp TCODImage::TCODImage(int width, int height)
@C TCOD_image_t TCOD_image_new(int width, int height)
@Py image_new( width, height)
@C# TCODImage::TCODImage(int width, int height)
@Param width,height Size of the image in pixels.
@CppEx TCODImage *pix = new TCODImage(80,50);
@CEx TCOD_image_t pix = TCOD_image_new(80,50);
@PyEx pix = libtcod.image_new(80,50)
*/
TCODImage(int width, int height);
/**
@PageName image_create
@FuncTitle Loading a .bmp or .png image
@FuncDesc You can read data from a .bmp or .png file (for example to draw an image using the background color of the console cells).
Note that only 24bits and 32bits PNG files are currently supported.
@Cpp TCODImage::TCODImage(const char *filename)
@C TCOD_image_t TCOD_image_load(const char *filename)
@Py image_load(filename)
@C# TCODImage::TCODImage(string filename)
@Param filename Name of the .bmp or .png file to load.
@CppEx TCODImage *pix = new TCODImage("mypic.bmp");
@CEx TCOD_image_t pix = TCOD_image_load("mypic.bmp");
@PyEx pix = libtcod.image_load("mypic.bmp")
*/
TCODImage(const char *filename);
/**
@PageName image_create
@FuncTitle Creating an image from a console
@FuncDesc You can create an image from any console (either the root console or an offscreen console).
The image size will depend on the console size and the font characters size.
You can then save the image to a file with the save function.
@Cpp TCODImage::TCODImage(const TCODConsole *console)
@C TCOD_image_t TCOD_image_from_console(TCOD_console_t console)
@Py image_from_console(console)
@C# TCODImage::TCODImage(TCODConsole console)
@Param console The console to convert. In the C version, use NULL for the root console.
@CppEx TCODImage *pix = new TCODImage(TCODConsole::root);
@CEx TCOD_image_t pix = TCOD_image_from_console(NULL);
@PyEx pix = libtcod.image_from_console(0)
*/
TCODImage(const TCODConsole *console);
TCODImage(const TCODImage&) = delete;
TCODImage& operator=(const TCODImage&) = delete;
TCODImage(TCODImage&& rhs) noexcept {
std::swap(data, rhs.data);
std::swap(deleteData, rhs.deleteData);
};
TCODImage& operator=(TCODImage&& rhs) noexcept {
std::swap(data, rhs.data);
std::swap(deleteData, rhs.deleteData);
return *this;
};
// clang-format on
/***************************************************************************
@brief Construct a new TCODImage object from a Matrix of pixels.
This constructor is provisional.
@param pixels A 2D matrix of RGB pixels.
*/
explicit TCODImage(const tcod::Matrix<TCOD_ColorRGB, 2>& pixels)
: TCODImage(pixels.get_shape().at(0), pixels.get_shape().at(1)) {
for (int y = 0; y < pixels.get_shape().at(1); ++y) {
for (int x = 0; x < pixels.get_shape().at(0); ++x) {
putPixel(x, y, pixels[{x, y}]);
}
}
}
// clang-format off
/**
@PageName image_create
@FuncTitle refreshing an image created from a console
@FuncDesc If you need to refresh the image with the console's new content, you don't have to delete it and create another one. Instead, use this function. Note that you must use the same console that was used in the TCOD_image_from_console call (or at least a console with the same size).
@Cpp void TCODImage::refreshConsole(const TCODConsole *console)
@C void TCOD_image_refresh_console(TCOD_image_t image, TCOD_console_t console)
@Py image_refresh_console(image, console)
@C# void TCODImage::refreshConsole(TCODConsole console)
@Param image In the C version, the image created with TCOD_image_from_console.
@Param console The console to capture. In the C version, use NULL for the root console.
@CppEx
TCODImage *pix = new TCODImage(TCODConsole::root); // create an image from the root console
// ... modify the console
pix->refreshConsole(TCODConsole::root); // update the image with the console's new content
@CEx
TCOD_image_t pix = TCOD_image_from_console(NULL);
// ... modify the console ..
TCOD_image_refresh_console(pix,NULL);
@PyEx
pix = libtcod.image_from_console(0)
# ... modify the console ..
libtcod.image_refresh_console(pix,0)
*/
void refreshConsole(const TCODConsole *console);
/**
@PageName image_read
@PageTitle Reading data from a TCODImage
@PageFather image
@FuncTitle Getting the size of an image
@FuncDesc You can read the size of an image in pixels with this function.
@Cpp void TCODImage::getSize(int *w,int *h) const
@C void TCOD_image_get_size(TCOD_image_t image, int *w,int *h)
@Py image_get_size(image) # returns w,h
@C# void TCODImage::getSize(out int w, out int h)
@Param image In the C version, the image handler, obtained with the load function.
@Param w,h When the function returns, those variables contain the size of the image.
@CppEx
TCODImage *pix = new TCODImage(80,50);
int w,h;
pix->getSize(&w,&h); // w = 80, h = 50
@CEx
TCOD_image_t pix = TCOD_image_new(80,50);
int w,h;
TCOD_image_get_size(pix,&w,&h); // w = 80, h = 50
@PyEx
pix = libtcod.image_new(80,50)
w,h=libtcod.image_get_size(pix)
# w = 80, h = 50
*/
void getSize(int *w,int *h) const;
/**
@PageName image_read
@FuncTitle Getting the color of a pixel
@FuncDesc You can read the colors from an image with this function.
@Cpp TCODColor TCODImage::getPixel(int x, int y) const
@C TCOD_color_t TCOD_image_get_pixel(TCOD_image_t image,int x, int y)
@Py image_get_pixel(image, x, y)
@C# TCODColor TCODImage::getPixel(int x, int y)
@Param image In the C and Python version, the image handler, obtained with the load function.
@Param x,y The pixel coordinates inside the image.
0 <= x < width
0 <= y < height
@CppEx
TCODImage *pix = new TCODImage(80,50);
TCODColor col=pix->getPixel(40,25);
@CEx
TCOD_image_t pix = TCOD_image_new(80,50);
TCOD_color_t col=TCOD_image_get_pixel(pix,40,25);
@PyEx
pix = libtcod.image_new(80,50)
col=libtcod.image_get_pixel(pix,40,25)
*/
TCODColor getPixel(int x, int y) const;
/**
@PageName image_read
@FuncTitle Getting the alpha value of a pixel
@FuncDesc If you have set a key color for this image with setKeyColor, or if this image was created from a 32 bits PNG file (with alpha layer), you can get the pixel transparency with this function. This function returns a value between 0 (transparent pixel) and 255 (opaque pixel).
@Cpp int TCODImage::getAlpha(int x, int y) const
@C int TCOD_image_get_alpha(TCOD_image_t image, int x, int y)
@Py image_get_alpha(image, x, y)
@C# int TCODImage::getAlpha(int x, int y)
@Param image In the C and Python version, the image handler, obtained with the load function.
@Param x,y The pixel coordinates inside the image.
0 <= x < width
0 <= y < height
*/
int getAlpha(int x,int y) const;
/**
@PageName image_read
@FuncTitle Checking if a pixel is transparent
@FuncDesc You can use this simpler version (for images with alpha layer, returns true only if alpha == 0) :
@Cpp bool TCODImage::isPixelTransparent(int x,int y) const
@C bool TCOD_image_is_pixel_transparent(TCOD_image_t image,int x, int y)
@Py image_is_pixel_transparent(image, x, y)
@C# bool TCODImage::isPixelTransparent(int x,int y)
@Param image In the C and Python version, the image handler, obtained with the load function.
@Param x,y The pixel coordinates inside the image.
0 <= x < width
0 <= y < height
*/
bool isPixelTransparent(int x, int y) const;
/**
@PageName image_read
@FuncTitle Getting the average color of a part of the image
@FuncDesc This method uses mipmaps to get the average color of an arbitrary rectangular region of the image.
It can be used to draw a scaled-down version of the image. It's used by libtcod's blitting functions.
@Cpp TCODColor TCODImage::getMipmapPixel(float x0,float y0, float x1, float y1)
@C TCOD_color_t TCOD_image_get_mipmap_pixel(TCOD_image_t image,float x0,float y0, float x1, float y1)
@Py image_get_mipmap_pixel(image,x0,y0, x1, y1)
@C# TCODColor TCODImage::getMipmapPixel(float x0,float y0, float x1, float y1)
@Param image In the C version, the image handler, obtained with the load function.
@Param x0,y0 Coordinates in pixels of the upper-left corner of the region.
0.0 <= x0 < x1
0.0 <= y0 < y1
@Param x1,y1 Coordinates in pixels of the lower-right corner of the region.
x0 < x1 < width
y0 < y1 < height
@CppEx
// Get the average color of a 5x5 "superpixel" in the center of the image.
TCODImage *pix = new TCODImage(80,50);
TCODColor col=pix->getMipMapPixel(37.5f, 22.5f, 42.5f, 28.5f);
@CEx
TCOD_image_t pix = TCOD_image_new(80,50);
TCOD_color_t col=TCOD_image_get_mipmap_pixel(pix,37.5f, 22.5f, 42.5f, 28.5f);
@PyEx
pix = libtcod.image_new(80,50)
col=libtcod.image_get_mipmap_pixel(pix,37.5, 22.5, 42.5, 28.5)
*/
TCODColor getMipmapPixel(float x0,float y0, float x1, float y1);
/**
@PageName image_update
@PageTitle Updating an image
@PageFather image
@FuncTitle Filling an image with a color
@FuncDesc You can fill the whole image with a color with :
@Cpp void TCODImage::clear(const TCODColor color)
@C void TCOD_image_clear(TCOD_image_t image, TCOD_color_t color)
@Py image_clear(image,color)
@C# void TCODImage::clear(TCODColor color)
@Param image In the C and Python version, the image to fill.
@Param color The color to use.
*/
void clear(const TCODColor col);
/**
@PageName image_update
@FuncTitle Changing the color of a pixel
@Cpp TCODColor TCODImage::putPixel(int x, int y, const TCODColor col)
@C void TCOD_image_put_pixel(TCOD_image_t image,int x, int y,TCOD_color_t col)
@Py image_put_pixel(image,x, y,col)
@C# TCODColor TCODImage::putPixel(int x, int y, TCODColor col)
@Param image In the C version, the image handler, obtained with the load function.
@Param x,y The pixel coordinates inside the image.
0 <= x < width
0 <= y < height
@Param col The new color of the pixel.
*/
void putPixel(int x, int y, const TCODColor col);
/**
@PageName image_update
@FuncTitle Scaling an image
@FuncDesc You can resize an image and scale its content. If new_w < old_w or new_h < old_h, supersampling is used to scale down the image. Else the image is scaled up using nearest neighbor.
@Cpp void TCODImage::scale(int new_w, int new_h)
@C void TCOD_image_scale(TCOD_image_t image,int new_w, int new_h)
@Py image_scale(image, new_w,new_h)
@C# void TCODImage::scale(int new_w, int new_h)
@Param image In the C and Python version, the image handler, obtained with the load function.
@Param new_w,new_h The new size of the image.
*/
void scale(int new_w, int new_h);
/**
@PageName image_update
@FuncTitle Flipping the image horizontally
@Cpp void TCODImage::hflip()
@C void TCOD_image_hflip(TCOD_image_t image)
@Py image_hflip(image)
@C# void TCODImage::hflip()
@Param image In the C and Python version, the image handler, obtained with the load function.
*/
void hflip();
/**
@PageName image_update
@FuncTitle Flipping the image vertically
@Cpp void TCODImage::vflip()
@C void TCOD_image_vflip(TCOD_image_t image)
@Py image_vflip(image)
@C# void TCODImage::vflip()
@Param image In the C and Python version, the image handler, obtained with the load function.
*/
void vflip();
/**
@PageName image_update
@FuncTitle Rotating the image clockwise
@FuncDesc Rotate the image clockwise by increment of 90 degrees.
@Cpp void TCODImage::rotate90(int numRotations=1)
@C void TCOD_image_rotate90(TCOD_image_t image, int numRotations)
@Py image_rotate90(image, num=1)
@C# void TCODImage::rotate90(int numRotations)
@Param image In the C and Python version, the image handler, obtained with the load function.
@Param numRotations Number of 90 degrees rotations. Should be between 1 and 3.
*/
void rotate90(int numRotations=1);
/**
@PageName image_update
@FuncTitle Inverting the colors of the image
@Cpp void TCODImage::invert()
@C void TCOD_image_invert(TCOD_image_t image)
@Py image_invert(image)
@C# void TCODImage::invert()
@Param image In the C and Python version, the image handler, obtained with the load function.
*/
void invert();
/**
@PageName image_save
@PageFather image
@PageTitle Saving an image to a bmp or png file.
@PageDesc You can save an image to a 24 bits .bmp or .png file.
@Cpp void TCODImage::save(const char *filename)
@C void TCOD_image_save(TCOD_image_t image, const char *filename)
@Py image_save(image, filename)
@C# void TCODImage::save(string filename)
@Param image In the C version, the image handler, obtained with any image creation function.
@Param filename Name of the .bmp or .png file.
@CppEx
TCODImage *pix = new TCODImage(10,10);
pix->save("mypic.bmp");
@CEx
TCOD_image_t pix = TCOD_image_from_console(my_offscreen_console);
TCOD_image_save(pix,"mypic.bmp");
@PyEx
pix = libtcod.image_from_console(my_offscreen_console)
libtcod.image_save(pix,"mypic.bmp")
*/
void save(const char *filename) const;
/**
@PageName image_blit
@PageFather image
@PageTitle Blitting an image on a console
@FuncTitle Standard blitting
@FuncDesc This function blits a rectangular part of the image on a console without scaling it or rotating it. Each pixel of the image fills a console cell.
@Cpp void TCODImage::blitRect(TCODConsole *console, int x, int y, int w=-1, int h=-1, TCOD_bkgnd_flag_t bkgnd_flag = TCOD_BKGND_SET ) const
@C void TCOD_image_blit_rect(TCOD_image_t image, TCOD_console_t console, int x, int y, int w, int h, TCOD_bkgnd_flag_t bkgnd_flag)
@Py image_blit_rect(image, console, x, y, w, h, bkgnd_flag)
@C#
void TCODImage::blitRect(TCODConsole console, int x, int y)
void TCODImage::blitRect(TCODConsole console, int x, int y, int w)
void TCODImage::blitRect(TCODConsole console, int x, int y, int w, int h)
void TCODImage::blitRect(TCODConsole console, int x, int y, int w, int h, TCODBackgroundFlag bkgnd_flag)
@Param image In the C version, the image handler, obtained with the load function.
@Param console The console on which the image will be drawn. In the C version, use NULL for the root console.
@Param x,y Coordinates in the console of the upper-left corner of the image.
@Param w,h Dimension of the image on the console. Use -1,-1 to use the image size.
@Param flag This flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t.
*/
void blitRect(TCODConsole *console, int x, int y, int w=-1, int h=-1, TCOD_bkgnd_flag_t bkgnd_flag = TCOD_BKGND_SET ) const;
void blitRect(TCOD_Console &console, int x, int y, int w=-1, int h=-1, TCOD_bkgnd_flag_t bkgnd_flag = TCOD_BKGND_SET ) const {
TCOD_image_blit_rect(data, &console, x, y, w, h, bkgnd_flag);
}
/**
@PageName image_blit
@FuncTitle Blitting with scaling and/or rotation
@FuncDesc This function allows you to specify the floating point coordinates of the center
of the image, its scale and its rotation angle.
@Cpp void TCODImage::blit(TCODConsole *console, float x, float y, TCOD_bkgnd_flag_t bkgnd_flag = TCOD_BKGND_SET, float scale_x=1.0f, float scale_y=1.0f, float angle=0.0f) const
@C void TCOD_image_blit(TCOD_image_t image, TCOD_console_t console, int x, int y, TCOD_bkgnd_flag_t bkgnd_flag, float scale_x, float scale_y, float angle)
@Py image_blit(image, console, x, y, bkgnd_flag, scale_x, scale_y, angle)
@C#
void TCODImage::blit(TCODConsole console, float x, float y)
void TCODImage::blit(TCODConsole console, float x, float y, TCODBackgroundFlag bkgnd_flag)
void TCODImage::blit(TCODConsole console, float x, float y, TCODBackgroundFlag bkgnd_flag, float scale_x)
void TCODImage::blit(TCODConsole console, float x, float y, TCODBackgroundFlag bkgnd_flag, float scale_x, float scale_y)
void TCODImage::blit(TCODConsole console, float x, float y, TCODBackgroundFlag bkgnd_flag, float scale_x, float scale_y, float angle)
@Param image In the C version, the image handler, obtained with the load function.
@Param console The console on which the image will be drawn. In the C version, use NULL for the root console.
@Param x,y Coordinates in the console of the center of the image.
@Param flag This flag defines how the cell's background color is modified. See TCOD_bkgnd_flag_t.
@Param scale_x,scale_y Scale coefficient. Must be > 0.0.
@Param angle Rotation angle in radians.
*/
void blit(TCODConsole *console, float x, float y, TCOD_bkgnd_flag_t bkgnd_flag = TCOD_BKGND_SET, float scale_x=1.0f, float scale_y=1.0f, float angle=0.0f) const;
void blit(TCOD_Console& console, float x, float y, TCOD_bkgnd_flag_t bkgnd_flag = TCOD_BKGND_SET, float scale_x=1.0f, float scale_y=1.0f, float angle=0.0f) const {
TCOD_image_blit(data, &console, x, y, bkgnd_flag, scale_x, scale_y, angle);
}
/**
@PageName image_blit
@FuncTitle Blitting with a mask
@FuncDesc When blitting an image, you can define a key color that will be ignored by the blitting function. This makes it possible to blit non rectangular images or images with transparent pixels.
@Cpp void TCODImage::setKeyColor(const TCODColor keyColor)
@C void TCOD_image_set_key_color(TCOD_image_t image, TCOD_color_t keyColor)
@Py image_set_key_color(image, keyColor)
@C# void TCODImage::setKeyColor(TCODColor keyColor)
@Param image In the C and Python version, the image handler, obtained with the load function.
@Param color Pixels with this color will be skipped by blitting functions.
@CppEx
TCODImage *pix = TCODImage("mypix.bmp");
pix->setKeyColor(TCODColor::red);
// blitting the image, omitting red pixels
pix->blitRect(TCODConsole::root,40,25);
@CEx
TCOD_image_t pix = TCOD_image_new(10,10);
TCOD_image_set_key_color(pix,TCOD_red);
TCOD_image_blit_rect(pix,NULL,40,25,5,5,TCOD_BKGND_SET);
@PyEx
pix = libtcod.image_new(10,10)
libtcod.image_set_key_color(pix,libtcod.red)
libtcod.image_blit_rect(pix,0,40,25,5,5,libtcod.BKGND_SET)
*/
void setKeyColor(const TCODColor keyColor);
/**
@PageName image_blit
@FuncTitle Blitting with subcell resolution
@FuncDesc Eventually, you can use some special characters in the libtcod fonts :
<img src="subcell.png">
to double the console resolution using this blitting function.
<table><tr><td>
Comparison before/after subcell resolution in TCOD :<br />
<img src="subcell_comp.png"></td><td>
Pyromancer ! screenshot, making full usage of subcell resolution :<br />
<img src="subcell_pyro.png"></td></tr></table>
@Cpp void TCODImage::blit2x(TCODConsole *dest, int dx, int dy, int sx=0, int sy=0, int w=-1, int h=-1 ) const;
@C void TCOD_image_blit_2x(TCOD_image_t image, TCOD_console_t dest, int dx, int dy, int sx, int sy, int w, int h);
@Py image_blit_2x(image, dest, dx, dy, sx=0, sy=0, w=-1, h=-1)
@C#
void TCODImage::blit2x(TCODConsole dest, int dx, int dy);
void TCODImage::blit2x(TCODConsole dest, int dx, int dy, int sx);
void TCODImage::blit2x(TCODConsole dest, int dx, int dy, int sx, int sy);
void TCODImage::blit2x(TCODConsole dest, int dx, int dy, int sx, int sy, int w);
void TCODImage::blit2x(TCODConsole dest, int dx, int dy, int sx, int sy, int w, int h);
@Param image In the C and Python version, the image handler, obtained with the load function.
@Param dest The console of which the image will be blitted. Foreground, background and character data will be overwritten.
@Param dx,dy Coordinate of the console cell where the upper left corner of the blitted image will be.
@Param sx,sy,w,h Part of the image to blit. Use -1 in w and h to blit the whole image.
*/
void blit2x(TCODConsole *dest, int dx, int dy, int sx=0, int sy=0, int w=-1, int h=-1) const;
[[deprecated("This call is replaced by tcod::draw_quartergraphics.")]]
void blit2x(TCOD_Console& dest, int dx, int dy, int sx=0, int sy=0, int w=-1, int h=-1) const {
TCOD_image_blit_2x(data, &dest, dx, dy, sx, sy, w, h);
}
/**
Return the pointer to this objects TCOD_Image data.
\rst
.. versionadded:: 1.17
\endrst
*/
TCOD_Image* get_data() noexcept { return data; }
/**
Return the const pointer to this objects TCOD_Image data.
\rst
.. versionadded:: 1.17
\endrst
*/
const TCOD_Image* get_data() const noexcept { return data; }
TCODImage(TCOD_image_t img) : data(img), deleteData(false) {}
virtual ~TCODImage();
/***************************************************************************
@brief Allow implicit conversions to TCOD_Image&.
\rst
.. versionadded:: 1.19
\endrst
*/
[[nodiscard]] operator TCOD_Image&() { return *data; }
/***************************************************************************
@brief Allow implicit conversions to const TCOD_Image&.
\rst
.. versionadded:: 1.19
\endrst
*/
[[nodiscard]] operator const TCOD_Image&() const { return *data; }
protected :
friend class TCODLIB_API TCODSystem;
friend class TCODLIB_API TCODZip;
struct TCOD_Image *data{nullptr};
bool deleteData{false};
};
// clang-format on
namespace tcod {
/***************************************************************************
@brief Draw a double resolution image on a console using quadrant character glyphs.
@param dest The console to draw to.
@param source The source image which will be rendered.
@param dest_xy The upper-left position to where the source will be drawn.
@param source_rect The `{left, top, width, height}` region of the source image to draw.
A width or height of -1 will use the full size of the image.
@code{.cpp}
auto console = tcod::Console{80, 50};
TCODImage* image = new TCODImage(console.get_width() * 2, console.get_height() * 2);
tcod::draw_quartergraphics(console, image);
@endcode
\rst
.. versionadded:: 1.19
\endrst
*/
inline void draw_quartergraphics(
TCOD_Console& dest,
const TCOD_Image& source,
const std::array<int, 2>& dest_xy = {0, 0},
const std::array<int, 4>& src_rect = {0, 0, -1, -1}) {
TCOD_image_blit_2x(
&source, &dest, dest_xy.at(0), dest_xy.at(1), src_rect.at(0), src_rect.at(1), src_rect.at(2), src_rect.at(3));
}
} // namespace tcod
#endif /* _TCOD_IMAGE_HPP */

View file

@ -0,0 +1,126 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
/// This is a libtcod internal module.
/// Use at your own risk.
/// @cond INTERNAL
#ifndef TCOD_LEX_H_
#define TCOD_LEX_H_
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
#define TCOD_LEX_FLAG_NOCASE 1
#define TCOD_LEX_FLAG_NESTING_COMMENT 2
#define TCOD_LEX_FLAG_TOKENIZE_COMMENTS 4
#define TCOD_LEX_ERROR -1
#define TCOD_LEX_UNKNOWN 0
#define TCOD_LEX_SYMBOL 1
#define TCOD_LEX_KEYWORD 2
#define TCOD_LEX_IDEN 3
#define TCOD_LEX_STRING 4
#define TCOD_LEX_INTEGER 5
#define TCOD_LEX_FLOAT 6
#define TCOD_LEX_CHAR 7
#define TCOD_LEX_EOF 8
#define TCOD_LEX_COMMENT 9
#define TCOD_LEX_MAX_SYMBOLS 100
#define TCOD_LEX_SYMBOL_SIZE 5
#define TCOD_LEX_MAX_KEYWORDS 100
#define TCOD_LEX_KEYWORD_SIZE 20
typedef struct TCOD_lex_t {
int file_line; // Current line number.
int token_type; // One of the TCOD_LEX_* values.
int token_int_val;
int token_idx;
float token_float_val;
char* tok;
int toklen;
char lastStringDelim;
char* pos;
char* buf;
char* filename;
char* last_javadoc_comment;
/* private stuff */
int nb_symbols; // Current number of symbols in `symbols` array.
int nb_keywords; // Current number of keywords in `keywords` array.
int flags;
char symbols[TCOD_LEX_MAX_SYMBOLS][TCOD_LEX_SYMBOL_SIZE];
char keywords[TCOD_LEX_MAX_KEYWORDS][TCOD_LEX_KEYWORD_SIZE];
const char* simple_comment;
const char* comment_start;
const char* comment_stop;
const char* javadoc_comment_start;
const char* stringDelim;
bool javadoc_read;
bool allocBuf; // True if `buf` is owned by this object.
bool is_savepoint; // is this object a savepoint (no free in destructor)
} TCOD_lex_t;
TCODLIB_API TCOD_lex_t* TCOD_lex_new_intern(void);
TCODLIB_API TCOD_lex_t* TCOD_lex_new(
const char* const* symbols,
const char* const* keywords,
const char* simpleComment,
const char* commentStart,
const char* commentStop,
const char* javadocCommentStart,
const char* stringDelim,
int flags);
TCODLIB_API void TCOD_lex_delete(TCOD_lex_t* lex);
TCODLIB_API void TCOD_lex_set_data_buffer(TCOD_lex_t* lex, char* dat);
TCODLIB_API bool TCOD_lex_set_data_file(TCOD_lex_t* lex, const char* filename);
TCODLIB_API int TCOD_lex_parse(TCOD_lex_t* lex);
TCODLIB_API int TCOD_lex_parse_until_token_type(TCOD_lex_t* lex, int token_type);
TCODLIB_API int TCOD_lex_parse_until_token_value(TCOD_lex_t* lex, const char* token_value);
TCODLIB_API bool TCOD_lex_expect_token_type(TCOD_lex_t* lex, int token_type);
TCODLIB_API bool TCOD_lex_expect_token_value(TCOD_lex_t* lex, int token_type, const char* token_value);
TCODLIB_API void TCOD_lex_savepoint(TCOD_lex_t* lex, TCOD_lex_t* savepoint);
TCODLIB_API void TCOD_lex_restore(TCOD_lex_t* lex, TCOD_lex_t* savepoint);
TCODLIB_API char* TCOD_lex_get_last_javadoc(TCOD_lex_t* lex);
TCODLIB_API const char* TCOD_lex_get_token_name(int token_type);
TCODLIB_API int TCOD_lex_hextoint(char c);
#ifdef __cplusplus
}
#endif
#endif // TCOD_LEX_H_
/// @endcond

View file

@ -0,0 +1,119 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
/// This is a libtcod internal module.
/// Use at your own risk.
/// @cond INTERNAL
#ifndef TCOD_LEX_HPP_
#define TCOD_LEX_HPP_
#include "lex.h"
class TCODLIB_API TCODLex {
public:
TCODLex();
TCODLex(
const char** symbols,
const char** keywords,
const char* simpleComment="//",
const char* commentStart="/*",
const char* commentStop="*/",
const char* javadocCommentStart="/**",
const char* stringDelim="\"",
int flags=TCOD_LEX_FLAG_NESTING_COMMENT);
~TCODLex();
void setDataBuffer(char* dat);
bool setDataFile(const char* filename);
int parse();
int parseUntil(int tokenType);
int parseUntil(const char* tokenValue);
bool expect(int tokenType);
bool expect(int tokenType, const char* tokenValue);
void savepoint(TCODLex* savepoint);
void restore(TCODLex* savepoint);
char* getLastJavadoc();
int getFileLine()
{
return data->file_line;
}
int getTokenType()
{
return data->token_type;
}
int getTokenIntVal()
{
return data->token_int_val;
}
int getTokenIdx()
{
return data->token_idx;
}
float getTokenFloatVal()
{
return data->token_float_val;
}
char* getToken()
{
return data->tok;
}
char getStringLastDelimiter()
{
return data->lastStringDelim;
}
char* getPos()
{ return data->pos; }
char* getBuf()
{
return data->buf;
}
char* getFilename()
{
return data->filename;
}
char* getLastJavadocComment()
{
return data->last_javadoc_comment;
}
static const char* getTokenName(int tokenType)
{
return TCOD_lex_get_token_name(tokenType);
}
protected:
TCOD_lex_t* data;
};
#endif // TCOD_LEX_HPP_
/// @endcond

View file

@ -0,0 +1,107 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_H_
#define LIBTCOD_H_
#include "bresenham.h"
#include "bsp.h"
#include "color.h"
#include "console.h"
#include "console_drawing.h"
#include "console_etc.h"
#include "console_init.h"
#include "console_printing.h"
#include "console_rexpaint.h"
#include "context.h"
#include "context_init.h"
#include "error.h"
#include "fov.h"
#include "globals.h"
#include "heightmap.h"
#include "image.h"
#include "lex.h"
#include "list.h"
#include "logging.h"
#include "mersenne.h"
#include "mouse.h"
#include "namegen.h"
#include "noise.h"
#include "parser.h"
#include "path.h"
#include "pathfinder.h"
#include "pathfinder_frontier.h"
#include "portability.h"
#include "random.h"
#include "renderer_sdl2.h"
#include "sdl2/event.h"
#include "sys.h"
#include "tileset.h"
#include "tileset_bdf.h"
#include "tileset_fallback.h"
#include "tileset_render.h"
#include "tileset_truetype.h"
#include "tree.h"
#include "txtfield.h"
#include "utility.h"
#include "version.h"
#include "zip.h"
#ifdef __cplusplus
#include "bresenham.hpp"
#include "bsp.hpp"
#include "color.hpp"
#include "console.hpp"
#include "console_printing.hpp"
#include "console_rexpaint.hpp"
#include "console_types.hpp"
#include "context.hpp"
#include "fov.hpp"
#include "heightmap.hpp"
#include "image.hpp"
#include "lex.hpp"
#include "list.hpp"
#include "mersenne.hpp"
#include "mouse.hpp"
#include "namegen.hpp"
#include "noise.hpp"
#include "parser.hpp"
#include "path.hpp"
#include "sys.hpp"
#include "tileset.hpp"
#include "tileset_bdf.hpp"
#include "tileset_fallback.hpp"
#include "tree.hpp"
#include "txtfield.hpp"
#include "zip.hpp"
#endif // __cplusplus
#endif // LIBTCOD_H_

View file

@ -0,0 +1,32 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#include "libtcod.h"

View file

@ -0,0 +1,528 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCODLIB_INT_H_
#define TCODLIB_INT_H_
#include <assert.h>
#include <stdarg.h>
#ifdef __cplusplus
#include <stdexcept>
#include <string>
#endif // __cplusplus
#include "color.h"
#include "console_types.h"
#include "context.h"
#include "error.h"
#include "fov.h"
#include "fov_types.h"
#include "mersenne_types.h"
#include "portability.h"
#include "sys.h"
#include "tileset.h"
/* tcodlib internal stuff */
#ifdef __cplusplus
extern "C" {
#endif
/* SDL2 forward declarations */
struct SDL_Surface;
struct SDL_Window;
struct SDL_Renderer;
union SDL_Event;
typedef struct TCOD_internal_context_t {
/* number of characters in the bitmap font */
int fontNbCharHoriz;
int fontNbCharVertic;
/* font type and layout */
bool font_tcod_layout;
bool font_in_row;
bool font_greyscale;
int font_flags;
/* character size in font */
int font_width;
int font_height;
char font_file[512];
char window_title[512];
/* ascii code to tcod layout converter */
int* ascii_to_tcod;
/* whether each character in the font is a colored tile */
bool* colored;
/* the root console */
struct TCOD_Console* root;
/* nb chars in the font */
int max_font_chars;
/* fullscreen data */
bool fullscreen;
int fullscreen_offset_x;
int fullscreen_offset_y;
/* asked by the user */
int fullscreen_width;
int fullscreen_height;
/* actual resolution */
int actual_fullscreen_width;
int actual_fullscreen_height;
/* user post-processing callback */
SDL_renderer_t sdl_cbk;
/* fading data */
TCOD_color_t fading_color;
uint8_t fade;
TCOD_key_t key_state;
/* application window was closed */
bool is_window_closed;
/* application has mouse focus */
bool app_has_mouse_focus;
/* application is active (not iconified) */
bool app_is_active;
/**
Active tileset for libtcod.
Use TCOD_set_default_tileset when you want to change this value, since it
needs to trigger some important side-effects.
*/
struct TCOD_Tileset* tileset;
struct TCOD_Context* engine;
} TCOD_internal_context_t;
extern TCOD_internal_context_t TCOD_ctx;
#if defined(__ANDROID__) && !defined(NDEBUG)
#include <android/log.h>
#ifdef printf
#undef printf
#endif
#ifdef vprintf
#undef vprintf
#endif
#define printf(args...) __android_log_print(ANDROID_LOG_INFO, "libtcod", ##args)
#define vprintf(args...) __android_log_vprint(ANDROID_LOG_INFO, "libtcod", ##args)
#ifdef assert
#undef assert
#endif
#define assert(cond) \
if (!(cond)) __android_log_assert(#cond, "libtcod", "assertion failed: %s", #cond)
#endif
#ifdef NDEBUG
#define TCOD_IF(x) if (x)
#define TCOD_IFNOT(x) if (!(x))
#define TCOD_ASSERT(x)
#define TCOD_LOG(x)
#else
#define TCOD_IF(x) assert(x);
#define TCOD_IFNOT(x) \
assert(x); \
if (0)
#define TCOD_ASSERT(x) assert(x)
#define TCOD_LOG(x) printf x
#endif
/* fov internal stuff */
TCOD_Error TCOD_map_compute_fov_circular_raycasting(
TCOD_Map* __restrict map, int pov_x, int pov_y, int max_radius, bool light_walls);
TCOD_Error TCOD_map_compute_fov_diamond_raycasting(
TCOD_Map* __restrict map, int pov_x, int pov_y, int max_radius, bool light_walls);
TCOD_Error TCOD_map_compute_fov_recursive_shadowcasting(
TCOD_Map* __restrict map, int pov_x, int pov_y, int max_radius, bool light_walls);
TCOD_Error TCOD_map_compute_fov_permissive2(
TCOD_Map* __restrict map, int pov_x, int pov_y, int max_radius, bool light_walls, int permissiveness);
TCOD_Error TCOD_map_compute_fov_restrictive_shadowcasting(
TCOD_Map* __restrict map, int pov_x, int pov_y, int max_radius, bool light_walls);
TCOD_Error TCOD_map_compute_fov_symmetric_shadowcast(
TCOD_Map* __restrict map, int pov_x, int pov_y, int max_radius, bool light_walls);
TCOD_Error TCOD_map_postprocess(TCOD_Map* __restrict map, int pov_x, int pov_y, int radius);
/**
Return true if `x` and `y` are in the boundaries of `map`.
Returns false if `map` is NULL.
*/
static inline bool TCOD_map_in_bounds(const struct TCOD_Map* map, int x, int y) {
return map && 0 <= x && x < map->width && 0 <= y && y < map->height;
}
/* switch fullscreen mode */
TCOD_key_t TCOD_sys_check_for_keypress(int flags);
TCOD_key_t TCOD_sys_wait_for_keypress(bool flush);
bool TCOD_sys_is_key_pressed(TCOD_keycode_t key);
void TCOD_sys_pixel_to_tile(double* x, double* y);
/***************************************************************************
@brief Deprecated EASCII internal printing.
*/
int TCOD_console_print_internal(
TCOD_Console* con,
int x,
int y,
int w,
int h,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t align,
char* msg,
bool can_split,
bool count_only);
char* TCOD_console_vsprint(const char* fmt, va_list ap);
/* UTF-8 stuff */
#ifndef NO_UNICODE
wchar_t* TCOD_console_vsprint_utf(const wchar_t* fmt, va_list ap);
int TCOD_console_print_internal_utf(
TCOD_console_t con,
int x,
int y,
int rw,
int rh,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t align,
wchar_t* msg,
bool can_split,
bool count_only);
#endif
/* image manipulation */
TCODLIB_API struct SDL_Surface* TCOD_sys_load_image(const char* filename);
void TCOD_sys_get_image_size(const struct SDL_Surface* image, int* w, int* h);
TCOD_color_t TCOD_sys_get_image_pixel(const struct SDL_Surface* image, int x, int y);
int TCOD_sys_get_image_alpha(const struct SDL_Surface* image, int x, int y);
bool TCOD_sys_check_magic_number(const char* filename, size_t size, uint8_t* data);
/* TCOD_list nonpublic methods */
void TCOD_list_set_size(TCOD_list_t l, int size);
/*
SDL12/SDL2 abstraction layer
*/
typedef struct TCOD_SDL_driver_t {
float scale_xc;
float scale_yc;
/* get a fullscreen mode suitable for the console */
void (*get_closest_mode)(int* w, int* h);
/* render the console on a surface/texture */
void (*render)(const struct TCOD_SDL_driver_t* sdl, void* vbitmap, struct TCOD_Console* console);
/* create a new surface */
struct SDL_Surface* (*create_surface)(int width, int height, bool with_alpha);
/* create the game window */
void (*create_window)(int w, int h, bool fullscreen);
/* destroy the game window */
void (*destroy_window)(void);
/* switch fullscreen on/off */
void (*set_fullscreen)(bool fullscreen);
/* change the game window title */
void (*set_window_title)(const char* title);
/* save game screenshot */
void (*save_screenshot)(const char* filename);
/* get desktop resolution */
void (*get_current_resolution)(int* w, int* h);
/* change the mouse cursor position */
void (*set_mouse_position)(int x, int y);
/* clipboard */
const char* (*get_clipboard_text)(void);
bool (*set_clipboard_text)(const char* text);
/* android compatible file access functions */
bool (*file_read)(const char* filename, unsigned char** buf, size_t* size);
bool (*file_exists)(const char* filename);
bool (*file_write)(const char* filename, unsigned char* buf, uint32_t size);
/* clean stuff */
void (*shutdown)(void);
/* get root cache */
struct TCOD_Console* (*get_root_console_cache)(void);
} TCOD_SDL_driver_t;
typedef struct {
float force_recalc;
float last_scale_xc, last_scale_yc;
float last_scale_factor;
bool last_fullscreen;
float min_scale_factor;
float src_height_width_ratio;
float dst_height_width_ratio;
int src_x0, src_y0;
int src_copy_width, src_copy_height;
int src_proportionate_width, src_proportionate_height;
int dst_display_width, dst_display_height;
int dst_offset_x, dst_offset_y;
int surface_width, surface_height;
} scale_data_t;
extern scale_data_t scale_data;
extern float scale_factor;
/* SDL & OpenGL */
extern int oldFade;
/* color values */
#define TCOD_BLACK 0, 0, 0
#define TCOD_DARKEST_GREY 31, 31, 31
#define TCOD_DARKER_GREY 63, 63, 63
#define TCOD_DARK_GREY 95, 95, 95
#define TCOD_GREY 127, 127, 127
#define TCOD_LIGHT_GREY 159, 159, 159
#define TCOD_LIGHTER_GREY 191, 191, 191
#define TCOD_LIGHTEST_GREY 223, 223, 223
#define TCOD_WHITE 255, 255, 255
#define TCOD_DARKEST_SEPIA 31, 24, 15
#define TCOD_DARKER_SEPIA 63, 50, 31
#define TCOD_DARK_SEPIA 94, 75, 47
#define TCOD_SEPIA 127, 101, 63
#define TCOD_LIGHT_SEPIA 158, 134, 100
#define TCOD_LIGHTER_SEPIA 191, 171, 143
#define TCOD_LIGHTEST_SEPIA 222, 211, 195
/* desaturated */
#define TCOD_DESATURATED_RED 127, 63, 63
#define TCOD_DESATURATED_FLAME 127, 79, 63
#define TCOD_DESATURATED_ORANGE 127, 95, 63
#define TCOD_DESATURATED_AMBER 127, 111, 63
#define TCOD_DESATURATED_YELLOW 127, 127, 63
#define TCOD_DESATURATED_LIME 111, 127, 63
#define TCOD_DESATURATED_CHARTREUSE 95, 127, 63
#define TCOD_DESATURATED_GREEN 63, 127, 63
#define TCOD_DESATURATED_SEA 63, 127, 95
#define TCOD_DESATURATED_TURQUOISE 63, 127, 111
#define TCOD_DESATURATED_CYAN 63, 127, 127
#define TCOD_DESATURATED_SKY 63, 111, 127
#define TCOD_DESATURATED_AZURE 63, 95, 127
#define TCOD_DESATURATED_BLUE 63, 63, 127
#define TCOD_DESATURATED_HAN 79, 63, 127
#define TCOD_DESATURATED_VIOLET 95, 63, 127
#define TCOD_DESATURATED_PURPLE 111, 63, 127
#define TCOD_DESATURATED_FUCHSIA 127, 63, 127
#define TCOD_DESATURATED_MAGENTA 127, 63, 111
#define TCOD_DESATURATED_PINK 127, 63, 95
#define TCOD_DESATURATED_CRIMSON 127, 63, 79
/* lightest */
#define TCOD_LIGHTEST_RED 255, 191, 191
#define TCOD_LIGHTEST_FLAME 255, 207, 191
#define TCOD_LIGHTEST_ORANGE 255, 223, 191
#define TCOD_LIGHTEST_AMBER 255, 239, 191
#define TCOD_LIGHTEST_YELLOW 255, 255, 191
#define TCOD_LIGHTEST_LIME 239, 255, 191
#define TCOD_LIGHTEST_CHARTREUSE 223, 255, 191
#define TCOD_LIGHTEST_GREEN 191, 255, 191
#define TCOD_LIGHTEST_SEA 191, 255, 223
#define TCOD_LIGHTEST_TURQUOISE 191, 255, 239
#define TCOD_LIGHTEST_CYAN 191, 255, 255
#define TCOD_LIGHTEST_SKY 191, 239, 255
#define TCOD_LIGHTEST_AZURE 191, 223, 255
#define TCOD_LIGHTEST_BLUE 191, 191, 255
#define TCOD_LIGHTEST_HAN 207, 191, 255
#define TCOD_LIGHTEST_VIOLET 223, 191, 255
#define TCOD_LIGHTEST_PURPLE 239, 191, 255
#define TCOD_LIGHTEST_FUCHSIA 255, 191, 255
#define TCOD_LIGHTEST_MAGENTA 255, 191, 239
#define TCOD_LIGHTEST_PINK 255, 191, 223
#define TCOD_LIGHTEST_CRIMSON 255, 191, 207
/* lighter */
#define TCOD_LIGHTER_RED 255, 127, 127
#define TCOD_LIGHTER_FLAME 255, 159, 127
#define TCOD_LIGHTER_ORANGE 255, 191, 127
#define TCOD_LIGHTER_AMBER 255, 223, 127
#define TCOD_LIGHTER_YELLOW 255, 255, 127
#define TCOD_LIGHTER_LIME 223, 255, 127
#define TCOD_LIGHTER_CHARTREUSE 191, 255, 127
#define TCOD_LIGHTER_GREEN 127, 255, 127
#define TCOD_LIGHTER_SEA 127, 255, 191
#define TCOD_LIGHTER_TURQUOISE 127, 255, 223
#define TCOD_LIGHTER_CYAN 127, 255, 255
#define TCOD_LIGHTER_SKY 127, 223, 255
#define TCOD_LIGHTER_AZURE 127, 191, 255
#define TCOD_LIGHTER_BLUE 127, 127, 255
#define TCOD_LIGHTER_HAN 159, 127, 255
#define TCOD_LIGHTER_VIOLET 191, 127, 255
#define TCOD_LIGHTER_PURPLE 223, 127, 255
#define TCOD_LIGHTER_FUCHSIA 255, 127, 255
#define TCOD_LIGHTER_MAGENTA 255, 127, 223
#define TCOD_LIGHTER_PINK 255, 127, 191
#define TCOD_LIGHTER_CRIMSON 255, 127, 159
/* light */
#define TCOD_LIGHT_RED 255, 63, 63
#define TCOD_LIGHT_FLAME 255, 111, 63
#define TCOD_LIGHT_ORANGE 255, 159, 63
#define TCOD_LIGHT_AMBER 255, 207, 63
#define TCOD_LIGHT_YELLOW 255, 255, 63
#define TCOD_LIGHT_LIME 207, 255, 63
#define TCOD_LIGHT_CHARTREUSE 159, 255, 63
#define TCOD_LIGHT_GREEN 63, 255, 63
#define TCOD_LIGHT_SEA 63, 255, 159
#define TCOD_LIGHT_TURQUOISE 63, 255, 207
#define TCOD_LIGHT_CYAN 63, 255, 255
#define TCOD_LIGHT_SKY 63, 207, 255
#define TCOD_LIGHT_AZURE 63, 159, 255
#define TCOD_LIGHT_BLUE 63, 63, 255
#define TCOD_LIGHT_HAN 111, 63, 255
#define TCOD_LIGHT_VIOLET 159, 63, 255
#define TCOD_LIGHT_PURPLE 207, 63, 255
#define TCOD_LIGHT_FUCHSIA 255, 63, 255
#define TCOD_LIGHT_MAGENTA 255, 63, 207
#define TCOD_LIGHT_PINK 255, 63, 159
#define TCOD_LIGHT_CRIMSON 255, 63, 111
/* normal */
#define TCOD_RED 255, 0, 0
#define TCOD_FLAME 255, 63, 0
#define TCOD_ORANGE 255, 127, 0
#define TCOD_AMBER 255, 191, 0
#define TCOD_YELLOW 255, 255, 0
#define TCOD_LIME 191, 255, 0
#define TCOD_CHARTREUSE 127, 255, 0
#define TCOD_GREEN 0, 255, 0
#define TCOD_SEA 0, 255, 127
#define TCOD_TURQUOISE 0, 255, 191
#define TCOD_CYAN 0, 255, 255
#define TCOD_SKY 0, 191, 255
#define TCOD_AZURE 0, 127, 255
#define TCOD_BLUE 0, 0, 255
#define TCOD_HAN 63, 0, 255
#define TCOD_VIOLET 127, 0, 255
#define TCOD_PURPLE 191, 0, 255
#define TCOD_FUCHSIA 255, 0, 255
#define TCOD_MAGENTA 255, 0, 191
#define TCOD_PINK 255, 0, 127
#define TCOD_CRIMSON 255, 0, 63
/* dark */
#define TCOD_DARK_RED 191, 0, 0
#define TCOD_DARK_FLAME 191, 47, 0
#define TCOD_DARK_ORANGE 191, 95, 0
#define TCOD_DARK_AMBER 191, 143, 0
#define TCOD_DARK_YELLOW 191, 191, 0
#define TCOD_DARK_LIME 143, 191, 0
#define TCOD_DARK_CHARTREUSE 95, 191, 0
#define TCOD_DARK_GREEN 0, 191, 0
#define TCOD_DARK_SEA 0, 191, 95
#define TCOD_DARK_TURQUOISE 0, 191, 143
#define TCOD_DARK_CYAN 0, 191, 191
#define TCOD_DARK_SKY 0, 143, 191
#define TCOD_DARK_AZURE 0, 95, 191
#define TCOD_DARK_BLUE 0, 0, 191
#define TCOD_DARK_HAN 47, 0, 191
#define TCOD_DARK_VIOLET 95, 0, 191
#define TCOD_DARK_PURPLE 143, 0, 191
#define TCOD_DARK_FUCHSIA 191, 0, 191
#define TCOD_DARK_MAGENTA 191, 0, 143
#define TCOD_DARK_PINK 191, 0, 95
#define TCOD_DARK_CRIMSON 191, 0, 47
/* darker */
#define TCOD_DARKER_RED 127, 0, 0
#define TCOD_DARKER_FLAME 127, 31, 0
#define TCOD_DARKER_ORANGE 127, 63, 0
#define TCOD_DARKER_AMBER 127, 95, 0
#define TCOD_DARKER_YELLOW 127, 127, 0
#define TCOD_DARKER_LIME 95, 127, 0
#define TCOD_DARKER_CHARTREUSE 63, 127, 0
#define TCOD_DARKER_GREEN 0, 127, 0
#define TCOD_DARKER_SEA 0, 127, 63
#define TCOD_DARKER_TURQUOISE 0, 127, 95
#define TCOD_DARKER_CYAN 0, 127, 127
#define TCOD_DARKER_SKY 0, 95, 127
#define TCOD_DARKER_AZURE 0, 63, 127
#define TCOD_DARKER_BLUE 0, 0, 127
#define TCOD_DARKER_HAN 31, 0, 127
#define TCOD_DARKER_VIOLET 63, 0, 127
#define TCOD_DARKER_PURPLE 95, 0, 127
#define TCOD_DARKER_FUCHSIA 127, 0, 127
#define TCOD_DARKER_MAGENTA 127, 0, 95
#define TCOD_DARKER_PINK 127, 0, 63
#define TCOD_DARKER_CRIMSON 127, 0, 31
/* darkest */
#define TCOD_DARKEST_RED 63, 0, 0
#define TCOD_DARKEST_FLAME 63, 15, 0
#define TCOD_DARKEST_ORANGE 63, 31, 0
#define TCOD_DARKEST_AMBER 63, 47, 0
#define TCOD_DARKEST_YELLOW 63, 63, 0
#define TCOD_DARKEST_LIME 47, 63, 0
#define TCOD_DARKEST_CHARTREUSE 31, 63, 0
#define TCOD_DARKEST_GREEN 0, 63, 0
#define TCOD_DARKEST_SEA 0, 63, 31
#define TCOD_DARKEST_TURQUOISE 0, 63, 47
#define TCOD_DARKEST_CYAN 0, 63, 63
#define TCOD_DARKEST_SKY 0, 47, 63
#define TCOD_DARKEST_AZURE 0, 31, 63
#define TCOD_DARKEST_BLUE 0, 0, 63
#define TCOD_DARKEST_HAN 15, 0, 63
#define TCOD_DARKEST_VIOLET 31, 0, 63
#define TCOD_DARKEST_PURPLE 47, 0, 63
#define TCOD_DARKEST_FUCHSIA 63, 0, 63
#define TCOD_DARKEST_MAGENTA 63, 0, 47
#define TCOD_DARKEST_PINK 63, 0, 31
#define TCOD_DARKEST_CRIMSON 63, 0, 15
/* metallic */
#define TCOD_BRASS 191, 151, 96
#define TCOD_COPPER 197, 136, 124
#define TCOD_GOLD 229, 191, 0
#define TCOD_SILVER 203, 203, 203
/* miscellaneous */
#define TCOD_CELADON 172, 255, 175
#define TCOD_PEACH 255, 159, 127
// TCODConsole non public methods
int TCOD_console_stringLength(const unsigned char* s);
unsigned char* TCOD_console_forward(unsigned char* s, int l);
// TCODSystem non public methods
#ifndef NO_SDL
void sync_time_(void);
#endif // NO_SDL
void TCOD_sys_map_ascii_to_font(int asciiCode, int fontCharX, int fontCharY);
void TCOD_sys_decode_font_(void);
TCOD_Error TCOD_sys_save_bitmap(struct SDL_Surface* bitmap, const char* filename);
void TCOD_sys_save_fps(void);
void TCOD_sys_restore_fps(void);
TCODLIB_CAPI TCOD_Error TCOD_sys_load_player_config(void);
/**
* Validate and return a constant console.
*/
static inline TCOD_Console* TCOD_console_validate_(const TCOD_Console* console) {
return (TCOD_Console*)(console ? console : TCOD_ctx.root);
}
/**
* Return true if the console is valid and the index is within it.
*/
static inline bool TCOD_console_is_index_valid_(const TCOD_Console* console, int x, int y) {
return console && 0 <= x && x < console->w && 0 <= y && y < console->h;
}
TCOD_event_t TCOD_sys_handle_mouse_event(const union SDL_Event* ev, TCOD_mouse_t* mouse);
TCOD_event_t TCOD_sys_handle_key_event(const union SDL_Event* ev, TCOD_key_t* key);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // TCODLIB_INT_H_

View file

@ -0,0 +1,74 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_LIST_H
#define _TCOD_LIST_H
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
struct TCOD_List;
typedef struct TCOD_List* TCOD_list_t;
TCODLIB_API
TCOD_DEPRECATED("TCOD_List is not a suitable container. Use a custom array or a C++ container instead.")
TCOD_list_t TCOD_list_new(void);
TCODLIB_API TCOD_list_t TCOD_list_allocate(int nb_elements);
TCODLIB_API TCOD_list_t TCOD_list_duplicate(TCOD_list_t l);
TCODLIB_API void TCOD_list_delete(TCOD_list_t l);
TCODLIB_API void TCOD_list_push(TCOD_list_t l, const void* elt);
TCODLIB_API void* TCOD_list_pop(TCOD_list_t l);
TCODLIB_API void* TCOD_list_peek(TCOD_list_t l);
TCODLIB_API void TCOD_list_add_all(TCOD_list_t l, TCOD_list_t l2);
TCODLIB_API void* TCOD_list_get(TCOD_list_t l, int idx);
TCODLIB_API void TCOD_list_set(TCOD_list_t l, const void* elt, int idx);
TCODLIB_API void** TCOD_list_begin(TCOD_list_t l);
TCODLIB_API void** TCOD_list_end(TCOD_list_t l);
TCODLIB_API void TCOD_list_reverse(TCOD_list_t l);
TCODLIB_API void** TCOD_list_remove_iterator(TCOD_list_t l, void** elt);
TCODLIB_API void TCOD_list_remove(TCOD_list_t l, const void* elt);
TCODLIB_API void** TCOD_list_remove_iterator_fast(TCOD_list_t l, void** elt);
TCODLIB_API void TCOD_list_remove_fast(TCOD_list_t l, const void* elt);
TCODLIB_API bool TCOD_list_contains(TCOD_list_t l, const void* elt);
TCODLIB_API void TCOD_list_clear(TCOD_list_t l);
TCODLIB_API void TCOD_list_clear_and_delete(TCOD_list_t l);
TCODLIB_API int TCOD_list_size(TCOD_list_t l);
TCODLIB_API void** TCOD_list_insert_before(TCOD_list_t l, const void* elt, int before);
TCODLIB_API bool TCOD_list_is_empty(TCOD_list_t l);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,631 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_LIST_HPP
#define _TCOD_LIST_HPP
#include <stdlib.h> // NULL
#include <string.h> // memcpy
#include <utility>
#include "list.h"
/**
@PageName list
@PageCategory Base toolkits
@PageTitle All purposes container
@PageDesc This is a fast, lightweight and generic container, that provides array, list and stack paradigms.
Note that this module has no Python wrapper. Use Python built-in containers instead.
*/
// fast & lightweight list template
template <class T>
class TCODList {
T* array = nullptr;
int fillSize = 0;
int allocSize = 0;
public:
/**
@PageName list_create
@PageFather list
@PageTitle Creating a list
@FuncTitle Using the default constructor
@FuncDesc You can create an empty list with the default constructor. The C version returns a handler on the list.
@Cpp template <class T> TCODList::TCODList()
@C TCOD_list_t TCOD_list_new()
@CppEx
TCODList<int> intList;
TCODList<float> *floatList = new TCODList<float>();
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_t floatList = TCOD_list_new();
*/
[[deprecated("TCODList is unsuitable as a C++ container.")]] TCODList() = default;
/**
@PageName list_create
@FuncTitle Duplicating an existing list
@FuncDesc You can create a list by duplicating an existing list.
@Cpp template <class T> TCODList::TCODList(const TCODList &l)
@C TCOD_list_t TCOD_list_duplicate(TCOD_list_t l)
@Param l Existing list to duplicate.
@CppEx
TCODList<int> intList;
intList.push(3);
intList.push(5);
TCODList<int> intList2(intList); // intList2 contains two elements : 3 and 5
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)3);
TCOD_list_push(intList,(const void *)5);
TCOD_list_t intList2 = TCOD_list_duplicate(intList); // intList2 contains two elements : 3 and 5
*/
TCODList(const TCOD_list_t l) {
for (void** it = TCOD_list_begin(l); it != TCOD_list_end(l); ++it) {
push(*static_cast<T*>(static_cast<void*>(it)));
}
}
TCODList(const TCODList<T>& rhs) { *this = rhs; }
TCODList<T>& operator=(const TCODList<T>& rhs) {
while (allocSize < rhs.allocSize) allocate();
fillSize = rhs.fillSize;
int i = 0;
for (T* t = rhs.begin(); t != rhs.end(); ++t) {
array[++i] = *t;
}
return *this;
}
TCODList(TCODList&& rhs) noexcept { swap(*this, rhs); };
TCODList& operator=(TCODList&& rhs) noexcept {
swap(*this, rhs);
return *this;
}
/**
@PageName list_create
@FuncTitle Deleting a list
@FuncDesc You can delete a list, freeing any allocated resources. Note that deleting the list does not delete it's
elements. You have to use clearAndDelete before deleting the list if you want to destroy the elements too.
@Cpp virtual template <class T> TCODList::~TCODList()
@C void TCOD_list_delete(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> *intList = new TCODList<int>(); // allocate a new empty list
intList->push(5); // the list contains 1 element at position 0, value = 5
delete intList; // destroy the list
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_delete(intList);
*/
virtual ~TCODList() {
if (array) delete[] array;
}
friend void swap(TCODList& lhs, TCODList& rhs) noexcept {
using std::swap;
swap(lhs.array, rhs.array);
swap(lhs.fillSize, rhs.fillSize);
swap(lhs.allocSize, rhs.allocSize);
}
/**
@PageName list_create
@FuncTitle Preallocating memory
@FuncDesc You can also create an empty list and pre-allocate memory for elements. Use this if you know the list size
and want the memory to fit it perfectly.
@Cpp template <class T> TCODList::TCODList(int nbElements)
@C TCOD_list_t TCOD_list_allocate(int nbElements)
@Param nbElements Allocate memory for nbElements.
@CppEx TCODList<int> intList(5); // create an empty list, pre-allocate memory for 5 elements
@CEx TCOD_list_t intList = TCOD_list_allocate(5);
*/
[[deprecated("TCODList is unsuitable as a C++ container.")]] TCODList(int nbElements) {
fillSize = 0;
allocSize = nbElements;
array = new T[nbElements];
}
// clang-format off
/**
@PageName list_array
@PageTitle Basic array operations
@PageFather list
@FuncTitle Setting an element
@FuncDesc You can assign a value with set. If needed, the array will allocate new elements up to idx.
@Cpp template <class T> void TCODList::set(const T elt, int idx)
@C void TCOD_list_set(TCOD_list_t l,const void *elt, int idx)
@Param elt Element to put in the array.
@Param idx Index of the element.
0 <= idx
@Param l In the C version, the handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the array is empty (contains 0 elements)
intList.set(5,0); // the array contains 1 element at position 0, value = 5
intList.set(7,2); // the array contains 3 elements : 5, 0, 7
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,(const void *)5,0);
TCOD_list_set(intList,(const void *)7,2);
*/
void set(const T elt, int idx) {
if ( idx < 0 ) return;
while ( allocSize < idx+1 ) allocate();
array[idx] = elt;
if ( idx+1 > fillSize ) fillSize = idx+1;
}
/**
@PageName list_array
@FuncTitle Getting an element value
@FuncDesc You can retrieve a value with get.
@Cpp template <class T> T TCODList::get(int idx) const
@C void * TCOD_list_get(TCOD_list_t l,int idx)
@Param idx Index of the element.
0 <= idx < size of the array
@Param l In the C version, the handler, returned by a constructor.
@CppEx
TCODList<int> intList;
intList.set(5,0);
int val = intList.get(0); // val == 5
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,(const void *)5,0);
int val = (int)TCOD_list_get(intList,0); // val == 5
*/
T get(int idx) const {
return array[idx];
}
/**
@PageName list_array
@FuncTitle Checking if a list is empty
@Cpp template <class T> bool TCODList::isEmpty() const
@C bool TCOD_list_is_empty(TCOD_list_t l)
@Param l In the C version, the handler, returned by a constructor.
@CppEx
TCODList<int> intList;
bool empty=intList.isEmpty(); // empty == true
intList.set(3,0);
empty=intList.isEmpty(); // empty == false
@CEx
TCOD_list_t intList = TCOD_list_new();
bool empty=TCOD_list_is_empty(intList); // empty == true
TCOD_list_set(intList,(const void *)5,0);
empty=TCOD_list_is_empty(intList); // empty == false
*/
bool isEmpty() const {
return ( fillSize == 0 );
}
/**
@PageName list_array
@FuncTitle Getting the list size
@Cpp template <class T> int TCODList::size() const
@C int TCOD_list_size(TCOD_list_t l)
@Param l In the C version, the handler, returned by a constructor.
@CppEx
TCODList<int> intList;
int size=intList.size(); // size == 0
intList.set(3,0);
size=intList.size(); // size == 1
@CEx
TCOD_list_t intList = TCOD_list_new();
int size=TCOD_list_size(intList); // size == 0
TCOD_list_set(intList,(const void *)5,0);
size=TCOD_list_size(intList); // size == 1
*/
int size() const {
return fillSize;
}
/**
@PageName list_array
@FuncTitle Checking if an element is in the list
@Cpp template <class T> bool TCODList::contains(const T elt) const
@C bool TCOD_list_contains(TCOD_list_t l,const void * elt)
@Param elt The element.
@Param l In the C version, the handler, returned by a constructor.
@CppEx
TCODList<int> intList;
intList.set(3,0);
bool has3 = intList.contains(3); // has3 == true
bool has4 = intList.contains(4); // has4 == false
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,(const void *)3,0);
bool has3 = TCOD_list_contains(intList,(const void *)3); // has3 == true
bool has4 = TCOD_list_contains(intList,(const void *)4); // has4 == false
*/
bool contains(const T elt) const
{
for (T* curElt = begin(); curElt != end(); ++curElt) {
if (*curElt == elt) { return true; }
}
return false;
}
/**
@PageName list_list
@PageFather list
@PageTitle Basic list operations
@FuncTitle Insert an element in the list
@Cpp template <class T> void TCODList::insertBefore(const T elt,int before)
@C void TCOD_list_insert_before(TCOD_list_t l,const void *elt,int before)
@Param elt Element to insert in the list.
@Param idx Index of the element after the insertion.
0 <= idx < list size
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.set(0,5); // the list contains 1 element at position 0, value = 5
intList.insertBefore(2,0); // the list contains 2 elements : 2,5
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,0,(const void *)5);
TCOD_list_insert_before(intList,(const void *)2,0);
*/
T * insertBefore(const T elt,int before) {
if ( fillSize+1 >= allocSize ) allocate();
for (int idx=fillSize; idx > before; idx--) {
array[idx]=array[idx-1];
}
array[before]=elt;
fillSize++;
return &array[before];
}
/**
@PageName list_list
@FuncTitle Removing an element from the list
@FuncDesc The _fast versions replace the element to remove with the last element of the list. They're faster, but do not preserve the list order.
@Cpp
template <class T> void TCODList::remove(const T elt)
template <class T> void TCODList::removeFast(const T elt)
@C
void TCOD_list_remove(TCOD_list_t l, const void * elt)
void TCOD_list_remove_fast(TCOD_list_t l, const void * elt)
@Param elt The element to remove
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.set(0,5); // the list contains 1 element at position 0, value = 5
intList.remove(5); // the list is empty
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,0,(const void *)5);
TCOD_list_remove(intList,(const void *)5);
*/
void remove(const T elt) {
for ( T* curElt = begin(); curElt != end(); curElt ++) {
if ( *curElt == elt ) {
remove(curElt);
return;
}
}
}
void removeFast(const T elt) {
for ( T* curElt = begin(); curElt != end(); curElt ++) {
if ( *curElt == elt ) {
removeFast(curElt);
return;
}
}
}
/**
@PageName list_list
@FuncTitle Concatenating two lists
@FuncDesc You can concatenate two lists. Every element of l2 will be added to current list (or l in the C version) :
@Cpp template <class T> void TCODList::addAll(const TCODList &l2)
@C void TCOD_list_add_all(TCOD_list_t l, TCOD_list_t l2)
@Param l The list inside which elements will be added.
@Param l2 the list handler containing elements to insert.
@CppEx
TCODList<int> intList;
intList.set(1,3); // intList contains 2 elements : 0, 3
TCODList<int> intList2; // intList2 is empty
intList2.set(0,1); // intList2 contains 1 element : 1
intList2.addAll(intList); // intList2 contains 3 elements : 1, 0, 3
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,1,(const void *)3);
TCOD_list_t intList2 = TCOD_list_new();
TCOD_list_set(intList2,0,(const void *)1);
TCOD_list_add_all(intList2,intList);
*/
void addAll(const TCODList<T> &l2) {
for (T *t=l2.begin(); t!= l2.end(); t++) {
push(*t);
}
}
/**
@PageName list_list
@FuncTitle Emptying a list
@Cpp template <class T> void TCODList::clear()
@C void TCOD_list_clear(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList;
intList.set(0,3); // intList contains 1 element
intList.clear(); // intList is empty
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,0,(const void *)5);
TCOD_list_clear(intList);
*/
void clear() {
fillSize=0;
}
/**
@PageName list_list
@FuncTitle Emptying a list and destroying its elements
@FuncDesc For lists containing pointers, you can clear the list and delete (or free for C) the elements :
@Cpp template <class T> void TCODList::clearAndDelete()
@C void TCOD_list_clear_and_delete(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<MyClass *> intList;
MyClass * cl=new MyClass(); // new instance of MyClass allocated here
intList.set(0,cl);
intList.clear(); // the list is empty. cl is always valid
intList.set(0,cl);
intList.clearAndDelete(); // the list is empty. delete cl has been called. The address cl is no longer valid.
@C
TCOD_list_t intList = TCOD_list_new();
void *data=calloc(10,1); // some memory allocation here
TCOD_list_set(intList,0,(const void *)data);
TCOD_list_clear(intList); // the list is empty, but data is always valid
TCOD_list_set(intList,0,(const void *)data);
TCOD_list_clear_and_delete(intList); // the list is empty, free(data) has been called. The address data is no longer valid
*/
void clearAndDelete() {
for ( T* curElt = begin(); curElt != end(); curElt ++ ) {
delete (*curElt);
}
fillSize=0;
}
/**
@PageName list_list
@FuncTitle Reversing a list
@FuncDesc This function reverses the order of the elements in the list.</b>
@Cpp
void TCODList::reverse()
@C
void TCOD_list_reverse(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.push(5); // the list contains 1 element at position 0, value = 5
intList.push(2); // the list contains 2 elements : 5,2
intList.reverse(); // now order is 2,5
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_push(intList,(const void *)2);
TCOD_list_reverse();
*/
void reverse() {
T* head = begin();
T* tail = end();
while ( head < tail ) {
T tmp = *head;
*head=*tail;
*tail=tmp;
head++;
tail--;
}
}
/**
@PageName list_stack
@PageTitle Basic stack operations
@PageFather list
@FuncTitle Pushing an element on the stack
@FuncDesc You can push an element on the stack (append it to the end of the list) :
@Cpp template <class T> void TCODList::push(const T elt)
@C void TCOD_list_push(TCOD_list_t l, const void * elt)
@Param elt Element to append to the list.
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.push(5); // the list contains 1 element at position 0, value = 5
intList.push(2); // the list contains 2 elements : 5,2
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_push(intList,(const void *)2);
*/
void push(const T elt) {
if ( fillSize+1 >= allocSize ) allocate();
array[fillSize++] = elt;
}
/**
@PageName list_stack
@FuncTitle Popping an element from the stack
@FuncDesc You can pop an element from the stack (remove the last element of the list).
@Cpp template <class T> T TCODList::pop()
@C void * TCOD_list_pop(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.push(5); // the list contains 1 element at position 0, value = 5
intList.push(2); // the list contains 2 elements : 5,2
int val = intList.pop(); // val == 2, the list contains 1 element : 5
val = intList.pop(); // val == 5, the list is empty
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_push(intList,(const void *)2);
int val = (int)TCOD_list_pop(intList);
val = (int)TCOD_list_pop(intList);
*/
T pop() {
if ( fillSize == 0 ) return T{};
return array[--fillSize];
}
/**
@PageName list_stack
@FuncTitle Peeking the last element of the stack
@FuncDesc You can read the last element of the stack without removing it :
@Cpp template <class T> T TCODList::peek() const
@C void * TCOD_list_peek(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList;
intList.push(3); // intList contains 1 elements : 3
int val = intList.peek(); // val == 3, inList contains 1 elements : 3
intList.push(2); // intList contains 2 elements : 3, 2
val = intList.peek(); // val == 2, inList contains 2 elements : 3, 2
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)3);
int val = (int)TCOD_list_peek(intList);
TCOD_list_push(intList,(const void *)2);
val = (int)TCOD_list_peek(intList);
*/
T peek() const {
if ( fillSize == 0 ) return T{};
return array[fillSize-1];
}
/**
@PageName list_iterator
@PageFather list
@PageTitle Iterators
@FuncDesc You can iterate through the elements of the list using an iterator. begin() returns the address of the first element of the list. You go to the next element using the increment operator ++. When the iterators value is equal to end(), you've gone through all the elements. <b>Warning ! You cannot insert elements in the list while iterating through it. Inserting elements can result in reallocation of the list and your iterator will not longer be valid.</b>
@Cpp
template <class T> T * TCODList::begin() const
template <class T> T * TCODList::end() const
@C
void ** TCOD_list_begin(TCOD_list_t l)
void ** TCOD_list_end(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.push(5); // the list contains 1 element at position 0, value = 5
intList.push(2); // the list contains 2 elements : 5,2
for ( int * iterator = intList.begin(); iterator != intList.end(); iterator ++ ) {
int currentValue=*iterator;
printf("value : %d\n", currentValue );
}
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_push(intList,(const void *)2);
for ( int * iterator = (int *)TCOD_list_begin(intList); iterator != (int *)TCOD_list_end(intList); iterator ++ ) {
int currentValue=*iterator;
printf("value : %d\n", currentValue );
}
*/
T * begin() const {
if ( fillSize == 0 ) return (T *)NULL;
return &array[0];
}
T * end() const {
if ( fillSize == 0 ) return (T *)NULL;
return &array[fillSize];
}
/**
@PageName list_iterator
@FuncDesc You can remove an element from the list while iterating. The element at the iterator position will be removed. The function returns the new iterator. The _fast versions replace the element to remove with the last element of the list. They're faster, but do not preserve the list order.
@Cpp
template <class T> T *TCODList::remove(T *iterator)
template <class T> T *TCODList::removeFast(T *iterator)
@C
void **TCOD_list_remove_iterator(TCOD_list_t l, void **iterator)
void **TCOD_list_remove_iterator_fast(TCOD_list_t l, void **iterator)
@Param iterator The list iterator.
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.push(5); // the list contains 1 element at position 0, value = 5
intList.push(2); // the list contains 2 elements : 5,2
intList.push(3); // the list contains 3 elements : 5,2,3
for ( int * iterator = intList.begin(); iterator != intList.end(); iterator ++ ) {
int currentValue=*iterator;
if ( currentValue == 2 ) {
// remove this value from the list and keep iterating on next element (value == 3)
iterator = intList.remove(iterator);
}
printf("value : %d\n", currentValue ); // all 3 values will be printed : 5,2,3
}
// now the list contains only two elements : 5,3
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_push(intList,(const void *)2);
TCOD_list_push(intList,(const void *)3);
for ( int * iterator = (int *)TCOD_list_begin(intList); iterator != (int *)TCOD_list_end(intList); iterator ++ ) {
int currentValue=*iterator;
if ( currentValue == 2 ) {
iterator = (int *)TCOD_list_remove_iterator(intList,(void **)iterator);
}
printf("value : %d\n", currentValue );
}
*/
T *remove(T *elt) {
for ( T* curElt = elt; curElt < end()-1; curElt ++) {
*curElt = *(curElt+1);
}
fillSize--;
if ( fillSize == 0 ) return ((T *)NULL)-1;
else return elt-1;
}
T *removeFast(T *elt) {
*elt = array[fillSize-1];
fillSize--;
if ( fillSize == 0 ) return ((T *)NULL)-1;
else return elt-1;
}
protected :
void allocate() {
int newSize = allocSize * 2;
if ( newSize == 0 ) newSize = 16;
T *newArray = new T[ newSize ];
if ( array ) {
if ( fillSize > 0 ) memcpy(newArray, array, sizeof(T)*fillSize);
delete [] array;
}
array=newArray;
allocSize=newSize;
}
};
#endif

View file

@ -0,0 +1,123 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_LOGGING_H_
#define LIBTCOD_LOGGING_H_
#include "config.h"
#include "error.h"
typedef enum TCOD_LogLevel {
TCOD_LOG_DEBUG = 10,
TCOD_LOG_INFO = 20,
TCOD_LOG_WARNING = 30,
TCOD_LOG_ERROR = 40,
TCOD_LOG_CRITICAL = 50,
} TCOD_LogLevel;
/***************************************************************************
@brief Information being logged, this is a temporary object which doesn't last longer than the logging callbacks.
This struct will not contain NULL character pointers.
\rst
.. versionadded:: 1.19
\endrst
*/
typedef struct TCOD_LogMessage {
const char* message; // Message that was logged.
int level; // The log level, usually one of TCOD_LogLevel.
const char* source; // Source file of the logged message, usually __FILE__.
int lineno; // Source line of the logged message, usually __LINE__.
} TCOD_LogMessage;
/***************************************************************************
@brief A callback for logger listeners.
*/
typedef void (*TCOD_LoggingCallback)(const TCOD_LogMessage* message, void* userdata);
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/***************************************************************************
@brief Set the level of messages being logged.
@param level Should be one of the levels from TCOD_LogLevel.
\rst
.. versionadded:: 1.19
\endrst
*/
TCODLIB_API void TCOD_set_log_level(int level);
/***************************************************************************
@brief Sets a callback for libtcod's logged output.
@param callback A `TCOD_LoggingCallback` function which processes `TCOD_LogMessage*` parameters.
Can be NULL to disable logging.
@param userdata Userdata to be passed to the log function.
\rst
.. versionadded:: 1.19
\endrst
*/
TCODLIB_API void TCOD_set_log_callback(TCOD_LoggingCallback callback, void* userdata);
/***************************************************************************
@brief Log a message without formatting. This function is provisional.
@param msg The message to log.
@param level The log level of this message.
@param source The source file of this message, should be __FILE__, may be NULL.
@param line The source line of this message, should be __LINE__.
*/
TCODLIB_API void TCOD_log_verbose_(const char* msg, int level, const char* source, int line);
/***************************************************************************
@brief Log a formatted message. This function is provisional.
@param level The log level of this message.
@param source The source file of this message, should be __FILE__, may be NULL.
@param line The source line of this message, should be __LINE__.
@param fmt The message format string.
@param ... Variable arguments for the format.
*/
TCODLIB_FORMAT(4, 5)
TCODLIB_API void TCOD_log_verbose_fmt_(int level, const char* source, int line, const char* fmt, ...);
// All of these are for internal use.
#define TCOD_log_debug_f(fmt, ...) TCOD_log_verbose_fmt_(TCOD_LOG_DEBUG, __FILE__, __LINE__, (fmt), __VA_ARGS__)
#define TCOD_log_info_f(fmt, ...) TCOD_log_verbose_fmt_(TCOD_LOG_DEBUG, __FILE__, __LINE__, (fmt), __VA_ARGS__)
#define TCOD_log_warning_f(fmt, ...) TCOD_log_verbose_fmt_(TCOD_LOG_DEBUG, __FILE__, __LINE__, (fmt), __VA_ARGS__)
#define TCOD_log_error_f(fmt, ...) TCOD_log_verbose_fmt_(TCOD_LOG_DEBUG, __FILE__, __LINE__, (fmt), __VA_ARGS__)
#define TCOD_log_critical_f(fmt, ...) TCOD_log_verbose_fmt_(TCOD_LOG_DEBUG, __FILE__, __LINE__, (fmt), __VA_ARGS__)
#define TCOD_log_debug(msg) TCOD_log_verbose_((msg), TCOD_LOG_DEBUG, __FILE__, __LINE__)
#define TCOD_log_info(msg) TCOD_log_verbose_((msg), TCOD_LOG_DEBUG, __FILE__, __LINE__)
#define TCOD_log_warning(msg) TCOD_log_verbose_((msg), TCOD_LOG_DEBUG, __FILE__, __LINE__)
#define TCOD_log_error(msg) TCOD_log_verbose_((msg), TCOD_LOG_DEBUG, __FILE__, __LINE__)
#define TCOD_log_critical(msg) TCOD_log_verbose_((msg), TCOD_LOG_DEBUG, __FILE__, __LINE__)
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // LIBTCOD_LOGGING_H_

View file

@ -0,0 +1,250 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_MATRIX_HPP_
#define LIBTCOD_MATRIX_HPP_
#include <array>
#include <stdexcept>
#include <string>
#include <vector>
namespace tcod {
namespace internal {
/// Return a small array has a human readable string.
template <typename ArrayType>
[[nodiscard]] static std::string array_as_string(const ArrayType& arr) {
std::string result{"{"};
for (const auto& it : arr) {
result += std::to_string(it);
if (&it != &arr.back()) {
result += ", ";
}
}
result += "}";
return result;
}
} // namespace internal
/***************************************************************************
@brief A view into a strided multi-dimensional array.
@tparam T The type viewed by this object.
@tparam Dimensions The number of dimensions of the view.
This class is a work-in-progress.
*/
template <typename T, size_t Dimensions>
class MatrixView {
public:
using size_type = int; // The int size of indexes.
using shape_type = std::array<size_type, Dimensions>; // The type used to store the matrixes shape.
using stride_type = std::array<size_type, Dimensions>; // The type used to store strides.
using index_type = std::array<size_type, Dimensions>; // The type used to index the container.
using reference = T&;
using const_reference = const T&;
/// Default constructor.
constexpr MatrixView() = default;
/// Create a new multi-dimensional view.
constexpr MatrixView(const shape_type& shape_xy, const stride_type& strides_xy, T* data) noexcept
: shape_xy_{shape_xy}, strides_xy_{strides_xy}, data_{reinterpret_cast<data_ptr>(data)} {};
/// Get the item at index.
[[nodiscard]] constexpr reference operator[](const index_type& index) noexcept {
return *reinterpret_cast<T*>(data_ + get_offset(index));
}
/// Get the const item at index.
[[nodiscard]] constexpr const_reference operator[](const index_type& index) const noexcept {
return *reinterpret_cast<const T*>(data_ + get_offset(index));
}
/// Get the item at index, checking bounds.
[[nodiscard]] constexpr reference at(const index_type& index) {
return *reinterpret_cast<T*>(data_ + check_range(index));
}
/// Get the const item at index, checking bounds.
[[nodiscard]] constexpr const_reference at(const index_type& index) const {
return *reinterpret_cast<const T*>(data_ + check_range(index));
}
/// Return true if index is within the bounds of this matrix.
[[nodiscard]] constexpr bool in_bounds(const index_type& index) const noexcept {
for (size_t dimension = 0; dimension < Dimensions; ++dimension) {
if (!(0 <= index.at(dimension) && index.at(dimension) < shape_xy_.at(dimension))) return false;
}
return true;
}
private:
// `unsigned char*` pointer which has the same const as `T`.
using data_ptr = typename std::conditional<std::is_const<T>::value, const unsigned char*, unsigned char*>::type;
/// Return the byte offset of `data_` for the index for this view.
[[nodiscard]] constexpr size_t get_offset(const index_type& index) const noexcept {
size_t data_index = 0;
for (size_t dimension{0}; dimension < Dimensions; ++dimension) {
data_index += strides_xy_.at(dimension) * index.at(dimension);
}
return data_index;
}
/// Check for out-of-bounds, then return the data offset for `index`.
constexpr size_t check_range(const index_type& index) const {
using internal::array_as_string;
if (!in_bounds(index)) {
throw std::out_of_range(
std::string("Out of bounds lookup ") + array_as_string(index) + " on matrix of shape " +
array_as_string(shape_xy_) + ".");
}
return get_offset(index);
}
shape_type shape_xy_; // The shape of this view.
stride_type strides_xy_; // The strides of this view in bytes.
data_ptr data_; // A pointer to the viewed memory.
};
/*****************************************************************************
@brief A template container for holding a multi-dimensional array of items.
@tparam T The type of value contained by this matrix.
@tparam Dimensions The number of dimensions of this matrix type.
@tparam Container The `std::vector`-like container used for this matrix.
This class is a work-in-progress.
*/
template <typename T, size_t Dimensions, typename Container = std::vector<T>>
class Matrix {
public:
using size_type = int; // The int size of indexes.
using shape_type = std::array<size_type, Dimensions>; // The type used to measure the matrixes shape.
using index_type = std::array<size_type, Dimensions>; // The type used to index the container.
using reference = typename Container::reference;
using const_reference = typename Container::const_reference;
/// Default constructor.
constexpr Matrix() = default;
/// Create a matrix of the given shape.
constexpr explicit Matrix(const shape_type& shape) : shape_{shape}, data_(get_size_from_shape(shape)) {}
/// Create a matrix of the given shape filled with a default value.
constexpr Matrix(const shape_type& shape, const T& fill_value)
: shape_{shape}, data_(get_size_from_shape(shape), fill_value) {}
/// Return the iterator beginning.
[[nodiscard]] constexpr auto begin() noexcept { return data_.begin(); }
/// Return the iterator beginning.
[[nodiscard]] constexpr auto begin() const noexcept { return data_.cbegin(); }
/// Return the iterator end.
[[nodiscard]] constexpr auto end() noexcept { return data_.end(); }
/// Return the iterator end.
[[nodiscard]] constexpr auto end() const noexcept { return data_.cend(); }
/// Get the item at index.
[[nodiscard]] constexpr reference operator[](const index_type& index) noexcept { return data_[get_index(index)]; }
/// Get the const item at index.
[[nodiscard]] constexpr const_reference operator[](const index_type& index) const noexcept {
return data_[get_index(index)];
}
/// Get the item at index, checking bounds.
[[nodiscard]] constexpr reference at(const index_type& index) { return data_.at(check_range(index)); }
/// Get the const item at index, checking bounds.
[[nodiscard]] constexpr const_reference at(const index_type& index) const { return data_.at(check_range(index)); }
/// Return the shape of this matrix.
[[nodiscard]] constexpr const shape_type& get_shape() const noexcept { return shape_; }
/// Return true if index is within the bounds of this matrix.
[[nodiscard]] constexpr bool in_bounds(const index_type& index) const noexcept {
for (size_t dimension = 0; dimension < Dimensions; ++dimension) {
if (!(0 <= index.at(dimension) && index.at(dimension) < shape_.at(dimension))) return false;
}
return true;
}
/// Implicit cast to a view of this matrix.
[[nodiscard]] constexpr operator MatrixView<T, Dimensions>() noexcept {
return {get_shape(), get_strides(), data_.data()};
}
/// Implicit cast to a const view of this matrix.
[[nodiscard]] constexpr operator MatrixView<const T, Dimensions>() const noexcept {
return {get_shape(), get_strides(), data_.data()};
}
/// Get the flat container for this matrix.
[[nodiscard]] constexpr Container& get_container() noexcept { return data_; }
/// Get the const flat container for this matrix.
[[nodiscard]] constexpr const Container& get_container() const noexcept { return data_; }
template <class Archive>
void serialize(Archive& archive) {
archive(shape_, data_);
}
private:
/// Return the total number of items in a given shape.
[[nodiscard]] static constexpr size_t get_size_from_shape(const shape_type& shape) noexcept {
size_t size = 1;
for (auto& it : shape) size *= it;
return size;
}
/// Return the 1D index to the flat container of this matrix.
[[nodiscard]] constexpr size_t get_index(const index_type& index) const noexcept {
size_t stride = 1;
size_t data_index = 0;
for (size_t dimension = 0; dimension < Dimensions; ++dimension) {
data_index += stride * index.at(dimension);
stride *= shape_.at(dimension);
}
return data_index;
}
/// Return the 1D index to the flat container. Throw if out-of-bounds.
constexpr size_t check_range(const index_type& index) const {
using internal::array_as_string;
if (!in_bounds(index)) {
throw std::out_of_range(
std::string("Out of bounds lookup ") + array_as_string(index) + " on matrix of shape " +
array_as_string(shape_) + ".");
}
return get_index(index);
}
/// Return the byte-strides of this matrix.
[[nodiscard]] constexpr index_type get_strides() const noexcept {
index_type strides{};
int stride = static_cast<int>(sizeof(T));
for (size_t dimension = 0; dimension < Dimensions; ++dimension) {
strides.at(dimension) = stride;
stride *= shape_.at(dimension);
}
return strides;
}
shape_type shape_;
Container data_;
};
} // namespace tcod
#endif // LIBTCOD_MATRIX_HPP_

View file

@ -0,0 +1,64 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_RANDOM_H
#define _TCOD_RANDOM_H
#include "mersenne_types.h"
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
TCODLIB_API TCOD_Random* TCOD_random_get_instance(void);
TCODLIB_API TCOD_Random* TCOD_random_new(TCOD_random_algo_t algo);
TCODLIB_API TCOD_Random* TCOD_random_save(TCOD_Random* mersenne);
TCODLIB_API void TCOD_random_restore(TCOD_Random* mersenne, TCOD_Random* backup);
TCODLIB_API TCOD_Random* TCOD_random_new_from_seed(TCOD_random_algo_t algo, uint32_t seed);
TCODLIB_API void TCOD_random_delete(TCOD_Random* mersenne);
TCODLIB_API void TCOD_random_set_distribution(TCOD_Random* mersenne, TCOD_distribution_t distribution);
TCODLIB_API int TCOD_random_get_int(TCOD_Random* mersenne, int min, int max);
TCODLIB_API float TCOD_random_get_float(TCOD_Random* mersenne, float min, float max);
TCODLIB_API double TCOD_random_get_double(TCOD_Random* mersenne, double min, double max);
TCODLIB_API int TCOD_random_get_int_mean(TCOD_Random* mersenne, int min, int max, int mean);
TCODLIB_API float TCOD_random_get_float_mean(TCOD_Random* mersenne, float min, float max, float mean);
TCODLIB_API double TCOD_random_get_double_mean(TCOD_Random* mersenne, double min, double max, double mean);
TCODLIB_API TCOD_dice_t TCOD_random_dice_new(const char* s);
TCODLIB_API int TCOD_random_dice_roll(TCOD_Random* mersenne, TCOD_dice_t dice);
TCODLIB_API int TCOD_random_dice_roll_s(TCOD_Random* mersenne, const char* s);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,426 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
#ifndef _TCOD_RANDOM_HPP
#define _TCOD_RANDOM_HPP
#include "mersenne.h"
/**
@PageName random
@PageCategory Base toolkits
@PageTitle Pseudorandom number generator
@PageDesc This toolkit is an implementation of two fast and high quality pseudorandom number generators:
* a Mersenne twister generator,
* a Complementary-Multiply-With-Carry generator.
CMWC is faster than MT (see table below) and has a much better period (1039460 vs. 106001). It is the default algo since libtcod 1.5.0.
Relative performances in two independent tests (lower is better) :
<table class="param">
<tr>
<th>Algorithm</th>
<th>Numbers generated</th>
<th>Perf (1)</th>
<th>Perf (2)</th>
</tr>
<tr class="hilite">
<td>MT</td>
<td>integer</td>
<td>62</td>
<td>50</td>
</tr>
<tr>
<td>MT</td>
<td>float</td>
<td>54</td>
<td>45</td>
</tr>
<tr class="hilite">
<td>CMWC</td>
<td>integer</td>
<td>21</td>
<td>34</td>
</tr>
<tr>
<td>CMWC</td>
<td>float</td>
<td>32</td>
<td>27</td>
</tr>
</table>
<h6>For Python users:</h6>
Python already has great builtin random generators. But some parts of the Doryen library (noise, heightmap, ...) uses RNG as parameters. If you intend to use those functions, you must provide a RNG created with the library.
<h6>For C# users:</h6>
.NET already has great builtin random generators. But some parts of the Doryen library (noise, heightmap, ...) uses RNG as parameters. If you intend to use those functions, you must provide a RNG created with the library.
*/
class TCODLIB_API TCODRandom {
public :
/**
@PageName random_init
@PageFather random
@PageTitle Creating a generator
@FuncTitle Default generator
@FuncDesc The simplest way to get random number is to use the default generator. The first time you get this generator, it is initialized by calling TCOD_random_new. Then, on successive calls, this function returns the same generator (singleton pattern).
@Cpp static TCODRandom * TCODRandom::getInstance (void)
@C TCOD_random_t TCOD_random_get_instance (void)
@Py random_get_instance ()
@C# static TCODRandom TCODRandom::getInstance()
@Param algo The PRNG algorithm the generator should be using. Possible values are:
* TCOD_RNG_MT for Mersenne Twister,
* TCOD_RNG_CMWC for Complementary Multiply-With-Carry.
*/
static TCODRandom * getInstance(void);
/**
@PageName random_init
@FuncTitle Generators with random seeds
@FuncDesc You can also create as many generators as you want with a random seed (the number of seconds since Jan 1 1970 at the time the constructor is called). Warning ! If you call this function several times in the same second, it will return the same generator.
@Cpp TCODRandom::TCODRandom (TCOD_random_algo_t algo = TCOD_RNG_CMWC)
@C TCOD_random_t TCOD_random_new (TCOD_random_algo_t algo)
@Py random_new (algo = RNG_CMWC)
@C#
TCODRandom::TCODRandom() // Defaults to ComplementaryMultiplyWithCarry
TCODRandom::TCODRandom(TCODRandomType algo)
@Param algo The PRNG algorithm the generator should be using.
*/
TCODRandom(TCOD_random_algo_t algo = TCOD_RNG_CMWC, bool allocate = true);
/**
@PageName random_init
@FuncTitle Generators with user defined seeds
@FuncDesc Finally, you can create generators with a specific seed. Those allow you to get a reproducible set of random numbers. You can for example save a dungeon in a file by saving only the seed used for its generation (provided you have a determinist generation algorithm)
@Cpp TCODRandom::TCODRandom (uint32_t seed, TCOD_random_algo_t algo = TCOD_RNG_CMWC);
@C TCOD_random_t TCOD_random_new_from_seed (TCOD_random_algo_t algo, uint32_t seed);
@Py random_new_from_seed(seed, algo=RNG_CMWC)
@C#
TCODRandom::TCODRandom(uint32_t seed) // Defaults to ComplementaryMultiplyWithCarry
TCODRandom::TCODRandom(uint32_t seed, TCODRandomType algo)
@Param seed The 32 bits seed used to initialize the generator. Two generators created with the same seed will generate the same set of pseudorandom numbers.
@Param algo The PRNG algorithm the generator should be using.
@CppEx
// default generator
TCODRandom * default = TCODRandom::getInstance();
// another random generator
TCODRandom * myRandom = new TCODRandom();
// a random generator with a specific seed
TCODRandom * myDeterministRandom = new TCODRandom(0xdeadbeef);
@CEx
// default generator
TCOD_random_t default = TCOD_random_get_instance();
// another random generator
TCOD_random_t my_random = TCOD_random_new(TCOD_RNG_CMWC);
// a random generator with a specific seed
TCOD_random_t my_determinist_random = TCOD_random_new_from_seed(TCOD_RNG_CMWC,0xdeadbeef);
@PyEx
# default generator
default = libtcod.random_get_instance()
# another random generator
my_random = libtcod.random_new()
# a random generator with a specific seed
my_determinist_random = libtcod.random_new_from_seed(0xdeadbeef)
*/
TCODRandom(uint32_t seed, TCOD_random_algo_t algo = TCOD_RNG_CMWC);
/**
Take ownership of a `TCOD_Random*` pointer.
\rst
.. versionadded:: 1.16
\endrst
*/
explicit TCODRandom(TCOD_Random*&& mersenne) : data(mersenne) {}
/**
@PageName random_init
@FuncTitle Destroying a RNG
@FuncDesc To release resources used by a generator, use those functions :
NB : do not delete the default random generator !
@Cpp TCODRandom::~TCODRandom()
@C void TCOD_random_delete(TCOD_random_t mersenne)
@Py random_delete(mersenne)
@C# void TCODRandom::Dispose()
@Param mersenne In the C and Python versions, the generator handler, returned by the initialization functions.
@CppEx
// create a generator
TCODRandom *rnd = new TCODRandom();
// use it
...
// destroy it
delete rnd;
@CEx
// create a generator
TCOD_random_t rnd = TCOD_random_new();
// use it
...
// destroy it
TCOD_random_delete(rnd);
@PyEx
# create a generator
rnd = libtcod.random_new()
# use it
...
# destroy it
libtcod.random_delete(rnd)
*/
virtual ~TCODRandom();
/**
@PageName random_distro
@PageFather random
@PageTitle Using a generator
@FuncTitle Setting the default RNG distribution
@FuncDesc Random numbers can be obtained using several different distributions. Linear is default, but if you wish to use one of the available Gaussian distributions, you can use this function to tell libtcod which is your preferred distribution. All random number getters will then use that distribution automatically to fetch your random numbers.
The distributions available are as follows:
1. TCOD_DISTRIBUTION_LINEAR
This is the default distribution. It will return a number from a range min-max. The numbers will be evenly distributed, ie, each number from the range has the exact same chance of being selected.
2. TCOD_DISTRIBUTION_GAUSSIAN
This distribution does not have minimum and maximum values. Instead, a mean and a standard deviation are used. The mean is the central value. It will appear with the greatest frequency. The farther away from the mean, the less the probability of appearing the possible results have. Although extreme values are possible, 99.7% of the results will be within the radius of 3 standard deviations from the mean. So, if the mean is 0 and the standard deviation is 5, the numbers will mostly fall in the (-15,15) range.
3. TCOD_DISTRIBUTION_GAUSSIAN_RANGE
This one takes minimum and maximum values. Under the hood, it computes the mean (which falls right between the minimum and maximum) and the standard deviation and applies a standard Gaussian distribution to the values. The difference is that the result is always guaranteed to be in the min-max range.
4. TCOD_DISTRIBUTION_GAUSSIAN_INVERSE
Essentially, this is the same as TCOD_DISTRIBUTION_GAUSSIAN. The difference is that the values near +3 and -3 standard deviations from the mean have the highest possibility of appearing, while the mean has the lowest.
5. TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE
Essentially, this is the same as TCOD_DISTRIBUTION_GAUSSIAN_RANGE, but the min and max values have the greatest probability of appearing, while the values between them, the lowest.
There exist functions to also specify both a min-max range AND a custom mean, which can be any value (possibly either min or max, but it can even be outside that range). In case such a function is used, the distributions will trigger a slightly different behaviour:
* TCOD_DISTRIBUTION_LINEAR
* TCOD_DISTRIBUTION_GAUSSIAN
* TCOD_DISTRIBUTION_GAUSSIAN_RANGE
In these cases, the selected mean will have the highest probability of appearing.
* TCOD_DISTRIBUTION_GAUSSIAN_INVERSE
* TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE
In these cases, the selected mean will appear with the lowest frequency.
@Cpp void TCODRandom::setDistribution(TCOD_distribution_t distribution)
@C void TCOD_random_set_distribution(TCOD_random_t mersenne, TCOD_distribution_t distribution)
@Py
@C#
@Param mersenne In the C and Python versions, the generator handler, returned by the initialization functions. If NULL, the default generator is used..
@Param distribution The distribution constant from the available set:<ul><li>TCOD_DISTRIBUTION_LINEAR</li><li>TCOD_DISTRIBUTION_GAUSSIAN</li><li>TCOD_DISTRIBUTION_GAUSSIAN_RANGE</li><li>TCOD_DISTRIBUTION_GAUSSIAN_INVERSE</li><li>TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE</li></ul>
*/
inline void setDistribution (TCOD_distribution_t distribution) { TCOD_random_set_distribution(data,distribution); }
/**
@PageName random_use
@PageFather random
@PageTitle Using a generator
@FuncTitle Getting an integer
@FuncDesc Once you obtained a generator (using one of those methods), you can get random numbers using the following functions, using either the explicit or simplified API where applicable:
@Cpp
//explicit API:
int TCODRandom::getInt(int min, int max, int mean = 0)
//simplified API:
int TCODRandom::get(int min, int max, int mean = 0)
@C
int TCOD_random_get_int(TCOD_random_t mersenne, int min, int max)
int TCOD_random_get_int_mean(TCOD_random_t mersenne, int min, int max, int mean)
@Py
@C#
@Param mersenne In the C and Python versions, the generator handler, returned by the initialization functions. If NULL, the default generator is used..
@Param min,max Range of values returned. Each time you call this function, you get a number between (including) min and max
@Param mean This is used to set a custom mean, ie, not min+((max-min)/2). It can even be outside of the min-max range. Using a mean will force the use of a weighted (Gaussian) distribution, even if linear is set.
*/
inline int getInt (int min, int max, int mean = 0) { return (mean <= 0) ? TCOD_random_get_int(data,min,max) : TCOD_random_get_int_mean(data,min,max,mean); }
inline int get (int min, int max, int mean = 0) { return (mean <= 0) ? TCOD_random_get_int(data,min,max) : TCOD_random_get_int_mean(data,min,max,mean); }
/**
@PageName random_use
@FuncTitle Getting a float
@FuncDesc To get a random floating point number, using either the explicit or simplified API where applicable
@Cpp
//explicit API:
float TCODRandom::getFloat(float min, float max, float mean = 0.0f)
//simplified API:
float TCODRandom::get(float min, float max, float mean = 0.0f)
@C
float TCOD_random_get_float(TCOD_random_t mersenne, float min, float max)
float TCOD_random_get_float_mean(TCOD_random_t mersenne, float min, float max, float mean)
@Py random_get_float(mersenne, mi, ma)
@C# float TCODRandom::getFloat(float min, float max)
@Param mersenne In the C and Python versions, the generator handler, returned by the initialization functions. If NULL, the default generator is used.
@Param min,max Range of values returned. Each time you call this function, you get a number between (including) min and max
@Param mean This is used to set a custom mean, ie, not min+((max-min)/2). It can even be outside of the min-max range. Using a mean will force the use of a weighted (Gaussian) distribution, even if linear is set.
@CppEx
// default generator
TCODRandom * default = TCODRandom::getInstance();
int aRandomIntBetween0And1000 = default->getInt(0,1000);
int anotherRandomInt = default->get(0,1000);
// another random generator
TCODRandom *myRandom = new TCODRandom();
float aRandomFloatBetween0And1000 = myRandom->getFloat(0.0f,1000.0f);
float anotherRandomFloat = myRandom->get(0.0f,1000.0f);
@CEx
// default generator
int a_random_int_between_0_and_1000 = TCOD_random_get_float(NULL,0,1000);
// another random generator
TCOD_random_t my_random = TCOD_random_new();
float a_random_float_between_0_and_1000 = TCOD_random_get_float(my_random,0.0f,1000.0f);
@PyEx
# default generator
a_random_int_between_0_and_1000 = libtcod.random_get_float(0,0,1000)
# another random generator
my_random = libtcod.random_new()
a_random_float_between_0_and_1000 = libtcod.random_get_float(my_random,0.0,1000.0)
*/
inline float getFloat (float min, float max, float mean = 0.0f) { return (mean <= 0) ? TCOD_random_get_float(data,min,max) : TCOD_random_get_float_mean(data,min,max,mean); }
inline float get (float min, float max, float mean = 0.0f) { return (mean <= 0.0f) ? TCOD_random_get_float(data,min,max) : TCOD_random_get_float_mean(data,min,max,mean); }
/**
@PageName random_use
@FuncTitle Getting a double
@FuncDesc To get a random double precision floating point number, using either the explicit or simplified API where applicable
@Cpp
//explicit API:
double TCODRandom::getDouble(double min, double max, double mean = 0.0f)
//simplified API:
double TCODRandom::get(double min, double max, double mean = 0.0f)
@C
double TCOD_random_get_double(TCOD_random_t mersenne, double min, double max)
double TCOD_random_get_double_mean(TCOD_random_t mersenne, double min, double max, double mean)
@Py
@C#
@Param mersenne In the C and Python versions, the generator handler, returned by the initialization functions. If NULL, the default generator is used.
@Param min,max Range of values returned. Each time you call this function, you get a number between (including) min and max
@Param mean This is used to set a custom mean, ie, not min+((max-min)/2). It can even be outside of the min-max range. Using a mean will force the use of a weighted (Gaussian) distribution, even if linear is set.
@CppEx
// default generator
TCODRandom * default = TCODRandom::getInstance();
int aRandomIntBetween0And1000 = default->getInt(0,1000);
int anotherRandomInt = default->get(0,1000);
// another random generator
TCODRandom *myRandom = new TCODRandom();
float aRandomFloatBetween0And1000 = myRandom->getFloat(0.0f,1000.0f);
float anotherRandomFloat = myRandom->get(0.0f,1000.0f);
@CEx
// default generator
int a_random_int_between_0_and_1000 = TCOD_random_get_float(NULL,0,1000);
// another random generator
TCOD_random_t my_random = TCOD_random_new();
float a_random_float_between_0_and_1000 = TCOD_random_get_float(my_random,0.0f,1000.0f);
@PyEx
# default generator
a_random_int_between_0_and_1000 = libtcod.random_get_float(0,0,1000)
# another random generator
my_random = libtcod.random_new()
a_random_float_between_0_and_1000 = libtcod.random_get_float(my_random,0.0,1000.0)
*/
inline double getDouble (double min, double max, double mean = 0.0) { return (mean <= 0) ? TCOD_random_get_double(data,min,max) : TCOD_random_get_double_mean(data,min,max,mean); }
inline double get (double min, double max, double mean = 0.0f) { return (mean <= 0.0) ? TCOD_random_get_double(data,min,max) : TCOD_random_get_double_mean(data,min,max,mean); }
/**
@PageName random_use
@FuncTitle Saving a RNG state
@FuncDesc You can save the state of a generator with :
@Cpp TCODRandom *TCODRandom::save() const
@C TCOD_random_t TCOD_random_save(TCOD_random_t mersenne)
@Py random_save(mersenne)
@C# TCODRandom TCODRandom::save()
@Param mersenne In the C and Python versions, the generator handler, returned by the initialization functions. If NULL, the default generator is used.
*/
TCODRandom * save() const;
/**
@PageName random_use
@FuncTitle Restoring a saved state
@FuncDesc And restore it later. This makes it possible to get the same series of number several times with a single generator.
@Cpp void TCODRandom::restore(const TCODRandom *backup)
@C void TCOD_random_restore(TCOD_random_t mersenne, TCOD_random_t backup)
@Py random_restore(mersenne, backup)
@C# void TCODRandom::restore(TCODRandom backup)
@Param mersenne In the C and Python versions, the generator handler, returned by the initialization functions. If NULL, the default generator is used.
@CppEx
// default generator
TCODRandom * default = TCODRandom::getInstance();
// save the state
TCODRandom *backup=default->save();
// get a random number (or several)
int number1 = default->getInt(0,1000);
// restore the state
default->restore(backup);
// get a random number
int number2 = default->getInt(0,1000);
// => number1 == number2
@CEx
// save default generator state
TCOD_random_t backup=TCOD_random_save(NULL);
// get a random number
int number1 = TCOD_random_get_float(NULL,0,1000);
// restore the state
TCOD_random_restore(NULL,backup);
// get a random number
int number2 = TCOD_random_get_float(NULL,0,1000);
// number1 == number2
@PyEx
# save default generator state
backup=libtcod.random_save(0)
# get a random number
number1 = libtcod.random_get_float(0,0,1000)
# restore the state
libtcod.random_restore(0,backup)
# get a random number
number2 = libtcod.random_get_float(0,0,1000)
# number1 == number2
*/
void restore(const TCODRandom *backup);
//dice
inline TCOD_dice_t dice (const char * s) { return TCOD_random_dice_new(s); }
inline int diceRoll (TCOD_dice_t dice) { return TCOD_random_dice_roll(data,dice); }
inline int diceRoll (const char * s) { return TCOD_random_dice_roll(data,TCOD_random_dice_new(s)); }
/**
Return this objects `TCOD_Random*` pointer.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_Random* get_data() noexcept
{
return data;
}
const TCOD_Random* get_data() const noexcept
{
return data;
}
protected :
friend class TCODLIB_API TCODNoise;
friend class TCODLIB_API TCODHeightMap;
friend class TCODLIB_API TCODNamegen;
friend class TCODNameGenerator; // Used for SWIG interface, does NOT need TCODLIB_API
TCOD_Random* data;
};
#endif

View file

@ -0,0 +1,89 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_RANDOM_TYPES_H
#define _TCOD_RANDOM_TYPES_H
#include <stdint.h>
#include "config.h"
/* dice roll */
typedef struct {
int nb_rolls;
int nb_faces;
float multiplier;
float addsub;
} TCOD_dice_t;
/* PRNG algorithms */
typedef enum {
/***************************************************************************
@brief Mersenne Twister implementation.
*/
TCOD_RNG_MT,
/***************************************************************************
@brief Complementary-Multiply-With-Carry implementation.
*/
TCOD_RNG_CMWC
} TCOD_random_algo_t;
typedef enum {
TCOD_DISTRIBUTION_LINEAR,
TCOD_DISTRIBUTION_GAUSSIAN,
TCOD_DISTRIBUTION_GAUSSIAN_RANGE,
TCOD_DISTRIBUTION_GAUSSIAN_INVERSE,
TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE
} TCOD_distribution_t;
// Old RNG, this struct and its attribute are private.
struct TCOD_Random_MT_CMWC {
TCOD_random_algo_t algorithm; // algorithm identifier
TCOD_distribution_t distribution; // distribution
// Mersenne Twister stuff
uint32_t mt[624];
int cur_mt;
// Complementary-Multiply-With-Carry stuff
// shared with Generalised Feedback Shift Register
uint32_t Q[4096], c;
int cur;
};
/***************************************************************************
@brief Pseudorandom number generator toolkit, all attributes are private.
*/
typedef union TCOD_Random {
TCOD_random_algo_t algorithm;
struct TCOD_Random_MT_CMWC mt_cmwc;
} TCOD_Random;
TCOD_DEPRECATED("This type hides indirection. Use TCOD_Random* instead.")
typedef union TCOD_Random* TCOD_random_t;
#endif /* _TCOD_RANDOM_TYPES_H */

View file

@ -0,0 +1,58 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_MOUSE_H
#define _TCOD_MOUSE_H
#include "mouse_types.h"
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
TCOD_DEPRECATED("Use SDL_ShowCursor to handle the mouse cursor.")
TCODLIB_API void TCOD_mouse_show_cursor(bool visible);
TCOD_DEPRECATED("Use SDL_GetMouseState to check the mouse state.")
TCODLIB_API TCOD_mouse_t TCOD_mouse_get_status(void);
TCOD_DEPRECATED("Use SDL_ShowCursor to check the mouse cursor.")
TCODLIB_API bool TCOD_mouse_is_cursor_visible(void);
TCOD_DEPRECATED("Use SDL_WarpMouseInWindow to move mouse cursor instead.")
TCODLIB_API void TCOD_mouse_move(int x, int y);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_mouse_includes_touch(bool enable);
#ifdef __cplusplus
}
#endif
#endif /* _TCOD_MOUSE_H */

View file

@ -0,0 +1,62 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_MOUSE_HPP
#define _TCOD_MOUSE_HPP
#include "mouse.h"
#include "mouse_types.h"
class TCODLIB_API TCODMouse {
public:
TCOD_DEPRECATED(
"Use SDL_ShowCursor to handle the mouse cursor."
"\n\tSDL_ShowCursor(visible);")
static void showCursor(bool visible);
TCOD_DEPRECATED(
"Use SDL_ShowCursor to handle the mouse cursor."
"\n\tint is_visible = SDL_ShowCursor(SDL_QUERY);")
static bool isCursorVisible();
TCOD_DEPRECATED(
"Use SDL_WarpMouseInWindow to handle the mouse cursor."
"\n\tSDL_WarpMouseInWindow(NULL, x, y);")
static void move(int x, int y);
TCOD_DEPRECATED(
"Use SDL_GetMouseState to check the mouse state."
"\n\tint x;"
"\n\tint y;"
"\n\nint buttons = SDL_GetMouseState(&x, &y);")
static TCOD_mouse_t getStatus();
};
#endif /* _TCOD_MOUSE_HPP */

View file

@ -0,0 +1,51 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_MOUSE_TYPES_H
#define _TCOD_MOUSE_TYPES_H
#include "portability.h"
/* mouse data */
typedef struct {
int x, y; /* absolute position */
int dx, dy; /* movement since last update in pixels */
int cx, cy; /* cell coordinates in the root console */
int dcx, dcy; /* movement since last update in console cells */
bool lbutton; /* left button status */
bool rbutton; /* right button status */
bool mbutton; /* middle button status */
bool lbutton_pressed; /* left button pressed event */
bool rbutton_pressed; /* right button pressed event */
bool mbutton_pressed; /* middle button pressed event */
bool wheel_up; /* wheel up event */
bool wheel_down; /* wheel down event */
} TCOD_mouse_t;
#endif /* _TCOD_MOUSE_TYPES_H */

View file

@ -0,0 +1,64 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
/*
* Mingos' NameGen
* This file was written by Dominik "Mingos" Marczuk.
*/
#ifndef _TCOD_NAMEGEN_H
#define _TCOD_NAMEGEN_H
#include "list.h"
#include "mersenne.h"
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
/* the generator typedef */
struct TCOD_NameGen;
typedef struct TCOD_NameGen* TCOD_namegen_t;
/* parse a file with syllable sets */
TCODLIB_API void TCOD_namegen_parse(const char* filename, TCOD_Random* random);
/* generate a name */
TCODLIB_API char* TCOD_namegen_generate(const char* name, bool allocate);
/* generate a name using a custom generation rule */
TCODLIB_API char* TCOD_namegen_generate_custom(const char* name, const char* rule, bool allocate);
/* retrieve the list of all available syllable set names */
TCODLIB_API TCOD_list_t TCOD_namegen_get_sets(void);
/* delete a generator */
TCODLIB_API void TCOD_namegen_destroy(void);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,305 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
/*
* Mingos' NameGen
* This file was written by Dominik "Mingos" Marczuk.
*/
#ifndef _TCOD_NAMEGEN_HPP
#define _TCOD_NAMEGEN_HPP
#include <string>
#include "list.hpp"
#include "mersenne.hpp"
#include "namegen.h"
/**
@PageName namegen
@PageCategory Roguelike toolkits
@PageTitle Name generator
@PageDesc This tool allows one to generate random names out of custom made syllable sets.
*/
class TCODLIB_API TCODNamegen {
public:
/**
@PageName namegen_init
@PageFather namegen
@PageTitle Creating a generator
@FuncDesc In order to be able to generate names, the name generator needs to be fed proper data. It will then be ready to generate random names defined in the file(s) it is fed. Syllable set parsing is achieved via the following.
Note 1: Each file will be parsed once only. If, for some reason, you would like to parse the same file twice, you will need to destroy the generator first, which will empty the list of parsed files along with erasing all the data retrieved from those files.
Note 2: The generator can be fed data multiple times if you have it in separate files. Just make sure the structure names in them aren't duplicated, otherwise they will be silently ignored.
Note 3: In the C++ version, you are not obliged to specify the random number generator. If you skip it in the function call, the generator will assume you would like to use an instance of the default generator.
@Cpp static void TCODNamegen::parse (const char * filename, TCODRandom * random = NULL)
@C void TCOD_namegen_parse (const char * filename, TCOD_random_t random)
@Py namegen_parse (filename, random = 0)
@C#
static void TCODNameGenerator::parse(string filename)
static void TCODNameGenerator::parse(string filename, TCODRandom random)
@Param filename The file where the desired syllable set is saved, along with its relative path, for instance, "data/names.txt".
@Param random A random number generator object. Use NULL for the default random number generator
@CppEx
TCODNamegen::parse("data/names.txt",TCODRandom::getInstance());
TCODNamegen::parse("data/names2.txt");
@CEx TCOD_namegen_parse("data/names.txt",TCOD_random_get_instance());
@PyEx libtcod.namegen_parse('data/names.txt')
*/
static void parse (const char * filename, TCODRandom * random = NULL);
/**
@PageName namegen_init
@FuncTitle Destroying a generator
@FuncDesc To release the resources used by a name generator, you may call:
This will free all memory used by the generator. In order to generate a name again, you have to parse a file again.
@Cpp static void TCODNamegen::destroy (void)
@C void TCOD_namegen_destroy (void)
@Py namegen_destroy ()
@C# static void TCODNameGenerator::destroy()
*/
static void destroy (void);
/**
@PageName namegen_generate
@PageTitle Generating a name
@PageFather namegen
@FuncTitle Generating a default name
@FuncDesc The following will output a random name generated using one of the generation rules specified in the syllable set:
Should you choose to allocate memory for the output, you need to remember to deallocate it once you don't need the name anymore using the free() function. This applies to C++ as well (delete won't work - you have to use free()).
On the other hand, should you choose not to allocate memory, be aware that subsequent calls will overwrite the previously returned pointer, so make sure to copy the output using strcpy(), strdup() or other means of your choosing.
The name you specify needs to be in one of the files the generator has previously parsed (see Creating a generator). If such a name doesn't exist, a warning will be displayed and NULL will be returned.
@Cpp static char * TCODNamegen::generate (char * name, bool allocate = false)
@C char * TCOD_namegen_generate (char * name, bool allocate)
@Py namegen_generate (name, allocate = 0)
@C# string TCODNameGenerator::generate (string name)
@Param name The structure name you wish to refer to, for instance, "celtic female".
For more about how structure names work, please refer to <a href="namegen_file.html">those</a> <a href="parser_format.html">chapters</a>.
@Param allocate Whether memory should be allocated for the output or not.
@CppEx
TCODNamegen::parse("data/names.txt",TCODRandom::getInstance());
char * myName = TCODNamegen::generate("fantasy female");
@CEx
TCOD_namegen_parse("data/names.txt",TCOD_random_get_instance());
char * my_name = TCOD_namegen_generate("Celtic male",false);
@PyEx
libtcod.namegen_parse('data/names.txt')
name = libtcod.namegen_generate('Nordic female')
*/
[[deprecated("This overload is deprecated, be sure to pass in const strings.")]]
static char * generate (char * name, bool allocate = false);
static std::string generate (const char * name, bool allocate = false);
/**
@PageName namegen_generate
@FuncTitle Generating a custom name
@FuncDesc It is also possible to generate a name using custom generation rules. This overrides the random choice of a generation rule from the syllable set. Please refer to chapter 16.5 to learn about the name generation rules syntax.
@Cpp static char * TCODNamegen::generateCustom (char * name, char * rule, bool allocate = false)
@C char * TCOD_namegen_generate_custom (char * name, char * rule, bool allocate)
@Py namegen_generate_custom (name, rule, allocate = 0)
@C# string TCODNameGenerator::generateCustom (string name, string rule)
@Param name The structure name you wish to refer to, for instance, "celtic female".
For more about how structure names work, please refer to <a href="namegen_file.html">those</a> <a href="parser_format.html">chapters</a>.
@Param rule The name generation rule. See <a href="namegen_file.html">this chapter</a> for more details.
@Param allocate Whether memory should be allocated for the output or not.
@CppEx
TCODNamegen::parse("data/names.txt",TCODRandom::getInstance());
char * myName = TCODNamegen::generateCustom("Nordic male","$s$e");
@CEx
TCOD_namegen_parse("data/names.txt",TCOD_random_get_instance());
char * my_name = TCOD_namegen_generate_custom("Mesopotamian female","$s$e",false);
@PyEx
libtcod.namegen_parse('data/names.txt')
name = libtcod.namegen_generate_custom('Nordic female','$s$e')
*/
[[deprecated("This overload is deprecated, be sure to pass in const strings.")]]
static char * generateCustom (char * name, char * rule, bool allocate = false);
static std::string generateCustom (const char * name, const char * rule, bool allocate = false);
/**
@PageName namegen_generate
@FuncTitle Retrieving available set names
@FuncDesc If you wish to check the syllable set names that are currently available, you may call:
This will create a list with all the available syllable set names. Remember to delete that list after you don't need it anymore!
@Cpp static TCODList TCODNamegen::getSets ()
@C TCOD_list_t TCOD_namegen_get_sets ()
@Py namegen_get_sets ()
@C# static IEnumerable<string> TCODNameGenerator::getSets()
*/
static TCOD_list_t getSets (void);
/**
@PageName namegen_file
@PageFather namegen
@PageTitle Syllable set configuration
@PageDesc Configuring the syllable set is vital to obtaining high quality randomly generated names. Please refer to the following subchapters for detailed information:
*/
/**
@PageName namegen_file_1
@PageFather namegen_file
@PageTitle Syllable set basic structure
@PageDesc The syllable sets need to be written in one or more text files that will be opened and parsed by the generator.
The data uses a standard TCODParser file and data should be inserted according to the general rules of creating a configuration file. For more information, please refer to <a href="parser_format.html">The libtcod config file format</a>.
The structure type that's defined in the generator is "name". This structure type must also be accompanied by a structure name. It will be used for identification purposes in the generator. For instance, if you use a structure name "fantasy female", you will be able to access this syllable set by creating a generator using "fantasy female" syllables. In the initialisation function, this is the "const char * name" argument.
The structure contains different members, all of which must be of TCOD_TYPE_STRING type. The tokens inside the strings, be them phonemes or syllables, form a single string, but are separated with separator characters. Characters used for token separation are all characters that are not Latin upper- or lowercase characters, dashes or apostrophes. A comma, a space or a comma+space are all perfectly valid, human-readable separators. In order to use a character inside a string that would normally be considered a separator, precede it with a slash (eg. "/:", "/.", "/!", etc.). An exception to this rule is the space character, which can also be achieved by using an underscore (eg. "the_Great").
The structure members that may thus be defined are:
<div class="code"><p>phonemesVocals
phonemesConsonants
syllablesPre
syllablesStart
syllablesMiddle
syllablesEnd
syllablesPost
</p></div>
All of those strings are considered optional. However, if you don't define a string, but reference it in the name generation rules, you will see a warning displayed on stderr about missing data.
*/
/**
@PageName namegen_file_2
@PageFather namegen_file
@PageTitle Illegal strings
@PageDesc Another optional property is
<div class="code"><p>illegal</p></div>
This property contains strings that are considered illegal and thus not desired in your names. Should a generated name contain any of the tokens specified in this string, it will be discarded and replaced by a new one. Illegal strings may be as short as single characters or as long as entire names. However, it is best to create a syllable set that generates very few names that sound bad. Otherwise, the illegal list might become very long.
Be aware that the generator will automatically correct or reject certain words, so you don't need to place every undesired possibility in this string.
The generator will correct the following:
* leading spaces ("_NAME")
* ending spaces ("NAME_")
* double spaces ("NAME1__NAME2")
It will generate a new name in the following cases:
* triple characters ("Raaagnar")
* two-character adjacent repetitions ("Bobofur" is wrong, but "Bombofur" is OK)
* three-character (or more) repetitions, whether adjacent or not ("Bombombur", "Dagbjoerdag", "Gwaerdygwaern")
Remember that all of this is case-insensitive, so you don't need to care about uppercase/lowercase distinction in your illegal strings.
*/
/**
@PageName namegen_file_3
@PageFather namegen_file
@PageTitle Rules
@PageDesc There's one last string that's contained within the structure:
<div class="code"><p>rules</p></div>
It is mandatory, so not defining it will trigger an error. It defines how the generator should join the supplied data in order to generate a name. This string uses a syntax of its own, which is also used when specifying a rule when generating a custom name (see chapter 16.2).
The rules are parsed pretty much the same way as all other strings, so all rules regarding separators and special characters apply as well. However, you can additionally use a set of wildcards and frequency markers. Each wildcard is preceded by the dollar sign ('$'), while frequency markers are preceded by the per cent sign ('%'). Here's the complete wildcard list:
<table class="param">
<tbody><tr><th>Wildcard</th><th>Example</th><th>Description</th></tr>
<tr class="hilite"><td>$[INT]P</td><td>$P, $25P</td><td>Use a random Pre syllable.<br>The optional integer value denotes the per cent chance of adding the syllable.</td></tr>
<tr><td>$[INT]s</td><td>$s, $25s</td><td>Use a random Start syllable.</td></tr>
<tr class="hilite"><td>$[INT]m</td><td>$m, $25m</td><td>Use a random Middle syllable.</td></tr>
<tr><td>$[INT]e</td><td>$e, $25e</td><td>Use a random End syllable.</td></tr>
<tr class="hilite"><td>$[INT]p</td><td>$p, $25p</td><td>Use a random Post syllable.</td></tr>
<tr><td>$[INT]v</td><td>$v, $25v</td><td>Use a random vocal.</td></tr>
<tr class="hilite"><td>$[INT]c</td><td>$c, $25c</td><td>Use a random consonant.</td></tr>
<tr><td>$[INT]?</td><td>$?, $25?</td><td>Use a random phoneme (vocal or consonant).</td></tr>
<tr class="hilite"><td>%INT</td><td>%50, %25</td><td>Frequency marker. Denotes the per cent chance for the rule to be accepted if it's picked.<br>If the rule is not accepted, another roll is made to choose a name generation rule.<br>It's used to reduce the frequency a given rule is chosen with.<br>This marker may only appear at the beginning of a rule.</td></tr>
</tbody></table>
*/
/**
@PageName namegen_file_4
@PageFather namegen_file
@PageTitle Example structure
@PageDesc Consider this example structure. It does not contain syllables, but rather full names.
<div class="code"><p>name "king" {
syllablesStart = "Alexander, Augustus, Casimir, Henry, John, Louis, Sigismund,"
"Stanislao, Stephen, Wenceslaus"
syllablesMiddle = "I, II, III, IV, V"
syllablesEnd = "Bathory, Herman, Jogaila, Lambert, of_Bohemia, of_France,"
"of_Hungary, of_Masovia, of_Poland, of_Valois, of_Varna, Probus,"
"Spindleshanks, Tanglefoot, the_Bearded, the_Black, the_Bold, the_Brave,"
"the_Chaste, the_Curly, the_Elbow-high, the_Exile, the_Great,"
"the_Jagiellonian, the_Just, the_Old, the_Pious, the_Restorer, the_Saxon,"
"the_Strong, the_Wheelwright, the_White, Vasa, Wrymouth"
rules = "%50$s, $s_$m, $s_$50m_$e"
}</p></div>
The above structure only uses three syllable lists and has three different rules. Let's analyze them one by one.
%50$s - this will simply output a random Start syllable, but this rule is not intended to be picked with the same frequency as the others, so the frequency marker at the beginning ("%50") ensures that 50% of the time this syllable will be rejected and a different one will be picked.
$s_$m - this will output a Start syllable and a Middle syllable, separated with a space.
$s_$50m_$e - This will output a Start syllable, followed by a Middle syllable, followed by an End syllable, all separated with spaces. However, the Middle syllable has only 50% chance of appearing at all, so 50% of the time the rule will actually produce a Start syllable followed directly by an End syllable, separated with a space.
As you may have noticed, the third rule may produce a double space if the Middle syllable is not chosen. You do not have to worry about such cases, as the generator will automatically reduce all double spaces to single spaces, and leading/ending spaces will be removed completely.
Output from this example set would contain kings' names based on the names of real monarchs of Poland. Have a look at the sample:
<div class="code"><p>Alexander IV
Alexander
Sigismund
Stanislao V
Stanislao
Henry I of Poland
Augustus V
Stanislao I the Pious
Sigismund IV the Brave
John the Great
Henry the Old
John the Bold
Stanislao II the Saxon
Wenceslaus of France
John Probus
Louis V
Wenceslaus Lambert
Stanislao Spindleshanks
Henry Herman
Alexander the Old
Louis V the Curly
Wenceslaus II
Augustus IV
Alexander V
Augustus Probus
</p></div>
*/
};
#endif

View file

@ -0,0 +1,162 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_PERLIN_H
#define _TCOD_PERLIN_H
#include "config.h"
#include "mersenne_types.h"
#include "noise_defaults.h"
typedef enum {
TCOD_NOISE_PERLIN = 1,
TCOD_NOISE_SIMPLEX = 2,
TCOD_NOISE_WAVELET = 4,
TCOD_NOISE_DEFAULT = 0
} TCOD_noise_type_t;
typedef struct TCOD_Noise {
int ndim;
/** Randomized map of indexes into buffer */
unsigned char map[256];
/** Random 256 x ndim buffer */
float buffer[256][TCOD_NOISE_MAX_DIMENSIONS];
/* fractal stuff */
float H;
float lacunarity;
float exponent[TCOD_NOISE_MAX_OCTAVES];
float* __restrict waveletTileData;
TCOD_Random* rand;
/* noise type */
TCOD_noise_type_t noise_type;
} TCOD_Noise;
typedef TCOD_Noise* TCOD_noise_t;
#ifdef __cplusplus
extern "C" {
#endif
/* create a new noise object */
TCOD_NODISCARD
TCOD_PUBLIC TCOD_Noise* TCOD_noise_new(int dimensions, float hurst, float lacunarity, TCOD_Random* random);
/* simplified API */
TCOD_PUBLIC void TCOD_noise_set_type(TCOD_Noise* __restrict noise, TCOD_noise_type_t type);
TCOD_NODISCARD
TCOD_PUBLIC float TCOD_noise_get_ex(TCOD_Noise* __restrict noise, const float* __restrict f, TCOD_noise_type_t type);
TCOD_NODISCARD
TCOD_PUBLIC float TCOD_noise_get_fbm_ex(
TCOD_Noise* __restrict noise, const float* __restrict f, float octaves, TCOD_noise_type_t type);
TCOD_NODISCARD
TCOD_PUBLIC float TCOD_noise_get_turbulence_ex(
TCOD_Noise* __restrict noise, const float* __restrict f, float octaves, TCOD_noise_type_t type);
TCOD_NODISCARD
TCOD_PUBLIC float TCOD_noise_get(TCOD_Noise* __restrict noise, const float* __restrict f);
TCOD_NODISCARD
TCOD_PUBLIC float TCOD_noise_get_fbm(TCOD_Noise* __restrict noise, const float* __restrict f, float octaves);
TCOD_NODISCARD
TCOD_PUBLIC float TCOD_noise_get_turbulence(TCOD_Noise* __restrict noise, const float* __restrict f, float octaves);
/* delete the noise object */
TCOD_PUBLIC void TCOD_noise_delete(TCOD_Noise* __restrict noise);
/**
Generate noise as a vectorized operation.
`noise` is the TCOD_Noise object to be used. Its dimensions will
determine how many input arrays are required.
`type` is which noise generator should be used.
Can be `TCOD_NOISE_DEFAULT` to use the type set by the TCOD_Noise object.
`n` is the length of the input and output arrays.
`x[n]`, `y[n]`, `z[n]`, `w[n]` are the input coordinates for the noise
generator. For a 2D generator you'd provide the `x[n]` and `y[n]` arrays
and leave the remaining arrays as NULL.
`out[n]` is the output array, which will receive the noise values.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC void TCOD_noise_get_vectorized(
TCOD_Noise* __restrict noise,
TCOD_noise_type_t type,
int n,
float* __restrict x,
float* __restrict y,
float* __restrict z,
float* __restrict w,
float* __restrict out);
/**
Generate noise as a vectorized operation with fractional Brownian motion.
`octaves` are the number of samples to take.
The remaining parameters are the same as `TCOD_noise_get_vectorized`.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC void TCOD_noise_get_fbm_vectorized(
TCOD_Noise* __restrict noise,
TCOD_noise_type_t type,
float octaves,
int n,
float* __restrict x,
float* __restrict y,
float* __restrict z,
float* __restrict w,
float* __restrict out);
/**
Generate noise as a vectorized operation with turbulence.
`octaves` are the number of samples to take.
The remaining parameters are the same as `TCOD_noise_get_vectorized`.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC void TCOD_noise_get_turbulence_vectorized(
TCOD_Noise* __restrict noise,
TCOD_noise_type_t type,
float octaves,
int n,
float* __restrict x,
float* __restrict y,
float* __restrict z,
float* __restrict w,
float* __restrict out);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,342 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
#ifndef _TCOD_PERLIN_HPP
#define _TCOD_PERLIN_HPP
#include <utility>
#include "mersenne.hpp"
#include "noise.h"
#include "noise_defaults.h"
/**
@PageName noise
@PageCategory Base toolkits
@PageTitle Noise generator
@PageDesc This toolkit provides several functions to generate Perlin noise and other derived noises. It can handle noise functions from 1 to 4 dimensions.
@FuncDesc
Usage example:
1D noise : the variation of a torch intensity
2D fbm : heightfield generation or clouds
3D fbm : animated smoke
If you don't know what is Perlin noise and derived functions, or what is the influence of the different fractal parameters, check the Perlin noise sample included with the library.
<table width="800px" class="none">
<tr><td align="center">Simplex noise, fbm, turbulence</td>
<td align="center"><img border="1" src="simplex.png"></td>
<td align="center"><img border="1" src="fbm_simplex.png"></td>
<td align="center"><img border="1" src="turbulence_simplex.png"></td></tr>
<tr><td align="center">Perlin noise, fbm, turbulence</td>
<td align="center"><img border="1" src="perlin.png"></td>
<td align="center"><img border="1" src="fbm_perlin.png"></td>
<td align="center"><img border="1" src="turbulence_perlin.png"></td></tr>
<tr><td align="center">Wavelet noise, fbm, turbulence</td>
<td align="center"><img border="1" src="wavelet.png"></td>
<td align="center"><img border="1" src="fbm_wavelet.png"></td>
<td align="center"><img border="1" src="turbulence_wavelet.png"></td></tr>
</table>
<h6>Noise functions relative times</h6>
For example, in 4D, Perlin noise is 17 times slower than simplex noise.
<table border="1">
<tr><td></td><td>1D</td><td>2D</td><td>3D</td><td>4D</td></tr>
<tr><td>simplex</td><td>1</td><td>1</td><td>1</td><td>1</td></tr>
<tr><td>Perlin</td><td>1.3</td><td>4</td><td>5</td><td>17</td></tr>
<tr><td>wavelet</td><td>53</td><td>32</td><td>14</td><td>X</td></tr>
</table>
*/
class TCODLIB_API TCODNoise {
public :
/**
@PageName noise_init
@PageFather noise
@PageTitle Creating a noise generator
@FuncDesc Those functions initialize a noise generator from a number of dimensions (from 1 to 4), some fractal parameters and a random number generator.
The C++ version provides several constructors. When the hurst and lacunarity parameters are omitted, default values (TCOD_NOISE_DEFAULT_HURST = 0.5f and TCOD_NOISE_DEFAULT_LACUNARITY = 2.0f) are used.
@Cpp
TCODNoise::TCODNoise(int dimensions, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
TCODNoise::TCODNoise(int dimensions, TCODRandom *random, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity, TCODRandom *random, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
@C TCOD_noise_t TCOD_noise_new(int dimensions, float hurst, float lacunarity, TCOD_random_t random)
@Py noise_new(dimensions, hurst=TCOD_NOISE_DEFAULT_HURST, lacunarity=TCOD_NOISE_DEFAULT_LACUNARITY, random=0)
@C#
TCODNoise::TCODNoise(int dimensions)
TCODNoise::TCODNoise(int dimensions, TCODRandom random)
TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity)
TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity, TCODRandom random)
@Param dimensions From 1 to 4.
@Param hurst For fractional brownian motion and turbulence, the fractal Hurst exponent. You can use the default value TCOD_NOISE_DEFAULT_HURST = 0.5f.
@Param lacunarity For fractional brownian motion and turbulence, the fractal lacunarity. You can use the default value TCOD_NOISE_DEFAULT_LACUNARITY = 2.0f.
@Param random A random number generator obtained with the Mersenne twister toolkit or NULL to use the default random number generator.
@CppEx
// 1 dimension generator
TCODNoise * noise1d = new TCODNoise(1);
// 2D noise with a predefined random number generator
TCODRandom *myRandom = new TCODRandom();
TCODNoise *noise2d = new TCODNoise(2,myRandom);
// a 3D noise generator with a specific fractal parameters
TCODNoise *noise3d = new TCODNoise(3,0.7f,1.4f);
@CEx
// 1 dimension generator
TCOD_noise_t noise1d = TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
// 2D noise with a predefined random number generator
TCOD_random_t my_random = TCOD_random_new();
TCOD_noise_t noise2d = TCOD_noise_new(2,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,my_random);
// a 3D noise generator with a specific fractal parameters
TCOD_noise_t noise3d = TCOD_noise_new(3,0.7f, 1.4f,NULL);
@PyEx
# 1 dimension generator
noise1d = libtcod.noise_new(1)
# 2D noise with a predefined random number generator
my_random = libtcod.random_new();
noise2d = libtcod.noise_new(2,libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY,my_random)
# a 3D noise generator with a specific fractal parameters
noise3d = libtcod.noise_new(3, 0.7, 1.4)
*/
TCODNoise(int dimensions, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
TCODNoise(int dimensions, TCODRandom *random, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
TCODNoise(int dimensions, float hurst, float lacunarity, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
TCODNoise(int dimensions, float hurst, float lacunarity, TCODRandom *random, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
TCODNoise(const TCODNoise&) = delete;
TCODNoise& operator=(const TCODNoise&) = delete;
TCODNoise(TCODNoise&& rhs) noexcept { std::swap(data, rhs.data); };
TCODNoise& operator=(TCODNoise&& rhs) noexcept {
std::swap(data, rhs.data);
return *this;
};
/**
@PageName noise_init
@FuncDesc To release resources used by a generator, use those functions :
@Cpp TCODNoise::~TCODNoise()
@C void TCOD_noise_delete(TCOD_noise_t noise)
@Py noise_delete(noise)
@C# void TCODNoise::Dispose()
@Param noise In the C and Python versions, the generator handler, returned by the initialization function.
@CppEx
// create a generator
TCODNoise *noise = new TCODNoise(2);
// use it
...
// destroy it
delete noise;
@CEx
// create a generator
TCOD_noise_t noise = TCOD_noise_new(2,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY, NULL);
// use it
...
// destroy it
TCOD_noise_delete(noise);
@PyEx
# create a generator
noise = libtcod.noise_new(2,libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY, 0)
# use it
...
# destroy it
libtcod.noise_delete(noise)
*/
virtual ~TCODNoise();
/**
@PageName noise_setType
@PageFather noise
@PageTitle Choosing a noise type
@FuncTitle Choosing a noise type
@FuncDesc Use this function to define the default algorithm used by the noise functions.
The default algorithm is simplex. It's much faster than Perlin, especially in 4 dimensions. It has a better contrast too.
@Cpp void TCODNoise::setType(TCOD_noise_type_t type)
@C void TCOD_noise_set_type(TCOD_noise_t noise, TCOD_noise_type_t type)
@Py noise_set_type(noise, type)
@C# void TCODNoise::setType(type)
@Param noise In the C version, the generator handler, returned by the initialization function.
@Param type The algorithm to use, either TCOD_NOISE_SIMPLEX, TCOD_NOISE_PERLIN or TCOD_NOISE_WAVELET.
@CppEx
TCODNoise * noise1d = new TCODNoise(1);
noise1d->setType(TCOD_NOISE_PERLIN);
@CEx
TCOD_noise_t noise1d = TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
TCOD_noise_set_type(noise1d,TCOD_NOISE_PERLIN);
@PyEx
noise1d = libtcod.noise_new(1)
libtcod.noise_set_type(noise1d,libtcod.NOISE_PERLIN)
*/
void setType (TCOD_noise_type_t type);
/**
@PageName noise_get
@PageFather noise
@PageTitle Getting flat noise
@FuncDesc This function returns the noise function value between -1.0 and 1.0 at given coordinates.
@Cpp float TCODNoise::get(float *f, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
@C float TCOD_noise_get(TCOD_noise_t noise, float *f)
float TCOD_noise_get_ex(TCOD_noise_t noise, float *f, TCOD_noise_type_t type)
@Py noise_get(noise, f, type=NOISE_DEFAULT)
@C# float TCODNoise::get(float[] f, type=NoiseDefault)
@Param noise In the C version, the generator handler, returned by the initialization function.
@Param f An array of coordinates, depending on the generator dimensions (between 1 and 4). The same array of coordinates will always return the same value.
@Param type The algorithm to use. If not defined, use the default one (set with setType or simplex if not set)
@CppEx
// 1d noise
TCODNoise * noise1d = new TCODNoise(1);
float p=0.5f;
// get a 1d simplex value
float value = noise1d->get(&p);
// 2d noise
TCODNoise * noise2d = new TCODNoise(2);
float p[2]={0.5f,0.7f};
// get a 2D Perlin value
float value = noise2d->get(p, TCOD_NOISE_PERLIN);
@CEx
// 1d noise
TCOD_noise_t noise1d = TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p=0.5f;
// get a 1d simplex value
float value = TCOD_noise_get(noise1d,&p);
// 2d noise
TCOD_noise_t noise2d = TCOD_noise_new(2,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p[2]={0.5f,0.7f};
// get a 2d perlin value
float value = TCOD_noise_get_ex(noise2d,p,TCOD_NOISE_PERLIN);
@PyEx
# 1d noise
noise1d = libtcod.noise_new(1)
# get a 1d simplex value
value = libtcod.noise_get(noise1d,[0.5])
# 2d noise
noise2d = libtcod.noise_new(2)
# get a 2d perlin value
value = libtcod.noise_get(noise2d,[0.5,0.7], libtcod.NOISE_PERLIN)
*/
float get(float *f, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
float get(const float *f, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
/**
@PageName noise_get_fbm
@PageFather noise
@PageTitle Getting fbm noise
@FuncDesc This function returns the fbm function value between -1.0 and 1.0 at given coordinates, using fractal hurst and lacunarity defined when the generator has been created.
@Cpp float TCODNoise::getFbm(float *f, float octaves, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
@C float TCOD_noise_get_fbm(TCOD_noise_t noise, float *f, float octaves)
float TCOD_noise_get_fbm(TCOD_noise_t noise, float *f, float octaves, TCOD_noise_type_t type)
@Py noise_get_fbm(noise, f, octaves, type=NOISE_DEFAULT)
@C# float TCODNoise::getBrownianMotion(float[] f, float octaves, type=NoiseDefault)
@Param noise In the C version, the generator handler, returned by the initialization function.
@Param f An array of coordinates, depending on the generator dimensions (between 1 and 4). The same array of coordinates will always return the same value.
@Param octaves Number of iterations. Must be < TCOD_NOISE_MAX_OCTAVES = 128
@Param type The algorithm to use. If not defined, use the default one (set with setType or simplex if not set)
@CppEx
// 1d fbm
TCODNoise * noise1d = new TCODNoise(1);
float p=0.5f;
// get a 1d simplex fbm
float value = noise1d->getFbm(&p,32.0f);
// 2d fbm
TCODNoise * noise2d = new TCODNoise(2);
float p[2]={0.5f,0.7f};
// get a 2d perlin fbm
float value = noise2d->getFbm(p,32.0f, TCOD_NOISE_PERLIN);
@CEx
// 1d fbm
TCOD_noise_t noise1d = TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p=0.5f;
// get a 1d simplex fbm
float value = TCOD_noise_get_fbm(noise1d,&p,32.0f);
// 2d fbm
TCOD_noise_t noise2d = TCOD_noise_new(2,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p[2]={0.5f,0.7f};
// get a 2d perlin fbm
float value = TCOD_noise_get_fbm_ex(noise2d,p,32.0f,TCOD_NOISE_PERLIN);
@PyEx
# 1d noise
noise1d = libtcod.noise_new(1)
# 1d simplex fbm
value = libtcod.noise_get_fbm(noise1d,[0.5],32.0)
# 2d noise
noise2d = libtcod.noise_new(2)
# 2d perlin fbm
value = libtcod.noise_get_fbm(noise2d,[0.5,0.7],32.0, libtcod.NOISE_PERLIN)
*/
float getFbm(float *f, float octaves, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
float getFbm(const float *f, float octaves, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
/**
@PageName noise_get_turbulence
@PageFather noise
@PageTitle Getting turbulence
@FuncDesc This function returns the turbulence function value between -1.0 and 1.0 at given coordinates, using fractal hurst and lacunarity defined when the generator has been created.
@Cpp float TCODNoise::getTurbulence(float *f, float octaves, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
@C float TCOD_noise_get_turbulence(TCOD_noise_t noise, float *f, float octaves)
float TCOD_noise_get_turbulence_ex(TCOD_noise_t noise, float *f, float octaves, TCOD_noise_type_t)
@Py noise_get_turbulence(noise, f, octaves, type=NOISE_DEFAULT)
@C# float TCODNoise::getTurbulence(float[] f, float octaves, type=NoiseDefault)
@Param noise In the C version, the generator handler, returned by the initialization function.
@Param f An array of coordinates, depending on the generator dimensions (between 1 and 4). The same array of coordinates will always return the same value.
@Param octaves Number of iterations. Must be < TCOD_NOISE_MAX_OCTAVES = 128
@CppEx
// 1d fbm
TCODNoise * noise1d = new TCODNoise(1);
float p=0.5f;
// a 1d simplex turbulence
float value = noise1d->getTurbulence(&p,32.0f);
// 2d fbm
TCODNoise * noise2d = new TCODNoise(2);
float p[2]={0.5f,0.7f};
// a 2d perlin turbulence
float value = noise2d->getTurbulence(p,32.0f, TCOD_NOISE_PERLIN);
@CEx
// 1d fbm
TCOD_noise_t noise1d = TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p=0.5f;
// a 1d simplex turbulence
float value = TCOD_noise_get_turbulence(noise1d,&p,32.0f);
// 2d fbm
TCOD_noise_t noise2d = TCOD_noise_new(2,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p[2]={0.5f,0.7f};
// a 2d perlin turbulence
float value = TCOD_noise_get_turbulence_ex(noise2d,p,32.0f, TCOD_NOISE_PERLIN);
@PyEx
# 1d noise
noise1d = libtcod.noise_new(1)
# 1d simplex turbulence
value = libtcod.noise_get_turbulence(noise1d,[0.5],32.0)
# 2d noise
noise2d = libtcod.noise_new(2)
# 2d perlin turbulence
value = libtcod.noise_get_turbulence(noise2d,[0.5,0.7],32.0,libtcod.NOISE_PERLIN)
*/
float getTurbulence(float *f, float octaves, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
float getTurbulence(const float *f, float octaves, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
protected :
friend class TCODLIB_API TCODHeightMap;
TCOD_noise_t data;
};
#endif

View file

@ -0,0 +1,40 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_NOISE_DEFAULTS
#define _TCOD_NOISE_DEFAULTS
#define TCOD_NOISE_MAX_OCTAVES 128
#define TCOD_NOISE_MAX_DIMENSIONS 4
#define TCOD_NOISE_DEFAULT_HURST 0.5f
#define TCOD_NOISE_DEFAULT_LACUNARITY 2.0f
#endif /* _TCOD_NOISE_DEFAULTS */

View file

@ -0,0 +1,196 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_PARSER_H
#define _TCOD_PARSER_H
#include "color.h"
#include "lex.h"
#include "list.h"
#include "mersenne.h"
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
/* generic type */
typedef enum {
TCOD_TYPE_NONE,
TCOD_TYPE_BOOL,
TCOD_TYPE_CHAR,
TCOD_TYPE_INT,
TCOD_TYPE_FLOAT,
TCOD_TYPE_STRING,
TCOD_TYPE_COLOR,
TCOD_TYPE_DICE,
TCOD_TYPE_VALUELIST00,
TCOD_TYPE_VALUELIST01,
TCOD_TYPE_VALUELIST02,
TCOD_TYPE_VALUELIST03,
TCOD_TYPE_VALUELIST04,
TCOD_TYPE_VALUELIST05,
TCOD_TYPE_VALUELIST06,
TCOD_TYPE_VALUELIST07,
TCOD_TYPE_VALUELIST08,
TCOD_TYPE_VALUELIST09,
TCOD_TYPE_VALUELIST10,
TCOD_TYPE_VALUELIST11,
TCOD_TYPE_VALUELIST12,
TCOD_TYPE_VALUELIST13,
TCOD_TYPE_VALUELIST14,
TCOD_TYPE_VALUELIST15,
TCOD_TYPE_CUSTOM00,
TCOD_TYPE_CUSTOM01,
TCOD_TYPE_CUSTOM02,
TCOD_TYPE_CUSTOM03,
TCOD_TYPE_CUSTOM04,
TCOD_TYPE_CUSTOM05,
TCOD_TYPE_CUSTOM06,
TCOD_TYPE_CUSTOM07,
TCOD_TYPE_CUSTOM08,
TCOD_TYPE_CUSTOM09,
TCOD_TYPE_CUSTOM10,
TCOD_TYPE_CUSTOM11,
TCOD_TYPE_CUSTOM12,
TCOD_TYPE_CUSTOM13,
TCOD_TYPE_CUSTOM14,
TCOD_TYPE_CUSTOM15,
TCOD_TYPE_LIST = 1024
} TCOD_value_type_t;
/* generic value */
typedef union {
bool b;
char c;
int32_t i;
float f;
char* s;
TCOD_color_t col;
TCOD_dice_t dice;
TCOD_list_t list;
void* custom;
} TCOD_value_t;
// Forward declarations for callback.
struct TCOD_parser_listener_t;
struct TCOD_ParserStruct;
/* a custom type parser */
typedef TCOD_value_t (*TCOD_parser_custom_t)(
TCOD_lex_t* lex, struct TCOD_parser_listener_t* listener, struct TCOD_ParserStruct* str, char* propname);
/***************************************************************************
@brief Parser struct, member variables are for internal use.
*/
typedef struct TCOD_ParserStruct {
char* name; // Entity type name.
TCOD_list_t flags; // List of flags.
TCOD_list_t props; // List of properties (name, type, mandatory)
TCOD_list_t lists; // List of value lists.
TCOD_list_t structs; // List of sub-structures.
} TCOD_ParserStruct;
typedef struct TCOD_ParserStruct TCOD_struct_int_t; // Deprecated
typedef struct TCOD_ParserStruct* TCOD_parser_struct_t; // Deprecated
/***************************************************************************
@brief Parser, member variables are for internal use.
*/
typedef struct TCOD_Parser {
TCOD_list_t structs; // List of structures.
TCOD_parser_custom_t customs[16]; // List of custom type parsers.
bool fatal; // True if a fatal error has occurred.
TCOD_list_t props; // List of properties if default listener is used.
} TCOD_Parser;
typedef struct TCOD_Parser TCOD_parser_int_t; // Deprecated
/* parser structures */
TCODLIB_API const char* TCOD_struct_get_name(const TCOD_ParserStruct* def);
TCODLIB_API void TCOD_struct_add_property(
TCOD_ParserStruct* def, const char* name, TCOD_value_type_t type, bool mandatory);
TCODLIB_API void TCOD_struct_add_list_property(
TCOD_ParserStruct* def, const char* name, TCOD_value_type_t type, bool mandatory);
TCODLIB_API void TCOD_struct_add_value_list(
TCOD_ParserStruct* def, const char* name, const char* const* value_list, bool mandatory);
TCODLIB_API void TCOD_struct_add_value_list_sized(
TCOD_ParserStruct* def, const char* name, const char* const* value_list, int size, bool mandatory);
TCODLIB_API void TCOD_struct_add_flag(TCOD_ParserStruct* def, const char* propname);
TCODLIB_API void TCOD_struct_add_structure(TCOD_ParserStruct* def, const TCOD_ParserStruct* sub_structure);
TCODLIB_API bool TCOD_struct_is_mandatory(TCOD_ParserStruct* def, const char* propname);
TCODLIB_API TCOD_value_type_t TCOD_struct_get_type(const TCOD_ParserStruct* def, const char* propname);
/* parser listener */
typedef struct TCOD_parser_listener_t {
bool (*new_struct)(TCOD_ParserStruct* str, const char* name);
bool (*new_flag)(const char* name);
bool (*new_property)(const char* propname, TCOD_value_type_t type, TCOD_value_t value);
bool (*end_struct)(TCOD_ParserStruct* str, const char* name);
void (*error)(const char* msg);
} TCOD_parser_listener_t;
/* the parser */
struct TCOD_Parser;
typedef struct TCOD_Parser* TCOD_parser_t;
TCODLIB_API TCOD_Parser* TCOD_parser_new(void);
TCODLIB_API TCOD_ParserStruct* TCOD_parser_new_struct(TCOD_Parser* parser, const char* name);
TCODLIB_API TCOD_value_type_t TCOD_parser_new_custom_type(TCOD_Parser* parser, TCOD_parser_custom_t custom_type_parser);
TCODLIB_API void TCOD_parser_run(TCOD_Parser* parser, const char* filename, TCOD_parser_listener_t* listener);
TCODLIB_API void TCOD_parser_delete(TCOD_Parser* parser);
/* error during parsing. can be called by the parser listener */
TCODLIB_FORMAT(1, 2)
TCODLIB_API void TCOD_parser_error(const char* msg, ...);
/* default parser listener */
TCODLIB_API bool TCOD_parser_has_property(TCOD_Parser* parser, const char* name);
TCODLIB_API bool TCOD_parser_get_bool_property(TCOD_Parser* parser, const char* name);
TCODLIB_API int TCOD_parser_get_char_property(TCOD_Parser* parser, const char* name);
TCODLIB_API int TCOD_parser_get_int_property(TCOD_Parser* parser, const char* name);
TCODLIB_API float TCOD_parser_get_float_property(TCOD_Parser* parser, const char* name);
TCODLIB_API const char* TCOD_parser_get_string_property(TCOD_Parser* parser, const char* name);
TCODLIB_API TCOD_color_t TCOD_parser_get_color_property(TCOD_Parser* parser, const char* name);
TCODLIB_API TCOD_dice_t TCOD_parser_get_dice_property(TCOD_Parser* parser, const char* name);
TCODLIB_API void TCOD_parser_get_dice_property_py(TCOD_Parser* parser, const char* name, TCOD_dice_t* dice);
TCODLIB_API void* TCOD_parser_get_custom_property(TCOD_Parser* parser, const char* name);
TCODLIB_API TCOD_list_t TCOD_parser_get_list_property(TCOD_Parser* parser, const char* name, TCOD_value_type_t type);
TCODLIB_API TCOD_value_t TCOD_parse_bool_value(void);
TCODLIB_API TCOD_value_t TCOD_parse_char_value(void);
TCODLIB_API TCOD_value_t TCOD_parse_integer_value(void);
TCODLIB_API TCOD_value_t TCOD_parse_float_value(void);
TCODLIB_API TCOD_value_t TCOD_parse_string_value(void);
TCODLIB_API TCOD_value_t TCOD_parse_color_value(void);
TCODLIB_API TCOD_value_t TCOD_parse_dice_value(void);
TCODLIB_API TCOD_value_t TCOD_parse_value_list_value(TCOD_ParserStruct* def, int list_num);
TCODLIB_API TCOD_value_t
TCOD_parse_property_value(TCOD_Parser* parser, TCOD_ParserStruct* def, char* propname, bool list);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,692 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
#ifndef _TCOD_PARSER_HPP
#define _TCOD_PARSER_HPP
#include <vector>
#include <memory>
#include "color.hpp"
#include "list.hpp"
#include "parser.h"
/**
@PageName parser
@PageTitle File parser
@PageCategory Base toolkits
@PageDesc This toolkit provides an easy way to parse complex text configuration files. It has two main advantages compared to a standard XML SAX parser:
* The configuration file format is more human readable than XML
* The parser knows some data types that it automatically converts to C variables (see <a href="parser_types.html">Standard data types</a>)
*/
/**
@PageName parser_format
@PageFather parser
@PageTitle The libtcod config file format
@FuncTitle Comments
@FuncDesc Your file can contain single line or multi-line comments :
<div class="code"><pre>// This is a single line comment
/<span>*</span>
This is a
multi-line comment
*<span>/</span>
</pre></div>
Multi-line comments can be nested :
<div class="code"><pre>/<span>*</span>
This is a
multi-line comment containing another
/<span>*</span>
&nbsp;&nbsp;&nbsp;&nbsp;multi-line
&nbsp;&nbsp;&nbsp;&nbsp;comment
*<span>/</span>
*<span>/</span>
</pre></div>
The parser is not sensible to space characters, tabulations or carriage return except inside strings.
*/
/**
@PageName parser_format
@FuncTitle Structures
@FuncDesc The libtcod config file format is basically a list of structures. A structure has a type, an optional name and contains properties. The type of the structure defines which properties are allowed / mandatory.
<div class="code"><pre>item_type "blade" { // structure's type : 'item_type'. structure's name : 'blade'
cost=300 // an integer property
weight=3.5 // a float property
deal_damage=true // a boolean property
damages="3d6+2" // a dice property
col="#FF0000" // a color property, using #RRGGBB syntax
damaged_color="128,96,96" // another color property, using rrr,ggg,bbb syntax
damage_type="slash" // a string property
description="This is a long"
"description." // a multi-line string property
abstract // a flag (simplified boolean property)
intList= [ 1,2,3 ] // a list of int values
floatList= [ 1.0,2,3.5 ] // a list of float values
stringList= [ "string1","string2","string3" ] // a list of string values
}
</pre></div>
A structure can also contain other structures either of the same type, or structures of another type :
<div class="code"><pre>item_type "blade" {
item_type "one-handed blades" {
// the item_type "blade" contains another item_type named "one-handed blades"
}
item_type "two-handed blades" {
// the item_type "blade" contains another item_type named "two-handed blades"
}
feature "damage" {
// the item_type "blade" contains another structure, type "feature", name "damage"
}
}
</pre></div>
Sometimes, you don't know the list of properties at compile-time. Fortunately, since libtcod 1.5.1, you can add auto-declaring properties in the file, using one of the type keywords :
<div class="code"><pre>item_type "blade" {
bool deal_damage=true
char character='D'
int cost=300
float weight=3.5
string damage_type="slash"
color col="#FF0000"
dice damages="3d6+2"
int[] intList= [ 1,2,3 ]
float[] floatList= [ 1.0,2,3.5 ]
string[] stringList= [ "string1","string2","string3" ]
}
</pre></div>
The properties declared with this syntax were not previously declared for the structure item_type. But since the type is specified, the parser won't reject them. Instead, it will add the property declaration to the structure dynamically (when it parses the file).
You can also dynamically create new structures and sub-structures with the struct keyword :
<div class="code"><pre>item_type "blade" {
struct component {
string name="blade"
float weight=1.0
}
}
</div>
With this syntax, you don't need to declare the "component" structure at all in the parser. It will be dynamically registered as the file is parsed.
*/
class TCODLIB_API TCODParser;
class TCODLIB_API TCODParserStruct;
class TCODLIB_API ITCODParserListener;
class TCODLIB_API TCODParser {
public :
/**
@PageName parser_str
@PageTitle Defining the file syntax
@PageFather parser
@FuncTitle Creating a parser
@FuncDesc Use this function to create a generic parser. Then you'll specialize this parser by defining the structures it can read.
@Cpp TCODParser::TCODParser()
@C TCOD_parser_t TCOD_parser_new()
@Py parser_new()
*/
TCODParser();
// Disable copy operators.
TCODParser(const TCODParser&) = delete;
TCODParser& operator=(const TCODParser&) = delete;
TCODParser(TCODParser&&) = default;
TCODParser& operator=(TCODParser&&) = default;
/**
@PageName parser_str
@FuncTitle Registering a new structure type
@Cpp TCODParserStruct *TCODParser::newStructure(const char *name)
@C TCOD_parser_struct_t TCOD_parser_new_struct(TCOD_parser_t parser, char *name)
@Py parser_new_struct(parser, name)
@Param parser In the C version, the parser handler, returned by TCOD_parser_new.
@Param name The name of the structure type (in the example, this would be "item_type").
@CppEx
TCODParser parser();
TCODParserStruct *itemTypeStruct = parser.newStructure("item_type");
@CEx
TCOD_parser_t parser = TCOD_parser_new();
TCOD_parser_struct_t item_type_struct = TCOD_parser_new_struct(parser, "item_type");
@PyEx
parser=libtcod.parser_new()
item_type_struct = libtcod.parser_new_struct(parser, "item_type")
*/
TCODParserStruct *newStructure(const char *name);
// register a new custom type
TCOD_value_type_t newCustomType(TCOD_parser_custom_t custom_type_parser);
/**
@PageName parser_run
@PageFather parser
@PageTitle Running the parser
@FuncTitle Running the parser
@FuncDesc Once you defined all the structure types and created your listener, you can start the actual parsing of the file :
@Cpp void TCODParser::run(const char *filename, ITCODParserListener *listener = NULL)
@C void TCOD_parser_run(TCOD_parser_t parser, const char *filename, TCOD_parser_listener_t *listener)
@Py parser_run(parser, filename, listener=0)
@Param parser In the C version, the parser handler, returned by TCOD_parser_new.
@Param filename The name of the text file to parse, absolute or relative to current directory.
@Param listener The listener containing the callbacks. Use NULL for the default listener
@Cpp myParser.run("config.txt",new MyListener());
@C TCOD_parser_run(my_parser,"config.txt", my_listener);
@Py libtcod.parser_run(my_parser,"config.txt", MyListener())
*/
void run(const char *filename, ITCODParserListener *listener = NULL);
/**
@PageName parser_run
@FuncTitle Destroying the parser
@FuncDesc Once you've done with the file parsing, you can release the resources used by the parser :
@Cpp TCODParser::~TCODParser()
@C void TCOD_parser_delete(TCOD_parser_t parser)
@Py parser_delete(parser)
@Param parser In the C version, the parser handler, returned by TCOD_parser_new.
*/
~TCODParser();
// error during parsing. can be called by the parser listener
void error(const char *msg, ...);
bool hasProperty(const char *name) const;
bool getBoolProperty(const char *name) const;
int getIntProperty(const char *name) const;
int getCharProperty(const char *name) const;
float getFloatProperty(const char *name) const;
TCODColor getColorProperty(const char *name) const;
TCOD_dice_t getDiceProperty(const char *name) const;
const char * getStringProperty(const char *name) const;
void * getCustomProperty(const char *name) const;
TCOD_list_t getListProperty(const char *name, TCOD_value_type_t type) const;
private :
bool parseEntity(TCODParserStruct *def, ITCODParserListener *listener);
TCOD_parser_t data;
#ifdef _MSC_VER
// Disable dll-interface warning. This value should only used internally.
#pragma warning(push)
#pragma warning(disable: 4251)
#endif // _MSC_VER
std::vector<std::unique_ptr<TCODParserStruct>> defs;
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
friend bool new_struct(TCOD_parser_struct_t def, const char* name) noexcept;
friend bool end_struct(TCOD_parser_struct_t def, const char* name) noexcept;
};
// a parser structure
class TCODLIB_API TCODParserStruct {
public :
/**
@PageName parser_str
@FuncTitle Adding a new flag
@FuncDesc Use this function to add a flag property to a structure type. A flag is a simplified boolean property. It cannot be mandatory: either it's present and it's true, or it's absent and it's false.<br />Note that in the C++ version, the function returns its parent object, allowing for chaining.
@Cpp TCODParserStruct* TCODParserStruct::addFlag(const char *name)
@C void TCOD_struct_add_flag(TCOD_parser_struct_t str,char *name)
@Py struct_add_flag(str,name)
@Param str In the C version, the structure handler, returned by TCOD_parser_new_struct.
@Param name The name of the flag (in the example, this would be "abstract").
@CppEx itemTypeStruct->addFlag("abstract")->addFlag("static");
@CEx TCOD_struct_add_flag(item_type_struct, "abstract");
@PyEx libtcod.struct_add_flag(item_type_struct, "abstract")
*/
TCODParserStruct* addFlag(const char *propname);
/**
@PageName parser_str
@FuncTitle Adding a new property
@FuncDesc Use this function to add a standard property to a structure type. Check standard property types here.<br />Note that in the C++ version, the function returns its parent object, allowing for chaining.
@Cpp TCODParserStruct* TCODParserStruct::addProperty(const char *name, TCOD_value_type_t type, bool mandatory)
@C void TCOD_struct_add_property(TCOD_parser_struct_t str, char *name, TCOD_value_type_t type, bool mandatory)
@Py struct_add_property(str, name, type, mandatory)
@Param str In the C version, the structure handler, returned by TCOD_parser_new_struct.
@Param name The name of the property (in the example, this would be "cost" or "damage" or ...).
@Param type The type of the property. It can be a standard type (see <a href="parser_types.html">this</a>).
@Param mandatory Is this property mandatory? If true and the property is not defined in the file, the parser will raise an error.
@CppEx
itemTypeStruct->addProperty("cost",TCOD_TYPE_INT,true)
->addProperty("weight",TCOD_TYPE_FLOAT,true)
->addProperty("deal_damage",TCOD_TYPE_BOOL,true)
->addProperty("damaged_color",TCOD_TYPE_COLOR,true);
@CEx
TCOD_struct_add_property(item_type_struct, "cost", TCOD_TYPE_INT, true);
TCOD_struct_add_property(item_type_struct, "damages", TCOD_TYPE_DICE, true);
TCOD_struct_add_property(item_type_struct, "color", TCOD_TYPE_COLOR, true);
TCOD_struct_add_property(item_type_struct, "damaged_color", TCOD_TYPE_COLOR, true);
@PyEx
libtcod.struct_add_property(item_type_struct, "cost", libtcod.TYPE_INT, True)
libtcod.struct_add_property(item_type_struct, "damages", libtcod.TYPE_DICE, True)
libtcod.struct_add_property(item_type_struct, "color", libtcod.TYPE_COLOR, True)
libtcod.struct_add_property(item_type_struct, "damaged_color", libtcod.TYPE_COLOR, True)
*/
TCODParserStruct* addProperty(const char *propname, TCOD_value_type_t type, bool mandatory);
/**
@PageName parser_str
@FuncTitle Adding a new value-list property
@FuncDesc A value-list property is a string property for which we define the list of allowed values. The parser will raise an error if the file contains an unauthorized value for this property.
The first value-list property that you add to a structure type will have the TCOD_TYPE_VALUELIST00 type. The next TCOD_TYPE_VALUELIST01. You can define up to 16 value list property for each structure type. The last one has the type TCOD_TYPE_VALUELIST15.
You must provide a value list as a NULL terminated array of strings.<br />Note that in the C++ version, the function returns its parent object, allowing for chaining.
@Cpp TCODParserStruct* TCODParserStruct::addValueList(const char *name, const char **value_list, bool mandatory)
@C void TCOD_struct_add_value_list(TCOD_parser_struct_t str, char *name, char **value_list, bool mandatory)
@Py struct_add_value_list(str, name, value_list, mandatory)
@Param str In the C version, the structure handler, returned by TCOD_parser_new_struct.
@Param name The name of the property (in the example, this would be "damage_type").
@Param value_list The list of allowed strings.
@Param mandatory Is this property mandatory ? If true and the property is not defined in the file, the parser will raise an error.
@CppEx
static const char *damageTypes[] = { "slash", "pierce", "bludgeon", NULL }; // note the ending NULL
itemTypeStruct->addValueList("damage_type", damageTypes, true);
@CEx
static const char *damage_types[] = { "slash", "pierce", "bludgeon", NULL };
TCOD_struct_add_value_list(item_type_struct, "damage_type", damage_types, true);
@PyEx
damage_types = [ "slash", "pierce", "bludgeon" ]
libtcod.struct_add_value_list(item_type_struct, "damage_type", damage_types, True)
*/
TCODParserStruct* addValueList(const char *propname, const char **value_list, bool mandatory);
/**
@PageName parser_str
@FuncTitle Adding a new list property
@FuncDesc Use this function to add a list property to a structure type.<br />Note that in the C++ version, the function returns its parent object, allowing for chaining.
@Cpp TCODParserStruct* TCODParserStruct::addListProperty(const char *name, TCOD_value_type_t type, bool mandatory)
@C void TCOD_struct_add_list_property(TCOD_parser_struct_t str, char *name, TCOD_value_type_t type, bool mandatory)
@Py struct_add_list_property(str, name, type, mandatory)
@Param str In the C version, the structure handler, returned by TCOD_parser_new_struct.
@Param name The name of the property (in the example, this would be "cost" or "damages" or ...).
@Param type The type of the list elements. It must be a standard type (see <a href="parser_types.html">this</a>). It cannot be TCOD_TYPE_LIST.
@Param mandatory Is this property mandatory ? If true and the property is not defined in the file, the parser will raise an error.
@CppEx
itemTypeStruct->addListProperty("intList",TCOD_TYPE_INT,true)
->addListProperty("floatList",TCOD_TYPE_FLOAT,true)
->addListProperty("stringList",TCOD_TYPE_STRING,true);
@CEx
TCOD_struct_add_list_property(item_type_struct, "intList", TCOD_TYPE_INT, true);
TCOD_struct_add_list_property(item_type_struct, "floatList", TCOD_TYPE_FLOAT, true);
TCOD_struct_add_list_property(item_type_struct, "stringList", TCOD_TYPE_STRING, true);
@PyEx
libtcod.struct_add_list_property(item_type_struct, "intList", libtcod.TYPE_INT, True)
libtcod.struct_add_list_property(item_type_struct, "floatList", libtcod.TYPE_FLOAT, True)
libtcod.struct_add_list_property(item_type_struct, "stringList", libtcod.TYPE_STRING, True)
*/
TCODParserStruct* addListProperty(const char *propname, TCOD_value_type_t type, bool mandatory);
/**
@PageName parser_str
@FuncTitle Adding a sub-structure
@FuncDesc A structure can contain others structures. You can tell the parser which structures are allowed inside one structure type with this function.<br />Note that in the C++ version, the function returns its parent object, allowing for chaining.
@Cpp TCODParserStruct* TCODParserStruct::addStructure(TCODParserStruct *sub_structure)
@C void TCOD_struct_add_structure(TCOD_parser_struct_t str, TCOD_parser_struct_t sub_structure)
@Py struct_add_structure(str, sub_structure)
@Param str In the C version, the structure handler, returned by TCOD_parser_new_struct.
@Param sub_structure The structure type that can be embedded.
@CppEx
// The item_type structure can contain itself
itemTypeStruct->addStructure(itemTypeStruct);
@CEx TCOD_struct_add_value_list(item_type_struct, item_type_struct);
@PyEx libtcod.struct_add_value_list(item_type_struct, item_type_struct)
*/
TCODParserStruct* addStructure(TCODParserStruct *sub_entity);
/**
@PageName parser_str
@FuncTitle Getting a structure type's name
@FuncDesc You can retrieve the name of the structure type with these functions. Warning ! Do not confuse the structure type's name with the structure's name :
<div class="code"><p>item_type "sword" { ... }</p></div>
Here, the structure type's name is "item_type", the structure name is "sword". Obviously, the structure name cannot be retrieved from the TCODParserStruct object because it's only known at "runtime" (while parsing the file).
@Cpp const char *TCODParserStruct::getName() const
@C const char *TCOD_struct_get_name(TCOD_parser_struct_t str)
@Py struct_get_name(str)
@Param str In the C version, the structure handler, returned by TCOD_parser_new_struct.
@CppEx const char *structName = itemTypeStruct->getName(); // returns "item_type"
@CEx const char *struct_name = TCOD_struct_get_name(item_type_struct);
@PyEx struct_name = libtcod.struct_get_name(item_type_struct)
*/
const char *getName() const;
/**
@PageName parser_str
@FuncTitle Checking if a property is mandatory
@FuncDesc You can know if a property is mandatory :
@Cpp bool TCODParserStruct::isPropertyMandatory(const char *name) const
@C bool TCOD_struct_is_mandatory(TCOD_parser_struct_t str,const char *name)
@Py struct_is_mandatory(str,name)
@Param str In the C version, the structure handler, returned by TCOD_parser_new_struct.
@Param name The name of the property, as defined when you called addProperty or addValueList or addListProperty.
@CppEx bool costMandatory = itemTypeStruct->isPropertyMandatory("cost");
@CEx bool cost_mandatory = TCOD_struct_is_mandatory(item_type_struct, "cost");
@PyEx cost_mandatory = libtcod.struct_is_mandatory(item_type_struct, "cost")
*/
bool isPropertyMandatory(const char *propname) const;
/**
@PageName parser_str
@FuncTitle Retrieving the type of a property
@FuncDesc You get the type of a property :
In the case of a list property, the value returned is a bitwise or of TCOD_TYPE_LIST and the list element's type. For example, for a list of int, it will return TCOD_TYPE_LIST | TCOD_TYPE_INT.
@Cpp TCOD_value_type_t TCODParserStruct::getPropertyType(const char *name) const
@C TCOD_value_type_t TCOD_struct_get_type(TCOD_parser_struct_t str, const char *name)
@Py struct_get_type(str, name)
@Param str In the C version, the structure handler, returned by TCOD_parser_new_struct.
@Param name The name of the property, as defined when you called addProperty or addValueList or addListProperty.
@CppEx
TCOD_value_type_t costType = itemTypeStruct->getPropertyType("cost"); // returns TCOD_TYPE_INT
TCOD_value_type_t intListType = itemTypeStruct->getPropertyType("intList"); // returns TCOD_TYPE_LIST|TCOD_TYPE_INT
@CEx TCOD_value_type_t cost_type = TCOD_struct_get_type(item_type_struct, "cost");
@PyEx cost_type = libtcod.struct_get_type(item_type_struct, "cost")
*/
TCOD_value_type_t getPropertyType(const char *propname) const;
// private stuff
TCOD_parser_struct_t data;
};
/**
@PageName parser_run
@FuncTitle Creating a listener
@FuncDesc For basic config files, you don't have to write a listener. Instead, use the default listener. The parser uses a SAX-like approach during the parsing of the file. This means that the whole file is not stored in memory in a tree structure. Instead, it works like a stream parser and raises events. Each event has an associated callback that is provided by a listener :
@Cpp
class ITCODParserListener {
public :
virtual bool parserNewStruct(TCODParser *parser,const TCODParserStruct *str,const char *name)=0;
virtual bool parserFlag(TCODParser *parser,const char *name)=0;
virtual bool parserProperty(TCODParser *parser,const char *name, TCOD_value_type_t type, TCOD_value_t value)=0;
virtual bool parserEndStruct(TCODParser *parser,const TCODParserStruct *str, const char *name)=0;
virtual void error(const char *msg) = 0;
};
@C
typedef struct {
bool (*new_struct)(TCOD_parser_struct_t str,const char *name);
bool (*new_flag)(const char *name);
bool (*new_property)(const char *name, TCOD_value_type_t type, TCOD_value_t value);
bool (*end_struct)(TCOD_parser_struct_t str, const char *name);
void (*error)(const char *msg);
} TCOD_parser_listener_t;
@Py
class ParserListener :
def new_struct(str,name) : ...
def new_flag(name) : ...
def new_property(name,type,value) : ...
def end_struct(self, struct, name) : ...
def error(msg) : ...
*/
/**
@PageName parser_run
@FuncDesc Before running the parser, you have to build a listener :
@Cpp
class MyListener : public ITCODParserListener {
bool parserNewStruct(TCODParser *parser,const TCODParserStruct *str,const char *name) {
printf ("new structure type '%s' with name '%s'\n",str->getname(),name ? name : "NULL");
return true;
}
bool parserFlag(TCODParser *parser,const char *name) {
printf ("found new flag '%s'\n",name);
return true;
}
bool parserProperty(TCODParser *parser,const char *name, TCOD_value_type_t type, TCOD_value_t value) {
printf ("found new property '%s'\n",name);
return true;
}
bool parserEndStruct(TCODParser *parser,const TCODParserStruct *str,const char *name) {
printf ("end of structure type '%s'\n",name);
return true;
}
void error(char *msg) {
fprintf(stderr,msg);
exit(1);
}
};
@C
bool my_parser_new_struct(TCOD_parser_struct_t str, const char *name) {
printf ("new structure type '%s' with name '%s'\n",TCOD_struct_get_name(str),name ? name : "NULL");
return true;
}
bool my_parser_flag(const char *name) {
printf ("found new flag '%s'\n",name);
return true;
}
bool my_parser_property(const char *name, TCOD_value_type_t type, TCOD_value_t value) {
printf ("found new property '%s'\n",name);
return true;
}
bool my_parser_end_struct(TCOD_parser_struct_t str, const char *name) {
printf ("end of structure type '%s'\n",name);
return true;
}
void my_parser_error(const char *msg) {
fprintf(stderr,msg);
exit(1);
}
TCOD_parser_listener_t my_listener = {
my_parser_new_struct,
my_parser_flag,
my_parser_property,
my_parser_end_struct,
my_parser_error
};
@Py
class MyListener:
def new_struct(self, struct, name):
print 'new structure type', libtcod.struct_get_name(struct),
' named ', name
return True
def new_flag(self, name):
print 'new flag named ', name
return True
def new_property(self,name, typ, value):
type_names = ['NONE', 'BOOL', 'CHAR', 'INT', 'FLOAT', 'STRING',
'COLOR', 'DICE']
if typ == libtcod.TYPE_COLOR :
print 'new property named ', name,' type ',type_names[typ],
' value ', value.r, value.g, value.b
elif typ == libtcod.TYPE_DICE :
print 'new property named ', name,' type ',type_names[typ],
' value ', value.nb_rolls, value.nb_faces,
value.multiplier, value.addsub
else:
print 'new property named ', name,' type ',type_names[typ],
' value ', value
return True
def end_struct(self, struct, name):
print 'end structure type', libtcod.struct_get_name(struct),
' named ', name
return True
def error(self,msg):
print 'error : ', msg
return True
*/
// sax event listener
class TCODLIB_API ITCODParserListener {
public :
virtual ~ITCODParserListener(){}
/**
@PageName parser_run
@FuncTitle Handling 'newStruct' events
@FuncDesc This callback is called each time the parser find a new structure declaration in the file. Example :
<div class="code"><pre>item_type "blade" { // <= newStruct event here
...
}
</pre></div>
It must return true if everything is right, false if there is an error and the parser must exit.
@Cpp bool ITCODParserListener::parserNewStruct(TCODParser *parser,TCODParserStruct *str,const char *name)
@C bool new_struct(TCOD_parser_struct_t str,const char *name)
@Py new_struct(str,name)
@Param parser In the C++ version, the parser object, returned by TCODParser constructor. It's used for error handling.
@Param str The structure type. Can be used to retrieve the type's name with getName. In the example above, this would be "item_type".
@Param name The name of the structure or NULL if no name is present in the file. In the example above, this would be "blade".
*/
virtual bool parserNewStruct(TCODParser *parser,const TCODParserStruct *str,const char *name)=0;
/**
@PageName parser_run
@FuncTitle Handling 'newFlag' events
@FuncDesc This callback is called each time the parser find a new flag in the file. Example :
<div class="code"><pre>item_type "blade" {
abstract // <= newFlag event here
}
</pre></div>
It must return true if everything is right, false if there is an error and the parser must exit.
@Cpp bool ITCODParserListener::parserFlag(TCODParser *parser,const char *name)
@C bool new_flag(const char *name)
@Py new_flag(name)
@Param parser In the C++ version, the parser object, returned by TCODParser constructor. It's used for error handling.
@Param name The name of the flag. In the example, this would be "abstract".
*/
virtual bool parserFlag(TCODParser *parser,const char *name)=0;
/**
@PageName parser_run
@FuncTitle Handling 'newProperty' events
@FuncDesc This callback is called each time the parser find a new property in the file. Example :
<div class="code"><pre>item_type "blade" {
abstract
cost=300 // <= newProperty event here
}
</pre></div>
It must return true if everything is right, false if there is an error and the parser must exit.
@Cpp bool ITCODParserListener::parserProperty(TCODParser *parser,const char *name, TCOD_value_type_t type, TCOD_value_t value)
@C bool new_property(const char *name, TCOD_value_type_t type, TCOD_value_t value)
@Py new_property(name,type,value)
@Param parser In the C++ version, the parser object, returned by TCODParser constructor. It's used for error handling.
@Param name The name of the property. In the example, this would be "cost".
@Param type The type of the property as defined when you called addProperty or addValueList. In the example, this would be TCOD_TYPE_INT.
@Param value The value of the property, stored in a generic value structure. In the example, we would have value.i == 300.
In the case of a value-list property, the type would reflect the list id (between TCOD_TYPE_VALUELIST00 and TCOD_TYPE_VALUELIST15) and value.s would contain the actual string.
*/
virtual bool parserProperty(TCODParser *parser,const char *propname, TCOD_value_type_t type, TCOD_value_t value)=0;
/**
@PageName parser_run
@FuncTitle Handling 'endStruct' events
@FuncDesc This callback is called each time the parser find the end of a structure declaration in the file. Example :
<div class="code"><pre>item_type "blade" {
...
} // <= endStruct event here
</pre></div>
It must return true if everything is right, false if there is an error and the parser must exit.
@Cpp bool ITCODParserListener::parserEndStruct(TCODParser *parser,TCODParserStruct *str,const char *name)
@C bool end_struct(TCOD_parser_struct_t str,const char *name)
@Py end_struct(str,name)
@Param parser In the C++ version, the parser object, returned by TCODParser constructor. It's used for error handling.
@Param str The structure type. Can be used to retrieve the type's name with getName. In the example above, this would be "item_type".
@Param name The name of the structure or NULL if no name is present in the file. In the example above, this would be "blade".
*/
virtual bool parserEndStruct(TCODParser *parser,const TCODParserStruct *str, const char *name)=0;
/**
@PageName parser_run
@FuncTitle Handling errors
@FuncDesc There are two kind of errors :
* Errors that are detected by the parser itself (malformed file, bad value syntax for a property, missing mandatory property in a structure, ...).
* Errors that you detect in your callbacks.
When the parser finds an error in the file, it will call the error callback and stop :
@Cpp void ITCODParserListener::error(const char *msg)
@C void error(const char *msg)
@Py error(msg)
@Param msg The error message from the parser with the file name and the line number.
*/
/**
@PageName parser_run
@FuncDesc If you find an error in your callback, you have to call the parser error function. It will add the file name and line number to your error message, and then call your error callback :
The code in the example below will result in your error callback called with the following string :
"error in &lt;filename&gt; line &lt;line_number&gt; : Bad cost value %d. Cost must be between 0 and 1000"
@Cpp void TCODParser::error(const char *msg, ...)
@C void TCOD_parser_error(const char *msg, ...)
@Py parser_error(msg)
@Param msg printf-like format string for your error message.
@CppEx parser->error("Bad cost value %d. Cost must be between 0 and 1000", value.i);
@CEx TCOD_parser_error("Bad cost value %d. Cost must be between 0 and 1000", value.i);
@PyEx libtcod.parser_error("Bad cost value %d. Cost must be between 0 and 1000"%( value ))
*/
virtual void error(const char *msg) = 0;
};
/**
@PageName parser_types
@PageFather parser
@PageTitle Standard types
@FuncDesc The parser can parse natively several data types. It stores them in a generic union :
@C
typedef struct {
int nb_rolls;
int nb_faces;
float multiplier;
float addsub;
} TCOD_dice_t;
typedef union {
bool b;
char c;
int32_t i;
float f;
char *s;
TCOD_color_t col;
TCOD_dice_t dice;
TCOD_list_t list;
void *custom;
} TCOD_value_t;
*/
/**
@PageName parser_types
@FuncDesc Possible types are defined by the TCOD_value_type_t enumeration :
For Python, remove TCOD_ : libtcod.TYPE_BOOL
<table class="param">
<tbody><tr><th>TCOD_value_type_t</th><th>Value in file</th><th>TCOD_value_t</th></tr>
<tr><td>TCOD_TYPE_BOOL</td><td>true<br>false</td><td>value.b == true/false</td></tr>
<tr><td>TCOD_TYPE_CHAR</td><td>decimal notation : 0 .. 255<br>
hexadecimal notation : 0x00 .. 0xff <br>
char notation : 'a' ';' ...<br>
Special characters :<br>
'\n' : carriage return (ascii 13)<br>
'\t' : tabulation (ascii 9)<br>
'\r' : line feed (ascii 10)<br>
'\\' : antislash (ascii 92)<br>
'\"' : double-quote (ascii 34)<br>
'\'' : simple quote (ascii 39)<br>
'\xHH' : hexadecimal value, same as 0xHH, HH between 0 and FF<br>
'\NNN' : octal value, NNN between 0 and 377<br>
</td><td>value.c == The corresponding ascii code</td></tr>
<tr><td>TCOD_TYPE_INT</td><td>decimal notation : -2147483648 .. 2147483647<br>hexadecimal notation : 0x0 .. 0xFFFFFFFF</td><td>value.i == the integer value</td></tr>
<tr><td>TCOD_TYPE_FLOAT</td><td>Any format parsable by atof. Examples:<br>3.14159<br>1.25E-3</td><td>value.f == the float value</td></tr>
<tr><td>TCOD_TYPE_STRING</td><td>A double-quote delimited string :<br>"This is a string"<br>Support the same special characters as TCOD_TYPE_CHAR.</td><td>value.s == the corresponding string.<br>Warning ! If you want to store this string, you have to duplicate it (with strdup) as it will be overwritten by the parser</td></tr>
<tr><td>TCOD_TYPE_COLOR</td><td>decimal notation : "16,32,64"<br>hexadecimal notation : "#102040"</td><td>value.col == the color.</td></tr>
<tr><td>TCOD_TYPE_DICE</td><td>[multiplier (x|*)] nb_rolls (d|D) nb_faces [(+|-) addsub] :<br>"3d6"<br>"3D6+2"<br>"0.5x3d6-2"<br>"2*3d8"</td><td>value.dice == the dice components</td></tr>
<tr><td>TCOD_TYPE_VALUELISTxx</td><td>Same as TCOD_TYPE_STRING</td><td>value.s == the string value from the value list</td></tr>
<tr><td>TCOD_TYPE_LIST</td><td>[ &lt;value1&gt;,&lt;value2&gt;,... ]</td><td>value.list == the TCOD_list_t containing the elements</td></tr>
</tbody></table>
To define a list type, use the appropriate function (TCODParserStruct::addListProperty / TCOD_parser_add_list_property) and specify the type of the elements in the list. Lists of list are not supported.
*/
#endif

View file

@ -0,0 +1,93 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_PATH_H
#define _TCOD_PATH_H
#include "fov_types.h"
#include "list.h"
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef float (*TCOD_path_func_t)(int xFrom, int yFrom, int xTo, int yTo, void* user_data);
struct TCOD_Path;
typedef struct TCOD_Path* TCOD_path_t;
TCODLIB_API TCOD_path_t TCOD_path_new_using_map(TCOD_map_t map, float diagonalCost);
TCODLIB_API TCOD_path_t
TCOD_path_new_using_function(int map_width, int map_height, TCOD_path_func_t func, void* user_data, float diagonalCost);
TCODLIB_API bool TCOD_path_compute(TCOD_path_t path, int ox, int oy, int dx, int dy);
TCODLIB_API bool TCOD_path_walk(TCOD_path_t path, int* x, int* y, bool recalculate_when_needed);
TCODLIB_API bool TCOD_path_is_empty(TCOD_path_t path);
TCODLIB_API int TCOD_path_size(TCOD_path_t path);
TCODLIB_API void TCOD_path_reverse(TCOD_path_t path);
TCODLIB_API void TCOD_path_get(TCOD_path_t path, int index, int* x, int* y);
TCODLIB_API void TCOD_path_get_origin(TCOD_path_t path, int* x, int* y);
TCODLIB_API void TCOD_path_get_destination(TCOD_path_t path, int* x, int* y);
TCODLIB_API void TCOD_path_delete(TCOD_path_t path);
/* Dijkstra stuff - by Mingos*/
/**
* Dijkstra data structure
*
* All attributes are considered private.
*/
typedef struct TCOD_Dijkstra {
int diagonal_cost;
int width, height, nodes_max;
TCOD_map_t map; /* a TCODMap with walkability data */
TCOD_path_func_t func;
void* user_data;
unsigned int* distances; /* distances grid */
unsigned int* nodes; /* the processed nodes */
TCOD_list_t path;
} TCOD_Dijkstra;
typedef struct TCOD_Dijkstra* TCOD_dijkstra_t;
TCODLIB_API TCOD_dijkstra_t TCOD_dijkstra_new(TCOD_map_t map, float diagonalCost);
TCODLIB_API TCOD_dijkstra_t TCOD_dijkstra_new_using_function(
int map_width, int map_height, TCOD_path_func_t func, void* user_data, float diagonalCost);
TCODLIB_API void TCOD_dijkstra_compute(TCOD_dijkstra_t dijkstra, int root_x, int root_y);
TCODLIB_API float TCOD_dijkstra_get_distance(TCOD_dijkstra_t dijkstra, int x, int y);
TCODLIB_API bool TCOD_dijkstra_path_set(TCOD_dijkstra_t dijkstra, int x, int y);
TCODLIB_API bool TCOD_dijkstra_is_empty(TCOD_dijkstra_t path);
TCODLIB_API int TCOD_dijkstra_size(TCOD_dijkstra_t path);
TCODLIB_API void TCOD_dijkstra_reverse(TCOD_dijkstra_t path);
TCODLIB_API void TCOD_dijkstra_get(TCOD_dijkstra_t path, int index, int* x, int* y);
TCODLIB_API bool TCOD_dijkstra_path_walk(TCOD_dijkstra_t dijkstra, int* x, int* y);
TCODLIB_API void TCOD_dijkstra_delete(TCOD_dijkstra_t dijkstra);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,585 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
#ifndef _TCOD_PATH_HPP
#define _TCOD_PATH_HPP
#include <utility>
#include "fov.hpp"
#include "path.h"
class TCODLIB_API ITCODPathCallback {
public :
virtual ~ITCODPathCallback() {}
virtual float getWalkCost( int xFrom, int yFrom, int xTo, int yTo, void *userData ) const = 0;
};
/**
@PageName path
@PageTitle Path finding
@PageCategory Roguelike toolkits
@PageDesc This toolkit allows one to easily calculate the optimal path between two points in your dungeon by using either the <a href="http://en.wikipedia.org/wiki/A*">A* algorithm</a> or <a href="http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Dijkstra's algorithm</a>.
Please note that the paths generated with the two algorithms may differ slightly. Due to how they're implemented, A* will usually prefer diagonal moves over orthogonal, while Dijkstra will have the opposite preference. In other words, paths from point X to point Y will look like this:
<div class="code"><pre>
Dijkstra: A*:
.......... ..........
.X........ .X*.......
..*....... ...**.....
...*...... .....**...
....****Y. .......*Y.
.......... ..........
</pre></div>
*/
class TCODLIB_API TCODPath {
public :
/**
@PageName path_init
@PageFather path
@PageTitle Creating a path
@FuncTitle Allocating a pathfinder from a map
@FuncDesc First, you have to allocate a path using a map from <a href="fov.html">the Field of view module</a>.
@Cpp
TCODPath::TCODPath(const TCODMap *map, float diagonalCost=1.41f)
TCODDijkstra::TCODDijkstra(const TCODMap *map, float diagonalCost=1.41f)
@C
TCOD_path_t TCOD_path_new_using_map(TCOD_map_t map, float diagonalCost)
TCOD_dijkstra_t TCOD_dijkstra_new(TCOD_map_t map, float diagonalCost)
@Py
path_new_using_map(map, diagonalCost=1.41)
dijkstra_new(map, diagonalCost=1.41)
@C#
TCODPath(TCODMap map, float diagonalCost)
TCODPath(TCODMap map)
TCODDijkstra(TCODMap map, float diagonalCost)
TCODDijkstra(TCODMap map)
@Param map The map. The path finder will use the 'walkable' property of the cells to find a path.
@Param diagonalCost Cost of a diagonal movement compared to an horizontal or vertical movement. On a standard cartesian map, it should be sqrt(2) (1.41f).
It you want the same cost for all movements, use 1.0f.
If you don't want the path finder to use diagonal movements, use 0.0f.
@CppEx
// A* :
TCODMap *myMap = new TCODMap(50,50);
TCODPath *path = new TCODPath(myMap); // allocate the path
// Dijkstra:
TCODMap *myMap = new TCODMap(50,50);
TCODDijkstra *dijkstra = new TCODDijkstra(myMap); // allocate the path
@CEx
// A* :
TCOD_map_t my_map=TCOD_map_new(50,50,true);
TCOD_path_t path = TCOD_path_new_using_map(my_map,1.41f);
// Dijkstra :
TCOD_map_t my_map=TCOD_map_new(50,50,true);
TCOD_dijkstra_t dijkstra = TCOD_dijkstra_new(my_map,1.41f);
@PyEx
# A* :
my_map=libtcod.map_new(50,50,True)
path = libtcod.path_new_using_map(my_map)
# Dijkstra
my_map=libtcod.map_new(50,50,True)
dijkstra = libtcod.dijkstra_new(my_map)
*/
TCODPath(const TCODMap *map, float diagonalCost=1.41f);
/**
@PageName path_init
@FuncTitle Allocating a pathfinder using a callback
@FuncDesc Since the walkable status of a cell may depend on a lot of parameters (the creature type, the weather, the terrain type...), you can also create a path by providing a function rather than relying on a TCODMap.
@Cpp
// Callback :
class ITCODPathCallback {
public: virtual float getWalkCost( int xFrom, int yFrom, int xTo, int yTo, void *userData ) const = 0;
};
// A* constructor:
TCODPath::TCODPath(int width, int height, const ITCODPathCallback *callback, void *userData, float diagonalCost=1.41f)
// Dijkstra constructor
TCODDijkstra::TCODDijkstra(int width, int height, const ITCODPathCallback *callback, void *userData, float diagonalCost=1.41f)
@C
typedef float (*TCOD_path_func_t)( int xFrom, int yFrom, int xTo, int yTo, void *user_data )
TCOD_path_t TCOD_path_new_using_function(int width, int height, TCOD_path_func_t callback, void *user_data, float diagonalCost)
TCOD_dijkstra_t TCOD_dijkstra_new_using_function(int width, int height, TCOD_path_func_t callback, void *user_data, float diagonalCost)
@Py
def path_func(xFrom,yFrom,xTo,yTo,userData) : ...
path_new_using_function(width, height, path_func, user_data=0, diagonalCost=1.41)
dijkstra_new_using_function(width, height, path_func, user_data=0, diagonalCost=1.41)
@C#
TCODPath(int width, int height, ITCODPathCallback listener, float diagonalCost)
TCODPath(int width, int height, ITCODPathCallback listener)
TCODDijkstra(int width, int height, ITCODPathCallback listener, float diagonalCost)
TCODDijkstra(int width, int height, ITCODPathCallback listener)
@Param width,height The size of the map (in map cells).
@Param callback A custom function that must return the walk cost from coordinates xFrom,yFrom to coordinates xTo,yTo.
The cost must be > 0.0f if the cell xTo,yTo is walkable.
It must be equal to 0.0f if it's not.
You must not take additional cost due to diagonal movements into account as it's already done by the pathfinder.
@Param userData Custom data that will be passed to the function.
@Param diagonalCost Cost of a diagonal movement compared to an horizontal or vertical movement. On a standard cartesian map, it should be sqrt(2) (1.41f).
It you want the same cost for all movements, use 1.0f.
If you don't want the path finder to use diagonal movements, use 0.0f.
@CppEx
class MyCallback : public ITCODPathCallback {
public :
float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const { ... }
};
TCODPath *path = new TCODPath(50,50,new MyCallback(),NULL); // allocate the path
TCODDijkstra *dijkstra = new TCODDijkstra(50,50,new MyCallback(),NULL); // allocate Dijkstra
@CEx
float my_func(int xFrom, int yFrom, int xTo, int yTo, void *user_data) { ... }
TCOD_path_t path = TCOD_path_new_using_function(50,50,my_func,NULL,1.41f);
TCOD_dijkstra_t dijkstra = TCOD_dijkstra_new_using_function(50,50,my_func,NULL,1.41f);
@PyEx
def my_func(xFrom, yFrom, xTo, yTo, user_data) :
# return a float cost for this movement
return 1.0
path = libtcod.path_new_using_function(50,50,my_func)
dijkstra = libtcod.dijkstra_new_using_function(50,50,my_func)
*/
TCODPath(int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost=1.41f);
TCODPath(const TCODPath&) = delete;
TCODPath& operator=(const TCODPath&) = delete;
TCODPath(TCODPath&& rhs) noexcept {
std::swap(data, rhs.data);
cppData = std::move(rhs.cppData);
}
TCODPath& operator=(TCODPath&& rhs) noexcept {
std::swap(data, rhs.data);
cppData = std::move(rhs.cppData);
return *this;
}
/**
@PageName path_init
@FuncTitle Destroying a path
@FuncDesc To release the resources used by a path, destroy it with :
@Cpp
TCODPath::~TCODPath()
TCODDijkstra::~TCODDijkstra()
@C
void TCOD_path_delete(TCOD_path_t path)
void TCOD_dijkstra_delete(TCOD_dijkstra_t dijkstra)
@Py
path_delete(path)
dijkstra_delete(dijkstra)
@C#
void TCODPath::Dispose()
void TCODDijkstra::Dispose()
@Param path In the C version, the path handler returned by one of the TCOD_path_new_* function.
@Param dijkstra In the C version, the path handler returned by one of the TCOD_dijkstra_new* function.
@CppEx
TCODPath *path = new TCODPath(myMap); // allocate the path
// use the path...
delete path; // destroy the path
TCODDijkstra *dijkstra = new TCODDijkstra(myMap); // allocate the path
// use the path...
delete dijkstra; // destroy the path
@CEx
TCOD_path_t path = TCOD_path_new_using_map(my_map);
// use the path ...
TCOD_path_delete(path);
TCOD_dijkstra_t dijkstra = TCOD_dijkstra_new(my_map);
// use the path ...
TCOD_dijkstra_delete(dijkstra);
@PyEx
path = libtcod.path_new_using_map(my_map)
# use the path ...
libtcod.path_delete(path)
dijkstra = libtcod.dijkstra_new(my_map)
# use the path ...
libtcod.dijkstra_delete(dijkstra)
*/
virtual ~TCODPath();
/**
@PageName path_compute
@PageFather path
@PageTitle Computing the path
@FuncTitle Computing an A* path
@FuncDesc Once you created a TCODPath object, you can compute the path between two points:
@Cpp bool TCODPath::compute(int ox, int oy, int dx, int dy)
@C bool TCOD_path_compute(TCOD_path_t path, int ox,int oy, int dx, int dy)
@Py path_compute(path, ox, oy, dx, dy)
@C# void TCODPath::compute(int ox, int oy, int dx, int dy)
@Param path In the C version, the path handler returned by a creation function.
@Param ox,oy Coordinates of the origin of the path.
@Param dx,dy Coordinates of the destination of the path.
Both points should be inside the map, and at a walkable position. The function returns false if there is no possible path.
@CppEx
TCODMap *myMap = new TCODMap(50,50);
TCODPath *path = new TCODPath(myMap); // allocate the path
path->compute(5,5,25,25); // calculate path from 5,5 to 25,25
@CEx
TCOD_map_t my_map=TCOD_map_new(50,50);
TCOD_path_t path = TCOD_path_new_using_map(my_map);
TCOD_path_compute(path,5,5,25,25);
@PyEx
my_map=libtcod.map_new(50,50)
path = libtcod.path_new_using_map(my_map)
libtcod.path_compute(path,5,5,25,25)
*/
bool compute(int ox, int oy, int dx, int dy);
/**
@PageName path_compute
@FuncTitle Reversing a path
@FuncDesc Once you computed a path, you can exchange origin and destination :
@Cpp
void TCODPath::reverse()
void TCODDijkstra::reverse()
@C
void TCOD_path_reverse(TCOD_path_t path)
void TCOD_dijkstra_reverse(TCOD_dijkstra_t dijkstra)
@Py
path_reverse(path)
dijkstra_reverse(dijkstra)
@C#
void TCODPath::reverse()
void TCODDijkstra::reverse()
@Param path In the C version, the path handler returned by a creation function.
@CppEx
TCODMap *myMap = new TCODMap(50,50);
TCODPath *path = new TCODPath(myMap); // allocate the path
path->compute(5,5,25,25); // calculate path from 5,5 to 25,25
path->reverse(); // now the path goes from 25,25 to 5,5
@CEx
TCOD_map_t my_map=TCOD_map_new(50,50);
TCOD_path_t path = TCOD_path_new_using_map(my_map);
TCOD_path_compute(path,5,5,25,25); // calculate path from 5,5 to 25,25
TCOD_path_reverse(path); // now the path goes from 25,25 to 5,5
@PyEx
my_map=libtcod.map_new(50,50)
path = libtcod.path_new_using_map(my_map)
libtcod.path_compute(path,5,5,25,25) # calculate path from 5,5 to 25,25
libtcod.path_reverse(path) # now the path goes from 25,25 to 5,5
*/
void reverse();
/**
@PageName path_read
@PageTitle Reading path information
@PageFather path
@PageDesc Once the path has been computed, you can get information about it using of one those functions.
@FuncTitle Getting the path origin and destination
@FuncDesc
You can read the current origin and destination cells with getOrigin/getDestination.
Note that when you walk the path, the origin changes at each step.
@Cpp
void TCODPath::getOrigin(int *x,int *y) const
void TCODPath::getDestination(int *x,int *y) const
@C
void TCOD_path_get_origin(TCOD_path_t path, int *x, int *y)
void TCOD_path_get_destination(TCOD_path_t path, int *x, int *y)
@Py
path_get_origin(path) # returns x,y
path_get_destination(path) # returns x,y
@C#
void TCODPath::getOrigin(out int x, out int y)
void TCODPath::getDestination(out int x, out int y)
@Param path In the C version, the path handler returned by a creation function.
@Param x,y The function returns the cell coordinates in these variables
*/
void getOrigin(int *x,int *y) const;
void getDestination(int *x,int *y) const;
/**
@PageName path_read
@FuncTitle Getting the path length
@FuncDesc You can get the number of steps needed to reach destination :
@Cpp
int TCODPath::size() const
int TCODDijkstra::size() const
@C
int TCOD_path_size(TCOD_path_t path)
int TCOD_dijkstra_size(TCOD_dijkstra_t dijkstra)
@Py
path_size(path)
dijkstra_size(dijkstra)
@C#
int TCODPath::size()
int TCODDijkstra::size()
@Param path, dijkstra In the C version, the path handler returned by a creation function.
*/
int size() const;
/**
@PageName path_read
@FuncTitle Read the path cells' coordinates
@FuncDesc You can get the coordinates of each point along the path :
@Cpp
void TCODPath::get(int index, int *x, int *y) const
void TCODDijkstra::get(int index, int *x, int *y) const
@C
void TCOD_path_get(TCOD_path_t path, int index, int *x, int *y)
void TCOD_dijkstra_get(TCOD_dijkstra_t dijkstra, int index, int *x, int *y)
@Py
path_get(path, index) # returns x,y
dijkstra_get(dijkstra, index) # returns x,y
@C#
int TCODPath::size()
int TCODDijkstra::size()
@Param path, dijkstra In the C version, the path handler returned by a creation function.
@Param index Step number.
0 <= index < path size
@Param x,y Address of the variables receiving the coordinates of the point.
@CppEx
for (int i=0; i < path->size(); i++ ) {
int x,y;
path->get(i,&x,&y);
printf ("Astar coord : %d %d\n", x,y );
}
for (int i=0; i < dijkstra->size(); i++ ) {
int x,y;
dijkstra->get(i,&x,&y);
printf ("Dijkstra coord : %d %d\n", x,y );
}
@CEx
int i;
for (i=0; i < TCOD_path_size(path); i++ ) {
int x,y;
TCOD_path_get(path,i,&x,&y);
printf ("Astar coord : %d %d\n", x,y );
}
for (i=0; i < TCOD_dijkstra_size(dijkstra); i++ ) {
int x,y;
TCOD_dijkstra_get(dijkstra,i,&x,&y);
printf ("Dijkstra coord : %d %d\n", x,y );
}
@PyEx
for i in range (libtcod.path_size(path)) :
x,y=libtcod.path_get(path,i)
print 'Astar coord : ',x,y
for i in range (libtcod.dijkstra_size(dijkstra)) :
x,y=libtcod.dijkstra_get(dijkstra,i)
print 'Dijkstra coord : ',x,y
*/
void get(int index, int *x, int *y) const;
/**
@PageName path_read
@FuncTitle Checking if the path is empty
@FuncDesc If you want a creature to follow the path, a more convenient way is to walk the path :
You know when you reached destination when the path is empty :
@Cpp
bool TCODPath::isEmpty() const
bool TCODDijkstra::isEmpty() const
@C
bool TCOD_path_is_empty(TCOD_path_t path)
bool TCOD_dijkstra_is_empty(TCOD_dijkstra_t dijkstra)
@Py
path_is_empty(path)
dijkstra_is_empty(dijkstra)
@C#
bool TCODPath::isEmpty()
bool TCODDijkstra::isEmpty()
@Param path, dijkstra In the C version, the path handler returned by a creation function.
*/
bool isEmpty() const;
/**
@PageName path_read
@FuncTitle Walking the path
@FuncDesc You can walk the path and go to the next step with :
Note that walking the path consume one step (and decrease the path size by one). The function returns false if recalculateWhenNeeded is false and the next cell on the path is no longer walkable, or if recalculateWhenNeeded is true, the next cell on the path is no longer walkable and no other path has been found. Also note that recalculateWhenNeeded only applies to A*.
@Cpp
bool TCODPath::walk(int *x, int *y, bool recalculateWhenNeeded)
bool TCODDijkstra::walk(int *x, int *y)
@C
bool TCOD_path_walk(TCOD_path_t path, int *x, int *y, bool recalculate_when_needed)
bool TCOD_dijkstra_walk(TCOD_dijkstra_t dijkstra, int *x, int *y)
@Py
path_walk(TCOD_path_t path, recalculate_when_needed) # returns x,y or None,None if no path
dijkstra_walk(TCOD_dijkstra_t dijkstra)
@C#
bool TCODPath::walk(ref int x, ref int y, bool recalculateWhenNeeded)
bool TCODDijkstra::walk(ref int x, ref int y)
@Param path, dijkstra In the C version, the path handler returned by a creation function.
@Param x,y Address of the variables receiving the coordinates of the next point.
@Param recalculateWhenNeeded If the next point is no longer walkable (another creature may be in the way), recalculate a new path and walk it.
@CppEx
while (! path->isEmpty()) {
int x,y;
if (path->walk(&x,&y,true)) {
printf ("Astar coord: %d %d\n",x,y );
} else {
printf ("I'm stuck!\n" );
break;
}
}
while (! dijkstra->isEmpty()) {
int x,y;
if (dijkstra->walk(&x,&y)) {
printf ("Dijkstra coord: %d %d\n",x,y );
} else {
printf ("I'm stuck!\n" );
break;
}
}
@CEx
while (! TCOD_path_is_empty(path)) {
int x,y;
if (TCOD_path_walk(path,&x,&y,true)) {
printf ("Astar coord: %d %d\n",x,y );
} else {
printf ("I'm stuck!\n" );
break;
}
}
while (! TCOD_dijkstra_is_empty(dijkstra)) {
int x,y;
if (TCOD_dijkstra_walk(dijkstra,&x,&y)) {
printf ("Dijkstra coord: %d %d\n",x,y );
} else {
printf ("I'm stuck!\n" );
break;
}
}
@PyEx
while not libtcod.path_is_empty(path)) :
x,y=libtcod.path_walk(path,True)
if not x is None :
print 'Astar coord: ',x,y
else :
print "I'm stuck!"
break
while not libtcod.dijkstra_is_empty(dijkstra)) :
x,y=libtcod.dijkstra_walk(dijkstra,True)
if not x is None :
print 'Dijkstra coord: ',x,y
else :
print "I'm stuck!"
break
*/
bool walk(int *x, int *y, bool recalculateWhenNeeded);
protected :
friend float TCOD_path_func(int xFrom, int yFrom, int xTo,int yTo, void *data);
TCOD_path_t data;
struct WrapperData {
void *userData;
const ITCODPathCallback *listener;
} cppData;
};
//Dijkstra kit
class TCODLIB_API TCODDijkstra {
public:
TCODDijkstra (TCODMap *map, float diagonalCost=1.41f);
TCODDijkstra (int width, int height, const ITCODPathCallback *listener, void *userData, float diagonalCost=1.41f);
TCODDijkstra(const TCODDijkstra&) = delete;
TCODDijkstra& operator=(const TCODDijkstra&) = delete;
TCODDijkstra(TCODDijkstra&& rhs) noexcept {
std::swap(data, rhs.data);
cppData = std::move(rhs.cppData);
}
TCODDijkstra& operator=(TCODDijkstra&& rhs)noexcept {
std::swap(data, rhs.data);
cppData = std::move(rhs.cppData);
return *this;
}
~TCODDijkstra (void);
/**
@PageName path_compute
@FuncTitle Computing a Dijkstra grid
@FuncDesc In case of Dijkstra, this works in a slightly different way. In order to be able to compute a path, Dijkstra must first analyze the distances from the selected root (origin) node to all other nodes:
@Cpp void TCODDijkstra::compute(int rootX, int rootY)
@C void TCOD_dijkstra_compute(TCOD_dijkstra_t dijkstra, int root_x, int root_y)
@Py dijkstra_compute(dijkstra, root_x, root_y)
@C# void TCODDijkstra::compute(int rootX, int rootY)
@Param dijkstra In the C version, the path handler returned by a creation function.
@Param root_x,root_y Coordinates of the root node (origin) of the path.
The coordinates should be inside the map, at a walkable position. Otherwise, the function's behaviour will be undefined.
*/
void compute (int rootX, int rootY);
/**
@PageName path_compute
@FuncTitle Computing a path from a Dijkstra grid
@FuncDesc After the map is analyzed and all the distances from the root node are known, an unlimited number of paths can be set, all originating at the root node, using:
The path setting function will return true if there's a path from the root node to the destination node. Otherwise, it will return false.
@Cpp bool TCODDijkstra::setPath(int toX, int toY)
@C bool TCOD_dijkstra_path_set(TCOD_dijkstra_t dijkstra, int to_x, int to_y)
@Py dijkstra_path_set(dijkstra, to_x, to_y)
@C# bool TCODDijkstra::setPath(int toX, int toY)
@Param dijkstra In the C version, the path handler returned by a creation function.
@Param to_x,to_y Coordinates of the destination node of the path.
@CppEx
TCODMap *myMap = new TCODMap(50,50);
TCODDijkstra *dijkstra = new TCODDijkstra(myMap); // allocate the path
dijkstra->compute(25,25); // calculate distance from 25,25 to all other nodes
dijkstra->setPath(5,5); // calculate a path to node 5,5
dijkstra->setPath(45,45); //calculate another path from the same origin
@CEx
TCOD_map_t my_map=TCOD_map_new(50,50);
TCOD_dijkstra_t dijkstra = TCOD_dijkstra_new(my_map);
TCOD_dijkstra_compute(dijkstra,25,25);
TCOD_dijkstra_path_set(dijkstra,5,5);
TCOD_dijkstra_path_set(dijkstra,45,45);
@PyEx
my_map=libtcod.map_new(50,50)
dijkstra = libtcod.dijkstra_new(my_map)
libtcod.dijkstra_compute(dijkstra,25,25)
libtcod.dijkstra_path_set(dijkstra,5,5)
libtcod.dijkstra_path_set(dijkstra,45,45)
*/
bool setPath (int toX, int toY);
/**
@PageName path_read
@FuncTitle Getting the distance from a cell to the root node
@FuncDesc You can get the distance of any set of coordinates from the root node:
Note that if the coordinates x,y are outside of the map or are a non-walkable position, the function will return -1.0f. This functionality is only available for Dijkstra's algorithm.
@Cpp float TCODDijkstra::getDistance(int x, int y)
@C float TCOD_dijkstra_get_distance(TCOD_dijkstra_t dijkstra, int x, int y)
@Py dijkstra_get_distance(dijkstra, x, y)
@C# float TCODDijkstra::getDistance(int x, int y)
@Param dijkstra In the C version, the path handler returned by a creation function.
@Param x,y The coordinates whose distance from the root node are to be checked
*/
float getDistance (int x, int y);
bool walk (int *x, int *y);
bool isEmpty() const;
void reverse();
int size() const;
void get(int index, int *x, int *y) const;
private:
TCOD_dijkstra_t data;
struct WrapperData {
void *userData;
const ITCODPathCallback *listener;
} cppData;
};
#endif

View file

@ -0,0 +1,84 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_PATHFINDER_H
#define TCOD_PATHFINDER_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "heapq.h"
#include "portability.h"
#define TCOD_PATHFINDER_MAX_DIMENSIONS 4
struct TCOD_ArrayData {
int8_t ndim;
int int_type;
size_t shape[TCOD_PATHFINDER_MAX_DIMENSIONS + 1];
size_t strides[TCOD_PATHFINDER_MAX_DIMENSIONS + 1];
unsigned char* data;
};
struct TCOD_BasicGraph2D {
struct TCOD_ArrayData cost;
int cardinal;
int diagonal;
};
struct TCOD_Pathfinder {
int8_t ndim;
size_t shape[TCOD_PATHFINDER_MAX_DIMENSIONS];
bool owns_distance;
bool owns_graph;
bool owns_traversal;
struct TCOD_ArrayData distance;
struct TCOD_BasicGraph2D graph;
struct TCOD_ArrayData traversal;
struct TCOD_Heap heap;
};
TCODLIB_CAPI struct TCOD_Pathfinder* TCOD_pf_new(int ndim, const size_t* shape);
TCODLIB_CAPI void TCOD_pf_delete(struct TCOD_Pathfinder* path);
TCODLIB_CAPI void TCOD_pf_set_distance_pointer(
struct TCOD_Pathfinder* path, void* data, int int_type, const size_t* strides);
TCODLIB_CAPI void TCOD_pf_set_graph2d_pointer(
struct TCOD_Pathfinder* path, void* data, int int_type, const size_t* strides, int cardinal, int diagonal);
TCODLIB_CAPI void TCOD_pf_set_traversal_pointer(
struct TCOD_Pathfinder* path, void* data, int int_type, const size_t* strides);
TCODLIB_CAPI int TCOD_pf_recompile(struct TCOD_Pathfinder* path);
TCODLIB_CAPI int TCOD_pf_compute(struct TCOD_Pathfinder* path);
TCODLIB_CAPI int TCOD_pf_compute_step(struct TCOD_Pathfinder* path);
#endif // TCOD_PATHFINDER_H

View file

@ -0,0 +1,97 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef TCOD_PATHFINDER_FRONTIER_H
#define TCOD_PATHFINDER_FRONTIER_H
#include <stdint.h>
#include "config.h"
#include "error.h"
#include "heapq.h"
#define TCOD_PATHFINDER_MAX_DIMENSIONS 4
struct TCOD_Frontier {
int8_t ndim;
int active_dist;
int active_index[TCOD_PATHFINDER_MAX_DIMENSIONS];
struct TCOD_Heap heap;
};
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
Create a new pathfinder frontier.
`ndim` is the number of dimensions. Must be in the range `1 <= n <= 4`.
*/
TCOD_PUBLIC TCOD_NODISCARD struct TCOD_Frontier* TCOD_frontier_new(int ndim);
/**
Delete a pathfinder frontier.
*/
TCOD_PUBLIC void TCOD_frontier_delete(struct TCOD_Frontier* frontier);
/**
Pop the next node from this frontier.
The popped node variables will placed in the `active_dist` and
`active_index` attributes.
*/
TCOD_PUBLIC TCOD_Error TCOD_frontier_pop(struct TCOD_Frontier* frontier);
/**
Add a node to this frontier.
`index[frontier->ndim]` is the position of the node to add to the frontier.
`dist` is the total distance of the node. This should be a low number
like 0, but can also be a negative number such as `INT_MIN`.
When adding a node as an edge then `dist` is `frontier->active_dist` plus
the cost of the edge.
`heuristic` is the true priority of the node, used to affect node order.
For Dijkstra-like algorithms this should be the same as `dist`.
For A* this should be `dist` plus the maximum possible distance to the
goal.
*/
TCOD_PUBLIC TCOD_Error
TCOD_frontier_push(struct TCOD_Frontier* __restrict frontier, const int* __restrict index, int dist, int heuristic);
/**
Return the current number of nodes in this frontier.
*/
TCOD_PUBLIC TCOD_NODISCARD int TCOD_frontier_size(const struct TCOD_Frontier* frontier);
/**
Remove all nodes from this frontier.
*/
TCOD_PUBLIC TCOD_Error TCOD_frontier_clear(struct TCOD_Frontier* frontier);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // TCOD_PATHFINDER_FRONTIER_H

View file

@ -0,0 +1,139 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_PORTABILITY_H
#define LIBTCOD_PORTABILITY_H
#include "config.h"
/* uncomment to disable unicode support */
/*#define NO_UNICODE */
/* uncomment to disable opengl support */
/*#define NO_OPENGL */
/* os identification
TCOD_WINDOWS : OS is windows
TCOD_LINUX : OS is Linux
TCOD_MACOSX : OS is Mac OS X
TCOD_HAIKU : OS is Haiku */
/* compiler identification
TCOD_VISUAL_STUDIO : compiler is Microsoft Visual Studio
TCOD_MINGW32 : compiler is Mingw32
TCOD_GCC : compiler is gcc/g++ */
/* word size
TCOD_64BITS : 64 bits OS
TCOD_WIN64 : 64 bits Windows
TCOD_WIN32 : 32 bits Windows
TCOD_LINUX64 : 64 bits Linux
TCOD_LINUX32 : 32 bits Linux
TCOD_FREEBSD64 : 64 bits FreeBSD
TCOD_FREEBSD32 : 32 bits FreeBSD */
#if defined(_MSC_VER)
#define TCOD_VISUAL_STUDIO
#define TCOD_WINDOWS
#ifdef _WIN64
#define TCOD_WIN64
#define TCOD_64BITS
#else
#define TCOD_WIN32
#endif
#elif defined(__MINGW32__)
#define TCOD_WINDOWS
#define TCOD_MINGW32
#ifdef _WIN64
#define TCOD_WIN64
#define TCOD_64BITS
#else
#define TCOD_WIN32
#endif
#elif defined(__HAIKU__)
#define TCOD_HAIKU
#define TCOD_GCC
#if __WORDSIZE == 64
#define TCOD_64BITS
#endif
#elif defined(__linux)
#define TCOD_LINUX
#define TCOD_GCC
#if __WORDSIZE == 64
#define TCOD_LINUX64
#define TCOD_64BITS
#else
#define TCOD_LINUX32
#endif
#elif defined(__FreeBSD__)
#define TCOD_FREEBSD
#define TCOD_GCC
#if __WORDSIZE == 64
#define TCOD_FREEBSD64
#define TCOD_64BITS
#else
#define TCOD_FREEBSD32
#endif
#elif defined(__APPLE__) && defined(__MACH__)
#define TCOD_MACOSX
#define TCOD_GCC
#if __WORDSIZE == 64
#define TCOD_64BITS
#endif
#endif
/* unicode rendering functions support */
#ifndef NO_UNICODE
#include <wchar.h>
#endif
/* int types */
#include <stdint.h>
/* bool type */
#include <stdbool.h>
/**
Allocate and return a duplicate of string `s`. The returned memory must be freed manually.
*/
TCODLIB_CAPI char* TCOD_strdup(const char* s);
/***************************************************************************
@brief Compare two ASCII strings ignoring case. Returns 0 if the strings are equal.
*/
TCODLIB_CAPI int TCOD_strcasecmp(const char* s1, const char* s2);
/***************************************************************************
@brief Compare two ASCII strings ignoring case. Returns 0 if the strings are equal.
*/
TCODLIB_CAPI int TCOD_strncasecmp(const char* s1, const char* s2, size_t n);
/* Define vswprintf across platforms. */
#ifdef _WIN32
#define vswprintf _vsnwprintf /* Windows */
#endif /* _WIN32 */
#endif /* LIBTCOD_PORTABILITY_H */

View file

@ -0,0 +1,61 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_RANDOM_H_
#define LIBTCOD_RANDOM_H_
#include <stdint.h>
#include "config.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
Return the next random uint64_t from a SplitMix64 generator.
`state[1]` is a non-NULL pointer to the internal state of the generator.
There is no initializer function because the first value of `state[1]` is
itself the seed which can start at any value.
`state[1]` will be updated by this call.
This function is provisional and may change.
*/
static inline uint64_t TCOD_rng_splitmix64_next(uint64_t* state) {
// Based on http://xoshiro.di.unimi.it/splitmix64.c
uint64_t z = (*state += 0x9e3779b97f4a7c15);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
z = (z ^ (z >> 27)) * 0x94d049bb133111eb;
return z ^ (z >> 31);
}
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // LIBTCOD_RANDOM_H_

View file

@ -0,0 +1,202 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_RENDERER_SDL2_H_
#define LIBTCOD_RENDERER_SDL2_H_
#include <stdbool.h>
#include "config.h"
#include "console.h"
#include "context.h"
#include "error.h"
#include "tileset.h"
struct SDL_Window;
struct SDL_Renderer;
struct SDL_Texture;
/**
An SDL2 tileset atlas. This prepares a tileset for use with SDL2.
\rst
.. versionadded:: 1.16
\endrst
*/
typedef struct TCOD_TilesetAtlasSDL2 {
/** The renderer used to create this atlas. */
struct SDL_Renderer* renderer;
/** The atlas texture. */
struct SDL_Texture* texture;
/** The tileset used to create this atlas. Internal use only. */
struct TCOD_Tileset* tileset;
/** Internal use only. */
struct TCOD_TilesetObserver* observer;
/** Internal use only. */
int texture_columns;
} TCOD_TilesetAtlasSDL2;
/***************************************************************************
@brief Info needed to convert between mouse pixel and tile coordinates.
Internal use only.
@code{.cpp}
double pixel_x, pixel_y, tile_x, tile_y;
TCOD_RendererSDL2CursorTransform transform;
// Convert pixel coordinates to tile coordinates.
tile_x = (pixel_x - transform.offset_x) * transform.scale_x;
tile_y = (pixel_y - transform.offset_y) * transform.scale_y;
// Convert tile coordinates to pixel coordinates.
pixel_x = tile_x / transform.scale_x + transform.offset_x;
pixel_y = tile_y / transform.scale_y + transform.offset_y;
@endcode
*/
typedef struct TCOD_RendererSDL2CursorTransform {
double offset_x;
double offset_y;
double scale_x;
double scale_y;
} TCOD_RendererSDL2CursorTransform;
/**
The renderer data for an SDL2 rendering context.
Internal use only.
*/
struct TCOD_RendererSDL2 {
struct SDL_Window* window; // Owning power to an SDL2 window.
struct SDL_Renderer* renderer; // Owning pointer to an SDL2 renderer.
struct TCOD_TilesetAtlasSDL2* __restrict atlas;
struct TCOD_Console* __restrict cache_console; // Tracks the data from the last console presented.
struct SDL_Texture* __restrict cache_texture; // Cached console rendering output.
uint32_t sdl_subsystems; // Which subsystems where initialzed by this context.
// Mouse cursor transform values of the last viewport used.
TCOD_RendererSDL2CursorTransform cursor_transform;
};
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
Return a libtcod rendering context using an SDL2 renderer.
*/
TCOD_PUBLIC TCOD_NODISCARD struct TCOD_Context* TCOD_renderer_init_sdl2(
int x,
int y,
int width,
int height,
const char* title,
int window_flags,
int renderer_flags,
struct TCOD_Tileset* tileset);
/**
Return a new SDL2 atlas created from a tileset for an SDL2 renderer.
You may delete the tileset if you no longer have use for it.
Will return NULL on an error, you can check the error with
`TCOD_get_error`.
*/
TCOD_PUBLIC TCOD_NODISCARD struct TCOD_TilesetAtlasSDL2* TCOD_sdl2_atlas_new(
struct SDL_Renderer* renderer, struct TCOD_Tileset* tileset);
/**
Delete an SDL2 tileset atlas.
*/
TCOD_PUBLIC void TCOD_sdl2_atlas_delete(struct TCOD_TilesetAtlasSDL2* atlas);
/**
Setup a cache and target texture for rendering.
`atlas` is an SDL2 atlas created with `TCOD_sdl2_atlas_new`.
The renderer used to make this `atlas` must support
`SDL_RENDERER_TARGETTEXTURE`.
`console` is a non-NULL pointer to the libtcod console you want to render.
`cache` can be NULL, or be pointer to a console pointer.
If `*cache` is NULL then a console will be created.
If `*cache` isn't NULL then the console pointed to might be deleted or
recreated if it does not match the size of `console`.
`target` must be a pointer to where you want the output texture to be placed.
The texture at `*target` may be deleted or recreated. When this function
is successful then the texture at `*target` will be non-NULL and will be
exactly fitted to the size of `console` and the tile size of `atlas`.
If SDL2 ever provides a `SDL_RENDER_TARGETS_RESET` event then the console
at `*cache` must be deleted and set to NULL, or else the next render will
only partially update the texture at `*target`.
Returns a negative value on an error, check `TCOD_get_error`.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_sdl2_render_texture_setup(
const struct TCOD_TilesetAtlasSDL2* __restrict atlas,
const struct TCOD_Console* __restrict console,
struct TCOD_Console* __restrict* cache,
struct SDL_Texture* __restrict* target);
/**
Render a console onto a managed target texture.
This function assumes that `cache` and `target` are valid.
You can use `TCOD_sdl2_render_texture_setup` to automatically prepare these
objects for use with this function.
`atlas` is an SDL2 atlas created with `TCOD_sdl2_atlas_new`.
The renderer used to make this `atlas` must support
`SDL_RENDERER_TARGETTEXTURE`, unless `target` is NULL.
`console` is a non-NULL pointer to the libtcod console you want to render.
`cache` can be NULL, or point to a console the same size as `console`.
`target` can be NULL, or be pointer an SDL2 texture used as the output.
If `target` is not NULL then it should be the size of the console times the
size of the individual tiles to fit the entire output.
If `target` is NULL then the current render target is used instead, the
drawn area will not be scaled to fit the render target.
If SDL2 ever provides a `SDL_RENDER_TARGETS_RESET` event then the console
at `cache` must be cleared, or else the next render will only partially
update the texture of `target`.
Returns a negative value on an error, check `TCOD_get_error`.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_sdl2_render_texture(
const struct TCOD_TilesetAtlasSDL2* __restrict atlas,
const struct TCOD_Console* __restrict console,
struct TCOD_Console* __restrict cache,
struct SDL_Texture* __restrict target);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // LIBTCOD_RENDERER_SDL2_H_

View file

@ -0,0 +1,50 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_RENDERER_XTERM_H_
#define LIBTCOD_RENDERER_XTERM_H_
#include "config.h"
#include "context.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
TCOD_PUBLIC TCOD_NODISCARD TCOD_Context* TCOD_renderer_init_xterm(
int window_x,
int window_y,
int pixel_width,
int pixel_height,
int columns,
int rows,
const char* window_title);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // LIBTCOD_RENDERER_XTERM_H_

View file

@ -0,0 +1,86 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_SDL2_EVENT_H_
#define LIBTCOD_SDL2_EVENT_H_
#include "../console_types.h"
#include "../mouse.h"
#include "../sys.h"
union SDL_Event;
#ifdef __cplusplus
namespace tcod {
namespace sdl2 {
/**
* Parse an SDL_Event into a key event and return the relevant TCOD_event_t.
*
* Returns TCOD_EVENT_NONE if the event wasn't keyboard related.
* \rst
* .. versionadded:: 1.11
* \endrst
*/
TCODLIB_API
TCOD_event_t process_event(const union SDL_Event& in, TCOD_key_t& out) noexcept;
/**
* Parse an SDL_Event into a mouse event and return the relevant TCOD_event_t.
*
* Returns TCOD_EVENT_NONE if the event wasn't mouse related.
* \rst
* .. versionadded:: 1.11
* \endrst
*/
TCODLIB_API
TCOD_event_t process_event(const union SDL_Event& in, TCOD_mouse_t& out) noexcept;
} // namespace sdl2
} // namespace tcod
#endif // __cplusplus
/**
* Parse an SDL_Event into a key event and return the relevant TCOD_event_t.
*
* Returns TCOD_EVENT_NONE if the event wasn't keyboard related.
* \rst
* .. versionadded:: 1.11
* \endrst
*/
TCODLIB_CAPI
TCOD_event_t TCOD_sys_process_key_event(const union SDL_Event* in, TCOD_key_t* out);
/**
* Parse an SDL_Event into a mouse event and return the relevant TCOD_event_t.
*
* Returns TCOD_EVENT_NONE if the event wasn't mouse related.
* \rst
* .. versionadded:: 1.11
* \endrst
*/
TCODLIB_CAPI
TCOD_event_t TCOD_sys_process_mouse_event(const union SDL_Event* in, TCOD_mouse_t* out);
#endif // LIBTCOD_SDL2_EVENT_H_

View file

@ -0,0 +1,256 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_SYS_H
#define _TCOD_SYS_H
#include "image.h"
#include "list.h"
#include "mouse_types.h"
#include "portability.h"
typedef enum {
TCOD_EVENT_NONE = 0,
TCOD_EVENT_KEY_PRESS = 1,
TCOD_EVENT_KEY_RELEASE = 2,
TCOD_EVENT_KEY = TCOD_EVENT_KEY_PRESS | TCOD_EVENT_KEY_RELEASE,
TCOD_EVENT_MOUSE_MOVE = 4,
TCOD_EVENT_MOUSE_PRESS = 8,
TCOD_EVENT_MOUSE_RELEASE = 16,
TCOD_EVENT_MOUSE = TCOD_EVENT_MOUSE_MOVE | TCOD_EVENT_MOUSE_PRESS | TCOD_EVENT_MOUSE_RELEASE,
/* #ifdef TCOD_TOUCH_INPUT */
TCOD_EVENT_FINGER_MOVE = 32,
TCOD_EVENT_FINGER_PRESS = 64,
TCOD_EVENT_FINGER_RELEASE = 128,
TCOD_EVENT_FINGER = TCOD_EVENT_FINGER_MOVE | TCOD_EVENT_FINGER_PRESS | TCOD_EVENT_FINGER_RELEASE,
/* #endif */
TCOD_EVENT_ANY = TCOD_EVENT_KEY | TCOD_EVENT_MOUSE | TCOD_EVENT_FINGER,
} TCOD_event_t;
struct SDL_Surface;
typedef void (*SDL_renderer_t)(struct SDL_Surface* sdl_renderer);
/* thread stuff */
typedef void* TCOD_thread_t;
typedef void* TCOD_semaphore_t;
typedef void* TCOD_mutex_t;
typedef void* TCOD_cond_t;
#ifdef __cplusplus
extern "C" {
#endif
TCODLIB_API void TCOD_sys_startup(void);
TCODLIB_API void TCOD_sys_shutdown(void);
/* filesystem stuff */
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API bool TCOD_sys_create_directory(const char* path);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API bool TCOD_sys_delete_file(const char* path);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API bool TCOD_sys_delete_directory(const char* path);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API bool TCOD_sys_is_directory(const char* path);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API TCOD_list_t TCOD_sys_get_directory_content(const char* path, const char* pattern);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API bool TCOD_sys_file_exists(const char* filename, ...);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API bool TCOD_sys_read_file(const char* filename, unsigned char** buf, size_t* size);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API bool TCOD_sys_write_file(const char* filename, unsigned char* buf, uint32_t size);
#ifndef TCOD_NO_THREADS
/* threads */
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API TCOD_thread_t TCOD_thread_new(int (*func)(void*), void* data);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_thread_delete(TCOD_thread_t th);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API int TCOD_sys_get_num_cores(void);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_thread_wait(TCOD_thread_t th);
/* mutex */
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API TCOD_mutex_t TCOD_mutex_new(void);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_mutex_in(TCOD_mutex_t mut);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_mutex_out(TCOD_mutex_t mut);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_mutex_delete(TCOD_mutex_t mut);
/* semaphore */
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API TCOD_semaphore_t TCOD_semaphore_new(int initVal);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_semaphore_lock(TCOD_semaphore_t sem);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_semaphore_unlock(TCOD_semaphore_t sem);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_semaphore_delete(TCOD_semaphore_t sem);
/* condition */
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API TCOD_cond_t TCOD_condition_new(void);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_condition_signal(TCOD_cond_t sem);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_condition_broadcast(TCOD_cond_t sem);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_condition_wait(TCOD_cond_t sem, TCOD_mutex_t mut);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_condition_delete(TCOD_cond_t sem);
#endif // TCOD_NO_THREADS
#ifndef NO_SDL
/* dynamic library */
typedef void* TCOD_library_t;
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API TCOD_library_t TCOD_load_library(const char* path);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void* TCOD_get_function_address(TCOD_library_t library, const char* function_name);
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_close_library(TCOD_library_t);
/***************************************************************************
@brief Alias for SDL_GetTicks.
\rst
.. deprecated:: 1.19
You should call SDL_GetTicks directly.
\endrst
*/
TCOD_DEPRECATED("Use SDL_GetTicks instead.")
TCODLIB_API uint32_t TCOD_sys_elapsed_milli(void);
/***************************************************************************
@brief Returns the number of seconds since the start of the program.
\rst
.. deprecated:: 1.19
Use SDL_GetTicks and convert the result into seconds instead of using this function.
\endrst
*/
TCOD_DEPRECATED("Use SDL_GetTicks instead.")
TCODLIB_API float TCOD_sys_elapsed_seconds(void);
/***************************************************************************
@brief Alias for SDL_Delay.
\rst
.. deprecated:: 1.19
You should call SDL_Delay directly.
\endrst
*/
TCOD_DEPRECATED("Use SDL_Delay instead.")
TCODLIB_API void TCOD_sys_sleep_milli(uint32_t val);
/***************************************************************************
@brief Set the desired framerate.
\rst
.. deprecated:: 1.19
This function will not affect libtcod contexts.
Set the framerate with :any:`tcod::Timer` instead.
\endrst
*/
TCOD_DEPRECATED("This function is not compatible with contexts. Use tcod::Timer or SDL timing functions instead.")
TCODLIB_API void TCOD_sys_set_fps(int val);
/***************************************************************************
@brief Get the current framerate.
\rst
.. deprecated:: 1.19
This function will not work with libtcod contexts.
Use :any:`tcod::Timer` instead.
\endrst
*/
TCOD_DEPRECATED("This function is not compatible with contexts. Use tcod::Timer or SDL timing functions instead.")
TCODLIB_API int TCOD_sys_get_fps(void);
/***************************************************************************
@brief Get the delta time between the last two frames.
\rst
.. deprecated:: 1.19
This function will not work with libtcod contexts.
Use :any:`tcod::Timer` instead.
\endrst
*/
TCOD_DEPRECATED("This function is not compatible with contexts. Use tcod::Timer or SDL timing functions instead.")
TCODLIB_API float TCOD_sys_get_last_frame_length(void);
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCODLIB_API void TCOD_sys_save_screenshot(const char* filename);
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCODLIB_API void TCOD_sys_force_fullscreen_resolution(int width, int height);
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCODLIB_API TCOD_NODISCARD int TCOD_sys_set_renderer(TCOD_renderer_t renderer);
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCODLIB_API TCOD_renderer_t TCOD_sys_get_renderer(void);
/**
Return the resolution of the current monitor.
*/
TCOD_DEPRECATED("Use SDL to determine the screen resolution instead.")
TCODLIB_API TCOD_Error TCOD_sys_get_current_resolution(int* w, int* h);
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCODLIB_API void TCOD_sys_get_fullscreen_offsets(int* offset_x, int* offset_y);
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCODLIB_API void TCOD_sys_get_char_size(int* w, int* h);
/**
* Upload a tile to the active tileset.
*
* `asciiCode` is the Unicode codepoint for this tile.
*
* `font_x` and `font_y` are the tile-coordinates on the active tilemap.
*
* `img` is the tile to upload.
*
* `x` and `y` are the upper-left pixel-coordinates of the tile on the `img`.
*/
TCODLIB_API void TCOD_sys_update_char(int asciiCode, int font_x, int font_y, TCOD_image_t img, int x, int y);
TCODLIB_API struct SDL_Window* TCOD_sys_get_SDL_window(void);
TCODLIB_API struct SDL_Renderer* TCOD_sys_get_SDL_renderer(void);
TCOD_DEPRECATED("This API is deprecated, use SDL_WaitEvent instead.")
TCODLIB_API TCOD_event_t TCOD_sys_wait_for_event(int eventMask, TCOD_key_t* key, TCOD_mouse_t* mouse, bool flush);
TCOD_DEPRECATED("This API is deprecated, use SDL_PollEvent instead.")
TCODLIB_API TCOD_event_t TCOD_sys_check_for_event(int eventMask, TCOD_key_t* key, TCOD_mouse_t* mouse);
/* clipboard */
TCOD_DEPRECATED("Use the SDL2 API to handle the clipboard.")
TCODLIB_API bool TCOD_sys_clipboard_set(const char* value);
TCOD_DEPRECATED("Use the SDL2 API to handle the clipboard.")
TCODLIB_API char* TCOD_sys_clipboard_get(void);
/* SDL renderer callback */
TCOD_DEPRECATED_NOMESSAGE
TCODLIB_API void TCOD_sys_register_SDL_renderer(SDL_renderer_t renderer);
#endif // NO_SDL
#ifdef __cplusplus
} // extern "C"
#endif
#endif

View file

@ -0,0 +1,602 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
#ifndef _TCOD_SYS_HPP
#define _TCOD_SYS_HPP
#include "image.hpp"
#include "mouse.hpp"
#include "sys.h"
/**
@PageName system
@PageCategory Core
@PageTitle System layer
@PageDesc This toolkit contains some system specific miscellaneous utilities. Use them is you want your code to be easily portable.
*/
class TCODLIB_API ITCODSDLRenderer {
public :
virtual ~ITCODSDLRenderer() {}
virtual void render(void *sdlSurface) = 0;
};
class TCODLIB_API TCODSystem {
public :
/**
@PageName system_time
@PageFather system
@PageTitle High precision time functions
@PageDesc These are functions specifically aimed at real time game development.
@FuncTitle Limit the frames per second
@FuncDesc The setFps function allows you to limit the number of frames per second.
If a frame is rendered faster than expected, the TCOD_console_flush function will wait so that the frame rate never exceed this value.
You can call this function during your game initialization.
You can dynamically change the frame rate. Just call this function once again.
<b>You should always limit the frame rate, except during benchmarks, else your game will use 100% of the CPU power</b>
@Cpp static void TCODSystem::setFps(int val)
@C void TCOD_sys_set_fps(int val)
@Py sys_set_fps(val)
@C# static void TCODSystem::setFps(int val)
@Lua tcod.system.setFps(val)
@Param val Maximum number of frames per second. 0 means unlimited frame rate.
*/
[[deprecated("This function is not compatible with contexts. Use tcod::Timer instead.")]]
static void setFps(int val);
/**
@PageName system_time
@FuncTitle Get the number of frames rendered during the last second
@FuncDesc The value returned by this function is updated every second.
@Cpp static int TCODSystem::getFps()
@C int TCOD_sys_get_fps()
@Py sys_get_fps()
@C# static int TCODSystem::getFps()
@Lua tcod.system.getFps()
*/
[[deprecated("This function is not compatible with contexts. Use tcod::Timer instead.")]]
static int getFps();
/**
@PageName system_time
@FuncTitle Get the duration of the last frame
@FuncDesc This function returns the length in seconds of the last rendered frame.
You can use this value to update every time dependent object in the world.
@Cpp static float TCODSystem::getLastFrameLength()
@C float TCOD_sys_get_last_frame_length()
@Py sys_get_last_frame_length()
@C# static float TCODSystem::getLastFrameLength()
@Lua tcod.system.getLastFrameLength()
@CppEx
// moving an objet at 5 console cells per second
float x=0,y=0; // object coordinates
x += 5 * TCODSystem::getLastFrameLength();
TCODConsole::root->putChar((int)(x),(int)(y),'X');
@CEx
float x=0,y=0;
x += 5 * TCOD_sys_get_last_frame_length();
TCOD_console_put_char(NULL,(int)(x),(int)(y),'X');
@PyEx
x=0.0
y=0.0
x += 5 * libtcod.sys_get_last_frame_length()
libtcod.console_put_char(0,int(x),int(y),'X')
@LuaEx
-- moving an objet at 5 console cells per second
x=0
y=0 -- object coordinates
x = x + 5 * tcod.system.getLastFrameLength()
libtcod.TCODConsole_root:putChar(x,y,'X')
*/
[[deprecated("This function is not compatible with contexts. Use tcod::Timer or SDL timing functions instead.")]]
static float getLastFrameLength();
/**
@PageName system_time
@FuncTitle Pause the program
@FuncDesc Use this function to stop the program execution for a specified number of milliseconds.
@Cpp static void TCODSystem::sleepMilli(uint32_t val)
@C void TCOD_sys_sleep_milli(uint32_t val)
@Py sys_sleep_milli(val)
@C# static void TCODSystem::sleepMilli(uint val)
@Lua tcod.system.sleepMilli(val)
@Param val number of milliseconds before the function returns
*/
[[deprecated("Use SDL_Delay instead.")]]
static void sleepMilli(uint32_t val);
/**
@PageName system_time
@FuncTitle Get global timer in milliseconds
@FuncDesc This function returns the number of milliseconds since the program has started.
@Cpp static uint32_t TCODSystem::getElapsedMilli()
@C uint32_t TCOD_sys_elapsed_milli()
@Py sys_elapsed_milli()
@C# static uint TCODSystem::getElapsedMilli()
@Lua tcod.system.getElapsedMilli()
*/
[[deprecated("Use SDL_GetTicks instead.")]]
static uint32_t getElapsedMilli();
/**
@PageName system_time
@FuncTitle Get global timer in seconds
@FuncDesc This function returns the number of seconds since the program has started.
@Cpp static float TCODSystem::getElapsedSeconds()
@C float TCOD_sys_elapsed_seconds()
@Py sys_elapsed_seconds()
@C# static float TCODSystem::getElapsedSeconds()
@Lua tcod.system.getElapsedSeconds()
*/
[[deprecated("Use SDL_GetTicks instead.")]]
static float getElapsedSeconds();
/**
@PageName console_blocking_input
@FuncTitle Waiting for any event (mouse or keyboard)
@FuncDesc This function waits for an event from the user. The eventMask shows what events we're waiting for.
The return value indicate what event was actually triggered. Values in key and mouse structures are updated accordingly.
If flush is false, the function waits only if there are no pending events, else it returns the first event in the buffer.
@Cpp typedef enum {
TCOD_EVENT_NONE=0,
TCOD_EVENT_KEY_PRESS=1,
TCOD_EVENT_KEY_RELEASE=2,
TCOD_EVENT_KEY=TCOD_EVENT_KEY_PRESS|TCOD_EVENT_KEY_RELEASE,
TCOD_EVENT_MOUSE_MOVE=4,
TCOD_EVENT_MOUSE_PRESS=8,
TCOD_EVENT_MOUSE_RELEASE=16,
TCOD_EVENT_MOUSE=TCOD_EVENT_MOUSE_MOVE|TCOD_EVENT_MOUSE_PRESS|TCOD_EVENT_MOUSE_RELEASE,
TCOD_EVENT_ANY=TCOD_EVENT_KEY|TCOD_EVENT_MOUSE,
} TCOD_event_t;
static TCOD_event_t TCODSystem::waitForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush)
@C TCOD_event_t TCOD_sys_wait_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush)
@Py sys_wait_for_event(eventMask,key,mouse,flush)
@Param eventMask event types to wait for (other types are discarded)
@Param key updated in case of a key event. Can be null if eventMask contains no key event type
@Param mouse updated in case of a mouse event. Can be null if eventMask contains no mouse event type
@Param flush if true, all pending events are flushed from the buffer. Else, return the first available event
@CppEx
TCOD_key_t key;
TCOD_mouse_t mouse;
TCOD_event_t ev = TCODSystem::waitForEvent(TCOD_EVENT_ANY,&key,&mouse,true);
if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... }
@CEx
TCOD_key_t key;
TCOD_mouse_t mouse;
TCOD_event_t ev = TCOD_sys_wait_for_event(TCOD_EVENT_ANY,&key,&mouse,true);
if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... }
*/
[[deprecated("This API is deprecated, use SDL_WaitEvent instead.")]]
static TCOD_event_t waitForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush);
/**
@PageName console_non_blocking_input
@FuncTitle Checking for any event (mouse or keyboard)
@FuncDesc This function checks if an event from the user is in the buffer. The eventMask shows what events we're waiting for.
The return value indicate what event was actually found. Values in key and mouse structures are updated accordingly.
@Cpp typedef enum {
TCOD_EVENT_KEY_PRESS=1,
TCOD_EVENT_KEY_RELEASE=2,
TCOD_EVENT_KEY=TCOD_EVENT_KEY_PRESS|TCOD_EVENT_KEY_RELEASE,
TCOD_EVENT_MOUSE_MOVE=4,
TCOD_EVENT_MOUSE_PRESS=8,
TCOD_EVENT_MOUSE_RELEASE=16,
TCOD_EVENT_MOUSE=TCOD_EVENT_MOUSE_MOVE|TCOD_EVENT_MOUSE_PRESS|TCOD_EVENT_MOUSE_RELEASE,
TCOD_EVENT_ANY=TCOD_EVENT_KEY|TCOD_EVENT_MOUSE,
} TCOD_event_t;
static TCOD_event_t TCODSystem::checkForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse)
@C TCOD_event_t TCOD_sys_check_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse)
@Py sys_check_for_event(eventMask,key,mouse)
@Param eventMask event types to wait for (other types are discarded)
@Param key updated in case of a key event. Can be null if eventMask contains no key event type
@Param mouse updated in case of a mouse event. Can be null if eventMask contains no mouse event type
@CppEx
TCOD_key_t key;
TCOD_mouse_t mouse;
TCOD_event_t ev = TCODSystem::checkForEvent(TCOD_EVENT_ANY,&key,&mouse);
if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... }
@CEx
TCOD_key_t key;
TCOD_mouse_t mouse;
TCOD_event_t ev = TCOD_sys_check_for_event(TCOD_EVENT_ANY,&key,&mouse);
if ( ev == TCOD_EVENT_KEY_PRESS && key.c == 'i' ) { ... open inventory ... }
*/
[[deprecated("This API is deprecated, use SDL_PollEvent instead.")]]
static TCOD_event_t checkForEvent(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse);
/**
@PageName system_screenshots
@PageFather system
@PageTitle Easy screenshots
@FuncDesc This function allows you to save the current game screen in a png file, or possibly a bmp file if you provide a filename ending with .bmp.
@Cpp static void TCODSystem::saveScreenshot(const char *filename)
@C void TCOD_sys_save_screenshot(const char *filename)
@Py sys_save_screenshot(filename)
@C# static void TCODSystem::saveScreenshot(string filename);
@Lua tcod.system.saveScreenshot(filename)
@Param filename Name of the file. If NULL, a filename is automatically generated with the form "./screenshotNNN.png", NNN being the first free number (if a file named screenshot000.png already exist, screenshot001.png will be used, and so on...).
*/
[[deprecated("This function is not compatible with contexts.")]]
static void saveScreenshot(const char *filename);
/**
@PageName system_filesystem
@PageFather system
@PageTitle Filesystem utilities
@PageDesc Those are a few function that cannot be easily implemented in a portable way in C/C++. They have no Python wrapper since Python provides its own builtin functions. All those functions return false if an error occurred.
@FuncTitle Create a directory
@Cpp static bool TCODSystem::createDirectory(const char *path)
@C bool TCOD_sys_create_directory(const char *path)
@Param path Directory path. The immediate father directory (<path>/..) must exist and be writable.
*/
TCOD_DEPRECATED_NOMESSAGE
static bool createDirectory(const char *path);
/**
@PageName system_filesystem
@FuncTitle Delete an empty directory
@Cpp static bool TCODSystem::deleteDirectory(const char *path)
@C bool TCOD_sys_delete_directory(const char *path)
@Param path directory path. This directory must exist, be writable and empty
*/
TCOD_DEPRECATED_NOMESSAGE
static bool deleteDirectory(const char *path);
/**
@PageName system_filesystem
@FuncTitle Delete a file
@Cpp static bool TCODSystem::deleteFile(const char *path)
@C bool TCOD_sys_delete_file(const char *path)
@Param path File path. This file must exist and be writable.
*/
TCOD_DEPRECATED_NOMESSAGE
static bool deleteFile(const char *path);
/**
@PageName system_filesystem
@FuncTitle Check if a path is a directory
@Cpp static bool TCODSystem::isDirectory(const char *path)
@C bool TCOD_sys_is_directory(const char *path)
@Param path a path to check
*/
TCOD_DEPRECATED_NOMESSAGE
static bool isDirectory(const char *path);
/**
@PageName system_filesystem
@FuncTitle List files in a directory
@FuncDesc To get the list of entries in a directory (including sub-directories, except . and ..).
The returned list is allocated by the function and must be deleted by you. All the const char * inside must be also freed with TCODList::clearAndDelete.
@Cpp static TCODList TCODSystem::getDirectoryContent(const char *path, const char *pattern)
@C TCOD_list_t TCOD_sys_get_directory_content(const char *path)
@Param path a directory
@Param pattern If NULL or empty, returns all directory entries. Else returns only entries matching the pattern. The pattern is NOT a regular expression. It can only handle one '*' wildcard. Examples : *.png, saveGame*, font*.png
*/
TCOD_DEPRECATED_NOMESSAGE
static TCOD_list_t getDirectoryContent(const char *path, const char *pattern);
/**
@PageName system_filesystem
@FuncTitle Check if a given file exists
@FuncDesc In order to check whether a given file exists in the filesystem. Useful for detecting errors caused by missing files.
@Cpp static bool TCODSystem::fileExists(const char *filename, ...)
@C bool TCOD_sys_file_exists(const char * filename, ...)
@Param filename the file name, using printf-like formatting
@Param ... optional arguments for filename formatting
@CppEx
if (!TCODSystem::fileExists("myfile.%s","txt")) {
fprintf(stderr,"no such file!");
}
@CEx
if (!TCOD_sys_file_exists("myfile.%s","txt")) {
fprintf(stderr,"no such file!");
}
*/
TCOD_DEPRECATED_NOMESSAGE
static bool fileExists(const char * filename, ...);
/**
@PageName system_filesystem
@FuncTitle Read the content of a file into memory
@FuncDesc This is a portable function to read the content of a file from disk or from the application apk (android).
buf must be freed with free(buf).
@Cpp static bool TCODSystem::readFile(const char *filename, unsigned char **buf, uint32_t *size)
@C bool TCOD_sys_read_file(const char *filename, unsigned char **buf, uint32_t *size)
@Param filename the file name
@Param buf a buffer to be allocated and filled with the file content
@Param size the size of the allocated buffer.
@CppEx
unsigned char *buf;
uint32_t size;
if (TCODSystem::readFile("myfile.dat",&buf,&size)) {
// do something with buf
free(buf);
}
@CEx
if (TCOD_sys_read_file("myfile.dat",&buf,&size)) {
// do something with buf
free(buf);
}
*/
TCOD_DEPRECATED_NOMESSAGE
static bool readFile(const char *filename, unsigned char **buf, size_t *size);
/**
@PageName system_filesystem
@FuncTitle Write the content of a memory buffer to a file
@FuncDesc This is a portable function to write some data to a file.
@Cpp static bool TCODSystem::writeFile(const char *filename, unsigned char *buf, uint32_t size)
@C bool TCOD_sys_write_file(const char *filename, unsigned char *buf, uint32_t size)
@Param filename the file name
@Param buf a buffer containing the data to write
@Param size the number of bytes to write.
@CppEx
TCODSystem::writeFile("myfile.dat",buf,size));
@CEx
TCOD_sys_write_file("myfile.dat",buf,size));
*/
TCOD_DEPRECATED_NOMESSAGE
static bool writeFile(const char *filename, unsigned char *buf, uint32_t size);
/**
@PageName system_sdlcbk
@PageFather system
@PageTitle Draw custom graphics on top of the root console
@PageDesc You can register a callback that will be called after the libtcod rendering phase, but before the screen buffer is swapped. This callback receives the screen SDL_Surface reference.
This makes it possible to use any SDL drawing functions (including openGL) on top of the libtcod console.
@FuncTitle Render custom graphics
@FuncDesc To disable the custom renderer, call the same method with a NULL parameter.
Note that to keep libtcod from requiring the SDL headers, the callback parameter is a void pointer. You have to include SDL headers and cast it to SDL_Surface in your code.
@Cpp
class TCODLIB_API ITCODSDLRenderer {
public :
virtual void render(void *sdlSurface) = 0;
};
static void TCODSystem::registerSDLRenderer(ITCODSDLRenderer *callback);
@C
typedef void (*SDL_renderer_t) (void *sdl_surface);
void TCOD_sys_register_SDL_renderer(SDL_renderer_t callback)
@Py
def renderer ( sdl_surface ) : ...
TCOD_sys_register_SDL_renderer( callback )
@Param callback The renderer to call before swapping the screen buffer. If NULL, custom rendering is disabled
@CppEx
class MyRenderer : public ITCODSDLRenderer {
public :
void render(void *sdlSurface) {
SDL_Surface *s = (SDL_Surface *)sdlSurface;
... draw something on s
}
};
TCODSystem::registerSDLRenderer(new MyRenderer());
@CEx
void my_renderer( void *sdl_surface ) {
SDL_Surface *s = (SDL_Surface *)sdl_surface;
... draw something on s
}
TCOD_sys_register_SDL_renderer(my_renderer);
@Py
def my_renderer(sdl_surface) :
... draw something on sdl_surface using pygame
libtcod.sys_register_SDL_renderer(my_renderer)
*/
TCOD_DEPRECATED_NOMESSAGE
static void registerSDLRenderer(ITCODSDLRenderer *renderer);
/**
@PageName system_sdlcbk
@FuncTitle Managing screen redraw
@FuncDesc libtcod is not aware of the part of the screen your SDL renderer has updated. If no change occurred in the console, it won't redraw them except if you tell him to do so with this function
@Cpp void TCODConsole::setDirty(int x, int y, int w, int h)
@C void TCOD_console_set_dirty(int x, int y, int w, int h)
@Py TCOD_console_set_dirty(x, y, w, h)
@Param x,y,w,h Part of the root console you want to redraw even if nothing has changed in the console back/fore/char.
*/
/**
@PageName system_misc
@PageFather system
@PageTitle Miscellaneous utilities
@FuncTitle Using a custom resolution for the fullscreen mode
@FuncDesc This function allows you to force the use of a specific resolution in fullscreen mode.
The default resolution depends on the root console size and the font character size.
@Cpp static void TCODSystem::forceFullscreenResolution(int width, int height)
@C void TCOD_sys_force_fullscreen_resolution(int width, int height)
@Py sys_force_fullscreen_resolution(width, height)
@C# static void TCODSystem::forceFullscreenResolution(int width, int height);
@Lua tcod.system.forceFullscreenResolution(width,height)
@Param width,height Resolution to use when switching to fullscreen.
Will use the smallest available resolution so that :
resolution width >= width and resolution width >= root console width * font char width
resolution width >= height and resolution height >= root console height * font char height
@CppEx
TCODSystem::forceFullscreenResolution(800,600); // use 800x600 in fullscreen instead of 640x400
TCODConsole::initRoot(80,50,"",true); // 80x50 console with 8x8 char => 640x400 default resolution
@CEx
TCOD_sys_force_fullscreen_resolution(800,600);
TCOD_console_init_root(80,50,"",true);
@PyEx
libtcod.sys_force_fullscreen_resolution(800,600)
libtcod.console_init_root(80,50,"",True)
@LuaEx
tcod.system.forceFullscreenResolution(800,600) -- use 800x600 in fullscreen instead of 640x400
tcod.console.initRoot(80,50,"",true) -- 80x50 console with 8x8 char => 640x400 default resolution
*/
[[deprecated("This function is not compatible with contexts.")]]
static void forceFullscreenResolution(int width, int height);
/**
@PageName system_misc
@FuncTitle Get current resolution
@FuncDesc You can get the current screen resolution with getCurrentResolution. You can use it for example to get the desktop resolution before initializing the root console.
@Cpp static void TCODSystem::getCurrentResolution(int *width, int *height)
@C void TCOD_sys_get_current_resolution(int *width, int *height)
@Py sys_get_current_resolution() # returns w,h
@C# static void TCODSystem::getCurrentResolution(out int w, out int h);
@Param width,height contains current resolution when the function returns
*/
[[deprecated("This function is not compatible with contexts.")]]
static void getCurrentResolution(int *width, int *height);
/**
@PageName system_misc
@FuncTitle Get fullscreen offset
@FuncDesc If the fullscreen resolution does not matches the console size in pixels, black borders are added. This function returns the position in pixels of the console top left corner in the screen.
@Cpp static void TCODSystem::getFullscreenOffsets(int *offset_x, int *offset_y)
@C void TCOD_sys_get_fullscreen_offsets(int *offset_x, int *offset_y)
@C# static void TCODSystem::getFullscreenOffsets(out int offset_x, out int offset_y);
@Param offset_x,offset_y contains the position of the console on the screen when using fullscreen mode.
*/
[[deprecated("This function is not compatible with contexts.")]]
static void getFullscreenOffsets(int *offset_x, int *offset_y);
/**
@PageName system_misc
@FuncTitle Get the font size
@FuncDesc You can get the size of the characters in the font
@Cpp static void TCODSystem::getCharSize(int *width, int *height)
@C void TCOD_sys_get_char_size(int *width, int *height)
@Py sys_get_char_size() # returns w,h
@C# static void TCODSystem::getCharSize(out int w, out int h);
@Param width,height contains a character size when the function returns
*/
[[deprecated("This function is not compatible with contexts.")]]
static void getCharSize(int *w, int *h);
/**
@PageName system_misc
@FuncTitle Dynamically updating the font bitmap
@FuncDesc You can dynamically change the bitmap of a character in the font. All cells using this ascii code will be updated at next flush call.
@Cpp static void TCODSystem::updateChar(int asciiCode, int font_x, int font_y,const TCODImage *img,int x,int y)
@C void TCOD_sys_update_char(int asciiCode, int font_x, int font_y, TCOD_image_t img, int x, int y)
@Py sys_update_char(asciiCode,font_x,font_y,img,x,y)
@Param asciiCode ascii code corresponding to the character to update
@Param font_x,font_y coordinate of the character in the bitmap font (in characters, not pixels)
@Param img image containing the new character bitmap
@Param x,y position in pixels of the top-left corner of the character in the image
*/
[[deprecated("This function is not compatible with contexts.")]]
static void updateChar(int asciiCode, int font_x, int font_y,const TCODImage *img,int x,int y);
/**
@PageName system_misc
@FuncTitle Dynamically change libtcod's internal renderer
@FuncDesc As of 1.5.1, libtcod contains 3 different renderers :
* SDL : historic libtcod renderer. Should work and be pretty fast everywhere
* OpenGL : requires OpenGL compatible video card. Might be much faster or much slower than SDL, depending on the drivers
* GLSDL : requires OpenGL 1.4 compatible video card with GL_ARB_shader_objects extension. Blazing fast if you have the proper hardware and drivers.
This function switches the current renderer dynamically.
@Cpp static void TCODSystem::setRenderer(TCOD_renderer_t renderer)
@C void TCOD_sys_set_renderer(TCOD_renderer_t renderer)
@Py sys_set_renderer(renderer)
@C# static void TCODSystem::setRenderer(TCODRendererType renderer);
@Param renderer Either TCOD_RENDERER_GLSL, TCOD_RENDERER_OPENGL or TCOD_RENDERER_SDL
*/
[[deprecated("This function is not compatible with contexts.")]]
static void setRenderer(TCOD_renderer_t renderer);
/**
@PageName system_misc
@FuncTitle Get the current internal renderer
@Cpp static TCOD_renderer_t TCODSystem::getRenderer()
@C TCOD_renderer_t TCOD_sys_get_renderer()
@Py sys_get_renderer()
@C# static TCODRendererType TCODSystem::getRenderer();
*/
[[deprecated("This function is not compatible with contexts.")]]
static TCOD_renderer_t getRenderer();
/**
@PageName system_clipboard
@PageTitle Clipboard integration
@PageDesc With these functions, you can copy data in your operating system's clipboard from the game or retrieve data from the clipboard.
@PageFather system
@FuncTitle Set current clipboard contents
@FuncDesc Takes UTF-8 text and copies it into the system clipboard. On Linux, because an application cannot access the system clipboard unless a window is open, if no window is open the call will do nothing.
@Cpp static bool TCODSystem::setClipboard(const char *value)
@C bool TCOD_sys_clipboard_set(const char *value)
@Py sys_clipboard_set(value)
@Param value UTF-8 text to copy into the clipboard
*/
TCOD_DEPRECATED_NOMESSAGE
static bool setClipboard(const char *value);
/**
@PageName system_clipboard
@FuncTitle Get current clipboard contents
@FuncDesc Returns the UTF-8 text currently in the system clipboard. On Linux, because an application cannot access the system clipboard unless a window is open, if no window is open an empty string will be returned. For C and C++, note that the pointer is borrowed, and libtcod will take care of freeing the memory.
@Cpp static char *TCODSystem::getClipboard()
@C char *TCOD_sys_clipboard_get()
@Py sys_clipboard_get() # Returns UTF-8 string
*/
TCOD_DEPRECATED_NOMESSAGE
static char *getClipboard();
#ifndef TCOD_NO_THREADS
// thread stuff
TCOD_DEPRECATED_NOMESSAGE
static int getNumCores();
TCOD_DEPRECATED_NOMESSAGE
static TCOD_thread_t newThread(int (*func)(void *), void *data);
TCOD_DEPRECATED_NOMESSAGE
static void deleteThread(TCOD_thread_t th);
TCOD_DEPRECATED_NOMESSAGE
static void waitThread(TCOD_thread_t th);
// mutex
TCOD_DEPRECATED_NOMESSAGE
static TCOD_mutex_t newMutex();
TCOD_DEPRECATED_NOMESSAGE
static void mutexIn(TCOD_mutex_t mut);
TCOD_DEPRECATED_NOMESSAGE
static void mutexOut(TCOD_mutex_t mut);
TCOD_DEPRECATED_NOMESSAGE
static void deleteMutex(TCOD_mutex_t mut);
// semaphore
TCOD_DEPRECATED_NOMESSAGE
static TCOD_semaphore_t newSemaphore(int initVal);
TCOD_DEPRECATED_NOMESSAGE
static void lockSemaphore(TCOD_semaphore_t sem);
TCOD_DEPRECATED_NOMESSAGE
static void unlockSemaphore(TCOD_semaphore_t sem);
TCOD_DEPRECATED_NOMESSAGE
static void deleteSemaphore( TCOD_semaphore_t sem);
// condition
TCOD_DEPRECATED_NOMESSAGE
static TCOD_cond_t newCondition();
TCOD_DEPRECATED_NOMESSAGE
static void signalCondition(TCOD_cond_t sem);
TCOD_DEPRECATED_NOMESSAGE
static void broadcastCondition(TCOD_cond_t sem);
TCOD_DEPRECATED_NOMESSAGE
static void waitCondition(TCOD_cond_t sem, TCOD_mutex_t mut);
TCOD_DEPRECATED_NOMESSAGE
static void deleteCondition( TCOD_cond_t sem);
#endif // TCOD_NO_THREADS
};
#endif

View file

@ -0,0 +1,323 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_TILESET_H_
#define LIBTCOD_TILESET_H_
#include <stddef.h>
#include "color.h"
#include "config.h"
#include "error.h"
struct TCOD_Tileset;
struct TCOD_TilesetObserver {
struct TCOD_Tileset* tileset;
struct TCOD_TilesetObserver* next;
void* userdata;
void (*on_observer_delete)(struct TCOD_TilesetObserver* observer);
int (*on_tile_changed)(struct TCOD_TilesetObserver* observer, int tile_id);
};
/**
@brief A container for libtcod tileset graphics.
\rst
.. versionadded:: 1.19
\endrst
*/
struct TCOD_Tileset {
int tile_width;
int tile_height;
int tile_length;
int tiles_capacity;
int tiles_count;
struct TCOD_ColorRGBA* __restrict pixels;
int character_map_length;
int* __restrict character_map;
struct TCOD_TilesetObserver* observer_list;
int virtual_columns;
volatile int ref_count;
};
typedef struct TCOD_Tileset TCOD_Tileset;
// clang-format off
// Character maps are defined in this way so that the C and C++ API don't duplicate them.
#define TCOD_CHARMAP_CP437_ {\
0x0000, 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022,\
0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C,\
0x25BA, 0x25C4, 0x2195, 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8,\
0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC,\
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,\
0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F,\
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,\
0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F,\
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,\
0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F,\
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,\
0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F,\
0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,\
0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F,\
0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077,\
0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x2302,\
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7,\
0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5,\
0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9,\
0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192,\
0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA,\
0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,\
0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,\
0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,\
0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,\
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,\
0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,\
0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,\
0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4,\
0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229,\
0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248,\
0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0,\
}
#define TCOD_CHARMAP_TCOD_ {\
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,\
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,\
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,\
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,\
0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x7B,\
0x7C, 0x7D, 0x7E, 0x2591, 0x2592, 0x2593, 0x2502, 0x2500,\
0x253C, 0x2524, 0x2534, 0x251C, 0x252C, 0x2514, 0x250C, 0x2510,\
0x2518, 0x2598, 0x259D, 0x2580, 0x2596, 0x259A, 0x2590, 0x2597,\
0x2191, 0x2193, 0x2190, 0x2192, 0x25B2, 0x25BC, 0x25C4, 0x25BA,\
0x2195, 0x2194, 0x2610, 0x2611, 0x25CB, 0x25C9, 0x2551, 0x2550,\
0x256C, 0x2563, 0x2569, 0x2560, 0x2566, 0x255A, 0x2554, 0x2557,\
0x255D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,\
0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50,\
0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,\
0x59, 0x5A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,\
0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70,\
0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,\
0x79, 0x7A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
}
// clang-format on
/**
A character mapping of a Code Page 437 tileset to Unicode.
\rst
.. versionadded:: 1.19
\endrst
*/
static const int TCOD_CHARMAP_CP437[256] = TCOD_CHARMAP_CP437_;
/**
A character mapping of a deprecated TCOD tileset to Unicode.
\rst
.. versionadded:: 1.19
\endrst
*/
static const int TCOD_CHARMAP_TCOD[256] = TCOD_CHARMAP_TCOD_;
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
Create a new tile-set with the given tile size.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_NODISCARD
TCOD_PUBLIC TCOD_Tileset* TCOD_tileset_new(int tile_width, int tile_height);
/**
Delete a tile-set.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_PUBLIC void TCOD_tileset_delete(TCOD_Tileset* tileset);
/**
* Return the pixel width of tiles in this tileset.
*
* The tileset functions are provisional, the API may change in the future.
*/
TCOD_NODISCARD
TCOD_PUBLIC int TCOD_tileset_get_tile_width_(const TCOD_Tileset* tileset);
/**
* Return the pixel height of tiles in this tileset.
*
* The tileset functions are provisional, the API may change in the future.
*/
TCOD_NODISCARD
TCOD_PUBLIC int TCOD_tileset_get_tile_height_(const TCOD_Tileset* tileset);
/**
* Fetch a tile, outputting its data to a pixel buffer.
*
* `codepoint` is the index for the tile. Unicode is recommend.
*
* `buffer` is a pointer to a contiguous row-major array of pixels. The tile
* data will be outputted here. This pointer can be NULL if you only want to
* know if the tileset has a specific tile.
*
* Returns 0 if the tile exists. Returns a negative value on an error or if
* the tileset does not have a tile for this codepoint.
*
* The tileset functions are provisional, the API may change in the future.
*/
TCOD_NODISCARD
TCOD_PUBLIC TCOD_Error
TCOD_tileset_get_tile_(const TCOD_Tileset* __restrict tileset, int codepoint, struct TCOD_ColorRGBA* __restrict buffer);
/**
* Upload a tile from a pixel buffer into this tileset.
*
* `codepoint` is the index for the tile. Unicode is recommend.
*
* `buffer` is a pointer to a contiguous row-major array of pixels.
* This can not be NULL.
*
* The tileset functions are provisional, the API may change in the future.
*/
TCOD_NODISCARD
TCOD_PUBLIC TCOD_Error
TCOD_tileset_set_tile_(TCOD_Tileset* __restrict tileset, int codepoint, const struct TCOD_ColorRGBA* __restrict buffer);
#ifndef TCOD_NO_PNG
/**
Load a PNG font as a tilesheet and return a TCOD_Tileset.
`filename` is the path to a PNG file.
`columns` and `rows` are the shape of the tileset in the image. The tile
size will be derived from these parameters and the size of the image.
`charmap[n]` is an array of which codepoints to assign to which tiles.
Tiles are assigned in row-major order.
`TCOD_CHARMAP_CP437` or `TCOD_CHARMAP_TCOD` could be used here.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_NODISCARD
TCOD_PUBLIC TCOD_Tileset* TCOD_tileset_load(
const char* filename, int columns, int rows, int n, const int* __restrict charmap);
/**
Load a PNG font from memory and return a TCOD_Tileset.
`buffer[buffer_length]` is the PNG data to load.
The remaining parameters are the same as `TCOD_tileset_load`.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_NODISCARD
TCOD_PUBLIC TCOD_Tileset* TCOD_tileset_load_mem(
size_t buffer_length, const unsigned char* buffer, int columns, int rows, int n, const int* __restrict charmap);
#endif // TCOD_NO_PNG
/**
Load raw RGBA data and return a TCOD_Tileset.
`pixels[width*height]` is a row-major RGBA-ordered byte array.
The remaining parameters are the same as `TCOD_tileset_load`.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_NODISCARD
TCOD_PUBLIC TCOD_Tileset* TCOD_tileset_load_raw(
int width,
int height,
const struct TCOD_ColorRGBA* __restrict pixels,
int columns,
int rows,
int n,
const int* __restrict charmap);
/***************************************************************************
@brief Assign a codepoint to an existing tile based on its tile ID.
@param tileset A TCOD_Tileset pointer, must not be NULL.
@param tile_id The index of the tile.
@param codepoint The Unicode codepoint to associate with tile_id.
@return Returns a negative value on error.
*/
TCOD_NODISCARD
TCOD_PUBLIC int TCOD_tileset_assign_tile(struct TCOD_Tileset* tileset, int tile_id, int codepoint);
/**
* Return a pointer to the tile for `codepoint`.
*
* Returns NULL if no tile exists for codepoint.
*/
TCOD_NODISCARD
TCOD_PUBLIC const struct TCOD_ColorRGBA* TCOD_tileset_get_tile(const TCOD_Tileset* tileset, int codepoint);
/**
* Return a new observer to this tileset.
*
* For internal use.
*/
TCOD_NODISCARD
struct TCOD_TilesetObserver* TCOD_tileset_observer_new(struct TCOD_Tileset* tileset);
/**
* Delete an existing observer.
*
* Will call this observers on_observer_delete callback.
*
* For internal use.
*/
void TCOD_tileset_observer_delete(struct TCOD_TilesetObserver* observer);
/**
* Called to notify any observers that a tile has been changed. This may
* cause running atlases to update or mark cache consoles as dirty.
*
* For internal use.
*/
void TCOD_tileset_notify_tile_changed(TCOD_Tileset* tileset, int tile_id);
/**
* Reserve memory for a specific amount of tiles.
*
* For internal use.
*/
TCOD_NODISCARD
TCOD_Error TCOD_tileset_reserve(TCOD_Tileset* tileset, int desired);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // LIBTCOD_TILESET_H_

View file

@ -0,0 +1,194 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_TILESET_HPP_
#define LIBTCOD_TILESET_HPP_
#include <array>
#include <filesystem>
#include <memory>
#include "error.hpp"
#include "tileset.h"
namespace tcod {
/**
A character mapping of a Code Page 437 tileset to Unicode.
\rst
.. versionadded:: 1.19
\endrst
*/
static constexpr std::array<int, 256> CHARMAP_CP437 = TCOD_CHARMAP_CP437_;
/**
A character mapping of a deprecated TCOD tileset to Unicode.
\rst
.. versionadded:: 1.19
\endrst
*/
static constexpr std::array<int, 256> CHARMAP_TCOD = TCOD_CHARMAP_TCOD_;
struct TilesetDeleter {
void operator()(TCOD_Tileset* tileset) const { TCOD_tileset_delete(tileset); }
};
/**
@brief A unique pointer to a TCOD_Tileset.
\rst
.. versionadded:: 1.19
\endrst
*/
typedef std::unique_ptr<TCOD_Tileset, TilesetDeleter> TilesetPtr;
/***************************************************************************
@brief A C++ Tileset container.
\rst
.. versionadded:: 1.19
\endrst
*/
class Tileset {
public:
/***************************************************************************
@brief Construct a new Tileset object.
*/
Tileset() = default;
/***************************************************************************
@brief Construct a new Tileset object with tiles of the given size. The tileset will be empty.
@param tile_width The width of the tiles of this object in pixels.
@param tile_height The width of the tiles of this object in pixels.
*/
explicit Tileset(int tile_width, int tile_height) : tileset_{TCOD_tileset_new(tile_width, tile_height)} {
if (!tileset_) throw std::runtime_error(TCOD_get_error());
}
/***************************************************************************
@brief Construct a new Tileset object with tiles of the given size. The tileset will be empty.
@param tile_shape The `{width, height}` of the tiles in pixels.
*/
explicit Tileset(const std::array<int, 2>& tile_shape) : Tileset{tile_shape.at(0), tile_shape.at(1)} {}
/***************************************************************************
@brief Pass ownership of a TilesetPtr to a new Tileset.
@param ptr A `tcod::TilesetPtr`, must not be nullptr.
*/
explicit Tileset(TilesetPtr ptr) : tileset_{std::move(ptr)} {
if (!tileset_) throw std::invalid_argument("Pointer must not be nullptr.");
}
/***************************************************************************
@brief Takes ownership of a raw TCOD_Tileset pointer.
@param ptr A pointer which will now be managed by this object.
*/
explicit Tileset(TCOD_Tileset* ptr) : tileset_{ptr} {
if (!tileset_) throw std::invalid_argument("Pointer must not be nullptr.");
}
/***************************************************************************
@brief Get the width of tiles in this Tileset.
@return int The total width of tiles in pixels.
*/
[[nodiscard]] auto get_tile_width() const noexcept -> int { return tileset_->tile_width; }
/***************************************************************************
@brief Get the height of tiles in this Tileset.
@return int The total height of tiles in pixels.
*/
[[nodiscard]] auto get_tile_height() const noexcept -> int { return tileset_->tile_height; }
/***************************************************************************
@brief Get the `{width, height}` shape of tiles in this Tileset.
@return std::array<int, 2> The `{width, height}` of tiles in this Tileset in pixels.
*/
[[nodiscard]] auto get_tile_shape() const noexcept -> std::array<int, 2> {
return {tileset_->tile_width, tileset_->tile_height};
}
/***************************************************************************
@brief Return a non-owning pointer to this objects TCOD_Tileset.
@return TCOD_Tileset
*/
[[nodiscard]] auto get() noexcept -> TCOD_Tileset* { return tileset_.get(); }
/***************************************************************************
@brief Return a non-owning pointer to this objects TCOD_Tileset.
@return TCOD_Tileset
*/
[[nodiscard]] auto get() const noexcept -> TCOD_Tileset* { return tileset_.get(); }
/***************************************************************************
@brief Release ownership of this Tileset's `TCOD_Tileset*` and return the pointer.
Using this Tileset afterwards is undefined.
*/
auto release() noexcept -> TCOD_Tileset* { return tileset_.release(); }
/***************************************************************************
@brief Allow implicit conversions to a TCOD_Console reference.
*/
[[nodiscard]] operator TCOD_Tileset&() { return *tileset_; }
/***************************************************************************
@brief Allow implicit conversions to a const TCOD_Console reference.
*/
[[nodiscard]] operator const TCOD_Tileset&() const { return *tileset_; }
private:
TilesetPtr tileset_ = nullptr;
};
#ifndef TCOD_NO_PNG
/**
@brief Load a tilesheet from a PNG file.
An exception will be thrown if the file is missing or corrupt.
Tiles are indexed in row-major order and should be assigned to Unicode codepoints.
\rst
.. versionadded:: 1.19
\endrst
@tparam ArrayType Must be a `std::vector` or `std::array` like type. With `size()` and `data()` methods.
@param path The file path to the PNG tilesheet image.
@param columns_rows The shape of the grid on the tileset as {columns, rows}.
@param charmap
An array of characters where `charmap[tile_index] = codepoint`.
`tcod::CHARMAP_CP437` or `tcod::CHARMAP_TCOD` are typical values for this argument.
@return TilesetPtr A unique pointer to a `TCOD_Tileset`.
*/
template <typename ArrayType>
TCOD_NODISCARD inline auto load_tilesheet(
const std::filesystem::path& path, const std::array<int, 2>& columns_rows, const ArrayType& charmap) -> Tileset {
tcod::check_path(path);
TilesetPtr tileset{TCOD_tileset_load(
path.string().c_str(), columns_rows.at(0), columns_rows.at(1), static_cast<int>(charmap.size()), charmap.data())};
if (!tileset) throw std::runtime_error(TCOD_get_error());
return Tileset{std::move(tileset)};
}
#endif // TCOD_NO_PNG
} // namespace tcod
#endif // LIBTCOD_TILESET_HPP_

View file

@ -0,0 +1,72 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_TILESET_BDF_H_
#define LIBTCOD_TILESET_BDF_H_
#include "config.h"
#include "tileset.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/// @addtogroup BDF
/// @{
/**
Load a BDF font from a file path.
For the best results, you should use a BDF font with a cell-based
monospace alignment.
May return NULL on failure. See `TCOD_get_error` for the error message.
\rst
.. versionadded:: 1.16
\endrst
*/
TCODLIB_API TCOD_NODISCARD TCOD_Tileset* TCOD_load_bdf(const char* path);
/**
Load a BDF font from memory.
`size` is the byte length of `buffer`. `buffer` is the BDF data to load.
May return NULL on failure. See `TCOD_get_error` for the error message.
\rst
.. versionadded:: 1.16
\endrst
*/
TCODLIB_API TCOD_NODISCARD TCOD_Tileset* TCOD_load_bdf_memory(int size, const unsigned char* buffer);
/// @}
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // LIBTCOD_TILESET_BDF_H_

View file

@ -0,0 +1,62 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_TILESET_BDF_HPP_
#define LIBTCOD_TILESET_BDF_HPP_
#include <filesystem>
#include "error.hpp"
#include "tileset.hpp"
#include "tileset_bdf.h"
namespace tcod {
/// @addtogroup BDF
/// @{
/**
Load a Tileset from a BDF font file.
Will throw an exception on a missing or corrupt file.
\rst
.. versionadded:: 1.19
\endrst
*/
TCOD_NODISCARD
inline auto load_bdf(const std::filesystem::path& path) -> TilesetPtr {
tcod::check_path(path);
TilesetPtr tileset{TCOD_load_bdf(path.string().c_str())};
if (!tileset) throw std::runtime_error(TCOD_get_error());
return tileset;
}
/// @}
} // namespace tcod
#endif // LIBTCOD_TILESET_BDF_HPP_

View file

@ -0,0 +1,49 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_TILESET_FALLBACK_H_
#define LIBTCOD_TILESET_FALLBACK_H_
#include "config.h"
#include "error.h"
#include "tileset.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
* Try to return a fall-back Tileset, may return NULL.
*
* Used when one is needed, but was not provided by the user.
*/
TCODLIB_API TCOD_NODISCARD TCOD_Tileset* TCOD_tileset_load_fallback_font_(int tile_width, int tile_height);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // LIBTCOD_TILESET_FALLBACK_H_

View file

@ -0,0 +1,51 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_TILESET_FALLBACK_HPP_
#define LIBTCOD_TILESET_FALLBACK_HPP_
#include <array>
#include "tileset.hpp"
#include "tileset_fallback.h"
namespace tcod {
namespace tileset {
TCOD_NODISCARD
inline auto new_fallback_tileset(const std::array<int, 2>& tile_size = {0, 12}) -> TilesetPtr {
TilesetPtr tileset{TCOD_tileset_load_fallback_font_(tile_size.at(0), tile_size.at(1))};
if (!tileset) {
throw std::runtime_error(TCOD_get_error());
}
return tileset;
}
} // namespace tileset
} // namespace tcod
#endif // LIBTCOD_TILESET_FALLBACK_HPP_

View file

@ -0,0 +1,73 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_TILESET_RENDER_H_
#define LIBTCOD_TILESET_RENDER_H_
#include "console.h"
#include "tileset.h"
struct SDL_Surface;
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#ifndef NO_SDL
/**
Render a console to a SDL_Surface with a software renderer.
`tileset` is the tiles to render with, must not be NULL.
`console` is the console to render, must not be NULL.
`cache` is an optional pointer to a consoled used as a cache. The console
at `*cache` will be created or modified. The `cache` will be used to skip
drawing already drawn tiles on any subsequent calls.
`surface_out` is a pointer to where to put the surface will be managed.
The surface at `*surface_out` will be created or modified and will change
to match the size of `console` and `tileset`. The pixel format will be
SDL_PIXELFORMAT_RGBA32.
Returns a negative value on error, see `TCOD_get_error`.
\rst
.. versionadded:: 1.16
\endrst
*/
TCOD_PUBLIC TCOD_Error TCOD_tileset_render_to_surface(
const TCOD_Tileset* __restrict tileset,
const TCOD_Console* __restrict console,
TCOD_Console* __restrict* cache,
struct SDL_Surface* __restrict* surface_out);
#endif // NO_SDL
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // LIBTCOD_TILESET_RENDER_H_

View file

@ -0,0 +1,58 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_TILESET_TRUETYPE_H_
#define LIBTCOD_TILESET_TRUETYPE_H_
#include "config.h"
#include "error.h"
#include "tileset.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
Return a tileset from a TrueType font file.
This function is provisional and may change in future releases.
*/
TCODLIB_API TCOD_NODISCARD TCOD_Tileset* TCOD_load_truetype_font_(const char* path, int tile_width, int tile_height);
/**
Set the global tileset from a TrueType font file.
This can be used in place of TCOD_console_set_custom_font.
This function is provisional and may change in future releases.
*/
TCOD_DEPRECATED("This function is not compatible with contexts.")
TCODLIB_API TCOD_NODISCARD TCOD_Error TCOD_tileset_load_truetype_(const char* path, int tile_width, int tile_height);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // LIBTCOD_TILESET_TRUETYPE_H_

View file

@ -0,0 +1,34 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifdef __cplusplus
#include "timer.hpp"
#endif // __cplusplus

View file

@ -0,0 +1,168 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_TIMER_HPP_
#define LIBTCOD_TIMER_HPP_
#include <SDL_timer.h>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <numeric>
#include <stdexcept>
#include <vector>
#include "config.h"
namespace tcod {
/***************************************************************************
@brief A timing class based on SDL's high performance time counter. Used to track delta time or set a framerate.
This class is based on using `SDL_GetPerformanceCounter` to track the time.
The time taken between calls to sync() is tracked. This is used to determine the real framerate if requested.
You must add ``#include <libtcod/timer.hpp>`` to include ths class.
@code{.cpp}
int desired_fps = 30;
auto timer = tcod::Timer();
while (1) {
float delta_time = timer.sync(desired_fps); // desired_fps is optional.
// ...
@endcode
\rst
.. versionadded:: 1.19
\endrst
*/
class [[nodiscard]] Timer {
public:
/***************************************************************************
@brief Construct a new Timer object.
*/
Timer() : last_time_{SDL_GetPerformanceCounter()} {}
/***************************************************************************
@brief Sync the time to a given framerate (if provided) and return the delta time compared to the previous call.
If `desired_fps` is non-zero then this function will block until the desired framerate is reached.
Timing starts once the Timer is constructed.
@param desired_fps The desired framerate in frames-per-second, or zero to disable framerate limiting.
@return The delta time in seconds since the last call to sync is returned as a float.
*/
float sync(int desired_fps = 0) {
const uint64_t frequency = SDL_GetPerformanceFrequency();
uint64_t current_time = SDL_GetPerformanceCounter(); // The precise current time.
int64_t delta_time = static_cast<int64_t>(current_time - last_time_); // The precise delta time.
if (desired_fps > 0) {
const int64_t desired_delta_time = frequency / desired_fps; // Desired precise delta time.
const int64_t time_until_next_frame_ms =
(desired_delta_time - delta_time) * 1000 / static_cast<int64_t>(frequency);
if (time_until_next_frame_ms > 2) {
// Sleep until 1 millisecond before the target time.
SDL_Delay(static_cast<uint32_t>(time_until_next_frame_ms) - 1);
}
while (delta_time < desired_delta_time) { // Spin for the remaining time.
current_time = SDL_GetPerformanceCounter();
delta_time = static_cast<int64_t>(current_time - last_time_);
}
}
last_time_ = current_time;
const float delta_time_s = std::max(0.0f, static_cast<float>(delta_time) / frequency); // Delta time in seconds.
// Drop samples as they hit the total time and count limits.
double total_time = std::accumulate(samples_.begin(), samples_.end(), 0.0); // Total time of all samples.
while (!samples_.empty() && (total_time > MAX_SAMPLES_TIME || samples_.size() >= MAX_SAMPLES_COUNT)) {
total_time -= samples_.front();
samples_.pop_front();
}
samples_.push_back(delta_time_s);
return delta_time_s;
}
/***************************************************************************
@brief Return the mean framerate. This is the average of all samples combined.
*/
[[nodiscard]] float get_mean_fps() const noexcept {
if (samples_.empty()) return 0;
const double total_time = std::accumulate(samples_.begin(), samples_.end(), 0.0);
if (total_time == 0) return 0;
return 1.0f / static_cast<float>(total_time / static_cast<double>(samples_.size()));
}
/***************************************************************************
@brief Return the framerate of the last call to sync().
*/
[[nodiscard]] float get_last_fps() const noexcept {
if (samples_.empty()) return 0;
if (samples_.back() == 0) return 0;
return 1.0f / samples_.back();
}
/***************************************************************************
@brief Return the lowest framerate recently sampled.
*/
[[nodiscard]] float get_min_fps() const noexcept {
if (samples_.empty()) return 0;
const float sample = *std::max_element(samples_.begin(), samples_.end());
if (sample == 0) return 0;
return 1.0f / sample;
}
/***************************************************************************
@brief Return the highest framerate recently sampled.
*/
[[nodiscard]] float get_max_fps() const noexcept {
if (samples_.empty()) return 0;
const float sample = *std::min_element(samples_.begin(), samples_.end());
if (sample == 0) return 0;
return 1.0f / sample;
}
/***************************************************************************
@brief Return the median framerate. This is the framerate of the middle sample when all samples are sorted.
*/
[[nodiscard]] float get_median_fps() const noexcept {
if (samples_.empty()) return 0;
std::vector<float> samples(samples_.begin(), samples_.end());
std::sort(samples.begin(), samples.end());
float median_sample = samples[samples.size() / 2];
if (samples.size() % 2 == 0 && samples.size() > 2) {
median_sample = (median_sample + samples[samples.size() / 2 + 1]) / 2.0f;
}
if (median_sample == 0) return 0;
return 1.0f / median_sample;
}
private:
static constexpr size_t MAX_SAMPLES_COUNT = 1024; // Hard limit on the number of samples held.
static constexpr double MAX_SAMPLES_TIME = 1.0; // Hard limit on the total time of samples held.
uint64_t last_time_; // The last precise time sampled.
std::deque<float> samples_; // The most recent delta time samples in seconds.
};
} // namespace tcod
#endif // LIBTCOD_TIMER_HPP_

View file

@ -0,0 +1,51 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_TREE_H
#define _TCOD_TREE_H
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _TCOD_tree_t {
struct _TCOD_tree_t* next;
struct _TCOD_tree_t* father;
struct _TCOD_tree_t* sons;
} TCOD_tree_t;
TCODLIB_API TCOD_tree_t* TCOD_tree_new(void);
TCODLIB_API void TCOD_tree_add_son(TCOD_tree_t* node, TCOD_tree_t* son);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,58 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
#ifndef _TCOD_TREE_HPP
#define _TCOD_TREE_HPP
#include "tree.h"
class TCODLIB_API TCODTree {
public :
TCODTree *next = nullptr;
TCODTree *father = nullptr;
TCODTree *sons = nullptr;
TCODTree() : next(NULL),father(NULL),sons(NULL){}
void addSon(TCODTree *data) {
data->father=this;
TCODTree *last_son = sons;
while ( last_son && last_son->next ) last_son=last_son->next;
if ( last_son ) {
last_son->next=data;
} else {
sons=data;
}
}
};
#endif

View file

@ -0,0 +1,60 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef _TCOD_TEXT_H_
#define _TCOD_TEXT_H_
#include "color.h"
#include "console_types.h"
#include "portability.h"
#ifdef __cplusplus
extern "C" {
#endif
struct TCOD_Text;
typedef struct TCOD_Text* TCOD_text_t;
TCODLIB_API TCOD_text_t TCOD_text_init(int x, int y, int w, int h, int max_chars);
TCODLIB_API TCOD_text_t TCOD_text_init2(int w, int h, int max_chars);
TCODLIB_API void TCOD_text_set_pos(TCOD_text_t txt, int x, int y);
TCODLIB_API void TCOD_text_set_properties(
TCOD_text_t txt, int cursor_char, int blink_interval, const char* prompt, int tab_size);
TCODLIB_API void TCOD_text_set_colors(TCOD_text_t txt, TCOD_color_t fore, TCOD_color_t back, float back_transparency);
TCODLIB_API bool TCOD_text_update(TCOD_text_t txt, TCOD_key_t key);
TCODLIB_API void TCOD_text_render(TCOD_text_t txt, TCOD_console_t con);
TCODLIB_API const char* TCOD_text_get(TCOD_text_t txt);
TCODLIB_API void TCOD_text_reset(TCOD_text_t txt);
TCODLIB_API void TCOD_text_delete(TCOD_text_t txt);
#ifdef __cplusplus
}
#endif
#endif /* _TCOD_TEXT_H_ */

View file

@ -0,0 +1,56 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
// clang-format off
#ifndef _TCOD_TEXT_HPP_
#define _TCOD_TEXT_HPP_
#include "color.hpp"
#include "console.hpp"
#include "txtfield.h"
class TCODLIB_API TCODText {
public :
TCODText(int x, int y, int w, int h, int max_chars);
TCODText(int w, int h, int max_chars);
~TCODText();
void setProperties(int cursor_char, int blink_interval, const char * prompt, int tab_size);
void setColors(TCODColor fore, TCODColor back, float back_transparency);
void setPos(int x, int y);
bool update(TCOD_key_t key);
void render(TCODConsole * con);
const char *getText();
void reset();
protected :
TCOD_text_t data;
};
#endif

View file

@ -0,0 +1,43 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_UTILITY_H
#define LIBTCOD_UTILITY_H
/******************************************
utility macros
******************************************/
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define ABS(a) ((a) < 0 ? -(a) : (a))
#define CLAMP(a, b, x) ((x) < (a) ? (a) : ((x) > (b) ? (b) : (x)))
#define LERP(a, b, x) ((a) + (x) * ((b) - (a)))
#endif

View file

@ -0,0 +1,88 @@
/* BSD 3-Clause License
*
* Copyright © 2008-2022, Jice and the libtcod contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef LIBTCOD_VERSION_H
#define LIBTCOD_VERSION_H
#define TCOD_MAJOR_VERSION 1
#define TCOD_MINOR_VERSION 23
#define TCOD_PATCHLEVEL 1
#define TCOD_STRVERSION "1.23.1"
/**
Converts version numbers into a numeric value.
\rst
(1, 2, 3) -> 0x10203
.. versionadded:: 1.16
\endrst
*/
#define TCOD_VERSIONNUM(major, minor, patch) ((major)*0x010000 + (minor)*0x0100 + (patch))
/**
The version of libtcod currently being compiled.
\rst
.. versionadded:: 1.16
\endrst
*/
#define TCOD_COMPILEDVERSION TCOD_VERSIONNUM(TCOD_MAJOR_VERSION, TCOD_MINOR_VERSION, TCOD_PATCHLEVEL)
/**
\rst
.. deprecated:: 1.16
\endrst
*/
#define TCOD_HEXVERSION TCOD_COMPILEDVERSION
/**
\rst
.. deprecated:: 1.16
\endrst
*/
#define TCOD_TECHVERSION (TCOD_HEXVERSION * 0x100)
/**
\rst
.. deprecated:: 1.16
\endrst
*/
#define TCOD_STRVERSIONNAME "libtcod " TCOD_STRVERSION
/***************************************************************************
@brief Returns true if the compiled version of libtcod is at least (major, minor).
\rst
.. versionadded:: 1.19
\endrst
*/
#define TCOD_VERSION_ATLEAST(major, minor) (TCOD_COMPILEDVERSION >= TCOD_VERSIONNUM(major, minor, 0))
#endif /* LIBTCOD_VERSION_H */

Some files were not shown because too many files have changed in this diff Show more