Committing Everything!

This commit is contained in:
Brian Buller 2015-03-18 11:58:14 -05:00
parent 96176db3df
commit e2d331db6b
74 changed files with 13196 additions and 0 deletions

3
compile.sh Executable file
View File

@ -0,0 +1,3 @@
#!/bin/bash
g++ src/*.cpp -o tuto -Iinclude -L. -ltcod -ltcodxx -Wl,-rpath=. -Wall -w

55
include/bresenham.h Normal file
View File

@ -0,0 +1,55 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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
typedef bool (*TCOD_line_listener_t) (int x, int y);
TCODLIB_API void TCOD_line_init(int xFrom, int yFrom, int xTo, int yTo);
TCODLIB_API bool TCOD_line_step(int *xCur, int *yCur); /* advance one step. returns true if we reach destination */
/* 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);
/* thread-safe versions */
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 *xCur, int *yCur, TCOD_bresenham_data_t *data);
TCODLIB_API bool TCOD_line_mt(int xFrom, int yFrom, int xTo, int yTo, TCOD_line_listener_t listener, TCOD_bresenham_data_t *data);
#endif

138
include/bresenham.hpp Normal file
View File

@ -0,0 +1,138 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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
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);
};
#endif

63
include/bsp.h Normal file
View File

@ -0,0 +1,63 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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
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 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();
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_t randomizer, int nb,
int minHSize, int minVSize, float maxHRatio, float maxVRatio);
TCODLIB_API void TCOD_bsp_remove_sons(TCOD_bsp_t *node);
#endif

406
include/bsp.hpp Normal file
View File

@ -0,0 +1,406 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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_HPP
#define _TCOD_BSP_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 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 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) {}
/**
@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 splitted 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 choosen :
@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 splitted 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 splitted 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 level; // level in the tree
...
}
@C
typedef struct {
int x,y,w,h;
int position;
bool horizontal;
uint8 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 splitted 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 (TCODBsp *)sons;
}
TCODBsp *getRight() const {
return sons ? (TCODBsp *)(sons->next) : NULL;
}
TCODBsp *getFather() const {
return (TCODBsp *)father;
}
/**
@PageName bsp_read
@FuncTitle Checking if a node is a leaf
@FuncDesc You can know if a node is a leaf (not splitted, 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

322
include/color.h Normal file
View File

@ -0,0 +1,322 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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
typedef struct {
uint8 r,g,b;
} TCOD_color_t;
/* constructors */
TCODLIB_API TCOD_color_t TCOD_color_RGB(uint8 r, uint8 g, uint8 b);
TCODLIB_API TCOD_color_t TCOD_color_HSV(float h, float s, float v);
/* 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);
/* HSV transformations */
TCODLIB_API void TCOD_color_set_HSV (TCOD_color_t *c,float h, float s, float v);
TCODLIB_API void TCOD_color_get_HSV (TCOD_color_t c,float * h, float * s, float * v);
TCODLIB_API float TCOD_color_get_hue (TCOD_color_t c);
TCODLIB_API void TCOD_color_set_hue (TCOD_color_t *c, float h);
TCODLIB_API float TCOD_color_get_saturation (TCOD_color_t c);
TCODLIB_API void TCOD_color_set_saturation (TCOD_color_t *c, float s);
TCODLIB_API float TCOD_color_get_value (TCOD_color_t c);
TCODLIB_API void TCOD_color_set_value (TCOD_color_t *c, float v);
TCODLIB_API void TCOD_color_shift_hue (TCOD_color_t *c, float hshift);
TCODLIB_API void TCOD_color_scale_HSV (TCOD_color_t *c, float scoef, float vcoef);
/* color map */
TCODLIB_API void TCOD_color_gen_map(TCOD_color_t *map, int nb_key, TCOD_color_t const *key_color, int const *key_index);
/* color names */
enum {
TCOD_COLOR_RED,
TCOD_COLOR_FLAME,
TCOD_COLOR_ORANGE,
TCOD_COLOR_AMBER,
TCOD_COLOR_YELLOW,
TCOD_COLOR_LIME,
TCOD_COLOR_CHARTREUSE,
TCOD_COLOR_GREEN,
TCOD_COLOR_SEA,
TCOD_COLOR_TURQUOISE,
TCOD_COLOR_CYAN,
TCOD_COLOR_SKY,
TCOD_COLOR_AZURE,
TCOD_COLOR_BLUE,
TCOD_COLOR_HAN,
TCOD_COLOR_VIOLET,
TCOD_COLOR_PURPLE,
TCOD_COLOR_FUCHSIA,
TCOD_COLOR_MAGENTA,
TCOD_COLOR_PINK,
TCOD_COLOR_CRIMSON,
TCOD_COLOR_NB
};
/* color levels */
enum {
TCOD_COLOR_DESATURATED,
TCOD_COLOR_LIGHTEST,
TCOD_COLOR_LIGHTER,
TCOD_COLOR_LIGHT,
TCOD_COLOR_NORMAL,
TCOD_COLOR_DARK,
TCOD_COLOR_DARKER,
TCOD_COLOR_DARKEST,
TCOD_COLOR_LEVELS
};
/* color array */
extern TCODLIB_API const TCOD_color_t TCOD_colors[TCOD_COLOR_NB][TCOD_COLOR_LEVELS];
/* grey levels */
extern TCODLIB_API const TCOD_color_t TCOD_black;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_grey;
extern TCODLIB_API const TCOD_color_t TCOD_darker_grey;
extern TCODLIB_API const TCOD_color_t TCOD_dark_grey;
extern TCODLIB_API const TCOD_color_t TCOD_grey;
extern TCODLIB_API const TCOD_color_t TCOD_light_grey;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_grey;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_grey;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_gray;
extern TCODLIB_API const TCOD_color_t TCOD_darker_gray;
extern TCODLIB_API const TCOD_color_t TCOD_dark_gray;
extern TCODLIB_API const TCOD_color_t TCOD_gray;
extern TCODLIB_API const TCOD_color_t TCOD_light_gray;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_gray;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_gray;
extern TCODLIB_API const TCOD_color_t TCOD_white;
/* sepia */
extern TCODLIB_API const TCOD_color_t TCOD_darkest_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_darker_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_dark_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_light_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_sepia;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_sepia;
/* standard colors */
extern TCODLIB_API const TCOD_color_t TCOD_red;
extern TCODLIB_API const TCOD_color_t TCOD_flame;
extern TCODLIB_API const TCOD_color_t TCOD_orange;
extern TCODLIB_API const TCOD_color_t TCOD_amber;
extern TCODLIB_API const TCOD_color_t TCOD_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_lime;
extern TCODLIB_API const TCOD_color_t TCOD_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_green;
extern TCODLIB_API const TCOD_color_t TCOD_sea;
extern TCODLIB_API const TCOD_color_t TCOD_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_sky;
extern TCODLIB_API const TCOD_color_t TCOD_azure;
extern TCODLIB_API const TCOD_color_t TCOD_blue;
extern TCODLIB_API const TCOD_color_t TCOD_han;
extern TCODLIB_API const TCOD_color_t TCOD_violet;
extern TCODLIB_API const TCOD_color_t TCOD_purple;
extern TCODLIB_API const TCOD_color_t TCOD_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_pink;
extern TCODLIB_API const TCOD_color_t TCOD_crimson;
/* dark colors */
extern TCODLIB_API const TCOD_color_t TCOD_dark_red;
extern TCODLIB_API const TCOD_color_t TCOD_dark_flame;
extern TCODLIB_API const TCOD_color_t TCOD_dark_orange;
extern TCODLIB_API const TCOD_color_t TCOD_dark_amber;
extern TCODLIB_API const TCOD_color_t TCOD_dark_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_dark_lime;
extern TCODLIB_API const TCOD_color_t TCOD_dark_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_dark_green;
extern TCODLIB_API const TCOD_color_t TCOD_dark_sea;
extern TCODLIB_API const TCOD_color_t TCOD_dark_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_dark_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_dark_sky;
extern TCODLIB_API const TCOD_color_t TCOD_dark_azure;
extern TCODLIB_API const TCOD_color_t TCOD_dark_blue;
extern TCODLIB_API const TCOD_color_t TCOD_dark_han;
extern TCODLIB_API const TCOD_color_t TCOD_dark_violet;
extern TCODLIB_API const TCOD_color_t TCOD_dark_purple;
extern TCODLIB_API const TCOD_color_t TCOD_dark_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_dark_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_dark_pink;
extern TCODLIB_API const TCOD_color_t TCOD_dark_crimson;
/* darker colors */
extern TCODLIB_API const TCOD_color_t TCOD_darker_red;
extern TCODLIB_API const TCOD_color_t TCOD_darker_flame;
extern TCODLIB_API const TCOD_color_t TCOD_darker_orange;
extern TCODLIB_API const TCOD_color_t TCOD_darker_amber;
extern TCODLIB_API const TCOD_color_t TCOD_darker_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_darker_lime;
extern TCODLIB_API const TCOD_color_t TCOD_darker_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_darker_green;
extern TCODLIB_API const TCOD_color_t TCOD_darker_sea;
extern TCODLIB_API const TCOD_color_t TCOD_darker_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_darker_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_darker_sky;
extern TCODLIB_API const TCOD_color_t TCOD_darker_azure;
extern TCODLIB_API const TCOD_color_t TCOD_darker_blue;
extern TCODLIB_API const TCOD_color_t TCOD_darker_han;
extern TCODLIB_API const TCOD_color_t TCOD_darker_violet;
extern TCODLIB_API const TCOD_color_t TCOD_darker_purple;
extern TCODLIB_API const TCOD_color_t TCOD_darker_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_darker_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_darker_pink;
extern TCODLIB_API const TCOD_color_t TCOD_darker_crimson;
/* darkest colors */
extern TCODLIB_API const TCOD_color_t TCOD_darkest_red;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_flame;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_orange;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_amber;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_lime;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_green;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_sea;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_sky;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_azure;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_blue;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_han;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_violet;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_purple;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_pink;
extern TCODLIB_API const TCOD_color_t TCOD_darkest_crimson;
/* light colors */
extern TCODLIB_API const TCOD_color_t TCOD_light_red;
extern TCODLIB_API const TCOD_color_t TCOD_light_flame;
extern TCODLIB_API const TCOD_color_t TCOD_light_orange;
extern TCODLIB_API const TCOD_color_t TCOD_light_amber;
extern TCODLIB_API const TCOD_color_t TCOD_light_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_light_lime;
extern TCODLIB_API const TCOD_color_t TCOD_light_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_light_green;
extern TCODLIB_API const TCOD_color_t TCOD_light_sea;
extern TCODLIB_API const TCOD_color_t TCOD_light_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_light_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_light_sky;
extern TCODLIB_API const TCOD_color_t TCOD_light_azure;
extern TCODLIB_API const TCOD_color_t TCOD_light_blue;
extern TCODLIB_API const TCOD_color_t TCOD_light_han;
extern TCODLIB_API const TCOD_color_t TCOD_light_violet;
extern TCODLIB_API const TCOD_color_t TCOD_light_purple;
extern TCODLIB_API const TCOD_color_t TCOD_light_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_light_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_light_pink;
extern TCODLIB_API const TCOD_color_t TCOD_light_crimson;
/* lighter colors */
extern TCODLIB_API const TCOD_color_t TCOD_lighter_red;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_flame;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_orange;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_amber;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_lime;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_green;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_sea;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_sky;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_azure;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_blue;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_han;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_violet;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_purple;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_pink;
extern TCODLIB_API const TCOD_color_t TCOD_lighter_crimson;
/* lightest colors */
extern TCODLIB_API const TCOD_color_t TCOD_lightest_red;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_flame;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_orange;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_amber;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_lime;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_green;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_sea;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_sky;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_azure;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_blue;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_han;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_violet;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_purple;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_pink;
extern TCODLIB_API const TCOD_color_t TCOD_lightest_crimson;
/* desaturated */
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_red;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_flame;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_orange;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_amber;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_yellow;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_lime;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_chartreuse;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_green;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_sea;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_turquoise;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_cyan;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_sky;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_azure;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_blue;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_han;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_violet;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_purple;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_fuchsia;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_magenta;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_pink;
extern TCODLIB_API const TCOD_color_t TCOD_desaturated_crimson;
/* metallic */
extern TCODLIB_API const TCOD_color_t TCOD_brass;
extern TCODLIB_API const TCOD_color_t TCOD_copper;
extern TCODLIB_API const TCOD_color_t TCOD_gold;
extern TCODLIB_API const TCOD_color_t TCOD_silver;
/* miscellaneous */
extern TCODLIB_API const TCOD_color_t TCOD_celadon;
extern TCODLIB_API const TCOD_color_t TCOD_peach;
#endif

690
include/color.hpp Normal file
View File

@ -0,0 +1,690 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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
// 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 r,g,b;
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)
*/
TCODColor(uint8 r, uint8 g, uint8 b): r(r), g(g), b(b) {}
TCODColor(int r, int g, int b): r(r), g(g), b(b) {}
TCODColor(const TCOD_color_t &col): r(col.r), g(col.g), b(col.b) {}
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 != litbcod.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 (c.r != r || c.g != g || c.b != b);
}
/**
@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 & a) const {
TCODColor ret;
ret.r=(uint8)(((int)r)*a.r/255);
ret.g=(uint8)(((int)g)*a.g/255);
ret.b=(uint8)(((int)b)*a.b/255);
return ret;
}
/**
@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 = litbcod.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 {
TCOD_color_t ret;
int r,g,b;
r = (int)(this->r * value);
g = (int)(this->g * value);
b = (int)(this->b * value);
r = CLAMP(0,255,r);
g = CLAMP(0,255,g);
b = CLAMP(0,255,b);
ret.r=(uint8)r;
ret.g=(uint8)g;
ret.b=(uint8)b;
return ret;
}
/**
@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 & a) const {
TCODColor ret;
int r=(int)(this->r)+a.r;
int g=(int)(this->g)+a.g;
int b=(int)(this->b)+a.b;
r = MIN(255,r);
g = MIN(255,g);
b = MIN(255,b);
ret.r=(uint8)r;
ret.g=(uint8)g;
ret.b=(uint8)b;
return ret;
}
/**
@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 & a) const {
TCODColor ret;
int r=(int)(this->r)-a.r;
int g=(int)(this->g)-a.g;
int b=(int)(this->b)-a.b;
r = MAX(0,r);
g = MAX(0,g);
b = MAX(0,b);
ret.r=(uint8)r;
ret.g=(uint8)g;
ret.b=(uint8)b;
return ret;
}
/**
@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, litbcod.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 &a, const TCODColor &b, float coef) {
TCODColor ret;
ret.r=(uint8)(a.r+(b.r-a.r)*coef);
ret.g=(uint8)(a.g+(b.g-a.g)*coef);
ret.b=(uint8)(a.b+(b.b-a.b)*coef);
return ret;
}
/**
@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);
// color array
static const TCODColor colors[TCOD_COLOR_NB][TCOD_COLOR_LEVELS];
// grey levels
static const TCODColor black;
static const TCODColor darkestGrey;
static const TCODColor darkerGrey;
static const TCODColor darkGrey;
static const TCODColor grey;
static const TCODColor lightGrey;
static const TCODColor lighterGrey;
static const TCODColor lightestGrey;
static const TCODColor white;
//sepia
static const TCODColor darkestSepia;
static const TCODColor darkerSepia;
static const TCODColor darkSepia;
static const TCODColor sepia;
static const TCODColor lightSepia;
static const TCODColor lighterSepia;
static const TCODColor lightestSepia;
// standard colors
static const TCODColor red;
static const TCODColor flame;
static const TCODColor orange;
static const TCODColor amber;
static const TCODColor yellow;
static const TCODColor lime;
static const TCODColor chartreuse;
static const TCODColor green;
static const TCODColor sea;
static const TCODColor turquoise;
static const TCODColor cyan;
static const TCODColor sky;
static const TCODColor azure;
static const TCODColor blue;
static const TCODColor han;
static const TCODColor violet;
static const TCODColor purple;
static const TCODColor fuchsia;
static const TCODColor magenta;
static const TCODColor pink;
static const TCODColor crimson;
// dark colors
static const TCODColor darkRed;
static const TCODColor darkFlame;
static const TCODColor darkOrange;
static const TCODColor darkAmber;
static const TCODColor darkYellow;
static const TCODColor darkLime;
static const TCODColor darkChartreuse;
static const TCODColor darkGreen;
static const TCODColor darkSea;
static const TCODColor darkTurquoise;
static const TCODColor darkCyan;
static const TCODColor darkSky;
static const TCODColor darkAzure;
static const TCODColor darkBlue;
static const TCODColor darkHan;
static const TCODColor darkViolet;
static const TCODColor darkPurple;
static const TCODColor darkFuchsia;
static const TCODColor darkMagenta;
static const TCODColor darkPink;
static const TCODColor darkCrimson;
// darker colors
static const TCODColor darkerRed;
static const TCODColor darkerFlame;
static const TCODColor darkerOrange;
static const TCODColor darkerAmber;
static const TCODColor darkerYellow;
static const TCODColor darkerLime;
static const TCODColor darkerChartreuse;
static const TCODColor darkerGreen;
static const TCODColor darkerSea;
static const TCODColor darkerTurquoise;
static const TCODColor darkerCyan;
static const TCODColor darkerSky;
static const TCODColor darkerAzure;
static const TCODColor darkerBlue;
static const TCODColor darkerHan;
static const TCODColor darkerViolet;
static const TCODColor darkerPurple;
static const TCODColor darkerFuchsia;
static const TCODColor darkerMagenta;
static const TCODColor darkerPink;
static const TCODColor darkerCrimson;
// darkest colors
static const TCODColor darkestRed;
static const TCODColor darkestFlame;
static const TCODColor darkestOrange;
static const TCODColor darkestAmber;
static const TCODColor darkestYellow;
static const TCODColor darkestLime;
static const TCODColor darkestChartreuse;
static const TCODColor darkestGreen;
static const TCODColor darkestSea;
static const TCODColor darkestTurquoise;
static const TCODColor darkestCyan;
static const TCODColor darkestSky;
static const TCODColor darkestAzure;
static const TCODColor darkestBlue;
static const TCODColor darkestHan;
static const TCODColor darkestViolet;
static const TCODColor darkestPurple;
static const TCODColor darkestFuchsia;
static const TCODColor darkestMagenta;
static const TCODColor darkestPink;
static const TCODColor darkestCrimson;
// light colors
static const TCODColor lightRed;
static const TCODColor lightFlame;
static const TCODColor lightOrange;
static const TCODColor lightAmber;
static const TCODColor lightYellow;
static const TCODColor lightLime;
static const TCODColor lightChartreuse;
static const TCODColor lightGreen;
static const TCODColor lightSea;
static const TCODColor lightTurquoise;
static const TCODColor lightCyan;
static const TCODColor lightSky;
static const TCODColor lightAzure;
static const TCODColor lightBlue;
static const TCODColor lightHan;
static const TCODColor lightViolet;
static const TCODColor lightPurple;
static const TCODColor lightFuchsia;
static const TCODColor lightMagenta;
static const TCODColor lightPink;
static const TCODColor lightCrimson;
//lighter colors
static const TCODColor lighterRed;
static const TCODColor lighterFlame;
static const TCODColor lighterOrange;
static const TCODColor lighterAmber;
static const TCODColor lighterYellow;
static const TCODColor lighterLime;
static const TCODColor lighterChartreuse;
static const TCODColor lighterGreen;
static const TCODColor lighterSea;
static const TCODColor lighterTurquoise;
static const TCODColor lighterCyan;
static const TCODColor lighterSky;
static const TCODColor lighterAzure;
static const TCODColor lighterBlue;
static const TCODColor lighterHan;
static const TCODColor lighterViolet;
static const TCODColor lighterPurple;
static const TCODColor lighterFuchsia;
static const TCODColor lighterMagenta;
static const TCODColor lighterPink;
static const TCODColor lighterCrimson;
// lightest colors
static const TCODColor lightestRed;
static const TCODColor lightestFlame;
static const TCODColor lightestOrange;
static const TCODColor lightestAmber;
static const TCODColor lightestYellow;
static const TCODColor lightestLime;
static const TCODColor lightestChartreuse;
static const TCODColor lightestGreen;
static const TCODColor lightestSea;
static const TCODColor lightestTurquoise;
static const TCODColor lightestCyan;
static const TCODColor lightestSky;
static const TCODColor lightestAzure;
static const TCODColor lightestBlue;
static const TCODColor lightestHan;
static const TCODColor lightestViolet;
static const TCODColor lightestPurple;
static const TCODColor lightestFuchsia;
static const TCODColor lightestMagenta;
static const TCODColor lightestPink;
static const TCODColor lightestCrimson;
// desaturated colors
static const TCODColor desaturatedRed;
static const TCODColor desaturatedFlame;
static const TCODColor desaturatedOrange;
static const TCODColor desaturatedAmber;
static const TCODColor desaturatedYellow;
static const TCODColor desaturatedLime;
static const TCODColor desaturatedChartreuse;
static const TCODColor desaturatedGreen;
static const TCODColor desaturatedSea;
static const TCODColor desaturatedTurquoise;
static const TCODColor desaturatedCyan;
static const TCODColor desaturatedSky;
static const TCODColor desaturatedAzure;
static const TCODColor desaturatedBlue;
static const TCODColor desaturatedHan;
static const TCODColor desaturatedViolet;
static const TCODColor desaturatedPurple;
static const TCODColor desaturatedFuchsia;
static const TCODColor desaturatedMagenta;
static const TCODColor desaturatedPink;
static const TCODColor desaturatedCrimson;
// metallic
static const TCODColor brass;
static const TCODColor copper;
static const TCODColor gold;
static const TCODColor silver;
// miscellaneous
static const TCODColor celadon;
static const TCODColor peach;
};
TCODLIB_API TCODColor operator *(float value, const TCODColor &c);
#endif

125
include/console.h Normal file
View File

@ -0,0 +1,125 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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 "console_types.h"
#define TCOD_BKGND_ALPHA(alpha) ((TCOD_bkgnd_flag_t)(TCOD_BKGND_ALPH|(((uint8)(alpha*255))<<8)))
#define TCOD_BKGND_ADDALPHA(alpha) ((TCOD_bkgnd_flag_t)(TCOD_BKGND_ADDA|(((uint8)(alpha*255))<<8)))
typedef void * TCOD_console_t;
TCODLIB_API void TCOD_console_init_root(int w, int h, const char * title, bool fullscreen, TCOD_renderer_t renderer);
TCODLIB_API void TCOD_console_set_window_title(const char *title);
TCODLIB_API void TCOD_console_set_fullscreen(bool fullscreen);
TCODLIB_API bool TCOD_console_is_fullscreen();
TCODLIB_API bool TCOD_console_is_window_closed();
TCODLIB_API bool TCOD_console_has_mouse_focus();
TCODLIB_API bool TCOD_console_is_active();
TCODLIB_API void TCOD_console_set_custom_font(const char *fontFile, int flags,int nb_char_horiz, int nb_char_vertic);
TCODLIB_API void TCOD_console_map_ascii_code_to_font(int asciiCode, int fontCharX, int fontCharY);
TCODLIB_API void TCOD_console_map_ascii_codes_to_font(int asciiCode, int nbCodes, int fontCharX, int fontCharY);
TCODLIB_API void TCOD_console_map_string_to_font(const char *s, int fontCharX, int fontCharY);
TCODLIB_API void TCOD_console_set_dirty(int x, int y, int w, int h);
TCODLIB_API void TCOD_console_set_default_background(TCOD_console_t con,TCOD_color_t col);
TCODLIB_API void TCOD_console_set_default_foreground(TCOD_console_t con,TCOD_color_t col);
TCODLIB_API void TCOD_console_clear(TCOD_console_t con);
TCODLIB_API void TCOD_console_set_char_background(TCOD_console_t con,int x, int y, TCOD_color_t col, TCOD_bkgnd_flag_t flag);
TCODLIB_API void TCOD_console_set_char_foreground(TCOD_console_t con,int x, int y, TCOD_color_t col);
TCODLIB_API void TCOD_console_set_char(TCOD_console_t con,int x, int y, int c);
TCODLIB_API void TCOD_console_put_char(TCOD_console_t con,int x, int y, int c, TCOD_bkgnd_flag_t flag);
TCODLIB_API void TCOD_console_put_char_ex(TCOD_console_t con,int x, int y, int c, TCOD_color_t fore, TCOD_color_t back);
TCODLIB_API void TCOD_console_set_background_flag(TCOD_console_t con,TCOD_bkgnd_flag_t flag);
TCODLIB_API TCOD_bkgnd_flag_t TCOD_console_get_background_flag(TCOD_console_t con);
TCODLIB_API void TCOD_console_set_alignment(TCOD_console_t con,TCOD_alignment_t alignment);
TCODLIB_API TCOD_alignment_t TCOD_console_get_alignment(TCOD_console_t con);
TCODLIB_API void TCOD_console_print(TCOD_console_t con,int x, int y, const char *fmt, ...);
TCODLIB_API void TCOD_console_print_ex(TCOD_console_t con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...);
TCODLIB_API int TCOD_console_print_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...);
TCODLIB_API int TCOD_console_print_rect_ex(TCOD_console_t con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...);
TCODLIB_API int TCOD_console_get_height_rect(TCOD_console_t con,int x, int y, int w, int h, const char *fmt, ...);
TCODLIB_API void TCOD_console_rect(TCOD_console_t con,int x, int y, int w, int h, bool clear, TCOD_bkgnd_flag_t flag);
TCODLIB_API void TCOD_console_hline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag);
TCODLIB_API void TCOD_console_vline(TCOD_console_t con,int x,int y, int l, TCOD_bkgnd_flag_t flag);
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, ...);
#ifndef NO_UNICODE
/* unicode support */
TCODLIB_API void TCOD_console_map_string_to_font_utf(const wchar_t *s, int fontCharX, int fontCharY);
TCODLIB_API void TCOD_console_print_utf(TCOD_console_t con,int x, int y, const wchar_t *fmt, ...);
TCODLIB_API void TCOD_console_print_ex_utf(TCOD_console_t con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...);
TCODLIB_API int TCOD_console_print_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...);
TCODLIB_API int TCOD_console_print_rect_ex_utf(TCOD_console_t con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...);
TCODLIB_API int TCOD_console_get_height_rect_utf(TCOD_console_t con,int x, int y, int w, int h, const wchar_t *fmt, ...);
#endif
TCODLIB_API TCOD_color_t TCOD_console_get_default_background(TCOD_console_t con);
TCODLIB_API TCOD_color_t TCOD_console_get_default_foreground(TCOD_console_t con);
TCODLIB_API TCOD_color_t TCOD_console_get_char_background(TCOD_console_t con,int x, int y);
TCODLIB_API TCOD_color_t TCOD_console_get_char_foreground(TCOD_console_t con,int x, int y);
TCODLIB_API int TCOD_console_get_char(TCOD_console_t con,int x, int y);
TCODLIB_API void TCOD_console_set_fade(uint8 val, TCOD_color_t fade);
TCODLIB_API uint8 TCOD_console_get_fade();
TCODLIB_API TCOD_color_t TCOD_console_get_fading_color();
TCODLIB_API void TCOD_console_flush();
TCODLIB_API void TCOD_console_set_color_control(TCOD_colctrl_t con, TCOD_color_t fore, TCOD_color_t back);
TCODLIB_API TCOD_key_t TCOD_console_check_for_keypress(int flags);
TCODLIB_API TCOD_key_t TCOD_console_wait_for_keypress(bool flush);
TCODLIB_API void TCOD_console_set_keyboard_repeat(int initial_delay, int interval);
TCODLIB_API void TCOD_console_disable_keyboard_repeat();
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);
TCODLIB_API TCOD_console_t TCOD_console_new(int w, int h);
TCODLIB_API int TCOD_console_get_width(TCOD_console_t con);
TCODLIB_API int TCOD_console_get_height(TCOD_console_t con);
TCODLIB_API void TCOD_console_set_key_color(TCOD_console_t con,TCOD_color_t col);
TCODLIB_API void TCOD_console_blit(TCOD_console_t src,int xSrc, int ySrc, int wSrc, int hSrc, TCOD_console_t dst, int xDst, int yDst, float foreground_alpha, float background_alpha);
TCODLIB_API void TCOD_console_delete(TCOD_console_t console);
TCODLIB_API void TCOD_console_credits();
TCODLIB_API void TCOD_console_credits_reset();
TCODLIB_API bool TCOD_console_credits_render(int x, int y, bool alpha);
#endif

