repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
Yunori/Fridge-menu
controller/splash_screen.c
#include "../game.h" void reset() { my_putstr("\033[2J"); my_putstr("\e[0m"); } void show_name() { reset(); my_putstr("\e[0;31m"); my_putstr("\n\n\n .--,--.\n"); my_putstr(" `. ,.'\n"); my_putstr(" |___|\n"); my_putstr(" :o o: O Bienvenue dans l'interface Chappie\n"); my_putstr(" _`~^~'_ | Miam miam !\n"); my_putstr(" /' ^ `\\=)\n"); my_putstr(" .' _______ '~|\n"); my_putstr(" `(<=| |= /'\n"); my_putstr(" | |\n"); my_putstr(" |_____|\n"); my_putstr("~~~~~~~ ===== ~~~~~~~~\n\n\n"); } void show_enter() { char *get; my_putstr("\e[5;36m"); my_putstr(" Press enter to cook\n\n\n"); my_putstr("\e[0m"); readLine(); start_game(); } void splash_screen() { show_name(); show_enter(); }
Yunori/Fridge-menu
functions/my_strncat.c
char *my_strncat(char *str1, char *str2, int n) { char *save; for (save = str1; *str1 && str1++;); for (; n; *str1++ = *str2++, n--); *str1 = 0; return (save); }
Yunori/Fridge-menu
functions/my_strncmp.c
<gh_stars>0 int my_strncmp(char *s1, char *s2, int n) { for (; n > 0; s1++, s2++, --n) if (*s1 != *s2) return ((*s1 > *s2) ? 1 : -1); else if (*s1 == '\0') return (0); return (0); }
Yunori/Fridge-menu
functions/my_str_to_wordtab.c
<gh_stars>0 #include <unistd.h> #include <stdlib.h> #include <stdio.h> int my_len(char *str); int my_word(char c) { if (c >= 'a' && c <= 'z') return (1); if (c >= 'A' && c <= 'Z') return (1); if (c >= '0' && c <= '9') return (1); return (0); } int my_len(char *str) { int i; for (i = 0; str[i] && my_word(str[i]); i++); return (i); } int count_word(char *str) { int i; int j; for (i = 0, j = 0; str[i] != 0; i++) if (my_word(str[i])) j++; return (i + 1); } char **my_str_to_wordtab(char *str) { char **result; int i; int j; int c; if (str == NULL) return (NULL); if ((result = malloc(sizeof(*result) * (count_word(str) + 1))) == NULL) return (NULL); for (i = -1, c = 0; ++i < count_word(str);) { while (!my_word(str[c])) c++; if ((result[i] = malloc(my_len(&str[c]) + 1)) == NULL) return (NULL); j = -1; for (; my_word(str[c]) && str[c] != 0 && str[c] != '\n'; c++) result[i][++j] = str[c]; result[i][j + 1] = '\0'; } result[i] = NULL; return (result); }
Yunori/Fridge-menu
controller/cuisiner.c
#include "../game.h" void recettes(FILE *fp) { int current = fgetc(fp); while(!feof(fp)) { if(current == ';') { nbr_ingredient(fp, current); current = fgetc(fp); } my_putchar(current); current = fgetc(fp); if(current == '\n') { current = fgetc(fp); break; } } } void nbr_ingredient(FILE*fp, int current) { if(current == ';') { current = fgetc(fp); my_putstr(" \e[0;31m"); while(current != '\n' && !feof(fp)) { my_putchar(current); current = fgetc(fp); } my_putstr(" \e[0;0m"); my_putchar(current); } } void get_cuisine() { FILE *fp = fopen("./assets/recettes.txt", "r"); int current = fgetc(fp); int x; int i; i = 1; while (!feof(fp)) { init_recette(fp, current, i); i++; recettes(fp); current = fgetc(fp); } } void init_recette(FILE*fp, int current, int i) { my_putstr("\n\n\t"); my_put_nbr(i); my_putstr(") "); while (current != '\n' && !feof(fp)) { my_putchar(current); current = fgetc(fp); if(current == ';') { type_recette(fp, current); current = '\n'; } } } void type_recette(FILE*fp, int current) { current = fgetc(fp); my_putstr(" ["); while(current != '\n' && !feof(fp)) { my_putchar(current); current = fgetc(fp); } my_putstr("] "); my_putchar(current); } void cuisiner() { my_putstr("\t\t|============================|\n\t\t|"); my_putstr(" INTERFACE DE CUISINE "); my_putstr("|\n\t\t|============================|\n\n\n"); my_putstr("\tRecettes :\n\n"); get_cuisine(); read_user(); }
Yunori/Fridge-menu
functions/my_strlen.c
<reponame>Yunori/Fridge-menu int my_strlen(char *str) { return ((*str) ? 1 + my_strlen(++str) : 0); }
Yunori/Fridge-menu
controller/start.c
<filename>controller/start.c #include "../game.h" void init() { my_putstr("\e[0;31m Veuillez selectionner le type de remplissage\n"); my_putstr(" 1) Random (etape 1)\n"); my_putstr(" 2) Fichier (etape 4)\n\e[0m"); get_type(); splash_screen(); } void get_type() { char *get; get = readLine(); if(my_strcmp(get, "1") == 0 || my_strcmp(get, "2") == 0) get_ingredients(get[0]); else init(); } void read_user() { char *get; my_putstr("\n\n\e[0;31m"); my_putstr(" Bienvenue dans l'interface de Chappie\n"); my_putstr(" 1) Voir le stock\n"); my_putstr(" 2) Cuisiner\n"); my_putstr(" 3) Mettre a jour les ingredients\n"); my_putstr(" 4) Quitter\n\n"); my_putstr(" \e[0m"); my_putstr("\n\n Choisir une option : "); get = readLine(); my_putstr("\n"); do_action(get); } void do_action(char *get) { int poss[4] = {'1', '2', '3', '4'}; void (*func[4])() = {ingredients, cuisiner, update_qte, game_over}; int x; int find; find = -1; for(x=0; x<4; x++) if(get[0] == poss[x]) find = x; if(find != -1) (*func[find])(); else if(find == -1) read_user(); } void game_over() { my_putstr("\n Powered bertoc_t\n\n\n\n\n"); my_putstr("\e[0m"); exit(0); } void start_game() { read_user(); }
Yunori/Fridge-menu
functions/my_aff_tab.c
void my_putchar(char c); void my_put_nbr(int n); void my_aff_tab(int tab[], int len) { int compteur; for (compteur = 0; compteur < len; compteur++) { my_put_nbr(tab[compteur]); my_putchar('\n'); } }
Yunori/Fridge-menu
game.h
<reponame>Yunori/Fridge-menu<filename>game.h<gh_stars>0 #ifndef GAME_H_ # define GAME_H_ # include "my.h" typedef struct s_ingredients s_ingredients; struct s_ingredients { char *name; int qte; struct s_ingredients *next; }; typedef s_ingredients* t_ingredients; typedef struct s_recettes s_recettes; struct s_recettes { char *name; char *type; t_ingredients *ingredients; struct s_recettes *next; }; typedef s_recettes* t_recettes; s_ingredients *ingredient; s_recettes *recette; char *readLine(); void init(); void add_ingredient(char *name, int num, int type); int search_ingredient(char *name, int num); void show_ingredients(); void update_ingredients(char *name, char *qte); t_ingredients delete_ingredient(t_ingredients liste, char *name); void update_ingredients(); void get_ingredients(char type); void get_infos(char* line, char type); void splash_screen(); void start_game(); void cuisiner(); void update_qte(); void game_over(); void do_action(char *get); void read_user(); void ingredients(); void reset(); void get_cuisine(); void type_recette(FILE*fp, int current); void init_recette(FILE*fp, int current, int i); void nbr_ingredient(FILE*fp, int current); void get_type(); int alea(); #endif
Yunori/Fridge-menu
functions/my_strncpy.c
<reponame>Yunori/Fridge-menu /* ** my_strncpy.c for my_strncpy in /home/mages_i/piscine/C/jour_04/mages_i/my_strncpy ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Thu Oct 2 09:34:28 2014 <NAME> ** Last update Sat Oct 4 18:42:19 2014 <NAME> */ #include <stdio.h> char *my_strncpy(char *dest, char *src, int n) { int i; for (i = 0; i < n && src[i]; i++) dest[i] = src[i]; for (; i < n; i++) dest[i] = '\0'; return (dest); }
Yunori/Fridge-menu
functions/my_strcat.c
char *my_strcat(char *str1, char *str2) { char *save; for (save = str1; *str1 && str1++; ); while (*str2) { *str1 = *str2; str1++; str2++; } *str1 = 0; return (save); }
Yunori/Fridge-menu
main.c
#include "game.h" int main(int argc, char **argv) { init(argc, argv); return (0); }
Yunori/Fridge-menu
functions/my_put_nbr.c
<reponame>Yunori/Fridge-menu void my_putchar(char c); void my_putstr(char *c); void my_put_nbr(int n) { if (n == -2147483648) { my_putstr("-2147483648"); } else { if (n < 0) { n = -n; my_putchar('-'); } if (n < 10) my_putchar(n + 48); else { my_put_nbr(n / 10); my_put_nbr(n % 10); } } }
Yunori/Fridge-menu
functions/my_isneg.c
int my_isneg(int n) { return ((n < 0) ? 0 : 1); }
Yunori/Fridge-menu
functions/my_putchar.c
#include <unistd.h> void my_putchar(char c) { write(1, &c, 1); }
Yunori/Fridge-menu
functions/my_strstr.c
<gh_stars>0 #include <stdio.h> int my_strncmp(char *s1, char *s2, int n); int my_strlen(char *str); char *my_strstr(char *str, char *to_find) { char c; size_t len; c = *to_find++; if (!c) return (char *) str;// Trivial empty string case len = my_strlen(to_find); do { char sc; do { sc = *str++; if (!sc) return "null"; } while (sc != c); } while (my_strncmp(str, to_find, len) != 0); return (str - 1); /* if (!my_strlen(str)) return ("null"); for (i = 0; str[i] != '\0'; i++) if (str[i] == to_find[0]) if (my_strncmp(&str[i], to_find, my_strlen(to_find))) return (&str[i]); return ("null"); */ }
Yunori/Fridge-menu
functions/my_putnbr_base.c
void my_putchar(char c); int my_strlen(char *str); int my_putnbr_base(int nbr, char *base) { int re; int d; int len; len = my_strlen(base); if (nbr < 0) { my_putchar('-'); nbr = -1 * nbr; } for (d = 1; (nbr / d) >= len; d = d * len); for (; d > 0; re = (nbr / d) % len, my_putchar(base[re]), d = d / len); return (re); }
Yunori/Fridge-menu
controller/stock.c
<reponame>Yunori/Fridge-menu #include "../game.h" void ingredients() { show_ingredients(); read_user(); } void update_qte() { char *name, *s_qte; my_putstr(" Quel ingredient voulez vous changer/ajouter ?\n > "); name = readLine(); my_putstr(" Combien y a t'il de "); my_putstr(name); my_putstr(" dans votre frigo ?\n > "); s_qte = readLine(); update_ingredients(name, s_qte); show_ingredients(); read_user(); }
Yunori/Fridge-menu
controller/parse_ingredients.c
<filename>controller/parse_ingredients.c #include "../game.h" void get_infos(char* line, char type) { int i; int c; char *name; char *s_qte; char *convert; int num; name = NULL; s_qte = NULL; convert = NULL; for (i = 0, c = 0; i < my_strlen(line) && line[i] != ';'; i++) { name = realloc(name, c+1*sizeof(int)); name[c++] = line[i]; } for (c = 0, i++; i < my_strlen(line); i++) { s_qte = realloc(s_qte, c+1*sizeof(int)); s_qte[c++] = line[i]; } if(type == '1') num = alea(); if(type == '2') num = strtol(s_qte, &convert, 10); add_ingredient(name, num, type); } void get_ingredients(char type) { FILE *fp = fopen("./assets/ingredients.txt", "r"); char line[1024]; time_t t; srand((unsigned) time(&t)); while (fgets(line, 1024, fp)) { get_infos(line, type); } }
Yunori/Fridge-menu
functions/my_putstr.c
void my_putchar(char c); void my_putstr(char *str) { int i; for (i = 0; str[i] != '\0'; i++) my_putchar(str[i]); }
Yunori/Fridge-menu
controller/ingredients.c
#include "../game.h" void add_ingredient(char *name, int num, int type) { long qte; s_ingredients* new = malloc(sizeof(s_ingredients)); int z; z = -1; if(type == '2') z = search_ingredient(name, num); if(z != -1) num = num + z; ingredient = delete_ingredient(ingredient, name); new->name = name; new->qte = num; new->next = ingredient; ingredient = new; } int search_ingredient(char *name, int num) { s_ingredients *tmp = ingredient; int nbr; nbr = -1; while(tmp != NULL) { if(my_strcmp(tmp->name, name) == 0) { nbr = tmp->qte; tmp->qte = nbr + num; } tmp = tmp->next; } return nbr; } void show_ingredients() { s_ingredients *tmp = ingredient; my_putstr("\n\n\t\t\t====Ingrédients ====\n\n"); while(tmp != NULL) { my_putstr("\t"); my_putstr(tmp->name); my_putstr(" \t\t "); my_put_nbr(tmp->qte); my_putstr("\n"); tmp = tmp->next; } my_putstr("\n\n\n\n"); } void update_ingredients(char *name, char *qte) { int num; char *convert; ingredient = delete_ingredient(ingredient, name); num = strtol(qte, &convert, 10); add_ingredient(name, num, 1); } t_ingredients delete_ingredient(t_ingredients liste, char *name) { if(liste == NULL) return (NULL); if(my_strcmp(liste->name, name) == 0) { s_ingredients *tmp = liste->next; free(liste); tmp = delete_ingredient(tmp, name); return (tmp); } else { liste->next = delete_ingredient(liste->next, name); return (liste); } }
Yunori/Fridge-menu
functions/my_getnbr.c
<filename>functions/my_getnbr.c<gh_stars>0 int my_getnbr(char *str) { int neg; int result; for (neg = 1; *str < '0' || *str > '9'; str++) neg = (*str == '-') ? -1 : 1; for (result = 0; *str >= '0' && *str <= '9'; ++str) result = (result * 10) + (*str - '0'); return (result * neg); }
Farhad-00009/SMS
school billing system.c
//LEARNPROGRAMO-PROGRAMMING MADE SIMPLE #include<stdio.h> #include<string.h> #include<stdlib.h> #include<conio.h> #include<windows.h> struct dat//for date(month and day { int d,m;//d=day,m=month }; int clscanf();//check class (1-12) struct student { struct dat dt; float f,fine,tot,adv,due;//f=fee char n[50]; int r,c;//roll and class } stud,s; struct teacher { struct dat dt; char n[50]; float sal,adv,tot; int id,no; } tech,t; int chkdat(int,int);// for checking date void addrec(int);//for adding records void modrec(int);//for modifying records void searchrec(int);//for searching records void delrec(int);//for deleting records void salary(int);//for the calculation of salary of teacher and staff FILE *fs,*ft;//file declaration int mm,dd;//mm=month, dd=day void ext();//for exiting void main(void) { int i,j,k; for(i=0; i<80; i++) { printf("\xdb"); } printf("\n"); for(i=0; i<80; i++) { printf("\xdb"); } system("color 9a"); printf(" \t_______________________________________________________\n"); printf("\t| |\n"); printf("\t|**WELCOME TO C PROGRAM SCHOOL BILLING SYSTEM PROJECT|**\n"); printf("\n\t| |\n"); printf("\t ______________________________________________________\n"); printf("\t| DEVELOPED BY LEARNPROGRAMO |\n"); printf(" \t________________________________________________________\n"); printf("\t| ***************************************** |\n"); printf("\t| ***************************************** |\n"); printf(" \t_______________________________________________________\n"); printf("\n\tPLEASE ENTER ANY KEY TO CONTINUE"); for(i=0; i<5; i++) { printf("."); Sleep(500);//after printing one . another comes after 0.5 seconds } getch(); system("cls");//clears the screen printf("\n"); for(i=0; i<80; i++) { printf("\xdb"); } system("color 6b"); printf("\n\n\t** WELCOME TO C PROGRAM SCHOOL BILLING SYSTEM PROJECT **\n\n\n"); for(i=0; i<80; i++) { printf("\xdb"); } printf("\nPLEASE ENTER ANY KEY TO START\n"); for(i=0; i<5; i++) { printf("."); Sleep(500); } fflush(stdin); getch(); system("cls"); system("color 0f");//1st is for back ground color and second is for text color printf("\n\t\tPLEASE ENTER CURRENT DATE\nmm dd\n "); scanf("%d%d",&mm,&dd); mm=chkdat(mm,dd); start(); } void start() { int i,j;//j is for selection of account type system("cls"); printf("\n\t\tPLEASE ENTER ACCOUNT TYPE"); printf("\n\t\t1:: Student"); printf("\n\t\t2:: Teachers and Staffs"); printf("\n\t\t3:: Exit"); printf("\n\t\tAccount type choice "); fflush(stdin); scanf("%d",&j); switch (j) { case 3: ext(); case 1: { system("cls"); printf("\n\t\tPLEASE ENTER THE CHOICE"); printf("\n\t\t1:: Add record"); printf("\n\t\t2:: Search record"); printf("\n\t\t3:: Modify record"); printf("\n\t\t4:: Delete record"); printf("\n\t\t5:: Calculate fee"); printf("\n\t\t6:: Exit"); printf("\n\n Enter choice "); fflush(stdin); scanf("%d",&i); switch (i) { case 1: addrec(j);//function call start();//function call case 2: searchrec(j); start(); case 3: modrec(j); start(); case 4: delrec(j); start(); case 5: fee(mm); start(); case 6: ext(); default : { printf("\n\n\tInvalid entry!!"); printf("\n\nTo Account Type\n\n\t"); system("pause"); start(); } } } case 2: { system("cls"); printf("\n\t\tPLEASE ENTER THE CHOICE"); printf("\n\t\t1:: Add record"); printf("\n\t\t2:: Search record"); printf("\n\t\t3:: Modify record"); printf("\n\t\t4:: Delete record"); printf("\n\t\t5:: Calculate Salary"); printf("\n\t\t6:: Exit"); printf("\n\n Enter choice "); fflush(stdin); scanf("%d",&i); switch (i) { case 1: addrec(j); start(); case 2: searchrec(j); start(); case 3: modrec(j); start(); case 4: delrec(j); case 5: salary(mm); start(); case 6: ext(); default : { printf("\n\n\tInvalid entry!!"); printf("\n\nTo Account Type\n\n\t"); system("pause"); start(); } } } default : { printf("\n\n\tInvalid entry!!"); printf("\n\nTo Account Type\n\n\t"); system("pause"); start(); } } } void addrec(int j) { int dif,cdat,ddat,month=0;//cdat=month till which fee is cleared float ff;//used in calculatin of fee of different class char c='y'; system("cls"); printf("\n\t******************************************************************"); printf("\n\t *************************** "); printf("\n\t********************* ADD RECORD *******************"); printf("\n\t *************************** "); printf("\n\t******************************************************************"); if (j==1) { while(c=='y'||c=='Y') { int a=1; printf("\n\nEnter the name of student: "); fflush(stdin); scanf("%[^\n]",stud.n); printf("\nEnter the class: "); fflush(stdin); stud.c=clscanf(); printf("\nEnter the Roll No.:"); fflush(stdin); scanf("%2d",&stud.r); printf("\nEnter month and day till which fee is paid:"); fflush(stdin); scanf("%2d%2d",&cdat,&ddat); cdat=chkdat(cdat,ddat); stud.dt.m=cdat; ff=stud.c/10.0; stud.f=1000*(1+ff);//fee of different classes dif=mm-stud.dt.m;//months of fee left to be paid stud.fine=(dif*stud.f)*1/100; stud.due=(dif)*stud.f;//fees left to be paid if(dif==1) { stud.tot=stud.f; stud.fine=0; } else { stud.tot=stud.fine+stud.due; }//for calculation of total fee fs=fopen("student","ab+");//opening a binary file in apend mode fwrite(&stud,sizeof(stud),1,fs); fclose(fs); printf("\n\nDo you want to continue with the process(press y or Y"); fflush(stdin); c=getch(); } getch(); } if (j==2) { while(c=='y'||c=='Y') { int a=1; printf("\n\nEnter name of teacher/staff:" ); fflush(stdin); scanf("%[^\n]",tech.n); printf("\nEnter teacher/staff id: "); fflush(stdin); scanf("%d",&tech.id); printf("\nEnter number of class/shift per month:: "); scanf("%d",&tech.no); fflush(stdin); printf("\nEnter month and day till which salary is paid::"); scanf("%d %d",&tech.dt.m,&tech.dt.d); cdat=chkdat(cdat,ddat); tech.dt.m=cdat; tech.sal=tech.no*500; tech.adv=(tech.dt.m-mm-1)*tech.sal; if (tech.adv<0) tech.adv=0; tech.tot=tech.sal; ft=fopen("teacher","ab+"); fwrite(&tech,sizeof(tech),1,ft); fclose(ft); printf("\n\nDo you want to continue with the process(press y or Y"); fflush(stdin); c=getch(); } fflush(stdin); printf("\n\n"); system("pause"); } } void searchrec(int j) { char name[50],namet[50]; int a=1,choice; char c='y'; if (j==1) { while(c=='y'||c=='Y') { int a=1; system("cls"); printf("\n\t******************************************************************"); printf("\n\t *************************** "); printf("\n\t********************* SEARCH RECORD *******************"); printf("\n\t *************************** "); printf("\n\t******************************************************************"); printf("\n\n\t\tPLEASE CHOOSE SEARCH TYPE::"); printf("\n\n\t\t1::Search by name::"); printf("\n\n\t\t2::Search by class::"); printf("\n\n\t\t3::Search by rollno::"); printf("\n\n\t\t4::Exit"); printf("\n\n\t\t::Enter your choice:: "); fflush(stdin); scanf("%d",&choice); if (choice==1) { a=1; printf("\n\nEnter name of student to search: "); fflush(stdin); scanf("%[^\n]",name); fs=fopen("student","rb"); while(fread(&stud,sizeof(stud),1,fs)==1) { if (strcmpi(name,stud.n)==0) { a=0; printf("\nname = %s",stud.n); printf("\nclass = %d",stud.c); printf("\nroll no = %d",stud.r); printf("\nmonthy fee =%.2f",stud.f); printf("\nlast fee paid in month =%2d",stud.dt.m); printf("\n due=%.2f",stud.due); printf("\n fine=%.2f",stud.fine); printf("\n total=%.2f\n\n",stud.tot); } } if (a==1) printf("\n\nRECORD NOT FOUND"); printf("\n\n"); system("pause"); fflush(stdin); fclose(fs); } else if (choice==2) { int cl; a=1; printf("\n\nEnter class of student to search: "); fflush(stdin); cl=clscanf(); fs=fopen("student","rb"); while(fread(&stud,sizeof(stud),1,fs)==1) { if (stud.c==cl) { a=0; printf("\nname = %s",stud.n); printf("\nclass = %d",stud.c); printf("\nroll no = %d",stud.r); printf("\nmonthy fee =%.2f",stud.f); printf("\nlast fee paid in month =%2d",stud.dt.m); printf("\n due=%.2f",stud.due); printf("\n fine=%.2f",stud.fine); printf("\n total=%.2f",stud.tot); } } if (a==1) printf("\n\nRECORD NOT FOUND"); printf("\n\n"); system("pause"); fflush(stdin); fclose(fs); } else if (choice==3) { int rll; a=1; printf("\n\nEnter roll of student to search: "); fflush(stdin); rll=clscanf(); fs=fopen("student","rb"); while(fread(&stud,sizeof(stud),1,fs)==1) { if (strcmpi(name,stud.n)==0) { a=0; printf("\nname = %s",stud.n); printf("\nclass = %d",stud.c); printf("\nroll no = %d",stud.r); printf("\nmonthy fee =%.2f",stud.f); printf("\nlast fee paid in month =%2d",stud.dt.m); printf("\n due=%.2f",stud.due); printf("\n fine=%.2f",stud.fine); printf("\n total=%.2f",stud.tot); } } if (a==1) printf("\n\nRECORD NOT FOUND"); printf("\n\n"); system("pause"); fflush(stdin); fclose(fs); } else if(choice==4) { ext(); } else { printf("\n\n\n\t\tINVALID ENTRY!!!!\n\n\t\t"); system("pause"); searchrec(1); } printf("\n\nDo you want to continue with the process(press y or Y"); fflush(stdin); c=getch(); } getch(); } if (j==2) { while(c=='y'||c=='Y') { int a=1; printf("\n\nname of teacher/staff to search: "); fflush(stdin); scanf("%[^\n]",namet); ft=fopen("teacher","rb"); while(fread(&tech,sizeof(tech),1,ft)==1) { if (strcmp(namet,tech.n)==0) { a=0; printf("\nname = %s",tech.n); printf("\nteacher/staff id = %d",tech.id); printf("\nmonth till when salary is paid =%d",tech.dt.m); printf("\nmonthy salary = %.2f",tech.sal); printf("\nadvance paid = %.2f",tech.adv); } } if (a==1) printf("\n\nRECORD NOT FOUND"); printf("\n\n"); system("pause"); fflush(stdin); fclose(ft); printf("\n\nDo you want to continue with the process(press y or Y"); fflush(stdin); c=getch(); } getch(); } } void modrec(int j) { char name[50]; int a=1,choice,cl,rolno; char c='y'; if (j==1) { while(c=='y'||c=='Y') { system("cls"); printf("\n\t******************************************************************"); printf("\n\t *************************** "); printf("\n\t********************* MODIFY RECORD *******************"); printf("\n\t *************************** "); printf("\n\t******************************************************************"); printf("\n\n\t\tPLEASE CHOOSE MODIFY TYPE::"); printf("\n\n\t\t1::Modify by name::"); printf("\n\n\t\t2::Modify by name &class::"); printf("\n\n\t\t3::Modify by name,class & rollno::"); printf("\n\n\t\t4::Exit"); printf("\n\n\t\t::Enter your choice:: "); fflush(stdin); scanf("%d",&choice); if (choice==1) { int a=0; printf("\n\nenter name of student to modify: "); fflush(stdin); scanf("%[^\n]",name); fs=fopen("student","rb+"); while(fread(&stud,sizeof(stud),1,fs)==1) { a=1; if (strcmpi(name,stud.n)==0) { a=0; printf("\nenter new name of student: "); fflush(stdin); scanf("%[^\n]",stud.n); printf("\nenter new class of student: "); fflush(stdin); stud.c=clscanf(); printf("\nenter new roll of student: "); fflush(stdin); scanf("%d",&stud.r); fseek(fs,-sizeof(stud),SEEK_CUR); fwrite(&stud,sizeof(stud),1,fs); fclose(fs); } } if (a==1) printf("\n\nRECORDS NOT FOUND"); else printf("\n\nRECORDS SUCCESSFULLY MODIFIED"); printf("\n\n"); system("pause"); } else if (choice==2) { int a=0; printf("\n\nenter name of student to modify: "); fflush(stdin); scanf("%[^\n]",name); printf("\n\nenter class of student to modify: "); fflush(stdin); cl=clscanf(); fs=fopen("student","rb+"); while(fread(&stud,sizeof(stud),1,fs)==1) { a=1; if (strcmpi(name,stud.n)==0 && cl==stud.c) { a=0; printf("\nenter new name of student: "); fflush(stdin); scanf("%[^\n]",stud.n); printf("\nenter new class of student: "); fflush(stdin); stud.c=clscanf(); printf("\nenter new roll of student: "); fflush(stdin); scanf("%d",&stud.r); fseek(fs,-sizeof(stud),SEEK_CUR); fwrite(&stud,sizeof(stud),1,fs); fclose(fs); } } if (a==1) printf("\n\nRECORDS NOT FOUND"); else printf("\n\nRECORDS SUCCESSFULLY MODIFIED"); printf("\n\n"); system("pause"); } else if (choice==3) { int a=0; printf("\n\nenter name of student to modify: "); fflush(stdin); scanf("%[^\n]",name); printf("\n\nenter class of student to modify: "); fflush(stdin); cl=clscanf(); printf("\n\nenter roll of student to modify: "); fflush(stdin); scanf("%d",&rolno); fs=fopen("student","rb+"); while(fread(&stud,sizeof(stud),1,fs)==1) { a=1; if (strcmpi(name,stud.n)==0 && cl==stud.c &&rolno==stud.r) { a=0; printf("\nenter new name of student: "); fflush(stdin); scanf("%[^\n]",stud.n); printf("\nenter new class of student: "); fflush(stdin); stud.c=clscanf(); printf("\nenter new roll of student: "); fflush(stdin); scanf("%d",&stud.r); fseek(fs,-sizeof(stud),SEEK_CUR); fwrite(&stud,sizeof(stud),1,fs); fclose(fs); } } if (a==1) printf("\n\nRECORDS NOT FOUND"); else printf("\n\nRECORDS SUCCESSFULLY MODIFIED"); printf("\n\n"); system("pause"); } else if (choice==4) ext(); else { printf("\n\n\n\t\tINVALID ENTRY!!!!\n\n\t\t"); system("pause"); modrec(1); } printf("\n\nDo you want to continue with the process(press y or Y"); fflush(stdin); c=getch(); } getch(); } if (j==2) { while(c=='y'||c=='Y') { int a=1; printf("enter name of teacher to modify: "); fflush(stdin); scanf("%[^\n]",name); ft=fopen("teacher","rb+"); while(fread(&tech,sizeof(tech),1,ft)==1) { if (strcmpi(name,tech.n)==0) { a=0; printf("\nenter new name of teacher: "); fflush(stdin); scanf("%[^\n]",tech.n); printf("\nenter new id of teacher: "); fflush(stdin); scanf("%d",&tech.id); fseek(ft,-sizeof(tech),SEEK_CUR); fwrite(&tech,sizeof(tech),1,ft); fclose(ft); } } if (a==1) printf("\n\nRECORD NOT FOUND"); else printf("\n\nRECORD SUCCESSFULLY MODIFIED"); printf("\n\n"); system("pause"); fflush(stdin); printf("\n\nDo you want to continue with the process(press y or Y"); fflush(stdin); c=getch(); } getch(); } } void delrec(int j) { system("cls"); printf("\n\t******************************************************************"); printf("\n\t *************************** "); printf("\n\t********************* DELETE RECORD *******************"); printf("\n\t *************************** "); printf("\n\t******************************************************************"); FILE *temp,*t1; int a=1; char name[50],c='y'; if (j==1) { while(c=='y'||c=='Y') { int a=1; printf("\n\nenter name of student to delete: "); fflush(stdin); scanf("%[^\n]",name); fs=fopen("student","rb"); temp=fopen("tempfile","wb");//opening of temporary file for deleting process while (fread(&stud,sizeof(stud),1,fs)==1) { if (strcmp(stud.n,name)==0) { a=0; continue; } else { fwrite(&stud,sizeof(stud),1,temp); } } if (a==1) printf("\n\nRECORD NOT FOUND"); else printf("\n\nRECORD SUCCESSFULLY DELETED"); printf("\n\n"); system("pause"); fflush(stdin); fclose(fs); fclose(temp); system("del student");/*all data except the data to be deleted in student were 1st moved to temp and data in student was deleted*/ system("ren tempfile, student");//renaming temp to student printf("\n\nDo you want to continue with the process(press y or Y"); fflush(stdin); c=getch(); } getch(); } if (j==2) { a=1; char namet[50]; while(c=='y'||c=='Y') { printf("\n\nEnter name of teacher to delete record: "); fflush(stdin); scanf("%[^\n]",namet); ft=fopen("teacher","rb"); t1=fopen("tempfile1","wb"); while (fread(&tech,sizeof(tech),1,ft)==1) { if (strcmp(tech.n,namet)==0) { a=0; continue; } else { fwrite(&tech,sizeof(tech),1,t1); } } if (a==1) printf("\n\nRECORD NOT FOUND"); else printf("\n\nRECORD SUCCESSFULLY DELETED"); printf("\n\n"); system("pause"); fflush(stdin); fclose(ft); fclose(t1); system("del teacher"); system("ren tempfile1, teacher"); printf("\n\nDo you want to continue with the process(press y or Y"); fflush(stdin); c=getch(); } getch(); } } void salary(int mm) { system("cls"); printf("\n\t******************************************************************"); printf("\n\t *************************** "); printf("\n\t********************* SALARY *******************"); printf("\n\t *************************** "); printf("\n\t******************************************************************"); FILE *f,*t; int a=1,day; char name[50],c='y'; int month,dif,id; while(c=='y'||c=='Y') { int a=1; fflush(stdin); printf("\n\nEnter name:: "); scanf("%[^\n]",name); printf("\n\nEnter ID:: "); scanf("%d",&id); f=fopen("teacher","rb+"); t=fopen("te","wb+"); while(fread(&tech,sizeof(tech),1,f)==1)//file opened { if(strcmp(tech.n,name)==0 )//name entered is compared to the existing name in file { float lsal; a=0; printf("\n\nEnter the month till which salary is to be paid:: "); fflush(stdin); scanf("%d",&month); month=chkdat(month,day); tech.adv=(month-mm-1)*tech.sal; if (tech.adv<0) tech.adv=0; lsal=mm-tech.dt.m;//months of salary left to be paid if(lsal<0) lsal=0; tech.tot=tech.adv+tech.sal*(1+lsal); if(month==tech.dt.m) tech.tot=0; printf("\nmonthy salary left to be paid:: %.2f",lsal); printf("\ntotal :: %.2f",tech.tot); printf("\nadvance :: %.2f",tech.adv); tech.dt.m=month; fwrite(&tech,sizeof(tech),1,t); fclose(f); fclose(t); if (a==1) printf("\n\nRECORD NOT FOUND"); printf("\n\n"); system("pause"); fflush(stdin); system("del teacher"); system("ren te, teacher"); } } printf("\n\nDo you want to continue with the process(press y or Y"); fflush(stdin); c=getch(); } getch(); } void fee(int mm) { system("cls"); printf("\n\t******************************************************************"); printf("\n\t *************************** "); printf("\n\t********************* FEE *******************"); printf("\n\t *************************** "); printf("\n\t******************************************************************"); FILE *f,*t; int a=0; char name[50],c='y'; int clas, roll,month,dif; while(c=='y'||c=='Y') { int a=1,day=0; fflush(stdin); printf("\n\nEnter name:: "); scanf("%[^\n]",name); printf("\n\nEnter class:: "); fflush(stdin); clas=clscanf(); printf("\n\nEnter roll:: "); fflush(stdin); scanf("%d",&roll); f=fopen("student","rb+"); t=fopen("te","wb"); while(fread(&stud,sizeof(stud),1,f)==1) { if(strcmp(stud.n,name)==0 && clas==stud.c && roll==stud.r) { a=0; printf("\n\nEnter the month till which fee to be paid:: "); fflush(stdin); scanf("%d",&month); month=chkdat(month,day); dif=mm-stud.dt.m; stud.fine=(dif*stud.f)*0.01; stud.due=(dif)*stud.f; if (stud.fine<0) stud.fine=0; if (stud.due<0) stud.due=0; if (stud.tot<0) stud.tot=0; stud.tot=stud.fine+stud.due+stud.adv; printf("\nfine :: %.2f",stud.fine); printf("\ndue :: %.2f",stud.due); printf("\ntotal :: %.2f",stud.tot); printf("\nadvance :: %.2f",stud.adv); stud.dt.m=month; stud.tot=0; stud.fine=0; stud.due=0; fwrite(&stud,sizeof(stud),1,t); } } if (a==1) printf("\n\nRECORD NOT FOUND"); printf("\n\n"); system("pause"); fflush(stdin); fclose(f); fclose(t); system("del student"); system("ren te, student"); printf("\n\nDo you want to continue with the process(press y or Y"); fflush(stdin); c=getch(); } getch(); } void ext() { int i; system("color 0c"); printf("\n\n\t\t Thank you for using C Program School Billing System Project\n\n"); system("pause"); system("cls"); printf("\n\n\t\t\t Exiting\n\n"); for(i=1; i<=80; i++) { Sleep(50); printf("*"); } exit(0); } int chkdat(int mnt,int dnt) { int mon,day; if (mnt>12 || mnt<1 || dnt<1 || dnt>32) { MessageBox(0,"Invalid Date!\nEnter Again","Error!",0); fflush(stdin); scanf("%d%d",&mon,&day); mon=chkdat(mon,day); } else return (mnt); } int clscanf() { int mnt,mon; fflush(stdin); scanf("%d",&mnt); if (mnt>12 ||mnt<1) { MessageBox(0,"Invalid Class!\nEnter Class","Error!!",0); fflush(stdin); mon=clscanf(); } else return mnt; }
BMSTU-IU8-15/algorithmic-languages-project-2
util/cli_util.h
<reponame>BMSTU-IU8-15/algorithmic-languages-project-2 #pragma once #include <iostream> using std::cout; using std::endl; namespace cli { void clear(); void print_logo(); void print_win_message(); void print_loose_message(); void print_player1_win_message(); void print_player2_win_message(); }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/game_configuration.h
<filename>battleships/game_configuration.h<gh_stars>0 #pragma once #include <cstddef> #include <map> using std::map; namespace battleships { /** * @brief Configuration of a game */ struct GameConfiguration { /** * @brief Width of the field */ size_t field_width; /** * @brief Height of the field */ size_t field_height; /** * @brief Maximal length of the ship */ size_t max_ship_length; /** * @brief Counts of ships by their length */ map<size_t, size_t> ships; GameConfiguration() : field_width(0), field_height(0), max_ship_length(0) {} GameConfiguration(const size_t &field_width, const size_t &field_height, const size_t &max_ship_length) : field_width(field_width), field_height(field_height), max_ship_length(max_ship_length) {} [[nodiscard]] size_t ship_cell_count() const { size_t ship_cell_count = 0; for (const auto &ship_count : ships) ship_cell_count += ship_count.first * ship_count.second; return ship_cell_count; } bool are_ships_valid() { size_t max_ship_coverage = 0; for (const auto entry : ships) max_ship_coverage += entry.second * (6 + entry.first * 2); return max_ship_coverage <= field_width * field_height; } }; }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/container_util.h
<filename>battleships/container_util.h #pragma once #include <algorithm> #include <random> #include <set> #include <stdexcept> using std::find; using std::set; using std::advance; namespace common_util { template<typename T> inline bool contains(const set<T> &container, const T &value) { return find(container.begin(), container.end(), value) != container.end(); } template<typename T> inline bool not_contains(const set<T> &container, const T &value) { return find(container.begin(), container.end(), value) == container.end(); } template<typename T> inline T get_random(set<T> &container, random_device &random) { if (container.empty()) throw out_of_range("Container is empty"); const auto index = uniform_int_distribution<size_t>(0, container.size() - 1)(random); auto iterator = container.begin(); advance(iterator, index); return *iterator; } }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/simple_game_field.h
<reponame>BMSTU-IU8-15/algorithmic-languages-project-2<filename>battleships/simple_game_field.h #pragma once #include <string> #include "game_field.h" #include "game_configuration.h" #include "coordinate.h" #include "game_field_cell.h" using std::string; using std::to_string; namespace battleships { class SimpleGameField : public GameField { protected: const GameConfiguration configuration_; GameFieldCell ***cells_; size_t ship_cells_alive_ = 0; inline void check_bounds(const Coordinate &coordinate) const noexcept(false) { if (is_out_of_bounds(coordinate)) throw out_of_range( "Coordinate (" + to_string(coordinate.x) + ":" + to_string(coordinate.y) + ") is out of its range" ); } [[nodiscard]] inline GameFieldCell *get_cell_at(const Coordinate &coordinate) const { return cells_[coordinate.x][coordinate.y]; } inline void set_cell_at(const Coordinate &coordinate, GameFieldCell *const value) { auto &cell = cells_[coordinate.x][coordinate.y]; delete cell; cell = value; } inline void try_make_discovered(const Coordinate &coordinate); inline void surround_destroyed_ship_cell(const Coordinate &coordinate); /** * @brief Attempts to destroy the ship by attacking the given point. * @param coordinate coordinate of the point attacked * @return {@code true} if the ship was fully destroyed by the attack and {@code false} otherwise */ inline bool attempt_destroy_ship(const Coordinate &coordinate); public: /* * Construction and deconstruction */ explicit SimpleGameField(const GameConfiguration &configuration); ~SimpleGameField() override; /* * Data access */ [[nodiscard]] GameConfiguration get_configuration() const noexcept override; /* * Game logic */ [[nodiscard]] bool is_discovered(const Coordinate &coordinate) const override; [[nodiscard]] bool can_be_attacked(const Coordinate &coordinate) const override; [[nodiscard]] bool can_place_near(const Coordinate &coordinate) const override; bool try_emplace_ship(const Coordinate &base_coordinate, const Direction &direction, const size_t &size) override; AttackStatus attack(const Coordinate &coordinate) override; /* * Misc */ void print_to_console() const noexcept override; [[nodiscard]] char get_public_icon_at(const Coordinate &coordinate) const override; [[nodiscard]] inline bool is_in_bounds(const Coordinate &coordinate) const noexcept override { return (0 <= coordinate.x && coordinate.x < configuration_.field_width) && (0 <= coordinate.y && coordinate.y < configuration_.field_height); } [[nodiscard]] inline bool is_out_of_bounds(const Coordinate &coordinate) const noexcept override { return (coordinate.x < 0 || configuration_.field_width <= coordinate.x) || (coordinate.y < 0 || configuration_.field_height <= coordinate.y); } void reset() noexcept override; [[nodiscard]] bool can_place_at(const Coordinate &coordinate) const override; void locate_not_visited_spot(Coordinate &coordinate, Direction direction, const bool &clockwise) const override; }; }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/game.h
#pragma once #include "game_field.h" namespace battleships { class Game : public ConsolePrintable { public: virtual ~Game() = default; [[nodiscard]] virtual GameConfiguration configuration() = 0; [[nodiscard]] virtual GameField *field_1() = 0; [[nodiscard]] virtual GameField *field_2() = 0; }; }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/game_field_cell.h
<reponame>BMSTU-IU8-15/algorithmic-languages-project-2<filename>battleships/game_field_cell.h #pragma once #include <set> #include <cstddef> #include <cstdint> #include <utility> #include "direction.h" #include "ship_position.h" using std::set; namespace battleships { class GameFieldCell { public: virtual ~GameFieldCell() noexcept = default; /** * @brief Checks if this cell has been discovered. * * @return {@code true} if this cell has been discovered and {@code false} otherwise */ [[nodiscard]] virtual bool is_discovered() const noexcept = 0; [[nodiscard]] virtual bool is_empty() const noexcept = 0; virtual void discover() = 0; [[nodiscard]] virtual char public_icon() const noexcept = 0; [[nodiscard]] virtual char private_icon() const noexcept = 0; }; class AbstractGameFieldCell : public GameFieldCell { protected: bool discovered_ = false; public: [[nodiscard]] bool is_discovered() const noexcept override { return discovered_; } void discover() override { discovered_ = true; } [[nodiscard]] char public_icon() const noexcept override { return discovered_ ? private_icon() : '.'; } }; class EmptyGameFieldCell final : public AbstractGameFieldCell { public: [[nodiscard]] bool is_empty() const noexcept override { return true; } [[nodiscard]] char private_icon() const noexcept override { return '~'; } }; class ShipGameFieldCell final : public AbstractGameFieldCell { protected: const size_t ship_size_ = 1; const ShipPosition position_ = NONE; public: explicit ShipGameFieldCell(const size_t &ship_size, const ShipPosition &position) : ship_size_(ship_size), position_(position) {} [[nodiscard]] bool is_empty() const noexcept override { return false; } [[nodiscard]] size_t get_ship_size() const { return ship_size_; } [[nodiscard]] ShipPosition get_position() const { return position_; } [[nodiscard]] char private_icon() const noexcept override { return '#'; } }; }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/rival_bot.h
<reponame>BMSTU-IU8-15/algorithmic-languages-project-2 #pragma once #include "game_field.h" namespace battleships { /** * @brief Bot responsible for playing against the player */ class RivalBot { public: /** * @brief Callback notified on attacks performed by the bot */ class AttackCallback { public: virtual void on_attack(const Coordinate &coordinate, const GameField::AttackStatus &attack_status) = 0; }; /** * @brief Attack callback doing nothing */ class EmptyAttackCallback : public AttackCallback { public: [[nodiscard]] static AttackCallback *empty() { /** * @brief Singleton instance of this empty attack callback */ static EmptyAttackCallback INSTANCE; return &INSTANCE; } [[nodiscard]] static AttackCallback *or_empty(AttackCallback *const attack_callback) { return attack_callback ? attack_callback : empty(); } void on_attack(const Coordinate &coordinate, const GameField::AttackStatus &attack_status) override {}; }; virtual void place_ships() = 0; virtual bool act(AttackCallback *attack_callback) = 0; }; }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/game_field.h
<reponame>BMSTU-IU8-15/algorithmic-languages-project-2<filename>battleships/game_field.h #pragma once #include "console_printable.h" #include "coordinate.h" #include "game_configuration.h" #include <stdexcept> using std::out_of_range; using std::runtime_error; namespace battleships { class GameField : public ConsolePrintable { public: enum AttackStatus { EMPTY_ALREADY_ATTACKED, SHIP_ALREADY_ATTACKED, MISS, DAMAGE_SHIP, DESTROY_SHIP, WIN }; virtual ~GameField() = default; [[nodiscard]] virtual GameConfiguration get_configuration() const noexcept = 0; [[nodiscard]] virtual bool is_discovered(const Coordinate &coordinate) const = 0; [[nodiscard]] virtual bool can_be_attacked(const Coordinate &coordinate) const = 0; [[nodiscard]] virtual bool can_place_near(const Coordinate &coordinate) const = 0; virtual bool try_emplace_ship(const Coordinate &coordinate, const Direction &direction, const size_t &size) = 0; virtual AttackStatus attack(const Coordinate &coordinate) noexcept(false) = 0; [[nodiscard]] virtual char get_public_icon_at(const Coordinate &coordinate) const = 0; [[nodiscard]] virtual bool is_in_bounds(const Coordinate &coordinate) const noexcept = 0; [[nodiscard]] virtual bool is_out_of_bounds(const Coordinate &coordinate) const noexcept = 0; virtual void reset() noexcept = 0; [[nodiscard]] virtual bool can_place_at(const Coordinate &coordinate) const = 0; virtual void locate_not_visited_spot(Coordinate &start, Direction direction, const bool &clockwise) const = 0; }; }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/console_printable.h
#pragma once #include <iostream> using std::cout; using std::endl; namespace battleships { class ConsolePrintable { public: virtual void print_to_console() const noexcept = 0; }; }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/simple_rival_bot.h
#pragma once #include <random> #include <set> #include <optional> #include "rival_bot.h" #include "direction.h" #include "ship_position.h" using std::default_random_engine; using std::random_device; using std::bernoulli_distribution; using std::uniform_int_distribution; using std::optional; using std::set; namespace battleships { class SimpleRivalBot : RivalBot { protected: // Uninitialized members GameField *const own_field_, *const rival_field_; // Initialized members optional<Coordinate> attacked_ship_coordinate_; ShipPosition ship_direction_ = NONE; random_device random_; /* non-const */ bernoulli_distribution free_spot_lookup_side_random_distribution_; /* non-const */ uniform_int_distribution<size_t> own_x_random_distribution_, own_y_random_distribution_, rival_x_random_distribution_, rival_y_random_distribution_; /* non-const */ uniform_int_distribution<int8_t> direction_random_distribution_; inline Coordinate random_own_coordinate() { return Coordinate(own_x_random_distribution_(random_), own_y_random_distribution_(random_)); } inline Coordinate random_rival_coordinate() { return Coordinate(rival_x_random_distribution_(random_), rival_y_random_distribution_(random_)); } inline void locate_not_visited_spot(/* mut */ Coordinate &coordinate, const GameField *const game_field) { game_field->locate_not_visited_spot( coordinate, random_direction(random_), free_spot_lookup_side_random_distribution_(random_) ); } void place_ship_randomly(const size_t &ship_size); bool continue_attack(AttackCallback *attack_callback); bool random_attack(AttackCallback *attack_callback); void handle_ship_destruction(); Direction random_available_attack_direction(const Coordinate &coordinate); public: explicit SimpleRivalBot(GameField *const own_field, GameField *const rival_field) : own_field_(own_field), rival_field_(rival_field), own_x_random_distribution_(0, own_field_->get_configuration().field_width - 1), own_y_random_distribution_(0, own_field_->get_configuration().field_height - 1), rival_x_random_distribution_(0, rival_field_->get_configuration().field_width - 1), rival_y_random_distribution_(0, rival_field_->get_configuration().field_height - 1), direction_random_distribution_(0, 3) {} void place_ships() override; bool act(AttackCallback *attack_callback) override; }; }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/coordinate.h
#pragma once #include <cstddef> #include <string> #include "direction.h" using std::string; namespace battleships { struct Coordinate { /* signed type is used to allow negative number comparisons */ int x, y; inline Coordinate(const int &x, const int &y) : x(x), y(y) {} void move(const Direction &direction, const int &delta) { switch (direction) { case RIGHT: { x += delta; break; } case DOWN: { y -= delta; break; } case LEFT: { x -= delta; break; } case UP: { y += delta; break; } default:throw invalid_argument(&"Unknown direction"[direction]); } } [[nodiscard]] Coordinate move(const Direction &direction, const int &delta) const { switch (direction) { case RIGHT: return Coordinate(x + delta, y); case DOWN: return Coordinate(x, y - delta); case LEFT: return Coordinate(x - delta, y); case UP: return Coordinate(x, y + delta); default:throw invalid_argument(&"Unknown direction"[direction]); } } void move(const int &deltaX, const int &deltaY) { this->x += deltaX; this->y += deltaX; } [[nodiscard]] Coordinate move(const int &deltaX, const int &deltaY) const { return Coordinate(x + deltaX, y + deltaY); } bool operator==(const Coordinate &other) const { return x == other.x && y == other.y; } bool operator!=(const Coordinate &other) const { return x != other.x || y != other.y; } bool operator>(const Coordinate &other) const { return x == other.x ? y > other.y : x > other.x; } bool operator<(const Coordinate &other) const { return x == other.x ? y < other.y : x < other.x; } [[nodiscard]] string to_string() const { return char(x + 'A') + std::to_string(y); } }; }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/simple_game.h
<filename>battleships/simple_game.h #pragma once #include "game.h" #include "simple_game_field.h" namespace battleships { class SimpleGame : public Game { const GameConfiguration configuration_; GameField *field_1_, *field_2_; public: explicit SimpleGame(const GameConfiguration &configuration) : configuration_(configuration), field_1_(new SimpleGameField(configuration)), field_2_(new SimpleGameField(configuration)) {} ~SimpleGame() override { delete field_1_; delete field_2_; } GameConfiguration configuration() override { return configuration_; } GameField *field_1() override { return field_1_; } GameField *field_2() override { return field_2_; } void print_to_console() const noexcept override { const auto width = configuration_.field_width, height = configuration_.field_height; // draw upper border { cout << ' '; auto letter = 'A'; for (size_t i = 0; i < width * 2 + 1; i++) cout << (i % 2 == 0 ? '|' : letter++); } cout << " "; { cout << ' '; auto letter = 'A'; for (size_t i = 0; i < width * 2 + 1; i++) cout << (i % 2 == 0 ? '|' : letter++); } cout << "\n"; { auto number = 0; for (size_t y = 0; y < height; y++) { cout << number << '|'; for (size_t x = 0; x < width; x++)cout << field_1_->get_public_icon_at(Coordinate(x, y)) << '|'; cout << " " << number++ << '|'; for (size_t x = 0; x < width; x++) cout << field_2_->get_public_icon_at(Coordinate(x, y)) << '|'; cout << "\n"; } } // draw lower border cout << ' '; for (size_t i = 0; i < width * 2 + 1; i++) cout << "¯"; cout << " "; for (size_t i = 0; i < width * 2 + 1; i++) cout << "¯"; cout << endl; } }; }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/ship_position.h
#pragma once #include <random> #include <stdexcept> using std::random_device; using std::bernoulli_distribution; using std::invalid_argument; using std::runtime_error; namespace battleships { static bernoulli_distribution ship_position_bool_distribution; // NOLINT(cert-err58-cpp) enum ShipPosition { NONE, VERTICAL, HORIZONTAL }; inline static ShipPosition invert_ship_position(const ShipPosition &ship_position) { switch (ship_position) { case VERTICAL: return HORIZONTAL; case HORIZONTAL: return VERTICAL; default: throw invalid_argument(&"Unknown ship position "[ship_position]); } } inline static ShipPosition random_ship_position(random_device &random) { return ship_position_bool_distribution(random) ? VERTICAL : HORIZONTAL; } }
BMSTU-IU8-15/algorithmic-languages-project-2
battleships/direction.h
<gh_stars>0 #pragma once #include <random> #include <stdexcept> #include <string> using std::random_device; using std::string; using std::uniform_int_distribution; using std::invalid_argument; using std::runtime_error; namespace battleships { static uniform_int_distribution<int8_t> direction_int_distribution(0, 3); // NOLINT(cert-err58-cpp) static uniform_int_distribution<int8_t> horizontal_direction_int_distribution(0, 1); // NOLINT(cert-err58-cpp) static uniform_int_distribution<int8_t> vertical_direction_int_distribution(0, 1); // NOLINT(cert-err58-cpp) enum Direction { RIGHT, DOWN, LEFT, UP }; const static Direction ALL_DIRECTIONS[] = { RIGHT, DOWN, LEFT, UP }; inline static Direction invert_direction(const Direction &direction) { switch (direction) { case RIGHT: return LEFT; case DOWN: return UP; case LEFT: return RIGHT; case UP: return DOWN; default:throw invalid_argument(&"Unknown direction "[direction]); } } inline static bool is_horizontal_direction(const Direction &direction) { switch (direction) { case RIGHT: case LEFT: return true; case UP: case DOWN: return false; default:throw invalid_argument(&"Unknown direction "[direction]); } } inline static bool is_vertical_direction(const Direction &direction) { switch (direction) { case RIGHT: case LEFT: return false; case UP: case DOWN: return true; default:throw invalid_argument(&"Unknown direction "[direction]); } } inline static Direction rotate_direction_clockwise(const Direction &direction) { switch (direction) { case RIGHT: return DOWN; case DOWN: return LEFT; case LEFT: return UP; case UP: return RIGHT; default:throw invalid_argument(&"Unknown direction "[direction]); } } inline static Direction rotate_direction_counter_clockwise(const Direction &direction) { switch (direction) { case RIGHT: return UP; case DOWN: return RIGHT; case LEFT: return DOWN; case UP: return LEFT; default:throw invalid_argument(&"Unknown direction "[direction]); } } inline static Direction random_direction(random_device &random) { switch (direction_int_distribution(random)) { case 0: return RIGHT; case 1: return DOWN; case 2: return LEFT; case 3: return UP; default:throw runtime_error("Generated random value is out of range"); } } inline static Direction random_horizontal_direction(random_device &random) { switch (horizontal_direction_int_distribution(random)) { case 0: return RIGHT; case 1: return LEFT; default:throw runtime_error("Generated random value is out of range"); } } inline static Direction random_vertical_direction(random_device &random) { switch (vertical_direction_int_distribution(random)) { case 0: return DOWN; case 1: return UP; default:throw runtime_error("Generated random value is out of range"); } } inline static string direction_name(const Direction &direction) { switch (direction) { case RIGHT: return "right"; case DOWN: return "down"; case LEFT: return "left"; case UP: return "up"; default:throw invalid_argument(&"Unknown direction "[direction]); } } }
d3r0/gorgbmatrix
vendor/rpi-rgb-led-matrix/lib/multiplex-transformers-internal.h
<reponame>d3r0/gorgbmatrix // -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*- // Copyright (C) 2017 <NAME> <<EMAIL>> // // This program 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 version 2. // // This program 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 this program. If not, see <http://gnu.org/licenses/gpl-2.0.txt> #ifndef RPI_RGBMATRIX_MULTIPLEX_TRANSFORMERS_INTERNAL_H #define RPI_RGBMATRIX_MULTIPLEX_TRANSFORMERS_INTERNAL_H #include "canvas.h" // A couple of 1:8 multiplexing mappings found on some common led matrices. // There are constantly new ones coming out, so please help adding one if your // matrix is different. namespace rgb_matrix { namespace internal { class StripeTransformer : public CanvasTransformer { public: StripeTransformer(int panel_rows, int panel_cols); virtual ~StripeTransformer(); virtual Canvas *Transform(Canvas *output); private: class TransformCanvas; TransformCanvas *const canvas_; }; // multiplexing is done in checkered patches. class CheckeredTransformer : public CanvasTransformer { public: CheckeredTransformer(int panel_rows, int panel_cols); virtual ~CheckeredTransformer(); virtual Canvas *Transform(Canvas *output); private: class TransformCanvas; TransformCanvas *const canvas_; }; class SpiralTransformer : public CanvasTransformer { public: SpiralTransformer(int panel_rows, int panel_cols); virtual ~SpiralTransformer(); virtual Canvas *Transform(Canvas *output); private: class TransformCanvas; TransformCanvas *const canvas_; }; // 1:4 scan Z scan stripe transformer // class ZStripeTransformer : public CanvasTransformer { public: ZStripeTransformer(int panel_rows, int panel_cols); virtual ~ZStripeTransformer(); virtual Canvas *Transform(Canvas *output); private: class TransformCanvas; TransformCanvas *const canvas_; }; } // namespace internal } // namespace rgb_matrix #endif // RPI_RGBMATRIX_MULTIPLEX_TRANSFORMERS_INTERNAL_H
luweiguo511/TimerEM2Mode
main.c
/**************************************************************************//** * @main_series0.c * @brief This project demonstrates frequency generation using the * TIMER module. The pin specified in readme.txt is configured for output * compare and toggles on each overflow event at a set frequency. * @version 0.0.1 ****************************************************************************** * @section License * <b>Copyright 2018 Silicon Labs, Inc. http://www.silabs.com</b> ******************************************************************************* * * This file is licensed under the Silabs License Agreement. See the file * "Silabs_License_Agreement.txt" for details. Before using this software for * any purpose, you must agree to the terms of that agreement. * ******************************************************************************/ #include "em_device.h" #include "em_cmu.h" #include "em_emu.h" #include "em_chip.h" #include "em_gpio.h" #include "em_timer.h" #include "bsp.h" #include "em_prs.h" // Desired frequency in Hz // Min: 107 Hz, Max: 7.5 MHz with default settings #define OUT_FREQ 1000 // Default prescale value #define TIMER1_PRESCALE timerPrescale1 /**************************************************************************//** * @brief * GPIO initialization *****************************************************************************/ void initGpio(void) { // Enable GPIO clock CMU_ClockEnable(cmuClock_GPIO, true); // Configure PD6 as output GPIO_PinModeSet(gpioPortD, 6, gpioModePushPull, 0); } /**************************************************************************//** * @brief * TIMER initialization *****************************************************************************/ void initTimer(void) { // Enable clock for TIMER1 module CMU_ClockEnable(cmuClock_TIMER1, true); // Configure TIMER1 Compare/Capture for output compare TIMER_InitCC_TypeDef timerCCInit = TIMER_INITCC_DEFAULT; timerCCInit.mode = timerCCModeCompare; timerCCInit.cmoa = timerOutputActionToggle; TIMER_InitCC(TIMER1, 0, &timerCCInit); // Route TIMER1 CC0 to location 4 and enable CC0 route pin // TIM1_CC0 #4 is GPIO Pin PD6 TIMER1->ROUTE |= (TIMER_ROUTE_CC0PEN | TIMER_ROUTE_LOCATION_LOC4)|(TIMER_ROUTE_CC1PEN ); // Set Top value // Note each overflow event constitutes 1/2 the signal period //uint32_t topValue = CMU_ClockFreqGet(cmuClock_HFPER) / (2*OUT_FREQ * (1 << TIMER1_PRESCALE))-1; TIMER_TopSet(TIMER1, 20); // Initialize and start timer with defined prescale TIMER_Init_TypeDef timerInit = TIMER_INIT_DEFAULT; timerInit.enable = false; timerInit.prescale = TIMER1_PRESCALE; TIMER_Init(TIMER1, &timerInit); } void initGpio1(void) { // Enable GPIO clock CMU_ClockEnable(cmuClock_GPIO, true); // Configure button 0 as input GPIO_PinModeSet(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, gpioModeInputPullFilter, 1); // Configure button 0 as input GPIO_PinModeSet(gpioPortD, 7, gpioModeInputPullFilter, 1); // Select button 0 as the interrupt source (configure as disabled since using PRS) GPIO_ExtIntConfig(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, BSP_GPIO_PB0_PIN, false, false, false); // Configure PD6 as output GPIO_PinModeSet(gpioPortD, 6, gpioModePushPull, 0); } /**************************************************************************//** * @brief * PRS initialization * * @details * prsEdgeOff is chosen because GPIO produces a level signal and the timer * CC0 input can accept either a pulse or level. Thus, we do not need the PRS * module to generate a pulse from the GPIO level signal (we can just leave * it as it is). See the PRS chapter in the reference manual for further * details on Producers and Consumers. *****************************************************************************/ void initPrs(void) { // Enable PRS clock CMU_ClockEnable(cmuClock_PRS, true); // Select GPIO as source and button 0 GPIO pin as signal for PRS channel 0 // Note that the PRS Channel Source Select splits LOWER (0-7) and HIGHER (8-15) GPIO pins if (BSP_GPIO_PB0_PIN < 8) { PRS_SourceSignalSet(0, PRS_CH_CTRL_SOURCESEL_GPIOL, BSP_GPIO_PB0_PIN, prsEdgeOff); } else { PRS_SourceSignalSet(0, PRS_CH_CTRL_SOURCESEL_GPIOH, (uint32_t)(BSP_GPIO_PB0_PIN - 8), prsEdgeOff); } } void initClockSource(void) { TIMER1->CC[1].CTRL = 0x02000000; //CLKSEL TIMER1->CTRL = (TIMER0->CTRL & 0xFFFCFFFF) | 0x010000; TIMER_Enable(TIMER1, true); } /**************************************************************************//** * @brief * Main function *****************************************************************************/ int main(void) { // Chip errata CHIP_Init(); // Initialization initGpio1(); initPrs(); initTimer(); initClockSource(); while (1) { EMU_EnterEM1(); // Enter EM1 (won't exit) } }
teemid/Capstan
include/Capstan/Containers/DynamicArray.h
#ifndef CAPSTAN_CONTAINERS_DYNAMIC_ARRAY_H #define CAPSTAN_CONTAINERS_DYNAMIC_ARRAY_H #include "Platform/Memory.h" #define Increment(variable) (variable) += 1 #define Decrement(variable) (variable) -= 1 namespace Capstan { #define DEFAULT_INITIAL_SIZE 24 template<typename T> class DynamicArray { public: DynamicArray (void); DynamicArray (UInt32 initialSize); ~DynamicArray (void); void Append (T item); void Insert (T item, UInt32 position); void Remove (T item); void Resize (UInt32 size); UInt32 Length (void); T & operator [](UInt32 index); private: T * memory; UInt32 size; UInt32 length; }; template<typename T> DynamicArray::DynamicArray (void) { memory = (T *)Memory::Allocate(DEFAULT_INITIAL_SIZE); size = DEFAULT_INITIAL_SIZE; length = 0; } template<typename T> DynamicArray::DynamicArray (UInt32 initial) { memory = (T *)Memory::Allocate(initial); length = 0; size = initial; } DynamicArray::~DynamicArray (void) { Memory::Free((void *)memory); } template<typename T> void DynamicArray::Append (T item) { if (length == size) { Resize(size * 2); } *(memory + length) = item; Increment(length); } template<typename T> void DynamicArray::Insert (T item, UInt32 position) { if (length == size) { Resize(size * 2); } Memory::Copy(memory + position, memory + position + 1, length - position); *(memory + position) = item; Increment(length); } template<typename T> void DynamicArray::Remove (UInt32 position) { Memory::Copy(memory + position + 1, memory + position, length - position); Decrement(length); } template<typename T> void DynamicArray::Resize (UInt32 size) { memory = (T *)Memory::Reallocate(memory, this->size, size); } UInt32 DynamicArray::Length (void) { return length; } template<typename T> T & DynamicArray::operator [](UInt32 index) { return *(memory + index); } } #endif
teemid/Capstan
include/Capstan/Platform/Win32/PlatformData.h
<reponame>teemid/Capstan<gh_stars>0 #ifndef CAPSTAN_PLATFORM_WIN32_PLATFORM_DATA_H #define CAPSTAN_PLATFORM_WIN32_PLATFORM_DATA_H #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <Windows.h> #include <WinGDI.h> namespace Capstan { namespace Platform { struct PlatformData { HWND windowHandle; HDC deviceContext; HGLRC renderContext; }; } } #endif
teemid/Capstan
include/Capstan/ECS/Components/BoxCollider2D.h
#ifndef CAPSTAN_ECS_COMPONENTS_BOX_COLLIDER_2D_H #define CAPSTAN_ECS_COMPONENTS_BOX_COLLIDER_2D_H #include "Capstan/ECS/Components/Collider2D.h" #include "Capstan/Math/Vector2f.h" namespace Capstan { namespace ECS { struct BoxCollider2D : Collider2D { Vector2f lower; Vector2f upper; }; } } #endif
teemid/Capstan
include/Capstan/ECS/Components/SpriteRenderer.h
#ifndef CAPSTAN_ECS_SPRITE_RENDERER_COMPONENT_H #define CAPSTAN_ECS_SPRITE_RENDERER_COMPONENT_H // #include "ECS/Components/Component.h" namespace Capstan { namespace ECS { struct SpriteRendererComponent { Sprite * sprite; Vector2f coordinates; }; } } #endif
teemid/Capstan
include/Capstan/AssetManager.h
<gh_stars>0 #ifndef CAPSTAN_ASSET_MANAGER_H #define CAPSTAN_ASSET_MANAGER_H #include "Capstan/Types.h" namespace Capstan { #define MAX_ASSET_COUNT 200 typedef UInt32 AssetId; enum class AssetType : UInt32 { BITMAP, SOUND, MUSIC, SHADER }; enum class AssetStatus : UInt32 { UNLOADED, RETREIVING, LOADED }; struct Asset { void * asset; AssetId id; AssetType type; AssetStatus status; }; struct ShaderAsset { char * source; Int64 size; }; enum class PixelLayout { RGB24, BGR24, RGBA32, BGRA32 }; struct ImageAsset { Int32 width; Int32 height; PixelLayout layout; void * data; }; class AssetManager { public: AssetManager (); ~AssetManager (); void StartUp (size_t size); void ShutDown (void); void LoadResource (char * filename); ShaderAsset LoadShader (char * filename); ImageAsset LoadTexture (char * filename); void Unload (Asset asset); private: Asset assets[MAX_ASSET_COUNT]; UInt32 current; }; } #endif
teemid/Capstan
include/Capstan/Platform/OpenGLContext.h
#ifndef CAPSTAN_PLATFORM_OPENGL_CONTEXT_H #define CAPSTAN_PLATFORM_OPENGL_CONTEXT_H #include "Capstan/Types.h" namespace Capstan { namespace Platform { struct PlatformData; namespace OpenGL { Bool32 CreateContext (PlatformData * data, Int32 major_version, Int32 minor_version); Bool32 DeleteContext (PlatformData * data); Bool32 SwapBuffers (PlatformData * data); void * GetFunctionAddress (char * name); } } } #endif
teemid/Capstan
include/Capstan/Common.h
<filename>include/Capstan/Common.h<gh_stars>0 #ifndef CAPSTAN_COMMON_H #define CAPSTAN_COMMON_H #include "Capstan/Types.h" #define local_persist static #define internal static #define ILLEGAL_CASE(message, ...) \ default: \ { \ Assert(false, message, __VA_ARGS__); \ } break #endif
teemid/Capstan
include/Capstan/Allocators/BitmappedAllocator.h
#ifndef CAPSTAN_ALLOCATORS_BITMAPPED_BLOCK_H #define CAPSTAN_ALLOCATORS_BITMAPPED_BLOCK_H namespace Capstan { class BitmappedAllocator { public: BitmappedAllocator (size_t size, size_t blockSize); ~BitmappedAllocator (void); void * Allocate (size_t size); void Deallocate (void * memory); private: void * memory; void * occupied; size_t blockSize; }; } #endif
teemid/Capstan
include/Capstan/ECS/Systems/System.h
<reponame>teemid/Capstan<filename>include/Capstan/ECS/Systems/System.h #ifndef CAPSTAN_ECS_SYSTEM_H #define CAPSTAN_ECS_SYSTEM_H #include "Capstan/Common.h" namespace Capstan { namespace ECS { class System { public: virtual void Update (Real64 deltaTime) = 0; }; } } #endif
teemid/Capstan
include/Capstan/Allocators/PoolAllocator.h
<gh_stars>0 #ifndef CAPSTAN_ALLOCATORS_POOLALLOCATOR_H #define CAPSTAN_ALLOCATORS_POOLALLOCATOR_H namespace Capstan { template <typename T> class PoolAllocator { public: PoolAllocator (size_t size); ~PoolAllocator (void); void * Allocate (); void Free (void * memory); private: T * freeList; T * pool; size_t size; }; } #endif
teemid/Capstan
include/Capstan/ECS/Systems/Physics2DSystem.h
#ifndef CAPSTAN_PHYSICS_2D_SYSTEM_H #define CAPSTAN_PHYSICS_2D_SYSTEM_H #include "Capstan/ECS/Systems/System.h" #include "Capstan/ECS/Components/Collider2D.h" #include "Capstan/ECS/Components/BoxCollider2D.h" #include "Capstan/ECS/Components/CircleCollider2D.h" namespace Capstan { namespace ECS { class Physics2DSystem : public System { public: void Update(Real64 deltaTime); }; } } #endif
teemid/Capstan
include/Capstan/Platform/FileSystem.h
<filename>include/Capstan/Platform/FileSystem.h #ifndef CAPSTAN_FILESYSTEM_H #define CAPSTAN_FILESYSTEM_H #include "Capstan/Types.h" namespace Capstan { class FileSystem { public: FileSystem (void); ~FileSystem (void); void StartUp (void); void ShutDown (void); struct File { Bool32 open; size_t size; struct PlatformFileData * platform; }; enum Mode { InvalidFlag = 0, ReadFlag = 1 << 0, WriteFlag = 1 << 1, SequentialFlag = 1 << 2, RandomAccessFlag = 1 << 3 }; static Bool32 Create (char * filename, File * file, Int32 mode = WriteFlag); static Bool32 Open (char * filename, File * file, Int32 mode = ReadFlag | SequentialFlag); static Bool32 Read (File * file, void * data, size_t bytesToRead = 0, size_t offset = 0); static Bool32 Write (File * file, void * data, size_t numberOfBytes); static Bool32 Delete (char * filename); // Int64 might not be necessary, atleast on Windows. // Check if max file size is 4 GB and if Int32 is enough? static Bool32 Seek (File * file, Int64 position); static Bool32 Close (File * file); private: static Int32 maxAsyncReads; static PlatformFileData * fileList; }; Int64 GetFileSize (char * filename); void Read (char * filename, void * buffer, size_t size = 0, size_t offset = 0); void Write (char * filename, void * buffer, size_t size); } #endif
teemid/Capstan
include/Capstan/Allocators/StackAllocator.h
<gh_stars>0 #ifndef CAPSTAN_MEMORY_STACK_ALLOCATOR_H #define CAPSTAN_MEMORY_STACK_ALLOCATOR_H #include "Capstan/Types.h" namespace Capstan { typedef UInt32 StackMarker; struct StackAllocation { void * memory; StackMarker marker; }; class StackAllocator { public: StackAllocator (size_t size); ~StackAllocator (void); StackAllocation Allocate (size_t size); StackAllocation AllocateAligned (size_t size, size_t alignment); void Free (StackAllocation allocation); private: void * start; void * end; StackMarker marker; }; } #endif
teemid/Capstan
include/Capstan/Graphics/Camera.h
#ifndef CAPSTAN_GRAPHICS_CAMERA_H #define CAPSTAN_GRAPHICS_CAMERA_H #include "Capstan/Math/Vector3f.h" namespace Capstan { namespace Graphics { class Camera { public: Camera (void); Camera (Vector3f position, Vector3f direction); ~Camera (void); void LookAt (Vector3f target); private: Vector3f position; Vector3f direction; Vector3f right; Vector3f up; }; } } #endif
teemid/Capstan
include/Capstan/Math/Color.h
<gh_stars>0 #ifndef CAPSTAN_COLOR_H #define CAPSTAN_COLOR_H namespace Capstan { struct Color3f { union { Real32 data[3]; struct { Real32 r; Real32 g; Real32 b; }; }; }; inline Lerp (Color3f start, Color3f end, Real32 t); struct Color4f { union { Real32 data[4]; struct { Real32 r; Real32 g; Real32 b; Real32 a; }; }; }; } #endif
teemid/Capstan
include/Capstan/Allocators/DoubleStackAllocator.h
<filename>include/Capstan/Allocators/DoubleStackAllocator.h<gh_stars>0 #ifndef CAPSTAN_ALLOCATORS_DOUBLE_STACK #define CAPSTAN_ALLOCATORS_DOUBLE_STACK #include "Capstan/Allocators/StackAllocator.h" namespace Capstan { class DoubleStackAllocator { public: DoubleStackAllocator (size_t size); ~DoubleStackAllocator (void); StackAllocation Allocate (size_t size); StackAllocation AllocateAligned (size_t size, size_t alignment); void Free (StackAllocation allocation); private: void * bottom; void * top; StackMarker bottomMarker; StackMarker topMarker; }; } #endif
teemid/Capstan
include/Capstan/Math/Vector2f.h
#ifndef CAPSTAN_MATH_VECTOR2F_H #define CAPSTAN_MATH_VECTOR2F_H #include "Capstan/Platform/Intrinsics.h" #include "Capstan/Types.h" namespace Capstan { struct Vector2f { union { Real32 data[2]; struct { Real32 x, y; }; struct { Real32 u, v; }; }; Vector2f (void); Vector2f (Real32 x); Vector2f (Real32 x, Real32 y); inline Vector2f operator +(const Vector2f & rhs); inline Vector2f operator -(const Vector2f & rhs); inline Vector2f operator *(const Vector2f & rhs); inline Vector2f operator /(const Vector2f & rhs); inline Vector2f operator +(const Real32 & scalar); inline Vector2f operator -(const Real32 & scalar); inline Vector2f operator *(const Real32 & scalar); inline Vector2f operator /(const Real32 & scalar); inline Bool32 operator ==(const Vector2f & rhs); }; inline Vector2f Normalize (Vector2f & v); inline Real32 LengthSquared (Vector2f & v); inline Real32 Length (Vector2f & v); inline Real32 Dot (Vector2f & v1, Vector2f & v2); inline Real32 Angle (Vector2f & v1, Vector2f & v2); inline Vector2f Lerp (Vector2f & start, Vector2f & end, Real32 t); //==== Implementation begin ====// inline Vector2f Vector2f::operator +(const Vector2f & rhs) { Vector2f v; v.x = x + rhs.x; v.y = y + rhs.y; return v; } inline Vector2f Vector2f::operator -(const Vector2f & rhs) { Vector2f v; v.x = x - rhs.x; v.y = y - rhs.y; return v; } inline Vector2f Vector2f::operator *(const Vector2f & rhs) { Vector2f v; v.x = x * rhs.x; v.y = y * rhs.y; return v; } inline Vector2f Vector2f::operator /(const Vector2f & rhs) { Vector2f v; v.x = x / rhs.x; v.y = y / rhs.y; return v; } inline Bool32 Vector2f::operator ==(const Vector2f & rhs) { return (x == rhs.x && y == rhs.y); } inline Vector2f Vector2f::operator +(const Real32 & scalar) { return Vector2f(x + scalar, y + scalar); } inline Vector2f Vector2f::operator -(const Real32 & scalar) { return Vector2f(x - scalar, y - scalar); } inline Vector2f Vector2f::operator *(const Real32 & scalar) { return Vector2f(x * scalar, y * scalar); } inline Vector2f Vector2f::operator /(const Real32 & scalar) { return Vector2f(x / scalar, y / scalar); } inline Real32 LengthSquared (Vector2f & v) { return v.x * v.x + v.y * v.y; } inline Real32 Length (Vector2f & v) { return SquareRoot(LengthSquared(v)); } inline Vector2f Normalize (Vector2f & v) { return v / Length(v); } inline Real32 Dot (Vector2f & v1, Vector2f & v2) { return v1.x * v2.x + v1.y * v2.y; } inline Real32 Angle (Vector2f & v1, Vector2f & v2) { return Cos(Dot(v1, v2) / Length(v1) * Length(v2)); } inline Vector2f Lerp (Vector2f & start, Vector2f & end, Real32 t) { return start * (1.0f - t) + end * t; } //==== Implementation end ====// } #endif
teemid/Capstan
include/Capstan/Math/Arithmetic.h
<gh_stars>0 #ifndef CAPSTAN_MATH_COMMON_H #define CAPSTAN_MATH_COMMON_H #include "Capstan/Common.h" namespace Capstan { namespace Math { inline UInt8 Abs (Int8 i) { return (i < 0) ? (-1) * i : i; } inline UInt16 Abs (Int16 i) { return (i < 0) ? (-1) * i : i; } inline UInt32 Abs (Int32 i) { return (i < 0) ? (-1) * i : i; } inline UInt64 Abs (Int64 i) { return (i < 0) ? (-1) * i : i; } } } #endif
teemid/Capstan
include/Capstan/Math/Vector3f.h
#ifndef CAPSTAN_MATH_VECTOR3F_H #define CAPSTAN_MATH_VECTOR3F_H #include "Capstan/Types.h" #include "Capstan/Platform/Intrinsics.h" #include "Capstan/Math/Vector2f.h" namespace Capstan { struct Vector3f { union { Real32 data[3]; struct { Real32 x, y, z; }; struct { Real32 r, g, b; }; }; Vector3f (void); Vector3f (Real32 x); Vector3f (Real32 x, Real32 y, Real32 z); Vector3f (Vector2f & v); Vector3f (Vector2f & v, Real32 f); inline Vector3f operator +(const Vector3f & rhs); inline Vector3f operator -(const Vector3f & rhs); inline Vector3f operator *(const Vector3f & rhs); inline Vector3f operator /(const Vector3f & rhs); inline Vector3f operator +(const Real32 & scalar); inline Vector3f operator -(const Real32 & scalar); inline Vector3f operator *(const Real32 & scalar); inline Vector3f operator /(const Real32 & scalar); inline Vector3f operator -(void); inline Bool32 operator ==(const Vector3f & rhs); }; inline Real32 LengthSquared (Vector3f & v); inline Real32 Length (Vector3f & v); inline Vector3f Normalize (Vector3f & v); inline Vector3f Cross (Vector3f & v1, Vector3f & v2); inline Real32 Dot (Vector3f & v1, Vector3f & v2); inline Real32 Angle (Vector3f & v1, Vector3f & v2); inline Vector3f Lerp (Vector3f & start, Vector3f & end, Real32 t); //==== Implementation begin ====// inline Vector3f Vector3f::operator +(const Vector3f & rhs) { Vector3f v; v.x = x + rhs.x; v.y = y + rhs.y; v.z = y + rhs.z; return v; } inline Vector3f Vector3f::operator -(const Vector3f & rhs) { Vector3f v; v.x = x - rhs.x; v.y = y - rhs.y; v.z = z - rhs.z; return v; } inline Vector3f Vector3f::operator *(const Vector3f & rhs) { Vector3f v; v.x = x * rhs.x; v.y = y * rhs.y; v.z = z * rhs.z; return v; } inline Vector3f Vector3f::operator /(const Vector3f & rhs) { Vector3f v; v.x = x / rhs.x; v.y = y / rhs.y; v.z = z / rhs.z; return v; } inline Vector3f Vector3f::operator +(const Real32 & scalar) { return Vector3f(x + scalar, y + scalar, z + scalar); } inline Vector3f Vector3f::operator -(const Real32 & scalar) { return Vector3f(x - scalar, y - scalar, z - scalar); } inline Vector3f Vector3f::operator *(const Real32 & scalar) { return Vector3f(x * scalar, y * scalar, z * scalar); } inline Vector3f Vector3f::operator /(const Real32 & scalar) { return Vector3f(x / scalar, y / scalar, z / scalar); } inline Vector3f Vector3f::operator -(void) { return Vector3f(-x, -y, -z); } inline Bool32 Vector3f::operator ==(const Vector3f & rhs) { return (x == rhs.x && y == rhs.y && z == rhs.z); } inline Real32 LengthSquared (Vector3f & v) { return v.x * v.x + v.y * v.y; } inline Real32 Length (Vector3f & v) { return SquareRoot(LengthSquared(v)); } inline Vector3f Normalize (Vector3f & v) { return v / Length(v); } inline Vector3f Cross (Vector3f & v1, Vector3f & v2) { return Vector3f( v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x ); } inline Real32 Dot (Vector3f & v1, Vector3f & v2) { return v1.x * v2.x + v1.y * v2.y; } inline Real32 Angle (Vector3f & v1, Vector3f & v2) { return Cos(Dot(v1, v2) / Length(v1) * Length(v2)); } inline Vector3f Lerp (Vector3f & start, Vector3f & end, Real32 t) { return start * (1.0f - t) + end * t; } //==== Implementation end ====// } #endif
teemid/Capstan
include/Capstan/Math/Constants.h
<filename>include/Capstan/Math/Constants.h #ifndef CAPSTAN_MATH_CONSTANTS_H #define CAPSTAN_MATH_CONSTANTS_H #include "Capstan/Types.h" namespace Capstan { namespace Math { #define TWO_PI 6.28318530718f #define PI 3.14159265359f #define PI_2 1.57079632679f #define PI_3 1.0471975512f #define PI_4 0.78539816339f #define PI_6 0.52359877559f } } #endif
teemid/Capstan
include/Capstan/ECS/Systems/SpriteRenderer.h
#ifndef CAPSTAN_ECS_SPRITE_RENDERER_SYSTEM_H #define CAPSTAN_ECS_SPRITE_RENDERER_SYSTEM_H #include "ECS/Systems/System.h" namespace Capstan { namespace ECS { class SpriteRendererSystem : public System { public: void Update (Real64 deltaTime); private: SpriteRendererComponent }; } }
teemid/Capstan
include/Capstan/Physics/2D/AABB.h
<filename>include/Capstan/Physics/2D/AABB.h<gh_stars>0 #ifndef CAPSTAN_PHYSICS_2D_AABB #define CAPSTAN_PHYSICS_2D_AABB #include "Capstan/Math/Vector2f.h" #include "Capstan/Types.h" namespace Capstan { namespace Physics { struct AABB { Vector2f lower; Vector2f upper; }; Bool32 Collision(AABB body1, AABB body2); } } #endif
teemid/Capstan
include/Capstan/Platform/Threading.h
<filename>include/Capstan/Platform/Threading.h #ifndef CAPSTAN_PLATFORM_THREADING_H #define CAPSTAN_PLATFORM_THREADING_H namespace Capstan { } #endif
teemid/Capstan
include/Capstan/Containers/HashMap.h
<reponame>teemid/Capstan #ifndef CAPSTAN_CONTAINERS_HASHMAP_H #define CAPSTAN_CONTAINERS_HASHMAP_H #include "Platform/Types.h" #define Increment(variable) (variable) += 1 #define Decrement(variable) (variable) -= 1 #define DEFAULT_BUCKET_COUNT 11 #define DEFAULT_BUCKET_LENGTH 4 namespace Capstan { typedef UInt32 Hash; typedef Hash (*HashFunction)(UInt8 bytes); template<typename T> Hash HashFunction (T item, UInt32 numberOfBytes) { Hash hash; UInt8 bytes = (UInt8)item; for (UInt32 index = 0; i < numberOfBytes; ++i) { hash += bytes[index]; } return hash; } template<typename Key, typename Value> class HashMap { public: struct HashMapNode { Hash hash; Key key; Value value; }; typedef DynamicArray<HashMapNode> Bucket; HashMap (void); HashMap (UInt32 bucketCount); HashMap (UInt32 bucketCount, UInt32 bucketLength); ~HashMap (void); void SetHashFunction (HashFunction function); void Add (Key key, Value value); Value Remove (Key key); UInt32 Length (void); Value & operator [](Key key); Value operator [](Key key) const; private: DynamicArray<Value> * buckets; HashFunction function; UInt32 length; }; template<typename Key, typename Value> HashMap::HashMap (void) { buckets = (Bucket *)Memory::Allocate(sizeof(Bucket) * DEFAULT_BUCKET_COUNT); for (UInt32 bucket = 0; bucket < DEFAULT_BUCKET_COUNT; ++bucket) { buckets[bucket] = DynamicArray(DEFAULT_BUCKET_LENGTH); } } template<typename Key, typename Value> HashMap::HashMap (UInt32 bucketCount, UInt32 bucketLength) { buckets = (Bucket *)Memory::Allocate(sizof(Bucket) * bucketCount); for (UInt32 bucket = 0; bucket < bucketCount; ++bucket) { buckets[bucket] = DynamicArray(bucketLength); } } void SetHashFunction (HashFunction function) { function = function; } template<typename Key, typename Value> void HashMap::Add (Key key, Value value) { Hash hash = function(key); UInt32 bucket = hash % buckets.Length(); Increment(length); } template<typename Key, typename Value> Value HashMap::Remove (Key key) { Hash hash = function(key); UInt32 bucket = hash % buckets.Length(); Decrement(length); } UInt32 HashMap::Length (void) { return length; } template<typename Key, typename Value> Value & operator [](Key key) { Hash hash = function(key); UInt32 bucket = hash % buckets.Length(); while (UInt32 index = 0; index < buckets[bucket].Length(); ++i) { if (key == buckets[bucket][index].key && value == buckets[bucket][index].value) { return buckets[bucket][index]; } } } template<typename Key, typename Value> Value operator [](Key key) const { Hash hash = function(key); UInt32 bucket = hash % buckets.Length(); while (UInt32 index = 0; index < buckets[bucket].Length(); ++i) { if (key == buckets[bucket][index].key && value == buckets[bucket][index].value) { return buckets[bucket][index]; } } } } #endif
teemid/Capstan
include/Capstan/ECS/Entity.h
#ifndef CAPSTAN_ECS_ENTITY_H #define CAPSTAN_ECS_ENTITY_H #include "Platform/Types.h" namespace Capstan { namespace ECS { typedef UInt32 Entity; } } #endif
teemid/Capstan
include/Capstan/Math/Vector4f.h
<gh_stars>0 #ifndef CAPSTAN_MATH_VECTOR4F_H #define CAPSTAN_MATH_VECTOR4F_H #include "Capstan/Platform/Memory.h" #include "Capstan/Platform/Intrinsics.h" namespace Capstan { struct Vector4f { union { Real32 data[4]; struct { Real32 x, y, z, w; }; struct { Real32 r, g, b, a; }; }; Vector4f (void); Vector4f (Real32 x); Vector4f (Real32 x, Real32 y, Real32 z); Vector4f (Real32 x, Real32 y, Real32 z, Real32 w); inline Vector4f operator +(const Vector4f & rhs); inline Vector4f operator -(const Vector4f & rhs); inline Vector4f operator *(const Vector4f & rhs); inline Vector4f operator +(const Real32 & scalar); inline Vector4f operator -(const Real32 & scalar); inline Vector4f operator *(const Real32 & scalar); inline Vector4f operator /(const Real32 & scalar); inline Vector4f operator -(void); inline Real32 & operator [](UInt32 index); inline Bool32 operator ==(const Vector4f & rhs); }; inline Real32 LengthSquared (Vector4f & v); inline Real32 Length (Vector4f & v); inline Vector4f Normalize (Vector4f & v); inline Real32 Dot (Vector4f & v1, Vector4f & v2); //==== Implementation begin ====// inline Vector4f Vector4f::operator -(void) { return Vector4f(-x, -y, -z, -w); } inline Real32 & Vector4f::operator [] (UInt32 index) { return data[index]; } inline Vector4f Vector4f::operator +(const Vector4f & rhs) { return Vector4f(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w); } inline Vector4f Vector4f::operator -(const Vector4f & rhs) { return Vector4f(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w); } inline Vector4f Vector4f::operator *(const Vector4f & rhs) { return Vector4f(x * rhs.x, y * rhs.y, z * rhs.z, w * rhs.w); } inline Vector4f Vector4f::operator +(const Real32 & scalar) { return Vector4f(x + scalar, y + scalar, z + scalar, w + scalar); } inline Vector4f Vector4f::operator -(const Real32 & scalar) { return Vector4f(x - scalar, y - scalar, z - scalar, w - scalar); } inline Vector4f Vector4f::operator *(const Real32 & scalar) { return Vector4f(x * scalar, y * scalar, z * scalar, w * scalar); } inline Vector4f Vector4f::operator /(const Real32 & scalar) { return Vector4f(x / scalar, y / scalar, z / scalar, w / scalar); } inline Real32 LengthSquared (Vector4f & v) { return v.x * v.x + v.y * v.y + v.z * v.z; } inline Real32 Length (Vector4f & v) { return SquareRoot(LengthSquared(v)); } inline Vector4f Normalize (Vector4f & v) { auto length = Length(v); return (v * (1 / length)); } inline Real32 Dot (Vector4f & v1, Vector4f & v2) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z + v1.w + v2.w; } //==== Implementation end ====// } #endif
teemid/Capstan
include/Capstan/EventManager.h
#ifndef ENGINE_EVENTMANAGER_H #define ENGINE_EVENTMANAGER_H namespace Capstan { struct Event { void * message; }; class EventManager { public: EventManager (); ~EventManager (); void StartUp (void); void ShutDown (void); private: Event * queue; }; } #endif
teemid/Capstan
include/Capstan/Platform/Win32/Debug.h
<reponame>teemid/Capstan #ifndef CAPSTAN_WIN32_DEBUG_H #define CAPSTAN_WIN32_DEBUG_H namespace Capstan { namespace Debug { void Win32HandleError (void); } } #endif
teemid/Capstan
include/Capstan/Graphics/OpenGL/Texture.h
#ifndef CAPSTAN_GRAPHICS_OPENGL_TEXTURE_H #define CAPSTAN_GRAPHICS_OPENGL_TEXTURE_H namespace Capstan { namespace Graphics { class Texture { public: enum class WrapMode { WRAP_CLAMP, WRAP_CLAMP_ZERO, WRAP_REPEAT, WRAP_MIRRORED_REPEAT, WRAP_MAX_ENUM }; enum class FilterMode { FILTER_NONE, FILTER_LINEAR, FILTER_NEAREST, FILTER_MAX_ENUM }; struct Wrap { WrapMode s; WrapMode t; }; Texture (void); ~Texture (void); private: }; } } #endif
teemid/Capstan
include/Capstan/HashFunctions.h
<filename>include/Capstan/HashFunctions.h #ifndef CAPSTAN_HASH_H #define CAPSTAN_HASH_H #include "Capstan/Types.h" namespace Capstan { Hash MultiplicativeHashFunction (UInt8 * bytes, UInt32 length) { Hash hash = 0; for (UInt32 i = 0; i < length; ++i) { hash = ((hash * 31) + bytes[i]) % 17; } return hash; }; Hash djb2HashFunction (UInt8 * bytes, UInt32 length) { Hash hash = 5381; Int32 c; while (c = *bytes++) { hash = ((hash << 5) + hash) + c; } return hash; } } #endif
teemid/Capstan
include/Capstan/Math/Quaternion.h
<filename>include/Capstan/Math/Quaternion.h #ifndef CAPSTAN_MATH_QUATERNION_H #define CAPSTAN_MATH_QUATERNION_H #include "Math/Vector.h" namespace Capstan { struct Quaternion { union { Real32 data[3]; struct { Real32 i; Real32 j; Real32 k; }; }; Quaternion (void); Quaternion (Real32 i, Real32 j, Real32 k); Quaternion operator +(const Quaternion & rhs); Quaternion operator -(const Quaternion & rhs); Quaternion operator *(const Quaternion & rhs); Quaternion operator /(const Quaternion & rhs); Quaternion operator +(const T scalar); Quaternion operator -(const T scalar); Quaternion operator *(const T scalar); Quaternion operator /(const T scalar); T operator[](UInt32 index); Bool32 operator ==(const Quaternion & rhs); }; } #endif
teemid/Capstan
include/Capstan/Math/Matrix4f.h
<reponame>teemid/Capstan #ifndef CAPSTAN_MATH_MATRIX4F_H #define CAPSTAN_MATH_MATRIX4F_H #include "Capstan/Platform/Intrinsics.h" #include "Capstan/Platform/Memory.h" #include "Capstan/Types.h" #include "Capstan/Math/Constants.h" #include "Capstan/Math/Vector3f.h" #include "Capstan/Math/Vector4f.h" namespace Capstan { struct Matrix4f { union { Real32 data[16]; Vector4f rows[4]; }; Matrix4f (void); Matrix4f (Vector4f & v); Matrix4f (Vector4f c1, Vector4f c2, Vector4f c3, Vector4f c4); Matrix4f operator +(const Matrix4f & rhs); Matrix4f operator -(const Matrix4f & rhs); Matrix4f operator *(const Matrix4f & rhs); Vector4f operator *(const Vector4f & columnVector); Vector4f operator [](UInt32 row) const; Vector4f & operator [](UInt32 row); Matrix4f & operator =(const Matrix4f & rhs); Bool32 operator ==(const Matrix4f & rhs); }; inline Matrix4f Identity (void); inline Matrix4f Transpose (Matrix4f * matrix); inline Matrix4f Rotate (Matrix4f & m, Real32 angle, Vector3f axis); inline Matrix4f Rotate (Real32 angle, Vector3f axis); inline Matrix4f RotateX (Real32 radians); inline Matrix4f RotateY (Real32 radians); inline Matrix4f RotateZ (Real32 radians); inline Matrix4f Translate (Vector3f & translation); inline Matrix4f TranslateX (Real32 x); inline Matrix4f TranslateY (Real32 x); inline Matrix4f TranslateZ (Real32 x); inline Matrix4f Scale (Vector3f & scaling); inline Matrix4f ScaleX (Real32 scaling); inline Matrix4f ScaleY (Real32 scaling); inline Matrix4f ScaleZ (Real32 scaling); namespace Projection { inline Matrix4f Orthographic (Real32 left, Real32 right, Real32 bottom, Real32 top, Real32 zNear, Real32 zFar); inline Matrix4f Perspective (Real32 fov, Real32 aspect, Real32 zNear, Real32 zFar); } inline Matrix4f Identity (void) { Matrix4f identity; identity[0].x = 1; identity[1].y = 1; identity[2].z = 1; identity[3].w = 1; return identity; } inline Matrix4f Transpose (Matrix4f * matrix) { Matrix4f result; for (UInt32 r = 0; r < 4; ++r) { for (UInt32 c = 0; c < 4; ++c) { result[c][r] = (*matrix)[r][c]; } } return result; } inline Matrix4f Rotate (Real32 theta, Vector3f axis) { Matrix4f result; Real32 c = Cos(theta); Real32 c_inv = 1 - c; Real32 s = Sin(theta); result[0][0] = c + axis.x * axis.x * c_inv; result[0][1] = axis.x * axis.y * c_inv - axis.z * s; result[0][2] = axis.x * axis.z * c_inv + axis.y * s; result[0][3] = 0; result[1][0] = axis.x * axis.y * c_inv + axis.z * s; result[1][1] = c + axis.y * axis.y * c_inv; result[1][2] = axis.y * axis.z * c_inv - axis.x * s; result[1][3] = 0; result[2][0] = axis.z * axis.x * c_inv - axis.y * s; result[2][1] = axis.z * axis.y * c_inv + axis.x * s; result[2][2] = c + axis.z * axis.z * c_inv; result[2][3] = 0; result[3] = Vector4f(0.0f, 0.0f, 0.0f, 1.0f); return result; } // NOTE (Emil): Rotates theta degrees around the axis defined by the // unit vector axis. inline Matrix4f Rotate(Matrix4f & m, Real32 theta, Vector3f axis) { Matrix4f result = Rotate(theta, axis); return m * result; } inline Matrix4f RotateX (Real32 radians) { Matrix4f transform = Identity(); transform[1].y = Cos(radians); transform[1].z = -Sin(radians); transform[2].y = Sin(radians); transform[2].z = Cos(radians); return transform; } inline Matrix4f RotateY (Real32 radians) { Matrix4f transform = Identity(); transform[0].x = Cos(radians); transform[0].z = Sin(radians); transform[2].x = -Sin(radians); transform[2].z = Cos(radians); return transform; } inline Matrix4f RotateZ (Real32 radians) { Matrix4f transform = Identity(); transform[0].x = Cos(radians); transform[0].y = -Sin(radians); transform[1].x = Sin(radians); transform[1].y = Cos(radians); return transform; } inline Matrix4f Translate (Vector3f & translation) { Matrix4f transform = Identity(); transform[0].w = translation.x; transform[1].w = translation.y; transform[2].w = translation.z; return transform; } inline Matrix4f TranslateX (Real32 x) { Matrix4f transform = Identity(); transform[0].w = x; return transform; } inline Matrix4f TranslateY (Real32 y) { Matrix4f transform = Identity(); transform[1].w = y; return transform; } inline Matrix4f TranslateZ (Real32 z) { Matrix4f transform = Identity(); transform[2].w = z; return transform; } inline Matrix4f Scale (Vector3f & scaling) { Matrix4f transform = Identity(); transform[0].x = scaling.x; transform[1].y = scaling.y; transform[2].z = scaling.z; return transform; } inline Matrix4f ScaleX (Real32 scaling) { Matrix4f transform = Identity(); transform[0].x = scaling; return transform; } inline Matrix4f ScaleY (Real32 scaling) { Matrix4f transform = Identity(); transform[1].y = scaling; return transform; } inline Matrix4f ScaleZ (Real32 scaling) { Matrix4f transform = Identity(); transform[2].z = scaling; return transform; } namespace Projection { inline Matrix4f Orthographic ( Real32 left, Real32 right, Real32 bottom, Real32 top, Real32 zNear, Real32 zFar ) { Matrix4f ortho; ortho[0][0] = 2.0f / (right - left); ortho[1][1] = 2.0f / (top - bottom); ortho[2][2] = -2.0f / (zFar - zNear); ortho[0][3] = -(right + left) / (right - left); ortho[1][3] = -(top + bottom) / (top - bottom); ortho[2][3] = -(zFar + zNear) / (zFar - zNear); ortho[3] = Vector4f(0.0f, 0.0f, 0.0f, 1.0f); return ortho; } inline Matrix4f Perspective (Real32 fov, Real32 aspect, Real32 zNear, Real32 zFar) { Matrix4f perspective; Real32 s = 1 / (Tan((fov / 2) * (PI / 180))); perspective[0][0] = s; perspective[1][1] = s; perspective[2][2] = -zFar / (zFar - zNear); perspective[2][3] = -1; perspective[3][2] = -(zFar * zNear) / (zFar - zNear); return perspective; } } } #endif
teemid/Capstan
include/Capstan/Physics/2D/2DPhysics.h
<gh_stars>0 #ifndef CAPSTAN_PHYSICS_2D #define CAPSTAN_PHYSICS_2D #include "Physics/2D/AABB.h" #endif
teemid/Capstan
include/Capstan/Graphics/OpenGL/Shader.h
<reponame>teemid/Capstan #ifndef CAPSTAN_GRAPHICS_OPENGL_SHADER_H #define CAPSTAN_GRAPHICS_OPENGL_SHADER_H #include "Capstan/Common.h" #include "Capstan/Graphics/OpenGL/OpenGL.h" namespace Capstan { namespace Graphics { enum class ShaderStage { Vertex, Fragment }; enum class UniformType { Matrix4fv, Float3fv, Float4fv, }; class Shader { public: Shader (void); Shader (GLchar * vertexShader, GLchar * fragmentShader); ~Shader (void); void SetUniform(char * name, UniformType type, void * value); void Use (void); private: GLuint Compile (GLenum shaderStage, GLchar ** shaderSource); void Link (void); GLuint program; }; } } #endif
teemid/Capstan
include/Capstan/ECS/EntityManager.h
<gh_stars>0 #ifndef CAPSTAN_ENTITY_MANAGER_H #define CAPSTAN_ENTITY_MANAGER_H #include "Capstan/Common.h" namespace Capstan { namespace ECS { typedef UInt32 Entity; class Capstan { public: Component * GetComponent (Entity entity, ComponentType type); void AddComponent (Entity entity, ComponentType type); Entity AddEntity (void); void RemoveEntity (Entity entity); private: Entity * entities; Entity currentId; }; } } #endif
teemid/Capstan
include/Capstan/Platform/Gamepad.h
<gh_stars>0 #ifndef CAPSTAN_GAMEPAD_H #define CAPSTAN_GAMEPAD_H #include "Capstan/Types.h" namespace Capstan { struct Stick { Real32 x; Real32 y; }; struct GamePadState { Stick leftStick; Stick rightStick; union { struct { Bool32 A; Bool32 B; Bool32 X; Bool32 Y; Bool32 DPadLeft; Bool32 DPadUp; Bool32 DPadRight; Bool32 DPadDown; Bool32 leftBumper; Bool32 rightBumper; Bool32 leftTrigger; Bool32 rightTrigger; Bool32 BLeftStick; Bool32 BRightStick; Bool32 start; Bool32 back; }; Bool32 Buttons[16]; }; }; // NOTE (Emil): Should this be between 0 and 1? struct Vibration { Real32 left; Real32 right; }; class GamePad { public: GamePad (void); ~GamePad (void); void Initialize (void); void Destroy (void); void GetState (Int32 index, GamePadState * state); void SetState (Int32 index, Vibration * vibration); private: struct PlatformData; PlatformData * platform; }; } #endif
teemid/Capstan
include/Capstan/Graphics/RenderManager.h
<reponame>teemid/Capstan #ifndef CAPSTAN_GRAPHICS_RENDER_MANAGER_H #define CAPSTAN_GRAPHICS_RENDER_MANAGER_H #include "Capstan/Graphics/Renderer.h" namespace Capstan { namespace Graphics { class RenderManager { public: RenderManager (void); ~RenderManager (void); void StartUp (void); void ShutDown (void); void Render (void); private: Renderer * renderer; }; } } #endif
teemid/Capstan
include/Capstan/Platform/Clock.h
<gh_stars>0 #ifndef CAPSTAN_CLOCK_H #define CAPSTAN_CLOCK_H #include "Capstan/Types.h" namespace Capstan { namespace Platform { Real64 GetPeriod (void); Real64 GetTime (void); } } #endif
teemid/Capstan
include/Capstan/Platform/Assert.h
#ifndef CAPSTAN_ASSERT_H #define CAPSTAN_ASSERT_H #ifdef _WIN32 #include <intrin.h> #define HALT() __debugbreak() #else #define HALT() __asm { int 3 } #endif END #ifdef _WIN32 #ifdef CAPSTAN_ASSERT namespace Capstan { void ReportAssertFailure (char * msg, char * filename, int linenumber); } #include <cstdlib> #include <cstdio> #define Assert(expression, message, ...) \ if (!expression) \ { \ printf("Expression: %s failed at %s: %i", #expression, __FILE__, __LINE__); \ printf(message, __VA_ARGS__); \ \ HALT(); \ } \ else { } #else #define assert(expr) #endif // END #ifdef CAPSTAN_ASSERT #endif // CAPSTAN_ASSERT_H
teemid/Capstan
include/Capstan/BitmapFile.h
<gh_stars>0 #ifndef CAPSTAN_BITMAP_H #define CAPSTAN_BITMAP_H #include "Capstan/Types.h" namespace Capstan { enum class Compression : UInt32 { RGB = 0x1, BITFIELDS = 0x3 }; #pragma pack(push, 1) struct BitmapCoreHeader { char signature[2]; Int32 fileSize; Int16 reserved[2]; Int32 pixelArrayOffset; }; struct BitmapInfoHeader { UInt32 headerSize; Int32 width; Int32 height; Int16 planes; Int16 bitsPerPixel; Compression compression; UInt32 imageSize; Int32 xPixelsPerMeter; Int32 yPixelsPerMeter; UInt32 colorIndexCount; UInt32 requiredColorIndexes; }; struct BitmapInfoV5Header { UInt32 headerSize; Int32 width; Int32 height; Int16 planes; Int16 bitsPerPixel; UInt32 compression; UInt32 imageSize; Int32 xPixelsPerMeter; Int32 yPixelsPerMeter; UInt32 colorIndexCount; UInt32 requiredColorIndexes; UInt32 redChannelBitMask; UInt32 greenChannelBitMask; UInt32 blueChannelBitMask; UInt32 alphaChannelBitMask; UInt32 ColorSpaceType; // NOTE (Emil): CIE Triple, Each CIE is a (x,y,z) point in CIE colorspace. Int32 CIEEndpoints[9]; // NOTE (Emil): Red, Green, and Blue gamma channels UInt32 gamma[3]; UInt32 intent; UInt32 profileData; UInt32 profileSize; UInt32 reserved; }; #pragma pack(pop) } #endif
teemid/Capstan
include/Capstan/Math/Trigonometric.h
#ifndef CAPSTAN_MATH_TRIGONOMETRIC_H #define CAPSTAN_MATH_TRIGONOMETRIC_H #include "Math/Constants.h" #include "Platform/Types.h" namespace Capstan { namespace Math { inline Real32 ToRadians (Real32 degrees) { return (degrees / 360.0f) * TWO_PI; } inline Real32 ToDegrees (Real32 radians) { return (radians / TWO_PI) * 360.0f; } } } #endif
teemid/Capstan
include/Capstan/Platform/Intrinsics.h
#ifndef CAPSTAN_PLATFORM_INTRINSICS #define CAPSTAN_PLATFORM_INTRINSICS #if defined(_MSC_VER) #include <intrin.h> #endif #include <cmath> #include "Capstan/Types.h" namespace Capstan { inline Real32 Sin (Real32 angle) { return sinf(angle); } inline Real32 Cos (Real32 angle) { return cosf(angle); } inline Real32 Tan (Real32 angle) { return tanf(angle); } inline Real32 Atan2 (Real32 r1, Real32 r2) { return atan2f(r1, r2); } inline Real32 SquareRoot (Real32 r) { return sqrtf(r); } inline Real32 Power(Real32 base, Real32 exponent) { return powf(base, exponent); } inline Real32 Ln (Real32 r) { return logf(r); } inline Real32 Log (Real32 r) { return log10f(r); } inline Real32 Exponential (Real32 r) { return expf(r); } } #endif
teemid/Capstan
include/Capstan/Types.h
<reponame>teemid/Capstan #ifndef CAPSTAN_TYPES_H #define CAPSTAN_TYPES_H #include <cstdint> typedef uint8_t Byte; typedef uint8_t UInt8; typedef uint16_t UInt16; typedef uint32_t UInt32; typedef uint64_t UInt64; typedef int8_t Int8; typedef int16_t Int16; typedef int32_t Int32; typedef int64_t Int64; typedef uint64_t Size; typedef float Real32; typedef double Real64; typedef Int32 Bool32; #endif
teemid/Capstan
include/Capstan/Utils.h
#ifndef CAPSTAN_UTILS_H #define CAPSTAN_UTILS_H namespace Capstan { #define ArrayLength(array) sizeof(array) / sizeof(array[0]) #define internal static #define global extern #define KB(size) ((size) * 1024L) #define MB(size) (KB(size) * 1024L) #define GB(size) (MB(size) * 1024L) } #endif
teemid/Capstan
include/Capstan/Graphics/Renderer.h
#ifndef CAPSTAN_GRAPHICS_RENDERER_H #define CAPSTAN_GRAPHICS_RENDERER_H namespace Capstan { class Renderer { public: virtual void StartUp (void) = 0; virtual void ShutDown (void) = 0; virtual void Render (void) = 0; }; } #endif
teemid/Capstan
include/Capstan/Sound/SoundManager.h
#ifndef CAPSTAN_SOUNDMANAGER_H #define CAPSTAN_SOUNDMANAGER_H namespace Capstan { class SoundManager { public: SoundManager (void); ~SoundManager (void); void StartUp (void); void ShutDown (void); }; } #endif
teemid/Capstan
include/Capstan/Graphics/Software/SoftwareRenderer.h
#ifndef CAPSTAN_GRAPHICS_SOFTWARE_H #define CAPSTAN_GRAPHICS_SOFTWARE_H #include "Capstan/Graphics/Renderer.h" namespace Capstan { namespace Graphics { class SoftwareRenderer : public Capstan::Renderer { public: SoftwareRenderer (void); ~SoftwareRenderer (void); void StartUp (void) override; void ShutDown (void) override; void Render (void) override; }; } } #endif
teemid/Capstan
include/Capstan/ECS/Components/CircleCollider2D.h
<gh_stars>0 #ifndef CAPSTAN_CIRCLE_COLLIDER_2D_H #define CAPSTAN_CIRCLE_COLLIDER_2D_H #include "Capstan/ECS/Components/Collider2D.h" #include "Capstan/Math/Vector2f.h" #include "Capstan/Common.h" namespace Capstan { namespace ECS { struct CircleCollider2D : Collider2D { Vector2f center; Real32 radius; }; } } #endif
teemid/Capstan
include/Capstan/MemoryManager.h
<reponame>teemid/Capstan #ifndef CAPSTAN_MEMORY_MANAGER_H #define CAPSTAN_MEMORY_MANAGER_H #include "Capstan/Types.h" namespace Capstan { enum class ManagerType { StackAllocator, DoubleStackAllocator, PoolAllocator }; class MemoryManager { public: MemoryManager (); ~MemoryManager (); void StartUp (UInt64 reserveSize); void ShutDown (void); void * Allocate (UInt64 size); Bool32 Free (void * memory); private: void * top; void * current; void * end; void * start; }; } #endif
teemid/Capstan
include/Capstan/Globals.h
<gh_stars>0 #ifndef CAPSTAN_GLOBALS_H #define CAPSTAN_GLOBALS_H #include "Capstan/AssetManager.h" #include "Capstan/InputManager.h" #include "Capstan/MemoryManager.h" #include "Capstan/Timer.h" #include "Capstan/Graphics/RenderManager.h" #include "Capstan/Platform/FileSystem.h" namespace Capstan { namespace Platform { struct PlatformData; } extern AssetManager gAssetManager; extern FileSystem gFileSystem; extern InputManager gInputManager; extern MemoryManager gMemoryManager; extern Graphics::RenderManager gRenderManager; extern Timer gTimer; extern Platform::PlatformData gPlatformData; } #endif
teemid/Capstan
include/Capstan/Timer.h
<reponame>teemid/Capstan #ifndef CAPSTAN_TIMER_H #define CAPSTAN_TIMER_H #include "Capstan/Types.h" namespace Capstan { class Timer { public: Timer (void); ~Timer (void); void StartUp (void); void ShutDown (void); void Step (void); Real64 GetDelta (void); private: Real64 current; Real64 previous; Real64 delta; // Frames UInt32 frames; }; } #endif
teemid/Capstan
include/Capstan/Strings.h
<reponame>teemid/Capstan #ifndef CAPSTAN_STRINGS_H #define CAPSTAN_STRINGS_H #include "Capstan/Types.h" namespace Capstan { namespace String { Bool32 Compare (const char * s1, const char * s2); Bool32 Compare (const char * s1, const char * s2, UInt32 lenght = 0); Bool32 Find (const char * string, const char * pattern); char ** Split (char * string, const char delimiter); } } #endif
teemid/Capstan
include/Capstan/Graphics/OpenGL/OpenGL.h
#ifndef CAPSTAN_GRAPHICS_OPENGL_H #define CAPSTAN_GRAPHICS_OPENGL_H #include "gl/glcorearb.h" #include "Capstan/Graphics/Renderer.h" #define CAPSTAN_GL(type, name) extern type name; #include "Capstan/Graphics/OpenGL/Functions.def" namespace Capstan { namespace Graphics { class Shader; class OpenGL : public Capstan::Renderer { public: explicit OpenGL (void); ~OpenGL (void); void StartUp (void) override; void ShutDown (void) override; void Render (void) override; private: Shader * shader; }; } } #endif
teemid/Capstan
include/Capstan/Platform/Memory.h
#ifndef CAPSTAN_PLATFORM_MEMORY_H #define CAPSTAN_PLATFORM_MEMORY_H #include "Capstan/Types.h" namespace Capstan { namespace Memory { void * Allocate(Size size); void * Reallocate(void * memory, Size prevSize, Size newSize); void Copy (void * source, void * destination, Size size); void Zero (void * memory, Size size); Bool32 Free (void * memory); } } #endif
teemid/Capstan
include/Capstan/ECS/Components.h
<reponame>teemid/Capstan<gh_stars>0 #ifndef CAPSTAN_ECS_COMPONENTS_H #define CAPSTAN_ECS_COMPONENTS_H namespace Capstan { namespace ECS { enum class ComponentType { BoxCollider2D, Sprite }; } } #endif
teemid/Capstan
include/Capstan/InputManager.h
<reponame>teemid/Capstan #ifndef CAPSTAN_INPUT_MANAGER_H #define CAPSTAN_INPUT_MANAGER_H namespace Capstan { class InputManager { public: InputManager (void); ~InputManager (void); void StartUp (void); void ShutDown (void); }; } #endif
teemid/Capstan
include/Capstan/ECS/Components/Collider2D.h
<reponame>teemid/Capstan #ifndef CAPSTAN_ECS_COMPONENT_COLLIDER_2D_H #define CAPSTAN_ECS_COMPONENT_COLLIDER_2D_H namespace Capstan { namespace ECS { namespace Collider2DType { Box, Circle }; struct Collider2D { Collider2DType type; }; } } #endif
teemid/Capstan
include/Capstan/Platform/Debug.h
<gh_stars>0 #ifndef CAPSTAN_DEBUG_H #define CAPSTAN_DEBUG_H #include <cstdio> namespace Capstan { namespace Debug { #ifdef CAPSTAN_DEBUG void Print (char * formattedString, ...); #endif } } #endif
FPGA-Research-Manchester/nextpnr-fabulous
fabulous/arch.h
/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #ifndef NEXTPNR_H #error Include "arch.h" via "nextpnr.h" only. #endif #include <boost/container/flat_map.hpp> #include <boost/algorithm/string/replace.hpp> NEXTPNR_NAMESPACE_BEGIN struct ChipInfo { ChipInfo(BaseCtx *ctx); ChipInfo() = delete; typedef unsigned TileId; std::vector<IdString> tile_to_name; std::vector<std::pair<int,int>> tile_to_xy; std::vector<TileId> bel_to_tile; std::vector<IdString> bel_to_name; std::unordered_map<IdString, int> bel_by_name; std::vector<IdString> bel_to_type; std::vector<Loc> bel_to_loc; std::vector<boost::container::flat_map<IdString,WireId>> bel_to_pin_wire; int num_bels; //std::vector<BelId> site_index_to_bel; //std::vector<IdString> site_index_to_type; //std::vector<Loc> bel_to_loc; //std::unordered_map<Segments::SegmentReference, WireId> segment_to_wire; //std::unordered_map<Tilewire, WireId> trivial_to_wire; std::vector<IdString> wire_to_name; std::vector<TileId> wire_to_tile; int num_wires; //std::vector<DelayInfo> wire_to_delay; //std::vector<std::vector<int>> wire_to_pips_uphill; std::vector<std::vector<PipId>> wire_to_pips_downhill; //std::vector<Arc> pip_to_arc; //std::vector<TileId> pip_to_tile; std::vector<std::pair<WireId,WireId>> pip_to_src_dst; int num_pips; int width; int height; //std::vector<bool> wire_is_global; //std::vector<std::pair<int,int>> tile_to_xy; std::vector<std::string> pip_to_txt; std::vector<DelayInfo> pip_to_delay; }; extern std::unique_ptr<const ChipInfo> chip_info; struct BelIterator { int cursor; BelIterator operator++() { cursor++; return *this; } BelIterator operator++(int) { BelIterator prior(*this); cursor++; return prior; } bool operator!=(const BelIterator &other) const { return cursor != other.cursor; } bool operator==(const BelIterator &other) const { return cursor == other.cursor; } BelId operator*() const { BelId ret; ret.index = cursor; return ret; } }; struct BelRange { BelIterator b, e; BelIterator begin() const { return b; } BelIterator end() const { return e; } }; // ----------------------------------------------------------------------- struct BelPinIterator { const BelId bel; //Array<const WireIndex>::iterator it; void operator++() { /*it++;*/ } bool operator!=(const BelPinIterator &other) const { return /*it != other.it &&*/ bel != other.bel; } BelPin operator*() const { BelPin ret; ret.bel = bel; ret.pin = IdString(); return ret; } }; struct BelPinRange { BelPinIterator b, e; BelPinIterator begin() const { return b; } BelPinIterator end() const { return e; } }; // ----------------------------------------------------------------------- struct WireIterator { int cursor = -1; void operator++() { cursor++; } bool operator!=(const WireIterator &other) const { return cursor != other.cursor; } WireId operator*() const { WireId ret; ret.index = cursor; return ret; } }; struct WireRange { WireIterator b, e; WireIterator begin() const { return b; } WireIterator end() const { return e; } }; // ----------------------------------------------------------------------- struct AllPipIterator { int cursor = -1; void operator++() { cursor++; } bool operator!=(const AllPipIterator &other) const { return cursor != other.cursor; } PipId operator*() const { PipId ret; ret.index = cursor; return ret; } }; struct AllPipRange { AllPipIterator b, e; AllPipIterator begin() const { return b; } AllPipIterator end() const { return e; } }; // ----------------------------------------------------------------------- struct PipIterator { const PipId *cursor = nullptr; void operator++() { cursor++; } bool operator!=(const PipIterator &other) const { return cursor != other.cursor; } PipId operator*() const { return *cursor; } }; struct PipRange { PipIterator b, e; PipIterator begin() const { return b; } PipIterator end() const { return e; } }; struct ArchArgs { enum ArchArgsTypes { NONE, Z020, VX980 } type = NONE; std::string package; }; struct Arch : BaseCtx { int width; int height; mutable std::unordered_map<IdString, int> wire_by_name; mutable std::unordered_map<IdString, int> pip_by_name; mutable std::unordered_map<Loc, BelId> bel_by_loc; // std::vector<bool> bel_carry; std::vector<CellInfo *> bel_to_cell; std::vector<NetInfo *> wire_to_net; std::vector<NetInfo *> pip_to_net; // std::vector<NetInfo *> switches_locked; ArchArgs args; Arch(ArchArgs args); std::string getChipName() const; IdString archId() const { return id("fabulous"); } ArchArgs archArgs() const { return args; } IdString archArgsToId(ArchArgs args) const; // ------------------------------------------------- int getGridDimX() const { return width; } int getGridDimY() const { return height; } int getTileBelDimZ(int, int) const { return 8; } int getTilePipDimZ(int, int) const { return 1; } // ------------------------------------------------- BelId getBelByName(IdString name) const; IdString getBelName(BelId bel) const { NPNR_ASSERT(bel != BelId()); std::stringstream bel_name; bel_name << chip_info->tile_to_name[chip_info->bel_to_tile[bel.index]].str(this); bel_name << "."; bel_name << chip_info->bel_to_name[bel.index].str(this); return id(bel_name.str()); } uint32_t getBelChecksum(BelId bel) const { return bel.index; } void bindBel(BelId bel, CellInfo *cell, PlaceStrength strength) { NPNR_ASSERT(bel != BelId()); NPNR_ASSERT(bel_to_cell[bel.index] == nullptr); bel_to_cell[bel.index] = cell; // bel_carry[bel.index] = (cell->type == id_ICESTORM_LC && cell->lcInfo.carryEnable); cell->bel = bel; cell->belStrength = strength; refreshUiBel(bel); } void unbindBel(BelId bel) { NPNR_ASSERT(bel != BelId()); NPNR_ASSERT(bel_to_cell[bel.index] != nullptr); bel_to_cell[bel.index]->bel = BelId(); bel_to_cell[bel.index]->belStrength = STRENGTH_NONE; bel_to_cell[bel.index] = nullptr; // bel_carry[bel.index] = false; refreshUiBel(bel); } bool checkBelAvail(BelId bel) const { NPNR_ASSERT(bel != BelId()); return bel_to_cell[bel.index] == nullptr; } CellInfo *getBoundBelCell(BelId bel) const { NPNR_ASSERT(bel != BelId()); return bel_to_cell[bel.index]; } CellInfo *getConflictingBelCell(BelId bel) const { NPNR_ASSERT(bel != BelId()); return bel_to_cell[bel.index]; } BelRange getBels() const { BelRange range; range.b.cursor = 0; range.e.cursor = chip_info->num_bels; return range; } Loc getBelLocation(BelId bel) const { return chip_info->bel_to_loc[bel.index]; } BelId getBelByLocation(Loc loc) const; BelRange getBelsByTile(int x, int y) const; bool getBelGlobalBuf(BelId bel) const { return getBelType(bel) == id_BUFGCTRL; } IdString getBelType(BelId bel) const { NPNR_ASSERT(bel != BelId()); return chip_info->bel_to_type[bel.index]; } std::vector<std::pair<IdString, std::string>> getBelAttrs(BelId bel) const; WireId getBelPinWire(BelId bel, IdString pin) const; PortType getBelPinType(BelId bel, IdString pin) const; std::vector<IdString> getBelPins(BelId bel) const; // ------------------------------------------------- WireId getWireByName(IdString name) const; IdString getWireName(WireId wire) const { NPNR_ASSERT(wire != WireId()); std::stringstream wire_name; wire_name << chip_info->tile_to_name[chip_info->wire_to_tile[wire.index]].str(this); wire_name << "."; wire_name << chip_info->wire_to_name[wire.index].str(this); return id(wire_name.str()); } IdString getWireType(WireId wire) const; std::vector<std::pair<IdString, std::string>> getWireAttrs(WireId wire) const; uint32_t getWireChecksum(WireId wire) const { return wire.index; } void bindWire(WireId wire, NetInfo *net, PlaceStrength strength) { NPNR_ASSERT(wire != WireId()); NPNR_ASSERT(wire_to_net[wire.index] == nullptr); wire_to_net[wire.index] = net; net->wires[wire].pip = PipId(); net->wires[wire].strength = strength; refreshUiWire(wire); } void unbindWire(WireId wire) { NPNR_ASSERT(wire != WireId()); NPNR_ASSERT(wire_to_net[wire.index] != nullptr); auto &net_wires = wire_to_net[wire.index]->wires; auto it = net_wires.find(wire); NPNR_ASSERT(it != net_wires.end()); auto pip = it->second.pip; if (pip != PipId()) { pip_to_net[pip.index] = nullptr; } net_wires.erase(it); wire_to_net[wire.index] = nullptr; refreshUiWire(wire); } bool checkWireAvail(WireId wire) const { NPNR_ASSERT(wire != WireId()); return wire_to_net[wire.index] == nullptr; } NetInfo *getBoundWireNet(WireId wire) const { NPNR_ASSERT(wire != WireId()); return wire_to_net[wire.index]; } WireId getConflictingWireWire(WireId wire) const { return wire; } NetInfo *getConflictingWireNet(WireId wire) const { NPNR_ASSERT(wire != WireId()); return wire_to_net[wire.index]; } DelayInfo getWireDelay(WireId wire) const { return {}; } BelPinRange getWireBelPins(WireId wire) const { BelPinRange range; // TODO return range; } WireRange getWires() const { WireRange range; range.b.cursor = 0; range.e.cursor = chip_info->num_wires; return range; } // ------------------------------------------------- PipId getPipByName(IdString name) const; void bindPip(PipId pip, NetInfo *net, PlaceStrength strength) { NPNR_ASSERT(pip != PipId()); NPNR_ASSERT(pip_to_net[pip.index] == nullptr); pip_to_net[pip.index] = net; WireId dst = getPipDstWire(pip); NPNR_ASSERT(wire_to_net[dst.index] == nullptr); wire_to_net[dst.index] = net; net->wires[dst].pip = pip; net->wires[dst].strength = strength; refreshUiPip(pip); refreshUiWire(dst); } void unbindPip(PipId pip) { NPNR_ASSERT(pip != PipId()); NPNR_ASSERT(pip_to_net[pip.index] != nullptr); WireId dst = getPipDstWire(pip); NPNR_ASSERT(wire_to_net[dst.index] != nullptr); wire_to_net[dst.index] = nullptr; pip_to_net[pip.index]->wires.erase(dst); pip_to_net[pip.index] = nullptr; refreshUiPip(pip); refreshUiWire(dst); } bool checkPipAvail(PipId pip) const { NPNR_ASSERT(pip != PipId()); return pip_to_net[pip.index] == nullptr; } NetInfo *getBoundPipNet(PipId pip) const { NPNR_ASSERT(pip != PipId()); return pip_to_net[pip.index]; } WireId getConflictingPipWire(PipId pip) const { return WireId(); } NetInfo *getConflictingPipNet(PipId pip) const { NPNR_ASSERT(pip != PipId()); return pip_to_net[pip.index]; } AllPipRange getPips() const { AllPipRange range; range.b.cursor = 0; range.e.cursor = chip_info->num_pips; return range; } Loc getPipLocation(PipId pip) const { Loc loc; NPNR_ASSERT("TODO"); return loc; } IdString getPipName(PipId pip) const; IdString getPipType(PipId pip) const { return IdString(); } std::vector<std::pair<IdString, std::string>> getPipAttrs(PipId pip) const; uint32_t getPipChecksum(PipId pip) const { return pip.index; } WireId getPipSrcWire(PipId pip) const { NPNR_ASSERT(pip != PipId()); return chip_info->pip_to_src_dst[pip.index].first; } WireId getPipDstWire(PipId pip) const { NPNR_ASSERT(pip != PipId()); return chip_info->pip_to_src_dst[pip.index].second; } DelayInfo getPipDelay(PipId pip) const { NPNR_ASSERT(pip != PipId()); return chip_info->pip_to_delay[pip.index]; } PipRange getPipsDownhill(WireId wire) const { PipRange range; NPNR_ASSERT(wire != WireId()); const auto &pips = chip_info->wire_to_pips_downhill[wire.index]; range.b.cursor = pips.data(); range.e.cursor = range.b.cursor + pips.size(); return range; } PipRange getPipsUphill(WireId wire) const { PipRange range; NPNR_ASSERT(wire != WireId()); // const auto &pips = chip_info->wire_to_pips_uphill[wire.index]; // range.b.cursor = pips.data(); // range.e.cursor = range.b.cursor + pips.size(); return range; } PipRange getWireAliases(WireId wire) const { PipRange range; NPNR_ASSERT(wire != WireId()); range.b.cursor = nullptr; range.e.cursor = nullptr; return range; } BelId getPackagePinBel(const std::string &pin) const; std::string getBelPackagePin(BelId bel) const; // ------------------------------------------------- GroupId getGroupByName(IdString name) const; IdString getGroupName(GroupId group) const; std::vector<GroupId> getGroups() const; std::vector<BelId> getGroupBels(GroupId group) const; std::vector<WireId> getGroupWires(GroupId group) const; std::vector<PipId> getGroupPips(GroupId group) const; std::vector<GroupId> getGroupGroups(GroupId group) const; // ------------------------------------------------- delay_t estimateDelay(WireId src, WireId dst) const; delay_t predictDelay(const NetInfo *net_info, const PortRef &sink) const; delay_t getDelayEpsilon() const { return 20; } delay_t getRipupDelayPenalty() const { return 200; } float getDelayNS(delay_t v) const { return v * 0.001; } DelayInfo getDelayFromNS(float ns) const { DelayInfo del; del.delay = delay_t(ns * 1000); return del; } uint32_t getDelayChecksum(delay_t v) const { return v; } bool getBudgetOverride(const NetInfo *net_info, const PortRef &sink, delay_t &budget) const; // ------------------------------------------------- bool pack(); bool place(); bool route(); // ------------------------------------------------- std::vector<GraphicElement> getDecalGraphics(DecalId decal) const; DecalXY getBelDecal(BelId bel) const; DecalXY getWireDecal(WireId wire) const; DecalXY getPipDecal(PipId pip) const; DecalXY getGroupDecal(GroupId group) const; // ------------------------------------------------- // Get the delay through a cell from one port to another, returning false // if no path exists bool getCellDelay(const CellInfo *cell, IdString fromPort, IdString toPort, DelayInfo &delay) const; // Get the port class, also setting clockDomain if applicable TimingPortClass getPortTimingClass(const CellInfo *cell, IdString port, int &clockInfoCount) const; // Get the TimingClockingInfo of a port TimingClockingInfo getPortClockingInfo(const CellInfo *cell, IdString port, int index) const; // Return true if a port is a net bool isGlobalNet(const NetInfo *net) const; // ------------------------------------------------- // Perform placement validity checks, returning false on failure (all // implemented in arch_place.cc) // Whether or not a given cell can be placed at a given Bel // This is not intended for Bel type checks, but finer-grained constraints // such as conflicting set/reset signals, etc bool isValidBelForCell(CellInfo *cell, BelId bel) const; // Return true whether all Bels at a given location are valid bool isBelLocationValid(BelId bel) const; // Helper function for above bool logicCellsCompatible(const CellInfo **it, const size_t size) const; // ------------------------------------------------- // Assign architecure-specific arguments to nets and cells, which must be // called between packing or further // netlist modifications, and validity checks void assignArchInfo(); void assignCellInfo(CellInfo *cell); // ------------------------------------------------- BelPin getIOBSharingPLLPin(BelId pll, IdString pll_pin) const { auto wire = getBelPinWire(pll, pll_pin); for (auto src_bel : getWireBelPins(wire)) { if (getBelType(src_bel.bel) == id_SB_IO && src_bel.pin == id_D_IN_0) { return src_bel; } } NPNR_ASSERT_FALSE("Expected PLL pin to share an output with an SB_IO D_IN_{0,1}"); } float placer_constraintWeight = 10; }; NEXTPNR_NAMESPACE_END
FPGA-Research-Manchester/nextpnr-fabulous
xc7/cells.h
/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 <NAME> <<EMAIL>> * Copyright (C) 2018 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "nextpnr.h" #ifndef ICE40_CELLS_H #define ICE40_CELLS_H NEXTPNR_NAMESPACE_BEGIN // Create a standard xc7 cell and return it // Name will be automatically assigned if not specified std::unique_ptr<CellInfo> create_xc7_cell(Context *ctx, IdString type, std::string name = ""); // Return true if a cell is a LUT inline bool is_lut(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == id_LUT1 || cell->type == id_LUT2 || cell->type == id_LUT3 || cell->type == id_LUT4 || cell->type == id_LUT5 || cell->type == id_LUT6; } // Return true if a cell is a flipflop inline bool is_ff(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == id_FDRE || cell->type == id_FDSE || cell->type == id_FDCE || cell->type == id_FDPE; } inline bool is_carry(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == ctx->id("SB_CARRY"); } inline bool is_lc(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == ctx->id("XC7_LC"); } // Return true if a cell is a SB_IO inline bool is_sb_io(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == ctx->id("SB_IO"); } // Return true if a cell is a global buffer inline bool is_gbuf(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == id_BUFGCTRL; } // Return true if a cell is a RAM inline bool is_ram(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == ctx->id("SB_RAM40_4K") || cell->type == ctx->id("SB_RAM40_4KNR") || cell->type == ctx->id("SB_RAM40_4KNW") || cell->type == ctx->id("SB_RAM40_4KNRNW"); } inline bool is_sb_lfosc(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == ctx->id("SB_LFOSC"); } inline bool is_sb_hfosc(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == ctx->id("SB_HFOSC"); } inline bool is_sb_spram(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == ctx->id("SB_SPRAM256KA"); } inline bool is_sb_mac16(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == ctx->id("SB_MAC16"); } inline bool is_sb_pll40(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == ctx->id("SB_PLL40_PAD") || cell->type == ctx->id("SB_PLL40_2_PAD") || cell->type == ctx->id("SB_PLL40_2F_PAD") || cell->type == ctx->id("SB_PLL40_CORE") || cell->type == ctx->id("SB_PLL40_2F_CORE"); } inline bool is_sb_pll40_pad(const BaseCtx *ctx, const CellInfo *cell) { return cell->type == ctx->id("SB_PLL40_PAD") || cell->type == ctx->id("SB_PLL40_2_PAD") || cell->type == ctx->id("SB_PLL40_2F_PAD"); } uint8_t sb_pll40_type(const BaseCtx *ctx, const CellInfo *cell); // Convert a SB_LUT primitive to (part of) an ICESTORM_LC, swapping ports // as needed. Set no_dff if a DFF is not being used, so that the output // can be reconnected void lut_to_lc(const Context *ctx, CellInfo *lut, CellInfo *lc, bool no_dff = true); // Convert a SB_DFFx primitive to (part of) an ICESTORM_LC, setting parameters // and reconnecting signals as necessary. If pass_thru_lut is True, the LUT will // be configured as pass through and D connected to I0, otherwise D will be // ignored void dff_to_lc(const Context *ctx, CellInfo *dff, CellInfo *lc, bool pass_thru_lut = false); // Convert a nextpnr IO buffer to a SB_IO void nxio_to_sb(Context *ctx, CellInfo *nxio, CellInfo *sbio); // Return true if a port is a clock port bool is_clock_port(const BaseCtx *ctx, const PortRef &port); // Return true if a port is a reset port bool is_reset_port(const BaseCtx *ctx, const PortRef &port); // Return true if a port is a clock enable port bool is_enable_port(const BaseCtx *ctx, const PortRef &port); NEXTPNR_NAMESPACE_END #endif
FPGA-Research-Manchester/nextpnr-fabulous
xc7/gfx.h
/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #ifndef GFX_H #define GFX_H #include "nextpnr.h" NEXTPNR_NAMESPACE_BEGIN const float main_swbox_x1 = 0.35; const float main_swbox_x2 = 0.60; const float main_swbox_y1 = 0.05; const float main_swbox_y2 = 0.73; const float local_swbox_x1 = 0.63; const float local_swbox_x2 = 0.73; const float local_swbox_y1 = 0.05; const float local_swbox_y2 = 0.55; const float lut_swbox_x1 = 0.76; const float lut_swbox_x2 = 0.80; const float logic_cell_x1 = 0.83; const float logic_cell_x2 = 0.95; const float logic_cell_y1 = 0.05; const float logic_cell_y2 = 0.10; const float logic_cell_pitch = 0.0625; NEXTPNR_NAMESPACE_END #endif // GFX_H