repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
KIodine/naiveds
threaded-avltree/include/list.h
#ifndef LIST_H #define LIST_H #include <stddef.h> #define list_entry(ptr, type, member) ({ \ void *__tmp = (void*)(ptr);\ (type *)((char*)(__tmp) - offsetof(type, member))\ }) struct list { struct list *prev, *next; }; #define list_decl(ident) struct list ident = {&(ident), &(ident)} #define list_is_empty(node) ((node)->prev == (node)) void list_push(struct list *head, struct list *node); struct list *list_pop(struct list *head); void list_append(struct list *head, struct list *node); struct list *list_get(struct list *head); void list_delete(struct list *node); #define list_traverse(head, sym) \ for (struct list *(sym) = (head)->next; (sym) != (head); (sym) = (sym)->next) #endif
KIodine/naiveds
arrayq/fifoq.h
#ifndef FIFOQ_H #define FIFOQ_H #include <stdlib.h> /* This implementation let indexes overflow freely, the size of queue is round up to power of 2 automatically. */ struct fifoq { int *arr; unsigned int size; unsigned int mask; unsigned int front, end; }; /* ...|X|... ^(front, end) -> empty ...| |?|... ^ ^(end) |(front) -> full */ struct fifoq *fifoq_alloc(unsigned int size); void fifoq_free(struct fifoq *q); /* Put value in front. */ int fifoq_push(struct fifoq *q, int val); /* Get value from back. */ int fifoq_get(struct fifoq *q, int *res); /* Put value in back. */ int fifoq_put(struct fifoq *q, int val); /* Get value from front. */ int fifoq_pop(struct fifoq *q, int *res); static int fifoq_is_empty(struct fifoq *q){ return ((q->front&q->mask) == (q->end&q->mask)); } static int fifoq_is_full(struct fifoq *q){ return (((q->front + 1)&q->mask) == (q->end&q->mask)); } #endif /* FIFOQ_H */
KIodine/naiveds
union-find/src/unionfind.c
#include <assert.h> #include "unionfind.h" #define ALIAS_OF(func) __attribute__((weak, alias(#func))) #define NO_UNUSED __attribute__((unused)) /* --- static functions --- */ /* NOTE: Implement different find with static function? */ NO_UNUSED static struct ufnode *find_path_halving(struct ufnode *node){ struct ufnode *parent; for (;node->parent != node;){ parent = node->parent; /* Move parent node upward. */ node->parent = parent->parent; /* Move upward. */ node = node->parent; } return node; } NO_UNUSED static struct ufnode *find_path_compress(struct ufnode *node){ /* Recursive approach of `path-compression`. */ if (node->parent != node){ node->parent = uf_find(node->parent); return node->parent; } else { return node; } } /* --- public functions --- */ void uf_init_set(struct ufnode *node){ node->parent = node; node->rank = 0; return; } struct ufnode *uf_find(struct ufnode *node) ALIAS_OF(find_path_compress); //struct ufnode *uf_find(struct ufnode *node){ // return find_path_compress(node); //} int uf_connected(struct ufnode *a, struct ufnode *b){ a = uf_find(a); b = uf_find(b); return (a == b); } int uf_union(struct ufnode *a, struct ufnode *b){ struct ufnode *tmp; a = uf_find(a); b = uf_find(b); /* append "smaller" set to the "bigger" one. */ if (a->rank < b->rank){ tmp = a; a = b; b = tmp; } /* a < b: a->parent = b */ /* a > b: b->parent = a */ b->parent = a; if (a->rank == b->rank){ a->rank += 1; } return 0; }
KIodine/naiveds
singly-linked-list/sllist.c
<reponame>KIodine/naiveds<filename>singly-linked-list/sllist.c #include "sllist.h" static struct sllnode *node_alloc(int val){ struct sllnode *node = NULL; node = calloc(1, sizeof(struct sllnode)); node->val = val; return node; } static void node_purge(struct sllist *list){ struct sllnode *hold, *cur; cur = list->first; for (;cur != NULL;){ hold = cur; cur = cur->next; free(hold); } list->first = NULL; return; } struct sllist *sll_alloc(void){ struct sllist *list = NULL; list = calloc(1, sizeof(struct sllist)); return list; } void sll_free(struct sllist *list){ node_purge(list); free(list); return; } void sll_purge(struct sllist *list){ node_purge(list); list->count = 0; return; } int sll_push(struct sllist *list, int val){ struct sllnode *node = NULL; node = node_alloc(val); node->next = list->first; list->first = node; list->count++; return SLL_OK; } int sll_append(struct sllist *list, int val){ struct sllnode **indirect; indirect = &list->first; for (;*indirect != NULL;){ // just get where our target is. indirect = &(*indirect)->next; } /* go on until we have a empty field (regardless who holds the field) */ *indirect = node_alloc(val); list->count++; return SLL_OK; } int sll_insert(struct sllist *list, unsigned int pos, int val){ struct sllnode **indirect, *new; new = node_alloc(val); indirect = &list->first; for (unsigned int i = 0; i < pos && *indirect != NULL; ++i){ indirect = &(*indirect)->next; } new->next = (*indirect); *indirect = new; list->count++; return SLL_OK; } int sll_get(struct sllist *list, unsigned int pos, int *res){ struct sllnode **indirect; indirect = &list->first; for (unsigned int i = 0; i < pos && *indirect != NULL; ++i){ indirect = &(*indirect)->next; } if (*indirect == NULL){ return SLL_NOELEM; } *res = (*indirect)->val; return SLL_OK; } int sll_pop(struct sllist *list, int *res){ struct sllnode **indirect, *hold; indirect = &list->first; if (*indirect == NULL){ return SLL_NOELEM; } hold = *indirect; *res = hold->val; *indirect = (*indirect)->next; free(hold); list->count--; return SLL_OK; } int sll_delete(struct sllist *list, int val){ struct sllnode **indirect, *hold; indirect = &list->first; for (;*indirect != NULL && (*indirect)->val != val;){ indirect = &(*indirect)->next; } if (*indirect == NULL){ return SLL_NOELEM; } hold = *indirect; *indirect = (*indirect)->next; free(hold); // it might be NULL, but this is ok. return SLL_OK; } void sll_reverse(struct sllist *list){ struct sllnode **indirect, *new_prev, *new_next; indirect = &list->first; new_next = NULL; // the next of new end is always NULL for (;*indirect != NULL;){ new_prev = (*indirect)->next; // preserve link to next (*indirect)->next = new_next; // link to "prev" new_next = *indirect; // step new_next if (new_prev == NULL){ break; // reached "old" end } *indirect = new_prev; // go to next node } return; }
KIodine/naiveds
intrusive-rbtree/rbtree.c
#include "rbtree.h" /* * Rewrite rbtree to intrusive version: * - new nodes are prepared outside APIs. * - no alloc and free inside API. */ enum chiral { CHIRAL_LEFT = 0, CHIRAL_RIGHT = 1 }; static int node_validate(struct rbtree *tree, struct rbtnode *node){ int bh_l = 0, bh_r; if (node == tree->nil){ return 1; } if (node->color == COLOR_RED){ /* constrain #4 */ assert(node->parent->color == COLOR_BLACK); assert(node->left->color == COLOR_BLACK); assert(node->right->color == COLOR_BLACK); } bh_l = node_validate(tree, node->left); bh_r = node_validate(tree, node->right); /* constrain #5 */ assert(bh_l == bh_r); if (node->color == COLOR_BLACK){ bh_l += 1; } return bh_l; } static void left_rotate(struct rbtree *tree, struct rbtnode *x){ struct rbtnode *y = x->right, *nil = tree->nil; // struct rbtnode **y = &(*x)->right; x->right = y->left; if (y->left != nil){ y->left->parent = x; } y->parent = x->parent; if (x->parent == nil){ tree->root = y; } else if (x == x->parent->left){ x->parent->left = y; } else { // x == x->parent->right x->parent->right = y; } y->left = x; x->parent = y; return; } static void right_rotate(struct rbtree *tree, struct rbtnode *x){ struct rbtnode *y = x->left, *nil = tree->nil; x->left = y->right; if (y->right != nil){ y->right->parent = x; } y->parent = x->parent; if (x->parent == nil){ tree->root = y; } else if (x == x->parent->left){ x->parent->left = y; } else { x->parent->right = y; } y->right = x; x->parent = y; return; } /* TODO: tighten the code flow */ static void insert_fix(struct rbtree *tree, struct rbtnode *node){ struct rbtnode *uncle, *parent, *gparent; void (*rotator[2])(struct rbtree*, struct rbtnode*) = { left_rotate, right_rotate }; /* array of function pointers*/ int chiral = 0, do_case2 = 0; for (;node->parent->color == COLOR_RED;){ parent = node->parent; gparent = parent->parent; if (parent == gparent->left){ uncle = gparent->right; chiral = CHIRAL_LEFT; /* left */ do_case2 = (node == parent->right); } else { uncle = gparent->left; chiral = CHIRAL_RIGHT; /* right */ do_case2 = (node == parent->left); } if (uncle->color == COLOR_RED){ /* case #1 */ parent->color = COLOR_BLACK; uncle->color = COLOR_BLACK; gparent->color = COLOR_RED; node = gparent; continue; } if (do_case2){ /* case #2 */ node = node->parent; rotator[chiral](tree, node); parent = node->parent; gparent = parent->parent; } /* case #3 */ parent->color = COLOR_BLACK; gparent->color = COLOR_RED; rotator[!chiral](tree, gparent); } tree->root->color = COLOR_BLACK; return; } static void delete_fix(struct rbtree *tree, struct rbtnode *node){ struct rbtnode *sibling, *parent; void (*rotator[2])(struct rbtree*, struct rbtnode*) = { left_rotate, right_rotate }; /* array of function pointers*/ int chiral; struct rbtnode *nephews[2]; for (;node != tree->root && rbt_is_black(node);){ parent = node->parent; if (node == parent->left){ sibling = parent->right; chiral = CHIRAL_LEFT; } else { sibling = parent->left; chiral = CHIRAL_RIGHT; } /* * if the layout is compact, we can just assign the address of * `sibling->left` to `nephews`. * nephews = (struct rbtnode *[2])&sibling->left; */ nephews[CHIRAL_LEFT] = sibling->left; nephews[CHIRAL_RIGHT] = sibling->right; if (rbt_is_red(sibling)){ /* case #1 */ rbt_set_black(sibling); rbt_set_red(parent); rotator[chiral](tree, parent); if (chiral == CHIRAL_LEFT){ sibling = parent->right; } else { sibling = parent->left; } nephews[CHIRAL_LEFT] = sibling->left; nephews[CHIRAL_RIGHT] = sibling->right; } if (rbt_is_black(sibling->left) && rbt_is_black(sibling->right)){ /* case #2 */ sibling->color = COLOR_RED; node = parent; continue; } if (nephews[!chiral]->color == COLOR_BLACK){ /* case #3 */ nephews[chiral]->color = COLOR_BLACK; rbt_set_red(sibling); rotator[!chiral](tree, sibling); if (chiral == CHIRAL_LEFT){ sibling = parent->right; } else { sibling = parent->left; } nephews[CHIRAL_LEFT] = sibling->left; nephews[CHIRAL_RIGHT] = sibling->right; } /* case #4 */ sibling->color = parent->color; rbt_set_black(parent); nephews[!chiral]->color = COLOR_BLACK; rotator[chiral](tree, parent); node = tree->root; } rbt_set_black(node); return; } void rbtree_init(struct rbtree *tree, struct rbtnode *nil, rbt_cmp_func cmp){ nil->left = NULL; nil->right = NULL; nil->parent = NULL; nil->color = COLOR_BLACK; tree->count = 0; tree->cmp = cmp; tree->nil = nil; tree->root = nil; return; } int rbtree_validate(struct rbtree *tree){ /* constrain #2 */ assert(tree->root->color == COLOR_BLACK); /* constrain #3 */ assert(tree->nil->color == COLOR_BLACK); /* constrain #4 #5 */ node_validate(tree, tree->root); return 0; } int rbtree_set(struct rbtree *tree, struct rbtnode *node){ struct rbtnode *parent, *nil = tree->nil, **indirect; int cmpres; indirect = &tree->root; parent = *indirect; for (;;){ // this field is containing "NIL" if ((*indirect) == nil){ /* we've found an empty place, implies no corresponding key was found. */ *indirect = node; node->parent = parent; node->left = nil; node->right = nil; tree->count++; insert_fix(tree, node); break; } /* assured (*indirect) is not NULL */ /* preserve which way coming and proceed */ parent = *indirect; cmpres = tree->cmp(node, *indirect); if (cmpres == CMP_LT){ /* indirect points to the field instead */ indirect = &(*indirect)->left; } else if (cmpres == CMP_GT){ indirect = &(*indirect)->right; } else { /* we're pointing is what we're looking for */ return RBT_EXISTED; } } return RBT_OK; } struct rbtnode *rbtree_get(struct rbtree *tree, struct rbtnode *hint){ struct rbtnode *cur, *nil = tree->nil; int cmpres; cur = tree->root; for (;cur != nil;){ cmpres = tree->cmp(hint, cur); if (cmpres == CMP_EQ){ break; } if (cmpres == CMP_LT){ cur = cur->left; } else { cur = cur->right; } } if (cur == nil){ return NULL; } return cur; } void rbtree_delete(struct rbtree *tree, struct rbtnode *node){ struct rbtnode **indirect, *subst, *orphan, *nil = tree->nil; if (node == tree->root){ indirect = &tree->root; } else if (node == node->parent->left){ indirect = &node->parent->left; } else { indirect = &node->parent->right; } /* --- just a direct copy from ngx_rbtree_delete */ // maybe there is a way to shrink code size. if (node->left == nil){ orphan = node->right; subst = node; } else if (node->right == nil){ orphan = node->left; subst = node; } else { subst = rbtree_min(*indirect, nil); if (subst->left != nil){ orphan = subst->left; } else { orphan = subst->right; } } if (subst == tree->root){ tree->root = orphan; rbt_set_black(orphan); node->left = NULL; node->right = NULL; node->parent = NULL; return; } /* orphan replaces where subst be */ if (subst == subst->parent->left){ subst->parent->left = orphan; } else { subst->parent->right = orphan; } if (subst == node){ /* * can't find subst other than node itself, node is * leaf node. */ orphan->parent = subst->parent; } else { /* * set parent of orphan as the "parent" of subst. */ if (subst->parent == node){ /* subst is direct child of node */ /* * subst is moving to where original parent is, so just * link it right away. */ orphan->parent = subst; } else { orphan->parent = subst->parent; } /* copy attributes of node */ subst->left = node->left; subst->right = node->right; subst->parent = node->parent; rbt_cpy_color(subst, node); /* substitute the place holding `node` with `subst` */ *indirect = subst; if (subst->left != nil){ subst->left->parent = subst; } if (subst->right != nil){ subst->right->parent = subst; } } node->left = NULL; node->right = NULL; node->parent = NULL; /* --- */ if (node->color == COLOR_BLACK){ delete_fix(tree, orphan); } tree->count--; return; }
KIodine/naiveds
doubly-linked-list/main.c
#include <stdio.h> #include <assert.h> #include "dllist.h" #define NL "\n" void basic_test(void){ // alloc int res; struct dllist *list; printf("alloc"NL); list = dll_alloc(); // push and pop printf("push pop"NL); for (int i = 0; i < 8; ++i){ dll_push(list, i); } for (int i = 0; i < 8; ++i){ assert(dll_pop(list, &res) == DLL_OK); } assert(dll_pop(list, &res) == DLL_NOELEM); // append and get printf("append get"NL); for (int i = 0; i < 8; ++i){ dll_append(list, i); } for (int i = 0; i < 8; ++i){ assert(dll_get(list, &res) == DLL_OK); } assert(dll_get(list, &res) == DLL_NOELEM); // push and get printf("push get"NL); for (int i = 0; i < 8; ++i){ dll_push(list, i); } for (int i = 0; i < 8; ++i){ assert(dll_get(list, &res) == DLL_OK); } assert(dll_get(list, &res) == DLL_NOELEM); // push and delete printf("push delete"NL); for (int i = 0; i < 8; ++i){ dll_push(list, i); } assert(dll_delete(list, 0) == DLL_OK); assert(dll_delete(list, 0) == DLL_NOELEM); // purge and free printf("purge free"NL); dll_purge(list); dll_free(list); return; } int main(void){ basic_test(); return 0; }
saltares/grannys-bloodbath
src/engine/parser.h
<filename>src/engine/parser.h /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _PARSER_ #define _PARSER_ #include <vector> #include <string> #include "ticpp/ticpp.h" //! Parsea ficheros XML /** @author <NAME> @version 1.0 Clase que sigue el patrón de diseño Singleton (una sóla instancia accesible desde todo el sistema). Se utiliza para parsear ficheros XML. Tratamos de que todos los datos del juego estén separados del código. De esta manera se consigue que los hipotéticos diseñadores puedan cambiar parámetros de la jugabilidad sin saber programar ni recompilar el código. Se utilizará generalmente para leer aunque también se puede escribir en ficheros XML con esta clase (ficheros de configuración, por ejemplo). Ejemplo de uso: Si tenemos un fichero xml con esta estructura: \code <personaje vx="5" vy="2" energia="4" ataque="2" imagen="personaje"> <colisiones> <colision x="48" y="0" w="20" h="94" /> <colision x="0" y="38" w="115" h="16" /> </colisiones> <animaciones> <animacion nombre="normal" anim="0,1,2,3,4,5,6,7" retardo="1"/> <animacion nombre="saltar" anim="0,8,9,10,11,12,13,14,15,16" retardo="1"/> <animacion nombre="atacar" anim="0,17,18,19,20,21" retardo="1"/> <animacion nombre="morir" anim="0,22,23,24,25,26" retardo="1"/> </animaciones> </personaje> \endcode Podemos parsearlo de la siguiente forma: \code ... Parser parser("personaje.xml"); ticpp::Element* element = parser.root(); // Atributos string img; int vx, vy, energia, ataque; parser.get_attribute("energia", element, &energia); parser.get_attribute("vx", element, &vx); parser.get_attribute("vy", element, &vy); parser.get_attribute("ataque", element, &ataque); img = parser.get_attribute("imagen", element); // Cajas de colisión SDL_Rect collision_box; vector<ticpp::Element*> collisions; parser.find("colision", collisions, parser.find("colisiones")); for(vector<ticpp::Element*>::iterator i = collisions.begin(); i != collisions.end(); i++){ parser.get_attribute("x", *i, &(collision_box.x)); parser.get_attribute("y", *i, &(collision_box.y)); parser.get_attribute("w", *i, &(collision_box.w)); parser.get_attribute("h", *i, &(collision_box.h)); } ... \endcode */ class Parser{ public: /** Constructor Carga el fichero xml indicado por la ruta @param path Ruta del fichero xml a cargar */ Parser(const std::string& path); /** @return Elemento raíz del fichero XML, a partir de él, cuelgan todos los demás. */ ticpp::Element* root(); /** Consultor Accede al contenido de texto de un elemento del fichero xml @param element Elemento del que se quiere consultar su contenido @return Contenido del elemento */ std::string get_content(const ticpp::Element* element) const; /** Consultor Obtiene el atributo en forma de cadena del nombre indicado del elemento dado @param name Nombre del atributo cuyo valor se quiere consultar @param element Elemento del que se quiere saber su atributo @return Cadena con el valor del atributo */ std::string get_attribute(const std::string& name, const ticpp::Element* element) const; /** Consultor Obtiene el atributo en forma del tipo deseado del nombre indicado del elemento dado @param name Nombre del atributo cuyo valor se quiere consultar @param element Elemento del que se quiere consultar el atributo @param value Variable en la que se quiere guardar el valor del atributo @return true si la operación ha tenido éxito, false en caso contrario */ template <typename T> bool get_attribute(const std::string& name, const ticpp::Element *element, T* value) const{ if(element){ try{ element->GetAttribute(name, value); } catch(ticpp::Exception& e){ return false; } return true; } return false; } /** Busca y devuelve el primer elemento a partir de un padre con el nombre dado @param name Nombre del elemento a buscar @param element Elemento padre desde el que se realizará la búsqueda. Si se omite, se tomará la raíz, es decir, se buscará desde el principio del documento XML. */ ticpp::Element* find(const std::string& name, ticpp::Element* element = 0); /** Busca e inserta en el vector dado los elementos que coincidan con el nombre indicado @param name Nombre de los elementos a buscar @param v Vector de elementos donde se gardarán los resultados coincidentes @param element Elemento padre a partir del cual se realiza la búsqueda. Si se omite se tomará la raíz. es decir, se buscará desde el principio del documento XML. @return true si la operación tiene éxito, false, en caso contrario */ bool find(const std::string& name, std::vector<ticpp::Element*>& v, ticpp::Element* element = 0); /** Añade el elemento dado como hijo de otro también indicado. @param name Nombre del elemento a añadir @param father Padre del elemento a añadir. Si se omite se toma por defecto el elemennto raíz. @return true si la operación tiene éxito, false en caso contrario */ bool add_element(const std::string& name, ticpp::Element* father = 0); /** Establece un parámetro al elemento dado @param name Nombre del atributo a establecer @param value Valor del atributo @param element Elemento del que se quiere establecer el atributo @return true si la operación tiene éxito, false en caso contrario */ template<typename T> bool set_attribute(const std::string& name, const T& value, ticpp::Element* element){ if(element){ try{ element->SetAttribute(name, value); }catch(ticpp::Exception& e){ return false; } return true; } return false; } /** Establece el contenido del elemento dado @param value Valor del contenido a establecer @param element Elemento del que queremos establecer su valor @return true si la operación tiene éxito, false en caso contrario */ template<typename T> bool set_content(const T& value, ticpp::Element* element){ if(element){ try{ element->SetText(value); }catch(ticpp::Exception& e){ return false; } return true; } return false; } /** Guarda el documento con las modificaciones realizadas @param path ruta del fichero a guardar @return true si la operación tiene éxito, false en caso contrario */ bool save_document(const char* path); private: ticpp::Document document; void find_aux(const std::string& name, ticpp::Element* father, ticpp::Element*& element, bool& stop); void find_aux(const std::string& name, ticpp::Element* father, std::vector<ticpp::Element*>& v); }; #endif
saltares/grannys-bloodbath
src/engine/image.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _IMAGE_ #define _IMAGE_ #include <string> #include <SDL/SDL.h> //!Carga y muestra imagenes /** @author <NAME> y <NAME> @version 1.0 Esta clase se encarga de cargar imagenes en memoria y mostrar un frame determinado de ellas. Los frames se enumeran de la siguiente forma: -Por ejemplo en la fila 1, columna 1, estara el frame 1, en la fila 1 columna 2, el frame 2, y asi sucesivamente. Ejemplo: \code //Inicializa SDL... Image abuela("granny.png",8,12); //mostramos el frame 5 de la imagen de la abuela abuela.draw(screen,5,100,100); \endcode */ class Image{ public: /** Constructor Carga en memoria la imagen @param path ruta donde se encuentra la imagen @param rows numero de filas de la imagen por defecto 1 @param columns numero de columnas de la imagen por defecto 1 */ Image(const char *path, int rows = 1, int columns = 1); /** Destructor Libera de la memoria la imagen cargada */ ~Image(); /** Muestra la imagen sobre una superficie dada @param screen superficie de destino donde queremos mostrar la imagen @param f el frame de la imagen que queremos mostrar @param x eje x de la superficie de destino donde se mostrara la imagen @param y eje y de la superficie de destino donde se mostrara la imagen @param flip determina si queremos mostrar la imagen reflejada o no, por defecto no(false) */ void draw(SDL_Surface *screen, int f, int x, int y, bool flip = false); /** Metodo consultor @return ancho de un frame de la imagen */ int width() const; /** Metodo consultor @return alto de un frame de la imagen */ int height() const; /** Metodo consultor @return número de frames que tiene la imagen */ int frames() const; /** Metodo consultor @return número de filas de la imagen */ int rows() const; /** Metodo consultor @return número de columnas de la imagen */ int columns() const; /** Método consultor @param Coordenada en el eje x @param Coordenada en el eje y @return Color del píxel indicado */ Uint32 get_pixel(int x, int y) const; private: enum colors {R, G, B}; SDL_Surface * reverse_image(SDL_Surface *image); SDL_Surface *normal_image; SDL_Surface *inverted_image; int columns_, rows_, height_, width_; }; inline int Image::width() const {return width_;} inline int Image::height() const {return height_;} inline int Image::rows() const {return rows_;} inline int Image::columns() const {return columns_;} inline int Image::frames() const {return rows_* columns_;} #endif
saltares/grannys-bloodbath
src/engine/scene.h
<filename>src/engine/scene.h<gh_stars>1-10 /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SCENE_ #define _SCENE_ #include "SDL/SDL.h" class SceneMngr; //! Clase virtual pura para tratar todos los tipos de escenas de la misma manera /** @author <NAME> @version 1.0 Esta clase se utiliza para tratar en la clase que controla todas las escenas(SceneMngr) de manera uniforme */ class Scene{ public: /** Controles de los distintos tipos de escenas que trataremos en el juego */ enum Scenes{MENU, GAME, STORY, CREDITS, BOSS}; /** Constructor @param sm puntero al SceneMngr que pertence */ Scene( SceneMngr* sm ); /** Destructor */ virtual ~Scene() {} /** Metodo virtual puro Mirar función correspondiente en la clase de una escena concreta para mas información */ virtual void update() = 0; /** Metodo virtual puro Mirar función correspondiente en la clase de una escena concreta para mas información */ virtual void reset() = 0; /** * Método virtual puro * * Función a llamar cuando se vuelve a activar una escena (reproducción de músicas etc) */ virtual void resume() = 0; /** Metodo virtual puro Mirar función correspondiente en la clase de una escena concreta para mas información */ virtual void draw(SDL_Surface* screen) = 0; protected: SceneMngr* scene_mngr; }; #endif
saltares/grannys-bloodbath
src/engine/hud.h
<reponame>saltares/grannys-bloodbath<filename>src/engine/hud.h<gh_stars>1-10 /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _HUD_ #define _HUD_ #include <SDL/SDL.h> #include <SDL/SDL_image.h> #include "image.h" #include "font.h" //!Actualiza y muestra el estado de la abuela /** @author <NAME> @version 1.0 Esta clase se encarga de actualizar el estado actual de la abuela y mostralo por pantalla. Ejemplo: \code void Granny::update(){ ... ... hud.update(lifes,points,munition,energy); } void Granny::draw(SDL_Surface *Screen){ ... ... hud.draw(screen); } \endcode */ class HUD{ public: /** Constructor Carga e inicializa los distinos recursos necesarios @param path Ruta del archivo donde se encuentra la configuración deseada. @param e energía máxima que podra tener la abuela. */ HUD(const char *path, int e); /** Destructor Libera los distintos recursos cargados. */ ~HUD(); /** Se encarga de actualizar el estado actual de la abuela @param l vidas actuales de la abuela @param p puntos actuales de la abuela @param m munición actual de la abuela @param e energía actual de la abuela. */ void update(int l, int p, int m, int e); /** Método encargado de dibujar el hud sobre la imagen dada @param screen superficie destino del hud. */ void draw(SDL_Surface* screen); private: SDL_Surface *bar; Image *hud; Font *font; std::string points, lifes, munition, image_code, font_code; SDL_Rect hud_destiny, bar_destiny;//, munition_destiny, lifes_destiny, points_destiny; SDL_Color color; int max_energy, energy, lifesx, lifesy, munitionx, munitiony, pointsx, pointsy; }; #endif
saltares/grannys-bloodbath
src/engine/scenemngr.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SCENEMANAGER_ #define _SCENEMANAGER_ #include <string> #include <vector> #include <utility> #include <SDL/SDL.h> #include "scene.h" #include "application.h" class Menu; class Game; class Story; class SpecialScene; //! Maneja las escenas y el cambio entre ellas /** @author <NAME> @version 1.0 La clase se encarga de gestionar todas las escenas y el cambio de una a otra. La clase Application simplemente pide que SceneMngr se actualice y ésta actualiza la escena concreta que estime oportuno. Carga un fichero XML con el guión del juego que enumera la secuencia de escenas de historia y niveles juagables. Un ejemplo de este fichero sería: \code <plot> <scene type = "story" path = "introduction.xml" /> <scene type = "level" path = "level1.tmx" /> <scene type = "story" path = "argument.xml" /> <scene type = "level" path = "level2.tmx" /> <scene type = "story" path = "ending.xml" /> </plot> \endcode Cuando el jugador selecciona Jugar se comienza por el primer elemento del guión, cuando finaliza uno con éxito pasamos al siguiente. Si en algún momento nos eliminan volvemos al menú y comenzaríamos el guión de nuevo. Si terminamos todos los elementos con éxito también volvemos al menú. Ejemplo: \code void Application::update(){ scene_mngr->update(); } void Application::draw(){ scene_mngr->update(screen); } ... void Game::update(){ ... // Hemos llegado al final del nivel scene_mngr->end_scene(SceneMngr::SCENE_COMPLETED); ... // Eliminan a nuestro personaje y no tenemos más vidas scene_mngr->end_scene(SceneMngr::GAME_OVER); } \endcode */ class SceneMngr{ public: //! Señales que le podemos enviar al SceneMngr para que el decida qué cambios de escena hacer enum Signal{GAME_OVER, DEATH, END_AND_GO_TO_MENU, SCENE_COMPLETED, PAUSE_TO_MENU, BACK_TO_SCENE, EXIT_GAME, TO_CREDITS}; /** Constructor @param plot ruta al fichero XML con el guión del juego Crea el Manejador de escenas y comienza en el menú principal */ SceneMngr(Application* app, const std::string& plot); /** Destructor Libera la memoria ocupada por las escenas cargadas actualmente */ ~SceneMngr(); /** Actualiza de manera lógica la escena actual */ void update(); /** @param screen superficie en la que se dibuja la escena Dibuja la escena actual en la superficie dada */ void draw(SDL_Surface* screen); /** @param signal Señal para decirle al SceneMngr lo ocurrido La escena concluye e informa a SceneMngr que debe pasar a otra escena. En función de la señal, SceneMngr decide qué hacer. */ void end_scene(Signal signal); /** * @return ancho en píxeles de la pantalla */ int get_screen_width() const; /** * @return alto en píxeles de la pantalla */ int get_screen_height() const; private: Application* application; Scene* actual_scene; Scene* old_scene; Menu* menu; Game* game; SpecialScene* credits; SpecialScene* gameover; Story* story; std::vector<std::pair<Scene::Scenes, std::string> > scenes; std::vector<std::pair<Scene::Scenes, std::string> >::iterator it; // Métodos para manejar las transiciones entre escenas void game_over(); void death(); void end_to_menu(); void scene_completed(); void pause_menu(); void back_to_scene(); void exit_game(); void to_credits(); }; inline int SceneMngr::get_screen_width() const {return application->get_screen_width();} inline int SceneMngr::get_screen_height() const {return application->get_screen_height();} #endif
saltares/grannys-bloodbath
src/engine/specialscene.h
<reponame>saltares/grannys-bloodbath /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SPECIALSCENE_ #define _SPECIALSCENE_ #include <iostream> #include <string> #include <SDL/SDL.h> #include "scenemngr.h" #include "scene.h" //!Clase para manejar escenas especiales (Game Over, Créditos) /** @author <NAME> y <NAME> @version 1.0 Esta clase se utiliza para crear las escenas de game over y de créditos del juego. */ class Image; class Music; class SpecialScene: public Scene{ public: /** Constructor @param sm puntero al SceneMngr que pertence @param path ruta al fichero xml con la configuración de la escena */ SpecialScene(SceneMngr* sm, const char* path); /** Destructor */ ~SpecialScene(); /** Actualiza de manera lógica la escena */ void update(); /** Detiene Musica, y hace que comience de nuevo */ void reset(); /** * Vuelve a la escena tras una pausa */ void resume(); /** Metodo Se encarga de pintar sobre la superficie dada, todo los componentes de la escena */ void draw(SDL_Surface* screen); private: std::string ImageCode; std::string MusicCode; Image *image; Music *music; }; #endif
saltares/grannys-bloodbath
src/engine/sound.h
<gh_stars>1-10 /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SOUND_ #define _SOUND_ #include <SDL/SDL_mixer.h> #include <SDL/SDL.h> //! Carga y reproduce efectos de sonido /** @author <NAME> @version 1.0 Esta clase se encarga de cargar en memoria efectos de sonido y reproducirlos. Ejemplo: \code Sound sonido("vomito.wav"); cout << "Pulsa UP para reproducir" << endl; while(!keyboard->quit()){ keyboard->update(); if(keyboard->newpressed(Keyboard::KEY_UP)) sonido.play(); } \endcode */ class Sound{ public: /** Constructor Carga en memoria el efecto de sonido @param path ruta del efecto de sonido */ Sound(const char* path); /** Destructor Libera la memoria ocupada por el efecto */ ~Sound(); /** Reproduce el efecto de sonido una vez */ void play(); private: Mix_Chunk *sound; }; #endif
saltares/grannys-bloodbath
src/engine/actorfactory.h
<filename>src/engine/actorfactory.h /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _ACTORFACTORY_ #define _ACTORFACTORY_ #include "actor.h" class Zombie; class Dog; class Fat; class Spider; class Boss; class Bullet; class Item; class Game; //! Carga y cachea todos los actores /** @author <NAME> @version 1.0 Se utiliza para cargar los actores y minimizar el consumo de memoria y el número de accesos a disco. Cuando queremos algun actor de un tipo lo obtenemos mendiate su metodo determinado. */ class ActorFactory{ public: /* Constructor @param game Puntero a Game con el que se asocia el actor */ ActorFactory(Game *game); /* Destructor Libera recursos */ ~ActorFactory(); /* @param x posicion x en la que se cargara el zombie @param y posicion y en la que se cargara el zombie @return Puntero a zombie */ Zombie* get_zombie(int x, int y); /* @param x posicion x en la que se cargara el fat @param y posicion y en la que se cargara el fat @return Puntero a fat */ Fat* get_fat(int x, int y); /* @param x posicion x en la que se cargara el dog @param y posicion y en la que se cargara el dog @return Puntero a dog */ Dog* get_dog(int x, int y); /* @param x posicion x en la que se cargara spider @param y posicion y en la que se cargara spider @return Puntero a spider */ Spider* get_spider(int x, int y); /* @param x posicion x en la que se cargara el boss @param y posicion y en la que se cargara el boss @return Puntero a boss */ Boss* get_boss(int x, int y); /* @param x posicion x en la que se cargara el pill @param y posicion y en la que se cargara el pill @return Puntero a pill */ Item* get_pill(int x, int y); /* @param x posicion x en la que se cargara el teeth @param y posicion y en la que se cargara el teeth @return Puntero a teeth */ Item* get_teeth(int x, int y); /* @param x posicion x en la que se cargara el ammo @param y posicion y en la que se cargara el ammo @return Puntero a ammo */ Item* get_ammo(int x, int y); private: ActorFactory(const ActorFactory &a); ActorFactory& operator = (const ActorFactory& m); Zombie *zombie; Fat* fat; Dog* dog; Spider* spider; Boss* boss; Item* pill; Item* teeth; Item* ammo; Game* g; }; #endif
saltares/grannys-bloodbath
src/engine/fpsmngr.h
<gh_stars>1-10 /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _FPSMANAGER_ #define _FPSMANAGER_ //! Controla el framerrate de la aplicación /** @author <NAME> @version 1.0 Se encarga de llevar el control del framerrate deseado. Al final de cada frame se invoca la función que controla el framerrate. Si el PC donde se ejecuta la aplicación es más potente de lo debido se espera para ajustarse a la velocidad deseada. Ejemplo: \code FPSMngr fpsmngr(30); while(!keyboard->quit()){ keyboard->update(); cout << "FPS: " << fpsmngr.get_fps() << endl; cout << "Max FPS: " << fpsmngr.get_max() << endl; cout << "Best FPS: " << fpsmngr.get_best() << endl; cout << "Worst FPS: " << fpsmngr.get_worst() << endl; cout << "Average FPS: " << fpsmngr.get_average() << endl; fpsmngr.fps_control(); } \endcode */ class FPSMngr{ public: /** Constructor @param maxfps Establece el framerrate deseado */ FPSMngr(int maxfps = 30); /** Método a llamar al final de cada iteración del game loop Si el PC ha ejecutado el game loop demasiado rápido espera para ajustarse a la velocidad deseada Si no, no espera */ void fps_control(); /** Consultor @return FPS conseguidos en el último frame */ int get_fps() const; /** Consultor @return Mejor FPS desde que se activó el control de FPS */ int get_best() const; /** Consultor @return Peor FPS desde que se activó el control de FPS */ int get_worst() const; /** Consultor @return FPS medio desde que se activó el control de FPS */ double get_average() const; /** Consultor @return FPS máximos (el máximo establecido) */ int get_max() const; /** @param maxfps Nuevo máximo framerrate Establece un nuevo framerrate máximo */ void set_fps(int maxfps); private: int fps, max_fps, frame_count, best_fps, worst_fps; double average_fps; int time0, time; }; inline int FPSMngr::get_fps() const {return fps;} inline int FPSMngr::get_best() const {return best_fps;} inline int FPSMngr::get_worst() const {return worst_fps;} inline int FPSMngr::get_max() const {return max_fps;} #endif
saltares/grannys-bloodbath
doc/pspdev/keyboard.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _KEYBOARD_ #define _KEYBOARD_ #include <pspkernel.h> #include <pspctrl.h> #include <valarray> #include <map> //! Gestiona el teclado, consultamos teclas pulsadas /** @author <NAME> @version 1.0 Clase que sigue el patron de diseno Singleton (una sola instancia accesible desde todo el sistema). Lleva el control de que teclas estan pulsadas en un momento determinado, cuales se sueltan y cuales se vuelven a presionar. Ejemplo de uso \code // Game loop while(!quit){ keyboard->update() // Equivalente a Keyboard::get_instance()->update(); if(keyboard->pressed(Keyboard::KEY_UP)) // Si pulsamos arriba ... if(keyboard->released(Keyboard::KEY_HIT)) // Si dejamos de pulsar golpear ... if(keyboard->newpressed(Keyboard::KEY_SHOOT)) // Si antes soltamos y // ahora pulsamos disparar } \endcode */ class Keyboard{ public: /** Controles del teclado utilizados en el juego */ enum keys{ KEY_UP, KEY_DOWN, KEY_RIGHT, KEY_LEFT, KEY_SHOOT, KEY_HIT, KEY_KNEEL, KEY_EXIT, KEY_ENTER }; /** @return Si es la primera vez que se usa Keyboard crea su instancia y la devuelve. Sino simplemente la devuelve. */ static Keyboard* get_instance(){ /* Si es la primera vez que necesitamos Keyboard, lo creamos */ if(_instance == 0) _instance = new Keyboard; return _instance; } /** Actualiza el estado del teclado. Debe llamarse una vez al comienzo del game loop. */ void update(); /** @param key Tecla a consultar @return true si la tecla esta pulsada, false en caso contrario. */ bool pressed(keys key); /** @param key Tecla a consultar @return true si la tecla estaba antes pulsada en la ultima actualizacion y ahora no lo esta, false en caso contrario. */ bool released(keys key); /** @param key Tecla a consultar @return true si la tecla no estaba pulsada en la ultima actualizacion y ahora lo esta, false en caso contrario. */ bool newpressed(keys key); /** @return true si se ha producido algun evento de salida, false en caso contrario */ bool quit(); void set_quit() {_quit = true;} protected: Keyboard(); ~Keyboard(); Keyboard(const Keyboard& k); Keyboard& operator = (const Keyboard& k); private: static Keyboard* _instance; std::valarray<bool> actual_keyboard; std::valarray<bool> old_keyboard; bool _quit; std::map<keys, PspCtrlButtons> configured_keys; SceCtrlData buttonInput; int n_keys; }; #define keyboard Keyboard::get_instance() #endif
saltares/grannys-bloodbath
src/engine/story.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _STORY_ #define _STORY_ #include <iostream> #include <string> #include <SDL/SDL.h> #include "scenemngr.h" #include "scene.h" class Image; class Music; class Font; class BoxedText; //! Clase virtual pura para tratar todos los tipos de escenas de la misma manera /** @author <NAME> @version 1.0 Esta clase se utiliza para tratar en la clase que controla todas las escenas(SceneMngr) de manera uniforme */ class Story: public Scene{ public: /** Constructor @param sm puntero al SceneMngr que pertence */ Story( SceneMngr* sm , const char* path ); /** Destructor */ ~Story(); /** Metodo Comprueba el estado de la escena */ void update(); /** Metodo Detiene Musica/Narrador, y hace que comiencen de nuevo */ void reset(); /** * Función a llamar cuando se vuelve a activar una escena story (vuelve a comenzar el narrador) */ void resume(); /** Metodo Se encarga de pintar sobre la superficie dada, todo los componentes de la escena */ void draw(SDL_Surface* screen); private: std::string ImageCode; std::string MusicCode; std::string FontCode; Image *image; Music *narrator; Font *font; BoxedText* boxedtext; SDL_Color ColorText; SDL_Rect PositionText; std::string text; }; #endif
saltares/grannys-bloodbath
src/engine/keyboard.h
<reponame>saltares/grannys-bloodbath /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _KEYBOARD_ #define _KEYBOARD_ #include <SDL/SDL.h> #include <valarray> #include <map> //! Gestiona el teclado, consultamos teclas pulsadas /** @author <NAME> @version 1.0 Clase que sigue el patrón de diseño Singleton (una sóla instancia accesible desde todo el sistema). Lleva el control de qué teclas están pulsadas en un momento determinado, cuáles se sueltan y cuáles se vuelven a presionar. Ejemplo de uso \code // Game loop while(!quit){ keyboard->update() // Equivalente a Keyboard::get_instance()->update(); if(keyboard->pressed(Keyboard::KEY_UP)) // Si pulsamos arriba ... if(keyboard->released(Keyboard::KEY_HIT)) // Si dejamos de pulsar golpear ... if(keyboard->newpressed(Keyboard::KEY_SHOOT)) // Si antes soltamos y ahora pulsamos disparar } \endcode */ class Keyboard{ public: //! Controles del teclado utilizados en el juego enum keys{ KEY_UP, KEY_DOWN, KEY_RIGHT, KEY_LEFT, KEY_SHOOT, KEY_HIT, KEY_EXIT, KEY_ACCEPT }; /** @return Si es la primera vez que se usa Keyboard crea su instancia y la devuelve. Sino simplemente la devuelve. */ static Keyboard* get_instance(){ /* Si es la primera vez que necesitamos Keyboard, lo creamos */ if(_instance == 0) _instance = new Keyboard; return _instance; } /** Actualiza el estado del teclado. Debe llamarse una vez al comienzo del game loop. */ void update(); /** @param key Tecla a consultar @return true si la tecla está pulsada, false en caso contrario. */ bool pressed(keys key); /** @param key Tecla a consultar @return true si la tecla estaba antes pulsada en la última actualización y ahora no lo está, false en caso contrario. */ bool released(keys key); /** @param key Tecla a consultar @return true si la tecla no estaba pulsada en la última actualización y ahora lo está, false en caso contrario. */ bool newpressed(keys key); /** @return true si se ha producido algún evento de salida, false en caso contrario */ bool quit(); /** * Activa el flag para indicar que se desea salir de la aplicación */ void set_quit(); protected: Keyboard(); ~Keyboard(); Keyboard(const Keyboard& k); Keyboard& operator = (const Keyboard& k); private: static Keyboard* _instance; std::valarray<bool> actual_keyboard; std::valarray<bool> old_keyboard; bool _quit; std::map<keys, SDLKey> configured_keys; int n_keys; }; #define keyboard Keyboard::get_instance() #endif
saltares/grannys-bloodbath
src/engine/item.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _ITEM_ #define _ITEM_ #include "actor.h" class Game; //! Clase que modela los objetos recolectables del juego /** * @author <NAME> * @version 1.0 * * Agrupa a los objetos que se pueden recoger en el juego. Contiene sus tipos y proporciona una forma de tratarlos de manera común. */ class Item: public Actor{ public: /** * Distintos tipos de Item */ enum ItemType{TEETH, PILLS, AMMO}; /** Constructor @param g Puntero a Game con el que se asocia el actor */ Item(Game *g); /** * Constructor * * @param game puntero al objeto que controla el juego * @param path ruta con la información del item en XML * @param x coordenada inicial en el eje x del item * @param y coordenada inicial en el eje y del item */ Item(Game* game, const char* path, int x, int y); /** * Destructor * * Libera la memoria ocupada por el ítem */ ~Item(); /** * Actualiza lógicamente el ítem */ void update(void); /** * Función a llamar cuando Granny colisiona con el ítem. * Marca a Ítem para ser borrado. * * @param a Actor con el que colisiona */ void collides(Actor& a); /** * @param x Coordenada en el eje x del nuevo item * @param y Coordenada en el eje y del nuevo item * * @return Crea un nuevo item copia del primero (salvo por la posición) y devuelve un puntero */ Item* clone(int x, int y); ItemType get_type() const; private: ItemType type; }; #endif
saltares/grannys-bloodbath
src/engine/game.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _GAMEGRANNY_ #define _GAMEGRANNY_ #include <list> #include <string> #include "story.h" #include "collisionmngr.h" #include "level.h" class SceneMngr; class Granny; class Enemy; class Item; class Bullet; class Music; //! Clase que lleva el control de una escena de juego /** * @author <NAME> * @version 1.0 * * Clase que crea un nivel de juego y controla a todos los actores que intervienen en él. Es la clase principal para el juego. * SceneMngr es el encargado (leyendo el guión del juego) de lanzar una escena tipo Game con un nivel determinado. * Simplemente llamando a sus métodos update y draw se va actualizando. * Cuando se llega al final del nivel, se produce la muerte del personaje o algún evento similar Game avisa a su SceneMngr para que actúe en consecuencia. */ class Game: public Scene{ public: /** * Constructor * @param sm SceneMngr que controla a la escena Game * @param path Ruta del fichero XML con el nivel a cargar * @param boos_fight true si estamos en una pelea con un jefe final, false si es un nivel normal. * Esto afecta a la manera de terminar el nivel: * - Escena normal: llegar al final del nivel. * - Boss Fight: eliminar a todos los enemigos. */ Game(SceneMngr* sm, const char* path, bool boss_fight = false); /** * Destructor * * Libera todos los recursos ocupados por la escena de juego */ ~Game(); /** * Actualiza lógicamente la escena de juego (mueve actores, hace scrolling, detecta y responde a las colisiones...) */ void update(); /** * Resetea la escena de juego */ void reset(); /** * Vuelve a la escena de juego (activa la bso) */ void resume(); /** * Dibuja en pantalla un frame de la escena * * @param screen Superficie donde se bliteará la escena */ void draw(SDL_Surface* screen); /** * Añade un Item a la escena de juego. * Esta función la utilizará el constructor de Level para establecer los actores iniciales bajo el control de Game * * @param item Item a añadir (se añadirá el item en su posición) */ void add_item(Item* item); /** * Añade un Enemy a la escena de juego. * Esta función la utilizará el constructor de Level para establecer los actores iniciales bajo el control de Game * * @param enemy Enemy a añadir (se añadirá el item en su posición) */ void add_enemy(Enemy* enemy); /** * Añade la abuelita bajo el control del juego * * @param abuelita que se añade (debe estar creada y sólo añadirse una vez cada vez que se crea Game) */ void add_granny(Granny* granny); /** * Añade una bala a la escena del juego * * @param bala que se añade */ void add_bullet(Bullet* bullet); /** * Establece la música que debe sonar durante el juego * * @param music Música a reproducir * * Esta función debería llamarla Level en su constructor */ void set_music(const std::string& music_code); /** * Detecta si un actor esta tocando el suelo * * @param actor actor del que se quiere saber si toca el suelo * @param level escenario que se quiere consultar * @param x coordenada en el eje x en la que se quiere comprobar la colisión * @param y coordenada en el eje y en la que se quiere comprobar la colisión * @return true si al actor toca el suelo, false en caso contrario */ bool on_ground(const Actor& actor, int x, int y) const; /** * Detecta si un actor está en pantalla * * @param actor actor del que se quiere saber si está en pantalla * @return true si el actor está en pantalla, false en caso contrario */ bool on_screen(const Actor& actor) const; /** * @return Scroll en el eje x del nivel */ int level_x() const; /** * @return Scroll en el eje y del nivel */ int level_y() const; const Granny* get_granny(); private: Level* level; Music* music; std::string music_code; std::string level_path; CollisionMngr collision_mngr; Granny* granny; std::list<Enemy*> enemy_list; std::list<Item*> item_list; std::list<Bullet*> bullet_list; bool boss_fight; void check_collisions(); void delete_actors(); void check_end(); }; inline int Game::level_x() const {return (level)? level->get_x() : 0;} inline int Game::level_y() const {return (level)? level->get_y() : 0;} inline const Granny* Game::get_granny(){ return granny; } #endif
saltares/grannys-bloodbath
src/engine/collisionmngr.h
<reponame>saltares/grannys-bloodbath #ifndef _COLLISIONMNGR_ #define _COLLISIONMNGR_ #include <vector> #include "actor.h" #include "level.h" //! Clase para gestionar colisiones entre actores y con el escenario /** @author <NAME> @version 1.0 Esta clase se utiliza para detectar y gestionar colisiones tanto actor-actor como actor-nivel. CollisionMngr se encarga de corregir propiedades de los actores relacionadas con el movimiento (posición, velocidad...) para que dejen de colisionar. La entidad que llame a los métodos de CollisionMngr es la responsable de cambiar otras propiedades como items, vida o eliminar a alguno de los que colisionan. Ejemplo de uso: \code void Game::update() { abuela->update(); update_enemies(); update_items(); ... // Colisiones escenario-abuela collision_mngr.level_collision(*abuela, *level); // Colisiones abuela-enemigo // para cada enemigo: for(list<Enemy*>::iterator i = enemies.begin(); i != enemies.end(); ++i){ if(collision_mngr.actor_collision(*abuela, *level)){ if(abuela->state == Actor::HIT) (*i)->collides(*abuela); else abuela->collides(*(*i)); } } ... } \endcode */ class CollisionMngr{ public: /** Detecta colisiones entre actores @param a1 Actor del que se quieren conocer sus colisiones @param actor2 Actor con el que se quieren consultar las colisiones @return true si el actor 1 colisiona con el actor 2, false en caso contrario */ bool actor_collision(Actor& a1, Actor& a2) const; /** Detecta colisiones actor-nivel y corrige la posición y estado del actor @param actor Actor del que se quieren conocer sus colisiones @param level Nivel con el que se quiere saber la colisión */ bool level_collision(Actor& actor, Level& level); /** * Detecta si un actor esta tocando el suelo * * @param actor del que se quiere saber si toca el suelo * @param level escenario que se quiere consultar * @param x coordenada en el eje x en la que se quiere comprobar la colisión * @param y coordenada en el eje y en la que se quiere comprobar la colisión * @return true si al actor toca el suelo, false en caso contrario */ bool on_ground(const Actor& actor, const Level& level, int x, int y) const; /** Detecta colisiones bala-nivel @param actor Bala del que se quieren conocer sus colisiones @param level Nivel con el que se quiere saber la colisión */ bool bullet_collision(const Actor& bullet, Level& level) const; private: bool collision(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) const; bool collision_hor(int x, int y, Uint16 w, Uint16 h, int& tilecoordy, const Level& level, bool up) const; bool collision_ver(int x, int y, Uint16 w, Uint16 h, int& tilecoordx, const Level& level, bool right) const; }; #endif
saltares/grannys-bloodbath
src/engine/level.h
<reponame>saltares/grannys-bloodbath /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _LEVEL_ #define _LEVEL_ #include <string> #include <map> #include "image.h" #include "actorfactory.h" class Game; /** Tipos de tiles que puede haber <ul> <li>PASSABLE: se puede atravesar</li> <li>NONPASSABLE: no se puede atravesar</li> <li>PLATFORM: se puede atravesar pero nos podemos montar encima</li> </ul> */ enum TileType{PASSABLE = 0, NONPASSABLE, PLATFORM}; //! Estructura que guarda la información de un tile del escenario /** @author <NAME> @version 1.0 Estructura que guarda el frame (para poder dibujarlo) del tileset que representa ese tile y su tipo (utilizado para las colisiones) */ struct Tile{ /** frame del tileset que representa */ int frame; /** tipo de tile */ TileType type; }; //! Clase para manejar los escenarios del juego /** @author <NAME> @version 1.0 Clase que nos permite cargar, actualizar y dibujar escenarios creados en formato XML con la herramienta Tiled. Al construirse crea el mapa, carga el tileset y coloca a todos los actores en el escenario Para construir un nivel compatible con Granny's Bloodbath debe usar Tiled siguiendo el manual que se proporciona para ello. Ejemplo de uso: \code // Inicialización Level level = new Level("level.tmx", screen); ... // Game loop while(!salir){ ... // Actualizamos lógicamente a los actores ... // Movemos la cámara del nivel level.move(x, y); // Dibujamos las capas del nivel level.draw(screen, 0); level.draw(screen, 1); dibujar_actores(); level.draw(screen, 2); // Capa que queda por encima if(level.get_x() >= ...){ // Hemos llegado al final del nivel } } \endcode */ class Level{ public: /** Constructor @param game Objeto Game con el que se asocia el nivel @param path Ruta donde está la información del nivel */ Level(Game* game, const char* path); /** Destructor Libera los recursos ocupados por nivel */ ~Level(); /** @param screen Superficie donde se dibujará el nivel @param layer Capa del nivel a dibujar Dibuja la capa indicada en la superficie dada */ void draw(SDL_Surface* screen, int layer); /** Consultor @return Coordenada en el eje x del nivel (scroll) En píxeles */ int get_x() const; /** Consultor @return Coordenada en el eje y del nivel (scroll) En píxeles */ int get_y() const; /** @param x Nueva coordenada en el eje x del nivel (scroll) En píxeles @param y Nueva coordenada en el eje y del nivel (scroll) En píxeles */ void move(int x, int y); /** @param x Coordenada en el eje x a consultar En tiles @param y Coordenada en el eje y a consultar En tiles */ Tile get_tile(int x, int y, int layer) const; /** Consultor @return Ancho del nivel en tiles */ int get_width() const; /** Consultor @return Alto del nivel en tiles */ int get_height() const; /** Consultor @return Ancho de un tile en píxeles */ int get_tile_width() const; /** Consultor @return Alto de un tile en píxeles */ int get_tile_height() const; private: void load_actors(); Game* g; Tile ***level; Image* tileset; std::map<int, std::string> actors_map; int x, y, width, height, tile_height, tile_width; ActorFactory* actor_factory; }; inline int Level::get_x() const {return x;} inline int Level::get_y() const {return y;} inline int Level::get_width() const {return width;} inline int Level::get_height() const {return height;} inline int Level::get_tile_width() const {return tile_height;} inline int Level::get_tile_height() const {return tile_width;} #endif
saltares/grannys-bloodbath
src/engine/boxedtext.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _BOXEDTEXT_ #define _BOXEDTEXT_ #include <string> #include <SDL/SDL.h> #include "font.h" //! Clase que se encarga de renderizar texto en un SDL_Rect de forma que no se salga del mismo /** @author <NAME> @version 1.0 Clase que almacena un texto y se encarga de renderizarlo dentro de unos límites. No es necesario introducir saltos de línea ya que la clase se encarga de colocarlos donde sean necesarios. Esta clase se utiliza para mostrar el texto con la historia en las escenas tipo Story */ class BoxedText{ public: /** Constructor @param font Fuente con la que se renderizará el texto @param color Color del texto @param box Caja que representa la posición y los límites del texto @param text Texto a renderizar */ BoxedText(Font* font, SDL_Color color, SDL_Rect box, const std::string& text = ""); /** Destructor Libera los recursos ocupados por el objecto BoxedText */ ~BoxedText(); /** @param screen Superficie donde se renderizará el texto Renderiza el texto en la superficie dada con sus propiedades (texto, color, caja y fuente) */ void draw(SDL_Surface* screen); /** Consultor @return Caja que limita al texto */ SDL_Rect get_rect() const; /** Consultor @return Color del texto */ SDL_Color get_color() const; /** Consultor @return Texto almacenado */ const std::string& get_text() const; /** @param rect Nuevo rectángulo que limitará al texto */ void set_rect(SDL_Rect rect); /** @param color Nuevo color del texto */ void set_color(SDL_Color color); /** @param font Nueva Fuente que usará el texto */ void set_font(Font* font); /** @param text Nuevo texto a dibujar */ void set_text(const std::string& text); private: bool changed; bool first_time; Font* font_; SDL_Color color_; SDL_Rect rect_; std::string text_; SDL_Surface* rendered_text; }; inline SDL_Rect BoxedText::get_rect() const {return rect_;} inline SDL_Color BoxedText::get_color() const {return color_;} inline const std::string& BoxedText::get_text() const {return text_;} #endif
saltares/grannys-bloodbath
src/engine/option.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _OPTION_ #define _OPTION_ #include <string> #include <iostream> #include <SDL/SDL.h> #include "font.h" //! Opción de la escena Menu /** @author <NAME> @version 1.0 Se utiliza para crear una opción del menú del juego, y posteriormente poder pintarla y gestionarla. En el menú cargaremos varias opciones, por lo que esta clase nos abstraerá bastante el trabajo. */ class Option{ public: Option(const std::string& text, Font* font, int x, int y, SDL_Color sel, SDL_Color nosel): text_(text), font_(font), x_(x), y_(y), selected_col(sel), nselected_col(nosel){}; void draw(SDL_Surface* screen, bool selected = false); int get_x() const; int get_y() const; const std::string& get_text() const; private: std::string text_; Font* font_; int x_, y_; SDL_Color selected_col, nselected_col; }; inline int Option::get_x() const {return x_;} inline int Option::get_y() const {return y_;} inline const std::string& Option::get_text() const {return text_;} #endif
saltares/grannys-bloodbath
src/engine/actor.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _ACTOR_ #define _ACTOR_ #include <iostream> #include <vector> #include <map> #include <string> #include "image.h" #include "animation.h" class Game; class Parser; //! Clase virtual pura que abstrae las características básicas de los actores (abuela, enemigos, ítems etc) /** @author <NAME> @version 1.0 Es una clase que abstrae lo básico del comportamiento y las características de los personajes (posición, estado, velocidad, animaciones, cajas de colisión...). No adjunto código de ejemplo ya que la clase es virtual pura. */ class Actor{ public: //! Tipos de actores enum Type{GRANNY, ENEMY, ITEM}; //! Posibles estados en los que puede encontrarse el actor enum State{NORMAL, MOVE, ATTACK, JUMP, DAMAGED, KNEEL, DIE, ERASE, RISE, NORMALDOWN}; //! Cada animación se asocia a un estado del personaje typedef std::map<State, Animation* > Animations; //! Conjunto de cajas de colisión, se asociará con un único estado del personaje typedef std::vector<SDL_Rect > Collision_Rects; //! Cajas de colisión asociadas a un estado del personaje typedef std::map<State, Collision_Rects > Collision_Map; /** Constructor @param game Puntero a Game con el que se asocia el actor */ Actor(Game* game); /** * Destructor * * Libera la memoria ocupada por Actor */ virtual ~Actor(); /** @return Posición en el eje x del actor */ int get_x() const; /** @return Posición en el eje y del actor */ int get_y() const; /** @return Posición en el eje x del actor en el frame anterior */ int get_old_x() const; /** @return Posición en el eje y del actor en el frame anterior */ int get_old_y() const; /** @return Velocidad en el eje x del actor */ int get_vx() const; /** @return Velocidad en el eje y del actor */ int get_vy() const; /** @return Estado actual del actor */ State get_state() const; /** @return Cajas de colisión del actor según su estado actual */ const Collision_Rects& get_rects() const; /** @return true el actor mira a la izquierda, false en caso contrario */ bool get_direction() const; /** * @return Ancho de un frame del sprite en píxeles */ bool get_image_width() const; /** * @return Alto de un frame del sprite en píxeles */ bool get_image_height() const; /** @return recuadro con las dimensiones reales de la abuela dentro de la rejilla */ SDL_Rect get_real_dimensions() const; /** @param x Nueva posición en el eje x @param y Nueva posición en el eje y */ void move(int x, int y); /** @param vx Nueva velocidad en el eje x */ void set_vx(int vx); /** @param vy Nueva velocidad en el eje y */ void set_vy(int vy); /** @param state Nuevo estado del actor */ void set_state(State state); /** @param direction Nueva dirección del actor (true -> izquierda, false -> derecha) */ void set_direction(bool direction); /** @param Superficie donde se dibujará el actor Dibuja el actor en la superficie dada según su posición y animación actuales */ void draw(SDL_Surface* screen); /** Virtual pura Actualiza lógicamente al personaje */ virtual void update() = 0; /** Virtual pura @param a Actor con el que colisiona Hace que el actor reaccione a la colisión (restar vida, añadir objeto...) */ virtual void collides(Actor& a) = 0; protected: Game* g; int x, y, vx, vy, vx0, vy0, old_x, old_y; bool direction; Image* image; std::string image_code; std::map<State, SDL_Rect> real_dimensions; std::map<State, SDL_Rect> real_dimensions_inverted; Collision_Map collision_map; Collision_Map collision_map_inverted; Animations animations; State state, previous_state; Type type; void parse_basic_info(Parser& parser); }; inline int Actor::get_x() const {return x;} inline int Actor::get_y() const {return y;} inline int Actor::get_old_x() const {return old_x;} inline int Actor::get_old_y() const {return old_y;} inline int Actor::get_vx() const {return vx;} inline int Actor::get_vy() const {return vy;} inline Actor::State Actor::get_state() const {return state;} inline bool Actor::get_direction() const {return direction;} inline bool Actor::get_image_width() const {return image->width();} inline bool Actor::get_image_height() const {return image->height();} #endif
saltares/grannys-bloodbath
src/engine/logger.h
#ifndef _LOGGER_ #define _LOGGER_ #include <iostream> #include <fstream> #include <string> //! Gestiona los logs de eventos, utilizado para depuración /** @author <NAME> @version 1.0 Clase que sigue el patrón de diseño Singleton (una sóla instancia accesible desde todo el sistema). Se utiliza para llevar un registro de lo que ocurre en el sistema. Si queremos escribir un mensaje (normal, de error o de aviso) lo utilizaremos. Podemos desviar la salida hacia un fichero en lugar de a la salida estándar. Ejemplo de uso \code // Comienzo del programa logger->open_file(); ... // Constructor de la clase Image Image::Image(const char* path, int rows, int cols) { logger->message("Entrando en Image::Image()"); // Equivalente a Logger::get_instance->message("Entrando en Image::Image()"); ... if(error){ logger->error("No se pudo abrir la imagen"); exit(1); } ... logger->message("Saliendo de Image::Image()"); } \endcode */ class Logger{ public: /** @return Si es la primera vez que se usa Logger llama a su constructor, sino es así, devuelve la única instancia de Logger */ static Logger* get_instance(){ if(_instance == 0) _instance = new Logger; return _instance; } /** Abre el fichero indicado (sino lo existe, lo crea) y comienza a escribir al final del fichero Si no se indica nombre de fichero toma por defecto: Grannys_dd-mm-aaaa_hh-mm-ss.log @param path Ruta del fichero */ void open_file(const std::string& path = ""); /** Cierra el fichero del log, si estaba cerrado no hace nada. A partir de ahora los mensajes se mostrarán en la salida estándar o en la salida estándar de errores (si es de error). */ void close_file(); /** Escribe un mensaje común en el fichero si está abierto, sino en la salida estándar @param msg Mensaje a escribir */ void message(const std::string& msg); /** Escribe un mensaje de error en el fichero si está abierto, sino en la salida estándar de errores @param msg Mensaje a escribir */ void error(const std::string& msg); /** Escribe un mensaje de aviso en el fichero si está abierto, sino en la salida estándar @param msg Mensaje a escribir */ void warning(const std::string& msg); protected: Logger(); Logger(const Logger& logger); Logger& operator = (const Logger& logger); ~Logger(); private: void write_header(); static Logger* _instance; std::ofstream file; }; #define logger Logger::get_instance() #endif
saltares/grannys-bloodbath
src/engine/spider.h
<filename>src/engine/spider.h /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _SPIDER_ #define _SPIDER_ #include "enemy.h" //! Clase encargada de controlar el comportamiento de la araña /** @author <NAME> @version 1.0 */ class Game; class Bullet; class Sound; class Spider:public Enemy{ public: /** Constructor @param g Puntero a Game con el que se asocia con la araña */ Spider(Game *g); /** Constructor @param g Puntero a Game con el que se asocia la araña @param path ruta del fichero que contiene las distintas caracteristicas del personaje @param x coordenada x del personaje @param y coordenada y del personaje */ Spider(Game *g, const char *path, int x, int y); /** Destructor Liberamos recursos usados por el personaje. */ ~Spider(); /** Actualiza lógicamente al personaje */ void update(); /** @param x Coordenada en el eje x del nuevo clon @param y Coordenada en el eje y del nuevo clon @return Clon del zombie gordo en una posición dada */ Actor *clone(int x, int y); /** @param a Actor con el que colisiona Hace que el zombie reaccione a la colisión (restar vida, añadir objeto...) */ void collides(Actor &a); private: Bullet *bullet; int vx2, actual_vx; Sound* attack; std::string attack_code; int shoot_delay, actual_shoot_delay; void shoot_spiderweb(); bool within_range(); void normal_state(); void jumping_state(); void moving_state(); void attack_state(); void attackTOnormal_state(); void damaged_state(); void death_state(); }; #endif
saltares/grannys-bloodbath
src/engine/music.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _MUSIC_ #define _MUSIC_ #include <SDL/SDL.h> #include <SDL/SDL_mixer.h> //!Carga y reproduce musica /** @author <NAME> @version 1.0; Esta clase se encarga de cargar musica/canciones y reproducirlos Ejemplo: \code Music musica("prueba.ogg"); while(!keyboard->quit()){ keyboard->update(); if(keyboard->newpressed(Keyboard::KEY_UP)) musica.play(); else if(keyboard->newpressed(Keyboard::KEY_DOWN)) musica.pause(); \endcode */ class Music{ public: /** Constructor Carga en memoria la canción @param path ruta de la cancion */ Music(const char *path); /** Destructor Libera la memoria ocupada por la cancion */ ~Music(); /** Reproduce la canción @param loop número de bucles (-1 para bucle infinito) */ void play(int loop = -1); /** Pausa la canción */ void pause(); /** Detiene la canción */ void stop(); /** Reproduce la canción con un fadein de unos milisegundos dados @param ms milisegundo de la duracion del fadein @param loop número de bucles (-1 para bucle infinito) */ void fadein(int ms, int loop = -1); /** Detiene la canción con un fadeout de unos milisegundos dados @param ms milisegundo de la duracion del fadeout */ void fadeout(int ms); /** @return true si hay música sonando, false en caso contrario */ bool playing() const; private: Mix_Music *music_; }; inline void Music::pause(){ Mix_PauseMusic(); } inline void Music::stop(){ Mix_HaltMusic(); } inline bool Music::playing() const {return (Mix_PlayingMusic())? true : false;} #endif
saltares/grannys-bloodbath
src/engine/enemy.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _ENEMY_ #define _ENEMY_ #include "actor.h" #include "game.h" //! Clase virtual pura que abstrae las características básicas de los enemigos (zombie, dog, fat) /** @author <NAME> @version 1.0 Es una clase que abstrae lo básico del comportamiento y las características de los enemigos. */ class Sound; class Enemy: public Actor{ public: /** Constructor @param g Puntero a la clase Game con la que se aosica el enemigo. */ Enemy(Game *g); ~Enemy(); /** @return Fuerza de ataque que tiene el enemigo */ int get_force()const; /** @param f nuevo valor para la fuerza del ataque del enemigo */ void set_force(int f); /** @return Energía actual del enemigo */ int get_energy()const; /** @param Nuevo valor para la energia del enemigo */ void set_energy(int e); /** Cambia la dirección del enemigo */ void change_direction(); /** @return retraso entre ataque y ataque */ int get_attackdelay()const; /** @param e nuevo valor para el retraro entre ataque y ataque */ void set_attackdelay(int e); /** @return retraso actual entre ataque y ataque */ int get_actualdelay()const; /** @param e nuevo valor para el retraso actual entre ataque y ataque */ void set_actualdelay(int e); /** * Función para dañar al enemigo */ void damaged(); protected: bool in_view(); Sound* hurt; std::string hurt_code; int energy, force, attack_delay, actual_delay; }; inline int Enemy::get_force()const{ return force; } inline void Enemy::set_force(int f){ force = f; } inline int Enemy::get_energy()const{ return energy; } inline void Enemy::set_energy(int e){ energy = e; } inline int Enemy::get_attackdelay()const{ return attack_delay; } inline void Enemy::set_attackdelay(int e){ attack_delay = e; } inline int Enemy::get_actualdelay()const { return actual_delay; } inline void Enemy::set_actualdelay(int e){ actual_delay = e; } #endif
saltares/grannys-bloodbath
src/engine/font.h
<filename>src/engine/font.h /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _FONT_ #define _FONT_ #include <string> #include <SDL/SDL.h> #include <SDL/SDL_ttf.h> //! Clase para cargar y dibujar fuentes ttf personalizadas /** @author <NAME> @version 1.0 Permite cargar de disco fuentes ttf a un tamaño determinado y dibujar cadenas de texto en un color dado. Es posible establecer el alineamiento horizontal con respecto a la superficie sobre la que se dibuja. Ejemplo: \code Font matter("matteroffact.ttf", 60); Font hand("handsean.ttf", 30); matter.draw(pantalla, "Granny's Bloodbath", rojo, 40, Font::CENTER); hand.draw(pantalla, "El plataformas de acción de la abuela y los zombies", blanco, 110, Font::CENTER); cout << "Ancho de Granny's Bloodbath: " << matter.text_width("Granny's Bloodbath") << endl; cout << "Alto de Granny's Bloodbath: " << matter.text_height("Granny's Bloodbath") << endl; cout << "Salto de línea de matteroffact: " << matter.line_skip() << endl; SDL_Flip(pantalla); \endcode */ class Font{ public: /** Sirve para determinar el alineamiento horizontal deseado a la hora de dibujar */ enum Alignment{LEFT, RIGHT, CENTER}; /** Constructor Carga de disco una fuente ttf a un tamaño determinado @param path ruta de la fuente a cargar @size tamaño en puntos de la fuente */ Font(const char* path, int size = 20); /** Destructor Libera la memoria ocupada por la fuente */ ~Font(); /** Dibuja la cadena de texto en el color dado en la superficie indicada @param screen superficie sobre la que se dibujará la cadena @param text texto a dibujar @param color color del texto @param x coordenadas en el eje x donde se dibujará (en píxeles) @param y coordenadas en el eje y donde se dibujará (en píxeles) */ void draw(SDL_Surface* screen, const std::string& text, SDL_Color color, int x, int y); /** Dibuja la cadena de texto en el color dado en la superficie indicada con alineamiento @param screen superficie sobre la que se dibujará la cadena @param text texto a dibujar @param color color del texto @param y coordenadas en el eje y donde se dibujará (en píxeles) @param alignment alineamiento de la cadena a dibujar */ void draw(SDL_Surface* screen, const std::string& text, SDL_Color color, int y, Alignment alignment); /** Consultor @return tamaño de la fuente en puntos */ int get_size() const; /** Consultor @param texto del que se quiere conocer su ancho @return ancho que ocuparía el texto al ser dibujado (en píxeles) */ int text_width(const std::string& text) const; /** Consultor @param texto del que se quiere conocer su alto @return alto que ocuparía el texto al ser dibujado (en píxeles) */ int text_height(const std::string& text) const; /** Consultor @return salto de línea recomendado */ int line_skip() const; private: TTF_Font* font; int size_; SDL_Surface* surface; }; inline int Font::get_size() const {return size_;} inline int Font::line_skip() const {return TTF_FontLineSkip(font);} #endif
saltares/grannys-bloodbath
src/engine/bullet.h
<filename>src/engine/bullet.h /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _BULLET_ #define _BULLET_ #include <string> #include "game.h" #include "image.h" #include "actor.h" //! Clase encarga del comportamiento de la bala /** @author <NAME> @version 1.0 Bullet hereda de la clase virtual pura Actor. */ class Bullet: public Actor{ public: //! Señales para indicar quien es el actor que dispara enum Owner{GRANNY, FAT, BOSS}; /** Constructor @param g Puntero a Game con el que se asocia la bala */ Bullet(Game *g); /** Constructor @param g Puntero a Game con el que se asocia la bala @param path ruta del fichero de configuración de la bala @param x coordenada del eje x de la bala @param y coordenada del eje y de la bala @param direction dirección de la bala @param o actor que dispara la bala. */ Bullet(Game *g, const char* path, int x, int y, bool direction, Owner o); /** Destructor */ ~Bullet(); /** Actualiza lógicamente la bala */ void update(); /** @param x Coordenada en el eje x del nuevo clon @param y Coordenada en el eje y del nuevo clon @return Clon del actor en una posición dada */ Actor* clone(int x, int y); /** @param a Actor con el que colisiona Hace que el bala raccione a la colision */ void collides(Actor& a); /** @return Fuerza de ataque que tiene el enemigo */ int get_force() const; /** @param f nuevo valor para la fuerza del ataque del enemigo */ void set_force(int f); /** @return Actor que a disparado la bala. */ Owner get_owner()const; private: int force; Owner owner; }; inline int Bullet::get_force()const{ return force; } inline void Bullet::set_force(int f){ force = f; } inline Bullet::Owner Bullet::get_owner()const{ return owner; } #endif
saltares/grannys-bloodbath
src/engine/resourcemngr.h
<reponame>saltares/grannys-bloodbath /* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _RESOURCEMNGR_ #define _RESOURCEMNGR_ #include <map> #include <string> #include "image.h" #include "font.h" #include "music.h" #include "sound.h" //! Carga y cachea todos los recursos multimedia /** @author <NAME> @version 1.0 Clase que sigue el patrón de diseño Singleton (una sóla instancia accesible desde todo el sistema). Se utiliza para cargar los recursos multimedia y minimizar el consumo de memoria y el número de accesos a disco. Cuando queremos recursos de algún tipo simplente accedemos mediante su clave. ResourceMngr guarda el número de referencias que existen de un recurso en el sistema. Cuando dejemos de usar un recurso debemos de avisarle de que no lo usaremos más. Este manejador se encarga de liberarlo definivamente si era la última referencia al recurso. Si queremos volver a cargar el recurso liberado quizás haya que volver a hacer un acceso a disco. Carga un fichero XML llamado "./multimedia/resources.xml" con el siguiente formato \code <resources> <images> <image code="granny" path="./multimedia/granny.png" rows="8" columns="12"/> </images> <fonts> <font code="matter" path="./multimedia/matteroffact.ttf" size="50"/> <font code="hand" path="./multimedia/handsean.ttf" size="20"/> </fonts> <musics> <music code="nivel" path="./multimedia/prueba.ogg"/> </musics> <sounds> <sound code="vomito" path="./multimedia/vomito.wav"/> </sounds> </resources> \endcode Ejemplo de uso: \code Music* music = resource->music("nivel"); // Equivalente a ResourceMngr::get_instance()->music("nivel"); Sound* sound = resource->sound("vomito"); Font* font1 = resource->font("matter"); Font* font2 = resource->font("hand"); Image* image = resource->image("granny"); ... // Cuando no los usemos más resource->free_image("granny"); resource->free_music("nivel"); resource->free_sound("vomito"); resource->free_font("matter"); resource->free_font("hand"); \endcode */ class ResourceMngr{ public: /** @return Si es la primera vez que se utiliza ResourceMngr se crea la única instancia que habrá de la clase en el sistema. En caso contrario simplemente la devuelve */ static ResourceMngr* get_instance(){ if(_instance == 0) _instance = new ResourceMngr; return _instance; } static void free_instance(); /** @param code Clave de la imagen a encontrar @return puntero a Image con la imagen deseada */ Image* image(const std::string& code); /** @param code Clave de la fuente a encontrar @return puntero a Font con la fuente deseada */ Font* font(const std::string& code); /** @param code Clave del efecto de sonido a encontrar @return puntero a Sound con el sonido deseado */ Sound* sound(const std::string& code); /** @param code Clave de la música a encontrar @return puntero a Music con la música deseada */ Music* music(const std::string& code); /** @param code Clave de la imagen a liberar Avisa a ResourceMngr del cese del uso de ese recurso. Si no existen más referencias a ese recurso, se libera definitivamente. La próxima vez que se le pida ResourceMngr tendrá que hacer un acceso a disco. */ void free_image(const std::string& code); /** @param code Clave de la fuente a liberar Avisa a ResourceMngr del cese del uso de ese recurso. Si no existen más referencias a ese recurso, se libera definitivamente. La próxima vez que se le pida ResourceMngr tendrá que hacer un acceso a disco. */ void free_font(const std::string& code); /** @param code Clave de la música a liberar Avisa a ResourceMngr del cese del uso de ese recurso. Si no existen más referencias a ese recurso, se libera definitivamente. La próxima vez que se le pida ResourceMngr tendrá que hacer un acceso a disco. */ void free_music(const std::string& code); /** @param code Clave del efecto de sonido a liberar Avisa a ResourceMngr del cese del uso de ese recurso. Si no existen más referencias a ese recurso, se libera definitivamente. La próxima vez que se le pida ResourceMngr tendrá que hacer un acceso a disco. */ void free_sound(const std::string& code); protected: ResourceMngr(); ResourceMngr(const ResourceMngr& m); ~ResourceMngr(); ResourceMngr& operator = (const ResourceMngr& m); private: //! Maneja un recurso de imagen struct ImageMngr{ std::string path; int rows, columns; Image* image; int counter; }; //! Maneja un recurso de fuente struct FontMngr{ std::string path; int size; Font* font; int counter; }; //! Maneja un recurso de sonido struct SoundMngr{ std::string path; Sound* sound; int counter; }; //! Maneja un recurso de música struct MusicMngr{ std::string path; Music* music; int counter; }; typedef std::map<std::string, ImageMngr> Images; typedef std::map<std::string, FontMngr> Fonts; typedef std::map<std::string, SoundMngr> Sounds; typedef std::map<std::string, MusicMngr> Musics; static ResourceMngr* _instance; Images images; Fonts fonts; Sounds sounds; Musics musics; }; #define resource ResourceMngr::get_instance() #endif
saltares/grannys-bloodbath
src/engine/granny.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _GRANNY_ #define _GRANNY_ #include <iostream> #include <string> #include <vector> #include "actor.h" #include "hud.h" class Game; class Sound; class Bullet; class Item; //! Clase que modela el comportamiento y las características de la abuelita protagonista /** @author <NAME> @version 1.0 Granny hereda de la clase virtual pura Actor y define los métodos update entre otros para darle comportamiento a la abuela Su uso es muy sencillo: \code // Game loop while(!exit){ ... granny->update(); // Actualizamos lógicamente a la abuela ... granny->draw(screen); // Dibumamos a la abuela en pantalla ... granny->set_state(Actor::NORMAL); // Si lo deseamos podemos cambiar su estado } \endcode */ class Granny: public Actor{ public: /** Constructor @param game Puntero a Game con el que se asocia el actor @param path ruta del fichero que contiene las distintas caracteristicas del personaje @param x coordenada x del personaje @param y coordenada y del personaje */ Granny(Game *g, const char *path, int x, int y); /** Destructor Liberamos recursos usados por el personaje. */ ~Granny(); /** Actualiza lógicamente al personaje */ void update(); /** * Resetea a la abuela (State = NORMAL vida al máximo) */ void reset(); /** @param a Actor con el que colisiona Hace que el actor reaccione a la colisión (restar vida, añadir objeto...) */ void collides(Actor& a); /** * @param i Daño inflingido a la abuela * * Le resta vida a la abuela */ void damaged(int i); /** * @param i Item que recoge la abuela * * Según el ítem reacciona la abuela */ void get_item(const Item& i); /** @return devuelve el numero de vidas actual */ int get_lives() const; /** @param nuevo numero de vidas Establece un nuevo numero de vidas */ void add_lives(int l); /** @return numero de puntos actuales. */ int get_points() const; /** @param numero de puntos actuales. Establece un nuevo numero de puntos */ void add_points(int p); /** @return municion restante que tiene el personaje. */ int get_munition() const; /** @param m numero para incrementar la municion.. */ void add_munition(int m); /** @return energia restante del personaje. */ int get_energy() const; /** @param e valor para incrementar la energua. */ void add_energy(int e); /** @param Superficie donde se dibujará el actor Dibuja al personaje en la superficie dada según su posición y animación actuales */ void draw(SDL_Surface* screen); /** Reproduce el sonido de victoria de la abuela */ void epic_win(); private: HUD *hud_; int lifes, points, munition, energy, max_energy; int y0; Sound* attack; Sound* shoot; Sound* win; Sound* jump; std::string attack_code, shoot_code, win_code, jump_code; std::vector<std::pair<Sound*, std::string> > hurt_sounds; void Normal_State(); void NormalDown_State(); void Moving_State(); void Jumping_State(); void Kneeled_State(); void Rising_State(); void Attaking_State(); void Damaged_State(); void Dead_State(); void shoot_gun(); Bullet* bullet; }; inline int Granny::get_lives() const { return lifes; } inline void Granny::add_lives(int l) { lifes+=l; } inline int Granny::get_points() const { return points; } inline void Granny::add_points(int p) { points+=p; } inline int Granny::get_munition() const { return munition; } inline void Granny::add_munition(int m) { munition+=m; } inline int Granny::get_energy() const { return energy; } inline void Granny::add_energy(int e) { (energy + e >= max_energy)? energy = max_energy : energy += e; } #endif
saltares/grannys-bloodbath
src/engine/application.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _APPLICATION_ #define _APPLICATION_ #include <SDL/SDL.h> #include "fpsmngr.h" class SceneMngr; //!Clase encargada de iniciar y cerrar SDL. Tiene el bucle principal /** @author <NAME> @version 1.0 Se encarga de inicializar la SDL, cerrarla e ir cargando cada escena. Tambien contiene el bucle principal del juego Ejemplo: \code #include "application.h" int main(){ Application app("Configuracion.xml"); app.run(); return 0; } \endcode */ class Application{ public: /** Constructor @param path ruta del fichero que contiene la configuración */ Application( const char* path ); /** Destructor Cierra SDL y libera recursos usados. */ ~Application(); /** Encargado de actualizar el juego. */ void run(); /** * @return ancho en píxeles de la pantalla */ int get_screen_width() const; /** * @return alto en píxeles de la pantalla */ int get_screen_height() const; private: SDL_Surface* screen; int screen_w,screen_h,bpp,fps; FPSMngr fps_mngr; SceneMngr* scene_mngr; SDL_Surface* SDL_Setup(); }; inline int Application::get_screen_width() const {return screen_w;} inline int Application::get_screen_height() const {return screen_h;} /** @mainpage Granny's Bloodbath <strong><center><h2><NAME></h2></center> <center><h2><NAME></h2></center> <center><h2><NAME></h2></center> <center><h3>Web del proyecto: http://granysbloodbath.wordpress.com</h3></center></strong> <center><img src=grannysbloodbath.png/></center> <h3>Introducción</h3> Granny's Bloodbath es un plataformas de acción en 2D de avance lateral. Está programado en C++ usando las librerías SDL y ticpp. <h3>Descarga y compilación</h3> Para descargar el código fuente de Granny's Bloodbath hay que entrar en una terminal y ejecutar: svn checkout https://forja.rediris.es/svn/grannysbloodbath (Es necesario tener Subversion instalado) Para poder compilar Granny's Bloodbath se debe tener instalados los siguientes paquetes: \li libsdl1.2-dev \li libsdl-image1.2-dev \li libsdl-ttf1.2-dev \li libsdl-mixer1.2-dev Posteriormente habrá que entrar en el directorio /grannysbloodbath/trunk/src y hacer make */ #endif
saltares/grannys-bloodbath
src/engine/animation.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _ANIMATIONH_ #define _ANIMATIONH_ #include <iostream> #include<vector> //! Gestiona las animaciones de ina imagen /** @author <NAME> @version 1.0; Clase sirve para gestionar las distintas animaciones que puede recoger un mismo sprite Ejemplo: \code Image abuelita("abuela.png"); Animation AbuelitaAndar(1,31,1); Animation AbuelaAgachar("90,91,92,93,94,95,96,95,94,93,92,91,90",1); SDL_Event evento; for(;;){ while(SDL_PollEvent(&evento)){ if(evento.type==SDL_QUIT) return 0; else if(evento.type==SDL_KEYDOWN){ if(evento.key.keysym.sym==SDLK_ESCAPE) return 0; if(evento.key.keysym.sym==SDLK_a){ cout<<"Abuela en ejecucion. Espere..."<<endl; PintarAnimacion(abuela,AbuelaAndar); cout<<"Abuela termino su ejecucion. Pulse otra tecla..."<<endl; } if(evento.key.keysym.sym==SDLK_d){ cout<<"Abuela agachandose. Espere..."<<endl; PintarAnimacion(abuela,AbuelaAgachar); cout<<"Abuela derecha. Pulse otra tecla..."<<endl; } } } } \endcode */ class Animation{ public: /** Constructor Recibe la secuencia de la animacion junto con su retardo @param frms secuencia con el formato "a1,a2,...an" @param delay retardo para pasar de un frame a otro */ Animation(const char* frms, int delay); /** Constructor Recibe la secuencia de la animacion junto con su retardo @param begin frame/cuadro de inicio @param end frame/cuadro de fin Si usamos 1 como begin y 4 como end es equivalente a usar el constructor anterior de la siguente forma Animation("1,2,3,4",...) @param delay retardo para pasar de un frame a otro */ Animation(int begin, int end, int delay); /** Reinicia la animacion */ void restart(); /** Incrementa en 1 el contador que controla el retardo, si es igual pasa al siguiente cuadro Si termina y se continua vuelve a empezar @return Verdadero si se termina la animación, falso si no es así */ bool update(); /** Establece el retardo @param newdelay valor que pasa a ser el nuevo retardo */ void set_delay(int newdelay); /** Metodo consultor @return valor que tiene el retardo actual */ int get_delay()const; /** Metodo consultor @return numeros de cuadros que posee la animación */ int get_frames()const; /** Metodo consultor @return cuadro actual en el que se encuentra la animación */ int get_frame()const; private: std::vector<int> frames; int delay,ActualFrame,CounterDelay,NumberFrames; }; inline void Animation::restart(){ActualFrame=0;CounterDelay=0;} inline void Animation::set_delay(int newdelay){delay=newdelay;} inline int Animation::get_delay()const{return delay;} inline int Animation::get_frames()const{return NumberFrames;} inline int Animation::get_frame()const{return frames[ActualFrame];} #endif
saltares/grannys-bloodbath
src/engine/menu.h
/* This file is part of Granny's Bloodbath. Granny's Bloodbath is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Granny's Bloodbath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _MENU_ #define _MENU_ #include <string> #include <iostream> #include <SDL/SDL.h> #include <vector> #include "font.h" #include "music.h" #include "sound.h" #include "scene.h" #include "image.h" #include "option.h" //! Gestiona y carga el menu, con sus distintas opciones /** @author <NAME> @version 1.0 Se utiliza para cargar las distintas opciones del Menú del juego, así como de pintarlo con todo su multimedia. Las opciones y el multimedia podemos modificarlo a nuestro gusto en el XML. */ class Menu: public Scene{ public: Menu( SceneMngr* sm , const char* path ); ~Menu(); void update(); void reset(); void resume(); void draw(SDL_Surface* screen); private: unsigned int selected; std::vector <Option *> options; Font* font; int x_, y_; Font *aux; Music* music; Sound* select_sound; Sound* move_sound; Image* background; Image* cursor; std::string background_code, cursor_code, font_code, music_code, select_code, move_code; }; #endif
unwiredlabs/geocoder-ios-sdk
Unwired Labs iOS SDK/Unwired_Labs_iOS_SDK.h
// // Unwired_Labs_iOS_SDK.h // Unwired Labs iOS SDK // // Copyright © 2018 Unwired Labs (India) Pvt. Ltd. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for Unwired_Labs_iOS_SDK. FOUNDATION_EXPORT double Unwired_Labs_iOS_SDKVersionNumber; //! Project version string for Unwired_Labs_iOS_SDK. FOUNDATION_EXPORT const unsigned char Unwired_Labs_iOS_SDKVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <Unwired_Labs_iOS_SDK/PublicHeader.h>
anthony-y/ftc
ftc.c
<reponame>anthony-y/ftc #include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char u8; typedef unsigned long int u64; #define ASSERT_FALSE() (*(int *)0) #define IO_BUFFER_SIZE 10240 // 10kb // For any of these, you can change the "1;" to a "0;" to make it non-bold (these are all bold by default, except ANSI_COLOR_DEFAULT). #define ANSI_COLOR_RED "\x1b[1;31m" #define ANSI_COLOR_GREEN "\x1b[1;32m" #define ANSI_COLOR_YELLOW "\x1b[1;33m" #define ANSI_COLOR_BLUE "\x1b[1;34m" #define ANSI_COLOR_MAGENTA "\x1b[1;35m" #define ANSI_COLOR_CYAN "\x1b[1;36m" #define ANSI_COLOR_DEFAULT "\x1b[0m" #define TITLE_COLOR ANSI_COLOR_MAGENTA #define INFO_COLOR ANSI_COLOR_DEFAULT #define USERNAME_COLOR ANSI_COLOR_RED #define HOSTNAME_COLOR ANSI_COLOR_DEFAULT // These are the core functions of the program. // They do all the heavy-lifting of querying the system for information. static char *do_command(const char *the_command); static char *read_file(const char *path); // These call do_command() and read_file() to get the right info. // They are "pure", so no state, and ultimately they just invoke printf(). static void fetch_installation_date(); static void fetch_uptime(); static void fetch_memory_info(); static void fetch_user_and_host_name(); static void fetch_pacman_package_count(); static void fetch_kernel_version(); static void fetch_cpu_temperature(); int main(int arg_count, char **args) { printf("\n"); /* * This is the order they will appear in. * It can be any order you want. * You can also comment out any you don't want. */ fetch_user_and_host_name(); fetch_kernel_version(); fetch_memory_info(); fetch_pacman_package_count(); fetch_uptime(); // fetch_cpu_temperature(); // fetch_installation_date(); printf("\n"); return 0; } // // Util functions for parsing. // static inline int is_letter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } static inline int is_numerical(char c) { return (c >= '0' && c <= '9'); } static void fetch_installation_date() { char *first_pacman_cmd = do_command("head -n1 /var/log/pacman.log"); if (!first_pacman_cmd || *first_pacman_cmd != '[') return; // we'll exit here if the system doesn't use pacman. char *start = first_pacman_cmd+1; char *cursor = start; while (*cursor++ != 'T'); cursor--; u64 length = (cursor - start); printf(TITLE_COLOR "System installed" INFO_COLOR ": "); printf("%.*s\n", length, start); free(first_pacman_cmd); } static void fetch_uptime() { char *uptime = do_command("uptime"); char *cursor = uptime; char *start = uptime; int colon_index = 0; int index = 0; if (!uptime) return; while (*cursor++ != 'p'); while (*cursor == ' ' || *cursor == '\t') cursor++; start = cursor; int minutes_only = 0; while (1) { if (*cursor == 'm') { minutes_only = 1; break; } if (*cursor == ',' || index >= 1000) break; if (*cursor == ':') colon_index = index; index++; cursor++; } if (minutes_only == 1) { u64 length = (cursor - start) - 1; printf(TITLE_COLOR "Uptime" INFO_COLOR ": "); printf("%.*s minutes\n", length, start); free(uptime); return; } u64 minutes_length = (index - colon_index) - 1; char *hour_string = malloc(colon_index); char *minutes_string = malloc(minutes_length); strncpy(hour_string, start, colon_index); hour_string[colon_index] = 0; strncpy(minutes_string, start+colon_index+1, minutes_length); minutes_string[minutes_length] = 0; u64 length = (cursor - start); printf(TITLE_COLOR "Uptime" INFO_COLOR ": "); printf("%s hours, %s minutes\n", hour_string, minutes_string); free(hour_string); free(minutes_string); free(uptime); } // Print format: // Memory: used / available MiB static void fetch_memory_info() { char *meminfo = read_file("/proc/meminfo"); if (!meminfo) return; u64 total_memory = 0, free_memory = 0; char *cursor = meminfo; char *text_start = 0, *text_end = 0; char *number_start = 0, *number_end = 0; while (*cursor) { // Each line starts with the name of the variable. // Then, a colon. // Then, some whitespace. // Then, an integer value. // Then, the units (kB, MiB, etc.) // Finally, a new line character. if (is_letter(*cursor)) { // Skip the text, storing a pointer to where it starts // and how long it is so we can use strncmp on it later. text_start = cursor; while (is_letter(*cursor) && *cursor++); text_end = cursor; u64 length = (u64)(text_end - text_start); // Skip the colon and the spaces. if (*cursor != ':') ASSERT_FALSE(); cursor++; // : while (*++cursor == ' '); // Skip the integer value, storing a pointer to where it starts // and how it long it is so we can copy it and convert it to an int. number_start = cursor; while (is_numerical(*cursor) && *cursor++); number_end = cursor; u64 number_length = (u64)(number_end - number_start); char number_as_text[number_length+1]; strncpy(number_as_text, number_start, length); // We're only interested in the total memory installed on the system... if (strncmp(text_start, "MemTotal", length) == 0) total_memory = atol(number_as_text); // ... and how much of it is available. else if (strncmp(text_start, "MemAvailable", length) == 0) free_memory = atol(number_as_text); // Skip the units. if (*cursor != 'k' && *cursor+1 != 'B') ASSERT_FALSE(); cursor += 2; // kB // Skip the new line character. if (*cursor != '\n') ASSERT_FALSE(); cursor++; } cursor++; } free(meminfo); // It's in kB originally but we want to display it in MiB. total_memory /= 1024; free_memory /= 1024; u64 used_memory = total_memory - free_memory; printf(TITLE_COLOR "Memory" INFO_COLOR ": %ld MiB / %ld MiB\n", used_memory, total_memory); } static void fetch_user_and_host_name() { char *username = do_command("whoami"); char *hostname = read_file("/proc/sys/kernel/hostname"); if (!username || !hostname) return; printf(USERNAME_COLOR "%s" ANSI_COLOR_DEFAULT "@" HOSTNAME_COLOR "%s", username, hostname); // Print vanity separator. int separator_length = strlen(username) + strlen(hostname) + 1; for (int i = 0; i < separator_length; i++) printf("-"); printf("\n"); free(hostname); free(username); } static void fetch_pacman_package_count() { // TODO: improve, we have to run pacman -Q which takes a while. char *packages = do_command("pacman -Q | wc -l"); if (!packages) return; // we'll exit here if the system doesn't use pacman. printf(TITLE_COLOR "Packages" INFO_COLOR ": "); printf("%s", packages); printf(" (pacman)\n"); free(packages); } static void fetch_kernel_version() { char *version = read_file("/proc/version"); // Skip the fluff "Linux version..." blah blah char *cursor = version, *start_of_text = version; while ((is_letter(*cursor) || *cursor == ' ') && *cursor != '\n' && *cursor++); char *start_of_version = cursor; while (*cursor != ' ' && *cursor++ != '\n'); char *end_of_version = cursor; printf(TITLE_COLOR "Kernel" INFO_COLOR ": "); printf("linux %.*s\n", (int)(end_of_version - start_of_version), start_of_version); free(version); } static void fetch_cpu_temperature() { char *cpu_temp = read_file("/sys/class/hwmon/hwmon1/temp2_input"); if (!cpu_temp) { printf(TITLE_COLOR "Processor temp" INFO_COLOR ": unavailable\n"); return; } float as_float = atof(cpu_temp); as_float /= 1000; int as_int = (int)as_float; printf(TITLE_COLOR "Processor temp" INFO_COLOR ": %d°C\n", as_int); free(cpu_temp); } static char *do_command(const char *the_command) { FILE *pipe = popen(the_command, "r"); if (!pipe) { fprintf(stderr, "ftc: error: failed to open pipe from command '%s'.\n", the_command); exit(1); } char buffer[IO_BUFFER_SIZE]; u64 bytes_read = fread(buffer, 1, IO_BUFFER_SIZE, pipe); if (bytes_read < 1) { fprintf(stderr, "ftc: error: failed to read pipe from command '%s'.\n", the_command); pclose(pipe); exit(1); } pclose(pipe); char *ret = malloc(bytes_read); strncpy(ret, buffer, bytes_read); // Remove trailing newline and null terminate. if (ret[bytes_read] == '\n') bytes_read--; ret[bytes_read-1] = 0; return ret; } // Read a /proc/ file into memory, the resulting pointer must be free()'d. static char *read_file(const char *path) { FILE *f = fopen(path, "r"); if (!f) { fprintf(stderr, "ftc: error: failed to open file %s.\n", path); exit(1); } char buffer[IO_BUFFER_SIZE]; u64 bytes_read = fread(buffer, 1, IO_BUFFER_SIZE, f); if (bytes_read < 1) // TODO: this might be wrong, but right now I don't think any /proc/ files are 0 size. { fprintf(stderr, "ftc: error: failed to read file \"%s\".\n", path); fclose(f); exit(1); } fclose(f); char *ret = malloc(bytes_read); strncpy(ret, buffer, bytes_read); ret[bytes_read] = 0; return ret; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex6.c
/*Escreva um programa que leia 10 números inteiros e os armazene em um vetor. Imprima o vetor, o maior elemento e a posição que ele se encontra.*/ #include <stdio.h> #include <stdlib.h> int main (){ int numeros [10],i=0,maior=0,cont=0; for (i;i<=9;i++){ printf("Digite o %d valor:\t", i+1); scanf("%d", &numeros[i]); } maior=numeros[0]; for (i=1;i<=9;i++){ if(numeros[i]>maior){ maior=numeros[i]; cont++; } } printf("O maior numero e: %d e ele se encontra na posicao %d\n",maior,cont); system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex3.c
/*Ler um conjunto de números reais, armazenando-o em vetor e calcular o quadrado dos componentes deste vetor, armazenando o resultado em outro vetor. Os conjuntos têm 10 elementos cada. Imprimir todos os conjuntos.*/ #include <stdio.h> #include <stdlib.h> #include <math.h> int main (void){ float vetor[10], result[10]; int i=0,j=0,x=0; for (i;i<10;i++){ printf("Digite o %d valor:\t", i+1); scanf("%f", &vetor[i]); result[i]=pow(vetor[i],2); } for(j;j<10;j++){ printf("Quadrado de %.2f e %.2f\n",vetor[j],result[j]); } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex2.c
/*Implemente um código que leia o Raio de um circulo e calcule a área */ #include <stdio.h> #include <stdlib.h> #include <math.h> int main (){ float raio, area=0; printf("Digite o raio de uma circunferencia: \n"); scanf("%f", &raio); area = M_PI * (pow(raio,2)); printf("Area da circunferencia: %.2f \n", area); system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex26.c
/*Informe se um número digitado é primo. Caso não for, informe por quais números ele é divisível;*/ #include<stdio.h> #include<stdlib.h> int main (void){ int i=1, x, cont=0; printf("Digite um numero:\t"); scanf("%d",&x); for(i;i<=x;i++){ if(x%i==0){ printf("O numero e divisivel por: %d\n",i); cont++; } } if(cont==2){ printf("O numero e primo.\n"); }else{ printf("O numero nao e primo."); } return 0; system("pause"); }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex17.c
<reponame>murilloaguiar/Faculdade-AEDS-I /*Leia uma matriz de 3 x 3 elementos. Calcule a soma dos elementos que estão na diagonal principal.*/ #include <stdlib.h> #include <stdio.h> int main(){ int matriz[3][3],soma=0,i=0,j=0; printf("Matriz 3X3: "); for(i;i<3;i++){ for(j=0;j<3;j++){ scanf("%d", &matriz[i][j]); if (i==j){ soma+=matriz[i][j]; } } } j=0; printf("Matriz: \n"); for(i=0;i<3;i++){ printf("[%d][%d][%d]\n",matriz[i][j],matriz[i][j+1],matriz[i][j+2]); } printf("A soma da diagonal principal e: %d.\n",soma); system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex13.c
<gh_stars>0 /*Declare uma matriz 5 x 5. Preencha com 1 a diagonal principal e com 0 os demais elementos. Escreva ao final a matriz obtida.*/ #include <stdlib.h> #include <stdio.h> int main(){ int matriz[5][5],i=0,j=0; printf("MATRIZ 5X5: \n"); for(i;i<5;i++){ for(j=0;j<5;j++){ if (i==j){ matriz[i][j]=1; }else{ matriz[i][j]=0; } } } j=0; printf("MATRIZ: \n"); for(i=0;i<5;i++){ printf("[%d][%d][%d][%d][%d]\n",matriz[i][j],matriz[i][j+1],matriz[i][j+2],matriz[i][j+3],matriz[i][j+4]); } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex14.c
/*Escrever um algoritmo que imprima a tabuada de um número informado pelo usuário*/ #include<stdio.h> #include<stdlib.h> int main (void){ int i=0; float a; printf("Digite um numero\n"); scanf("%f",&a); for(i;i<=10;i++){ printf("%.2f X %d = %.2f\n",a,i,a*i); } return 0; system("pause"); }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex28.c
<reponame>murilloaguiar/Faculdade-AEDS-I /*Calcule a soma de todos os números primos existentes entre 1 e 100;*/ #include<stdio.h> #include<stdlib.h> int main (void){ int i=2,cont=0,x=1,soma=0; for(i;i<=100;i++){ for(x;x<=i;x++){ if(i%x==0) cont++; } if(cont==2){ printf("%d\n",i); soma+=i; } cont=0; x=1; } printf("A soma dos numeros primos entre 1 e 100 e:\t%d", soma); }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex4.c
/*Leia um vetor de 10 posições. Contar e escrever quantos valores pares ele possui.*/ #include <stdio.h> #include <stdlib.h> int main (){ int numeros [10],i=0,cont=0,j=0; printf("DIGITE 10 VALORES\n"); for (i;i<=9;i++){ printf("Digite o %d valor:\t", i+1); scanf("%d", &numeros[i]); if (numeros[i]%2==0){ cont++; } } printf("A quantidade de numeros pares que existem sao: %d\n",cont); printf("E os numeros pares que existem sao:"); for (j;j<=9;j++){ if (numeros[j]%2==0){ printf("\n%d",numeros[j]); } } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex18.c
<reponame>murilloaguiar/Faculdade-AEDS-I /*17 - Escrever um programa de computador que leia 10 números inteiros e, ao final, apresente a soma de todos os números lidos;*/ /*18- Faça o mesmo que antes, porém, ao invés de ler 10 números, o programa deverá ler e somar números até que o valor digitado seja zero ( 0 ).*/ #include<stdio.h> #include<stdlib.h> int main (void){ float a=1,soma=0; printf("O programa so se encerrara quando digitar 0\n"); while (a!=0){ printf("Digite um numero\n"); scanf("%f",&a); soma+=a; } printf("Soma dos numeros: %.2f", soma); return 0; system("pause"); }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex16.c
/*Em uma turma há 10 alunos. Cada aluno tem 2 notas. Um professor precisa calcular a média das duas notas de cada aluno. Crie um programa que resolve este problema.*/ #include<stdio.h> #include<stdlib.h> int main (void){ int i=1,x=1; float nota,soma=0; for(i;i<=10;i++){ for(x;x<=2;x++){ printf("%d aluno, %d nota\t",i,x); scanf("%f",&nota); soma+=nota; } x=1; printf("A media do %d aluno e %.2f\n\n",i, soma/2); soma=0; } return 0; system("pause"); }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex18.c
<filename>Lista 2/lista_ex18.c /*Gere matriz 4 x 4 com valores no intervalo [1, 20]. Escreva um programa que transforme a matriz gerada numa matriz triangular inferior, ou seja, atribuindo zero a todos os elementos acima da diagonal principal. Imprima a matriz original e a matriz transformada*/ #include <stdlib.h> #include <stdio.h> int main(){ int matriz[4][4],soma=0,i=0,j=0; printf("Matriz 4X4: "); for(i;i<4;i++){ for(j=0;j<4;j++){ scanf("%d", &matriz[i][j]); while (matriz[i][j]<0 || matriz[i][j]>20){ printf("DIGITE UM VALOR ENTRE 0 E 20\n"); scanf("%d", &matriz[i][j]); } } } j=0; printf("Matriz: \n"); for(i=0;i<4;i++){ printf("[%d][%d][%d][%d]\n",matriz[i][j],matriz[i][j+1],matriz[i][j+2],matriz[i][j+3]); } for(i=0;i<4;i++){ for(j=0;j<4;j++){ if(i<j){ matriz[i][j]=0; } } } j=0; printf("Matriz nova: \n"); for(i=0;i<4;i++){ printf("[%d][%d][%d][%d]\n",matriz[i][j],matriz[i][j+1],matriz[i][j+2],matriz[i][j+3]); } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex2.c
/*Faça um programa que lê três palavras do teclado e imprime as três palavras na ordem inversa.*/ #include <stdio.h> #include <stdlib.h> #include <conio.h> int main (void){ char vetor[10]; int i=0,j=0,x=0; scanf("%s",&vetor); printf("%s\n",vetor); setbuf(stdin, NULL); for(i=9;i>=0;i--){ setbuf(stdin, NULL); printf("%c", vetor[i]); } printf("\n"); system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex24.c
/*Escreva um programa que leia um valor correspondente ao número de jogadores de um time de vôlei. O programa deverá ler uma altura para cada um dos jogadores , ao final, informar a altura média do time.*/ #include<stdio.h> #include<stdlib.h> int main (void){ int i=1,j; float altura,soma=0; printf("Digiite a quantidade de jogadores no time:\t"); scanf("%d", &j); for(i;i<=j;i++){ printf("Altura do %d atleta em cm:\t",i); scanf("%f",&altura); soma+=altura; } printf("A media de altura do time e %.2fm\n\n",((soma/j)/100)); return 0; system("pause"); }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex11.c
<reponame>murilloaguiar/Faculdade-AEDS-I /*Faça um programa que leia um vetor de 5 posições para números reais e, depois, um código inteiro. Se o código for zero, finalize o programa; se for 1, mostre o vetor na ordem direta; se for 2, mostre o vetor na ordem inversa. Caso, o código for diferente de 1 e 2 escreva uma mensagem informando que o código e inválido.*/ #include <stdio.h> #include <stdlib.h> int main (){ float numeros [5]; int i=0, opc; printf("DIGITE 5 NUMEROS: \n"); for (i;i<=4;i++){ printf("Digite o %d valor:\t", i+1); scanf("%f", &numeros[i]); } printf("DIGITE UMA OPCAO\n"); scanf("%d",&opc); switch (opc){ case 0: break; case 1: for (i=0;i<=4;i++){ printf("%.2f ", numeros[i]); } case 2: for (i=4;i>=0;i--){ printf("%.2f ", numeros[i]); } default: printf("Opcao invalida\n s"); break; } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex10.c
/*Ler 4 notas de um aluno. Fazer a média e informar “Aprovado” caso seja maior ou igual a 7. Caso seja menor que 7, deve-se solicitar a nota da avaliação de recuperação e fazer média novamente.*/ #include<stdio.h> #include<stdlib.h> int main (void){ float nota,soma=0,n3,n4; int i=1,x=1; for(i;i<=4;i++){ printf("Digite o valor da %d prova:\t",i); scanf("%f", &nota); while (nota>10){ printf("Digite um valor entre 0 e 10 para a prova %d\t",i); scanf("%f", &nota); } soma+=nota; } if((soma/4)<7){ printf("O aluno foi pra recuperacao.\n"); for(x;x<=4;x++){ printf("Digite o valor da %d prova de recuperacao:\t",x); scanf("%f", &nota); while (nota>10){ printf("Digite um valor entre 0 e 10 para a %d prova de recuperacao:\t",x); scanf("%f", &nota); } soma+=nota; } if((soma/4)<7) printf("REPROVADO\n"); else printf("APROVADO\n"); }else{ printf("APROVADO\n"); } return 0; system("pause"); }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex22.c
/*Escreva um programa que leia dois valores reais. Ambos valores deverão ser lidos até que o usuário digite um número no intervalo de 1 a 100. Apresentar a soma dos dois valores lidos.*/ #include<stdio.h> #include<stdlib.h> int main (void){ float a,b,soma=0; printf("O programa so se encerrara quando digitar um numero entre 1 e 100\n"); while (a<1 || a>100 || b<1 || b>100){ printf("Digite dois numeros\n"); scanf("%f %f",&a, &b); soma+=a+b; printf("Soma dos numeros: %.2f\n", soma); soma=0; } return 0; system("pause"); }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex19.c
<gh_stars>0 /*Crie um programa em C que leia uma matriz de 5 linhas e 4 colunas contendo as seguintes informações sobre alunos de uma disciplina, sendo todas as informações do tipo inteiro: 1 - Primeira coluna: numero de matricula (use um inteiro); 2 - Segunda coluna: média das provas; 3 - Terceira coluna: media dos trabalhos; 4 - Quarta coluna: nota final. Elabore um programa que: A - Leia as três primeiras informações de cada aluno; B. Calcule a nota final como sendo a soma da média das provas e da média dos trabalhos; C. Imprima a matrícula do aluno que obteve a maior nota final (assuma que só existe uma maior nota); D. Imprima a média aritmética das notas finais. */ #include <stdlib.h> #include <stdio.h> int main(){ int matriz[4][4],i=0,j=0,mp[4],mt[4],soma=0,cont=0,maior=0; for(i;i<4;i++){ printf("Matricula do aluno %d: ",i+1); scanf("%d", &matriz[0][i]); } for(i=0;i<4;i++){ printf("Media das provas do aluno %d: ",i+1); scanf("%d", &matriz[1][i]); mp[i]=matriz[1][i]; } for(i=0;i<4;i++){ printf("Media dos trabalhos do aluno %d: ",i+1); scanf("%d", &matriz[2][i]); mt[i]=matriz[2][i]; } for(i=0;i<4;i++){ matriz[3][i]=mp[i]+mt[i]; } maior=matriz[3][0]; printf("Matriz: \n"); for(i=0;i<4;i++){ printf("[%d][%d][%d][%d]\n",matriz[i][j],matriz[i][j+1],matriz[i][j+2],matriz[i][j+3]); } for(i=0;i<4;i++){ soma+=matriz[3][i]; if (matriz[3][i]>maior){ maior=matriz[3][i]; cont++; } } printf("A maior media foi do aluno de matricula: %d\n",matriz[0][cont]); printf("A media das notas finais foram: %.2f\n",(float)soma/4); system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex15.c
<gh_stars>0 /*Leia uma matriz 5 x 5. Leia também um valor X. O programa deverá fazer uma busca desse valor na matriz e, ao final, escrever a localização (linha e coluna) ou uma mensagem de “não encontrado”. */ #include <stdlib.h> #include <stdio.h> int main(){ char matriz[5][5]; int i=0,j,cont=0,c=0,l=0; printf("MATRIZ 5X5: \n"); for(i;i<5;i++){ for(j=0;j<5;j++){ setbuf(stdin,NULL); scanf("%c", &matriz[i][j]); if(matriz[i][j]=='x' || matriz[i][j]=='X'){ l=i; c=j; cont++; } } } j=0; for(i=0;i<5;i++){ printf("[%c][%c][%c][%c][%c]\n",matriz[i][j],matriz[i][j+1],matriz[i][j+2],matriz[i][j+3],matriz[i][j+4]); } if (cont==0){ printf("VALOR N�O ENCONTRADO\n"); }else{ printf("O valor X est� na linha %d e coluna %d\n",l,c); } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex20.c
<reponame>murilloaguiar/Faculdade-AEDS-I /*Faça um programa para corrigir uma prova com 10 questões de múltipla escolha (a, b, c, d). Cada questão vale um ponto. Primeiro solicite ao usuário que digite o gabarito, depois peça para digitar as respostas dos alunos. Calcule e escreva: A nota do aluno e se ele foi aprovado (média 7). */ #include <stdlib.h> #include <stdio.h> int main(){ char gabarito[10],resposta; int i=0,cont=0; printf("-----GABARITO-----\n"); for(i;i<10;i++){ printf("ALTERNATIVA QUESTAO %d\n",i+1); setbuf(stdin,NULL); scanf("%c", &gabarito[i]); } printf("-----CORRECAO-----\n"); for(i=0;i<10;i++){ printf("Digite a resposta para a questao %d:\n",i+1); setbuf(stdin,NULL); scanf("%c",&resposta); if (resposta==gabarito[i]){ cont++; } } printf("A nota do aluno foi %d.\n",cont); if (cont>=7){ printf("ALUNO APROVADO\n"); }else{ printf("ALUNO REPROVADO\n"); } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex14.c
<reponame>murilloaguiar/Faculdade-AEDS-I /*Leia uma matriz 4 x 4, imprima a matriz e retorne à localização (linha e a coluna) do maior valor.*/ #include <stdlib.h> #include <stdio.h> int main(){ int matriz[4][4],i=0,j=0,maior=0,c=0,l=0; printf("MATRIZ 4X4: \n"); for(i;i<4;i++){ for(j=0;j<4;j++){ scanf("%d", &matriz[i][j]); } } maior=matriz[0][0]; for(i=0;i<4;i++){ for(j=0;j<4;j++){ if(matriz[i][j]>maior){ maior=matriz[i][j]; l=i; c=j; } } } j=0; printf("MATRIZ: \n"); for(i=0;i<4;i++){ printf("[%d][%d][%d][%d]\n",matriz[i][j],matriz[i][j+1],matriz[i][j+2],matriz[i][j+3]); } printf("O maior numero e %d e ele se encontra na linha %d e coluna %d. \n",maior,l,c); system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex6.c
<reponame>murilloaguiar/Faculdade-AEDS-I<filename>Lista 1/lista-ex6.c /*Faça um algoritmo que leia um número e diga se este número está no intervalo entre 100 e 200.*/ #include<stdio.h> #include<stdlib.h> int main (void){ float x; printf("Digite um numero\t"); scanf("%f", &x); if(x>100 && x<200){ printf("%.2f esta entre 100 e 200.\n", x); }else{ printf("%.2f nao esta entre 100 e 200.\n", x); } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex1.c
/*Crie um programa que lê 6 valores inteiros e, em seguida, mostre na tela os valores lidos.*/ #include <stdio.h> #include <stdlib.h> int main (void){ int vetor[6], i=0; for (i;i<6;i++){ printf("Digite o %d valor:\t", i+1); scanf("%d", &vetor[i]); } for (i=0;i<6;i++){ printf("O valor na posicao %d e %d\n",i+1,vetor[i]); } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex12.c
<filename>Lista 2/lista_ex12.c /*Leia uma matriz 4 x 4, conte e escreva quantos valores maiores que 10 ela possui.*/ #include <stdlib.h> #include <stdio.h> int main(){ int matriz[4][4],i=0,j=0,cont=0; printf("MATRIZ 4X4: \n"); for(i;i<4;i++){ for(j=0;j<4;j++){ scanf("%d", &matriz[i][j]); if (matriz[i][j]>10){ cont++; } } } j=0; printf("MATRIZ: \n"); for(i=0;i<4;i++){ printf("[%d][%d][%d][%d]\n",matriz[i][j],matriz[i][j+1],matriz[i][j+2],matriz[i][j+3]); } printf("A quantidade de numeros maiores que 10 sao: %d\n",cont); system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex4.c
<filename>Lista 1/lista-ex4.c /*Um aluno do Curso de Engenharia da Unimontes deseja ir ao FEPEG 2019. Crie um algoritmo que leia duas informações: 1 - O alunto tem dinheiro para a viagem (verdadeiro ou falso) e 2 - Os pais deixam participar do evento (verdadeiro ou falso) Exiba como resposta se o aluno irá à FEPEG ou não */ #include<stdio.h> #include<stdlib.h> #include<stdbool.h> int main (void){ bool d = false, p = false; char r; printf("O aluno tem dinheiro?('S' para sim e 'N' para nao)\n"); setbuf(stdin, NULL); scanf("%c", &r); setbuf(stdin, NULL); if (r=='s' || r=='S'){ d=true; } printf("O aluno tem permissao dos pais?('S' para sim e 'N' para nao)\n"); setbuf(stdin, NULL); scanf("%c", &r); setbuf(stdin, NULL); if (r=='s' || r=='S'){ p=true; } if(d==true && p==true){ printf("O aluno pode ir\n"); }else{ printf("O aluno nao pode ir\n"); } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex16.c
/*Leia duas matrizes 4 x 4 e escreva uma terceira com os maiores valores de cada posição das matrizes lidas*/ #include <stdlib.h> #include <stdio.h> int main(){ int matriz[4][4],matriz1[4][4],result[4][4],i=0,j=0; printf("Primeira matriz(4x4): "); for(i;i<4;i++){ for(j=0;j<4;j++){ scanf("%d", &matriz[i][j]); } } printf("Segunda matriz(4x4): "); for(i=0;i<4;i++){ for(j=0;j<4;j++){ scanf("%d", &matriz1[i][j]); } } for(i=0;i<4;i++){ for(j=0;j<4;j++){ if(matriz[i][j]>matriz1[i][j]){ result[i][j]=matriz[i][j]; }else if(matriz1[i][j]>matriz[i][j]){ result[i][j]=matriz1[i][j]; }else{ result[i][j]=matriz[i][j]; } } } j=0; printf("Primeira matriz: \n"); for(i=0;i<4;i++){ printf("[%d][%d][%d][%d]\n",matriz[i][j],matriz[i][j+1],matriz[i][j+2],matriz[i][j+3]); } printf("Segunda matriz: \n"); for(i=0;i<4;i++){ printf("[%d][%d][%d][%d]\n",matriz[i][j],matriz[i][j+1],matriz[i][j+2],matriz[i][j+3]); } printf("Matriz Resultante: \n"); for(i=0;i<4;i++){ printf("[%d][%d][%d][%d]\n",matriz[i][j],matriz[i][j+1],matriz[i][j+2],matriz[i][j+3]); } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex12.c
<filename>Lista 1/lista-ex12.c /*Faça um programa que imprima os 20 primeiros itens da sequência de Fibonacci. Sequência: 0,1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89...*/ #include <stdio.h> int main(void) { int n1 = 0, n2 = 1, n3 = 0, i; for (i = 1; i < 20; i++){ if (i == 1){ printf("%d, ", n1); _sleep(500); printf("%d, ", n2); _sleep(500); }else{ n3 = n1 + n2; if (i != 19){ printf("%d, ", n3); } else { printf("%d", n3); } _sleep(500); n1 = n2; n2 = n3; } } return 0; system("pause"); }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex20.c
/*Escreva um algoritmo que leia valores inteiros e encontre o maior e o menor deles. Termine a leitura se o usuário digitar zero (0);*/ #include<stdio.h> #include<stdlib.h> int main (void){ int a=1,maior=0,menor=0; printf("O programa so se encerrara quando digitar 0\n"); while (a!=0){ printf("Digite um numero:\t"); scanf("%d", &a); if (a>maior) maior=a; else if(a<menor) menor=a; else a=a; } printf("Maior numero: %d\n", maior); printf("Menor numero: %d", menor); return 0; system("pause"); }
murilloaguiar/Faculdade-AEDS-I
Lista 1/lista-ex8.c
<reponame>murilloaguiar/Faculdade-AEDS-I<filename>Lista 1/lista-ex8.c /*Implemente um código que receba três números inteiros e retorne uma destas três mensagens: 1 - Os três valores são iguais 2 - Não há valores iguais; ou 3 - Há dois valores iguais e um diferente. */ #include<stdio.h> #include<stdlib.h> int main (void){ int a,b,c; printf("Digite tres numeros inteiros\n"); scanf("%d %d %d",&a, &b, &c); if(a==b && a==c && b==c){ printf("Todos valores sao iguais"); }else if(a==c){ printf("Ha dois valores iguais"); }else if(b==c){ printf("Ha dois valores iguais"); }else if(a==b){ printf("Ha dois valores iguais"); }else{ printf("Todos valores sao diferentes"); } return 0; system("pause"); }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex10.c
<reponame>murilloaguiar/Faculdade-AEDS-I<filename>Lista 2/lista_ex10.c /*Leia um vetor de 10 posições e atribua valor 0 para todos os elementos que possuírem valores negativos.*/ #include <stdio.h> #include <stdlib.h> int main (){ int i=0,j=0,numeros [10]; printf("DIGITE 10 NUMEROS: \n"); for (i;i<=9;i++){ printf("Digite o %d valor:\t", i+1); scanf("%d", &numeros[i]); if (numeros[i]<0){ numeros[i]=0; } } printf("O novo vetor sera: "); for (j;j<=9;j++){ printf("%d , ",numeros[j]); } system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex9.c
<gh_stars>0 /*Fazer um programa para ler 5 valores e em seguida, mostrar a posição onde se entram o maior e o menor valor.*/ #include <stdio.h> #include <stdlib.h> int main (){ int numeros [10],i=0,menor=0,maior=0,cont1=0,cont=0; printf("DIGITE 10 NUMEROS: \n"); for (i;i<=9;i++){ printf("Digite o %d valor:\t", i+1); scanf("%d", &numeros[i]); } menor=numeros[0]; maior=numeros[0]; for (i=1;i<=9;i++){ if(numeros[i]>maior){ maior=numeros[i]; cont1++; }else if (numeros[i]<menor){ menor=numeros[i]; cont++; } } printf("O maior numero e: %d e ele se encontra na %d posicao\n",maior,cont1); printf("O menor numero e: %d e ele se encontra na %d posicao\n",menor,cont); system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex8.c
<gh_stars>0 /*Faça um programa que preencha um vetor com 10 números reais, calcule e mostre a quantidade de números negativos e a soma dos números positivos desse vetor.*/ #include <stdio.h> #include <stdlib.h> int main (){ float numeros [10],cont=0; int i=0,j=0; printf("DIGITE 10 NUMEROS: \n"); for (i;i<=9;i++){ printf("Digite o %d valor:\t", i+1); scanf("%f", &numeros[i]); if (numeros[i]<0){ cont++; } } printf("A quantidade de numeros negativos que existem sao: %.2f\n",cont); printf("E os numeros negativos que existem sao:"); cont=0; for (j;j<=9;j++){ if (numeros[j]<0){ printf("\n%.2f",numeros[j]); }else{ cont+=numeros[j]; } } printf("\nE a soma dos numeros positivos que existem e: %.2f\n", cont); system("pause"); return 0; }
murilloaguiar/Faculdade-AEDS-I
Lista 2/lista_ex7.c
<filename>Lista 2/lista_ex7.c /*Faça um programa para ler a nota da prova de 15 alunos e armazene num vetor, calcule e imprima a média geral.*/ #include <stdio.h> #include <stdlib.h> int main (){ float notas [15],cont=0; int i=0; printf("DIGITE 15 NOTAS: \n"); for (i;i<=14;i++){ printf("Digite a %d nota:\t", i+1); scanf("%f", &notas[i]); cont+=notas[i]; } printf("Media geral: %.2f\n",(float)cont/15); system("pause"); return 0; }
muyoy/box2d-lite
include/box2d-lite/World.h
/* * Copyright (c) 2006-2009 <NAME> http://www.gphysics.com * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies. * Erin Catto makes no representations about the suitability * of this software for any purpose. * It is provided "as is" without express or implied warranty. */ #ifndef WORLD_H #define WORLD_H #include <vector> #include <map> #include "MathUtils.h" #include "Arbiter.h" struct Body; struct Joint; struct Circle; struct World { World(Vec2 gravity, int iterations) : gravity(gravity), iterations(iterations) {} void Add(Body* body); void Add(Joint* joint); void Add(Circle* circles); void Clear(); void Step(float dt); void BroadPhase(); std::vector<Body*> bodies; std::vector<Circle*> circles; std::vector<Joint*> joints; std::map<ArbiterKey, Arbiter> arbiters; Vec2 gravity; int iterations; static bool accumulateImpulses; static bool warmStarting; static bool positionCorrection; }; #endif
sshutdownow/rsyslog-mmexternal-C-example
mmexternal_strip_garbage.c
#include <stdio.h> #include <stdlib.h> #include <string.h> static int is_working = 1; int main(int argc, char **argv) { char buf[64*1024]; do { unsigned int idx; if (fgets(buf, sizeof(buf), stdin) == NULL) { is_working = 0; /* end of file means terminate */ } for (idx = 0; idx < sizeof(buf) && buf[idx] != '|'; idx++); if (idx+3 < sizeof(buf)) { fprintf(stdout, "{ \"msg\" : \"%s\" }\n", buf+idx+3); fflush(stdout); } } while (is_working != 0); return EXIT_SUCCESS; }
manicphotons/vss
main.c
/*───────────────────────────────────────────────────────────────────────────── * PENDING TASKS * * Check for and correctly handle errors when using xlib. * Set all relavent window properties (WM_NAME etc…) for window manager usage. * Load/save settings from/to a config file. * Create vulkan interface. * Handle window resizing. * Enable both fullscreen and windowed modes. */ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include <stdio.h> #include <stdlib.h> #define IGNORE_INPUT( Arg ) ((void)Arg); void PrintError( char* Message ){ fprintf( stderr, "ERROR:\n\t%s\n\tClosing…\n", Message ); } int main( int ArgCount, char** ArgValues ){ IGNORE_INPUT( ArgCount ); IGNORE_INPUT( ArgValues ); Display* DefaultDisplay = XOpenDisplay( NULL ); if( !DefaultDisplay ){ PrintError( "Xlib: Could not open the default display." ); return EXIT_FAILURE; } int RootWindow = DefaultRootWindow( DefaultDisplay ); int DefaultScreen = DefaultScreen( DefaultDisplay ); int32_t ScreenBitDepth = 24; XVisualInfo VisualInfo = {}; if( !XMatchVisualInfo( DefaultDisplay, DefaultScreen, ScreenBitDepth, TrueColor, &VisualInfo) ){ PrintError( "Xlib: No matching visual info." ); return EXIT_FAILURE; } int32_t WindowPosition[2] = {0, 0}; int32_t WindowDimensions[2] = {800, 600}; XSetWindowAttributes WindowAttributes; WindowAttributes.background_pixel = 0; WindowAttributes.colormap = XCreateColormap( DefaultDisplay, RootWindow, VisualInfo.visual, AllocNone ); WindowAttributes.event_mask = StructureNotifyMask; unsigned long AttributeMask = CWBackPixel | CWColormap | CWEventMask; Window WindowID = XCreateWindow( DefaultDisplay, RootWindow, WindowPosition[0], WindowPosition[1], WindowDimensions[0], WindowDimensions[1], 0, VisualInfo.depth, InputOutput, VisualInfo.visual, AttributeMask, &WindowAttributes ); if( !WindowID ){ PrintError( "Xlib: Window wasn't created properly" ); return EXIT_FAILURE; } XStoreName( DefaultDisplay, WindowID, "Hello, World!" ); Atom DeleteWindowProtocol = XInternAtom( DefaultDisplay, "WM_DELETE_WINDOW", False); if( !XSetWMProtocols( DefaultDisplay, WindowID, &DeleteWindowProtocol, 1 ) ){ PrintError( "Xlib: Delete window protocol wasn't set properly" ); return EXIT_FAILURE; } XMapWindow( DefaultDisplay, WindowID ); XFlush( DefaultDisplay ); int WindowIsOpen = 1; while( WindowIsOpen ){ XEvent Event = {}; while( XPending( DefaultDisplay ) > 0 ){ XNextEvent( DefaultDisplay, &Event ); switch( Event.type ){ case ClientMessage: { if( Event.xclient.data.l[0] == DeleteWindowProtocol ) { XDestroyWindow( DefaultDisplay, WindowID ); } } case DestroyNotify: { XDestroyWindowEvent* e = (XDestroyWindowEvent*)&Event; if( e->window == WindowID ){ WindowIsOpen = 0; } } break; } } }; XCloseDisplay( DefaultDisplay ); DefaultDisplay = NULL; return EXIT_SUCCESS; }
RabbitBio/RabbitBM
src/DataPool.h
<reponame>RabbitBio/RabbitBM /* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ /* This file is modified by SDU HPC lab for RabbitQC project. Last modified: JULY2019 */ #ifndef H_DATA_POOL #define H_DATA_POOL #include "Globals.h" #include <vector> #include <iostream> #ifdef USE_BOOST_THREAD #include <boost/thread.hpp> namespace th = boost; #else #include <thread> #include <mutex> #include <condition_variable> namespace th = std; #endif namespace dsrc { namespace core { template <class _TDataType> class TDataPool { typedef _TDataType DataType; typedef std::vector<DataType*> part_pool; const uint32 maxPartNum; const uint32 bufferPartSize; uint32 partNum; part_pool availablePartsPool; part_pool allocatedPartsPool; th::mutex mutex; th::condition_variable partsAvailableCondition; public: static const uint32 DefaultMaxPartNum = 32; static const uint32 DefaultBufferPartSize = 1 << 22; TDataPool(uint32 maxPartNum_ = DefaultMaxPartNum, uint32 bufferPartSize_ = DefaultBufferPartSize) : maxPartNum(maxPartNum_) , bufferPartSize(bufferPartSize_) , partNum(0) { availablePartsPool.resize(maxPartNum); allocatedPartsPool.reserve(maxPartNum); } ~TDataPool() { for (typename part_pool::iterator i = allocatedPartsPool.begin(); i != allocatedPartsPool.end(); ++i) { ASSERT(*i != NULL); delete *i; } } void Acquire(DataType* &part_) { th::unique_lock<th::mutex> lock(mutex); while (partNum >= maxPartNum) partsAvailableCondition.wait(lock); ASSERT(availablePartsPool.size() > 0); DataType*& pp = availablePartsPool.back(); availablePartsPool.pop_back(); if (pp == NULL) { pp = new DataType(bufferPartSize); allocatedPartsPool.push_back(pp); } else { pp->Reset(); } partNum++; part_ = pp; } void Release(const DataType* part_) { th::lock_guard<th::mutex> lock(mutex); ASSERT(part_ != NULL); ASSERT(partNum != 0 && partNum <= maxPartNum); ASSERT(std::find(allocatedPartsPool.begin(), allocatedPartsPool.end(), part_) != allocatedPartsPool.end()); availablePartsPool.push_back((DataType*)part_); partNum--; partsAvailableCondition.notify_one(); } }; } // namespace core } // namespace dsrc #endif // H_DATA_POOL
RabbitBio/RabbitBM
src/Fastq.h
/* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ /* This file is modified by SDU HPC lab for RabbitQC project. Last modified: JULY2019 */ #ifndef H_FASTQ_SRC #define H_FASTQ_SRC #include "Globals.h" #include "common.h" #include <vector> #include "Buffer.h" #include "utils.h" namespace dsrc { namespace fq { typedef core::DataChunk FastqDataChunk; // 8B padding struct FastqRecord { uchar *title; uchar *sequence; uchar *quality; uint16 titleLen; uint16 sequenceLen; // can be specialized uint16 qualityLen; // can be specialized uint16 truncatedLen; // can be specialized FastqRecord() : title(NULL) , sequence(NULL) , quality(NULL) , titleLen(0) , sequenceLen(0) , qualityLen(0) , truncatedLen(0) {} void Reset() { title = NULL; titleLen = 0; sequence = NULL; sequenceLen = 0; quality = NULL; qualityLen = 0; truncatedLen = 0; } }; struct FastqChecksum { enum CheksumFlags { CALC_TAG = BIT(0), CALC_SEQUENCE = BIT(1), CALC_QUALITY = BIT(2), CALC_NONE = 0, CALC_ALL = CALC_TAG | CALC_SEQUENCE | CALC_QUALITY }; uint32 tag; uint32 sequence; uint32 quality; FastqChecksum() : tag(0) , sequence(0) , quality(0) {} void Reset() { tag = 0; sequence = 0; quality = 0; } }; } // namespace fq } // namespace dsrc #endif
RabbitBio/RabbitBM
src/pigz.h
// // Created by ylf9811 on 2021/10/14. // #ifndef PAC2022_PIGZ_H #define PAC2022_PIGZ_H #include "readerwriterqueue.h" #include "atomicops.h" #include <atomic> int main_pigz(int argc, char **argv, moodycamel::ReaderWriterQueue<std::pair<int, std::pair<char *, int>>> *Q, std::atomic_int *wDone, std::pair<char *, int> &L); #endif //PAC2022_PIGZ_H
RabbitBio/RabbitBM
src/barcodeToPositionMulti.h
#ifndef BARCODETOPOSITIONMULTI_H #define BARCODETOPOSITIONMULTI_H #include <string> #include <unordered_map> //#include "robin_hood.h" #include <atomic> #include <thread> #include <functional> #include <sys/time.h> #include "options.h" #include "barcodePositionMap.h" #include "barcodeProcessor.h" #include "fixedfilter.h" #include "writerThread.h" #include "result.h" #include "readerwriterqueue.h" #include "atomicops.h" using namespace std; struct ReadPairPack { //ReadPair** data; vector<ReadPair *> data; int count; }; struct ReadPack { //Read** data; vector<Read *> data; int count; }; typedef struct ReadPairPack ReadPairPack; typedef struct ReadPack ReadPack; typedef struct ReadPairRepository { ChunkPair **packBuffer; atomic_long readPos; atomic_long writePos; } ReadPairRepository; class BarcodeToPositionMulti { public: BarcodeToPositionMulti(Options *opt); ~BarcodeToPositionMulti(); bool process(); private: void initOutput(); void closeOutput(); bool processPairEnd(ReadPairPack *pack, Result *result); void initPackRepositoey(); void destroyPackRepository(); // void producePack(ReadPairPack *pack); void producePack(ChunkPair *pack); void consumePack(Result *result); void pugzTask1(); void pugzTask2(); void producerTask(); void consumerTask(Result *result); void writeTask(WriterThread *config); void getMbpmap(); void pigzWrite(); void mergeWrite(); public: Options *mOptions; BarcodePositionMap *mbpmap; FixedFilter *fixedFilter; moodycamel::ReaderWriterQueue<std::pair<char *, int>> *pugzQueue1; moodycamel::ReaderWriterQueue<std::pair<char *, int>> *pugzQueue2; moodycamel::ReaderWriterQueue<std::pair<int, std::pair<char *, int>>> *pigzQueue; // moodycamel::ReaderWriterQueue<std::pair<char *, int>> *mergeQueue; pair<char *, int> pigzLast; std::atomic_int pugz1Done; std::atomic_int pugz2Done; std::atomic_int producerDone; std::atomic_int writerDone; std::atomic_int mergeDone; //unordered_map<uint64, Position*> misBarcodeMap; private: ReadPairRepository mRepo; atomic_bool mProduceFinished; atomic_int mFinishedThreads; std::mutex mOutputMtx; std::mutex mInputMutx; gzFile mZipFile; ofstream *mOutStream; WriterThread *mWriter; WriterThread *mUnmappedWriter; bool filterFixedSequence = false; FastqChunkReaderPair *pairReader; dsrc::fq::FastqDataPool *fastqPool; }; #endif
RabbitBio/RabbitBM
src/common.h
<reponame>RabbitBio/RabbitBM<gh_stars>0 #ifndef COMMON_H #define COMMON_H #define FASTP_VER "0.20.0" #define _DEBUG false #include <boost/serialization/string.hpp> #include <boost/serialization/unordered_map.hpp> #include <mpi.h> //#define PRINT_INFO typedef long long int int64; typedef unsigned long long int uint64; typedef int int32; typedef unsigned int uint32; typedef short int16; typedef unsigned short uint16; typedef char int8; typedef unsigned char uint8; const char ATCG_BASES[4] = {'A', 'C', 'T', 'G'}; const uint8 RC_BASE[4] = {2, 3, 0, 1}; static const int SEQ_BINARY_SIZE = 8; static const int COUNT_BINARY_SUZE = 2; static const long long int MAX_BARCODE = 0xffffffffffffffff; typedef long long ll; typedef __int128_t i128; #define MOD 1073807359 #pragma pack(2) #pragma pack() // the limit of the queue to store the packs // error may happen if it generates more packs than this number static const int PACK_NUM_LIMIT = 10000000; //buckets number for barcode unordered set static const int BARCODE_SET_LIMIT = 100000000; // how many reads one pack has static const int PACK_SIZE = 1000; // if one pack is produced, but not consumed, it will be kept in the memory // this number limit the number of in memory packs // if the number of in memory packs is full, the producer thread should sleep //static const int PACK_IN_MEM_LIMIT = 500; static const int PACK_IN_MEM_LIMIT = 1 << 20; // if read number is more than this, warn it static const int WARN_STANDALONE_READ_LIMIT = 10000; //block number per fov static const int BLOCK_COL_NUM = 10; static const int BLOCK_ROW_NUM = 10; static const int TRACK_WIDTH = 3; static const int FOV_GAP = 0; static const int MAX_DNB_EXP = 250; static const int EST_DNB_DISTANCE = 1; //static const int mod = 1000000007; //static const int mod = 73939133; static const int mod = 1073807359; //static const int mod = 2000000011; static const i128 oneI = 1; static const i128 _base = (oneI << 64) / mod; //inline uint64 mol(uint64 x) { return x - mod * (_base * x >> 64); } #define mol(x) ( (x) - mod * (_base * (x) >> 64) ) //some hash func inline uint32 Hash0(uint64 barCode) { barCode = (~barCode) + (barCode << 18); // key = (key << 18) - key - 1; barCode = barCode ^ (barCode >> 31); barCode = barCode * 21; // key = (key + (key << 2)) + (key << 4); barCode = barCode ^ (barCode >> 11); barCode = barCode + (barCode << 6); barCode = barCode ^ (barCode >> 22); return (uint32) barCode; } inline uint32 Hash1(uint64 barCode) { return barCode % 1073807359; } inline uint32 Hash2(uint64 barCode, uint64 seed = 0) { barCode ^= seed; barCode ^= barCode >> 33; barCode *= 0xff51afd7ed558ccd; barCode ^= barCode >> 33; barCode *= 0xc4ceb9fe1a85ec53; barCode ^= barCode >> 33; return uint32(barCode >> 33); } inline uint32 Hash3(uint64 barCode) { return uint32((barCode >> 32) ^ (barCode & ((1ll << 32) - 1))); } inline uint32 Hash4(uint64 barCode) { return uint32((barCode >> 25) ^ (barCode & ((1ll << 25) - 1))); } #define bfIdx(x) //outside dnb idx reture value static const int OUTSIDE_DNB_POS_ROW = 1410065408; static const int OUTSIDE_DNB_POS_COL = 1410065408; typedef struct slideRange { uint32 colStart; uint32 colEnd; uint32 rowStart; uint32 rowEnd; } slideRange; typedef struct Position { friend class boost::serialization::access; uint8 fov_c; uint8 fov_r; uint32 x; uint32 y; template<typename Archive> void serialize(Archive &ar, const unsigned int version) { ar & fov_c; ar & fov_r; ar & x; ar & y; } } Position; typedef struct Position1 { friend class boost::serialization::access; uint32 x; uint32 y; template<typename Archive> void serialize(Archive &ar, const unsigned int version) { ar & x; ar & y; } } Position1; typedef struct node { int pre; uint64 v; int32 p; } node; typedef struct bpmap_key_value { uint64 key; Position1 value; } bpmap_key_value; /* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ //#include "../include/dsrc/Globals.h" #include "Globals.h" #ifndef NDEBUG # define DEBUG 1 #endif #define BIT(x) (1 << (x)) #define BIT_ISSET(x, pos) ((x & BIT(pos)) != 0) #define BIT_SET(x, pos) (x |= BIT(pos)) #define BIT_UNSET(x, pos) (x &= ~(BIT(pos))) #define MIN(x, y) ((x) <= (y) ? (x) : (y)) #define MAX(x, y) ((x) >= (y) ? (x) : (y)) #define ABS(x) ((x) >= 0 ? (x) : -(x)) #define SIGN(x) ((x) >= 0 ? 1 : -1) #define REC_EXTENSION_FACTOR(size) ( ((size) / 4 > 1024) ? ((size) / 4) : 1024 ) #define MEM_EXTENSION_FACTOR(size) REC_EXTENSION_FACTOR(size) #if defined (_WIN32) # define _CRT_SECURE_NO_WARNINGS # pragma warning(disable : 4996) // D_SCL_SECURE # pragma warning(disable : 4244) // conversion uint64 to uint32 # pragma warning(disable : 4267) # pragma warning(disable : 4800) // conversion byte to bool #endif // TODO: refactor raw data structs to avoid using <string> as a member #include <string> #define COMPILE_TIME_ASSERT(COND, MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1] #define COMPILE_TIME_ASSERT1(X, L) COMPILE_TIME_ASSERT(X,static_assertion_at_line_##L) #define COMPILE_TIME_ASSERT2(X, L) COMPILE_TIME_ASSERT1(X,L) #define STATIC_ASSERT(X) COMPILE_TIME_ASSERT2(X,__LINE__) namespace dsrc { namespace fq { // ******************************************************************************************** struct FastqDatasetType { static const uint32 AutoQualityOffset = 0; static const uint32 DefaultQualityOffset = 33; uint32 qualityOffset; bool plusRepetition; bool colorSpace; FastqDatasetType() : qualityOffset(AutoQualityOffset), plusRepetition(false), colorSpace(false) {} static FastqDatasetType Default() { FastqDatasetType ds; ds.qualityOffset = AutoQualityOffset; ds.plusRepetition = false; ds.colorSpace = false; return ds; } }; struct StreamsInfo { enum StreamName { MetaStream = 0, TagStream, DnaStream, QualityStream, StreamCount = 4 }; uint64 sizes[4]; StreamsInfo() { Clear(); } void Clear() { std::fill(sizes, sizes + StreamCount, 0); } }; struct FastqRecord; } // namespace fq namespace comp { struct CompressionSettings { static const uint32 MaxDnaOrder = 9; static const uint32 MaxQualityOrder = 6; static const uint32 DefaultDnaOrder = 0; static const uint32 DefaultQualityOrder = 0; static const uint32 DefaultTagPreserveFlags = 0; // 0 -- keep all uint32 dnaOrder; uint32 qualityOrder; uint64 tagPreserveFlags; bool lossy; bool calculateCrc32; CompressionSettings() : dnaOrder(0), qualityOrder(0), tagPreserveFlags(DefaultTagPreserveFlags), lossy(false), calculateCrc32(false) {} static CompressionSettings Default() { CompressionSettings s; s.dnaOrder = DefaultDnaOrder; s.qualityOrder = DefaultQualityOrder; s.tagPreserveFlags = DefaultTagPreserveFlags; s.lossy = false; s.calculateCrc32 = false; return s; } }; struct InputParameters { static const uint32 DefaultQualityOffset = fq::FastqDatasetType::AutoQualityOffset; static const uint32 DefaultDnaCompressionLevel = 0; static const uint32 DefaultQualityCompressionLevel = 0; static const uint32 DefaultProcessingThreadNum = 2; static const uint64 DefaultTagPreserveFlags = 0; static const uint32 DefaultFastqBufferSizeMB = 8; static const bool DefaultLossyCompressionMode = false; static const bool DefaultCalculateCrc32 = false; uint32 qualityOffset; uint32 dnaCompressionLevel; uint32 qualityCompressionLevel; uint32 threadNum; uint64 tagPreserveFlags; uint32 fastqBufferSizeMB; bool lossyCompression; bool calculateCrc32; bool useFastqStdIo; std::string inputFilename; std::string outputFilename; InputParameters() : qualityOffset(DefaultQualityOffset), dnaCompressionLevel(DefaultDnaCompressionLevel), qualityCompressionLevel(DefaultQualityCompressionLevel), threadNum(DefaultProcessingThreadNum), tagPreserveFlags(DefaultTagPreserveFlags), fastqBufferSizeMB(DefaultFastqBufferSizeMB), lossyCompression(DefaultLossyCompressionMode), calculateCrc32(DefaultCalculateCrc32), useFastqStdIo(false) {} static InputParameters Default() { InputParameters args; return args; } }; struct Field; struct DnaStats; struct QualityStats; class BlockCompressor; class HuffmanEncoder; struct DsrcDataChunk; } // namespace comp namespace core { class Buffer; class BitMemoryReader; class BitMemoryWriter; class ErrorHandler; } // namespace core } // namespace dsrc #endif /* COMMON_H */
RabbitBio/RabbitBM
src/Globals.h
/* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ /* This file is modified by SDU HPC lab for RabbitQC project. Last modified: JULY2019 */ #ifndef H_GLOBALS #define H_GLOBALS #ifndef NDEBUG # define DEBUG 1 #endif // Visual Studio warning supression // #if defined (_WIN32) # define _CRT_SECURE_NO_WARNINGS # pragma warning(disable : 4996) // D_SCL_SECURE # pragma warning(disable : 4244) // conversion uint64 to uint32 # pragma warning(disable : 4267) # pragma warning(disable : 4800) // conversion byte to bool #endif // assertions // #if defined(DEBUG) || defined(_DEBUG) # include "assert.h" # define ASSERT(x) assert(x) #else # define ASSERT(x) (void)(x) #endif #include <string> #include <stdexcept> namespace dsrc { // basic types // typedef char int8; typedef unsigned char uchar, byte, uint8; typedef short int int16; typedef unsigned short int uint16; typedef int int32; typedef unsigned int uint32; typedef long long int64; typedef unsigned long long uint64; // exception class // class DsrcException : public std::exception { std::string message; public: DsrcException(const char* msg_) : message(msg_) {} DsrcException(const std::string& msg_) : message(msg_) {} ~DsrcException() throw() {} const char* what() const throw() // for std::exception interface { return message.c_str(); } }; } // namespace dsrc #endif // H_GLOBALS
RabbitBio/RabbitBM
src/barcodeListMerge.h
#ifndef BARCODELISTMERGE_H #define BARCODELISTMERGE_H #include <iostream> #include <unordered_map> //#include "robin_hood.h" #include <vector> #include <fstream> #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/serialization/unordered_map.hpp> #include "options.h" using namespace std; class BarcodeListMerge{ public: BarcodeListMerge(Options* opt); ~BarcodeListMerge(); void mergeBarcodeLists(); private: void addBarcodeList(unordered_map<uint64, int>& dnbMap); void dumpMergedBarcodeList(string& outfile); private: Options* mOptions; vector<string> dnbMapFiles; string mergedDnbMapFile; unordered_map<uint64, int> mergedDnbMap; }; #endif
RabbitBio/RabbitBM
src/yarn.h
<filename>src/yarn.h /* yarn.h -- generic interface for threadPigz operations * Copyright (C) 2008, 2011, 2012, 2015, 2018, 2019, 2020 <NAME> * Version 1.7 12 Apr 2020 <NAME> */ /* This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. <NAME> <EMAIL> */ /* Basic threadPigz operations This interface isolates the local operating system implementation of threads from the application in order to facilitate platform independent use of threads. All of the implementation details are deliberately hidden. Assuming adequate system resources and proper use, none of these functions can fail. As a result, any errors encountered will cause an exit() to be executed, or the execution of your own optionally-provided abort function. These functions allow the simple launching and joining of threads, and the locking of objects and synchronization of changes of objects. The latter is implemented with a single lock_pigz type that contains an integer value. The value can be ignored for simple exclusive access to an object, or the value can be used to signal and wait for changes to an object. -- Arguments -- threadPigz *threadPigz; identifier for launched threadPigz, used by join_pigz void probe(void *); pointer to function "probe", run when threadPigz starts void *payload; single argument passed to the probe function lock_pigz *lock_pigz; a lock_pigz with a value -- used for exclusive access to an object and to synchronize threads waiting for changes to an object long val; value to set lock_pigz, increment lock_pigz, or wait for int n; number of threads joined -- Thread functions -- threadPigz = launch_pigz(probe, payload) - launch_pigz a threadPigz -- exit via probe() return join_pigz(threadPigz) - join_pigz a threadPigz and by joining end it, waiting for the threadPigz to exit if it hasn't already -- will free the resources allocated by launch_pigz() (don't try to join_pigz the same threadPigz more than once) n = join_all_pigz() - join_pigz all threads launched by launch_pigz() that are not joined yet and free the resources allocated by the launches, usually to clean up when the threadPigz processing is done -- join_all_pigz() returns an int with the count of the number of threads joined (join_all_pigz() should only be called from the main threadPigz, and should only be called after any calls of join_pigz() have completed) -- Lock functions -- lock_pigz = new_lock_pigz(val) - create a new lock_pigz with initial value val (lock_pigz is created in the released state) possess_pigz(lock_pigz) - acquire exclusive possession of a lock_pigz, waiting if necessary twist_pigz(lock_pigz, [TO | BY], val) - set lock_pigz to or increment lock_pigz by val, signal all threads waiting on this lock_pigz and then release_pigz the lock_pigz -- must possess_pigz the lock_pigz before calling (twist_pigz releases, so don't do a release_pigz() after a twist_pigz() on the same lock_pigz) wait_for_pigz(lock_pigz, [TO_BE | NOT_TO_BE | TO_BE_MORE_THAN | TO_BE_LESS_THAN], val) - wait on lock_pigz value to be, not to be, be greater than, or be less than val -- must possess_pigz the lock_pigz before calling, will possess_pigz the lock_pigz on return but the lock_pigz is released while waiting to permit other threads to use twist_pigz() to change the value and signal the change (so make sure that the object is in a usable state when waiting) release_pigz(lock_pigz) - release_pigz a possessed lock_pigz (do not try to release_pigz a lock_pigz that the current threadPigz does not possess_pigz) val = peek_lock(lock_pigz) - return the value of the lock_pigz (assumes that lock_pigz is already possessed, no possess_pigz or release_pigz is done by peek_lock()) free_lock_pigz(lock_pigz) - free the resources allocated by new_lock_pigz() (application must assure that the lock_pigz is released before calling free_lock_pigz()) -- Memory allocation --- yarn_mem(better_malloc, better_free) - set the memory allocation and free routines for use by the yarn routines where the supplied routines have the same interface and operation as malloc() and free(), and may be provided in order to supply threadPigz-safe memory allocation routines or for any other reason -- by default malloc() and free() will be used -- Error control -- yarn_prefix - a char pointer to a string that will be the prefix for any error messages that these routines generate before exiting -- if not changed by the application, "yarn" will be used yarn_abort - an external function that will be executed when there is an internal yarn error, due to out of memory or misuse -- this function may exit to abort the application, or if it returns, the yarn error handler will exit (set to NULL by default for no action) */ #ifdef __cplusplus extern "C" { #endif extern char *yarn_prefix; extern void (*yarn_abort)(int); void yarn_mem(void *(*)(size_t), void (*)(void *)); typedef struct thread_s threadPigz; threadPigz *launch_(void (*)(void *), void *, char const *, long); #define launch_pigz(a, b) launch_(a, b, __FILE__, __LINE__) void join_(threadPigz *, char const *, long); #define join_pigz(a) join_(a, __FILE__, __LINE__) int join_all_(char const *, long); #define join_all_pigz() join_all_(__FILE__, __LINE__) typedef struct lock_s lock_pigz; lock_pigz *new_lock_(long, char const *, long); #define new_lock_pigz(a) new_lock_(a, __FILE__, __LINE__) void possess_(lock_pigz *, char const *, long); #define possess_pigz(a) possess_(a, __FILE__, __LINE__) void release_(lock_pigz *, char const *, long); #define release_pigz(a) release_(a, __FILE__, __LINE__) enum twist_op { TO, BY }; void twist_(lock_pigz *, enum twist_op, long, char const *, long); #define twist_pigz(a, b, c) twist_(a, b, c, __FILE__, __LINE__) enum wait_op { TO_BE, /* or */ NOT_TO_BE, /* that is the question */ TO_BE_MORE_THAN, TO_BE_LESS_THAN }; void wait_for_(lock_pigz *, enum wait_op, long, char const *, long); #define wait_for_pigz(a, b, c) wait_for_(a, b, c, __FILE__, __LINE__) long peek_lock(lock_pigz *); void free_lock_(lock_pigz *, char const *, long); #define free_lock_pigz(a) free_lock_(a, __FILE__, __LINE__) #ifdef __cplusplus } #endif
RabbitBio/RabbitBM
src/fastqreader.h
#ifndef FASTQ_READER_H #define FASTQ_READER_H #include <stdio.h> #include <stdlib.h> #include "read.h" #ifdef DYNAMIC_ZLIB #include <zlib.h> #else #include "zlib/zlib.h" #endif #include "common.h" #include <iostream> #include <fstream> #include "FastqIo.h" #include "FastqStream.h" #include "readerwriterqueue.h" #include "atomicops.h" class FastqReader { public: FastqReader(string filename, bool hasQuality = true, bool phred64 = false); ~FastqReader(); bool isZipped(); void getBytes(size_t &bytesRead, size_t &bytesTotal); //this function is not thread-safe //do not call read() of a same FastqReader object from different threads concurrently Read *read(); bool eof(); bool hasNoLineBreakAtEnd(); public: static bool isZipFastq(string filename); static bool isFastq(string filename); static bool test(); private: void init(); void close(); string getLine(); void clearLineBreaks(char *line); void readToBuf(); private: string mFilename; gzFile mZipFile; FILE *mFile; bool mZipped; bool mHasQuality; bool mPhred64; char *mBuf; int mBufDataLen; int mBufUsedLen; bool mStdinMode; bool mHasNoLineBreakAtEnd; }; class FastqReaderPair { public: FastqReaderPair(FastqReader *left, FastqReader *right); FastqReaderPair(string leftName, string rightName, bool hasQuality = true, bool phred64 = false, bool interleaved = false); ~FastqReaderPair(); ReadPair *read(); public: FastqReader *mLeft; FastqReader *mRight; bool mInterleaved; }; class FastqChunkReaderPair { public: FastqChunkReaderPair(dsrc::fq::FastqReader *left, dsrc::fq::FastqReader *right); FastqChunkReaderPair(string leftName, string rightName, bool hasQuality = true, bool phred64 = false, bool interleaved = false); ~FastqChunkReaderPair(); void SkipToEol(dsrc::uchar *data_, uint64 &pos_, const uint64 size_); uint64 GetNextRecordPos(dsrc::uchar *data_, uint64 pos_, const uint64 size_); ChunkPair *readNextChunkPair(moodycamel::ReaderWriterQueue<std::pair<char *, int>> *q1, moodycamel::ReaderWriterQueue<std::pair<char *, int>> *q2, atomic_int *d1, atomic_int *d2, pair<char *, int> &last1, pair<char *, int> &last2); ChunkPair *readNextChunkPair(); ChunkPair *readNextChunkPair_interleaved(); ChunkPair *readNextChunkPair_interleaved(moodycamel::ReaderWriterQueue<std::pair<char *, int>> *q1, moodycamel::ReaderWriterQueue<std::pair<char *, int>> *q2, atomic_int *d1, atomic_int *d2, pair<char *, int> &last1, pair<char *, int> &last2); public: dsrc::fq::FastqDataPool *fastqPool_left; dsrc::fq::FastqFileReader *fileReader_left; dsrc::fq::FastqDataPool *fastqPool_right; dsrc::fq::FastqFileReader *fileReader_right; dsrc::fq::FastqReader *mLeft; dsrc::fq::FastqReader *mRight; bool mInterleaved; //---mamber variable for readNextchunkpair dsrc::core::Buffer swapBuffer_left; dsrc::core::Buffer swapBuffer_right; bool usesCrlf; bool eof; uint64 bufferSize_left; uint64 bufferSize_right; }; #endif
RabbitBio/RabbitBM
lib/gzip_constants.h
/* * gzip_constants.h - constants for the gzip wrapper format */ #ifndef LIB_GZIP_CONSTANTS_H #define LIB_GZIP_CONSTANTS_H #define GZIP_MIN_HEADER_SIZE 10 #define GZIP_FOOTER_SIZE 8 #define GZIP_MIN_OVERHEAD (GZIP_MIN_HEADER_SIZE + GZIP_FOOTER_SIZE) #define GZIP_ID1 byte(0x1F) #define GZIP_ID2 byte(0x8B) #define GZIP_CM_DEFLATE byte(8) #define GZIP_FTEXT uint8_t(0x01) #define GZIP_FHCRC uint8_t(0x02) #define GZIP_FEXTRA uint8_t(0x04) #define GZIP_FNAME uint8_t(0x08) #define GZIP_FCOMMENT uint8_t(0x10) #define GZIP_FRESERVED uint8_t(0xE0) #define GZIP_MTIME_UNAVAILABLE 0 #define GZIP_XFL_SLOWEST_COMRESSION 0x02 #define GZIP_XFL_FASTEST_COMRESSION 0x04 #define GZIP_OS_FAT 0 #define GZIP_OS_AMIGA 1 #define GZIP_OS_VMS 2 #define GZIP_OS_UNIX 3 #define GZIP_OS_VM_CMS 4 #define GZIP_OS_ATARI_TOS 5 #define GZIP_OS_HPFS 6 #define GZIP_OS_MACINTOSH 7 #define GZIP_OS_Z_SYSTEM 8 #define GZIP_OS_CP_M 9 #define GZIP_OS_TOPS_20 10 #define GZIP_OS_NTFS 11 #define GZIP_OS_QDOS 12 #define GZIP_OS_RISCOS 13 #define GZIP_OS_UNKNOWN 255 #endif /* LIB_GZIP_CONSTANTS_H */
RabbitBio/RabbitBM
src/tree.h
<filename>src/tree.h /* Copyright 2011 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Author: <EMAIL> (<NAME>) Author: <EMAIL> (<NAME>) */ /* Utilities for creating and using Huffman trees. */ #ifndef ZOPFLI_TREE_H_ #define ZOPFLI_TREE_H_ #include <string.h> #ifdef __cplusplus extern "C" { #endif /* Calculates the bitlengths for the Huffman tree, based on the counts of each symbol. */ void ZopfliCalculateBitLengths(const size_t *count, size_t n, int maxbits, unsigned *bitlengths); /* Converts a series of Huffman tree bitlengths, to the bit values of the symbols. */ void ZopfliLengthsToSymbols(const unsigned *lengths, size_t n, unsigned maxbits, unsigned *symbols); /* Calculates the entropy of each symbol, based on the counts of each symbol. The result is similar to the result of ZopfliCalculateBitLengths, but with the actual theoritical bit lengths according to the entropy. Since the resulting values are fractional, they cannot be used to encode the tree specified by DEFLATE. */ void ZopfliCalculateEntropy(const size_t *count, size_t n, double *bitlengths); #ifdef __cplusplus } #endif #endif /* ZOPFLI_TREE_H_ */
RabbitBio/RabbitBM
src/Buffer.h
<gh_stars>0 /* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ /* This file is modified by SDU HPC lab for RabbitQC project. Last modified: JULY2019 */ #ifndef BUFFER_H #define BUFFER_H //#include "../include/dsrc/Globals.h" #include "Globals.h" #include <algorithm> #include "utils.h" namespace dsrc { namespace core { #define USE_64BIT_MEMORY 1 class Buffer { public: Buffer(uint64 size_) { ASSERT(size_ != 0); #if (USE_64BIT_MEMORY) uint64 size64 = size_ / 8; if (size64 * 8 < size_) size64 += 1; buffer = new uint64[size64]; #else buffer = new byte[size_]; #endif size = size_; } ~Buffer() { delete buffer; } uint64 Size() const { return size; } byte* Pointer() const { return (byte*)buffer; } #if (USE_64BIT_MEMORY) uint64* Pointer64() const { return buffer; } #endif void Extend(uint64 size_, bool copy_ = false) { #if (USE_64BIT_MEMORY) uint64 size64 = size / 8; if (size64 * 8 < size) size64 += 1; uint64 newSize64 = size_ / 8; if (newSize64 * 8 < size_) newSize64 += 1; if (size > size_) return; if (size64 == newSize64) { size = size_; return; } uint64* p = new uint64[newSize64]; if (copy_) std::copy(buffer, buffer + size64, p); #else if (size > size_) return; byte* p = new byte[size_]; if (copy_) std::copy(buffer, buffer + size, p); #endif delete[] buffer; buffer = p; size = size_; } void Swap(Buffer& b) { TSwap(b.buffer, buffer); TSwap(b.size, size); } private: Buffer(const Buffer& ) {} Buffer& operator= (const Buffer& ) { return *this; } #if (USE_64BIT_MEMORY) uint64* buffer; #else byte* buffer; #endif uint64 size; }; struct DataChunk { static const uint64 DefaultBufferSize = 1 << 20; // 1 << 22 Buffer data; uint64 size; DataChunk(const uint64 bufferSize_ = DefaultBufferSize) : data(bufferSize_) , size(0) {} void Reset() { size = 0; } }; } // namespace core } // namespace dsrc #endif // BUFFER_H
RabbitBio/RabbitBM
src/writerThread.h
<gh_stars>0 #ifndef WRITER_THREAD_H #define WRITER_THREAD_H #include <stdio.h> #include <stdlib.h> #include <string> #include <cstring> #include <vector> #include "writer.h" #include <atomic> #include <mutex> #include "atomicops.h" #include "readerwriterqueue.h" #include "util.h" #include "options.h" using namespace std; class WriterThread { public: WriterThread(string filename, int compressionLevel = 4); WriterThread(string filename, Options *options, int compressionLevel = 4); ~WriterThread(); void initWriter(string filename1); void initWriter(ofstream *stream); void initWriter(gzFile gzfile); void cleanup(); bool isCompleted(); void output(); void output(MPI_Comm communicator); void output(moodycamel::ReaderWriterQueue<pair<int, pair<char *, int>>> *Q); void input(char *data, size_t size); void inputFromMerge(char *data, size_t size); bool setInputCompleted(); long bufferLength(); string getFilename() { return mFilename; } private: void deleteWriter(); private: Writer *mWriter1; int compression; string mFilename; Options *mOptions; //for split output bool mInputCompleted; atomic_long mInputCounter; atomic_long mOutputCounter; char **mRingBuffer; size_t *mRingBufferSizes; int *mRingBufferTags; public: const atomic_long &GetMInputCounter() const; const atomic_long &GetMOutputCounter() const; private: int cSum; public: int GetCSum() const; private: long long wSum; public: long long GetWSum() const; private: mutex mtx; }; #endif
RabbitBio/RabbitBM
src/try.h
<reponame>RabbitBio/RabbitBM /* try.h -- try / catch / throw exception handling for C99 Copyright (C) 2013, 2015 <NAME> Version 1.2 19 January 2015 This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. <NAME> <EMAIL> */ /* Version History 1.0 7 Jan 2013 - First version 1.1 2 Nov 2013 - Use variadic macros and functions instead of partial structure assignment, allowing arbitrary arguments to printf() 1.2 19 Jan 2015 - Obey setjmp() invocation limits from C standard */ /* To use, include try.h in all source files that use these operations, and compile and link try.c. If pthread threads are used, then there must be an #include <pthread.h> in try.h to make the exception handling thread-safe. (Uncomment the include below.) If threads other than pthread are being used, then try.h and try.c must be modified to use that environment's thread-local storage for the try_stack_ pointer. try.h and try.c assume that the compiler and library conform to the C99 standard, at least with respect to the use of variadic macro and function arguments. */ /* try.h provides a try / catch / throw exception handler, which allows catching exceptions across any number of levels of function calls. try blocks can be nested as desired, with a throw going to the end of the innermost enclosing try, passing the thrown information to the associated catch block. A global try stack is used, to avoid having to pass exception handler information through all of the functions down to the invocations of throw. The try stack is thread-unique if requested by uncommenting the pthread.h include below. In addition to the macros try, catch, and throw, the macros always, retry, punt, and drop, and the type ball_t are created. All other symbols are of the form try_*_ or TRY_*_, where the final underscore should avoid conflicts with application symbols. The eight exposed names can be changed easily in #defines below. A try block encloses code that may throw an exception with the throw() macro, either directly in the try block or in any function called directly or indirectly from the try block. throw() must have at least one argument, which is an integer. The try block is followed by a catch block whose code will be executed when throw() is called with a non-zero first argument. If the first argument of throw() is zero, then execution continues after the catch block. If the try block completes normally, with no throw() being called, then execution continues normally after the catch block. There can be only one catch block. catch has one argument which must be a ball_t type variable declared in the current function or block containing the try and catch. That variable is loaded with the information sent by the throw() for use in the catch block. throw() may optionally include more information that is passed to the catch block in the ball_t structure. throw() can have one or more arguments, where the first (possibly only) argument is an integer code. The second argument can be a pointer, which will be replaced by NULL in the ball_t structure if not provided. The implementation of throw() in try.c assumes that if the second argument is present and is not NULL, that it is a string. If that string has any percent (%) signs in it, then throw() will run that string through vsnprintf() with any other arguments provided after the string in the throw() invocation, and save the resulting formatted string in the ball_t structure. Information on whether or not the string was allocated is also maintained in the ball_t structure. throw() in try.c can be modified to not assume that the second argument is a string. For example, an application may want to assume instead that the second argument is a pointer to a set of information for use in the catch block. The catch block may conditionally do a punt(), where the argument of punt() is the argument of catch. This passes the exception on to the next enclosing try/catch handler. If a catch block does not always end with a punt(), it should contain a drop(), where the argument of drop() is the argument of catch. This frees the allocated string made if vsnprintf() was used by throw() to generate the string. If printf() format strings are never used, then drop() is not required. An always block may be placed between the try and catch block. The statements in that block will be executed regardless of whether or not the try block completed normally. As indicated by the ordering, the always block will be executed before the catch block. This block is not named "finally", since it is different from the finally block in other languages which is executed after the catch block. A naked break or continue in a try or always block will go directly to the end of that block. A retry from the try block or from any function called from the try block at any level of nesting will restart the try block from the beginning. try is thread-safe when compiled with pthread.h. A throw() in a thread can only be caught in the same thread. If a throw() is attempted from a thread without an enclosing try in that thread, even if in another thread there is a try around the pthread_create() that spawned this thread, then the throw will fail on an assert. Each thread has its own thread-unique try stack, which starts off empty. If an intermediate function does not have a need for operations in a catch block other than punt, and does not need an always block, then that function does not need a try block. "try { block } catch (err) { punt(err); }" is the same as just "block". More precisely, it's equivalent to "do { block } while (0);", which replicates the behavior of a naked break or continue in a block when it follows try. throw() can be used from a function that has no try. All that is necessary is that there is a try somewhere up the function chain that called the current function in the current thread. There must not be a return in any try block, nor a goto in any try block that leaves that block. The always block does not catch a return from the try block. There is no check or protection for an improper use of return or goto. It is up to the user to assure that this doesn't happen. If it does happen, then the reference to the current try block is left on the try stack, and the next throw which is supposed to go to an enclosing try would instead go to this try, possibly after the enclosing function has returned. Mayhem will then ensue. This may be caught by the longjmp() implementation, which would report "longjmp botch" and then abort. Any automatic storage variables that are modified in the try block and used in the catch or always block must be declared volatile. Otherwise their value in the catch or always block is indeterminate. Any statements between try and always, between try and catch if there is no always, or between always and catch are part of those respective try or always blocks. Use of { } to enclose those blocks is optional, but { } should be used anyway for clarity, style, and to inform smart source editors that the enclosed code is to be indented. Enclosing the catch block with { } is not optional if there is more than one statement in the block. However, even if there is just one statement in the catch block, it should be enclosed in { } anyway for style and editing convenience. The contents of the ball_t structure after the first element (int code) can be customized for the application. If ball_t is customized, then the code in try.c should be updated accordingly. If there is no memory allocation in throw(), then drop() can be eliminated. Example usage: ball_t err; volatile char *temp = NULL; try { ... do something ... if (ret == -1) throw(1, "bad thing happened to %s\n", me); temp = malloc(sizeof(me) + 1); if (temp == NULL) throw(2, "out of memory"); ... do more ... if (ret == -1) throw(3, "worse thing happened to %s\n", temp); ... some more code ... } always { free(temp); } catch (err) { fputs(err.why, stderr); drop(err); return err.code; } ... end up here if nothing bad happened ... More involved example: void check_part(void) { ball_t err; try { ... if (part == bad1) throw(1); ... if (part == bad2) throw(1); ... } catch (err) { drop(err); throw(3, "part was bad"); } } void check_input(void) { ... if (input == wrong) throw(4, "input was wrong"); ... if (input == stupid) throw(5, "input was stupid"); ... check_part(); ... } void *build_something(void) { ball_t err; volatile void *thing; try { thing = malloc(sizeof(struct thing)); ... build up thing ... check_input(); ... finish building it ... } catch (err) { free(thing); punt(err); } return thing; } int grand_central(void) { ball_t err; void *thing; try { thing = build_something(); } catch (err) { fputs(err.why, stderr); drop(err); return err.code; } ... use thing ... free(thing); return 0; } */ #ifndef _TRY_H #define _TRY_H #include <stdlib.h> #include <string.h> #include <assert.h> #include <setjmp.h> #ifdef __cplusplus extern "C" { #endif /* If pthreads are used, uncomment this include to make try thread-safe. */ #ifndef NOTHREAD # include <pthread.h> #endif /* The exposed names can be changed here. */ #define ball_t try_ball_t_ #define try TRY_TRY_ #define always TRY_ALWAYS_ #define catch TRY_CATCH_ #define throw TRY_THROW_ #define retry TRY_RETRY_ #define punt TRY_PUNT_ #define drop TRY_DROP_ /* Package of an integer code and any other data to be thrown and caught. Here, why is a string with information to be displayed to indicate why an exception was thrown. free is true if why was allocated and should be freed when no longer needed. This structure can be customized as needed, but it must start with an int code. If it is customized, the try_throw_() function in try.c must also be updated accordingly. As an example, why could be a structure with information for use in the catch block. */ typedef struct { int code; /* integer code (required) */ int free; /* if true, the message string was allocated */ char *why; /* informational string or NULL */ } try_ball_t_; /* Element in the global try stack (a linked list). */ typedef struct try_s_ try_t_; struct try_s_ { jmp_buf env; /* state information for longjmp() to jump back */ try_ball_t_ ball; /* data passed from the throw() */ try_t_ *next; /* link to the next enclosing try_t, or NULL */ }; /* Global try stack. try.c must be compiled and linked to provide the stack pointer. Use thread-local storage if pthread.h is included before this. Note that a throw can only be caught within the same thread. A new and unique try stack is created for each thread, so any attempt to throw across threads will fail with an assert, by virtue of reaching the end of the stack. */ #ifdef PTHREAD_ONCE_INIT extern pthread_key_t try_key_; void try_setup_(void); # define try_stack_ ((try_t_ *)pthread_getspecific(try_key_)) # define try_stack_set_(next) \ do { \ assert(pthread_setspecific(try_key_, next) == 0 && \ "try: pthread_setspecific() failed"); \ } while (0) #else /* !PTHREAD_ONCE_INIT */ extern try_t_ *try_stack_; # define try_setup_() # define try_stack_set_(next) try_stack_ = (next) #endif /* PTHREAD_ONCE_INIT */ /* Try a block. The block should follow the invocation of try enclosed in { }. The block must be immediately followed by an always or a catch. You must not goto or return out of the try block. A naked break or continue in the try block will go to the end of the block. */ #define TRY_TRY_ \ do { \ try_t_ try_this_; \ volatile int try_pushed_ = 1; \ try_this_.ball.code = 0; \ try_this_.ball.free = 0; \ try_this_.ball.why = NULL; \ try_setup_(); \ try_this_.next = try_stack_; \ try_stack_set_(&try_this_); \ if (setjmp(try_this_.env) < 2) \ do { \ /* Execute the code between always and catch, whether or not something was thrown. An always block is optional. If present, the always block must follow a try block and be followed by a catch block. The always block should be enclosed in { }. A naked break or continue in the always block will go to the end of the block. It is permitted to use throw in the always block, which will fall up to the next enclosing try. However this will result in a memory leak if the original throw() allocated space for the informational string. So it's best to not throw() in an always block. Keep the always block simple. Great care must be taken if the always block uses an automatic storage variable local to the enclosing function that can be modified in the try block. Such variables must be declared volatile. If such a variable is not declared volatile, and if the compiler elects to keep that variable in a register, then the throw will restore that variable to its state at the beginning of the try block, wiping out any change that occurred in the try block. This can cause very confusing bugs until you remember that you didn't follow this rule. */ #define TRY_ALWAYS_ \ } while (0); \ if (try_pushed_) { \ try_stack_set_(try_this_.next); \ try_pushed_ = 0; \ } \ do { /* Catch an error thrown in the preceding try block. The catch block must follow catch and its parameter, and must be enclosed in { }. The catch must immediately follow the try or always block. It is permitted to use throw() in the catch block, which will fall up to the next enclosing try. However the ball_t passed by throw() must be freed using drop() before doing another throw, to avoid a potential memory leak. The parameter of catch must be a ball_t declared in the function or block containing the catch. It is set to the parameters of the throw() that jumped to the catch. The catch block is not executed if the first parameter of the throw() was zero. A catch block should end with either a punt() or a drop(). Great care must be taken if the catch block uses an automatic storage variable local to the enclosing function that can be modified in the try block. Such variables must be declared volatile. If such a variable is not declared volatile, and if the compiler elects to keep that variable in a register, then the throw will restore that variable to its state at the beginning of the try block, wiping out any change that occurred in the try block. This can cause very confusing bugs until you remember that you didn't follow this rule. */ #define TRY_CATCH_(try_ball_) \ } while (0); \ if (try_pushed_) { \ try_stack_set_(try_this_.next); \ try_pushed_ = 0; \ } \ try_ball_ = try_this_.ball; \ } while (0); \ if (try_ball_.code) /* Throw an error. This can be in the try block or in any function called from the try block, at any level of nesting. This will fall back to the end of the first enclosing try block in the same thread, invoking the associated catch block with a ball_t set to the arguments of throw(). throw() will abort the program with an assert() if there is no nesting try. Make sure that there's a nesting try! try may have one or more arguments, where the first argument is an int, the optional second argument is a string, and the remaining optional arguments are referred to by printf() formatting commands in the string. If there are formatting commands in the string, i.e. any percent (%) signs, then vsnprintf() is used to generate the formatted string from the arguments before jumping to the enclosing try block. This allows throw() to use information on the stack in the scope of the throw() statement, which will be lost after jumping back to the enclosing try block. That formatted string will use allocated memory, which is why it is important to use drop() in catch blocks to free that memory, or punt() to pass the string on to another catch block. Eventually some catch block down the chain will have to drop() it. If a memory allocation fails during the execution of a throw(), then the string provided to the catch block is not the formatted string at all, but rather the string: "try: out of memory", with the integer code from the throw() unchanged. If the first argument of throw is zero, then the catch block is not executed. A throw(0) from a function called in the try block is equivalent to a break or continue in the try block. A throw(0) should not have any other arguments, to avoid a potential memory leak. There is no opportunity to make use of any arguments after the 0 anyway. try.c must be compiled and linked to provide the try_throw_() function. */ void try_throw_(int code, char *fmt, ...); #define TRY_THROW_(...) try_throw_(__VA_ARGS__, NULL) /* Retry the try block. This will start over at the beginning of the try block. This can be used in the try block or in any function called from the try block at any level of nesting, just like throw. retry has no argument. If there is a retry in the always or catch block, then it will retry the next enclosing try, not the immediately preceding try. If you use this, make sure you have carefully thought through how it will work. It can be tricky to correctly rerun a chunk of code that has been partially executed. Especially if there are different degrees of progress that could have been made. Also note that automatic variables changed in the try block and not declared volatile will have indeterminate values. We use 1 here instead of 0, since some implementations prevent returning a zero value from longjmp() to setjmp(). */ #define TRY_RETRY_ \ do { \ try_setup_(); \ assert(try_stack_ != NULL && "try: naked retry"); \ longjmp(try_stack_->env, 1); \ } while (0) /* Punt a caught error on to the next enclosing catcher. This is normally used in a catch block with same argument as the catch. */ #define TRY_PUNT_(try_ball_) \ do { \ try_setup_(); \ assert(try_stack_ != NULL && "try: naked punt"); \ try_stack_->ball = try_ball_; \ longjmp(try_stack_->env, 2); \ } while (0) /* Clean up at the end of the line in a catch (no more punts). */ #define TRY_DROP_(try_ball_) \ do { \ if (try_ball_.free) { \ free(try_ball_.why); \ try_ball_.free = 0; \ try_ball_.why = NULL; \ } \ } while (0) #ifdef __cplusplus } #endif #endif /* _TRY_H */
RabbitBio/RabbitBM
src/FastqIo.h
<reponame>RabbitBio/RabbitBM /* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ #ifndef H_FASTQREADER #define H_FASTQREADER #include "Globals.h" #include "common.h" #include "Fastq.h" #include "DataQueue.h" #include "DataPool.h" #include "FastqStream.h" #include "read.h" #include "readerwriterqueue.h" #include "atomicops.h" #include <vector> namespace dsrc { namespace fq { typedef core::TDataQueue<FastqDataChunk> FastqDataQueue; typedef core::TDataPool<FastqDataChunk> FastqDataPool; class FastqReader //: public IFastqIoOperator { public: FastqReader(FastqFileReader &reader_, FastqDataPool &pool_) : recordsPool(pool_), fileReader(reader_), numParts(0) {}; void readChunk(); FastqDataChunk *readNextChunk(); //single pe file FastqDataChunk *readNextPairedChunk(); int64 Read(byte *memory_, uint64 size_) { int64 n = fileReader.Read(memory_, size_); return n; } int64 Read(byte *memory_, uint64 size_, moodycamel::ReaderWriterQueue<std::pair<char *, int>> *q, atomic_int *done, pair<char *, int> &lastInfo, int num) { int64 n = fileReader.Read(memory_, size_, q, done, lastInfo, num); return n; } private: FastqDataPool &recordsPool; FastqFileReader &fileReader; uint32 numParts; }; int chunkFormat(FastqDataChunk *&chunk, std::vector<Read *> &, bool); //single pe file int pairedChunkFormat(FastqDataChunk *&chunk, std::vector<ReadPair *> &, bool mHasQuality); Read *getOnePairedRead(FastqDataChunk *&chunk, int &pos_, bool mHasQuality); //end single pe file string getLine(FastqDataChunk *&chunk, int &pos); pair<char *, int> getLineFast(FastqDataChunk *&chunk, int &pos); } // namespace fq } // namespace dsrc #endif
RabbitBio/RabbitBM
src/htmlreporter.h
#ifndef HTML_REPORTER_H #define HTML_REPORTER_H #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include "options.h" #include <fstream> #include <sstream> #include "barcodePositionMap.h" using namespace std; class HtmlReporter{ public: HtmlReporter(Options* opt); ~HtmlReporter(); static void outputRow(ofstream& ofs, string key, long value); static void outputRow(ofstream& ofs, string key, string value); static string formatNumber(long number); static string toThousands(long number); static string getPercents(long numerator, long denominator); void printReport(string htmlFile, long totalBarcodes, long overlapBarcodes, long dupBarcodes, long uniqueBarcodes, vector<string>& maskFileList); private: const string getCurrentSystemTime(); void printHeader(ofstream& ofs); void printCSS(ofstream& ofs); void printJS(ofstream& ofs); void printFooter(ofstream& ofs); void reportBarcode(ofstream& ofs, long* barcodeStat, int maxReadsNumber); void printSummary(ofstream& ofs, long totalBarcodes, long overlapBarcodes, long dupBarcodes, long uniqueBarcodes, vector<string>& maskFileList); string list2string(long* list, int size); private: Options* mOptions; }; #endif
RabbitBio/RabbitBM
src/options.h
<filename>src/options.h #ifndef OPTIONS_H #define OPTIONS_H #include <stdio.h> #include <stdlib.h> #include <string> #include <cctype> #include <algorithm> #include "util.h" using namespace std; class DrawHeatMapOptions { public: DrawHeatMapOptions() { } public: //hashmap file of the overlaped barcode list string map; //mask file path string maskFile; string fovRange; //min fov colimn int minCol; // max fov column int maxCol; //min fov row int minRow; //max fov row int maxRow; //wether generate q10 heatmap tiff bool getQ10Tiff = false; string q10TiffFile; }; class BarcodeOverlapOptions { public: BarcodeOverlapOptions() { } public: // map file contianning the barcode hash map of second sequencing string in2; int mismatch; // number of base trimed on the front of sequence //int frontTrim = 0; // number of base trimed on the tail of sequence //int tailTrim = 0; // map bucket size }; class BarcodeStatOptions { public: BarcodeStatOptions() { } public: int segment; // wheather the barcodes of two sequencing are reverse complement string rcString; int rc; string readidSep; }; class TransBarcodeToPosOptions { public: TransBarcodeToPosOptions() { } public: //first sequencing fastq file or barcode map file string in; //second sequencing fastq file or barcode map file of read1 string in1; //second sequencing fastq file of read2 string in2; // second sequencing output fastq file of read1 string out1; //second sequencing output fastq file of read2 string out2; //allowed max mismatch int mismatch; //barcode to position map dump file path //string bpMapOutFile; //file path for reads with unmapped barcode string unmappedOutFile; //file path for reads with unmapped barcode of read2 string unmappedOutFile2; //which read contains the umi int umiRead; //umi start position int umiStart; //umi length int umiLen; //which read contians the barcode int barcodeRead; //mapped dnb list file string mappedDNBOutFile; //fixed sequence that will be detected in the read1. string fixedSequence; //fixed sequence file contianing fixed sequence string fixedSequenceFile; //fixed sequence start position int fixedStart; //if PEoutput was true, PE reads will be writen to output. bool PEout = false; }; class Options { public: Options(); void init(); bool validate(); int transRC(string isRC); bool getIsSeq500(string &platform); void setFovRange(string fovRange); public: enum actions { map_barcode_to_slide = 1, merge_barcode_list = 2, mask_format_change = 3, mask_merge = 4 } action; int actionInt = 1; // file name of first sequencing read string in; // output file name string out; // report output file path string report; //compression level for gzip output int compression; uint32_t barcodeLen; int barcodeStart; uint8_t barcodeSegment; int turnFovDegree; string platform; string chipID; bool isSeq500; string maskFile; long mapSize = 100000000; bool verbose; bool usePugz; int thread; int thread2; int pugzThread; int usePigz; int pigzThread; //h5 dims1 size int dims1Size; // //test numa socket // int numaId; //mpi id int myRank; //mpi process int numPro; //test MPI_Comm communicator; //out gz spilt bool outGzSpilt; string rcString; int rc; DrawHeatMapOptions drawHeatMap; BarcodeOverlapOptions barcodeOverlap; BarcodeStatOptions barcodeStat; TransBarcodeToPosOptions transBarcodeToPos; }; #endif
RabbitBio/RabbitBM
src/barcodePositionConfig.h
#ifndef BARCODE_POSITION_CONFIG_H #define BARCODE_POSITION_CONFIG_H #include <stdio.h> #include <unordered_map> //#include "robin_hood.h" #include <unordered_set> #include "common.h" #include "options.h" #include "barcodePositionMap.h" using namespace std; class BarcodePositionConfig { public: BarcodePositionConfig(Options* opt, int threadId); ~BarcodePositionConfig(); static BarcodePositionConfig* merge(BarcodePositionConfig** configs); void addBarcode(uint64 barcodeInt, Position1& pos); void print(); public: Options* mOptions; long totalReads; long lowQReads; long dupReads; long withoutPositionRead; int mThreadId; unordered_set<uint64> barcodeSet; unordered_map<uint64, Position1> bpmap; }; #endif
RabbitBio/RabbitBM
src/bloomFilter.h
<reponame>RabbitBio/RabbitBM // // Created by ylf9811 on 2021/9/28. // #ifndef PAC2022_BLOOMFILTER_H #define PAC2022_BLOOMFILTER_H #include "common.h" #include <iostream> class BloomFilter { public: BloomFilter(); bool push(uint64 key); bool get(uint64 key); bool push_mod(uint64 key); bool get_mod(uint64 key); bool push_xor(uint64 key); bool get_xor(uint64 key); bool push_Classification(uint64 key); bool get_Classification(uint64 key); bool push_wang(uint64 key); bool get_wang(uint64 key); public: uint64* hashtable; uint64* hashtableClassification; uint64 size; const static uint32 HashTableMax = 1ll<<26; const uint64 Bloom_MOD = 73939133; }; #endif //PAC2022_BLOOMFILTER_H
RabbitBio/RabbitBM
lib/deflate_constants.h
/* * deflate_constants.h - constants for the DEFLATE compression format */ #ifndef LIB_DEFLATE_CONSTANTS_H #define LIB_DEFLATE_CONSTANTS_H /* Valid block types */ #define DEFLATE_BLOCKTYPE_UNCOMPRESSED 0 #define DEFLATE_BLOCKTYPE_STATIC_HUFFMAN 1 #define DEFLATE_BLOCKTYPE_DYNAMIC_HUFFMAN 2 /* Minimum and maximum supported match lengths (in bytes) */ #define DEFLATE_MIN_MATCH_LEN 3 #define DEFLATE_MAX_MATCH_LEN 258 /* Minimum and maximum supported match offsets (in bytes) */ #define DEFLATE_MIN_MATCH_OFFSET 1 #define DEFLATE_MAX_MATCH_OFFSET 32768 #define DEFLATE_MAX_WINDOW_SIZE 32768 /* Number of symbols in each Huffman code. Note: for the literal/length * and offset codes, these are actually the maximum values; a given block * might use fewer symbols. */ #define DEFLATE_NUM_PRECODE_SYMS 19 #define DEFLATE_NUM_LITLEN_SYMS 288 #define DEFLATE_NUM_OFFSET_SYMS 32 /* The maximum number of symbols across all codes */ #define DEFLATE_MAX_NUM_SYMS 288 /* Division of symbols in the literal/length code */ #define DEFLATE_NUM_LITERALS 256 #define DEFLATE_END_OF_BLOCK 256 #define DEFLATE_NUM_LEN_SYMS 31 /* Maximum codeword length, in bits, within each Huffman code */ #define DEFLATE_MAX_PRE_CODEWORD_LEN 7 #define DEFLATE_MAX_LITLEN_CODEWORD_LEN 15 #define DEFLATE_MAX_OFFSET_CODEWORD_LEN 15 /* The maximum codeword length across all codes */ #define DEFLATE_MAX_CODEWORD_LEN 15 /* Maximum possible overrun when decoding codeword lengths */ #define DEFLATE_MAX_LENS_OVERRUN 137 /* * Maximum number of extra bits that may be required to represent a match * length or offset. * * TODO: are we going to have full DEFLATE64 support? If so, up to 16 * length bits must be supported. */ #define DEFLATE_MAX_EXTRA_LENGTH_BITS 5 #define DEFLATE_MAX_EXTRA_OFFSET_BITS 14 /* The maximum number of bits in which a match can be represented. This * is the absolute worst case, which assumes the longest possible Huffman * codewords and the maximum numbers of extra bits. */ #define DEFLATE_MAX_MATCH_BITS \ (DEFLATE_MAX_LITLEN_CODEWORD_LEN + DEFLATE_MAX_EXTRA_LENGTH_BITS + DEFLATE_MAX_OFFSET_CODEWORD_LEN \ + DEFLATE_MAX_EXTRA_OFFSET_BITS) #endif /* LIB_DEFLATE_CONSTANTS_H */
RabbitBio/RabbitBM
src/symbols.h
<gh_stars>0 /* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Author: <EMAIL> (<NAME>) Author: <EMAIL> (<NAME>) */ /* Utilities for using the lz77 symbols of the deflate spec. */ #ifndef ZOPFLI_SYMBOLS_H_ #define ZOPFLI_SYMBOLS_H_ #ifdef __cplusplus extern "C" { #endif /* Gets the amount of extra bits for the given dist, cfr. the DEFLATE spec. */ int ZopfliGetDistExtraBits(int dist); /* Gets value of the extra bits for the given dist, cfr. the DEFLATE spec. */ int ZopfliGetDistExtraBitsValue(int dist); /* Gets the symbol for the given dist, cfr. the DEFLATE spec. */ int ZopfliGetDistSymbol(int dist); /* Gets the amount of extra bits for the given length, cfr. the DEFLATE spec. */ int ZopfliGetLengthExtraBits(int l); /* Gets value of the extra bits for the given length, cfr. the DEFLATE spec. */ int ZopfliGetLengthExtraBitsValue(int l); /* Gets the symbol for the given length, cfr. the DEFLATE spec. Returns the symbol in the range [257-285] (inclusive) */ int ZopfliGetLengthSymbol(int l); /* Gets the amount of extra bits for the given length symbol. */ int ZopfliGetLengthSymbolExtraBits(int s); /* Gets the amount of extra bits for the given distance symbol. */ int ZopfliGetDistSymbolExtraBits(int s); #ifdef __cplusplus } #endif #endif /* ZOPFLI_SYMBOLS_H_ */
RabbitBio/RabbitBM
src/result.h
<reponame>RabbitBio/RabbitBM #ifndef RESULT_H #define RESULT_H #include <iostream> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <map> #include <unordered_map> //#include "robin_hood.h" #include <iomanip> #include "common.h" #include "options.h" #include "writer.h" #include "barcodeProcessor.h" #include <boost/archive/binary_oarchive.hpp> #include <boost/serialization/map.hpp> using namespace std; class Result { public: Result(Options *opt, int threadId, bool paired = true); ~Result(); Writer *getWriter() { return mWriter; } static Result *merge(vector<Result *> &list); void print(); void dumpDNBs(string &mappedDNBOutFile); void setBarcodeProcessor(unordered_map<uint64, Position1> *bpmap); // void setBarcodeProcessor(int headNum, int *hashHead, node *hashMap, uint64 *bloomFilter); void setBarcodeProcessorHashTableOneArrayWithBloomFilter(int *bpmap_head, int *bpmap_nxt, bpmap_key_value *position_all, BloomFilter *bloomFilter); private: void setBarcodeProcessor(); public: Options *mOptions; double GetCostPe() const; bool mPaired; long mTotalRead; long mFxiedFilterRead; long mDupRead; long mLowQuaRead; long mWithoutPositionReads; long overlapReadsWithMis = 0; double GetCostWait() const; double GetCostNew() const; double GetCostAll() const; long overlapReadsWithN = 0; Writer *mWriter; BarcodeProcessor *mBarcodeProcessor; int mThreadId; double GetCostFormat() const; double costWait; double costFormat; double costNew; double costPE; double costAll; }; #endif // ! RESULT_H
RabbitBio/RabbitBM
src/DataQueue.h
/* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ /* This file is modified by SDU HPC lab for RabbitQC project. Last modified: JULY2019 */ #ifndef H_DATAQUEUE #define H_DATAQUEUE #include "Globals.h" #include <queue> #ifdef USE_BOOST_THREAD #include <boost/thread.hpp> namespace th = boost; #else #include <mutex> #include <condition_variable> namespace th = std; #endif namespace dsrc { namespace core { template <class _TDataType> class TDataQueue { typedef _TDataType DataType; typedef std::queue<std::pair<int64, DataType*> > part_queue; const uint32 threadNum; const uint32 maxPartNum; uint64 completedThreadMask; uint32 partNum; uint64 currentThreadMask; part_queue parts; th::mutex mutex; th::condition_variable queueFullCondition; th::condition_variable queueEmptyCondition; public: static const uint32 DefaultMaxPartNum = 64; static const uint32 DefaultMaxThreadtNum = 64; TDataQueue(uint32 maxPartNum_ = DefaultMaxPartNum, uint32 threadNum_ = 1) : threadNum(threadNum_) , maxPartNum(maxPartNum_) , partNum(0) , currentThreadMask(0) { ASSERT(maxPartNum_ > 0); ASSERT(threadNum_ >= 1); ASSERT(threadNum_ < 64); completedThreadMask = ((uint64)1 << threadNum) - 1; } ~TDataQueue() {} bool IsEmpty() { return parts.empty(); } bool IsCompleted() { return parts.empty() && currentThreadMask == completedThreadMask; } void SetCompleted() { th::lock_guard<th::mutex> lock(mutex); ASSERT(currentThreadMask != completedThreadMask); currentThreadMask = (currentThreadMask << 1) | 1; queueEmptyCondition.notify_all(); } void Push(int64 partId_, const DataType* part_) { th::unique_lock<th::mutex> lock(mutex); while (partNum > maxPartNum) queueFullCondition.wait(lock); parts.push(std::make_pair(partId_, (DataType*)part_)); partNum++; queueEmptyCondition.notify_one(); } bool Pop(int64 &partId_, DataType* &part_) { th::unique_lock<th::mutex> lock(mutex); while ((parts.size() == 0) && currentThreadMask != completedThreadMask) queueEmptyCondition.wait(lock); if (parts.size() != 0) { partId_ = parts.front().first; part_ = parts.front().second; partNum--; parts.pop(); queueFullCondition.notify_one(); return true; } // assure this is impossible ASSERT(currentThreadMask == completedThreadMask); ASSERT(parts.size() == 0); return false; } void Reset() { ASSERT(currentThreadMask == completedThreadMask); partNum = 0; currentThreadMask = 0; } }; } // namespace core } // namespace dsrc #endif // DATA_QUEUE_H
RabbitBio/RabbitBM
src/DataStream.h
/* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ /* This file is modified by SDU HPC lab for RabbitQC project. Last modified: JULY2019 */ #ifndef H_DATASTREAM #define H_DATASTREAM #include "Globals.h" namespace dsrc { namespace core { class IDataStream { public: virtual ~IDataStream() {} virtual int64 PerformIo(uchar* mem_, uint64 size_) = 0; virtual void Close() = 0; }; class IDataStreamReader : public IDataStream { public: int64 PerformIo(uchar* mem_, uint64 size_) { return Read(mem_, size_); } virtual int64 Read(uchar* mem_, uint64 size_) = 0; }; class IDataStreamWriter : public IDataStream { public: int64 PerformIo(uchar* mem_, uint64 size_) { return Write(mem_, size_); } virtual int64 Write(const uchar* mem_, uint64 size_) = 0; }; } // namespace core } // namespace dsrc #endif // H_DATASTREAM
RabbitBio/RabbitBM
src/barcodeProcessor.h
<reponame>RabbitBio/RabbitBM #ifndef BARCODE_PROCESSOR_H #define BARCODE_PROCESSOR_H #include <stdio.h> #include <stdlib.h> #include <string> #include <sstream> #include <iostream> #include <unordered_map> #include "read.h" #include "util.h" #include "barcodePositionMap.h" #include "options.h" #include "util.h" #include "bloomFilter.h" //#include "robin_hood.h" using namespace std; class BarcodeProcessor { public: BarcodeProcessor(Options *opt, unordered_map<uint64, Position1> *mbpmap); BarcodeProcessor(Options *opt, int mhashNum, int *mhashHead, node *mhashMap); // BarcodeProcessor(Options *opt, int mhashNum, int *mhashHead, node *mhashMap, uint64 *mBloomFilter); BarcodeProcessor(Options *opt, int *mbpmap_head, int *mbpmap_nxt, bpmap_key_value *mposition_all, BloomFilter *mbloomFilter); BarcodeProcessor(); ~BarcodeProcessor(); bool process(Read *read1, Read *read2); void dumpDNBmap(string &dnbMapFile); private: void addPositionToName(Read *r, Position1 *position, pair<string, string> *umi = NULL); void addPositionToNames(Read *r1, Read *r2, Position1 *position, pair<string, string> *umi = NULL); void getUMI(Read *r, pair<string, string> &umi, bool isRead2 = false); void decodePosition(const uint32 codePos, pair<uint16, uint16> &decodePos); void decodePosition(const uint64 codePos, pair<uint32, uint32> &decodePos); uint32 encodePosition(int fovCol, int fovRow); uint64 encodePosition(uint32 x, uint32 y); long getBarcodeTypes(); int getPosition(uint64 barcodeInt); int getPosition(string &barcodeString); void misMaskGenerate(); void misMaskGenerateSegment(); string positionToString(int position); string positionToString(Position1 *position); // unordered_map<uint64, Position1>::iterator getMisOverlap(uint64 barcodeInt); pair<int, int> getMisOverlap(uint64 barcodeInt); int getNOverlap(string &barcodeString, uint8 Nindex); Position1 *getNOverlapZZ(string &barcodeString, uint8 Nindex); int getNindex(string &barcodeString); void addDNB(uint64 barcodeInt); bool barcodeStatAndFilter(pair<string, string> &barcode); bool barcodeStatAndFilter(string &barcodeQ); bool umiStatAndFilter(pair<string, string> &umi); pair<int, int> queryMap(uint64 barcodeInt); int getMisOverlapHashTableOneArrayWithBloomFiler(uint64 barcodeInt, Position1 *&result_value); Position1 *getPositionHashTableOneArrayWithBloomFiler(string &barcodeString); Position1 *getPositionHashTableOneArrayWithBloomFiler(uint64 barcodeInt); private: uint64 *misMask; int misMaskLen; int *misMaskLens; int misMaskClassificationNumber; int *misMaskClassification; uint64 *misMaskLensSegmentL; uint64 *misMaskLensSegmentR; uint64 *misMaskHash; const char q10 = '+'; const char q20 = '5'; const char q30 = '?'; string polyT = "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTT"; uint64 polyTInt; public: Options *mOptions; unordered_map<uint64, Position1> *bpmap; //***********list-hash add by ylf************// int *hashHead; node *hashMap; int hashNum; //******************************************// BloomFilter *bloomFilter; int *bpmap_head; int *bpmap_nxt; uint64 *bpmap_key; int *bpmap_value; int *bpmap_len; bpmap_key_value *position_all; long totQuery = 0; long filterQuery = 0; long queryYes = 0; long totalReads = 0;//tot reads long mMapToSlideRead = 0;//tot mapped long overlapReads = 0;//mismatch=0 mapped long overlapReadsWithMis = 0;//mismatch>0 mapped long overlapReadsWithN = 0; long barcodeQ10 = 0; long barcodeQ20 = 0; long barcodeQ30 = 0; long umiQ10 = 0; long umiQ20 = 0; long umiQ30 = 0; long umiQ10FilterReads = 0; long umiNFilterReads = 0; long umiPloyAFilterReads = 0; unordered_map<uint64, int> mDNB; int mismatch; int barcodeLen; }; #endif // ! BARCODE_PROCESSOR_H
RabbitBio/RabbitBM
src/util.h
#ifndef UTIL_H #define UTIL_H #include <stdlib.h> #include <string> #include <iostream> #include <vector> #include <sys/stat.h> #include <algorithm> #include <time.h> #include <mutex> #include "common.h" using namespace std; inline bool starts_with(string const &value, string const &starting) { if (starting.size() > value.size()) return false; return equal(starting.begin(), starting.end(), value.begin()); } inline bool ends_with(string const &value, string const &ending) { if (ending.size() > value.size()) return false; return equal(ending.rbegin(), ending.rend(), value.rbegin()); } inline string trim(const string &str) { string::size_type pos = str.find_first_not_of(' '); if (pos == string::npos) { return string(""); } string::size_type pos2 = str.find_last_not_of(' '); if (pos2 != string::npos) { return str.substr(pos, pos2 - pos + 1); } return str.substr(pos); } inline int split(const string &str, vector<string> &ret_, string sep = ",") { if (str.empty()) { return 0; } string tmp; string::size_type pos_begin = str.find_first_not_of(sep); string::size_type comma_pos = 0; while (pos_begin != string::npos) { comma_pos = str.find(sep, pos_begin); if (comma_pos != string::npos) { tmp = str.substr(pos_begin, comma_pos - pos_begin); pos_begin = comma_pos + sep.length(); } else { tmp = str.substr(pos_begin); pos_begin = comma_pos; } ret_.push_back(tmp); tmp.clear(); } return 0; } inline void error_exit(const string &msg) { cerr << "Error: " << msg << endl; exit(-1); } inline string basename(const string &filename) { string::size_type pos = filename.find_last_of('/'); if (pos == string::npos) return filename; else if (pos == filename.length() - 1) return ""; // a bad filename else return filename.substr(pos + 1, filename.length() - pos - 1); } //#define ASSERT(condition, error_message) ((condition)? 0: assertion(__FILE__, __func__, __LINE__, error_message)) inline int assertion(const string &filePath, const string &function, int line, const string &info) { //get file name string filename = basename(filePath); string err = filename + " " + function + " " + std::to_string(line) + ">> " + info; //throw exception throw std::runtime_error(err); } inline string dirname(const string &filename) { string::size_type pos = filename.find_last_of('/'); if (pos == string::npos) { return "./"; } else return filename.substr(0, pos + 1); } //Check if a string is a file or directory inline bool file_exists(const string &s) { bool exists = false; if (s.length() > 0) { struct stat status; int result = stat(s.c_str(), &status); if (result == 0) { exists = true; } } return exists; } //check if a string is a directory inline bool is_directory(const string &path) { bool isdir = false; struct stat status; // visual studion use _S_IFDIR instead of S_IFDIR // http://msdn.microsoft.com/en-us/library/14h5k7ff.aspx #ifdef _MSC_VER #define S_IFDIR _S_IFDIR #endif // _MSC_VER stat(path.c_str(), &status); if (status.st_mode & S_IFDIR) { isdir = true; } return isdir; } inline void check_file_valid(const string &s) { if (!file_exists(s)) { cerr << "ERROR: file '" << s << "' doesn't exist, quit now" << endl; exit(-1); } if (is_directory(s)) { cerr << "ERROR: '" << s << "' is a folder, not a file, quit now" << endl; exit(-1); } } inline void check_file_writable(const string &s) { string dir = dirname(s); if (!file_exists(dir)) { cerr << "ERROR: '" << dir << " doesn't exist. Create this folder and run this command again." << endl; exit(-1); } if (is_directory(s)) { cerr << "ERROR: '" << s << "' is not a writable file, quit now" << endl; exit(-1); } } inline char complement(char base) { switch (base) { case 'A': case 'a': return 'T'; case 'T': case 't': return 'A'; case 'C': case 'c': return 'G'; case 'G': case 'g': return 'C'; default: return 'N'; } } inline string reverse(const string &str) { string ret(str.length(), 0); for (int pos = 0; pos < str.length(); pos++) { ret[pos] = str[str.length() - pos - 1]; } return ret; } inline string reverseComplement(const string &str) { string rc(str.length(), 0); for (int pos = 0; pos < str.length(); pos++) { rc[pos] = complement(str[str.length() - pos - 1]); } return rc; } /* keep this 2 bits || A 65 01000|00|1 0 C 67 01000|01|1 1 G 71 01000|11|1 3 T 84 01010|10|0 2 */ inline uint64 seqEncode(const char *sequence, const int &seqStart, const int &seqLen, bool isRC = false) { uint64 n = 0; uint64 k = 0; for (int i = seqStart; i < seqLen; i++) { n = (sequence[i] & 6) >> 1; //6: ob00000110 if (isRC) { n = RC_BASE[n]; k |= (n << ((seqLen - i - 1) * 2)); } else { k |= (n << (i * 2)); } } return k; } inline string seqDecode(const uint64 &seqInt, const int &seqLen) { uint8_t tint; string seqs = ""; for (int i = 0; i < seqLen; i++) { tint = (seqInt >> (i * 2)) & 3; seqs.push_back(ATCG_BASES[tint]); } return seqs; } inline uint64 getPolyTint(const int &seqLen) { char ployT[] = "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT"; return seqEncode(ployT, 0, seqLen); } inline int possibleMis(int bl, int mismatch) { switch (mismatch) { case 1: return bl * 3; case 2: return bl * 3 + bl * (bl - 1) * 3 * 3 / 2; case 3: return bl * 3 + bl * (bl - 1) * 3 * 3 / 2 + bl * (bl - 1) * (bl - 2) * 3 * 3 * 3 / 6; default: return 0; } } extern mutex logmtx; inline void loginfo(const string s) { logmtx.lock(); time_t tt = time(NULL); tm *t = localtime(&tt); cerr << "[" << t->tm_hour << ":" << t->tm_min << ":" << t->tm_sec << "] " << s << endl; logmtx.unlock(); } #endif