1770
include/console.hpp Normal file

File diff suppressed because it is too large Load Diff

265
include/console_types.h Normal file
View File

@ -0,0 +1,265 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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
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 ralt ;
bool rctrl ;
bool shift ;
} TCOD_key_t;
typedef enum {
/* single walls */
TCOD_CHAR_HLINE=196,
TCOD_CHAR_VLINE=179,
TCOD_CHAR_NE=191,
TCOD_CHAR_NW=218,
TCOD_CHAR_SE=217,
TCOD_CHAR_SW=192,
TCOD_CHAR_TEEW=180,
TCOD_CHAR_TEEE=195,
TCOD_CHAR_TEEN=193,
TCOD_CHAR_TEES=194,
TCOD_CHAR_CROSS=197,
/* double walls */
TCOD_CHAR_DHLINE=205,
TCOD_CHAR_DVLINE=186,
TCOD_CHAR_DNE=187,
TCOD_CHAR_DNW=201,
TCOD_CHAR_DSE=188,
TCOD_CHAR_DSW=200,
TCOD_CHAR_DTEEW=185,
TCOD_CHAR_DTEEE=204,
TCOD_CHAR_DTEEN=202,
TCOD_CHAR_DTEES=203,
TCOD_CHAR_DCROSS=206,
/* blocks */
TCOD_CHAR_BLOCK1=176,
TCOD_CHAR_BLOCK2=177,
TCOD_CHAR_BLOCK3=178,
/* arrows */
TCOD_CHAR_ARROW_N=24,
TCOD_CHAR_ARROW_S=25,
TCOD_CHAR_ARROW_E=26,
TCOD_CHAR_ARROW_W=27,
/* arrows without tail */
TCOD_CHAR_ARROW2_N=30,
TCOD_CHAR_ARROW2_S=31,
TCOD_CHAR_ARROW2_E=16,
TCOD_CHAR_ARROW2_W=17,
/* double arrows */
TCOD_CHAR_DARROW_H=29,
TCOD_CHAR_DARROW_V=18,
/* GUI stuff */
TCOD_CHAR_CHECKBOX_UNSET=224,
TCOD_CHAR_CHECKBOX_SET=225,
TCOD_CHAR_RADIO_UNSET=9,
TCOD_CHAR_RADIO_SET=10,
/* sub-pixel resolution kit */
TCOD_CHAR_SUBP_NW=226,
TCOD_CHAR_SUBP_NE=227,
TCOD_CHAR_SUBP_N=228,
TCOD_CHAR_SUBP_SE=229,
TCOD_CHAR_SUBP_DIAG=230,
TCOD_CHAR_SUBP_E=231,
TCOD_CHAR_SUBP_SW=232,
/* miscellaneous */
TCOD_CHAR_SMILIE = 1,
TCOD_CHAR_SMILIE_INV = 2,
TCOD_CHAR_HEART = 3,
TCOD_CHAR_DIAMOND = 4,
TCOD_CHAR_CLUB = 5,
TCOD_CHAR_SPADE = 6,
TCOD_CHAR_BULLET = 7,
TCOD_CHAR_BULLET_INV = 8,
TCOD_CHAR_MALE = 11,
TCOD_CHAR_FEMALE = 12,
TCOD_CHAR_NOTE = 13,
TCOD_CHAR_NOTE_DOUBLE = 14,
TCOD_CHAR_LIGHT = 15,
TCOD_CHAR_EXCLAM_DOUBLE = 19,
TCOD_CHAR_PILCROW = 20,
TCOD_CHAR_SECTION = 21,
TCOD_CHAR_POUND = 156,
TCOD_CHAR_MULTIPLICATION = 158,
TCOD_CHAR_FUNCTION = 159,
TCOD_CHAR_RESERVED = 169,
TCOD_CHAR_HALF = 171,
TCOD_CHAR_ONE_QUARTER = 172,
TCOD_CHAR_COPYRIGHT = 184,
TCOD_CHAR_CENT = 189,
TCOD_CHAR_YEN = 190,
TCOD_CHAR_CURRENCY = 207,
TCOD_CHAR_THREE_QUARTERS = 243,
TCOD_CHAR_DIVISION = 246,
TCOD_CHAR_GRADE = 248,
TCOD_CHAR_UMLAUT = 249,
TCOD_CHAR_POW1 = 251,
TCOD_CHAR_POW3 = 252,
TCOD_CHAR_POW2 = 253,
TCOD_CHAR_BULLET_SQUARE = 254,
/* diacritics */
} TCOD_chars_t;
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;
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;
typedef enum {
TCOD_KEY_PRESSED=1,
TCOD_KEY_RELEASED=2,
} TCOD_key_status_t;
/* custom font flags */
typedef enum {
TCOD_FONT_LAYOUT_ASCII_INCOL=1,
TCOD_FONT_LAYOUT_ASCII_INROW=2,
TCOD_FONT_TYPE_GREYSCALE=4,
TCOD_FONT_TYPE_GRAYSCALE=4,
TCOD_FONT_LAYOUT_TCOD=8,
} TCOD_font_flags_t;
typedef enum {
TCOD_RENDERER_GLSL,
TCOD_RENDERER_OPENGL,
TCOD_RENDERER_SDL,
TCOD_NB_RENDERERS,
} TCOD_renderer_t;
typedef enum {
TCOD_LEFT,
TCOD_RIGHT,
TCOD_CENTER
} TCOD_alignment_t;
#endif /* _TCOD_CONSOLE_TYPES_H */

58
include/fov.h Normal file
View File

@ -0,0 +1,58 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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
typedef void *TCOD_map_t;
#include "fov_types.h"
/* allocate a new map */
TCODLIB_API TCOD_map_t TCOD_map_new(int width, int height);
/* set all cells as solid rock (cannot see through nor walk) */
TCODLIB_API void TCOD_map_clear(TCOD_map_t map, bool transparent, bool walkable);
/* copy a map to another, reallocating it when needed */
TCODLIB_API void TCOD_map_copy(TCOD_map_t source, TCOD_map_t dest);
/* change a cell properties */
TCODLIB_API void TCOD_map_set_properties(TCOD_map_t map, int x, int y, bool is_transparent, bool is_walkable);
/* destroy a map */
TCODLIB_API void TCOD_map_delete(TCOD_map_t map);
/* calculate the field of view (potentially visible cells from player_x,player_y) */
TCODLIB_API 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);
/* check if a cell is in the last computed field of view */
TCODLIB_API bool TCOD_map_is_in_fov(TCOD_map_t map, int x, int y);
TCODLIB_API void TCOD_map_set_in_fov(TCOD_map_t map, int x, int y, bool fov);
/* retrieve properties from the map */
TCODLIB_API bool TCOD_map_is_transparent(TCOD_map_t map, int x, int y);
TCODLIB_API bool TCOD_map_is_walkable(TCOD_map_t map, int x, int y);
TCODLIB_API int TCOD_map_get_width(TCOD_map_t map);
TCODLIB_API int TCOD_map_get_height(TCOD_map_t map);
TCODLIB_API int TCOD_map_get_nb_cells(TCOD_map_t map);
#endif

257
include/fov.hpp Normal file
View File

@ -0,0 +1,257 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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_HPP
#define _TCOD_FOV_HPP
#include "fov_types.h"
class TCODPath;
/**
@PageName fov
@PageCategory Roguelike toolkits
@PageTitle Field of view
@PageDesc This toolkit allows 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);
/**
@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 Wether 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 informations 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

54
include/fov_types.h Normal file
View File

@ -0,0 +1,54 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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
/* FOV_BASIC : http://roguebasin.roguelikedevelopment.org/index.php?title=Ray_casting
FOV_DIAMOND : http://www.geocities.com/temerra/los_rays.html
FOV_SHADOW : http://roguebasin.roguelikedevelopment.org/index.php?title=FOV_using_recursive_shadowcasting
FOV_PERMISSIVE : http://roguebasin.roguelikedevelopment.org/index.php?title=Precise_Permissive_Field_of_View
FOV_RESTRICTIVE : Mingos' Restrictive Precise Angle Shadowcasting (contribution by Mingos) */
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;
#define FOV_PERMISSIVE(x) ((TCOD_fov_algorithm_t)(FOV_PERMISSIVE_0 + (x)))
#endif /* _TCOD_FOV_TYPES_H */

70
include/heightmap.h Normal file
View File

@ -0,0 +1,70 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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
typedef struct {
int w,h;
float *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 *hmres, float coef);
TCODLIB_API void TCOD_heightmap_add_hm(const TCOD_heightmap_t *hm1, const TCOD_heightmap_t *hm2, TCOD_heightmap_t *hmres);
TCODLIB_API void TCOD_heightmap_multiply_hm(const TCOD_heightmap_t *hm1, const TCOD_heightmap_t *hm2, TCOD_heightmap_t *hmres);
TCODLIB_API void TCOD_heightmap_add_hill(TCOD_heightmap_t *hm, float hx, float hy, float hradius, float hheight);
TCODLIB_API void TCOD_heightmap_dig_hill(TCOD_heightmap_t *hm, float hx, float hy, float hradius, float hheight);
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_t rnd);
/* TCODLIB_API void TCOD_heightmap_heat_erosion(TCOD_heightmap_t *hm, int nbPass,float minSlope,float erosionCoef,float sedimentationCoef,TCOD_random_t rnd); */
TCODLIB_API void TCOD_heightmap_kernel_transform(TCOD_heightmap_t *hm, int kernelsize, 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_t rnd);
TCODLIB_API void TCOD_heightmap_mid_point_displacement(TCOD_heightmap_t *hm, TCOD_random_t rnd, float roughness);
TCODLIB_API void TCOD_heightmap_add_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mulx, float muly, float addx, float addy, float octaves, float delta, float scale);
TCODLIB_API void TCOD_heightmap_scale_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mulx, float muly, float addx, float addy, float octaves, float delta, float scale);
TCODLIB_API void TCOD_heightmap_islandify(TCOD_heightmap_t *hm, float seaLevel,TCOD_random_t rnd);
#endif

500
include/heightmap.hpp Normal file
View File

@ -0,0 +1,500 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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_HPP
#define _TCOD_HEIGHTMAP_HPP
/**
@PageName heightmap
@PageCategory Roguelike toolkits
@PageTitle Heightmap toolkit
@PageDesc This toolkit allows 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 w, int h);
/**
@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 hradius, 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 hradius, 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 hradius, 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 kernelsize, int *dx, int *dy, float *weight, float minLevel,float maxLevel)
@Py heightmap_kernel_transform(hm, kernelsize, 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 mulx, float muly, float addx, float addy, float octaves, float delta, float scale)
@C void TCOD_heightmap_add_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mulx, float muly, float addx, float addy, float octaves, float delta, float scale)
@Py heightmap_add_fbm(hm, noise,mulx, muly, addx, addy, octaves, delta, scale)
@C# void TCODHeightMap::addFbm(TCODNoise noise, float mulx, float muly, float addx, float addy, 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 mulx, muly / addx, addy The noise coordinate for map cell (x,y) are (x + addx)*mulx / width , (y + addy)*muly / 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 mulx, float muly, float addx, float addy, 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 mulx, float muly, float addx, float addy, float octaves, float delta, float scale)
@C void TCOD_heightmap_scale_fbm(TCOD_heightmap_t *hm, TCOD_noise_t noise,float mulx, float muly, float addx, float addy, float octaves, float delta, float scale)
@Py heightmap_scale_fbm(hm, noise,mulx, muly, addx, addy, octaves, delta, scale)
@C# void TCODHeightMap::scaleFbm(TCODNoise noise, float mulx, float muly, float addx, float addy, float octaves, float delta, float scale)
*/
void scaleFbm(TCODNoise *noise,float mulx, float muly, float addx, float addy, 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 adress 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

155
include/howto.hpp Normal file
View File

@ -0,0 +1,155 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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 file contains no code. It's only an input for doctcod */
/**
@PageName compile_libtcod
@PageCategory Howtos
@PageTitle How to compile libtcod
@PageDesc This page contains howtos about how to get the latest libtcod source code and compile it.
*/
/**
@PageName compile_libtcod_mingw
@PageFather compile_libtcod
@PageTitle On Windows with Mingw
@PageDesc <h4>Mingw installation</h4>
Download the latest version of Mingw from this adress :
<a href="http://sourceforge.net/projects/mingw/files/">http://sourceforge.net/projects/mingw/files/</a>
The latest installer should be at the top of the page with a name starting with mingw-get-inst..
<img src="mingw1.png" />
Download and run the program. Follow the installation steps. Be sure to check the "Use pre-packaged repository" option :
<img src="mingw2.png" />
The latest version might be less stable and might not work with a precompiled libtcod.
When you arrive at the component selection screen, check C compiler, C++ compiler and MSys system :
<img src="mingw3.png" />
Keep on following the installation steps until the installation is finished. Now you have a "Mingw Shell" program in your start menu. This is the terminal you will use to compile and debug your game.
<h4>TortoiseHg installation</h4>
In order to get the latest version of libtcod, you need a mercurial client.
Go to the download page and grab the client corresponding to your version of Windows :
<a href="http://tortoisehg.bitbucket.org/download/index.html">http://tortoisehg.bitbucket.org/download/index.html</a>
Follow the installation wizard using the default configuration. Once the installation is finished, restart your computer.
Now you should be able to use mercurial (hg) from the Mingw Shell. To check if everything is ok, start a shell and type "which hg" :
<img src="mingw4.png" />
<h4>Getting libtcod source code</h4>
In Mingw Shell, type :
<pre name="code" class="brush: bash">hg clone https://bitbucket.org/jice/libtcod</pre>
This might take some time so grab a beer. Once it's finished, a libtcod directory has been created.
You can check the documentation (the same you're currently reading) in libtcod/doc/index2.html.
The headers are in libtcod/include.
The source code in libtcod/src.
<h4>Compiling libtcod</h4>
Go in libtcod's main directory :
<pre name="code" class="brush: bash">cd libtcod</pre>
And start the compilation :
<pre name="code" class="brush: bash">make -f makefiles/makefile-mingw</pre>
The compilation make take a few seconds depending on your CPU speed. Once it's finished, compile the samples :
<pre name="code" class="brush: bash">make -f makefiles/makefile-samples-mingw</pre>
Check that everything is ok by running the samples :
<pre name="code" class="brush: bash">./samples_cpp</pre>
*/
/**
@PageName compile_libtcod_linux
@PageFather compile_libtcod
@PageTitle On Linux
@PageDesc <h4>Linux compilation</h4>
On a freshly installed Ubuntu :
Get the tools :
<pre name="code" class="brush: bash">sudo apt-get install gcc g++ make upx electric-fence libsdl1.2-dev mercurial</pre>
Get the latest sources :
<pre name="code" class="brush: bash">hg clone https://bitbucket.org/jice/libtcod</pre>
Compile the library :
<pre name="code" class="brush: bash">cd libtcod/</pre>
<pre name="code" class="brush: bash">make -f makefiles/makefile-linux clean all</pre>
Compile the samples :
<pre name="code" class="brush: bash">make -f makefiles/makefile-samples-linux</pre>
Enjoy :
<pre name="code" class="brush: bash">./samples_cpp</pre>
*/
/**
@PageName compile_libtcod_codelite
@PageFather compile_libtcod
@PageTitle Using CodeLite
@PageDesc TODO
*/
/**
@PageName compile_libtcod_haiku
@PageFather compile_libtcod
@PageTitle On Haiku
@PageDesc TODO
*/
/**
@PageName start_project
@PageCategory Howtos
@PageTitle How to start a project
@PageDesc This page contains howtos about how to create a project from scratch
*/
/**
@PageName start_mingw
@PageFather start_project
@PageTitle On Windows with Mingw
@PageDesc TODO
*/
/**
@PageName start_linux
@PageFather start_project
@PageTitle On Linux
@PageDesc TODO
*/
/**
@PageName start_codelite
@PageFather start_project
@PageTitle Using CodeLite
@PageDesc TODO
*/

54
include/image.h Normal file
View File

@ -0,0 +1,54 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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.
*/
typedef void *TCOD_image_t;
TCODLIB_API TCOD_image_t TCOD_image_new(int width, int height);
TCODLIB_API TCOD_image_t TCOD_image_from_console(TCOD_console_t console);
TCODLIB_API void TCOD_image_refresh_console(TCOD_image_t image, TCOD_console_t console);
TCODLIB_API TCOD_image_t TCOD_image_load(const char *filename);
TCODLIB_API void TCOD_image_clear(TCOD_image_t image, TCOD_color_t color);
TCODLIB_API void TCOD_image_invert(TCOD_image_t image);
TCODLIB_API void TCOD_image_hflip(TCOD_image_t image);
TCODLIB_API void TCOD_image_rotate90(TCOD_image_t image, int numRotations);
TCODLIB_API void TCOD_image_vflip(TCOD_image_t image);
TCODLIB_API void TCOD_image_scale(TCOD_image_t image, int neww, int newh);
TCODLIB_API void TCOD_image_save(TCOD_image_t image, const char *filename);
TCODLIB_API void TCOD_image_get_size(TCOD_image_t image, int *w,int *h);
TCODLIB_API TCOD_color_t TCOD_image_get_pixel(TCOD_image_t image,int x, int y);
TCODLIB_API int TCOD_image_get_alpha(TCOD_image_t image,int x, int y);
TCODLIB_API TCOD_color_t TCOD_image_get_mipmap_pixel(TCOD_image_t image,float x0,float y0, float x1, float y1);
TCODLIB_API void TCOD_image_put_pixel(TCOD_image_t image,int x, int y,TCOD_color_t col);
TCODLIB_API void TCOD_image_blit(TCOD_image_t image, TCOD_console_t console, float x, float y,
TCOD_bkgnd_flag_t bkgnd_flag, float scalex, float scaley, float angle);
TCODLIB_API 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);
TCODLIB_API 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);
TCODLIB_API void TCOD_image_delete(TCOD_image_t image);
TCODLIB_API void TCOD_image_set_key_color(TCOD_image_t image, TCOD_color_t key_color);
TCODLIB_API bool TCOD_image_is_pixel_transparent(TCOD_image_t image, int x, int y);

440
include/image.hpp Normal file
View File

@ -0,0 +1,440 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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.
*/
class TCODLIB_API TCODImage {
public :
/**
@PageName image
@PageTitle Image toolkit
@PageCategory Base toolkits
@PageDesc This toolkit contains some image manipulation utilities.
*/
/**
@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 = litbcod.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);
/**
@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 = litbcod.image_new(80,50)
col=litbcod.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 neww < oldw or newh < oldh, supersampling is used to scale down the image. Else the image is scaled up using nearest neightbor.
@Cpp void TCODImage::scale(int neww, int newh)
@C void TCOD_image_scale(TCOD_image_t image,int neww, int newh)
@Py image_scale(image, neww,newh)
@C# void TCODImage::scale(int neww, int newh)
@Param image In the C and python version, the image handler, obtained with the load function.
@Param neww,newh The new size of the image.
*/
void scale(int neww, int newh);
/**
@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;
/**
@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 scalex=1.0f, float scaley=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 scalex, float scaley, float angle)
@Py image_blit(image, console, x, y, bkgnd_flag, scalex, scaley, 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 scalex)
void TCODImage::blit(TCODConsole console, float x, float y, TCODBackgroundFlag bkgnd_flag, float scalex, float scaley)
void TCODImage::blit(TCODConsole console, float x, float y, TCODBackgroundFlag bkgnd_flag, float scalex, float scaley, 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 scalex,scaley 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 scalex=1.0f, float scaley=1.0f, float angle=0.0f) const;
/**
@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 blited. 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;
TCODImage(TCOD_image_t img) : data(img), deleteData(false) {}
virtual ~TCODImage();
protected :
friend class TCODLIB_API TCODSystem;
friend class TCODLIB_API TCODZip;
void *data;
bool deleteData;
};

101
include/lex.h Normal file
View File

@ -0,0 +1,101 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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_LEX_H
#define _TCOD_LEX_H
/*
* This is a libtcod internal module.
* Use at your own risks...
*/
#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 {
int file_line, token_type, token_int_val, 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, nb_keywords, flags;
char symbols[ TCOD_LEX_MAX_SYMBOLS][ TCOD_LEX_SYMBOL_SIZE ],
keywords[ TCOD_LEX_MAX_KEYWORDS ][ TCOD_LEX_KEYWORD_SIZE ];
const char *simpleCmt;
const char *cmtStart, *cmtStop, *javadocCmtStart;
const char *stringDelim;
bool javadoc_read;
bool allocBuf;
bool savept; /* is this object a savepoint (no free in destructor) */
} TCOD_lex_t;
TCODLIB_API TCOD_lex_t *TCOD_lex_new_intern();
TCODLIB_API TCOD_lex_t *TCOD_lex_new(const char **symbols, const char **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 *savept);
TCODLIB_API void TCOD_lex_restore(TCOD_lex_t *lex,TCOD_lex_t *savept);
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 char *TCOD_lex_get_last_error();
TCODLIB_API int TCOD_lex_hextoint(char c);
#endif

73
include/lex.hpp Normal file
View File

@ -0,0 +1,73 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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_LEX_HPP
#define _TCOD_LEX_HPP
/*
* This is a libtcod internal module.
* Use at your own risks...
*/
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(void);
int parseUntil(int tokenType);
int parseUntil(const char *tokenValue);
bool expect(int tokenType);
bool expect(int tokenType,const char *tokenValue);
void savepoint(TCODLex *savept);
void restore(TCODLex *savept);
char *getLastJavadoc();
int getFileLine() { return ((TCOD_lex_t *)data)->file_line; }
int getTokenType() { return ((TCOD_lex_t *)data)->token_type; }
int getTokenIntVal() { return ((TCOD_lex_t *)data)->token_int_val; }
int getTokenIdx() { return ((TCOD_lex_t *)data)->token_idx; }
float getTokenFloatVal() { return ((TCOD_lex_t *)data)->token_float_val; }
char *getToken() { return ((TCOD_lex_t *)data)->tok; }
char getStringLastDelimiter() { return ((TCOD_lex_t *)data)->lastStringDelim; }
char *getPos() { return ((TCOD_lex_t *)data)->pos; }
char *getBuf() { return ((TCOD_lex_t *)data)->buf; }
char *getFilename() { return ((TCOD_lex_t *)data)->filename; }
char *getLastJavadocComment() { return ((TCOD_lex_t *)data)->last_javadoc_comment; }
static const char *getTokenName(int tokenType) { return TCOD_lex_get_token_name(tokenType); }
protected :
void *data;
};
#endif

218
include/libtcod.h Normal file
View File

@ -0,0 +1,218 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _LIBTCOD_H
#define _LIBTCOD_H
/* uncomment to disable unicode support */
/*#define NO_UNICODE */
/* uncomment to disable opengl support */
/*#define NO_OPENGL */
/* os identification
TCOD_WINDOWS : OS is windows
TCOD_LINUX : OS is Linux
TCOD_MACOSX : OS is Mac OS X
TCOD_HAIKU : OS is Haiku */
/* compiler identification
TCOD_VISUAL_STUDIO : compiler is Microsoft Visual Studio
TCOD_MINGW32 : compiler is Mingw32
TCOD_GCC : compiler is gcc/g++ */
/* word size
TCOD_64BITS : 64 bits OS
TCOD_WIN64 : 64 bits Windows
TCOD_WIN32 : 32 bits Windows
TCOD_LINUX64 : 64 bits Linux
TCOD_LINUX32 : 32 bits Linux
TCOD_FREEBSD64 : 64 bits FreeBSD
TCOD_FREEBSD32 : 32 bits FreeBSD */
#if defined( _MSC_VER )
# define TCOD_VISUAL_STUDIO
# define TCOD_WINDOWS
# ifdef _WIN64
# define TCOD_WIN64
# define TCOD_64BITS
# else
# define TCOD_WIN32
# endif
#elif defined( __MINGW32__ )
# define TCOD_WINDOWS
# define TCOD_MINGW32
# define TCOD_WIN32
#elif defined( __MINGW64__ )
# define TCOD_WINDOWS
# define TCOD_MINGW32
# ifdef _WIN64
# define TCOD_WIN64
# define TCOD_64BITS
# else
# define TCOD_WIN32
# endif
#elif defined( __HAIKU__ )
# define TCOD_HAIKU
# define TCOD_GCC
# if __WORDSIZE == 64
# define TCOD_64BITS
# endif
#elif defined( __linux )
# define TCOD_LINUX
# define TCOD_GCC
# if __WORDSIZE == 64
# define TCOD_LINUX64
# define TCOD_64BITS
# else
# define TCOD_LINUX32
# endif
#elif defined( __FreeBSD__ )
# define TCOD_FREEBSD
# define TCOD_GCC
# if __WORDSIZE == 64
# define TCOD_FREEBSD64
# define TCOD_64BITS
# else
# define TCOD_FREEBSD32
# endif
#elif defined (__APPLE__) && defined (__MACH__)
# define TCOD_MACOSX
# define TCOD_GCC
#endif
/* unicode rendering functions support */
#ifndef NO_UNICODE
#include <wchar.h>
#endif
/* This is a hack. SDL by default want you to rename your main statement, and insert it's own first
It does that to handle some init code. However, libtcod handles that for you. If we did this
wrappers like libtcod-net would be hosed, since there is no main statement there. */
#ifdef TCOD_MACOSX
#define _SDL_main_h
#include "SDL/SDL.h"
#endif
/* base types */
#ifndef TCOD_NOBASETYPES
typedef unsigned char uint8;
typedef char int8;
typedef unsigned short uint16;
typedef short int16;
typedef unsigned int uint32;
typedef int int32;
#endif
/* int with the same size as a pointer (32 or 64 depending on OS) */
#ifdef TCOD_WIN64
typedef long long intptr;
typedef unsigned long long uintptr;
#else
typedef long intptr;
typedef unsigned long uintptr;
#endif
#define TCOD_HEXVERSION 0x010600
#define TCOD_STRVERSION "1.6.0"
#define TCOD_TECHVERSION 0x01060000
/* bool support for C */
#ifndef __cplusplus
#ifndef bool
typedef uint8 bool;
#define false ((bool)0)
#define true ((bool)1)
#endif
#else
/* in C++ all C functions prototypes should use uint8 instead of bool */
#define bool uint8
#endif
/* DLL export */
#ifdef TCOD_WINDOWS
#ifdef LIBTCOD_EXPORTS
#define TCODLIB_API __declspec(dllexport)
#else
#define TCODLIB_API __declspec(dllimport)
#endif
#else
#define TCODLIB_API
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* ansi C lacks support for those functions */
TCODLIB_API char *TCOD_strdup(const char *s);
TCODLIB_API int TCOD_strcasecmp(const char *s1, const char *s2);
TCODLIB_API int TCOD_strncasecmp(const char *s1, const char *s2, size_t n);
#if defined(TCOD_WINDOWS)
char *strcasestr (const char *haystack, const char *needle);
#endif
#if defined(TCOD_LINUX) || defined(TCOD_HAIKU) || defined(TCOD_FREEBSD) || defined(TCOD_MACOSX)
#define vsnwprintf vswprintf
#endif
#ifdef TCOD_WINDOWS
#define vsnwprintf _vsnwprintf
#endif
/******************************************
utility macros
******************************************/
#define MAX(a,b) ((a)<(b)?(b):(a))
#define MIN(a,b) ((a)>(b)?(b):(a))
#define ABS(a) ((a)<0?-(a):(a))
#define CLAMP(a, b, x) ((x) < (a) ? (a) : ((x) > (b) ? (b) : (x)))
#define LERP(a, b, x) ( (a) + (x) * ((b) - (a)) )
#include "list.h"
#include "color.h"
#include "console.h"
#include "image.h"
#include "mouse.h"
#include "sys.h"
#include "mersenne.h"
#include "bresenham.h"
#include "noise.h"
#include "fov.h"
#include "path.h"
#include "lex.h"
#include "parser.h"
#include "tree.h"
#include "bsp.h"
#include "heightmap.h"
#include "zip.h"
#include "namegen.h"
#include "txtfield.h"
#ifdef __cplusplus
#undef bool
}
#endif
#endif

