Refactor, separate docs from headers, add ru docs

Doxygen kind'a sucks and I need multilanguage documentation, so I did
that. Also, separated massive Math.h file into smaller files.
This commit is contained in:
2025-06-21 20:12:15 +03:00
parent 7ee69fc397
commit fc774fd0ff
116 changed files with 10693 additions and 3521 deletions

5
.gitignore vendored
View File

@@ -73,3 +73,8 @@ _deps
# MacOS
.DS_Store
# Exclude docs artifacts
*.html
*.3
*.zip

View File

@@ -113,7 +113,22 @@ set(BH_HEADER
include/BH/Common.h
include/BH/Hashmap.h
include/BH/IO.h
include/BH/Math.h
include/BH/Math/Box2f.h
include/BH/Math/Box3f.h
include/BH/Math/Line.h
include/BH/Math/Mat3f.h
include/BH/Math/Mat4f.h
include/BH/Math/Misc.h
include/BH/Math/Plane.h
include/BH/Math/Quat.h
include/BH/Math/Ray2f.h
include/BH/Math/Ray3f.h
include/BH/Math/Vec2f.h
include/BH/Math/Vec2i.h
include/BH/Math/Vec3f.h
include/BH/Math/Vec3i.h
include/BH/Math/Vec4f.h
include/BH/Math/Vec4i.h
include/BH/Queue.h
include/BH/Thread.h
include/BH/Util.h

View File

@@ -1,5 +1,5 @@
#include <BH/IO.h>
#include <BH/String.h>
#include <BH/Unicode.h>
#include <stdlib.h>
#include <stdio.h>

View File

@@ -16,7 +16,7 @@ To do this we would run the following command:
To implement this utility, we are going to need to include the following headers:
- `BH/IO.h` to work with files (or input/output devices)
- `BH/String.h` to work with UTF-8 sequences
- `BH/Unicode.h` to work with UTF-8 sequences
## Working with Files
@@ -88,7 +88,7 @@ while (...)
```c
#include <BH/IO.h>
#include <BH/String.h>
#include <BH/Unicode.h>
#include <stdlib.h>
#include <stdio.h>

162
doc/Manual/en/BH_Algo.pod Normal file
View File

@@ -0,0 +1,162 @@
=encoding UTF-8
=head1 NAME
BH_Algo - General algorithms
=head1 SYNTAX
#include <BH/Algo.h>
int data[4] = {5, 2, 3, 1};
int value, i;
value = 4;
BH_Partition(&value, data, 4, sizeof(int), intEqual);
BH_Sort(data, 4, sizeof(int), intEqual);
BH_HeapMake(data, 4, sizeof(int), intEqual);
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Algo library provides a set of algorithms for working with data:
=over
=item *
Value swapping (L</BH_Swap>)
=item *
Array partitioning (L</BH_Partition>)
=item *
Sorting (L</BH_Sort>)
=item *
Heap operations (L</BH_HeapMake>, L</BH_HeapRemove>, L</BH_HeapInsert>,
L</BH_HeapReplace>)
=back
These algorithms allow you to efficiently perform various operations on arrays
and other data structures.
=head1 API CALLS
=head2 BH_Swap
void BH_Swap(void *dest,
void *src,
size_t size);
Swaps the values between the variables I<dest> and I<src> of the specified size
I<size>.
=head2 BH_Partition
void *BH_Partition(void *pivot,
void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Partitions the array of elements I<array> (with the number of elements I<size>
and the size of the element I<element>) into two groups relative to the pivot
element I<pivot>.
The I<equal> parameter takes a pointer to a function that compares two elements.
The I<pivot> parameter can refer to an element of the array being partitioned.
The function returns a pointer to the first element of the array that belongs to
the second group.
=head2 BH_Sort
void BH_Sort(void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Sorts the array of elements I<array> (with the number of elements I<size> and
the size of the element I<element>).
The I<equal> parameter takes a pointer to a function that compares two elements.
=head2 BH_HeapMake
void BH_HeapMake(void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Creates a heap in the array I<array> (with the number of elements I<size> and
the size of the element I<element>).
The I<equal> parameter takes a pointer to a function that compares two elements.
=head2 BH_HeapRemove
void BH_HeapRemove(void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Extracts the top element of the heap in the array I<array> (with the number of
elements I<size> and the size of the element I<element>).
The I<equal> parameter takes a pointer to a function that compares two elements.
=head2 BH_HeapInsert
void BH_HeapInsert(void *value,
void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Adds the element I<value> to the heap in the array I<array> (with the number of
elements I<size> and the size of the element I<element>).
If I<value> is NULL, it is assumed that the new value is at the end of the
array.
The I<equal> parameter takes a pointer to a function that compares two elements.
=head2 BH_HeapReplace
void BH_HeapReplace(void *value,
void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Extracts the top element of the heap in the array I<array> (with the number of
elements I<size> and the size of the element I<element>) and adds the element
I<value> to it.
If I<value> is NULL, it is assumed that the new value is at the end of the
array.
The I<equal> parameter takes a pointer to a function that compares two elements.
=head1 SEE ALSO
L<BH>

164
doc/Manual/en/BH_Args.pod Normal file
View File

@@ -0,0 +1,164 @@
=encoding UTF-8
=head1 NAME
BH_Args - command line argument processing
=head1 SYNTAX
#include <BH/Args.h>
static BH_ArgsOption options[] =
{
{'h', "help", 0, "Display this help"},
{1000, "list", 0, "List files"},
{'i', "input", BH_ARGS_VALUE, "Input file"},
{'o', "output", BH_ARGS_VALUE | BH_ARGS_OPTIONAL, "Output file"},
{0, NULL, 0, NULL}
};
static int OptionsCallback(int key,
char *arg,
void *data)
{
switch (key)
{
case BH_ARGS_UNKNOWN:
/* Unknown options */
break;
case BH_ARGS_ARGUMENT:
/* Regular argument in arg */
break;
case 'h':
/* Named option without argument */
break;
case 1000:
/* Long-only option without argument */
break;
case 'i':
/* Option with argument in arg */
break;
case 'o':
/* Option with optional argument in arg */
break;
}
return BH_OK;
}
BH_ArgsParse(argc, argv, options, OptionsCallback, NULL);
BH_ArgsHelp(options, 0);
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Args library is designed for convenient handling of command line
arguments in programs. It allows you to define a set of options that can be
specified when starting a program and provides mechanisms for their analysis and
processing.
Argument parsing follows these rules:
=over
=item *
If the "--" argument is specified, subsequent argument parsing is stopped.
=item *
If the "-" argument is specified, it is processed as is.
=item *
For long argument values, the string after the equal sign or the next argument
("--define=value" or "--define value") will be used.
=item *
For short argument values, the remainder of the string after the parameter
character or the next argument ("-dvalue" or "-d value") will be used.
=back
=head1 API CALLS
=head2 BH_ArgsParse
int BH_ArgsParse(int argc,
char **argv,
BH_ArgsOption *options,
BH_ArgsCallback callback,
void *data);
Parses the command line arguments I<options> (specified in I<argc> and I<argv>)
and calls the specified handler I<callback> (with user data I<data>).
The I<options> parameter refers to a null-terminated array.
If successful, this function returns 0, otherwise it returns an error code.
=head2 BH_ArgsHelp
void BH_ArgsHelp(BH_ArgsOption *options,
int padding);
Prints help information for the arguments I<options> to F<stdout> (with the
specified alignment I<padding>).
If the I<padding> parameter is 0, the default value (30) will be used.
=head1 STRUCTURES
=head2 BH_ArgsOption
typedef struct BH_ArgsOption
{
int key;
const char *name;
int flags;
const char *description;
} BH_ArgsOption;
The I<key> field contains the option identifier. If the I<key> identifier is a
printable ASCII character, it will be used as a short argument.
The optional I<name> field contains a string that will be used as a long
argument.
The I<flags> field contains argument flags. A combination of the following flags
is possible:
=over
=item B<BH_ARGS_VALUE>
The argument accepts a value.
=item B<BH_ARGS_OPTIONAL>
The argument value is optional.
=back
The I<description> field contains a string that will be used when displaying
help information using the L</BH_ArgsHelp> function.
=head1 SEE ALSO
L<BH>

View File

@@ -0,0 +1,98 @@
=encoding UTF-8
=head1 NAME
BH_Box2f - two-dimensional bounding box
=head1 SYNTAX
#include <BH/Math/Box2f.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Box2f module provides functions for working with two-dimensional bounding
boxes. It includes operations for union, intersection, checking if a point is
inside a rectangle, and calculating the bounding box for a set of points.
=head1 API CALLS
=head2 BH_Box2fUnion
void BH_Box2fUnion(const float aMin[2],
const float aMax[2],
const float bMin[2],
const float bMax[2],
float outMin[2],
float outMax[2]);
Combines two bounding boxes A and B.
The parameters I<aMin> and I<aMax> describe the bounding box A.
The parameters I<bMin> and I<bMax> describe the bounding box B.
The parameters I<outMin> and I<outMax> describe the resulting bounding box.
=head2 BH_Box2fIntersect
int BH_Box2fIntersect(const float aMin[2],
const float aMax[2],
const float bMin[2],
const float bMax[2],
float outMin[2],
float outMax[2]);
Calculates the intersection of two bounding boxes A and B.
The parameters I<aMin> and I<aMax> describe the bounding box A.
The parameters I<bMin> and I<bMax> describe the bounding box B.
The parameters I<outMin> and I<outMax> describe the resulting bounding box.
Returns 0 in case of successful intersection or an error code.
=head2 BH_Box2fContains
int BH_Box2fContains(const float aMin[2],
const float aMax[2],
const float point[2]);
Checks if the point is inside the bounding box.
The parameters I<aMin> and I<aMax> describe the bounding box.
The parameter I<point> describes the point.
Returns 0 if the point is inside the rectangle, or an error code.
=head2 BH_Box2fEnclose
int BH_Box2fEnclose(const float *points,
size_t size,
float outMin[2],
float outMax[2]);
Calculates the bounding box for the given points.
The parameters I<points> and I<size> describe the input array of points.
The parameters I<outMin> and I<outMax> describe the resulting bounding box.
Returns 0 in case of successful calculation or an error code.
=head1 SEE ALSO
L<BH>,
L<BH_Box3f>

View File

@@ -0,0 +1,98 @@
=encoding UTF-8
=head1 NAME
BH_Box3f - three-dimensional bounding box
=head1 SYNTAX
#include <BH/Math/Box3f.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Box3f module provides functions for working with three-dimensional
bounding boxes. It includes operations for union, intersection, checking if a
point is inside a box, and calculating the bounding box for a set of points.
=head1 API CALLS
=head2 BH_Box3fUnion
void BH_Box3fUnion(const float aMin[3],
const float aMax[3],
const float bMin[3],
const float bMax[3],
float outMin[3],
float outMax[3]);
Combines two bounding boxes I<A> and I<B>.
The parameters I<aMin> and I<aMax> describe the bounding box A.
The parameters I<bMin> and I<bMax> describe the bounding box B.
The parameters I<outMin> and I<outMax> describe the resulting bounding box.
=head2 BH_Box3fIntersect
int BH_Box3fIntersect(const float aMin[3],
const float aMax[3],
const float bMin[3],
const float bMax[3],
float outMin[3],
float outMax[3]);
Calculates the intersection of two bounding boxes A and B.
The parameters I<aMin> and I<aMax> describe the bounding box A.
The parameters I<bMin> and I<bMax> describe the bounding box B.
The parameters I<outMin> and I<outMax> describe the resulting bounding box.
Returns 0 in case of successful intersection or an error code.
=head2 BH_Box3fContains
int BH_Box3fContains(const float aMin[3],
const float aMax[3],
const float point[3]);
Checks if the point is inside the bounding box.
The parameters I<aMin> and I<aMax> describe the bounding box.
The parameter I<point> describes the point.
Returns 0 if the point is inside the bounding box, or an error code.
=head2 BH_Box3fEnclose
int BH_Box3fEnclose(const float *points,
size_t size,
float outMin[3],
float outMax[3]);
Calculates the bounding box for the given points.
The parameters I<points> and I<size> describe the input array of points.
The parameters I<outMin> and I<outMax> describe the resulting bounding box.
Returns 0 in case of success or an error code.
=head1 SEE ALSO
L<BH>,
L<BH_Box2f>

View File

@@ -0,0 +1,197 @@
=encoding UTF-8
=head1 NAME
BH_Hashmap - unordered associative array
=head1 SYNTAX
#include <BH/Hashmap.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Hashmap library provides an implementation of an unordered associative
array based on a hash table. It allows you to store and retrieve data by key
efficiently.
=head1 API CALLS
=head2 BH_HashmapNew
BH_Hashmap *BH_HashmapNew(BH_EqualCallback equal,
BH_HashCallback hash);
Creates an associative array.
The I<equal> parameter takes a pointer to a function that compares two elements.
The I<hash> parameter takes a pointer to a function that calculates the hash
value of an element.
If successful, the function returns a pointer to a new BH_Hashmap object or NULL
in case of an error.
=head2 BH_HashmapFree
void BH_HashmapFree(BH_Hashmap *hashmap);
Destroys the associative array.
=head2 BH_HashmapClear
void BH_HashmapClear(BH_Hashmap *hashmap);
Clears the associative array.
=head2 BH_HashmapReserve
int BH_HashmapReserve(BH_Hashmap *hashmap,
size_t size);
Reserves space for at least I<size> elements.
Calling this function invalidates existing iterators.
If successful, the function returns 0; otherwise, it returns an error code.
=head2 BH_HashmapInsert
int BH_HashmapInsert(BH_Hashmap *hashmap,
void *key,
void *value);
Inserts an element represented by the key-value pair I<key> and I<value>.
The function allows inserting multiple elements with the same key value.
Calling this function invalidates existing iterators.
If successful, the function returns 0; otherwise, it returns an error code.
=head2 BH_HashmapRemove
void BH_HashmapRemove(BH_Hashmap *hashmap,
void *key);
Removes the element with the given key value I<key>.
If the associative array contains multiple elements with the same key value, the
function will remove only one key-value pair.
Calling this function invalidates existing iterators.
=head2 BH_HashmapAt
int BH_HashmapAt(BH_Hashmap *hashmap,
void *key,
void **value);
Checks if there is an element with the given key I<key>.
The optional I<value> parameter returns the value of the element with the given
key.
If successful, the function returns 0; otherwise, it returns an error code.
=head2 BH_HashmapEmpty
int BH_HashmapEmpty(BH_Hashmap *hashmap);
Checks if the associative array is empty.
=head2 BH_HashmapSize
size_t BH_HashmapSize(BH_Hashmap *hashmap);
Returns the number of elements.
=head2 BH_HashmapCapacity
size_t BH_HashmapCapacity(BH_Hashmap *hashmap);
Returns the capacity.
=head2 BH_HashmapFactor
float BH_HashmapFactor(BH_Hashmap *hashmap);
Returns the maximum load factor.
=head2 BH_HashmapSetFactor
void BH_HashmapSetFactor(BH_Hashmap *hashmap,
float factor);
Sets the maximum load factor I<factor>.
The new value of the maximum load factor will be applied on the next call to
L</BH_HashmapInsert> or L</BH_HashmapReserve>.
=head2 BH_HashmapIterAt
void *BH_HashmapIterAt(BH_Hashmap *hashmap,
void *key);
Returns an iterator to the element with the given key I<key>.
If successful, the function returns an iterator or NULL.
=head2 BH_HashmapIterNext
void *BH_HashmapIterNext(BH_Hashmap *hashmap,
void *iter);
Returns an iterator to the next element.
The optional I<iter> parameter takes an iterator to the current element.
If successful, the function returns an iterator or NULL.
=head2 BH_HashmapIterRemove
void BH_HashmapIterRemove(BH_Hashmap *hashmap,
void *iter);
Removes the element by the given iterator I<iter>.
Calling this function invalidates existing iterators.
=head2 BH_HashmapIterKey
void *BH_HashmapIterKey(void *iter);
Returns the key of the element pointed to by the iterator I<iter>.
=head2 BH_HashmapIterValue
void *BH_HashmapIterValue(void *iter);
Returns the value of the element pointed to by the iterator I<iter>.
=head1 SEE ALSO
L<BH>

510
doc/Manual/en/BH_IO.pod Normal file
View File

@@ -0,0 +1,510 @@
=encoding UTF-8
=head1 NAME
BH_IO - I/O subsystem
=head1 SYNOPSIS
#include <BH/io.h>
BH_IO *io = BH_FileNew("input.txt", BH_FILE_WRITE | BH_FILE_TRUNCATE, NULL);
BH_IOWrite(io, "Hello, world!", 13, NULL);
BH_IOFree(io);
cc prog.c -o prog -lbh
=head1 DESCRIPTION
BH_IO provides a subsystem that allows you to work with various objects (files,
sockets, memory) via a single I/O interface. This allows you to write code that
is not tied to a specific input/output system.
It is guaranteed that any BH_IO object supports the following operations:
L</BH_IORead>, L</BH_IOWrite>, L</BH_IOCtl> и L</BH_IOCap>.
Depending on the implementation of a particular BH_IO object, additional
operations may be available: L</BH_IOFlags>, L</BH_IOClear>, L</BH_IOFlush>,
L</BH_IOSize>, L</BH_IOTell>, L</BH_IOSeek>, L</BH_IOPeek> and others.
By default, the I/O subsystem allows you to work with files (L</BH_FileNew>) or
RAM (L</BH_BytesNew>), as well as buffer I/O (L</BH_BufferNew>).
=head1 EXTENSIONS
BH_IO provides the developer with the ability to create custom implementations
of I/O devices. Example:
typedef struct BH_MyIO
{
BH_IO parent;
int flags;
};
static int ioDestroy(BH_MyIO *io)
{
/* Ommitted for the example */
}
static int ioRead(BH_MyIO *io,
BH_IOReadInfo *info)
{
/* Ommitted for the example */
}
static int ioWrite(BH_MyIO *io,
BH_IOWriteInfo *info)
{
/* Ommited for the example */
}
static int ioFlags(BH_MyIO *io,
int *flags)
{
*flags = io->flags;
return BH_OK;
}
static int ioCap(BH_MyIO *io,
int *op)
{
BH_UNUSED(io);
switch (*op)
{
case BH_IO_CTL_FLAGS:
return BH_OK;
default:
return BH_NOIMPL;
}
}
static int ioCtl(BH_MyIO *io,
BH_IOCtlInfo *info)
{
switch (info->op)
{
case BH_IO_CTL_FLAGS:
return ioFlags(io, (int *)info->arg);
default:
return BH_NOIMPL;
}
}
static int ioCallback(BH_MyIO *io,
int type,
void *arg)
{
switch (type)
{
case BH_IO_OP_DESTROY: return ioDestroy(io);
case BH_IO_OP_READ: return ioRead(io, (BH_IOReadInfo *)arg);
case BH_IO_OP_WRITE: return ioWrite(io, (BH_IOWriteInfo *)arg);
case BH_IO_OP_CTL: return ioCtl(io, (BH_IOCtlInfo *)arg);
case BH_IO_OP_CAP: return ioCap(io, (int*)arg);
default: return BH_NOIMPL;
}
}
BH_IO *BH_MyIONew(int *result)
{
BH_MyIO *io;
int code;
code = BH_OOM;
if ((io = malloc(sizeof(*io))))
{
io->parent.callback = (BH_IOCallback)ioCallback;
io->flags = 0;
}
if (result)
*result = code;
return (BH_IO*)io;
}
=head1 API CALLS
=head2 BH_FileNew
BH_IO *BH_FileNew(const char *path,
int mode,
int *result);
Creates an I/O device for working with the file using the I<path>.
The I<mode> parameter can take a combination of the following values:
=over
=item B<BH_FILE_READ>
Opens the file for reading
=item B<BH_FILE_WRTIE>
Opens the file for writing
=item B<BH_FILE_APPEND>
Opens the file in append mode
=item B<BH_FILE_TRUNCATE>
Truncates the file
=item B<BH_FILE_CREATE>
The file must be created
=item B<BH_FILE_EXIST>
The file must exist
=back
The optional parameter I<result> returns 0 or an error code.
This function returns a pointer to a new BH_IO object or NULL.
=head2 BH_BufferNew
BH_IO *BH_BufferNew(BH_IO *device,
size_t size,
int *result);
Creates an I/O device to buffer data to another I<device>.
The I<size> parameter is responsible for the size of the read and write buffers.
The optional parameter I<result> returns 0 or an error code.
If successful, this function returns a pointer to the new BH_IO object or
NULL in case of an error.
=head2 BH_BytesNew
BH_IO *BH_BytesNew(char *data,
size_t size,
int *result);
Creates an I/O device for the memory region I<data> with the size I<size>.
The optional parameter I<result> returns 0 or an error code.
If successful, this function returns a pointer to the new BH_IO object or
NULL in case of an error.
=head2 BH_IOFree
void BH_IOFree(BH_IO *device);
Destroys the I/O device.
=head2 BH_IORead
int BH_IORead(BH_IO *device,
char *buffer,
size_t size,
size_t *actual);
Reads up to I<size> bytes from the I/O device and writes data to
I<buffer>.
The optional parameter I<actual> returns the number of bytes that was read.
If successful, this function returns 0 or an error code.
=head2 BH_IOWrite
int BH_IOWrite(BH_IO *io,
const char *buffer,
size_t size,
size_t *actual);
Writes up to I<size> bytes to the I/O device from I<buffer>.
The optional parameter I<actual> returns the number of bytes that was written.
If successful, this function returns 0 or an error code.
=head2 BH_IOCtl
int BH_IOCtl(BH_IO *device,
int op,
void *arg);
Manipulates the parameters of the I/O device using the I<op> command and
the I<arg> argument.
Possible values of I<op>:
=over
=item B<BH_IO_CTL_FLAGS>
Argument: int *
Return the I/O device flags.
=item B<BH_IO_CTL_CLEAR>
Reset the I/O device errors.
=item B<BH_IO_CTL_PEEK>
Argument: L<BH_IOReadInfo *|/BH_IOReadInfo>
Reads data from an I/O device without extracting it.
=item B<BH_IO_CTL_FLUSH>
Write buffered data to the I/O device.
=item B<BH_IO_CTL_SIZE>
Argument: int64_t *
Get the size of the I/O device.
=item B<BH_IO_CTL_TELL>
Argument: int64_t *
Reads the current offset of the I/O device reader pointer.
=item B<BH_IO_CTL_SEEK>
Argument: L<BH_IOSeekInfo *|/BH_IOSeekInfo>
Changes the current position of the I/O reader pointer.
=item B<BH_IO_CTL_GET_IO>
Argument: L<BH_IO **|/BH_IO>|void *
Gets the device I/O object used in the implementation.
=item B<BH_IO_CTL_SET_IO>
Argument: L<BH_IO *|/BH_IO>|void *
Sets the device I/O object to be used in the implementation.
=back
If successful, this function returns 0 or an error code.
=head2 BH_IOCap
int BH_IOCap(BH_IO *device,
int op);
Checks whether the I<op> command can be executed on the I/O device.
If successful, this function returns 0 or an error code.
=head2 BH_IOFlags
int BH_IOFlags(BH_IO *device,
int *flags);
Returns the current I<flags> flags of the I/O device.
Possible flags (and their combinations):
=over
=item B<BH_IO_FLAG_ERROR>
An error occurred during the execution.
=item B<BH_IO_FLAG_EOF>
The device has reached the end of the file.
=back
If successful, this function returns 0 or an error code.
=head2 BH_IOClear
int BH_IOClear(BH_IO *device);
Cleans the I/O device from errors.
If successful, this function returns 0 or an error code.
=head2 BH_IOPeek
int BH_IOPeek(BH_IO *device,
char *buffer,
size_t size,
size_t *actual);
Reads up to I<size> bytes from the I/O device without extraction and writes
the data to I<buffer>.
The optional parameter I<actual> returns the number of bytes that was actually
read.
If successful, this function returns 0 or an error code.
=head2 BH_IOFlush
int BH_IOFlush(BH_IO *device);
Writes buffered values to the I/O device.
If successful, this function returns 0 or an error code.
=head2 BH_IOSize
int BH_IOSize(BH_IO *device,
int64_t *size);
Reads the current size of the I/O device in bytes and writes the value to
I<size>.
For different types of I/O devices, this value can mean different things (for
example: the current file size, the size of the memory allocated for I/O, etc.).
If successful, this function returns 0 or an error code.
=head2 BH_IOTell
int BH_IOTell(BH_IO *device,
int64_t *offset);
Reads the current offset of the I/O reader pointer relative
to the start and writes the value to I<offset>.
If successful, this function returns 0 or an error code.
=head2 BH_IOSeek
int BH_IOSeek(BH_IO *device,
int64_t offset,
int whence);
Changes the current position of the I/O reader pointer, taking into account
the offset I<offset> and the initial position I<whence>.
Possible values of the initial position I<whence>:
=over
=item B<BH_IO_SEEK_SET>
Offset relative to the beginning of the device.
=item B<BH_IO_SEEK_CUR>
Offset relative to the current position of the device.
=item B<BH_IO_SEEK_END>
Offset relative to the end of the device.
=back
If successful, this function returns 0 or an error code.
=head2 BH_IOError
int BH_IOError(BH_IO *device);
Checks whether the I/O device is in an error state.
This function is equivalent to the following code:
(BH_IOFlags(device) & BH_IO_FLAG_ERROR)
=head2 BH_IOEndOfFile
int BH_IOEndOfFile(BH_IO *device);
Checks whether the I/O device has reached the end.
This function is equivalent to the following code:
(BH_IOFlags(device) & BH_IO_FLAG_EOF)
=head1 STRUCTURES
=head2 BH_IO
typedef struct BH_IO
{
BH_IOCallback callback;
} BH_IO;
=head2 BH_IOReadInfo
typedef struct BH_IOReadInfo
{
char *data;
size_t size;
size_t *actual;
} BH_IOReadInfo;
=head2 BH_IOWriteInfo
typedef struct BH_IOWriteInfo
{
const char *data;
size_t size;
size_t *actual;
} BH_IOWriteInfo;
=head2 BH_IOCtlInfo
typedef struct BH_IOCtlInfo
{
int op;
void *arg;
} BH_IOCtlInfo;
=head2 BH_IOSeekInfo
typedef struct BH_IOSeekInfo
{
int64_t offset;
int whence;
} BH_IOSeekInfo;
=head1 SEE ALSO
L<BH>

62
doc/Manual/en/BH_Line.pod Normal file
View File

@@ -0,0 +1,62 @@
=encoding UTF-8
=head1 NAME
BH_Line - a straight line on a plane.
=head1 SYNTAX
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Line module provides functions for working with straight lines on a
plane. It allows you to calculate the coefficients of a line based on two
points, find the distance from a point to a line, and determine the closest
point on the line to a given point.
=head1 API CALLS
=head2 BH_LineFromPoints
int BH_LineFromPoints(const float a[2],
const float b[2],
float out[3]);
Calculates the coefficients of a line on a plane based on two points I<a> and
I<b>.
The I<out> parameter describes the resulting line on the plane.
If successful, the function returns 0, otherwise it returns an error code.
=head2 BH_LineDistance
float BH_LineDistance(const float line[3],
const float point[2]);
Calculates the distance from the point I<point> to the line I<line>.
=head2 BH_LineClosestPoint
void BH_LineClosestPoint(const float line[3],
const float point[2],
float out[2]);
Calculates the closest point on the line I<line> to another point I<point>.
The I<out> parameter describes the resulting point.
=head1 SEE ALSO
L<BH>

168
doc/Manual/en/BH_Mat3f.pod Normal file
View File

@@ -0,0 +1,168 @@
=encoding UTF-8
=head1 NAME
BH_Mat3f - a real 3x3 matrix
=head1 SYNTAX
#include <BH/Math/Mat3f.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Mat3f module provides a set of functions for working with real 3x3
matrices.
=head1 API CALLS
=head2 BH_Mat3fIdentity
void BH_Mat3fIdentity(float out[9]);
Writes an identity matrix to I<out>.
=head2 BH_Mat3fAdd
void BH_Mat3fAdd(const float a[9],
const float b[9],
float out[9]);
Calculates the sum of two matrices I<a> and I<b>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat3fSub
void BH_Mat3fSub(const float a[9],
const float b[9],
float out[9]);
Calculates the difference between two matrices I<a> and I<b>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat3fMul
void BH_Mat3fMul(const float a[9],
const float b[9],
float out[9]);
Calculates the result of multiplying two matrices I<a> and I<b>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat3fScale
void BH_Mat3fScale(const float a[9],
float b,
float out[9]);
Calculates the result of multiplying matrix I<a> by value I<b>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat3fTranspose
void BH_Mat3fTranspose(const float in[9],
float out[9]);
Transposes matrix I<in>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat3fTrace
float BH_Mat3fTrace(const float in[9]);
Calculates the sum of the elements of the main diagonal of matrix I<in>.
=head2 BH_Mat3fDet
float BH_Mat3fDet(const float in[9]);
Calculates the determinant of matrix I<in>.
=head2 BH_Mat3fInverse
int BH_Mat3fInverse(const float in[9],
float out[9]);
Calculates the inverse matrix for I<in>.
The I<out> parameter describes the resulting matrix.
If successful, the function returns 0, otherwise it returns an error code.
=head2 BH_Mat3fFromScale
void BH_Mat3fFromScale(float x,
float y,
float out[9]);
Calculates a scaling matrix with scales I<x> and I<y>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat3fFromTranslation
void BH_Mat3fFromTranslation(float x,
float y,
float out[9]);
Calculates a translation matrix with values I<x> and I<y>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat3fFromRotation
void BH_Mat3fFromRotation(float angle,
float out[9]);
Calculates a rotation matrix with a given I<angle>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat3fApplyVec3f
void BH_Mat3fApplyVec3f(float a[9],
float b[3],
float out[3]);
Calculates the result of multiplying matrix I<a> by vector I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Mat3fApplyVec2f
void BH_Mat3fApplyVec2f(float a[9],
float b[2],
float out[2]);
Calculates the result of multiplying matrix I<a> by vector I<b>.
The I<out> parameter describes the resulting vector.
=head1 SEE ALSO
L<BH>

286
doc/Manual/en/BH_Mat4f.pod Normal file
View File

@@ -0,0 +1,286 @@
=encoding UTF-8
=head1 NAME
BH_Mat4f - real 4x4 matrix
=head1 SYNTAX
#include <BH/Math/Mat4f.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Mat4f module provides a set of functions for working with real 4x4
matrices. These functions allow you to perform various operations on matrices,
such as addition, subtraction, multiplication, transposition, determinant
calculation, and others.
=head1 API CALLS
=head2 BH_Mat4fIdentity
void BH_Mat4fIdentity(float out[16]);
Writes an identity matrix to I<out>.
=head2 BH_Mat4fAdd
void BH_Mat4fAdd(const float a[16],
const float b[16],
float out[16]);
Calculates the sum of two matrices I<a> and I<b>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fSub
void BH_Mat4fSub(const float a[16],
const float b[16],
float out[16]);
Calculates the difference between two matrices I<a> and I<b>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fMul
void BH_Mat4fMul(const float a[16],
const float b[16],
float out[16]);
Calculates the result of multiplying two matrices I<a> and I<b>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fScale
void BH_Mat4fScale(const float a[16],
float b,
float out[16]);
Calculates the result of multiplying matrix I<a> by value I<b>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fTranspose
void BH_Mat4fTranspose(const float in[16],
float out[16]);
Transposes matrix I<in>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fTrace
float BH_Mat4fTrace(const float in[16]);
Calculates the sum of the elements of the main diagonal of matrix I<in>.
=head2 BH_Mat4fDet
float BH_Mat4fDet(const float in[16]);
Calculates the determinant of matrix I<in>.
=head2 BH_Mat4fInverse
int BH_Mat4fInverse(const float in[16],
float out[16]);
Calculates the inverse matrix for I<in>.
The I<out> parameter describes the resulting matrix.
If successful, the function returns 0, otherwise it returns an error code.
=head2 BH_Mat4fFromScale
void BH_Mat4fFromScale(float x,
float y,
float z,
float out[16]);
Calculates a scaling matrix with scales I<x>, I<y>, and I<z>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fFromTranslation
void BH_Mat4fFromTranslation(float x,
float y,
float z,
float out[16]);
Calculates a translation matrix with values I<x>, I<y>, and I<z>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fFromRotationX
void BH_Mat4fFromRotationX(float angle,
float out[16]);
Calculates a rotation matrix around the X axis with a given I<angle>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fFromRotationY
void BH_Mat4fFromRotationY(float angle,
float out[16]);
Calculates a rotation matrix around the Y axis with a given I<angle>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fFromRotationZ
void BH_Mat4fFromRotationZ(float angle,
float out[16]);
Calculates a rotation matrix around the Z axis with a given I<angle>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fFromAxis
void BH_Mat4fFromAxis(const float axis[3],
float angle,
float out[16]);
Calculates a rotation matrix around the axis I<axis> with a given I<angle>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fFromEuler
void BH_Mat4fFromEuler(float roll,
float pitch,
float yaw,
float out[16]);
Calculates a rotation matrix from the angles of the associated coordinate system
I<roll>, I<pitch>, and I<yaw>.
The order of rotation application is ZYX (yaw, pitch, roll).
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fFromQuat4f
void BH_Mat4fFromQuat4f(const float in[4],
float out[16]);
Calculates a rotation matrix from quaternion I<in>.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fFromOrtho
void BH_Mat4fFromOrtho(float xMin,
float xMax,
float yMin,
float yMax,
float zMin,
float zMax,
float out[16]);
Calculates an orthographic projection matrix.
The I<xMin> and I<xMax> parameters define the valid range of X coordinates.
The I<yMin> and I<yMax> parameters define the valid range of Y coordinates.
The I<zMin> and I<zMax> parameters define the valid range of Z coordinates.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fFromFrustum
void BH_Mat4fFromFrustum(float fov,
float aspect,
float zMin,
float zMax,
float out[16]);
Calculates a perspective projection matrix.
The I<fov> parameter defines the field of view.
The I<aspect> parameter defines the aspect ratio.
The I<zMin> and I<zMax> parameters define the valid range of Z coordinates.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fFromLookAt
void BH_Mat4fFromLookAt(const float position[3],
const float at[3],
const float up[3],
float out[16]);
Calculates the camera view matrix.
The I<position> parameter defines the position of the camera in space.
The I<at> parameter defines the point where the camera is aimed.
The I<up> parameter defines the "up" direction of the camera.
The I<out> parameter describes the resulting matrix.
=head2 BH_Mat4fApplyVec4f
void BH_Mat4fApplyVec4f(const float a[16],
const float b[4],
float out[4]);
Calculates the result of multiplying matrix I<a> by vector I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Mat4fApplyVec3f
void BH_Mat4fApplyVec3f(const float a[16],
const float b[3],
float out[3]);
Calculates the result of multiplying matrix I<a> by vector I<b>.
The I<out> parameter describes the resulting vector.
=head1 SEE ALSO
L<BH>

50
doc/Manual/en/BH_Math.pod Normal file
View File

@@ -0,0 +1,50 @@
=encoding UTF-8
=head1 NAME
BH_Math - Mathematical functions
=head1 SYNTAX
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Math library provides a set of mathematical functions for various
calculations.
=head1 API CALLS
=head2 BH_Lerpf
float BH_Lerpf(float a,
float b,
float t);
Interpolates the value between I<a> and I<b> with a given coefficient I<t>.
=head2 BH_Triangle3fBarycentric
void BH_Triangle3fBarycentric(const float a[3],
const float b[3],
const float c[3],
const float point[3],
float out[3]);
Calculates the barycentric coordinates of the I<point> relative to the
triangle defined by points I<a>, I<b>, I<c>.
The I<out> parameter describes the resulting vector.
=head1 SEE ALSO
L<BH>

View File

@@ -0,0 +1,66 @@
=encoding UTF-8
=head1 NAME
BH_Plane - Plane in space
=head1 SYNTAX
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Plane module provides functions for working with planes in
three-dimensional space. It allows you to calculate the coefficients of a plane
from three points, determine the distance from a point to a plane, and find the
closest point on the plane to a given point.
=head1 API CALLS
=head2 BH_PlaneFromPoints
int BH_PlaneFromPoints(const float a[3],
const float b[3],
const float c[3],
float out[4]);
Calculates the coefficients of a plane from three points I<a>, I<b>, I<c>.
It is assumed that the points are arranged in a clockwise order.
If the points form a degenerate triangle, the function will return an error.
The I<out> parameter defines the resulting plane.
If successful, the function returns 0, otherwise it returns an error code.
=head2 BH_PlaneDistance
float BH_PlaneDistance(const float plane[4],
const float point[3]);
Calculates the distance from the I<point> to the I<plane>.
=head2 BH_PlaneClosestPoint
void BH_PlaneClosestPoint(const float plane[4],
const float point[3],
float out[3]);
Calculates the closest point on the I<plane> to another I<point>.
The I<out> parameter describes the resulting point.
=head1 SEE ALSO
L<BH>

219
doc/Manual/en/BH_Quat.pod Normal file
View File

@@ -0,0 +1,219 @@
=encoding UTF-8
=head1 NAME
BH_Quat - Quaternion
=head1 SYNTAX
#include <BH/Math/Quat.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
This module provides a set of functions for working with quaternions.
Quaternions are used to represent rotations in three-dimensional space and have
advantages over other methods, such as rotation matrices or Euler angles, in
terms of stability against error accumulation during multiple rotation
operations.
=head1 API CALLS
=head2 BH_Quat4fAdd
#define BH_Quat4fAdd(a, b, out) \
BH_Vec4fAdd(a, b, out)
Calculates the sum of two quaternions I<a> and I<b>.
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fSub
#define BH_Quat4fSub(a, b, out) \
BH_Vec4fSub(a, b, out)
Calculates the difference between two quaternions I<a> and I<b>.
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fScale
#define BH_Quat4fScale(a, b, out) \
BH_Vec4fScale(a, b, out)
Calculates the result of multiplying quaternion I<a> by value I<b>.
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fNegate
#define BH_Quat4fNegate(in, out) \
BH_Vec4fNegate(in, out)
Calculates the opposite quaternion from quaternion I<in>.
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fDot
#define BH_Quat4fDot(a, b) \
BH_Vec4fDot(a, b)
Calculates the dot product of quaternions I<a> and I<b>.
=head2 BH_Quat4fLength
#define BH_Quat4fLength(in) \
BH_Vec4fLength(in)
float BH_Vec4fLength(const float in[4]);
Calculates the length of quaternion I<in>.
=head2 BH_Quat4fNormal
#define BH_Quat4fNormal(in, out) \
BH_Vec4fNormal(in, out)
Calculates the normalized form of quaternion I<in>.
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fLerp
#define BH_Quat4fLerp(a, b, t, out) \
BH_Vec4fLerp(a, b, t, out)
Performs linear interpolation between two quaternions I<a> and I<b> with
parameter I<t>.
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fIdentity
void BH_Quat4fIdentity(float out[4]);
Writes the identity quaternion to I<out>.
=head2 BH_Quat4fConjugate
void BH_Quat4fConjugate(const float in[4],
float out[4]);
Calculates the conjugate quaternion from I<in>.
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fInverse
void BH_Quat4fInverse(const float in[4],
float out[4]);
Calculates the inverse quaternion from I<in>.
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fMul
void BH_Quat4fMul(const float a[4],
const float b[4],
float out[4]);
Calculates the result of multiplying two quaternions I<a> and I<b>.
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fSlerp
void BH_Quat4fSlerp(const float a[4],
const float b[4],
float t,
float out[4]);
Performs spherical linear interpolation between two quaternions I<a> and I<b>
with parameter I<t>.
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fFromEuler
void BH_Quat4fFromEuler(float roll,
float pitch,
float yaw,
float out[4]);
Calculates the quaternion from the angles of the associated coordinate system
I<roll>, I<pitch>, and I<yaw>.
The order of rotation application is ZYX (yaw, pitch, roll).
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fFromAxis
void BH_Quat4fFromAxis(const float axis[3],
float angle,
float out[4]);
Calculates the quaternion from rotation around the I<axis> with the given
I<angle>.
The parameter I<out> describes the resulting quaternion.
=head2 BH_Quat4fToEuler
void BH_Quat4fToEuler(const float in[4],
float *roll,
float *pitch,
float *yaw);
Calculates the angles of the associated coordinate system I<roll>, I<pitch>,
and I<yaw> from quaternion I<in>.
The order of rotation application is ZYX (yaw, pitch, roll).
=head2 BH_Quat4fToAxis
void BH_Quat4fToAxis(const float in[4],
float axis[3],
float *angle);
Calculates the rotation I<axis> and I<angle> from quaternion I<in>.
=head2 BH_Quat4fToMat4f
void BH_Quat4fToMat4f(const float in[4],
float out[16]);
Calculates the rotation matrix from quaternion I<in>.
The parameter I<out> describes the resulting matrix.
=head1 SEE ALSO
L<BH>

138
doc/Manual/en/BH_Queue.pod Normal file
View File

@@ -0,0 +1,138 @@
=encoding UTF-8
=head1 NAME
BH_Queue - queue container
=head1 SYNTAX
#include <BH/Queue.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Queue module provides an implementation of a queue container that allows
adding elements to the end and removing them from the beginning. The queue is
based on a dynamic array, which ensures efficient memory usage and fast access
to elements.
=head1 API CALLS
=head2 BH_QueueNew
BH_Queue *BH_QueueNew(void);
Creates a queue.
If successful, the function returns a pointer to a new BH_Queue object, or NULL
in case of an error.
=head2 BH_QueueFree
void BH_QueueFree(BH_Queue *queue);
Destroys the queue.
=head2 BH_QueueClear
void BH_QueueClear(BH_Queue *queue);
Clears the queue.
=head2 BH_QueueReserve
int BH_QueueReserve(BH_Queue *queue,
size_t size);
Reserves space for at least I<size> elements.
Calling this function invalidates existing iterators.
If successful, the function returns 0; otherwise, it returns an error code.
=head2 BH_QueueInsert
int BH_QueueInsert(BH_Queue *queue,
void *value);
Inserts an element I<value>.
Calling this function invalidates existing iterators.
If successful, the function returns 0; otherwise, it returns an error code.
=head2 BH_QueueRemove
void BH_QueueRemove(BH_Queue *queue);
Removes the first element from the queue.
Calling this function invalidates existing iterators.
=head2 BH_QueueFront
int BH_QueueFront(BH_Queue *queue,
void **value);
Returns the first element of the queue.
The I<value> parameter returns the value of the element.
If successful, the function returns 0; otherwise, it returns an error code.
=head2 BH_QueueEmpty
int BH_QueueEmpty(BH_Queue *queue);
Checks if the queue is empty.
=head2 BH_QueueSize
size_t BH_QueueSize(BH_Queue *queue);
Returns the number of elements.
=head2 BH_QueueCapacity
size_t BH_QueueCapacity(BH_Queue *queue);
Returns the capacity.
=head2 BH_QueueIterNext
void *BH_QueueIterNext(BH_Queue *queue,
void *iter);
Returns an iterator to the next element.
The optional I<iter> parameter accepts an iterator to the current element.
If successful, the function returns an iterator or NULL.
=head2 BH_QueueIterValue
void *BH_QueueIterValue(void *iter);
Returns the value of the element pointed to by the iterator.
=head1 SEE ALSO
L<BH>

205
doc/Manual/en/BH_Ray2f.pod Normal file
View File

@@ -0,0 +1,205 @@
=encoding UTF-8
=head1 NAME
BH_Ray2f, BH_Segment2f - Ray/segment on a plane
=head1 SYNTAX
#include <BH/Math/Ray2f.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
This module provides functions for working with rays and segments on a plane.
It includes functions for checking intersections between rays, segments, lines,
and bounding rectangles.
=head1 API CALLS
=head2 BH_Ray2fIntersectLine
int BH_Ray2fIntersectLine(const float start[2],
const float direction[2],
const float line[3],
float *t,
float out[2]);
Checks the intersection between a ray and a line.
The parameters I<start> and I<direction> describe the ray.
The parameter I<line> describes the line.
The parameter I<t> describes the resulting time of the ray's intersection.
The parameter I<out> describes the resulting intersection point.
If successful, the function returns 0, otherwise it returns an error code.
=head2 BH_Ray2fIntersectTime
int BH_Ray2fIntersectTime(const float aStart[2],
const float aDirection[2],
const float bStart[2],
const float bDirection[2],
float *time1,
float *time2);
Calculates the intersection time between two rays.
The parameters I<aStart> and I<aDirection> describe the first ray.
The parameters I<bStart> and I<bDirection> describe the second ray.
The parameter I<time1> describes the resulting intersection time of the first
ray.
The parameter I<time2> describes the resulting intersection time of the second
ray.
If successful, the function returns 0, otherwise it returns an error code.
=head2 BH_Ray2fIntersectRay
int BH_Ray2fIntersectRay(const float aStart[2],
const float aDirection[2],
const float bStart[2],
const float bDirection[2],
float *t,
float out[2]);
Checks the intersection between two rays.
The parameters I<aStart> and I<aDirection> describe the first ray.
The parameters I<bStart> and I<bDirection> describe the second ray.
The parameter I<t> describes the resulting intersection time of the first ray.
The parameter I<out> describes the resulting intersection point.
If successful, the function returns 0, otherwise it returns an error code.
=head2 BH_Ray2fIntersectSegment
int BH_Ray2fIntersectSegment(const float aStart[2],
const float aDirection[2],
const float bStart[2],
const float bEnd[2],
float *t,
float out[2]);
Checks the intersection between a ray and a segment.
The parameters I<aStart> and I<aDirection> describe the ray.
The parameters I<bStart> and I<bEnd> describe the segment.
The parameter I<t> describes the resulting intersection time of the ray.
The parameter I<out> describes the resulting intersection point.
If successful, the function returns 0, otherwise it returns an error code.
=head2 BH_Segment2fIntersectLine
int BH_Segment2fIntersectLine(const float start[2],
const float end[2],
const float line[3],
float *t,
float out[2]);
Checks the intersection between a segment and a line.
The parameters I<start> and I<end> describe the segment.
The parameter I<line> describes the line.
The parameter I<t> describes the resulting intersection time of the segment.
The parameter I<out> describes the resulting intersection point.
If successful, the function returns 0, otherwise it returns an error code.
=head2 BH_Segment2fIntersectSegment
int BH_Segment2fIntersectSegment(const float aStart[2],
const float aEnd[2],
const float bStart[2],
const float bEnd[2],
float *t,
float out[2]);
Checks the intersection between two segments.
The parameters I<aStart> and I<aEnd> describe the first segment.
The parameters I<bStart> and I<bEnd> describe the second segment.
The parameter I<t> describes the resulting intersection time of the first
segment.
The parameter I<out> describes the resulting intersection point.
If successful, the function returns 0, otherwise it returns an error code.
=head2 BH_Ray2fIntersectBox2f
int BH_Ray2fIntersectBox2f(const float aStart[2],
const float aDirection[2],
const float bMin[2],
const float bMax[2],
float *t,
float out[2]);
Checks the intersection between a ray and a bounding box.
The parameters I<aStart> and I<aDirection> describe the ray.
The parameters I<bMin> and I<bMax> describe the bounding box.
The parameter I<t> describes the resulting intersection time of the ray.
The parameter I<out> describes the resulting intersection point.
If successful, the function returns 0, otherwise it returns an error code.
=head2 BH_Segment2fIntersectBox2f
int BH_Segment2fIntersectBox2f(const float aStart[2],
const float aEnd[2],
const float bMin[2],
const float bMax[2],
float *t,
float out[2]);
Checks the intersection between a segment and a bounding box.
The parameters I<aStart> and I<aEnd> describe the segment.
The parameters I<bMin> and I<bMax> describe the bounding box.
The parameter I<t> describes the resulting intersection time of the segment.
The parameter I<out> describes the resulting intersection point.
If successful, the function returns 0, otherwise it returns an error code.
=head1 SEE ALSO
L<BH>

162
doc/Manual/en/BH_Ray3f.pod Normal file
View File

@@ -0,0 +1,162 @@
=encoding UTF-8
=head1 NAME
BH_Ray3f, BH_Segment3f - ray/segment in space
=head1 SYNTAX
#include <BH/Math/Ray3f.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
This module provides functions for working with rays and segments in
three-dimensional space. It includes methods for checking intersections of rays
and segments with planes, triangles, and bounding boxes.
=head1 API CALLS
=head2 BH_Ray3fIntersectPlane
int BH_Ray3fIntersectPlane(const float start[3],
const float direction[3],
const float plane[4],
float *t,
float out[3]);
Checks the intersection between a ray and a plane.
The parameters I<start> and I<direction> describe the ray.
The parameter I<plane> describes the plane.
The parameter I<t> describes the resulting time of the ray's intersection.
The parameter I<out> describes the resulting point of intersection.
In case of success, the function returns 0, in case of an error - an error code.
=head2 BH_Ray3fIntersectTriangle
int BH_Ray3fIntersectTriangle(const float start[3],
const float direction[3],
const float a[3],
const float b[3],
const float c[3],
float *t,
float out[3]);
Checks the intersection between a ray and a triangle.
The parameters I<start> and I<direction> describe the ray.
The parameters I<a>, I<b>, I<c> describe the points of the triangle.
The parameter I<t> describes the resulting time of the ray's intersection.
The parameter I<out> describes the resulting point of intersection.
In case of success, the function returns 0, in case of an error - an error code.
=head2 BH_Segment3fIntersectPlane
int BH_Segment3fIntersectPlane(const float start[3],
const float end[3],
const float plane[4],
float *t,
float out[3]);
Checks the intersection between a segment and a plane.
The parameters I<start> and I<end> describe the segment.
The parameter I<plane> describes the plane.
The parameter I<t> describes the resulting time of the segment's intersection.
The parameter I<out> describes the resulting point of intersection.
In case of success, the function returns 0, in case of an error - an error code.
=head2 BH_Segment3fIntersectTriangle
int BH_Segment3fIntersectTriangle(const float start[3],
const float end[3],
const float a[3],
const float b[3],
const float c[3],
float *t,
float out[3]);
Checks the intersection between a segment and a triangle.
The parameters I<start> and I<end> describe the segment.
The parameters I<a>, I<b>, I<c> describe the points of the triangle.
The parameter I<t> describes the resulting time of the ray's intersection.
The parameter I<out> describes the resulting point of intersection.
In case of success, the function returns 0, in case of an error - an error code.
=head2 BH_Ray3fIntersectBox3f
int BH_Ray3fIntersectBox3f(const float aStart[3],
const float aDirection[3],
const float bMin[3],
const float bMax[3],
float *t,
float out[3]);
Checks the intersection between a ray and a bounding box.
The parameters I<aStart> and I<aDirection> describe the ray.
The parameters I<bMin> and I<bMax> describe the bounding box.
The parameter I<t> describes the resulting time of the first segment's
intersection.
The parameter I<out> describes the resulting point of intersection.
In case of success, the function returns 0, in case of an error - an error code.
=head2 BH_Segment3fIntersectBox3f
int BH_Segment3fIntersectBox3f(const float aStart[3],
const float aEnd[3],
const float bMin[3],
const float bMax[3],
float *t,
float out[3]);
Checks the intersection between a segment and a bounding box.
The parameters I<aStart> and I<aEnd> describe the segment.
The parameters I<bMin> and I<bMax> describe the bounding box.
The parameter I<t> describes the resulting time of the first segment's
intersection.
The parameter I<out> describes the resulting point of intersection.
In case of success, the function returns 0, in case of an error - an error code.
=head1 SEE ALSO
L<BH>

382
doc/Manual/en/BH_String.pod Normal file
View File

@@ -0,0 +1,382 @@
=encoding UTF-8
=head1 NAME
BH_String - Working with strings
=head1 SYNTAX
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_String library provides a set of functions for working with strings,
including converting numbers to strings and back.
=head1 DEFINING THE BASE
The functions of the I<StringToInt> family have an algorithm for determining the
base of a number by string prefixes:
=over
=item *
If the prefix I<0b>, then base 2
=item *
If the prefix I<0>, then base 8
=item *
If the prefix I<0x>, then base 16
=item *
Otherwise, base 10.
=back
=head1 API CALLS
=head2 BH_StringFromDouble
int BH_StringFromDouble(char *string,
size_t size,
double value,
char format,
int precision,
size_t *actual);
Formats a real number I<value> into a null-terminated string I<string>
(with a length limit of I<size>).
The I<format> parameter specifies the format for converting a number to a
string. Acceptable formats:
=over
=item B<f>, B<F>
Fixed format: [-]ddd.ddd
=item B<e>, B<E>
Scientific format: [-]d.dddedd
=item B<g>, B<G>
Fixed or scientific format, depending on which one is shorter.
=back
The I<precision> parameter sets the precision of converting a number to a
string. If the accuracy value is negative, the conversion will be performed with
the minimum required accuracy so that the reverse conversion results in the
original number.
The optional parameter I<actual> returns the length of the recorded string.
This function follows the IEEE 754 rule of rounding to an even number.
If successful, it returns 0 or an error code.
=head2 BH_StringFromInt8s
int BH_StringFromInt8s(char *string,
size_t size,
int8_t value,
int base,
size_t *actual);
Formats an 8-bit signed integer I<value> into a null-terminated string
I<string> (with a length limit of I<size>).
The I<base> parameter sets the base for the conversion.
The optional parameter I<actual> returns the length of the recorded string.
If successful, it returns 0 or an error code.
=head2 BH_StringFromInt16s
int BH_StringFromInt16s(char *string,
size_t size,
int16_t value,
int base,
size_t *actual);
Formats a 16-bit signed integer I<value> into a null-terminated string I<string>
(with a length limit of I<size>).
The I<base> parameter sets the base for the conversion.
The optional parameter I<actual> returns the length of the recorded string.
If successful, it returns 0 or an error code.
=head2 BH_StringFromInt32s
int BH_StringFromInt32s(char *string,
size_t size,
int32_t value,
int base,
size_t *actual);
Formats a 32-bit signed integer I<value> into a null-terminated string I<string>
(with a length limit of I<size>).
The I<base> parameter sets the base for the conversion.
The optional parameter I<actual> returns the length of the recorded string.
If successful, it returns 0 or an error code.
=head2 BH_StringFromInt64s
int BH_StringFromInt64s(char *string,
size_t size,
int64_t value,
int base,
size_t *actual);
Formats a 64-bit signed integer I<value> into a null-terminated string I<string>
(with a length limit of I<size>).
The I<base> parameter sets the base for the conversion.
The optional parameter I<actual> returns the length of the recorded string.
If successful, it returns 0 or an error code.
=head2 BH_StringFromInt8u
int BH_StringFromInt8u(char *string,
size_t size,
uint8_t value,
int base,
size_t *actual);
Formats an 8-bit unsigned integer I<value> into a null-terminated string
I<string> (with a length limit of I<size>).
The I<base> parameter sets the base for the conversion.
The optional parameter I<actual> returns the length of the recorded string.
If successful, it returns 0 or an error code.
=head2 BH_StringFromInt16u
int BH_StringFromInt16u(char *string,
size_t size,
uint16_t value,
int base,
size_t *actual);
Formats a 16-bit unsigned integer I<value> into a null-terminated string
I<string> (with a length limit of I<size>).
The I<base> parameter sets the base for the conversion.
The optional parameter I<actual> returns the length of the recorded string.
If successful, it returns 0 or an error code.
=head2 BH_StringFromInt32u
int BH_StringFromInt32u(char *string,
size_t size,
uint32_t value,
int base,
size_t *actual);
Formats a 32-bit unsigned integer I<value> into a null-terminated string
I<string> (with a length limit of I<size>).
The I<base> parameter sets the base for the conversion.
The optional parameter I<actual> returns the length of the recorded string.
If successful, it returns 0 or an error code.
=head2 BH_StringFromInt64u
int BH_StringFromInt64u(char *string,
size_t size,
uint64_t value,
int base,
size_t *actual);
Formats a 64-bit unsigned integer I<value> into a null-terminated string
I<string> (with a length limit of I<size>).
The I<base> parameter sets the base for the conversion.
The optional parameter I<actual> returns the length of the recorded string.
If successful, it returns 0 or an error code.
=head2 BH_StringToDouble
double BH_StringToDouble(const char *string,
size_t *size);
Converts the string I<string> to a real number.
The optional parameter I<size> returns the number of characters read from the
string.
If successful, it returns the converted number or 0.
=head2 BH_StringToInt8s
int8_t BH_StringToInt8s(const char *string,
size_t *size,
int base);
Converts the string I<string> to an 8-bit signed integer.
The optional parameter I<size> returns the number of characters read from the
string.
The optional parameter I<base> specifies the base of the number.
If successful, it returns the converted number or 0.
=head2 BH_StringToInt16s
int16_t BH_StringToInt16s(const char *string,
size_t *size,
int base);
Converts the string I<string> to a signed 16-bit integer.
The optional parameter I<size> returns the number of characters read from the
string.
The optional parameter I<base> specifies the base of the number.
If successful, it returns the converted number or 0.
=head2 BH_StringToInt32s
int32_t BH_StringToInt32s(const char *string,
size_t *size,
int base);
Converts the string I<string> to a signed 32-bit integer.
The optional parameter I<size> returns the number of characters read from the
string.
The optional parameter I<base> specifies the base of the number.
If successful, it returns the converted number or 0.
=head2 BH_StringToInt64s
int64_t BH_StringToInt64s(const char *string,
size_t *size,
int base);
Converts the string I<string> to a signed 64-bit integer.
The optional parameter I<size> returns the number of characters read from the
string.
The optional parameter I<base> specifies the base of the number.
If successful, it returns the converted number or 0.
=head2 BH_StringToInt8u
uint8_t BH_StringToInt8u(const char *string,
size_t *size,
int base);
Converts the string I<string> to an unsigned 8-bit integer.
The optional parameter I<size> returns the number of characters read from the
string.
The optional parameter I<base> specifies the base of the number.
If successful, it returns the converted number or 0.
=head2 BH_StringToInt16u
uint16_t BH_StringToInt16u(const char *string,
size_t *size,
int base);
Converts the string I<string> to an unsigned 16-bit integer.
The optional parameter I<size> returns the number of characters read from the
string.
The optional parameter I<base> specifies the base of the number.
If successful, it returns the converted number or 0.
=head2 BH_StringToInt32u
uint32_t BH_StringToInt32u(const char *string,
size_t *size,
int base);
Converts the string I<string> to an unsigned 32-bit integer.
The optional parameter I<size> returns the number of characters read from the
string.
The optional parameter I<base> specifies the base of the number.
If successful, it returns the converted number or 0.
=head2 BH_StringToInt64u
uint64_t BH_StringToInt64u(const char *string,
size_t *size,
int base);
Converts the string I<string> to an unsigned 64-bit integer.
The optional parameter I<size> returns the number of characters read from the
string.
The optional parameter I<base> specifies the base of the number.
If successful, it returns the converted number or 0.
=head1 SEE ALSO
L<BH>

289
doc/Manual/en/BH_Thread.pod Normal file
View File

@@ -0,0 +1,289 @@
=encoding UTF-8
=head1 NAME
BH_Thread - multithreading and synchronization primitives
=head1 SYNTAX
#include <BH/Thread.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Thread library provides a set of functions for working with
multithreading and thread synchronization. It includes functions for creating
and managing threads, working with mutexes, semaphores, condition variables, and
spinlocks.
=head1 API CALLS
=head2 BH_ThreadNew
BH_Thread *BH_ThreadNew(size_t stack,
BH_ThreadCallback callback,
void *data);
Creates a thread with a specified stack size I<stack>, execution function
I<callback>, and data I<data>.
Returns a pointer to the thread object on success, otherwise NULL.
=head2 BH_ThreadJoin
int BH_ThreadJoin(BH_Thread *thread);
Blocks the execution of the current thread until another thread completes.
Upon completion of the thread, the resources of the I<thread> are freed.
Returns 0 on success, otherwise an error code.
=head2 BH_ThreadDetach
int BH_ThreadDetach(BH_Thread *thread);
Detaches the thread from the current process.
Upon completion of the thread, the resources of the I<thread> are freed.
Returns 0 on success, otherwise an error code.
=head2 BH_MutexNew
BH_Mutex *BH_MutexNew(void);
Creates a mutex.
Returns a pointer to the mutex object on success, otherwise NULL.
=head2 BH_MutexFree
void BH_MutexFree(BH_Mutex *mutex);
Destroys the mutex.
If the mutex is locked, the behavior is undefined.
=head2 BH_MutexLock
int BH_MutexLock(BH_Mutex *mutex);
Locks the mutex.
If the mutex is already locked, the behavior is undefined.
Returns 0 on success, otherwise an error code.
=head2 BH_MutexUnlock
int BH_MutexUnlock(BH_Mutex *mutex);
Unlocks the mutex.
If the mutex is locked by another thread, the behavior is undefined.
Returns 0 on success, otherwise an error code.
=head2 BH_MutexLockTry
int BH_MutexLockTry(BH_Mutex *mutex);
Attempts to lock the mutex.
Returns 0 on success, otherwise an error code.
=head2 BH_SemaphoreNew
BH_Semaphore *BH_SemaphoreNew(int value);
Creates a semaphore with a specified initial value I<value>.
Returns a pointer to the semaphore object on success, otherwise NULL.
=head2 BH_SemaphoreFree
void BH_SemaphoreFree(BH_Semaphore *semaphore);
Destroys the semaphore.
=head2 BH_SemaphorePost
int BH_SemaphorePost(BH_Semaphore *semaphore);
Increases the semaphore value by 1.
Returns 0 on success, otherwise an error code.
=head2 BH_SemaphoreWait
int BH_SemaphoreWait(BH_Semaphore *semaphore);
Decreases the semaphore value by 1.
If the semaphore value is 0, blocks the execution of the current thread until
the semaphore value becomes greater than 0.
Returns 0 on success, otherwise an error code.
=head2 BH_SemaphoreWaitTry
int BH_SemaphoreWaitTry(BH_Semaphore *semaphore);
Attempts to decrease the semaphore value by 1.
Returns 0 on success, otherwise an error code.
=head2 BH_SemaphoreWaitFor
int BH_SemaphoreWaitFor(BH_Semaphore *semaphore,
uint32_t timeout);
Attempts to decrease the semaphore value by 1 within a specified time
I<timeout>.
The I<timeout> parameter specifies the waiting time in milliseconds.
Returns 0 on success, otherwise an error code.
=head2 BH_ConditionNew
BH_Condition *BH_ConditionNew(void);
Creates a new condition variable.
Returns a pointer to the condition variable object on success, otherwise NULL.
=head2 BH_ConditionFree
void BH_ConditionFree(BH_Condition *condition);
Destroys the condition variable.
If the condition variable is used by other threads, the behavior is undefined.
=head2 BH_ConditionWait
int BH_ConditionWait(BH_Condition *condition,
BH_Mutex *mutex);
Blocks the execution of the current thread until another thread signals
a change in the condition.
In some situations, the signal of a condition change may be false.
The I<mutex> parameter specifies the mutex used in conjunction with the
condition variable.
Returns 0 on success, otherwise an error code.
=head2 BH_ConditionWaitFor
int BH_ConditionWaitFor(BH_Condition *condition,
BH_Mutex *mutex,
uint32_t timeout);
Attempts to block the execution of the current thread until another thread
signals a change in the condition within a specified time I<timeout>.
In some situations, the signal of a condition change may be false.
The I<mutex> parameter specifies the mutex used in conjunction with the
condition variable.
The I<timeout> parameter specifies the waiting time in milliseconds.
Returns 0 on success, otherwise an error code.
=head2 BH_ConditionSignal
int BH_ConditionSignal(BH_Condition *condition);
Signals one waiting thread about a change in the condition.
Returns 0 on success, otherwise an error code.
=head2 BH_ConditionBroadcast
int BH_ConditionBroadcast(BH_Condition *condition);
Signals all waiting threads about a change in the condition.
Returns 0 on success, otherwise an error code.
=head2 BH_SpinlockLock
void BH_SpinlockLock(int *lock);
Locks the spinlock.
=head2 BH_SpinlockLockTry
int BH_SpinlockLockTry(int *lock);
Attempts to lock the spinlock.
Returns 0 on success, otherwise an error code.
=head2 BH_SpinlockUnlock
void BH_SpinlockUnlock(int *lock);
Unlocks the spinlock.
=head2 BH_TssCreate
int BH_TssCreate(BH_GenericCallback callback);
Creates a new TSS/TLS index with a cleanup function I<callback>.
Returns the TSS/TLS index on success, otherwise an error code.
=head2 BH_TssRead
void *BH_TssRead(int index);
Reads data from the TSS/TLS slot.
=head2 BH_TssWrite
void BH_TssWrite(int index,
void *value);
Writes data I<value> to the TSS/TLS slot.
=head1 SEE ALSO
L<BH>

View File

@@ -0,0 +1,184 @@
=encoding UTF-8
=head1 NAME
BH_Unicode - Working with Unicode and UTF encodings
=head1 SYNTAX
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Unicode library provides a set of functions for working with various
Unicode encodings, including UTF-8, UTF-16, and UTF-32. It allows you to
convert characters to uppercase and lowercase, as well as encode and decode
strings in the specified encodings.
=head1 API CALLS
=head2 BH_UnicodeLower
uint32_t BH_UnicodeLower(uint32_t unit);
Converts the Unicode code I<unit> to lowercase.
The conversion is performed for characters in the Basic Multilingual Plane
(i.e., the first 65,536 codes).
=head2 BH_UnicodeUpper
uint32_t BH_UnicodeUpper(uint32_t unit);
Converts the Unicode code I<unit> to uppercase.
The conversion is performed for characters in the Basic Multilingual Plane
(i.e., the first 65,536 codes).
=head2 BH_UnicodeDecodeUtf8
size_t BH_UnicodeDecodeUtf8(const char *string,
size_t size,
uint32_t *unit);
Decodes the UTF-8 sequence from I<string> (with the specified length I<size>)
and writes the code to I<unit>.
Invalid UTF-8 sequences will be converted to code -1.
If successful, the function returns the number of bytes read or 0 if I<string>
contains only part of the sequence.
=head2 BH_UnicodeEncodeUtf8
size_t BH_UnicodeEncodeUtf8(uint32_t unit,
char *string);
Encodes the UTF-8 sequence into I<string> from the code I<unit>.
It is assumed that the string contains 4 bytes of free space.
If successful, the function returns the number of bytes written or 0.
=head2 BH_UnicodeDecodeUtf16LE
size_t BH_UnicodeDecodeUtf16LE(const char *string,
size_t size,
uint32_t *unit);
Decodes the UTF-16LE sequence from I<string> (with the specified length I<size>)
and writes the code to I<unit>.
Invalid UTF-16LE sequences will be converted to code -1.
If successful, the function returns the number of bytes read or 0 if I<string>
contains only part of the sequence.
=head2 BH_UnicodeDecodeUtf16BE
size_t BH_UnicodeDecodeUtf16BE(const char *string,
size_t size,
uint32_t *unit);
Decodes the UTF-16BE sequence from I<string> (with the specified length I<size>)
and writes the code to I<unit>.
Invalid UTF-16BE sequences will be converted to code -1.
If successful, the function returns the number of bytes read or 0 if I<string>
contains only part of the sequence.
=head2 BH_UnicodeEncodeUtf16LE
size_t BH_UnicodeEncodeUtf16LE(uint32_t unit,
char *string);
Encodes the UTF-16LE sequence into I<string> from the code I<unit>.
It is assumed that the string contains 4 bytes of free space.
If successful, the function returns the number of bytes written or 0.
=head2 BH_UnicodeEncodeUtf16BE
size_t BH_UnicodeEncodeUtf16BE(uint32_t unit,
char *string);
Encodes the UTF-16BE sequence into I<string> from the code I<unit>.
It is assumed that the string contains 4 bytes of free space.
If successful, the function returns the number of bytes written or 0.
=head2 BH_UnicodeDecodeUtf32LE
size_t BH_UnicodeDecodeUtf32LE(const char *string,
size_t size,
uint32_t *unit);
Decodes the UTF-32LE sequence from I<string> (with the specified length I<size>)
and writes the code to I<unit>.
Invalid UTF-32LE sequences will be converted to code -1.
If successful, the function returns the number of bytes read or 0 if I<string>
contains only part of the sequence.
=head2 BH_UnicodeDecodeUtf32BE
size_t BH_UnicodeDecodeUtf32BE(const char *string,
size_t size,
uint32_t *unit);
Decodes the UTF-32BE sequence from I<string> (with the specified length I<size>)
and writes the code to I<unit>.
Invalid UTF-32BE sequences will be converted to code -1.
If successful, the function returns the number of bytes read or 0 if I<string>
contains only part of the sequence.
=head2 BH_UnicodeEncodeUtf32LE
size_t BH_UnicodeEncodeUtf32LE(uint32_t unit,
char *string);
Encodes the UTF-32LE sequence into I<string> from the code I<unit>.
It is assumed that the string contains 4 bytes of free space.
If successful, the function returns the number of bytes written or 0.
=head2 BH_UnicodeEncodeUtf32BE
size_t BH_UnicodeEncodeUtf32BE(uint32_t unit,
char *string);
Encodes the UTF-32BE sequence into I<string> from the code I<unit>.
It is assumed that the string contains 4 bytes of free space.
If successful, the function returns the number of bytes written or 0.
=head1 SEE ALSO
L<BH>

241
doc/Manual/en/BH_Util.pod Normal file
View File

@@ -0,0 +1,241 @@
=encoding UTF-8
=head1 NAME
BH_Util - Utility Functions
=head1 SYNTAX
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Util library provides a set of functions for working with numbers in
little-endian and big-endian formats, as well as for classifying floating-point
values.
=head1 API CALLS
=head2 BH_ClassifyDouble
int BH_ClassifyDouble(double value);
Classifies a floating-point value.
This function returns a combination of the following values:
=over
=item B<BH_FP_NORMAL>
The value is normal or subnormal.
=item B<BH_FP_ZERO>
The value is positive or negative zero.
=item B<BH_FP_INFINITE>
The value is positive or negative infinity.
=item B<BH_FP_NAN>
The value is not a number (NaN).
=item B<BH_FP_NEGATIVE>
The value is negative.
=back
=head2 BH_Read16LEu
uint16_t BH_Read16LEu(const char *buffer);
Reads an unsigned 16-bit little-endian integer from the buffer.
=head2 BH_Read16LEs
int16_t BH_Read16LEs(const char *buffer);
Reads a signed 16-bit little-endian integer from the buffer.
=head2 BH_Read32LEu
uint32_t BH_Read32LEu(const char *buffer);
Reads an unsigned 32-bit little-endian integer from the buffer.
=head2 BH_Read32LEs
int32_t BH_Read32LEs(const char *buffer);
Reads a signed 32-bit little-endian integer from the buffer.
=head2 BH_Read64LEu
uint64_t BH_Read64LEu(const char *buffer);
Reads an unsigned 64-bit little-endian integer from the buffer.
=head2 BH_Read64LEs
int64_t BH_Read64LEs(const char *buffer);
Reads a signed 64-bit little-endian integer from the buffer.
=head2 BH_Read16BEu
uint16_t BH_Read16BEu(const char *buffer);
Reads an unsigned 16-bit big-endian integer from the buffer.
=head2 BH_Read16BEs
int16_t BH_Read16BEs(const char *buffer);
Reads a signed 16-bit big-endian integer from the buffer.
=head2 BH_Read32BEu
uint32_t BH_Read32BEu(const char *buffer);
Reads an unsigned 32-bit big-endian integer from the buffer.
=head2 BH_Read32BEs
int32_t BH_Read32BEs(const char *buffer);
Reads a signed 32-bit big-endian integer from the buffer.
=head2 BH_Read64BEu
uint64_t BH_Read64BEu(const char *buffer);
Reads an unsigned 64-bit big-endian integer from the buffer.
=head2 BH_Read64BEs
int64_t BH_Read64BEs(const char *buffer);
Reads a signed 64-bit big-endian integer from the buffer.
=head2 BH_Write16LEu
void BH_Write16LEu(char *buffer,
uint16_t value);
Writes an unsigned 16-bit little-endian integer to the buffer.
=head2 BH_Write16LEs
void BH_Write16LEs(char *buffer,
int16_t value);
Writes a signed 16-bit little-endian integer to the buffer.
=head2 BH_Write32LEu
void BH_Write32LEu(char *buffer,
uint32_t value);
Writes an unsigned 32-bit little-endian integer to the buffer.
=head2 BH_Write32LEs
void BH_Write32LEs(char *buffer,
int32_t value);
Writes a signed 32-bit little-endian integer to the buffer.
=head2 BH_Write64LEu
void BH_Write64LEu(char *buffer,
uint64_t value);
Writes an unsigned 64-bit little-endian integer to the buffer.
=head2 BH_Write64LEs
void BH_Write64LEs(char *buffer,
int64_t value);
Writes a signed 64-bit little-endian integer to the buffer.
=head2 BH_Write16BEu
void BH_Write16BEu(char *buffer,
uint16_t value);
Writes an unsigned 16-bit big-endian integer to the buffer.
=head2 BH_Write16BEs
void BH_Write16BEs(char *buffer,
int16_t value);
Writes a signed 16-bit big-endian integer to the buffer.
=head2 BH_Write32BEu
void BH_Write32BEu(char *buffer,
uint32_t value);
Writes an unsigned 32-bit big-endian integer to the buffer.
=head2 BH_Write32BEs
void BH_Write32BEs(char *buffer,
int32_t value);
Writes a signed 32-bit big-endian integer to the buffer.
=head2 BH_Write64BEu
void BH_Write64BEu(char *buffer,
uint64_t value);
Writes an unsigned 64-bit big-endian integer to the buffer.
=head2 BH_Write64BEs
void BH_Write64BEs(char *buffer,
int64_t value);
Writes a signed 64-bit big-endian integer to the buffer.
=head1 SEE ALSO
L<BH>

200
doc/Manual/en/BH_Vec2f.pod Normal file
View File

@@ -0,0 +1,200 @@
=encoding UTF-8
=head1 NAME
BH_Vec2f - two-dimensional real vector
=head1 SYNTAX
#include <BH/Math/Vec2f.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Vec2f module provides a set of functions for working with two-dimensional
vectors. It includes operations for addition, subtraction, multiplication,
scaling, calculating the dot and cross product, as well as normalizing vectors.
=head1 API CALLS
=head2 BH_Vec2fAdd
void BH_Vec2fAdd(const float a[2],
const float b[2],
float out[2]);
Calculates the sum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fSub
void BH_Vec2fSub(const float a[2],
const float b[2],
float out[2]);
Calculates the difference between two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fMul
void BH_Vec2fMul(const float a[2],
const float b[2],
float out[2]);
Calculates the result of multiplying two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fScale
void BH_Vec2fScale(const float a[2],
float b,
float out[2]);
Calculates the result of multiplying vector I<a> by value I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fMulAdd
void BH_Vec2fMulAdd(const float a[2],
const float b[2],
const float c[2],
float out[2]);
Calculates the result of the sum I<c> and the product of vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fNegate
void BH_Vec2fNegate(const float in[2],
float out[2]);
Calculates the opposite vector from vector I<in>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fDot
float BH_Vec2fDot(const float a[2],
const float b[2]);
Calculates the dot product of vectors I<a> and I<b>.
=head2 BH_Vec2fCross
float BH_Vec2fCross(const float a[2],
const float b[2]);
Calculates the cross product of vectors I<a> and I<b>.
=head2 BH_Vec2fLength
float BH_Vec2fLength(const float in[2]);
Calculates the length of vector I<in>.
=head2 BH_Vec2fNormal
void BH_Vec2fNormal(const float in[2],
float out[2]);
Calculates the normalized form of vector I<in>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fNormalEx
float BH_Vec2fNormalEx(const float in[2],
float out[2]);
Calculates the normalized form of vector I<in> and returns its original length.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fMin
void BH_Vec2fMin(const float a[2],
const float b[2],
float out[2]);
Calculates the element-wise minimum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fMax
void BH_Vec2fMax(const float a[2],
const float b[2],
float out[2]);
Calculates the element-wise maximum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fLerp
void BH_Vec2fLerp(const float a[2],
const float b[2],
float t,
float out[2]);
Performs linear interpolation between two vectors I<a> and I<b> with parameter
I<t>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fProject
void BH_Vec2fProject(const float a[2],
const float b[2],
float out[2]);
Calculates the result of projecting vector I<a> onto vector I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2fBarycentric
void BH_Vec2fBarycentric(const float a[2],
const float b[2],
const float c[2],
float v,
float w,
float out[2]);
Calculates the vector from the barycentric coordinates I<v>, I<w> and vectors of
points I<a>, I<b>, I<c>.
The calculation is performed using the formula A + v*(B-A) + w*(C-A).
The I<out> parameter describes the resulting vector.
=head1 SEE ALSO
L<BH>

116
doc/Manual/en/BH_Vec2i.pod Normal file
View File

@@ -0,0 +1,116 @@
=encoding UTF-8
=head1 NAME
BH_Vec2i - two-dimensional integer vector
=head1 SYNTAX
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Vec2i module provides a set of functions for working with two-dimensional
integer vectors.
=head1 API CALLS
=head2 BH_Vec2iAdd
void BH_Vec2iAdd(const int a[2],
const int b[2],
int out[2]);
Calculates the sum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2iSub
void BH_Vec2iSub(const int a[2],
const int b[2],
int out[2]);
Calculates the difference between two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2iMul
void BH_Vec2iMul(const int a[2],
const int b[2],
int out[2]);
Calculates the result of multiplying two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2iScale
void BH_Vec2iScale(const int a[2],
int b,
int out[2]);
Calculates the result of multiplying vector I<a> by value I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2iMulAdd
void BH_Vec2iMulAdd(const int a[2],
const int b[2],
const int c[2],
int out[2]);
Calculates the result of the sum I<c> and the result of multiplying vectors I<a>
and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2iNegate
void BH_Vec2iNegate(const int in[2],
int out[2]);
Calculates the opposite vector from vector I<in>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2iMin
void BH_Vec2iMin(const int a[2],
const int b[2],
int out[2]);
Calculates the element-wise minimum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec2iMax
void BH_Vec2iMax(const int a[2],
const int b[2],
int out[2]);
Calculates the element-wise maximum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head1 SEE ALSO
L<BH>

203
doc/Manual/en/BH_Vec3f.pod Normal file
View File

@@ -0,0 +1,203 @@
=encoding UTF-8
=head1 NAME
BH_Vec3f - three-dimensional real vector
=head1 SYNTAX
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Vec3f module provides a set of functions for working with
three-dimensional vectors. The functions allow performing arithmetic operations,
calculating scalar and vector products, normalizing vectors, and performing
other vector operations.
=head1 API CALLS
=head2 BH_Vec3fAdd
void BH_Vec3fAdd(const float a[3],
const float b[3],
float out[3]);
Calculates the sum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fSub
void BH_Vec3fSub(const float a[3],
const float b[3],
float out[3]);
Calculates the difference between two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fMul
void BH_Vec3fMul(const float a[3],
const float b[3],
float out[3]);
Calculates the result of multiplying two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fScale
void BH_Vec3fScale(const float a[3],
float b,
float out[3]);
Calculates the result of multiplying vector I<a> by value I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fMulAdd
void BH_Vec3fMulAdd(const float a[3],
const float b[3],
const float c[3],
float out[3]);
Calculates the result of the sum I<c> and the result of multiplying vectors I<a>
and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fNegate
void BH_Vec3fNegate(const float in[3],
float out[3]);
Calculates the opposite vector from vector I<in>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fDot
float BH_Vec3fDot(const float a[3],
const float b[3]);
Calculates the dot product of vectors I<a> and I<b>.
=head2 BH_Vec3fCross
void BH_Vec3fCross(const float a[3],
const float b[3],
float out[3]);
Calculates the cross product of vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fLength
float BH_Vec3fLength(const float in[3]);
Calculates the length of vector I<in>.
=head2 BH_Vec3fNormal
void BH_Vec3fNormal(const float in[3],
float out[3]);
Calculates the normalized form of vector I<in>.
=head2 BH_Vec3fNormalEx
float BH_Vec3fNormalEx(const float in[3],
float out[3]);
Calculates the normalized form of vector I<in> and returns its original length.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fMin
void BH_Vec3fMin(const float a[3],
const float b[3],
float out[3]);
Calculates the element-wise minimum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fMax
void BH_Vec3fMax(const float a[3],
const float b[3],
float out[3]);
Calculates the element-wise maximum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fLerp
void BH_Vec3fLerp(const float a[3],
const float b[3],
float t,
float out[3]);
Performs linear interpolation between two vectors I<a> and I<b> with parameter
I<t>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fProject
void BH_Vec3fProject(const float a[3],
const float b[3],
float out[3]);
Calculates the result of projecting vector I<a> onto vector I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3fBarycentric
void BH_Vec3fBarycentric(const float a[3],
const float b[3],
const float c[3],
float v,
float w,
float out[3]);
Calculates the vector from barycentric coordinates I<v>, I<w> and vectors of
points I<a>, I<b>, I<c>.
The calculation is performed using the formula A + v*(B-A) + w*(C-A).
The I<out> parameter describes the resulting vector.
=head1 SEE ALSO
L<BH>

116
doc/Manual/en/BH_Vec3i.pod Normal file
View File

@@ -0,0 +1,116 @@
=encoding UTF-8
=head1 NAME
BH_Vec3i - three-dimensional integer vector
=head1 SYNTAX
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Vec3i module provides a set of functions for working with
three-dimensional integer vectors.
=head1 API CALLS
=head2 BH_Vec3iAdd
void BH_Vec3iAdd(const int a[3],
const int b[3],
int out[3]);
Calculates the sum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3iSub
void BH_Vec3iSub(const int a[3],
const int b[3],
int out[3]);
Calculates the difference between two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3iMul
void BH_Vec3iMul(const int a[3],
const int b[3],
int out[3]);
Calculates the result of multiplying two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3iScale
void BH_Vec3iScale(const int a[3],
int b,
int out[3]);
Calculates the result of multiplying vector I<a> by value I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3iMulAdd
void BH_Vec3iMulAdd(const int a[3],
const int b[3],
const int c[3],
int out[3]);
Calculates the result of the sum I<c> and the result of multiplying vectors
I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3iNegate
void BH_Vec3iNegate(const int in[3],
int out[3]);
Calculates the opposite vector from vector I<in>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3iMin
void BH_Vec3iMin(const int a[3],
const int b[3],
int out[3]);
Calculates the element-wise minimum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec3iMax
void BH_Vec3iMax(const int a[3],
const int b[3],
int out[3]);
Calculates the element-wise maximum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head1 SEE ALSO
L<BH>

194
doc/Manual/en/BH_Vec4f.pod Normal file
View File

@@ -0,0 +1,194 @@
=encoding UTF-8
=head1 NAME
BH_Vec4f - four-dimensional real vector
=head1 SYNTAX
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Vec4f module provides a set of functions for working with
four-dimensional vectors. The functions allow performing arithmetic operations,
normalization, calculating the dot product, and other mathematical operations
on vectors.
=head1 API CALLS
=head2 BH_Vec4fAdd
void BH_Vec4fAdd(const float a[4],
const float b[4],
float out[4]);
Calculates the sum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fSub
void BH_Vec4fSub(const float a[4],
const float b[4],
float out[4]);
Calculates the difference between two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fMul
void BH_Vec4fMul(const float a[4],
const float b[4],
float out[4]);
Calculates the result of multiplying two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fScale
void BH_Vec4fScale(const float a[4],
float b,
float out[4]);
Calculates the result of multiplying vector I<a> by value I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fMulAdd
void BH_Vec4fMulAdd(const float a[4],
const float b[4],
const float c[4],
float out[4]);
Calculates the result of the sum I<c> and the result of multiplying vectors I<a>
and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fNegate
void BH_Vec4fNegate(const float in[4],
float out[4]);
Calculates the opposite vector from vector I<in>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fDot
float BH_Vec4fDot(const float a[4],
const float b[4]);
Calculates the dot product of vectors I<a> and I<b>.
=head2 BH_Vec4fLength
float BH_Vec4fLength(const float in[4]);
Calculates the length of vector I<in>.
=head2 BH_Vec4fNormal
void BH_Vec4fNormal(const float in[4],
float out[4]);
Calculates the normalized form of vector I<in>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fNormalEx
float BH_Vec4fNormalEx(const float in[4],
float out[4]);
Calculates the normalized form of vector I<in> and returns its original length.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fMin
void BH_Vec4fMin(const float a[4],
const float b[4],
float out[4]);
Calculates the element-wise minimum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fMax
void BH_Vec4fMax(const float a[4],
const float b[4],
float out[4]);
Calculates the element-wise maximum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fLerp
void BH_Vec4fLerp(const float a[4],
const float b[4],
float t,
float out[4]);
Performs linear interpolation between two vectors I<a> and I<b> with parameter
I<t>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fProject
void BH_Vec4fProject(const float a[4],
const float b[4],
float out[4]);
Calculates the result of projecting vector I<a> onto vector I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4fBarycentric
void BH_Vec4fBarycentric(const float a[4],
const float b[4],
const float c[4],
float v,
float w,
float out[4]);
Calculates the vector from barycentric coordinates I<v>, I<w> and vectors of
points I<a>, I<b>, I<c>.
The calculation is performed using the formula A + v*(B-A) + w*(C-A).
The I<out> parameter describes the resulting vector.
=head1 SEE ALSO
L<BH>

116
doc/Manual/en/BH_Vec4i.pod Normal file
View File

@@ -0,0 +1,116 @@
=encoding UTF-8
=head1 NAME
BH_Vec4i - four-dimensional integer vector
=head1 SYNTAX
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 DESCRIPTION
The BH_Vec4i module provides a set of functions for working with
four-dimensional integer vectors.
=head1 API CALLS
=head2 BH_Vec4iAdd
void BH_Vec4iAdd(const int a[4],
const int b[4],
int out[4]);
Calculates the sum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4iSub
void BH_Vec4iSub(const int a[4],
const int b[4],
int out[4]);
Calculates the difference between two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4iMul
void BH_Vec4iMul(const int a[4],
const int b[4],
int out[4]);
Calculates the result of multiplying two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4iScale
void BH_Vec4iScale(const int a[4],
int b,
int out[4]);
Calculates the result of multiplying vector I<a> by value I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4iMulAdd
void BH_Vec4iMulAdd(const int a[4],
const int b[4],
const int c[4],
int out[4]);
Calculates the result of the sum I<c> and the result of multiplying vectors I<a>
and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4iNegate
void BH_Vec4iNegate(const int in[4],
int out[4]);
Calculates the opposite vector from vector I<in>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4iMin
void BH_Vec4iMin(const int a[4],
const int b[4],
int out[4]);
Calculates the element-wise minimum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head2 BH_Vec4iMax
void BH_Vec4iMax(const int a[4],
const int b[4],
int out[4]);
Calculates the element-wise maximum of two vectors I<a> and I<b>.
The I<out> parameter describes the resulting vector.
=head1 SEE ALSO
L<BH>

165
doc/Manual/ru/BH_Algo.pod Normal file
View File

@@ -0,0 +1,165 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Algo - Общие алгоритмы
=head1 СИНТАКСИС
#include <BH/Algo.h>
int data[4] = {5, 2, 3, 1};
int value, i;
value = 4;
BH_Partition(&value, data, 4, sizeof(int), intEqual);
BH_Sort(data, 4, sizeof(int), intEqual);
BH_HeapMake(data, 4, sizeof(int), intEqual);
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Библиотека BH_Algo предоставляет набор алгоритмов для работы с данными:
=over
=item *
Обмен значениями (L</BH_Swap>)
=item *
Разбиение массива (L</BH_Partition>)
=item *
Сортировка (L</BH_Sort>)
=item *
Работа с кучей (L</BH_HeapMake>, L</BH_HeapRemove>, L</BH_HeapInsert>,
L</BH_HeapReplace>)
=back
Эти алгоритмы позволяют эффективно выполнять различные операции над массивами и
другими структурами данных.
=head1 API ВЫЗОВЫ
=head2 BH_Swap
void BH_Swap(void *dest,
void *src,
size_t size);
Меняет значение между переменными I<dest> и I<src> заданного размера I<size>.
=head2 BH_Partition
void *BH_Partition(void *pivot,
void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Разбивает массив элементов I<array> (с количеством элементов I<size> и размером
элемента I<element>) на две группы относительно элемента I<pivot>.
Параметр I<equal> принимает указатель на функцию, которая сравнивает два
элемента.
Параметр I<pivot> может ссылаться на элемент разбиваемого массива.
Функция возвращает указатель на первый элемент массива, который принадлежит
второй группе.
=head2 BH_Sort
void BH_Sort(void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Сортирует массив элементов I<array> (с количеством элементов I<size> и размером
элемента I<element>).
Параметр I<equal> принимает указатель на функцию, которая сравнивает два
элемента.
=head2 BH_HeapMake
void BH_HeapMake(void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Создаёт кучу в массиве I<array> (с количеством элементов I<size> и размером
элемента I<element>).
Параметр I<equal> принимает указатель на функцию, которая сравнивает два
элемента.
=head2 BH_HeapRemove
void BH_HeapRemove(void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Извлекает верхний элемент кучи в массиве I<array> (с количеством элементов
I<size> и размером элемента I<element>).
Параметр I<equal> принимает указатель на функцию, которая сравнивает два
элемента.
=head2 BH_HeapInsert
void BH_HeapInsert(void *value,
void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Добавляет элемент I<value> в кучу в массиве I<array> (с количеством элементов
I<size> и размером элемента I<element>).
Если I<value> равен NULL, предполагается, что новое значение находится в конце
массива.
Параметр I<equal> принимает указатель на функцию, которая сравнивает два
элемента.
=head2 BH_HeapReplace
void BH_HeapReplace(void *value,
void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
Извлекает верхний элемент кучи в массиве I<array> (с количеством элементов
I<size> и размером элемента I<element>) и добавляет в неё элемент I<value>.
Если I<value> равен NULL, предполагается, что новое значение находится в конце
массива.
Параметр I<equal> принимает указатель на функцию, которая сравнивает два
элемента.
=head1 СМ. ТАКЖЕ
L<BH>

165
doc/Manual/ru/BH_Args.pod Normal file
View File

@@ -0,0 +1,165 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Args - обработка аргументов командной строки
=head1 СИНТАКСИС
#include <BH/Args.h>
static BH_ArgsOption options[] =
{
{'h', "help", 0, "Display this help"},
{1000, "list", 0, "List files"},
{'i', "input", BH_ARGS_VALUE, "Input file"},
{'o', "output", BH_ARGS_VALUE | BH_ARGS_OPTIONAL, "Output file"},
{0, NULL, 0, NULL}
};
static int OptionsCallback(int key,
char *arg,
void *data)
{
switch (key)
{
case BH_ARGS_UNKNOWN:
/* Unknown options */
break;
case BH_ARGS_ARGUMENT:
/* Regular argument in arg */
break;
case 'h':
/* Named option without argument */
break;
case 1000:
/* Long-only option without argument */
break;
case 'i':
/* Option with argument in arg */
break;
case 'o':
/* Option with optional argument in arg */
break;
}
return BH_OK;
}
BH_ArgsParse(argc, argv, options, OptionsCallback, NULL);
BH_ArgsHelp(options, 0);
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Библиотека BH_Args предназначена для удобной обработки аргументов командной
строки в программах. Она позволяет определить набор опций, которые могут быть
указаны при запуске программы, и предоставляет механизмы для их анализа и
обработки.
Разбор аргументов происходит с учётом следующих правил:
=over
=item *
Если указан аргумент "--", последующий разбор аргументов прекращается.
=item *
Если указан аргумент "-", он обрабатывается как есть.
=item *
Для значений длинных аргументов будет использоваться строка после знака равно
или следующий аргумент ("--define=value" или "--define value").
=item *
Для значений коротких аргументов будет использоваться остаток строки после
символа параметра или следующий аргумент ("-dvalue" или "-d value").
=back
=head1 API ВЫЗОВЫ
=head2 BH_ArgsParse
int BH_ArgsParse(int argc,
char **argv,
BH_ArgsOption *options,
BH_ArgsCallback callback,
void *data);
Разбирает аргументы I<options> командной строки (заданные в I<argc> и I<argv>) и
вызывает указанный обработчик I<callback> (с пользовательскими данными I<data>).
Параметр I<options> ссылается на нуль-терминированный массив.
В случае успеха данная функция возвращает 0, в противном случае - код ошибки.
=head2 BH_ArgsHelp
void BH_ArgsHelp(BH_ArgsOption *options,
int padding);
Выводит в F<stdout> справочную информацию для аргументов I<options> (с указанным
выравниванием I<padding>).
В случае если параметр I<padding> равен 0, то будет использовано значение
по умолчанию (30).
=head1 СТРУКТУРЫ
=head2 BH_ArgsOption
typedef struct BH_ArgsOption
{
int key;
const char *name;
int flags;
const char *description;
} BH_ArgsOption;
Поле I<key> содержит идентификатор опции. В случае если идентификатор I<key>
является печатным символом ASCII, то он будет использоваться в качестве
короткого аргумента.
Опциональное поле I<name> содержит строку, которая будет использоваться в
качестве длинного аргумента.
Поле I<flags> содержит флаги аргумента. Возможна комбинация из следующих флагов:
=over
=item B<BH_ARGS_VALUE>
Аргумент принимает значение.
=item B<BH_ARGS_OPTIONAL>
Значение аргумента опционально.
=back
Поле I<description> содержит строку, которая будет использоваться при выводе
справочной информации при помощи функции L</BH_ArgsHelp>.
=head1 СМ. ТАКЖЕ
L<BH>

102
doc/Manual/ru/BH_Box2f.pod Normal file
View File

@@ -0,0 +1,102 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Box2f - двухмерный ограничивающий прямоугольник
=head1 СИНТАКСИС
#include <BH/Math/Box2f.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Box2f предоставляет функции для работы с двухмерными ограничивающими
прямоугольниками. Он включает в себя операции объединения, пересечения, проверки
вхождения точки в прямоугольник и вычисления ограничивающего прямоугольника по
набору точек.
=head1 API ВЫЗОВЫ
=head2 BH_Box2fUnion
void BH_Box2fUnion(const float aMin[2],
const float aMax[2],
const float bMin[2],
const float bMax[2],
float outMin[2],
float outMax[2]);
Объединяет два ограничивающих прямоугольника A и B.
Параметры I<aMin> и I<aMax> описывают ограничивающий прямоугольник A.
Параметры I<bMin> и I<bMax> описывают ограничивающий прямоугольник B.
Параметры I<outMin> и I<outMax> описывают результирующий ограничивающий
прямоугольник.
=head2 BH_Box2fIntersect
int BH_Box2fIntersect(const float aMin[2],
const float aMax[2],
const float bMin[2],
const float bMax[2],
float outMin[2],
float outMax[2]);
Вычисляет пересечение двух ограничивающих прямоугольников A и B.
Параметры I<aMin> и I<aMax> описывают ограничивающий прямоугольник A.
Параметры I<bMin> и I<bMax> описывают ограничивающий прямоугольник B.
Параметры I<outMin> и I<outMax> описывают результирующий ограничивающий
прямоугольник.
Возвращает 0 в случае успешного пересечения или код ошибки.
=head2 BH_Box2fContains
int BH_Box2fContains(const float aMin[2],
const float aMax[2],
const float point[2]);
Проверяет, находится ли точка I<point> внутри ограничивающего прямоугольника.
Параметры I<aMin> и I<aMax> описывают ограничивающий прямоугольник.
Параметр I<point> описывает точку.
Возвращает 0, если точка находится внутри прямоугольника, или код ошибки.
=head2 BH_Box2fEnclose
int BH_Box2fEnclose(const float *points,
size_t size,
float outMin[2],
float outMax[2]);
Вычисляет ограничивающий прямоугольник по заданным точкам I<points>.
Параметры I<points> и I<size> описывают входной массив точек.
Параметры I<outMin> и I<outMax> описывают результирующий ограничивающий
прямоугольник.
Возвращает 0 в случае успешного вычисления или код ошибки.
=head1 СМ. ТАКЖЕ
L<BH>,
L<BH_Box3f>

103
doc/Manual/ru/BH_Box3f.pod Normal file
View File

@@ -0,0 +1,103 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Box3f - трёхмерный ограничивающий прямоугольник
=head1 СИНТАКСИС
#include <BH/Math/Box3f.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Box3f предоставляет функции для работы с трёхмерными ограничивающими
прямоугольниками. Он включает в себя операции объединения, пересечения, проверки
вхождения точки в прямоугольник и вычисления ограничивающего прямоугольника по
набору точек.
=head1 API ВЫЗОВЫ
=head2 BH_Box3fUnion
void BH_Box3fUnion(const float aMin[3],
const float aMax[3],
const float bMin[3],
const float bMax[3],
float outMin[3],
float outMax[3]);
Объединяет два ограничивающих прямоугольника A и B.
Параметры I<aMin> и I<aMax> описывают ограничивающий прямоугольник A.
Параметры I<bMin> и I<bMax> описывают ограничивающий прямоугольник B.
Параметры I<outMin> и I<outMax> описывают результирующий ограничивающий
прямоугольник.
=head2 BH_Box3fIntersect
int BH_Box3fIntersect(const float aMin[3],
const float aMax[3],
const float bMin[3],
const float bMax[3],
float outMin[3],
float outMax[3]);
Вычисляет пересечение двух ограничивающих прямоугольников A и B.
Параметры I<aMin> и I<aMax> описывают ограничивающий прямоугольник A.
Параметры I<bMin> и I<bMax> описывают ограничивающий прямоугольник B.
Параметры I<outMin> и I<outMax> описывают результирующий ограничивающий
прямоугольник.
Возвращает 0 в случае успешного пересечения или код ошибки.
=head2 BH_Box3fContains
int BH_Box3fContains(const float aMin[3],
const float aMax[3],
const float point[3]);
Проверяет, находится ли точка I<point> внутри ограничивающего прямоугольника.
Параметры I<aMin> и I<aMax> описывают ограничивающий прямоугольник.
Параметр I<point> описывает точку.
Возвращает 0, если точка находится внутри ограничивающего прямоугольника, или
код ошибки.
=head2 BH_Box3fEnclose
int BH_Box3fEnclose(const float *points,
size_t size,
float outMin[3],
float outMax[3]);
Вычисляет ограничивающий прямоугольник по заданным точкам.
Параметры I<points> и I<size> описывают входной массив точек.
Параметры I<outMin> и I<outMax> описывают результирующий ограничивающий
прямоугольник.
Возвращает 0 в случае успеха или код ошибки.
=head1 СМ. ТАКЖЕ
L<BH>,
L<BH_Box2f>

View File

@@ -0,0 +1,198 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Hashmap - неупорядочный ассоциативный массив
=head1 СИНТАКСИС
#include <BH/Hashmap.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Библиотека BH_Hashmap предоставляет реализацию неупорядоченного ассоциативного
массива, основанного на хэш-таблице. Она позволяет эффективно хранить и
извлекать данные по ключу.
=head1 API ВЫЗОВЫ
=head2 BH_HashmapNew
BH_Hashmap *BH_HashmapNew(BH_EqualCallback equal,
BH_HashCallback hash);
Создаёт ассоциативный массив.
Параметр I<equal> принимает указатель на функцию, которая сравнивает два
элемента.
Параметр I<hash> принимает указатель на функцию, вычисляющую хэш-значение
элемента.
В случае успеха функция возвращает указатель на новый объект BH_Hashmap или NULL
в случае ошибки.
=head2 BH_HashmapFree
void BH_HashmapFree(BH_Hashmap *hashmap);
Уничтожает ассоциативный массив.
=head2 BH_HashmapClear
void BH_HashmapClear(BH_Hashmap *hashmap);
Очищает ассоциативный массив.
=head2 BH_HashmapReserve
int BH_HashmapReserve(BH_Hashmap *hashmap,
size_t size);
Резервирует место как минимум для I<size> элементов.
Вызов этой функции делает существующие итераторы недействительными.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head2 BH_HashmapInsert
int BH_HashmapInsert(BH_Hashmap *hashmap,
void *key,
void *value);
Вставляет элемент, представленный парой ключ-значение I<key> и I<value>.
Функция позволяет вставлять несколько элементов с одинаковым значением ключа.
Вызов этой функции делает существующие итераторы недействительными.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head2 BH_HashmapRemove
void BH_HashmapRemove(BH_Hashmap *hashmap,
void *key);
Удаляет элемент с заданным значением ключа I<key>.
Если ассоциативный массив содержит несколько элементов с одинаковым значением
ключа, функция удалит только одну пару ключ-значение.
Вызов этой функции делает существующие итераторы недействительными.
=head2 BH_HashmapAt
int BH_HashmapAt(BH_Hashmap *hashmap,
void *key,
void **value);
Проверяет наличие элемента с заданным ключом I<key>.
Опциональный параметр I<value> возвращает значение элемента с заданным ключом.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head2 BH_HashmapEmpty
int BH_HashmapEmpty(BH_Hashmap *hashmap);
Проверяет, является ли ассоциативный массив пустым.
=head2 BH_HashmapSize
size_t BH_HashmapSize(BH_Hashmap *hashmap);
Возвращает количество элементов.
=head2 BH_HashmapCapacity
size_t BH_HashmapCapacity(BH_Hashmap *hashmap);
Возвращает ёмкость.
=head2 BH_HashmapFactor
float BH_HashmapFactor(BH_Hashmap *hashmap);
Возвращает максимальный коэффициент загрузки.
=head2 BH_HashmapSetFactor
void BH_HashmapSetFactor(BH_Hashmap *hashmap,
float factor);
Задаёт максимальный коэффициент загрузки I<factor>.
Новое значение максимального коэффициента загрузки будет применено при следующем
вызове функции
L</BH_HashmapInsert> или L</BH_HashmapReserve>.
=head2 BH_HashmapIterAt
void *BH_HashmapIterAt(BH_Hashmap *hashmap,
void *key);
Возвращает итератор на элемент с заданным ключом I<key>.
В случае успеха функция возвращает итератор или NULL.
=head2 BH_HashmapIterNext
void *BH_HashmapIterNext(BH_Hashmap *hashmap,
void *iter);
Возвращает итератор на следующий элемент.
Опциональный параметр I<iter> принимает итератор на текущий элемент.
В случае успеха функция возвращает итератор или NULL.
=head2 BH_HashmapIterRemove
void BH_HashmapIterRemove(BH_Hashmap *hashmap,
void *iter);
Удаляет элемент по заданному итератору I<iter>.
Вызов этой функции делает существующие итераторы недействительными.
=head2 BH_HashmapIterKey
void *BH_HashmapIterKey(void *iter);
Возвращает ключ элемента, указываемый итератором I<iter>.
=head2 BH_HashmapIterValue
void *BH_HashmapIterValue(void *iter);
Возвращает значение элемента, указываемое итератором I<iter>.
=head1 СМ. ТАКЖЕ
L<BH>

514
doc/Manual/ru/BH_IO.pod Normal file
View File

@@ -0,0 +1,514 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_IO - Подсистема ввода-вывода
=head1 СИНТАКСИС
#include <BH/io.h>
BH_IO *io = BH_FileNew("input.txt", BH_FILE_WRITE | BH_FILE_TRUNCATE, NULL);
BH_IOWrite(io, "Hello, world!", 13, NULL);
BH_IOFree(io);
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
BH_IO предоставляет подсистему, позволяющей работать с различными объектами
(файлы, сокеты, память) через единый интерфейс ввода-вывода. Это позволяет
писать код, непривязанный к конкретной системе ввода-вывода.
Гарантируется, что любой объект BH_IO поддерживает следующие операции:
L</BH_IORead>, L</BH_IOWrite>, L</BH_IOCtl> и L</BH_IOCap>.
В зависимости от реализации того или иного объекта BH_IO, могут быть доступны
дополнительные операции: L</BH_IOFlags>, L</BH_IOClear>, L</BH_IOFlush>,
L</BH_IOSize>, L</BH_IOTell>, L</BH_IOSeek>, L</BH_IOPeek> и другие.
По-умолчанию подсистема ввода-вывода позволяет работать с файлами
(L</BH_FileNew>) или оперативной памятью (L</BH_BytesNew>), а также
буферизировать ввод-вывод (L</BH_BufferNew>).
=head1 РАСШИРЕНИЕ
BH_IO предоставляет разработчику возможность создавать собственные реализации
устройств ввода-вывода. Пример:
typedef struct BH_MyIO
{
BH_IO parent;
int flags;
};
static int ioDestroy(BH_MyIO *io)
{
/* Ommitted for the example */
}
static int ioRead(BH_MyIO *io,
BH_IOReadInfo *info)
{
/* Ommitted for the example */
}
static int ioWrite(BH_MyIO *io,
BH_IOWriteInfo *info)
{
/* Ommited for the example */
}
static int ioFlags(BH_MyIO *io,
int *flags)
{
*flags = io->flags;
return BH_OK;
}
static int ioCap(BH_MyIO *io,
int *op)
{
BH_UNUSED(io);
switch (*op)
{
case BH_IO_CTL_FLAGS:
return BH_OK;
default:
return BH_NOIMPL;
}
}
static int ioCtl(BH_MyIO *io,
BH_IOCtlInfo *info)
{
switch (info->op)
{
case BH_IO_CTL_FLAGS:
return ioFlags(io, (int *)info->arg);
default:
return BH_NOIMPL;
}
}
static int ioCallback(BH_MyIO *io,
int type,
void *arg)
{
switch (type)
{
case BH_IO_OP_DESTROY: return ioDestroy(io);
case BH_IO_OP_READ: return ioRead(io, (BH_IOReadInfo *)arg);
case BH_IO_OP_WRITE: return ioWrite(io, (BH_IOWriteInfo *)arg);
case BH_IO_OP_CTL: return ioCtl(io, (BH_IOCtlInfo *)arg);
case BH_IO_OP_CAP: return ioCap(io, (int*)arg);
default: return BH_NOIMPL;
}
}
BH_IO *BH_MyIONew(int *result)
{
BH_MyIO *io;
int code;
code = BH_OOM;
if ((io = malloc(sizeof(*io))))
{
io->parent.callback = (BH_IOCallback)ioCallback;
io->flags = 0;
}
if (result)
*result = code;
return (BH_IO*)io;
}
=head1 API ВЫЗОВЫ
=head2 BH_FileNew
BH_IO *BH_FileNew(const char *path,
int mode,
int *result);
Создает устройство ввода-вывода для работы с файлом по пути I<path>.
Параметр I<mode> может принимать комбинацию из следующих значений:
=over
=item B<BH_FILE_READ>
Открывает файл на чтение
=item B<BH_FILE_WRTIE>
Открывает файл на запись
=item B<BH_FILE_APPEND>
Открывает файл в режиме добавление в конец
=item B<BH_FILE_TRUNCATE>
Усекает файл
=item B<BH_FILE_CREATE>
Файл должен быть создан
=item B<BH_FILE_EXIST>
Файл должен существовать
=back
Опциональный параметр I<result> возвращает 0 или код ошибки.
Данная функция возвращает указатель на новый BH_IO объект или NULL.
=head2 BH_BufferNew
BH_IO *BH_BufferNew(BH_IO *device,
size_t size,
int *result);
Создает устройство ввода-вывода для буферизации данных к другому устройству
I<device>.
Параметр I<size> отвечает за размер буферов чтения и записи.
Опциональный параметр I<result> возвращает 0 или код ошибки.
В случае успеха, данная функция возвращает указатель на новый BH_IO объект или
NULL в случае ошибки.
=head2 BH_BytesNew
BH_IO *BH_BytesNew(char *data,
size_t size,
int *result);
Создает устройство ввода-вывода для региона памяти I<data> с размером I<size>.
Опциональный параметр I<result> возвращает код ошибки.
В случае успеха, данная функция возвращает указатель на новый BH_IO объект или
NULL в случае ошибки.
=head2 BH_IOFree
void BH_IOFree(BH_IO *device);
Уничтожает устройство ввода-вывода.
=head2 BH_IORead
int BH_IORead(BH_IO *device,
char *buffer,
size_t size,
size_t *actual);
Читает до I<size> байт из устройства ввода-вывода и записывает данные в
I<buffer>.
Опциональный параметр I<actual> возвращает число байт, которое было фактически
прочитано.
В случае успеха, данная функция возвращает 0 или код ошибки.
=head2 BH_IOWrite
int BH_IOWrite(BH_IO *io,
const char *buffer,
size_t size,
size_t *actual);
Записывает до I<size> байт в устройство ввода-вывода из I<buffer>.
Опциональный параметр I<actual> возвращает число байт, которое было записано.
В случае успеха, данная функция возвращает 0 или код ошибки.
=head2 BH_IOCtl
int BH_IOCtl(BH_IO *device,
int op,
void *arg);
Манипулирует параметрами устройства ввода-вывода с помощью команды I<op> и
параметра I<arg>.
Возможные значения I<op>:
=over
=item B<BH_IO_CTL_FLAGS>
Аргумент: int *
Вернуть флаги устройства ввода-вывода.
=item B<BH_IO_CTL_CLEAR>
Сбросить ошибки устройства ввода-вывода.
=item B<BH_IO_CTL_PEEK>
Аргумент: L<BH_IOReadInfo *|/BH_IOReadInfo>
Читает без извлечения данные из устройства ввода-вывода.
=item B<BH_IO_CTL_FLUSH>
Записать буферизированные данные в устройство ввода-вывода.
=item B<BH_IO_CTL_SIZE>
Аргумент: int64_t *
Получить размер устройства ввода-вывода.
=item B<BH_IO_CTL_TELL>
Аргумент: int64_t *
Читает текущее смещение указателя чтения устройства ввода-вывода.
=item B<BH_IO_CTL_SEEK>
Аргумент: L<BH_IOSeekInfo *|/BH_IOSeekInfo>
Изменяет текущее положение указателя чтения устройства ввода-вывода.
=item B<BH_IO_CTL_GET_IO>
Аргумент: L<BH_IO **|/BH_IO>|void *
Получает объект устройства, используемый в реализации.
=item B<BH_IO_CTL_SET_IO>
Аргумент: L<BH_IO *|/BH_IO>|void *
Устанавливает объект устройства, который будет использоваться в реализации.
=back
В случае успеха, данная функция возвращает 0 или код ошибки.
=head2 BH_IOCap
int BH_IOCap(BH_IO *device,
int op);
Проверяет возможность выполнения команды I<op> на устройстве ввода-вывода.
В случае успеха, данная функция возвращает 0 или код ошибки.
=head2 BH_IOFlags
int BH_IOFlags(BH_IO *device,
int *flags);
Возвращает текущие флаги I<flags> устройства ввода-вывода.
Возможные флаги (и их комбинации):
=over
=item B<BH_IO_FLAG_ERROR>
В процессе выполнения возникла ошибка.
=item B<BH_IO_FLAG_EOF>
Устройство достигло конца файла.
=back
В случае успеха, данная функция возвращает 0 или код ошибки.
=head2 BH_IOClear
int BH_IOClear(BH_IO *device);
Очищает устройство ввода-вывода от ошибок.
В случае успеха, данная функция возвращает 0 или код ошибки.
=head2 BH_IOPeek
int BH_IOPeek(BH_IO *device,
char *buffer,
size_t size,
size_t *actual);
Читает без извлечения до I<size> байт из устройства ввода-вывода и записывает
данные в I<buffer>.
Опциональный параметр I<actual> возвращает число байт, которое было фактически
прочитано.
В случае успеха, данная функция возвращает 0 или код ошибки.
=head2 BH_IOFlush
int BH_IOFlush(BH_IO *device);
Записывает буферизированные значения в устройство ввода-вывода.
В случае успеха, данная функция возвращает 0 или код ошибки.
=head2 BH_IOSize
int BH_IOSize(BH_IO *device,
int64_t *size);
Читает текущий размер устройства ввода-вывода в байтах и записывает значение в
I<size>.
Для различных типов устройств ввода-вывода данное значение может означать разные
вещи (к примеру: текущий размер файла, размер выделенной для ввода-вывода памяти
и т.д.).
В случае успеха, данная функция возвращает 0 или код ошибки.
=head2 BH_IOTell
int BH_IOTell(BH_IO *device,
int64_t *offset);
Читает текущее смещение указателя чтения устройства ввода-вывода относительно
начала и записывает значение в I<offset>.
В случае успеха, данная функция возвращает 0 или код ошибки.
=head2 BH_IOSeek
int BH_IOSeek(BH_IO *device,
int64_t offset,
int whence);
Изменяет текущее положение указателя чтения устройства ввода-вывода с учетом
смещения I<offset> и начальной позиции I<whence>.
Возможные значения начальной позиции I<whence>:
=over
=item B<BH_IO_SEEK_SET>
Смещение относительно начала устройства.
=item B<BH_IO_SEEK_CUR>
Смещение относительно текущей позиции устройства.
=item B<BH_IO_SEEK_END>
Смещение относительно конца устройства.
=back
В случае успеха, данная функция возвращает 0 или код ошибки.
=head2 BH_IOError
int BH_IOError(BH_IO *device);
Проверяет, находится ли устройство ввода-вывода в состоянии ошибки.
Данная функция эквивалентна следующему коду:
(BH_IOFlags(device) & BH_IO_FLAG_ERROR)
=head2 BH_IOEndOfFile
int BH_IOEndOfFile(BH_IO *device);
Проверяет, достигло ли устройство ввода-вывода конца.
Данная функция эквивалентна следующему коду:
(BH_IOFlags(device) & BH_IO_FLAG_EOF)
=head1 СТРУКТУРЫ ДАННЫХ
=head2 BH_IO
typedef struct BH_IO
{
BH_IOCallback callback;
} BH_IO;
=head2 BH_IOReadInfo
typedef struct BH_IOReadInfo
{
char *data;
size_t size;
size_t *actual;
} BH_IOReadInfo;
=head2 BH_IOWriteInfo
typedef struct BH_IOWriteInfo
{
const char *data;
size_t size;
size_t *actual;
} BH_IOWriteInfo;
=head2 BH_IOCtlInfo
typedef struct BH_IOCtlInfo
{
int op;
void *arg;
} BH_IOCtlInfo;
=head2 BH_IOSeekInfo
typedef struct BH_IOSeekInfo
{
int64_t offset;
int whence;
} BH_IOSeekInfo;
=head1 СМ. ТАКЖЕ
L<BH>

60
doc/Manual/ru/BH_Line.pod Normal file
View File

@@ -0,0 +1,60 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Line - прямая на плоскости.
=head1 СИНТАКСИС
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Line предоставляет функции для работы с прямыми на плоскости. Он
позволяет вычислять коэффициенты прямой по двум точкам, находить расстояние от
точки до прямой и определять ближайшую точку на прямой к заданной точке.
=head1 API ВЫЗОВЫ
=head2 BH_LineFromPoints
int BH_LineFromPoints(const float a[2],
const float b[2],
float out[3]);
Вычисляет коэффициенты прямой на плоскости по двум точкам I<a> и I<b>.
Параметр I<out> описывает результирующую прямую на плоскости.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head2 BH_LineDistance
float BH_LineDistance(const float line[3],
const float point[2]);
Вычисляет расстояние от точки I<point> до прямой I<line>.
=head2 BH_LineClosestPoint
void BH_LineClosestPoint(const float line[3],
const float point[2],
float out[2]);
Вычисляет ближайшую точку на прямой I<line> к другой точке I<point>.
Параметр I<out> описывает результирующую точку.
=head1 СМ. ТАКЖЕ
L<BH>

168
doc/Manual/ru/BH_Mat3f.pod Normal file
View File

@@ -0,0 +1,168 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Mat3f - вещественная матрица 3x3
=head1 СИНТАКСИС
#include <BH/Math/Mat3f.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Mat3f предоставляет набор функций для работы с вещественными матрицами
размером 3x3.
=head1 API ВЫЗОВЫ
=head2 BH_Mat3fIdentity
void BH_Mat3fIdentity(float out[9]);
Записывает единичную матрицу в I<out>.
=head2 BH_Mat3fAdd
void BH_Mat3fAdd(const float a[9],
const float b[9],
float out[9]);
Вычисляет сумму двух матриц I<a> и I<b>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat3fSub
void BH_Mat3fSub(const float a[9],
const float b[9],
float out[9]);
Вычисляет разность двух матриц I<a> и I<b>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat3fMul
void BH_Mat3fMul(const float a[9],
const float b[9],
float out[9]);
Вычисляет результат перемножения двух матриц I<a> и I<b>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat3fScale
void BH_Mat3fScale(const float a[9],
float b,
float out[9]);
Вычисляет результат умножения матрицы I<a> на значение I<b>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat3fTranspose
void BH_Mat3fTranspose(const float in[9],
float out[9]);
Транспонирует матрицу I<in>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat3fTrace
float BH_Mat3fTrace(const float in[9]);
Вычисляет сумму элементов главной диагонали матрицы I<in>.
=head2 BH_Mat3fDet
float BH_Mat3fDet(const float in[9]);
Вычисляет определитель матрицы I<in>.
=head2 BH_Mat3fInverse
int BH_Mat3fInverse(const float in[9],
float out[9]);
Вычисляет обратную матрицу для I<in>.
Параметр I<out> описывает результирующую матрицу.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head2 BH_Mat3fFromScale
void BH_Mat3fFromScale(float x,
float y,
float out[9]);
Вычисляет масштабирующую матрицу с масштабами I<x> и I<y>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat3fFromTranslation
void BH_Mat3fFromTranslation(float x,
float y,
float out[9]);
Вычисляет матрицу смещения со значениями I<x> и I<y>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat3fFromRotation
void BH_Mat3fFromRotation(float angle,
float out[9]);
Вычисляет матрицу вращения с заданным углом I<angle>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat3fApplyVec3f
void BH_Mat3fApplyVec3f(float a[9],
float b[3],
float out[3]);
Вычисляет результат перемножения матрицы I<a> и вектора I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Mat3fApplyVec2f
void BH_Mat3fApplyVec2f(float a[9],
float b[2],
float out[2]);
Вычисляет результат перемножения матрицы I<a> и вектора I<b>.
Параметр I<out> описывает результирующий вектор.
=head1 СМ. ТАКЖЕ
L<BH>

290
doc/Manual/ru/BH_Mat4f.pod Normal file
View File

@@ -0,0 +1,290 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Mat4f - вещественная матрица 4x4
=head1 СИНТАКСИС
#include <BH/Math/Mat4f.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Mat4f предоставляет набор функций для работы с вещественными матрицами
размером 4x4. Эти функции позволяют выполнять различные операции над матрицами,
такие как сложение, вычитание, умножение, транспонирование, вычисление
определителя и другие.
=head1 API ВЫЗОВЫ
=head2 BH_Mat4fIdentity
void BH_Mat4fIdentity(float out[16]);
Записывает единичную матрицу в I<out>.
=head2 BH_Mat4fAdd
void BH_Mat4fAdd(const float a[16],
const float b[16],
float out[16]);
Вычисляет сумму двух матриц I<a> и I<b>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fSub
void BH_Mat4fSub(const float a[16],
const float b[16],
float out[16]);
Вычисляет разность двух матриц I<a> и I<b>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fMul
void BH_Mat4fMul(const float a[16],
const float b[16],
float out[16]);
Вычисляет результат перемножения двух матриц I<a> и I<b>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fScale
void BH_Mat4fScale(const float a[16],
float b,
float out[16]);
Вычисляет результат умножения матрицы I<a> на значение I<b>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fTranspose
void BH_Mat4fTranspose(const float in[16],
float out[16]);
Транспонирует матрицу I<in>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fTrace
float BH_Mat4fTrace(const float in[16]);
Вычисляет сумму элементов главной диагонали матрицы I<in>.
=head2 BH_Mat4fDet
float BH_Mat4fDet(const float in[16]);
Вычисляет определитель матрицы I<in>.
=head2 BH_Mat4fInverse
int BH_Mat4fInverse(const float in[16],
float out[16]);
Вычисляет обратную матрицу для I<in>.
Параметр I<out> описывает результирующую матрицу.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head2 BH_Mat4fFromScale
void BH_Mat4fFromScale(float x,
float y,
float z,
float out[16]);
Вычисляет масштабирующую матрицу с масштабами I<x>, I<y> и I<z>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fFromTranslation
void BH_Mat4fFromTranslation(float x,
float y,
float z,
float out[16]);
Вычисляет матрицу смещения со значениями I<x>, I<y> и I<z>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fFromRotationX
void BH_Mat4fFromRotationX(float angle,
float out[16]);
Вычисляет матрицу вращения относительно оси X с заданным углом I<angle>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fFromRotationY
void BH_Mat4fFromRotationY(float angle,
float out[16]);
Вычисляет матрицу вращения относительно оси Y с заданным углом I<angle>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fFromRotationZ
void BH_Mat4fFromRotationZ(float angle,
float out[16]);
Вычисляет матрицу вращения относительно оси Z с заданным углом I<angle>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fFromAxis
void BH_Mat4fFromAxis(const float axis[3],
float angle,
float out[16]);
Вычисляет матрицу вращения относительно оси I<axis> с заданным углом I<angle>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fFromEuler
void BH_Mat4fFromEuler(float roll,
float pitch,
float yaw,
float out[16]);
Вычисляет матрицу вращения из углов связанной системы координат I<roll>,
I<pitch> и I<yaw>.
Порядок применения вращения ZYX (yaw, pitch, roll).
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fFromQuat4f
void BH_Mat4fFromQuat4f(const float in[4],
float out[16]);
Вычисляет матрицу вращения из кватерниона I<in>.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fFromOrtho
void BH_Mat4fFromOrtho(float xMin,
float xMax,
float yMin,
float yMax,
float zMin,
float zMax,
float out[16]);
Вычисляет матрицу ортографической проекции.
Параметры I<xMin> и I<xMax> определяют допустимый диапазон значений X
координат.
Параметры I<yMin> и I<yMax> определяют допустимый диапазон значений Y
координат.
Параметры I<zMin> и I<zMax> определяют допустимый диапазон значений Z
координат.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fFromFrustum
void BH_Mat4fFromFrustum(float fov,
float aspect,
float zMin,
float zMax,
float out[16]);
Вычисляет матрицу перспективной проекции.
Параметр I<fov> определяет угол обзора.
Параметр I<aspect> определяет соотношение сторон.
Параметры I<zMin> и I<zMax> определяют допустимый диапазон значений Z
координат.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fFromLookAt
void BH_Mat4fFromLookAt(const float position[3],
const float at[3],
const float up[3],
float out[16]);
Вычисляет видовую матрицу камеры.
Параметр I<position> определяет положение камеры в пространстве.
Параметр I<at> определяет точку, куда направлена камера.
Параметр I<up> определяет «верх» камеры.
Параметр I<out> описывает результирующую матрицу.
=head2 BH_Mat4fApplyVec4f
void BH_Mat4fApplyVec4f(const float a[16],
const float b[4],
float out[4]);
Вычисляет результат перемножения матрицы I<a> и вектора I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Mat4fApplyVec3f
void BH_Mat4fApplyVec3f(const float a[16],
const float b[3],
float out[3]);
Вычисляет результат перемножения матрицы I<a> и вектора I<b>.
Параметр I<out> описывает результирующий вектор.
=head1 СМ. ТАКЖЕ
L<BH>

48
doc/Manual/ru/BH_Math.pod Normal file
View File

@@ -0,0 +1,48 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Math - Математические функции
=head1 СИНТАКСИС
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Библиотека BH_Math предоставляет набор математических функций для различных
вычислений.
=head1 API ВЫЗОВЫ
=head2 BH_Lerpf
float BH_Lerpf(float a, float b, float t);
Интерполирует значение между I<a> и I<b> с заданным коэффициентом I<t>.
=head2 BH_Triangle3fBarycentric
void BH_Triangle3fBarycentric(const float a[3],
const float b[3],
const float c[3],
const float point[3],
float out[3]);
Вычисляет барицентрические координаты точки I<point> относительно треугольника,
заданного точками I<a>, I<b>, I<c>.
Параметр I<out> описывает результирующий вектор.
=head1 СМ. ТАКЖЕ
L<BH>

View File

@@ -0,0 +1,66 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Plane - Плоскость в пространстве
=head1 СИНТАКСИС
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Plane предоставляет функции для работы с плоскостями в трёхмерном
пространстве. Он позволяет вычислять коэффициенты плоскости по трём точкам,
определять расстояние от точки до плоскости и находить ближайшую точку на
плоскости к заданной точке.
=head1 API ВЫЗОВЫ
=head2 BH_PlaneFromPoints
int BH_PlaneFromPoints(const float a[3],
const float b[3],
const float c[3],
float out[4]);
Вычисляет коэффициенты плоскости по трём точкам I<a>, I<b>, I<c>.
Предполагается, что точки расположены в порядке по часовой стрелке.
Если точки образуют вырожденный треугольник, функция вернёт ошибку.
Параметр I<out> определяет результирующую плоскость.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head2 BH_PlaneDistance
float BH_PlaneDistance(const float plane[4],
const float point[3]);
Вычисляет расстояние от точки I<point> до плоскости I<plane>.
=head2 BH_PlaneClosestPoint
void BH_PlaneClosestPoint(const float plane[4],
const float point[3],
float out[3]);
Вычисляет ближайшую точку на плоскости I<plane> к другой точке I<point>.
Параметр I<out> описывает результирующую точку.
=head1 СМ. ТАКЖЕ
L<BH>

219
doc/Manual/ru/BH_Quat.pod Normal file
View File

@@ -0,0 +1,219 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Quat - Кватернион
=head1 СИНТАКСИС
#include <BH/Math/Quat.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Данный модуль предоставляет набор функций для работы с кватернионами.
Кватернионы используются для представления вращений в трёхмерном пространстве и
обладают преимуществами перед другими методами, такими как матрицы вращения или
углы Эйлера, в части устойчивости к накоплению ошибок при многократных операциях
вращения.
=head1 API ВЫЗОВЫ
=head2 BH_Quat4fAdd
#define BH_Quat4fAdd(a, b, out) \
BH_Vec4fAdd(a, b, out)
Вычисляет сумму двух кватернионов I<a> и I<b>.
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fSub
#define BH_Quat4fSub(a, b, out) \
BH_Vec4fSub(a, b, out)
Вычисляет разность двух кватернионов I<a> и I<b>.
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fScale
#define BH_Quat4fScale(a, b, out) \
BH_Vec4fScale(a, b, out)
Вычисляет результат умножения кватерниона I<a> на значение I<b>.
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fNegate
#define BH_Quat4fNegate(in, out) \
BH_Vec4fNegate(in, out)
Вычисляет противоположный кватернион от кватерниона I<in>.
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fDot
#define BH_Quat4fDot(a, b) \
BH_Vec4fDot(a, b)
Вычисляет скалярное произведение кватернионов I<a> и I<b>.
=head2 BH_Quat4fLength
#define BH_Quat4fLength(in) \
BH_Vec4fLength(in)
float BH_Vec4fLength(const float in[4]);
Вычисляет длину кватерниона I<in>.
=head2 BH_Quat4fNormal
#define BH_Quat4fNormal(in, out) \
BH_Vec4fNormal(in, out)
Вычисляет нормализованную форму кватерниона I<in>.
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fLerp
#define BH_Quat4fLerp(a, b, t, out) \
BH_Vec4fLerp(a, b, t, out)
Выполняет линейную интерполяцию между двумя кватернионами I<a> и I<b> с
параметром I<t>.
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fIdentity
void BH_Quat4fIdentity(float out[4]);
Записывает единичный кватернион в I<out>.
=head2 BH_Quat4fConjugate
void BH_Quat4fConjugate(const float in[4],
float out[4]);
Вычисляет сопряжённый кватернион из I<in>.
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fInverse
void BH_Quat4fInverse(const float in[4],
float out[4]);
Вычисляет обратный кватернион из I<in>.
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fMul
void BH_Quat4fMul(const float a[4],
const float b[4],
float out[4]);
Вычисляет результат перемножения двух кватернионов I<a> и I<b>.
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fSlerp
void BH_Quat4fSlerp(const float a[4],
const float b[4],
float t,
float out[4]);
Выполняет сферическую линейную интерполяцию между двумя кватернионами I<a> и
I<b> с параметром I<t>.
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fFromEuler
void BH_Quat4fFromEuler(float roll,
float pitch,
float yaw,
float out[4]);
Вычисляет кватернион из углов связанной системы координат I<roll>, I<pitch> и
I<yaw>.
Порядок применения вращения ZYX (yaw, pitch, roll).
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fFromAxis
void BH_Quat4fFromAxis(const float axis[3],
float angle,
float out[4]);
Вычисляет кватернион из вращения относительно оси I<axis> с заданным углом
I<angle>.
Параметр I<out> описывает результирующий кватернион.
=head2 BH_Quat4fToEuler
void BH_Quat4fToEuler(const float in[4],
float *roll,
float *pitch,
float *yaw);
Вычисляет углы связанной системы координат I<roll>, I<pitch> и I<yaw> из
кватерниона I<in>.
Порядок применения вращения ZYX (yaw, pitch, roll).
=head2 BH_Quat4fToAxis
void BH_Quat4fToAxis(const float in[4],
float axis[3],
float *angle);
Вычисляет ось вращения I<axis> и угол I<angle> из кватерниона I<in>.
=head2 BH_Quat4fToMat4f
void BH_Quat4fToMat4f(const float in[4],
float out[16]);
Вычисляет матрицу вращения из кватерниона I<in>.
Параметр I<out> описывает результирующую матрицу.
=head1 СМ. ТАКЖЕ
L<BH>

137
doc/Manual/ru/BH_Queue.pod Normal file
View File

@@ -0,0 +1,137 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Queue - контейнер очереди
=head1 СИНТАКСИС
#include <BH/Queue.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Queue предоставляет реализацию контейнера очереди, который позволяет
добавлять элементы в конец и извлекать их из начала. Очередь основана на
динамическом массиве, что обеспечивает эффективное использование памяти и
быстрый доступ к элементам.
=head1 API ВЫЗОВЫ
=head2 BH_QueueNew
BH_Queue *BH_QueueNew(void);
Создаёт очередь.
В случае успеха функция возвращает указатель на новый объект BH_Queue,
или NULL в случае ошибки.
=head2 BH_QueueFree
void BH_QueueFree(BH_Queue *queue);
Уничтожает очередь.
=head2 BH_QueueClear
void BH_QueueClear(BH_Queue *queue);
Очищает очередь.
=head2 BH_QueueReserve
int BH_QueueReserve(BH_Queue *queue,
size_t size);
Резервирует место как минимум для I<size> элементов.
Вызов этой функции делает существующие итераторы недействительными.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head2 BH_QueueInsert
int BH_QueueInsert(BH_Queue *queue,
void *value);
Вставляет элемент I<value>.
Вызов этой функции делает существующие итераторы недействительными.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head2 BH_QueueRemove
void BH_QueueRemove(BH_Queue *queue);
Удаляет первый элемент из очереди.
Вызов этой функции делает существующие итераторы недействительными.
=head2 BH_QueueFront
int BH_QueueFront(BH_Queue *queue,
void **value);
Возвращает первый элемент очереди.
Параметр I<value> возвращает значение элемента.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head2 BH_QueueEmpty
int BH_QueueEmpty(BH_Queue *queue);
Проверяет, является ли очередь пустой.
=head2 BH_QueueSize
size_t BH_QueueSize(BH_Queue *queue);
Возвращает количество элементов.
=head2 BH_QueueCapacity
size_t BH_QueueCapacity(BH_Queue *queue);
Возвращает ёмкость.
=head2 BH_QueueIterNext
void *BH_QueueIterNext(BH_Queue *queue, void *iter);
Возвращает итератор на следующий элемент.
Опциональный параметр I<iter> принимает итератор на текущий элемент.
В случае успеха функция возвращает итератор или NULL.
=head2 BH_QueueIterValue
void *BH_QueueIterValue(void *iter);
Возвращает значение элемента, указываемое итератором I<iter>.
=head1 СМ. ТАКЖЕ
L<BH>

202
doc/Manual/ru/BH_Ray2f.pod Normal file
View File

@@ -0,0 +1,202 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Ray2f, BH_Segment2f - Луч/сегмент на плоскости
=head1 СИНТАКСИС
#include <BH/Math/Ray2f.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Данный модуль предоставляет функции для работы с лучами и сегментами на
плоскости. Он включает в себя функции для проверки пересечений между лучами,
сегментами, прямыми и ограничивающими прямоугольниками.
=head1 API ВЫЗОВЫ
=head2 BH_Ray2fIntersectLine
int BH_Ray2fIntersectLine(const float start[2],
const float direction[2],
const float line[3],
float *t,
float out[2]);
Проверяет пересечение между лучом и прямой.
Параметры I<start> и I<direction> описывают луч.
Параметр I<line> описывает прямую.
Параметр I<t> описывает результирующее время пересечения луча.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head2 BH_Ray2fIntersectTime
int BH_Ray2fIntersectTime(const float aStart[2],
const float aDirection[2],
const float bStart[2],
const float bDirection[2],
float *time1,
float *time2);
Вычисляет время пересечения между двумя лучами.
Параметры I<aStart> и I<aDirection> описывают первый луч.
Параметры I<bStart> и I<bDirection> описывают второй луч.
Параметр I<time1> описывает результирующее время пересечения первого луча.
Параметр I<time2> описывает результирующее время пересечения второго луча.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head2 BH_Ray2fIntersectRay
int BH_Ray2fIntersectRay(const float aStart[2],
const float aDirection[2],
const float bStart[2],
const float bDirection[2],
float *t,
float out[2]);
Проверяет пересечение между двумя лучами.
Параметры I<aStart> и I<aDirection> описывают первый луч.
Параметры I<bStart> и I<bDirection> описывают второй луч.
Параметр I<t> описывает результирующее время пересечения первого луча.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head2 BH_Ray2fIntersectSegment
int BH_Ray2fIntersectSegment(const float aStart[2],
const float aDirection[2],
const float bStart[2],
const float bEnd[2],
float *t,
float out[2]);
Проверяет пересечение между лучом и сегментом.
Параметры I<aStart> и I<aDirection> описывают луч.
Параметры I<bStart> и I<bEnd> описывают сегмент.
Параметр I<t> описывает результирующее время пересечения луча.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head2 BH_Segment2fIntersectLine
int BH_Segment2fIntersectLine(const float start[2],
const float end[2],
const float line[3],
float *t,
float out[2]);
Проверяет пересечение между сегментом и прямой.
Параметры I<start> и I<end> описывают сегмент.
Параметр I<line> описывают прямую.
Параметр I<t> описывает результирующее время пересечения сегмента.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head2 BH_Segment2fIntersectSegment
int BH_Segment2fIntersectSegment(const float aStart[2],
const float aEnd[2],
const float bStart[2],
const float bEnd[2],
float *t,
float out[2]);
Проверяет пересечение между двумя сегментами.
Параметры I<aStart> и I<aEnd> описывают первый сегмент.
Параметры I<bStart> и I<bEnd> описывают второй сегмент.
Параметр I<t> описывает результирующее время пересечения первого сегмента.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head2 BH_Ray2fIntersectBox2f
int BH_Ray2fIntersectBox2f(const float aStart[2],
const float aDirection[2],
const float bMin[2],
const float bMax[2],
float *t,
float out[2]);
Проверяет пересечение между лучом и ограничивающим прямоугольником.
Параметры I<aStart> и I<aDirection> описывают луч.
Параметры I<bMin> и I<bMax> описывают ограничивающий прямоугольник.
Параметр I<t> описывает результирующее время пересечения луча.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head2 BH_Segment2fIntersectBox2f
int BH_Segment2fIntersectBox2f(const float aStart[2],
const float aEnd[2],
const float bMin[2],
const float bMax[2],
float *t,
float out[2]);
Проверяет пересечение между сегментом и ограничивающим прямоугольником.
Параметры I<aStart> и I<aEnd> описывают сегмент.
Параметры I<bMin> и I<bMax> описывают ограничивающий прямоугольник.
Параметр I<t> описывает результирующее время пересечения сегмента.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в противном случае - код ошибки.
=head1 СМ. ТАКЖЕ
L<BH>

161
doc/Manual/ru/BH_Ray3f.pod Normal file
View File

@@ -0,0 +1,161 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Ray3f, BH_Segment3f - луч/сегмент в пространстве
=head1 СИНТАКСИС
#include <BH/Math/Ray3f.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Данный модуль предоставляет функции для работы с лучами и сегментами в
трёхмерном пространстве. Он включает в себя методы для проверки пересечений
лучей и сегментов с плоскостями, треугольниками и ограничивающими
прямоугольниками.
=head1 API ВЫЗОВЫ
=head2 BH_Ray3fIntersectPlane
int BH_Ray3fIntersectPlane(const float start[3],
const float direction[3],
const float plane[4],
float *t,
float out[3]);
Проверяет пересечение между лучом и плоскостью.
Параметры I<start> и I<direction> описывают луч.
Параметр I<plane> описывает плоскость.
Параметр I<t> описывает результирующее время пересечения луча.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head2 BH_Ray3fIntersectTriangle
int BH_Ray3fIntersectTriangle(const float start[3],
const float direction[3],
const float a[3],
const float b[3],
const float c[3],
float *t,
float out[3]);
Проверяет пересечение между лучом и треугольником.
Параметры I<start> и I<direction> описывают луч.
Параметры I<a>, I<b>, I<c> описывают точки треугольника.
Параметр I<t> описывает результирующее время пересечения луча.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head2 BH_Segment3fIntersectPlane
int BH_Segment3fIntersectPlane(const float start[3],
const float end[3],
const float plane[4],
float *t,
float out[3]);
Проверяет пересечение между сегментом и плоскостью.
Параметры I<start> и I<end> описывают сегмент.
Параметр I<plane> описывает плоскость.
Параметр I<t> описывает результирующее время пересечения сегмента.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head2 BH_Segment3fIntersectTriangle
int BH_Segment3fIntersectTriangle(const float start[3],
const float end[3],
const float a[3],
const float b[3],
const float c[3],
float *t,
float out[3]);
Проверяет пересечение между сегментом и треугольником.
Параметры I<start> и I<end> описывают сегмент.
Параметры I<a>, I<b>, I<c> описывают точки треугольника.
Параметр I<t> описывает результирующее время пересечения луча.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head2 BH_Ray3fIntersectBox3f
int BH_Ray3fIntersectBox3f(const float aStart[3],
const float aDirection[3],
const float bMin[3],
const float bMax[3],
float *t,
float out[3]);
Проверяет пересечение между лучом и ограничивающим прямоугольником.
Параметры I<aStart> и I<aDirection> описывают луч.
Параметры I<bMin> и I<bMax> описывают ограничивающий прямоугольник.
Параметр I<t> описывает результирующее время пересечения первого сегмента.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head2 BH_Segment3fIntersectBox3f
int BH_Segment3fIntersectBox3f(const float aStart[3],
const float aEnd[3],
const float bMin[3],
const float bMax[3],
float *t,
float out[3]);
Проверяет пересечение между сегментом и ограничивающим прямоугольником.
Параметры I<aStart> и I<aEnd> описывают сегмент.
Параметры I<bMin> и I<bMax> описывают ограничивающий прямоугольник.
Параметр I<t> описывает результирующее время пересечения первого сегмента.
Параметр I<out> описывает результирующую точку пересечения.
В случае успеха функция возвращает 0, в случае ошибки - код ошибки.
=head1 СМ. ТАКЖЕ
L<BH>

373
doc/Manual/ru/BH_String.pod Normal file
View File

@@ -0,0 +1,373 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_String - Работа со строками
=head1 СИНТАКСИС
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Библиотека BH_String предоставляет набор функций для работы со строками, включая
преобразование чисел в строки и обратно.
=head1 ОПРЕДЛЕНИЕ ОСНОВАНИЯ
В функциях семейства I<StringToInt> присутсвует алгоритм определения основания
числа по префиксам строки:
=over
=item *
Если префикс I<0b> - основние 2
=item *
Если префикс I<0> - основние 8
=item *
Если префикс I<0x> - основние 16
=item *
Иначе - основание 10
=back
=head1 API ВЫЗОВЫ
=head2 BH_StringFromDouble
int BH_StringFromDouble(char *string,
size_t size,
double value,
char format,
int precision,
size_t *actual);
Форматирует вещественное число I<value> в нуль-терминированную строку I<string>
(с ограничением по длинне I<size>).
Параметр I<format> задает формат преобразования числа в строку. Допустимые
форматы:
=over
=item B<f>, B<F>
Фиксированный формат: [-]ddd.ddd
=item B<e>, B<E>
Научный формат: [-]d.dddedd
=item B<g>, B<G>
Фиксированный или научный формат, в зависимости от того, какой из них короче
=back
Параметр I<precision> задает точность преобразования числа в строку. Если
значение точности отрицательное, преобразование будет выполнено с минимально
необходимой точностью, чтобы при обратном преобразовании получилось исходное
число.
Опциональный параметр I<actual> возвращает длину записанной строки.
Данная функция следует правилу IEEE 754 округление до четного.
В случае успеха, возвращает 0 или код ошибки.
=head2 BH_StringFromInt8s
int BH_StringFromInt8s(char *string,
size_t size,
int8_t value,
int base,
size_t *actual);
Форматирует целое 8-битное знаковое число I<value> в нуль-терминированную строку
I<string> (с ограничением по длинне I<size>).
Параметр I<base> задает основание для преобразования.
Опциональный параметр I<actual> возвращает длину записанной строки.
В случае успеха, возвращает 0 или код ошибки.
=head2 BH_StringFromInt16s
int BH_StringFromInt16s(char *string,
size_t size,
int16_t value,
int base,
size_t *actual);
Форматирует целое 16-битное знаковое число I<value> в нуль-терминированную
строку I<string> (с ограничением по длинне I<size>).
Параметр I<base> задает основание для преобразования.
Опциональный параметр I<actual> возвращает длину записанной строки.
В случае успеха, возвращает 0 или код ошибки.
=head2 BH_StringFromInt32s
int BH_StringFromInt32s(char *string,
size_t size,
int32_t value,
int base,
size_t *actual);
Форматирует целое 32-битное знаковое число I<value> в нуль-терминированную
строку I<string> (с ограничением по длинне I<size>).
Параметр I<base> задает основание для преобразования.
Опциональный параметр I<actual> возвращает длину записанной строки.
В случае успеха, возвращает 0 или код ошибки.
=head2 BH_StringFromInt64s
int BH_StringFromInt64s(char *string,
size_t size,
int64_t value,
int base,
size_t *actual);
Форматирует целое 64-битное знаковое число I<value> в нуль-терминированную
строку I<string> (с ограничением по длинне I<size>).
Параметр I<base> задает основание для преобразования.
Опциональный параметр I<actual> возвращает длину записанной строки.
В случае успеха, возвращает 0 или код ошибки.
=head2 BH_StringFromInt8u
int BH_StringFromInt8u(char *string,
size_t size,
uint8_t value,
int base,
size_t *actual);
Форматирует целое 8-битное беззнаковое число I<value> в нуль-терминированную
строку I<string> (с ограничением по длинне I<size>).
Параметр I<base> задает основание для преобразования.
Опциональный параметр I<actual> возвращает длину записанной строки.
В случае успеха, возвращает 0 или код ошибки.
=head2 BH_StringFromInt16u
int BH_StringFromInt16u(char *string,
size_t size,
uint16_t value,
int base,
size_t *actual);
Форматирует целое 16-битное беззнаковое число I<value> в нуль-терминированную
строку I<string> (с ограничением по длинне I<size>).
Параметр I<base> задает основание для преобразования.
Опциональный параметр I<actual> возвращает длину записанной строки.
В случае успеха, возвращает 0 или код ошибки.
=head2 BH_StringFromInt32u
int BH_StringFromInt32u(char *string,
size_t size,
uint32_t value,
int base,
size_t *actual);
Форматирует целое 32-битное беззнаковое число I<value> в нуль-терминированную
строку I<string> (с ограничением по длинне I<size>).
Параметр I<base> задает основание для преобразования.
Опциональный параметр I<actual> возвращает длину записанной строки.
В случае успеха, возвращает 0 или код ошибки.
=head2 BH_StringFromInt64u
int BH_StringFromInt64u(char *string,
size_t size,
uint64_t value,
int base,
size_t *actual);
Форматирует целое 64-битное беззнаковое число I<value> в нуль-терминированную
строку I<string> (с ограничением по длинне I<size>).
Параметр I<base> задает основание для преобразования.
Опциональный параметр I<actual> возвращает длину записанной строки.
В случае успеха, возвращает 0 или код ошибки.
=head2 BH_StringToDouble
double BH_StringToDouble(const char *string,
size_t *size);
Преобразовывает строку I<string> в вещественное число.
Опциональный параметр I<size> возвращает число прочитанных символов из строки.
В случае успеха, возвращает преобразованное число или 0.
=head2 BH_StringToInt8s
int8_t BH_StringToInt8s(const char *string,
size_t *size,
int base);
Преобразовывает строку I<string> в целое знаковое 8-битное число.
Опциональный параметр I<size> возвращает число прочитанных символов из строки.
Опциональный параметр I<base> задает основание числа.
В случае успеха, возвращает преобразованное число или 0.
=head2 BH_StringToInt16s
int16_t BH_StringToInt16s(const char *string,
size_t *size,
int base);
Преобразовывает строку I<string> в целое знаковое 16-битное число.
Опциональный параметр I<size> возвращает число прочитанных символов из строки.
Опциональный параметр I<base> задает основание числа.
В случае успеха, возвращает преобразованное число или 0.
=head2 BH_StringToInt32s
int32_t BH_StringToInt32s(const char *string,
size_t *size,
int base);
Преобразовывает строку I<string> в целое знаковое 32-битное число.
Опциональный параметр I<size> возвращает число прочитанных символов из строки.
Опциональный параметр I<base> задает основание числа.
В случае успеха, возвращает преобразованное число или 0.
=head2 BH_StringToInt64s
int64_t BH_StringToInt64s(const char *string,
size_t *size,
int base);
Преобразовывает строку I<string> в целое знаковое 64-битное число.
Опциональный параметр I<size> возвращает число прочитанных символов из строки.
Опциональный параметр I<base> задает основание числа.
В случае успеха, возвращает преобразованное число или 0.
=head2 BH_StringToInt8u
uint8_t BH_StringToInt8u(const char *string,
size_t *size,
int base);
Преобразовывает строку I<string> в целое беззнаковое 8-битное число.
Опциональный параметр I<size> возвращает число прочитанных символов из строки.
Опциональный параметр I<base> задает основание числа.
В случае успеха, возвращает преобразованное число или 0.
=head2 BH_StringToInt16u
uint16_t BH_StringToInt16u(const char *string,
size_t *size,
int base);
Преобразовывает строку I<string> в целое беззнаковое 16-битное число.
Опциональный параметр I<size> возвращает число прочитанных символов из строки.
Опциональный параметр I<base> задает основание числа.
В случае успеха, возвращает преобразованное число или 0.
=head2 BH_StringToInt32u
uint32_t BH_StringToInt32u(const char *string,
size_t *size,
int base);
Преобразовывает строку I<string> в целое беззнаковое 32-битное число.
Опциональный параметр I<size> возвращает число прочитанных символов из строки.
Опциональный параметр I<base> задает основание числа.
В случае успеха, возвращает преобразованное число или 0.
=head2 BH_StringToInt64u
uint64_t BH_StringToInt64u(const char *string,
size_t *size,
int base);
Преобразовывает строку I<string> в целое беззнаковое 64-битное число.
Опциональный параметр I<size> возвращает число прочитанных символов из строки.
Опциональный параметр I<base> задает основание числа.
В случае успеха, возвращает преобразованное число или 0.
=head1 СМ. ТАКЖЕ
L<BH>

289
doc/Manual/ru/BH_Thread.pod Normal file
View File

@@ -0,0 +1,289 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Thread - многопоточность и примитивы синхронизации
=head1 СИНТАКСИС
#include <BH/Thread.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Библиотека BH_Thread предоставляет набор функций для работы с многопоточностью
и синхронизацией потоков. Она включает в себя функции для создания и управления
потоками, работы с мьютексами, семафорами, условными переменными и спинлоками.
=head1 API ВЫЗОВЫ
=head2 BH_ThreadNew
BH_Thread *BH_ThreadNew(size_t stack,
BH_ThreadCallback callback,
void *data);
Создаёт поток с заданным размером стека I<stack>, исполняемой функцией
I<callback> и данными I<data>.
В случае успеха возвращает указатель на объект потока, иначе NULL.
=head2 BH_ThreadJoin
int BH_ThreadJoin(BH_Thread *thread);
Блокирует исполнение текущего потока до завершения другого потока.
По завершении выполнения потока ресурсы I<thread> освобождаются.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_ThreadDetach
int BH_ThreadDetach(BH_Thread *thread);
Отсоединяет поток от текущего процесса.
По завершении выполнения потока ресурсы I<thread> освобождаются.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_MutexNew
BH_Mutex *BH_MutexNew(void);
Создаёт мьютекс.
В случае успеха возвращает указатель на объект мьютекса, иначе NULL.
=head2 BH_MutexFree
void BH_MutexFree(BH_Mutex *mutex);
Уничтожает мьютекс.
Если мьютекс захвачен, поведение не определено.
=head2 BH_MutexLock
int BH_MutexLock(BH_Mutex *mutex);
Захватывает мьютекс.
Если мьютекс уже был захвачен, поведение не определено.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_MutexUnlock
int BH_MutexUnlock(BH_Mutex *mutex);
Отпускает мьютекс.
Если мьютекс захвачен другим потоком, поведение не определено.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_MutexLockTry
int BH_MutexLockTry(BH_Mutex *mutex);
Производит попытку захвата мьютекса.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_SemaphoreNew
BH_Semaphore *BH_SemaphoreNew(int value);
Создаёт семафор с заданным изначальным значением I<value>.
В случае успеха возвращает указатель на объект семафора, иначе NULL.
=head2 BH_SemaphoreFree
void BH_SemaphoreFree(BH_Semaphore *semaphore);
Уничтожает семафор.
=head2 BH_SemaphorePost
int BH_SemaphorePost(BH_Semaphore *semaphore);
Увеличивает значение семафора на 1.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_SemaphoreWait
int BH_SemaphoreWait(BH_Semaphore *semaphore);
Уменьшает значение семафора на 1.
Если значение семафора равно 0, блокирует выполнение текущего потока до тех пор,
пока значение семафора не станет больше 0.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_SemaphoreWaitTry
int BH_SemaphoreWaitTry(BH_Semaphore *semaphore);
Пытается уменьшить значение семафора на 1.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_SemaphoreWaitFor
int BH_SemaphoreWaitFor(BH_Semaphore *semaphore,
uint32_t timeout);
Пытается уменьшить значение семафора на 1 в пределах заданного времени
I<timeout>.
Параметр I<timeout> задаёт время ожидания в миллисекундах.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_ConditionNew
BH_Condition *BH_ConditionNew(void);
Создаёт новую условную переменную.
В случае успеха возвращает указатель на объект условной переменной, иначе NULL.
=head2 BH_ConditionFree
void BH_ConditionFree(BH_Condition *condition);
Уничтожает условную переменную.
Если условная переменная используется другими потоками, поведение не определено.
=head2 BH_ConditionWait
int BH_ConditionWait(BH_Condition *condition,
BH_Mutex *mutex);
Блокирует исполнение текущего потока до тех пор, пока другой поток не
просигнализирует об изменении условия.
В некоторых ситуациях сигнал об изменении условия может быть ложным.
Параметр I<mutex> определяет мьютекс, который используется совместно с условной
переменной.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_ConditionWaitFor
int BH_ConditionWaitFor(BH_Condition *condition,
BH_Mutex *mutex,
uint32_t timeout);
Пытается заблокировать исполнение текущего потока до тех пор, пока другой поток
не просигнализирует об изменении условия в пределах заданного времени
I<timeout>.
В некоторых ситуациях сигнал об изменении условия может быть ложным.
Параметр I<mutex> определяет мьютекс, который используется совместно с условной
переменной.
Параметр I<timeout> задаёт время ожидания в миллисекундах.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_ConditionSignal
int BH_ConditionSignal(BH_Condition *condition);
Сигнализирует одному ожидающему потоку об изменении условия.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_ConditionBroadcast
int BH_ConditionBroadcast(BH_Condition *condition);
Сигнализирует всем ожидающим потокам об изменении условия.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_SpinlockLock
void BH_SpinlockLock(int *lock);
Блокирует спинлок.
=head2 BH_SpinlockLockTry
int BH_SpinlockLockTry(int *lock);
Пытается заблокировать спинлок.
В случае успеха возвращает 0, иначе код ошибки.
=head2 BH_SpinlockUnlock
void BH_SpinlockUnlock(int *lock);
Разблокирует спинлок.
=head2 BH_TssCreate
int BH_TssCreate(BH_GenericCallback callback);
Создаёт новый TSS/TLS индекс с функцией очистки I<callback>.
В случае успеха возвращает TSS/TLS индекс, иначе код ошибки.
=head2 BH_TssRead
void *BH_TssRead(int index);
Читает данные из слота TSS/TLS.
=head2 BH_TssWrite
void BH_TssWrite(int index,
void *value);
Записывает данные I<value> в слот TSS/TLS.
=head1 СМ. ТАКЖЕ
L<BH>

View File

@@ -0,0 +1,184 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Unicode - Работа с Unicode и UTF кодировками
=head1 СИНТАКСИС
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Библиотека BH_Unicode предоставляет набор функций для работы с различными
кодировками Unicode, включая UTF-8, UTF-16 и UTF-32. Она позволяет
преобразовывать символы в верхний и нижний регистр, а также кодировать и
декодировать строки в указанных кодировках.
=head1 API ВЫЗОВЫ
=head2 BH_UnicodeLower
uint32_t BH_UnicodeLower(uint32_t unit);
Преобразует Unicode-код I<unit> в нижний регистр.
Преобразование выполняется для символов в Basic Multilingual Plane (т. е. первые
65 536 кодов).
=head2 BH_UnicodeUpper
uint32_t BH_UnicodeUpper(uint32_t unit);
Преобразует Unicode-код I<unit> в верхний регистр.
Преобразование выполняется для символов в Basic Multilingual Plane (т. е. первые
65 536 кодов).
=head2 BH_UnicodeDecodeUtf8
size_t BH_UnicodeDecodeUtf8(const char *string,
size_t size,
uint32_t *unit);
Декодирует UTF-8 последовательность из I<string> (с заданной длиной I<size>) и
записывает код в I<unit>.
Недопустимые последовательности UTF-8 будут преобразованы к коду -1.
В случае успеха функция возвращает количество прочитанных байтов или 0, если
I<string> содержит только часть последовательности.
=head2 BH_UnicodeEncodeUtf8
size_t BH_UnicodeEncodeUtf8(uint32_t unit,
char *string);
Кодирует UTF-8 последовательность в I<string> из кода I<unit>.
Предполагается, что строка содержит 4 байта свободного места.
В случае успеха функция возвращает количество записанных байтов или 0.
=head2 BH_UnicodeDecodeUtf16LE
size_t BH_UnicodeDecodeUtf16LE(const char *string,
size_t size,
uint32_t *unit);
Декодирует UTF-16LE последовательность из I<string> (с заданной длиной I<size>)
и записывает код в I<unit>.
Недопустимые последовательности UTF-16LE будут преобразованы к коду -1.
В случае успеха функция возвращает количество прочитанных байтов или 0, если
I<string> содержит только часть последовательности.
=head2 BH_UnicodeDecodeUtf16BE
size_t BH_UnicodeDecodeUtf16BE(const char *string,
size_t size,
uint32_t *unit);
Декодирует UTF-16BE последовательность из I<string> (с заданной длиной I<size>)
и записывает код в I<unit>.
Недопустимые последовательности UTF-16BE будут преобразованы к коду -1.
В случае успеха функция возвращает количество прочитанных байтов или 0, если
I<string> содержит только часть последовательности.
=head2 BH_UnicodeEncodeUtf16LE
size_t BH_UnicodeEncodeUtf16LE(uint32_t unit,
char *string);
Кодирует UTF-16LE последовательность в I<string> из кода I<unit>.
Предполагается, что строка содержит 4 байта свободного места.
В случае успеха функция возвращает количество записанных байтов или 0.
=head2 BH_UnicodeEncodeUtf16BE
size_t BH_UnicodeEncodeUtf16BE(uint32_t unit,
char *string);
Кодирует UTF-16BE последовательность в I<string> из кода I<unit>.
Предполагается, что строка содержит 4 байта свободного места.
В случае успеха функция возвращает количество записанных байтов или 0.
=head2 BH_UnicodeDecodeUtf32LE
size_t BH_UnicodeDecodeUtf32LE(const char *string,
size_t size,
uint32_t *unit);
Декодирует UTF-32LE последовательность из I<string> (с заданной длиной I<size>)
и записывает код в I<unit>.
Недопустимые последовательности UTF-32LE будут преобразованы к коду -1.
В случае успеха функция возвращает количество прочитанных байтов или 0, если
I<string> содержит только часть последовательности.
=head2 BH_UnicodeDecodeUtf32BE
size_t BH_UnicodeDecodeUtf32BE(const char *string,
size_t size,
uint32_t *unit);
Декодирует UTF-32BE последовательность из I<string> (с заданной длиной I<size>)
и записывает код в I<unit>.
Недопустимые последовательности UTF-32BE будут преобразованы к коду -1.
В случае успеха функция возвращает количество прочитанных байтов или 0, если
I<string> содержит только часть последовательности.
=head2 BH_UnicodeEncodeUtf32LE
size_t BH_UnicodeEncodeUtf32LE(uint32_t unit,
char *string);
Кодирует UTF-32LE последовательность в I<string> из кода I<unit>.
Предполагается, что строка содержит 4 байта свободного места.
В случае успеха функция возвращает количество записанных байтов или 0.
=head2 BH_UnicodeEncodeUtf32BE
size_t BH_UnicodeEncodeUtf32BE(uint32_t unit,
char *string);
Кодирует UTF-32BE последовательность в I<string> из кода I<unit>.
Предполагается, что строка содержит 4 байта свободного места.
В случае успеха функция возвращает количество записанных байтов или 0.
=head1 СМ. ТАКЖЕ
L<BH>

241
doc/Manual/ru/BH_Util.pod Normal file
View File

@@ -0,0 +1,241 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Util - Вспомогательные функции
=head1 СИНТАКСИС
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Библиотека BH_Util предоставляет набор функций для работы с числами в форматах
little-endian и big-endian, а также для классификации значений с плавающей
точкой.
=head1 API ВЫЗОВЫ
=head2 BH_ClassifyDouble
int BH_ClassifyDouble(double value);
Классифицирует значение с плавающей точкой.
Данная функция возвращает комбинацию из следующих значений:
=over
=item B<BH_FP_NORMAL>
Значение является нормальным или субнормальным.
=item B<BH_FP_ZERO>
Значение является положительным или отрицательным нулём.
=item B<BH_FP_INFINITE>
Значение является положительной или отрицательной бесконечностью.
=item B<BH_FP_NAN>
Значение не является числом (NaN).
=item B<BH_FP_NEGATIVE>
Значение является отрицательным.
=back
=head2 BH_Read16LEu
uint16_t BH_Read16LEu(const char *buffer);
Считывает целое 16-битное беззнаковое little-endian число из буфера.
=head2 BH_Read16LEs
int16_t BH_Read16LEs(const char *buffer);
Считывает целое 16-битное знаковое little-endian число из буфера.
=head2 BH_Read32LEu
uint32_t BH_Read32LEu(const char *buffer);
Считывает целое 32-битное беззнаковое little-endian число из буфера.
=head2 BH_Read32LEs
int32_t BH_Read32LEs(const char *buffer);
Считывает целое 32-битное знаковое little-endian число из буфера.
=head2 BH_Read64LEu
uint64_t BH_Read64LEu(const char *buffer);
Считывает целое 64-битное беззнаковое little-endian число из буфера.
=head2 BH_Read64LEs
int64_t BH_Read64LEs(const char *buffer);
Считывает целое 64-битное знаковое little-endian число из буфера.
=head2 BH_Read16BEu
uint16_t BH_Read16BEu(const char *buffer);
Считывает целое 16-битное беззнаковое big-endian число из буфера.
=head2 BH_Read16BEs
int16_t BH_Read16BEs(const char *buffer);
Считывает целое 16-битное знаковое big-endian число из буфера.
=head2 BH_Read32BEu
uint32_t BH_Read32BEu(const char *buffer);
Считывает целое 32-битное беззнаковое big-endian число из буфера.
=head2 BH_Read32BEs
int32_t BH_Read32BEs(const char *buffer);
Считывает целое 32-битное знаковое big-endian число из буфера.
=head2 BH_Read64BEu
uint64_t BH_Read64BEu(const char *buffer);
Считывает целое 64-битное беззнаковое big-endian число из буфера.
=head2 BH_Read64BEs
int64_t BH_Read64BEs(const char *buffer);
Считывает целое 64-битное знаковое big-endian число из буфера.
=head2 BH_Write16LEu
void BH_Write16LEu(char *buffer,
uint16_t value);
Записывает целое 16-битное беззнаковое little-endian число в буфер.
=head2 BH_Write16LEs
void BH_Write16LEs(char *buffer,
int16_t value);
Записывает целое 16-битное знаковое little-endian число в буфер.
=head2 BH_Write32LEu
void BH_Write32LEu(char *buffer,
uint32_t value);
Записывает целое 32-битное беззнаковое little-endian число в буфер.
=head2 BH_Write32LEs
void BH_Write32LEs(char *buffer,
int32_t value);
Записывает целое 32-битное знаковое little-endian число в буфер.
=head2 BH_Write64LEu
void BH_Write64LEu(char *buffer,
uint64_t value);
Записывает целое 64-битное беззнаковое little-endian число в буфер.
=head2 BH_Write64LEs
void BH_Write64LEs(char *buffer,
int64_t value);
Записывает целое 64-битное знаковое little-endian число в буфер.
=head2 BH_Write16BEu
void BH_Write16BEu(char *buffer,
uint16_t value);
Записывает целое 16-битное беззнаковое big-endian число в буфер.
=head2 BH_Write16BEs
void BH_Write16BEs(char *buffer,
int16_t value);
Записывает целое 16-битное знаковое big-endian число в буфер.
=head2 BH_Write32BEu
void BH_Write32BEu(char *buffer,
uint32_t value);
Записывает целое 32-битное беззнаковое big-endian число в буфер.
=head2 BH_Write32BEs
void BH_Write32BEs(char *buffer,
int32_t value);
Записывает целое 32-битное знаковое big-endian число в буфер.
=head2 BH_Write64BEu
void BH_Write64BEu(char *buffer,
uint64_t value);
Записывает целое 64-битное беззнаковое big-endian число в буфер.
=head2 BH_Write64BEs
void BH_Write64BEs(char *buffer,
int64_t value);
Записывает целое 64-битное знаковое big-endian число в буфер.
=head1 СМ. ТАКЖЕ
L<BH>

201
doc/Manual/ru/BH_Vec2f.pod Normal file
View File

@@ -0,0 +1,201 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Vec2f - двухмерный вещественный вектор
=head1 СИНТАКСИС
#include <BH/Math/Vec2f.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Vec2f предоставляет набор функций для работы с двухмерными
векторами. Он включает в себя операции сложения, вычитания, умножения,
масштабирования, вычисления скалярного и векторного произведения, а также
нормализации векторов.
=head1 API ВЫЗОВЫ
=head2 BH_Vec2fAdd
void BH_Vec2fAdd(const float a[2],
const float b[2],
float out[2]);
Вычисляет сумму двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fSub
void BH_Vec2fSub(const float a[2],
const float b[2],
float out[2]);
Вычисляет разность двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fMul
void BH_Vec2fMul(const float a[2],
const float b[2],
float out[2]);
Вычисляет результат перемножения двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fScale
void BH_Vec2fScale(const float a[2],
float b,
float out[2]);
Вычисляет результат умножения вектора I<a> на значение I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fMulAdd
void BH_Vec2fMulAdd(const float a[2],
const float b[2],
const float c[2],
float out[2]);
Вычисляет результат суммы I<c> и произведения векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fNegate
void BH_Vec2fNegate(const float in[2],
float out[2]);
Вычисляет противоположный вектор от вектора I<in>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fDot
float BH_Vec2fDot(const float a[2],
const float b[2]);
Вычисляет скалярное произведение векторов I<a> и I<b>.
=head2 BH_Vec2fCross
float BH_Vec2fCross(const float a[2],
const float b[2]);
Вычисляет векторное произведение векторов I<a> и I<b>.
=head2 BH_Vec2fLength
float BH_Vec2fLength(const float in[2]);
Вычисляет длину вектора I<in>.
=head2 BH_Vec2fNormal
void BH_Vec2fNormal(const float in[2],
float out[2]);
Вычисляет нормализованную форму вектора I<in>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fNormalEx
float BH_Vec2fNormalEx(const float in[2],
float out[2]);
Вычисляет нормализованную форму вектора I<in> и возвращает его исходную длину.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fMin
void BH_Vec2fMin(const float a[2],
const float b[2],
float out[2]);
Вычисляет поэлементный минимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fMax
void BH_Vec2fMax(const float a[2],
const float b[2],
float out[2]);
Вычисляет поэлементный максимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fLerp
void BH_Vec2fLerp(const float a[2],
const float b[2],
float t,
float out[2]);
Выполняет линейную интерполяцию между двумя векторами I<a> и I<b> с параметром
I<t>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fProject
void BH_Vec2fProject(const float a[2],
const float b[2],
float out[2]);
Вычисляет результат проекции вектора I<a> на вектор I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2fBarycentric
void BH_Vec2fBarycentric(const float a[2],
const float b[2],
const float c[2],
float v,
float w,
float out[2]);
Вычисляет вектор из барицентрических координат I<v>, I<w> и векторов точек I<a>,
I<b>, I<c>.
Вычисление происходит по формуле A + v*(B-A) + w*(C-A).
Параметр I<out> описывает результирующий вектор.
=head1 СМ. ТАКЖЕ
L<BH>

115
doc/Manual/ru/BH_Vec2i.pod Normal file
View File

@@ -0,0 +1,115 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Vec2i - двухмерный целочисленный вектор
=head1 СИНТАКСИС
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Vec2i предоставляет набор функций для работы с двухмерными
целочисленными векторами.
=head1 API ВЫЗОВЫ
=head2 BH_Vec2iAdd
void BH_Vec2iAdd(const int a[2],
const int b[2],
int out[2]);
Вычисляет сумму двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2iSub
void BH_Vec2iSub(const int a[2],
const int b[2],
int out[2]);
Вычисляет разность двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2iMul
void BH_Vec2iMul(const int a[2],
const int b[2],
int out[2]);
Вычисляет результат перемножения двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2iScale
void BH_Vec2iScale(const int a[2],
int b,
int out[2]);
Вычисляет результат умножения вектора I<a> на значение I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2iMulAdd
void BH_Vec2iMulAdd(const int a[2],
const int b[2],
const int c[2],
int out[2]);
Вычисляет результат суммы I<c> и результата перемножения векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2iNegate
void BH_Vec2iNegate(const int in[2],
int out[2]);
Вычисляет противоположный вектор от вектора I<in>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2iMin
void BH_Vec2iMin(const int a[2],
const int b[2],
int out[2]);
Вычисляет поэлементный минимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec2iMax
void BH_Vec2iMax(const int a[2],
const int b[2],
int out[2]);
Вычисляет поэлементный максимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head1 СМ. ТАКЖЕ
L<BH>

202
doc/Manual/ru/BH_Vec3f.pod Normal file
View File

@@ -0,0 +1,202 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Vec3f - трёхмерный вещественный вектор
=head1 СИНТАКСИС
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Vec3f предоставляет набор функций для работы с трёхмерными
векторами. Функции позволяют выполнять арифметические операции, вычислять
скалярные и векторные произведения, нормализовать векторы, а также выполнять
другие операции над векторами.
=head1 API ВЫЗОВЫ
=head2 BH_Vec3fAdd
void BH_Vec3fAdd(const float a[3],
const float b[3],
float out[3]);
Вычисляет сумму двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fSub
void BH_Vec3fSub(const float a[3],
const float b[3],
float out[3]);
Вычисляет разность двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fMul
void BH_Vec3fMul(const float a[3],
const float b[3],
float out[3]);
Вычисляет результат перемножения двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fScale
void BH_Vec3fScale(const float a[3],
float b,
float out[3]);
Вычисляет результат умножения вектора I<a> на значение I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fMulAdd
void BH_Vec3fMulAdd(const float a[3],
const float b[3],
const float c[3],
float out[3]);
Вычисляет результат суммы I<c> и результата перемножения векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fNegate
void BH_Vec3fNegate(const float in[3],
float out[3]);
Вычисляет противоположный вектор от вектора I<in>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fDot
float BH_Vec3fDot(const float a[3],
const float b[3]);
Вычисляет скалярное произведение векторов I<a> и I<b>.
=head2 BH_Vec3fCross
void BH_Vec3fCross(const float a[3],
const float b[3],
float out[3]);
Вычисляет векторное произведение векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fLength
float BH_Vec3fLength(const float in[3]);
Вычисляет длину вектора I<in>.
=head2 BH_Vec3fNormal
void BH_Vec3fNormal(const float in[3],
float out[3]);
Вычисляет нормализованную форму вектора I<in>.
=head2 BH_Vec3fNormalEx
float BH_Vec3fNormalEx(const float in[3],
float out[3]);
Вычисляет нормализованную форму вектора I<in> и возвращает его исходную длину.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fMin
void BH_Vec3fMin(const float a[3],
const float b[3],
float out[3]);
Вычисляет поэлементный минимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fMax
void BH_Vec3fMax(const float a[3],
const float b[3],
float out[3]);
Вычисляет поэлементный максимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fLerp
void BH_Vec3fLerp(const float a[3],
const float b[3],
float t,
float out[3]);
Выполняет линейную интерполяцию между двумя векторами I<a> и I<b> с параметром
I<t>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fProject
void BH_Vec3fProject(const float a[3],
const float b[3],
float out[3]);
Вычисляет результат проекции вектора I<a> на вектор I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3fBarycentric
void BH_Vec3fBarycentric(const float a[3],
const float b[3],
const float c[3],
float v,
float w,
float out[3]);
Вычисляет вектор из барицентрических координат I<v>, I<w> и векторов точек I<a>,
I<b>, I<c>.
Вычисление происходит по формуле A + v*(B-A) + w*(C-A).
Параметр I<out> описывает результирующий вектор.
=head1 СМ. ТАКЖЕ
L<BH>

115
doc/Manual/ru/BH_Vec3i.pod Normal file
View File

@@ -0,0 +1,115 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Vec3i - трёхмерный целочисленный вектор
=head1 СИНТАКСИС
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Vec3i предоставляет набор функций для работы с трёхмерными
целочисленными векторами.
=head1 API ВЫЗОВЫ
=head2 BH_Vec3iAdd
void BH_Vec3iAdd(const int a[3],
const int b[3],
int out[3]);
Вычисляет сумму двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3iSub
void BH_Vec3iSub(const int a[3],
const int b[3],
int out[3]);
Вычисляет разность двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3iMul
void BH_Vec3iMul(const int a[3],
const int b[3],
int out[3]);
Вычисляет результат перемножения двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3iScale
void BH_Vec3iScale(const int a[3],
int b,
int out[3]);
Вычисляет результат умножения вектора I<a> на значение I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3iMulAdd
void BH_Vec3iMulAdd(const int a[3],
const int b[3],
const int c[3],
int out[3]);
Вычисляет результат суммы I<c> и результата перемножения векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3iNegate
void BH_Vec3iNegate(const int in[3],
int out[3]);
Вычисляет противоположный вектор от вектора I<in>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3iMin
void BH_Vec3iMin(const int a[3],
const int b[3],
int out[3]);
Вычисляет поэлементный минимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec3iMax
void BH_Vec3iMax(const int a[3],
const int b[3],
int out[3]);
Вычисляет поэлементный максимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head1 СМ. ТАКЖЕ
L<BH>

193
doc/Manual/ru/BH_Vec4f.pod Normal file
View File

@@ -0,0 +1,193 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Vec4f - четырёхмерный вещественный вектор
=head1 СИНТАКСИС
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Vec4f предоставляет набор функций для работы с четырёхмерными
векторами. Функции позволяют выполнять арифметические операции, нормализацию,
вычисление скалярного произведения и другие математические операции над
векторами.
=head1 API ВЫЗОВЫ
=head2 BH_Vec4fAdd
void BH_Vec4fAdd(const float a[4],
const float b[4],
float out[4]);
Вычисляет сумму двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fSub
void BH_Vec4fSub(const float a[4],
const float b[4],
float out[4]);
Вычисляет разность двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fMul
void BH_Vec4fMul(const float a[4],
const float b[4],
float out[4]);
Вычисляет результат перемножения двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fScale
void BH_Vec4fScale(const float a[4],
float b,
float out[4]);
Вычисляет результат умножения вектора I<a> на значение I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fMulAdd
void BH_Vec4fMulAdd(const float a[4],
const float b[4],
const float c[4],
float out[4]);
Вычисляет результат суммы I<c> и результата перемножения векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fNegate
void BH_Vec4fNegate(const float in[4],
float out[4]);
Вычисляет противоположный вектор от вектора I<in>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fDot
float BH_Vec4fDot(const float a[4],
const float b[4]);
Вычисляет скалярное произведение векторов I<a> и I<b>.
=head2 BH_Vec4fLength
float BH_Vec4fLength(const float in[4]);
Вычисляет длину вектора I<in>.
=head2 BH_Vec4fNormal
void BH_Vec4fNormal(const float in[4],
float out[4]);
Вычисляет нормализованную форму вектора I<in>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fNormalEx
float BH_Vec4fNormalEx(const float in[4],
float out[4]);
Вычисляет нормализованную форму вектора I<in> и возвращает его исходную длину.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fMin
void BH_Vec4fMin(const float a[4],
const float b[4],
float out[4]);
Вычисляет поэлементный минимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fMax
void BH_Vec4fMax(const float a[4],
const float b[4],
float out[4]);
Вычисляет поэлементный максимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fLerp
void BH_Vec4fLerp(const float a[4],
const float b[4],
float t,
float out[4]);
Выполняет линейную интерполяцию между двумя векторами I<a> и I<b> с параметром
I<t>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fProject
void BH_Vec4fProject(const float a[4],
const float b[4],
float out[4]);
Вычисляет результат проекции вектора I<a> на вектор I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4fBarycentric
void BH_Vec4fBarycentric(const float a[4],
const float b[4],
const float c[4],
float v,
float w,
float out[4]);
Вычисляет вектор из барицентрических координат I<v>, I<w> и векторов точек I<a>,
I<b>, I<c>.
Вычисление происходит по формуле A + v*(B-A) + w*(C-A).
Параметр I<out> описывает результирующий вектор.
=head1 СМ. ТАКЖЕ
L<BH>

115
doc/Manual/ru/BH_Vec4i.pod Normal file
View File

@@ -0,0 +1,115 @@
=encoding UTF-8
=head1 НАИМЕНОВАНИЕ
BH_Vec4i - четырёхмерный целочисленный вектор
=head1 СИНТАКСИС
#include <BH/Math.h>
cc prog.c -o prog -lbh
=head1 ОПИСАНИЕ
Модуль BH_Vec4i предоставляет набор функций для работы с четырёхмерными
целочисленными векторами.
=head1 API ВЫЗОВЫ
=head2 BH_Vec4iAdd
void BH_Vec4iAdd(const int a[4],
const int b[4],
int out[4]);
Вычисляет сумму двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4iSub
void BH_Vec4iSub(const int a[4],
const int b[4],
int out[4]);
Вычисляет разность двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4iMul
void BH_Vec4iMul(const int a[4],
const int b[4],
int out[4]);
Вычисляет результат перемножения двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4iScale
void BH_Vec4iScale(const int a[4],
int b,
int out[4]);
Вычисляет результат умножения вектора I<a> на значение I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4iMulAdd
void BH_Vec4iMulAdd(const int a[4],
const int b[4],
const int c[4],
int out[4]);
Вычисляет результат суммы I<c> и результата перемножения векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4iNegate
void BH_Vec4iNegate(const int in[4],
int out[4]);
Вычисляет противоположный вектор от вектора I<in>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4iMin
void BH_Vec4iMin(const int a[4],
const int b[4],
int out[4]);
Вычисляет поэлементный минимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head2 BH_Vec4iMax
void BH_Vec4iMax(const int a[4],
const int b[4],
int out[4]);
Вычисляет поэлементный максимум двух векторов I<a> и I<b>.
Параметр I<out> описывает результирующий вектор.
=head1 СМ. ТАКЖЕ
L<BH>

155
doc/Manual/style.css Normal file
View File

@@ -0,0 +1,155 @@
/* CSS to make pod2html files look a little bit better. */
body {
margin-left: 4em;
}
body p, body ul, ol, body dl {
margin-left: 2em;
width: 41em;
}
pre {
width: 41em;
}
li {
padding-bottom: 0.5em;
}
/* Code sections. */
pre {
background-color: #f8f8f8;
color: rgb(204,0,0);
font-weight: 550;
border-left: 6px solid rgb(204,64,64);
padding: 6px;
margin-left: 1em;
font-size: 120%;
}
/* Bold, italic in man pages. */
b, strong {
color: rgb(204,0,0);
}
i, em {
color: rgb(204,0,0);
}
/* Name heading. */
body > h1:first-of-type {
display: none;
}
body > h1:first-of-type + p {
font-size: 125%;
font-weight: bold;
color: rgb(204,0,0);
margin-left: -32px;
}
/* Warning heading in man pages. */
a[name="warning"] {
-moz-border-radius-topleft: 5px;
-moz-border-radius-topright: 5px;
border-radius-topleft: 5px;
border-radius-topright: 5px;
color: white;
background-color: rgb(204,0,0);
}
a[name="warning"]:before {
content: "\00a0\00a0\00a0";
}
a[name="warning"]:after {
content: "\00a0\00a0\00a0";
}
/* Put the index on the right hand side in a floating box. */
ul[id="index"] {
float: right;
width: 18em;
border-left: 3em solid white;
background-color: #fcfcfc;
margin-top: 32px;
padding-top: 0px;
margin-left: 1em;
padding-left: 1em;
padding-right: 1em;
font-size: 90%;
}
ul[id="index"] a[href] {
text-decoration: none;
}
ul[id="index"] a[href]:hover {
text-decoration: underline;
}
ul[id="index"] a[href]:before {
content: '#\00a0';
color: rgb(204,0,0);
font-size: x-small;
}
ul[id="index"] {
width: 17em;
list-style: none;
margin-left: 0px;
margin-right: 0px;
padding-left: 0px;
padding-right: 0px;
}
ul[id="index"] > li {
margin-bottom: 0.5em;
}
ul[id="index"] > li ul {
width: 16em;
list-style: none;
margin-left: 0px;
margin-right: 0px;
padding-left: 0px;
padding-right: 0px;
margin-bottom: 0.5em;
}
ul[id="index"] > li ul li {
display: inline;
margin-right: 1em;
}
/*
ul[id="index"] > li ul li:after {
color: #ccc;
content: '\2014';
}
*/
/* Get rid of those horrible <hr>'s :-( */
hr { display: none; }
/* Demote <h1>'s and set rest of headers relative. */
h1 {
font-size: 100%;
color: black;
border-bottom: solid 1px rgb(204,0,0);
}
h2 {
font-size: 95%;
border-bottom: none;
}
h3 {
font-size: 90%;
}
h4 {
font-size: 85%;
}

View File

@@ -5,32 +5,11 @@
#include "Common.h"
/**
* Exchanges values between \a src and \a dest elements of sizze \a size.
*
* \param dest Destination element pointer
* \param src Source element pointer
* \param size Element size in bytes
*/
void BH_Swap(void *dest,
void *src,
size_t size);
/**
* Partitions the \a array (with specified \a size and \a element size)
* relative to specified \a pivot element.
*
* The \a pivot element can be part of the partitioned \a array.
*
* \param pivot Pivot element pointer
* \param array Array pointer
* \param size Array size
* \param element Array element size
* \param equal Comparision function
*
* \return Pointer to the first element of the second partition.
*/
void *BH_Partition(void *pivot,
void *array,
size_t size,
@@ -38,65 +17,24 @@ void *BH_Partition(void *pivot,
BH_EqualCallback equal);
/**
* Sorts the \a array (with specified \a size and \a element size).
*
* The sorting algorithm is implementation defined and may change between
* revisions.
*
* \param array Array pointer
* \param size Array size
* \param element Array element size
* \param equal Comparision function
*/
void BH_Sort(void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
/**
* Heapifies an \a array (with specified \a size and \a element size).
*
* \param array Array pointer
* \param size Array size
* \param element Array element size
* \param equal Comparision function
*/
void BH_HeapMake(void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
/**
* Removes top value from the heapified \a array (with specified \a size
* and \a element size).
*
* \param array Array pointer
* \param size Array size
* \param element Array element size
* \param equal Comparasion function
*/
void BH_HeapRemove(void *array,
size_t size,
size_t element,
BH_EqualCallback equal);
/**
* Inserts new \a value into heapified \a array in an array (with specified
* \a size and \a element size)
*
* If \a value pointer is NULL, it is assumed that new value is placed at the
* end of the array.
*
* \param value Value pointer
* \param array Array pointer
* \param size Array size
* \param element Array element size
* \param equal Comparasion function
*/
void BH_HeapInsert(void *value,
void *array,
size_t size,
@@ -104,19 +42,6 @@ void BH_HeapInsert(void *value,
BH_EqualCallback equal);
/**
* Removes top value from heapified \a array (with specified \a size and
* \a element size) and inserts new \a value.
*
* If value pointer is NULL, it is assumed that new value is placed at the
* end of the array.
*
* \param value Value pointer
* \param array Array pointer
* \param size Array size
* \param element Array element size
* \param equal Comparasion function
*/
void BH_HeapReplace(void *value,
void *array,
size_t size,

View File

@@ -24,32 +24,6 @@ typedef struct BH_ArgsOption
typedef int (*BH_ArgsCallback)(int key, char *arg, void *data);
/**
* Parses command line \a options (given by \a argc and \a argv) and calls the
* specified \a callback with \a data.
*
* There are few internal rules:
* - If the "--" argument is specified, option parsing stops, and the rest of
* the arguments are processed as is.
* - If the "-" argument is specified, it is processed as is.
* - For long options, if a value is required, the string after the equal sign
* or the next argument will be used as the value ("--define=Value" or
* "--define Value").
* - For short options, if a value is required, the string after the option
* letter or the next argument will be used as the value ("-DValue" or
* "-D Value").
*
* Options array should have last element filled with zeros.
*
* \param argc Arguments count
* \param argv Arguments array
* \param options Options array pointer
* \param callback Callback function
* \param data Callback data
*
* \return On success, returns zero value.
* \return On failure, returns error code.
*/
int BH_ArgsParse(int argc,
char **argv,
BH_ArgsOption *options,
@@ -57,12 +31,6 @@ int BH_ArgsParse(int argc,
void *data);
/**
* Prints documentation for \a options (with specified \a padding).
*
* \param options Options array pointer
* \param padding Padding
*/
void BH_ArgsHelp(BH_ArgsOption *options,
int padding);

View File

@@ -8,215 +8,82 @@
typedef struct BH_Hashmap BH_Hashmap;
/**
* Creates the new hashmap with specified \a equal and \a hash callbacks.
*
* \param equal Comparision function
* \param hash Key hash function
*
* \return On success, returns hashmap pointer.
* \return On failure, returns a null pointer.
*/
BH_Hashmap *BH_HashmapNew(BH_EqualCallback equal,
BH_HashCallback hash);
/**
* Destroys the \a hashmap.
*
* \param hashmap Hashmap pointer
*/
void BH_HashmapFree(BH_Hashmap *hashmap);
/**
* Clears the \a hashmap.
*
* \param hashmap Hashmap pointer
*/
void BH_HashmapClear(BH_Hashmap *hashmap);
/**
* Reserves space for \a size amount of elements in the \a hashmap.
*
* This function can both expand and shrink the available space in hashmap.
* This function takes into account current hashmap load factor.
*
* \param hashmap Hahsmap pointer
* \param size Capacity
*
* \note Calling this function will invalidate iterators.
* \note Actual hashmap capacity can be bigger then requested.
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_HashmapReserve(BH_Hashmap *hashmap,
size_t size);
/**
* Inserts the pair \a key \a value pair into the \a hashmap.
*
* \param hashmap Hashmap pointer
* \param key Key
* \param value Value
*
* \note This function allows duplicates to be inserted.
* \note Calling this function will invalidate iterators.
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_HashmapInsert(BH_Hashmap *hashmap,
void *key,
void *value);
/**
* Removes value from the \a hashmap by \a key.
*
* \param hashmap Hashmap pointer
* \param key Key
*
* \note Calling this function will invalidate iterators.
* \note If hashmap contains several elements with the same key, this function
* will remove only one key-value pair.
*/
void BH_HashmapRemove(BH_Hashmap *hashmap,
void *key);
/**
* Returns \a value from the \a hashmap by \a key.
*
* \param hashmap Hashmap pointer
* \param key Key
* \param value Value (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_HashmapAt(BH_Hashmap *hashmap,
void *key,
void **value);
/**
* Checks if the \a hashmap is empty.
*
* \param hashmap Hashmap pointer
*
* \return If hashmap is empty, returns non-zero value
* \return If hashmap is not empty, returns zero
*/
int BH_HashmapEmpty(BH_Hashmap *hashmap);
/**
* Returns the size of the \a hashmap.
*
* \param hashmap Hashmap pointer
*
* \return Returns the size of the hashmap.
*/
size_t BH_HashmapSize(BH_Hashmap *hashmap);
/**
* Returns the capacity of the \a hashmap.
*
* \param hashmap Hashmap pointer
*
* \return Returns the capacity of the hashmap.
*/
size_t BH_HashmapCapacity(BH_Hashmap *hashmap);
/**
* Returns the load factor of the \a hashmap.
*
* \param hashmap Hashmap pointer
*
* \return Returns the load factor of the hashmap.
*/
float BH_HashmapFactor(BH_Hashmap *hashmap);
/**
* Sets the load \a factor of the \a hashmap.
*
* \param hashmap Hashmap pointer
* \param factor Load factor
*
* \note New load factor will be applied on the next reserve/insert operation.
*/
void BH_HashmapSetFactor(BH_Hashmap *hashmap,
float factor);
/**
* Returns the iterator to the element in the \a hashmap by \a key.
*
* \param hashmap Hashmap pointer
* \param iter Iterator
*
* \return On success, returns iterator value.
* \return On failure, returns NULL pointer.
*
* \note If hashmap contains several elements with the same key, this function
* will return iterator to one of them
*/
void *BH_HashmapIterAt(BH_Hashmap *hashmap,
void *key);
/**
* Returns next element \a iter in the \a hashmap.
*
* If \a iter is NULL pointer, then this function will return iter to the
* first element of the hashmap.
*
* \param hashmap Hashmap pointer
* \param iter Iterator
*
* \return On success, returns new iterator value for the next element.
* \return On failure, returns NULL pointer.
*/
void *BH_HashmapIterNext(BH_Hashmap *hashmap,
void *iter);
/**
* Removes key-value from the \a hashmap pointed by \a iter.
*
* \param hashmap Hashmap pointer
* \param iter Iterator
*
* \note Calling this function will invalidate iterators.
*/
void BH_HashmapIterRemove(BH_Hashmap *hashmap,
void *iter);
/**
* Returns key, pointed by the \a iter.
*
* \param iter Iterator
*
* \return Returns key.
*/
void *BH_HashmapIterKey(void *iter);
/**
* Returns value, pointed by the \a iter.
*
* \param iter Iterator
*
* \return Returns value.
*/
void *BH_HashmapIterValue(void *iter);

View File

@@ -81,231 +81,77 @@ typedef struct BH_IOSeekInfo
} BH_IOSeekInfo;
/**
* Creates an input/output device representing a file at the given \a path.
*
* \param path File path
* \param mode Open mode
* \param result Result code
*
* \return On success, returns IO device pointer.
* \return On failure, returns NULL pointer.
*/
BH_IO *BH_FileNew(const char *path,
int mode,
int *result);
/**
* Creates an input/output deivce that buffers access to other \a device.
*
* \param device IO device pointer
* \param size Buffer size
* \param result Result code
*
* \return On success, returns IO device pointer.
* \return On failure, returns NULL pointer.
*/
BH_IO *BH_BufferNew(BH_IO *device,
size_t size,
int *result);
/**
* Creates an input/output devices that access memory buffer.
*
* \param data Buffer pointer
* \param size Buffer size
* \param result Result code
*
* \return On success, returns IO device pointer.
* \return On failure, returns NULL pointer.
*/
BH_IO *BH_BytesNew(char *data,
size_t size,
int *result);
/**
* Destroys the input/output \a device.
*
* \param device IO device pointer
*/
void BH_IOFree(BH_IO *device);
/**
* Reads up to \a size bytes from the \a device into \a buffer.
*
* \param device IO device pointer
* \param buffer Buffer pointer
* \param size Buffer size
* \param actual Bytes read (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_IORead(BH_IO *device,
char *buffer,
size_t size,
size_t *actual);
/**
* Writes up to \a size bytes to the \a device from \a buffer.
*
* \param io IO device pointer
* \param buffer Buffer pointer
* \param size Buffer size
* \param actual Bytes written (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_IOWrite(BH_IO *io,
const char *buffer,
size_t size,
size_t *actual);
/**
* Manupulates an input/output \a device with specific \a op and and \a arg.
*
* \param device IO device pointer
* \param op Operation
* \param arg Argument
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_IOCtl(BH_IO *device,
int op,
void *arg);
/**
* Checks if an input/output \a device supports specific \a op.
*
* \param device IO device pointer
* \param op Operation
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_IOCap(BH_IO *device,
int op);
/**
* Peeks up to \a size bytes from the \a device into \a buffer.
*
* \param device IO device pointer
* \param buffer Buffer pointer
* \param size Buffer size
* \param actial Bytes peeked (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_IOPeek(BH_IO *device,
char *buffer,
size_t size,
size_t *actual);
/**
* Tells current \a offset in the \a device.
*
* \param device IO device pointer
* \param offset Position
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_IOTell(BH_IO *device,
int64_t *offset);
/**
* Seeks to specified \a offset and \a whence in the \a device.
*
* \param device IO device pointer
* \param offset Position
* \param whence Direction
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_IOSeek(BH_IO *device,
int64_t offset,
int whence);
/**
* Flushes the internal buffers of the \a device.
*
* \param device IO device pointer
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_IOFlush(BH_IO *device);
/**
* Returns total or available size of the \a device.
*
* \param device IO pointer
* \param size Available/total size
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_IOSize(BH_IO *device,
int64_t *size);
/**
* Returns flags of the \a device.
*
* \param device IO device pointer
* \param flags Flags
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_IOFlags(BH_IO *device,
int *flags);
/**
* Returns error flag of the \a device.
*
* \param device IO device pointer
*
* \return Returns error flag.
*/
int BH_IOError(BH_IO *device);
/**
* Returns end-of-file flag of the \a device.
*
* \param device IO device pointer
*
* \return Returns end-of-file flag.
*/
int BH_IOEndOfFile(BH_IO *device);
/**
* Clears errors of the \a device.
*
* \param device IO device pointer
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_IOClear(BH_IO *device);

File diff suppressed because it is too large Load Diff

37
include/BH/Math/Box2f.h Normal file
View File

@@ -0,0 +1,37 @@
#ifndef BH_MATH_BOX2F_H
#define BH_MATH_BOX2F_H
#include "../Common.h"
void BH_Box2fUnion(const float aMin[2],
const float aMax[2],
const float bMin[2],
const float bMax[2],
float outMin[2],
float outMax[2]);
int BH_Box2fIntersect(const float aMin[2],
const float aMax[2],
const float bMin[2],
const float bMax[2],
float outMin[2],
float outMax[2]);
int BH_Box2fContains(const float aMin[2],
const float aMax[2],
const float point[2]);
int BH_Box2fEnclose(const float *points,
size_t size,
float outMin[2],
float outMax[2]);
#endif /* BH_MATH_BOX2F_H */

37
include/BH/Math/Box3f.h Normal file
View File

@@ -0,0 +1,37 @@
#ifndef BH_MATH_BOX3F_H
#define BH_MATH_BOX3F_H
#include "../Common.h"
void BH_Box3fUnion(const float aMin[3],
const float aMax[3],
const float bMin[3],
const float bMax[3],
float outMin[3],
float outMax[3]);
int BH_Box3fIntersect(const float aMin[3],
const float aMax[3],
const float bMin[3],
const float bMax[3],
float outMin[3],
float outMax[3]);
int BH_Box3fContains(const float aMin[3],
const float aMax[3],
const float point[3]);
int BH_Box3fEnclose(const float *points,
size_t size,
float outMin[3],
float outMax[3]);
#endif /* BH_MATH_BOX3F_H */

23
include/BH/Math/Line.h Normal file
View File

@@ -0,0 +1,23 @@
#ifndef BH_MATH_LINE_H
#define BH_MATH_LINE_H
#include "../Common.h"
int BH_LineFromPoints(const float a[2],
const float b[2],
float out[3]);
float BH_LineDistance(const float line[3],
const float point[2]);
void BH_LineClosestPoint(const float line[3],
const float point[2],
float out[2]);
#endif /* BH_MATH_LINE_H */

81
include/BH/Math/Mat3f.h Normal file
View File

@@ -0,0 +1,81 @@
#ifndef BH_MATH_MAT3F_H
#define BH_MATH_MAT3F_H
#include "../Common.h"
void BH_Mat3fIdentity(float out[9]);
void BH_Mat3fAdd(const float a[9],
const float b[9],
float out[9]);
void BH_Mat3fSub(const float a[9],
const float b[9],
float out[9]);
void BH_Mat3fMul(const float a[9],
const float b[9],
float out[9]);
void BH_Mat3fScale(const float a[9],
float b,
float out[9]);
void BH_Mat3fTranspose(const float in[9],
float out[9]);
float BH_Mat3fTrace(const float in[9]);
float BH_Mat3fDet(const float in[9]);
int BH_Mat3fInverse(const float in[9],
float out[9]);
void BH_Mat3fFromScale(float x,
float y,
float out[9]);
void BH_Mat3fFromTranslation(float x,
float y,
float out[9]);
void BH_Mat3fFromRotation(float angle,
float out[9]);
void BH_Mat3fApplyVec3f(float a[9],
float b[3],
float out[3]);
void BH_Mat3fApplyVec2f(float a[9],
float b[2],
float out[2]);
#endif /* BH_MATH_MAT3F */

136
include/BH/Math/Mat4f.h Normal file
View File

@@ -0,0 +1,136 @@
#ifndef BH_MATH_MAT4F_H
#define BH_MATH_MAT4F_H
#include "../Common.h"
void BH_Mat4fIdentity(float out[16]);
void BH_Mat4fAdd(const float a[16],
const float b[16],
float out[16]);
void BH_Mat4fSub(const float a[16],
const float b[16],
float out[16]);
void BH_Mat4fMul(const float a[16],
const float b[16],
float out[16]);
void BH_Mat4fScale(const float a[16],
float b,
float out[16]);
void BH_Mat4fTranspose(const float in[16],
float out[16]);
float BH_Mat4fTrace(const float in[16]);
float BH_Mat4fDet(const float in[16]);
int BH_Mat4fInverse(const float in[16],
float out[16]);
void BH_Mat4fFromScale(float x,
float y,
float z,
float out[16]);
void BH_Mat4fFromTranslation(float x,
float y,
float z,
float out[16]);
void BH_Mat4fFromRotationX(float angle,
float out[16]);
void BH_Mat4fFromRotationY(float angle,
float out[16]);
void BH_Mat4fFromRotationZ(float angle,
float out[16]);
void BH_Mat4fFromAxis(const float axis[3],
float angle,
float out[16]);
void BH_Mat4fFromEuler(float roll,
float pitch,
float yaw,
float out[16]);
void BH_Mat4fFromQuat4f(const float in[4],
float out[16]);
void BH_Mat4fFromOrtho(float xMin,
float xMax,
float yMin,
float yMax,
float zMin,
float zMax,
float out[16]);
void BH_Mat4fFromFrustum(float fov,
float aspect,
float zMin,
float zMax,
float out[16]);
void BH_Mat4fFromLookAt(const float position[3],
const float at[3],
const float up[3],
float out[16]);
void BH_Mat4fApplyVec4f(const float a[16],
const float b[4],
float out[4]);
void BH_Mat4fApplyVec3f(const float a[16],
const float b[3],
float out[3]);
#endif /* BH_MATH_MAT4F */

17
include/BH/Math/Misc.h Normal file
View File

@@ -0,0 +1,17 @@
#ifndef BH_MATH_MISC_H
#define BH_MATH_MISC_H
#include "../Common.h"
float BH_Lerpf(float a, float b, float t);
void BH_Triangle3fBarycentric(const float a[3],
const float b[3],
const float c[3],
const float point[3],
float out[3]);
#endif /* BH_MATH_MISC */

24
include/BH/Math/Plane.h Normal file
View File

@@ -0,0 +1,24 @@
#ifndef BH_MATH_PLANE_H
#define BH_MATH_PLANE_H
#include "../Common.h"
int BH_PlaneFromPoints(const float a[3],
const float b[3],
const float c[3],
float out[4]);
float BH_PlaneDistance(const float plane[4],
const float point[3]);
void BH_PlaneClosestPoint(const float plane[4],
const float point[3],
float out[3]);
#endif /* BH_MATH_PLANE_H */

105
include/BH/Math/Quat.h Normal file
View File

@@ -0,0 +1,105 @@
#ifndef BH_MATH_QUAT_H
#define BH_MATH_QUAT_H
#include "../Common.h"
#include "Vec4f.h"
#define BH_Quat4fAdd(a, b, out) \
BH_Vec4fAdd(a, b, out)
#define BH_Quat4fSub(a, b, out) \
BH_Vec4fSub(a, b, out)
#define BH_Quat4fScale(a, b, out) \
BH_Vec4fScale(a, b, out)
#define BH_Quat4fNegate(in, out) \
BH_Vec4fNegate(in, out)
#define BH_Quat4fDot(a, b) \
BH_Vec4fDot(a, b)
#define BH_Quat4fLength(in) \
BH_Vec4fLength(in)
#define BH_Quat4fNormal(in, out) \
BH_Vec4fNormal(in, out)
#define BH_Quat4fLerp(a, b, t, out) \
BH_Vec4fLerp(a, b, t, out)
void BH_Quat4fIdentity(float out[4]);
void BH_Quat4fConjugate(const float in[4],
float out[4]);
void BH_Quat4fInverse(const float in[4],
float out[4]);
void BH_Quat4fMul(const float a[4],
const float b[4],
float out[4]);
void BH_Quat4fSlerp(const float a[4],
const float b[4],
float t,
float out[4]);
void BH_Quat4fFromEuler(float roll,
float pitch,
float yaw,
float out[4]);
void BH_Quat4fFromAxis(const float axis[3],
float angle,
float out[4]);
void BH_Quat4fToEuler(const float in[4],
float *roll,
float *pitch,
float *yaw);
void BH_Quat4fToAxis(const float in[4],
float axis[3],
float *angle);
void BH_Quat4fToMat4f(const float in[4],
float out[16]);
#endif /* BH_MATH_QUAT */

76
include/BH/Math/Ray2f.h Normal file
View File

@@ -0,0 +1,76 @@
#ifndef BH_MATH_RAY2F_H
#define BH_MATH_RAY2F_H
#include "../Common.h"
int BH_Ray2fIntersectLine(const float start[2],
const float direction[2],
const float line[3],
float *t,
float out[2]);
int BH_Ray2fIntersectTime(const float aStart[2],
const float aDirection[2],
const float bStart[2],
const float bDirection[2],
float *time1,
float *time2);
int BH_Ray2fIntersectRay(const float aStart[2],
const float aDirection[2],
const float bStart[2],
const float bDirection[2],
float *t,
float out[2]);
int BH_Ray2fIntersectSegment(const float aStart[2],
const float aDirection[2],
const float bStart[2],
const float bEnd[2],
float *t,
float out[2]);
int BH_Segment2fIntersectLine(const float start[2],
const float end[2],
const float line[3],
float *t,
float out[2]);
int BH_Segment2fIntersectSegment(const float aStart[2],
const float aEnd[2],
const float bStart[2],
const float bEnd[2],
float *t,
float out[2]);
int BH_Ray2fIntersectBox2f(const float aStart[2],
const float aDirection[2],
const float bMin[2],
const float bMax[2],
float *t,
float out[2]);
int BH_Segment2fIntersectBox2f(const float aStart[2],
const float aEnd[2],
const float bMin[2],
const float bMax[2],
float *t,
float out[2]);
#endif /* BH_MATH_RAY2F_H */

58
include/BH/Math/Ray3f.h Normal file
View File

@@ -0,0 +1,58 @@
#ifndef BH_MATH_RAY3F_H
#define BH_MATH_RAY3F_H
#include "../Common.h"
int BH_Ray3fIntersectPlane(const float start[3],
const float direction[3],
const float plane[4],
float *t,
float out[3]);
int BH_Ray3fIntersectTriangle(const float start[3],
const float direction[3],
const float a[3],
const float b[3],
const float c[3],
float *t,
float out[3]);
int BH_Segment3fIntersectPlane(const float start[3],
const float end[3],
const float plane[4],
float *t,
float out[3]);
int BH_Segment3fIntersectTriangle(const float start[3],
const float end[3],
const float a[3],
const float b[3],
const float c[3],
float *t,
float out[3]);
int BH_Ray3fIntersectBox3f(const float aStart[3],
const float aDirection[3],
const float bMin[3],
const float bMax[3],
float *t,
float out[3]);
int BH_Segment3fIntersectBox3f(const float aStart[3],
const float aEnd[3],
const float bMin[3],
const float bMax[3],
float *t,
float out[3]);
#endif /* BH_MATH_RAY3F_H */

100
include/BH/Math/Vec2f.h Normal file
View File

@@ -0,0 +1,100 @@
#ifndef BH_MATH_VEC2F_H
#define BH_MATH_VEC2F_H
#include "../Common.h"
void BH_Vec2fAdd(const float a[2],
const float b[2],
float out[2]);
void BH_Vec2fSub(const float a[2],
const float b[2],
float out[2]);
void BH_Vec2fMul(const float a[2],
const float b[2],
float out[2]);
void BH_Vec2fScale(const float a[2],
float b,
float out[2]);
void BH_Vec2fMulAdd(const float a[2],
const float b[2],
const float c[2],
float out[2]);
void BH_Vec2fNegate(const float in[2],
float out[2]);
float BH_Vec2fDot(const float a[2],
const float b[2]);
float BH_Vec2fCross(const float a[2],
const float b[2]);
float BH_Vec2fLength(const float in[2]);
void BH_Vec2fNormal(const float in[2],
float out[2]);
float BH_Vec2fNormalEx(const float in[2],
float out[2]);
void BH_Vec2fMin(const float a[2],
const float b[2],
float out[2]);
void BH_Vec2fMax(const float a[2],
const float b[2],
float out[2]);
void BH_Vec2fLerp(const float a[2],
const float b[2],
float t,
float out[2]);
void BH_Vec2fProject(const float a[2],
const float b[2],
float out[2]);
void BH_Vec2fBarycentric(const float a[2],
const float b[2],
const float c[2],
float v,
float w,
float out[2]);
#endif /* BH_MATH_VEC2F */

52
include/BH/Math/Vec2i.h Normal file
View File

@@ -0,0 +1,52 @@
#ifndef BH_MATH_VEC2I_H
#define BH_MATH_VEC2I_H
#include "../Common.h"
void BH_Vec2iAdd(const int a[2],
const int b[2],
int out[2]);
void BH_Vec2iSub(const int a[2],
const int b[2],
int out[2]);
void BH_Vec2iMul(const int a[2],
const int b[2],
int out[2]);
void BH_Vec2iScale(const int a[2],
int b,
int out[2]);
void BH_Vec2iMulAdd(const int a[2],
const int b[2],
const int c[2],
int out[2]);
void BH_Vec2iNegate(const int in[2],
int out[2]);
void BH_Vec2iMin(const int a[2],
const int b[2],
int out[2]);
void BH_Vec2iMax(const int a[2],
const int b[2],
int out[2]);
#endif /* BH_MATH_VEC2I */

100
include/BH/Math/Vec3f.h Normal file
View File

@@ -0,0 +1,100 @@
#ifndef BH_MATH_VEC3F_H
#define BH_MATH_VEC3F_H
#include "../Common.h"
void BH_Vec3fAdd(const float a[3],
const float b[3],
float out[3]);
void BH_Vec3fSub(const float a[3],
const float b[3],
float out[3]);
void BH_Vec3fMul(const float a[3],
const float b[3],
float out[3]);
void BH_Vec3fScale(const float a[3],
float b,
float out[3]);
void BH_Vec3fMulAdd(const float a[3],
const float b[3],
const float c[3],
float out[3]);
void BH_Vec3fNegate(const float in[3],
float out[3]);
float BH_Vec3fDot(const float a[3],
const float b[3]);
void BH_Vec3fCross(const float a[3],
const float b[3],
float out[3]);
float BH_Vec3fLength(const float in[3]);
void BH_Vec3fNormal(const float in[3],
float out[3]);
float BH_Vec3fNormalEx(const float in[3],
float out[3]);
void BH_Vec3fMin(const float a[3],
const float b[3],
float out[3]);
void BH_Vec3fMax(const float a[3],
const float b[3],
float out[3]);
void BH_Vec3fLerp(const float a[3],
const float b[3],
float t,
float out[3]);
void BH_Vec3fProject(const float a[3],
const float b[3],
float out[3]);
void BH_Vec3fBarycentric(const float a[3],
const float b[3],
const float c[3],
float v,
float w,
float out[3]);
#endif /* BH_MATH_VEC3F_H */

53
include/BH/Math/Vec3i.h Normal file
View File

@@ -0,0 +1,53 @@
#ifndef BH_MATH_VEC3I_H
#define BH_MATH_VEC3I_H
#include "../Common.h"
void BH_Vec3iAdd(const int a[3],
const int b[3],
int out[3]);
void BH_Vec3iSub(const int a[3],
const int b[3],
int out[3]);
void BH_Vec3iMul(const int a[3],
const int b[3],
int out[3]);
void BH_Vec3iScale(const int a[3],
int b,
int out[3]);
void BH_Vec3iMulAdd(const int a[3],
const int b[3],
const int c[3],
int out[3]);
void BH_Vec3iNegate(const int in[3],
int out[3]);
void BH_Vec3iMin(const int a[3],
const int b[3],
int out[3]);
void BH_Vec3iMax(const int a[3],
const int b[3],
int out[3]);
#endif /* BH_MATH_VEC3I */

80
include/BH/Math/Vec4f.h Normal file
View File

@@ -0,0 +1,80 @@
#ifndef BH_MATH_VEC4F_H
#define BH_MATH_VEC4F_H
#include "../Common.h"
void BH_Vec4fAdd(const float a[4],
const float b[4],
float out[4]);
void BH_Vec4fSub(const float a[4],
const float b[4],
float out[4]);
void BH_Vec4fMul(const float a[4],
const float b[4],
float out[4]);
void BH_Vec4fScale(const float a[4],
float b,
float out[4]);
void BH_Vec4fMulAdd(const float a[4],
const float b[4],
const float c[4],
float out[4]);
void BH_Vec4fNegate(const float in[4],
float out[4]);
float BH_Vec4fDot(const float a[4],
const float b[4]);
float BH_Vec4fLength(const float in[4]);
void BH_Vec4fNormal(const float in[4],
float out[4]);
float BH_Vec4fNormalEx(const float in[4],
float out[4]);
void BH_Vec4fMin(const float a[4],
const float b[4],
float out[4]);
void BH_Vec4fMax(const float a[4],
const float b[4],
float out[4]);
void BH_Vec4fLerp(const float a[4],
const float b[4],
float t,
float out[4]);
void BH_Vec4fProject(const float a[4],
const float b[4],
float out[4]);
void BH_Vec4fBarycentric(const float a[4],
const float b[4],
const float c[4],
float v,
float w,
float out[4]);
#endif /* BH_MATH_VEC4F */

54
include/BH/Math/Vec4i.h Normal file
View File

@@ -0,0 +1,54 @@
#ifndef BH_MATH_VEC4I_H
#define BH_MATH_VEC4I_H
#include "../Common.h"
void BH_Vec4iAdd(const int a[4],
const int b[4],
int out[4]);
void BH_Vec4iSub(const int a[4],
const int b[4],
int out[4]);
void BH_Vec4iMul(const int a[4],
const int b[4],
int out[4]);
void BH_Vec4iScale(const int a[4],
int b,
int out[4]);
void BH_Vec4iMulAdd(const int a[4],
const int b[4],
const int c[4],
int out[4]);
void BH_Vec4iNegate(const int in[4],
int out[4]);
void BH_Vec4iMin(const int a[4],
const int b[4],
int out[4]);
void BH_Vec4iMax(const int a[4],
const int b[4],
int out[4]);
#endif /* BH_MATH_VEC4I */

View File

@@ -8,138 +8,55 @@
typedef struct BH_Queue BH_Queue;
/**
* Creates the new queue.
*
* \return On success, returns the queue pointer.
* \return On failure, returns a null pointer.
*/
BH_Queue *BH_QueueNew(void);
/**
* Frees the \a queue.
*
* \param queue Queue pointer
*/
void BH_QueueFree(BH_Queue *queue);
/**
* Clears the \a queue.
*
* \param queue Queue pointer
*/
void BH_QueueClear(BH_Queue *queue);
/**
* Reserves the space for \a size amount of value in the \a queue.
*
* This function can both expand and shrink the available space in queue.
*
* \param queue Queue pointer
* \param size Capacity
*
* \note Calling this function will invalidate iterators.
* \note Actual queue capacity can be bigger then requested.
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_QueueReserve(BH_Queue *queue,
size_t size);
/**
* Inserts the \a value into the \a queue.
*
* \param queue Queue pointer
* \param value Value
*
* \note Calling this function will invalidate iterators.
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_QueueInsert(BH_Queue *queue,
void *value);
/**
* Removes front value from the \a queue.
*
* \param queue Queue pointer
*
* \note Calling this function will invalidate iterators.
*/
void BH_QueueRemove(BH_Queue *queue);
/**
* Returns front \a value from the \a queue.
*
* \param queue Queue pointer
* \param value Value
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_QueueFront(BH_Queue *queue,
void **value);
/**
* Checks if the \a queue is empty.
*
* \param queue Queue pointer
*
* \return If queue is empty, returns non-zero value
* \return If queue is not empty, returns zero
*/
int BH_QueueEmpty(BH_Queue *queue);
/**
* Returns the size of the \a queue.
*
* \param queue Queue pointer
*
* \return Returns the size of the queue.
*/
size_t BH_QueueSize(BH_Queue *queue);
/**
* Returns the capacity of the \a queue.
*
* \param queue Queue pointer
*
* \return Returns the capacity of the queue.
*/
size_t BH_QueueCapacity(BH_Queue *queue);
/**
* Returns the iterator to the next element in the \a queue.
*
* \param queue Queue pointer
* \param iter Iterator
*
* \return On success, returns new iterator value for the next element.
* \return On failure, returns NULL pointer.
*/
void *BH_QueueIterNext(BH_Queue *queue,
void *iter);
/**
* Returns the value, pointed by the \a iter.
*
* \param iter Iterator
*
* \return Returns value, pointed by iterator.
*/
void *BH_QueueIterValue(void *iter);

View File

@@ -5,31 +5,7 @@
#include "Common.h"
/**
* Formats a double \a value into a zero terminated \a string (limited by
* \a size) using the provided \a format and \a precision and stores \a actual
* length (if it's provided).
*
* Formats supported:
* - Scientific or fixed format ('g' or 'G')
* - Scientific format ('e' or 'E')
* - Fixed format ('f' or 'F')
*
* If precision is negative, string will contain shortest representation of the
* double that can round-trip (i.e. converted back without information loss).
*
* This function follows IEEE 754 round to even to break ties during rounding.
*
* \param string String
* \param size String size
* \param value Value
* \param format Format
* \param precision Precision
* \param actual Written size (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_StringFromDouble(char *string,
size_t size,
double value,
@@ -38,19 +14,7 @@ int BH_StringFromDouble(char *string,
size_t *actual);
/**
* Formats signed 8-bit \a value into a \a string (limited by \a size) with
* provided \a base and stores \a actual length (if it's provided).
*
* \param string String
* \param size String size
* \param value Value
* \param base Base
* \param actual Written size (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_StringFromInt8s(char *string,
size_t size,
int8_t value,
@@ -58,19 +22,7 @@ int BH_StringFromInt8s(char *string,
size_t *actual);
/**
* Formats signed 16-bit \a value into a \a string (limited by \a size) with
* provided \a base and stores \a actual length (if it's provided).
*
* \param string String
* \param size String size
* \param value Value
* \param base Base
* \param actual Written size (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_StringFromInt16s(char *string,
size_t size,
int16_t value,
@@ -78,19 +30,7 @@ int BH_StringFromInt16s(char *string,
size_t *actual);
/**
* Formats signed 32-bit \a value into a \a string (limited by \a size) with
* provided \a base and stores \a actual length (if it's provided).
*
* \param string String
* \param size String size
* \param value Value
* \param base Base
* \param actual Written size (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_StringFromInt32s(char *string,
size_t size,
int32_t value,
@@ -98,19 +38,7 @@ int BH_StringFromInt32s(char *string,
size_t *actual);
/**
* Formats signed 64-bit \a value into a \a string (limited by \a size) with
* provided \a base and stores \a actual length (if it's provided).
*
* \param string String
* \param size String size
* \param value Value
* \param base Base
* \param actual Written size (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_StringFromInt64s(char *string,
size_t size,
int64_t value,
@@ -118,19 +46,7 @@ int BH_StringFromInt64s(char *string,
size_t *actual);
/**
* Formats unsigned 8-bit \a value into a \a string (limited by \a size) with
* provides \a base and stores \a actual length (if it's provided).
*
* \param string String
* \param size String size
* \param value Value
* \param base Base
* \param actual Written size (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_StringFromInt8u(char *string,
size_t size,
uint8_t value,
@@ -138,19 +54,7 @@ int BH_StringFromInt8u(char *string,
size_t *actual);
/**
* Formats unsigned 16-bit \a value into a \a string (limited by \a size) with
* provides \a base and stores \a actual length (if it's provided).
*
* \param string String
* \param size String size
* \param value Value
* \param base Base
* \param actual Written size (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_StringFromInt16u(char *string,
size_t size,
uint16_t value,
@@ -158,19 +62,7 @@ int BH_StringFromInt16u(char *string,
size_t *actual);
/**
* Formats unsigned 32-bit \a value into a \a string (limited by \a size) with
* provided \a base and stores \a actual length (if it's provided).
*
* \param string String
* \param size String size
* \param value Value
* \param base Base
* \param actual Written size (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_StringFromInt32u(char *string,
size_t size,
uint32_t value,
@@ -178,19 +70,7 @@ int BH_StringFromInt32u(char *string,
size_t *actual);
/**
* Formats unsigned 64-bit \a value into a \a string (limited by \a size) with
* provided \a base and stores \a actual length (if it's provided).
*
* \param string String
* \param size String size
* \param value Value
* \param base Base
* \param actual Written size (optional)
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_StringFromInt64u(char *string,
size_t size,
uint64_t value,
@@ -198,385 +78,58 @@ int BH_StringFromInt64u(char *string,
size_t *actual);
/**
* Reads \a string containing double value in fixed or scientific format,
* optionally reports \a size amount of characters consumed and returns
* the result value.
*
* \param string String
* \param size Optional size
*
* \return On success, returns parsed double value.
* \return On failure, returns zero.
*/
double BH_StringToDouble(const char *string,
size_t *size);
/**
* Reads \a string containing value in specified \a base, optionally reports
* \a size amount of characters consumed and returns the result value.
*
* If base is 0, function will automaticly detect input base by the prefix:
* - Base 2 if prefix is 0b
* - Base 8 if prefix is 0
* - Base 16 if prefix is 0x
* - Base 10 in other cases
*
* \param string String
* \param size Optional size
* \param base Base
*
* \return On success, returns parsed value.
* \return On failure, returns zero.
*/
int8_t BH_StringToInt8s(const char *string,
size_t *size,
int base);
/**
* Reads \a string containing value in specified \a base, optionally reports
* \a size amount of characters consumed and returns the result value.
*
* If base is 0, function will automaticly detect input base by the prefix:
* - Base 2 if prefix is 0b
* - Base 8 if prefix is 0
* - Base 16 if prefix is 0x
* - Base 10 in other cases
*
* \param string String
* \param size Optional size
* \param base Base
*
* \return On success, returns parsed value.
* \return On failure, returns zero.
*/
int16_t BH_StringToInt16s(const char *string,
size_t *size,
int base);
/**
* Reads \a string containing value in specified \a base, optionally reports
* \a size amount of characters consumed and returns the result value.
*
* If base is 0, function will automaticly detect input base by the prefix:
* - Base 2 if prefix is 0b
* - Base 8 if prefix is 0
* - Base 16 if prefix is 0x
* - Base 10 in other cases
*
* \param string String
* \param size Optional size
* \param base Base
*
* \return On success, returns parsed value.
* \return On failure, returns zero.
*/
int32_t BH_StringToInt32s(const char *string,
size_t *size,
int base);
/**
* Reads \a string containing value in specified \a base, optionally reports
* \a size amount of characters consumed and returns the result value.
*
* If base is 0, function will automaticly detect input base by the prefix:
* - Base 2 if prefix is 0b
* - Base 8 if prefix is 0
* - Base 16 if prefix is 0x
* - Base 10 in other cases
*
* \param string String
* \param size Optional size
* \param base Base
*
* \return On success, returns parsed value.
* \return On failure, returns zero.
*/
int64_t BH_StringToInt64s(const char *string,
size_t *size,
int base);
/**
* Reads \a string containing value in specified \a base, optionally reports
* \a size amount of characters consumed and returns the result value.
*
* If base is 0, function will automaticly detect input base by the prefix:
* - Base 2 if prefix is 0b
* - Base 8 if prefix is 0
* - Base 16 if prefix is 0x
* - Base 10 in other cases
*
* \param string String
* \param size Optional size
* \param base Base
*
* \return On success, returns parsed value.
* \return On failure, returns zero.
*/
uint8_t BH_StringToInt8u(const char *string,
size_t *size,
int base);
/**
* Reads \a string containing value in specified \a base, optionally reports
* \a size amount of characters consumed and returns the result value.
*
* If base is 0, function will automaticly detect input base by the prefix:
* - Base 2 if prefix is 0b
* - Base 8 if prefix is 0
* - Base 16 if prefix is 0x
* - Base 10 in other cases
*
* \param string String
* \param size Optional size
* \param base Base
*
* \return On success, returns parsed value.
* \return On failure, returns zero.
*/
uint16_t BH_StringToInt16u(const char *string,
size_t *size,
int base);
/**
* Reads \a string containing value in specified \a base, optionally reports
* \a size amount of characters consumed and returns the result value.
*
* If base is 0, function will automaticly detect input base by the prefix:
* - Base 2 if prefix is 0b
* - Base 8 if prefix is 0
* - Base 16 if prefix is 0x
* - Base 10 in other cases
*
* \param string String
* \param size Optional size
* \param base Base
*
* \return On success, returns parsed value.
* \return On failure, returns zero.
*/
uint32_t BH_StringToInt32u(const char *string,
size_t *size,
int base);
/**
* Reads \a string containing value in specified \a base, optionally reports
* \a size amount of characters consumed and returns the result value.
*
* If base is 0, function will automaticly detect input base by the prefix:
* - Base 2 if prefix is 0b
* - Base 8 if prefix is 0
* - Base 16 if prefix is 0x
* - Base 10 in other cases
*
* \param string String
* \param size Optional size
* \param base Base
*
* \return On success, returns parsed value.
* \return On failure, returns zero.
*/
uint64_t BH_StringToInt64u(const char *string,
size_t *size,
int base);
/**
* Converts unicode \a unit codepoint to lowercase.
*
* \param unit Codepoint
*
* \return On success, returns lowercased codepoint.
* \return On failure, returns codepoint without a change.
*/
uint32_t BH_UnicodeLower(uint32_t unit);
/**
* Converts unicode \a unit codepoint to uppercase.
*
* \param unit Codepoint
*
* \return On success, returns uppercased codepoint.
* \return On failure, returns codepoint without a change.
*/
uint32_t BH_UnicodeUpper(uint32_t unit);
/**
* Decodes a UTF-8 sequence from a \a string (with the given \a size), storing
* the result in a \a unit and returning the number of bytes read.
*
* Invalid UTF-8 sequences result in a -1 codepoint.
*
* \param string String
* \param size Size
* \param unit Codepoint
*
* \return Returns readed amount of bytes
* \return Returns zero if the string contains only a portion of the sequence.
*/
size_t BH_UnicodeDecodeUtf8(const char *string,
size_t size,
uint32_t *unit);
/**
* Encodes a Unicode \a unit to UTF-8 encoded bytes (stored in a \a string)
* and returns the number of bytes written.
*
* String are assumed to have 4 bytes of space.
*
* \param unit Codepoint
* \param string String
*
* \return On success, returns written amount of bytes.
* \return Of faulure, returns zero.
*/
size_t BH_UnicodeEncodeUtf8(uint32_t unit,
char *string);
/**
* Decodes a UTF-16LE sequence from a \a string (with the given \a size),
* storing the result in a \a unit and returning the number of bytes read.
*
* Invalid UTF-16 sequences result in a -1 codepoint.
*
* \param string String
* \param size Size
* \param unit Codepoint
*
* \return Returns readed amount of bytes
* \return Returns zero if the string contains only a portion of the sequence.
*/
size_t BH_UnicodeDecodeUtf16LE(const char *string,
size_t size,
uint32_t *unit);
/**
* Decodes a UTF-16BE sequence from a \a string (with the given \a size),
* storing the result in a \a unit and returning the number of bytes read.
*
* Invalid UTF-16 sequences result in a -1 codepoint.
*
* \param string String
* \param size Size
* \param unit Codepoint
*
* \return Returns readed amount of bytes
* \return Returns zero if the string contains only a portion of the sequence.
*/
size_t BH_UnicodeDecodeUtf16BE(const char *string,
size_t size,
uint32_t *unit);
/**
* Encodes a Unicode \a unit to UTF-16LE encoded bytes (stored in a \a string)
* and returns the number of bytes written.
*
* String are assumed to have 4 bytes of space.
*
* \param unit Codepoint
* \param string String
*
* \return On success, returns written amount of bytes.
* \return Of faulure, returns zero.
*/
size_t BH_UnicodeEncodeUtf16LE(uint32_t unit,
char *string);
/**
* Encodes a Unicode \a unit to UTF-16BE encoded bytes (stored in a \a string)
* and returns the number of bytes written.
*
* String are assumed to have 4 bytes of space.
*
* \param unit Codepoint
* \param string String
*
* \return On success, returns written amount of bytes.
* \return Of faulure, returns zero.
*/
size_t BH_UnicodeEncodeUtf16BE(uint32_t unit,
char *string);
/**
* Decodes a UTF-32LE symbol from a \a string (with the given \a size),
* storing the result in a \a unit and returning the number of bytes read.
*
* Invalid UTF-32 result in a -1 codepoint.
*
* \param string String
* \param size Size
* \param unit Codepoint
*
* \return Returns readed amount of bytes
* \return Returns zero if the string contains only a portion of the sequence.
*/
size_t BH_UnicodeDecodeUtf32LE(const char *string,
size_t size,
uint32_t *unit);
/**
* Decodes a UTF-32BE symbol from a \a string (with the given \a size),
* storing the result in a \a unit and returning the number of bytes read.
*
* Invalid UTF-32 result in a -1 codepoint.
*
* \param string String
* \param size Size
* \param unit Codepoint
*
* \return Returns readed amount of bytes
* \return Returns zero if the string contains only a portion of the sequence.
*/
size_t BH_UnicodeDecodeUtf32BE(const char *string,
size_t size,
uint32_t *unit);
/**
* Encodes a Unicode \a unit to UTF-32LE encoded bytes (stored in a \a string)
* and returns the number of bytes written.
*
* String are assumed to have 4 bytes of space.
*
* \param unit Codepoint
* \param string String
*
* \return On success, returns written amount of bytes.
* \return Of faulure, returns zero.
*/
size_t BH_UnicodeEncodeUtf32LE(uint32_t unit,
char *string);
/**
* Encodes a Unicode \a unit to UTF-32LE encoded bytes (stored in a \a string)
* and returns the number of bytes written.
*
* String are assumed to have 4 bytes of space.
*
* \param unit Codepoint
* \param string String
*
* \return On success, returns written amount of bytes.
* \return Of faulure, returns zero.
*/
size_t BH_UnicodeEncodeUtf32BE(uint32_t unit,
char *string);
#endif /* BH_STRING_H */

View File

@@ -16,284 +16,113 @@ typedef struct BH_Condition BH_Condition;
typedef int (*BH_ThreadCallback)(void *);
/**
* Creates new thread with specified \a stack size, thread \a callback
* function and \a data.
*
* \param stack Stack size
* \param callback Callback function
* \param data User data
*
* \return On success, returns thread pointer.
* \return On failure, returns NULL pointer.
*/
BH_Thread *BH_ThreadNew(size_t stack,
BH_ThreadCallback callback,
void *data);
/**
* Joins the specified \a thread.
*
* \param thread Thread
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_ThreadJoin(BH_Thread *thread);
/**
* Detaches the specified \a thread.
*
* \param thread Thread
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_ThreadDetach(BH_Thread *thread);
/**
* Creates new mutex.
*
* \return On success, returns mutex pointer.
* \return On failure, returns NULL pointer.
*/
BH_Mutex *BH_MutexNew(void);
/**
* Frees the \a mutex.
*
* \param mutex Mutex
*/
void BH_MutexFree(BH_Mutex *mutex);
/**
* Locks the \a mutex.
*
* \param mutex Mutex
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_MutexLock(BH_Mutex *mutex);
/**
* Unlocks the \a mutex.
*
* \param mutex Mutex
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_MutexUnlock(BH_Mutex *mutex);
/**
* Tries to lock the \a mutex.
*
* \param mutex Mutex
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_MutexLockTry(BH_Mutex *mutex);
/**
* Creates new semaphore.
*
* \param value Semaphore value
*
* \return On success, returns thread pointer.
* \return On failure, returns NULL pointer.
*/
BH_Semaphore *BH_SemaphoreNew(int value);
/**
* Frees the \a semaphore.
*
* \param semaphore Semaphore
*/
void BH_SemaphoreFree(BH_Semaphore *semaphore);
/**
* Posts/increments the \a semaphore.
*
* \param semaphore Semaphore
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_SemaphorePost(BH_Semaphore *semaphore);
/**
* Waits/decrements the \a semaphore.
*
* \param semaphore Semaphore
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_SemaphoreWait(BH_Semaphore *semaphore);
/**
* Tries to wait/decrement the \a semaphore.
*
* \param semaphore Semaphore
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_SemaphoreWaitTry(BH_Semaphore *semaphore);
/**
* Waits/decrements the \a semaphore with \a timeout.
*
* If timeout occures, return code will be BH_TIMEOUT.
*
* \param semaphore Semaphore
* \param timeout Timeout in milliseconds
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_SemaphoreWaitFor(BH_Semaphore *semaphore,
uint32_t timeout);
/**
* Creates new condition variable.
*
* \return On success, returns condition variable pointer.
* \return On failure, returns NULL pointer.
*/
BH_Condition *BH_ConditionNew(void);
/**
* Frees the \a condition variable.
*
* \param condition Condition
*/
void BH_ConditionFree(BH_Condition *condition);
/**
* Unlocks the \a mutex and waits for the \a condition variable.
*
* \param condition Condition variable
* \param mutex Mutex
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_ConditionWait(BH_Condition *condition,
BH_Mutex *mutex);
/**
* Unlocks the \a mutex and waits for the \a condition variable with \a timeout.
*
* If timeout occures, return code will be BH_TIMEOUT.
*
* \param condition Condition variable
* \param mutex Mutex
* \param timeout Timeout in milliseconds
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_ConditionWaitFor(BH_Condition *condition,
BH_Mutex *mutex,
uint32_t timeout);
/**
* Signals the \a condition variable.
*
* \param condition Condition variable
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_ConditionSignal(BH_Condition *condition);
/**
* Broadcasts the \a condition variable.
*
* \param condition Condition variable
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_ConditionBroadcast(BH_Condition *condition);
/**
* Locks the \a spinlock.
*
* \param lock Spinlock
*/
void BH_SpinlockLock(int *lock);
/**
* Tries to lock the \a spinlock.
*
* \param lock Spinlock
*
* \return On success, returns zero.
* \return On failure, returns error code.
*/
int BH_SpinlockLockTry(int *lock);
/**
* Unlocks the \a spinlock.
*
* \param lock Spinlock
*/
void BH_SpinlockUnlock(int *lock);
/**
* Create new TSS/TLS slot index and destruction \a callback.
*
* \param callback Destruction callback
*
* \return On success, returns slot index.
* \return On failure, returns error code.
*/
int BH_TssCreate(BH_GenericCallback callback);
/**
* Reads the value associated with the TSS \a index.
*
* \param index TSS index
*
* \return Index value
*/
void *BH_TssRead(int index);
/**
* Writes the \a value to the TSS \a index.
*
* \param index TSS index to
* \param value Value
*/
void BH_TssWrite(int index,
void *value);

70
include/BH/Unicode.h Normal file
View File

@@ -0,0 +1,70 @@
#ifndef BH_UNICODE_H
#define BH_UNICODE_H
#include "Common.h"
uint32_t BH_UnicodeLower(uint32_t unit);
uint32_t BH_UnicodeUpper(uint32_t unit);
size_t BH_UnicodeDecodeUtf8(const char *string,
size_t size,
uint32_t *unit);
size_t BH_UnicodeEncodeUtf8(uint32_t unit,
char *string);
size_t BH_UnicodeDecodeUtf16LE(const char *string,
size_t size,
uint32_t *unit);
size_t BH_UnicodeDecodeUtf16BE(const char *string,
size_t size,
uint32_t *unit);
size_t BH_UnicodeEncodeUtf16LE(uint32_t unit,
char *string);
size_t BH_UnicodeEncodeUtf16BE(uint32_t unit,
char *string);
size_t BH_UnicodeDecodeUtf32LE(const char *string,
size_t size,
uint32_t *unit);
size_t BH_UnicodeDecodeUtf32BE(const char *string,
size_t size,
uint32_t *unit);
size_t BH_UnicodeEncodeUtf32LE(uint32_t unit,
char *string);
size_t BH_UnicodeEncodeUtf32BE(uint32_t unit,
char *string);
#endif /* BH_UNICODE_H */

View File

@@ -12,253 +12,114 @@
#define BH_FP_NEGATIVE 0x0020
/**
* Classifies the floating point \a value.
*
* \param value Value
*
* \return On success, returns BH_FP_NORMAL, BH_FP_ZERO, BH_FP_INFINITE,
* BH_FP_NAN or BH_FP_NEGATIVE.
*/
int BH_ClassifyDouble(double value);
/**
* Reads 16-bit unsigned integer from the \a buffer in little-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 16-bit unsigned integer value.
*/
uint16_t BH_Read16LEu(const char *buffer);
/**
* Reads 16-bit signed integer from the \a buffer in little-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 16-bit signed integer value.
*/
int16_t BH_Read16LEs(const char *buffer);
/**
* Reads 32-bit unsigned integer from the \a buffer in little-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 32-bit unsigned integer value.
*/
uint32_t BH_Read32LEu(const char *buffer);
/**
* Reads 32-bit signed integer from the \a buffer in little-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 32-bit signed integer value.
*/
int32_t BH_Read32LEs(const char *buffer);
/**
* Reads 64-bit unsigned integer from the \a buffer in little-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 64-bit unsigned integer value.
*/
uint64_t BH_Read64LEu(const char *buffer);
/**
* Reads 64-bit signed integer from the \a buffer in little-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 64-bit signed integer value.
*/
int64_t BH_Read64LEs(const char *buffer);
/**
* Reads 16-bit unsigned integer from the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 16-bit unsigned integer value.
*/
uint16_t BH_Read16BEu(const char *buffer);
/**
* Reads 16-bit signed integer from the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 16-bit signed integer value.
*/
int16_t BH_Read16BEs(const char *buffer);
/**
* Reads 32-bit unsigned integer from the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 32-bit unsigned integer value.
*/
uint32_t BH_Read32BEu(const char *buffer);
/**
* Reads 32-bit signed integer from the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 32-bit signed integer value.
*/
int32_t BH_Read32BEs(const char *buffer);
/**
* Reads 64-bit unsigned integer from the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 64-bit unsigned integer value.
*/
uint64_t BH_Read64BEu(const char *buffer);
/**
* Reads 64-bit signed integer from the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
*
* \return Returns 64-bit signed integer value.
*/
int64_t BH_Read64BEs(const char *buffer);
/**
* Writes 16-bit unsigned integer to the \a buffer in little-endian format.
*
* \param buffer Buffer pointer
* \param value Value
*/
void BH_Write16LEu(char *buffer,
uint16_t value);
/**
* Writes 16-bit signed integer to the \a buffer in little-endian format.
*
* \param buffer Buffer pointer
* \param value Value
*/
void BH_Write16LEs(char *buffer,
int16_t value);
/**
* Writes 32-bit unsigned integer to the \a buffer in little-endian format.
*
* \param buffer Buffer pointer\param buffer Buffer pointer
* \param value Value
*/
void BH_Write32LEu(char *buffer,
uint32_t value);
/**
* Writes 32-bit signed integer to the \a buffer in little-endian format.
*
* \param buffer Buffer pointer
* \param value Value
*/
void BH_Write32LEs(char *buffer,
int32_t value);
/**
* Writes 64-bit unsigned integer to the \a buffer in little-endian format.
*
* \param buffer Buffer pointer
* \param value Value
*/
void BH_Write64LEu(char *buffer,
uint64_t value);
/**
* Writes 64-bit signed integer to the \a buffer in little-endian format.
*
* \param buffer Buffer pointer
* \param value Value
*/
void BH_Write64LEs(char *buffer,
int64_t value);
/**
* Writes 16-bit unsigned integer to the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
* \param value Value
*/
void BH_Write16BEu(char *buffer,
uint16_t value);
/**
* Writes 16-bit signed integer to the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
* \param value Value
*/
void BH_Write16BEs(char *buffer,
int16_t value);
/**
* Writes 32-bit unsigned integer to the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
* \param value Value
*/
void BH_Write32BEu(char *buffer,
uint32_t value);
/**
* Writes 32-bit signed integer to the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
* \param value Value
*/
void BH_Write32BEs(char *buffer,
int32_t value);
/**
* Writes 64-bit unsigned integer to the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
* \param value Value
*/
void BH_Write64BEu(char *buffer,
uint64_t value);
/**
* Writes 64-bit signed integer to the \a buffer in big-endian format.
*
* \param buffer Buffer pointer
* \param value Value
*/
void BH_Write64BEs(char *buffer,
int64_t value);

View File

@@ -1,4 +1,5 @@
#include <BH/Math.h>
#include <BH/Math/Box2f.h>
#include <BH/Math/Vec2f.h>
#include <string.h>

View File

@@ -1,4 +1,5 @@
#include <BH/Math.h>
#include <BH/Math/Box3f.h>
#include <BH/Math/Vec3f.h>
#include <string.h>

View File

@@ -1,4 +1,5 @@
#include <BH/Math.h>
#include <BH/Math/Line.h>
#include <BH/Math/Vec2f.h>
#include <string.h>

View File

@@ -1,4 +1,5 @@
#include <BH/Math.h>
#include <BH/Math/Mat3f.h>
#include <BH/Math/Vec3f.h>
#include <string.h>
#include <math.h>

View File

@@ -1,4 +1,7 @@
#include <BH/Math.h>
#include <BH/Math/Mat4f.h>
#include <BH/Math/Vec4f.h>
#include <BH/Math/Vec3f.h>
#include <BH/Math/Quat.h>
#include <string.h>
#include <math.h>

View File

@@ -1,4 +1,5 @@
#include <BH/Math.h>
#include <BH/Math/Misc.h>
#include <BH/Math/Vec3f.h>
float BH_Lerpf(float a, float b, float t)

View File

@@ -1,4 +1,5 @@
#include <BH/Math.h>
#include <BH/Math/Plane.h>
#include <BH/Math/Vec3f.h>
#include <string.h>

View File

@@ -1,4 +1,6 @@
#include <BH/Math.h>
#include <BH/Math/Quat.h>
#include <BH/Math/Vec3f.h>
#include <BH/Math/Mat4f.h>
#include <string.h>
#include <math.h>

View File

@@ -1,4 +1,6 @@
#include <BH/Math.h>
#include <BH/Math/Ray2f.h>
#include <BH/Math/Vec2f.h>
#include <BH/Math/Box2f.h>
#include <string.h>
#include <math.h>

View File

@@ -1,4 +1,7 @@
#include <BH/Math.h>
#include <BH/Math/Ray3f.h>
#include <BH/Math/Vec3f.h>
#include <BH/Math/Box3f.h>
#include <BH/Math/Plane.h>
#include <string.h>
#include <math.h>

View File

@@ -1,4 +1,4 @@
#include <BH/Math.h>
#include <BH/Math/Vec2f.h>
#include <math.h>

View File

@@ -1,4 +1,4 @@
#include <BH/Math.h>
#include <BH/Math/Vec2i.h>
void BH_Vec2iAdd(const int a[2],

View File

@@ -1,4 +1,4 @@
#include <BH/Math.h>
#include <BH/Math/Vec3f.h>
#include <string.h>
#include <math.h>

View File

@@ -1,4 +1,4 @@
#include <BH/Math.h>
#include <BH/Math/Vec3i.h>
void BH_Vec3iAdd(const int a[3],

View File

@@ -1,4 +1,4 @@
#include <BH/Math.h>
#include <BH/Math/Vec4f.h>
#include <math.h>

View File

@@ -1,4 +1,4 @@
#include <BH/Math.h>
#include <BH/Math/Vec4i.h>
void BH_Vec4iAdd(const int a[4],

View File

@@ -1,4 +1,4 @@
#include <BH/String.h>
#include <BH/Unicode.h>
#include <BH/Util.h>
#include "Inline/Unicode.h"

View File

@@ -1,4 +1,4 @@
#include <BH/Math.h>
#include <BH/Math/Box2f.h>
#include <BH/Unit.h>

View File

@@ -1,4 +1,4 @@
#include <BH/Math.h>
#include <BH/Math/Box3f.h>
#include <BH/Unit.h>

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