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

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,64 @@
cmake_minimum_required (VERSION 3.13...3.21)
if(NOT DEFINED CMAKE_TOOLCHAIN_FILE)
set(CMAKE_TOOLCHAIN_FILE
"${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake"
CACHE STRING "Vcpkg toolchain file")
endif()
file(STRINGS src/libtcod/version.h LIBTCOD_VERSION_LINE REGEX "TCOD_STRVERSION")
string(REGEX MATCH "TCOD_STRVERSION \"([^\"]+)\"" LIBTCOD_VERSION_LINE ${LIBTCOD_VERSION_LINE})
set(LIBTCOD_VERSION_FULL ${CMAKE_MATCH_1})
string(REGEX MATCH "([0-9]+\.[0-9]+\.[0-9]+)" LIBTCOD_VERSION ${LIBTCOD_VERSION_FULL})
message(STATUS "Libtcod version: ${LIBTCOD_VERSION}")
project(
libtcod
VERSION ${LIBTCOD_VERSION}
LANGUAGES C CXX
)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake OPTIONAL RESULT_VARIABLE CONAN_FILE)
if(CONAN_FILE)
conan_basic_setup(TARGETS)
endif()
if(NOT CMAKE_INSTALL_BINDIR)
set(CMAKE_INSTALL_BINDIR "bin" CACHE STRING "")
endif()
if(NOT CMAKE_INSTALL_LIBDIR)
set(CMAKE_INSTALL_LIBDIR "lib" CACHE STRING "")
endif()
if(NOT CMAKE_INSTALL_DATAROOTDIR)
set(CMAKE_INSTALL_DATAROOTDIR "share" CACHE STRING "")
endif()
if(NOT CMAKE_INSTALL_INCLUDEDIR)
set(CMAKE_INSTALL_INCLUDEDIR "include" CACHE STRING "")
endif()
if(NOT CMAKE_ARCHIVE_OUTPUT_DIRECTORY)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib")
endif()
if(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin")
endif()
if(NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin")
endif()
set(LIBTCOD_SAMPLES OFF CACHE BOOL "Build sources from the samples directory.")
set(LIBTCOD_TESTS OFF CACHE BOOL "Build unit tests.")
add_library(${PROJECT_NAME})
add_library(${PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
add_subdirectory(src)
set(VCPKG_MANIFEST_NO_DEFAULT_FEATURES ON)
if(LIBTCOD_SAMPLES)
add_subdirectory(samples)
endif()
if(LIBTCOD_TESTS)
add_subdirectory(tests)
list(APPEND VCPKG_MANIFEST_FEATURES "tests")
endif()

View file

@ -0,0 +1,101 @@
# Issue Reporting / Suggestions
The easiest way to help is to provide feedback using the
[GitHub issues](https://github.com/libtcod/libtcod/issues) page.
Most of libtcod's tasks are organized here.
Python specific issues should go to the [python-tcod issues page](https://github.com/libtcod/python-tcod/issues).
# Documentation
The current setup for doc generation is by using
[Breathe](https://breathe.readthedocs.io/en/latest/) to add
[Sphinx](https://www.sphinx-doc.org/en/master/) directives for
[Doxygen](https://www.doxygen.nl/index.html)'s documentation style.
The [docs](docs) directory has instructions on how to build the documentation.
This isn't strictly necessary, but it can help with larger documentation tasks.
Newer C/C++ documentation on functions should generally try to follow this format:
```c
/***************************************************************************
@brief [Brief summary]
@details [Extended description]
@param value Description of parameter.
@return Description of the return value if any.
@code{.cpp}
// Code example if necessary.
@endcode
\rst
.. versionadded:: Unreleased
\endrst
*/
int example(int value);
```
Functions which are expected to always be documented are the public functions in headers, and the static functions in sources.
# Building libtcod for Development
The easiest and recommended build method is to use the Visual Studio Code with the CMake Tools extension.
This automates a significant portion of the build process.
Code formatting is handled via [clang-format](https://clang.llvm.org/docs/ClangFormat.html)
and [EditorConfig](https://editorconfig.org/), make sure your IDE supports these tools.
## Visual Studio Code
This is the common setup for developing libtcod on Windows. It should also work on all platforms.
Dependencies are installed using Vcpkg and CMake is invoked by Visual Studio Code.
* Install [Visual Studio Community](https://visualstudio.microsoft.com/vs/community/)'s desktop C++
* Install [Visual Studio Code](https://code.visualstudio.com/).
* Install [LLVM](https://releases.llvm.org/download.html) and make sure it's added to your PATH.
* Clone the libtcod repository and its submodules.
* In Visual Studio Code choose `File -> Open folder...` then select the libtcod repository.
* Install the extensions recommended for this workspace.
* CMake Tools will ask permission to configure the project, select yes.
* When CMake Tools asks for a kit, the recommended option is: `Visual Studio Community 2019 Release - amd64`
* When CMake Tools asks for a launch target. Scroll down and pick `samples_cpp`.
The status bar at the bottom of Visual Studio Code can be used to configure CMake Tools.
You can now run the samples project from the IDE. Other launch targets like
`samples_c` or `unittest` may be useful choices.
If you set `libtcod` as the build target you could check libtcod for compile errors without having to build and run the samples too.
## MacOS / Linux
For MacOS and Linux you should be able to compile libtcod easily from the
command line. See the instructions in the relevant [buildsys](buildsys) subfolder.
Some compilation methods, including SCons (Windows, Linux, MacOS) and Autotools (Linux, MacOS), are located within the `buildsys/` subdirectory.
SCons automatically downloads SDL2 and can be used on all platforms.
Instructions are [provided here](https://github.com/libtcod/libtcod/tree/master/buildsys/scons).
The current release builds are built using SCons.
Autotools is a common standard on Linux, and can be used for MacOS.
Instructions are [provided here](https://github.com/libtcod/libtcod/tree/master/buildsys/autotools).
## CMake
The libtcod repository includes a CMake script for compiling libtcod and its tests and samples.
You can include the repository as a submodule allowing another project to build and run any version of libtcod.
By default it is assumed that Vcpkg will be used to get dependencies, but this can be changed by setting the following cache variables.
`find_package` means CMake's `find_package` command will be used.
`vendored` means that sources bundled in the repository will be statically compiled, this is generally not recommended.
`conan` and `vcpkg` means that package manager specific scripts are used to link these dependencies.
`disable` can be used to ignore a library, but functions which require that library will no longer function.
| Cache Variable | Default | Options | Notes |
| ---------------- | ------------ | ------- | ----- |
| LIBTCOD_SDL2 | find_package | conan, disable, find_package | Support for libtcod contexts.
| LIBTCOD_ZLIB | find_package | conan, disable, find_package | Support for REXPaint and TCODZip.
| LIBTCOD_LODEPNG | find_package | disable, find_package, vendored |
| LIBTCOD_UTF8PROC | vcpkg | disable, find_package, vcpkg | Support for console printing functions.
| LIBTCOD_STB | find_package | find_package, vendored |
| LIBTCOD_THREADS | false | bool | Support for deprecated functions, leave this off.

View file

@ -0,0 +1,47 @@
Products :
- zlib 1.2.8, by Jean-loup Gailly and Mark Adler
http://www.zlib.org
- lodepng 20160501, by Lode Vandevenne
http://lodev.org/lodepng
- SDL 2, by Sam Lantinga
http://www.libsdl.org
- stb_truetype, authored from 2009-2016 by Sean Barrett / RAD Game Tools
http://github.com/nothings/stb
- utf8proc
https://github.com/JuliaStrings/utf8proc
(modified to be statically linkable, and to compile for C89)
Many thanks to everyone who provided feedback and patches, and especially :
- Dominik 'Mingos' Marczuk for the restrictive shadow casting fov, dijkstra
pathfinding, name generator, documentation skin, lots of bitmap fonts and
being the #1 libtcod user, supporter and contributor.
- Joao 'Jotaf' Henriques for his long time support, priceless comments and
suggestions and the awesome Python tutorial.
- Chris 'donblas' Hamons for libtcod-net, the cmake system, the swig wrappers...
- Jonathon Duerig for the permissive field of view algorithm
- dividee for polishing and optimizing the Python wrapper.
- John Klimek for the early C# port and valuable bug fixes.
- Kyle 'HexDecimal' Benesch & Emmanuel 'Altefcat' Dempuré for their contribution
to the Python port.
- Antagonist for the awesome SkyFire GLSL roguelike engine, hence libtcod's GLSL
renderer
- Sandman for various tricky bug fixes.
- Joe Osborn for the OSX port, bug fixes and the bresenham 3d routines (still
to be backported from the old 1.5 branch...).
- Paul Sexton for the common Lisp wrapper.
- Bernard Helyer for the D wrapper.
- Adam 'Blinks' Blinkinsop for the OSX port and the autotools compilation system.
- Nick Glauber for being the first libtcod Paypal sponsor.
- Matt Sullivan for the py3k support
- namor for the FreeBSD cmake support
- Anylo for putting some of the demos in the cmake compilation
- Michael De Rosa, Killer_X and Joe Rumsey for their work on OSX port
- Denis Belov for fixes on the heightmap toolkit
- owners of projects using libtcod.
Fonts :
The celtic garamond and dundalk fonts are from 1001freefonts.com.
The caeldera font is from blambot.com.
Other fonts are included in windows.
The celtic_garamond, arial, courier, dejavu, consolas, prestige and lucida 10x10/12x12 bitmap fonts were created by Mingos.

View file

@ -0,0 +1,30 @@
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.

View file

@ -0,0 +1,94 @@
# Introduction
libtcod is a free, fast, portable and uncomplicated API for roguelike developers providing a true color console, pathfinding, field-of-view, and a few other utilities frequently used in roguelikes.
Status:
[![Build status](https://ci.appveyor.com/api/projects/status/pemepxo2221f8heo/branch/master?svg=true)](https://ci.appveyor.com/project/HexDecimal/libtcod-6e1jk/branch/master)
[![Build Status](https://travis-ci.org/libtcod/libtcod.svg?branch=master)](https://travis-ci.org/libtcod/libtcod)
[![Documentation Status](https://readthedocs.org/projects/libtcod/badge/?version=latest)](https://libtcod.readthedocs.io/en/latest/?badge=latest)
[![codecov](https://codecov.io/gh/libtcod/libtcod/branch/develop/graph/badge.svg?token=pmHy3jXemj)](https://codecov.io/gh/libtcod/libtcod)
# How do I get set up?
## Using Vcpkg
This is the easiest way to get the latest stable version of libtcod for any project.
Libtcod is included as a port in [Vcpkg](https://github.com/microsoft/vcpkg).
You can install libtcod via Vcpkg and then link the library using a [CMake](https://cmake.org/) script as you normally do for that package manager.
## As a submodule
This is the best option for testing the development versions of libtcod.
You can include libtcod in a project by adding the libtcod repository as a [submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules) and then adding that directory to a [CMake](https://cmake.org/) script.
You will want to fork [this template project](https://github.com/HexDecimal/libtcod-vcpkg-template) if you plan on starting a project with this setup.
It is expected that Vcpkg will be used, but libtcod's CMake script can be configured to compile without using Vcpkg for dependencies.
See [CONTRIBUTING.md](CONTRIBUTING.md) for details on configuring dependencies.
## Using one of our downloads
This is not recommend as these releases are unwieldy, are more difficult to update, and are less cross-platform.
*Do not upload binary files to your projects source repository.*
If you are programming in C or C++ then
Windows and MacOS binaries are available from the
[GitHub Releases page](https://github.com/libtcod/libtcod/releases).
Various C/C++ sample projects are included within
the repository which can be used as examples of various features.
Keep in mind that as a C++ library, you may need to distribute the
appropriate runtime with your program such as the
[Visual Studio 2015 runtimes](https://www.microsoft.com/en-us/download/details.aspx?id=53587)
or else the program will fail to run.
For those who wish to program in Python you can install python-tcod using
[this installation guide](https://python-tcod.readthedocs.io/en/latest/installation.html).
Once installed you can follow
[the Python 3 tutorial](http://rogueliketutorials.com/)
or you can find Python example scripts on the
[python-tcod repository](https://github.com/libtcod/python-tcod).
A alternative version of the Python library (libtcodpy) exists in the binary
downloads, but you should avoid using this version as it is not as well
maintained.
## Compiling from source
This is only recommended for libtcod developers.
See [CONTRIBUTING.md](CONTRIBUTING.md).
# Getting Started
The latest documentation is [here](https://libtcod.readthedocs.io/en/latest).
Currently it's very incomplete, so most people will want to read the
[1.6.4 documentation](https://libtcod.github.io/docs/index2.html?c=true&cpp=true&cs=false&py=false&lua=false)
instead.
Python users should use the
[python-tcod documentation](http://python-tcod.readthedocs.io).
libtcod comes with a sample application, implementations of which are provided
in each of
C ([samples_c.c](https://github.com/libtcod/libtcod/blob/master/samples/samples_c.c)),
C++ ([samples_cpp.cpp](https://github.com/libtcod/libtcod/blob/master/samples/samples_cpp.cpp)),
and Python ([samples_py.py](https://github.com/libtcod/python-tcod/blob/master/examples/samples_tcod.py)).
This provides a decent overview of the basic features, in an interactive
fashion.
Each should be identical for the most part, so if you are using Windows,
downloading the pre-compiled binaries and running the included `samples.exe`
which is compiled from the C source code, should be representative of the other
versions.
# Contact / Community
For reporting bugs or requesting features you should use the [GitHub Issues page](https://github.com/libtcod/libtcod/issues).
For smaller questions or help with a tutorial or project you can join ``#libtcod`` on the [Roguelikes Discord](https://discord.gg/jEgZtqB) or on the [Libera.Chat](https://libera.chat/) IRC.
# Sponsors
[Sponsors donating $25 or more per month](https://github.com/sponsors/HexDecimal) will have their names or logos listed here.
* [q00u](https://github.com/q00u)
* [amaya30](https://github.com/amaya30)

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,43 @@
myStruct "struct_name" {
//
bool_field=true
char_field='Z'
int_field=24
float_field=3.14
string_field="hello"
color_field="255,128,128"
dice_field="0.5x3d5+2"
// dynamically declared fields
bool bool_field2=false
char char_field2='@'
int int_field2=4
float float_field2=4.3
string string_field2="world"
color color_field2=#FF22CC
dice dice_field2="3d20"
bool_list=[true, false, true]
char_list=['a', 'b', 'z']
integer_list=[13,2,-3]
float_list=[5.0,2.0,-3.5]
string_list=["item one","time_two"]
color_list=["42,42,142","128,64,128"]
// dice_list=["3d4","2d4+2","0.75x4d6-1"]
// dynamically declared list fields
bool[] bool_list2=[true, false, true]
char[] char_list2=['a', 'b', 'z']
int[] integer_list2=[13,2,-3]
float[] float_list2=[5.0,2.0,-3.5]
string[] string_list2=["item one","time_two"]
color[] color_list2=["42,42,142","128,64,128"]
}
// a completely dynamic structure (not declared at compile time)
struct dynStruct {
int someVar=4
struct subStruct {
float anotherVar=4.3
}
}

View file

@ -0,0 +1,148 @@
/*
* Pyromancer ! configuration file, used for regression tests.
*/
config {
debug=true // enable some debug/cheat stuff
multithread=false // enable background threads
// uncomment to force the number of background threads
// threadPoolSize = 1
display {
wallColor=#ABABAB
groundColor=#E4E4E4
memoryWallColor=#331100
playerLightRange=15
playerLightColor=#FF7722 // player light at level 1
playerLightColorEnd=#990000 // player light at last level
// messages config
messageLife=5.0 // how many time a message is displayed
debugColor=#AAAAAA
infoColor=#FFFF72
warnColor=#FF9F00
criticalColor=#FF0000
fadeTime=0.8
fireSpeed=5.0 // for intro/end screen
corpseColor=#888888
// flash when the player is hit
hitFlashDelay=0.2
flashColor=#FF0000
// amulet light properties
treasureLightRange=15
treasureLightColor=#888844
treasureIntensityDelay=0.6
treasureIntensityPattern="979897989798"
finalExplosionTime=5.0
}
spells {
fireball {
lightColor=#FF7700
trailLength=1
speed=0.3 // cells per second
sparkLife=0.4 // in seconds
sparkleLife=1.4 // in seconds
sparkleSpeed=0.5 // cells/seconds
standardLife=1.2 // in seconds
baseRange=1.0
baseDamage=1
stunDelay=1.0 // in seconds
}
}
fog {
maxLevel=1.0
scale=5.0
octaves=3.0
speed=1.0
color=#000000
}
creatures {
burnDamage=1.0 // hp per second
pathDelay=1.0 // seconds between path computation for a creature
player {
char='@'
color=#FFFFFF
speed=8.0 // cells per second. x2 when sprinting
sprintLength=5.0 // in seconds
sprintRecovery=10.0 // in seconds
rangeAccommodation=5.0 // in seconds
maxPathFinding=20 // cancel pathfinding if path too long
healRate=2.0 // health points per second
healIntensityDelay=15.0
healIntensityPattern="noise"
longButtonDelay=0.3
longSpellDelay=1.0
// keyboard movement config. Only letter/number keys allowed.
// Arrows, numpad, vi-keys, WASD always work
moveUpKey='Z'
moveDownKey='S'
moveLeftKey='Q'
moveRightKey='D'
// quickslot shortcuts
// (should correspond to main keyboard 1-0 keys)
// qwerty layout
quickslot1='1'
quickslot2='2'
quickslot3='3'
quickslot4='4'
quickslot5='5'
quickslot6='6'
quickslot7='7'
quickslot8='8'
quickslot9='9'
quickslot10='0'
// azerty layout
/*
quickslot1='&'
quickslot2='<27>'
quickslot3='\"'
quickslot4='\''
quickslot5='('
quickslot6='-'
quickslot7='<27>'
quickslot8='_'
quickslot9='<27>'
quickslot10='<27>'
*/
}
minion {
char='m'
color=#BBFF55
life=10
speed=6.0 // cells per second
damage=2.0 // hp per second when at melee range
}
boss {
char='Z'
color=#FF8800
life=2500
speed=4.0 // cells per second
secureDist=16 // try to keep squared distance to player above this value
secureCoef=3.0
summonTime=10.0 // time to summon minions
minionCount=10 // how many minions are summoned
}
}
gameplay {
timeScale=1.0 // time scale. Increase to increase game speed
nbLevels=8 // number of levels
dungeonMinSize=80 // size of dungeon at level 1
dungeonMaxSize=200 // size of dungeon at last level
darknessLevel=50 // if light r+g+b < darknessLevel, creatures not seen
penumbraLevel=100 // if light r+g+b < penumbraLevel, creatures seen as ?
}
ai_director {
waveLength=30.0 // in seconds
lowLevel=0.2 // no creatures below this level
medLevel=0.8
medRate=20 // creatures per minute
highRate=50 // creatures per minute
hordeDelay=120 // horde attack every 2 minutes
maxCreatures=100
spawnSourceRange=10 // spawn source covers an area of 10x10
distReplace=40 // if creature is too far from player, move it closer
itemKillCount=30 // item dropped every 30 creatures
}
}

View file

@ -0,0 +1,56 @@
# Libtcod font examples
This directory contains some example fonts for libtcod.
These fonts are generally free to use, but the license for the `terminal` tilesets has not been accounted for correctly.
## Tilesets
Tilesets are a smaller collection of glyphs arranged in a specific layout, usually [Code Page 437](https://en.wikipedia.org/wiki/Code_page_437).
All standard Code Page 437 tilesets are loaded with the following call:
```cpp
auto tileset = tcod::load_tilesheet("path/to/tileset.png", {32, 32}, tcod::CHARMAP_CP437);
```
Libtcod is able to load tilesets from the [Dwarf Fortress Tileset Repository](https://dwarffortresswiki.org/Tileset_repository) with the above extra configuration.
It also supports all the tilesets from [this tileset browser](https://extended-ascii-viewer.herokuapp.com/).
The file names in this directory are composed with:
```
<font_name><font_size>_<type>_<layout>.png
<type> : gs 8-bit or less greyscale PNG
<layout> : ro standard Code Page 437 layout in standard row-major order
tc Deprecated TCOD layout
```
## BDF
Libtcod also supports BDF files.
These fonts usually have decent Unicode support.
BDF files can be loaded in libtcod with the following call:
```cpp
auto tileset = tcod::load_bdf("path/to/font.bdf");
```
You can find BDF's in various places.
Recommended fonts are:
[Unicode fonts for X11](https://www.cl.cam.ac.uk/~mgk25/ucs-fonts.html),
[Cozette](https://github.com/slavfox/Cozette),
[Tamzen](https://github.com/sunaku/tamzen-font),
and [Envypn](https://github.com/Sorixelle/envypn-powerline).
## TrueType Font
TrueType font files are aliased and have good Unicode support.
Tilesets can be generated from TTF files using a tool like [Typesheet](https://github.com/graysonchao/typesheet).
There is limited support for loading TTF files in libtcod.
*This experimental function is provisional and may change in the future:*
```cpp
TCOD_Tileset* tileset = TCOD_load_truetype_font_("path/to/font.ttf", 20, 10); // 20 pixels high, half-width glyphs.
TCOD_Tileset* tileset = TCOD_load_truetype_font_("path/to/font.ttf", 20, 20); // 20 pixels high, monospaced glyphs.
```
To get the most of a TTF you should regenerate the tileset with a size closely matching your tile size whenever the window is resized.
Otherwise you'll get scaling artifacts from the font being rendered at a low resolution and then scaled up.

File diff suppressed because it is too large Load diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 322 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View file

@ -0,0 +1,70 @@
/*
* Collections of syllables and other data used for name generation.
*
* All the strings must be enclosed between quotation marks, with no semicolon
* at the end.
*
* SYLLABLE SETS:
* Please use only latin characters, apostrophes and dashes for syllables. All
* other characters will be treated as separators between syllables, eg. "ish"
* and "is'h" are syllables, but "|sh" and "ish!" aren't (the erroneous
* syllables will be read as "sh" and "ish", respectively). If you wish to use
* a special character, please write it after a slash, eg. a semicolon will need
* to be written as "/;" in order to be correctly parsed. Beware: a slash at the
* end of a string will not trigger an error whatsoever, but the final syllable
* will not be added to the list at all. Spaces are a special case: they can be
* triggered either with the above method, or with a single underscore: "\ " and
* "_" are both valid and will produce a space.
*
* PHONEME SETS:
* Phoneme sets should be single characters or digraphs. Please use lowercase
* characters only. "ch" and "tz" are valid consonants, but "Ch" or "trz" are
* not. They will be rejected upon generating phoneme lists.
*
* RULES:
* These denote how a word is generated. A rule is a string consisting of
* normal characters [a-z,A-Z,',-], special characters preceded by a slash (see
* the notes concerning syllables), underscores to denote spaces and wildcards.
* Wildcards are preceded by a dollar sign. Here's the full list:
* "$P" - a random Pre syllable
* "$s" - a random Start syllable
* "$m" - a random Middle syllable
* "$e" - a random End syllable
* "$p" - a random Post syllable
* "$v" - a random vocal
* "$c" - a random consonant
* "$?" - a random phoneme
* So, if we hav the following data:
* syllablesStart = "Ivan"
* syllablesEnd = "Terrible"
* rules = "$s_the_$e"
* the generator will output "Ivan the Terrible".
* The wildcards may also include an integer number. This number marks the per
* cent chance of actually appearing the related wildcard has. The number is
* placed after the asterisk, but before the corresponding character. For
* instance, "*50m" means "50% chance of adding a Middle syllable".
* If multiple rules are specified, they should be separated by characters that
* are not special character or wildcard indicators. A comma is a legible
* separator.
* A rule may be preceded by a special wildcard consisting of a per cent sign
* "%" and an integer number. This means the per cent chance of picking this
* rule should the RNG encounter it. For instance, if two rules are specified,
* each will have 50% chance of being chosen. However, if one of them is
* preceded by the "%50" sign, it will actually have a 100/2*50% = 25% chance of
* being selected (100/2 is the initial chance any single rule from a set of two
* will be picked, for five rules this would be 100/5, etc.).
* The rules are a mandatory field. Also, any field thai it references are to be
* included as well, lest it produce errors or, in the best of cases, generate
* an empty syllable as output.
*
* Don't get paranoid about controlling whether the syllables are repeated. The
* program will ignore repeated entries anyway. This applies to phonemes too.
*
* Please make sure you have enough syllables specified to ensure variety in the
* generated names. A string with 512 characters should be sufficient in most
* cases. Anything below that is a risk of making the names predictable.
*
* I hope this little tool is both fun and useful for you. Take care!
*
* -Mingos
*/

View file

@ -0,0 +1,15 @@
//Celtic names from Jice's "The Cave"
name "Celtic male" {
syllablesStart = "Aen, Agno, All, Ba, Beo, Brig, Ci, Cre, Dan, Del, Ela, Eo, En, Er, Et, In, Io, Morr, Nem, Nu, Og, Or, Ta"
syllablesMiddle = "a, ar, ba, bo, ch, d, ig"
syllablesEnd = "aid, ain, an, and, th, ed, eth, gus, lam, lor, man, od, t, thach"
rules = "$s$m$e, $s$e"
}
name "Celtic female" {
syllablesStart = "Aen, Agno, All, Ba, Beo, Brig, Ci, Cre, Dan, Del, Ela, Eo, En, Er, Et, In, Io, Morr, Nem, Nu, Og, Or, Ta"
syllablesMiddle = "a, ar, ba, bo, ch, d, ig"
syllablesEnd = "ai, an, da, id, iu, ma, me, na, ne, tha"
rules = "$s$m$e, $s$e"
}

View file

@ -0,0 +1,17 @@
//Fantasy names from Jice's "The Cave"
name "Fantasy male" {
syllablesStart = "Aer, An, Ar, Ban, Bar, Ber, Beth, Bett, Cut, Dan, Dar, Dell, Der, Edr, Er, Eth, Ett, Fin, Ian, Iarr, Ill, Jed, Kan, Kar, Ker, Kurr, Kyr, Man, Mar, Mer, Mir, Tsal, Tser, Tsir, Van, Var, Yur, Yyr"
syllablesMiddle = "al, an, ar, el, en, ess, ian, onn, or"
syllablesEnd = "ai, an, ar, ath, en, eo, ian, is, u, or"
illegal = "orar, arrar"
rules = "$s$m$e, $s$e"
}
name "Fantasy female" {
syllablesStart = "Aer, An, Ar, Ban, Bar, Ber, Beth, Bett, Cut, Dan, Dar, Dell, Der, Edr, Er, Eth, Ett, Fin, Ian, Iarr, Ill, Jed, Kan, Kar, Ker, Kurr, Kyr, Man, Mar, Mer, Mir, Tsal, Tser, Tsir, Van, Var, Yur, Yyr"
syllablesMiddle = "al, an, ar, el, en, ess, ian, onn, or"
syllablesEnd = "a, ae, aelle, ai, ea, i, ia, u, wen, wyn"
illegal = "arrar"
rules = "$s$m$e, $s$e"
}

View file

@ -0,0 +1,17 @@
//Mesopotamian names from Jice's "The Cave"
name "Mesopotamian male" {
syllablesStart = "A, Ann, Ash, E', En, Er, Gil, In, Ir, Ish, Mar, Ni, Nin, Re, Ti, Ur"
syllablesMiddle = "am, an, du, esh, gam, gir, ka, ki, li, un, ur, ta"
syllablesEnd = "aki, al, ar, at, du, eph, esh, il, im, ki, nu, uk, ur, uz"
illegal = "aa, e'e"
rules = "$s$m$e, $s$e"
}
name "Mesopotamian female" {
syllablesStart = "A, Ann, Ash, E', En, Er, Gil, In, Ir, Ish, Mar, Ni, Nin, Re, Ti, Ur"
syllablesMiddle = "am, an, du, esh, gam, gir, ka, ki, li, un, ur, ta"
syllablesEnd = "ag, il, la, na, sag, su, ta"
illegal = "aa, e'e"
rules = "$s$m$e, $s$e"
}

View file

@ -0,0 +1,17 @@
//Norse names from Jice's "The Cave"
name "Norse male" {
syllablesStart = "Al, Ae, As, Bi, Fen, Ha, Hag, Ho, Hu, Iv, Jot, Ma, Mio, Mu, Nid, Ors, Ra, Sta, Svar, Tys, Vae, Van, Vol, Y, Ygg"
syllablesMiddle = "an, ar, ba, da, dra, gar, na, tal"
syllablesEnd = "ad, ald, agr, ar, ard, eyr, far, frost, heim, hogg, in, mir, nar, nir, or, osk, rir, sil, sir, ttir, urd"
illegal = "yor, yar, yad, yin"
rules = "$s$m$e, $s$e"
}
name "Norse female" {
syllablesStart = "Al, Ae, As, Bi, Fen, Ha, Hag, Ho, Hu, Iv, Jot, Ma, Mio, Mu, Nid, Ors, Ra, Sta, Svar, Tys, Vae, Van, Vol, Y, Ygg"
syllablesMiddle = "an, ar, ba, da, dra, gar, na, tal"
syllablesEnd = "a, la, li, va"
illegal = "raa, ya, aea, aea"
rules = "$s$m$e, $s$e"
}

View file

@ -0,0 +1,7 @@
//Region names from Jice's "The Cave"
name "region" {
syllablesStart = "Act, Afr, Ag, Agr, Alb, Am, An, Angl, Ant, As, Asys, Asis, At, Atl, Brund, Cath, Cor, Dan, Eb, Eg, Er, Esc, Esp, Est, Eth, Eur, Flor, It, Lyr, Mal, Mir, Myr, Nor, Pel, Rom, Seg, Sib, Sylv, Terr, Tir, Tr, Tyr, Xan"
syllablesMiddle = "ad, ag, al, an, and, ant, anth, ar, ard, as, at, atr, eg, en, ent, ern, et, ian, in, itr, on, op, ov, ur, ymn, yr"
syllablesEnd = "a, aia, ana, as, ea, ene, eos, esia, ia, iad, ias, is, ium, ius, on, ona, or, ova, um, us, ya"
rules = "$s$m$e, $s$e"
}

View file

@ -0,0 +1,6 @@
//Town names from Jice's "The Cave"
name "town" {
syllablesStart = "Ael, Ash, Barrow, Bel, Black, Clear, Cold, Crystal, Deep, Edge, Falcon, Fair, Fall, Glass, Gold, Ice, Iron, Mill, Moon, Mor, Ray, Red, Rock, Rose, Shadow, Silver, Spell, Spring, Stone, Strong, Summer, Swyn, Wester, Winter"
syllablesEnd = "ash, burn, barrow, bridge, castle, cliff, coast, crest, dale, dell, dor, fall, field, ford, fort, gate, haven, hill, hold, hollow, iron, lake, marsh, mill, mist, mount, moor, pond, shade, shore, summer, town, wick"
rules = "$s$e"
}

View file

@ -0,0 +1,16 @@
//Demon names
name "demon male" {
phonemesVocals = "a, e, i, o, u"
syllablesStart = "Aam, Ab, Ad, Ahr, Alas, Al-A'w, All, Al-M, Ap, As, Ast, Az, Bal, Bal S, Bag, Balb, Ban, Bansh, Baph, Barb, Bath, Bazt, Be'L, Beel, Beelz, Bel, Belph, Ber, Bh, Bifr, Biul, Bush, Caac, Cagn, Caim, Chalk, Char, Chem, Coal, Dag, Dant, Decer, Demog, Dev, Dj, Dragh, Elig, Emp, Errt, Etr, Ett, Eur, Euryn, Gorg, Graph, Grig, Haag, Halph, Haur, Hoeth, Ifr, Inc, Ibl, Ith, Kabh, Kas, Kokb', Kray, Lab, Lam, Lech, Leg, Lil, Lioth, Lix, Luc, Mal, Malph, Mamm, March, Mast, Math, Meph, Merm, Mol, Murm, Naam, Naph, Nek, Neph, Neq, Nix, Noud, Onom, Onos, Orc, Orob, Oul, Paim, Phen, Pont, Proc, Rah, Rak, Raksh, Ram, Rang, Raum, Raz, Rimm, Rub, Rus, Sabn, Salps, Sam, Sat, Sc, Scarm, Seer, Sem, Set, Shait, Shax, Shed, Shez, Sidr, Sitr, Sth, Succ, Surg, Tann, Tart, Tch, Teer, Thamm, Thub, Tlal, Tsab, Val, Vap, Vass, Vep, Verr, Vin, Vol, Vual, Xaph, Xiph, Xitr, Zaeb, Zim, Ziz, Zaln"
syllablesMiddle = "b'ae, ba, be, chi, dra, du, ga, ghi, go, lia, ma, mba, mu, n'e, na, nti, nzu, phe, pho, r'e, rba, rgo, ssa, thi, tryu, ttu, tzi, v-e, vna, xra, ya"
syllablesEnd = "b'ael, bel, bub, bur, bus, ces, chus, dai, ddon, des, dhaka, el, fer, flas, gion, gon, gor, klet, kor, ksha, kuth, laas, lech, les, lion, lith, loch, lsu, mael, math, mejes, meus, mon, moth, mmut, mosh, nai, nar, neus, nex, nias, nnin, nomos, phas, r'el, raal, rept, res, rgon, riax, rith, rius, rous, rus, ruth, sias, stor, swath, tath, than, the, thra, tryus, tura, vart, ztuk"
rules = "$s$v$35m$10m$e"
}
name "demon female" {
phonemesVocals = "a, e, i, o, u"
syllablesStart = "Aam, Ab, Ad, Ahr, Alas, Al-A'w, All, Al-M, Ap, As, Ast, Az, Bal, Bal S, Bag, Balb, Ban, Bansh, Baph, Barb, Bath, Bazt, Be'L, Beel, Beelz, Bel, Belph, Ber, Bh, Bifr, Biul, Bush, Caac, Cagn, Caim, Chalk, Char, Chem, Coal, Dag, Dant, Decer, Demog, Dev, Dj, Dragh, Elig, Emp, Errt, Etr, Ett, Eur, Euryn, Gorg, Graph, Grig, Haag, Halph, Haur, Hoeth, Ifr, Inc, Ibl, Ith, Kabh, Kas, Kokb', Kray, Lab, Lam, Lech, Leg, Lil, Lioth, Lix, Luc, Mal, Malph, Mamm, March, Mast, Math, Meph, Merm, Mol, Murm, Naam, Naph, Nek, Neph, Neq, Nix, Noud, Onom, Onos, Orc, Orob, Oul, Paim, Phen, Pont, Proc, Rah, Rak, Raksh, Ram, Rang, Raum, Raz, Rimm, Rub, Rus, Sabn, Salps, Sam, Sat, Sc, Scarm, Seer, Sem, Set, Shait, Shax, Shed, Shez, Sidr, Sitr, Sth, Succ, Surg, Tann, Tart, Tch, Teer, Thamm, Thub, Tlal, Tsab, Val, Vap, Vass, Vep, Verr, Vin, Vol, Vual, Xaph, Xiph, Xitr, Zaeb, Zim, Ziz, Zaln"
syllablesMiddle = "b'ae, ba, be, chi, dra, du, ga, ghi, go, lia, ma, mba, mu, n'e, na, nti, nzu, phe, pho, r'e, rba, rgo, ssa, thi, tryu, ttu, tzi, v-e, vna, xra, ya"
syllablesEnd = "b'a, bel, bua, bure, buth, cess, chia, dai, ddea, dea, dhaka, el, fea, fla, gia, goa, gora, klath, kore, ksha, kua, laal, lexa, less, lia, lith, loth, lsa, mara, math, maja, mea, moa, moth, mmuth, mosh, na, nai, neuth, nex, nia, nnine, nomoa, pha, r'el, raala, repte, reshe, rgona, riaxe, rith, rish, rothe, rushe, ruth, sia, stora, swath, tath, thann, the, thra, trya, tura, varte, ztura"
rules = "$s$v$35m$10m$e"
}

View file

@ -0,0 +1,29 @@
//dwarf names
name "dwarf male" {
syllablesStart = "A, An, Ba, Bi, Bo, Bom, Da, Dar, De, Do, Du, Due, Duer, Dwa, Fa, Fal, Fi, Fre, Fun, Ga, Gar, Gim, Glo, Go, Gom, Gro, Gwar, Ib, Jor, Ka, Ki, Kil, Lo, Mar, Na, Nal, O, Ras, Ren, Ro, Ta, Tar, Tel, Thi, Tho, Thon, Thra, Tor, Von, We, Wer, Yen, Yur"
syllablesEnd = "bil, bin, bur, char, den, dir, dur, fri, fur, in, li, lin, mil, mur, ni, nur, ran, ri, ril, rimm, rin, thur, tri, ulf, un, ur, vi, vil, vim, vin, vri"
rules = "$s$e"
illegal = "rur, ueu"
}
name "dwarf female" {
syllablesStart = "A, An, Ba, Bi, Bo, Bom, Da, Dar, De, Do, Du, Due, Duer, Dwa, Fa, Fal, Fi, Fre, Fun, Ga, Gar, Gim, Glo, Go, Gom, Gro, Gwar, Ib, Jor, Ka, Ki, Kil, Lo, Mar, Na, Nal, O, Ras, Ren, Ro, Ta, Tar, Tel, Thi, Tho, Thon, Thra, Tor, Von, We, Wer, Yen, Yur"
syllablesEnd = "al, ali, ba, bida, bra, da, deth, di, fra, gret, hild, iess, kala, la, laani, li, lona, ma, mae, mala, na, nuda, ra, ta, tala, tu, tuna, vada, vara, ya"
rules = "$s$e"
illegal = "dueal, frefra, grogret"
}
//surnames have semantic information. Here, they're separated into three
//somewhat coherent sets and either is chosen
name "dwarf surname" {
//1st set - smith & Mr.Muscle surnames
syllablesPre = "Boulder, Bronze, Coal, Copper, Gem, Granite, Hammer, Iron, Marble, Metal, Rock, Steel, Stone, Thunder"
syllablesPost = "bender, breaker, carver, club, crusher, cutter, digger, fist, foot, forger, heart, smasher, smith"
//2nd set - warrior surnames
syllablesStart = "Bear, Boar, Dragon, Giant, Goblin, Elf, Ettin, Foe, Kobold, Ogre, Orc,Spider, Troll, Wolf"
syllablesEnd = "bane, basher, _Battler, _Beheader, boxer, _Butcher, choker, cleaver, crusher, cutter, doom, eater, _Executioner, _Fighter, _Garrotter, grapple, _Gutter, hammer, killer, mauler, masher, ripper, slasher, slayer, slicer, smasher, _Strangler, striker, _Wrestler"
//3rd set - heroic and general
phonemesVocals = "Black, Blood, Bronze, Fire, Firm, Grey, Hard, Ice, Iron, Moon, Oak, Onyx, Red, Steel, Stone, Strong, Thunder, White"
phonemesConsonants = "axe, beard, blade, brand, cheek, fist, foot, hair, hammer, hand, head, heart, pick, shield, spear, spike, sword"
rules = "$P$p, $s$e, $v$c"
}

View file

@ -0,0 +1,19 @@
//Norse names. Most of them are syllables extracted from names that
//actually appear in Norse written texts. Norse names consist of two parts,
//which is easy to reflect in a generator such as this one.
name "Mingos Norse male" {
//these are ready-made names
syllablesPre = "Aunn, Bjoern, Bjolfr, Bjorr, Boltr, Byulfr, Erik, Erpr, Eykr, Feitr, Fotr, Froekn, Gaukr, Gauss, Gils, Gimp, Griss, Gyi, Haegwin, Haengr, Hakon, Hand, Harekr, Hattr, Haukr, Helf, Hjalli, Hjaerne, Hjarrandi, Hnaki, Hneitr, Hrafn, Jarl, Karl, Kar-Toki, Kaun, Kilfisr, Kiuli, Knut, Knutr, Krakr, Leifr, Lokki, Manni, Mar, Moegr, Naemr, Nagli, Nef-Bjoern, Njall, Oelfun, Oenn, Oern, Rafn, Roki, Skjalf, Skog, Spjall, Sveinn, Tannr, Trani, Trjonn, Utryggr, Vagn, Varg, Ve-Finnr, Voettr, Vragi, Vrai"
//and these are syllables to stick together
syllablesStart = "Ab, Adal, Adi, Alf, An, And, Ans, Arn, Arm, Ask, Au, Audh, Ba, Bae, Bag, Bal, Bar, Bas, Bein, Berg, Bern, Bjad, Bjarn, Bjart, Boan, Boed, Boerk, Bogg, Bor, Bot, Bram, Bran, Bratt, Brei, Bro, Brunn, Bukk, Dag, Djur, Dor, Duf, Dun, Ed, Ei, Ein, Ekk, Ey, Fa, Fad, Fal, Far, Fast, Fen, Finn, Fjall, Fjoel, Flae, Fol, Folk, Foest, Frey, Frid, Frost, Ful, Fuld, Gaes, Geir, Gag, Gal, Gam, Gar, Gaut, Geir, Ginn, Gis, Gjaf, Gjal, God, Gnaudi, Gny, Gret, Grim, Grom, Grum, Gud, Gull, Gunn, Gutt, Gyll, Gyr, Ha, Haf, Hag, Hagn, Half, Hall, Ham, Har, Haur, Hedin, Hef, Heg, Heil, Hein, Hel, Hildi, Hjall, Hjalm, Hjoer, Hlif, Hloed, Hoeg, Hoegg, Hoer, Hoes, Hol, Holm, Hord, Horn, Hrad, Hrafn, Hring, Hroeng, Hross, Hug, Hul, Hum, Hus, Hvit, Hyr, Igul, Illu, In, Ingi, Is, Ja, Jar, Jarn, Jat, Jo, Joefur, Kjoet, Kol, Kon, Lamb, Lids, Lik, Ljot, Lyd, Nadd, Nef, Odal, Odd, Oeg, Oel, Oen, Oeng, Oes, Rad, Rafn, Ragn, Rask, Reid, Reyr, Roegn, Rok, Run, Sae, Sig, Skae, Skjald, Skjoeld, Skol, Slag, Snae, Soel, Soend, Spjall, Stafn, Stark, Stein, Stig, Stod, Stygg, Styr, Sunn, Svein, Svart, Svarta, Tid, Tindr, Tjoer, Trygg, Tyr, Thyr, Ud, Ulf, Yngv, Vae, Val, Varg, Ve, Ved, Vest, Vetr, Vid, Vig, Vik"
syllablesEnd = "adr, afr, all, andi, arfr, arr, astr, autr, bi, beinn, bert, bjoern, bodi, bodr, bori, brandr, burinn, burt, daenni, dan, di, din, diarfr, dinn, dr, dridr, dur, eifr, eirr, fast, fasti, fastr, fidr, fill, fing, fingr, finnr, fli, fri, frimr, fuss, gall, geir, geirr, gils, gir, gisl, glir, glumr, grimr, gripr, gur, guri, haldr, hegn, hjalmr, hjoefr, hjofr, hoefdi, hoess, hofdi, horir, horr, hoess, hvatr, ilir, ill, ingr, inn, jadr, jarn, jarr, jartan, jartr, joern, jofr, karl, kell, ketill, kirr, kuldr, kull, kundr, kunnr, laugr, lan, leifr, leikr, li, lidi, lidr, lingr, madr, maer, mann, marr, mingr, modr, mr, mund, mundr, nall, narr, nefr, nir, niutr, olfr, ormr, phorr, pli, r, raeifr, radr, rik, rikr, ring, rinn, rir, roedr, rudr, rukr, si, sir, skegg, skeggi, sjall, steinn, styrr, sur, tir, tyr, utr, ulf, ulfr, undr, ungr, urd, urdr, valdr, vandi, vandill, veinr, ver, vett, vi, vidr, vifr, vind, vindr, vi, vini, vir, visl"
rules = "$s$e, %10$P"
illegal = "bjarnbj, gp, vv, aea, aee, aeo, drd"
}
name "Mingos Norse female" {
syllablesStart = "A, Aer, Aerin, Aes, Aet, Afri, Agaer, Ager, Al, Alf, Alm, Arinn, Arn, As, Au, Aud, Bau, Be, Beg, Berg, Bir, Bjol, Bod, Bol, Bor, Borg, Bot, Bri, Brun, Bryn, Bus, Dag, Dis, Dom, Dor, Dot, Dri, Dyr, Ed, Ei, Em, Emb, Engil, Er, Es, Ev, Ey, Fal, Fast, Fin, Fjol, Fjor, Fjot, Folk, Frey, Frid, Frost, Gaut, Geir, Ger, Gil, Ginn, Gis, Gjaf, Gre, Grim, Gud, Gy, Gyd, Haf, Hall, Haur, Hedin, Heil, Heim, Hel, Her, Hidin, Hil, Hildi, Hjalm, Hjor, Hlad, Hlif, Holm, Hrim, Hrod, Hun, Igul, In, Ingi, Ingil, Is, Jar, Jo, Jofur, Jor, Jut, Ljuf, Lofn, Mal, Malm, Mar, Mat, Matt, Mund, Nid, Odd, Ol, Olm, Ot, Rad, Ragn, Rand, Rann, Regin, Run, Sal, Sae, Sig, Skjald, Sol, Stein, Svan, Svein, Tid, Ulf, Vet, Val, Ve, Vig, Vil, Yng"
syllablesEnd = "bjorg, borg, da, dis, disa, disla, dora, eida, erna, fasta, finna, frida, frosta, fura, ga, gard, gauta, geid, gerda, gida, gret, grid, grima, gudr, gunn, gunna, heidr, hilda, ja, la, laug, lina, linn, ma, maer, rida, run, ta, trid, trida, truda, unn, ve, velda, vi, vilda, vina"
illegal = "ii, iei, edeid, tg, ee, vev"
rules = "$s$e"
}

View file

@ -0,0 +1,17 @@
//Names based on syllables from J.R.R. Tolkien's and David Eddings' novels.
name "male" {
phonemesVocals = "a, e, i, o, u, y"
phonemesConsonants = "b, c, ch, ck, cz, d, dh, f, g, gh, h, j, k, kh, l, m, n, p, ph, q, r, rh, s, sh, t, th, ts, tz, v, w, x, z, zh"
syllablesStart = "Aer, Al, Am, An, Ar, Arm, Arth, B, Bal, Bar, Be, Bel, Ber, Bok, Bor, Bran, Breg, Bren, Brod, Cam, Chal, Cham, Ch, Cuth, Dag, Daim, Dair, Del, Dr, Dur, Duv, Ear, Elen, Er, Erel, Erem, Fal, Ful, Gal, G, Get, Gil, Gor, Grin, Gun, H, Hal, Han, Har, Hath, Hett, Hur, Iss, Khel, K, Kor, Lel, Lor, M, Mal, Man, Mard, N, Ol, Radh, Rag, Relg, Rh, Run, Sam, Tarr, T, Tor, Tul, Tur, Ul, Ulf, Unr, Ur, Urth, Yar, Z, Zan, Zer"
syllablesMiddle = "de, do, dra, du, duna, ga, go, hara, kaltho, la, latha, le, ma, nari, ra, re, rego, ro, rodda, romi, rui, sa, to, ya, zila"
syllablesEnd = "bar, bers, blek, chak, chik, dan, dar, das, dig, dil, din, dir, dor, dur, fang, fast, gar, gas, gen, gorn, grim, gund, had, hek, hell, hir, hor, kan, kath, khad, kor, lach, lar, ldil, ldir, leg, len, lin, mas, mnir, ndil, ndur, neg, nik, ntir, rab, rach, rain, rak, ran, rand, rath, rek, rig, rim, rin, rion, sin, sta, stir, sus, tar, thad, thel, tir, von, vor, yon, zor"
rules = "$s$v$35m$10m$e"
}
name "female" {
phonemesVocals = "a, e, i, o, u, y"
syllablesStart = "Ad, Aer, Ar, Bel, Bet, Beth, Ce'N, Cyr, Eilin, El, Em, Emel, G, Gl, Glor, Is, Isl, Iv, Lay, Lis, May, Ner, Pol, Por, Sal, Sil, Vel, Vor, X, Xan, Xer, Yv, Zub"
syllablesMiddle = "bre, da, dhe, ga, lda, le, lra, mi, ra, ri, ria, re, se, ya"
syllablesEnd = "ba, beth, da, kira, laith, lle, ma, mina, mira, na, nn, nne, nor, ra, rin, ssra, ta, th, tha, thra, tira, tta, vea, vena, we, wen, wyn"
rules = "$s$v$35m$10m$e"
}

View file

@ -0,0 +1,9 @@
//Town names. The town name construction is based on real British town names,
//although many starting syllables are made up.
name "Mingos town" {
syllablesPre = "East, Fort, Great, High, Lower, Middle, Mount, New, North, Old, Royal, Saint, South, Upper, West"
syllablesStart = "Ales, Apple, Ash, Bald, Bay, Bed, Bell, Birdling, Black, Blue, Bow, Bran, Brass, Bright, Brown, Bruns, Bulls, Camp, Cherry, Clark, Clarks, Clay, Clear, Copper, Corn, Cross, Crystal, Dark, Deep, Deer, Drac, Eagle, Earth, Elk, Elles, Elm, Ester, Ewes, Fair, Falcon, Ferry, Fire, Fleet, Fox, Gold, Grand, Green, Grey, Guild, Hammer, Hart, Hawks, Hay, Haze, Hazel, Hemlock, Ice, Iron, Kent, Kings, Knox, Layne, Lint, Lor, Mable, Maple, Marble, Mare, Marsh, Mist, Mor, Mud, Nor, Oak, Orms, Ox, Oxen, Pear, Pine, Pitts, Port, Purple, Red, Rich, Roch, Rock, Rose, Ross, Rye, Salis, Salt, Shadow, Silver, Skeg, Smith, Snow, Sows, Spring, Spruce, Staff, Star, Steel, Still, Stock, Stone, Strong, Summer, Swan, Swine, Sword, Yellow, Val, Wart, Water, Well, Wheat, White, Wild, Winter, Wolf, Wool, Wor"
syllablesEnd = "bank, borne, borough, brook, burg, burgh, bury, castle, cester, cliff, crest, croft, dale, dam, dorf, edge, field, ford, gate, grad, hall, ham, hollow, holm, hurst, keep, kirk, land, ley, lyn, mere, mill, minster, mont, moor, mouth, ness, pool, river, shire, shore, side, stead, stoke, ston, thorpe, ton, town, vale, ville, way, wich, wick, wood, worth"
syllablesPost = "Annex, Barrens, Barrow, Corner, Cove, Crossing, Dell, Dales, Estates, Forest, Furnace, Grove, Haven, Heath, Hill, Junction, Landing, Meadow, Park, Plain, Point, Reserve, Retreat, Ridge, Springs, View, Village, Wells, Woods"
rules = "$15P_$s$e_$15p"
}

Binary file not shown.

Binary file not shown.

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

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