51
include/libtcod.hpp Normal file
View File

@ -0,0 +1,51 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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_HPP
#define _LIBTCOD_HPP
#include "libtcod.h"
#include "list.hpp"
#include "color.hpp"
#include "console.hpp"
#include "image.hpp"
#include "sys.hpp"
#include "mersenne.hpp"
#include "mouse.hpp"
#include "bresenham.hpp"
#include "noise.hpp"
#include "fov.hpp"
#include "path.hpp"
#include "lex.hpp"
#include "parser.hpp"
#include "tree.hpp"
#include "bsp.hpp"
#include "heightmap.hpp"
#include "zip.hpp"
#include "namegen.hpp"
#include "txtfield.hpp"
#endif

531
include/libtcod_int.h Normal file
View File

@ -0,0 +1,531 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCODLIB_INT_H
#define _TCODLIB_INT_H
#include <stdarg.h>
#include <assert.h>
#if defined (__HAIKU__) || defined(__ANDROID__)
#include <SDL.h>
#include <android/log.h>
#elif defined (TCOD_SDL2)
#include <SDL.h>
#else
#include <SDL/SDL.h>
#endif
/* tcodlib internal stuff */
#ifdef __cplusplus
extern "C" {
#endif
/* a cell in the console */
typedef struct {
int c; /* character ascii code */
int cf; /* character number in font */
TCOD_color_t fore; /* foreground color */
TCOD_color_t back; /* background color */
uint8 dirt; /* cell modified since last flush ? */
} char_t;
/* TCODConsole non public data */
typedef struct {
char_t *buf; /* current console */
char_t *oldbuf; /* console for last frame */
/* console width and height (in characters,not pixels) */
int w,h;
/* 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), background and key colors */
TCOD_color_t fore,back,key;
uint8 fade;
bool haskey; /* a key color has been defined */
} TCOD_console_data_t;
/* fov internal stuff */
typedef struct {
bool transparent:1;
bool walkable:1;
bool fov:1;
} cell_t;
typedef struct {
int width;
int height;
int nbcells;
cell_t *cells;
} map_t;
/* pseudorandom number generator toolkit */
typedef struct {
/* algorithm identifier */
TCOD_random_algo_t algo;
/* distribution */
TCOD_distribution_t distribution;
/* Mersenne Twister stuff */
uint32 mt[624];
int cur_mt;
/* Complementary-Multiply-With-Carry stuff */
/* shared with Generalised Feedback Shift Register */
uint32 Q[4096], c;
int cur;
} mersenne_data_t;
typedef struct {
/* number of characters in the bitmap font */
int fontNbCharHoriz;
int fontNbCharVertic;
/* font type and layout */
bool font_tcod_layout;
bool font_in_row;
bool font_greyscale;
/* character size in font */
int font_width;
int font_height;
char font_file[512];
char window_title[512];
/* ascii code to tcod layout converter */
int *ascii_to_tcod;
/* whether each character in the font is a colored tile */
bool *colored;
/* the root console */
TCOD_console_data_t *root;
/* nb chars in the font */
int max_font_chars;
/* fullscreen data */
bool fullscreen;
int fullscreen_offsetx;
int fullscreen_offsety;
/* asked by the user */
int fullscreen_width;
int fullscreen_height;
/* actual resolution */
int actual_fullscreen_width;
int actual_fullscreen_height;
/* renderer to use */
TCOD_renderer_t renderer;
/* user post-processing callback */
SDL_renderer_t sdl_cbk;
/* fading data */
TCOD_color_t fading_color;
uint8 fade;
TCOD_key_t key_state;
/* application window was closed */
bool is_window_closed;
/* application has mouse focus */
bool app_has_mouse_focus;
/* application is active (not iconified) */
bool app_is_active;
} TCOD_internal_context_t;
extern TCOD_internal_context_t TCOD_ctx;
#if defined(__ANDROID__) && !defined(NDEBUG)
#include <android/log.h>
#ifdef printf
#undef printf
#endif
#ifdef vprintf
#undef vprintf
#endif
#define printf(args...) __android_log_print(ANDROID_LOG_INFO, "libtcod", ## args)
#define vprintf(args...) __android_log_vprint(ANDROID_LOG_INFO, "libtcod", ## args)
#ifdef assert
#undef assert
#endif
#define assert(cond) if(!(cond)) __android_log_assert(#cond, "libtcod", "assertion failed: %s", #cond)
#endif
#ifdef NDEBUG
#define TCOD_IF(x) if (x)
#define TCOD_IFNOT(x) if (!(x))
#define TCOD_ASSERT(x)
#define TCOD_LOG(x)
#else
#define TCOD_IF(x) assert(x);
#define TCOD_IFNOT(x) assert(x); if (0)
#define TCOD_ASSERT(x) assert(x)
#define TCOD_LOG(x) printf x
#endif
#ifndef NO_OPENGL
/* opengl utilities */
void TCOD_opengl_init_attributes();
bool TCOD_opengl_init_state(int conw, int conh, void *font_tex);
bool TCOD_opengl_init_shaders();
bool TCOD_opengl_render(int oldFade, bool *ascii_updated, char_t *console_buffer, char_t *prev_console_buffer);
void TCOD_opengl_swap();
void * TCOD_opengl_get_screen();
#endif
/* fov internal stuff */
void TCOD_map_compute_fov_circular_raycasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls);
void TCOD_map_compute_fov_diamond_raycasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls);
void TCOD_map_compute_fov_recursive_shadowcasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls);
void TCOD_map_compute_fov_permissive2(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls, int fovType);
void TCOD_map_compute_fov_restrictive_shadowcasting(TCOD_map_t map, int player_x, int player_y, int max_radius, bool light_walls);
void TCOD_map_postproc(map_t *map,int x0,int y0, int x1, int y1, int dx, int dy);
/* TCODConsole non public methods*/
bool TCOD_console_init(TCOD_console_t con,const char *title, bool fullscreen);
int TCOD_console_print_internal(TCOD_console_t con,int x,int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t align, char *msg, bool can_split, bool count_only);
int TCOD_console_stringLength(const unsigned char *s);
unsigned char * TCOD_console_forward(unsigned char *s,int l);
char *TCOD_console_vsprint(const char *fmt, va_list ap);
char_t *TCOD_console_get_buf(TCOD_console_t con);
/* fatal errors */
void TCOD_fatal(const char *fmt, ...);
void TCOD_fatal_nopar(const char *msg);
/* TCODSystem non public methods */
bool TCOD_sys_init(int w,int h, char_t *buf, char_t *oldbuf, bool fullscreen);
void TCOD_sys_set_custom_font(const char *font_name,int nb_ch, int nb_cv,int flags);
void TCOD_sys_map_ascii_to_font(int asciiCode, int fontCharX, int fontCharY);
void *TCOD_sys_create_bitmap_for_console(TCOD_console_t console);
void TCOD_sys_save_bitmap(void *bitmap, const char *filename);
void *TCOD_sys_create_bitmap(int width, int height, TCOD_color_t *buf);
void TCOD_sys_delete_bitmap(void *bitmap);
void TCOD_sys_console_to_bitmap(void *bitmap, int console_width, int console_height, char_t *console_buffer, char_t *prev_console_buffer);
void TCOD_sys_set_keyboard_repeat(int initial_delay, int interval);
TCODLIB_API void *TCOD_sys_get_surface(int width, int height, bool alpha);
void TCOD_sys_save_fps();
void TCOD_sys_restore_fps();
/* switch fullscreen mode */
void TCOD_sys_set_fullscreen(bool fullscreen);
void TCOD_sys_set_clear_screen();
void TCOD_sys_set_scale_factor(float value);
void TCOD_sys_convert_console_to_screen_coords(int cx, int cy, int *sx, int *sy);
void TCOD_sys_convert_screen_to_console_coords(int sx, int sy, int *cx, int *cy);
void TCOD_sys_flush(bool render);
TCOD_key_t TCOD_sys_check_for_keypress(int flags);
TCOD_key_t TCOD_sys_wait_for_keypress(bool flush);
bool TCOD_sys_is_key_pressed(TCOD_keycode_t key);
void TCOD_sys_set_window_title(const char *title);
/* close the window */
void TCOD_sys_term();
/* UTF-8 stuff */
#ifndef NO_UNICODE
wchar_t *TCOD_console_vsprint_utf(const wchar_t *fmt, va_list ap);
int TCOD_console_print_internal_utf(TCOD_console_t con,int x,int y, int rw, int rh, TCOD_bkgnd_flag_t flag,
TCOD_alignment_t align, wchar_t *msg, bool can_split, bool count_only);
#endif
/* image manipulation */
TCODLIB_API void *TCOD_sys_load_image(const char *filename);
void TCOD_sys_get_image_size(const void *image, int *w,int *h);
TCOD_color_t TCOD_sys_get_image_pixel(const void *image,int x, int y);
int TCOD_sys_get_image_alpha(const void *image,int x, int y);
bool TCOD_sys_check_magic_number(const char *filename, int size, uint8 *data);
/* TCOD_list nonpublic methods */
void TCOD_list_set_size(TCOD_list_t l, int size);
/*
SDL12/SDL2 abstraction layer
*/
typedef struct {
/* get a fullscreen mode suitable for the console */
void (*get_closest_mode)(int *w, int *h);
/* render the console on a surface/texture */
void (*render)(void *vbitmap, int console_width, int console_height, char_t *console_buffer, char_t *prev_console_buffer);
/* create a new surface */
SDL_Surface *(*create_surface) (int width, int height, bool with_alpha);
/* create the game window */
void (*create_window)(int w, int h, bool fullscreen);
/* switch fullscreen on/off */
void (*set_fullscreen)(bool fullscreen);
/* change the game window title */
void (*set_window_title)(const char *title);
/* save game screenshot */
void (*save_screenshot)(const char *filename);
/* get desktop resolution */
void (*get_current_resolution)(int *w, int *h);
/* change the mouse cursor position */
void (*set_mouse_position)(int x, int y);
/* android compatible file access functions */
bool (*file_read)(const char *filename, unsigned char **buf, size_t *size);
bool (*file_exists)(const char * filename);
bool (*file_write)(const char *filename, unsigned char *buf, uint32 size);
/* clean stuff */
void (*term)();
} TCOD_SDL_driver_t;
/* defined in TCOD_sys_sdl12_c.c and TCOD_sys_sdl2_c.c */
TCOD_SDL_driver_t *SDL_implementation_factory();
void find_resolution();
void TCOD_sys_init_screen_offset();
extern SDL_Surface* screen;
extern int oldFade;
extern bool *ascii_updated;
extern bool any_ascii_updated;
extern SDL_Surface* charmap;
typedef struct {
float force_recalc;
float last_scale_xc, last_scale_yc;
float last_scale_factor;
float last_fullscreen;
float min_scale_factor;
float src_height_width_ratio;
float dst_height_width_ratio;
int src_x0, src_y0;
int src_copy_width, src_copy_height;
int src_proportionate_width, src_proportionate_height;
int dst_display_width, dst_display_height;
int dst_offset_x, dst_offset_y;
int surface_width, surface_height;
} scale_data_t;
extern scale_data_t scale_data;
#ifdef TCOD_SDL2
extern float scale_factor;
extern SDL_Window* window;
extern SDL_Renderer* renderer;
#endif
/* color values */
#define TCOD_BLACK 0,0,0
#define TCOD_DARKEST_GREY 31,31,31
#define TCOD_DARKER_GREY 63,63,63
#define TCOD_DARK_GREY 95,95,95
#define TCOD_GREY 127,127,127
#define TCOD_LIGHT_GREY 159,159,159
#define TCOD_LIGHTER_GREY 191,191,191
#define TCOD_LIGHTEST_GREY 223,223,223
#define TCOD_WHITE 255,255,255
#define TCOD_DARKEST_SEPIA 31,24,15
#define TCOD_DARKER_SEPIA 63,50,31
#define TCOD_DARK_SEPIA 94,75,47
#define TCOD_SEPIA 127,101,63
#define TCOD_LIGHT_SEPIA 158,134,100
#define TCOD_LIGHTER_SEPIA 191,171,143
#define TCOD_LIGHTEST_SEPIA 222,211,195
/* desaturated */
#define TCOD_DESATURATED_RED 127,63,63
#define TCOD_DESATURATED_FLAME 127,79,63
#define TCOD_DESATURATED_ORANGE 127,95,63
#define TCOD_DESATURATED_AMBER 127,111,63
#define TCOD_DESATURATED_YELLOW 127,127,63
#define TCOD_DESATURATED_LIME 111,127,63
#define TCOD_DESATURATED_CHARTREUSE 95,127,63
#define TCOD_DESATURATED_GREEN 63,127,63
#define TCOD_DESATURATED_SEA 63,127,95
#define TCOD_DESATURATED_TURQUOISE 63,127,111
#define TCOD_DESATURATED_CYAN 63,127,127
#define TCOD_DESATURATED_SKY 63,111,127
#define TCOD_DESATURATED_AZURE 63,95,127
#define TCOD_DESATURATED_BLUE 63,63,127
#define TCOD_DESATURATED_HAN 79,63,127
#define TCOD_DESATURATED_VIOLET 95,63,127
#define TCOD_DESATURATED_PURPLE 111,63,127
#define TCOD_DESATURATED_FUCHSIA 127,63,127
#define TCOD_DESATURATED_MAGENTA 127,63,111
#define TCOD_DESATURATED_PINK 127,63,95
#define TCOD_DESATURATED_CRIMSON 127,63,79
/* lightest */
#define TCOD_LIGHTEST_RED 255,191,191
#define TCOD_LIGHTEST_FLAME 255,207,191
#define TCOD_LIGHTEST_ORANGE 255,223,191
#define TCOD_LIGHTEST_AMBER 255,239,191
#define TCOD_LIGHTEST_YELLOW 255,255,191
#define TCOD_LIGHTEST_LIME 239,255,191
#define TCOD_LIGHTEST_CHARTREUSE 223,255,191
#define TCOD_LIGHTEST_GREEN 191,255,191
#define TCOD_LIGHTEST_SEA 191,255,223
#define TCOD_LIGHTEST_TURQUOISE 191,255,239
#define TCOD_LIGHTEST_CYAN 191,255,255
#define TCOD_LIGHTEST_SKY 191,239,255
#define TCOD_LIGHTEST_AZURE 191,223,255
#define TCOD_LIGHTEST_BLUE 191,191,255
#define TCOD_LIGHTEST_HAN 207,191,255
#define TCOD_LIGHTEST_VIOLET 223,191,255
#define TCOD_LIGHTEST_PURPLE 239,191,255
#define TCOD_LIGHTEST_FUCHSIA 255,191,255
#define TCOD_LIGHTEST_MAGENTA 255,191,239
#define TCOD_LIGHTEST_PINK 255,191,223
#define TCOD_LIGHTEST_CRIMSON 255,191,207
/* lighter */
#define TCOD_LIGHTER_RED 255,127,127
#define TCOD_LIGHTER_FLAME 255,159,127
#define TCOD_LIGHTER_ORANGE 255,191,127
#define TCOD_LIGHTER_AMBER 255,223,127
#define TCOD_LIGHTER_YELLOW 255,255,127
#define TCOD_LIGHTER_LIME 223,255,127
#define TCOD_LIGHTER_CHARTREUSE 191,255,127
#define TCOD_LIGHTER_GREEN 127,255,127
#define TCOD_LIGHTER_SEA 127,255,191
#define TCOD_LIGHTER_TURQUOISE 127,255,223
#define TCOD_LIGHTER_CYAN 127,255,255
#define TCOD_LIGHTER_SKY 127,223,255
#define TCOD_LIGHTER_AZURE 127,191,255
#define TCOD_LIGHTER_BLUE 127,127,255
#define TCOD_LIGHTER_HAN 159,127,255
#define TCOD_LIGHTER_VIOLET 191,127,255
#define TCOD_LIGHTER_PURPLE 223,127,255
#define TCOD_LIGHTER_FUCHSIA 255,127,255
#define TCOD_LIGHTER_MAGENTA 255,127,223
#define TCOD_LIGHTER_PINK 255,127,191
#define TCOD_LIGHTER_CRIMSON 255,127,159
/* light */
#define TCOD_LIGHT_RED 255,63,63
#define TCOD_LIGHT_FLAME 255,111,63
#define TCOD_LIGHT_ORANGE 255,159,63
#define TCOD_LIGHT_AMBER 255,207,63
#define TCOD_LIGHT_YELLOW 255,255,63
#define TCOD_LIGHT_LIME 207,255,63
#define TCOD_LIGHT_CHARTREUSE 159,255,63
#define TCOD_LIGHT_GREEN 63,255,63
#define TCOD_LIGHT_SEA 63,255,159
#define TCOD_LIGHT_TURQUOISE 63,255,207
#define TCOD_LIGHT_CYAN 63,255,255
#define TCOD_LIGHT_SKY 63,207,255
#define TCOD_LIGHT_AZURE 63,159,255
#define TCOD_LIGHT_BLUE 63,63,255
#define TCOD_LIGHT_HAN 111,63,255
#define TCOD_LIGHT_VIOLET 159,63,255
#define TCOD_LIGHT_PURPLE 207,63,255
#define TCOD_LIGHT_FUCHSIA 255,63,255
#define TCOD_LIGHT_MAGENTA 255,63,207
#define TCOD_LIGHT_PINK 255,63,159
#define TCOD_LIGHT_CRIMSON 255,63,111
/* normal */
#define TCOD_RED 255,0,0
#define TCOD_FLAME 255,63,0
#define TCOD_ORANGE 255,127,0
#define TCOD_AMBER 255,191,0
#define TCOD_YELLOW 255,255,0
#define TCOD_LIME 191,255,0
#define TCOD_CHARTREUSE 127,255,0
#define TCOD_GREEN 0,255,0
#define TCOD_SEA 0,255,127
#define TCOD_TURQUOISE 0,255,191
#define TCOD_CYAN 0,255,255
#define TCOD_SKY 0,191,255
#define TCOD_AZURE 0,127,255
#define TCOD_BLUE 0,0,255
#define TCOD_HAN 63,0,255
#define TCOD_VIOLET 127,0,255
#define TCOD_PURPLE 191,0,255
#define TCOD_FUCHSIA 255,0,255
#define TCOD_MAGENTA 255,0,191
#define TCOD_PINK 255,0,127
#define TCOD_CRIMSON 255,0,63
/* dark */
#define TCOD_DARK_RED 191,0,0
#define TCOD_DARK_FLAME 191,47,0
#define TCOD_DARK_ORANGE 191,95,0
#define TCOD_DARK_AMBER 191,143,0
#define TCOD_DARK_YELLOW 191,191,0
#define TCOD_DARK_LIME 143,191,0
#define TCOD_DARK_CHARTREUSE 95,191,0
#define TCOD_DARK_GREEN 0,191,0
#define TCOD_DARK_SEA 0,191,95
#define TCOD_DARK_TURQUOISE 0,191,143
#define TCOD_DARK_CYAN 0,191,191
#define TCOD_DARK_SKY 0,143,191
#define TCOD_DARK_AZURE 0,95,191
#define TCOD_DARK_BLUE 0,0,191
#define TCOD_DARK_HAN 47,0,191
#define TCOD_DARK_VIOLET 95,0,191
#define TCOD_DARK_PURPLE 143,0,191
#define TCOD_DARK_FUCHSIA 191,0,191
#define TCOD_DARK_MAGENTA 191,0,143
#define TCOD_DARK_PINK 191,0,95
#define TCOD_DARK_CRIMSON 191,0,47
/* darker */
#define TCOD_DARKER_RED 127,0,0
#define TCOD_DARKER_FLAME 127,31,0
#define TCOD_DARKER_ORANGE 127,63,0
#define TCOD_DARKER_AMBER 127,95,0
#define TCOD_DARKER_YELLOW 127,127,0
#define TCOD_DARKER_LIME 95,127,0
#define TCOD_DARKER_CHARTREUSE 63,127,0
#define TCOD_DARKER_GREEN 0,127,0
#define TCOD_DARKER_SEA 0,127,63
#define TCOD_DARKER_TURQUOISE 0,127,95
#define TCOD_DARKER_CYAN 0,127,127
#define TCOD_DARKER_SKY 0,95,127
#define TCOD_DARKER_AZURE 0,63,127
#define TCOD_DARKER_BLUE 0,0,127
#define TCOD_DARKER_HAN 31,0,127
#define TCOD_DARKER_VIOLET 63,0,127
#define TCOD_DARKER_PURPLE 95,0,127
#define TCOD_DARKER_FUCHSIA 127,0,127
#define TCOD_DARKER_MAGENTA 127,0,95
#define TCOD_DARKER_PINK 127,0,63
#define TCOD_DARKER_CRIMSON 127,0,31
/* darkest */
#define TCOD_DARKEST_RED 63,0,0
#define TCOD_DARKEST_FLAME 63,15,0
#define TCOD_DARKEST_ORANGE 63,31,0
#define TCOD_DARKEST_AMBER 63,47,0
#define TCOD_DARKEST_YELLOW 63,63,0
#define TCOD_DARKEST_LIME 47,63,0
#define TCOD_DARKEST_CHARTREUSE 31,63,0
#define TCOD_DARKEST_GREEN 0,63,0
#define TCOD_DARKEST_SEA 0,63,31
#define TCOD_DARKEST_TURQUOISE 0,63,47
#define TCOD_DARKEST_CYAN 0,63,63
#define TCOD_DARKEST_SKY 0,47,63
#define TCOD_DARKEST_AZURE 0,31,63
#define TCOD_DARKEST_BLUE 0,0,63
#define TCOD_DARKEST_HAN 15,0,63
#define TCOD_DARKEST_VIOLET 31,0,63
#define TCOD_DARKEST_PURPLE 47,0,63
#define TCOD_DARKEST_FUCHSIA 63,0,63
#define TCOD_DARKEST_MAGENTA 63,0,47
#define TCOD_DARKEST_PINK 63,0,31
#define TCOD_DARKEST_CRIMSON 63,0,15
/* metallic */
#define TCOD_BRASS 191,151,96
#define TCOD_COPPER 197,136,124
#define TCOD_GOLD 229,191,0
#define TCOD_SILVER 203,203,203
/* miscellaneous */
#define TCOD_CELADON 172,255,175
#define TCOD_PEACH 255,159,127
#ifdef __cplusplus
}
#endif
#endif

57
include/list.h Normal file
View File

@ -0,0 +1,57 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_LIST_H
#define _TCOD_LIST_H
typedef void *TCOD_list_t;
TCODLIB_API TCOD_list_t TCOD_list_new();
TCODLIB_API TCOD_list_t TCOD_list_allocate(int nb_elements);
TCODLIB_API TCOD_list_t TCOD_list_duplicate(TCOD_list_t l);
TCODLIB_API void TCOD_list_delete(TCOD_list_t l);
TCODLIB_API void TCOD_list_push(TCOD_list_t l, const void * elt);
TCODLIB_API void * TCOD_list_pop(TCOD_list_t l);
TCODLIB_API void * TCOD_list_peek(TCOD_list_t l);
TCODLIB_API void TCOD_list_add_all(TCOD_list_t l, TCOD_list_t l2);
TCODLIB_API void * TCOD_list_get(TCOD_list_t l,int idx);
TCODLIB_API void TCOD_list_set(TCOD_list_t l,const void *elt, int idx);
TCODLIB_API void ** TCOD_list_begin(TCOD_list_t l);
TCODLIB_API void ** TCOD_list_end(TCOD_list_t l);
TCODLIB_API void TCOD_list_reverse(TCOD_list_t l);
TCODLIB_API void **TCOD_list_remove_iterator(TCOD_list_t l, void **elt);
TCODLIB_API void TCOD_list_remove(TCOD_list_t l, const void * elt);
TCODLIB_API void **TCOD_list_remove_iterator_fast(TCOD_list_t l, void **elt);
TCODLIB_API void TCOD_list_remove_fast(TCOD_list_t l, const void * elt);
TCODLIB_API bool TCOD_list_contains(TCOD_list_t l,const void * elt);
TCODLIB_API void TCOD_list_clear(TCOD_list_t l);
TCODLIB_API void TCOD_list_clear_and_delete(TCOD_list_t l);
TCODLIB_API int TCOD_list_size(TCOD_list_t l);
TCODLIB_API void ** TCOD_list_insert_before(TCOD_list_t l,const void *elt,int before);
TCODLIB_API bool TCOD_list_is_empty(TCOD_list_t l);
#endif

616
include/list.hpp Normal file
View File

@ -0,0 +1,616 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_LIST_HPP
#define _TCOD_LIST_HPP
#include <string.h> // memcpy
#include <stdlib.h> // NULL
/**
@PageName list
@PageCategory Base toolkits
@PageTitle All purposes container
@PageDesc This is a fast, lightweight and generic container, that provides array, list and stack paradigms.
Note that this module has no python wrapper. Use python built-in containers instead.
*/
// fast & lightweight list template
template <class T> class TCODList {
T *array;
int fillSize;
int allocSize;
public :
/**
@PageName list_create
@PageFather list
@PageTitle Creating a list
@FuncTitle Using the default constructor
@FuncDesc You can create an empty list with the default constructor. The C version returns a handler on the list.
@Cpp template <class T> TCODList::TCODList()
@C TCOD_list_t TCOD_list_new()
@CppEx
TCODList<int> intList;
TCODList<float> *floatList = new TCODList<float>();
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_t floatList = TCOD_list_new();
*/
TCODList() {
array=NULL;
fillSize=allocSize=0;
}
/**
@PageName list_create
@FuncTitle Duplicating an existing list
@FuncDesc You can create a list by duplicating an existing list.
@Cpp template <class T> TCODList::TCODList(const TCODList &l)
@C TCOD_list_t TCOD_list_duplicate(TCOD_list_t l)
@Param l Existing list to duplicate.
@CppEx
TCODList<int> intList;
intList.push(3);
intList.push(5);
TCODList<int> intList2(intList); // intList2 contains two elements : 3 and 5
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)3);
TCOD_list_push(intList,(const void *)5);
TCOD_list_t intList2 = TCOD_list_duplicate(intList); // intList2 contains two elements : 3 and 5
*/
TCODList(const TCOD_list_t l) {
array=NULL;
fillSize=allocSize=0;
for ( void **it=TCOD_list_begin(l); it != TCOD_list_end(l); it++ ) {
push(*((T *)(it)));
}
}
TCODList(const TCODList<T> &l2) {
array=NULL;
fillSize=allocSize=0;
*this = l2;
}
/**
@PageName list_create
@FuncTitle Preallocating memory
@FuncDesc You can also create an empty list and pre-allocate memory for elements. Use this if you know the list size and want the memory to fit it perfectly.
@Cpp template <class T> TCODList::TCODList(int nbElements)
@C TCOD_list_t TCOD_list_allocate(int nbElements)
@Param nbElements Allocate memory for nbElements.
@CppEx TCODList<int> intList(5); // create an empty list, pre-allocate memory for 5 elements
@CEx TCOD_list_t intList = TCOD_list_allocate(5);
*/
TCODList(int nbElements) {
fillSize=0;
allocSize=nbElements;
array=new T[ nbElements ];
}
/**
@PageName list_create
@FuncTitle Deleting a list
@FuncDesc You can delete a list, freeing any allocated resources. Note that deleting the list does not delete it's elements. You have to use clearAndDelete before deleting the list if you want to destroy the elements too.
@Cpp virtual template <class T> TCODList::~TCODList()
@C void TCOD_list_delete(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> *intList = new TCODList<int>(); // allocate a new empty list
intList->push(5); // the list contains 1 element at position 0, value = 5
delete intList; // destroy the list
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_delete(intList);
*/
virtual ~TCODList() {
if ( array ) delete [] array;
}
/**
@PageName list_array
@PageTitle Basic array operations
@PageFather list
@FuncTitle Setting an element
@FuncDesc You can assign a value with set. If needed, the array will allocate new elements up to idx.
@Cpp template <class T> void TCODList::set(const T elt, int idx)
@C void TCOD_list_set(TCOD_list_t l,const void *elt, int idx)
@Param elt Element to put in the array.
@Param idx Index of the element.
0 <= idx
@Param l In the C version, the handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the array is empty (contains 0 elements)
intList.set(5,0); // the array contains 1 element at position 0, value = 5
intList.set(7,2); // the array contains 3 elements : 5, 0, 7
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,(const void *)5,0);
TCOD_list_set(intList,(const void *)7,2);
*/
void set(const T elt, int idx) {
if ( idx < 0 ) return;
while ( allocSize < idx+1 ) allocate();
array[idx] = elt;
if ( idx+1 > fillSize ) fillSize = idx+1;
}
/**
@PageName list_array
@FuncTitle Getting an element value
@FuncDesc You can retrieve a value with get.
@Cpp template <class T> T TCODList::get(int idx) const
@C void * TCOD_list_get(TCOD_list_t l,int idx)
@Param idx Index of the element.
0 <= idx < size of the array
@Param l In the C version, the handler, returned by a constructor.
@CppEx
TCODList<int> intList;
intList.set(5,0);
int val = intList.get(0); // val == 5
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,(const void *)5,0);
int val = (int)TCOD_list_get(intList,0); // val == 5
*/
T get(int idx) const {
return array[idx];
}
/**
@PageName list_array
@FuncTitle Checking if a list is empty
@Cpp template <class T> bool TCODList::isEmpty() const
@C bool TCOD_list_is_empty(TCOD_list_t l)
@Param l In the C version, the handler, returned by a constructor.
@CppEx
TCODList<int> intList;
bool empty=intList.isEmpty(); // empty == true
intList.set(3,0);
empty=intList.isEmpty(); // empty == false
@CEx
TCOD_list_t intList = TCOD_list_new();
bool empty=TCOD_list_is_empty(intList); // empty == true
TCOD_list_set(intList,(const void *)5,0);
empty=TCOD_list_is_empty(intList); // empty == false
*/
bool isEmpty() const {
return ( fillSize == 0 );
}
/**
@PageName list_array
@FuncTitle Getting the list size
@Cpp template <class T> int TCODList::size() const
@C int TCOD_list_size(TCOD_list_t l)
@Param l In the C version, the handler, returned by a constructor.
@CppEx
TCODList<int> intList;
int size=intList.size(); // size == 0
intList.set(3,0);
size=intList.size(); // size == 1
@CEx
TCOD_list_t intList = TCOD_list_new();
int size=TCOD_list_size(intList); // size == 0
TCOD_list_set(intList,(const void *)5,0);
size=TCOD_list_size(intList); // size == 1
*/
int size() const {
return fillSize;
}
/**
@PageName list_array
@FuncTitle Checking if an element is in the list
@Cpp template <class T> bool TCODList::contains(const T elt) const
@C bool TCOD_list_contains(TCOD_list_t l,const void * elt)
@Param elt The element.
@Param l In the C version, the handler, returned by a constructor.
@CppEx
TCODList<int> intList;
intList.set(3,0);
bool has3 = intList.contains(3); // has3 == true
bool has4 = intList.contains(4); // has4 == false
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,(const void *)3,0);
bool has3 = TCOD_list_contains(intList,(const void *)3); // has3 == true
bool has4 = TCOD_list_contains(intList,(const void *)4); // has4 == false
*/
bool contains(const T elt) const {
for ( T* curElt = begin(); curElt != end(); curElt ++) {
if ( *curElt == elt ) return true;
}
return false;
}
/**
@PageName list_list
@PageFather list
@PageTitle Basic list operations
@FuncTitle Insert an element in the list
@Cpp template <class T> void TCODList::insertBefore(const T elt,int before)
@C void TCOD_list_insert_before(TCOD_list_t l,const void *elt,int before)
@Param elt Element to insert in the list.
@Param idx Index of the element after the insertion.
0 <= idx < list size
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.set(0,5); // the list contains 1 element at position 0, value = 5
intList.insertBefore(2,0); // the list contains 2 elements : 2,5
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,0,(const void *)5);
TCOD_list_insert_before(intList,(const void *)2,0);
*/
T * insertBefore(const T elt,int before) {
if ( fillSize+1 >= allocSize ) allocate();
for (int idx=fillSize; idx > before; idx--) {
array[idx]=array[idx-1];
}
array[before]=elt;
fillSize++;
return &array[before];
}
/**
@PageName list_list
@FuncTitle Removing an element from the list
@FuncDesc The _fast versions replace the element to remove with the last element of the list. They're faster, but do not preserve the list order.
@Cpp
template <class T> void TCODList::remove(const T elt)
template <class T> void TCODList::removeFast(const T elt)
@C
void TCOD_list_remove(TCOD_list_t l, const void * elt)
void TCOD_list_remove_fast(TCOD_list_t l, const void * elt)
@Param elt The element to remove
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.set(0,5); // the list contains 1 element at position 0, value = 5
intList.remove(5); // the list is empty
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,0,(const void *)5);
TCOD_list_remove(intList,(const void *)5);
*/
void remove(const T elt) {
for ( T* curElt = begin(); curElt != end(); curElt ++) {
if ( *curElt == elt ) {
remove(curElt);
return;
}
}
}
void removeFast(const T elt) {
for ( T* curElt = begin(); curElt != end(); curElt ++) {
if ( *curElt == elt ) {
removeFast(curElt);
return;
}
}
}
/**
@PageName list_list
@FuncTitle Concatenating two lists
@FuncDesc You can concatenate two lists. Every element of l2 will be added to current list (or l in the C version) :
@Cpp template <class T> void TCODList::addAll(const TCODList &l2)
@C void TCOD_list_add_all(TCOD_list_t l, TCOD_list_t l2)
@Param l The list inside which elements will be added.
@Param l2 the list handler containing elements to insert.
@CppEx
TCODList<int> intList;
intList.set(1,3); // intList contains 2 elements : 0, 3
TCODList<int> intList2; // intList2 is empty
intList2.set(0,1); // intList2 contains 1 element : 1
intList2.addAll(intList); // intList2 contains 3 elements : 1, 0, 3
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,1,(const void *)3);
TCOD_list_t intList2 = TCOD_list_new();
TCOD_list_set(intList2,0,(const void *)1);
TCOD_list_add_all(intList2,intList);
*/
void addAll(const TCODList<T> &l2) {
for (T *t=l2.begin(); t!= l2.end(); t++) {
push(*t);
}
}
/**
@PageName list_list
@FuncTitle Emptying a list
@Cpp template <class T> void TCODList::clear()
@C void TCOD_list_clear(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList;
intList.set(0,3); // intList contains 1 element
intList.clear(); // intList is empty
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_set(intList,0,(const void *)5);
TCOD_list_clear(intList);
*/
void clear() {
fillSize=0;
}
/**
@PageName list_list
@FuncTitle Emptying a list and destroying its elements
@FuncDesc For lists containing pointers, you can clear the list and delete (or free for C) the elements :
@Cpp template <class T> void TCODList::clearAndDelete()
@C void TCOD_list_clear_and_delete(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<MyClass *> intList;
MyClass * cl=new MyClass(); // new instance of MyClass allocated here
intList.set(0,cl);
intList.clear(); // the list is empty. cl is always valid
intList.set(0,cl);
intList.clearAndDelete(); // the list is empty. delete cl has been called. The address cl is no longer valid.
@C
TCOD_list_t intList = TCOD_list_new();
void *data=calloc(10,1); // some memory allocation here
TCOD_list_set(intList,0,(const void *)data);
TCOD_list_clear(intList); // the list is empty, but data is always valid
TCOD_list_set(intList,0,(const void *)data);
TCOD_list_clear_and_delete(intList); // the list is empty, free(data) has been called. The address data is no longer valid
*/
void clearAndDelete() {
for ( T* curElt = begin(); curElt != end(); curElt ++ ) {
delete (*curElt);
}
fillSize=0;
}
/**
@PageName list_list
@FuncTitle Reversing a list
@FuncDesc This function reverses the order of the elements in the list.</b>
@Cpp
void TCODList::reverse()
@C
void TCOD_list_reverse(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.push(5); // the list contains 1 element at position 0, value = 5
intList.push(2); // the list contains 2 elements : 5,2
intList.reverse(); // now order is 2,5
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_push(intList,(const void *)2);
TCOD_list_reverse();
*/
void reverse() {
T* head = begin();
T* tail = end();
while ( head < tail ) {
T tmp = *head;
*head=*tail;
*tail=tmp;
head++;
tail--;
}
}
/**
@PageName list_stack
@PageTitle Basic stack operations
@PageFather list
@FuncTitle Pushing an element on the stack
@FuncDesc You can push an element on the stack (append it to the end of the list) :
@Cpp template <class T> void TCODList::push(const T elt)
@C void TCOD_list_push(TCOD_list_t l, const void * elt)
@Param elt Element to append to the list.
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.push(5); // the list contains 1 element at position 0, value = 5
intList.push(2); // the list contains 2 elements : 5,2
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_push(intList,(const void *)2);
*/
void push(const T elt) {
if ( fillSize+1 >= allocSize ) allocate();
array[fillSize++] = elt;
}
/**
@PageName list_stack
@FuncTitle Poping an element from the stack
@FuncDesc You can pop an element from the stack (remove the last element of the list).
@Cpp template <class T> T TCODList::pop()
@C void * TCOD_list_pop(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.push(5); // the list contains 1 element at position 0, value = 5
intList.push(2); // the list contains 2 elements : 5,2
int val = intList.pop(); // val == 2, the list contains 1 element : 5
val = intList.pop(); // val == 5, the list is empty
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_push(intList,(const void *)2);
int val = (int)TCOD_list_pop(intList);
val = (int)TCOD_list_pop(intList);
*/
T pop() {
if ( fillSize == 0 ) return (T)0;
return array[--fillSize];
}
/**
@PageName list_stack
@FuncTitle Peeking the last element of the stack
@FuncDesc You can read the last element of the stack without removing it :
@Cpp template <class T> T TCODList::peek() const
@C void * TCOD_list_peek(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList;
intList.push(3); // intList contains 1 elements : 3
int val = intList.peek(); // val == 3, inList contains 1 elements : 3
intList.push(2); // intList contains 2 elements : 3, 2
val = intList.peek(); // val == 2, inList contains 2 elements : 3, 2
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)3);
int val = (int)TCOD_list_peek(intList);
TCOD_list_push(intList,(const void *)2);
val = (int)TCOD_list_peek(intList);
*/
T peek() const {
if ( fillSize == 0 ) return (T)0;
return array[fillSize-1];
}
/**
@PageName list_iterator
@PageFather list
@PageTitle Iterators
@FuncDesc You can iterate through the elements of the list using an iterator. begin() returns the address of the first element of the list. You go to the next element using the increment operator ++. When the iterator's value is equal to end(), you've gone through all the elements. <b>Warning ! You cannot insert elements in the list while iterating through it. Inserting elements can result in reallocation of the list and your iterator will not longer be valid.</b>
@Cpp
template <class T> T * TCODList::begin() const
template <class T> T * TCODList::end() const
@C
void ** TCOD_list_begin(TCOD_list_t l)
void ** TCOD_list_end(TCOD_list_t l)
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.push(5); // the list contains 1 element at position 0, value = 5
intList.push(2); // the list contains 2 elements : 5,2
for ( int * iterator = intList.begin(); iterator != intList.end(); iterator ++ ) {
int currentValue=*iterator;
printf("value : %d\n", currentValue );
}
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_push(intList,(const void *)2);
for ( int * iterator = (int *)TCOD_list_begin(intList); iterator != (int *)TCOD_list_end(intList); iterator ++ ) {
int currentValue=*iterator;
printf("value : %d\n", currentValue );
}
*/
T * begin() const {
if ( fillSize == 0 ) return (T *)NULL;
return &array[0];
}
T * end() const {
if ( fillSize == 0 ) return (T *)NULL;
return &array[fillSize];
}
/**
@PageName list_iterator
@FuncDesc You can remove an element from the list while iterating. The element at the iterator position will be removed. The function returns the new iterator. The _fast versions replace the element to remove with the last element of the list. They're faster, but do not preserve the list order.
@Cpp
template <class T> T *TCODList::remove(T *iterator)
template <class T> T *TCODList::removeFast(T *iterator)
@C
void **TCOD_list_remove_iterator(TCOD_list_t l, void **iterator)
void **TCOD_list_remove_iterator_fast(TCOD_list_t l, void **iterator)
@Param iterator The list iterator.
@Param l In the C version, the list handler, returned by a constructor.
@CppEx
TCODList<int> intList; // the list is empty (contains 0 elements)
intList.push(5); // the list contains 1 element at position 0, value = 5
intList.push(2); // the list contains 2 elements : 5,2
intList.push(3); // the list contains 3 elements : 5,2,3
for ( int * iterator = intList.begin(); iterator != intList.end(); iterator ++ ) {
int currentValue=*iterator;
if ( currentValue == 2 ) {
// remove this value from the list and keep iterating on next element (value == 3)
iterator = intList.remove(iterator);
}
printf("value : %d\n", currentValue ); // all 3 values will be printed : 5,2,3
}
// now the list contains only two elements : 5,3
@CEx
TCOD_list_t intList = TCOD_list_new();
TCOD_list_push(intList,(const void *)5);
TCOD_list_push(intList,(const void *)2);
TCOD_list_push(intList,(const void *)3);
for ( int * iterator = (int *)TCOD_list_begin(intList); iterator != (int *)TCOD_list_end(intList); iterator ++ ) {
int currentValue=*iterator;
if ( currentValue == 2 ) {
iterator = (int *)TCOD_list_remove_iterator(intList,(void **)iterator);
}
printf("value : %d\n", currentValue );
}
*/
T *remove(T *elt) {
for ( T* curElt = elt; curElt < end()-1; curElt ++) {
*curElt = *(curElt+1);
}
fillSize--;
if ( fillSize == 0 ) return ((T *)NULL)-1;
else return elt-1;
}
T *removeFast(T *elt) {
*elt = array[fillSize-1];
fillSize--;
if ( fillSize == 0 ) return ((T *)NULL)-1;
else return elt-1;
}
TCODList<T> & operator = (TCODList<T> const & l2) {
while ( allocSize < l2.allocSize ) allocate();
fillSize=l2.fillSize;
int i=0;
for (T *t=l2.begin(); t != l2.end(); t++) {
array[i++]=*t;
}
return *this;
}
protected :
void allocate() {
int newSize = allocSize * 2;
if ( newSize == 0 ) newSize = 16;
T *newArray = new T[ newSize ];
if ( array ) {
if ( fillSize > 0 ) memcpy(newArray, array, sizeof(T)*fillSize);
delete [] array;
}
array=newArray;
allocSize=newSize;
}
};
#endif

56
include/mersenne.h Normal file
View File

@ -0,0 +1,56 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_RANDOM_H
#define _TCOD_RANDOM_H
#include "mersenne_types.h"
typedef void *TCOD_random_t;
TCODLIB_API TCOD_random_t TCOD_random_get_instance(void);
TCODLIB_API TCOD_random_t TCOD_random_new(TCOD_random_algo_t algo);
TCODLIB_API TCOD_random_t TCOD_random_save(TCOD_random_t mersenne);
TCODLIB_API void TCOD_random_restore(TCOD_random_t mersenne, TCOD_random_t backup);
TCODLIB_API TCOD_random_t TCOD_random_new_from_seed(TCOD_random_algo_t algo, uint32 seed);
TCODLIB_API void TCOD_random_delete(TCOD_random_t mersenne);
TCODLIB_API void TCOD_random_set_distribution (TCOD_random_t mersenne, TCOD_distribution_t distribution);
TCODLIB_API int TCOD_random_get_int (TCOD_random_t mersenne, int min, int max);
TCODLIB_API float TCOD_random_get_float (TCOD_random_t mersenne, float min, float max);
TCODLIB_API double TCOD_random_get_double (TCOD_random_t mersenne, double min, double max);
TCODLIB_API int TCOD_random_get_int_mean (TCOD_random_t mersenne, int min, int max, int mean);
TCODLIB_API float TCOD_random_get_float_mean (TCOD_random_t mersenne, float min, float max, float mean);
TCODLIB_API double TCOD_random_get_double_mean (TCOD_random_t mersenne, double min, double max, double mean);
TCODLIB_API TCOD_dice_t TCOD_random_dice_new (const char * s);
TCODLIB_API int TCOD_random_dice_roll (TCOD_random_t mersenne, TCOD_dice_t dice);
TCODLIB_API int TCOD_random_dice_roll_s (TCOD_random_t mersenne, const char * s);
#endif

400
include/mersenne.hpp Normal file
View File

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

53
include/mersenne_types.h Normal file
View File

@ -0,0 +1,53 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_RANDOM_TYPES_H
#define _TCOD_RANDOM_TYPES_H
/* dice roll */
typedef struct {
int nb_rolls;
int nb_faces;
float multiplier;
float addsub;
} TCOD_dice_t;
/* PRNG algorithms */
typedef enum {
TCOD_RNG_MT,
TCOD_RNG_CMWC
} TCOD_random_algo_t;
typedef enum {
TCOD_DISTRIBUTION_LINEAR,
TCOD_DISTRIBUTION_GAUSSIAN,
TCOD_DISTRIBUTION_GAUSSIAN_RANGE,
TCOD_DISTRIBUTION_GAUSSIAN_INVERSE,
TCOD_DISTRIBUTION_GAUSSIAN_RANGE_INVERSE
} TCOD_distribution_t;
#endif /* _TCOD_RANDOM_TYPES_H */

39
include/mouse.h Normal file
View File

@ -0,0 +1,39 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_MOUSE_H
#define _TCOD_MOUSE_H
#include "mouse_types.h"
TCODLIB_API void TCOD_mouse_show_cursor(bool visible);
TCODLIB_API TCOD_mouse_t TCOD_mouse_get_status();
TCODLIB_API bool TCOD_mouse_is_cursor_visible();
TCODLIB_API void TCOD_mouse_move(int x, int y);
TCODLIB_API void TCOD_mouse_includes_touch(bool enable);
#endif

76
include/mouse.hpp Normal file
View File

@ -0,0 +1,76 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_MOUSE_HPP
#define _TCOD_MOUSE_HPP
#include "mouse_types.h"
class TCODLIB_API TCODMouse {
public :
/**
@PageName mouse
@PageTitle Mouse support
@PageCategory Base toolkits
@FuncTitle Display and hide the mouse cursor
@FuncDesc By default, the mouse cursor in visible in windowed mode, hidden in fullscreen mode. You can change it with:
@Cpp static void TCODMouse::showCursor (bool visible)
@C void TCOD_mouse_show_cursor (bool visible)
@Py mouse_show_cursor (visible)
@C# void TCODMouse::showCursor(bool visible)
@Param visible If true, this function turns the mouse cursor on. Else it turns the mouse cursor off.
*/
static void showCursor(bool visible);
/**
@PageName mouse
@FuncTitle Getting the cursor status
@FuncDesc You can get the current cursor status (hidden or visible) with:
@Cpp static bool TCODMouse::isCursorVisible (void)
@C bool TCOD_mouse_is_cursor_visible (void)
@Py mouse_is_cursor_visible ()
@C# bool TCODMouse::isCursorVisible()
*/
static bool isCursorVisible();
/**
@PageName mouse
@FuncTitle Setting the mouse cursor's position
@FuncDesc You can set the cursor position (in pixel coordinates, where [0,0] is the window's top left corner) with:
@Cpp static void TCODMouse::move (int x, int y)
@C void TCOD_mouse_move (int x, int y)
@Py mouse_move (x, y)
@C# void TCODMouse::moveMouse(int x, int y)
@Param x,y New coordinates of the mouse cursor in pixels.
*/
static void move(int x, int y);
/* deprecated as of 1.5.1 */
static TCOD_mouse_t getStatus();
};
#endif

47
include/mouse_types.h Normal file
View File

@ -0,0 +1,47 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_MOUSE_TYPES_H
#define _TCOD_MOUSE_TYPES_H
/* mouse data */
typedef struct {
int x,y; /* absolute position */
int dx,dy; /* movement since last update in pixels */
int cx,cy; /* cell coordinates in the root console */
int dcx,dcy; /* movement since last update in console cells */
bool lbutton ; /* left button status */
bool rbutton ; /* right button status */
bool mbutton ; /* middle button status */
bool lbutton_pressed ; /* left button pressed event */
bool rbutton_pressed ; /* right button pressed event */
bool mbutton_pressed ; /* middle button pressed event */
bool wheel_up ; /* wheel up event */
bool wheel_down ; /* wheel down event */
} TCOD_mouse_t;
#endif /* _TCOD_MOUSE_TYPES_H */

49
include/namegen.h Normal file
View File

@ -0,0 +1,49 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Mingos' NameGen
* This file was written by Dominik "Mingos" Marczuk.
*/
#ifndef _TCOD_NAMEGEN_H
#define _TCOD_NAMEGEN_H
/* the generator typedef */
typedef void * TCOD_namegen_t;
/* parse a file with syllable sets */
TCODLIB_API void TCOD_namegen_parse (const char * filename, TCOD_random_t random);
/* generate a name */
TCODLIB_API char * TCOD_namegen_generate (char * name, bool allocate);
/* generate a name using a custom generation rule */
TCODLIB_API char * TCOD_namegen_generate_custom (char * name, char * rule, bool allocate);
/* retrieve the list of all available syllable set names */
TCODLIB_API TCOD_list_t TCOD_namegen_get_sets (void);
/* delete a generator */
TCODLIB_API void TCOD_namegen_destroy (void);
#endif

290
include/namegen.hpp Normal file
View File

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

56
include/noise.h Normal file
View File

@ -0,0 +1,56 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_PERLIN_H
#define _TCOD_PERLIN_H
typedef void *TCOD_noise_t;
typedef enum {
TCOD_NOISE_PERLIN = 1,
TCOD_NOISE_SIMPLEX = 2,
TCOD_NOISE_WAVELET = 4,
TCOD_NOISE_DEFAULT = 0
} TCOD_noise_type_t;
#include "noise_defaults.h"
/* create a new noise object */
TCODLIB_API TCOD_noise_t TCOD_noise_new(int dimensions, float hurst, float lacunarity, TCOD_random_t random);
/* simplified API */
TCODLIB_API void TCOD_noise_set_type (TCOD_noise_t noise, TCOD_noise_type_t type);
TCODLIB_API float TCOD_noise_get_ex (TCOD_noise_t noise, float *f, TCOD_noise_type_t type);
TCODLIB_API float TCOD_noise_get_fbm_ex (TCOD_noise_t noise, float *f, float octaves, TCOD_noise_type_t type);
TCODLIB_API float TCOD_noise_get_turbulence_ex (TCOD_noise_t noise, float *f, float octaves, TCOD_noise_type_t type);
TCODLIB_API float TCOD_noise_get (TCOD_noise_t noise, float *f);
TCODLIB_API float TCOD_noise_get_fbm (TCOD_noise_t noise, float *f, float octaves);
TCODLIB_API float TCOD_noise_get_turbulence (TCOD_noise_t noise, float *f, float octaves);
/* delete the noise object */
TCODLIB_API void TCOD_noise_delete(TCOD_noise_t noise);
#endif

323
include/noise.hpp Normal file
View File

@ -0,0 +1,323 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_PERLIN_HPP
#define _TCOD_PERLIN_HPP
#include "noise_defaults.h"
/**
@PageName noise
@PageCategory Base toolkits
@PageTitle Noise generator
@PageDesc This toolkit provides several functions to generate Perlin noise and other derived noises. It can handle noise functions from 1 to 4 dimensions.
@FuncDesc
Usage example:
1D noise : the variation of a torch intensity
2D fbm : heightfield generation or clouds
3D fbm : animated smoke
If you don't know what is Perlin noise and derived functions, or what is the influence of the different fractal parameters, check the Perlin noise sample included with the library.
<table width="800px" class="none">
<tr><td align="center">Simplex noise, fbm, turbulence</td>
<td align="center"><img border="1" src="simplex.png"></td>
<td align="center"><img border="1" src="fbm_simplex.png"></td>
<td align="center"><img border="1" src="turbulence_simplex.png"></td></tr>
<tr><td align="center">Perlin noise, fbm, turbulence</td>
<td align="center"><img border="1" src="perlin.png"></td>
<td align="center"><img border="1" src="fbm_perlin.png"></td>
<td align="center"><img border="1" src="turbulence_perlin.png"></td></tr>
<tr><td align="center">Wavelet noise, fbm, turbulence</td>
<td align="center"><img border="1" src="wavelet.png"></td>
<td align="center"><img border="1" src="fbm_wavelet.png"></td>
<td align="center"><img border="1" src="turbulence_wavelet.png"></td></tr>
</table>
<h6>Noise functions relative times</h6>
For example, in 4D, Perlin noise is 17 times slower than simplex noise.
<table border="1">
<tr><td></td><td>1D</td><td>2D</td><td>3D</td><td>4D</td></tr>
<tr><td>simplex</td><td>1</td><td>1</td><td>1</td><td>1</td></tr>
<tr><td>Perlin</td><td>1.3</td><td>4</td><td>5</td><td>17</td></tr>
<tr><td>wavelet</td><td>53</td><td>32</td><td>14</td><td>X</td></tr>
</table>
*/
class TCODLIB_API TCODNoise {
public :
/**
@PageName noise_init
@PageFather noise
@PageTitle Creating a noise generator
@FuncDesc Those functions initialize a noise generator from a number of dimensions (from 1 to 4), some fractal parameters and a random number generator.
The C++ version provides several constructors. When the hurst and lacunarity parameters are omitted, default values (TCOD_NOISE_DEFAULT_HURST = 0.5f and TCOD_NOISE_DEFAULT_LACUNARITY = 2.0f) are used.
@Cpp
TCODNoise::TCODNoise(int dimensions, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
TCODNoise::TCODNoise(int dimensions, TCODRandom *random, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity, TCODRandom *random, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
@C TCOD_noise_t TCOD_noise_new(int dimensions, float hurst, float lacunarity, TCOD_random_t random)
@Py noise_new(dimensions, hurst=TCOD_NOISE_DEFAULT_HURST, lacunarity=TCOD_NOISE_DEFAULT_LACUNARITY, random=0)
@C#
TCODNoise::TCODNoise(int dimensions)
TCODNoise::TCODNoise(int dimensions, TCODRandom random)
TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity)
TCODNoise::TCODNoise(int dimensions, float hurst, float lacunarity, TCODRandom random)
@Param dimensions From 1 to 4.
@Param hurst For fractional brownian motion and turbulence, the fractal Hurst exponent. You can use the default value TCOD_NOISE_DEFAULT_HURST = 0.5f.
@Param lacunarity For fractional brownian motion and turbulence, the fractal lacunarity. You can use the default value TCOD_NOISE_DEFAULT_LACUNARITY = 2.0f.
@Param random A random number generator obtained with the Mersenne twister toolkit or NULL to use the default random number generator.
@CppEx
// 1 dimension generator
TCODNoise * noise1d = new TCODNoise(1);
// 2D noise with a predefined random number generator
TCODRandom *myRandom = new TCODRandom();
TCODNoise *noise2d = new TCODNoise(2,myRandom);
// a 3D noise generator with a specific fractal parameters
TCODNoise *noise3d = new TCODNoise(3,0.7f,1.4f);
@CEx
// 1 dimension generator
TCOD_noise_t noise1d = TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
// 2D noise with a predefined random number generator
TCOD_random_t my_random = TCOD_random_new();
TCOD_noise_t noise2d = TCOD_noise_new(2,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,my_random);
// a 3D noise generator with a specific fractal parameters
TCOD_noise_t noise3d = TCOD_noise_new(3,0.7f, 1.4f,NULL);
@PyEx
# 1 dimension generator
noise1d = libtcod.noise_new(1)
# 2D noise with a predefined random number generator
my_random = libtcod.random_new();
noise2d = libtcod.noise_new(2,libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY,my_random)
# a 3D noise generator with a specific fractal parameters
noise3d = libtcod.noise_new(3, 0.7, 1.4)
*/
TCODNoise(int dimensions, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
TCODNoise(int dimensions, TCODRandom *random, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
TCODNoise(int dimensions, float hurst, float lacunarity, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
TCODNoise(int dimensions, float hurst, float lacunarity, TCODRandom *random, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
/**
@PageName noise_init
@FuncDesc To release ressources used by a generator, use those functions :
@Cpp TCODNoise::~TCODNoise()
@C void TCOD_noise_delete(TCOD_noise_t noise)
@Py noise_delete(noise)
@C# void TCODNoise::Dispose()
@Param noise In the C and python versions, the generator handler, returned by the initialization function.
@CppEx
// create a generator
TCODNoise *noise = new TCODNoise(2);
// use it
...
// destroy it
delete noise;
@CEx
// create a generator
TCOD_noise_t noise = TCOD_noise_new(2,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAUT_LACUNARITY, NULL);
// use it
...
// destroy it
TCOD_noise_delete(noise);
@PyEx
# create a generator
noise = libtcod.noise_new(2,litbcod.NOISE_DEFAULT_HURST, litbcod.NOISE_DEFAUT_LACUNARITY, 0)
# use it
...
# destroy it
litbcod.noise_delete(noise)
*/
virtual ~TCODNoise();
/**
@PageName noise_setType
@PageFather noise
@PageTitle Choosing a noise type
@FuncTitle Choosing a noise type
@FuncDesc Use this function to define the default algorithm used by the noise functions.
The default algorithm is simplex. It's much faster than Perlin, especially in 4 dimensions. It has a better contrast too.
@Cpp void TCODNoise::setType(TCOD_noise_type_t type)
@C void TCOD_noise_set_type(TCOD_noise_t noise, TCOD_noise_type_t type)
@Py noise_set_type(noise, type)
@C# void TCODNoise::setType(type)
@Param noise In the C version, the generator handler, returned by the initialization function.
@Param type The algorithm to use, either TCOD_NOISE_SIMPLEX, TCOD_NOISE_PERLIN or TCOD_NOISE_WAVELET.
@CppEx
TCODNoise * noise1d = new TCODNoise(1);
noise1d->setType(TCOD_NOISE_PERLIN);
@CEx
TCOD_noise_t noise1d = TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
TCOD_noise_set_type(noise1d,TCOD_NOISE_PERLIN);
@PyEx
noise1d = libtcod.noise_new(1)
libtcod.noise_set_type(noise1d,libtcod.NOISE_PERLIN)
*/
void setType (TCOD_noise_type_t type);
/**
@PageName noise_get
@PageFather noise
@PageTitle Getting flat noise
@FuncDesc This function returns the noise function value between -1.0 and 1.0 at given coordinates.
@Cpp float TCODNoise::get(float *f, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
@C float TCOD_noise_get(TCOD_noise_t noise, float *f)
float TCOD_noise_get_ex(TCOD_noise_t noise, float *f, TCOD_noise_type_t type)
@Py noise_get(noise, f, type=NOISE_DEFAULT)
@C# float TCODNoise::get(float[] f, type=NoiseDefault)
@Param noise In the C version, the generator handler, returned by the initialization function.
@Param f An array of coordinates, depending on the generator dimensions (between 1 and 4). The same array of coordinates will always return the same value.
@Param type The algorithm to use. If not defined, use the default one (set with setType or simplex if not set)
@CppEx
// 1d noise
TCODNoise * noise1d = new TCODNoise(1);
float p=0.5f;
// get a 1d simplex value
float value = noise1d->get(&p);
// 2d noise
TCODNoise * noise2d = new TCODNoise(2);
float p[2]={0.5f,0.7f};
// get a 2D Perlin value
float value = noise2d->get(p, TCOD_NOISE_PERLIN);
@CEx
// 1d noise
TCOD_noise_t noise1d = TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p=0.5f;
// get a 1d simplex value
float value = TCOD_noise_get(noise1d,&p);
// 2d noise
TCOD_noise_t noise2d = TCOD_noise_new(2,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p[2]={0.5f,0.7f};
// get a 2d perlin value
float value = TCOD_noise_get_ex(noise2d,p,TCOD_NOISE_PERLIN);
@PyEx
# 1d noise
noise1d = libtcod.noise_new(1)
# get a 1d simplex value
value = libtcod.noise_get(noise1d,[0.5])
# 2d noise
noise2d = libtcod.noise_new(2)
# get a 2d perlin value
value = libtcod.noise_get(noise2d,[0.5,0.7], libtcod.NOISE_PERLIN)
*/
float get(float *f, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
/**
@PageName noise_get_fbm
@PageFather noise
@PageTitle Getting fbm noise
@FuncDesc This function returns the fbm function value between -1.0 and 1.0 at given coordinates, using fractal hurst and lacunarity defined when the generator has been created.
@Cpp float TCODNoise::getFbm(float *f, float octaves, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
@C float TCOD_noise_get_fbm(TCOD_noise_t noise, float *f, float octaves)
float TCOD_noise_get_fbm(TCOD_noise_t noise, float *f, float octaves, TCOD_noise_type_t type)
@Py noise_get_fbm(noise, f, octaves, type=NOISE_DEFAULT)
@C# float TCODNoise::getBrownianMotion(float[] f, float octaves, type=NoiseDefault)
@Param noise In the C version, the generator handler, returned by the initialization function.
@Param f An array of coordinates, depending on the generator dimensions (between 1 and 4). The same array of coordinates will always return the same value.
@Param octaves Number of iterations. Must be < TCOD_NOISE_MAX_OCTAVES = 128
@Param type The algorithm to use. If not defined, use the default one (set with setType or simplex if not set)
@CppEx
// 1d fbm
TCODNoise * noise1d = new TCODNoise(1);
float p=0.5f;
// get a 1d simplex fbm
float value = noise1d->getFbm(&p,32.0f);
// 2d fbm
TCODNoise * noise2d = new TCODNoise(2);
float p[2]={0.5f,0.7f};
// get a 2d perlin fbm
float value = noise2d->getFbm(p,32.0f, TCOD_NOISE_PERLIN);
@CEx
// 1d fbm
TCOD_noise_t noise1d = TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p=0.5f;
// get a 1d simplex fbm
float value = TCOD_noise_get_fbm(noise1d,&p,32.0f);
// 2d fbm
TCOD_noise_t noise2d = TCOD_noise_new(2,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p[2]={0.5f,0.7f};
// get a 2d perlin fbm
float value = TCOD_noise_get_fbm_ex(noise2d,p,32.0f,TCOD_NOISE_PERLIN);
@PyEx
# 1d noise
noise1d = libtcod.noise_new(1)
# 1d simplex fbm
value = libtcod.noise_get_fbm(noise1d,[0.5],32.0)
# 2d noise
noise2d = libtcod.noise_new(2)
# 2d perlin fbm
value = libtcod.noise_get_fbm(noise2d,[0.5,0.7],32.0, libtcod.NOISE_PERLIN)
*/
float getFbm(float *f, float octaves, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
/**
@PageName noise_get_turbulence
@PageFather noise
@PageTitle Getting turbulence
@FuncDesc This function returns the turbulence function value between -1.0 and 1.0 at given coordinates, using fractal hurst and lacunarity defined when the generator has been created.
@Cpp float TCODNoise::getTurbulence(float *f, float octaves, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT)
@C float TCOD_noise_get_turbulence(TCOD_noise_t noise, float *f, float octaves)
float TCOD_noise_get_turbulence_ex(TCOD_noise_t noise, float *f, float octaves, TCOD_noise_type_t)
@Py noise_get_turbulence(noise, f, octaves, type=NOISE_DEFAULT)
@C# float TCODNoise::getTurbulence(float[] f, float octaves, type=NoiseDefault)
@Param noise In the C version, the generator handler, returned by the initialization function.
@Param f An array of coordinates, depending on the generator dimensions (between 1 and 4). The same array of coordinates will always return the same value.
@Param octaves Number of iterations. Must be < TCOD_NOISE_MAX_OCTAVES = 128
@CppEx
// 1d fbm
TCODNoise * noise1d = new TCODNoise(1);
float p=0.5f;
// a 1d simplex turbulence
float value = noise1d->getTurbulence(&p,32.0f);
// 2d fbm
TCODNoise * noise2d = new TCODNoise(2);
float p[2]={0.5f,0.7f};
// a 2d perlin turbulence
float value = noise2d->getTurbulence(p,32.0f, TCOD_NOISE_PERLIN);
@CEx
// 1d fbm
TCOD_noise_t noise1d = TCOD_noise_new(1,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p=0.5f;
// a 1d simplex turbulence
float value = TCOD_noise_get_turbulence(noise1d,&p,32.0f);
// 2d fbm
TCOD_noise_t noise2d = TCOD_noise_new(2,TCOD_NOISE_DEFAULT_HURST, TCOD_NOISE_DEFAULT_LACUNARITY,NULL);
float p[2]={0.5f,0.7f};
// a 2d perlin turbulence
float value = TCOD_noise_get_turbulence_ex(noise2d,p,32.0f, TCOD_NOISE_PERLIN);
@PyEx
# 1d noise
noise1d = libtcod.noise_new(1)
# 1d simplex turbulence
value = libtcod.noise_get_turbulence(noise1d,[0.5],32.0)
# 2d noise
noise2d = libtcod.noise_new(2)
# 2d perlin turbulence
value = libtcod.noise_get_turbulence(noise2d,[0.5,0.7],32.0,libtcod.NOISE_PERLIN)
*/
float getTurbulence(float *f, float octaves, TCOD_noise_type_t type = TCOD_NOISE_DEFAULT);
protected :
friend class TCODLIB_API TCODHeightMap;
TCOD_noise_t data;
};
#endif

9
include/noise_defaults.h Normal file
View File

@ -0,0 +1,9 @@
#ifndef _TCOD_NOISE_DEFAULTS
#define _TCOD_NOISE_DEFAULTS
#define TCOD_NOISE_MAX_OCTAVES 128
#define TCOD_NOISE_MAX_DIMENSIONS 4
#define TCOD_NOISE_DEFAULT_HURST 0.5f
#define TCOD_NOISE_DEFAULT_LACUNARITY 2.0f
#endif /* _TCOD_NOISE_DEFAULTS */

171
include/parser.h Normal file
View File

@ -0,0 +1,171 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_PARSER_H
#define _TCOD_PARSER_H
/* generic type */
typedef enum {
TCOD_TYPE_NONE,
TCOD_TYPE_BOOL,
TCOD_TYPE_CHAR,
TCOD_TYPE_INT,
TCOD_TYPE_FLOAT,
TCOD_TYPE_STRING,
TCOD_TYPE_COLOR,
TCOD_TYPE_DICE,
TCOD_TYPE_VALUELIST00,
TCOD_TYPE_VALUELIST01,
TCOD_TYPE_VALUELIST02,
TCOD_TYPE_VALUELIST03,
TCOD_TYPE_VALUELIST04,
TCOD_TYPE_VALUELIST05,
TCOD_TYPE_VALUELIST06,
TCOD_TYPE_VALUELIST07,
TCOD_TYPE_VALUELIST08,
TCOD_TYPE_VALUELIST09,
TCOD_TYPE_VALUELIST10,
TCOD_TYPE_VALUELIST11,
TCOD_TYPE_VALUELIST12,
TCOD_TYPE_VALUELIST13,
TCOD_TYPE_VALUELIST14,
TCOD_TYPE_VALUELIST15,
TCOD_TYPE_CUSTOM00,
TCOD_TYPE_CUSTOM01,
TCOD_TYPE_CUSTOM02,
TCOD_TYPE_CUSTOM03,
TCOD_TYPE_CUSTOM04,
TCOD_TYPE_CUSTOM05,
TCOD_TYPE_CUSTOM06,
TCOD_TYPE_CUSTOM07,
TCOD_TYPE_CUSTOM08,
TCOD_TYPE_CUSTOM09,
TCOD_TYPE_CUSTOM10,
TCOD_TYPE_CUSTOM11,
TCOD_TYPE_CUSTOM12,
TCOD_TYPE_CUSTOM13,
TCOD_TYPE_CUSTOM14,
TCOD_TYPE_CUSTOM15,
TCOD_TYPE_LIST=1024
} TCOD_value_type_t;
/* generic value */
typedef union {
bool b;
char c;
int32 i;
float f;
char *s;
TCOD_color_t col;
TCOD_dice_t dice;
TCOD_list_t list;
void *custom;
} TCOD_value_t;
/* parser structures */
typedef void *TCOD_parser_struct_t;
TCODLIB_API const char *TCOD_struct_get_name(TCOD_parser_struct_t def);
TCODLIB_API void TCOD_struct_add_property(TCOD_parser_struct_t def, const char *name,TCOD_value_type_t type, bool mandatory);
TCODLIB_API void TCOD_struct_add_list_property(TCOD_parser_struct_t def, const char *name,TCOD_value_type_t type, bool mandatory);
TCODLIB_API void TCOD_struct_add_value_list(TCOD_parser_struct_t def,const char *name, const char **value_list, bool mandatory);
TCODLIB_API void TCOD_struct_add_value_list_sized(TCOD_parser_struct_t def,const char *name, const char **value_list, int size, bool mandatory);
TCODLIB_API void TCOD_struct_add_flag(TCOD_parser_struct_t def,const char *propname);
TCODLIB_API void TCOD_struct_add_structure(TCOD_parser_struct_t def,TCOD_parser_struct_t sub_structure);
TCODLIB_API bool TCOD_struct_is_mandatory(TCOD_parser_struct_t def,const char *propname);
TCODLIB_API TCOD_value_type_t TCOD_struct_get_type(TCOD_parser_struct_t def, const char *propname);
/* parser listener */
typedef struct {
bool (*new_struct)(TCOD_parser_struct_t str,const char *name);
bool (*new_flag)(const char *name);
bool (*new_property)(const char *propname, TCOD_value_type_t type, TCOD_value_t value);
bool (*end_struct)(TCOD_parser_struct_t str, const char *name);
void (*error)(const char *msg);
} TCOD_parser_listener_t;
/* a custom type parser */
typedef TCOD_value_t (*TCOD_parser_custom_t)(TCOD_lex_t *lex, TCOD_parser_listener_t *listener, TCOD_parser_struct_t str, char *propname);
/* the parser */
typedef void *TCOD_parser_t;
TCODLIB_API TCOD_parser_t TCOD_parser_new();
TCODLIB_API TCOD_parser_struct_t TCOD_parser_new_struct(TCOD_parser_t parser, char *name);
TCODLIB_API TCOD_value_type_t TCOD_parser_new_custom_type(TCOD_parser_t parser,TCOD_parser_custom_t custom_type_parser);
TCODLIB_API void TCOD_parser_run(TCOD_parser_t parser, const char *filename, TCOD_parser_listener_t *listener);
TCODLIB_API void TCOD_parser_delete(TCOD_parser_t parser);
/* error during parsing. can be called by the parser listener */
TCODLIB_API void TCOD_parser_error(const char *msg, ...);
/* default parser listener */
TCODLIB_API bool TCOD_parser_has_property(TCOD_parser_t parser, const char *name);
TCODLIB_API bool TCOD_parser_get_bool_property(TCOD_parser_t parser, const char *name);
TCODLIB_API int TCOD_parser_get_char_property(TCOD_parser_t parser, const char *name);
TCODLIB_API int TCOD_parser_get_int_property(TCOD_parser_t parser, const char *name);
TCODLIB_API float TCOD_parser_get_float_property(TCOD_parser_t parser, const char *name);
TCODLIB_API const char * TCOD_parser_get_string_property(TCOD_parser_t parser, const char *name);
TCODLIB_API TCOD_color_t TCOD_parser_get_color_property(TCOD_parser_t parser, const char *name);
TCODLIB_API TCOD_dice_t TCOD_parser_get_dice_property(TCOD_parser_t parser, const char *name);
TCODLIB_API void TCOD_parser_get_dice_property_py(TCOD_parser_t parser, const char *name, TCOD_dice_t *dice);
TCODLIB_API void * TCOD_parser_get_custom_property(TCOD_parser_t parser, const char *name);
TCODLIB_API TCOD_list_t TCOD_parser_get_list_property(TCOD_parser_t parser, const char *name, TCOD_value_type_t type);
/* parser internals (may be used by custom type parsers) */
/* parser structures */
typedef struct {
char *name; /* entity type name */
/* list of flags */
TCOD_list_t flags;
/* list of properties (name, type, mandatory) */
TCOD_list_t props;
/* list of value lists */
TCOD_list_t lists;
/* list of sub-structures */
TCOD_list_t structs;
} TCOD_struct_int_t;
/* the parser */
typedef struct {
/* list of structures */
TCOD_list_t structs;
/* list of custom type parsers */
TCOD_parser_custom_t customs[16];
/* fatal error occured */
bool fatal;
/* list of properties if default listener is used */
TCOD_list_t props;
} TCOD_parser_int_t;
TCODLIB_API TCOD_value_t TCOD_parse_bool_value();
TCODLIB_API TCOD_value_t TCOD_parse_char_value();
TCODLIB_API TCOD_value_t TCOD_parse_integer_value();
TCODLIB_API TCOD_value_t TCOD_parse_float_value();
TCODLIB_API TCOD_value_t TCOD_parse_string_value();
TCODLIB_API TCOD_value_t TCOD_parse_color_value();
TCODLIB_API TCOD_value_t TCOD_parse_dice_value();
TCODLIB_API TCOD_value_t TCOD_parse_value_list_value(TCOD_struct_int_t *def,int listnum);
TCODLIB_API TCOD_value_t TCOD_parse_property_value(TCOD_parser_int_t *parser, TCOD_parser_struct_t def, char *propname, bool list);
#endif

672
include/parser.hpp Normal file
View File

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

63
include/path.h Normal file
View File

@ -0,0 +1,63 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_PATH_H
#define _TCOD_PATH_H
typedef float (*TCOD_path_func_t)( int xFrom, int yFrom, int xTo, int yTo, void *user_data );
typedef void *TCOD_path_t;
TCODLIB_API TCOD_path_t TCOD_path_new_using_map(TCOD_map_t map, float diagonalCost);
TCODLIB_API TCOD_path_t TCOD_path_new_using_function(int map_width, int map_height, TCOD_path_func_t func, void *user_data, float diagonalCost);
TCODLIB_API bool TCOD_path_compute(TCOD_path_t path, int ox,int oy, int dx, int dy);
TCODLIB_API bool TCOD_path_walk(TCOD_path_t path, int *x, int *y, bool recalculate_when_needed);
TCODLIB_API bool TCOD_path_is_empty(TCOD_path_t path);
TCODLIB_API int TCOD_path_size(TCOD_path_t path);
TCODLIB_API void TCOD_path_reverse(TCOD_path_t path);
TCODLIB_API void TCOD_path_get(TCOD_path_t path, int index, int *x, int *y);
TCODLIB_API void TCOD_path_get_origin(TCOD_path_t path, int *x, int *y);
TCODLIB_API void TCOD_path_get_destination(TCOD_path_t path, int *x, int *y);
TCODLIB_API void TCOD_path_delete(TCOD_path_t path);
/* Dijkstra stuff - by Mingos*/
typedef void *TCOD_dijkstra_t;
TCODLIB_API TCOD_dijkstra_t TCOD_dijkstra_new (TCOD_map_t map, float diagonalCost);
TCODLIB_API TCOD_dijkstra_t TCOD_dijkstra_new_using_function(int map_width, int map_height, TCOD_path_func_t func, void *user_data, float diagonalCost);
TCODLIB_API void TCOD_dijkstra_compute (TCOD_dijkstra_t dijkstra, int root_x, int root_y);
TCODLIB_API float TCOD_dijkstra_get_distance (TCOD_dijkstra_t dijkstra, int x, int y);
TCODLIB_API bool TCOD_dijkstra_path_set (TCOD_dijkstra_t dijkstra, int x, int y);
TCODLIB_API bool TCOD_dijkstra_is_empty(TCOD_dijkstra_t path);
TCODLIB_API int TCOD_dijkstra_size(TCOD_dijkstra_t path);
TCODLIB_API void TCOD_dijkstra_reverse(TCOD_dijkstra_t path);
TCODLIB_API void TCOD_dijkstra_get(TCOD_dijkstra_t path, int index, int *x, int *y);
TCODLIB_API bool TCOD_dijkstra_path_walk (TCOD_dijkstra_t dijkstra, int *x, int *y);
TCODLIB_API void TCOD_dijkstra_delete (TCOD_dijkstra_t dijkstra);
#endif

552
include/path.hpp Normal file
View File

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

120
include/sys.h Normal file
View File

@ -0,0 +1,120 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_SYS_H
#define _TCOD_SYS_H
TCODLIB_API void TCOD_sys_startup();
TCODLIB_API uint32 TCOD_sys_elapsed_milli();
TCODLIB_API float TCOD_sys_elapsed_seconds();
TCODLIB_API void TCOD_sys_sleep_milli(uint32 val);
TCODLIB_API void TCOD_sys_save_screenshot(const char *filename);
TCODLIB_API void TCOD_sys_force_fullscreen_resolution(int width, int height);
TCODLIB_API void TCOD_sys_set_renderer(TCOD_renderer_t renderer);
TCODLIB_API TCOD_renderer_t TCOD_sys_get_renderer();
TCODLIB_API void TCOD_sys_set_fps(int val);
TCODLIB_API int TCOD_sys_get_fps();
TCODLIB_API float TCOD_sys_get_last_frame_length();
TCODLIB_API void TCOD_sys_get_current_resolution(int *w, int *h);
TCODLIB_API void TCOD_sys_get_fullscreen_offsets(int *offx, int *offy);
TCODLIB_API void TCOD_sys_update_char(int asciiCode, int fontx, int fonty, TCOD_image_t img, int x, int y);
TCODLIB_API void TCOD_sys_get_char_size(int *w, int *h);
TCODLIB_API void *TCOD_sys_get_SDL_window();
typedef enum {
TCOD_EVENT_NONE=0,
TCOD_EVENT_KEY_PRESS=1,
TCOD_EVENT_KEY_RELEASE=2,
TCOD_EVENT_KEY=TCOD_EVENT_KEY_PRESS|TCOD_EVENT_KEY_RELEASE,
TCOD_EVENT_MOUSE_MOVE=4,
TCOD_EVENT_MOUSE_PRESS=8,
TCOD_EVENT_MOUSE_RELEASE=16,
TCOD_EVENT_MOUSE=TCOD_EVENT_MOUSE_MOVE|TCOD_EVENT_MOUSE_PRESS|TCOD_EVENT_MOUSE_RELEASE,
/* #ifdef TCOD_TOUCH_INPUT */
TCOD_EVENT_FINGER_MOVE=32,
TCOD_EVENT_FINGER_PRESS=64,
TCOD_EVENT_FINGER_RELEASE=128,
TCOD_EVENT_FINGER=TCOD_EVENT_FINGER_MOVE|TCOD_EVENT_FINGER_PRESS|TCOD_EVENT_FINGER_RELEASE,
/* #endif */
TCOD_EVENT_ANY=TCOD_EVENT_KEY|TCOD_EVENT_MOUSE|TCOD_EVENT_FINGER,
} TCOD_event_t;
TCODLIB_API TCOD_event_t TCOD_sys_wait_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse, bool flush);
TCODLIB_API TCOD_event_t TCOD_sys_check_for_event(int eventMask, TCOD_key_t *key, TCOD_mouse_t *mouse);
/* filesystem stuff */
TCODLIB_API bool TCOD_sys_create_directory(const char *path);
TCODLIB_API bool TCOD_sys_delete_file(const char *path);
TCODLIB_API bool TCOD_sys_delete_directory(const char *path);
TCODLIB_API bool TCOD_sys_is_directory(const char *path);
TCODLIB_API TCOD_list_t TCOD_sys_get_directory_content(const char *path, const char *pattern);
TCODLIB_API bool TCOD_sys_file_exists(const char * filename, ...);
TCODLIB_API bool TCOD_sys_read_file(const char *filename, unsigned char **buf, size_t *size);
TCODLIB_API bool TCOD_sys_write_file(const char *filename, unsigned char *buf, uint32 size);
/* clipboard */
TCODLIB_API void TCOD_sys_clipboard_set(const char *value);
TCODLIB_API char *TCOD_sys_clipboard_get();
/* thread stuff */
typedef void *TCOD_thread_t;
typedef void *TCOD_semaphore_t;
typedef void *TCOD_mutex_t;
typedef void *TCOD_cond_t;
/* threads */
TCODLIB_API TCOD_thread_t TCOD_thread_new(int (*func)(void *), void *data);
TCODLIB_API void TCOD_thread_delete(TCOD_thread_t th);
TCODLIB_API int TCOD_sys_get_num_cores();
TCODLIB_API void TCOD_thread_wait(TCOD_thread_t th);
/* mutex */
TCODLIB_API TCOD_mutex_t TCOD_mutex_new();
TCODLIB_API void TCOD_mutex_in(TCOD_mutex_t mut);
TCODLIB_API void TCOD_mutex_out(TCOD_mutex_t mut);
TCODLIB_API void TCOD_mutex_delete(TCOD_mutex_t mut);
/* semaphore */
TCODLIB_API TCOD_semaphore_t TCOD_semaphore_new(int initVal);
TCODLIB_API void TCOD_semaphore_lock(TCOD_semaphore_t sem);
TCODLIB_API void TCOD_semaphore_unlock(TCOD_semaphore_t sem);
TCODLIB_API void TCOD_semaphore_delete( TCOD_semaphore_t sem);
/* condition */
TCODLIB_API TCOD_cond_t TCOD_condition_new();
TCODLIB_API void TCOD_condition_signal(TCOD_cond_t sem);
TCODLIB_API void TCOD_condition_broadcast(TCOD_cond_t sem);
TCODLIB_API void TCOD_condition_wait(TCOD_cond_t sem, TCOD_mutex_t mut);
TCODLIB_API void TCOD_condition_delete( TCOD_cond_t sem);
/* dynamic library */
typedef void *TCOD_library_t;
TCODLIB_API TCOD_library_t TCOD_load_library(const char *path);
TCODLIB_API void * TCOD_get_function_address(TCOD_library_t library, const char *function_name);
TCODLIB_API void TCOD_close_library(TCOD_library_t);
/* SDL renderer callback */
#ifdef TCOD_SDL2
typedef void (*SDL_renderer_t) (void *sdl_renderer);
#else
typedef void (*SDL_renderer_t) (void *sdl_surface);
#endif
TCODLIB_API void TCOD_sys_register_SDL_renderer(SDL_renderer_t renderer);
#endif

541
include/sys.hpp Normal file
View File

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

40
include/tree.h Normal file
View File

@ -0,0 +1,40 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_TREE_H
#define _TCOD_TREE_H
typedef struct _TCOD_tree_t {
struct _TCOD_tree_t *next;
struct _TCOD_tree_t *father;
struct _TCOD_tree_t *sons;
} TCOD_tree_t;
TCODLIB_API TCOD_tree_t *TCOD_tree_new();
TCODLIB_API void TCOD_tree_add_son(TCOD_tree_t *node, TCOD_tree_t *son);
#endif

51
include/tree.hpp Normal file
View File

@ -0,0 +1,51 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_TREE_HPP
#define _TCOD_TREE_HPP
class TCODLIB_API TCODTree {
public :
TCODTree *next;
TCODTree *father;
TCODTree *sons;
TCODTree() : next(NULL),father(NULL),sons(NULL){}
void addSon(TCODTree *data) {
data->father=this;
TCODTree *lastson = sons;
while ( lastson && lastson->next ) lastson=lastson->next;
if ( lastson ) {
lastson->next=data;
} else {
sons=data;
}
}
};
#endif

45
include/txtfield.h Normal file
View File

@ -0,0 +1,45 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_TEXT_H_
#define _TCOD_TEXT_H_
typedef void * TCOD_text_t;
TCODLIB_API TCOD_text_t TCOD_text_init(int x, int y, int w, int h, int max_chars);
TCODLIB_API TCOD_text_t TCOD_text_init2(int w, int h, int max_chars);
TCODLIB_API void TCOD_text_set_pos(TCOD_text_t txt, int x, int y);
TCODLIB_API void TCOD_text_set_properties(TCOD_text_t txt, int cursor_char, int blink_interval, const char * prompt, int tab_size);
TCODLIB_API void TCOD_text_set_colors(TCOD_text_t txt, TCOD_color_t fore, TCOD_color_t back, float back_transparency);
TCODLIB_API bool TCOD_text_update(TCOD_text_t txt, TCOD_key_t key);
TCODLIB_API void TCOD_text_render(TCOD_text_t txt, TCOD_console_t con);
TCODLIB_API const char * TCOD_text_get(TCOD_text_t txt);
TCODLIB_API void TCOD_text_reset(TCOD_text_t txt);
TCODLIB_API void TCOD_text_delete(TCOD_text_t txt);
#endif

50
include/txtfield.hpp Normal file
View File

@ -0,0 +1,50 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TCOD_TEXT_HPP_
#define _TCOD_TEXT_HPP_
#include "color.hpp"
class TCODLIB_API TCODText {
public :
TCODText(int x, int y, int w, int h, int max_chars);
TCODText(int w, int h, int max_chars);
~TCODText();
void setProperties(int cursor_char, int blink_interval, const char * prompt, int tab_size);
void setColors(TCODColor fore, TCODColor back, float back_transparency);
void setPos(int x, int y);
bool update(TCOD_key_t key);
void render(TCODConsole * con);
const char *getText();
void reset();
protected :
TCOD_text_t data;
};
#endif

148
include/wrappers.h Normal file
View File

@ -0,0 +1,148 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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 WRAPPERS_H
#define WRAPPERS_H
/* wrappers to ease other languages integration */
typedef unsigned int colornum_t;
/* color module */
TCODLIB_API bool TCOD_color_equals_wrapper (colornum_t c1, colornum_t c2);
TCODLIB_API colornum_t TCOD_color_add_wrapper (colornum_t c1,
colornum_t c2);
TCODLIB_API colornum_t TCOD_color_subtract_wrapper (colornum_t c1,
colornum_t c2);
TCODLIB_API colornum_t TCOD_color_multiply_wrapper (colornum_t c1,
colornum_t c2);
TCODLIB_API colornum_t TCOD_color_multiply_scalar_wrapper (colornum_t c1,
float value);
TCODLIB_API colornum_t TCOD_color_lerp_wrapper(colornum_t c1,
colornum_t c2, float coef);
TCODLIB_API void TCOD_color_get_HSV_wrapper(colornum_t c,float * h,
float * s, float * v);
TCODLIB_API float TCOD_color_get_hue_ (colornum_t c);
TCODLIB_API float TCOD_color_get_saturation_ (colornum_t c);
TCODLIB_API float TCOD_color_get_value_ (colornum_t c);
/* console module */
/* TCODLIB_API void TCOD_console_set_custom_font_wrapper(const char *fontFile,
int char_width, int char_height, int nb_char_horiz,
int nb_char_vertic, bool chars_by_row,
colornum_t key_color); */
TCODLIB_API void TCOD_console_set_default_background_wrapper(TCOD_console_t con,
colornum_t col);
TCODLIB_API void TCOD_console_set_default_foreground_wrapper(TCOD_console_t con,
colornum_t col);
TCODLIB_API colornum_t TCOD_console_get_default_background_wrapper(TCOD_console_t con);
TCODLIB_API colornum_t TCOD_console_get_default_foreground_wrapper(TCOD_console_t con);
TCODLIB_API colornum_t TCOD_console_get_char_background_wrapper(TCOD_console_t con,
int x, int y);
TCODLIB_API void TCOD_console_set_char_background_wrapper(TCOD_console_t con,int x, int y,
colornum_t col,
TCOD_bkgnd_flag_t flag);
TCODLIB_API colornum_t TCOD_console_get_char_foreground_wrapper (TCOD_console_t con,
int x, int y);
TCODLIB_API void TCOD_console_set_char_foreground_wrapper(TCOD_console_t con,int x, int y,
colornum_t col);
TCODLIB_API void TCOD_console_put_char_ex_wrapper(TCOD_console_t con, int x,
int y, int c, colornum_t fore, colornum_t back);
TCODLIB_API void TCOD_console_set_fade_wrapper(uint8 val, colornum_t fade);
TCODLIB_API colornum_t TCOD_console_get_fading_color_wrapper();
TCODLIB_API void TCOD_console_set_color_control_wrapper(TCOD_colctrl_t con,
colornum_t fore,
colornum_t back);
TCODLIB_API bool TCOD_console_check_for_keypress_wrapper(TCOD_key_t *holder,
int flags);
TCODLIB_API void TCOD_console_wait_for_keypress_wrapper(TCOD_key_t *holder,
bool flush);
TCODLIB_API uint32 TCOD_console_check_for_keypress_bitfield (int flags);
TCODLIB_API uint32 TCOD_console_wait_for_keypress_bitfield (bool flush);
TCODLIB_API void TCOD_console_fill_background(TCOD_console_t con, int *r, int *g, int *b);
TCODLIB_API void TCOD_console_fill_foreground(TCOD_console_t con, int *r, int *g, int *b);
TCODLIB_API void TCOD_console_fill_char(TCOD_console_t con, int *arr);
TCODLIB_API void TCOD_console_double_hline(TCOD_console_t con,int x,int y, int l,
TCOD_bkgnd_flag_t flag);
TCODLIB_API void TCOD_console_double_vline(TCOD_console_t con,int x,int y,
int l, TCOD_bkgnd_flag_t flag);
TCODLIB_API void TCOD_console_print_double_frame(TCOD_console_t con,int x,int y,
int w,int h, bool empty,
TCOD_bkgnd_flag_t flag,
const char *fmt, ...);
TCODLIB_API char *TCOD_console_print_return_string(TCOD_console_t con,int x,
int y, int rw, int rh,
TCOD_bkgnd_flag_t flag,
TCOD_alignment_t align, char *msg,
bool can_split,
bool count_only);
TCODLIB_API void console_set_key_color_wrapper (TCOD_console_t con, colornum_t c);
/* image module */
TCODLIB_API void TCOD_image_clear_wrapper(TCOD_image_t image,
colornum_t color);
TCODLIB_API colornum_t TCOD_image_get_pixel_wrapper(TCOD_image_t image,
int x, int y);
TCODLIB_API colornum_t TCOD_image_get_mipmap_pixel_wrapper(TCOD_image_t image,
float x0,float y0, float x1, float y1);
TCODLIB_API void TCOD_image_put_pixel_wrapper(TCOD_image_t image,int x, int y,
colornum_t col);
TCODLIB_API void TCOD_image_set_key_color_wrapper(TCOD_image_t image,
colornum_t key_color);
/* mouse module */
TCODLIB_API void TCOD_mouse_get_status_wrapper(TCOD_mouse_t *holder);
TCODLIB_API int TCOD_mouse_get_x();
TCODLIB_API int TCOD_mouse_get_y();
TCODLIB_API int TCOD_mouse_get_cx();
TCODLIB_API int TCOD_mouse_get_cy();
TCODLIB_API int TCOD_mouse_get_dx();
TCODLIB_API int TCOD_mouse_get_dy();
TCODLIB_API int TCOD_mouse_get_dcx();
TCODLIB_API int TCOD_mouse_get_dcy();
TCODLIB_API uint32 TCOD_mouse_get_lbutton();
TCODLIB_API uint32 TCOD_mouse_get_mbutton();
TCODLIB_API uint32 TCOD_mouse_get_rbutton();
TCODLIB_API uint32 TCOD_mouse_get_lbutton_pressed();
TCODLIB_API uint32 TCOD_mouse_get_mbutton_pressed();
TCODLIB_API uint32 TCOD_mouse_get_rbutton_pressed();
/* parser module */
TCODLIB_API colornum_t TCOD_parser_get_color_property_wrapper(TCOD_parser_t parser, const char *name);
/* namegen module */
TCODLIB_API int TCOD_namegen_get_nb_sets_wrapper();
TCODLIB_API void TCOD_namegen_get_sets_wrapper(char **sets);
/* sys module */
TCODLIB_API int TCOD_sys_get_current_resolution_x();
TCODLIB_API int TCOD_sys_get_current_resolution_y();
#endif /* WRAPPERS_H */

62
include/zip.h Normal file
View File

@ -0,0 +1,62 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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_ZIP_H
#define _TCOD_ZIP_H
typedef void *TCOD_zip_t;
TCODLIB_API TCOD_zip_t TCOD_zip_new();
TCODLIB_API void TCOD_zip_delete(TCOD_zip_t zip);
/* output interface */
TCODLIB_API void TCOD_zip_put_char(TCOD_zip_t zip, char val);
TCODLIB_API void TCOD_zip_put_int(TCOD_zip_t zip, int val);
TCODLIB_API void TCOD_zip_put_float(TCOD_zip_t zip, float val);
TCODLIB_API void TCOD_zip_put_string(TCOD_zip_t zip, const char *val);
TCODLIB_API void TCOD_zip_put_color(TCOD_zip_t zip, const TCOD_color_t val);
TCODLIB_API void TCOD_zip_put_image(TCOD_zip_t zip, const TCOD_image_t val);
TCODLIB_API void TCOD_zip_put_console(TCOD_zip_t zip, const TCOD_console_t val);
TCODLIB_API void TCOD_zip_put_data(TCOD_zip_t zip, int nbBytes, const void *data);
TCODLIB_API uint32 TCOD_zip_get_current_bytes(TCOD_zip_t zip);
TCODLIB_API int TCOD_zip_save_to_file(TCOD_zip_t zip, const char *filename);
/* input interface */
TCODLIB_API int TCOD_zip_load_from_file(TCOD_zip_t zip, const char *filename);
TCODLIB_API char TCOD_zip_get_char(TCOD_zip_t zip);
TCODLIB_API int TCOD_zip_get_int(TCOD_zip_t zip);
TCODLIB_API float TCOD_zip_get_float(TCOD_zip_t zip);
TCODLIB_API const char *TCOD_zip_get_string(TCOD_zip_t zip);
TCODLIB_API TCOD_color_t TCOD_zip_get_color(TCOD_zip_t zip);
TCODLIB_API TCOD_image_t TCOD_zip_get_image(TCOD_zip_t zip);
TCODLIB_API TCOD_console_t TCOD_zip_get_console(TCOD_zip_t zip);
TCODLIB_API int TCOD_zip_get_data(TCOD_zip_t zip, int nbBytes, void *data);
TCODLIB_API uint32 TCOD_zip_get_remaining_bytes(TCOD_zip_t zip);
TCODLIB_API void TCOD_zip_skip_bytes(TCOD_zip_t zip, uint32 nbBytes);
#endif

331
include/zip.hpp Normal file
View File

@ -0,0 +1,331 @@
/*
* libtcod 1.6.0
* Copyright (c) 2008,2009,2010,2012,2013 Jice & Mingos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice or Mingos may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS 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_ZIP_HPP
#define _TCOD_ZIP_HPP
/**
@PageName zip
@PageCategory Base toolkits
@PageTitle Compression toolkit
@PageDesc This toolkit provides functions to save or read compressed data from a file. While the module is named Zip, it has nothing to do with the .zip format as it uses zlib compression (.gz format).
Note that this modules has no python wrapper. Use python built-in zip module instead.
You can use the compression buffer in two modes:
* put data in the buffer, then save it to a file,
* load a file into the buffer, then get data from it.
*/
class TCODLIB_API TCODZip {
public :
/**
@PageName zip_init
@PageFather zip
@PageTitle Creating a compression buffer
@FuncDesc This function initializes a compression buffer.
@Cpp TCODZip::TCODZip()
@C TCOD_zip_t TCOD_zip_new()
*/
TCODZip();
/**
@PageName zip_init
@FuncDesc Once you don't need the buffer anymore, you can release resources. Note that the adresses returned by the getString function are no longer valid once the buffer has been destroyed.
@Cpp TCODZip::~TCODZip()
@C void TCOD_zip_delete(TCOD_zip_t zip)
@Param zip In the C version, the buffer handler, returned by the constructor.
@CppEx
TCODZip *zip = new TCODZip();
zip->loadFromFile("myCompressedFile.gz");
char c=zip->getChar();
int i=zip->getInt();
float f= zip->getFloat();
const char *s=strdup(zip->getString()); // we duplicate the string to be able to use it after the buffer deletion
zip->getData(nbBytes, dataPtr);
delete zip;
@CEx
TCOD_zip_t zip=TCOD_zip_new();
TCOD_zip_load_from_file(zip,"myCompressedFile.gz");
char c=TCOD_zip_get_char(zip);
int i=TCOD_zip_get_int(zip);
float f=TCOD_zip_get_float(zip);
const char *s=strdup(TCOD_zip_get_string(zip));
TCOD_zip_get_data(zip,nbBytes, dataPtr);
TCOD_zip_delete(zip);
*/
~TCODZip();
/**
@PageName zip_put
@PageFather zip
@PageTitle Using the buffer in output mode
@FuncTitle Putting a char in the buffer
@Cpp void TCODZip::putChar(char val)
@C void TCOD_zip_put_char(TCOD_zip_t zip, char val)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param val A 8 bits value to store in the buffer
*/
void putChar(char val);
/**
@PageName zip_put
@FuncTitle Putting an integer in the buffer
@Cpp void TCODZip::putInt(int val)
@C void TCOD_zip_put_int(TCOD_zip_t zip, int val)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param val An integer value to store in the buffer
*/
void putInt(int val);
/**
@PageName zip_put
@FuncTitle Putting a floating point value in the buffer
@Cpp void TCODZip::putFloat(float val)
@C void TCOD_zip_put_float(TCOD_zip_t zip, float val)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param val A float value to store in the buffer
*/
void putFloat(float val);
/**
@PageName zip_put
@FuncTitle Putting a string in the buffer
@Cpp void TCODZip::putString(const char *val)
@C void TCOD_zip_put_string(TCOD_zip_t zip, const char *val)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param val A string to store in the buffer
*/
void putString(const char *val);
/**
@PageName zip_put
@FuncTitle Putting a color in the buffer
@Cpp void TCODZip::putColor(const TCODColor *val)
@C void TCOD_zip_put_color(TCOD_zip_t zip, const TCOD_color_t val)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param val A color to store in the buffer
*/
void putColor(const TCODColor *val);
/**
@PageName zip_put
@FuncTitle Putting an image in the buffer
@Cpp void TCODZip::putImage(const TCODImage *val)
@C void TCOD_zip_put_image(TCOD_zip_t zip, const TCOD_image_t val)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param val An image to store in the buffer
*/
void putImage(const TCODImage *val);
/**
@PageName zip_put
@FuncTitle Putting a console in the buffer
@Cpp void TCODZip::putConsole(const TCODConsole *val)
@C void TCOD_zip_put_console(TCOD_zip_t zip, const TCOD_console_t val)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param val A console to store in the buffer
*/
void putConsole(const TCODConsole *val);
/**
@PageName zip_put
@FuncTitle Putting some custom data in the buffer
@Cpp void TCODZip::putData(int nbBytes, const void *data)
@C void TCOD_zip_put_data(TCOD_zip_t zip, int nbBytes, const void *data)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param nbBytes Number of bytes to store in the buffer
@Param val Address of the data to store in the buffer
*/
void putData(int nbBytes, const void *data);
/**
@PageName zip_put
@FuncTitle Reading the number of (uncompressed) bytes in the buffer
@Cpp uint32 TCODZip::getCurrentBytes()
@C uint32 TCOD_zip_get_current_bytes(TCOD_zip_t zip)
@Param zip In the C version, the buffer handler, returned by the constructor.
*/
uint32 getCurrentBytes() const;
/**
@PageName zip_put
@FuncTitle Saving the buffer on disk
@FuncDesc Once you have finished adding data in the buffer, you can compress it and save it in a file.
The function returns the number of (uncompressed) bytes saved.
@Cpp int TCODZip::saveToFile(const char *filename)
@C int TCOD_zip_save_to_file(TCOD_zip_t zip, const char *filename)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param filename Name of the file
@CppEx
TCODZip zip;
zip.putChar('A');
zip.putInt(1764);
zip.putFloat(3.14f);
zip.putString("A string");
zip.putData(nbBytes, dataPtr);
zip.saveToFile("myCompressedFile.gz");
@CEx
TCOD_zip_t zip=TCOD_zip_new();
TCOD_zip_put_char(zip,'A');
TCOD_zip_put_int(zip,1764);
TCOD_zip_put_float(zip,3.14f);
TCOD_zip_put_string(zip,"A string");
TCOD_zip_put_data(zip,nbBytes, dataPtr);
TCOD_zip_save_to_file(zip,"myCompressedFile.gz");
*/
int saveToFile(const char *filename);
/**
@PageName zip_load
@PageTitle Using the buffer in input mode
@PageFather zip
@FuncTitle Reading from a compressed file
@FuncDesc You can read data from a file (compressed or not) into the buffer.
The function returns the number of (uncompressed) bytes read or 0 if an error occured.
@Cpp int TCODZip::loadFromFile(const char *filename)
@C int TCOD_zip_load_from_file(TCOD_zip_t zip, const char *filename)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param filename Name of the file
*/
int loadFromFile(const char *filename);
/**
@PageName zip_load
@FuncTitle Reading a char from the buffer
@Cpp char TCODZip::getChar()
@C char TCOD_zip_get_char(TCOD_zip_t zip)
@Param zip In the C version, the buffer handler, returned by the constructor
*/
char getChar();
/**
@PageName zip_load
@FuncTitle Reading an integer from the buffer
@Cpp int TCODZip::getInt()
@C int TCOD_zip_get_int(TCOD_zip_t zip)
@Param zip In the C version, the buffer handler, returned by the constructor.
*/
int getInt();
/**
@PageName zip_load
@FuncTitle Reading a floating point value from the buffer
@Cpp float TCODZip::getFloat()
@C float TCOD_zip_get_float(TCOD_zip_t zip)
@Param zip In the C version, the buffer handler, returned by the constructor.
*/
float getFloat();
/**
@PageName zip_load
@FuncTitle Reading a string from the buffer
@FuncDesc The address returned is in the buffer. It is valid as long as you don't destroy the buffer.
@Cpp const char *TCODZip::getString()
@C const char *TCOD_zip_get_string(TCOD_zip_t zip)
@Param zip In the C version, the buffer handler, returned by the constructor.
*/
const char *getString();
/**
@PageName zip_load
@FuncTitle Reading a color from the buffer
@Cpp TCODColor TCODZip::getColor()
@C TCOD_color_t TCOD_zip_get_color(TCOD_zip_t zip)
@Param zip In the C version, the buffer handler, returned by the constructor.
*/
TCODColor getColor();
/**
@PageName zip_load
@FuncTitle Reading a color from the buffer
@Cpp TCODImage *TCODZip::getImage()
@C TCOD_image_t TCOD_zip_get_image(TCOD_zip_t zip)
@Param zip In the C version, the buffer handler, returned by the constructor.
*/
TCODImage *getImage();
/**
@PageName zip_load
@FuncTitle Reading a console from the buffer
@Cpp TCODConsole *TCODZip::getConsole()
@C TCOD_console_t TCOD_zip_get_console(TCOD_zip_t zip)
@Param zip In the C version, the buffer handler, returned by the constructor.
*/
TCODConsole *getConsole();
/**
@PageName zip_load
@FuncTitle Reading some custom data from the buffer
@FuncDesc Note that the getData length must match the length of the data when the file was created (with putData).
The function returns the number of bytes that were stored in the file by the putData call. If more than nbBytes were stored, the function read only nbBytes and skip the rest of them.
@Cpp int TCODZip::getData(int nbBytes, void *data)
@C int TCOD_zip_get_data(TCOD_zip_t zip, int nbBytes, void *data)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param nbBytes Number of bytes to read
@Param data Address of a pre-allocated buffer (at least nbBytes bytes)
@CppEx
TCODZip zip;
zip.loadFromFile("myCompressedFile.gz");
char c=zip.getChar();
int i=zip.getInt();
float f= zip.getFloat();
const char *s=zip.getString();
zip.getData(nbBytes, dataPtr);
@CEx
TCOD_zip_t zip=TCOD_zip_new();
TCOD_zip_load_from_file(zip,"myCompressedFile.gz");
char c=TCOD_zip_get_char(zip);
int i=TCOD_zip_get_int(zip);
float f=TCOD_zip_get_float(zip);
const char *s=TCOD_zip_get_string(zip);
TCOD_zip_get_data(zip,nbBytes, dataPtr);
*/
int getData(int nbBytes, void *data);
/**
@PageName zip_load
@FuncTitle Getting the number of remaining bytes in the buffer
@Cpp uint32 TCODZip::getRemainingBytes() const
@C uint32 TCOD_zip_get_remaining_bytes(TCOD_zip_t zip)
@Param zip In the C version, the buffer handler, returned by the constructor.
*/
uint32 getRemainingBytes() const;
/**
@PageName zip_load
@FuncTitle Skiping some bytes in the buffer
@Cpp void TCODZip::skipBytes(uint32 nbBytes)
@C void TCOD_zip_skip_bytes(TCOD_zip_t zip, uint32 nbBytes)
@Param zip In the C version, the buffer handler, returned by the constructor.
@Param nbBytes number of uncompressed bytes to skip
*/
void skipBytes(uint32 nbBytes);
protected :
TCOD_zip_t data;
};
#endif

32
makefile Normal file
View File

@ -0,0 +1,32 @@
SOURCES=$(wildcard src/*.cpp)
OBJS=$(SOURCES:.cpp=.o)
# compiler options : add debug information in debug mode
# optimize speed and size in release mode
ifneq (,$(findstring debug,$(MAKECMDGOALS)))
CFLAGS=-g
else
CFLAGS=-02 -s
endif
# linker options : OS dependant
ifeq ($(shell sh -c 'uname -s'),Linux)
LIBFLAGS=-L. -ltcod_debug -ltcodxx_debug -Wl,-rpath=.
else
LIBFLAGS=-Llib -ltcod-mingw-debug -static-libgcc -static-libstdc++
endif
debug : tuto
release : tuto
tuto : $(OBJS)
g++ $(OBJS) -o tuto -Wall $(LIBFLAGS) -g -w
src/main.hpp.gch : src/*.hpp
g++ src/main.hpp -Iinclude -Wall
src/%.o : src/%.cpp src/main.hpp.gch
g++ $< -c -o $@ -Iinclude -Wall -g
clean :
rm -f src/main.hpp.gch $(OBJS)

BIN
menu_background1.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

86
src/Actor.cpp Normal file
View File

@ -0,0 +1,86 @@
#include <math.h>
#include "main.hpp"
Actor::Actor(int x, int y, int ch, const char *name, const TCODColor &col) :
x(x), y(y), ch(ch), col(col), blocks(true), fovOnly(true),
attacker(NULL), destructible(NULL), ai(NULL),
pickable(NULL), container(NULL) {
strcpy(this->name, name);
}
Actor::~Actor() {
if(attacker) delete attacker;
if(destructible) delete destructible;
if(ai) delete ai;
if(pickable) delete pickable;
if(container) delete container;
}
void Actor::update() {
if(ai) ai->update(this);
}
void Actor::render() const {
TCODConsole::root->setChar(x, y, ch);
TCODConsole::root->setCharForeground(x, y, col);
}
float Actor::getDistance(int cx, int cy) const {
int dx=x-cx;
int dy=y-cy;
return sqrtf(dx*dx+dy*dy);
}
void Actor::save(TCODZip &zip) {
zip.putInt(x);
zip.putInt(y);
zip.putInt(ch);
zip.putColor(&col);
zip.putString(name);
zip.putInt(blocks);
zip.putInt(attacker != NULL);
zip.putInt(destructible != NULL);
zip.putInt(ai != NULL);
zip.putInt(pickable != NULL);
zip.putInt(container != NULL);
if(attacker) attacker->save(zip);
if(destructible) destructible->save(zip);
if(ai) ai->save(zip);
if(pickable) pickable->save(zip);
if(container) container->save(zip);
}
void Actor::load(TCODZip &zip) {
x = zip.getInt();
y = zip.getInt();
ch = zip.getInt();
col = zip.getColor();
strcpy(name, strdup(zip.getString()));
blocks = zip.getInt();
bool hasAttacker=zip.getInt();
bool hasDestructible=zip.getInt();
bool hasAi=zip.getInt();
bool hasPickable=zip.getInt();
bool hasContainer=zip.getInt();
if(hasAttacker) {
attacker = new Attacker(0.0f);
attacker->load(zip);
}
if(hasDestructible) {
destructible = Destructible::create(zip);
}
if(hasAi) {
ai = Ai::create(zip);
}
if(hasPickable) {
pickable = Pickable::create(zip);
}
if(hasContainer) {
container = new Container(0);
container->load(zip);
}
}

27
src/Actor.hpp Normal file
View File

@ -0,0 +1,27 @@
class Actor : public Persistent {
static const int MAX_NAME_LENGTH = 30;
public :
int x, y; // position on map
int ch; // ascii code
TCODColor col; // color
char name [ MAX_NAME_LENGTH ]; // the actor's name
bool blocks; // can we walk on this actor?
bool fovOnly; // only display when in fov
Attacker *attacker; // something that deals damage
Destructible *destructible; // something that can be damaged
Ai *ai; // something self-updating
Pickable *pickable; // Something that can be picked and used
Container *container; // Something that can contain other actors
Actor(int x, int y, int ch, const char *name, const TCODColor &col);
~Actor();
void update();
void render() const;
float getDistance(int cx, int cy) const;
void load(TCODZip &zip);
void save(TCODZip &zip);
};

285
src/Ai.cpp Normal file
View File

@ -0,0 +1,285 @@
#include "main.hpp"
#include <stdio.h>
#include <math.h>
// How many turns the monster chases the player
// After losing his sight
static const int TRACKING_TURNS = 3;
Ai *Ai::create(TCODZip &zip) {
AiType type=(AiType)zip.getInt();
Ai *ai=NULL;
switch(type) {
case PLAYER: ai = new PlayerAi(); break;
case MONSTER: ai = new MonsterAi(); break;
case CONFUSED_MONSTER: ai = new ConfusedMonsterAi(0, NULL); break;
}
ai->load(zip);
return ai;
}
/* Player AI */
PlayerAi::PlayerAi() : xpLevel(1) { }
const int LEVEL_UP_BASE=200;
const int LEVEL_UP_FACTOR=150;
int PlayerAi::getNextLevelXp() {
return LEVEL_UP_BASE + xpLevel*LEVEL_UP_FACTOR;
}
void PlayerAi::update(Actor *owner) {
int levelUpXp = getNextLevelXp();
if(owner->destructible->xp >= levelUpXp) {
xpLevel++;
owner->destructible->xp -= levelUpXp;
engine.gui->message(TCODColor::yellow, "Your battle skills grow stronger! You reached level %d", xpLevel);
engine.gui->menu.clear();
engine.gui->menu.addItem(Menu::CONSTITUTION, "Constitution (+20HP)");
engine.gui->menu.addItem(Menu::STRENGTH, "Strength (+1 Attack)");
engine.gui->menu.addItem(Menu::AGILITY, "Agility (+1 Defense)");
Menu::MenuItemCode menuItem=engine.gui->menu.pick(Menu::PAUSE);
switch(menuItem) {
case Menu::CONSTITUTION:
owner->destructible->maxHp+=20;
owner->destructible->hp+=20;
break;
case Menu::STRENGTH:
owner->attacker->power+=1;
break;
case Menu::AGILITY:
owner->destructible->defense+=1;
break;
default: break;
}
}
if(owner->destructible && owner->destructible->isDead()) {
return;
}
int dx=0, dy=0;
switch(engine.lastKey.vk) {
case TCODK_UP: case TCODK_KP8: dy=-1; break;
case TCODK_DOWN: case TCODK_KP2: dy=1; break;
case TCODK_LEFT: case TCODK_KP4: dx=-1; break;
case TCODK_RIGHT: case TCODK_KP6: dx=1; break;
case TCODK_KP7: dy=dx=-1; break;
case TCODK_KP9: dy=-1;dx=1; break;
case TCODK_KP1: dy=1;dx=-1; break;
case TCODK_KP3: dy=dx=1; break;
case TCODK_CHAR: handleActionKey(owner, engine.lastKey.c); break;
default:break;
}
if(dx != 0 || dy != 0) {
engine.gameStatus=Engine::NEW_TURN;
if(moveOrAttack(owner, owner->x+dx, owner->y+dy)) {
engine.map->computeFov();
}
}
}
bool PlayerAi::moveOrAttack(Actor *owner, int targetx, int targety) {
if(engine.map->isWall(targetx, targety)) return false;
// look for living actors to attack
for(Actor **iterator=engine.actors.begin();
iterator != engine.actors.end(); iterator++) {
Actor *actor=*iterator;
if(actor->destructible && !actor->destructible->isDead()
&& actor->x == targetx && actor->y == targety) {
owner->attacker->attack(owner, actor);
return false;
}
}
// Look for corpses or items
for(Actor **iterator=engine.actors.begin();
iterator != engine.actors.end(); iterator++) {
Actor *actor = *iterator;
bool corpseOrItem=(actor->destructible && actor->destructible->isDead())
|| actor->pickable;
if(corpseOrItem && actor->x == targetx && actor->y == targety) {
engine.gui->message(TCODColor::lightGrey, "There's a %s here\n", actor->name);
}
}
owner->x = targetx;
owner->y = targety;
return true;
}
void PlayerAi::handleActionKey(Actor *owner, int ascii) {
switch(ascii) {
case 'g': // pickup item
{
bool found=false;
for(Actor **iterator=engine.actors.begin();
iterator != engine.actors.end(); iterator++) {
Actor *actor = *iterator;
if(actor->pickable && actor->x == owner->x && actor->y == owner->y) {
if(actor->pickable->pick(actor, owner)) {
found=true;
engine.gui->message(TCODColor::lightGrey, "Picked up the %s.", actor->name);
break;
} else if(!found) {
found = true;
engine.gui->message(TCODColor::red, "Your inventory is full.");
}
}
}
if(!found) {
engine.gui->message(TCODColor::lightGrey, "There's nothing here.");
}
engine.gameStatus=Engine::NEW_TURN;
}
break;
case 'i': // Display inventory
{
Actor *actor=choseFromInventory(owner);
if(actor) {
actor->pickable->use(actor, owner);
engine.gameStatus=Engine::NEW_TURN;
}
}
break;
case 'd': // Drop item
{
Actor *actor = choseFromInventory(owner);
if(actor) {
actor->pickable->drop(actor, owner);
engine.gameStatus = Engine::NEW_TURN;
}
}
break;
case '>':
if(engine.stairs->x == owner->x && engine.stairs->y == owner->y) {
engine.nextLevel();
} else {
engine.gui->message(TCODColor::lightGrey,"There are no stairs here.");
}
break;
}
}
Actor *PlayerAi::choseFromInventory(Actor *owner) {
static const int INVENTORY_WIDTH=50;
static const int INVENTORY_HEIGHT=28;
static TCODConsole con(INVENTORY_WIDTH, INVENTORY_HEIGHT);
// Display the inventory frame
con.setDefaultForeground(TCODColor(200, 180, 50));
con.printFrame(0, 0, INVENTORY_WIDTH, INVENTORY_HEIGHT, true, TCOD_BKGND_DEFAULT, "inventory");
// Display the items with their keyboard shortcut
con.setDefaultForeground(TCODColor::white);
int shortcut='a';
int y=1;
for(Actor **it=owner->container->inventory.begin();
it != owner->container->inventory.end(); it++) {
Actor *actor = *it;
con.print(2, y, "(%c) %s", shortcut, actor->name);
y++;
shortcut++;
}
// blit the inventory console on the root console
TCODConsole::blit(&con, 0, 0, INVENTORY_WIDTH, INVENTORY_HEIGHT,
TCODConsole::root, engine.screenWidth/2 - INVENTORY_WIDTH/2,
engine.screenHeight/2 - INVENTORY_HEIGHT/2);
TCODConsole::flush();
// wait for a key press
TCOD_key_t key;
TCODSystem::waitForEvent(TCOD_EVENT_KEY_PRESS, &key, NULL, true);
if(key.vk == TCODK_CHAR) {
int actorIndex = key.c - 'a';
if(actorIndex >= 0 && actorIndex < owner->container->inventory.size()) {
return owner->container->inventory.get(actorIndex);
}
}
return NULL;
}
void PlayerAi::load(TCODZip &zip) { }
void PlayerAi::save(TCODZip &zip) {
zip.putInt(PLAYER);
}
/* Monster AI */
void MonsterAi::update(Actor *owner) {
if(owner->destructible && owner->destructible->isDead()) {
return;
}
if(engine.map->isInFov(owner->x, owner->y)) {
// We can see the player. Move towards him.
moveCount=TRACKING_TURNS;
} else {
moveCount--;
}
if(moveCount > 0) {
moveOrAttack(owner, engine.player->x, engine.player->y);
}
}
void MonsterAi::moveOrAttack(Actor *owner, int targetx, int targety) {
int dx = targetx - owner->x;
int dy = targety - owner->y;
int stepdx = (dx > 0 ? 1:-1);
int stepdy = (dy > 0 ? 1:-1);
float distance=sqrtf(dx*dx+dy*dy);
if(distance >= 2) {
dx = (int)(round(dx/distance));
dy = (int)(round(dy/distance));
if(engine.map->canWalk(owner->x+dx, owner->y+dy)) {
owner->x += dx;
owner->y += dy;
} else if(engine.map->canWalk(owner->x + stepdx, owner->y)) {
owner->x += stepdx;
} else if(engine.map->canWalk(owner->x, owner->y + stepdy)) {
owner->y += stepdy;
}
} else if(owner->attacker) {
owner->attacker->attack(owner, engine.player);
}
}
void MonsterAi::load(TCODZip &zip) {
moveCount = zip.getInt();
}
void MonsterAi::save(TCODZip &zip) {
zip.putInt(MONSTER);
zip.putInt(moveCount);
}
TemporaryAi::TemporaryAi(int nbTurns) : nbTurns(nbTurns) { }
/* RIGHT HERE */
ConfusedMonsterAi::ConfusedMonsterAi(int nbTurns, Ai *oldAi)
: nbTurns(nbTurns), oldAi(oldAi) { }
void ConfusedMonsterAi::update(Actor *owner) {
TCODRandom *rng = TCODRandom::getInstance();
int dx = rng->getInt(-1, 1);
int dy = rng->getInt(-1, 1);
if(dx != 0 || dy != 0) {
int destx = owner->x + dx;
int desty = owner->y + dy;
if(engine.map->canWalk(destx, desty)) {
owner->x = destx;
owner->y = desty;
} else {
Actor *actor = engine.getActor(destx, desty);
if(actor) {
owner->attacker->attack(owner, actor);
}
}
}
nbTurns--;
if(nbTurns == 0) {
owner->ai = oldAi;
delete this;
}
}
void ConfusedMonsterAi::load(TCODZip &zip) {
nbTurns=zip.getInt();
oldAi=Ai::create(zip);
}
void ConfusedMonsterAi::save(TCODZip &zip) {
zip.putInt(CONFUSED_MONSTER);
zip.putInt(nbTurns);
oldAi->save(zip);
}

55
src/Ai.hpp Normal file
View File

@ -0,0 +1,55 @@
class Ai : public Persistent {
public:
virtual void update(Actor *owner)=0;
static Ai *create(TCODZip &zip);
protected:
enum AiType {
MONSTER, CONFUSED_MONSTER, PLAYER
};
};
class PlayerAi : public Ai {
public :
int xpLevel;
PlayerAi();
int getNextLevelXp();
void update(Actor *owner);
void load(TCODZip &zip);
void save(TCODZip &zip);
protected :
bool moveOrAttack(Actor *owner, int targetx, int targety);
void handleActionKey(Actor *owner, int ascii);
Actor *choseFromInventory(Actor *owner);
};
class MonsterAi : public Ai {
public :
void update(Actor *owner);
void load(TCODZip &zip);
void save(TCODZip &zip);
protected :
void moveOrAttack(Actor *owner, int targetx, int targety);
int moveCount;
};
class TemporaryAi : public Ai {
public:
TemporaryAi(int nbTurns);
void update(Actor *owner);
void applyTo(Actor *actor);
protected:
int nbTurns;
Ai *oldAi;
};
class ConfusedMonsterAi : public Ai {
public:
ConfusedMonsterAi(int nbTurns, Ai *oldAi);
void update(Actor *owner);
void load(TCODZip &zip);
void save(TCODZip &zip);
protected:
int nbTurns;
Ai *oldAi;
};

25
src/Attacker.cpp Normal file
View File

@ -0,0 +1,25 @@
#include <stdio.h>
#include "main.hpp"
Attacker::Attacker(float power) : power(power) { }
void Attacker::attack(Actor *owner, Actor *target) {
if(target->destructible && !target->destructible->isDead()) {
if(power - target->destructible->defense > 0) {
engine.gui->message(owner==engine.player ? TCODColor::red : TCODColor::lightGrey, "%s attacks %s for %g hit points.\n", owner->name, target->name, power - target->destructible->defense);
} else {
engine.gui->message(TCODColor::lightGrey, "%s attacks %s but it has no effect!\n", owner->name, target->name);
}
target->destructible->takeDamage(target, power);
} else {
engine.gui->message(TCODColor::lightGrey, "%s attacks %s in vain.\n", owner->name, target->name);
}
}
void Attacker::load(TCODZip &zip) {
power = zip.getFloat();
}
void Attacker::save(TCODZip &zip) {
zip.putFloat(power);
}

8
src/Attacker.hpp Normal file
View File

@ -0,0 +1,8 @@
class Attacker : public Persistent {
public :
float power; // hit points given
Attacker(float power);
void attack(Actor *owner, Actor *target);
void load(TCODZip &zip);
void save(TCODZip &zip);
};

38
src/Container.cpp Normal file
View File

@ -0,0 +1,38 @@
#include "main.hpp"
Container::Container(int size) : size(size) {}
Container::~Container() {
inventory.clearAndDelete();
}
bool Container::add(Actor *actor) {
if(size > 0 && inventory.size() >= size) {
// inventory full
return false;
}
inventory.push(actor);
return true;
}
void Container::remove(Actor *actor) {
inventory.remove(actor);
}
void Container::load(TCODZip &zip) {
size=zip.getInt();
int nbActors=zip.getInt();
while(nbActors > 0) {
Actor *actor=new Actor(0, 0, 0, " ", TCODColor::white);
actor->load(zip);
inventory.push(actor);
nbActors--;
}
}
void Container::save(TCODZip &zip) {
zip.putInt(size);
zip.putInt(inventory.size());
for(Actor **it=inventory.begin(); it != inventory.end(); it++) {
(*it)->save(zip);
}
}

12
src/Container.hpp Normal file
View File

@ -0,0 +1,12 @@
class Container {
public:
int size; // maximum number of actors. 0=unlimited
TCODList<Actor *> inventory;
Container(int size);
~Container();
bool add(Actor *actor);
void remove(Actor *actor);
void load(TCODZip &zip);
void save(TCODZip &zip);
};

100
src/Destructible.cpp Normal file
View File

@ -0,0 +1,100 @@
#include <stdio.h>
#include "main.hpp"
Destructible::Destructible(float maxHp, float defense, const char *corpseName, int xp) :
maxHp(maxHp), hp(maxHp), defense(defense), xp(xp) {
this->corpseName = strdup(corpseName);
}
Destructible::~Destructible() {
free(corpseName);
}
float Destructible::takeDamage(Actor *owner, float damage) {
damage -= defense;
if(damage > 0) {
hp -= damage;
if(hp <= 0) {
die(owner);
}
} else {
damage = 0;
}
return damage;
}
void Destructible::die(Actor *owner) {
// Transform the actor into a corpse!
owner->ch='%';
owner->col=TCODColor::darkRed;
strcpy(owner->name, corpseName);
owner->blocks = false;
// Make sure corpses are drawn before living actors
engine.sendToBack(owner);
}
float Destructible::heal(float amount) {
hp += amount;
if(hp > maxHp) {
amount -= hp-maxHp;
hp=maxHp;
}
return amount;
}
void Destructible::load(TCODZip &zip) {
maxHp = zip.getFloat();
hp = zip.getFloat();
defense = zip.getFloat();
corpseName = strdup(zip.getString());
xp = zip.getInt();
}
void Destructible::save(TCODZip &zip) {
zip.putFloat(maxHp);
zip.putFloat(hp);
zip.putFloat(defense);
zip.putString(corpseName);
zip.putInt(xp);
}
Destructible *Destructible::create(TCODZip &zip) {
DestructibleType type=(DestructibleType)zip.getInt();
Destructible *destructible=NULL;
switch(type) {
case MONSTER: destructible = new MonsterDestructible(0, 0, " ", 0); break;
case PLAYER: destructible = new PlayerDestructible(0, 0, " "); break;
}
destructible->load(zip);
return destructible;
}
/* Monster/Player Specific Sub-Destructibles */
MonsterDestructible::MonsterDestructible(float maxHp, float defense, const char *corpseName, int xp) :
Destructible(maxHp, defense, corpseName, xp) { }
void MonsterDestructible::die(Actor *owner) {
// transform it into a nasty corpse! it doesn't block, can't be
// attacked and doesn't move
engine.gui->message(TCODColor::lightGrey, "%s is dead. You gain %d xp\n", owner->name, xp);
engine.player->destructible->xp += xp;
Destructible::die(owner);
}
void MonsterDestructible::save(TCODZip &zip) {
zip.putInt(MONSTER);
Destructible::save(zip);
}
PlayerDestructible::PlayerDestructible(float maxHp, float defense, const char *corpseName) : Destructible(maxHp, defense, corpseName, 0) { }
void PlayerDestructible::die(Actor *owner) {
engine.gui->message(TCODColor::red, "You died!\n");
Destructible::die(owner);
engine.gameStatus=Engine::DEFEAT;
}
void PlayerDestructible::save(TCODZip &zip) {
zip.putInt(PLAYER);
Destructible::save(zip);
}

38
src/Destructible.hpp Normal file
View File

@ -0,0 +1,38 @@
class Destructible : public Persistent {
public :
float maxHp;
float hp;
float defense;
char *corpseName;
int xp; // XP gained when killing this monster (or player xp)
Destructible(float maxHp, float defense, const char *corpseName, int xp);
~Destructible();
inline bool isDead() { return hp <= 0; }
float takeDamage(Actor *owner, float damage);
virtual void die(Actor *owner);
float heal(float amount);
void load(TCODZip &zip);
void save(TCODZip &zip);
static Destructible *create(TCODZip &zip);
protected:
enum DestructibleType {
MONSTER, PLAYER
};
};
class MonsterDestructible : public Destructible {
public :
MonsterDestructible(float maxHp, float defense, const char *corpseName, int xp);
void die(Actor *owner);
void save(TCODZip &zip);
};
class PlayerDestructible : public Destructible {
public :
PlayerDestructible(float maxHp, float defense, const char *corpseName);
void die(Actor *owner);
void save(TCODZip &zip);
};

239
src/Engine.cpp Normal file
View File

@ -0,0 +1,239 @@
#include "libtcod.hpp"
#include "main.hpp"
Engine::Engine(int screenWidth, int screenHeight) : gameStatus(STARTUP),
player(NULL), map(NULL), fovRadius(10),
screenWidth(screenWidth), screenHeight(screenHeight), level(1) {
TCODConsole::initRoot(80, 50, "libtcod C++ tutorial", false);
gui = new Gui();
}
Engine::~Engine() {
term();
delete gui;
}
void Engine::update() {
if(gameStatus == STARTUP) map->computeFov();
gameStatus=IDLE;
TCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS|TCOD_EVENT_MOUSE, &lastKey, &mouse);
if(lastKey.vk == TCODK_ESCAPE) {
save();
load();
}
player->update();
if(gameStatus == NEW_TURN) {
for(Actor **iterator=actors.begin(); iterator != actors.end(); iterator++) {
Actor *actor=*iterator;
if(actor != player) {
actor->update();
}
}
}
}
void Engine::render() {
TCODConsole::root->clear();
// draw the map
map->render();
// draw the actors
for(Actor **iterator=actors.begin();
iterator != actors.end(); iterator++) {
Actor *actor = *iterator;
if(actor != player
&& ((!actor->fovOnly && map->isExplored(actor->x, actor->y))
|| map->isInFov(actor->x, actor->y))) {
actor->render();
}
}
player->render();
gui->render();
}
void Engine::sendToBack(Actor *actor) {
actors.remove(actor);
actors.insertBefore(actor, 0);
}
Actor *Engine::getClosestMonster(int x, int y, float range) const {
Actor *closest = NULL;
float bestDistance=1E6f;
for(Actor **iterator=actors.begin();
iterator != actors.end(); iterator++) {
Actor *actor = *iterator;
if(actor != player && actor->destructible
&& !actor->destructible->isDead()) {
float distance=actor->getDistance(x, y);
if(distance < bestDistance &&
(distance <= range || range == 0.0f)) {
bestDistance = distance;
closest = actor;
}
}
}
return closest;
}
Actor *Engine::getActor(int x, int y) const {
for(Actor **iterator = actors.begin();
iterator != actors.end(); iterator++) {
Actor *actor = *iterator;
if(actor->x == x && actor->y == y && actor->destructible
&& !actor->destructible->isDead()) {
return actor;
}
}
return NULL;
}
bool Engine::pickATile(int *x, int *y, float maxRange) {
while(!TCODConsole::isWindowClosed()) {
render();
// highlight the possible range
for(int cx=0; cx < map->width; cx++) {
for(int cy=0; cy < map->height; cy++) {
if(map->isInFov(cx, cy)
&& (maxRange == 0 || player->getDistance(cx, cy) <= maxRange)) {
TCODColor col = TCODConsole::root->getCharBackground(cx, cy);
col = col * 1.2f;
TCODConsole::root->setCharBackground(cx, cy, col);
}
}
}
TCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS|TCOD_EVENT_MOUSE, &lastKey, &mouse);
if(map->isInFov(mouse.cx, mouse.cy)
&& (maxRange == 0 || player->getDistance(mouse.cx, mouse.cy) <= maxRange)) {
TCODConsole::root->setCharBackground(mouse.cx, mouse.cy, TCODColor::white);
if(mouse.lbutton_pressed) {
*x = mouse.cx;
*y = mouse.cy;
return true;
}
}
if(mouse.rbutton_pressed || lastKey.vk != TCODK_NONE) {
return false;
}
TCODConsole::flush();
}
return false;
}
void Engine::init() {
player = new Actor(40, 25, '@', "player", TCODColor::white);
player->destructible = new PlayerDestructible(30, 2, "Your cadaver");
player->attacker = new Attacker(5);
player->ai = new PlayerAi();
player->container = new Container(26);
actors.push(player);
stairs = new Actor(0, 0,'>',"stairs",TCODColor::white);
stairs->blocks=false;
stairs->fovOnly=false;
actors.push(stairs);
map = new Map(80, 43);
map->init(true);
gui->message(TCODColor::red, "Welcome stranger!\nPrepare to perish in the Tombs of the Ancient Kings.");
gameStatus=STARTUP;
}
void Engine::term() {
actors.clearAndDelete();
if(map) delete map;
}
void Engine::save() {
if(player->destructible->isDead()) {
TCODSystem::deleteFile("game.sav");
} else {
TCODZip zip;
// Save the map first
zip.putInt(map->width);
zip.putInt(map->height);
map->save(zip);
// Then the player
player->save(zip);
// Then the stairs
stairs->save(zip);
// Then all the other actors
zip.putInt(actors.size() - 2);
for(Actor **it = actors.begin(); it != actors.end(); it++) {
if(*it != player && *it != stairs) {
(*it)->save(zip);
}
}
// Finally the message log
gui->save(zip);
zip.saveToFile("game.sav");
}
}
void Engine::load() {
engine.gui->menu.clear();
engine.gui->menu.addItem(Menu::NEW_GAME, "New Game");
if(TCODSystem::fileExists("game.sav")) {
engine.gui->menu.addItem(Menu::CONTINUE, "Continue");
}
engine.gui->menu.addItem(Menu::EXIT, "Exit");
Menu::MenuItemCode menuItem = engine.gui->menu.pick();
if(menuItem == Menu::EXIT || menuItem == Menu::NONE) {
// Exit or window closed
exit(0);
} else if(menuItem == Menu::NEW_GAME) {
// new game
engine.term();
engine.init();
} else {
TCODZip zip;
// Continue a saved game
engine.term();
zip.loadFromFile("game.sav");
// Load the map
int width = zip.getInt();
int height = zip.getInt();
map = new Map(width, height);
map->load(zip);
// Then load the player
player = new Actor(0, 0, 0, " ", TCODColor::white);
player->load(zip);
actors.push(player);
// The stairs
stairs=new Actor(0, 0, 0, " ", TCODColor::white);
stairs->load(zip);
actors.push(stairs);
// then all other actors
int nbActors=zip.getInt();
while(nbActors > 0) {
Actor *actor = new Actor(0, 0, 0, " ", TCODColor::white);
actor->load(zip);
actors.push(actor);
nbActors--;
}
// Finally the message log
gui->load(zip);
// to force FOV recomputation
gameStatus = STARTUP;
}
}
void Engine::nextLevel() {
level++;
gui->message(TCODColor::lightViolet, "You take a moment to rest and recover your strength.");
player->destructible->heal(player->destructible->maxHp/2);
gui->message(TCODColor::red, "After a rare moment of peace, you descend\ndeeper into the heart of the dungeon...");
delete map;
// Delete all actors but player and stairs
for(Actor **it=actors.begin(); it!=actors.end(); it++) {
if(*it != player && *it != stairs) {
delete *it;
it = actors.remove(it);
}
}
// Create a new map
map = new Map(80,43);
map->init(true);
gameStatus=STARTUP;
}

46
src/Engine.hpp Normal file
View File

@ -0,0 +1,46 @@
class Engine {
public :
enum GameStatus {
STARTUP,
IDLE,
NEW_TURN,
VICTORY,
DEFEAT
} gameStatus;
int fovRadius;
TCODList<Actor *> actors;
Actor *player;
Actor *stairs;
Map *map;
TCOD_key_t lastKey;
TCOD_mouse_t mouse;
int screenWidth;
int screenHeight;
Gui *gui;
Engine(int screenWidth, int screenHeight);
~Engine();
void update();
void render();
void sendToBack(Actor *actor);
Actor *getClosestMonster(int x, int y, float range) const;
Actor *getActor(int x, int y) const;
bool pickATile(int *x, int *y, float maxRange = 0.0f);
int level;
void nextLevel();
void init();
void term();
void load();
void save();
void log(unsigned char *msg);
};
extern Engine engine;

228
src/Gui.cpp Normal file
View File

@ -0,0 +1,228 @@
#include <stdio.h>
#include <stdarg.h>
#include "main.hpp"
static const int PANEL_HEIGHT=7;
static const int BAR_WIDTH=20;
static const int MSG_X=BAR_WIDTH+2;
static const int MSG_HEIGHT=PANEL_HEIGHT-1;
Gui::Gui() {
con = new TCODConsole(engine.screenWidth, PANEL_HEIGHT);
}
Gui::~Gui() {
delete con;
clear();
}
void Gui::clear() {
log.clearAndDelete();
}
void Gui::render() {
// Clear the GUI console
con->setDefaultBackground(TCODColor::black);
con->clear();
// Draw the Health bar
renderBar(1, 1, BAR_WIDTH, "HP", engine.player->destructible->hp,
engine.player->destructible->maxHp,
TCODColor::lightRed, TCODColor::darkerRed);
// Draw the XP bar
PlayerAi *ai=(PlayerAi *)engine.player->ai;
char xpTxt[128];
sprintf(xpTxt, "XP(%d)", ai->xpLevel);
renderBar(1, 5, BAR_WIDTH, xpTxt, engine.player->destructible->xp,
ai->getNextLevelXp(), TCODColor::lightViolet, TCODColor::darkerViolet);
// Draw the message log
int y=1;
float colorCoef=0.4f;
for(Message **it=log.begin(); it != log.end(); it++) {
Message *message=*it;
con->setDefaultForeground(message->col * colorCoef);
con->print(MSG_X, y, message->text);
y++;
if(colorCoef < 1.0f) {
colorCoef += 0.3f;
}
}
con->setDefaultForeground(TCODColor::white);
con->print(3, 3, "Dungeon level %d", engine.level);
// blit the GUI console on the root console
TCODConsole::blit(con, 0, 0, engine.screenWidth, PANEL_HEIGHT,
TCODConsole::root, 0, engine.screenHeight - PANEL_HEIGHT);
// Mouse look
renderMouseLook();
}
void Gui::renderBar(int x, int y, int width, const char *name,
float value, float maxValue, const TCODColor &barColor,
const TCODColor &backColor) {
// Fill the background
con->setDefaultBackground(backColor);
con->rect(x, y, width, 1, false, TCOD_BKGND_SET);
int barWidth = (int)(value / maxValue * width);
if(barWidth > 0) {
// Draw the bar
con->setDefaultBackground(barColor);
con->rect(x, y, barWidth, 1, false, TCOD_BKGND_SET);
}
// Print text on top of the bar
con->setDefaultForeground(TCODColor::white);
con->printEx(x + width/2, y, TCOD_BKGND_NONE, TCOD_CENTER,
"%s : %g/%g", name, value, maxValue);
}
Gui::Message::Message(const char *text, const TCODColor &col) : text(strdup(text)), col(col) { }
Gui::Message::~Message() {
free(text);
}
void Gui::message(const TCODColor &col, const char *text, ...) {
// Build the text
va_list ap;
char buf[128];
va_start(ap, text);
vsprintf(buf, text, ap);
va_end(ap);
char *lineBegin=buf;
char *lineEnd;
do {
// make room for the new message
if(log.size() == MSG_HEIGHT) {
Message *toRemove=log.get(0);
log.remove(toRemove);
delete toRemove;
}
// Detect end of the line
lineEnd=strchr(lineBegin, '\n');
if(lineEnd) {
*lineEnd='\0';
}
// Add a new message to the log
Message *msg = new Message(lineBegin, col);
log.push(msg);
// Go to next line
lineBegin = lineEnd + 1;
} while(lineEnd);
}
void Gui::renderMouseLook() {
if(!engine.map->isInFov(engine.mouse.cx, engine.mouse.cy)) {
// If mouse is out of fov, nothing to render
return;
}
char buf[128]="";
bool first=true;
for(Actor **it=engine.actors.begin(); it != engine.actors.end(); it++) {
Actor *actor=*it;
// Find the actors under the mouse cursor
if(actor->x == engine.mouse.cx && actor->y == engine.mouse.cy) {
if(!first) {
strcat(buf, ", ");
} else {
first=false;
}
strcat(buf, actor->name);
}
}
// Display the list of actors under the mouse cursor
con->setDefaultForeground(TCODColor::lightGrey);
con->print(1, 0, buf);
}
void Gui::save(TCODZip &zip) {
zip.putInt(log.size());
for(Message **it = log.begin(); it != log.end(); it++) {
zip.putString((*it)->text);
zip.putColor(&(*it)->col);
}
}
void Gui::load(TCODZip &zip) {
int nbMessages = zip.getInt();
while(nbMessages > 0) {
const char *text = zip.getString();
TCODColor col = zip.getColor();
message(col, text);
nbMessages--;
}
}
Menu::~Menu() {
clear();
}
void Menu::clear() {
items.clearAndDelete();
}
void Menu::addItem(MenuItemCode code, const char *label) {
MenuItem *item=new MenuItem();
item->code=code;
item->label=label;
items.push(item);
}
const int PAUSE_MENU_WIDTH=30;
const int PAUSE_MENU_HEIGHT=15;
Menu::MenuItemCode Menu::pick(DisplayMode mode) {
int selectedItem=0;
int menux, menuy;
if(mode == PAUSE) {
menux = engine.screenWidth/2-PAUSE_MENU_WIDTH/2;
menuy = engine.screenHeight/2-PAUSE_MENU_HEIGHT/2;
TCODConsole::root->setDefaultForeground(TCODColor(200, 180, 50));
TCODConsole::root->printFrame(menux, menuy, PAUSE_MENU_WIDTH, PAUSE_MENU_HEIGHT, true,
TCOD_BKGND_ALPHA(70), "menu");
menux+=2;
menuy+=3;
} else {
static TCODImage img("menu_background1.png");
img.blit2x(TCODConsole::root, 0, 0);
menux = 10;
menuy = TCODConsole::root->getHeight()/3;
}
while(!TCODConsole::isWindowClosed()) {
int currentItem = 0;
for(MenuItem **it = items.begin(); it != items.end(); it++) {
if(currentItem == selectedItem) {
TCODConsole::root->setDefaultForeground(TCODColor::lighterOrange);
} else {
TCODConsole::root->setDefaultForeground(TCODColor::lightGrey);
}
TCODConsole::root->print(menux, menuy + currentItem * 3, (*it)->label);
currentItem++;
}
TCODConsole::flush();
// Check key presses
TCOD_key_t key;
TCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS, &key, NULL);
switch(key.vk) {
case TCODK_UP:
selectedItem--;
if(selectedItem < 0) {
selectedItem=items.size()-1;
}
break;
case TCODK_DOWN:
selectedItem = (selectedItem + 1) % items.size();
break;
case TCODK_ENTER: return items.get(selectedItem)->code;
default: break;
}
}
return NONE;
}

56
src/Gui.hpp Normal file
View File

@ -0,0 +1,56 @@
class Menu {
public :
enum MenuItemCode {
NONE,
NEW_GAME,
CONTINUE,
EXIT,
CONSTITUTION,
STRENGTH,
AGILITY
};
enum DisplayMode {
MAIN,
PAUSE
};
~Menu();
void clear();
void addItem(MenuItemCode code, const char *label);
MenuItemCode pick(DisplayMode mode=MAIN);
protected :
struct MenuItem {
MenuItemCode code;
const char *label;
};
TCODList<MenuItem *> items;
};
class Gui : public Persistent {
public :
Menu menu;
Gui();
~Gui();
void render();
void message(const TCODColor &col, const char *text, ...);
void load(TCODZip &zip);
void save(TCODZip &zip);
void clear();
protected:
TCODConsole *con;
struct Message {
char *text;
TCODColor col;
Message(const char *text, const TCODColor &col);
~Message();
};
TCODList<Message *> log;
void renderBar(int x, int y, int width, const char *name,
float value, float maxValue, const TCODColor &barColor,
const TCODColor &backColor);
void renderMouseLook();
};

240
src/Map.cpp Normal file
View File

@ -0,0 +1,240 @@
#include "libtcod.hpp"
#include "main.hpp"
static const int ROOM_MAX_SIZE = 12;
static const int ROOM_MIN_SIZE = 6;
static const int MAX_ROOM_MONSTERS = 3;
static const int MAX_ROOM_ITEMS = 2;
class BspListener : public ITCODBspCallback {
private :
Map &map; // a map to dig
int roomNum; // room number
int lastx, lasty; // center of the last room
public :
BspListener(Map &map) : map(map), roomNum(0) {}
bool visitNode(TCODBsp *node, void *userData) {
if(node->isLeaf()) {
int x, y, w, h;
bool withActors = (bool)userData;
// dig a room
w=map.rng->getInt(ROOM_MIN_SIZE, node->w-2);
h=map.rng->getInt(ROOM_MIN_SIZE, node->h-2);
x=map.rng->getInt(node->x+1, node->x+node->w-w-1);
y=map.rng->getInt(node->y+1, node->y+node->h-h-1);
map.createRoom(roomNum == 0, x, y, x+w-1, y+h-1, withActors);
if(roomNum != 0) {
// Dig a corridor from last room
map.dig(lastx, lasty, x+w/2, lasty);
map.dig(x+w/2, lasty, x+w/2, y+h/2);
}
lastx=x+w/2;
lasty=y+h/2;
roomNum++;
}
return true;
}
};
Map::Map(int width, int height) : width(width), height(height) {
seed = TCODRandom::getInstance()->getInt(0, 0x7FFFFFFF);
}
void Map::init(bool withActors) {
rng = new TCODRandom(seed, TCOD_RNG_CMWC);
tiles = new Tile[width*height];
map = new TCODMap(width, height);
TCODBsp bsp(0, 0, width, height);
bsp.splitRecursive(rng, 8, ROOM_MAX_SIZE, ROOM_MAX_SIZE, 1.5f, 1.5f);
BspListener listener(*this);
bsp.traverseInvertedLevelOrder(&listener, (void *)withActors);
}
Map::~Map() {
delete [] tiles;
delete map;
}
bool Map::isExplored(int x, int y) const {
return tiles[x+y*width].explored;
}
bool Map::isInFov(int x, int y) const {
if(x < 0 || x >= width || y < 0 || y >= height) {
return false;
}
if(map->isInFov(x, y)) {
tiles[x+y*width].explored=true;
return true;
}
return false;
}
void Map::computeFov() {
map->computeFov(engine.player->x, engine.player->y,
engine.fovRadius);
}
void Map::dig(int x1, int y1, int x2, int y2) {
if(x2 < x1) {
int tmp=x2;
x2=x1;
x1=tmp;
}
if(y2 < y1) {
int tmp=y2;
y2=y1;
y1=tmp;
}
for(int tilex=x1; tilex <= x2; tilex++) {
for(int tiley=y1; tiley <= y2; tiley++) {
map->setProperties(tilex, tiley, true, true);
}
}
}
void Map::createRoom(bool first, int x1, int y1, int x2, int y2, bool withActors) {
dig(x1, y1, x2, y2);
if(!withActors) {
return;
}
if(first) {
// Put the player in the first room
engine.player->x=(x1+x2)/2;
engine.player->y=(y1+y2)/2;
} else {
TCODRandom *rng=TCODRandom::getInstance();
// Add Monsters
int nbMonsters=rng->getInt(0, MAX_ROOM_MONSTERS);
while(nbMonsters > 0) {
int x=rng->getInt(x1, x2);
int y=rng->getInt(y1, y2);
if(canWalk(x, y)) {
addMonster(x, y);
}
nbMonsters--;
}
// Add Items
int nbItems=rng->getInt(0, MAX_ROOM_ITEMS);
while(nbItems > 0) {
int x=rng->getInt(x1, x2);
int y=rng->getInt(y1, y2);
if(canWalk(x, y)) {
addItem(x, y);
}
nbItems--;
}
}
engine.stairs->x=(x1+x2)/2;
engine.stairs->y=(y1+y2)/2;
}
bool Map::isWall(int x, int y) const {
return !map->isWalkable(x, y);
}
bool Map::canWalk(int x, int y) const {
if(isWall(x, y)) {
// This is a wall
return false;
}
for(Actor **iterator=engine.actors.begin();
iterator!=engine.actors.end();iterator++) {
Actor *actor=*iterator;
if(actor->x == x && actor->y == y) {
// There is an actor there. Cannot walk.
return false;
}
}
return true;
}
void Map::addMonster(int x, int y) {
TCODRandom *rng=TCODRandom::getInstance();
if(rng->getInt(0, 100) < 80) {
// Create an orc
Actor *orc = new Actor(x, y, 'o', "orc", TCODColor::desaturatedGreen);
orc->destructible = new MonsterDestructible(10, 0, "Dead orc", 10);
orc->attacker = new Attacker(3);
orc->ai = new MonsterAi();
engine.actors.push(orc);
} else {
// Create a troll
Actor *troll = new Actor(x, y, 'T', "troll", TCODColor::darkerGreen);
troll->destructible = new MonsterDestructible(16, 1, "Dead troll", 25);
troll->attacker = new Attacker(4);
troll->ai = new MonsterAi();
engine.actors.push(troll);
}
}
void Map::addItem(int x, int y) {
TCODRandom *rng=TCODRandom::getInstance();
int dice = rng->getInt(0, 100);
if(dice < 70) {
Actor *healthPotion = new Actor(x, y, '!', "Health Potion",
TCODColor::violet);
healthPotion->blocks=false;
healthPotion->pickable=new Healer(4);
engine.actors.push(healthPotion);
} else if(dice < 70 + 10) {
// Create a scroll of lightning bolt
Actor *scrollOfLightningBolt = new Actor(x, y, '#',
"Scroll of lightning bolt", TCODColor::lightYellow);
scrollOfLightningBolt->blocks = false;
scrollOfLightningBolt->pickable = new LightningBolt(5, 20);
engine.actors.push(scrollOfLightningBolt);
} else if(dice < 70 + 10 + 10) {
// Create a scroll of fireball
Actor *scrollOfFireball = new Actor(x, y, '#', "Scroll of fireball",
TCODColor::lightYellow);
scrollOfFireball->blocks = false;
scrollOfFireball->pickable = new Fireball(3, 12);
engine.actors.push(scrollOfFireball);
} else {
// create a scroll of confusion
Actor *scrollOfConfusion = new Actor(x, y, '#',
"Scroll of confusion", TCODColor::lightYellow);
scrollOfConfusion->blocks=false;
scrollOfConfusion->pickable = new Confuser(10,8);
engine.actors.push(scrollOfConfusion);
}
}
void Map::render() const {
static const TCODColor darkWall(0, 0, 100);
static const TCODColor darkGround(50, 50, 150);
static const TCODColor lightWall(130, 110, 50);
static const TCODColor lightGround(200, 180, 50);
for(int x=0; x < width; x++) {
for(int y=0; y < height; y++) {
if(isInFov(x, y)) {
TCODConsole::root->setCharBackground(x, y,
isWall(x, y) ? lightWall:lightGround);
} else if(isExplored(x, y)) {
TCODConsole::root->setCharBackground(x, y,
isWall(x,y) ? darkWall:darkGround);
}
}
}
}
void Map::save(TCODZip &zip) {
zip.putInt(seed);
for(int i = 0; i < width * height; i++) {
zip.putInt(tiles[i].explored);
}
}
void Map::load(TCODZip &zip) {
seed=zip.getInt();
init(false);
for(int i =0; i < width * height; i++) {
tiles[i].explored=zip.getInt();
}
}

32
src/Map.hpp Normal file
View File

@ -0,0 +1,32 @@
struct Tile {
bool explored; // has the player already seen this tile?
Tile() : explored(false) {}
};
class Map : public Persistent {
public:
int width, height;
Map(int width, int height);
~Map();
bool isWall(int x, int y) const;
bool isInFov(int x, int y) const;
bool isExplored(int x, int y) const;
bool canWalk(int x, int y) const;
void computeFov();
void render() const;
void addMonster(int x, int y);
void addItem(int x, int y);
void init(bool withActors);
void load(TCODZip &zip);
void save(TCODZip &zip);
protected :
Tile *tiles;
TCODMap *map;
long seed;
TCODRandom *rng;
friend class BspListener;
void dig(int x1, int y1, int x2, int y2);
void createRoom(bool first, int x1, int y1, int x2, int y2, bool withActors);
};

5
src/Persistent.hpp Normal file
View File

@ -0,0 +1,5 @@
class Persistent {
public:
virtual void load(TCODZip &zip) = 0;
virtual void save(TCODZip &zip) = 0;
};

222
src/Pickable.cpp Normal file
View File

@ -0,0 +1,222 @@
#include "main.hpp"
bool Pickable::pick(Actor *owner, Actor *wearer) {
if(wearer->container && wearer->container->add(owner)) {
engine.actors.remove(owner);
return true;
}
return false;
}
bool Pickable::use(Actor *owner, Actor *wearer) {
if(wearer->container) {
wearer->container->remove(owner);
delete owner;
return true;
}
return false;
}
void Pickable::drop(Actor *owner, Actor *wearer) {
if(wearer->container) {
wearer->container->remove(owner);
engine.actors.push(owner);
owner->x = wearer->x;
owner->y = wearer->y;
engine.gui->message(TCODColor::lightGrey, "%s drops a %s.",
wearer->name, owner->name);
}
}
/* Pickable Factory */
Pickable *Pickable::create(TCODZip &zip) {
PickableType type=(PickableType)zip.getInt();
Pickable *pickable=NULL;
switch(type) {
case HEALER: pickable = new Healer(0); break;
case LIGHTNING_BOLT: pickable = new LightningBolt(0, 0); break;
case CONFUSER: pickable = new Confuser(0, 0); break;
case FIREBALL: pickable = new Fireball(0, 0); break;
}
pickable->load(zip);
return pickable;
}
TargetSelector::TargetSelector(SelectorType type, float range) :
type(type), range(range) { }
void TargetSelector::selectTargets(Actor *wearer, TCODList<Actor *> & list) {
switch(type) {
case CLOSEST_MONSTER: {
Actor *closestMonster=engine.getClosestMonster(wearer->x, wearer->y, range);
if(closestMonster) {
list.push(closestMonster);
}
}
break;
case SELECTED_MONSTER: {
int x, y;
engine.gui->message(TCODColor::cyan, "Left-click to select a target,\nor right-click to cancel.");
if(engine.pickATile(&x, &y, range)) {
Actor *actor=engine.getActor(x, y);
if(actor) {
list.push(actor);
}
}
}
break;
case WEARER_RANGE:
for(Actor **iterator=engine.actors.begin();
iterator != engine.actors.end(); iterator++) {
Actor *actor=*iterator;
if(actor != wearer && actor->destructible && !actor->destructible->isDead()
&& actor->getDistance(wearer->x, wearer->y) <= range) {
list.push(actor);
}
}
break;
case SELECTED_RANGE:
int x, y;
engine.gui->message(TCODColor::cyan, "Left-click to select a tile,\nor right-click to cancel.");
if(engine.pickATile(&x, &y)) {
for(Actor **iterator = engine.actors.begin();
iterator != engine.actors.end(); iterator++) {
Actor *actor=*iterator;
if(actor->destructible && !actor->destructible->isDead()
&& actor->getDistance(x, y) <= range) {
list.push(actor);
}
}
}
break;
}
if(list.isEmpty()) {
engine.gui->message(TCODColor::lightGrey, "No enemy is close enough");
}
}
/* Sub-Pickables */
Healer::Healer(float amount) : amount(amount) { }
bool Healer::use(Actor *owner, Actor *wearer) {
if(wearer->destructible) {
float amountHealed = wearer->destructible->heal(amount);
if(amountHealed > 0) {
return Pickable::use(owner, wearer);
}
}
return false;
}
void Healer::load(TCODZip &zip) {
amount=zip.getFloat();
}
void Healer::save(TCODZip &zip) {
zip.putInt(HEALER);
zip.putFloat(amount);
}
LightningBolt::LightningBolt(float range, float damage)
: range(range), damage(damage) { }
bool LightningBolt::use(Actor *owner, Actor *wearer) {
Actor *closestMonster = engine.getClosestMonster(
wearer->x, wearer->y, range);
if(!closestMonster) {
engine.gui->message(TCODColor::lightGrey, "No enemy is close enough to strike.");
return false;
}
// Hit closest monster for <damage> hit points
engine.gui->message(TCODColor::lightBlue,
"A lightning bolt strikes the %s with a loud thunder!\nThe damage is %g hit points.",
closestMonster->name, damage);
closestMonster->destructible->takeDamage(closestMonster, damage);
return Pickable::use(owner, wearer);
}
void LightningBolt::load(TCODZip &zip) {
range=zip.getFloat();
damage=zip.getFloat();
}
void LightningBolt::save(TCODZip &zip) {
zip.putInt(LIGHTNING_BOLT);
zip.putFloat(range);
zip.putFloat(damage);
}
Fireball::Fireball(float range, float damage)
: LightningBolt(range, damage) { }
bool Fireball::use(Actor *owner, Actor *wearer) {
engine.gui->message(TCODColor::cyan, "Left-click a target tile for the fireball,\nor right-click to cancel.");
int x, y;
if(!engine.pickATile(&x, &y)) {
return false;
}
// Burn everything in <range> (including player)
engine.gui->message(TCODColor::orange, "The fireball explodes, burning everything within %g tiles!", range);
for(Actor **iterator=engine.actors.begin();
iterator != engine.actors.end(); iterator++) {
Actor *actor = *iterator;
if(actor->destructible && !actor->destructible->isDead()
&& actor->getDistance(x, y) <= range) {
engine.gui->message(TCODColor::orange, "The %s gets burned for %g hit points.",
actor->name, damage);
actor->destructible->takeDamage(actor, damage);
}
}
return Pickable::use(owner, wearer);
}
void Fireball::save(TCODZip &zip) {
zip.putInt(FIREBALL);
zip.putFloat(range);
zip.putFloat(damage);
}
Confuser::Confuser(int nbTurns, float range)
: nbTurns(nbTurns), range(range) { }
bool Confuser::use(Actor *owner, Actor *wearer) {
engine.gui->message(TCODColor::cyan, "Left-click an enemy to confuse it,\nor right-click to cancel.");
int x, y;
if(!engine.pickATile(&x, &y, range)) {
return false;
}
Actor *actor = engine.getActor(x, y);
if(!actor) {
return false;
}
// Confuse the monster for <nbTurns> turns
Ai *confusedAi = new ConfusedMonsterAi(nbTurns, actor->ai);
actor->ai = confusedAi;
engine.gui->message(TCODColor::lightGreen, "The eyes of the %s look vacant,\nas he starts to stumble around!", actor->name);
return Pickable::use(owner, wearer);
}
void Confuser::load(TCODZip &zip) {
nbTurns=zip.getInt();
range=zip.getFloat();
}
void Confuser::save(TCODZip &zip) {
zip.putInt(CONFUSER);
zip.putInt(nbTurns);
zip.putFloat(range);
}
HealthEffect::HealthEffect(float amount, const char *message)
: amount(amount), message(message) { }
bool HealthEffect::applyTo(Actor *actor) {
if(!actor->destructible) return false;
if(amount > 0) {
float pointsHealed = actor->destructible->heal(amount);
if(pointsHealed > 0) {
if(message) {
engine.gui->message(TCODColor::lightGrey, message, actor->name, pointsHealed);
}
return true;
}
} else {
if(message && -amount-actor->destructible->defense > 0) {
engine.gui->message(TCODColor::lightGrey, message, actor->name,
-amount-actor->destructible->defense);
}
if(actor->destructible->takeDamage(actor, -amount) > 0) {
return true;
}
}
return false;
}

78
src/Pickable.hpp Normal file
View File

@ -0,0 +1,78 @@
class TargetSelector {
public:
enum SelectorType {
CLOSEST_MONSTER,
SELECTED_MONSTER,
WEARER_RANGE,
SELECTED_RANGE
};
TargetSelector(SelectorType type, float range);
void selectTargets(Actor *wearer, TCODList<Actor *>& list);
protected:
SelectorType type;
float range;
};
class Effect {
public:
virtual bool applyTo(Actor *actor) = 0;
};
class Pickable : public Persistent {
public:
bool pick(Actor *owner, Actor *wearer);
void drop(Actor *owner, Actor *wearer);
virtual bool use(Actor *owner, Actor *wearer);
static Pickable *create(TCODZip &zip);
protected:
enum PickableType {
HEALER, LIGHTNING_BOLT, CONFUSER, FIREBALL
};
};
/* Sub-Pickables */
class Healer : public Pickable {
public:
float amount; // how much?
Healer(float amount);
bool use(Actor *owner, Actor *wearer);
void load(TCODZip &zip);
void save(TCODZip &zip);
};
/* Aggro Spells */
class LightningBolt: public Pickable {
public:
float range, damage;
LightningBolt(float range, float damage);
bool use(Actor *owner, Actor *wearer);
void load(TCODZip &zip);
void save(TCODZip &zip);
};
class Fireball : public LightningBolt {
public:
Fireball(float range, float damage);
bool use(Actor *owner, Actor *wearer);
void save(TCODZip &zip);
};
class Confuser : public Pickable {
public:
int nbTurns;
float range;
Confuser(int nbTurns, float range);
bool use(Actor *owner, Actor *wearer);
void load(TCODZip &zip);
void save(TCODZip &zip);
};
/* Effects */
class HealthEffect : public Effect {
public:
float amount;
const char *message;
HealthEffect(float amount, const char *message);
bool applyTo(Actor *actor);
};

16
src/main.cpp Normal file
View File

@ -0,0 +1,16 @@
#include <stdio.h>
#include "libtcod.hpp"
#include "main.hpp"
Engine engine(80, 50);
int main() {
engine.load();
while(!TCODConsole::isWindowClosed()) {
engine.update();
engine.render();
TCODConsole::flush();
}
engine.save();
return 0;
}

12
src/main.hpp Normal file
View File

@ -0,0 +1,12 @@
#include "libtcod.hpp"
class Actor;
#include "Persistent.hpp"
#include "Destructible.hpp"
#include "Attacker.hpp"
#include "Ai.hpp"
#include "Pickable.hpp"
#include "Container.hpp"
#include "Actor.hpp"
#include "Map.hpp"
#include "Gui.hpp"
#include "Engine.hpp"

BIN
src/main.hpp.gch Normal file

Binary file not shown.

BIN
terminal.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB