id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,534,113
|
terminaldialog.h
|
MiyooCFW_gmenu2x/src/terminaldialog.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef TERMINALDIALOG_H_
#define TERMINALDIALOG_H_
#include <string>
#include "gmenu2x.h"
#include "textdialog.h"
using std::string;
using std::vector;
class TerminalDialog : protected TextDialog {
public:
TerminalDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon, const string &backdrop = "");
void exec(string cmd);
void preProcess() { };
};
#endif /*TERMINALDIALOG_H_*/
| 1,828
|
C++
|
.h
| 33
| 53.606061
| 131
| 0.510056
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,114
|
menusettingfile.h
|
MiyooCFW_gmenu2x/src/menusettingfile.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MENUSETTINGFILE_H
#define MENUSETTINGFILE_H
#include "menusettingstringbase.h"
class MenuSettingFile : public MenuSettingStringBase {
protected:
virtual void edit();
std::string filter, startPath, dialogTitle, dialogIcon;
public:
MenuSettingFile(GMenu2X *gmenu2x, const std::string &title, const std::string &description, std::string *value, const std::string &filter, const std::string &startPath, const std::string &dialogTitle, const std::string &dialogIcon);
virtual ~MenuSettingFile() {}
};
#endif
| 1,924
|
C++
|
.h
| 31
| 60.193548
| 233
| 0.53125
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,115
|
debug.h
|
MiyooCFW_gmenu2x/src/debug.h
|
#ifndef DEBUG_H
#define DEBUG_H
#define NODEBUG_L 0
#define ERROR_L 1
#define WARNING_L 2
#define INFO_L 3
#define DEBUG_L 4
#ifndef LOG_LEVEL
#define LOG_LEVEL INFO_L
#endif
#ifndef DEBUG_START
#define DEBUG_START "\e[1;34m"
#endif
#ifndef WARNING_START
#define WARNING_START "\e[1;33m"
#endif
#ifndef ERROR_START
#define ERROR_START "\e[1;31m"
#endif
#ifndef INFO_START
#define INFO_START "\e[1;32m"
#endif
#define LOG_END "\e[00m\n"
#define D(str, ...) \
fprintf(stdout, DEBUG_START "%s:%d %s: " str LOG_END, __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#if (LOG_LEVEL >= DEBUG_L)
#define DEBUG(str, ...) \
fprintf(stdout, DEBUG_START str LOG_END, ##__VA_ARGS__)
#endif
#if (LOG_LEVEL >= INFO_L)
#define INFO(str, ...) \
fprintf(stdout, INFO_START str LOG_END, ##__VA_ARGS__)
#endif
#if (LOG_LEVEL >= WARNING_L)
#define WARNING(str, ...) \
fprintf(stderr, WARNING_START str LOG_END, ##__VA_ARGS__)
#endif
#if (LOG_LEVEL >= ERROR_L)
#define ERROR(str, ...) \
fprintf(stderr, ERROR_START str LOG_END, ##__VA_ARGS__)
#endif
#ifndef DEBUG
#define DEBUG(...)
#endif
#ifndef WARNING
#define WARNING(...)
#endif
#ifndef ERROR
#define ERROR(...)
#endif
#ifndef INFO
#define INFO(...)
#endif
#endif // DEBUG_H
| 1,239
|
C++
|
.h
| 54
| 21.37037
| 100
| 0.679181
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,116
|
utilities.h
|
MiyooCFW_gmenu2x/src/utilities.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef UTILITIES_H
#define UTILITIES_H
#ifndef PATH_MAX
#define PATH_MAX 2048
#endif
#include <string>
#include <sstream>
#include <vector>
#include <tr1/unordered_map>
#include <unistd.h>
#include <sys/statvfs.h>
using std::tr1::unordered_map;
using std::tr1::hash;
using std::string;
using std::vector;
using std::stringstream;
class case_less {
public:
bool operator()(const string &left, const string &right) const;
};
string trim(const string& s);
string strreplace (string orig, const string &search, const string &replace);
string cmdclean (string cmdline);
char *string_copy(const string &);
void string_copy(const string &, char **);
bool file_exists(const string &path);
bool dir_exists(const string &path);
bool rmtree(string path);
int max(int a, int b);
int min(int a, int b);
int constrain(int x, int imin, int imax);
int evalIntConf(int val, int def, int imin, int imax);
int evalIntConf(int *val, int def, int imin, int imax);
const string &evalStrConf(const string &val, const string &def);
const string &evalStrConf(string *val, const string &def);
float max(float a, float b);
float min(float a, float b);
float constrain(float x, float imin, float imax);
bool split(vector<string> &vec, const string &str, const string &delim, bool destructive=true);
int intTransition(int from, int to, int32_t tickStart, int32_t duration = 500, int32_t tickNow = -1);
string exec(const char* cmd);
string real_path(const string &path);
string dir_name(const string &path);
string base_name(string path, bool strip_extension = false);
string file_ext(const string &path, bool tolower = false);
string file_read(const string &path);
string lowercase(string s);
string unique_filename(string path, string ext);
string exe_path();
string disk_free(const char *path);
const string get_date_time();
void sync_date_time(time_t t);
void init_date_time();
void build_date_time();
void set_date_time(const char* timestamp);
bool file_copy(const string &src, const string &dst);
#endif
| 3,403
|
C++
|
.h
| 76
| 43.302632
| 101
| 0.625378
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,117
|
imageviewerdialog.h
|
MiyooCFW_gmenu2x/src/imageviewerdialog.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef IMAGEVIEWERDIALOG_H_
#define IMAGEVIEWERDIALOG_H_
#include <string>
#include <fstream>
#include "gmenu2x.h"
#include "dialog.h"
using namespace std;
using std::string;
using std::vector;
using std::ifstream;
using std::ios_base;
class ImageViewerDialog : protected Dialog {
protected:
string path;
public:
ImageViewerDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon = "icons/ebook.png", const string &path = "");
void exec();
};
#endif /*IMAGEVIEWERDIALOG_H_*/
| 1,926
|
C++
|
.h
| 38
| 48.947368
| 150
| 0.524721
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,118
|
menu.h
|
MiyooCFW_gmenu2x/src/menu.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MENU_H
#define MENU_H
#include <string>
#include <vector>
#include "link.h"
using std::string;
using std::vector;
class LinkApp;
class GMenu2X;
typedef vector<Link*> linklist;
/**
Handles the menu structure
@author Massimiliano Torromeo <massimiliano.torromeo@gmail.com>
*/
class Menu {
private:
GMenu2X *gmenu2x;
int iSection, iLink;
int32_t iFirstDispSection, iFirstDispRow;
vector<string> sections;
vector<linklist> links;
const int iconPadding = 4;
uint32_t section_changed, icon_changed;
Surface *iconSD, *iconManual, *iconCPU, *iconMenu, *iconL, *iconR, *iconBGoff, *iconBGon;
Surface *sectionBackdrop, *sectionBackdropGeneric;
Surface *iconBrightness[6], *iconBattery[7], *iconVolume[3];
int8_t brightnessIcon = 5;
string iconDescription = "";
string iconTitle = "";
string readSection = "";
SDL_TimerID sectionChangedTimer, iconChangedTimer;
void freeLinks();
void drawList();
void drawGrid();
void drawSectionBar();
void drawStatusBar();
void drawIconTray();
public:
Menu(GMenu2X *gmenu2x);
~Menu();
uint32_t linkCols, linkRows, linkWidth, linkHeight, linkSpacing = 4;
linklist *sectionLinks(int i = -1);
int selSectionIndex();
int sectionNumItems();
const string &selSection();
const string selSectionName();
void decSectionIndex();
void incSectionIndex();
void setSectionIndex(int i);
uint32_t firstDispSection();
uint32_t firstDispRow();
void readSections();
void readLinks();
bool addActionLink(uint32_t section, const string &title, fastdelegate::FastDelegate0<> action, const string &description="", const string &icon="");
bool addLink(string exec);
bool addSection(const string §ionName);
void deleteSelectedLink();
void deleteSelectedSection();
bool allyRead = false;
void loadIcons();
bool linkChangeSection(uint32_t linkIndex, uint32_t oldSectionIndex, uint32_t newSectionIndex);
int selLinkIndex();
Link *selLink();
LinkApp *selLinkApp();
void pageUp();
void pageDown();
void linkLeft();
void linkRight();
void linkUp();
void linkDown();
void setLinkIndex(int i);
string sectionPath(int section = -1);
const vector<string> &getSections() { return sections; }
void renameSection(int index, const string &name);
int getSectionIndex(const string &name);
const string getSectionIcon(int i = -1);
void initLayout();
void exec();
};
#endif
| 3,757
|
C++
|
.h
| 99
| 35.89899
| 150
| 0.641717
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,119
|
gmenu2x.h
|
MiyooCFW_gmenu2x/src/gmenu2x.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef GMENU2X_H
#define GMENU2X_H
class PowerManager;
#include <iostream>
#include <string>
#include <vector>
#include <tr1/unordered_map>
#include "surfacecollection.h"
#include "iconbutton.h"
#include "translator.h"
#include "FastDelegate.h"
#include "utilities.h"
#include "touchscreen.h"
#include "inputmanager.h"
#include "surface.h"
#include "fonthelper.h"
#include "debug.h"
// Note: Keep this in sync with colorNames!
enum color {
COLOR_TOP_BAR_BG,
COLOR_LIST_BG,
COLOR_BOTTOM_BAR_BG,
COLOR_SELECTION_BG,
COLOR_PREVIEW_BG,
COLOR_MESSAGE_BOX_BG,
COLOR_MESSAGE_BOX_BORDER,
COLOR_MESSAGE_BOX_SELECTION,
COLOR_FONT,
COLOR_FONT_OUTLINE,
COLOR_FONT_ALT,
COLOR_FONT_ALT_OUTLINE,
NUM_COLORS,
};
enum sb {
SB_OFF,
SB_LEFT,
SB_BOTTOM,
SB_RIGHT,
SB_TOP,
SB_CLASSIC,
};
enum sbak {
SBAK_OFF,
SBAK_LINK,
SBAK_EXEC,
};
enum bd {
BD_OFF,
BD_MENU,
BD_DIALOG,
};
enum tvout {
TV_OFF,
TV_PAL,
TV_NTSC,
};
using std::string;
using std::vector;
using fastdelegate::FastDelegate0;
extern uint16_t mmcPrev, mmcStatus;
extern uint16_t udcPrev, udcStatus;
extern uint16_t tvOutPrev, tvOutStatus;
extern uint16_t volumeModePrev, volumeMode;
extern uint16_t batteryIcon;
extern uint8_t numJoyPrev, numJoy; // number of connected joysticks
extern int CPU_MENU;
extern int CPU_LINK;
extern int CPU_MAX;
extern int CPU_MIN;
extern int CPU_STEP;
extern int LAYOUT_VERSION;
extern int LAYOUT_VERSION_MAX;
extern int TEFIX;
extern int TEFIX_MAX;
extern int SLOW_GAP_TTS;
extern int SLOW_SPEED_TTS;
extern int MEDIUM_GAP_TTS;
extern int MEDIUM_SPEED_TTS;
extern int FAST_GAP_TTS;
extern int FAST_SPEED_TTS;
extern string VOICE_TTS;
typedef FastDelegate0<> MenuAction;
typedef unordered_map<string, string, hash<string> > ConfStrHash;
typedef unordered_map<string, int, hash<string> > ConfIntHash;
struct MenuOption {
string text;
MenuAction action;
};
class Menu;
class GMenu2X {
private:
string lastSelectorDir;
int lastSelectorElement;
void explorer();
void readConfig();
bool readTmp();
void initFont(bool deffont);
void umountSdDialog();
void opkInstall(string path);
void opkScanner();
string ipkName(string cmd);
void ipkInstall(string path);
string skinFont = "";
virtual void udcDialog(int udcStatus = -1) { };
virtual void tvOutDialog(int16_t mode = -1) { };
virtual void hwInit() { };
virtual void hwDeinit() { };
public:
static GMenu2X *instance;
/*
* Variables needed for elements disposition
*/
uint32_t w = 320, h = 240, bpp = 16;
SDL_Rect listRect, linksRect, sectionBarRect, bottomBarRect;
//Configuration hashes
ConfStrHash confStr, skinConfStr;
ConfIntHash confInt, skinConfInt;
RGBAColor skinConfColors[NUM_COLORS];
SurfaceCollection sc;
Surface *s, *bg, *iconInet = NULL;
Translator tr;
FontHelper *font = NULL, *titlefont = NULL;
PowerManager *powerManager;
InputManager input;
Touchscreen ts;
Menu *menu;
bool f200 = true; //gp2x type // touchscreen
string currBackdrop;
~GMenu2X();
void quit();
void quit_nosave();
void main(bool autoStart);
void settings();
void settings_date();
void reinit(bool showDialog = false);
void reinit_save();
void poweroffDialog();
void resetSettings();
void cpuSettings();
void showManual();
void setSkin(string skin, bool clearSC = true);
void skinMenu();
void skinColors();
uint32_t onChangeSkin() { return 1; }
bool inputCommonActions(bool &inputAction);
bool autoStart;
bool actionPerformed = false;
bool deffont = true;
void cls(Surface *s = NULL, bool flip = true);
void about();
void viewLog();
void viewAutoStart();
void contextMenu();
void changeWallpaper();
void changeSelectorDir();
bool saveScreenshot(string path);
void drawSlider(int val, int min, int max, Surface &icon, Surface &bg);
void setInputSpeed();
void writeConfig();
void writeSkinConfig();
void writeTmp(int selelem = -1, const string &selectordir = "");
void initMenu();
void addLink();
void editLink();
void deleteLink();
void addSection();
void renameSection();
void deleteSection();
void allyTTS(const char* text);
void allyTTS(const char* file, int gap, int speed);
void allyTTS(const char* text, int gap, int speed, bool wait);
string setBackground(Surface *bg, string wallpaper);
int drawButton(Button *btn, int x = 5, int y = -8);
int drawButton(Surface *s, const string &btn, const string &text = "", int x = 5, int y = -8);
int drawButtonRight(Surface *s, const string &btn, const string &text = "", int x = 5, int y = -8);
void drawScrollBar(uint32_t pagesize, uint32_t totalsize, uint32_t pagepos, SDL_Rect scrollRect, const uint8_t align = HAlignRight);
static uint32_t timerFlip(uint32_t interval, void *param = NULL);
virtual void setScaleMode(unsigned int mode) { };
virtual void setTVOut(unsigned int mode) { };
virtual void setCPU(uint32_t mhz) { };
virtual void ledOn() { };
virtual void ledOff() { };
virtual int setVolume(int val, bool popup = false);
virtual void setKbdLayout(int val) { };
virtual void setTefix(int val) { };
virtual bool isUsbConnected() { return false; };
virtual int getVolume() { return 0; };
virtual int getBacklight() { return -1; };
virtual int setBacklight(int val, bool popup = false);
virtual string hwPreLinkLaunch() { return ""; };
virtual void enableTerminal() { };
virtual void setGamma(int value) { };
};
#endif
| 6,751
|
C++
|
.h
| 213
| 29.798122
| 133
| 0.685547
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,120
|
menusettingbool.h
|
MiyooCFW_gmenu2x/src/menusettingbool.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MENUSETTINGBOOL_H
#define MENUSETTINGBOOL_H
#include "menusetting.h"
// class GMenu2X;
class MenuSettingBool : public MenuSetting {
private:
void initButton();
void toggle();
bool originalValue;
bool *_value;
int *_ivalue;
std::string strvalue;
public:
MenuSettingBool(GMenu2X *gmenu2x, const std::string &title, const std::string &description, bool *value);
MenuSettingBool(GMenu2X *gmenu2x, const std::string &title, const std::string &description, int *value);
virtual ~MenuSettingBool() {};
virtual void draw(int y);
virtual uint32_t manageInput();
virtual bool edited();
void setValue(int value);
void setValue(bool value, bool readValue);
bool value();
void current();
};
#endif
| 2,121
|
C++
|
.h
| 44
| 46.25
| 106
| 0.545191
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,121
|
menusettingstringbase.h
|
MiyooCFW_gmenu2x/src/menusettingstringbase.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MENUSETTINGSTRINGBASE_H
#define MENUSETTINGSTRINGBASE_H
#include "menusetting.h"
class MenuSettingStringBase : public MenuSetting {
protected:
std::string originalValue;
std::string *_value;
virtual void edit() = 0;
void clear();
void current();
public:
MenuSettingStringBase(
GMenu2X *gmenu2x, const std::string &title,
const std::string &description, std::string *value);
virtual ~MenuSettingStringBase();
virtual void draw(int y);
virtual uint32_t manageInput();
virtual bool edited();
void setValue(const std::string &value) { *_value = value; }
const std::string &value() { return *_value; }
};
#endif
| 2,044
|
C++
|
.h
| 41
| 47.804878
| 77
| 0.533567
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,122
|
menusettingmultistring.h
|
MiyooCFW_gmenu2x/src/menusettingmultistring.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MENUSETTINGMULTISTRING_H
#define MENUSETTINGMULTISTRING_H
#include "menusettingstringbase.h"
#include <vector>
#include "debug.h"
#include "FastDelegate.h"
using namespace fastdelegate;
using fastdelegate::MakeDelegate;
typedef FastDelegate0<uint32_t> msms_onchange_t;
typedef FastDelegate0<> msms_onselect_t;
class MenuSettingMultiString : public MenuSettingStringBase {
private:
virtual void edit() {
/* never called because manageInput() is overridden */
}
const std::vector<std::string> *choices;
int selected;
void incSel();
void decSel();
void setSel(int sel, bool readValue);
void currentSel();
msms_onchange_t onChange;
msms_onselect_t onSelect; // variable to store function pointer type
public:
MenuSettingMultiString(GMenu2X *gmenu2x, const std::string &title, const std::string &description, std::string *value, const std::vector<std::string> *choices, msms_onchange_t onChange = 0, msms_onselect_t onSelect = 0);
uint32_t voidAction() { return 0; };
virtual ~MenuSettingMultiString() {};
virtual uint32_t manageInput();
virtual void draw(int y);
};
#endif
| 2,510
|
C++
|
.h
| 50
| 48.26
| 221
| 0.586601
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,123
|
selector.h
|
MiyooCFW_gmenu2x/src/selector.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef SELECTOR_H_
#define SELECTOR_H_
#include "browsedialog.h"
#include <sstream>
using namespace std;
class LinkApp;
class Selector : public BrowseDialog {
private:
LinkApp *link;
unordered_map<string, string> aliases;
unordered_map<string, string> params;
unordered_map<string, string> previews;
void loadAliases();
void parseAliases(istream &infile);
const std::string getPreview(uint32_t i = 0);
public:
Selector(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon, LinkApp *link);
const std::string getFileName(uint32_t i = 0);
const std::string getParams(uint32_t i = 0);
void addFavorite();
void customOptions(vector<MenuOption> &options);
};
#endif /*SELECTOR_H_*/
| 2,133
|
C++
|
.h
| 42
| 48.880952
| 111
| 0.547768
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,124
|
inputdialog.h
|
MiyooCFW_gmenu2x/src/inputdialog.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef INPUTDIALOG_H_
#define INPUTDIALOG_H_
#define KEY_WIDTH 20
#define KEY_HEIGHT 20
#define KB_TOP 90
#define MAX_KB 5
#include <string>
#include "gmenu2x.h"
using std::string;
using std::vector;
typedef vector<string> stringlist;
// class InputManager;
// class Touchscreen;
class InputDialog {
protected:
GMenu2X *gmenu2x;
SDL_TimerID wakeUpTimer = NULL;
private:
enum id_actions {
ID_NO_ACTION,
ID_ACTION_SAVE,
ID_ACTION_CLOSE,
ID_ACTION_UP,
ID_ACTION_DOWN,
ID_ACTION_LEFT,
ID_ACTION_RIGHT,
ID_ACTION_BACKSPACE,
ID_ACTION_SPACE,
ID_ACTION_GOUP,
ID_ACTION_SELECT,
ID_ACTION_KB_CHANGE
};
bool customKb = false;
int selRow, selCol;
string title, text, icon;
string kb11, kb12, kb13, kb21, kb22, kb23, kb31, kb32, kb33;
string kbc11, kbc12, kbc13, kbc21, kbc22, kbc23, kbc31, kbc32, kbc33;
int16_t curKeyboard;
vector<stringlist> keyboard;
stringlist *kb;
int kbLength, kbWidth, kbHeight, kbLeft;
int bottomBarWidth = gmenu2x->w;
SDL_Rect kbRect;
IconButton *btnBackspaceX, *btnBackspaceL, *btnSpace, *btnConfirm, *btnChangeKeys;
string input;
string currKey();
bool allyRead = false;
void backspace();
void space();
void confirm();
void changeKeys();
void changeKeysCustom();
int drawVirtualKeyboard();
void setKeyboard(int);
public:
InputDialog(GMenu2X *gmenu2x, /*Touchscreen &ts,*/ const string &text, const string &startvalue = "", const string &title = "", const string &icon = "");
~InputDialog();
bool exec();
const string &getInput() { return input; }
};
#endif /*INPUTDIALOG_H_*/
| 2,969
|
C++
|
.h
| 80
| 35
| 154
| 0.595752
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,125
|
fonthelper.h
|
MiyooCFW_gmenu2x/src/fonthelper.h
|
#ifndef FONTHELPER_H
#define FONTHELPER_H
#include "surface.h"
#include <string>
#include <vector>
#include <SDL_ttf.h>
#ifdef _WIN32
typedef unsigned int uint32_t;
#endif
using std::vector;
using std::string;
class FontHelper {
private:
int height, halfHeight, fontSize;
RGBAColor textColor, outlineColor;
string fontName;
public:
FontHelper(const string &fontName, int size, RGBAColor textColor = (RGBAColor){255,255,255}, RGBAColor outlineColor = (RGBAColor){5,5,5});
~FontHelper();
bool utf8Code(uint8_t c);
void free();
void write(Surface *surface, const string &text, int x, int y, RGBAColor fgColor, RGBAColor bgColor);
void write(Surface *surface, const string &text, int x, int y, const uint8_t align = HAlignLeft | VAlignTop);
void write(Surface *surface, const string &text, int x, int y, const uint8_t align, RGBAColor fgColor, RGBAColor bgColor);
void write(Surface *surface, const string &text, SDL_Rect &wrapRect, const uint8_t align = HAlignLeft | VAlignTop);
void write(Surface *surface, vector<string> *text, int x, int y, const uint8_t align, RGBAColor fgColor, RGBAColor bgColor);
void write(Surface *surface, vector<string> *text, int x, int y, const uint8_t align = HAlignLeft | VAlignTop);
uint32_t getLineWidth(const string &text);
uint32_t getTextWidth(const string &text);
int getTextHeight(const string &text);
uint32_t getTextWidth(vector<string> *text);
uint32_t getHeight() { return height; };
uint32_t getHalfHeight() { return halfHeight; };
void loadFont(const string &fontName, int fontSize);
FontHelper *setSize(const int size);
FontHelper *setColor(RGBAColor color);
FontHelper *setOutlineColor(RGBAColor color);
TTF_Font *font, *fontOutline;
string fontFamilyName;
};
#endif /* FONTHELPER_H */
| 1,774
|
C++
|
.h
| 41
| 41.195122
| 139
| 0.764843
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,126
|
surface.h
|
MiyooCFW_gmenu2x/src/surface.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef SURFACE_H
#define SURFACE_H
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
using std::string;
using std::istream;
const uint8_t HAlignLeft = 1,
HAlignRight = 2,
HAlignCenter = 4,
VAlignTop = 8,
VAlignBottom = 16,
VAlignMiddle = 32;
const uint8_t SScaleStretch = 0,
SScaleMax = 1,
SScaleFit = 2;
class FontHelper;
struct RGBAColor {
uint8_t r,g,b,a;
// static RGBAColor fromString(std::string const& strColor);
// static string toString(RGBAColor &color);
RGBAColor() : r(0), g(0), b(0), a(0) {}
RGBAColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255)
: r(r), g(g), b(b), a(a) {}
Uint32 pixelValue(SDL_PixelFormat *fmt) const {
return SDL_MapRGBA(fmt, r, g, b, a);
}
};
RGBAColor strtorgba(const string &strColor);
string rgbatostr(RGBAColor color);
SDL_Color rgbatosdl(RGBAColor color);
/**
Wrapper around SDL_Surface
@author Massimiliano Torromeo <massimiliano.torromeo@gmail.com>
*/
class Surface {
private:
bool locked;
int halfW, halfH;
SDL_Surface *dblbuffer;
public:
Surface();
Surface(const string &img, const string &skin = "", bool alpha = true);
Surface(const string &img, bool alpha, const string &skin = "");
Surface(SDL_Surface *s, SDL_PixelFormat *fmt = NULL, uint32_t flags = 0);
Surface(Surface *s);
Surface(int w, int h, uint32_t flags = SDL_HWSURFACE | SDL_SRCALPHA);
Surface(void *s, size_t &size);
~Surface();
void enableVirtualDoubleBuffer(SDL_Surface *surface);
void enableAlpha();
SDL_Surface *raw, *screen;
void free();
void load(const string &img, bool alpha = true, string skin = "");
void lock();
void unlock();
void flip();
SDL_PixelFormat *format();
void putPixel(int,int,RGBAColor);
void putPixel(int,int,uint32_t);
RGBAColor pixelColor(int,int);
uint32_t pixel(int,int);
void blendAdd(Surface*, int,int);
void clearClipRect();
void setClipRect(SDL_Rect rect);
bool blit(Surface *destination, int x, int y, const uint8_t align = HAlignLeft | VAlignTop, uint8_t alpha = -1);
bool blit(Surface *destination, SDL_Rect destrect, const uint8_t align = HAlignLeft | VAlignTop, uint8_t alpha = -1);
void write(FontHelper *font, const string &text, SDL_Rect &wrapRect, const uint8_t align = HAlignLeft | VAlignTop);
void write(FontHelper *font, const string &text, int x, int y, const uint8_t align = HAlignLeft | VAlignTop);
void write(FontHelper *font, const string &text, int x, int y, const uint8_t align, RGBAColor fgColor, RGBAColor bgColor);
void box(SDL_Rect re, RGBAColor c);
void box(Sint16 x, Sint16 y, Uint16 w, Uint16 h, RGBAColor c) {
box((SDL_Rect){ x, y, w, h }, c);
}
void box(Sint16 x, Sint16 y, Uint16 w, Uint16 h, Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
box((SDL_Rect){ x, y, w, h }, RGBAColor(r, g, b, a));
}
/** Draws the given rectangle on this surface in the given color, blended
* according to the alpha value of the color argument.
*/
void fillRectAlpha(SDL_Rect rect, RGBAColor c);
/** Clips the given rectangle against this surface's active clipping
* rectangle.
*/
void applyClipRect(SDL_Rect& rect);
void rectangle(SDL_Rect re, RGBAColor c);
void rectangle(Sint16 x, Sint16 y, Uint16 w, Uint16 h, RGBAColor c) {
rectangle((SDL_Rect){ x, y, w, h }, c);
}
void rectangle(Sint16 x, Sint16 y, Uint16 w, Uint16 h, Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
rectangle((SDL_Rect){ x, y, w, h }, RGBAColor(r, g, b, a));
}
void operator = (SDL_Surface*);
void operator = (Surface*);
void softStretch(uint16_t w, uint16_t h, uint8_t scale_mode = SScaleStretch);
void setAlpha(uint8_t alpha);
int width() { return raw->w; }
int height() { return raw->h; }
};
#endif
| 5,072
|
C++
|
.h
| 119
| 40.310924
| 123
| 0.630479
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,127
|
opkscannerdialog.h
|
MiyooCFW_gmenu2x/src/opkscannerdialog.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef OPKSCANNERDIALOG_H_
#define OPKSCANNERDIALOG_H_
#include <string>
#include "gmenu2x.h"
#include "textdialog.h"
using std::string;
using std::vector;
class GMenu2X;
class OPKScannerDialog : public TextDialog {
public:
string opkpath = "";
void opkInstall(const string &path);
void opkScan(string opkdir);
OPKScannerDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon, const string &backdrop = "");
void preProcess() { };
void exec(bool any_platform = false);
};
#endif /*OPKSCANNERDIALOG_H_*/
| 1,956
|
C++
|
.h
| 37
| 51.054054
| 133
| 0.526921
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,128
|
textdialog.h
|
MiyooCFW_gmenu2x/src/textdialog.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef TEXTDIALOG_H_
#define TEXTDIALOG_H_
#include <string>
#include "gmenu2x.h"
#include "dialog.h"
using std::string;
using std::vector;
class TextDialog : protected Dialog {
protected:
vector<string> text;
string backdrop, rawText = "";
int32_t firstCol = 0, lineWidth = 0, firstRow = 0;
uint32_t rowsPerPage = 0;
int drawText(vector<string> *text, int32_t firstCol, int32_t firstRow, uint32_t rowsPerPage);
public:
TextDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon, const string &backdrop = "");
void appendText(const string &text);
void appendFile(const string &file);
virtual void exec();
virtual void preProcess();
};
#endif /*TEXTDIALOG_H_*/
| 2,122
|
C++
|
.h
| 41
| 49.829268
| 127
| 0.540802
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,129
|
menusetting.h
|
MiyooCFW_gmenu2x/src/menusetting.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MENUSETTING_H
#define MENUSETTING_H
#include "buttonbox.h"
#include "iconbutton.h"
class MenuSetting {
protected:
GMenu2X *gmenu2x;
ButtonBox buttonBox;
std::string title, description;
public:
MenuSetting(GMenu2X *gmenu2x, const std::string &title, const std::string &description);
IconButton *btn;
virtual ~MenuSetting();
virtual void draw(int y);
virtual void handleTS();
virtual uint32_t manageInput() = 0;
virtual void adjustInput();
virtual void drawSelected(int y);
virtual bool edited() = 0;
const std::string &getTitle() { return title; };
const std::string &getDescription() { return description; }
};
#endif
| 2,053
|
C++
|
.h
| 42
| 46.904762
| 89
| 0.536963
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,130
|
settingsdialog.h
|
MiyooCFW_gmenu2x/src/settingsdialog.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef SETTINGSDIALOG_H_
#define SETTINGSDIALOG_H_
#include <string>
#include "gmenu2x.h"
#include "menusetting.h"
#include "dialog.h"
using std::string;
using std::vector;
class Touchscreen;
class SettingsDialog : protected Dialog {
private:
enum sd_action_t {
SD_NO_ACTION,
SD_ACTION_CLOSE,
SD_ACTION_CLOSE_NOMB,
SD_ACTION_CLOSE_LINK,
SD_ACTION_CLOSE_LINK_NOMB,
SD_ACTION_UP,
SD_ACTION_DOWN,
SD_ACTION_SAVE,
SD_ACTION_PAGEUP,
SD_ACTION_PAGEDOWN,
};
Touchscreen &ts;
vector<MenuSetting *> voices;
public:
SettingsDialog(GMenu2X *gmenu2x, Touchscreen &ts, const string &title, const string &icon = "skin:sections/settings.png");
~SettingsDialog();
bool save = false, loop = true, allowCancel = false, allowCancel_nomb = false, allowCancel_link = false, allowCancel_link_nomb = false;
bool edited();
bool exec();
void addSetting(MenuSetting* set);
int32_t selected = 0;
};
#endif /*SETTINGSDIALOG_H_*/
| 2,345
|
C++
|
.h
| 54
| 41.388889
| 137
| 0.559545
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,131
|
menusettingint.h
|
MiyooCFW_gmenu2x/src/menusettingint.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MENUSETTINGINT_H
#define MENUSETTINGINT_H
#include "menusetting.h"
class MenuSettingInt : public MenuSetting {
private:
int originalValue;
int *_value;
std::string strvalue;
int def, min, max, delta;
bool off=false;
int offValue;
void inc();
void dec();
void current();
public:
MenuSettingInt(GMenu2X *gmenu2x, const std::string &title, const std::string &description, int *value, int def, int min, int max, int delta=1);
virtual ~MenuSettingInt() {};
virtual uint32_t manageInput();
virtual void draw(int);
virtual bool edited();
virtual void setValue(int value, bool readValue);
virtual void setDefault();
int value();
MenuSettingInt *setOff(int value);
};
#endif
| 2,104
|
C++
|
.h
| 45
| 44.777778
| 144
| 0.540224
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,132
|
menusettingimage.h
|
MiyooCFW_gmenu2x/src/menusettingimage.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MENUSETTINGIMAGE_H
#define MENUSETTINGIMAGE_H
#include "menusettingfile.h"
class MenuSettingImage : public MenuSettingFile {
public:
MenuSettingImage(GMenu2X *gmenu2x, const std::string &title, const std::string &description, std::string *value, const std::string &filter, const std::string &startPath, const std::string &dialogTitle, const std::string &dialogIcon);
virtual ~MenuSettingImage() {}
virtual void setValue(const std::string &value);
};
#endif
| 1,875
|
C++
|
.h
| 29
| 62.827586
| 234
| 0.523603
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,133
|
powermanager.h
|
MiyooCFW_gmenu2x/src/powermanager.h
|
#ifndef POWERMANAGER_H
#define POWERMANAGER_H
#include <SDL.h>
#include "gmenu2x.h"
class PowerManager {
public:
PowerManager(GMenu2X *gmenu2x, uint32_t suspendTimeout, uint32_t powerTimeout);
~PowerManager();
void setSuspendTimeout(uint32_t suspendTimeout);
void setPowerTimeout(uint32_t powerTimeout);
void clearTimer();
void resetSuspendTimer();
void resetPowerTimer();
static uint32_t doSuspend(uint32_t interval, void *param = NULL);
static uint32_t doPowerOff(uint32_t interval, void *param = NULL);
bool suspendActive = false;
SDL_TimerID powerTimer = NULL;
private:
GMenu2X *gmenu2x;
uint32_t suspendTimeout, powerTimeout;
static PowerManager *instance;
};
#endif
| 690
|
C++
|
.h
| 23
| 28.217391
| 80
| 0.800905
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,134
|
translator.h
|
MiyooCFW_gmenu2x/src/translator.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef TRANSLATOR_H
#define TRANSLATOR_H
#include "utilities.h"
/**
Hash Map of translation strings.
@author Massimiliano Torromeo <massimiliano.torromeo@gmail.com>
*/
class Translator {
private:
string _lang;
unordered_map<string, string> translations;
public:
Translator(const string &lang="");
~Translator();
string lang();
void setLang(const string &lang);
// bool exists(const string &term);
string translate(const string &term,const char *replacestr=NULL,...);
string operator[](const string &term);
};
#endif
| 1,937
|
C++
|
.h
| 40
| 46.575
| 77
| 0.524061
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,135
|
filelister.h
|
MiyooCFW_gmenu2x/src/filelister.h
|
/***************************************************************************
* Copyright (C) 2006 by Massimiliano Torromeo *
* massimiliano.torromeo@gmail.com *
* *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef FILELISTER_H_
#define FILELISTER_H_
#include <string>
#include <vector>
using std::string;
using std::vector;
class FileLister {
private:
vector<string> directories, files, excludes;
public:
string path, filter;
FileLister(const string &startPath = "/", bool showDirectories = true, bool showFiles = true);
bool showDirectories = true, showFiles = true, allowDirUp = true;
void browse();
uint32_t size();
uint32_t dirCount();
uint32_t fileCount();
string operator[](uint32_t);
string getFile(uint32_t);
bool isFile(uint32_t);
bool isDirectory(uint32_t);
const string getExt(uint32_t i = 0);
const string getFilePath(uint32_t i = 0);
const string &getPath() { return path; }
void setPath(const string &path);
const string &getFilter() { return filter; }
void setFilter(const string &filter);
const vector<string> &getDirectories() { return directories; }
const vector<string> &getFiles() { return files; }
void insertFile(const string &file);
void addExclude(const string &exclude);
};
#endif /*FILELISTER_H_*/
| 2,451
|
C++
|
.h
| 52
| 45.230769
| 95
| 0.56689
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,136
|
miyoo.h
|
MiyooCFW_gmenu2x/src/platform/miyoo.h
|
#ifndef HW_MIYOO_H
#define HW_MIYOO_H
#include <sys/mman.h>
#include <bitset>
// MiyooCFW 2.0 Key Codes. Apaczer, 2023
// BUTTON GMENU SDL NUMERIC GPIO
// -----------------------------------------------------------------------------
// A CONFIRM SDLK_LALT 308
// B CANCEL SDLK_LCTRL 306
// X MODIFIER SDLK_LSHIFT 304
// Y MANUAL SDLK_SPACE 32
// L1 SECTION_PREV SDLK_TAB 9
// R1 SECTION_NEXT BACKSPACE 8
// L2 DEC SDLK_PAGEUP 280
// R2 INC SDLK_PAGEDOWN 281
// L3 DEC SDLK_RALT 307
// R3 INC SDLK_RSHIFT 303
// RESET POWER SDLK_RCTRL 305
// START SETTINGS SDLK_RETURN 13
// SELECT MENU SDLK_ESCAPE 27
// UP UP SDLK_UP 273
// DOWN DOWN SDLK_DOWN 274
// RIGHT RIGHT SDLK_RIGHT 275
// LEFT LEFT SDLK_LEFT 276
//
#define MIYOO_VIR_SET_MODE _IOWR(0x100, 0, unsigned long)
#define MIYOO_VIR_SET_VER _IOWR(0x101, 0, unsigned long)
#define MIYOO_SND_SET_VOLUME _IOWR(0x100, 0, unsigned long)
#define MIYOO_SND_GET_VOLUME _IOWR(0x101, 0, unsigned long)
#define MIYOO_KBD_GET_HOTKEY _IOWR(0x100, 0, unsigned long)
#define MIYOO_KBD_SET_VER _IOWR(0x101, 0, unsigned long)
#define MIYOO_KBD_LOCK_KEY _IOWR(0x102, 0, unsigned long) //unused
#define MIYOO_LAY_SET_VER _IOWR(0x103, 0, unsigned long)
#define MIYOO_KBD_GET_VER _IOWR(0x104, 0, unsigned long)
#define MIYOO_LAY_GET_VER _IOWR(0x105, 0, unsigned long)
#define MIYOO_FB0_PUT_OSD _IOWR(0x100, 0, unsigned long)
#define MIYOO_FB0_SET_MODE _IOWR(0x101, 0, unsigned long)
#define MIYOO_FB0_GET_VER _IOWR(0x102, 0, unsigned long)
#define MIYOO_FB0_SET_FLIP _IOWR(0x103, 0, unsigned long) //unused
#define MIYOO_FB0_SET_FPBP _IOWR(0x104, 0, unsigned long)
#define MIYOO_FB0_GET_FPBP _IOWR(0x105, 0, unsigned long)
#define MIYOO_FB0_SET_TEFIX _IOWR(0x106, 0, unsigned long)
#define MIYOO_FB0_GET_TEFIX _IOWR(0x107, 0, unsigned long)
#define MIYOO_FBP_FILE "/mnt/.fpbp.conf"
#define MIYOO_LID_FILE "/mnt/.backlight.conf"
#define MIYOO_VOL_FILE "/mnt/.volume.conf"
#define MIYOO_BUTTON_FILE "/mnt/.buttons.conf"
#define MIYOO_BATTERY_FILE "/mnt/.batterylow.conf"
#define MIYOO_LID_CONF "/sys/devices/platform/backlight/backlight/backlight/brightness"
#define MIYOO_BATTERY "/sys/class/power_supply/miyoo-battery/voltage_now"
#define MIYOO_USB_STATE "/sys/class/udc/musb-hdrc.1.auto/state"
#define MIYOO_USB_SUSPEND "/sys/devices/platform/usb_phy_generic.0.auto/subsystem/devices/1c13000.usb/musb-hdrc.1.auto/gadget/suspended"
#define MIYOO_OPTIONS_FILE "/mnt/options.cfg"
#define MIYOO_TVOUT_FILE "/mnt/tvout"
#define MIYOO_SND_FILE "/dev/miyoo_snd"
#define MIYOO_FB0_FILE "/dev/miyoo_fb0"
#define MIYOO_KBD_FILE "/dev/miyoo_kbd"
#define MIYOO_VIR_FILE "/dev/miyoo_vir"
#define TTS_ENGINE "espeak"
#define MULTI_INT
#define DEFAULT_CPU 720
#define DEFAULT_LAYOUT 1
#define DEFAULT_TEFIX 0
static uint32_t oc_table[] = {
// F1C100S PLL_CPU Control Register.
// 24MHz*N*K/(M*P) ; N = (Nf+1)<=32 ; K = (Kf+1)<=4 ; M = (Mf+1)<=4 ; P = (00: /1 | 01: /2 | 10: /4); --> CPU_PLL output must be in 200MHz~2.6GHz range
// 27:18 are 10bit non-affecting space thus starting to read "int mhz" value here "(MHz << 18)" up to last 32bit.
// ((24 * N * K) << 18) | (Nf << 8) | (Kf << 4) | (Mf << 0) | (Pf << 16),
//
(216 << 18) | (8 << 8) | (0 << 4),// 216MHz = 24MHz*9*1/(1*1)
(240 << 18) | (9 << 8) | (0 << 4),
(264 << 18) | (10 << 8) | (0 << 4),
(288 << 18) | (11 << 8) | (0 << 4),
(312 << 18) | (12 << 8) | (0 << 4),
(336 << 18) | (13 << 8) | (0 << 4),
(360 << 18) | (14 << 8) | (0 << 4),
(384 << 18) | (15 << 8) | (0 << 4),
(408 << 18) | (16 << 8) | (0 << 4),
(432 << 18) | (17 << 8) | (0 << 4),
(456 << 18) | (18 << 8) | (0 << 4),
(480 << 18) | (19 << 8) | (0 << 4),
(504 << 18) | (20 << 8) | (0 << 4),
(528 << 18) | (21 << 8) | (0 << 4),
(552 << 18) | (22 << 8) | (0 << 4),
(576 << 18) | (23 << 8) | (0 << 4),
(600 << 18) | (24 << 8) | (0 << 4),
(624 << 18) | (25 << 8) | (0 << 4),
(648 << 18) | (26 << 8) | (0 << 4),
(672 << 18) | (27 << 8) | (0 << 4),
(696 << 18) | (28 << 8) | (0 << 4),
(DEFAULT_CPU << 18) | (29 << 8) | (0 << 4),
(744 << 18) | (30 << 8) | (0 << 4),
(768 << 18) | (31 << 8) | (0 << 4),
(792 << 18) | (10 << 8) | (2 << 4),
(816 << 18) | (16 << 8) | (1 << 4),
(864 << 18) | (17 << 8) | (1 << 4),
(912 << 18) | (18 << 8) | (1 << 4),
(936 << 18) | (12 << 8) | (2 << 4),
(960 << 18) | (19 << 8) | (1 << 4),
(1008 << 18) | (20 << 8) | (1 << 4)// 1.008GHz = 24MHz*21*2/(1*1)
};
int oc_choices[] = {
216,240,264,288,312,336,360,384,408,432,
456,480,504,528,552,576,600,624,648,672,
696,720,744,768,792,816,864,912,936,960,
1008,9999
}; // last value[] is dummy point - do not modify
int oc_choices_size = sizeof(oc_choices)/sizeof(int);
int kbd, fb0, snd;
int32_t tickBattery = 0;
void setTVoff() {
system("rm " MIYOO_TVOUT_FILE " ; sync ; reboot");
}
int getKbdLayoutHW() {
kbd = open(MIYOO_KBD_FILE, O_RDWR);
if (kbd > 0) {
ioctl(kbd, MIYOO_LAY_GET_VER, &LAYOUT_VERSION);
int val = LAYOUT_VERSION;
close(kbd);
return val;
} else {
WARNING("Could not open " MIYOO_KBD_FILE);
return 0;
}
}
int getTefixHW() {
fb0 = open(MIYOO_FB0_FILE, O_RDWR);
if (fb0 > 0) {
ioctl(fb0, MIYOO_FB0_GET_TEFIX, &TEFIX);
int val = TEFIX;
close(fb0);
return val;
} else {
WARNING("Could not open " MIYOO_FB0_FILE);
return -1;
}
}
int32_t getBatteryLevel() {
int val = -1;
if (FILE *f = fopen(MIYOO_BATTERY, "r")) {
fscanf(f, "%i", &val);
fclose(f);
}
return val;
}
uint8_t getBatteryStatus(int32_t val, int32_t min, int32_t max) {
if ((val > 4300) || (val < 0)) return 6; // >100% - max voltage 4320
if (val > 4100) return 5; // 100% - fully charged 4150
if (val > 3900) return 4; // 80%
if (val > 3800) return 3; // 60%
if (val > 3700) return 2; // 40%
if (val > 3520) return 1; // 20%
return 0; // 0% :(
}
uint32_t hwCheck(unsigned int interval = 0, void *param = NULL) {
tickBattery++;
if (tickBattery > 30) { // update battery level every 30 hwChecks
tickBattery = 0;
batteryIcon = getBatteryStatus(getBatteryLevel(), 0, 0);
}
return interval;
}
uint8_t getMMCStatus() {
return MMC_REMOVE;
}
uint8_t getUDCStatus() {
return UDC_REMOVE;
}
uint8_t getTVOutStatus() {
return TV_REMOVE;
}
uint8_t getDevStatus() {
return 0;
}
uint8_t getVolumeMode(uint8_t vol) {
return VOLUME_MODE_NORMAL;
}
class GMenu2X_platform : public GMenu2X {
private:
void hwDeinit() {
}
void hwInit() {
CPU_MENU = DEFAULT_CPU;
CPU_LINK = CPU_MENU;
CPU_MAX = oc_choices[oc_choices_size - 2]; //omitting last value in oc_choices
CPU_EDGE = oc_choices[oc_choices_size - 4];
CPU_MIN = oc_choices[8]; //408MHz, below may be insufficient and result in occasional freezes
// CPU_STEP = 1;
LAYOUT_VERSION_MAX = 6;
TEFIX_MAX = 3;
batteryIcon = getBatteryStatus(getBatteryLevel(), 0, 0);
// setenv("HOME", "/mnt", 1);
//system("mount -o remount,async /mnt");
getKbdLayoutHW();
getTefixHW();
w = 320;
h = 240;
INFO("MIYOO");
}
int getBacklight() {
int val = -1;
FILE *f = fopen(MIYOO_LID_CONF, "r");
if (f) {
fscanf(f, "%i", &val);
fclose(f);
val = val * 10;
}
return val;
}
int getVolume() {
int val = -1;
snd = open(MIYOO_SND_FILE, O_RDWR);
if (snd > 0) {
ioctl(snd, MIYOO_SND_GET_VOLUME, &val);
close(snd);
val = val * 10;
} else {
WARNING("Could not open " MIYOO_SND_FILE);
}
return val;
}
public:
int setVolume(int val, bool popup = false) {
val = GMenu2X::setVolume(val, popup);
char buf[128] = {0};
int vol = val / 10;
if (vol > 9) vol = 9;
else if (vol < 0) vol = 0;
snd = open(MIYOO_SND_FILE, O_RDWR);
if (snd > 0) {
ioctl(snd, MIYOO_SND_SET_VOLUME, vol);
close(snd);
}
sprintf(buf, "echo %i > " MIYOO_VOL_FILE, vol);
system(buf);
volumeMode = getVolumeMode(val);
return val;
}
bool isUsbConnected() {
string state = file_read(MIYOO_USB_STATE);
string suspended = file_read(MIYOO_USB_SUSPEND);
return (state == "configured" && suspended == "0");
}
int setBacklight(int val, bool popup = false) {
val = GMenu2X::setBacklight(val, popup);
int lid = val / 10;
if (lid > 10) lid = 10;
char buf[128] = {0};
if (FILE *f = fopen(MIYOO_TVOUT_FILE, "r")) {
return 0;
} else if (lid != 0) {
sprintf(buf, "echo %i > " MIYOO_LID_FILE " && echo %i > " MIYOO_LID_CONF, lid, lid);
} else {
sprintf(buf, "echo %i > " MIYOO_LID_CONF, lid);
}
system(buf);
return val;
}
void setKbdLayout(int val) {
int f = open(MIYOO_KBD_FILE, O_RDWR);
if (f > 0) {
if (val <= 0 || val > LAYOUT_VERSION_MAX) val = DEFAULT_LAYOUT;
ioctl(f, MIYOO_LAY_SET_VER, val);
close(f);
} else {
WARNING("Could not open " MIYOO_KBD_FILE);
val = 0;
}
}
void setTefix(int val) {
int f = open(MIYOO_FB0_FILE, O_RDWR);
if (f > 0) {
if (val < 0 || val > TEFIX_MAX) val = DEFAULT_TEFIX;
ioctl(f, MIYOO_FB0_SET_TEFIX, val);
close(f);
} else {
WARNING("Could not open " MIYOO_FB0_FILE);
val = -1;
}
}
void setCPU(uint32_t mhz) {
volatile uint8_t memdev = open("/dev/mem", O_RDWR);
if (memdev > 0) {
uint32_t *mem = (uint32_t*)mmap(0, 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED, memdev, 0x01c20000);
if (mem == MAP_FAILED) {
ERROR("Could not mmap hardware registers!");
return;
} else {
uint32_t total = sizeof(oc_table) / sizeof(oc_table[0]);
for (int x = total - 1; x >= 0; x--) {
if ((oc_table[x] >> 18) <= mhz) {
mem[0] = (1 << 31) | (oc_table[x] & 0x0003ffff);
uint32_t v = mem[0];
while (std::bitset<32>(v).test(28) == 0) {
v = mem[0];
//INFO("PLL unstable wait for register lock");
}
INFO("Set CPU clock: %d(0x%08x)", mhz, v);
break;
}
}
}
munmap(mem, 0x1000);
} else {
WARNING("Could not open /dev/mem");
}
close(memdev);
}
string hwPreLinkLaunch() {
//system("mount -o remount,sync /mnt");
return "";
}
};
#endif
| 10,375
|
C++
|
.h
| 314
| 30.570064
| 151
| 0.577234
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,137
|
gp2x.h
|
MiyooCFW_gmenu2x/src/platform/gp2x.h
|
#ifndef HW_GP2X_H
#define HW_GP2X_H
const int MAX_VOLUME_SCALE_FACTOR = 200;
// Default values - going to add settings adjustment, saving, loading and such
const int VOLUME_SCALER_MUTE = 0;
const int VOLUME_SCALER_PHONES = 65;
const int VOLUME_SCALER_NORMAL = 100;
const int BATTERY_READS = 10;
volatile uint16_t *memregs;
int SOUND_MIXER = SOUND_MIXER_READ_PCM;
int memdev = 0;
uint32_t hwCheck(unsigned int interval = 0, void *param = NULL) {
printf("%s:%d: %s\n", __FILE__, __LINE__, __func__);
return interval;
}
uint8_t getMMCStatus() {
return MMC_REMOVE;
}
uint8_t getUDCStatus() {
return UDC_REMOVE;
}
uint8_t getTVOutStatus() {
return TV_REMOVE;
}
uint8_t getVolumeMode(uint8_t vol) {
return VOLUME_MODE_NORMAL;
}
int32_t getBatteryStatus() {
return -1;
}
class GMenu2X_platform : public GMenu2X {
private:
typedef struct {
uint16_t batt;
uint16_t remocon;
} MMSP2ADC;
int batteryHandle;
string ip, defaultgw;
bool inet, //!< Represents the configuration of the basic network services. @see readCommonIni @see usbnet @see samba @see web
usbnet,
samba,
web;
volatile uint16_t *MEM_REG;
int cx25874; //tv-out
void gp2x_tvout_on(bool pal);
void gp2x_tvout_off();
void readCommonIni();
void initServices();
void hwInit() {
setenv("SDL_NOMOUSE", "1", 1);
#if defined(TARGET_GP2X) || defined(TARGET_WIZ) || defined(TARGET_CAANOO) || defined(TARGET_RETROFW)
memdev = open("/dev/mem", O_RDWR);
if (memdev < 0) WARNING("Could not open /dev/mem");
#endif
if (memdev > 0) {
#if defined(TARGET_GP2X)
memregs = (uint16_t*)mmap(0, 0x10000, PROT_READ|PROT_WRITE, MAP_SHARED, memdev, 0xc0000000);
MEM_REG = &memregs[0];
//Fix tv-out
if (memregs[0x2800 >> 1] & 0x100) {
memregs[0x2906 >> 1] = 512;
//memregs[0x290C >> 1]=640;
memregs[0x28E4 >> 1] = memregs[0x290C >> 1];
}
memregs[0x28E8 >> 1] = 239;
#elif defined(TARGET_WIZ) || defined(TARGET_CAANOO)
memregs = (uint16_t*)mmap(0, 0x20000, PROT_READ|PROT_WRITE, MAP_SHARED, memdev, 0xc0000000);
#endif
if (memregs == MAP_FAILED) {
ERROR("Could not mmap hardware registers!");
close(memdev);
}
}
#if defined(TARGET_GP2X)
if (file_exists("/etc/open2x")) fwType = "open2x";
else fwType = "gph";
f200 = file_exists("/dev/touchscreen/wm97xx");
//open2x
savedVolumeMode = 0;
volumeScalerNormal = VOLUME_SCALER_NORMAL;
volumeScalerPhones = VOLUME_SCALER_PHONES;
o2x_usb_net_on_boot = false;
o2x_usb_net_ip = "";
o2x_ftp_on_boot = false;
o2x_telnet_on_boot = false;
o2x_gp2xjoy_on_boot = false;
o2x_usb_host_on_boot = false;
o2x_usb_hid_on_boot = false;
o2x_usb_storage_on_boot = false;
usbnet = samba = inet = web = false;
if (fwType=="open2x") {
readConfigOpen2x();
// VOLUME MODIFIER
switch(volumeMode) {
case VOLUME_MODE_MUTE: setVolumeScaler(VOLUME_SCALER_MUTE); break;
case VOLUME_MODE_PHONES: setVolumeScaler(volumeScalerPhones); break;
case VOLUME_MODE_NORMAL: setVolumeScaler(volumeScalerNormal); break;
}
}
readCommonIni();
cx25874 = 0;
batteryHandle = 0;
// useSelectionPng = false;
batteryHandle = open(f200 ? "/dev/mmsp2adc" : "/dev/batt", O_RDONLY);
//if wm97xx fails to open, set f200 to false to prevent any further access to the touchscreen
if (f200) f200 = ts.init();
#elif defined(TARGET_WIZ) || defined(TARGET_CAANOO)
/* get access to battery device */
batteryHandle = open("/dev/pollux_batt", O_RDONLY);
#endif
w = 320;
h = 240;
initServices();
setGamma(confInt["gamma"]);
applyDefaultTimings();
INFO("GP2X Init Done!");
}
void hwDeinit() {
#if defined(TARGET_GP2X)
if (memdev > 0) {
//Fix tv-out
if (memregs[0x2800 >> 1] & 0x100) {
memregs[0x2906 >> 1] = 512;
memregs[0x28E4 >> 1] = memregs[0x290C >> 1];
}
memregs[0x28DA >> 1] = 0x4AB;
memregs[0x290C >> 1] = 640;
}
if (f200) ts.deinit();
if (batteryHandle != 0) close(batteryHandle);
if (memdev > 0) {
memregs = NULL;
close(memdev);
}
#endif
}
public:
// Open2x settings ---------------------------------------------------------
bool o2x_usb_net_on_boot, o2x_ftp_on_boot, o2x_telnet_on_boot, o2x_gp2xjoy_on_boot, o2x_usb_host_on_boot, o2x_usb_hid_on_boot, o2x_usb_storage_on_boot;
string o2x_usb_net_ip;
int savedVolumeMode; // just use the const int scale values at top of source
// Volume scaling values to store from config files
int volumeScalerPhones;
int volumeScalerNormal;
//--------------------------------------------------------------------------
void ledOn() {
#if defined(TARGET_GP2X)
if (memdev != 0 && !f200) memregs[0x106E >> 1] ^= 16;
//SDL_SYS_JoystickGp2xSys(joy.joystick, BATT_LED_ON);
#endif
}
void ledOff() {
#if defined(TARGET_GP2X)
if (memdev != 0 && !f200) memregs[0x106E >> 1] ^= 16;
//SDL_SYS_JoystickGp2xSys(joy.joystick, BATT_LED_OFF);
#endif
}
uint16_t getBatteryLevel() {
int32_t val = getBatteryStatus();
#if defined(TARGET_GP2X)
//if (batteryHandle<=0) return 6; //AC Power
if (f200) {
MMSP2ADC val;
read(batteryHandle, &val, sizeof(MMSP2ADC));
if (val.batt==0) return 5;
if (val.batt==1) return 3;
if (val.batt==2) return 1;
if (val.batt==3) return 0;
return 6;
} else {
int battval = 0;
uint16_t cbv, min=900, max=0;
for (int i = 0; i < BATTERY_READS; i ++) {
if ( read(batteryHandle, &cbv, 2) == 2) {
battval += cbv;
if (cbv>max) max = cbv;
if (cbv<min) min = cbv;
}
}
battval -= min+max;
battval /= BATTERY_READS-2;
if (battval>=850) return 6;
if (battval>780) return 5;
if (battval>740) return 4;
if (battval>700) return 3;
if (battval>690) return 2;
if (battval>680) return 1;
}
#elif defined(TARGET_WIZ) || defined(TARGET_CAANOO)
uint16_t cbv;
if ( read(batteryHandle, &cbv, 2) == 2) {
// 0=fail, 1=100%, 2=66%, 3=33%, 4=0%
switch (cbv) {
case 4: return 1;
case 3: return 2;
case 2: return 4;
case 1: return 5;
default: return 6;
}
}
#endif
}
void setCPU(uint32_t mhz) {
// mhz = constrain(mhz, CPU_CLK_MIN, CPU_CLK_MAX);
if (memdev > 0) {
DEBUG("Setting clock to %d", mhz);
#if defined(TARGET_GP2X)
uint32_t v, mdiv, pdiv=3, scale=0;
#define SYS_CLK_FREQ 7372800
mhz *= 1000000;
mdiv = (mhz * pdiv) / SYS_CLK_FREQ;
mdiv = ((mdiv-8)<<8) & 0xff00;
pdiv = ((pdiv-2)<<2) & 0xfc;
scale &= 3;
v = mdiv | pdiv | scale;
MEM_REG[0x910>>1] = v;
#elif defined(TARGET_CAANOO) || defined(TARGET_WIZ)
volatile uint32_t *memregl = static_cast<volatile uint32_t*>((volatile void*)memregs);
int mdiv, pdiv = 9, sdiv = 0;
uint32_t v;
#define SYS_CLK_FREQ 27
#define PLLSETREG0 (memregl[0xF004>>2])
#define PWRMODE (memregl[0xF07C>>2])
mdiv = (mhz * pdiv) / SYS_CLK_FREQ;
if (mdiv & ~0x3ff) return;
v = pdiv<<18 | mdiv<<8 | sdiv;
PLLSETREG0 = v;
PWRMODE |= 0x8000;
for (int i = 0; (PWRMODE & 0x8000) && i < 0x100000; i++);
#endif
setTVOut(TVOut);
}
}
void gp2x_tvout_on(bool pal) {
if (memdev != 0) {
/*Ioctl_Dummy_t *msg;
#define FBMMSP2CTRL 0x4619
int TVHandle = ioctl(SDL_videofd, FBMMSP2CTRL, msg);*/
if (cx25874!=0) gp2x_tvout_off();
//if tv-out is enabled without cx25874 open, stop
//if (memregs[0x2800 >> 1]&0x100) return;
cx25874 = open("/dev/cx25874",O_RDWR);
ioctl(cx25874, _IOW('v', 0x02, uint8_t), pal ? 4 : 3);
memregs[0x2906 >> 1] = 512;
memregs[0x28E4 >> 1] = memregs[0x290C >> 1];
memregs[0x28E8 >> 1] = 239;
}
}
void gp2x_tvout_off() {
if (memdev != 0) {
close(cx25874);
cx25874 = 0;
memregs[0x2906 >> 1] = 1024;
}
}
void settingsOpen2x() {
SettingsDialog sd(this, ts, tr["Open2x Settings"]);
sd.addSetting(new MenuSettingBool(this, tr["USB net on boot"], tr["Allow USB networking to be started at boot time"],&o2x_usb_net_on_boot));
sd.addSetting(new MenuSettingString(this, tr["USB net IP"], tr["IP address to be used for USB networking"],&o2x_usb_net_ip));
sd.addSetting(new MenuSettingBool(this, tr["Telnet on boot"], tr["Allow telnet to be started at boot time"],&o2x_telnet_on_boot));
sd.addSetting(new MenuSettingBool(this, tr["FTP on boot"], tr["Allow FTP to be started at boot time"],&o2x_ftp_on_boot));
sd.addSetting(new MenuSettingBool(this, tr["GP2XJOY on boot"], tr["Create a js0 device for GP2X controls"],&o2x_gp2xjoy_on_boot));
sd.addSetting(new MenuSettingBool(this, tr["USB host on boot"], tr["Allow USB host to be started at boot time"],&o2x_usb_host_on_boot));
sd.addSetting(new MenuSettingBool(this, tr["USB HID on boot"], tr["Allow USB HID to be started at boot time"],&o2x_usb_hid_on_boot));
sd.addSetting(new MenuSettingBool(this, tr["USB storage on boot"], tr["Allow USB storage to be started at boot time"],&o2x_usb_storage_on_boot));
//sd.addSetting(new MenuSettingInt(this, tr["Speaker Mode on boot"], tr["Set Speaker mode. 0 = Mute, 1 = Phones, 2 = Speaker"],&volumeMode,0,2,1));
sd.addSetting(new MenuSettingInt(this, tr["Speaker Scaler"], tr["Set the Speaker Mode scaling 0-150\% (default is 100\%)"],&volumeScalerNormal,100, 0,150));
sd.addSetting(new MenuSettingInt(this, tr["Headphones Scaler"], tr["Set the Headphones Mode scaling 0-100\% (default is 65\%)"],&volumeScalerPhones,65, 0,100));
if (sd.exec() && sd.edited()) {
writeConfigOpen2x();
switch(volumeMode) {
case VOLUME_MODE_MUTE: setVolumeScaler(VOLUME_SCALER_MUTE); break;
case VOLUME_MODE_PHONES: setVolumeScaler(volumeScalerPhones); break;
case VOLUME_MODE_NORMAL: setVolumeScaler(volumeScalerNormal); break;
}
setVolume(confInt["globalVolume"]);
}
}
void readConfigOpen2x() {
string conffile = "/etc/config/open2x.conf";
if (!file_exists(conffile)) return;
ifstream inf(conffile.c_str(), ios_base::in);
if (!inf.is_open()) return;
string line;
while (getline(inf, line, '\n')) {
string::size_type pos = line.find("=");
string name = trim(line.substr(0,pos));
string value = trim(line.substr(pos+1,line.length()));
if (name=="USB_NET_ON_BOOT") o2x_usb_net_on_boot = value == "y" ? true : false;
else if (name=="USB_NET_IP") o2x_usb_net_ip = value;
else if (name=="TELNET_ON_BOOT") o2x_telnet_on_boot = value == "y" ? true : false;
else if (name=="FTP_ON_BOOT") o2x_ftp_on_boot = value == "y" ? true : false;
else if (name=="GP2XJOY_ON_BOOT") o2x_gp2xjoy_on_boot = value == "y" ? true : false;
else if (name=="USB_HOST_ON_BOOT") o2x_usb_host_on_boot = value == "y" ? true : false;
else if (name=="USB_HID_ON_BOOT") o2x_usb_hid_on_boot = value == "y" ? true : false;
else if (name=="USB_STORAGE_ON_BOOT") o2x_usb_storage_on_boot = value == "y" ? true : false;
else if (name=="VOLUME_MODE") volumeMode = savedVolumeMode = constrain( atoi(value.c_str()), 0, 2);
else if (name=="PHONES_VALUE") volumeScalerPhones = constrain( atoi(value.c_str()), 0, 100);
else if (name=="NORMAL_VALUE") volumeScalerNormal = constrain( atoi(value.c_str()), 0, 150);
}
inf.close();
}
void writeConfigOpen2x() {
ledOn();
string conffile = "/etc/config/open2x.conf";
ofstream inf(conffile.c_str());
if (inf.is_open()) {
inf << "USB_NET_ON_BOOT=" << ( o2x_usb_net_on_boot ? "y" : "n" ) << endl;
inf << "USB_NET_IP=" << o2x_usb_net_ip << endl;
inf << "TELNET_ON_BOOT=" << ( o2x_telnet_on_boot ? "y" : "n" ) << endl;
inf << "FTP_ON_BOOT=" << ( o2x_ftp_on_boot ? "y" : "n" ) << endl;
inf << "GP2XJOY_ON_BOOT=" << ( o2x_gp2xjoy_on_boot ? "y" : "n" ) << endl;
inf << "USB_HOST_ON_BOOT=" << ( (o2x_usb_host_on_boot || o2x_usb_hid_on_boot || o2x_usb_storage_on_boot) ? "y" : "n" ) << endl;
inf << "USB_HID_ON_BOOT=" << ( o2x_usb_hid_on_boot ? "y" : "n" ) << endl;
inf << "USB_STORAGE_ON_BOOT=" << ( o2x_usb_storage_on_boot ? "y" : "n" ) << endl;
inf << "VOLUME_MODE=" << volumeMode << endl;
if (volumeScalerPhones != VOLUME_SCALER_PHONES) inf << "PHONES_VALUE=" << volumeScalerPhones << endl;
if (volumeScalerNormal != VOLUME_SCALER_NORMAL) inf << "NORMAL_VALUE=" << volumeScalerNormal << endl;
inf.close();
sync();
}
ledOff();
}
void activateSdUsb() {
if (usbnet) {
MessageBox mb(this, tr["Operation not permitted."]+"\n"+tr["You should disable Usb Networking to do this."]);
mb.exec();
} else {
MessageBox mb(this, tr["USB Enabled (SD)"],"skin:icons/usb.png");
mb.setButton(CONFIRM, tr["Turn off"]);
mb.exec();
system("scripts/usbon.sh nand");
}
}
void activateNandUsb() {
if (usbnet) {
MessageBox mb(this, tr["Operation not permitted."]+"\n"+tr["You should disable Usb Networking to do this."]);
mb.exec();
} else {
system("scripts/usbon.sh nand");
MessageBox mb(this, tr["USB Enabled (Nand)"],"skin:icons/usb.png");
mb.setButton(CONFIRM, tr["Turn off"]);
mb.exec();
system("scripts/usboff.sh nand");
}
}
void activateRootUsb() {
if (usbnet) {
MessageBox mb(this,tr["Operation not permitted."]+"\n"+tr["You should disable Usb Networking to do this."]);
mb.exec();
} else {
system("scripts/usbon.sh root");
MessageBox mb(this,tr["USB Enabled (Root)"],"skin:icons/usb.png");
mb.setButton(CONFIRM, tr["Turn off"]);
mb.exec();
system("scripts/usboff.sh root");
}
}
void applyRamTimings() {
// 6 4 1 1 1 2 2
if (memdev!=0) {
int tRC = 5, tRAS = 3, tWR = 0, tMRD = 0, tRFC = 0, tRP = 1, tRCD = 1;
memregs[0x3802>>1] = ((tMRD & 0xF) << 12) | ((tRFC & 0xF) << 8) | ((tRP & 0xF) << 4) | (tRCD & 0xF);
memregs[0x3804>>1] = ((tRC & 0xF) << 8) | ((tRAS & 0xF) << 4) | (tWR & 0xF);
}
}
void applyDefaultTimings() {
// 8 16 3 8 8 8 8
if (memdev!=0) {
int tRC = 7, tRAS = 15, tWR = 2, tMRD = 7, tRFC = 7, tRP = 7, tRCD = 7;
memregs[0x3802>>1] = ((tMRD & 0xF) << 12) | ((tRFC & 0xF) << 8) | ((tRP & 0xF) << 4) | (tRCD & 0xF);
memregs[0x3804>>1] = ((tRC & 0xF) << 8) | ((tRAS & 0xF) << 4) | (tWR & 0xF);
}
}
void setGamma(int gamma) {
float fgamma = (float)constrain(gamma,1,100)/10;
fgamma = 1 / fgamma;
MEM_REG[0x2880>>1] &= ~(1<<12);
MEM_REG[0x295C>>1] = 0;
for (int i = 0; i < 256; i++) {
uint8_t g = (uint8_t)(255.0*pow(i/255.0,fgamma));
uint16_t s = (g << 8) | g;
MEM_REG[0x295E >> 1] = s;
MEM_REG[0x295E >> 1] = g;
}
}
void setVolumeScaler(int scale) {
scale = constrain(scale,0,MAX_VOLUME_SCALE_FACTOR);
uint32_t soundDev = open("/dev/mixer", O_WRONLY);
if (soundDev) {
ioctl(soundDev, SOUND_MIXER_PRIVATE2, &scale);
close(soundDev);
}
}
int getVolumeScaler() {
int currentscalefactor = -1;
uint32_t soundDev = open("/dev/mixer", O_RDONLY);
if (soundDev) {
ioctl(soundDev, SOUND_MIXER_PRIVATE1, ¤tscalefactor);
close(soundDev);
}
return currentscalefactor;
}
void readCommonIni() {
if (!file_exists("/usr/gp2x/common.ini")) return;
ifstream inf("/usr/gp2x/common.ini", ios_base::in);
if (!inf.is_open()) return;
string line;
string section = "";
while (getline(inf, line, '\n')) {
line = trim(line);
if (line[0]=='[' && line[line.length()-1]==']') {
section = line.substr(1,line.length()-2);
} else {
string::size_type pos = line.find("=");
string name = trim(line.substr(0,pos));
string value = trim(line.substr(pos+1,line.length()));
if (section=="usbnet") {
if (name=="enable")
usbnet = value=="true" ? true : false;
else if (name=="ip")
ip = value;
} else if (section=="server") {
if (name=="inet")
inet = value=="true" ? true : false;
else if (name=="samba")
samba = value=="true" ? true : false;
else if (name=="web")
web = value=="true" ? true : false;
}
}
}
inf.close();
}
void initServices() {
if (usbnet) {
string services = "scripts/services.sh "+ip+" "+(inet?"on":"off")+" "+(samba?"on":"off")+" "+(web?"on":"off")+" &";
system(services.c_str());
}
}
// void GMenu2X::about() {
// vector<string> text;
// string temp, buf;
// temp = tr["Build date: "] + __DATE__ + "\n";
// // { stringstream ss; ss << w << "x" << h << "px"; ss >> buf; }
// // temp += tr["Resolution: "] + buf + "\n";
// #ifdef TARGET_RETROFW
// // temp += tr["CPU: "] + entryPoint() + "\n";
// float battlevel = getBatteryStatus();
// { stringstream ss; ss.precision(2); ss << battlevel/1000; ss >> buf; }
// temp += tr["Battery: "] + ((battlevel < 0 || battlevel > 10000) ? tr["Charging"] : buf + " V") + "\n";
// #endif
// // char *hms = ;
// temp += tr["Uptime: "] + ms2hms(SDL_GetTicks()) + "\n";
// // temp += "----\n";
// // temp += tr["Storage:"];
// // temp += "\n " + tr["Root: "] + getDiskFree("/");
// // temp += "\n " + tr["Internal: "] + getDiskFree("/mnt/int_sd");
// // temp += "\n " + tr["External: "] + getDiskFree("/mnt/ext_sd");
// temp += "----\n";
// TextDialog td(this, "GMenu2X", tr["Info about system"], "skin:icons/about.png");
// // #if defined(TARGET_CAANOO)
// // string versionFile = "";
// // // if (file_exists("/usr/gp2x/version"))
// // // versionFile = "/usr/gp2x/version";
// // // else if (file_exists("/tmp/gp2x/version"))
// // // versionFile = "/tmp/gp2x/version";
// // // if (!versionFile.empty()) {
// // // ifstream f(versionFile.c_str(), ios_base::in);
// // // if (f.is_open()) {
// // // string line;
// // // if (getline(f, line, '\n'))
// // // temp += "\nFirmware version: " + line + "\n" + exec("uname -srm");
// // // f.close();
// // // }
// // // }
// // td.appendText("\nFirmware version: ");
// // td.appendFile(versionFile);
// // td.appendText(exec("uname -srm"));
// // #endif
// td.appendText(temp);
// td.appendFile("about.txt");
// td.exec();
// }
}
// // VOLUME SCALE MODIFIER
// #if defined(TARGET_GP2X)
// else if ( fwType=="open2x" && input[CANCEL] ) {
// volumeMode = constrain(volumeMode - 1, -VOLUME_MODE_MUTE - 1, VOLUME_MODE_NORMAL);
// if (volumeMode < VOLUME_MODE_MUTE)
// volumeMode = VOLUME_MODE_NORMAL;
// switch(volumeMode) {
// case VOLUME_MODE_MUTE: setVolumeScaler(VOLUME_SCALER_MUTE); break;
// case VOLUME_MODE_PHONES: setVolumeScaler(volumeScalerPhones); break;
// case VOLUME_MODE_NORMAL: setVolumeScaler(volumeScalerNormal); break;
// }
// setVolume(confInt["globalVolume"]);
// }
// #endif
#endif
| 18,229
|
C++
|
.h
| 500
| 33.374
| 162
| 0.626204
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,138
|
rg350.h
|
MiyooCFW_gmenu2x/src/platform/rg350.h
|
#ifndef HW_PC_H
#define HW_PC_H
volatile uint16_t *memregs;
uint8_t memdev = 0;
int32_t tickBattery = 0;
uint16_t getDevStatus() {
char buf[10000];
if (FILE *f = fopen("/proc/bus/input/devices", "r")) {
size_t sz = fread(buf, sizeof(char), 10000, f);
fclose(f);
return sz;
}
return 0;
}
uint8_t getMMCStatus() {
return MMC_REMOVE;
}
uint8_t getUDCStatus() {
int val = -1;
if (FILE *f = fopen("/sys/class/power_supply/usb/online", "r")) {
fscanf(f, "%i", &val);
fclose(f);
if (val == 1) {
return UDC_CONNECT;
}
}
return UDC_REMOVE;
}
uint8_t getTVOutStatus() {
return TV_REMOVE;
}
uint8_t getVolumeMode(uint8_t vol) {
if (!vol) return VOLUME_MODE_MUTE;
return VOLUME_MODE_NORMAL;
}
int16_t getBatteryLevel() {
int val = -1;
FILE *f;
if (getUDCStatus() == UDC_REMOVE && (f = fopen("/sys/class/power_supply/battery/capacity", "r"))) {
fscanf(f, "%i", &val);
fclose(f);
}
return val;
};
uint8_t getBatteryStatus(int32_t val, int32_t min, int32_t max) {
if ((val > 10000) || (val < 0)) return 6;
if (val > 90) return 5; // 100%
if (val > 75) return 4; // 80%
if (val > 55) return 3; // 55%
if (val > 30) return 2; // 30%
if (val > 15) return 1; // 15%
return 0; // 0% :(
}
uint32_t hwCheck(unsigned int interval = 0, void *param = NULL) {
tickBattery++;
if (tickBattery > 30) { // update battery level every 30 hwChecks
tickBattery = 0;
batteryIcon = getBatteryStatus(getBatteryLevel(), 0, 0);
}
if (tickBattery > 1) {
udcStatus = getUDCStatus();
if (udcPrev != udcStatus) {
udcPrev = udcStatus;
InputManager::pushEvent(udcStatus);
return 2000;
}
numJoy = getDevStatus();
if (numJoyPrev != numJoy) {
numJoyPrev = numJoy;
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
SDL_InitSubSystem(SDL_INIT_JOYSTICK);
InputManager::pushEvent(JOYSTICK_CONNECT);
return 5000;
}
}
return interval;
}
class GMenu2X_platform : public GMenu2X {
private:
void hwInit() {
CPU_MENU = 0;
CPU_LINK = 0;
CPU_MAX = 0;
CPU_MIN = 0;
CPU_STEP = 0;
batteryIcon = getBatteryStatus(getBatteryLevel(), 0, 0);
#if defined(OPK_SUPPORT)
system("umount -fl /mnt");
#endif
w = 320;
h = 240;
bpp = 32;
system("echo 1 > /sys/class/hdmi/hdmi &");
}
int getBacklight() {
int val = -1;
if (FILE *f = fopen("/sys/class/backlight/pwm-backlight/brightness", "r")) {
fscanf(f, "%i", &val);
fclose(f);
}
return val * (100.0f / 255.0f);
}
public:
void enableTerminal() {
/* Enable the framebuffer console */
char c = '1';
int fd = open("/sys/devices/virtual/vtconsole/vtcon1/bind", O_WRONLY);
if (fd) {
write(fd, &c, 1);
close(fd);
}
fd = open("/dev/tty1", O_RDWR);
if (fd) {
ioctl(fd, VT_ACTIVATE, 1);
close(fd);
}
}
void setScaleMode(unsigned int mode) {
if (FILE *f = fopen("/sys/devices/platform/jz-lcd.0/keep_aspect_ratio", "w")) {
fprintf(f, "%d", (mode == 1));
fclose(f);
}
if (FILE *f = fopen("/sys/devices/platform/jz-lcd.0/integer_scaling", "w")) {
fprintf(f, "%d", (mode == 2));
fclose(f);
}
}
int setBacklight(int val, bool popup = false) {
if (val < 1 && getUDCStatus() != UDC_REMOVE) {
val = 0; // suspend only if not charging
} else if (popup) {
val = GMenu2X::setBacklight(val, popup);
}
if (FILE *f = fopen("/sys/class/graphics/fb0/blank", "w")) {
fprintf(f, "%d", val <= 0);
fclose(f);
}
if (FILE *f = fopen("/sys/class/backlight/pwm-backlight/brightness", "w")) {
fprintf(f, "%d", val * (255.0f / 100.0f)); // fputs(val, f);
fclose(f);
}
return val;
}
int setVolume(int val, bool popup = false) {
val = GMenu2X::setVolume(val, popup);
val = val * (63.0f / 100.0f);
int hp = 0;
char cmd[96];
if (val > 32) {
hp = 31;
val -= 32;
} else if (val > 1) {
hp = val;
val = 1;
}
sprintf(cmd, "alsa-setvolume default Headphone %d; alsa-setvolume default PCM %d", hp, val);
system(cmd);
return (val + hp) * (100.0f / 63.0f);
}
int getVolume() {
int pcm = 0, hp = 0;
if (FILE *f = popen("alsa-getvolume default PCM", "r")) {
fscanf(f, "%i", &pcm);
pclose(f);
}
if (FILE *f = popen("alsa-getvolume default Headphone", "r")) {
fscanf(f, "%i", &hp);
pclose(f);
}
return (pcm + hp) * (100.0f / 63.0f);
}
};
#endif
| 4,267
|
C++
|
.h
| 173
| 21.861272
| 100
| 0.622261
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,139
|
retrofw.h
|
MiyooCFW_gmenu2x/src/platform/retrofw.h
|
#ifndef HW_RETROFW_H
#define HW_RETROFW_H
#include <sys/mman.h>
#include <linux/soundcard.h>
/* RetroGame Key Codes. pingflood, 2018
BUTTON GMENU SDL NUMERIC GPIO
-----------------------------------------------------------------------------
X MODIFIER SDLK_SPACE 32 !(mem[PEPIN] >> 07 & 1)
A CONFIRM SDLK_LCTRL 306 !(mem[PDPIN] >> 22 & 1)
B CANCEL SDLK_LALT 308 !(mem[PDPIN] >> 23 & 1)
Y MANUAL SDLK_LSHIFT 304 !(mem[PEPIN] >> 11 & 1)
L SECTION_PREV SDLK_TAB 9 !(mem[PBPIN] >> 23 & 1)
R SECTION_NEXT SDLK_BACKSPACE 8 !(mem[PDPIN] >> 24 & 1)
START SETTINGS SDLK_RETURN 13 (mem[PDPIN] >> 18 & 1)
SELECT MENU SDLK_ESCAPE 27 (mem[PDPIN] >> 17 & 1)
BACKLIGHT BACKLIGHT SDLK_3 51 !(mem[PDPIN] >> 21 & 1)
POWER POWER SDLK_END 279 !(mem[PAPIN] >> 30 & 1)
UP UP SDLK_UP 273 !(mem[PBPIN] >> 25 & 1)
DOWN DOWN SDLK_DOWN 274 !(mem[PBPIN] >> 24 & 1)
RIGHT RIGHT SDLK_RIGHT 275 !(mem[PBPIN] >> 26 & 1)
LEFT LEFT SDLK_LEFT 276 !(mem[PDPIN] >> 00 & 1)
*/
volatile uint32_t *mem;
volatile uint8_t memdev = 0;
int32_t tickBattery = 0;
#define BASE 0x10000000
#define CPPCR (0x10 >> 2)
#define PAPIN (0x10000 >> 2)
#define PBPIN (0x10100 >> 2)
#define PCPIN (0x10200 >> 2)
#define PDPIN (0x10300 >> 2)
#define PEPIN (0x10400 >> 2)
#define PFPIN (0x10500 >> 2)
uint16_t getMMCStatus() {
if (memdev > 0 && !(mem[PFPIN] >> 0 & 1)) return MMC_INSERT;
return MMC_REMOVE;
}
uint16_t getUDCStatus() {
// if (memdev > 0 && ((mem[PDPIN] >> 7 & 1) || (mem[PEPIN] >> 13 & 1))) return UDC_CONNECT;
if (memdev > 0 && (mem[PDPIN] >> 7 & 1)) return UDC_CONNECT;
return UDC_REMOVE;
}
uint16_t getTVOutStatus() {
if (memdev > 0) {
if (fwType == "RETROARCADE" && !(mem[PDPIN] >> 6 & 1)) return TV_CONNECT;
if (!(mem[PDPIN] >> 25 & 1)) return TV_CONNECT;
}
return TV_REMOVE;
}
uint16_t getDevStatus() {
char buf[10000];
if (FILE *f = fopen("/proc/bus/input/devices", "r")) {
size_t val = fread(buf, sizeof(char), 10000, f);
fclose(f);
return val;
}
return 0;
}
int32_t getBatteryLevel() {
int val = -1;
if (FILE *f = fopen("/proc/jz/battery", "r")) {
fscanf(f, "%i", &val);
fclose(f);
}
return val;
}
uint8_t getBatteryStatus(int32_t val, int32_t min, int32_t max) {
if ((val > 10000) || (val < 0)) return 6;
if (val > 4000) return 5; // 100%
if (val > 3900) return 4; // 80%
if (val > 3800) return 3; // 60%
if (val > 3700) return 2; // 40%
if (val > 3520) return 1; // 20%
return 0; // 0% :(
}
uint16_t getTVOut() {
int val = 0;
if (FILE *f = fopen("/proc/jz/tvout", "r")) {
fscanf(f, "%i", &val);
fclose(f);
}
return val;
}
uint16_t getVolumeMode(uint8_t vol) {
if (!vol) return VOLUME_MODE_MUTE;
if (memdev > 0 && !(mem[PDPIN] >> 6 & 1)) return VOLUME_MODE_PHONES;
return VOLUME_MODE_NORMAL;
}
void printbin(const char *id, int n) {
printf("%s: 0x%08x ", id, n);
for (int i = 31; i >= 0; i--) {
printf("%d", !!(n & 1 << i));
if (!(i % 8)) printf(" ");
}
printf("\e[0K\n");
}
uint32_t hwCheck(unsigned int interval = 0, void *param = NULL) {
tickBattery++;
if (tickBattery > 30) { // update battery level every 30 hwChecks
tickBattery = 0;
batteryIcon = getBatteryStatus(getBatteryLevel(), 0, 0);
}
if (memdev > 0 && tickBattery > 2) {
udcStatus = getUDCStatus();
if (udcPrev != udcStatus) {
udcPrev = udcStatus;
InputManager::pushEvent(udcStatus);
return 2000;
}
mmcStatus = getMMCStatus();
if (mmcPrev != mmcStatus) {
mmcPrev = mmcStatus;
InputManager::pushEvent(mmcStatus);
if (mmcStatus == MMC_REMOVE) {
system("umount -fl /mnt &> /dev/null");
}
return 2000;
}
volumeMode = getVolumeMode(1);
if (volumeModePrev != volumeMode) {
volumeModePrev = volumeMode;
InputManager::pushEvent(PHONES_CONNECT);
return 2000;
}
if (fwType == "RETROARCADE") {
numJoy = getDevStatus();
if (numJoyPrev != numJoy) {
numJoyPrev = numJoy;
InputManager::pushEvent(JOYSTICK_CONNECT);
return 3000;
}
}
tvOutStatus = getTVOutStatus();
if (tvOutPrev != tvOutStatus) {
tvOutPrev = tvOutStatus;
InputManager::pushEvent(tvOutStatus);
return 2000;
}
// volumeMode = getVolumeMode(confInt["globalVolume"]);
// if (volumeModePrev != volumeMode && volumeMode == VOLUME_MODE_PHONES) {
// setVolume(min(70, confInt["globalVolume"]), true);
// }
// volumeModePrev = volumeMode;
}
return interval;
}
class GMenu2X_platform : public GMenu2X {
private:
void hwDeinit() {
if (memdev > 0) {
close(memdev);
}
}
void hwInit() {
CPU_MENU = 528;
CPU_LINK = 600;
CPU_MAX = CPU_MENU * 2;
CPU_MIN = CPU_MENU / 2;
CPU_STEP = 6;
batteryIcon = getBatteryStatus(getBatteryLevel(), 0, 0);
system("[ -d /home/retrofw ] && mount -o remount,async /home/retrofw");
#if defined(OPK_SUPPORT)
system("umount -fl /mnt &> /dev/null");
#endif
memdev = open("/dev/mem", O_RDWR);
if (memdev > 0) {
mem = (uint32_t*)mmap(0, 0x20000, PROT_READ | PROT_WRITE, MAP_SHARED, memdev, BASE);
if (mem == MAP_FAILED) {
ERROR("Could not mmap hardware registers!");
close(memdev);
}
} else {
WARNING("Could not open /dev/mem");
}
struct fb_var_screeninfo vinfo;
int fbdev = open("/dev/fb0", O_RDWR);
if (fbdev >= 0 && ioctl(fbdev, FBIOGET_VSCREENINFO, &vinfo) >= 0) {
w = vinfo.width;
h = vinfo.height;
close(fbdev);
}
if (w == 320 && h == 480) h = 240;
if (FILE *f = fopen("/proc/jz/gpio", "r")) {
char buf[7];
fread(buf, sizeof(char), 7, f);
fclose(f);
if (!strncmp(buf, "480x272", 7)) {
fwType = "RETROARCADE";
}
}
INFO("%s", fwType.c_str());
}
void udcDialog(int udcStatus) {
if (udcStatus == UDC_REMOVE) {
INFO("USB Disconnected. Disabling devices...");
system("/usr/bin/retrofw stop");
return;
}
int option;
if (confStr["usbMode"] == "Storage") option = CONFIRM;
else if (confStr["usbMode"] == "Charger") option = CANCEL;
else {
MessageBox mb(this, tr["USB mode"], "skin:icons/usb.png");
mb.setButton(CANCEL, tr["Charger"]);
mb.setButton(CONFIRM, tr["Storage"]);
option = mb.exec();
}
if (option == CONFIRM) { // storage
INFO("Enabling storage device");
quit();
execlp("/bin/sh", "/bin/sh", "-c", "exec /usr/bin/retrofw storage on", NULL);
return;
}
INFO("Enabling networking device");
system("/usr/bin/retrofw network on");
iconInet = sc["skin:imgs/inet.png"];
}
void tvOutDialog(int16_t mode) {
if (!file_exists("/proc/jz/tvout")) return;
if (mode < 0) {
int option;
mode = TV_OFF;
if (confStr["tvMode"] == "NTSC") option = CONFIRM;
else if (confStr["tvMode"] == "PAL") option = MANUAL;
else if (confStr["tvMode"] == "OFF") option = CANCEL;
else {
MessageBox mb(this, tr["TV-out connected. Enable?"], "skin:icons/tv.png");
mb.setButton(CONFIRM, tr["NTSC"]);
mb.setButton(MANUAL, tr["PAL"]);
mb.setButton(CANCEL, tr["OFF"]);
option = mb.exec();
}
switch (option) {
case CONFIRM:
mode = TV_NTSC;
break;
case MANUAL:
mode = TV_PAL;
break;
}
}
if (mode != getTVOut()) {
setTVOut(mode);
setBacklight(confInt["backlight"]);
writeTmp();
exit(0);
}
}
int getBacklight() {
int val = -1;
if (FILE *f = fopen("/proc/jz/backlight", "r")) {
fscanf(f, "%i", &val);
fclose(f);
}
return val;
}
public:
int getVolume() {
int vol = -1;
uint32_t soundDev = open("/dev/mixer", O_RDONLY);
if (soundDev) {
ioctl(soundDev, SOUND_MIXER_READ_VOLUME, &vol);
close(soundDev);
if (vol != -1) {
// just return one channel , not both channels, they're hopefully the same anyways
return vol & 0xFF;
}
}
return vol;
}
int setVolume(int val, bool popup = false) {
val = GMenu2X::setVolume(val, popup);
uint32_t soundDev = open("/dev/mixer", O_RDWR);
if (soundDev) {
int vol = (val << 8) | val;
ioctl(soundDev, SOUND_MIXER_WRITE_VOLUME, &vol);
close(soundDev);
}
volumeMode = getVolumeMode(val);
return val;
}
int setBacklight(int val, bool popup = false) {
if (val < 1 && getUDCStatus() != UDC_REMOVE /* && !getTVOut() */) {
val = 0; // suspend only if not charging and TV out is not enabled
} else if (popup) {
val = GMenu2X::setBacklight(val, popup);
}
if (FILE *f = fopen("/proc/jz/backlight", "w")) {
if (val == 0) {
fprintf(f, "-"); // disable backlight button
}
fprintf(f, "%d", val); // fputs(val, f);
fclose(f);
}
return val;
}
void setScaleMode(unsigned int mode) {
/* Scaling Modes:
0: stretch
1: aspect
2: original (fallback to aspect when downscale is needed)
3: 4:3
*/
if (FILE *f = fopen("/proc/jz/ipu", "w")) {
fprintf(f, "%d", mode); // fputs(val, f);
fclose(f);
}
}
void setTVOut(unsigned int mode) {
if (FILE *f = fopen("/proc/jz/tvout", "w")) {
fprintf(f, "%d", mode); // fputs(val, f);
fclose(f);
}
}
void setCPU(uint32_t mhz) {
if (getTVOut()) {
WARNING("Can't overclock when TV out is enabled.");
return;
}
mhz = constrain(mhz, confInt["cpuMenu"], confInt["cpuMax"]);
if (memdev > 0) {
DEBUG("Setting clock to %d", mhz);
uint32_t m = mhz / 6;
mem[CPPCR] = (m << 24) | 0x090520;
INFO("CPU clock: %d MHz", mhz);
}
}
string hwPreLinkLaunch() {
system("[ -d /home/retrofw ] && mount -o remount,sync /home/retrofw");
return "";
}
};
#endif
| 9,709
|
C++
|
.h
| 333
| 26.111111
| 92
| 0.593971
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,140
|
linux.h
|
MiyooCFW_gmenu2x/src/platform/linux.h
|
#ifndef HW_PC_H
#define HW_PC_H
#include <linux/soundcard.h>
#define TTS_ENGINE "espeak"
volatile uint16_t *memregs;
uint8_t memdev = 0;
int SOUND_MIXER_READ = SOUND_MIXER_READ_PCM;
int SOUND_MIXER_WRITE = SOUND_MIXER_WRITE_PCM;
int32_t setTVoff() {
return 0;
}
uint16_t getDevStatus() {
FILE *f;
char buf[10000];
if (f = fopen("/proc/bus/input/devices", "r")) {
// if (f = fopen("/proc/bus/input/handlers", "r")) {
size_t sz = fread(buf, sizeof(char), 10000, f);
fclose(f);
return sz;
}
return 0;
}
uint32_t hwCheck(unsigned int interval = 0, void *param = NULL) {
printf("%s:%d: %s\n", __FILE__, __LINE__, __func__);
numJoy = getDevStatus();
if (numJoyPrev != numJoy) {
numJoyPrev = numJoy;
InputManager::pushEvent(JOYSTICK_CONNECT);
}
return 0;
}
uint8_t getMMCStatus() {
return MMC_REMOVE;
}
uint8_t getUDCStatus() {
return UDC_REMOVE;
}
uint8_t getTVOutStatus() {
return TV_REMOVE;
}
int16_t getBatteryLevel() {
return 0;
}
uint8_t getBatteryStatus(int32_t val, int32_t min, int32_t max) {
return 6;
}
uint8_t getVolumeMode(uint8_t vol) {
return VOLUME_MODE_NORMAL;
}
class GMenu2X_platform : public GMenu2X {
private:
void hwInit() {
CPU_MENU = 528;
CPU_LINK = 600;
CPU_MAX = 700;
CPU_MIN = 500;
CPU_STEP = 5;
w = 320;
h = 240;
}
uint16_t getBatteryLevel() {
return 6;
};
};
#endif
| 1,353
|
C++
|
.h
| 65
| 18.815385
| 65
| 0.686861
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,141
|
libopk.h
|
MiyooCFW_gmenu2x/src/libopk/libopk.h
|
#ifndef OPK_H
#define OPK_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
struct OPK;
struct OPK *opk_open(const char *opk_filename);
void opk_close(struct OPK *opk);
/* Open the next meta-data file.
* if 'filename' is set, the pointer passed as argument will
* be set to point to a string corresponding to the filename.
* XXX: the pointer will be invalid as soon as opk_close() is called.
*
* Returns:
* -EIO if the file cannot be read,
* -ENOMEM if the buffer cannot be allocated,
* 0 if no more meta-data file can be found,
* 1 otherwise.
*/
int opk_open_metadata(struct OPK *opk, const char **filename);
/* Read a key/value pair.
* 'key_chars' and 'val_chars' must be valid pointers. The pointers passed
* as arguments will point to the key and value read. 'key_size' and
* 'val_size' are set to the length of their respective char arrays.
* XXX: the pointers will be invalid as soon as opk_close() is called.
*
* Returns:
* -EIO if the file cannot be read,
* 0 if no more key/value pairs can be found,
* 1 otherwise.
*/
int opk_read_pair(struct OPK *opk,
const char **key_chars, size_t *key_size,
const char **val_chars, size_t *val_size);
/* Extract the file with the given filename from the OPK archive.
* The 'data' pointer is set to an allocated buffer containing
* the file's content. The 'size' variable is set to the length
* of the buffer, in bytes.
*
* Returns:
* -ENOENT if the file to extract is not found,
* -ENOMEM if the buffer cannot be allocated,
* -EIO if the file cannot be read,
* 0 otherwise.
*/
int opk_extract_file(struct OPK *opk,
const char *name, void **data, size_t *size);
#ifdef __cplusplus
}
#endif
#endif /* OPK_H */
| 1,723
|
C++
|
.h
| 52
| 31.230769
| 74
| 0.71463
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,142
|
ini.h
|
MiyooCFW_gmenu2x/src/libopk/ini.h
|
/*
* libini - Library to read INI configuration files
*
* Copyright (C) 2014 Paul Cercueil <paul@crapouillou.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*/
#ifndef __INI_H
#define __INI_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _WIN32
# ifdef LIBINI_EXPORTS
# define __api __declspec(dllexport)
# else
# define __api __declspec(dllimport)
# endif
#elif __GNUC__ >= 4
# define __api __attribute__((visibility ("default")))
#else
# define __api
#endif
#include <stdlib.h>
struct INI;
__api struct INI *ini_open(const char *file);
__api struct INI *ini_open_mem(const char *buf, size_t len);
__api void ini_close(struct INI *ini);
/* Jump to the next section.
* if 'name' is set, the pointer passed as argument
* points to the name of the section. 'name_len' is set to the length
* of the char array.
* XXX: the pointer will be invalid as soon as ini_close() is called.
*
* Returns:
* -EIO if an error occured while reading the file,
* 0 if no more section can be found,
* 1 otherwise.
*/
__api int ini_next_section(struct INI *ini,
const char **name, size_t *name_len);
/* Read a key/value pair.
* 'key' and 'value' must be valid pointers. The pointers passed as arguments
* will point to the key and value read. 'key_len' and 'value_len' are
* set to the length of their respective char arrays.
* XXX: the pointers will be invalid as soon as ini_close() is called.
*
* Returns:
* -EIO if an error occured while reading the file,
* 0 if no more key/value pairs can be found,
* 1 otherwise.
*/
__api int ini_read_pair(struct INI *ini,
const char **key, size_t *key_len,
const char **value, size_t *value_len);
/* Set the read head to a specified offset. */
__api void ini_set_read_pointer(struct INI *ini, const char *pointer);
/* Get the number of the line that contains the specified address.
*
* Returns:
* -EINVAL if the pointer points outside the INI string,
* The line number otherwise.
*/
__api int ini_get_line_number(struct INI *ini, const char *pointer);
#ifdef __cplusplus
}
#endif
#undef __api
#endif /* __INI_H */
| 2,579
|
C++
|
.h
| 77
| 31.701299
| 77
| 0.717846
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,143
|
unsqfs.h
|
MiyooCFW_gmenu2x/src/libopk/unsqfs.h
|
#ifndef PRIVATE_H
#define PRIVATE_H
struct PkgData;
struct PkgData *opk_sqfs_open(const char *image_name);
void opk_sqfs_close(struct PkgData *pdata);
int opk_sqfs_extract_file(struct PkgData *pdata, const char *name,
void **out_data, size_t *out_size);
int opk_sqfs_get_metadata(struct PkgData *pdata, const char **filename);
#endif
| 339
|
C++
|
.h
| 9
| 36.111111
| 72
| 0.7737
|
MiyooCFW/gmenu2x
| 30
| 27
| 9
|
GPL-2.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,144
|
tessellation.cpp
|
agordon_openscad-step-reader/tessellation.cpp
|
/*
* Copyright 2019 Assaf Gordon <assafgordon@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*/
#include <BRepPrimAPI_MakeCylinder.hxx>
#include <BRepPrimAPI_MakeCone.hxx>
#include <BRepPrimAPI_MakeBox.hxx>
#include <BRepPrimAPI_MakeSphere.hxx>
#include <BRepPrimAPI_MakePrism.hxx>
#include <BRepAlgoAPI_Cut.hxx>
#include <BRepAlgoAPI_Fuse.hxx>
#include <BRepAlgoAPI_Common.hxx>
#include <BRepBuilderAPI_Sewing.hxx>
#include <BRepBuilderAPI_MakeSolid.hxx>
#include <TopoDS_Shell.hxx>
#include <TopExp.hxx>
#include <TopoDS.hxx>
#include <ShapeFix_Shape.hxx>
#include <BRepGProp.hxx>
#include <STEPControl_Reader.hxx>
#include <STEPControl_Writer.hxx>
#include <GProp_GProps.hxx>
#include <IGESControl_Reader.hxx>
#include <IGESControl_Writer.hxx>
#include <BRepTools.hxx>
#include <BRep_Builder.hxx>
#include <StlAPI_Writer.hxx>
#include <BRepMesh_IncrementalMesh.hxx>
#include <RWStl.hxx>
#include <Poly_Triangulation.hxx>
#include <OSD_Path.hxx>
#include <TopoDS_Compound.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Wire.hxx>
#include <TopoDS_Face.hxx>
#include <Bnd_Box.hxx>
#include <BRepBndLib.hxx>
#include <BRepBuilderAPI_MakeVertex.hxx>
#include <BRepBuilderAPI_MakePolygon.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <gp_Circ.hxx>
#include <TopExp_Explorer.hxx>
#include <Font_BRepFont.hxx>
#include <Font_BRepTextBuilder.hxx>
#include <BRepBuilderAPI_GTransform.hxx>
#include <BRepBuilderAPI_Transform.hxx>
#include <gp_GTrsf.hxx>
#include <BRepFilletAPI_MakeFillet.hxx>
#include <BRepFilletAPI_MakeChamfer.hxx>
#include <TColgp_HArray1OfPnt.hxx>
#include <BRepTools_WireExplorer.hxx>
#include <math.hxx>
#include "triangle.h"
#include "tessellation.h"
Face tessellate_face(const TopoDS_Face &aFace)
{
Face output_face;
/* This code is based on
https://www.opencascade.com/content/how-get-triangles-vertices-data-absolute-coords-native-opengl-rendering
*/
TopAbs_Orientation faceOrientation = aFace.Orientation();
TopLoc_Location aLocation;
Handle(Poly_Triangulation) aTr = BRep_Tool::Triangulation(aFace,aLocation);
if(!aTr.IsNull())
{
const TColgp_Array1OfPnt& aNodes = aTr->Nodes();
const Poly_Array1OfTriangle& triangles = aTr->Triangles();
const TColgp_Array1OfPnt2d & uvNodes = aTr->UVNodes();
TColgp_Array1OfPnt aPoints(1, aNodes.Length());
for(Standard_Integer i = 1; i < aNodes.Length()+1; i++)
aPoints(i) = aNodes(i).Transformed(aLocation);
Standard_Integer nnn = aTr->NbTriangles();
Standard_Integer nt,n1,n2,n3;
for( nt = 1 ; nt < nnn+1 ; nt++)
{
triangles(nt).Get(n1,n2,n3);
if (faceOrientation != TopAbs_Orientation::TopAbs_FORWARD)
{
int tmp = n1;
n1 = n3;
n3 = tmp;
}
gp_Pnt aPnt1 = aPoints(n1);
gp_Pnt aPnt2 = aPoints(n2);
gp_Pnt aPnt3 = aPoints(n3);
const Triangle tr(aPnt1, aPnt2, aPnt3);
output_face.addTriangle(tr);
}
}
return output_face;
}
Face_vector tessellate_shape (const TopoDS_Shape& shape)
{
Face_vector output_faces;
for (TopExp_Explorer FaceExp(shape, TopAbs_FACE); FaceExp.More(); FaceExp.Next())
{
const TopoDS_Face &aFace = TopoDS::Face(FaceExp.Current());
const Face &f = tessellate_face(aFace);
output_faces.push_back(f);
}
return output_faces;
}
| 3,778
|
C++
|
.cpp
| 113
| 31.39823
| 111
| 0.766383
|
agordon/openscad-step-reader
| 30
| 10
| 3
|
LGPL-2.1
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,145
|
openscad-step-reader.cpp
|
agordon_openscad-step-reader/openscad-step-reader.cpp
|
/*
* Copyright 2019 Assaf Gordon <assafgordon@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*/
#include <iostream>
#include <string>
#include <err.h>
#include <getopt.h>
#include <STEPControl_Reader.hxx>
#include <StlAPI_Writer.hxx>
#include <BRepMesh_IncrementalMesh.hxx>
#include "triangle.h"
#include "tessellation.h"
#include "openscad-triangle-writer.h"
#include "explore-shape.h"
static struct option options[] = {
{"help", no_argument, 0, 'h' },
{"version", no_argument, 0, 'V' },
{"stl-ascii", no_argument, 0, 'a' },
{"stl-scad", no_argument, 0, 's' },
{"stl-faces", no_argument, 0, 'f' },
{"stl-occt", no_argument, 0, 'o' },
{"stl-lin-tol", required_argument, 0, 'L'},
{"explore", no_argument, 0, 'e' },
};
void show_help()
{
std::cout << "openscad-step-reader\n"
"\n"
"A proof-of-concept program for STEP/OpenSCAD integration\n"
"\n"
"usage: openscad-step-reader [options] INPUT.STEP\n"
"\n"
"Output is written to STDOUT.\n"
"\n"
"options are:\n"
" -h, --help this help screen\n"
" -V, --version version information\n"
"\n"
" -o, --stl-occt convert the input STEP file into ASCII STL file\n"
" using OpenCASCADE code. This should be the baseline\n"
" when debugging/troubleshooting incorrect outputs.\n"
"\n"
" -a, --stl-ascii convert the input STEP file into custom ASCII STL file,\n"
" using our code. This is a good test to check mesh\n"
" triangulation code. EXCEPT for the 'normal' values\n"
" which are not produced, the vertex values should be\n"
" equivalent to those with --stl-occt.\n"
"\n"
" -s, --stl-scad convert the input STEP file into SCAD code, containing\n"
" a single 'polyhedron' call with the STL triangles stored\n"
" in SCAD vectors.\n"
"\n"
" -f, --stl-faces convert the input STEP file into SCAD code, retaining the\n"
" 'face' information from the STEP file. Each face will be rendered\n"
" in a different color in openscad $preview mode.\n"
"\n"
" -e, --explore Work-in-progress code, used for development and exploration\n"
" of OpenCASCADE class hierarchy, e.g.\n"
" Shell->Face->Surface->Wire->Edge->Vertex.\n"
" produces debug messges and no useful output.\n"
"\n"
"Written by Assaf Gordon (assafgordon@gmail.com)\n"
"License: LGPLv2.1 or later\n"
"\n";
exit(0);
}
void show_version()
{
std::cout << 42 << endl;
exit(0);
}
int main(int argc, char *argv[])
{
double stl_lin_tol = 0.5 ; //default linear tolerace.
int c;
enum {
OUT_UNDEFINED,
OUT_STL_ASCII,
OUT_STL_SCAD,
OUT_STL_FACES,
OUT_STL_OCCT,
OUT_EXPLORE
} output = OUT_UNDEFINED;
while ((c = getopt_long(argc, argv, "hVasfoL:e", options, NULL))!=-1) {
switch (c)
{
case 'h':
show_help();
break;
case 'v':
show_version();
break;
case 'a':
output = OUT_STL_ASCII;
break;
case 's':
output = OUT_STL_SCAD;
break;
case 'f':
output = OUT_STL_FACES;
break;
case 'o':
output = OUT_STL_OCCT;
break;
case 'e':
output = OUT_EXPLORE;
break;
case 'L':
stl_lin_tol = atof(optarg);
if (stl_lin_tol<=0)
errx(1,"invalid tolerance value '%s'",optarg);
break;
}
}
if (optind >= argc)
errx(1,"missing input STEP filename. Use --help for usage information");
if (output == OUT_UNDEFINED)
errx(1,"missing output format option. Use --help for usage information");
std::string filename(argv[optind]);
/* Load the shape from STEP file.
See https://github.com/miho/OCC-CSG/blob/master/src/occ-csg.cpp#L311
and https://github.com/lvk88/OccTutorial/blob/master/OtherExamples/runners/convertStepToStl.cpp
*/
TopoDS_Shape shape;
STEPControl_Reader Reader;
enum IFSelect_ReturnStatus s = Reader.ReadFile(filename.c_str());
if (s != IFSelect_RetDone)
err(1,"failed to load STEP file '%s'", filename.c_str());
Reader.TransferRoots();
shape = Reader.OneShape();
/* Is this required (for Tessellation and/or StlAPI_Writer?) */
BRepMesh_IncrementalMesh mesh( shape, stl_lin_tol);
mesh.Perform();
Face_vector faces;
if ( (output==OUT_STL_ASCII) || (output==OUT_STL_SCAD) || (output==OUT_STL_FACES) )
faces = tessellate_shape (shape);
switch (output)
{
case OUT_STL_ASCII:
write_triangles_ascii_stl(faces);
break;
case OUT_STL_SCAD:
write_triangle_scad(faces);
break;
case OUT_STL_FACES:
write_faces_scad(faces);
break;
case OUT_STL_OCCT:
try
{
StlAPI_Writer writer;
writer.Write(shape,"/dev/stdout");
} catch(Standard_ConstructionError& e) {
errx(1,"failed to write OCCT/STL: %s", e.GetMessageString());
}
break;
case OUT_EXPLORE:
explore_shape (shape);
break;
}
return 0;
}
| 5,368
|
C++
|
.cpp
| 172
| 28.883721
| 99
| 0.658404
|
agordon/openscad-step-reader
| 30
| 10
| 3
|
LGPL-2.1
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,146
|
shape_explorer.cpp
|
agordon_openscad-step-reader/shape_explorer.cpp
|
std::string SurfaceTypeName ( enum GeomAbs_SurfaceType t )
{
switch (t)
{
case GeomAbs_Plane:
return "Plane";
case GeomAbs_Cylinder:
return "Cylinder";
case GeomAbs_Cone:
return "Cone";
case GeomAbs_Sphere:
return "Sphere";
case GeomAbs_Torus:
return "Torus";
case GeomAbs_BezierSurface:
return "Bezier";
case GeomAbs_BSplineSurface:
return "BSplineSurface";
case GeomAbs_SurfaceOfRevolution:
return "SurfaceOfRevolution";
case GeomAbs_SurfaceOfExtrusion:
return "SurfaceOfExtrusion";
case GeomAbs_OffsetSurface:
return "OffsetSurface";
case GeomAbs_OtherSurface:
return "OtherSurface";
}
return "UNKNOWN";
}
std::string OrientationName (enum TopAbs_Orientation o)
{
switch (o)
{
case TopAbs_FORWARD:
return "FORWARD";
case TopAbs_REVERSED:
return "REVERSED";
case TopAbs_INTERNAL:
return "INTERNAL";
case TopAbs_EXTERNAL:
return "EXTERNAL";
}
return "UNKNOWN";
}
| 918
|
C++
|
.cpp
| 44
| 18.636364
| 58
| 0.770905
|
agordon/openscad-step-reader
| 30
| 10
| 3
|
LGPL-2.1
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,147
|
openscad-triangle-writer.cpp
|
agordon_openscad-step-reader/openscad-triangle-writer.cpp
|
/*
* Copyright 2019 Assaf Gordon <assafgordon@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*/
#include <ostream>
#include <iostream>
#include <vector>
#include <gp_Pnt.hxx>
#include "triangle.h"
using namespace std;
/* Write the faces/triangles as an ASCII stl file
(with invalud 'normals' value - but these are ignored anyhow in OpenSCAD */
void write_triangles_ascii_stl(const Face_vector& faces)
{
cout << "solid" << endl;
for (auto &f : faces)
f.write_ascii_stl(cout);
cout << "endsolid" << endl;
}
/* Write the faces/triangles as two vectors (one "POINTS", one "FACES")
that will be used with a single call to "polyhedron"). */
void write_triangle_scad(const Face_vector& faces)
{
Face all;
// Merge all faces (i.e. triangles from all faces)
// into one "face" (just a container, no special meaning of a "face").
for (auto &f : faces)
all.add_face(f);
// Write vector of points and faces
cout << "points = " ;
all.write_points_vector(cout);
cout << "faces = ";
all.write_face_vector(cout);
// Call Polyhedron
cout << "module solid_object() {" << endl;
cout << " polyhedron (points,faces);"<< endl;
cout << "}" << endl;
cout << endl;
cout << "solid_object();" << endl;
}
#define NUM_COLORS 12
const char* colors[NUM_COLORS] = {
"black",
"Violet",
"red",
"blue",
"LawnGreen",
"Orange",
"DeepPink",
"Gold",
"Cyan",
"Olive",
"Gray",
"SpringGreen"
};
/* Write every faces (i.e. all trianges of each face) into a separate points/faces
vector pairs.
Include $preview code to show each face in a different color
(sadly, resulting in an invalid 3D object which can't be exported to STL,
because each face is a 2D object with depth of ZERO).
In non-preview mode,
Include code to merge all the vectors and make a single "Polyhedron" call. */
void write_faces_scad (const Face_vector& faces)
{
int i = 1;
for (auto &f : faces) {
cout << "face_" << i << "_points = " ;
f.write_points_vector(cout);
cout << "face_" << i << "_faces = " ;
f.write_face_vector(cout);
cout << endl ;
++i;
}
/* crazy colors version, draw each face by itself */
cout << "module crazy_colors() {" << endl;
for (i=1;i<=faces.size();++i) {
const char* color = colors[i%NUM_COLORS] ;
cout << "color(\"" << color << "\")" << endl;
cout << "polyhedron(face_" << i <<"_points, face_" << i << "_faces);" << endl ;
}
cout << "}" << endl;
cout << "function add_offset(vec,ofs) = [for (x=vec) x + [ofs,ofs,ofs]];" << endl;
cout << "module solid_object() {" << endl;
cout << " tmp1_points = face_1_points;" << endl;
cout << " tmp1_faces = face_1_faces;" << endl;
cout << endl;
for (i=2;i<=faces.size();++i) {
cout << " tmp"<<i<<"_points = concat(tmp"<<(i-1)<<"_points, face_"<<i<<"_points);" << endl;
cout << " tmp"<<i<<"_faces = concat(tmp"<<(i-1)<<"_faces,add_offset(face_"<<i<<"_faces,len(tmp"<<(i-1)<<"_points)));" << endl;
cout << endl;
}
cout << " polyhedron (tmp"<<(faces.size())<<"_points, tmp"<<(faces.size())<<"_faces);"<< endl;
cout << "}" << endl;
cout << endl;
cout << endl;
cout << "if ($preview) {;" << endl;
cout << " crazy_colors();" << endl;
cout << "} else {" << endl;
cout << " solid_object();" << endl;
cout << "}" << endl;
}
| 3,726
|
C++
|
.cpp
| 110
| 31.618182
| 130
| 0.643215
|
agordon/openscad-step-reader
| 30
| 10
| 3
|
LGPL-2.1
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,148
|
explore-shape.cpp
|
agordon_openscad-step-reader/explore-shape.cpp
|
/*
* Copyright 2019 Assaf Gordon <assafgordon@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*/
#include <BRepBuilderAPI_MakeSolid.hxx>
#include <TopoDS_Shell.hxx>
#include <TopExp.hxx>
#include <TopoDS.hxx>
#include <ShapeFix_Shape.hxx>
#include <BRepGProp.hxx>
#include <GProp_GProps.hxx>
#include <BRepTools.hxx>
#include <BRep_Builder.hxx>
#include <BRepMesh_IncrementalMesh.hxx>
#include <TopoDS_Compound.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Wire.hxx>
#include <TopoDS_Face.hxx>
#include <Bnd_Box.hxx>
#include <BRepBndLib.hxx>
#include <gp_Circ.hxx>
#include <TopExp_Explorer.hxx>
#include <gp_GTrsf.hxx>
#include <TColgp_HArray1OfPnt.hxx>
#include <BRepTools_WireExplorer.hxx>
#include <math.hxx>
/* good resources:
https://github.com/miho/OCC-CSG
https://github.com/lvk88/OccTutorial
https://dev.opencascade.org/doc/overview/html/index.html#OCCT_OVW_SECTION_7
*/
std::string SurfaceTypeName ( enum GeomAbs_SurfaceType t )
{
switch (t)
{
case GeomAbs_Plane:
return "Plane";
case GeomAbs_Cylinder:
return "Cylinder";
case GeomAbs_Cone:
return "Cone";
case GeomAbs_Sphere:
return "Sphere";
case GeomAbs_Torus:
return "Torus";
case GeomAbs_BezierSurface:
return "Bezier";
case GeomAbs_BSplineSurface:
return "BSplineSurface";
case GeomAbs_SurfaceOfRevolution:
return "SurfaceOfRevolution";
case GeomAbs_SurfaceOfExtrusion:
return "SurfaceOfExtrusion";
case GeomAbs_OffsetSurface:
return "OffsetSurface";
case GeomAbs_OtherSurface:
return "OtherSurface";
}
return "UNKNOWN";
}
std::string OrientationName (enum TopAbs_Orientation o)
{
switch (o)
{
case TopAbs_FORWARD:
return "FORWARD";
case TopAbs_REVERSED:
return "REVERSED";
case TopAbs_INTERNAL:
return "INTERNAL";
case TopAbs_EXTERNAL:
return "EXTERNAL";
}
return "UNKNOWN";
}
void get_vertex_points_test1 (const TopoDS_Shape& shape)
{
// from: https://www.opencascade.com/content/extracting-boundary-topodsshape
TopTools_IndexedMapOfShape vertices;
TopExp::MapShapes(shape,TopAbs_VERTEX,vertices);
Handle_TColgp_HArray1OfPnt result = new TColgp_HArray1OfPnt(1,vertices.Extent());
for(Standard_Integer i = 1;i<=vertices.Extent();i++)
{
TopoDS_Vertex vertex = TopoDS::Vertex(vertices.FindKey(i));
gp_Pnt currentGeometricPoint = BRep_Tool::Pnt(vertex);
result->SetValue(i,currentGeometricPoint);
}
//Convert to array
//See: https://github.com/lvk88/OccTutorial/blob/master/Chapter1_Basics/src/WriteCoordinatesToFile.cpp
const TColgp_Array1OfPnt& points = result->Array1();
for(Standard_Integer i = points.Lower();i <= points.Upper();i++)
{
std::cout << " vertex " << i << ": " << points.Value(i).X() << " " << points.Value(i).Y() << " " << points.Value(i).Z() << std::endl;
auto &p = points.Value(i);
}
}
void get_vertex_points_test2 (const TopoDS_Shape& shape)
{
//from: https://www.opencascade.com/content/how-get-wires-single-face
int i = 0;
for (TopExp_Explorer anExp(shape, TopAbs_EDGE); anExp.More(); anExp.Next())
{
// Iterate over edges in input shape.
const TopoDS_Edge& anEdge = TopoDS::Edge(anExp.Current());
std::cout << "Edge " << i << " orientatino = " << OrientationName(anEdge.Orientation()) << std::endl;
// Take the first and the last vertices from edge
TopoDS_Vertex aVFirst = TopExp::FirstVertex(anEdge);
TopoDS_Vertex aVLast = TopExp::LastVertex(anEdge);
// Take geometrical information from vertices.
gp_Pnt aPntFirst = BRep_Tool::Pnt(aVFirst);
gp_Pnt aPntLast = BRep_Tool::Pnt(aVLast);
if (anEdge.Orientation() == TopAbs_FORWARD)
{
}
else
{
}
++i;
}
}
void get_vertex_points_test3 (const TopoDS_Shape& shape)
{
//from: https://www.opencascade.com/content/how-get-wires-single-face
int i = 0;
for (TopExp_Explorer anExp(shape, TopAbs_VERTEX); anExp.More(); anExp.Next())
{
const TopoDS_Vertex& anVertex = TopoDS::Vertex(anExp.Current());
std::cout << "Vertex " << i << " orientatino = " << OrientationName(anVertex.Orientation()) << std::endl;
// Take geometrical information from vertices.
gp_Pnt aPnt = BRep_Tool::Pnt(anVertex);
++i;
}
}
void get_wire_edge_points_test4(const TopoDS_Shape& shape)
{
int wire_idx = 0;
for (TopExp_Explorer WireExp(shape, TopAbs_WIRE); WireExp.More(); WireExp.Next())
{
const TopoDS_Wire& aWire = TopoDS::Wire(WireExp.Current());
std::cout << " Wire " << wire_idx << std::endl;
int edge_idx = 0;
for (TopExp_Explorer EdgeExp(aWire, TopAbs_EDGE); EdgeExp.More(); EdgeExp.Next())
{
std::cout << " edge " << edge_idx << std::endl;
const TopoDS_Edge& anEdge = TopoDS::Edge(EdgeExp.Current());
// Take the first and the last vertices from edge
TopoDS_Vertex aVFirst = TopExp::FirstVertex(anEdge);
TopoDS_Vertex aVLast = TopExp::LastVertex(anEdge);
// Take geometrical information from vertices.
gp_Pnt aPntFirst = BRep_Tool::Pnt(aVFirst);
gp_Pnt aPntLast = BRep_Tool::Pnt(aVLast);
std::cout << " VertexFirst " << aPntFirst.X() << ", "
<< aPntFirst.Y() << ", "
<< aPntFirst.Z() << std::endl;
std::cout << " VertexLast " << aPntLast.X() << ", "
<< aPntLast.Y() << ", "
<< aPntLast.Z() << std::endl;
++edge_idx;
}
++wire_idx;
}
}
TopoDS_Shape make_solid(const TopoDS_Shape& shape)
{
BRepBuilderAPI_MakeSolid solidmaker;
int i = 0;
for (TopExp_Explorer fExpl(shape, TopAbs_SHELL); fExpl.More(); fExpl.Next())
{
const TopoDS_Shell &curShell = TopoDS::Shell(fExpl.Current());
++i;
//debugGetVerticesOfShape(curShell);
solidmaker.Add(curShell);
}
std::cout << std::endl;
TopoDS_Shape solid = solidmaker.Solid();
return solid;
}
void explore_shape(const TopoDS_Shape& shape)
{
int shell_i = 0;
for (TopExp_Explorer ShellExp(shape, TopAbs_SHELL); ShellExp.More(); ShellExp.Next())
{
const TopoDS_Shell &curShell = TopoDS::Shell(ShellExp.Current());
std::cout << "Shell " << shell_i << std::endl;
int i = 0;
for (TopExp_Explorer FaceExp(curShell, TopAbs_FACE); FaceExp.More(); FaceExp.Next())
{
const TopoDS_Face &aFace = TopoDS::Face(FaceExp.Current());
//from: https://www.opencascade.com/content/how-determine-whether-topodsface-flat-or-volumetric
BRepAdaptor_Surface anAdaptor(aFace);
std::cout << " Face " << i << " Type = " << anAdaptor.GetType() << ":" << SurfaceTypeName(anAdaptor.GetType()) << std::endl;
get_wire_edge_points_test4(aFace);
}
}
}
| 6,879
|
C++
|
.cpp
| 204
| 31.176471
| 136
| 0.714824
|
agordon/openscad-step-reader
| 30
| 10
| 3
|
LGPL-2.1
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,149
|
openscad-triangle-writer.h
|
agordon_openscad-step-reader/openscad-triangle-writer.h
|
/*
* Copyright 2019 Assaf Gordon <assafgordon@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*/
#ifndef __OPENSCAD_TRIANGLE_WRITER__
#define __OPENSCAD_TRIANGLE_WRITER__
void write_faces_scad (const Face_vector& faces);
void write_triangles_ascii_stl(const Face_vector& faces);
void write_triangle_scad(const Face_vector& faces);
#endif
| 827
|
C++
|
.h
| 19
| 41.631579
| 69
| 0.778331
|
agordon/openscad-step-reader
| 30
| 10
| 3
|
LGPL-2.1
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,150
|
triangle.h
|
agordon_openscad-step-reader/triangle.h
|
/*
* Copyright 2019 Assaf Gordon <assafgordon@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*/
#ifndef __TRIANGLE__
#define __TRIANGLE__
class Point {
double _x,_y,_z;
public:
Point() : _x(0), _y(0), _z(0) {};
Point(double x, double y, double z):_x(x),_y(y),_z(z) {};
Point(const gp_Pnt& p) : _x(p.X()),_y(p.Y()),_z(p.Z()) {} ;
double x() const { return _x; };
double y() const { return _y; };
double z() const { return _z; };
void write_ascii_stl(std::ostream &ostrm) const
{
ostrm << "vertex " << _x << " " << _y << " " << _z ;
}
};
static ostream & operator << (ostream &out, const Point &p)
{
out << "[" << p.x() << "," << p.y() << "," << p.z() << "]";
return out;
}
class Triangle {
Point _p1, _p2, _p3;
public:
Triangle() {} ;
Triangle(const Point& p1, const Point& p2, const Point& p3) : _p1(p1), _p2(p2), _p3(p3) {}
void write_points_vector(std::ostream &ostrm) const
{
ostrm << _p1 << "," << _p2 << "," << _p3 ;
}
void write_ascii_stl(std::ostream &ostrm) const
{
ostrm << " " ;
_p1.write_ascii_stl(ostrm);
ostrm << endl;
ostrm << " " ;
_p2.write_ascii_stl(ostrm);
ostrm << endl;
ostrm << " " ;
_p3.write_ascii_stl(ostrm);
ostrm << endl;
}
};
class Face {
std::vector<Triangle> triangles;
public:
Face() {};
void addTriangle(const Triangle& tr) { triangles.push_back(tr); };
void add_face(const Face& other_face)
{
triangles.insert(triangles.end(),
other_face.triangles.begin(),
other_face.triangles.end());
}
void write_ascii_stl(std::ostream &ostrm) const
{
for (auto &t : triangles) {
ostrm << " facet normal 42 42 42" << std::endl;
ostrm << " outer loop" << std::endl;
t.write_ascii_stl(ostrm);
ostrm << " endloop" << std::endl;
ostrm << " endfacet" << std::endl;
}
}
void write_points_vector(std::ostream &ostrm) const
{
int i = 1 ;
ostrm << "[" << std::endl;
for (auto &t : triangles) {
ostrm << " ";
t.write_points_vector(ostrm);
ostrm << ",";
if (i==1 || (i%10==0 && triangles.size()>10))
ostrm << " // Triangle " << i << " / " << triangles.size();
ostrm << std::endl;
++i;
}
ostrm << "];" << std::endl;
}
void write_face_vector(std::ostream &ostrm) const
{
ostrm << "[" << std::endl;
for (int i=0;i<triangles.size();++i) {
int idx = i*3;
ostrm << " [" << idx << "," << (idx+1) << "," << (idx+2) << "],";
if (i==0 || ((i+1)%10==0 && triangles.size()>10))
ostrm << " // Triangle " << (i+1) << " / " << triangles.size();
ostrm << std::endl;
}
ostrm << "];" << std::endl;
}
};
typedef std::vector<Face> Face_vector;
#endif
| 3,158
|
C++
|
.h
| 107
| 26.345794
| 91
| 0.580805
|
agordon/openscad-step-reader
| 30
| 10
| 3
|
LGPL-2.1
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,151
|
explore-shape.h
|
agordon_openscad-step-reader/explore-shape.h
|
/*
* Copyright 2019 Assaf Gordon <assafgordon@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*/
#ifndef __EXPLORE__
#define __EXPLORE__
void explore_shape(const TopoDS_Shape& shape);
#endif
| 677
|
C++
|
.h
| 17
| 38
| 69
| 0.770517
|
agordon/openscad-step-reader
| 30
| 10
| 3
|
LGPL-2.1
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,152
|
tessellation.h
|
agordon_openscad-step-reader/tessellation.h
|
/*
* Copyright 2019 Assaf Gordon <assafgordon@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*/
#ifndef __TESSELLATION__
#define __TESSELLATION__
Face tessellate_face(const TopoDS_Face &aFace);
Face_vector tessellate_shape (const TopoDS_Shape& shape);
#endif
| 746
|
C++
|
.h
| 18
| 39.666667
| 69
| 0.77686
|
agordon/openscad-step-reader
| 30
| 10
| 3
|
LGPL-2.1
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,154
|
FEMElement.cpp
|
joconnor22_LIFE/src/FEMElement.cpp
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
// Includes
#include "../inc/FEMElement.h"
#include "../inc/FEMBody.h"
#include "../inc/Grid.h"
#include "../inc/Objects.h"
#include "../inc/Utils.h"
// Construct load vector
void FEMElementClass::loadVector() {
// Declare vectors
array<array<double, dims>, dims> Tsub;
array<double, dims> F;
array<double, elementDOFs> RGlobal;
// Get weight vector
array<double, dims> weight = {rho * A * gravityX, rho * A * gravityY};
// Get force scaling parameter
double forceScale = fPtr->iPtr->oPtr->gPtr->Dm / SQ(fPtr->iPtr->oPtr->gPtr->Dt);
// Loop through all force mapping nodes
for (size_t n = 0; n < forceMap.size(); n++) {
// Get node and integration ranges
IBMNodeClass *node = fPtr->iPtr->node[forceMap[n].nodeID];
double a = forceMap[n].zeta1;
double b = forceMap[n].zeta2;
// Get subset of transpose matrix
Tsub = {{{T[0][0], T[0][1]},
{T[1][0], T[1][1]}}};
// Convert force to local coordinates
F = Tsub * (((-node->epsilon * 1.0 * forceScale) * node->force) + weight);
// Get the nodal values by integrating over range of IB point
R[0] = F[0] * 0.5 * L * (0.5 * b - 0.5 * a + 0.25 * SQ(a) - 0.25 * SQ(b));
R[1] = F[1] * 0.5 * L * (0.5 * b - 0.5 * a - SQ(a) * SQ(a) / 16.0 + SQ(b) * SQ(b) / 16.0 + 3.0 * SQ(a) / 8.0 - 3.0 * SQ(b) / 8.0);
R[2] = F[1] * 0.5 * L * (L * (-SQ(a) * SQ(a) + SQ(b) * SQ(b)) / 32.0 - L * (-TH(a) + TH(b)) / 24.0 - L * (-SQ(a) + SQ(b)) / 16.0 + L * (b - a) / 8.0);
R[3] = F[0] * 0.5 * L * (-0.25 * SQ(a) + 0.25 * SQ(b) + 0.5 * b - 0.5 * a);
R[4] = F[1] * 0.5 * L * (0.5 * b - 0.5 * a + SQ(a) * SQ(a) / 16.0 - SQ(b) * SQ(b) / 16.0 - 3.0 * SQ(a) / 8.0 + 3.0 * SQ(b) / 8.0);
R[5] = F[1] * 0.5 * L * (L * (-SQ(a) * SQ(a) + SQ(b) * SQ(b)) / 32.0 + L * (-TH(a) + TH(b)) / 24.0 - L * (-SQ(a) + SQ(b)) / 16.0 - L * (b - a) / 8.0);
// Get element load vector
RGlobal = Utils::Transpose(T) * R;
// Assemble into global vector
assembleGlobalMat(RGlobal, fPtr->R);
}
}
// Construct internal force vector
void FEMElementClass::forceVector() {
// Calculate the local displacements
double u = (SQ(L) - SQ(L0)) / (L + L0);
double theta1 = Utils::shiftAngle(node[0]->angle - angle);
double theta2 = Utils::shiftAngle(node[1]->angle - angle);
// Calculate internal forces for beam
double F0 = (E * A / L0) * u;
double M1 = (2 * E * I / L0) * (2.0 * theta1 + theta2);
double M2 = (2 * E * I / L0) * (theta1 + 2.0 * theta2);
// Set the internal local nodal forces
F[0] = -F0;
F[1] = (1.0 / L0) * (M1 + M2);
F[2] = M1;
F[3] = F0;
F[4] = -(1.0 / L0) * (M1 + M2);
F[5] = M2;
// Get element internal forces
array<double, elementDOFs> FGlobal = Utils::Transpose(T) * F;
// Assemble into global vector
assembleGlobalMat(FGlobal, fPtr->F);
}
// Construct mass matrix
void FEMElementClass::massMatrix() {
// Get linear stiffness matrix in global coordinates
array<array<double, elementDOFs>, elementDOFs> MGlobal = Utils::Transpose(T) * M * T;
// Assemble into global matrix
assembleGlobalMat(MGlobal, fPtr->M);
}
// Construct stiffness matrix
void FEMElementClass::stiffMatrix() {
// Get linear stiffness matrix in global coordinates
array<array<double, elementDOFs>, elementDOFs> KGlobal = Utils::Transpose(T) * K_L * T;
// Internal forces
double F0 = -F[0];
double V0 = F[4];
// Construct upper half of local stiffness matrix for single element
K_NL[0][1] = -V0 / L0;
K_NL[0][4] = V0 / L0;
K_NL[1][0] = -V0 / L0;
K_NL[1][1] = F0 / L0;
K_NL[1][3] = V0 / L0;
K_NL[1][4] = -F0 / L0;
K_NL[3][1] = V0 / L0;
K_NL[3][4] = -V0 / L0;
K_NL[4][0] = V0 / L0;
K_NL[4][1] = -F0 / L0;
K_NL[4][3] = -V0 / L0;
K_NL[4][4] = F0 / L0;
// Multiply by transformation matrices to get global matrix for single element
KGlobal = KGlobal + Utils::Transpose(T) * K_NL * T;
// Assemble into global matrix
assembleGlobalMat(KGlobal, fPtr->K);
}
// Multiply by shape functions
array<double, dims> FEMElementClass::shapeFuns(const array<double, elementDOFs> &vec, double zeta) {
// Results vector
array<double, dims> resVec;
// Use shape functions to calculate values
double N0 = 1.0 - (zeta + 1.0) / 2.0;
double N1 = 1.0 - 3.0 * SQ((zeta + 1.0) / 2.0) + 2.0 * TH((zeta + 1.0) / 2.0);
double N2 = ((zeta + 1.0) / 2.0 - 2.0 * SQ((zeta + 1.0) / 2.0) + TH((zeta + 1.0) / 2.0)) * L;
double N3 = (zeta + 1.0) / 2.0;
double N4 = 3.0 * SQ((zeta + 1.0) / 2.0) - 2.0 * TH((zeta + 1.0) / 2.0);
double N5 = (-SQ((zeta + 1.0) / 2.0) + TH((zeta + 1.0) / 2.0)) * L;
// Calculate values using shape functions
resVec[eX] = vec[0] * N0 + vec[3] * N3;
resVec[eY] = vec[1] * N1 + vec[2] * N2 + vec[4] * N4 + vec[5] * N5;
// Return
return resVec;
}
// Assemble into global vector
void FEMElementClass::assembleGlobalMat(const array<double, elementDOFs> &localVec, vector<double> &globalVec) {
// Loop through and set
for (size_t i = 0; i < localVec.size(); i++)
globalVec[DOFs[i]] += localVec[i];
}
// Assemble into global matrix
void FEMElementClass::assembleGlobalMat(const array<array<double, elementDOFs>, elementDOFs> &localVec, vector<double> &globalVec) {
// Get dimensions
int dim = fPtr->bodyDOFs;
// Get rows and cols
size_t rows = localVec.size();
size_t cols = localVec[0].size();
// Now loop through and set
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
globalVec[DOFs[i] * dim + DOFs[j]] += localVec[i][j];
}
}
}
// Assemble into global vector
array<double, elementDOFs> FEMElementClass::disassembleGlobalMat(const vector<double> &globalVec) {
// Declare vector
array<double, elementDOFs> localVec;
// Loop through and set
for (size_t i = 0; i < localVec.size(); i++)
localVec[i] = globalVec[DOFs[i]];
// Return
return localVec;
}
// Set local mass and stiffness matrices
void FEMElementClass::setLocalMatrices() {
// Size the local matrices
M.fill({0.0});
K_L.fill({0.0});
K_NL.fill({0.0});
R.fill(0.0);
F.fill(0.0);
// Coefficients
double C1 = rho * A * L0 / 420.0;
// Set mass matrix first
M[0][0] = C1 * 140.0;
M[0][3] = C1 * 70.0;
M[1][1] = C1 * 156.0;
M[1][2] = C1 * 22.0 * L0;
M[1][4] = C1 * 54;
M[1][5] = C1 * (-13.0 * L0);
M[2][2] = C1 * 4.0 * SQ(L0);
M[2][4] = C1 * 13.0 * L0;
M[2][5] = C1 * (-3.0 * SQ(L0));
M[3][3] = C1 * 140.0;
M[4][4] = C1 * 156.0;
M[4][5] = C1 * (-22.0 * L0);
M[5][5] = C1 * 4.0 * SQ(L0);
// Now set stiffness matrix
K_L[0][0] = E * A / L0;
K_L[0][3] = -E * A / L0;
K_L[1][1] = 12.0 * E * I / TH(L0);
K_L[1][2] = 6.0 * E * I / SQ(L0);
K_L[1][4] = -12.0 * E * I / TH(L0);
K_L[1][5] = 6.0 * E * I / SQ(L0);
K_L[2][2] = 4.0 * E * I / L0;
K_L[2][4] = -6.0 * E * I / SQ(L0);
K_L[2][5] = 2.0 * E * I / L0;
K_L[3][3] = E * A / L0;
K_L[4][4] = 12.0 * E * I / TH(L0);
K_L[4][5] = -6.0 * E * I / SQ(L0);
K_L[5][5] = 4.0 * E * I / L0;
// Copy to the lower half (symmetrical matrix)
for (size_t i = 1; i < M.size(); i++) {
for (size_t j = 0; j < i; j++) {
M[i][j] = M[j][i];
K_L[i][j] = K_L[j][i];
}
}
}
// Set transformation matrix for element
void FEMElementClass::setElementTransform() {
// Set to correct values
T[0][0] = T[1][1] = T[3][3] = T[4][4] = cos(angle);
T[0][1] = T[3][4] = sin(angle);
T[1][0] = T[4][3] = -sin(angle);
T[2][2] = T[5][5] = 1.0;
}
// Custom constructor for building elements
FEMElementClass::FEMElementClass(FEMBodyClass *fBody, int i, const array<double, dims> &geom, double angleRad, double length, double den, double youngMod) {
// Set pointer to fBody
fPtr = fBody;
// Set values
L0 = length;
L = length;
angle = angleRad;
A = fPtr->iPtr->oPtr->gPtr->Dx * geom[1];
I = fPtr->iPtr->oPtr->gPtr->Dx * TH(geom[1]) / 12.0;
E = youngMod;
rho = den;
// Vector of node indices
array<int, elementNodes> nodeIdx;
// Get nodal indices
nodeIdx[0] = i;
nodeIdx[1] = i + 1;
// Set pointers and global DOFs
for (int i = 0; i < elementNodes; i++) {
// Insert pointer to node
node[i] = &(fPtr->node[nodeIdx[i]]);
// Get DOFs
for (int j = 0; j < nodeDOFs; j++)
DOFs[i * nodeDOFs + j] = nodeIdx[i] * nodeDOFs + j;
}
// Set transformation matrix
T.fill({0.0});
setElementTransform();
// Set local mass and stiffness matrices
setLocalMatrices();
}
| 8,919
|
C++
|
.cpp
| 240
| 34.75
| 156
| 0.607707
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,155
|
main.cpp
|
joconnor22_LIFE/src/main.cpp
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
// Includes
#include "../inc/Grid.h"
#include "../inc/Objects.h"
#include "../inc/Utils.h"
// ***** Main function ***** //
int main() {
// Write out header
Utils::writeHeader();
// Start initialising
cout << endl << endl << "*** INITIALISING LIFE ***";
// Time the code
double start = omp_get_wtime();
// Set number of threads
#ifdef THREADS
omp_set_num_threads(THREADS);
#endif
// Create grid and initialise values
GridClass grid;
// If IBM then setup the body object
ObjectsClass objects(grid);
// Read in restart file if required
if (grid.restartFlag == true) {
// Read in restart file
Utils::readRestart(grid);
}
// Write log
Utils::writeLog(grid);
// Starting main algorithm
cout << endl << endl << endl << "*** STARTING LIFE ***";
// Write out info
Utils::writeInfo(grid);
// Write VTK
Utils::writeVTK(grid);
// Start the clock
grid.startClock();
// ***** MAIN LBM ALGORITHM ***** //
for (grid.t = grid.tOffset + 1; grid.t <= grid.tOffset + nSteps; grid.t++) {
// Run the main LBM solver
grid.solver();
// Write out info
if (grid.t % tinfo == 0)
Utils::writeInfo(grid);
// Write VTK
if (grid.t % tVTK == 0)
Utils::writeVTK(grid);
// Write restart data
if (tRestart > 0 && grid.t % tRestart == 0)
Utils::writeRestart(grid);
}
// Starting main algorithm
cout << endl << endl << endl << "*** FINISHED LIFE ***";
// Finish timing
double end = omp_get_wtime();
cout << fixed << setprecision(2) << endl << endl << "Simulation took " << end - start << " seconds" << endl << endl << endl;
}
| 2,332
|
C++
|
.cpp
| 69
| 30.84058
| 125
| 0.680518
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,156
|
FEMNode.cpp
|
joconnor22_LIFE/src/FEMNode.cpp
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
// Includes
#include "../inc/FEMNode.h"
// Custom constructor for building nodes
FEMNodeClass::FEMNodeClass(int ID, const array<double, dims> &position, double angleRad) {
// Set values
pos0 = position;
pos = position;
angle0 = angleRad;
angle = angleRad;
// Set the global DOFs
for (int i = 0; i < nodeDOFs; i++)
DOFs[i] = ID * nodeDOFs + i;
}
| 1,117
|
C++
|
.cpp
| 27
| 38
| 90
| 0.739612
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,157
|
Grid.cpp
|
joconnor22_LIFE/src/Grid.cpp
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
// Includes
#include "../inc/Grid.h"
#include "../inc/Objects.h"
#include "../inc/Utils.h"
// Main solver
void GridClass::solver() {
// Do grid kernel (LBM)
lbmKernel();
// Do object kernel (IBM + FEM)
if (oPtr->hasIBM == true)
oPtr->objectKernel();
}
// Main LBM kernel
void GridClass::lbmKernel() {
// Calculate convective speed
if (WALL_RIGHT == eConvective)
convectiveSpeed();
// Swap to start of timestep
f_n.swap(f);
u_n.swap(u);
rho_n.swap(rho);
// Start parallel section
#pragma omp parallel
{
// Set forcing if Womersley pressure gradient is used
#ifdef WOMERSLEY
// Loop through all points
#pragma omp for schedule(guided)
for (int id = 0; id < Nx * Ny; id++) {
// Calculate forcing
force_xy[id * dims + eX] = (rho_n[id] * Drho * gravityX + dpdx * cos(2.0 * M_PI * t * Dt / ((SQ(height_p) * M_PI) / (2.0 * SQ(WOMERSLEY) * nu_p)))) * SQ(Dx * Dt) / Dm;
force_xy[id * dims + eY] = (rho_n[id] * Drho * gravityY + dpdy * cos(2.0 * M_PI * t * Dt / ((SQ(height_p) * M_PI) / (2.0 * SQ(WOMERSLEY) * nu_p)))) * SQ(Dx * Dt) / Dm;
}
#endif
// Loop through all points
#pragma omp for schedule(guided) collapse(2)
for (int i = 0; i < Nx; i++) {
for (int j = 0; j < Ny; j++) {
// ID
int id = i * Ny + j;
// Stream and collide in one go
streamCollide(i, j, id);
}
}
// Loop through all points
#pragma omp for schedule(guided)
for (int id = 0; id < Nx * Ny; id++) {
// Update fluid site macroscopic values
if (type[id] == eFluid)
macroscopic(id);
}
// Loop through all BC sites and apply BCs before getting macroscopic
#pragma omp for schedule(guided)
for (size_t bc = 0; bc < BCVec.size(); bc++) {
// ID
int id = BCVec[bc];
int i = id / Ny;
int j = id - (i * Ny);
// Apply boundary condition and update macroscopic
applyBCs(i, j, id);
macroscopic(id);
}
}
}
// Stream and collide in one go (push algorithm)
inline void GridClass::streamCollide(int i, int j, int id) {
// Stream and collide
#ifdef CENTRAL_MOMENTS
// Central moments
double k4Pre = 0.0;
double k5Pre = 0.0;
// Loop through velocities on src_id
for (int v = 0; v < nVels; v++) {
// Shift lattice velocities
double cx = c[v * dims + eX] - u_n[id * dims + eX];
double cy = c[v * dims + eY] - u_n[id * dims + eY];
// Transform f to central moments (k)
k4Pre += f_n[id * nVels + v] * (SQ(cx) - SQ(cy));
k5Pre += f_n[id * nVels + v] * cx * cy;
}
// Get post-collision central moments
double k0 = rho_n[id];
double k1 = 0.5 * (force_xy[id * dims + eX] + force_ibm[id * dims + eX]);
double k2 = 0.5 * (force_xy[id * dims + eY] + force_ibm[id * dims + eY]);
double k3 = 2.0 * rho_n[id] * SQ(c_s);
double k4 = (1.0 - omega) * k4Pre;
double k5 = (1.0 - omega) * k5Pre;
double k6 = 0.5 * (force_xy[id * dims + eY] + force_ibm[id * dims + eY]) * SQ(c_s);
double k7 = 0.5 * (force_xy[id * dims + eX] + force_ibm[id * dims + eX]) * SQ(c_s);
double k8 = rho_n[id] * QU(c_s);
// Get velocity
double ux = u_n[id * dims + eX];
double uy = u_n[id * dims + eY];
// Declare array
array<double, nVels> fStar;
// Set array (transform from central moments to f)
fStar[0] = (SQ(ux) * SQ(uy) - SQ(ux) - SQ(uy) + 1.0) * k0
+ (2.0 * ux * SQ(uy) - 2.0 * ux) * k1
+ (2.0 * uy * SQ(ux) - 2.0 * uy) * k2
+ (0.5 * SQ(ux) + 0.5 * SQ(uy) - 1.0) * k3
+ (0.5 * SQ(uy) - 0.5 * SQ(ux)) * k4
+ 4.0 * ux * uy * k5
+ 2.0 * uy * k6
+ 2.0 * ux * k7
+ k8;
fStar[1] = (0.5 * SQ(ux) - 0.5 * (SQ(ux) * SQ(uy)) - 0.5 * (ux * SQ(uy)) + 0.5 * ux) * k0
+ (ux - ux * SQ(uy) - 0.5 * SQ(uy) + 0.5) * k1
+ (-uy * SQ(ux) - uy * ux) * k2
+ (-0.25 * SQ(ux) - 0.25 * ux - 0.25 * SQ(uy) + 0.25) * k3
+ (0.25 * SQ(ux) + 0.25 * ux - 0.25 * SQ(uy) + 0.25) * k4
+ (-uy - 2.0 * ux * uy) * k5
+ (-uy) * k6
+ (-ux - 0.5) * k7
- 0.5 * k8;
fStar[2] = (-0.5 * (SQ(ux) * SQ(uy)) + 0.5 * SQ(ux) + 0.5 * (ux * SQ(uy)) - 0.5 * ux) * k0
+ (ux - ux * SQ(uy) + 0.5 * SQ(uy) - 0.5) * k1
+ (-uy * SQ(ux) + uy * ux) * k2
+ (-0.25 * SQ(ux) + 0.25 * ux - 0.25 * SQ(uy) + 0.25) * k3
+ (0.25 * SQ(ux) - 0.25 * ux - 0.25 * SQ(uy) + 0.25) * k4
+ (uy - 2.0 * ux * uy) * k5
+ (-uy) * k6
+ (0.5 - ux) * k7
- 0.5 * k8;
fStar[3] = (0.5 * SQ(uy) - 0.5 * (SQ(ux) * uy) - 0.5 * (SQ(ux) * SQ(uy)) + 0.5 * uy) * k0
+ (-ux * SQ(uy) - ux * uy) * k1
+ (uy - SQ(ux) * uy - 0.5 * SQ(ux) + 0.5) * k2
+ (-0.25 * SQ(ux) - 0.25 * SQ(uy) - 0.25 * uy + 0.25) * k3
+ (0.25 * SQ(ux) - 0.25 * SQ(uy) - 0.25 * uy - 0.25) * k4
+ (-ux - 2.0 * ux * uy) * k5
+ (-uy - 0.5) * k6
+ (-ux) * k7
- 0.5 * k8;
fStar[4] = (-0.5 * (SQ(ux) * SQ(uy)) + 0.5 * (SQ(ux) * uy) + 0.5 * SQ(uy) - 0.5 * uy) * k0
+ (-ux * SQ(uy) + ux * uy) * k1
+ (uy - SQ(ux) * uy + 0.5 * SQ(ux) - 0.5) * k2
+ (-0.25 * SQ(ux) - 0.25 * SQ(uy) + 0.25 * uy + 0.25) * k3
+ (0.25 * SQ(ux) - 0.25 * SQ(uy) + 0.25 * uy - 0.25) * k4
+ (ux - 2.0 * ux * uy) * k5
+ (0.5 - uy) * k6
+ (-ux) * k7
- 0.5 * k8;
fStar[5] = (0.25 * (SQ(ux) * SQ(uy)) + 0.25 * (SQ(ux) * uy) + 0.25 * (ux * SQ(uy)) + 0.25 * (ux * uy)) * k0
+ (0.25 * uy + 0.5 * (ux * uy) + 0.5 * (ux * SQ(uy)) + 0.25 * SQ(uy)) * k1
+ (0.25 * ux + 0.5 * (ux * uy) + 0.5 * (SQ(ux) * uy) + 0.25 * SQ(ux)) * k2
+ (0.125 * SQ(ux) + 0.125 * ux + 0.125 * SQ(uy) + 0.125 * uy) * k3
+ (-0.125 * SQ(ux) - 0.125 * ux + 0.125 * SQ(uy) + 0.125 * uy) * k4
+ (0.5 * ux + 0.5 * uy + ux * uy + 0.25) * k5
+ (0.5 * uy + 0.25) * k6
+ (0.5 * ux + 0.25) * k7
+ 0.25 * k8;
fStar[6] = (0.25 * (SQ(ux) * SQ(uy)) - 0.25 * (SQ(ux) * uy) - 0.25 * (ux * SQ(uy)) + 0.25 * (ux * uy)) * k0
+ (0.25 * uy - 0.5 * (ux * uy) + 0.5 * (ux * SQ(uy)) - 0.25 * SQ(uy)) * k1
+ (0.25 * ux - 0.5 * (ux * uy) + 0.5 * (SQ(ux) * uy) - 0.25 * SQ(ux)) * k2
+ (0.125 * SQ(ux) - 0.125 * ux + 0.125 * SQ(uy) - 0.125 * uy) * k3
+ (-0.125 * SQ(ux) + 0.125 * ux + 0.125 * SQ(uy) - 0.125 * uy) * k4
+ (ux * uy - 0.5 * uy - 0.5 * ux + 0.25) * k5
+ (0.5 * uy - 0.25) * k6
+ (0.5 * ux - 0.25) * k7
+ 0.25 * k8;
fStar[7] = (0.25 * (SQ(ux) * SQ(uy)) - 0.25 * (SQ(ux) * uy) + 0.25 * (ux * SQ(uy)) - 0.25 * (ux * uy)) * k0
+ (0.5 * (ux * SQ(uy)) - 0.5 * (ux * uy) - 0.25 * uy + 0.25 * SQ(uy)) * k1
+ (0.5 * (ux * uy) - 0.25 * ux + 0.5 * (SQ(ux) * uy) - 0.25 * SQ(ux)) * k2
+ (0.125 * SQ(ux) + 0.125 * ux + 0.125 * SQ(uy) - 0.125 * uy) * k3
+ (-0.125 * SQ(ux) - 0.125 * ux + 0.125 * SQ(uy) - 0.125 * uy) * k4
+ (0.5 * uy - 0.5 * ux + ux * uy - 0.25) * k5
+ (0.5 * uy - 0.25) * k6
+ (0.5 * ux + 0.25) * k7
+ 0.25 * k8;
fStar[8] = (0.25 * (SQ(ux) * SQ(uy)) + 0.25 * (SQ(ux) * uy) - 0.25 * (ux * SQ(uy)) - 0.25 * (ux * uy)) * k0
+ (0.5 * (ux * uy) - 0.25 * uy + 0.5 * (ux * SQ(uy)) - 0.25 * SQ(uy)) * k1
+ (0.5 * (SQ(ux) * uy) - 0.5 * (ux * uy) - 0.25 * ux + 0.25 * SQ(ux)) * k2
+ (0.125 * SQ(ux) - 0.125 * ux + 0.125 * SQ(uy) + 0.125 * uy) * k3
+ (-0.125 * SQ(ux) + 0.125 * ux + 0.125 * SQ(uy) + 0.125 * uy) * k4
+ (0.5 * ux - 0.5 * uy + ux * uy - 0.25) * k5
+ (0.5 * uy + 0.25) * k6
+ (0.5 * ux - 0.25) * k7
+ 0.25 * k8;
// Now set to f
for (int v = 0; v < nVels; v++) {
// Calculate newx and newy then collide and stream
int recv_id = ((i + c[v * dims + eX] + Nx) % Nx) * Ny + ((j + c[v * dims + eY] + Ny) % Ny);
// Update new f
f[recv_id * nVels + v] = fStar[v];
}
#else
// BGK
for (int v = 0; v < nVels; v++) {
// Calculate newx and newy then collide and stream
int recv_id = ((i + c[v * dims + eX] + Nx) % Nx) * Ny + ((j + c[v * dims + eY] + Ny) % Ny);
// Update new f
f[recv_id * nVels + v] = f_n[id * nVels + v] + omega * (equilibrium(id, v) - f_n[id * nVels + v]) + (1.0 - 0.5 * omega) * latticeForce(id, v);
}
#endif
}
// Equilibrium function
inline double GridClass::equilibrium(int id, int v) {
// Extract required quantities
int cx = c[v * dims + eX];
int cy = c[v * dims + eY];
double ux = u_n[id * dims + eX];
double uy = u_n[id * dims + eY];
#ifdef CENTRAL_MOMENTS
// Central moments (4th order Hermite)
return 0.25 * rho_n[id] * w[v] * (9.0 * SQ(cx) * SQ(ux) + 6.0 * cx * ux - 3.0 * SQ(ux) + 2.0) * (9.0 * SQ(cy) * SQ(uy) + 6.0 * cy * uy - 3.0 * SQ(uy) + 2.0);
#else
// BGK (2nd order Hermite)
return rho_n[id] * w[v] * (1.0 + 3.0 * (cx * ux + cy * uy) + 4.5 * (SQ(ux) * (SQ(cx) - 1.0 / 3.0) + SQ(uy) * (SQ(cy) - 1.0 / 3.0)) + 9.0 * cx * cy * ux * uy);
#endif
}
// Discretise cartesian force onto lattice (BGK only)
inline double GridClass::latticeForce(int id, int v) {
// Extract required quantities
int cx = c[v * dims + eX];
int cy = c[v * dims + eY];
double ux = u_n[id * dims + eX];
double uy = u_n[id * dims + eY];
double Fx = force_xy[id * dims + eX] + force_ibm[id * dims + eX];
double Fy = force_xy[id * dims + eY] + force_ibm[id * dims + eY];
// Return value
return 3.0 * w[v] * (Fx * (cx - ux + cx * 3.0 * (cx * ux + cy * uy)) + (Fy * (cy - uy + cy * 3.0 * (cx * ux + cy * uy))));
}
// Compute macroscopic quantities
inline void GridClass::macroscopic(int id) {
// Reset
rho[id] = 0.0;
u[id * dims + eX] = 0.0;
u[id * dims + eY] = 0.0;
// Sum to find rho and momentum
for (int v = 0; v < nVels; v++) {
rho[id] += f[id * nVels + v];
u[id * dims + eX] += c[v * dims + eX] * f[id * nVels + v];
u[id * dims + eY] += c[v * dims + eY] * f[id * nVels + v];
}
// Divide by rho to get velocity
u[id * dims + eX] = (u[id * dims + eX] + 0.5 * force_xy[id * dims + eX]) / rho[id];
u[id * dims + eY] = (u[id * dims + eY] + 0.5 * force_xy[id * dims + eY]) / rho[id];
}
// Apply boundary conditions
void GridClass::applyBCs(int i, int j, int id) {
// Get ramp coefficient
double rampCoefficient = getRampCoefficient();
// Get normal direction
eDirectionType normalDirection;
array<int, dims> normalVector = getNormalVector(i, j, normalDirection);
// Boundary type
switch (type[id]) {
// Wall BC
case eWall:
// Set velocity to zero
u_n[id * dims + eX] = 0.0;
u_n[id * dims + eY] = 0.0;
// Do regularised BC
regularisedBC(i, j, id, normalVector, normalDirection);
break;
// Velocity BC
case eVelocity:
// Set velocity to boundary values
u_n[id * dims + eX] = u_in[j * dims + eX] * rampCoefficient;
u_n[id * dims + eY] = u_in[j * dims + eY] * rampCoefficient;
// Do regularised BC
regularisedBC(i, j, id, normalVector, normalDirection);
break;
// Free slip BC
case eFreeSlip:
// Normal velocity is zero
u_n[id * dims + normalDirection] = 0.0;
// Extrapolate tangential velocities
for (int d = 0; d < dims; d++) {
if (d != normalDirection)
u_n[id * dims + d] = Utils::zeroGradient(u, normalVector, 2, i, j, d, dims);
}
// Do regularised BC
regularisedBC(i, j, id, normalVector, normalDirection);
break;
// Uniform pressure BC
case ePressure:
// Set density to boundary values
rho_n[id] = rho_in[j];
// Extrapolate tangential velocities
for (int d = 0; d < dims; d++) {
if (d != normalDirection)
u_n[id * dims + d] = Utils::zeroGradient(u, normalVector, 2, i, j, d, dims);
}
// Do regularised BC
regularisedBC(i, j, id, normalVector, normalDirection);
break;
// Convective BC
case eConvective:
// Do regularised BC
convectiveBC(j, id);
break;
// Fluid (don't do anything)
case eFluid:
break;
}
}
// Regularised BC
void GridClass::regularisedBC(int i, int j, int id, array<int, dims> &normalVector, eDirectionType normalDirection) {
// If it is a corner then we need to extrapolate
if (normalVector[eX] != 0 && normalVector[eY] != 0) {
// If velocity BC then extrapolate density
if (type[id] == eVelocity || type[id] == eWall || type[id] == eFreeSlip)
rho_n[id] = Utils::extrapolate(rho, normalVector, 1, i, j);
}
// Otherwise normal edge
else {
// Declare fplus and fzero
double fplus = 0.0, fzero = 0.0;
// Loop through velocities
for (int v = 0; v < nVels; v++) {
// If normal is opposite then add to fplus
if (c[v * dims + normalDirection] == -normalVector[normalDirection])
fplus += f[id * nVels + v];
// If it is perpendicular to wall then add to fzero
else if (c[v * dims + normalDirection] == 0)
fzero += f[id * nVels + v];
}
// Velocity condition
if (type[id] == eVelocity || type[id] == eWall || type[id] == eFreeSlip) {
rho_n[id] = (2.0 * fplus + fzero) / (1.0 - normalVector[normalDirection] * u_n[id * dims + normalDirection]);
}
// Pressure condition
else if (type[id] == ePressure) {
u_n[id * dims + normalDirection] = normalVector[normalDirection] * (1.0 - (2.0 * fplus + fzero) / rho_n[id]);
}
}
// Declare stresses
double Sxx = 0.0, Syy = 0.0, Sxy = 0.0;
// Update f values
for (int v = 0; v < nVels; v++) {
// Get feq
double feq = equilibrium(id, v);
// If corner then unknowns share at least one of normal components
if (normalVector[eX] != 0 && normalVector[eY] != 0) {
if (c[v * dims + eX] == normalVector[eX] || c[v * dims + eY] == normalVector[eY]) {
// If buried link just set to feq
if (normalVector[eX] * c[v * dims + eX] + normalVector[eY] * c[v * dims + eY] == 0)
f[id * nVels + v] = feq;
else
f[id * nVels + v] = feq + (f[id * nVels + opposite[v]] - equilibrium(id, opposite[v]));
}
}
// If other then unknowns share the normal vector component
else {
if (c[v * dims + normalDirection] == normalVector[normalDirection])
f[id * nVels + v] = feq + (f[id * nVels + opposite[v]] - equilibrium(id, opposite[v]));
}
// Store off-equilibrium
double fneq = f[id * nVels + v] - feq;
// Compute off-equilbrium stress components
Sxx += c[v * dims + eX] * c[v * dims + eX] * fneq;
Syy += c[v * dims + eY] * c[v * dims + eY] * fneq;
Sxy += c[v * dims + eX] * c[v * dims + eY] * fneq;
}
// Compute regularised non-equilibrium components and add to feq to get new populations
for (int v = 0; v < nVels; v++)
f[id * nVels + v] = equilibrium(id, v) + (w[v] / (2.0 * QU(c_s))) * (((SQ(c[v * dims + eX]) - SQ(c_s)) * Sxx) + ((SQ(c[v * dims + eY]) - SQ(c_s)) * Syy) + (2.0 * c[v * dims + eX] * c[v * dims + eY] * Sxy));
}
// Convective BC
void GridClass::convectiveBC(int j, int id) {
// Set the values
f[id * nVels + 2] = f_n[id * nVels + 2] + 3.0 * w[2] * (delU[j * dims + eX] * c[2 * dims + eX] + delU[j * dims + eY] * c[2 * dims + eY]);
f[id * nVels + 6] = f_n[id * nVels + 6] + 3.0 * w[6] * (delU[j * dims + eX] * c[6 * dims + eX] + delU[j * dims + eY] * c[6 * dims + eY]);
f[id * nVels + 8] = f_n[id * nVels + 8] + 3.0 * w[8] * (delU[j * dims + eX] * c[8 * dims + eX] + delU[j * dims + eY] * c[8 * dims + eY]);
}
// Calculate convective speed
void GridClass::convectiveSpeed() {
// Set uOut to zero
double uOut = 0.0;
// Loop through outlet
for (int j = 0; j < Ny; j++)
uOut += u[((Nx - 1) * Ny + j) * dims + eX];
// Get average
uOut /= static_cast<double>(Ny);
// Now loop through again and get delU
#pragma omp parallel for schedule(guided)
for (int j = 0; j < Ny; j++) {
delU[j * dims + eX] = (-uOut / 2.0) * (3.0 * u[((Nx - 1) * Ny + j) * dims + eX] - 4.0 * u[((Nx - 2) * Ny + j) * dims + eX] + u[((Nx - 3) * Ny + j) * dims + eX]);
delU[j * dims + eY] = (-uOut / 2.0) * (3.0 * u[((Nx - 1) * Ny + j) * dims + eY] - 4.0 * u[((Nx - 2) * Ny + j) * dims + eY] + u[((Nx - 3) * Ny + j) * dims + eY]);
}
}
// Get normal vector for bounday site
inline array<int, dims> GridClass::getNormalVector(int i, int j, eDirectionType &normalDirection) {
// Declare vector
array<int, dims> normalVector = {0};
// Get normal direction in x
if (i == 0) {
normalVector[eX] = 1;
normalDirection = eX;
}
else if (i == Nx - 1) {
normalVector[eX] = -1;
normalDirection = eX;
}
// Get normal direction in x
if (j == 0) {
normalVector[eY] = 1;
normalDirection = eY;
}
else if (j == Ny - 1) {
normalVector[eY] = -1;
normalDirection = eY;
}
// Do some extra checking for corners
if (normalVector[eX] != 0 && normalVector[eY] != 0) {
// If surrounded by periodic cells then something has gone wrong
if (type[(i + normalVector[eX]) * Ny + j] == eFluid && type[i * Ny + j + normalVector[eY]] == eFluid)
ERROR("Corner node is surrounded by fluid lattice sites...exiting");
// Check in x-direction
else if (type[(i + normalVector[eX]) * Ny + j] == eFluid) {
normalDirection = eX;
normalVector[eY] = 0;
}
// Check in y-direction
else if (type[i * Ny + j + normalVector[eY]] == eFluid) {
normalDirection = eY;
normalVector[eX] = 0;
}
}
// Return normal direction
return normalVector;
}
// Get inlet ramp coefficient
double GridClass::getRampCoefficient() {
// Get ramp coefficient
#ifdef INLET_RAMP
if (Dt * t <= INLET_RAMP)
return (1.0 - cos(M_PI * Dt * t / INLET_RAMP)) / 2.0;
#endif
return 1.0;
}
// Write info at tInfo frequency
void GridClass::writeInfo() {
// Calculate max velocity
double maxVel = 0.0;
for (int i = 0; i < Nx; i++) {
for (int j = 0; j < Ny; j++) {
// Get id
int id = i * Ny + j;
// Get velocity
double vel = sqrt(SQ(u[id * dims + eX]) + SQ(u[id * dims + eY]));
// Check if isnan then break
if (std::isnan(vel) == true) {
// Write VTK data
#ifdef VTK
Utils::writeVTK(*this);
#endif
// Tell user where it blew up
ERROR("Simulation blew up (t = " + to_string(t) + ") at i = " + to_string(i) + ", j = " + to_string(j) + "...exiting");
}
// If bigger then set
if (vel > maxVel) {
maxVel = vel;
}
}
}
// Calculate values
double maxRe = (maxVel * Dx / Dt) * ref_L / ref_nu;
// Calculate new average time per time step
if (t == tOffset) {
loopTime = 0.0;
}
else {
loopTime = omp_get_wtime() - startTime;
loopTime /= (t - tOffset);
}
// Get estimated time left
array<int, 3> hms = Utils::secs2hms(loopTime * (tOffset + nSteps - t));
// Write out performance information
cout << endl << endl;
cout << "Time step " << t << " of " << tOffset + nSteps << endl;
cout << setprecision(4) << "Simulation has done " << t * Dt << " of " << (tOffset + nSteps) * Dt << " seconds" << endl;
cout << "Time to finish = " << hms[0] << " [h] " << hms[1] << " [m] " << hms[2] << " [s]" << endl;
cout << setprecision(4) << "MLUPS = " << Nx * Ny / (1000000.0 * loopTime) << endl;
// Write out max velocity information
cout << setprecision(5) << "Max Velocity = " << maxVel << endl;
cout << setprecision(5) << "Max Velocity (m/s) = " << maxVel * Dx / Dt << endl;
cout << setprecision(5) << "Max Reynolds number = " << maxRe;
}
// Write log data at start
void GridClass::writeLog() {
// Add a triple line break if this is a restart
if (restartFlag == true) {
ofstream output("Results/Log.out", Utils::io_ofstream::app);
output << endl << endl << endl;
output.close();
}
// Create stream for output to stdout and file
Utils::io_ofstream output("Results/Log.out", Utils::io_ofstream::app);
int ss = static_cast<int>(output.precision());
// Set precision
output << setprecision(PRECISION);
// HEADER
cout << endl << endl << endl;
output << "*** LOG INFO ***\n";
// Get values to write to header
time_t now = time(0);
struct tm *localnow = localtime(&now);
char buffer[80];
strftime (buffer, 80, "%r on %e/%m/%Y", localnow);
// TIME
output << "\nSimulation started at " << buffer;
// Number of threads
output << "\n\nRunning with " << Utils::omp_thread_count() << " threads\n";
// OPTIONS
output << "\nOPTIONS:\n";
// Restart
if (restartFlag == true)
output << "RESTART = ON\n";
else
output << "RESTART = OFF\n";
// Inlet ramp
#ifdef INLET_RAMP
output << "Inlet Ramp = " << INLET_RAMP << " s\n";
#else
output << "Inlet Ramp = OFF\n";
#endif
// Universal epsilon calculation
#ifdef UNI_EPSILON
output << "Universal Epsilon Calculation = ON\n";
#else
output << "Universal Epsilon Calculation = OFF\n";
#endif
// Ordered reductions
#ifdef ORDERED
output << "Ordered Reductions = ON\n";
#else
output << "Ordered Reductions = OFF\n";
#endif
// Initial deflect
#ifdef INITIAL_DEFLECT
output << "Initial Deflection = " << 100*INITIAL_DEFLECT << " %L\n";
#else
output << "Initial Deflection = OFF\n";
#endif
// Womersley flow
#ifdef WOMERSLEY
output << "Womersley Number = " << WOMERSLEY << "\n";
#else
output << "Womersley Number = OFF\n";
#endif
// OUTPUT OPTIONS
output << "\nOUTPUT OPTIONS:\n";
// VTK option
#ifdef VTK
output << "VTK Output = ON\n";
#else
output << "VTK Output = OFF\n";
#endif
// FEM VTK option
#ifdef VTK_FEM
output << "FEM VTK Output = ON\n";
#else
output << "FEM VTK Output = OFF\n";
#endif
// IBM forces
#ifdef FORCES
output << "Write IBM Forces = ON\n";
#else
output << "Write IBM Forces = OFF\n";
#endif
// Tip
#ifdef TIPS
output << "Write Tip Positions = ON\n";
#else
output << "Write Tip Positions = OFF\n";
#endif
// LATTICE VALUES
output << "\nLATTICE VALUES:\n";
output << "Nx = " << Nx << "\n";
output << "Ny = " << Ny << "\n";
output << "omega = " << omega << "\n";
output << "tau = " << tau << "\n";
output << "nu = " << nu << "\n";
output << "Dx = " << Dx << "\n";
output << "Dt = " << Dt << "\n";
output << "Dm = " << Dm << "\n";
output << "Drho = " << Drho << "\n";
// PHYSICAL VALUES
output << "\nPHYSICAL VALUES:\n";
output << "Length (m) = " << Dx * (Nx - 1) << "\n";
output << "Height (m) = " << Dx * (Ny - 1) << "\n";
output << "Density (kg/m^3) = " << rho_p << "\n";
output << "Viscosity (m^2/s) = " << nu_p << "\n";
output << "Initial Velocity (m/s) = { " << ux0_p << ", " << uy0_p << " }\n";
output << "Inlet Velocity (m/s) = { " << uxInlet_p << ", " << uyInlet_p << " }\n";
output << "Gravity vector (m/s^2) = { " << gravityX << ", " << gravityY << " }\n";
output << "Pressure gradient vector (Pa/m) = { " << dpdx << ", " << dpdy << " }\n";
// BOUNDARY CONDITIONS
output << "\nBOUNDARY CONDITIONS\n";
output << "Left Wall = " << Utils::getBoundaryString(WALL_LEFT) << "\n";
output << "Right Wall = " << Utils::getBoundaryString(WALL_RIGHT) << "\n";
output << "Bottom Wall = " << Utils::getBoundaryString(WALL_BOTTOM) << "\n";
output << "Top Wall = " << Utils::getBoundaryString(WALL_TOP) << "\n";
// TIME STEP
output << "\nTIME STEP:\n";
output << "Time = " << Dt * nSteps << " s\n";
output << "nSteps = " << nSteps << "\n";
output << "tInfo = " << tinfo << "\n";
#ifdef VTK
output << "tVTK = " << tVTK << "\n";
#endif
output << "tRestart = " << tRestart << "\n";
// If doing a restart then write out how many time steps for this run
if (restartFlag == true) {
output << "Total Time = " << Dt * (tOffset + nSteps) << " s\n";
output << "Total nSteps = " << (tOffset + nSteps) << "\n";
}
// REFERENCE VALUES
output << "\nREFERENCE VALUES:\n";
output << "Reference Viscosity (m^2/s) = " << ref_nu << "\n";
output << "Reference Density (kg/m^3) = " << ref_rho << "\n";
output << "Reference Pressure (Pa) = " << ref_P << "\n";
output << "Reference Length (m) = " << ref_L << "\n";
output << "Reference Velocity = " << ref_U * Dt / Dx << "\n";
output << "Reference Velocity (m/s) = " << ref_U << "\n";
output << "Reynolds Number = " << ref_U * ref_L / ref_nu;
// Set precision
output << setprecision(ss);
// Close
output.close();
}
// Write fluid VTK
void GridClass::writeVTK() {
// Get the endianness
string endianStr = (bigEndian ? "BigEndian" : "LittleEndian");
// Create file
ofstream output;
output.open("Results/VTK/Fluid." + to_string(t) + ".vti", ios::binary);
// Handle failure to open
if (!output.is_open())
ERROR("Error opening fluid VTK file...exiting");
// Write XML header
output << "<?xml version=\"1.0\"?>\n";
// Begin VTK file
int level = 0;
output << "<VTKFile type=\"ImageData\" version=\"1.0\" byte_order=\"" << endianStr << "\" header_type=\"UInt64\">\n";
// New level -> ImageData
level = 1;
output << string(level, '\t') << "<ImageData "
<< "WholeExtent=\"" << 0.0 << " " << Nx - 1 << " " << 0.0 << " " << Ny - 1 << " " << 0.0 << " " << 0.0 << "\" "
<< "Origin=\"" << 0.0 << " " << 0.0 << " " << 0.0 << "\" "
<< "Spacing=\"" << Dx << " " << Dx << " " << Dx << "\">\n";
// New level -> Piece
level = 2;
output << string(level, '\t') << "<Piece Extent=\"" << 0.0 << " " << Nx - 1 << " " << 0.0 << " " << Ny - 1 << " " << 0.0 << " " << 0.0 << "\">\n";
// New level -> PointData
level = 3;
output << string(level, '\t') << "<PointData>\n";
// New level -> DataArray
level = 4;
// Density
output << string(level, '\t') << "<DataArray type=\"Float64\" Name=\"Density\" format=\"appended\" offset=\"" << 0 << "\"/>\n";
// Pressure
output << string(level, '\t') << "<DataArray type=\"Float64\" Name=\"Pressure\" format=\"appended\" offset=\"" << 1*(Nx*Ny*sizeof(double) + sizeof(unsigned long long)) << "\"/>\n";
// Velocity
output << string(level, '\t') << "<DataArray type=\"Float64\" Name=\"Velocity\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << 2*(Nx*Ny*sizeof(double) + sizeof(unsigned long long)) << "\"/>\n";
// Back level -> PointData
level = 3;
output << string(level, '\t') << "</PointData>\n";
// Back level -> Piece
level = 2;
output << string(level, '\t') << "</Piece>\n";
// Back level -> ImageData
level = 1;
output << string(level, '\t') << "</ImageData>\n";
// New level -> AppendedData
level = 1;
output << string(level, '\t') << "<AppendedData encoding=\"raw\">\n";
// New level -> Raw data
level = 2;
output << string(level, '\t') << "_";
// Density
unsigned long long size = Nx * Ny * sizeof(double);
output.write((char*)&size, sizeof(unsigned long long));
for (int j = 0; j < Ny; j++) {
for (int i = 0; i < Nx; i++) {
double density = rho[i * Ny + j] * Drho;
output.write((char*)&density, sizeof(double));
}
}
// Pressure
size = Nx * Ny * sizeof(double);
output.write((char*)&size, sizeof(unsigned long long));
for (int j = 0; j < Ny; j++) {
for (int i = 0; i < Nx; i++) {
double pressure = ref_P + (rho[i * Ny + j] - rho_p / Drho) * SQ(c_s) * Dm / (Dx * SQ(Dt));
output.write((char*)&pressure, sizeof(double));
}
}
// Velocity
size = 3 * Nx * Ny * sizeof(double);
output.write((char*)&size, sizeof(unsigned long long));
for (int j = 0; j < Ny; j++) {
for (int i = 0; i < Nx; i++) {
double ux = u[(i * Ny + j) * dims + eX] * (Dx / Dt);
double uy = u[(i * Ny + j) * dims + eY] * (Dx / Dt);
double uz = 0.0;
output.write((char*)&ux, sizeof(double));
output.write((char*)&uy, sizeof(double));
output.write((char*)&uz, sizeof(double));
}
}
// Back level -> AppendedData
level = 1;
output << "\n" << string(level, '\t') << "</AppendedData>\n";
// Back level -> VTKFile
level = 0;
output << string(level, '\t') << "</VTKFile>\n";
// Close file
output.close();
// Check if we should write some blank VTK files for the body
if (!oPtr->hasIBM && boost::filesystem::exists("Results/VTK/IBM.0.vtp")) {
string fname = "Results/VTK/IBM." + to_string(t) + string(".vtp");
oPtr->writeEmptyVTK(fname);
}
#ifdef VTK_FEM
if (!oPtr->hasFlex && boost::filesystem::exists("Results/VTK/FEM.0.vtp")) {
string fname = "Results/VTK/FEM." + to_string(t) + string(".vtp");
oPtr->writeEmptyVTK(fname);
}
#endif
}
// Initialise grid values
void GridClass::initialiseGrid() {
// First check to make we don't have convective BC anywhere other than RHS
if (WALL_LEFT == eConvective || WALL_BOTTOM == eConvective || WALL_TOP == eConvective)
ERROR("Currently convective BC only supported for right boundary...exiting");
else if (WALL_RIGHT == eConvective)
delU.resize(Ny * dims, 0.0);
// Set type matrix
for (int i = 0; i < Nx; i++) {
for (int j = 0; j < Ny; j++) {
// Get id
int id = i * Ny + j;
// Left wall
if (i == 0)
type[id] = WALL_LEFT;
// Right wall
else if (i == Nx - 1)
type[id] = WALL_RIGHT;
// Bottom wall
if (j == 0)
type[id] = WALL_BOTTOM;
// Top wall
else if (j == Ny - 1)
type[id] = WALL_TOP;
// Add to the BC vector
if (type[id] != eFluid)
BCVec.push_back(id);
}
}
// Loop through and set inlet profile
for (int j = 0; j < Ny; j++) {
#ifndef PROFILE
// Set initial velocity to be uniform
u_in[j * dims + eX] = uxInlet_p * Dt / Dx;
u_in[j * dims + eY] = uyInlet_p * Dt / Dx;
#else
// Generate velocity profile
if (PROFILE == eParabolic) {
// Get parameters for working out parabolic profile
double R = height_p / 2.0;
double YPos = j * Dx - R;
// Set velocity
u_in[j * dims + eX] = 1.5 * (uxInlet_p * Dt / Dx) * (1.0 - SQ(YPos / R));
u_in[j * dims + eY] = 1.5 * (uyInlet_p * Dt / Dx) * (1.0 - SQ(YPos / R));
}
else if (PROFILE == eShear) {
// Get parameters for working out shear profile
double H = height_p;
double YPos = j * Dx;
// Set velocity
u_in[j * dims + eX] = (uxInlet_p * Dt / Dx) * (YPos / H);
u_in[j * dims + eY] = (uyInlet_p * Dt / Dx) * (YPos / H);
}
else if (PROFILE == eBoundaryLayer) {
// Get parameters for working out shear profile
double H = height_p;
double YPos = j * Dx;
// Set velocity
u_in[j * dims + eX] = ((1.5 * uxInlet_p * Dt / Dx) / SQ(H)) * YPos * (2.0 * H - YPos);
u_in[j * dims + eY] = ((1.5 * uyInlet_p * Dt / Dx) / SQ(H)) * YPos * (2.0 * H - YPos);
}
#endif
}
// Set initial velocity
for (int i = 0; i < Nx; i++) {
for (int j = 0; j < Ny; j++) {
// Get id
int id = i * Ny + j;
#ifdef INLET_RAMP
u[id * dims + eX] = 0.0;
u[id * dims + eY] = 0.0;
#else
#ifdef PROFILE
// Set velocity
u[id * dims + eX] = u_in[j * dims + eX];
u[id * dims + eY] = u_in[j * dims + eY];
#else
// Set initial velocity to be uniform
u[id * dims + eX] = ux0_p * Dt / Dx;
u[id * dims + eY] = uy0_p * Dt / Dx;
#endif
#endif
// If a wall then set to zero
if (type[id] == eWall) {
u[id * dims + eX] = 0.0;
u[id * dims + eY] = 0.0;
}
}
}
// Set start of time step values
u_n = u;
rho_n = rho;
// Set the xy forces
for (int i = 0; i < Nx; i++) {
for (int j = 0; j < Ny; j++) {
// ID
int id = i * Ny + j;
// Set the xyz cartesian forces
force_xy[id * dims + eX] = (rho[id] * Drho * gravityX + dpdx) * SQ(Dx * Dt) / Dm;
force_xy[id * dims + eY] = (rho[id] * Drho * gravityY + dpdy) * SQ(Dx * Dt) / Dm;
}
}
// Set f values to equilibrium
for (int i = 0; i < Nx; i++) {
for (int j = 0; j < Ny; j++) {
// ID
int id = i * Ny + j;
// Loop though vels
for (int v = 0; v < nVels; v++)
f[id * nVels + v] = equilibrium(id, v);
}
}
// Set start of time step values
f_n = f;
}
// Start the clock for getting MLUPS
void GridClass::startClock() {
// Start clock
startTime = omp_get_wtime();
}
// Read in restart file
void GridClass::readRestart() {
// Open file
ifstream file;
file.open("Results/Restart/Fluid.restart", ios::binary);
// Handle failure to open
if (!file.is_open())
ERROR("Error opening Fluid.restart file...exiting");
// Declare values
int tRead, nxRead, nyRead;
double omegaRead, dxRead, dtRead, dmRead;
// Read in global info
file.read((char*)&tRead, sizeof(int));
file.read((char*)&nxRead, sizeof(int));
file.read((char*)&nyRead, sizeof(int));
file.read((char*)&omegaRead, sizeof(double));
file.read((char*)&dxRead, sizeof(double));
file.read((char*)&dtRead, sizeof(double));
file.read((char*)&dmRead, sizeof(double));
// Swap byte order if bigEndian
int nxSwap = (bigEndian ? Utils::swapEnd(nxRead) : nxRead);
int nySwap = (bigEndian ? Utils::swapEnd(nyRead) : nyRead);
double omegaSwap = (bigEndian ? Utils::swapEnd(omegaRead) : omegaRead);
double dxSwap = (bigEndian ? Utils::swapEnd(dxRead) : dxRead);
double dtSwap = (bigEndian ? Utils::swapEnd(dtRead) : dtRead);
double dmSwap = (bigEndian ? Utils::swapEnd(dmRead) : dmRead);
// Check they match up
if (Nx != nxSwap || Ny != nySwap || omega != omegaSwap || Dx != dxSwap || Dt != dtSwap || Dm != dmSwap)
ERROR("Grid size/scaling has changed between runs...this is not supported");
// Get the time to start from
tOffset = (bigEndian ? Utils::swapEnd(tRead) : tRead);
t = tOffset;
// Now loop through each lattice site and read necessary data
for (int i = 0; i < Nx; i++) {
for (int j = 0; j < Ny; j++) {
// ID
int id = i * Ny + j;
// Declare values
int iRead, jRead;
double rhoRead, uxRead, uyRead, fxRead, fyRead;
// Read in data
file.read((char*)&iRead, sizeof(int));
file.read((char*)&jRead, sizeof(int));
file.read((char*)&rhoRead, sizeof(double));
file.read((char*)&uxRead, sizeof(double));
file.read((char*)&uyRead, sizeof(double));
file.read((char*)&fxRead, sizeof(double));
file.read((char*)&fyRead, sizeof(double));
// Swap byte order if bigEndian
int iSwap = (bigEndian ? Utils::swapEnd(iRead) : iRead);
int jSwap = (bigEndian ? Utils::swapEnd(jRead) : jRead);
double rhoSwap = (bigEndian ? Utils::swapEnd(rhoRead) : rhoRead);
double uxSwap = (bigEndian ? Utils::swapEnd(uxRead) : uxRead);
double uySwap = (bigEndian ? Utils::swapEnd(uyRead) : uyRead);
double fxSwap = (bigEndian ? Utils::swapEnd(fxRead) : fxRead);
double fySwap = (bigEndian ? Utils::swapEnd(fyRead) : fyRead);
// Check they match up
if (i != iSwap || j != jSwap)
ERROR("Grid indices do not match Fluid.restart file...exiting");
// Read into grid data
rho[id] = rhoSwap;
u[id * dims + eX] = uxSwap;
u[id * dims + eY] = uySwap;
force_ibm[id * dims + eX] = fxSwap;
force_ibm[id * dims + eY] = fySwap;
// Read in f values
for (int v = 0; v < nVels; v++) {
double fRead;
file.read((char*)&fRead, sizeof(double));
double fSwap = (bigEndian ? Utils::swapEnd(fRead) : fRead);
f[id * nVels + v] = fSwap;
}
}
}
}
// Read in restart file
void GridClass::writeRestart() {
// Create file
ofstream output;
output.open("Results/Restart/Fluid.restart.temp", ios::binary);
// Handle failure to open
if (!output.is_open())
ERROR("Error opening Fluid.restart.temp file...exiting");
// Swap byte order if bigEndian
int tWrite = (bigEndian ? Utils::swapEnd(t) : t);
int nxWrite = (bigEndian ? Utils::swapEnd(Nx) : Nx);
int nyWrite = (bigEndian ? Utils::swapEnd(Ny) : Ny);
double omegaWrite = (bigEndian ? Utils::swapEnd(omega) : omega);
double dxWrite = (bigEndian ? Utils::swapEnd(Dx) : Dx);
double dtWrite = (bigEndian ? Utils::swapEnd(Dt) : Dt);
double dmWrite = (bigEndian ? Utils::swapEnd(Dm) : Dm);
// Write out global information
output.write((char*)&tWrite, sizeof(int));
output.write((char*)&nxWrite, sizeof(int));
output.write((char*)&nyWrite, sizeof(int));
output.write((char*)&omegaWrite, sizeof(double));
output.write((char*)&dxWrite, sizeof(double));
output.write((char*)&dtWrite, sizeof(double));
output.write((char*)&dmWrite, sizeof(double));
// Now loop through each lattice site and write necessary data
for (int i = 0; i < Nx; i++) {
for (int j = 0; j < Ny; j++) {
// ID
int id = i * Ny + j;
// Swap byte order if bigEndian
int iWrite = (bigEndian ? Utils::swapEnd(i) : i);
int jWrite = (bigEndian ? Utils::swapEnd(j) : j);
double rhoWrite = (bigEndian ? Utils::swapEnd(rho[id]) : rho[id]);
double uxWrite = (bigEndian ? Utils::swapEnd(u[id * dims + eX]) : u[id * dims + eX]);
double uyWrite = (bigEndian ? Utils::swapEnd(u[id * dims + eY]) : u[id * dims + eY]);
double fxWrite = (bigEndian ? Utils::swapEnd(force_ibm[id * dims + eX]) : force_ibm[id * dims + eX]);
double fyWrite = (bigEndian ? Utils::swapEnd(force_ibm[id * dims + eY]) : force_ibm[id * dims + eY]);
// Write out global information
output.write((char*)&iWrite, sizeof(int));
output.write((char*)&jWrite, sizeof(int));
output.write((char*)&rhoWrite, sizeof(double));
output.write((char*)&uxWrite, sizeof(double));
output.write((char*)&uyWrite, sizeof(double));
output.write((char*)&fxWrite, sizeof(double));
output.write((char*)&fyWrite, sizeof(double));
// Write out f values
for (int v = 0; v < nVels; v++) {
double fWrite = (bigEndian ? Utils::swapEnd(f[id * nVels + v]) : f[id * nVels + v]);
output.write((char*)&fWrite, sizeof(double));
}
}
}
// Close file
output.close();
// Now rename the temp file
boost::filesystem::rename("Results/Restart/Fluid.restart.temp", "Results/Restart/Fluid.restart");
}
// Constructor
GridClass::GridClass() {
// Create directories
restartFlag = Utils::createDirectories();
// Write out
cout << endl << endl << "Initialising grid...";
// Initially set objects to NULL
oPtr = NULL;
// Some default parameters
double rho0 = 1.0;
// D2Q9 parameters (can be hard-coded)
c_s = 1.0 / sqrt(3.0);
w = {4.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0};
c = {0, 0, 1, 0, -1, 0, 0, 1, 0, -1, 1, 1, -1, -1, 1, -1, -1, 1};
opposite = {0, 2, 1, 4, 3, 6, 5, 8, 7};
// Initialise parameters
t = 0;
tOffset = 0;
tau = 1.0 / omega;
nu = (tau - 0.5) * SQ(c_s);
Dx = height_p / (Ny - 1);
Dt = SQ(Dx) * nu / nu_p;
Dm = (rho_p / rho0) * TH(Dx);
Drho = (rho_p / rho0);
// Call clock
startTime = omp_get_wtime();
loopTime = 0.0;
// Set the sizes and initialise arrays
u.resize(Nx * Ny * dims, 0.0);
u_n.resize(Nx * Ny * dims, 0.0);
rho.resize(Nx * Ny, rho0);
rho_n.resize(Nx * Ny, rho0);
force_xy.resize(Nx * Ny * dims, 0.0);
force_ibm.resize(Nx * Ny * dims, 0.0);
type.resize(Nx * Ny, eFluid);
f.resize(Nx * Ny * nVels, 0.0);
f_n.resize(Nx * Ny * nVels, 0.0);
// Set sizes of helper arrays
u_in.resize(Ny * dims, 0.0);
rho_in.resize(Ny, rho0);
// Initialise grid
initialiseGrid();
// Check for big or little endian
bigEndian = Utils::isBigEndian();
// Write out header
cout << "finished";
}
| 38,489
|
C++
|
.cpp
| 1,036
| 34.150579
| 208
| 0.577903
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,158
|
FEMBody.cpp
|
joconnor22_LIFE/src/FEMBody.cpp
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
// Includes
#include "../inc/FEMBody.h"
#include "../inc/Grid.h"
#include "../inc/Objects.h"
#include "../inc/Utils.h"
// Dynamic FEM routine
void FEMBodyClass::dynamicFEM() {
// Reset back to start of time step
U = U_n;
Udot = Udot_n;
Udotdot = Udotdot_n;
// Update FEM elements
updateFEMValues();
// Construct load vector as invariant during Newton-Raphson iterations
constructRVector();
// While loop parameters
double TOL = 1e-10;
double MAXIT = 20;
// Set while counter to zero
itNR = 0;
// While loop for FEM solver
do {
// Solve and iterate over the system
newtonRaphsonDynamic();
// Check residual
resNR = checkNRConvergence();
// Increment counter
itNR++;
} while (resNR > TOL && itNR < MAXIT);
// Compute new velocities and accelerations
finishNewmark();
// Update IBM nodes
updateIBMValues();
// Get subiteration residual for this body (will be summed later on)
subResidual();
}
// Newton raphson iterator
void FEMBodyClass::newtonRaphsonDynamic() {
// Build global matrices
buildGlobalMatrices();
// Apply Newmark scheme (using Newmark coefficients)
setNewmark();
// Solve linear system using LAPACK library
delU = Utils::solveLAPACK(K, F, bcDOFs);
// Add deltaU to U
U = U + delU;
// Update FEM positions
updateFEMValues();
}
// Build global matrices
void FEMBodyClass::buildGlobalMatrices() {
// Set matrices to zero
fill(M.begin(), M.end(), 0.0);
fill(K.begin(), K.end(), 0.0);
fill(F.begin(), F.end(), 0.0);
// Loop through and build global matrices
for (size_t el = 0; el < element.size(); el++) {
// Build force vector
element[el].forceVector();
// Build mass matrix
element[el].massMatrix();
// Build stiffness matrix
element[el].stiffMatrix();
}
}
// Set Newmark
void FEMBodyClass::setNewmark() {
// Newmark-beta method for time integration
double Dt = iPtr->oPtr->gPtr->Dt;
double a0, a2, a3;
a0 = 1.0 / (alpha * SQ(Dt));
a2 = 1.0 / (alpha * Dt);
a3 = 1.0 / (2.0 * alpha) - 1.0;
// Calculate effective load vector
F = R - F + Utils::MatMultiply(M, a0 * (U_n - U) + a2 * Udot + a3 * Udotdot);
// Calculate effective stiffness matrix
K = K + a0 * M;
}
// Finish Newmark
void FEMBodyClass::finishNewmark() {
// Get timestep
double Dt = iPtr->oPtr->gPtr->Dt;
// Newmark coefficients
double a6 = 1.0 / (alpha * SQ(Dt));
double a7 = -1.0 / (alpha * Dt);
double a8 = -(1.0 / (2.0 * alpha) - 1.0);
double a9 = Dt * (1.0 - delta);
double a10 = delta * Dt;
// Update velocities and accelerations
Udotdot = a6 * (U - U_n) + a7 * Udot_n + a8 * Udotdot_n;
Udot = Udot_n + a9 * Udotdot_n + a10 * Udotdot;
}
// Update IBM markers
void FEMBodyClass::updateIBMValues() {
// Declare local vectors
array<double, elementDOFs> dashU;
array<double, elementDOFs> dashUdot;
array<double, dims> dashUShape;
array<double, dims> dashUdotShape;
array<array<double, dims>, dims> Tsub;
// Loop through posMap points
for (size_t i = 0; i < posMap.size(); i++) {
// Get pointer to element and zeta value
FEMElementClass *el = &(element[posMap[i].elID]);
double zeta = posMap[i].zeta;
// Disassemble positions, velocities and accelerations
dashU = el->disassembleGlobalMat(U);
dashUdot = el->disassembleGlobalMat(Udot);
// Convert the displacement into local coordinates (shift angle as well)
for (size_t n = 0; n < el->node.size(); n++) {
dashU[n*nodeDOFs+eX] += el->node[n]->pos0[eX] - el->node[0]->pos[eX];
dashU[n*nodeDOFs+eY] += el->node[n]->pos0[eY] - el->node[0]->pos[eY];
dashU[n*nodeDOFs+(nodeDOFs-1)] += el->node[n]->angle0 - el->angle;
dashU[n*nodeDOFs+(nodeDOFs-1)] = Utils::shiftAngle(dashU[n*nodeDOFs+(nodeDOFs-1)]);
}
// Get element values in local coordinates
dashU = el->T * dashU;
dashUdot = el->T * dashUdot;
// Multiply by shape functions
dashUShape = el->shapeFuns(dashU, zeta);
dashUdotShape = el->shapeFuns(dashUdot, zeta);
// Get subset of transformation matrix
Tsub = {{{el->T[0][0], el->T[0][1]},
{el->T[1][0], el->T[1][1]}}};
// Shift back to global coordinates
dashUShape = Utils::Transpose(Tsub) * dashUShape;
dashUdotShape = Utils::Transpose(Tsub) * dashUdotShape;
// Set the IBM nodes
iPtr->node[i]->pos = el->node[0]->pos + dashUShape;
iPtr->node[i]->vel = dashUdotShape;
}
}
// Update FEM values
void FEMBodyClass::updateFEMValues() {
// Set the new positions
for (size_t n = 0; n < node.size(); n++) {
// Positions
for (int d = 0; d < dims; d++)
node[n].pos[d] = node[n].pos0[d] + U[node[n].DOFs[d]];
// Set angle
node[n].angle = node[n].angle0 + U[node[n].DOFs[dims]];
}
// Set the new angles and lengths of the elements
array<double, dims> elVector;
for (size_t el = 0; el < element.size(); el++) {
// Set the new angles and lengths of the elements
elVector = element[el].node[1]->pos - element[el].node[0]->pos;
element[el].angle = atan2(elVector[eY], elVector[eX]);
element[el].L = sqrt(elVector * elVector);
// Set new transformation matrix
element[el].setElementTransform();
}
}
// Get load vector
void FEMBodyClass::constructRVector() {
// Set R to zero
fill(R.begin(), R.end(), 0.0);
// Loop through all FEM elements
for (size_t el = 0; el < element.size(); el++)
element[el].loadVector();
}
// Check convergence of Newton Raphson iterator
inline double FEMBodyClass::checkNRConvergence () {
// Get the norm of delU
return sqrt(delU * delU) / (ref_L * sqrt(static_cast<double>(delU.size())));
}
// Do a sum reduction to get the subiteration residual
void FEMBodyClass::subResidual() {
// Get the residual from this time step and reassign old time step value
R_km1 = R_k;
R_k = U - U_km1;
// Get residual for this body
subRes = R_k * R_k;
// Get numerator and denominator for calculating relaxation factor
subNum = R_km1 * (R_k - R_km1);
subDen = (R_k - R_km1) * (R_k - R_km1);
}
// predictor
void FEMBodyClass::predictor() {
// Extrapolate the values
if (iPtr->oPtr->gPtr->t > 2) {
// Do 2rd order extrapolation
U = 2.5 * U_n - 2.0 * U_nm1 + 0.5 * U_nm2;
}
else if (iPtr->oPtr->gPtr->t == 2) {
// Do 1st order extrapolation
U = 2.0 * U_n - U_nm1;
}
else if (iPtr->oPtr->gPtr->t == 1) {
// Do zeroth order extrapolation
U = U_n;
}
// Update FEM elements
updateFEMValues();
// Update the velocity
finishNewmark();
// Update IBM values
updateIBMValues();
// Set U_km1
U_km1.swap(U);
}
// Get node mappings between FEM and IBM grids
void FEMBodyClass::computeNodeMapping(int nIBMNodes, int nFEMNodes) {
// Size the map from FEM to IBM (1 for each IBM node)
posMap.resize(nIBMNodes);
// Set first node first
posMap[0].elID = 0;
posMap[0].zeta = -1.0;
// Now loop through and set values
for (int i = 1; i < nIBMNodes; i++) {
// Check if remainder is zero
if (fmod(i * ((nFEMNodes - 1.0) / (nIBMNodes - 1.0)), 1.0) == 0.0) {
posMap[i].elID = static_cast<int>(std::floor(i * ((nFEMNodes - 1.0) / (nIBMNodes - 1.0)))) - 1;
posMap[i].zeta = 1.0;
}
else {
posMap[i].elID = static_cast<int>(std::floor(i * ((nFEMNodes - 1.0) / (nIBMNodes - 1.0))));
posMap[i].zeta = fmod(i * ((nFEMNodes - 1.0) / (nIBMNodes - 1.0)), 1.0) * 2.0 - 1.0;
}
}
// Loop through elements
double node1, node2;
for (size_t el = 0; el < element.size(); el++) {
// Loop through all nodes and scale range to local coordinates for element
for (int node = 0; node < nIBMNodes; node++) {
node1 = -1 + 2.0 * ((static_cast<double>(node) - 0.5) * ((nFEMNodes - 1.0) / (nIBMNodes - 1.0)) - static_cast<double>(el)) / 1.0;
node2 = -1 + 2.0 * ((static_cast<double>(node) + 0.5) * ((nFEMNodes - 1.0) / (nIBMNodes - 1.0)) - static_cast<double>(el)) / 1.0;
// Check if any points lie within element coordinate range
if ((node1 > -1.0 && node1 < 1.0) || (node2 > -1.0 && node2 < 1.0)) {
// Sort out end nodes where one point lie outside element
if (node1 < -1.0)
node1 = -1.0;
if (node2 > 1.0)
node2 = 1.0;
// Call constructor for chile IB point
element[el].forceMap.emplace_back(node, node1, node2);
}
}
}
}
// Reset the start of time step values
void FEMBodyClass::resetValues() {
// Reset start of time step values
U_nm2.swap(U_nm1);
U_nm1.swap(U_n);
U_n.swap(U);
Udot_n.swap(Udot);
Udotdot_n.swap(Udotdot);
}
// Set initial deflection using static FEM
void FEMBodyClass::setInitialDeflection() {
// Write out
cout << endl << "Starting static FEM for body " << iPtr->ID << "...";
// Initial deflection
double deflect = 0.0;
// Set initial deflection
#ifdef INITIAL_DEFLECT
deflect = -INITIAL_DEFLECT;
#endif
// Get beam properties
double E = element[0].E;
double I = element[0].I;
// Calculate linear force required to give specified deflection
double linearForce = 3.0 * E * I * deflect / SQ(L0);
// Set load steps and get max deltaForce
int nSteps = 100;
double deltaForceMax = linearForce / static_cast<double>(nSteps);
// Get rotation matrix
array<array<double, dims>, dims> T = Utils::getRotationMatrix(angle0);
// Get initial force at tip
array<double, dims> localForce = {0.0, deltaForceMax};
array<double, dims> globalForce = T * localForce;
// Set it to load vector
R[bodyDOFs-nodeDOFs] = globalForce[0];
R[bodyDOFs-nodeDOFs+1] = globalForce[1];
// Declare feedback loop parameters
array<double, dims> deflectVector;
double gain = 1e-3;
double TOL = 1e-10;
int MAXIT = 10000;
int it = 0;
double error;
// Start feedback loop
do {
// Static FEM calculation
staticFEM();
// Get deflection vector
deflectVector = {U[bodyDOFs-nodeDOFs], U[bodyDOFs-nodeDOFs+1]};
deflectVector = Utils::Transpose(T) * deflectVector;
// Get error
error = (deflect - (deflectVector[1] / L0));
// Force correction
double forceCorrect = error * gain;
// Check force correction is smaller than force interval
if (fabs(forceCorrect) > fabs(deltaForceMax))
forceCorrect = Utils::sgn(forceCorrect) * fabs(deltaForceMax);
// Add to R vector
localForce[1] += forceCorrect;
globalForce = T * localForce;
// Add to R vector
R[bodyDOFs-nodeDOFs] = globalForce[0];
R[bodyDOFs-nodeDOFs+1] = globalForce[1];
// Increment counter
it++;
// Check if done max iterations
if (it >= MAXIT)
ERROR("max iterations hit! Try changing the gain...exiting");
} while (fabs(error) > TOL);
// Write out
cout << "finished in " << it << " iterations";
// Reset values to zero
itNR = 0;
resNR = 0.0;
fill(R.begin(), R.end(), 0.0);
fill(delU.begin(), delU.end(), 0.0);
}
// Newton raphson iterator
void FEMBodyClass::staticFEM() {
// While loop parameters
double TOL = 1e-10;
double MAXIT = 20;
// Set while counter to zero
itNR = 0;
// While loop for FEM solver
do {
// Solve and iterate over the system
newtonRaphsonStatic();
// Check residual
resNR = checkNRConvergence();
// Increment counter
itNR++;
} while (resNR > TOL && itNR < MAXIT);
// Update IBM nodes
updateIBMValues();
}
// Newton raphson iterator
void FEMBodyClass::newtonRaphsonStatic() {
// Build global matrices
buildGlobalMatrices();
// Solve linear system using LAPACK library
delU = Utils::solveLAPACK(K, R - F, bcDOFs);
// Add deltaU to U
U = U + delU;
// Update FEM positions
updateFEMValues();
}
// Custom constructor for building corotational FEM body
FEMBodyClass::FEMBodyClass(IBMBodyClass *iBodyPtr, const array<double, dims> &pos, const array<double, dims> &geom, double angle, string nElementsStr, string BC, double rho, double E) {
// Set pointer
iPtr = iBodyPtr;
// Set to initial value
itNR = 0;
resNR = 0.0;
// Set sub residaul, numerator and denominator to initial value
subRes = 0.0;
subNum = 0.0;
subDen = 0.0;
// Get number of DOFs required for BC
if (BC == "CLAMPED")
bcDOFs = 3;
else if (BC == "SUPPORTED")
bcDOFs = 2;
// Unpack geometry
angle0 = angle;
L0 = geom[0];
// Get number of elements
int numElements;
if (nElementsStr == "CONFORMING")
numElements = static_cast<int>(floor(L0 / iPtr->oPtr->gPtr->Dx));
else
numElements = static_cast<int>(stod(nElementsStr));
// Get number of nodes
int numNodes = numElements + 1;
// Get number of DOFs in body
bodyDOFs = numNodes * nodeDOFs;
// Get critical time step for this body
tCrit = (L0 / numElements) / sqrt(E / rho);
// Get rotation matrix
array<array<double, dims>, dims> T = Utils::getRotationMatrix(angle);
// Position vector for marker
array<double, dims> position;
// Loop through and build nodes
for (int i = 0; i < numNodes; i++) {
// Get position of this marker
position[eX] = i * L0 / numElements;
position[eY] = 0.0;
// Rotate
position = T * position;
// Add the start point
position = pos + position;
// Call node constructor
node.emplace_back(i, position, angle);
}
// Loop through and build elements
for (int i = 0; i < numElements; i++)
element.emplace_back(this, i, geom, angle, L0 / numElements, rho, E);
// Get number of IBM and FEM nodes
int nIBMNodes = static_cast<int>(iPtr->node.size());
int nFEMNodes = static_cast<int>(node.size());
// Compute IBM-FEM conforming parameters
computeNodeMapping(nIBMNodes, nFEMNodes);
// Size the matrices
M.resize(bodyDOFs * bodyDOFs, 0.0);
K.resize(bodyDOFs * bodyDOFs, 0.0);
R.resize(bodyDOFs, 0.0);
F.resize(bodyDOFs, 0.0);
U.resize(bodyDOFs, 0.0);
delU.resize(bodyDOFs, 0.0);
Udot.resize(bodyDOFs, 0.0);
Udotdot.resize(bodyDOFs, 0.0);
U_n.resize(bodyDOFs, 0.0);
U_nm1.resize(bodyDOFs, 0.0);
U_nm2.resize(bodyDOFs, 0.0);
Udot_n.resize(bodyDOFs, 0.0);
Udotdot_n.resize(bodyDOFs, 0.0);
U_km1.resize(bodyDOFs, 0.0);
R_k.resize(bodyDOFs, 0.0);
R_km1.resize(bodyDOFs, 0.0);
}
| 14,424
|
C++
|
.cpp
| 433
| 30.662818
| 185
| 0.684385
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,159
|
Objects.cpp
|
joconnor22_LIFE/src/Objects.cpp
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
// Includes
#include "../inc/Objects.h"
#include "../inc/FEMBody.h"
#include "../inc/Grid.h"
#include "../inc/Utils.h"
// Main kernel for objects
void ObjectsClass::objectKernel() {
// While loop parameters
subIt = 0;
int MAXIT = 20;
// Subiteration loop
do {
// Do predictor, recompute support, ds, and epsilon
if (hasFlex == true)
recomputeObjectVals();
// Do IBM interpolation step
ibmKernelInterp();
// If only rigid bodies then we can break
if (hasFlex == false)
break;
// Do FEM step
femKernel();
// Increase subIt
subIt++;
} while (subIt < MAXIT && subRes > subTol);
// Do IBM spreading step
ibmKernelSpread();
// If it reached max iterations then exit
if (subIt == MAXIT)
ERROR("Subiteration scheme hit " + to_string(subIt) + " iterations...exiting");
}
// Do FEM and update IBM positions and velocities
void ObjectsClass::femKernel() {
// Declare residual parameters
double res = 0.0;
double num = 0.0;
double den = 0.0;
// Loop through all bodies, do FEM, and then sum to get residual values
#ifdef ORDERED
#pragma omp parallel for ordered schedule(dynamic,1)
#else
#pragma omp parallel for schedule(guided) reduction(+:res, num, den)
#endif
for (size_t ib = 0; ib < iBody.size(); ib++) {
if (iBody[ib].flex == eFlexible) {
// Do the dynamic FEM routine
iBody[ib].sBody->dynamicFEM();
// Either do ordered or non-deterministic sum (it can affect results)
#ifdef ORDERED
#pragma omp ordered
#endif
{
// Sum to get global values
res += iBody[ib].sBody->subRes;
num += iBody[ib].sBody->subNum;
den += iBody[ib].sBody->subDen;
}
}
}
// Set global values
subRes = sqrt(res) / (ref_L * sqrt(static_cast<double>(simDOFs)));
subNum = num;
subDen = den;
}
// Interpolate and force calc
void ObjectsClass::ibmKernelInterp() {
// Reset IBM forces
fill(gPtr->force_ibm.begin(), gPtr->force_ibm.end(), 0.0);
// Loop through all bodies and nodes
#pragma omp parallel for schedule(guided)
for (size_t i = 0; i < iNode.size(); i++) {
// Interpolate
iNode[i].interpolate();
// Force calculation
iNode[i].forceCalc();
}
}
// Force spread and update macro
void ObjectsClass::ibmKernelSpread() {
// Reset IBM forces
fill(gPtr->force_ibm.begin(), gPtr->force_ibm.end(), 0.0);
// Start parallel section
#pragma omp parallel
{
// Loop through all bodies and nodes
#ifdef ORDERED
#pragma omp for ordered schedule(dynamic,1)
#else
#pragma omp for schedule(guided)
#endif
for (size_t i = 0; i < iNode.size(); i++) {
// Force spread
iNode[i].spread();
}
// Loop through all bodies and nodes
#pragma omp for schedule(guided)
for (size_t i = 0; i < iNode.size(); i++) {
// Update macroscopic
iNode[i].updateMacroscopic();
}
}
}
// Recompute support, ds, and epsilon and subiteration values
void ObjectsClass::recomputeObjectVals() {
// Start parallel section
#pragma omp parallel
{
// Do predictor step if first iteration
if (subIt == 0) {
// Loop through bodies, set start of time step, and do predictor (if on)
#pragma omp for schedule(guided)
for (size_t ib = 0; ib < iBody.size(); ib++) {
if (iBody[ib].flex == eFlexible) {
// Set the start of timestep values
iBody[ib].sBody->resetValues();
// Predictor step
iBody[ib].sBody->predictor();
}
}
}
// Else calculate new relaxation parameter and do the relaxation
else {
// Get relaxation value (only one thread)
#pragma omp single
{
if (subIt == 1) {
// Use max relax if need be on first iteration
relax = static_cast<double>(Utils::sgn(relax) * min(fabs(relax), relaxMax));
}
else {
// Use global residual values to get next relaxation factor
relax = -relax * subNum / subDen;
}
}
// Relax displacements and update IBM
#pragma omp for schedule(guided)
for (size_t ib = 0; ib < iBody.size(); ib++) {
if (iBody[ib].flex == eFlexible) {
// Apply relaxation
iBody[ib].sBody->U = iBody[ib].sBody->U_km1 + relax * (iBody[ib].sBody->U - iBody[ib].sBody->U_km1);
// Update FEM elements
iBody[ib].sBody->updateFEMValues();
// Update the velocity
iBody[ib].sBody->finishNewmark();
// Update IBM values
iBody[ib].sBody->updateIBMValues();
// Set previous iteration value
iBody[ib].sBody->U_km1.swap(iBody[ib].sBody->U);
}
}
}
// Loop through all bodies and nodes
#pragma omp for schedule(guided)
for (size_t i = 0; i < iNode.size(); i++) {
if (iNode[i].iPtr->flex == eFlexible) {
// Find support
iNode[i].findSupport();
// Compute ds
iNode[i].computeDs();
}
}
}
// Compute epsilon
computeEpsilon();
}
// Compute epsilon
void ObjectsClass::computeEpsilon() {
// If universal calculation then need to move all markers into tmp iBody holder
#ifdef UNI_EPSILON
// Temporary iBody for storing all markers in whole simulation
vector<IBMBodyClass> iBodyTmp;
// Call constructor with vector of all iBodies
iBodyTmp.emplace_back(iNode);
// Set pointer to stop copying of data
vector<IBMBodyClass> *iBodyPtr = &iBodyTmp;
#else
// If separated epsilon then just set pointer to point to existing vector
vector<IBMBodyClass> *iBodyPtr = &iBody;
#endif
// Get lattice spacing
double Dx = gPtr->Dx;
// Loop through all bodies and get epsilon
#pragma omp parallel for schedule(guided)
for (size_t ib = 0; ib < (*iBodyPtr).size(); ib++) {
// Do if first time step; if not first time step then only do if flexible
if(gPtr->t == 0 || (*iBodyPtr)[ib].flex == eFlexible) {
// Get size of A matrix
size_t dim = (*iBodyPtr)[ib].node.size();
// Set A matrix
vector<double> A(dim * dim, 0.0);
// Loop through all nodes
for (size_t i = 0; i < dim; i++) {
// Set node i
IBMNodeClass *nodei = (*iBodyPtr)[ib].node[i];
// Loop though all nodes again
for (size_t j = 0; j < dim; j++) {
// Set node j
IBMNodeClass *nodej = (*iBodyPtr)[ib].node[j];
// Now loop through all support markers for node i
for (size_t s = 0; s < nodei->suppCount; s++) {
// Dirac delta value of support marker for node i and support s
double diracVal_i = nodei->supp[s].diracVal;
// Delta value between node i support s and node j
double distX = fabs(nodej->pos[eX] / Dx - nodei->supp[s].idx);
double distY = fabs(nodej->pos[eY] / Dx - nodei->supp[s].jdx);
double diracVal_j = Utils::diracDelta(distX) * Utils::diracDelta(distY);
// Add to A matrix
A[i * dim + j] += diracVal_i * diracVal_j;
}
// Mulitply by volume
A[i * dim + j] *= 1.0 * 1.0 * nodej->ds;
}
}
// Set RHS
vector<double> b(dim, 1.0);
// Solve system
vector<double> epsilon = Utils::solveLAPACK(A, b);
// Set to node values
for (size_t i = 0; i < dim; i++)
(*iBodyPtr)[ib].node[i]->epsilon = epsilon[i];
}
}
// If universal calculation then need to feed them back to iBody vector
#ifdef UNI_EPSILON
// Loop through all bodies and nodes
for (size_t n = 0; n < iNode.size(); n++)
iNode[n].epsilon = (*iBodyPtr)[0].node[n]->epsilon;
#endif
}
// Read in geometry file
void ObjectsClass::geometryReadIn() {
// First check if restart file exists
if (!boost::filesystem::exists("input/geometry.config"))
return;
// Open config file
ifstream file;
file.open("input/geometry.config");
// Handle failure to open
if (!file.is_open())
ERROR("Error opening geometry configuration file...exiting");
// Skip comment lines in config file
streamoff fileOffset;
string line;
file.seekg(ios::beg);
do {
// Get the current position within the file
fileOffset = file.tellg();
// Get the whole line
getline(file, line);
} while (line[0] == '#' && !file.eof());
// Reset file position to the start of the last read line
file.seekg(fileOffset, ios::beg);
// Type of case (the first entry on each line is the keyword describing the body case)
string bodyCase;
// Do a quick scan to see how many bodies there are for reserving memory
int bodyCount = 0, nodeCount = 0;
while (file >> bodyCase) {
// Get number of bodies
int nBodies; file >> nBodies;
// Fast forward to dimensions of body
string dummy;
for (int i = 0; i < 5; i++)
file >> dummy;
// Read in specific values
double dim; file >> dim;
// ** CIRCLE ** //
if (bodyCase == "CIRCLE") {
bodyCount += nBodies;
nodeCount += nBodies * static_cast<int>(floor(2.0 * M_PI * dim / gPtr->Dx));
}
// ** FILAMENT ** //
else if (bodyCase == "FILAMENT") {
bodyCount += nBodies;
nodeCount += nBodies * (static_cast<int>(floor(dim / gPtr->Dx)) + 1);
}
// Skip to end of line
file.ignore(numeric_limits<streamsize>::max(), '\n');
}
// Reserve the space in iBody
iBody.reserve(bodyCount);
iNode.reserve(nodeCount);
// Clear the end of file error within the ifstream
file.clear();
// Reset to start of geometry configurations
file.seekg(fileOffset, ios::beg);
// Start reading in config file
while(file) {
// Get type of body
file >> bodyCase;
// Read in general values first
int number; file >> number;
int ID; file >> ID;
array<double, dims> start; file >> start[eX]; file >> start[eY];
array<double, dims> space; file >> space[eX]; file >> space[eY];
// ** CIRCLE ** //
if (bodyCase == "CIRCLE") {
// Read in specific values
double radius; file >> radius;
// Loop through and build
for (int i = 0; i < number; i++) {
// Get position vector
array<double, dims> pos = {start[eX] + i * space[eX], start[eY] + i * space[eY]};
// Call constructor to build it
iBody.emplace_back(this, ID, pos, radius);
// Increment body ID
ID++;
}
}
// ** FILAMENT ** //
else if (bodyCase == "FILAMENT") {
// Read in specific values
array<double, dims> geom; file >> geom[eX]; file >> geom[eY];
double angle; file >> angle;
string flex; file >> flex;
string nElements; file >> nElements;
string BC; file >> BC;
double rho; file >> rho;
double E; file >> E;
// Loop through and build
for (int i = 0; i < number; i++) {
// Get position vector
array<double, dims> pos = {start[eX] + i * space[eX], start[eY] + i * space[eY]};
// Call constructor to build it
iBody.emplace_back(this, ID, pos, geom, angle, flex, nElements, BC, rho, E);
// Increment body ID
ID++;
}
}
// Set case to none
bodyCase = "NONE";
}
// Check there is no duplicate IDs
for (size_t i = 0; i < iBody.size(); i++) {
for (size_t j = i + 1; j < iBody.size(); j++) {
if (iBody[i].ID == iBody[j].ID)
ERROR("Duplicate body IDs in geometry.config...exiting");
}
}
// Remove overlapping markres
removeOverlapMarkers();
// Set IBM body flag
if (iBody.size() > 0)
hasIBM = true;
// Loop through all bodies
for (size_t ib = 0; ib < iBody.size(); ib++) {
// Set flag
if (iBody[ib].flex == eFlexible)
hasFlex = true;
}
// Print number of bodies
if (hasIBM == true)
cout << "found " << iBody.size() << " object(s)";
else if (hasIBM == false)
cout << "no bodies found";
}
// Write out forces on bodies
void ObjectsClass::writeTotalForces() {
// Only write if there are IBM bodies
if (hasIBM == true) {
// File name
string fname = "Results/TotalForces.out";
// Check if file already exists
bool existing = false;
if (boost::filesystem::exists(fname))
existing = true;
// Open the file
ofstream output;
output.open(fname.c_str(), ios::app);
output.precision(PRECISION);
// Handle failure to open
if (!output.is_open())
ERROR("Error opening forces file...exiting");
// Write out header
if (existing == false)
output << "Timestep\tTime (s)\tFx (N)\tFy (N)\tCx\tCy";
// Get force scaling
double forceScale = gPtr->Dm * gPtr->Dx / SQ(gPtr->Dt) * 1.0 / gPtr->Dx;
// Force vector
array<double, dims> force = {0.0};
// Get total force
for (size_t n = 0; n < iNode.size(); n++) {
for (int d = 0; d < dims; d++) {
force[d] -= iNode[n].force[d] * 1.0 * iNode[n].epsilon * iNode[n].ds * forceScale;
}
}
// Get ND force
double ND = 0.5 * ref_rho * SQ(ref_U) * ref_L;
// Write out
output << endl << gPtr->t << "\t" << gPtr->Dt * gPtr->t << "\t" << force[eX] << "\t" << force[eY] << "\t" << force[eX] / ND << "\t" << force[eY] / ND;
// Close file
output.close();
}
}
// Write out tip positions
void ObjectsClass::writeTips() {
// Only write if there are FEM bodies
if (hasFlex == true) {
// File names
string fnamePos = "Results/TipPositions.out";
string fnameVel = "Results/TipVelocities.out";
// Check if files already exist
bool existingPos = false;
bool existingVel = false;
if (boost::filesystem::exists(fnamePos))
existingPos = true;
if (boost::filesystem::exists(fnameVel))
existingVel = true;
// Open the file
ofstream outputPos, outputVel;
outputPos.open(fnamePos.c_str(), ios::app);
outputVel.open(fnameVel.c_str(), ios::app);
outputPos.precision(PRECISION);
outputVel.precision(PRECISION);
// Handle failure to open
if (!outputPos.is_open() || !outputVel.is_open())
ERROR("Error opening tip positions/velocities files...exiting");
// Write out header
if (existingPos == false)
outputPos << "Timestep\tTime (s)\tTipX\tTipY";
if (existingVel == false)
outputVel << "Timestep\tTime (s)\tTipX\tTipY";
// Write out
outputPos << endl << gPtr->t << "\t" << gPtr->Dt * gPtr->t;
outputVel << endl << gPtr->t << "\t" << gPtr->Dt * gPtr->t;
// Now loop through all flexible bodies
for (size_t ib = 0; ib < iBody.size(); ib++) {
// Only do if flexible
if (iBody[ib].flex == eFlexible) {
outputPos << "\t" << iBody[ib].node[iBody[ib].node.size()-1]->pos[eX] << "\t" << iBody[ib].node[iBody[ib].node.size()-1]->pos[eY];
outputVel << "\t" << iBody[ib].node[iBody[ib].node.size()-1]->vel[eX] << "\t" << iBody[ib].node[iBody[ib].node.size()-1]->vel[eY];
}
}
// Close file
outputPos.close();
outputVel.close();
}
}
// Write info data at tInfo frequency
void ObjectsClass::writeInfo() {
// Only write if there are FEM bodies
if (hasFlex == true) {
// Average values
int count = 0;
int aveIt = 0;
double aveRes = 0.0;
double aveDisp = 0.0;
array<array<double, dims>, dims> T;
array<double, dims> deflectVector;
// Loop through all FEM bodies and get average iterations, residual and deflection
for (size_t ib = 0; ib < iBody.size(); ib++) {
// Only do if body is flexible
if (iBody[ib].flex == eFlexible) {
// Increment count
count++;
// Sum to get average FEM loop parameters
aveIt += iBody[ib].sBody->itNR;
aveRes += iBody[ib].sBody->resNR;
// Get rotation matrix
T = Utils::getRotationMatrix(iBody[ib].sBody->angle0);
// Get deflection vector and rotate into local coordinates
int idx = iBody[ib].sBody->bodyDOFs - nodeDOFs;
deflectVector = {iBody[ib].sBody->U[idx], iBody[ib].sBody->U[idx+1]};
deflectVector = Utils::Transpose(T) * deflectVector;
// Sum to get average displacement
aveDisp -= deflectVector[eY] / iBody[ib].sBody->L0;
}
}
// Get average
aveIt /= count;
aveRes /= static_cast<double>(count);
aveDisp /= static_cast<double>(count);
// Write out sub iterations
cout << endl;
cout << "Current relaxation factor = " << relax << endl;
cout << "Subiterations taking " << subIt << " iterations to reach a residual of " << subRes << endl;
// Write out average values
cout << "FEM taking " << aveIt << " iterations to reach a residual of " << aveRes << " on average" << endl;
cout << setprecision(2) << "Average tip deflection = " << 100.0 * aveDisp << " (% of L)";
}
}
// Write info data at tInfo frequency
void ObjectsClass::writeLog() {
// Only write if we have IBM bodies
if (hasIBM == true) {
// Test to see if over tCrit is met
bool tCritTest = false;
// Create stream for output to stdout and file
Utils::io_ofstream output("Results/Log.out", Utils::io_ofstream::app);
// Loop through all bodies
for (size_t ib = 0; ib < iBody.size(); ib++) {
// BODY HEADER
output << "\n\nBODY " << iBody[ib].ID;
// Write out body type
if (iBody[ib].bodyType == eCircle)
output << " (CIRCLE):\n";
else if (iBody[ib].bodyType == eFilament)
output << " (FILAMENT):\n";
// Write out number of nodes
output << "IBM Nodes = " << iBody[ib].node.size() << "\n";
// Write out flexible type
if (iBody[ib].flex == eFlexible)
output << "FlexType = FLEXIBLE";
if (iBody[ib].flex == eRigid)
output << "FlexType = RIGID";
// If flexible then write out some more information
if (iBody[ib].flex == eFlexible) {
// Write out number of elements
output << "\n";
output << "Number of elements = " << iBody[ib].sBody->element.size() << "\n";
output << "Density (kg/m^3) = " << iBody[ib].sBody->element[0].rho << "\n";
output << "Young Modulus (Pa) = " << iBody[ib].sBody->element[0].E << "\n";
output << "tCrit (s) = " << iBody[ib].sBody->tCrit;
// Do a check to see if tCrit has been met
if (iBody[ib].sBody->tCrit < gPtr->Dt)
tCritTest = true;
}
}
// If tCrit has been met then write warning
if (tCritTest == true)
WARN("SOME TCRITS ARE SMALLER THAN TIMESTEP");
// Close
output.close();
}
}
// Write VTK (IBM or FEM)
void ObjectsClass::writeVTK(bool writeIBM) {
// Only write if we have IBM/FEM bodies to write
if ((writeIBM && hasIBM == true) || (!writeIBM && hasFlex == true)) {
// Get the endianness
string endianStr = (gPtr->bigEndian ? "BigEndian" : "LittleEndian");
// Create file
string fStr = (writeIBM ? "IBM" : "FEM");
ofstream output;
output.open("Results/VTK/" + fStr + "." + to_string(gPtr->t) + ".vtp", ios::binary);
// Handle failure to open
if (!output.is_open())
ERROR("Error opening body VTK file...exiting");
// Write XML header
output << "<?xml version=\"1.0\"?>\n";
// Begin VTK file
int level = 0;
output << "<VTKFile type=\"PolyData\" version=\"1.0\" byte_order=\"" << endianStr << "\" header_type=\"UInt64\">\n";
// New level -> PolyData
level = 1;
output << string(level, '\t') << "<PolyData>\n";
// Now loop through each IBM body
unsigned long long offset = 0;
for (size_t ib = 0; ib < iBody.size(); ib++) {
// If FEM then only write flexible bodies
if (writeIBM || (!writeIBM && iBody[ib].flex == eFlexible)) {
// Get number of nodes and lines
size_t nNodes = (writeIBM ? iBody[ib].node.size() : iBody[ib].sBody->node.size());
size_t nLines = (iBody[ib].bodyType == eCircle ? nNodes : nNodes - 1);
// New level -> Piece
level = 2;
output << string(level, '\t') << "<Piece "
<< "NumberOfPoints=\"" << nNodes << "\" "
<< "NumberOfVerts=\"" << 0 << "\" "
<< "NumberOfLines=\"" << nLines << "\" "
<< "NumberOfStrips=\"" << 0 << "\" "
<< "NumberOfPolys=\"" << 0 << "\">\n";
// New level -> Points
level = 3;
output << string(level, '\t') << "<Points>\n";
// New level -> Points data (increment offset)
level = 4;
output << string(level, '\t') << "<DataArray type=\"Float64\" Name=\"Points\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset << "\"/>\n";
offset += 3 * nNodes * sizeof(double) + sizeof(unsigned long long);
// Back level -> Points
level = 3;
output << string(level, '\t') << "</Points>\n";
// New level -> Lines
level = 3;
output << string(level, '\t') << "<Lines>\n";
// New level -> connectivity and offsets
level = 4;
output << string(level, '\t') << "<DataArray type=\"Int64\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset << "\"/>\n";
offset += 2 * nLines * sizeof(long long) + sizeof(unsigned long long);
output << string(level, '\t') << "<DataArray type=\"Int64\" Name=\"offsets\" format=\"appended\" offset=\"" << offset << "\"/>\n";
offset += nLines * sizeof(long long) + sizeof(unsigned long long);
// Back level -> Lines
level = 3;
output << string(level, '\t') << "</Lines>\n";
// Back level -> Piece
level = 2;
output << string(level, '\t') << "</Piece>\n";
}
}
// Back level -> PolyData
level = 1;
output << string(level, '\t') << "</PolyData>\n";
// New level -> AppendedData
level = 1;
output << string(level, '\t') << "<AppendedData encoding=\"raw\">\n";
// New level -> Raw data
level = 2;
output << string(level, '\t') << "_";
// Now loop through each IBM body
for (size_t ib = 0; ib < iBody.size(); ib++) {
// If FEM then only write flexible bodies
if (writeIBM || (!writeIBM && iBody[ib].flex == eFlexible)) {
// Get number of nodes and lines
size_t nNodes = (writeIBM ? iBody[ib].node.size() : iBody[ib].sBody->node.size());
size_t nLines = (iBody[ib].bodyType == eCircle ? nNodes : nNodes - 1);
// Positions
unsigned long long size = 3 * nNodes * sizeof(double);
output.write((char*)&size, sizeof(unsigned long long));
for (size_t n = 0; n < nNodes; n++) {
double posX = (writeIBM ? iBody[ib].node[n]->pos[eX] : iBody[ib].sBody->node[n].pos[eX]);
double posY = (writeIBM ? iBody[ib].node[n]->pos[eY] : iBody[ib].sBody->node[n].pos[eY]);
double posZ = 0.0;
output.write((char*)&posX, sizeof(double));
output.write((char*)&posY, sizeof(double));
output.write((char*)&posZ, sizeof(double));
}
// Connectivity
size = 2 * nLines * sizeof(long long);
output.write((char*)&size, sizeof(unsigned long long));
for (size_t n = 0; n < nLines; n++) {
long long node1 = n;
long long node2 = (n + 1) % nNodes;
output.write((char*)&node1, sizeof(long long));
output.write((char*)&node2, sizeof(long long));
}
// Offsets
size = nLines * sizeof(long long);
output.write((char*)&size, sizeof(unsigned long long));
for (size_t n = 0; n < nLines; n++) {
long long offsets = 2 * (n + 1);
output.write((char*)&offsets, sizeof(long long));
}
}
}
// Back level -> AppendedData
level = 1;
output << "\n" << string(level, '\t') << "</AppendedData>\n";
// Back level -> VTKFile
level = 0;
output << string(level, '\t') << "</VTKFile>\n";
// Close file
output.close();
// If FEM writing on then write
#ifdef VTK_FEM
if(writeIBM)
writeVTK(false);
#endif
}
}
// Remove markers that are too close to each other
void ObjectsClass::removeOverlapMarkers() {
// IDs of nodes to erase
vector<int> eraseID;
// Loop through all IBM bodies and nodes
for (size_t n1 = 0; n1 < iNode.size(); n1++) {
// Loop through all nodes ahead in the array
for (size_t n2 = n1 + 1; n2 < iNode.size(); n2++) {
// Get distance between nodes
double mag = sqrt((iNode[n1].pos - iNode[n2].pos) * (iNode[n1].pos - iNode[n2].pos)) / gPtr->Dx;
// If distance is smaller than 0.5Dx then delete
if (mag < 0.5) {
// If both bodies are flexible then error
if ((iNode[n1].iPtr->flex == eFlexible) && (iNode[n2].iPtr->flex == eFlexible))
ERROR("Cannot place two flexible bodies so close to each other...exiting");
// If body1 is flex and body2 is rigid then remove from body2
if ((iNode[n1].iPtr->flex == eFlexible) && (iNode[n2].iPtr->flex == eRigid))
eraseID.push_back(iNode[n2].ID);
// If body1 is rigid and body2 is flex then remove from body1
if ((iNode[n1].iPtr->flex == eRigid) && (iNode[n2].iPtr->flex == eFlexible))
eraseID.push_back(iNode[n1].ID);
// If both bodies are rigid then remove from body1 (there is probably a more elegant way to choose)
if ((iNode[n1].iPtr->flex == eRigid) && (iNode[n2].iPtr->flex == eRigid))
eraseID.push_back(iNode[n1].ID);
}
}
}
// Now loop through and delete
for (size_t i = 0; i < eraseID.size(); i++) {
// First delete pointer stored in iBody
bool foundMatch = false;
for (size_t ib = 0; ib < iBody.size(); ib++) {
for (size_t n = 0; n < iBody[ib].node.size(); n++) {
// Check ID
if (iBody[ib].node[n]->ID == eraseID[i]) {
iBody[ib].node.erase(iBody[ib].node.begin() + n);
foundMatch = true;
}
// Move rest of pointers back
if (foundMatch)
iBody[ib].node[n]--;
}
}
// Now delete the actual node
for (size_t n = 0; n < iNode.size(); n++) {
// Check ID
if (iNode[n].ID == eraseID[i]) {
iNode.erase(iNode.begin() + n);
break;
}
}
}
// Now reset the IDs of all nodes
int ID = 0;
for (size_t n = 0; n < iNode.size(); n++)
iNode[n].ID = ID++;
}
// Initialise objects
void ObjectsClass::initialiseObjects() {
// Call static FEM to give it an initial deflection
#ifdef INITIAL_DEFLECT
if (hasFlex == true)
initialDeflect();
#endif
// Loop through all nodes
for (size_t n = 0; n < iNode.size(); n++) {
// Find support
iNode[n].findSupport();
// Compute ds
iNode[n].computeDs();
}
// Compute epsilon
computeEpsilon();
}
// Call static FEM to give initial deflection
void ObjectsClass::initialDeflect() {
// Starting main algorithm
cout << endl << endl << endl << "*** INITIALISING DEFLECTIONS ***" << endl;
// Loop through all bodies
for (size_t ib = 0; ib < iBody.size(); ib++) {
// Only do if flexible
if (iBody[ib].flex == eFlexible)
iBody[ib].sBody->setInitialDeflection();
}
}
// Read in restart file
void ObjectsClass::readRestart() {
// ** IBM FILE ** //
if (boost::filesystem::exists("Results/Restart/IBM.restart")) {
// Get flag for endianess
bool bigEndian = gPtr->bigEndian;
// Open file
ifstream file;
file.open("Results/Restart/IBM.restart", ios::binary);
// Handle failure to open
if (!file.is_open())
ERROR("Error opening IBM.restart file...exiting");
// Read in number of IBM bodies
size_t nIBMRead;
file.read((char*)&nIBMRead, sizeof(size_t));
size_t nIBMSwap = (bigEndian ? Utils::swapEnd(nIBMRead) : nIBMRead);
// Loop through lines in IBM.restart file
for (size_t i = 0; i < nIBMSwap; i++) {
// Read in body ID and number of nodes
int idRead;
size_t nodeSizeRead;
file.read((char*)&idRead, sizeof(int));
file.read((char*)&nodeSizeRead, sizeof(size_t));
// Swap byte order if bigEndian
int idSwap = (bigEndian ? Utils::swapEnd(idRead) : idRead);
size_t nodeSizeSwap = (bigEndian ? Utils::swapEnd(nodeSizeRead) : nodeSizeRead);
// Check to make sure it exists in this run
int ib = getBodyIdxFromID(idSwap);
// If it doesn't exist then skip the rest of the data for this body
if (ib < 0) {
size_t shift = (6 * sizeof(double) * nodeSizeSwap);
file.seekg (shift, ios::cur);
continue;
}
// Check to make sure number of nodes match up
if (nodeSizeSwap != iBody[ib].node.size())
ERROR("Number of nodes in IBM.restart do not match existing number of nodes...exiting");
// Read in rest of the line
for (size_t n = 0; n < nodeSizeSwap; n++) {
// Read in positions and velocities
double posxRead, posyRead, velxRead, velyRead, forcexRead, forceyRead;
file.read((char*)&posxRead, sizeof(double));
file.read((char*)&posyRead, sizeof(double));
file.read((char*)&velxRead, sizeof(double));
file.read((char*)&velyRead, sizeof(double));
file.read((char*)&forcexRead, sizeof(double));
file.read((char*)&forceyRead, sizeof(double));
// Swap byte order if bigEndian
iBody[ib].node[n]->pos[eX] = (bigEndian ? Utils::swapEnd(posxRead) : posxRead);
iBody[ib].node[n]->pos[eY] = (bigEndian ? Utils::swapEnd(posyRead) : posyRead);
iBody[ib].node[n]->vel[eX] = (bigEndian ? Utils::swapEnd(velxRead) : velxRead);
iBody[ib].node[n]->vel[eY] = (bigEndian ? Utils::swapEnd(velyRead) : velyRead);
iBody[ib].node[n]->force[eX] = (bigEndian ? Utils::swapEnd(forcexRead) : forcexRead);
iBody[ib].node[n]->force[eY] = (bigEndian ? Utils::swapEnd(forceyRead) : forceyRead);
}
}
}
// ** FEM FILE ** //
if (boost::filesystem::exists("Results/Restart/FEM.restart")) {
// Get flag for endianess
bool bigEndian = gPtr->bigEndian;
// Open file
ifstream file;
file.open("Results/Restart/FEM.restart", ios::binary);
// Handle failure to open
if (!file.is_open())
ERROR("Error opening FEM.restart file...exiting");
// Read in body ID and number of nodes
int nFEMRead;
double relaxRead;
file.read((char*)&nFEMRead, sizeof(int));
file.read((char*)&relaxRead, sizeof(double));
// Swap byte order if bigEndian
int nFEMSwap = (bigEndian ? Utils::swapEnd(nFEMRead) : nFEMRead);
relax = (bigEndian ? Utils::swapEnd(relaxRead) : relaxRead);
// Loop through lines in FEM.restart file
for (int i = 0; i < nFEMSwap; i++) {
// Read in body ID and number of nodes
int idRead;
size_t elSizeRead, nodeSizeRead;
file.read((char*)&idRead, sizeof(int));
file.read((char*)&elSizeRead, sizeof(size_t));
file.read((char*)&nodeSizeRead, sizeof(size_t));
// Swap byte order if bigEndian
int idSwap = (bigEndian ? Utils::swapEnd(idRead) : idRead);
size_t elSizeSwap = (bigEndian ? Utils::swapEnd(elSizeRead) : elSizeRead);
size_t nodeSizeSwap = (bigEndian ? Utils::swapEnd(nodeSizeRead) : nodeSizeRead);
// Check to make sure it exists in this run
int ib = getBodyIdxFromID(idSwap);
// If it doesn't exist or if it is now rigid then skip this line
if (ib < 0 || iBody[ib].flex == eRigid) {
size_t shift = (6 * sizeof(double) * nodeSizeSwap * nodeDOFs + 2 * sizeof(double) * elSizeSwap + 6 * sizeof(double) * nodeSizeSwap);
file.seekg (shift, ios::cur);
continue;
}
// Check to make sure number of nodes match up
if (elSizeSwap != iBody[ib].sBody->element.size() || nodeSizeSwap != iBody[ib].sBody->node.size())
ERROR("Number of nodes/elements in FEM.restart do not match existing number of nodes/elements...exiting");
// Read in U
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valRead;
file.read((char*)&valRead, sizeof(double));
iBody[ib].sBody->U[i] = (bigEndian ? Utils::swapEnd(valRead) : valRead);
}
// Read in Udot
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valRead;
file.read((char*)&valRead, sizeof(double));
iBody[ib].sBody->Udot[i] = (bigEndian ? Utils::swapEnd(valRead) : valRead);
}
// Read in Udotdot
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valRead;
file.read((char*)&valRead, sizeof(double));
iBody[ib].sBody->Udotdot[i] = (bigEndian ? Utils::swapEnd(valRead) : valRead);
}
// Read in U_n
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valRead;
file.read((char*)&valRead, sizeof(double));
iBody[ib].sBody->U_n[i] = (bigEndian ? Utils::swapEnd(valRead) : valRead);
}
// Read in U_nm1
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valRead;
file.read((char*)&valRead, sizeof(double));
iBody[ib].sBody->U_nm1[i] = (bigEndian ? Utils::swapEnd(valRead) : valRead);
}
// Read in R_k
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valRead;
file.read((char*)&valRead, sizeof(double));
iBody[ib].sBody->R_k[i] = (bigEndian ? Utils::swapEnd(valRead) : valRead);
}
// Read in elements
for (size_t el = 0; el < elSizeSwap; el++) {
double lengthRead, angleRead;
file.read((char*)&lengthRead, sizeof(double));
file.read((char*)&angleRead, sizeof(double));
iBody[ib].sBody->element[el].L = (bigEndian ? Utils::swapEnd(lengthRead) : lengthRead);
iBody[ib].sBody->element[el].angle = (bigEndian ? Utils::swapEnd(angleRead) : angleRead);
}
// Read in nodes
for (size_t n = 0; n < nodeSizeSwap; n++) {
double pos0xRead, pos0yRead, posxRead, posyRead, angle0Read, angleRead;
file.read((char*)&pos0xRead, sizeof(double));
file.read((char*)&pos0yRead, sizeof(double));
file.read((char*)&posxRead, sizeof(double));
file.read((char*)&posyRead, sizeof(double));
file.read((char*)&angle0Read, sizeof(double));
file.read((char*)&angleRead, sizeof(double));
iBody[ib].sBody->node[n].pos0[eX] = (bigEndian ? Utils::swapEnd(pos0xRead) : pos0xRead);
iBody[ib].sBody->node[n].pos0[eY] = (bigEndian ? Utils::swapEnd(pos0yRead) : pos0yRead);
iBody[ib].sBody->node[n].pos[eX] = (bigEndian ? Utils::swapEnd(posxRead) : posxRead);
iBody[ib].sBody->node[n].pos[eY] = (bigEndian ? Utils::swapEnd(posyRead) : posyRead);
iBody[ib].sBody->node[n].angle0 = (bigEndian ? Utils::swapEnd(angle0Read) : angle0Read);
iBody[ib].sBody->node[n].angle = (bigEndian ? Utils::swapEnd(angleRead) : angleRead);
}
}
}
// Loop through all nodes
for (size_t n = 0; n < iNode.size(); n++) {
// Find support
iNode[n].findSupport();
// Compute ds
iNode[n].computeDs();
}
// Compute epsilon
if (hasIBM)
computeEpsilon();
// If flexible then recalculate FEM values too
for (size_t ib = 0; ib < iBody.size(); ib++) {
if (iBody[ib].flex == eFlexible) {
// Loop through elements
for (size_t el = 0; el < iBody[ib].sBody->element.size(); el++) {
// Recalculate values
iBody[ib].sBody->element[el].setElementTransform();
iBody[ib].sBody->element[el].setLocalMatrices();
}
}
}
// Clean up files from previous runs
restartCleanup();
}
// Write out restart file
void ObjectsClass::writeRestart() {
// ** IBM FILE ** //
if (hasIBM == true) {
// Get flag for endianess
bool bigEndian = gPtr->bigEndian;
// Open file
ofstream outputIBM;
outputIBM.open("Results/Restart/IBM.restart.temp", ios::binary);
// Handle failure to open
if (!outputIBM.is_open())
ERROR("Error opening IBM.restart.temp file...exiting");
// Swap byte order if bigEndian
size_t ibSizeWrite = (bigEndian ? Utils::swapEnd(iBody.size()) : iBody.size());
// Write out number of bodies
outputIBM.write((char*)&ibSizeWrite, sizeof(size_t));
// Loop through IBM bodies
for (size_t ib = 0; ib < iBody.size(); ib++) {
// Swap byte order if bigEndian
int idWrite = (bigEndian ? Utils::swapEnd(iBody[ib].ID) : iBody[ib].ID);
size_t nodeSizeWrite = (bigEndian ? Utils::swapEnd(iBody[ib].node.size()) : iBody[ib].node.size());
// Write out body ID and node
outputIBM.write((char*)&idWrite, sizeof(int));
outputIBM.write((char*)&nodeSizeWrite, sizeof(size_t));
// Loop through nodes and write out ID, pos, pos0, vel
for (size_t n = 0; n < iBody[ib].node.size(); n++) {
// Swap byte order if bigEndian
double posxWrite = (bigEndian ? Utils::swapEnd(iBody[ib].node[n]->pos[eX]) : iBody[ib].node[n]->pos[eX]);
double posyWrite = (bigEndian ? Utils::swapEnd(iBody[ib].node[n]->pos[eY]) : iBody[ib].node[n]->pos[eY]);
double velxWrite = (bigEndian ? Utils::swapEnd(iBody[ib].node[n]->vel[eX]) : iBody[ib].node[n]->vel[eX]);
double velyWrite = (bigEndian ? Utils::swapEnd(iBody[ib].node[n]->vel[eY]) : iBody[ib].node[n]->vel[eY]);
double forcexWrite = (bigEndian ? Utils::swapEnd(iBody[ib].node[n]->force[eX]) : iBody[ib].node[n]->force[eX]);
double forceyWrite = (bigEndian ? Utils::swapEnd(iBody[ib].node[n]->force[eY]) : iBody[ib].node[n]->force[eY]);
// Write out number of bodies
outputIBM.write((char*)&posxWrite, sizeof(double));
outputIBM.write((char*)&posyWrite, sizeof(double));
outputIBM.write((char*)&velxWrite, sizeof(double));
outputIBM.write((char*)&velyWrite, sizeof(double));
outputIBM.write((char*)&forcexWrite, sizeof(double));
outputIBM.write((char*)&forceyWrite, sizeof(double));
}
}
// Close file
outputIBM.close();
// Now rename the temp file
boost::filesystem::rename("Results/Restart/IBM.restart.temp", "Results/Restart/IBM.restart");
}
// ** FEM FILE ** //
if (hasFlex == true) {
// Get flag for endianess
bool bigEndian = gPtr->bigEndian;
// Open file
ofstream outputFEM;
outputFEM.open("Results/Restart/FEM.restart.temp", ios::binary);
// Handle failure to open
if (!outputFEM.is_open())
ERROR("Error opening FEM.restart.temp file...exiting");
// Swap byte order if bigEndian
int flexWrite = (bigEndian ? Utils::swapEnd(nFlex) : nFlex);
double relaxWrite = (bigEndian ? Utils::swapEnd(relax) : relax);
// Write out global information
outputFEM.write((char*)&flexWrite, sizeof(int));
outputFEM.write((char*)&relaxWrite, sizeof(double));
// Loop through IBM bodies
for (size_t ib = 0; ib < iBody.size(); ib++) {
if (iBody[ib].flex == eFlexible) {
// Swap byte order if bigEndian
int idWrite = (bigEndian ? Utils::swapEnd(iBody[ib].ID) : iBody[ib].ID);
size_t elSizeWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->element.size()) : iBody[ib].sBody->element.size());
size_t nodeSizeWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->node.size()) : iBody[ib].sBody->node.size());
// Write out body ID and node
outputFEM.write((char*)&idWrite, sizeof(int));
outputFEM.write((char*)&elSizeWrite, sizeof(size_t));
outputFEM.write((char*)&nodeSizeWrite, sizeof(size_t));
// Write out U
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->U[i]) : iBody[ib].sBody->U[i]);
outputFEM.write((char*)&valWrite, sizeof(double));
}
// Write out Udot
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->Udot[i]) : iBody[ib].sBody->Udot[i]);
outputFEM.write((char*)&valWrite, sizeof(double));
}
// Write out Udotdot
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->Udotdot[i]) : iBody[ib].sBody->Udotdot[i]);
outputFEM.write((char*)&valWrite, sizeof(double));
}
// Write out U_n
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->U_n[i]) : iBody[ib].sBody->U_n[i]);
outputFEM.write((char*)&valWrite, sizeof(double));
}
// Write out U_nm1
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->U_nm1[i]) : iBody[ib].sBody->U_nm1[i]);
outputFEM.write((char*)&valWrite, sizeof(double));
}
// Write out R_k
for (int i = 0; i < iBody[ib].sBody->bodyDOFs; i++) {
double valWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->R_k[i]) : iBody[ib].sBody->R_k[i]);
outputFEM.write((char*)&valWrite, sizeof(double));
}
// Write out elements
for (size_t el = 0; el < iBody[ib].sBody->element.size(); el++) {
double lengthWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->element[el].L) : iBody[ib].sBody->element[el].L);
double angleWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->element[el].angle) : iBody[ib].sBody->element[el].angle);
outputFEM.write((char*)&lengthWrite, sizeof(double));
outputFEM.write((char*)&angleWrite, sizeof(double));
}
// Write out nodes
for (size_t n = 0; n < iBody[ib].sBody->node.size(); n++) {
double pos0xWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->node[n].pos0[eX]) : iBody[ib].sBody->node[n].pos0[eX]);
double pos0yWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->node[n].pos0[eY]) : iBody[ib].sBody->node[n].pos0[eY]);
double posxWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->node[n].pos[eX]) : iBody[ib].sBody->node[n].pos[eX]);
double posyWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->node[n].pos[eY]) : iBody[ib].sBody->node[n].pos[eY]);
double angle0Write = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->node[n].angle0) : iBody[ib].sBody->node[n].angle0);
double angleWrite = (bigEndian ? Utils::swapEnd(iBody[ib].sBody->node[n].angle) : iBody[ib].sBody->node[n].angle);
outputFEM.write((char*)&pos0xWrite, sizeof(double));
outputFEM.write((char*)&pos0yWrite, sizeof(double));
outputFEM.write((char*)&posxWrite, sizeof(double));
outputFEM.write((char*)&posyWrite, sizeof(double));
outputFEM.write((char*)&angle0Write, sizeof(double));
outputFEM.write((char*)&angleWrite, sizeof(double));
}
}
}
// Close file
outputFEM.close();
// Now rename the temp file
boost::filesystem::rename("Results/Restart/FEM.restart.temp", "Results/Restart/FEM.restart");
}
}
// Get body index from the ID
int ObjectsClass::getBodyIdxFromID(int id) {
// Loop through all bodies
for (size_t i = 0; i < iBody.size(); i++) {
if (iBody[i].ID == id)
return static_cast<int>(i);
}
// If we get here then it doesn't exist
return -1;
}
// Clean up files from previous simulations before restart
void ObjectsClass::restartCleanup() {
// If there are fluid VTKs with no corresponding body VTK then write some empty ones
fillEmptyVTK();
// Sort out tips/forces
deleteTipsAndForces();
// If this part of simulation has no IBM or FEM then get rid of their old restart files
if (!hasIBM && boost::filesystem::exists("Results/Restart/IBM.restart")) {
if(!boost::filesystem::remove("Results/Restart/IBM.restart"))
ERROR("Problem removing IBM.restart...exiting");;
}
if (!hasFlex && boost::filesystem::exists("Results/Restart/FEM.restart")) {
if(!boost::filesystem::remove("Results/Restart/FEM.restart"))
ERROR("Problem removing FEM.restart...exiting");;
}
}
// Fill in empty VTK files
void ObjectsClass::fillEmptyVTK() {
// Only write if we have IBM bodies
if (hasIBM == true) {
// Results path
string path = "Results/VTK";
// Check if it exists
if (boost::filesystem::exists(path)) {
// Extract string
string rmStr = "Fluid.";
string exStrGrid = ".vti";
string exStrBody = ".vtp";
// Get directory iterator
boost::filesystem::directory_iterator endit;
// Loop through all fluid vtk files
for (boost::filesystem::directory_iterator it(path); it != endit; it++) {
// Get string
string fStr = it->path().stem().string();
// Check to make sure it is a fluid VTK file
if (fStr.find(rmStr) != string::npos && it->path().extension() == exStrGrid) {
// Get time step
string tStep = fStr.substr(rmStr.size(), fStr.size());
// Create fname string
string fname = path + "/IBM." + tStep + exStrBody;
// Check if file exists
if (!boost::filesystem::exists(fname))
writeEmptyVTK(fname);
// If writing FEM we need to do the same for them as well
#ifdef VTK_FEM
// Create fname string
fname = path + "/FEM." + tStep + exStrBody;
// Check if file exists
if (!boost::filesystem::exists(fname) && hasFlex == true)
writeEmptyVTK(fname);
#endif
}
}
}
}
}
// Write empty VTK polydata
void ObjectsClass::writeEmptyVTK(string &fname) {
// Get the endianness
string endianStr = (gPtr->bigEndian ? "BigEndian" : "LittleEndian");
// Create file
ofstream output;
output.open(fname, ios::binary);
// Handle failure to open
if (!output.is_open())
ERROR("Error opening body VTK file...exiting");
// Write XML header
output << "<?xml version=\"1.0\"?>\n";
// Begin VTK file
int level = 0;
output << "<VTKFile type=\"PolyData\" version=\"1.0\" byte_order=\"" << endianStr << "\" header_type=\"UInt64\">\n";
// New level -> PolyData
level = 1;
output << string(level, '\t') << "<PolyData>\n";
// New level -> Piece
level = 2;
output << string(level, '\t') << "<Piece "
<< "NumberOfPoints=\"" << 0 << "\" "
<< "NumberOfVerts=\"" << 0 << "\" "
<< "NumberOfLines=\"" << 0 << "\" "
<< "NumberOfStrips=\"" << 0 << "\" "
<< "NumberOfPolys=\"" << 0 << "\">\n";
// Back level -> Piece
level = 2;
output << string(level, '\t') << "</Piece>\n";
// Back level -> PolyData
level = 1;
output << string(level, '\t') << "</PolyData>\n";
// Back level -> VTKFile
level = 0;
output << string(level, '\t') << "</VTKFile>\n";
// Close file
output.close();
}
// Delete the tip and force data that was written after last restart
void ObjectsClass::deleteTipsAndForces() {
// Delete the tip positions that were written after last restart
deleteFileOutput("Results/TipPositions.out");
// Delete the tip velocities that were written after last restart
deleteFileOutput("Results/TipVelocities.out");
// Delete the forces that were written after last restart
deleteFileOutput("Results/TotalForces.out");
}
// Delete data from output files that were written after last restart
void ObjectsClass::deleteFileOutput(string fname) {
// Check file exists
if (boost::filesystem::exists(fname)) {
// Set vector
vector<string> fileStr;
// Open file
ifstream file;
file.open(fname);
// Handle failure to open
if (!file.is_open())
ERROR("Error opening file for deleting future tips/forces...exiting");
// String for holding the line
string lineStr;
// Get the header
getline(file, lineStr);
fileStr.push_back(lineStr);
// Loop through each line in file
while (getline(file, lineStr)) {
// Get the timestep
int tStep = stoi(lineStr);
// If tStep is bigger than gPtr->t then break
if (tStep >= gPtr->t)
break;
// Else we add the string to the vector
fileStr.push_back(lineStr);
}
// File name
string fout = "Results/Output.temp";
// Open the file
ofstream output;
output.open(fout.c_str());
// Handle failure to open
if (!output.is_open())
ERROR("Error opening temporary output file...exiting");
// Write out header
output << fileStr[0];
// Loop through and write out
for (size_t i = 1; i < fileStr.size(); i++)
output << endl << fileStr[i];
// Close file
output.close();
// Now rename the temp file
boost::filesystem::rename(fout, fname);
}
}
// Custom constructor
ObjectsClass::ObjectsClass(GridClass &g) {
// Write out header
cout << endl << endl << "Initialising objects...";
// Set pointers
gPtr = &g;
gPtr->oPtr = this;
// Initial sub iteration members
subIt = 0;
subRes = 0.0;
relax = relaxMax;
subNum = 0.0;
subDen = 0.0;
// Set flag to false initially
hasIBM = false;
hasFlex = false;
// Read in geometry file
geometryReadIn();
// Initialise objects
if (hasIBM)
initialiseObjects();
// Get numer of FEM DOFs in whole simulation
nFlex = simDOFs = 0;
for (size_t ib = 0; ib < iBody.size(); ib++) {
if (iBody[ib].flex == eFlexible) {
nFlex++;
simDOFs += iBody[ib].sBody->bodyDOFs;
}
}
}
| 47,154
|
C++
|
.cpp
| 1,254
| 33.791069
| 160
| 0.648825
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,160
|
Utils.cpp
|
joconnor22_LIFE/src/Utils.cpp
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
// Includes
#include "../inc/Utils.h"
#include "../inc/Grid.h"
#include "../inc/Objects.h"
// Write header at start of run
void Utils::writeHeader() {
// Write out version number and release date
cout << endl << "*** LIFE " << version << " (" << date << ") ***" << endl << endl;
// Write out license header
cout << "LIFE: Lattice boltzmann-Immersed boundary-Finite Element" << endl;
cout << "Copyright (C) 2019 Joseph O'Connor" << endl << endl;
cout << "This program is free software: you can redistribute it and/or modify" << endl;
cout << "it under the terms of the GNU General Public License as published by" << endl;
cout << "the Free Software Foundation, either version 3 of the License, or" << endl;
cout << "(at your option) any later version." << endl << endl;
cout << "This program is distributed in the hope that it will be useful," << endl;
cout << "but WITHOUT ANY WARRANTY; without even the implied warranty of" << endl;
cout << "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" << endl;
cout << "GNU General Public License for more details." << endl << endl;
cout << "You should have received a copy of the GNU General Public License" << endl;
cout << "along with this program. If not, see <http://www.gnu.org/licenses/>." << endl;
}
// Create directories at start
bool Utils::createDirectories() {
// First check if restart file exists
if (boost::filesystem::exists("Results/Restart/Fluid.restart"))
return true;
// Remove directories
if (boost::filesystem::exists("Results")) {
if (!boost::filesystem::remove_all("Results"))
ERROR("Problem removing results directory...exiting");
}
// Create results directory
if (!boost::filesystem::create_directory("Results"))
ERROR("Problem creating results directory...exiting");
// Create VTK directory
#ifdef VTK
if (!boost::filesystem::create_directory("Results/VTK"))
ERROR("Problem creating vtk directory...exiting");
#endif
// Only create restart directory if we need to
if (tRestart > 0) {
if (!boost::filesystem::create_directory("Results/Restart"))
ERROR("Problem creating restart directory...exiting");
}
// If we make it here then this is not a restart case
return false;
}
// Read in restart file
void Utils::readRestart(GridClass &grid) {
// Starting main algorithm
cout << endl << endl << endl << "*** READ IN RESTART DATA ***";
// Reading in restart files
cout << endl << endl << "Reading in restart files...";
// Read grid restart data
grid.readRestart();
// Read bodies restart data
grid.oPtr->readRestart();
// Delete VTK files that were written after last restart written
Utils::deleteVTKs(grid);
// Write out header
cout << "finished";
}
// Write out restart file
void Utils::writeRestart(GridClass &grid) {
// Wrting restart files
cout << endl << "Writing restart data...";
// Write grid info
grid.writeRestart();
// Write IBM info
grid.oPtr->writeRestart();
// Write header
cout << "finished";
}
// Write info
void Utils::writeInfo(GridClass &grid) {
// Write grid info
grid.writeInfo();
// Write IBM info
grid.oPtr->writeInfo();
// Write out forces on bodies
#ifdef FORCES
grid.oPtr->writeTotalForces();
#endif
// Write out forces on bodies
#ifdef TIPS
grid.oPtr->writeTips();
#endif
}
// Write log
void Utils::writeLog(GridClass &grid) {
// Write grid info
grid.writeLog();
// Write IBM info
grid.oPtr->writeLog();
}
// Write VTK
void Utils::writeVTK(GridClass &grid) {
// Write VTK
#ifdef VTK
// Write header
cout << endl << "Writing VTK data...";
// Write grid VTK
grid.writeVTK();
// Write IBM VTK
grid.oPtr->writeVTK();
// Write header
cout << "finished";
#endif
}
// Delete future VTKs
void Utils::deleteVTKs(GridClass &grid) {
// Results path
string path = "Results/VTK";
// Check if it exists
if (boost::filesystem::exists(path)) {
// Loop through three different file types
for (int i = 0; i < 3; i++) {
// File strings
string fileStr, extStr;
// Get types
if (i == 0) {
fileStr = "Fluid";
extStr = ".vti";
}
else if (i == 1) {
fileStr = "IBM";
extStr = ".vtp";
}
else if (i == 2) {
fileStr = "FEM";
extStr = ".vtp";
}
// Get directory iterator
boost::filesystem::directory_iterator endit;
// Loop through all fluid vtk files
for (boost::filesystem::directory_iterator it(path); it != endit; it++) {
// Get string
string fStr = it->path().stem().string();
// Check to make sure it is the files we want
if (fStr.find(fileStr) != string::npos && it->path().extension() == extStr) {
// Get time step
string tStepStr = fStr.substr(fileStr.size() + 1, fStr.size());
// Convert to int
int tStep = stoi(tStepStr);
// If tStep is bigger than current time then delete
if (tStep >= grid.t) {
if (!boost::filesystem::remove(path + "/" + fStr + extStr))
ERROR("Problem removing future VTK files...exiting");
}
}
}
}
}
}
// Get number of omp threads (as built in doesn't work on GCC)
int Utils::omp_thread_count() {
// Thread counters
int n = 0;
// Do parallel reduction on n
#pragma omp parallel reduction(+:n)
n += 1;
// Return total thread count
return n;
}
// Convert seconds to hours:minutes:seconds
array<int, 3> Utils::secs2hms(double seconds) {
// Round to nearest second
seconds = round(seconds);
// Get number of hours and number of minutes
double hours = seconds / (60.0 * 60.0);
double minutes = seconds / (60.0);
// Declare vector
array<int, 3> hms;
// Get hours:minutes:seconds
hms[0] = static_cast<int>(floor(hours));
hms[1] = static_cast<int>(floor(minutes - (static_cast<double>(hms[0]) * 60.0)));
hms[2] = static_cast<int>(floor(static_cast<double>(seconds) - static_cast<double>(hms[1]) * 60.0 - static_cast<double>(hms[0]) * 60.0 * 60.0));
// Return
return hms;
}
// Get string for boundary condition
string Utils::getBoundaryString(eLatType BCType) {
// String
string str;
// Check against possible options
if (BCType == eFluid)
str = "Periodic BC";
else if (BCType == eVelocity)
str = "Velocity BC";
else if (BCType == ePressure)
str = "Pressure BC";
else if (BCType == eWall)
str = "Wall BC";
else if (BCType == eFreeSlip)
str = "Free Slip BC";
else if (BCType == eConvective)
str = "Convective BC";
// Return
return str;
}
// Solve linear system using LAPACK routines
vector<double> Utils::solveLAPACK(vector<double> A, vector<double> b, int BC) {
// Set up the correct values
char trans = 'T';
int dim = static_cast<int>(sqrt(static_cast<int>(A.size())));
int row = dim - BC;
int col = dim - BC;
int offset = BC * dim + BC;
int nrhs = 1;
int LDA = dim;
int LDB = dim;
int info;
std::vector<int> ipiv(row, 0);
// Factorise and solve
dgetrf_(&row, &col, A.data() + offset, &LDA, ipiv.data(), &info);
dgetrs_(&trans, &row, &nrhs, A.data() + offset, &LDA, ipiv.data(), b.data() + BC, &LDB, &info);
// Set return values not included to zero
fill(b.begin(), b.begin() + BC, 0.0);
// Return RHS
return b;
}
| 7,850
|
C++
|
.cpp
| 236
| 30.444915
| 145
| 0.68391
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,162
|
IBMBody.cpp
|
joconnor22_LIFE/src/IBMBody.cpp
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
// Includes
#include "../inc/IBMBody.h"
#include "../inc/FEMBody.h"
#include "../inc/Grid.h"
#include "../inc/Objects.h"
#include "../inc/Utils.h"
// Custom constructor for creating one object from vector of all objects
IBMBodyClass::IBMBodyClass(vector<IBMNodeClass> &iNode) {
// Set values (some of them don't matter)
oPtr = iNode[0].iPtr->oPtr;
ID = 0;
flex = eFlexible;
bodyType = eCircle;
sBody = NULL;
// Reserve space
node.reserve(iNode.size());
// Loop through all markers and copy into this vector
for (size_t n = 0; n < iNode.size(); n++)
node.push_back(&iNode[n]);
}
// Custom constructor for building circle
IBMBodyClass::IBMBodyClass(ObjectsClass *objects, int bodyID, const array<double, dims> &pos, double radius) {
// Set body values
oPtr = objects;
ID = bodyID;
flex = eRigid;
bodyType = eCircle;
sBody = NULL;
// Get number of markers
int numNodes = static_cast<int>(floor(2.0 * M_PI * radius / oPtr->gPtr->Dx));
// Position vector for marker
array<double, dims> position;
// Reserve space
node.reserve(numNodes);
// Loop through and build body
for (int i = 0; i < numNodes; i++) {
// Get position of this marker
position[eX] = pos[eX] + radius * cos(i * 2.0 * M_PI / numNodes);
position[eY] = pos[eY] + radius * sin(i * 2.0 * M_PI / numNodes);
// Call node constructor
oPtr->iNode.emplace_back(this, oPtr->iNode.size(), position);
// Insert pointer into node vector
node.push_back(&(oPtr->iNode.back()));
}
}
// Custom constructor for building filament
IBMBodyClass::IBMBodyClass(ObjectsClass *objects, int bodyID, const array<double, dims> &pos, const array<double, dims> &geom,
double angle, string flexStr, string nElements, string BC, double rho, double E) {
// Set body values
oPtr = objects;
ID = bodyID;
bodyType = eFilament;
sBody = NULL;
// Set flex type
if (flexStr == "FLEXIBLE")
flex = eFlexible;
else if (flexStr == "RIGID")
flex = eRigid;
else
ERROR("Not a proper flexible type set...exiting");
// Unpack geometry and convert angle to radians
double length = geom[0];
angle = angle * M_PI / 180.0;
// Get rotation matrix
array<array<double, dims>, dims> T = Utils::getRotationMatrix(angle);
// Build the IBM body
int numNodes = static_cast<int>(floor(length / oPtr->gPtr->Dx)) + 1;
// Position vector for marker
array<double, dims> position;
// Reserve space
node.reserve(numNodes);
// Loop through and build body
for (int i = 0; i < numNodes; i++) {
// Get position of this marker
position[eX] = i * length / (numNodes - 1);
position[eY] = 0.0;
// Rotate
position = T * position;
// Add the start point
position = pos + position;
// Call node constructor
oPtr->iNode.emplace_back(this, oPtr->iNode.size(), position);
// Insert pointer into node vector
node.push_back(&(oPtr->iNode.back()));
}
// If flexible then build body
if (flex == eFlexible)
sBody = new FEMBodyClass(this, pos, geom, angle, nElements, BC, rho, E);
}
| 3,743
|
C++
|
.cpp
| 103
| 33.61165
| 126
| 0.709257
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,163
|
params.h
|
joconnor22_LIFE/examples/PELskin/params.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef PARAMS_H // PARAMS_H
#define PARAMS_H
// Include defs
#include "defs.h"
// Set number of OMP threads (if commented then it will use system max)
//#define THREADS 12
// Set resFactor (for easily changing mesh resolution)
const int resFactor = 3;
// Simulation options
//#define CENTRAL_MOMENTS // Use central moments collision operator (BGK otherwise)
//#define INLET_RAMP 2.0 // Inlet velocity ramp-up
#define WOMERSLEY 7.52 // Womersley number for oscillating pressure gradients
#define UNI_EPSILON // Calculate epsilon over all IBM bodies at once
#define ORDERED // For deterministic reduction operations
//#define INITIAL_DEFLECT 0.01 // Set an initial deflection (fraction of L)
// Outputs
#define VTK // Write out VTK
//#define VTK_FEM // Write out the FEM VTK
#define FORCES // Write out forces on structures
#define TIPS // Write out tip positions
// Domain setup (lattice)
const int Nx = resFactor * (5 * 9 + 10 * 20); // Number of lattice sites in x-direction
const int Ny = resFactor * (10 * 3) + 1; // Number of lattice sites in y-direction
// Domain setup (physical)
const double height_p = 0.06; // Domain height (m)
const double rho_p = 1200.0; // Fluid density (kg/m^3)
const double nu_p = 0.0001; // Fluid kinematic viscosity (m^2/s)
// Initial conditions
const double ux0_p = 0.0; // Initial x-velocity (m/s)
const double uy0_p = 0.0; // Initial y-velocity (m/s)
// Gravity and pressure gradient
const double gravityX = 0.0; // Gravity component in x-direction (m/s^2)
const double gravityY = 0.0; // Gravity component in y-direction (m/s^2)
const double dpdx = 4550.0; // Pressure gradient in x-direction (Pa/m)
const double dpdy = 0.0; // Pressure gradient in x-direction (Pa/m)
// Boundary conditions (set to eFluid for periodic)
#define WALL_LEFT eFluid // Boundary condition at left wall
#define WALL_RIGHT eFluid // Boundary condition at right wall
#define WALL_BOTTOM eWall // Boundary condition at bottom wall
#define WALL_TOP eWall // Boundary condition at top wall
//#define PROFILE eParabolic // Profile shape (uncomment for uniform)
// Inlet conditions
const double uxInlet_p = 0.0; // Inlet x-velocity (m/s)
const double uyInlet_p = 0.0; // Inlet y-velocity (m/s)
// FEM Newmark integration parameters
const double alpha = 0.25; // Alpha parameter
const double delta = 0.5; // Delta parameter
// FSI Coupling parameters
const double relaxMax = 1.0; // Relaxation parameter (initial guess)
const double subTol = 1e-4; // Tolerance for subiterations
// Set omega by three different methods (comment/uncomment)
// Set omega directly
//const double omega = 1.875;
//const double tStep = pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0) * (1.0 - 0.5 * omega) / (nu_p * omega);
// Set time step
const double tStep = (0.001 / 3.0) / (resFactor * resFactor);
const double omega = 1.0 / (nu_p * tStep / (pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0)) + 0.5);
// Set lattice velocity
//const double uLB = (2.0 / 3.0) * 0.2 * 1.0 / sqrt(3.0);
//const double omega = 1.0 / (uLB * (Ny-1) / (uxInlet_p * height_p / (3.0 * nu_p)) + 0.5);
// Number of time steps and how often to write out
const int nSteps = static_cast<int>(round(10.0 / tStep)); // Number of timesteps
const int tinfo = nSteps / 10000; // Frequency to write out info and logs
const int tVTK = nSteps / 1000; // Frequency to write out VTK
const int tRestart = nSteps / 10; // Frequency to write out restart files
// Reference values
const double ref_nu = nu_p; // Reference kinematic viscosity (m^2/s)
const double ref_rho = rho_p; // Reference density (kg/m^3)
const double ref_P = 0.0; // Reference pressure (Pa)
const double ref_L = 0.02; // Reference length (m)
const double ref_U = 0.06; // Reference velocity (m/s)
// Precision for ASCII output
const int PRECISION = 10;
#endif // PARAMS_H
| 4,712
|
C++
|
.h
| 88
| 51.727273
| 120
| 0.703696
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,164
|
params.h
|
joconnor22_LIFE/examples/InvertedFlag/params.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef PARAMS_H // PARAMS_H
#define PARAMS_H
// Include defs
#include "defs.h"
// Set number of OMP threads (if commented then it will use system max)
//#define THREADS 12
// Set resFactor (for easily changing mesh resolution)
const int resFactor = 3;
// Simulation options
//#define CENTRAL_MOMENTS // Use central moments collision operator (BGK otherwise)
//#define INLET_RAMP 2.0 // Inlet velocity ramp-up
//#define WOMERSLEY 5.0 // Womersley number for oscillating pressure gradients
//#define UNI_EPSILON // Calculate epsilon over all IBM bodies at once
#define ORDERED // For deterministic reduction operations
#define INITIAL_DEFLECT 0.01 // Set an initial deflection (fraction of L)
// Outputs
#define VTK // Write out VTK
//#define VTK_FEM // Write out the FEM VTK
#define FORCES // Write out forces on structures
#define TIPS // Write out tip positions
// Domain setup (lattice)
const int Nx = resFactor * 10 * 21 + 1; // Number of lattice sites in x-direction
const int Ny = resFactor * 10 * 15 + 1; // Number of lattice sites in y-direction
// Domain setup (physical)
const double height_p = 0.855; // Domain height (m)
const double rho_p = 1.2047; // Fluid density (kg/m^3)
const double nu_p = 1.5111e-2; // Fluid kinematic viscosity (m^2/s)
// Initial conditions
const double ux0_p = 8.0; // Initial x-velocity (m/s)
const double uy0_p = 0.0; // Initial y-velocity (m/s)
// Gravity and pressure gradient
const double gravityX = 0.0; // Gravity component in x-direction (m/s^2)
const double gravityY = 0.0; // Gravity component in y-direction (m/s^2)
const double dpdx = 0.0; // Pressure gradient in x-direction (Pa/m)
const double dpdy = 0.0; // Pressure gradient in x-direction (Pa/m)
// Boundary conditions (set to eFluid for periodic)
#define WALL_LEFT eVelocity // Boundary condition at left wall
#define WALL_RIGHT eConvective // Boundary condition at right wall
#define WALL_BOTTOM eVelocity // Boundary condition at bottom wall
#define WALL_TOP eVelocity // Boundary condition at top wall
//#define PROFILE eParabolic // Profile shape (uncomment for uniform)
// Inlet conditions
const double uxInlet_p = ux0_p; // Inlet x-velocity (m/s)
const double uyInlet_p = 0.0; // Inlet y-velocity (m/s)
// FEM Newmark integration parameters
const double alpha = 0.25; // Alpha parameter
const double delta = 0.5; // Delta parameter
// FSI Coupling parameters
const double relaxMax = 1.0; // Relaxation parameter (initial guess)
const double subTol = 1e-5; // Tolerance for subiterations
// Set omega by three different methods (comment/uncomment)
// Set omega directly
//const double omega = 1.875;
//const double tStep = pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0) * (1.0 - 0.5 * omega) / (nu_p * omega);
// Set time step
const double tStep = 0.00005 / (resFactor * resFactor);
const double omega = 1.0 / (nu_p * tStep / (pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0)) + 0.5);
// Set lattice velocity
//const double uLB = (2.0 / 3.0) * 0.2 * 1.0 / sqrt(3.0);
//const double omega = 1.0 / (uLB * (Ny-1) / (uxInlet_p * height_p / (3.0 * nu_p)) + 0.5);
// Number of time steps and how often to write out
const int nSteps = static_cast<int>(round(4.0 / tStep)); // Number of timesteps
const int tinfo = nSteps / 10000; // Frequency to write out info and logs
const int tVTK = nSteps / 1000; // Frequency to write out VTK
const int tRestart = nSteps / 10; // Frequency to write out restart files
// Reference values
const double ref_nu = nu_p; // Reference kinematic viscosity (m^2/s)
const double ref_rho = rho_p; // Reference density (kg/m^3)
const double ref_P = 0.0; // Reference pressure (Pa)
const double ref_L = 0.057; // Reference length (m)
const double ref_U = uxInlet_p; // Reference velocity (m/s)
// Precision for ASCII output
const int PRECISION = 10;
#endif // PARAMS_H
| 4,719
|
C++
|
.h
| 88
| 51.806818
| 120
| 0.707402
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,165
|
params.h
|
joconnor22_LIFE/examples/ChannelFlow/params.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef PARAMS_H // PARAMS_H
#define PARAMS_H
// Include defs
#include "defs.h"
// Set number of OMP threads (if commented then it will use system max)
//#define THREADS 12
// Set resFactor (for easily changing mesh resolution)
const int resFactor = 1;
// Simulation options
//#define CENTRAL_MOMENTS // Use central moments collision operator (BGK otherwise)
//#define INLET_RAMP 2.0 // Inlet velocity ramp-up
//#define WOMERSLEY 5.0 // Womersley number for oscillating pressure gradients
//#define UNI_EPSILON // Calculate epsilon over all IBM bodies at once
//#define ORDERED // For deterministic reduction operations
//#define INITIAL_DEFLECT 0.01 // Set an initial deflection (fraction of L)
// Outputs
#define VTK // Write out VTK
//#define VTK_FEM // Write out the FEM VTK
//#define FORCES // Write out forces on structures
//#define TIPS // Write out tip positions
// Domain setup (lattice)
const int Nx = resFactor * 500 + 1; // Number of lattice sites in x-direction
const int Ny = resFactor * 50 + 1; // Number of lattice sites in y-direction
// Domain setup (physical)
const double height_p = 1.0; // Domain height (m)
const double rho_p = 1.0; // Fluid density (kg/m^3)
const double nu_p = 0.01; // Fluid kinematic viscosity (m^2/s)
// Initial conditions
const double ux0_p = 0.0; // Initial x-velocity (m/s)
const double uy0_p = 0.0; // Initial y-velocity (m/s)
// Gravity and pressure gradient
const double gravityX = 0.0; // Gravity component in x-direction (m/s^2)
const double gravityY = 0.0; // Gravity component in y-direction (m/s^2)
const double dpdx = 0.0; // Pressure gradient in x-direction (Pa/m)
const double dpdy = 0.0; // Pressure gradient in x-direction (Pa/m)
// Boundary conditions (set to eFluid for periodic)
#define WALL_LEFT eVelocity // Boundary condition at left wall
#define WALL_RIGHT ePressure // Boundary condition at right wall
#define WALL_BOTTOM eWall // Boundary condition at bottom wall
#define WALL_TOP eWall // Boundary condition at top wall
//#define PROFILE eParabolic // Profile shape (uncomment for uniform)
// Inlet conditions
const double uxInlet_p = 1.0; // Inlet x-velocity (m/s)
const double uyInlet_p = 0.0; // Inlet y-velocity (m/s)
// FEM Newmark integration parameters
const double alpha = 0.25; // Alpha parameter
const double delta = 0.5; // Delta parameter
// FSI Coupling parameters
const double relaxMax = 1.0; // Relaxation parameter (initial guess)
const double subTol = 1e-8; // Tolerance for subiterations
// Set omega by three different methods (comment/uncomment)
// Set omega directly
//const double omega = 1.875;
//const double tStep = pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0) * (1.0 - 0.5 * omega) / (nu_p * omega);
// Set time step
const double tStep = 0.0005 / (resFactor * resFactor);
const double omega = 1.0 / (nu_p * tStep / (pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0)) + 0.5);
// Set lattice velocity
//const double uLB = (2.0 / 3.0) * 0.2 * 1.0 / sqrt(3.0);
//const double omega = 1.0 / (uLB * (Ny-1) / (uxInlet_p * height_p / (3.0 * nu_p)) + 0.5);
// Number of time steps and how often to write out
const int nSteps = static_cast<int>(round(30.0 / tStep)); // Number of timesteps
const int tinfo = nSteps / 1000; // Frequency to write out info and logs
const int tVTK = nSteps / 100; // Frequency to write out VTK
const int tRestart = nSteps / 10; // Frequency to write out restart files
// Reference values
const double ref_nu = nu_p; // Reference kinematic viscosity (m^2/s)
const double ref_rho = rho_p; // Reference density (kg/m^3)
const double ref_P = 0.0; // Reference pressure (Pa)
const double ref_L = height_p; // Reference length (m)
const double ref_U = uxInlet_p; // Reference velocity (m/s)
// Precision for ASCII output
const int PRECISION = 10;
#endif // PARAMS_H
| 4,697
|
C++
|
.h
| 88
| 51.556818
| 120
| 0.70578
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,166
|
params.h
|
joconnor22_LIFE/examples/LidDrivenCavity/params.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef PARAMS_H // PARAMS_H
#define PARAMS_H
// Include defs
#include "defs.h"
// Set number of OMP threads (if commented then it will use system max)
//#define THREADS 12
// Set resFactor (for easily changing mesh resolution)
const int resFactor = 1;
// Simulation options
#define CENTRAL_MOMENTS // Use central moments collision operator (BGK otherwise)
//#define INLET_RAMP 2.0 // Inlet velocity ramp-up
//#define WOMERSLEY 5.0 // Womersley number for oscillating pressure gradients
//#define UNI_EPSILON // Calculate epsilon over all IBM bodies at once
//#define ORDERED // For deterministic reduction operations
//#define INITIAL_DEFLECT 0.01 // Set an initial deflection (fraction of L)
// Outputs
#define VTK // Write out VTK
//#define VTK_FEM // Write out the FEM VTK
//#define FORCES // Write out forces on structures
//#define TIPS // Write out tip positions
// Domain setup (lattice)
const int Nx = resFactor * 100 + 1; // Number of lattice sites in x-direction
const int Ny = resFactor * 100 + 1; // Number of lattice sites in y-direction
// Domain setup (physical)
const double height_p = 1.0; // Domain height (m)
const double rho_p = 1.0; // Fluid density (kg/m^3)
const double nu_p = 0.0002; // Fluid kinematic viscosity (m^2/s)
// Initial conditions
const double ux0_p = 0.0; // Initial x-velocity (m/s)
const double uy0_p = 0.0; // Initial y-velocity (m/s)
// Gravity and pressure gradient
const double gravityX = 0.0; // Gravity component in x-direction (m/s^2)
const double gravityY = 0.0; // Gravity component in y-direction (m/s^2)
const double dpdx = 0.0; // Pressure gradient in x-direction (Pa/m)
const double dpdy = 0.0; // Pressure gradient in x-direction (Pa/m)
// Boundary conditions (set to eFluid for periodic)
#define WALL_LEFT eWall // Boundary condition at left wall
#define WALL_RIGHT eWall // Boundary condition at right wall
#define WALL_BOTTOM eWall // Boundary condition at bottom wall
#define WALL_TOP eVelocity // Boundary condition at top wall
//#define PROFILE eParabolic // Profile shape (uncomment for uniform)
// Inlet conditions
const double uxInlet_p = 1.0; // Inlet x-velocity (m/s)
const double uyInlet_p = 0.0; // Inlet y-velocity (m/s)
// FEM Newmark integration parameters
const double alpha = 0.25; // Alpha parameter
const double delta = 0.5; // Delta parameter
// FSI Coupling parameters
const double relaxMax = 1.0; // Relaxation parameter (initial guess)
const double subTol = 1e-8; // Tolerance for subiterations
// Set omega by three different methods (comment/uncomment)
// Set omega directly
//const double omega = 1.875;
//const double tStep = pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0) * (1.0 - 0.5 * omega) / (nu_p * omega);
// Set time step
const double tStep = 0.001 / (resFactor * resFactor);
const double omega = 1.0 / (nu_p * tStep / (pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0)) + 0.5);
// Set lattice velocity
//const double uLB = (2.0 / 3.0) * 0.2 * 1.0 / sqrt(3.0);
//const double omega = 1.0 / (uLB * (Ny-1) / (uxInlet_p * height_p / (3.0 * nu_p)) + 0.5);
// Number of time steps and how often to write out
const int nSteps = static_cast<int>(round(50.0 / tStep)); // Number of timesteps
const int tinfo = nSteps / 1000; // Frequency to write out info and logs
const int tVTK = nSteps / 200; // Frequency to write out VTK
const int tRestart = nSteps / 100; // Frequency to write out restart files
// Reference values
const double ref_nu = nu_p; // Reference kinematic viscosity (m^2/s)
const double ref_rho = rho_p; // Reference density (kg/m^3)
const double ref_P = 0.0; // Reference pressure (Pa)
const double ref_L = 1.0; // Reference length (m)
const double ref_U = uxInlet_p; // Reference velocity (m/s)
// Precision for ASCII output
const int PRECISION = 10;
#endif // PARAMS_H
| 4,692
|
C++
|
.h
| 88
| 51.5
| 120
| 0.70524
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,167
|
params.h
|
joconnor22_LIFE/examples/Cylinder/params.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef PARAMS_H // PARAMS_H
#define PARAMS_H
// Include defs
#include "defs.h"
// Set number of OMP threads (if commented then it will use system max)
//#define THREADS 12
// Set resFactor (for easily changing mesh resolution)
const int resFactor = 2;
// Simulation options
//#define CENTRAL_MOMENTS // Use central moments collision operator (BGK otherwise)
#define INLET_RAMP 2.0 // Inlet velocity ramp-up
//#define WOMERSLEY 5.0 // Womersley number for oscillating pressure gradients
//#define UNI_EPSILON // Calculate epsilon over all IBM bodies at once
#define ORDERED // For deterministic reduction operations
//#define INITIAL_DEFLECT 0.01 // Set an initial deflection (fraction of L)
// Outputs
#define VTK // Write out VTK
//#define VTK_FEM // Write out the FEM VTK
#define FORCES // Write out forces on structures
//#define TIPS // Write out tip positions
// Domain setup (lattice)
const int Nx = resFactor * 220 + 1; // Number of lattice sites in x-direction
const int Ny = resFactor * 41 + 1; // Number of lattice sites in y-direction
// Domain setup (physical)
const double height_p = 0.41; // Domain height (m)
const double rho_p = 1.0; // Fluid density (kg/m^3)
const double nu_p = 0.001; // Fluid kinematic viscosity (m^2/s)
// Initial conditions
const double ux0_p = 0.0; // Initial x-velocity (m/s)
const double uy0_p = 0.0; // Initial y-velocity (m/s)
// Gravity and pressure gradient
const double gravityX = 0.0; // Gravity component in x-direction (m/s^2)
const double gravityY = 0.0; // Gravity component in y-direction (m/s^2)
const double dpdx = 0.0; // Pressure gradient in x-direction (Pa/m)
const double dpdy = 0.0; // Pressure gradient in x-direction (Pa/m)
// Boundary conditions (set to eFluid for periodic)
#define WALL_LEFT eVelocity // Boundary condition at left wall
#define WALL_RIGHT ePressure // Boundary condition at right wall
#define WALL_BOTTOM eWall // Boundary condition at bottom wall
#define WALL_TOP eWall // Boundary condition at top wall
#define PROFILE eParabolic // Profile shape (uncomment for uniform)
// Inlet conditions
const double uxInlet_p = 1.0; // Inlet x-velocity (m/s)
const double uyInlet_p = 0.0; // Inlet y-velocity (m/s)
// FEM Newmark integration parameters
const double alpha = 0.25; // Alpha parameter
const double delta = 0.5; // Delta parameter
// FSI Coupling parameters
const double relaxMax = 1.0; // Relaxation parameter (initial guess)
const double subTol = 1e-8; // Tolerance for subiterations
// Set omega by three different methods (comment/uncomment)
// Set omega directly
//const double omega = 1.875;
//const double tStep = pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0) * (1.0 - 0.5 * omega) / (nu_p * omega);
// Set time step
const double tStep = 0.001 / (resFactor * resFactor);
const double omega = 1.0 / (nu_p * tStep / (pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0)) + 0.5);
// Set lattice velocity
//const double uLB = (2.0 / 3.0) * 0.2 * 1.0 / sqrt(3.0);
//const double omega = 1.0 / (uLB * (Ny-1) / (uxInlet_p * height_p / (3.0 * nu_p)) + 0.5);
// Number of time steps and how often to write out
const int nSteps = static_cast<int>(round(20.0 / tStep)); // Number of timesteps
const int tinfo = nSteps / 1000; // Frequency to write out info and logs
const int tVTK = nSteps / 200; // Frequency to write out VTK
const int tRestart = nSteps / 100; // Frequency to write out restart files
// Reference values
const double ref_nu = nu_p; // Reference kinematic viscosity (m^2/s)
const double ref_rho = rho_p; // Reference density (kg/m^3)
const double ref_P = 0.0; // Reference pressure (Pa)
const double ref_L = 0.1; // Reference length (m)
const double ref_U = uxInlet_p; // Reference velocity (m/s)
// Precision for ASCII output
const int PRECISION = 10;
#endif // PARAMS_H
| 4,691
|
C++
|
.h
| 88
| 51.488636
| 120
| 0.706049
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,168
|
params.h
|
joconnor22_LIFE/examples/Honami/params.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef PARAMS_H // PARAMS_H
#define PARAMS_H
// Include defs
#include "defs.h"
// Set number of OMP threads (if commented then it will use system max)
//#define THREADS 12
// Set resFactor (for easily changing mesh resolution)
//const int resFactor = 1;
// Simulation options
//#define CENTRAL_MOMENTS // Use central moments collision operator (BGK otherwise)
#define INLET_RAMP 250.0 // Inlet velocity ramp-up
//#define WOMERSLEY 5.0 // Womersley number for oscillating pressure gradients
//#define UNI_EPSILON // Calculate epsilon over all IBM bodies at once
#define ORDERED // For deterministic reduction operations
//#define INITIAL_DEFLECT 0.01 // Set an initial deflection (fraction of L)
// Outputs
#define VTK // Write out VTK
//#define VTK_FEM // Write out the FEM VTK
#define FORCES // Write out forces on structures
#define TIPS // Write out tip positions
// Domain setup (lattice)
const int Nx = 1200 + 127 * 15 + 1; // Number of lattice sites in x-direction
const int Ny = 90 + 1; // Number of lattice sites in y-direction
// Domain setup (physical)
const double height_p = 3.0; // Domain height (m)
const double rho_p = 1.0; // Fluid density (kg/m^3)
const double nu_p = 0.0125; // Fluid kinematic viscosity (m^2/s)
// Initial conditions
const double ux0_p = 0.0; // Initial x-velocity (m/s)
const double uy0_p = 0.0; // Initial y-velocity (m/s)
// Gravity and pressure gradient
const double gravityX = 0.0; // Gravity component in x-direction (m/s^2)
const double gravityY = 0.0; // Gravity component in y-direction (m/s^2)
const double dpdx = 0.0; // Pressure gradient in x-direction (Pa/m)
const double dpdy = 0.0; // Pressure gradient in x-direction (Pa/m)
// Boundary conditions (set to eFluid for periodic)
#define WALL_LEFT eVelocity // Boundary condition at left wall
#define WALL_RIGHT ePressure // Boundary condition at right wall
#define WALL_BOTTOM eWall // Boundary condition at bottom wall
#define WALL_TOP eFreeSlip // Boundary condition at top wall
#define PROFILE eBoundaryLayer // Profile shape (uncomment for uniform)
// Inlet conditions
const double uxInlet_p = 1.0; // Inlet x-velocity (m/s)
const double uyInlet_p = 0.0; // Inlet y-velocity (m/s)
// FEM Newmark integration parameters
const double alpha = 0.25; // Alpha parameter
const double delta = 0.5; // Delta parameter
// FSI Coupling parameters
const double relaxMax = 1.0; // Relaxation parameter (initial guess)
const double subTol = 1e-8; // Tolerance for subiterations
// Set omega by three different methods (comment/uncomment)
// Set omega directly
//const double omega = 1.875;
//const double tStep = pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0) * (1.0 - 0.5 * omega) / (nu_p * omega);
// Set time step
const double tStep = 0.00625 / (3.0 * 3.0);
const double omega = 1.0 / (nu_p * tStep / (pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0)) + 0.5);
// Set lattice velocity
//const double uLB = (2.0 / 3.0) * 0.2 * 1.0 / sqrt(3.0);
//const double omega = 1.0 / (uLB * (Ny-1) / (uxInlet_p * height_p / (3.0 * nu_p)) + 0.5);
// Number of time steps and how often to write out
const int nSteps = 900000; // Number of timesteps
const int tinfo = 45; // Frequency to write out info and logs
const int tVTK = 900; // Frequency to write out VTK
const int tRestart = 9000; // Frequency to write out restart files
// Reference values
const double ref_nu = nu_p; // Reference kinematic viscosity (m^2/s)
const double ref_rho = rho_p; // Reference density (kg/m^3)
const double ref_P = 0.0; // Reference pressure (Pa)
const double ref_L = 1.0; // Reference length (m)
const double ref_U = uxInlet_p; // Reference velocity (m/s)
// Precision for ASCII output
const int PRECISION = 10;
#endif // PARAMS_H
| 4,626
|
C++
|
.h
| 88
| 50.75
| 120
| 0.704475
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,169
|
params.h
|
joconnor22_LIFE/examples/TurekHron/params.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef PARAMS_H // PARAMS_H
#define PARAMS_H
// Include defs
#include "defs.h"
// Set number of OMP threads (if commented then it will use system max)
//#define THREADS 12
// Set resFactor (for easily changing mesh resolution)
const int resFactor = 2;
// Simulation options
//#define CENTRAL_MOMENTS // Use central moments collision operator (BGK otherwise)
#define INLET_RAMP 2.0 // Inlet velocity ramp-up
//#define WOMERSLEY 5.0 // Womersley number for oscillating pressure gradients
#define UNI_EPSILON // Calculate epsilon over all IBM bodies at once
#define ORDERED // For deterministic reduction operations
//#define INITIAL_DEFLECT 0.01 // Set an initial deflection (fraction of L)
// Outputs
#define VTK // Write out VTK
//#define VTK_FEM // Write out the FEM VTK
#define FORCES // Write out forces on structures
#define TIPS // Write out tip positions
// Domain setup (lattice)
const int Nx = resFactor * 250 + 1; // Number of lattice sites in x-direction
const int Ny = resFactor * 41 + 1; // Number of lattice sites in y-direction
// Domain setup (physical)
const double height_p = 0.41; // Domain height (m)
const double rho_p = 1000.0; // Fluid density (kg/m^3)
const double nu_p = 0.001; // Fluid kinematic viscosity (m^2/s)
// Initial conditions
const double ux0_p = 0.0; // Initial x-velocity (m/s)
const double uy0_p = 0.0; // Initial y-velocity (m/s)
// Gravity and pressure gradient
const double gravityX = 0.0; // Gravity component in x-direction (m/s^2)
const double gravityY = 0.0; // Gravity component in y-direction (m/s^2)
const double dpdx = 0.0; // Pressure gradient in x-direction (Pa/m)
const double dpdy = 0.0; // Pressure gradient in x-direction (Pa/m)
// Boundary conditions (set to eFluid for periodic)
#define WALL_LEFT eVelocity // Boundary condition at left wall
#define WALL_RIGHT ePressure // Boundary condition at right wall
#define WALL_BOTTOM eWall // Boundary condition at bottom wall
#define WALL_TOP eWall // Boundary condition at top wall
#define PROFILE eParabolic // Profile shape (uncomment for uniform)
// Inlet conditions
const double uxInlet_p = 1.0; // Inlet x-velocity (m/s)
const double uyInlet_p = 0.0; // Inlet y-velocity (m/s)
// FEM Newmark integration parameters
const double alpha = 0.25; // Alpha parameter
const double delta = 0.5; // Delta parameter
// FSI Coupling parameters
const double relaxMax = 1.0; // Relaxation parameter (initial guess)
const double subTol = 1e-8; // Tolerance for subiterations
// Set omega by three different methods (comment/uncomment)
// Set omega directly
//const double omega = 1.875;
//const double tStep = pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0) * (1.0 - 0.5 * omega) / (nu_p * omega);
// Set time step
const double tStep = 0.001 / (resFactor * resFactor);
const double omega = 1.0 / (nu_p * tStep / (pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0)) + 0.5);
// Set lattice velocity
//const double uLB = (2.0 / 3.0) * 0.2 * 1.0 / sqrt(3.0);
//const double omega = 1.0 / (uLB * (Ny-1) / (uxInlet_p * height_p / (3.0 * nu_p)) + 0.5);
// Number of time steps and how often to write out
const int nSteps = static_cast<int>(round(20.0 / tStep)); // Number of timesteps
const int tinfo = nSteps / 1000; // Frequency to write out info and logs
const int tVTK = nSteps / 200; // Frequency to write out VTK
const int tRestart = nSteps / 100; // Frequency to write out restart files
// Reference values
const double ref_nu = nu_p; // Reference kinematic viscosity (m^2/s)
const double ref_rho = rho_p; // Reference density (kg/m^3)
const double ref_P = 0.0; // Reference pressure (Pa)
const double ref_L = 0.1; // Reference length (m)
const double ref_U = uxInlet_p; // Reference velocity (m/s)
// Precision for ASCII output
const int PRECISION = 10;
#endif // PARAMS_H
| 4,689
|
C++
|
.h
| 88
| 51.465909
| 120
| 0.707013
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,170
|
FEMBody.h
|
joconnor22_LIFE/inc/FEMBody.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef FEMBODY_H // FEMBODY_H
#define FEMBODY_H
// Includes
#include "defs.h"
#include "FEMNode.h"
#include "FEMElement.h"
// Forward declarations
class IBMBodyClass;
// FEM body class
class FEMBodyClass {
// Friend classes
friend class FEMElementClass;
friend class ObjectsClass;
// Nested class for mapping to IBM positions
class posMapClass {
// Set friend class
friend class FEMBodyClass;
// Default constructor and destructor
public:
posMapClass() {elID = 0; zeta = 0.0;};
~posMapClass() {};
// Members
private:
int elID; // Element ID
double zeta; // Node position in local coordinates
};
// Default constructor and destructor
public:
FEMBodyClass() {iPtr = NULL; L0 = 0.0; angle0 = 0.0; bodyDOFs = 0; bcDOFs = 0; itNR = 0; resNR = 0.0; tCrit = 0.0; subRes = 0.0; subNum = 0.0; subDen = 0.0;};
~FEMBodyClass() {};
// Custom constructor for building corotational FEM body
FEMBodyClass(IBMBodyClass *iBodyPtr, const array<double, dims> &pos, const array<double, dims> &geom, double angle, string nElementsStr, string BC, double rho, double E);
// Private members
private:
// Pointer to IBM body
IBMBodyClass *iPtr;
// Geometry
double L0; // Initial length
double angle0; // Initial angle
// System values
int bodyDOFs; // DOFs for whole body
int bcDOFs; // Number of DOFs removed when applying BCs
int itNR; // Number of iterations for Newton-Raphson solver
double resNR; // Residual Newton-Raphson solver reached
double tCrit; // Critical time step
// System matrices
vector<double> M; // Mass matrix
vector<double> K; // Stiffness matrix
vector<double> R; // Load vector
vector<double> F; // Vector of internal forces
vector<double> U; // Vector of displacements
vector<double> delU; // Vector of incremental displacements
vector<double> Udot; // Vector velocities
vector<double> Udotdot; // Vector of accelerations
vector<double> U_n; // Vector of displacements at start of timestep
vector<double> U_nm1; // Vector of displacements at last time step
vector<double> U_nm2; // Vector of displacements at two time steps ago
vector<double> Udot_n; // Vector velocities at start of timestep
vector<double> Udotdot_n; // Vector of accelerations at start of timestep
vector<double> U_km1; // Vector of displacements at last iteration
// Vector of nodes and elements
vector<FEMNodeClass> node; // Vector of nodes
vector<FEMElementClass> element; // Vector of elements
// Vector of parent elements for each IBM node
vector<posMapClass> posMap;
// Parameters for Aitken relaxation
double subRes; // Residual
double subNum; // Numerator
double subDen; // Denominator
vector<double> R_k; // Vector of nodal residuals
vector<double> R_km1; // Vector of nodal residuals at last iteration
// Private methods
private:
// FEM methods
void dynamicFEM(); // Dynamic FEM routine
void newtonRaphsonDynamic(); // Newton Raphson iterator
void constructRVector(); // Get load vector
void buildGlobalMatrices(); // Build global matrices
void setNewmark(); // Set Newmark scheme
void finishNewmark(); // Finish Newmark
void updateIBMValues(); // Update IBM values
void updateFEMValues(); // Update FEM parameters
double checkNRConvergence(); // Check convergence of Newton Raphson iterator
void setInitialDeflection(); // Set initial deflection
void staticFEM(); // Static FEM routine
void newtonRaphsonStatic(); // Static Newton Raphson iterator
void predictor(); // Structural predictor at start of time step
void subResidual(); // Subiteration residual for this body
// Helper routines
void computeNodeMapping(int nIBMNodes, int nFEMNodes); // Get node mappings between FEM and IBM grids
void resetValues(); // Reset the start of time step values
};
#endif // FEMBODY_H
| 4,658
|
C++
|
.h
| 107
| 41.037383
| 171
| 0.73326
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,171
|
FEMElement.h
|
joconnor22_LIFE/inc/FEMElement.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef FEMELEMENT_H // FEMELEMENT_H
#define FEMELEMENT_H
// Includes
#include "defs.h"
// Forward declarations
class FEMBodyClass;
class FEMNodeClass;
// FEM element class
class FEMElementClass {
// Friend classes
friend class FEMBodyClass;
friend class ObjectsClass;
// Nested class for mapping forces from IBM
class forceMapClass {
// Friend classes
friend class FEMElementClass;
// Default constructor and destructor
public:
forceMapClass() {nodeID = 0; zeta1 = 0.0; zeta2 = 0.0;};
~forceMapClass() {};
// Custom constructor for initialising members
forceMapClass(int node, double zetaA, double zetaB) {nodeID = node; zeta1 = zetaA; zeta2 = zetaB;};
// Members
private:
int nodeID; // IBM node ID
double zeta1; // Local coordinate of start of IBM force
double zeta2; // Local coordinate of end of IBM force
};
// Default constructor and destructor
public:
FEMElementClass() {fPtr = NULL; L0 = 0.0; L = 0.0; angle = 0.0; A = 0.0; I = 0.0; E = 0.0; rho = 0.0;};
~FEMElementClass() {};
// Custom constructor for building elements
FEMElementClass(FEMBodyClass *fBody, int i, const array<double, dims> &geom, double angle, double L, double den, double youngMod);
// Private members
private:
// Pointer to fBody
FEMBodyClass *fPtr;
// Geometry properties
double L0; // Initial length of element
double L; // Current length of element
double angle; // Orientation of element at start of timestep
double A; // Cross-sectional area of element
double I; // Second moment areas
// Structural properties
double E; // Youngs modulus
double rho; // Material density
// Transformation matrix
array<array<double, elementDOFs>, elementDOFs> T; // Local transformation matrix
// Local mass and stiffness matrices (which are constant throughout simulation)
array<array<double, elementDOFs>, elementDOFs> M; // Mass matrix
array<array<double, elementDOFs>, elementDOFs> K_L; // Stiffness matrix (linear)
array<array<double, elementDOFs>, elementDOFs> K_NL; // Stiffness matrix (non-linear)
array<double, elementDOFs> R; // Load vector
array<double, elementDOFs> F; // Vector of internal forces
// Global DOFs
array<int, elementDOFs> DOFs; // Global DOFs for this element
// Pointers to the nodes belonging to this element
array<FEMNodeClass*, elementNodes> node;
// Vector of force mappings from IBM to element
vector<forceMapClass> forceMap;
// Private methods
private:
// FEM routines
void loadVector(); // Construct load vector
void massMatrix(); // Construct mass matrix
void stiffMatrix(); // Construct stiffness matrix
void forceVector(); // Construct internal force vector
array<double, dims> shapeFuns(const array<double, elementDOFs> &vec, double zeta); // Multiply by shape functions
// Helper routines
void setLocalMatrices(); // Set local mass and stiffness matrices
void setElementTransform(); // Set the transformation matrix for the element
void assembleGlobalMat(const array<double, elementDOFs> &localVec, vector<double> &globalVec); // Assemble into global vector
void assembleGlobalMat(const array<array<double, elementDOFs>, elementDOFs> &localVec, vector<double> &globalVec); // Assemble into global matrix
array<double, elementDOFs> disassembleGlobalMat(const vector<double> &globalVec); // Disassemble global vector
};
#endif // FEMELEMENT_H
| 4,297
|
C++
|
.h
| 91
| 44.571429
| 146
| 0.725467
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,172
|
IBMBody.h
|
joconnor22_LIFE/inc/IBMBody.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef IBMBODY_H // IBMBODY_H
#define IBMBODY_H
// Includes
#include "defs.h"
#include "IBMNode.h"
// Forward declarations
class ObjectsClass;
class FEMBodyClass;
// IBM body class
class IBMBodyClass {
// Friend classes
friend class ObjectsClass;
friend class IBMNodeClass;
friend class FEMBodyClass;
friend class FEMElementClass;
// Default constructor and destructor
public:
IBMBodyClass() {oPtr = NULL; ID = 0; flex = eRigid; bodyType = eCircle; sBody = NULL;};
~IBMBodyClass() {};
// Custom constructor for creating one object from vector of all objects
IBMBodyClass(vector<IBMNodeClass> &iNode);
// Custom constructor for building circle
IBMBodyClass(ObjectsClass *objects, int bodyID, const array<double, dims> &pos, double radius);
// Custom constructor for building filament
IBMBodyClass(ObjectsClass *objects, int bodyID, const array<double, dims> &pos, const array<double, dims> &geom,
double angle, string flex, string nElements, string BC, double rho, double E);
// Private members
private:
// Pointer to objects
ObjectsClass *oPtr;
// Body parameters
int ID; // Body ID
eFlexibleType flex; // Flexible or rigid
eBodyType bodyType; // Type of body
// Vector of IBM nodes
vector<IBMNodeClass*> node; // Vector of IBM nodes
// Pointer to FEM body
FEMBodyClass *sBody; // Pointer to structural solver
};
#endif // IBMBODY_H
| 2,156
|
C++
|
.h
| 54
| 37.185185
| 113
| 0.756718
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,173
|
IBMNode.h
|
joconnor22_LIFE/inc/IBMNode.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef IBMNODE_H // IBMNODE_H
#define IBMNODE_H
// Includes
#include "defs.h"
#include "IBMSupport.h"
// Forward declarations
class IBMBodyClass;
// IBM node class
class IBMNodeClass {
// Friend classes
friend class ObjectsClass;
friend class FEMElementClass;
friend class FEMBodyClass;
friend class IBMBodyClass;
// Default constructor and destructor
public:
IBMNodeClass() {iPtr = NULL; ID = 0; ds = 0.0; epsilon = 0.0; interpRho = 0.0; suppCount = 0;};
~IBMNodeClass() {};
// Custom constructor for building node
IBMNodeClass(IBMBodyClass *iPtr, int nodeID, const array<double, dims> &pos);
// Private members
private:
// Pointer to body
IBMBodyClass *iPtr; // Pointer to owning IBM body
// ID
int ID; // Global node ID
// Positions, velocities and forces
array<double, dims> pos; // Position of node
array<double, dims> vel; // Velocity at node
array<double, dims> force; // Force on IBM marker
// Spacing and force multiplier
double ds; // Spacing between points (lattice units)
double epsilon; // Multiplier for IBM
// Interpolated values
array<double, dims> interpMom; // Interpolated momentum
double interpRho; // Interpolated density
// Vector of support points
size_t suppCount; // Number of support points for this IBM marker
array<IBMSupportClass, suppSize> supp; // Vector of support points
// Private methods
private:
// IBM methods
void findSupport(); // Find support
void computeDs(); // Compute spacing between IBM nodes
void interpolate(); // Interpolation
void forceCalc(); // Force calculation
void spread(); // Spread force back
void updateMacroscopic(); // Update macroscopic values at support points
};
#endif // IBMNODE_H
| 2,536
|
C++
|
.h
| 64
| 37
| 96
| 0.731648
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,174
|
Utils.h
|
joconnor22_LIFE/inc/Utils.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef UTILS_H // UTILS_H
#define UTILS_H
// Includes
#include "params.h"
// Forward declarations
class GridClass;
// Utility namespace for helper functions
namespace Utils {
// DECLARATIONS
// Write header at start of run
void writeHeader();
// Create directories at start
bool createDirectories();
// Read in restart file
void readRestart(GridClass &grid);
// Read in restart file
void writeRestart(GridClass &grid);
// Write out info
void writeInfo(GridClass &grid);
// Write out log
void writeLog(GridClass &grid);
// Write out VTK
void writeVTK(GridClass &grid);
// Delete future VTKs
void deleteVTKs(GridClass &grid);
// Get number of omp threads (as built in doesn't work on GCC)
int omp_thread_count();
// Convert seconds to hours:minutes:seconds
array<int, 3> secs2hms(double seconds);
// Get string for boundary condition
string getBoundaryString(eLatType BCType);
// Solve linear system using LAPACK routines
vector<double> solveLAPACK(vector<double> A, vector<double> b, int BC = 0);
// DEFINITIONS
// Error and exit
inline void errorExit(const string &msg) {
// Write message then exit
cout << endl << endl << msg << endl << endl;
exit(99);
}
// Warning
inline void warning(const string &msg) {
// Write message then exit
cout << endl << endl << endl << "** WARNING: " << msg << " **";
}
// Derived struct from ofstream for writing to stdout and file at same time
struct io_ofstream : ofstream {
// Constructor
io_ofstream(const string& fileNameIn, openmode mode = out) : ofstream(fileNameIn, mode) , fileName(fileNameIn) {};
// Name of file
const string fileName;
};
// Overloaded << operator for writing to file and stdout
template <typename T>
io_ofstream& operator<<(Utils::io_ofstream& strm, const T &var) {
// Write to stout and file
std::cout << var;
static_cast<ofstream&>(strm) << var;
// Return
return strm;
}
// Check for endianness
inline bool isBigEndian()
{
// Create union and assign bytes
union {uint32_t i; char c[4];} bint = {0x01020304};
// Return fist byte
return bint.c[0] == 1;
}
// Swap byte orders between big and little endian
template <typename T>
inline T swapEnd(const T &val) {
// Results
T res = val;
// Create pointer to char arrays
char* resArray = reinterpret_cast<char*>(&res);
// Loop through and reorder
for(size_t i = 0; i < sizeof(res) / 2; i++)
swap(resArray[i], resArray[sizeof(res) - 1 - i]);
// Return
return res;
}
// Extrapolate value
inline double extrapolate(const vector<double> &vec, const array<int, dims> &normal, int order, int i, int j, int d = 0, int arrayDims = 1) {
// 0th order extrapolation
if (order == 0) {
// Get indices for extrapolation
int i1 = i + normal[eX];
int j1 = j + normal[eY];
// Return value
return vec[(i1 * Ny + j1) * arrayDims + d];
}
// 1st order extrapolation
else if (order == 1) {
// Get indices for extrapolation
int i1 = i + normal[eX];
int i2 = i + 2 * normal[eX];
int j1 = j + normal[eY];
int j2 = j + 2 * normal[eY];
// Return value
return 2.0 * vec[(i1 * Ny + j1) * arrayDims + d] - vec[(i2 * Ny + j2) * arrayDims + d];
}
// 2st order extrapolation
else if (order == 2) {
// Get indices for extrapolation
int i1 = i + normal[eX];
int i2 = i + 2 * normal[eX];
int i3 = i + 3 * normal[eX];
int j1 = j + normal[eY];
int j2 = j + 2 * normal[eY];
int j3 = j + 3 * normal[eY];
// Return value
return 2.5 * vec[(i1 * Ny + j1) * arrayDims + d] - 2.0 * vec[(i2 * Ny + j2) * arrayDims + d] + 0.5 * vec[(i3 * Ny + j3) * arrayDims + d];
}
// Can't do other extrapolations
else {
ERROR("Invalid order of extrapolation...exiting");
return 99;
}
}
// Get value by applying a zero gradient
inline double zeroGradient(const vector<double> &vec, const array<int, dims> &normal, int order, int i, int j, int d = 0, int arrayDims = 1) {
// 1st order extrapolation
if (order == 1) {
// Get indices for extrapolation
int i1 = i + normal[eX];
int j1 = j + normal[eY];
// Return value
return vec[(i1 * Ny + j1) * arrayDims + d];
}
// 2nd order extrapolation
else if (order == 2) {
// Get indices for extrapolation
int i1 = i + normal[eX];
int i2 = i + 2 * normal[eX];
int j1 = j + normal[eY];
int j2 = j + 2 * normal[eY];
// Return value
return (4.0 / 3.0) * vec[(i1 * Ny + j1) * arrayDims + d] - (1.0 / 3.0) * vec[(i2 * Ny + j2) * arrayDims + d];
}
// Can't do other extrapolations
else {
ERROR("Invalid order of zero gradient...exiting");
return 99;
}
}
// Get discretised dirac delta
inline double diracDelta(double dist) {
// Get absolute value
double absDist = fabs(dist);
// Get discretised 3-point dirac delta
if (absDist > 1.5)
return 0.0;
else if (absDist > 0.5)
return (5.0 - 3.0 * absDist - sqrt(-3.0 * SQ(1.0 - absDist) + 1.0)) / 6.0;
else
return (1.0 + sqrt(1.0 - 3.0 * SQ(absDist))) / 3.0;
}
// Shift angle into -pi -> pi range
inline double shiftAngle(double angle) {
// Get angle
angle = fmod(angle + M_PI, 2.0 * M_PI);
// Check if it is below zero
if (angle < 0.0)
angle += 2.0 * M_PI;
// Return new angle
return angle - M_PI;
}
// Get sign of number
template <typename T>
inline int sgn(T val) {
// Return sign of number
return (T(0) < val) - (val < T(0));
}
// Get rotation matrix
template <typename T>
inline array<array<T, dims>, dims> getRotationMatrix(T angle) {
// Declare rotation matrix
array<array<T, dims>, dims> R = {{{cos(angle), -sin(angle)}, {sin(angle), cos(angle)}}};
// Return
return R;
}
// Get transpose of matrix
template <typename T, size_t N1, size_t N2>
inline array<array<T, N1>, N2> Transpose(const array<array<T, N2>, N1> &Mat) {
// Declare results matrix
array<array<T, N1>, N2> ResMat;
// Loop through and switch i's and j's
for (size_t i = 0; i < N2; i++) {
for (size_t j = 0; j < N1; j++)
ResMat[i][j] = Mat[j][i];
}
// Return
return ResMat;
}
// Matrix multiply (flat matrix x vector)
template <typename T>
inline vector<T> MatMultiply(const vector<T> &LMat, const vector<T> &RVec) {
// Check they are the right size
if (LMat.size() % RVec.size() != 0)
ERROR("Matrix and vector not right size for multiplying...exiting");
// Get dimensions
size_t cols = RVec.size();
size_t rows = LMat.size() / cols;
// Declare res vector
vector<T> ResVec(rows, 0.0);
// Loop through
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
ResVec[i] += LMat[i * cols + j] * RVec[j];
}
}
// Return
return ResVec;
}
}
// OVERLOADED OPERATORS FOR ARRAYS
// Overloaded + operator for vectors
template <typename T, size_t N>
inline array<T, N> operator+(const array<T, N> &LVec, const array<T, N> &RVec) {
// Declare res vector
array<T, N> ResVec;
// Add the left and right vectors
for (size_t i = 0; i < N; i++)
ResVec[i] = LVec[i] + RVec[i];
// Return value
return ResVec;
}
// Overloaded - operator for vectors
template <typename T, size_t N>
inline array<T, N> operator-(const array<T, N> &LVec, const array<T, N> &RVec) {
// Declare res vector
array<T, N> ResVec;
// Add the left and right vectors
for (size_t i = 0; i < N; i++)
ResVec[i] = LVec[i] - RVec[i];
// Return value
return ResVec;
}
// Overloaded * operator for scalar * vector
template <typename T, size_t N>
inline array<T, N> operator*(double LScalar, const array<T, N> &RVec) {
// Declare res vector
array<T, N> ResVec;
// Add the left and right vectors
for (size_t i = 0; i < N; i++)
ResVec[i] = LScalar * RVec[i];
// Return value
return ResVec;
}
// Overloaded * operator for vector * vector
template <size_t N>
inline double operator*(const array<double, N> &LVec, const array<double, N> &RVec) {
// Declare res vector
double res = 0.0;
// Multiply the left and right vectors
for (size_t i = 0; i < N; i++)
res += LVec[i] * RVec[i];
// Return value
return res;
}
// Overloaded * operator for matrix * vector
template <typename T, size_t N1, size_t N2>
inline array<T, N2> operator*(const array<array<T, N1>, N2> &LMat, const array<T, N1> &RVec) {
// Declare res vector
array<T, N2> ResVec = {0.0};
// Multiply the matrix and vector
for (size_t i = 0; i < N2; i++) {
for (size_t j = 0; j < N1; j++) {
ResVec[i] += LMat[i][j] * RVec[j];
}
}
// Return value
return ResVec;
}
// Overloaded * operator for matrix * matrix
template <typename T, size_t N1, size_t N2, size_t N3>
inline array<array<T, N3>, N1> operator*(const array<array<T, N2>, N1> &LMat, const array<array<T, N3>, N2> &RMat) {
// Declare results matrix
array<array<T, N3>, N1> ResMat = {0.0};
// Multiply the left and right matrices
for (size_t i = 0; i < N1; i++) {
for (size_t j = 0; j < N3; j++) {
for (size_t k = 0; k < N2; k++) {
ResMat[i][j] += LMat[i][k] * RMat[k][j];
}
}
}
// Return
return ResMat;
}
// OVERLOADED OPERATORS FOR VECTORS
// Overloaded + operator for vectors
template <typename T>
inline vector<T> operator+(const vector<T> &LVec, const vector<T> &RVec) {
// Check they are the same size
if (LVec.size() != RVec.size())
ERROR("Vectors not right size for adding...exiting");
// Get rows
size_t rows = LVec.size();
// Declare res vector
vector<T> ResVec;
ResVec.reserve(rows);
// Add the left and right vectors
for (size_t i = 0; i < rows; i++)
ResVec.push_back(LVec[i] + RVec[i]);
// Return value
return ResVec;
}
// Overloaded - operator for vectors
template <typename T>
inline vector<T> operator-(const vector<T> &LVec, const vector<T> &RVec) {
// Check they are the same size
if (LVec.size() != RVec.size())
ERROR("Vectors not right size for subtracting...exiting");
// Get rows
size_t rows = LVec.size();
// Declare res vector
vector<T> ResVec;
ResVec.reserve(rows);
// Add the left and right vectors
for (size_t i = 0; i < rows; i++)
ResVec.push_back(LVec[i] - RVec[i]);
// Return value
return ResVec;
}
// Overloaded * operator for scalar * vector
template <typename T>
inline vector<T> operator*(const T LScalar, const vector<T> &RVec) {
// Get rows
size_t rows = RVec.size();
// Declare res vector
vector<T> ResVec;
ResVec.reserve(rows);
// Multiply the left and right matrices (right matrix is a column vector)
for (size_t i = 0; i < rows; i++)
ResVec.push_back(LScalar * RVec[i]);
// Return value
return ResVec;
}
// Overloaded * operator for vector * vector
template <typename T>
inline T operator*(const vector<T> &LVec, const vector<T> &RVec) {
// Check they are the same size
if (LVec.size() != RVec.size())
ERROR("Vectors not right size for multiplying...exiting");
// Get cols
size_t cols = LVec.size();
// Declare res scalar
T res = 0.0;
// Multiply vectors
for (size_t i = 0; i < cols; i++)
res += LVec[i] * RVec[i];
// Return value
return res;
}
// LAPACK interfaces
extern "C" void dgetrf_(int* dim1, int* dim2, double* a, int* lda, int* ipiv, int* info);
extern "C" void dgetrs_(char *TRANS, int *N, int *NRHS, double *A, int *LDA, int *IPIV, double *B, int *LDB, int *INFO );
#endif // UTILS_H
| 11,850
|
C++
|
.h
| 374
| 29.219251
| 142
| 0.669311
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,176
|
Objects.h
|
joconnor22_LIFE/inc/Objects.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef OBJECTS_H // OBJECTS_H
#define OBJECTS_H
// Includes
#include "params.h"
#include "IBMBody.h"
#include "IBMNode.h"
// Forward declarations
class GridClass;
// Objects class
class ObjectsClass {
// Friend classes
friend class GridClass;
friend class IBMBodyClass;
// Default constructor and destructor
public:
ObjectsClass() {gPtr = NULL; nFlex = 0; simDOFs = 0; hasIBM = false; hasFlex = false; subIt = 0; relax = relaxMax; subRes = 0.0; subNum = 0.0; subDen = 0.0;};
~ObjectsClass() {};
// Custom constructor for reading in geometries
ObjectsClass(GridClass &grid);
// Public members
public:
// Pointer to grid
GridClass *gPtr;
// Flag to say if there are IBM bodies
bool hasIBM;
// Private members
private:
// Set helper members
bool hasFlex; // Flag to say if there are flexible bodies in case
int nFlex; // Number of flexible bodies
int simDOFs; // Number of FEM DOFs in full system
// Vectors of IBM bodies and nodes
vector<IBMBodyClass> iBody;
vector<IBMNodeClass> iNode;
// Subiteration loop parameters
int subIt; // Number of iterations
double relax; // Aitken relaxation parameter
double subRes; // Residual
double subNum; // Numerator
double subDen; // Denominator
// Public methods
public:
// I/O
void writeInfo(); // Write info every tinfo time steps
void writeLog(); // Write out log info at start
void writeVTK(bool writeIBM = true); // Write IBM VTK
void writeTotalForces(); // Write out forces on bodies
void writeTips(); // Write out tip positions
void writeRestart(); // Write restart file
void readRestart(); // Read restart file
// Object routines
void objectKernel(); // Main kernel for objects
// Private methods
private:
// IBM routines
void ibmKernelInterp(); // Interpolate and force calc
void ibmKernelSpread(); // Force spread and update macro
void femKernel(); // Do FEM and update IBM positions and velocities
void recomputeObjectVals(); // Recompute objects support, ds, and epsilon
void computeEpsilon(); // Compute epsilon
// Initialisation
void removeOverlapMarkers(); // Remove overlapping markers
void initialiseObjects(); // Initialise objects
void initialDeflect(); // Give FEM body an initial deflection
// I/O
void geometryReadIn(); // Geometry read in
int getBodyIdxFromID(int id); // Get body index from the ID
void restartCleanup(); // Clean up files from previous simulations before restart
void fillEmptyVTK(); // Fill in empty VTK files
void writeEmptyVTK(string &fname); // Write empty VTK file
void deleteTipsAndForces(); // Delete tip and force data that was written after last restart
void deleteFileOutput(string fname); // Delete data from output files that was written after last restart
};
#endif // OBJECTS_H
| 3,606
|
C++
|
.h
| 88
| 38.5
| 159
| 0.735757
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,177
|
params.h
|
joconnor22_LIFE/inc/params.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef PARAMS_H // PARAMS_H
#define PARAMS_H
// Include defs
#include "defs.h"
// Set number of OMP threads (if commented then it will use system max)
//#define THREADS 12
// Set resFactor (for easily changing mesh resolution)
const int resFactor = 2;
// Simulation options
//#define CENTRAL_MOMENTS // Use central moments collision operator (BGK otherwise)
#define INLET_RAMP 2.0 // Inlet velocity ramp-up
//#define WOMERSLEY 5.0 // Womersley number for oscillating pressure gradients
#define UNI_EPSILON // Calculate epsilon over all IBM bodies at once
#define ORDERED // For deterministic reduction operations
//#define INITIAL_DEFLECT 0.01 // Set an initial deflection (fraction of L)
// Outputs
#define VTK // Write out VTK
//#define VTK_FEM // Write out the FEM VTK
#define FORCES // Write out forces on structures
#define TIPS // Write out tip positions
// Domain setup (lattice)
const int Nx = resFactor * 250 + 1; // Number of lattice sites in x-direction
const int Ny = resFactor * 41 + 1; // Number of lattice sites in y-direction
// Domain setup (physical)
const double height_p = 0.41; // Domain height (m)
const double rho_p = 1000.0; // Fluid density (kg/m^3)
const double nu_p = 0.001; // Fluid kinematic viscosity (m^2/s)
// Initial conditions
const double ux0_p = 0.0; // Initial x-velocity (m/s)
const double uy0_p = 0.0; // Initial y-velocity (m/s)
// Gravity and pressure gradient
const double gravityX = 0.0; // Gravity component in x-direction (m/s^2)
const double gravityY = 0.0; // Gravity component in y-direction (m/s^2)
const double dpdx = 0.0; // Pressure gradient in x-direction (Pa/m)
const double dpdy = 0.0; // Pressure gradient in x-direction (Pa/m)
// Boundary conditions (set to eFluid for periodic)
#define WALL_LEFT eVelocity // Boundary condition at left wall
#define WALL_RIGHT ePressure // Boundary condition at right wall
#define WALL_BOTTOM eWall // Boundary condition at bottom wall
#define WALL_TOP eWall // Boundary condition at top wall
#define PROFILE eParabolic // Profile shape (uncomment for uniform)
// Inlet conditions
const double uxInlet_p = 1.0; // Inlet x-velocity (m/s)
const double uyInlet_p = 0.0; // Inlet y-velocity (m/s)
// FEM Newmark integration parameters
const double alpha = 0.25; // Alpha parameter
const double delta = 0.5; // Delta parameter
// FSI Coupling parameters
const double relaxMax = 1.0; // Relaxation parameter (initial guess)
const double subTol = 1e-8; // Tolerance for subiterations
// Set omega by three different methods (comment/uncomment)
// Set omega directly
//const double omega = 1.875;
//const double tStep = pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0) * (1.0 - 0.5 * omega) / (nu_p * omega);
// Set time step
const double tStep = 0.001 / (resFactor * resFactor);
const double omega = 1.0 / (nu_p * tStep / (pow(1.0 / sqrt(3.0), 2.0) * pow(height_p / (Ny - 1), 2.0)) + 0.5);
// Set lattice velocity
//const double uLB = (2.0 / 3.0) * 0.2 * 1.0 / sqrt(3.0);
//const double omega = 1.0 / (uLB * (Ny-1) / (uxInlet_p * height_p / (3.0 * nu_p)) + 0.5);
// Number of time steps and how often to write out
const int nSteps = 500;
const int tinfo = nSteps / 50;
const int tVTK = nSteps / 10;
const int tRestart = nSteps / 5;
// Reference values
const double ref_nu = nu_p; // Reference kinematic viscosity (m^2/s)
const double ref_rho = rho_p; // Reference density (kg/m^3)
const double ref_P = 0.0; // Reference pressure (Pa)
const double ref_L = 0.1; // Reference length (m)
const double ref_U = uxInlet_p; // Reference velocity (m/s)
// Precision for ASCII output
const int PRECISION = 10;
#endif // PARAMS_H
| 4,498
|
C++
|
.h
| 88
| 49.295455
| 120
| 0.708618
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,178
|
Grid.h
|
joconnor22_LIFE/inc/Grid.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef GRID_H // GRID_H
#define GRID_H
// Includes
#include "defs.h"
// Forward declarations
class ObjectsClass;
// Grid class
class GridClass {
// Friend classes
friend class ObjectsClass;
friend class IBMNodeClass;
// Default constructor and destructor
public:
GridClass();
~GridClass() {};
// Public members
public:
// Grid values
int t; // Time step
int tOffset; // Offset time (for restarts)
// Object pointer
ObjectsClass *oPtr; // Pointer to objects class
// Scaling parameters
double Dx; // Length scaling
double Dt; // Time scaling
double Dm; // Mass scaling
double Drho; // Density scaling
// Restart flag
bool restartFlag; // Restart flag
// Big or little endian
bool bigEndian; // For binary output
// Private members
private:
// Lattice parameters
double c_s; // Speed of sound
array<double, nVels> w; // Weightings
array<int, nVels * dims> c; // Direction vectors
array<int, nVels> opposite; // Opposite vectors
// Grid values
double tau; // Relaxation time
double nu; // Lattice viscosity
// Flattened kernel arrays
vector<double> u; // Velocity
vector<double> u_n; // Velocity (start of timestep)
vector<double> rho; // Density
vector<double> rho_n; // Density (start of timestep)
vector<double> force_xy; // Cartesian force (pressure and gravity)
vector<double> force_ibm; // Cartesian force (IBM)
vector<eLatType> type; // Lattice type matrix
vector<double> f; // Populations
vector<double> f_n; // Populations (start of timestep)
// Boundary conditions
vector<int> BCVec; // Vector of site IDs to apply boundary conditions
vector<double> delU; // Convective speed through boundary
// Helper arrays
vector<double> u_in; // Inlet velocity profile
vector<double> rho_in; // Inlet density profile
// Timings
double startTime; // Start time when clock is called
double loopTime; // Average loop time
// Public methods
public:
// LBM methods
void solver(); // Main solver
// I/O
void writeInfo(); // Write info every tinfo time steps
void writeLog(); // Write log data at start
void writeVTK(); // Write grid VTK
void writeRestart(); // Write restart file
void readRestart(); // Read restart file
void startClock(); // Start the clock for getting MLUPS
// Private methods
private:
// LBM methods
void lbmKernel(); // Main LBM kernel
void streamCollide(int i, int j, int id); // Stream and collide in one go (push algorithm)
double equilibrium(int id, int v); // Equilibrium function
double latticeForce(int id, int v); // Discretise lattice force (BGK only)
void macroscopic(int id); // Compute macroscopic quantities
void applyBCs(int i, int j, int id); // Apply boundary conditions
void convectiveSpeed(); // Get convective speed through right boundary
void convectiveBC(int j, int id); // Convective BC
void regularisedBC(int i, int j, int id,
array<int, dims> &normalVector, eDirectionType normalDirection); // Regularised BC
// Initialisation
void initialiseGrid(); // Initialise grid values
// Helper routines
array<int, dims> getNormalVector(int i, int j, eDirectionType &normalDirection); // Get normal vector for boundary site
double getRampCoefficient(); // Get inlet ramp coefficient
};
#endif // GRID_H
| 4,292
|
C++
|
.h
| 105
| 38.380952
| 120
| 0.692974
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,179
|
FEMNode.h
|
joconnor22_LIFE/inc/FEMNode.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef FEMNODE_H // FEMNODE_H
#define FEMNODE_H
// Includes
#include "defs.h"
// FEM node class
class FEMNodeClass {
// Friend classes
friend class FEMElementClass;
friend class FEMBodyClass;
friend class ObjectsClass;
// Default constructor and destructor
public:
FEMNodeClass() {angle0 = 0; angle = 0;};
~FEMNodeClass() {};
// Custom constructor for building nodes
FEMNodeClass(int ID, const array<double, dims> &position, double angleRad);
// Private members
private:
// Values
array<double, dims> pos0; // Initial position of FEM node
array<double, dims> pos; // Current position of FEM node
double angle0; // Initial angles of FEM node
double angle; // Current angles of FEM node
array<int, nodeDOFs> DOFs; // Global DOFs for this node
};
#endif // FEMNODE_H
| 1,565
|
C++
|
.h
| 40
| 36.225
| 76
| 0.747521
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,180
|
defs.h
|
joconnor22_LIFE/inc/defs.h
|
/*
LIFE: Lattice boltzmann-Immersed boundary-Finite Element
Copyright (C) 2019 Joseph O'Connor
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, either version 3 of the License, or
(at your option) any later version.
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://www.gnu.org/licenses/>.
*/
#ifndef DEFS_H // DEFS_H
#define DEFS_H
// Include headers and set namespace
#include <iostream>
#include <iomanip>
#include <cmath>
#include <omp.h>
#include <boost/filesystem.hpp>
using namespace std;
// Version and release date
const string version = "v1.0.3";
const string date = "10th June 2020";
// Number of dimensions and lattice velocities
const int dims = 2;
const int nVels = 9;
// IBM support buffer size
const int suppSize = 9;
// Set default values for 2D beam
const int nodeDOFs = 3;
const int elementNodes = 2;
const int elementDOFs = elementNodes * nodeDOFs;
// Enumerations
enum eDirectionType {eX, eY};
enum eFlexibleType {eFlexible, eRigid};
enum eBCType {eClamped, eSupported};
enum eBodyType {eCircle, eFilament};
enum eLatType {eFluid, eWall, eVelocity, eFreeSlip, ePressure, eConvective};
enum eProfileType {eParabolic, eShear, eBoundaryLayer};
// Macros
#define SQ(x) ((x) * (x))
#define TH(x) ((x) * (x) * (x))
#define QU(x) ((x) * (x) * (x) * (x))
#define ERROR Utils::errorExit
#define WARN Utils::warning
#endif // DEFS_H
| 1,819
|
C++
|
.h
| 49
| 34.897959
| 76
| 0.748578
|
joconnor22/LIFE
| 38
| 16
| 6
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,182
|
intropage.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/intropage.cpp
|
#include "intropage.h"
#include "ui_intropage.h"
#include <QtDebug>
IntroPage::IntroPage(QWidget *parent) :
QLightBoxWidget(parent),
ui(new Ui::IntroPage)
{
ui->setupUi(this);
// connect(this,&IntroPage::PlayClicked,main,&UIMainWindow::onPlayButtonClicked);
// connect(this,&IntroPage::HelpClicked,main,&UIMainWindow::onHelpButtonClicked);
// connect(this,&IntroPage::ExitClicked,main,&UIMainWindow::onExitButtonClicked);
// connect(this,&IntroPage::AboutClicked,main,&UIMainWindow::onAboutButtonClicked);
//m_timer = new QTimer;
//connect(m_timer,&QTimer::timeout,this,&IntroPage::repaintWidget);
}
//void IntroPage::AutoUpdate(const bool &x)
//{
// if(x){
// m_timer->start(10);
// }else{
// m_timer->stop();
// }
//}
IntroPage::~IntroPage()
{
delete ui;
}
void IntroPage::on_m_PlayButton_clicked()
{
emit PlayClicked();
}
void IntroPage::on_m_ExitButton_clicked()
{
emit ExitClicked();
}
void IntroPage::on_m_AboutButton_clicked()
{
//qDebug()<<"Hello";
emit AboutClicked();
}
void IntroPage::on_m_HelpButton_clicked()
{
emit HelpClicked();
}
void IntroPage::repaintWidget()
{
resize(parentWidget()->size());
repaint();
//QApplication::processEvents();
//update();
}
| 1,280
|
C++
|
.cpp
| 51
| 22.627451
| 86
| 0.695222
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,183
|
graphicsview.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/graphicsview.cpp
|
#include "graphicsview.h"
GraphicsView::GraphicsView(QWidget *parent):QGraphicsView(parent)
{
setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
setOptimizationFlag(GraphicsView::DontSavePainterState);
setCacheMode(QGraphicsView::CacheBackground);
//setDragMode(QGraphicsView::ScrollHandDrag);
}
void GraphicsView::wheelEvent(QWheelEvent *event)
{
//this->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
// Scale the view / do the zoom
// GraphicsView::wheelEvent(event);
double scaleFactor = 1.15;
//int level_of_zoom = 5;
if( /*m_max <120*level_of_zoom&&*/event->delta()>0){
//m_min -= 120;
//m_max += event->delta();
//setSceneRect(0,0,size().height()*scaleFactor,size().width()*scaleFactor);
this->scale(scaleFactor, scaleFactor);
}
if(/* m_min < 120*level_of_zoom&&*/event->delta()<0){
//m_max -= 120;
//m_min -= event->delta();
//setSceneRect(0,0,size().height()/scaleFactor,size().width()/scaleFactor);
this->scale(1.0 / scaleFactor, 1.0 / scaleFactor);
}
}
//void GraphicsView::mouseMoveEvent(QMouseEvent *event)
//{
// QGraphicsView::mouseMoveEvent(event);
// //qDebug()<<"Actual Position "<<event->pos()<<"Scene Pos "<<event->screenPos();
// if(event->buttons() == Qt::RightButton){
// this->setCursor(Qt::SizeAllCursor);
// }
// if(event->buttons() == Qt::LeftButton){
// if(dynamic_cast<Vehicle*>(this->scene()->itemAt(this->mapToScene(event->pos()),this->transform()))){
// this->setCursor(Qt::OpenHandCursor);
// //qDebug()<<event->pos();
// }
// }
//}
//void GraphicsView::mouseReleaseEvent(QMouseEvent *event)
//{
// QGraphicsView::mouseReleaseEvent(event);
// this->setCursor(Qt::ArrowCursor);
//}
/*void GraphicsView::resizeEvent(QResizeEvent *event)
{
setSceneRect(event->size().width()/2,event->size().height()/2,event->size().width(),event->size().height());
qDebug()<<sceneRect();
qDebug()<<event->size();
}*/
void GraphicsView::Initializer()
{
fitInView(scene()->sceneRect(),Qt::KeepAspectRatio);
}
//void GraphicsView::mousePressEvent(QMouseEvent *event)
//{
// QGraphicsView::mousePressEvent(event);
// qDebug()<<"Hello";
//}
| 2,298
|
C++
|
.cpp
| 62
| 33.83871
| 112
| 0.658131
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,184
|
helpwidget.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/helpwidget.cpp
|
#include "helpwidget.h"
#include "ui_helpwidget.h"
HelpWidget::HelpWidget(QWidget *parent)
:QWidget(parent)
,ui(new Ui::HelpWidget)
{
ui->setupUi(this);
//ui->demo_widget->setTransformationAnchor(QGraphicsView::AnchorViewCenter);
m_demo = new RoadIntersectionSimulation(ui->demo_widget);
m_demo->initialize();
//ui->demo_widget->centerOn(ui->demo_widget->width()/2,ui->demo_widget->height()/2);
ui->demo_widget->scale(0.55,0.55);
//qDebug()<<ui->demo_widget->rect();
}
void HelpWidget::startDemo()
{
m_demo->startDemo();
}
void HelpWidget::stopDemo()
{
m_demo->pauseSimulation();
}
HelpWidget::~HelpWidget()
{
delete ui;
}
void HelpWidget::on_next_button_clicked()
{
int totalPage = ui->stackedWidget->count();
int current = ui->stackedWidget->currentIndex();
if(current == totalPage - 1){
startDemo();
ui->stackedWidget->setCurrentIndex(0);
}else{
stopDemo();
ui->stackedWidget->setCurrentIndex(current + 1);
}
}
void HelpWidget::on_back_button_clicked()
{
int totalPage = ui->stackedWidget->count();
int current = ui->stackedWidget->currentIndex();
if(current - 1 == 0){
startDemo();
}else{
stopDemo();
}
if(current == 0){
ui->stackedWidget->setCurrentIndex(totalPage - 1);
}else{
ui->stackedWidget->setCurrentIndex(current - 1);
}
}
RoadIntersectionSimulation *HelpWidget::demo() const
{
return m_demo;
}
| 1,492
|
C++
|
.cpp
| 57
| 21.947368
| 88
| 0.663143
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,185
|
mainwindow.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "UI/simulationcontrolwidget.h"
MainWindow::MainWindow(QWidget *parent)
:QMainWindow(parent)
,ui(new Ui::MainWindow)
,m_simulate_state(false)
,m_sightseeing(false)
,m_visualize_state(false)
{
ui->setupUi(this);
setWindowTitle ("Intersection Road Simulation and Visulization");
setWindowIcon(QIcon(":/icon/Image/Logo-AI.png"));
set_up ();
ui->stackedWidget->setCurrentIndex(0);
m_machine_state = new QTimer();
this->connect(m_machine_state,SIGNAL(timeout()),this,SLOT(check_state()));
//QObject::connect(m_machine_state,SIGNAL(timeout()),m_scene,SLOT(advance()));
m_machine_state->start(TIME_UNIT);
ui->m_visualize_frame->hide();
ui->m_visualzie_widget->setController(m_scene->getController());
//ui->m_visualzie_widget->setEtimer(m_controller->getTimer());
//ui->m_visualzie_widget->setMainWindows(this);
//ui->m_visualzie_widget->initialize();
//qDebug()<<"Passed";
SimulationControlWidget *control = new SimulationControlWidget;
control->show();
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if(event->key () == Qt::Key_Space){
if(m_simulate_state){
on_pause_clicked ();
}else{
on_play_clicked ();
}
}
}
void MainWindow::turnOnSimulationState()
{
m_simulate_state = true;
}
void MainWindow::turnOffSimulationState()
{
m_simulate_state = false;
}
GENMETHOD MainWindow::getCurrentMethod() const
{
if(ui->m_3_lanes->isChecked()){
return GENMETHOD::GEN_3;
}
if(ui->m_5_lanes->isChecked()){
return GENMETHOD::GEN_5;
}
if(ui->m_no_turn->isChecked()){
return GENMETHOD::NO_TURN;
}
return GENMETHOD::NO_TURN;
}
VEHICLEMETHOD MainWindow::getCurrentVehicleMethod() const
{
if(ui->m_go_though->isChecked()){
return VEHICLEMETHOD::GO_THROUGH;
}
return VEHICLEMETHOD::SIGHTSEEING;
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::check_state()
{
// qDebug()<<"Simulation State"<<m_simulate_state;
/////////////////
/// \brief items
///Getting Item in Scene and Cast to Vehicles
////////////////
//QList<QGraphicsItem *> items = m_scene->items();
if(m_simulate_state){
m_scene->advance();
QList<Vehicle *> car = m_scene->getVehicle();
//QList<TrafficDetector *> detector = m_scene->getDetector();
for(int i = 0; i<car.size() ; ++i){
//car.at(i)->turnOnEngine();
if(this->m_sightseeing){
car.at(i)->turnOnSightSeeing();
}else{
car.at(i)->turnOffSightSeeing();
}
if(car.at(i)->isDeletable()){
//m_scene->removeItem(car.at(i));
m_scene->removeVehicle(car.at(i));
// m_scene->removeItem(car.at(i));
// delete car.at(i);
}
}
//m_controller->startTrafficLightAll();
if(m_visualize_state){
//double t1 = omp_get_wtime();
ui->m_visualzie_widget->update_all();
//double t2 = omp_get_wtime();
//qDebug()<<"CTim"<<t2-t1;
}
}else{
//m_scene->trunOffAllCar();
ui->m_simulation_control_widget->generator()->stopGenerator();
}
// for(int i = 0 ; i < items.size() ; ++i){
// Vehicle *v = dynamic_cast<Vehicle *>(items.at(i));
// TrafficDetector *d = dynamic_cast<TrafficDetector *>(items.at(i));
// if(v){
// car.append(v);
// }
// if(d){
// detector.append(d);
// }
// }
//qDebug()<<car.size();
//WorkerThread *thread = new WorkerThread(ui->m_visualzie_widget,this);
//connect(thread, &WorkerThread::finished, thread, &QObject::deleteLater);
//thread->start();
// for(int i = 0 ; i < detector.size() ; ++i){
// if(m_simulate_state){
// //car.at(i)->setActionOn();
// detector.at(i)->startEngine();
// }else{
// //car.at(i)->setActionOff();
// detector.at(i)->stopEngine();
// }
// }
//qDebug()<<"Number"<<m_scene->getVehicle().length();
}
void MainWindow::on_actionExit_triggered()
{
QApplication::quit();
}
void MainWindow::on_play_clicked()
{
m_simulate_state = true;
}
void MainWindow::on_back_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_open_simulation_button_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_exit_clicked()
{
QApplication::quit();
}
void MainWindow::on_reset_clicked()
{
// m_car_list_1->clear ();
// ui->m_simulation_control_widget->generator()->stopGenerator();
// this->turnOffSimulationState();
// for(int i = 0 ; i < m_scene->getVehicle().length() ; i++){
// delete m_scene->getVehicle().at(i);
// }
ui->m_simulation_control_widget->stopGenerating();
ui->tool_panel->setEnabled(false);
ui->tool_panel->update();
m_simulate_state = false;
m_visualize_state = false;
m_scene->getController()->stopTrafficLightAll();
m_scene->resetScene();
}
void MainWindow::on_pause_clicked()
{
m_simulate_state = false;
}
void MainWindow::on_stop_clicked()
{
// m_car_list_1->first ()->get_timer ()->stop ();
}
void MainWindow::set_up()
{
//m_scene->addText ("1",QFont("Century",18))->setPos (450,180);
//m_scene->addText ("2",QFont("Century",18))->setPos (150,180);
//m_scene->addText ("3",QFont("Century",18))->setPos (180,380);
//m_scene->addText ("4",QFont("Century",18))->setPos (400,420);
//Add path for vehicle
m_scene->setSceneRect(0,0,800,600);
// m_traffic_light = new QList<TrafficLight *>();
// for(int i = 0 ; i < 4 ; ++i){
// m_traffic_light->append(new TrafficLight());
// m_traffic_light->at(i)->setUpFacilities();
// }
// m_controller->setTraffic_light(m_traffic_light);
// //Arrange Traffic Light
// //TrafficLight 1
// m_traffic_light->at(0)->setPos(400,380);
// m_traffic_light->at(0)->setRegion(region::REGION_S_N);
// //TrafficLight 2
// m_traffic_light->at(1)->setRotation(90);
// m_traffic_light->at(1)->setPos(260,380);
// m_traffic_light->at(1)->setRegion(region::REGION_W_E);
// //TrafficLight 3
// m_traffic_light->at(2)->setPos(250,240);
// m_traffic_light->at(2)->setRotation(180);
// m_traffic_light->at(2)->setRegion(region::REGION_N_S);
// m_traffic_light->at(2)->setTransform(QTransform::fromScale(1, -1));
// //TrafficLight 4
// m_traffic_light->at(3)->setPos(410,230);
// m_traffic_light->at(3)->setRotation(270);
// m_traffic_light->at(3)->setRegion(region::REGION_E_W);
// //m_traffic_light->at(3)->setTransform(QTransform::fromScale(-1, 1));
// for(int i = 0 ; i < m_traffic_light->size() ; ++i){
// for(int j = 0 ; j < m_traffic_light->at(i)->getLight()->size() ; j++){
// m_traffic_light->at(i)->getLight()->at(j)->setScale(0.8);
// }
// }
//Add Control Widget
// m_control_sim = new QGraphicsProxyWidget();
// m_control_sim->setWidget (ui->m_simulation_control_widget);
//m_control_sim->setFlags (QGraphicsItem::ItemIsMovable);
//m_control_sim->setFlags (QGraphicsItem::ItemIsFocusable);
//m_control_sim->setFlags (QGraphicsItem::ItemIsPanel);
// m_control_sim->setPos (500,0);
// m_scene->addItem (m_control_sim);
// m_data_control = new QGraphicsProxyWidget();
//m_data_control->setFlags (QGraphicsItem::ItemIsSelectable);
// m_data_control->setWidget (m_data_widget);
// m_scene->addItem (m_data_control);
// m_data_control->setPos (500,400);
//AddSecen
ui->graphicsView->setScene(m_scene);
ui->graphicsView->setResizeAnchor(QGraphicsView::AnchorViewCenter);
ui->graphicsView->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
ui->graphicsView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
// ui->graphicsView->Initializer();
//ui->m_simulation_control_widget = new SimulationControl(this);
ui->m_simulation_control_widget->initialize(this);
}
void MainWindow::set_up_demo()
{
}
void MainWindow::on_m_road_check_button_toggled(bool checked)
{
}
void MainWindow::on_m_detector_button_clicked(bool checked)
{
if(checked){
m_scene->getController()->turnOnDetector();
}else{
m_scene->getController()->turnOffDetector();
}
}
void MainWindow::on_m_sightseeing_button_clicked(bool checked)
{
if(checked){
m_sightseeing = true;
}else{
m_sightseeing = false;
}
}
void MainWindow::on_m_aboutus_button_clicked()
{
ui->stackedWidget->setCurrentIndex(3);
}
void MainWindow::on_m_manul_control_button_clicked(bool checked)
{
if(checked){
m_scene->getController()->manualControl();
}else{
m_scene->getController()->startTrafficLightAll();
}
}
void MainWindow::on_m_5_lanes_clicked()
{
ui->m_simulation_control_widget->setMethod(GENMETHOD::GEN_5);
}
void MainWindow::on_m_3_lanes_clicked()
{
ui->m_simulation_control_widget->setMethod(GENMETHOD::GEN_3);
}
SimulationScene *MainWindow::scene() const
{
return m_scene;
}
void MainWindow::on_m_no_traffic_clicked(bool checked)
{
showTraffic(checked);
}
bool MainWindow::getSimulate_state() const
{
return m_simulate_state;
}
void MainWindow::showTraffic(bool checked)
{
if(checked){
m_scene->showTrafficLight();
}else{
m_scene->HideTrafficLight();
}
}
void MainWindow::set3LaneCheck(const bool &b)
{
ui->m_3_lanes->setChecked(b);
}
void MainWindow::setGenMethod(const GENMETHOD &gen)
{
ui->m_simulation_control_widget->generator()->setMethod(gen);
}
void MainWindow::setGoThroguht(const bool &b)
{
ui->m_go_though->setChecked(b);
}
void MainWindow::setSimMode(const VEHICLEMETHOD &m)
{
ui->m_simulation_control_widget->generator()->setMode(m);
}
void MainWindow::setTrafficState(const bool &b)
{
ui->m_no_traffic->setChecked(b);
}
TrafficController *MainWindow::getController() const
{
return m_scene->getController();
}
void MainWindow::on_m_no_turn_clicked()
{
ui->m_simulation_control_widget->generator()->setMethod(GENMETHOD::NO_TURN);
}
void MainWindow::on_m_go_though_clicked(bool checked)
{
if(checked){
ui->m_simulation_control_widget->generator()->setMode(VEHICLEMETHOD::GO_THROUGH);
m_scene->setGoThrough(true);
}else{
ui->m_simulation_control_widget->generator()->setMode(VEHICLEMETHOD::SIGHTSEEING);
m_scene->setGoThrough(false);
}
}
void MainWindow::on_m_drop_in_clicked()
{
// m_scene->addItem(VehiclesGenerator::getRightTurningVehicle(region::REGION_E_W,VEHICLEMETHOD::SIGHTSEEING));
// m_scene->getVehicle().at(0)->turnOnEngine();
// this->turnOnSimulationState();
}
void MainWindow::on_actionPNG_triggered()
{
QString fileName = QFileDialog::getSaveFileName(this,
tr("Export PNG file"), "",
tr("Portable Network Graphics (*.png);;All Files (*)"));
if (fileName.isEmpty())
return;
else {
QPixmap pixmap = QWidget::grab(ui->graphicsView->viewport()->rect());
QPainter printer(&pixmap);
printer.setRenderHint(QPainter::Antialiasing);
ui->graphicsView->render(&printer,pixmap.rect(),ui->graphicsView->viewport()->rect(),Qt::KeepAspectRatio);
printer.end();
pixmap.save(fileName);
}
}
void MainWindow::on_m_tool_panel_check_box_clicked(bool checked)
{
if(checked){
ui->m_tool_panel_frame->show();
}else{
ui->m_tool_panel_frame->hide();
}
}
void MainWindow::on_m_visualize_panel_check_box_clicked(bool checked)
{
if(checked){
ui->m_visualize_frame->show();
m_visualize_state = true;
}else{
ui->m_visualize_frame->hide();
m_visualize_state = false;
}
}
void MainWindow::on_m_back_button_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_m_only_turn_clicked()
{
ui->m_simulation_control_widget->generator()->setMethod(GENMETHOD::ONLY_TURN);
}
| 12,224
|
C++
|
.cpp
| 383
| 27.801567
| 118
| 0.637337
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,186
|
uimainwindow.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/uimainwindow.cpp
|
#include "uimainwindow.h"
#include "ui_uimainwindow.h"
UIMainWindow::UIMainWindow(QWidget *parent)
:QWidget(parent)
,ui(new Ui::UIMainWindow)
,m_time_frame(0)
{
ui->setupUi(this);
ui->graphicsView->setResizeAnchor(QGraphicsView::AnchorViewCenter);
ui->graphicsView->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
ui->graphicsView->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
m_Simulation = new RoadIntersectionSimulation(ui->graphicsView);
connect(m_Simulation,&RoadIntersectionSimulation::updatedOneFrame,
this,&UIMainWindow::updateStatus);
//m_Simulation->initialize(ui->graphicsView);
m_Demo = new RoadIntersectionSimulation(ui->m_demo_widget_1);
m_Demo->initialize();
m_Demo->startDemo();
m_intro_page = new IntroPage(ui->m_first_page);
//m_intro_page->AutoUpdate(true);
connect(m_Demo,&RoadIntersectionSimulation::updatedOneFrame,
m_intro_page,&IntroPage::repaintWidget);
connect(m_intro_page,&IntroPage::PlayClicked,
this,&UIMainWindow::onPlayButtonClicked);
connect(m_intro_page,&IntroPage::AboutClicked,
this,&UIMainWindow::onAboutButtonClicked);
connect(m_intro_page,&IntroPage::HelpClicked,
this,&UIMainWindow::onHelpButtonClicked);
connect(m_intro_page,&IntroPage::ExitClicked,
this,&UIMainWindow::onExitButtonClicked);
m_setup = new SimulationSetup;
connect(m_setup,&SimulationSetup::inputReady,
m_Simulation,&RoadIntersectionSimulation::initializeFrominput);
connect(m_setup,&SimulationSetup::onRandomClicked,
m_Simulation,&RoadIntersectionSimulation::initializeFrominput);
connect(m_setup,&SimulationSetup::onHelpClicked,
this,&UIMainWindow::onHelpButtonClicked);
// ui->m_visualize_panel->setController(m_Simulation->Scene()->getController());
// connect(m_Simulation,&RoadIntersectionSimulation::updatedOneFrame,
// ui->m_visualize_panel,&VisualizePanel::update_all);
}
UIMainWindow::~UIMainWindow()
{
delete ui;
delete m_Simulation;
delete m_Demo;
delete m_intro_page;
}
void UIMainWindow::onExitButtonClicked()
{
QApplication::exit();
}
void UIMainWindow::onAboutButtonClicked()
{
ui->m_stacked_widget->setCurrentIndex(1);
m_Demo->pauseSimulation();
}
void UIMainWindow::onPlayButtonClicked()
{
ui->m_stacked_widget->setCurrentIndex(4);
m_Demo->pauseSimulation();
if(m_Simulation->State() == SimulationState::UNINITIALIZED){
//EnableSimulationButton(false,false,false,false);
//ui->m_simulation_page->setEnabled(false);
m_setup->show();
}
}
void UIMainWindow::onHelpButtonClicked()
{
ui->m_stacked_widget->setCurrentIndex(2);
m_Demo->pauseSimulation();
ui->help_widget->startDemo();
}
void UIMainWindow::EnableSimulationButton(const bool &play,
const bool &pause,
const bool &stop,
const bool &restart)
{
ui->m_simulation_play_button->setEnabled(play);
ui->m_simulation_pause_button->setEnabled(pause);
ui->m_simulation_restart_button->setEnabled(restart);
ui->m_simulation_stop_button->setEnabled(stop);
}
void UIMainWindow::updateStatus()
{
m_time_frame++;
}
void UIMainWindow::on_m_about_back_button_clicked()
{
ui->m_stacked_widget->setCurrentIndex(0);
m_Demo->startSimulation();
}
void UIMainWindow::on_m_help_back_button_clicked()
{
ui->m_stacked_widget->setCurrentIndex(0);
ui->help_widget->stopDemo();
m_Demo->startSimulation();
}
void UIMainWindow::on_m_simulation_back_icon_clicked()
{
ui->m_stacked_widget->setCurrentIndex(0);
m_Simulation->pauseSimulation();
m_Demo->startSimulation();
}
void UIMainWindow::on_m_setting_back_icon_clicked()
{
ui->m_stacked_widget->setCurrentIndex(0);
}
void UIMainWindow::on_m_simulation_play_button_clicked()
{
m_Simulation->startSimulation();
ui->m_simulation_play_button->setEnabled(false);
ui->m_simulation_pause_button->setEnabled(true);
}
void UIMainWindow::on_m_simulation_pause_button_clicked()
{
m_Simulation->pauseSimulation();
ui->m_simulation_play_button->setEnabled(true);
ui->m_simulation_pause_button->setEnabled(false);
}
void UIMainWindow::on_m_simulation_restart_button_clicked()
{
m_Simulation->stopSimulation();
m_setup->show();
}
void UIMainWindow::on_m_simulation_stop_button_clicked()
{
m_Simulation->stopSimulation();
}
void UIMainWindow::on_show_road_check_box_stateChanged(int arg1)
{
if(arg1 == Qt::Checked){
m_Simulation->showRoad();
}else if(arg1 == Qt::Unchecked){
m_Simulation->hideRoad();
}
}
void UIMainWindow::on_show_detectors_check_box_stateChanged(int arg1)
{
if(arg1 == Qt::Checked){
m_Simulation->showDetectors();
}else if(arg1 == Qt::Unchecked){
m_Simulation->hideDetectors();
}
}
void UIMainWindow::on_show_vehicles_vision_check_box_stateChanged(int arg1)
{
if(arg1 == Qt::Checked){
m_Simulation->showVehiclesVision();
}else if(arg1 == Qt::Unchecked){
m_Simulation->hideVehiclesVision();
}
}
void UIMainWindow::on_show_traffic_light_check_box_stateChanged(int arg1)
{
if(arg1 == Qt::Checked){
m_Simulation->showTraffic();
}else if(arg1 == Qt::Unchecked){
m_Simulation->hideTraffic();
}
}
void UIMainWindow::on_m_3_lanes_button_clicked()
{
m_Simulation->setGenerationMethod(GENMETHOD::GEN_3);
}
void UIMainWindow::on_m_5_lanes_button_clicked()
{
m_Simulation->setGenerationMethod(GENMETHOD::GEN_5);
}
void UIMainWindow::on_m_no_turn_button_clicked()
{
m_Simulation->setGenerationMethod(GENMETHOD::NO_TURN);
}
void UIMainWindow::on_m_turn_only_button_clicked()
{
m_Simulation->setGenerationMethod(GENMETHOD::ONLY_TURN);
}
void UIMainWindow::on_m_go_through_check_box_stateChanged(int arg1)
{
if(arg1 == Qt::Checked){
m_Simulation->turnOnGoThrough();
}else if(arg1 == Qt::Unchecked){
m_Simulation->turnOffGoThrough();
}
}
| 6,173
|
C++
|
.cpp
| 185
| 28.551351
| 83
| 0.703567
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,187
|
simulationscene.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/simulationscene.cpp
|
#include "simulationscene.h"
SimulationScene::SimulationScene(QGraphicsScene *parent):QGraphicsScene (parent)
{
//Add Road and Background to scene
//QGraphicsPixmapItem *m_picture = new QGraphicsPixmapItem(QPixmap(":/image/Image/road-image.png")/*.scaled (600,600)*/);
QGraphicsSvgItem *m_terrain = new QGraphicsSvgItem(":/image/Image/terrain.svg");
m_terrain->setFlag(QGraphicsItem::ItemIsMovable,false);
m_terrain->setFlag(QGraphicsItem::ItemIsSelectable,false);
m_path = new QGraphicsSvgItem(":/image/Image/road-path.svg");
m_path->setFlag(QGraphicsItem::ItemIsMovable,false);
m_path->setFlag(QGraphicsItem::ItemIsSelectable,false);
//m_terrain->moveBy (-60,0);
//m_picture->moveBy(30,0);
m_path->moveBy (15,-15);
m_path->setScale (0.7);
m_path->setZValue (-1);
m_path->setOpacity(0);
//m_picture->setZValue (-2);
m_terrain->setZValue (-3);
m_terrain->moveBy(-70,5);
this->addItem (m_terrain);
this->addItem (m_path);
setItemIndexMethod(QGraphicsScene::NoIndex);
setBackgroundBrush (Qt::white);
m_Controller = new TrafficController;
this->addItem(m_Controller);
}
uint SimulationScene::getNumber(const region &x) const
{
uint size = 0;
QList<QGraphicsItem *> v = this->items();
QList<Vehicle *> p;
for(int i = 0 ; i < v.size() ; ++i){
if(dynamic_cast<Vehicle *>(v.at(i))){
p.append(dynamic_cast<Vehicle *>(v.at(i)));
}
}
for(int i = 0 ; i < p.size() ; ++i){
if(p.at(i)->getRegion() == x){
size++;
}
}
return size;
}
QList<Vehicle *> SimulationScene::getVehicle() const
{
return m_Vehicles;
}
QList<Vehicle *> SimulationScene::getVehicle(const region &r) const
{
QList<Vehicle* > ve;
for(size_t i = 0 ; i < m_Vehicles.size() ; ++i ){
if(m_Vehicles.at(i)->getRegion() == r){
ve.append(m_Vehicles.at(i));
}
}
return ve;
}
QList<TrafficDetector *> SimulationScene::getDetector() const
{
return m_Controller->getDetector();
}
void SimulationScene::addVehicle(Vehicle *vehicle)
{
m_Vehicles.append(vehicle);
this->addItem(vehicle);
}
void SimulationScene::removeVehicle(Vehicle *ve)
{
m_Vehicles.removeOne(ve);
this->removeItem(ve);
delete ve;
}
TrafficLight * SimulationScene::getTrafficLight(const region &r) const
{
return m_Controller->getTrafficLight(r);
}
QList<TrafficLight *> SimulationScene::getTrafficLight() const
{
return m_Controller->getTraffic_light();
}
void SimulationScene::setGoThrough(bool x)
{
if(x){
for(int i = 0 ; i < m_Vehicles.size() ; ++i){
m_Vehicles.at(i)->setMode(VEHICLEMETHOD::GO_THROUGH);
}
}else{
for(int i = 0 ; i < getVehicle().size() ; ++i){
m_Vehicles.at(i)->setMode(VEHICLEMETHOD::SIGHTSEEING);
}
}
}
void SimulationScene::resetScene()
{
for(int i = 0 ; i < this->getVehicle().size() ; i++){
this->removeItem(this->getVehicle().at(i));
//delete this->getVehicle().at(i);
}
for(int i = 0 ; i < this->getTrafficLight().size() ; i++){
this->removeItem(this->getTrafficLight().at(i));
}
}
void SimulationScene::showTrafficLight()
{
for(int i = 0 ; i < m_Controller->getTraffic_light().size() ; ++i){
m_Controller->getTraffic_light().at(i)->setMode(TRAFFICMODE::HAS_SIGNAL);
this->addItem(m_Controller->getTraffic_light().at(i));
}
}
void SimulationScene::HideTrafficLight()
{
for(int i = 0 ; i < m_Controller->getTraffic_light().size() ; ++i){
m_Controller->getTraffic_light().at(i)->setMode(TRAFFICMODE::NO_SIGNAL);
this->removeItem(m_Controller->getTraffic_light().at(i));
}
}
void SimulationScene::showIntersectionPath(const bool &show)
{
if(show){
m_path->setOpacity(100);
}else{
m_path->setOpacity(0);
}
}
void SimulationScene::showDetectors()
{
m_Controller->showDetector();
}
void SimulationScene::hideDetectors()
{
m_Controller->hideDetector();
}
void SimulationScene::turnOffDetectors()
{
m_Controller->turnOffDetector();
}
void SimulationScene::turnOnDetectors()
{
m_Controller->turnOnDetector();
}
void SimulationScene::showVehiclesVision()
{
for(int i = 0 ; i < m_Vehicles.size() ; ++i){
m_Vehicles.at(i)->turnOnSightSeeing();
}
}
void SimulationScene::hideVehiclesVision()
{
for(int i = 0 ; i < m_Vehicles.size() ; ++i){
m_Vehicles.at(i)->turnOffSightSeeing();
}
}
TrafficController *SimulationScene::getController() const
{
return m_Controller;
}
void SimulationScene::updateScene(const VEHICLEMETHOD &seeing)
{
#if PARALLEL_OMP
omp_set_num_threads(4);
#pragma omp parallel private(m_Vehicles)
{
for(auto i = m_Vehicles.begin() ; i != m_Vehicles.end() ; ++i){
#pragma omp single nowait
{
(*i)->update(seeing);
}
}
}
#pragma omp parallel for
for(size_t i = 0 ; i < m_Vehicles.size() ; ++i ){
if(m_Vehicles.at(i)->isDeletable()){
removeVehicle(m_Vehicles.at(i));
}
}
#elif PARALLEL_CONCURRENT
for(int i = 0; i < m_Vehicles.size() ; ++i){
QFuture<void> f = QtConcurrent::run(m_Vehicles.at(i),&Vehicle::update,seeing);
}
#else
advance();
for(size_t i = 0 ; i < m_Vehicles.size() ; ++i ){
if(m_Vehicles.at(i)->isDeletable()){
removeVehicle(m_Vehicles.at(i));
}
}
#endif
}
void SimulationScene::turnOffInteraction()
{
for(int i = 0 ; i < m_Vehicles.size() ; ++i){
m_Vehicles.at(i)->turnOffInteraction();
}
m_Controller->turnOffLightInteraction();
}
void SimulationScene::turnOnInteraction()
{
for(int i = 0 ; i < m_Vehicles.size() ; ++i){
m_Vehicles.at(i)->turnOnInteraction();
}
m_Controller->turnOnLightInteraction();
}
| 5,913
|
C++
|
.cpp
| 203
| 24.428571
| 125
| 0.639168
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,188
|
visualizepanel.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/visualizepanel.cpp
|
#include "visualizepanel.h"
#include "ui_visualizepanel.h"
VisualizePanel::VisualizePanel(QWidget *parent)
:QWidget(parent)
,ui(new Ui::VisualizePanel)
{
ui->setupUi(this);
// Set up file for writing
// Number in queue vs time
for(int i = 0 ; i < 4 ; i++){
m_queue_size.append(new QFile("queue_" + QString::number(i) + ".txt"));
}
for(int i = 0 ; i < m_queue_size.size() ; i++){
if(!m_queue_size.at(i)->exists()){
qDebug()<<m_queue_size.at(i)->fileName() + " Error";
}
if(m_queue_size.at(i)->open(QIODevice::ReadOnly|QIODevice::Text|QIODevice::WriteOnly)){
QTextStream txtStream(m_queue_size.at(i));
txtStream<<"This file contain data for queue size vs simulation time.\n";
txtStream<<"This is queue size for approach " + QString::number(i) +"\n";
txtStream.flush();
}
}
// setUp Timer
// m_timer = new QList<QTimer *>();
// for(int i = 0 ; i < 4 ; ++i){
// m_timer->append(new QTimer());
// }
// this->connect(m_timer->at(0),SIGNAL(timeout()),this,SLOT(update_1()));
// this->connect(m_timer->at(1),SIGNAL(timeout()),this,SLOT(update_2()));
// this->connect(m_timer->at(2),SIGNAL(timeout()),this,SLOT(update_3()));
// this->connect(m_timer->at(3),SIGNAL(timeout()),this,SLOT(update_4()));
// for(int i = 0 ; i < 4 ; ++i){
// m_timer->at(i)->start(10);
// }
// Number Widget
m_number_widget.append(ui->m_number_widget_1);
m_number_widget.append(ui->m_number_widget_2);
m_number_widget.append(ui->m_number_widget_3);
m_number_widget.append(ui->m_number_widget_4);
// Flow Widget
m_flow_widget.append(ui->m_flow_widget_1);
m_flow_widget.append(ui->m_flow_widget_2);
m_flow_widget.append(ui->m_flow_widget_3);
m_flow_widget.append(ui->m_flow_widget_4);
// Density Widget
m_density_widget.append(ui->m_density_widget_1);
m_density_widget.append(ui->m_density_widget_2);
m_density_widget.append(ui->m_density_widget_3);
m_density_widget.append(ui->m_density_widget_4);
// HeadWay Widget
m_headway_widget.append(ui->m_headway_widget_1);
m_headway_widget.append(ui->m_headway_widget_2);
m_headway_widget.append(ui->m_headway_widget_3);
m_headway_widget.append(ui->m_headway_widget_4);
//Parent
// if(dynamic_cast<MainWindow *>(this->parentWidget())){
// m_w = dynamic_cast<MainWindow *>(this->parentWidget());
// //qDebug()<<"Hello";
// }
// SetUp
//setWindowTitle(QApplication::translate("toplevel", "Real-Time Data Visualization"));
//setWindowFlags(Qt::Widget);
setUpNumberWidget();
setUpFlowWidget();
setUpHeadwayWidget();
setUpDensityWidget();
//qDebug()<<"Hello";
}
//void VisualizePanel::initialize()
//{
// m_timer = new QList<QTimer *>();
// for(int i = 0 ; i < 4 ; ++i){
// m_timer->append(new QTimer());
// }
// this->connect(m_timer->at(0),SIGNAL(timeout()),this,SLOT(update_1()));
// this->connect(m_timer->at(1),SIGNAL(timeout()),this,SLOT(update_2()));
// this->connect(m_timer->at(2),SIGNAL(timeout()),this,SLOT(update_3()));
// this->connect(m_timer->at(3),SIGNAL(timeout()),this,SLOT(update_4()));
// for(int i = 0 ; i < 4 ; ++i){
// m_timer->at(i)->start(10);
// }
//}
//bool VisualizePanel::event(QEvent *event)
//{
// if(event->type() == QEvent::MouseButtonPress){
// qDebug()<<"Hello";
// setWindowOpacity(1.0);
// }
// return QWidget::event(event);
//}
//void VisualizePanel::dragMoveEvent(QDragMoveEvent *event)
//{
// qDebug()<<"Hello";
// setWindowOpacity(1.0);
//}
//void VisualizePanel::mousePressEvent(QMouseEvent *event)
//{
// //qDebug()<<"Hello";
// setWindowOpacity(1.0);
// //QWidget::mousePressEvent(event);
//}
//void VisualizePanel::mouseReleaseEvent(QMouseEvent *event)
//{
// //qDebug()<<"Hello";
// setWindowOpacity(0.5);
// //QWidget::mousePressEvent(event);
//}
VisualizePanel::~VisualizePanel()
{
delete ui;
}
void VisualizePanel::setUpNumberWidget()
{
for(int i = 0 ; i < m_number_widget.size() ; ++i){
m_number_widget.at(i)->addGraph();
// graph1->setData(x1, y1);
m_number_widget.at(i)->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QPen(Qt::black, 1.5), QBrush(Qt::white), 9));
m_number_widget.at(i)->graph(0)->setPen(QPen(QColor(120, 120, 120), 2));
// move bars above graphs and grid below bars:
m_number_widget.at(i)->addLayer("abovemain", m_number_widget.at(i)->layer("main"), QCustomPlot::limAbove);
m_number_widget.at(i)->addLayer("belowmain", m_number_widget.at(i)->layer("main"), QCustomPlot::limBelow);
m_number_widget.at(i)->graph(0)->setLayer("abovemain");
m_number_widget.at(i)->xAxis->grid()->setLayer("belowmain");
m_number_widget.at(i)->yAxis->grid()->setLayer("belowmain");
// set some pens, brushes and backgrounds:
m_number_widget.at(i)->xAxis->setBasePen(QPen(Qt::white, 1));
m_number_widget.at(i)->yAxis->setBasePen(QPen(Qt::white, 1));
m_number_widget.at(i)->xAxis->setTickPen(QPen(Qt::white, 1));
m_number_widget.at(i)->yAxis->setTickPen(QPen(Qt::white, 1));
m_number_widget.at(i)->xAxis->setSubTickPen(QPen(Qt::white, 1));
m_number_widget.at(i)->yAxis->setSubTickPen(QPen(Qt::white, 1));
m_number_widget.at(i)->xAxis->setTickLabelColor(Qt::white);
m_number_widget.at(i)->yAxis->setTickLabelColor(Qt::white);
m_number_widget.at(i)->xAxis->grid()->setPen(QPen(QColor(140, 140, 140), 1, Qt::DotLine));
m_number_widget.at(i)->yAxis->grid()->setPen(QPen(QColor(140, 140, 140), 1, Qt::DotLine));
m_number_widget.at(i)->xAxis->grid()->setSubGridPen(QPen(QColor(80, 80, 80), 1, Qt::DotLine));
m_number_widget.at(i)->yAxis->grid()->setSubGridPen(QPen(QColor(80, 80, 80), 1, Qt::DotLine));
m_number_widget.at(i)->xAxis->grid()->setSubGridVisible(true);
m_number_widget.at(i)->yAxis->grid()->setSubGridVisible(true);
m_number_widget.at(i)->xAxis->grid()->setZeroLinePen(Qt::NoPen);
m_number_widget.at(i)->yAxis->grid()->setZeroLinePen(Qt::NoPen);
m_number_widget.at(i)->xAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);
m_number_widget.at(i)->yAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);
QLinearGradient plotGradient;
plotGradient.setStart(0, 0);
plotGradient.setFinalStop(0, 350);
plotGradient.setColorAt(0, QColor(80, 80, 80));
plotGradient.setColorAt(1, QColor(50, 50, 50));
m_number_widget.at(i)->setBackground(plotGradient);
QLinearGradient axisRectGradient;
axisRectGradient.setStart(0, 0);
axisRectGradient.setFinalStop(0, 350);
axisRectGradient.setColorAt(0, QColor(80, 80, 80));
axisRectGradient.setColorAt(1, QColor(30, 30, 30));
m_number_widget.at(i)->axisRect()->setBackground(axisRectGradient);
m_number_widget.at(i)->rescaleAxes();
m_number_widget.at(i)->yAxis->setRange(0,20);
m_number_widget.at(i)->xAxis->setRange(0,20);
m_number_widget.at(i)->graph(0)->layer()->setMode(QCPLayer::lmBuffered);
connect(m_number_widget.at(i)->xAxis, SIGNAL(rangeChanged(QCPRange)), m_number_widget.at(i)->xAxis2, SLOT(setRange(QCPRange)));
connect(m_number_widget.at(i)->yAxis, SIGNAL(rangeChanged(QCPRange)), m_number_widget.at(i)->yAxis2, SLOT(setRange(QCPRange)));
}
m_number_widget.at(0)->yAxis->setRange(0,MAX_E_W);
m_number_widget.at(1)->yAxis->setRange(0,MAX_N_S);
m_number_widget.at(2)->yAxis->setRange(0,MAX_W_E);
m_number_widget.at(3)->yAxis->setRange(0,MAX_S_N);
for(int i = 0 ; i < m_number_widget.size() ; ++i){
m_number_widget.at(i)->addGraph(); // blue line
m_number_widget.at(i)->graph(0)->setPen(QPen(QColor(40, 110, 255)));
QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
timeTicker->setTimeFormat("%s");
m_number_widget.at(i)->xAxis->setTicker(timeTicker);
m_number_widget.at(i)->axisRect()->setupFullAxesBox();
m_number_widget.at(i)->yAxis->setRange(0, 5);
m_number_widget.at(i)->xAxis->setRange(0, 20);
//m_number_widget.at(i)->graph(0)->layer()->setMode(QCPLayer::lmBuffered);
// make left and bottom axes transfer their ranges to right and top axes:
connect(m_number_widget.at(i)->xAxis, SIGNAL(rangeChanged(QCPRange)), m_number_widget.at(i)->xAxis2, SLOT(setRange(QCPRange)));
connect(m_number_widget.at(i)->yAxis, SIGNAL(rangeChanged(QCPRange)), m_number_widget.at(i)->yAxis2, SLOT(setRange(QCPRange)));
}
m_number_widget.at(0)->yAxis->setRange(0,MAX_E_W);
m_number_widget.at(1)->yAxis->setRange(0,MAX_N_S);
m_number_widget.at(2)->yAxis->setRange(0,MAX_W_E);
m_number_widget.at(3)->yAxis->setRange(0,MAX_S_N);
}
void VisualizePanel::setUpFlowWidget()
{
for(int i = 0 ; i < m_flow_widget.size() ; ++i){
m_flow_widget.at(i)->addGraph(); // blue line
m_flow_widget.at(i)->graph(0)->setPen(QPen(QColor(40, 110, 255)));
QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
timeTicker->setTimeFormat("%s");
m_flow_widget.at(i)->xAxis->setTicker(timeTicker);
m_flow_widget.at(i)->axisRect()->setupFullAxesBox();
m_flow_widget.at(i)->yAxis->setRange(0, 5);
m_flow_widget.at(i)->xAxis->setRange(0, 20);
//m_flow_widget.at(i)->graph(0)->layer()->setMode(QCPLayer::lmBuffered);
// make left and bottom axes transfer their ranges to right and top axes:
connect(m_flow_widget.at(i)->xAxis, SIGNAL(rangeChanged(QCPRange)), m_flow_widget.at(i)->xAxis2, SLOT(setRange(QCPRange)));
connect(m_flow_widget.at(i)->yAxis, SIGNAL(rangeChanged(QCPRange)), m_flow_widget.at(i)->yAxis2, SLOT(setRange(QCPRange)));
}
m_flow_widget.at(0)->yAxis->setRange(0,MAX_E_W);
m_flow_widget.at(1)->yAxis->setRange(0,MAX_N_S);
m_flow_widget.at(2)->yAxis->setRange(0,MAX_W_E);
m_flow_widget.at(3)->yAxis->setRange(0,MAX_S_N);
}
void VisualizePanel::setUpDensityWidget()
{
for(int i = 0 ; i < m_density_widget.size() ; ++i){
m_density_widget.at(i)->addGraph(); // blue line
m_density_widget.at(i)->graph(0)->setPen(QPen(QColor(40, 110, 255)));
QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
timeTicker->setTimeFormat("%s");
m_density_widget.at(i)->xAxis->setTicker(timeTicker);
m_density_widget.at(i)->axisRect()->setupFullAxesBox();
m_density_widget.at(i)->yAxis->setRange(0, 5);
m_density_widget.at(i)->xAxis->setRange(0, 20);
//m_density_widget.at(i)->graph(0)->layer()->setMode(QCPLayer::lmBuffered);
// make left and bottom axes transfer their ranges to right and top axes:
connect(m_density_widget.at(i)->xAxis, SIGNAL(rangeChanged(QCPRange)), m_density_widget.at(i)->xAxis2, SLOT(setRange(QCPRange)));
connect(m_density_widget.at(i)->yAxis, SIGNAL(rangeChanged(QCPRange)), m_density_widget.at(i)->yAxis2, SLOT(setRange(QCPRange)));
}
m_density_widget.at(0)->yAxis->setRange(0,MAX_E_W);
m_density_widget.at(1)->yAxis->setRange(0,MAX_N_S);
m_density_widget.at(2)->yAxis->setRange(0,MAX_W_E);
m_density_widget.at(3)->yAxis->setRange(0,MAX_S_N);
}
void VisualizePanel::setUpHeadwayWidget()
{
for(int i = 0 ; i < m_headway_widget.size() ; ++i){
m_headway_widget.at(i)->addGraph(); // blue line
m_headway_widget.at(i)->graph(0)->setPen(QPen(QColor(40, 110, 255)));
QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
timeTicker->setTimeFormat("%s");
m_headway_widget.at(i)->xAxis->setTicker(timeTicker);
m_headway_widget.at(i)->axisRect()->setupFullAxesBox();
m_headway_widget.at(i)->yAxis->setRange(0, 5);
m_headway_widget.at(i)->xAxis->setRange(0, 20);
//m_headway_widget.at(i)->graph(0)->layer()->setMode(QCPLayer::lmBuffered);
// make left and bottom axes transfer their ranges to right and top axes:
connect(m_headway_widget.at(i)->xAxis, SIGNAL(rangeChanged(QCPRange)), m_headway_widget.at(i)->xAxis2, SLOT(setRange(QCPRange)));
connect(m_headway_widget.at(i)->yAxis, SIGNAL(rangeChanged(QCPRange)), m_headway_widget.at(i)->yAxis2, SLOT(setRange(QCPRange)));
}
m_headway_widget.at(0)->yAxis->setRange(0,MAX_E_W);
m_headway_widget.at(1)->yAxis->setRange(0,MAX_N_S);
m_headway_widget.at(2)->yAxis->setRange(0,MAX_W_E);
m_headway_widget.at(3)->yAxis->setRange(0,MAX_S_N);
}
int VisualizePanel::getNumber(const int &x) const
{
switch (x) {
case 0 :
return getNumberEW();
case 1 :
return getNumberNS();
case 2:
return getNumberWE();
case 3:
return getNumberSN();
}
return 0;
}
int VisualizePanel::getNumberNS() const
{
int num = 0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_N_S).size() ; ++i){
num += m_controller->getDetectorByRegion(REGION_N_S).at(i)->getNumbersOfVehicles();
}
return num;
}
int VisualizePanel::getNumberSN() const
{
int num = 0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_S_N).size() ; ++i){
num += m_controller->getDetectorByRegion(REGION_S_N).at(i)->getNumbersOfVehicles();
}
return num;
}
int VisualizePanel::getNumberWE() const
{
int num = 0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_W_E).size() ; ++i){
num += m_controller->getDetectorByRegion(REGION_W_E).at(i)->getNumbersOfVehicles();
}
return num;
}
int VisualizePanel::getNumberEW() const
{
int num = 0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_E_W).size() ; ++i){
num += m_controller->getDetectorByRegion(REGION_E_W).at(i)->getNumbersOfVehicles();
}
return num;
}
double VisualizePanel::getFlow(const int &x) const
{
switch (x) {
case 0 :
return getFlowEW();//EW
case 1 :
return getFlowNS();//NS
case 2:
return getFlowWE();//WE
case 3:
return getFlowSN();//SN
}
return 0;
}
double VisualizePanel::getFlowNS() const
{
double flow = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_N_S).size() ; ++i){
flow += static_cast<double>(m_controller->getDetectorByRegion(REGION_N_S).at(i)->getFlow());
}
return flow;
}
double VisualizePanel::getFlowSN() const
{
double flow = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_S_N).size() ; ++i){
flow += static_cast<double>(m_controller->getDetectorByRegion(REGION_S_N).at(i)->getFlow());
}
return flow;
}
double VisualizePanel::getFlowWE() const
{
double flow = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_W_E).size() ; ++i){
flow += static_cast<double>(m_controller->getDetectorByRegion(REGION_W_E).at(i)->getFlow());
}
return flow;
}
double VisualizePanel::getFlowEW() const
{
double flow = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_E_W).size() ; ++i){
flow += static_cast<double>(m_controller->getDetectorByRegion(REGION_E_W).at(i)->getFlow());
}
return flow;
}
double VisualizePanel::getDensity(const int &x) const
{
switch (x) {
case 0 :
return getDensityEW();//EW
case 1 :
return getDensityNS();//NS
case 2:
return getDensityWE();//WE
case 3:
return getDensitySN();//SN
}
return 0;
}
double VisualizePanel::getDensityNS() const
{
double den = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_N_S).size() ; ++i){
den += static_cast<double>(m_controller->getDetectorByRegion(REGION_N_S).at(i)->getDensity());
}
return den;
}
double VisualizePanel::getDensitySN() const
{
double den = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_S_N).size() ; ++i){
den += static_cast<double>(m_controller->getDetectorByRegion(REGION_S_N).at(i)->getDensity());
}
return den;
}
double VisualizePanel::getDensityWE() const
{
double den = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_W_E).size() ; ++i){
den += static_cast<double>(m_controller->getDetectorByRegion(REGION_W_E).at(i)->getDensity());
}
return den;
}
double VisualizePanel::getDensityEW() const
{
double den = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_E_W).size() ; ++i){
den += static_cast<double>(m_controller->getDetectorByRegion(REGION_E_W).at(i)->getDensity());
}
return den;
}
double VisualizePanel::getHeadWay(const int &x) const
{
switch (x) {
case 0 :
return getHeadWayEW();//EW
case 1 :
return getHeadWayNS();//NS
case 2:
return getHeadWayWE();//WE
case 3:
return getHeadWaySN();//SN
}
return 0;
}
double VisualizePanel::getHeadWayNS() const
{
double head = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_N_S).size() ; ++i){
head += static_cast<double>(m_controller->getDetectorByRegion(REGION_N_S).at(i)->getHeadWay());
}
return head;
}
double VisualizePanel::getHeadWaySN() const
{
double head = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_S_N).size() ; ++i){
head += static_cast<double>(m_controller->getDetectorByRegion(REGION_S_N).at(i)->getHeadWay());
}
return head;
}
double VisualizePanel::getHeadWayWE() const
{
double head = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_W_E).size() ; ++i){
head += static_cast<double>(m_controller->getDetectorByRegion(REGION_W_E).at(i)->getHeadWay());
}
return head;
}
double VisualizePanel::getHeadWayEW() const
{
double head = 0.0;
for(int i = 0 ; i < m_controller->getDetectorByRegion(REGION_E_W).size() ; ++i){
head += static_cast<double>(m_controller->getDetectorByRegion(REGION_E_W).at(i)->getHeadWay());
}
return head;
}
void VisualizePanel::update_1()
{
update_NUM();
}
void VisualizePanel::update_2()
{
update_FLOW();
}
void VisualizePanel::update_3()
{
update_DEN();
}
void VisualizePanel::update_4()
{
update_HEAD();
}
void VisualizePanel::update_all()
{
update_1();
update_2();
update_3();
update_4();
}
void VisualizePanel::update_FLOW()
{
static QTime time(QTime::currentTime());
double key = time.elapsed()/1000.0; // time elapsed since start of demo, in seconds
static double lastPointKey = 0;
// if(key >= RESET_RANGED){
// for(int i = 0 ; i < 4 ; ++i){
//// m_flow_widget.at(i)->graph(0)->data().clear();
//// m_flow_widget.at(i)->graph(0)->data().data()->clear();
// m_flow_widget.at(i)->clearGraphs();
//// m_flow_widget.at(i)->clearItems();
//// m_flow_widget.at(i)->clearPlottables();
// m_flow_widget.at(i)->addGraph();
// m_flow_widget.at(i)->graph(0)->setPen(QPen(QColor(40, 110, 255)));
// //m_flow_widget.at(i)->graph(0)->layer()->setMode(QCPLayer::lmBuffered);
// }
// time.restart();
// key = 0;
// lastPointKey = 0;
// }
if(key - lastPointKey > 0.1){
for(int i = 0 ; i < m_flow_widget.size() ; ++i){
//m_flow_widget.at(i)->graph(0)->data().data()->clear();
//m_flow_widget.at(i)->graph(0)->data().data()->removeBefore(key-20.0);
m_flow_widget.at(i)->graph(0)->addData(key,getFlow(i));
}
lastPointKey = key;
}
for(int i = 0 ; i < m_flow_widget.size() ; ++i){
m_flow_widget.at(i)->xAxis->setRange(key,20, Qt::AlignRight);
m_flow_widget.at(i)->replot();
}
}
void VisualizePanel::update_NUM()
{
static QTime time(QTime::currentTime());
double key = time.elapsed()/1000.0; // time elapsed since start of demo, in seconds
static double lastPointKey = 0;
// if(key >= RESET_RANGED){
// for(int i = 0 ; i < 4 ; ++i){
//// m_number_widget.at(i)->graph(0)->data().clear();
//// m_number_widget.at(i)->graph(0)->data().data()->clear();
// m_number_widget.at(i)->clearGraphs();
// m_number_widget.at(i)->addGraph();
// m_number_widget.at(i)->graph(0)->setPen(QPen(QColor(40, 110, 255)));
// //m_number_widget.at(i)->graph(0)->layer()->setMode(QCPLayer::lmBuffered);
// }
// time.restart();
// key = 0;
// lastPointKey = 0;
// }
if(key - lastPointKey > 1){
for(int i = 0 ; i < m_number_widget.size() ; ++i){
//m_number_widget.at(i)->graph(0)->data().data()->clear();
//m_number_widget.at(i)->graph(0)->data().data()->removeBefore(key-20.0);
m_number_widget.at(i)->graph(0)->addData(key,getNumber(i));
//QTextStream txtStream(m_queue_size.at(i));
//txtStream<<QString::number(key)<<"\t"<<QString::number(getNumber(i))<<"\n";
//txtStream.flush();
}
lastPointKey = key;
}
for(int i = 0 ; i < m_number_widget.size() ; ++i){
m_number_widget.at(i)->xAxis->setRange(key,20, Qt::AlignRight);
m_number_widget.at(i)->replot();
}
}
void VisualizePanel::update_DEN()
{
static QTime time(QTime::currentTime());
double key = time.elapsed()/1000.0; // time elapsed since start of demo, in seconds
static double lastPointKey = 0;
// if(key >= RESET_RANGED){
// for(int i = 0 ; i < 4 ; ++i){
//// m_density_widget.at(i)->graph(0)->data().clear();
//// m_density_widget.at(i)->graph(0)->data().data()->clear();
// m_density_widget.at(i)->clearGraphs();
// m_density_widget.at(i)->addGraph();
// m_density_widget.at(i)->graph(0)->setPen(QPen(QColor(40, 110, 255)));
// //m_density_widget.at(i)->graph(0)->layer()->setMode(QCPLayer::lmBuffered);
// }
// time.restart();
// key = 0;
// lastPointKey = 0;
// }
if(key - lastPointKey > 0.1){
for(int i = 0 ; i < m_density_widget.size() ; ++i){
//m_density_widget.at(i)->graph(0)->data().data()->clear();
//m_density_widget.at(i)->graph(0)->data().data()->removeBefore(key-20.0);
m_density_widget.at(i)->graph(0)->addData(key,getDensity(i));
}
lastPointKey = key;
}
for(int i = 0 ; i < m_density_widget.size() ; ++i){
m_density_widget.at(i)->xAxis->setRange(key,20, Qt::AlignRight);
m_density_widget.at(i)->replot();
}
}
void VisualizePanel::update_HEAD()
{
static QTime time(QTime::currentTime());
double key = time.elapsed()/1000.0; // time elapsed since start of demo, in seconds
static double lastPointKey = 0;
// if(key >= RESET_RANGED){
// for(int i = 0 ; i < 4 ; ++i){
//// m_headway_widget.at(i)->graph(0)->data().clear();
//// m_headway_widget.at(i)->graph(0)->data().data()->clear();
// m_headway_widget.at(i)->clearGraphs();
// m_headway_widget.at(i)->addGraph();
// m_headway_widget.at(i)->graph(0)->setPen(QPen(QColor(40, 110, 255)));
// //m_headway_widget.at(i)->graph(0)->layer()->setMode(QCPLayer::lmBuffered);
// }
// time.restart();
// key = 0;
// lastPointKey = 0;
// }
if(key - lastPointKey > 0.1){
for(int i = 0 ; i < m_headway_widget.size() ; ++i){
//m_headway_widget.at(i)->graph(0)->data().data()->clear();
//m_headway_widget.at(i)->graph(0)->data().data()->removeBefore(key-20.0);
m_headway_widget.at(i)->graph(0)->addData(key,getHeadWay(i));
}
lastPointKey = key;
}
for(int i = 0 ; i < m_headway_widget.size() ; ++i){
m_headway_widget.at(i)->xAxis->setRange(key,20, Qt::AlignRight);
m_headway_widget.at(i)->replot();
}
}
void VisualizePanel::setController(TrafficController *controller)
{
m_controller = controller;
}
//void VisualizePanel::setEtimer(QList<QElapsedTimer *> *etimer)
//{
// m_etimer = etimer;
//}
| 24,491
|
C++
|
.cpp
| 593
| 36.18887
| 145
| 0.616421
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,190
|
simulationsetup.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/simulationsetup.cpp
|
#include "simulationsetup.h"
#include "ui_simulationsetup.h"
SimulationSetup::SimulationSetup(QWidget *parent) :
QWidget(parent),
ui(new Ui::SimulationSetup)
{
ui->setupUi(this);
trafficButton.append(ui->traffic_level_easy_input);
trafficButton.append(ui->traffic_mode_moderate_input);
trafficButton.append(ui->traffic_mode_busy_input);
lightButton.append(ui->light_quick_input);
lightButton.append(ui->light_moderate_input);
lightButton.append(ui->light_long_input);
}
SimulationSetup::~SimulationSetup()
{
delete ui;
}
void SimulationSetup::on_start_simulation_button_clicked()
{
for(int i = 0 ; i < 3 ; ++i){
if(trafficButton.at(i)->isChecked()){
for(int j = 0 ; j < 3 ; ++j){
if(lightButton.at(j)->isChecked()){
emit inputReady(input);
close();
}
}
}
}
return;
}
void SimulationSetup::on_random_setup_clicked()
{
input.random();
emit inputReady(input);
close();
}
void SimulationSetup::on_help_setup_button_clicked()
{
onHelpClicked();
close();
}
void SimulationSetup::on_traffic_level_easy_input_clicked()
{
input.trafficEasy();
}
void SimulationSetup::on_traffic_mode_moderate_input_clicked()
{
input.trafficModerate();
}
void SimulationSetup::on_traffic_mode_busy_input_clicked()
{
input.trafficBusy();
}
void SimulationSetup::on_light_quick_input_clicked()
{
input.LightingQuick();
}
void SimulationSetup::on_light_moderate_input_clicked()
{
input.LightingModerate();
}
void SimulationSetup::on_light_long_input_clicked()
{
input.LightingLong();
}
void SimulationSetup::on_experimental_mode_crazy_clicked()
{
input.ExperimentalCrazy();
emit inputReady(input);
close();
}
void SimulationSetup::on_experimental_free_clicked()
{
input.ExperimentalFreeForAll();
emit inputReady(input);
close();
}
| 1,947
|
C++
|
.cpp
| 79
| 20.531646
| 62
| 0.687702
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,191
|
simulationcontrolwidget.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/simulationcontrolwidget.cpp
|
#include "simulationcontrolwidget.h"
#include "ui_simulationcontrolwidget.h"
#include <QDebug>
SimulationControlWidget::SimulationControlWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::SimulationControlWidget)
{
ui->setupUi(this);
}
//void SimulationControlWidget::installSimulation(RoadIntersectionSimulation *instance)
//{
// m_Simulation = instance;
//}
SimulationControlWidget::~SimulationControlWidget()
{
delete ui;
}
void SimulationControlWidget::on_start_simulation_button_clicked()
{
emit inputedReady(ui->north_south_input->value(),
ui->south_north_input->value(),
ui->west_east_input->value(),
ui->east_west_input->value(),
ui->red_light_input->value(),
ui->green_light_input->value(),
ui->left_green_light_input->value());
hide();
}
void SimulationControlWidget::on_random_setup_clicked()
{
emit randomClicked();
hide();
}
void SimulationControlWidget::on_help_setup_button_clicked()
{
emit helpClicked();
hide();
}
| 1,115
|
C++
|
.cpp
| 38
| 23.657895
| 87
| 0.662932
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,192
|
simulationcontrol.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Utilities/simulationcontrol.cpp
|
#include "simulationcontrol.h"
#include "ui_simulationcontrol.h"
SimulationControl::SimulationControl(QWidget *parent) :
QWidget(parent),m_w(nullptr),
ui(new Ui::SimulationControl)
{
ui->setupUi(this);
setWindowFlags(Qt::Widget);
//this->setFixedSize (300,200);
this->setWindowTitle ("Simulation Controller");
ui->m_green->setValidator(new QIntValidator(0, 10000, ui->m_green));
//ui->m_red->setValidator(new QIntValidator(0, 10000, ui->m_red));
ui->m_yellow->setValidator(new QIntValidator(0, 1000, ui->m_yellow));
ui->m_road_1->setValidator(new QIntValidator(0, 100, ui->m_road_1));
ui->m_road_2->setValidator(new QIntValidator(0, 100, ui->m_road_2));
ui->m_road_3->setValidator(new QIntValidator(0, 100, ui->m_road_3));
ui->m_road_4->setValidator(new QIntValidator(0, 100, ui->m_road_4));
//qDebug()<<"Hello";
setWindowTitle(QApplication::translate("toplevel", "Simulation Control"));
//setWindowFlags(Qt::Window);
}
SimulationControl::~SimulationControl()
{
delete ui;
}
void SimulationControl::initialize(QWidget *widget)
{
m_generator = new Generator();
if(dynamic_cast<MainWindow *>(widget)){
m_w = dynamic_cast<MainWindow *>(widget);
m_generator->setScene(m_w->scene());
m_generator->setMethod(m_w->getCurrentMethod());
m_generator->setMode(m_w->getCurrentVehicleMethod());
//qDebug()<<"Hello";
}
}
void SimulationControl::stopGenerating()
{
m_generator->stopGenerator();
}
void SimulationControl::on_m_setup_button_clicked()
{
}
void SimulationControl::on_m_setup_birth_rate_button_clicked()
{
m_generator->setTimer(4000/(ui->m_road_1->text().toInt())
,4000/(ui->m_road_2->text().toInt())
,4000/(ui->m_road_3->text().toInt())
,4000/(ui->m_road_4->text().toInt())
);
m_generator->startGenerator();
m_w->turnOnSimulationState();
// ui->m_road_1->setText("0");
// ui->m_road_2->setText("0");
// ui->m_road_3->setText("0");
// ui->m_road_4->setText("0");
}
void SimulationControl::on_m_stop_clicked()
{
m_w->getController()->stopTrafficLightAll();
}
void SimulationControl::on_m_auto_traffic_clicked()
{
m_w->getController()->setLightDuration(5000,3000,500,6000);
}
void SimulationControl::on_m_random_birth_clicked()
{
m_generator->startAutoGeneraion();
m_w->turnOnSimulationState();
m_w->getController()->setLightDuration(3000,2000,500,6000);
m_w->getController()->startTrafficLightAll();
// Ui Stuff
m_w->set3LaneCheck(true);
m_w->setGenMethod(GENMETHOD::GEN_3);
m_w->setGoThroguht(false);
m_w->setSimMode(VEHICLEMETHOD::SIGHTSEEING);
m_w->setTrafficState(true);
// m_w->getUi()->m_3_lanes->setChecked(true);
// m_w->getUi()->m_simulation_control_widget->generator()->setMethod(GENMETHOD::GEN_3);
// m_w->getUi()->m_go_though->setChecked(false);
// m_w->getUi()->m_simulation_control_widget->generator()->setMode(VEHICLEMETHOD::SIGHTSEEING);
// m_w->getUi()->m_no_traffic->setChecked(true);
//m_w->getUi()->m_visualize_panel_check_box->setChecked(true);
m_w->showTraffic(true);
//m_w->getUi()->m_visualize_frame->show();
}
void SimulationControl::on_m_setup_birth_rate_button_3_clicked()
{
}
Generator *SimulationControl::generator() const
{
return m_generator;
}
void SimulationControl::setMethod(const GENMETHOD &m)
{
m_generator->setMethod(m);
}
| 3,515
|
C++
|
.cpp
| 97
| 31.824742
| 98
| 0.665979
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,194
|
vehiclesgenerator.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Utilities/vehiclesgenerator.cpp
|
#include "vehiclesgenerator.h"
Vehicle *VehiclesGenerator::getLeftTurningVehicle(const region &approach
, const VEHICLEMETHOD &x
, const bool &vision
, const bool &interact)
{
Vehicle *p = new Vehicle();
p->extract_coordinate(road::getLeft(approach));
p->setDirection(Direction::LEFT_TURNING);
p->setRegion(approach);
p->initialize();
p->setMode(x);
p->setScale(0.8);
if(vision){
p->turnOnSightSeeing();
}else{
p->turnOffSightSeeing();
}
if(interact){
p->turnOnInteraction();
}else{
p->turnOffInteraction();
}
// p->get_timer()->start(10);
// p->set_on_action(true);
return p;
}
Vehicle *VehiclesGenerator::getThroughVehicle(const region &approach
, const int &lane
, const VEHICLEMETHOD &x
, const bool& vision
, const bool& interact)
{
Vehicle *p = new Vehicle();
p->extract_coordinate(road::getThrough(approach,lane));
p->setDirection(Direction::THROUGH);
p->setRegion(approach);
p->initialize();
p->setMode(x);
p->setScale(0.8);
if(vision){
p->turnOnSightSeeing();
}else{
p->turnOffSightSeeing();
}
if(interact){
p->turnOnInteraction();
}else{
p->turnOffInteraction();
}
// p->get_timer()->start(10);
// p->set_on_action(true);
return p;
}
Vehicle *VehiclesGenerator::getRightTurningVehicle(const region &approach
, const VEHICLEMETHOD &x
, const bool &vision, const bool &interact)
{
Vehicle *p = new Vehicle();
p->extract_coordinate(road::getRight(approach));
p->setDirection(Direction::RIGHT_TURNING);
p->setRegion(approach);
p->initialize();
p->setMode(x);
p->setScale(0.8);
if(vision){
p->turnOnSightSeeing();
}else{
p->turnOffSightSeeing();
}
if(interact){
p->turnOnInteraction();
}else{
p->turnOffInteraction();
}
// p->get_timer()->start(10);
// p->set_on_action(true);
return p;
}
| 2,416
|
C++
|
.cpp
| 79
| 20.670886
| 94
| 0.519503
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,195
|
generator.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Utilities/generator.cpp
|
#include "generator.h"
Generator::Generator(SimulationScene *scene)
:m_scene(scene)
,m_mode(VEHICLEMETHOD::GO_THROUGH)
,m_running_state(false)
,m_VisionOn(false)
,m_IsInteraction(true)
{
for(int i = 0 ; i < 4 ; ++i){
m_timer.append( new QTimer());
}
this->connect(m_timer.at(0),SIGNAL(timeout()),this,SLOT(makeEastWest()));
this->connect(m_timer.at(1),SIGNAL(timeout()),this,SLOT(makeNorthSouth()));
this->connect(m_timer.at(2),SIGNAL(timeout()),this,SLOT(makeSouthNorth()));
this->connect(m_timer.at(3),SIGNAL(timeout()),this,SLOT(makeWestEast()));
//qsrand(static_cast<uint>(QTime(0,0,0).secsTo(QTime::currentTime())));
}
Generator::Generator()
:m_number_N_S(0)
,m_number_S_N(0)
,m_number_W_E(0)
,m_number_E_W(0)
,m_time_N_S(0)
,m_time_S_N(0)
,m_time_W_E(0)
,m_time_E_W(0)
,m_mode(VEHICLEMETHOD::GO_THROUGH)
,m_running_state(false)
{
for(int i = 0 ; i < 4 ; ++i){
m_timer.append( new QTimer());
}
//qsrand(static_cast<uint>(QTime(0,0,0).secsTo(QTime::currentTime())));
}
Generator::~Generator()
{
delete m_timer.at(0);
delete m_timer.at(1);
delete m_timer.at(2);
delete m_timer.at(3);
}
void Generator::setMethod(const GENMETHOD& x)
{
m_method = x;
}
void Generator::startGenerator()
{
m_timer.at(0)->start(m_time_E_W);
m_timer.at(1)->start(m_time_N_S);
m_timer.at(2)->start(m_time_S_N);
m_timer.at(3)->start(m_time_W_E);
}
void Generator::stopGenerator()
{
m_timer.at(0)->stop();
m_timer.at(1)->stop();
m_timer.at(2)->stop();
m_timer.at(3)->stop();
}
void Generator::startAutoGeneraion()
{
setTimer(2500,2000,2600,3000);
startGenerator();
}
void Generator::setTimer(const int& N_S,const int& S_N,const int& E_W,const int& W_E)
{
m_time_N_S = N_S;
m_time_S_N = S_N;
m_time_E_W = E_W;
m_time_W_E = W_E;
}
void Generator::makeNorthSouth()
{
if(m_scene->getNumber(REGION_N_S) > MAX_N_S){
return;
}
//qDebug()<<"Hello";
switch (m_method) {
case GEN_3:
switch (qrand()%3){
case 0:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_N_S,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_N_S,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_N_S,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
}
break;
case GEN_5:
switch (qrand()%5){
case 0:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_N_S,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_N_S,1,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_N_S,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 3:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_N_S,3,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 4:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_N_S,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
}
break;
case NO_TURN:
switch (qrand()%3){
case 0:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_N_S,1,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_N_S,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_N_S,3,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
}
break;
case ONLY_TURN:
switch (qrand()%2) {
case 0:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_N_S,m_mode,m_VisionOn,m_IsInteraction));
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_N_S,m_mode,m_VisionOn,m_IsInteraction));
break;
}
break;
}
}
void Generator::makeSouthNorth()
{
if(m_scene->getNumber(REGION_S_N) > MAX_S_N){
return;
}
//qDebug()<<"Hello";
switch (m_method) {
case GEN_3:
switch (qrand()%3){
case 0:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_S_N,m_mode,m_VisionOn,m_IsInteraction));
//m_number_S_N++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_S_N,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_S_N++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_S_N,m_mode,m_VisionOn,m_IsInteraction));
//m_number_S_N++;
break;
}
break;
case GEN_5:
switch (qrand()%5){
case 0:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_S_N,m_mode,m_VisionOn,m_IsInteraction));
//m_number_S_N++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_S_N,1,m_mode,m_VisionOn,m_IsInteraction));
//m_number_S_N++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_S_N,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_S_N++;
break;
case 3:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_S_N,3,m_mode,m_VisionOn,m_IsInteraction));
//m_number_S_N++;
break;
case 4:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_S_N,m_mode,m_VisionOn,m_IsInteraction));
//m_number_S_N++;
break;
}
break;
case NO_TURN:
switch (qrand()%3){
case 0:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_S_N,1,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_S_N,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_S_N,3,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
}
break;
case ONLY_TURN:
switch (qrand()%2) {
case 0:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_S_N,m_mode,m_VisionOn,m_IsInteraction));
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_S_N,m_mode,m_VisionOn,m_IsInteraction));
break;
}
break;
}
}
void Generator::makeWestEast()
{
if(m_scene->getNumber(REGION_W_E) > MAX_W_E){
return;
}
//qDebug()<<"Hello";
switch (m_method) {
case GEN_3:
switch (qrand()%3){
case 0:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_W_E,m_mode,m_VisionOn,m_IsInteraction));
//m_number_W_E++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_W_E,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_W_E++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_W_E,m_mode,m_VisionOn,m_IsInteraction));
//m_number_W_E++;
break;
}
break;
case GEN_5:
switch (qrand()%5){
case 0:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_W_E,m_mode,m_VisionOn,m_IsInteraction));
//m_number_W_E++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_W_E,1,m_mode,m_VisionOn,m_IsInteraction));
//m_number_W_E++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_W_E,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_W_E++;
break;
case 3:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_W_E,3,m_mode,m_VisionOn,m_IsInteraction));
//m_number_W_E++;
break;
case 4:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_W_E,m_mode,m_VisionOn,m_IsInteraction));
//m_number_W_E++;
break;
}
break;
case NO_TURN:
switch (qrand()%3){
case 0:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_W_E,1,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_W_E,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_W_E,3,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
}
break;
case ONLY_TURN:
switch (qrand()%2) {
case 0:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_W_E,m_mode,m_VisionOn,m_IsInteraction));
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_W_E,m_mode,m_VisionOn,m_IsInteraction));
break;
}
break;
}
}
void Generator::makeEastWest()
{
if(m_scene->getNumber(REGION_E_W) > MAX_E_W){
return;
}
//qDebug()<<"Hello";
switch (m_method) {
case GEN_3:
switch (qrand()%3){
case 0:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_E_W,m_mode,m_VisionOn,m_IsInteraction));
//m_number_E_W++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_E_W,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_E_W++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_E_W,m_mode,m_VisionOn,m_IsInteraction));
//m_number_E_W++;
break;
}
break;
case GEN_5:
switch (qrand()%5){
case 0:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_E_W,m_mode,m_VisionOn,m_IsInteraction));
//m_number_E_W++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_E_W,1,m_mode,m_VisionOn,m_IsInteraction));
//m_number_E_W++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_E_W,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_E_W++;
break;
case 3:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_E_W,3,m_mode,m_VisionOn,m_IsInteraction));
//m_number_E_W++;
break;
case 4:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_E_W,m_mode,m_VisionOn,m_IsInteraction));
//m_number_E_W++;
break;
}
break;
case NO_TURN:
switch (qrand()%3){
case 0:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_E_W,1,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_E_W,2,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
case 2:
m_scene->addVehicle(VehiclesGenerator::getThroughVehicle(REGION_E_W,3,m_mode,m_VisionOn,m_IsInteraction));
//m_number_N_S++;
break;
}
break;
case ONLY_TURN:
switch (qrand()%2) {
case 0:
m_scene->addVehicle(VehiclesGenerator::getLeftTurningVehicle(REGION_E_W,m_mode,m_VisionOn,m_IsInteraction));
break;
case 1:
m_scene->addVehicle(VehiclesGenerator::getRightTurningVehicle(REGION_E_W,m_mode,m_VisionOn,m_IsInteraction));
break;
}
break;
}
}
void Generator::setMode(const VEHICLEMETHOD &mode)
{
m_mode = mode;
}
void Generator::setVisionOn(const bool &vision)
{
m_VisionOn = vision;
}
void Generator::setInteraction(const bool &interact)
{
m_IsInteraction = interact;
}
void Generator::setScene(SimulationScene *scene)
{
m_scene = scene;
}
void Generator::turnOn()
{
m_running_state = true;
}
void Generator::turnOff()
{
m_running_state = false;
}
| 14,580
|
C++
|
.cpp
| 395
| 25.663291
| 129
| 0.545474
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,196
|
road.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Utilities/road.cpp
|
#include "road.h"
QPainterPath road::get_1_1()
{
return draw_1_1 ();
}
QPainterPath road::get_1_2()
{
return draw_1_2 ();
}
QPainterPath road::get_1_3()
{
return draw_1_3 ();
}
QPainterPath road::get_1_4()
{
return draw_1_4 ();
}
QPainterPath road::get_1_5()
{
return draw_1_5 ();
}
QPainterPath road::get_2_1()
{
return draw_2_1 ();
}
QPainterPath road::get_2_2()
{
return draw_2_2 ();
}
QPainterPath road::get_2_3()
{
return draw_2_3 ();
}
QPainterPath road::get_2_4()
{
return draw_2_4 ();
}
QPainterPath road::get_2_5()
{
return draw_2_5 ();
}
QPainterPath road::get_3_1()
{
return draw_3_1 ();
}
QPainterPath road::get_3_2()
{
return draw_3_2 ();
}
QPainterPath road::get_3_3()
{
return draw_3_3 ();
}
QPainterPath road::get_3_4()
{
return draw_3_4 ();
}
QPainterPath road::get_3_5()
{
return draw_3_5 ();
}
QPainterPath road::get_4_1()
{
return draw_4_1 ();
}
QPainterPath road::get_4_2()
{
return draw_4_2 ();
}
QPainterPath road::get_4_3()
{
return draw_4_3 ();
}
QPainterPath road::get_4_4()
{
return draw_4_4 ();
}
QPainterPath road::get_4_5()
{
return draw_4_5 ();
}
QPainterPath road::draw_1_1()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_2_1());
return m_path;
}
QPainterPath road::draw_1_2()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_2_2());
return m_path;
}
QPainterPath road::draw_1_3()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_2_3());
return m_path;
}
QPainterPath road::draw_1_4()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_2_4());
return m_path;
}
QPainterPath road::draw_1_5()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_2_5());
return m_path;
}
QPainterPath road::draw_2_1()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_3_1());
return m_path;
}
QPainterPath road::draw_2_2()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_3_2());
return m_path;
}
QPainterPath road::draw_2_3()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_3_3());
return m_path;
}
QPainterPath road::draw_2_4()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_3_4());
return m_path;
}
QPainterPath road::draw_2_5()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_3_5());
return m_path;
}
QPainterPath road::draw_3_1()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_4_1());
//m_path.translate (100,100);
return m_path;
}
QPainterPath road::draw_3_2()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_4_2());
return m_path;
}
QPainterPath road::draw_3_3()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_4_3());
return m_path;
}
QPainterPath road::draw_3_4()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_4_4());
return m_path;
}
QPainterPath road::draw_3_5()
{
QTransform transform;
transform.rotate (90);
transform.translate (-25,-620);
QPainterPath m_path = transform.map(get_4_5());
return m_path;
}
QPainterPath road::draw_4_1()
{
QPainterPath m_path;
m_path.moveTo(325,600);
m_path.lineTo(325,328 + 30 +20);
m_path.arcTo(225-150,280 + 30 - 50 ,100 + 150,100 + 150,5,75);
m_path.lineTo(0,280 - 20);
return m_path;
}
QPainterPath road::draw_4_2()
{
QPainterPath m_path;
m_path.moveTo (325,600);
m_path.lineTo (325,0);
return m_path;
}
QPainterPath road::draw_4_3()
{
QPainterPath m_path;
m_path.moveTo (340,600);
m_path.lineTo (340,0);
return m_path;
}
QPainterPath road::draw_4_4()
{
QPainterPath m_path;
m_path.moveTo (355,600);
m_path.lineTo (355,0);
return m_path;
}
QPainterPath road::draw_4_5()
{
QPainterPath m_path;
m_path.moveTo (355,600);
m_path.lineTo(355,328 + 30 +20+50 -30);
m_path.quadTo (QPointF(355,328 + 30-25),QPointF(410,330));
m_path.lineTo (700,330);
return m_path;
}
QPainterPath road::getLeft(const region& approach)
{
switch (approach) {
case region::REGION_W_E:
return get_3_1();
case region::REGION_N_S:
return get_2_1();
case region::REGION_E_W:
return get_1_1();
case region::REGION_S_N:
return get_4_1();
}
return QPainterPath(QPointF(0,0));
}
QPainterPath road::getThrough(const region &approach, const int& lane)
{
switch (approach) {
case region::REGION_W_E :
switch (lane) {
case 1:
return get_3_2();
case 2 :
return get_3_3();
case 3 :
return get_3_4();
}
case region::REGION_N_S:
switch (lane) {
case 1:
return get_2_2();
case 2 :
return get_2_3();
case 3 :
return get_2_4();
}
case region::REGION_E_W:
switch (lane) {
case 1:
return get_1_2();
case 2 :
return get_1_3();
case 3 :
return get_1_4();
}
case region::REGION_S_N:
switch (lane) {
case 1:
return get_4_2();
case 2 :
return get_4_3();
case 3 :
return get_4_4();
}
}
return QPainterPath(QPointF(0,0));
}
QPainterPath road::getRight(const region& approach)
{
switch (approach) {
case region::REGION_W_E:
return get_3_5();
case region::REGION_N_S:
return get_2_5();
case region::REGION_E_W:
return get_1_5();
case region::REGION_S_N:
return get_4_5();
}
return QPainterPath(QPointF(0,0));
}
| 6,678
|
C++
|
.cpp
| 311
| 17.334405
| 70
| 0.620275
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,197
|
roadintersectionsimulation.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Utilities/roadintersectionsimulation.cpp
|
#include "roadintersectionsimulation.h"
#include <QDebug>
RoadIntersectionSimulation::RoadIntersectionSimulation(QGraphicsView *view)
:m_State(UNINITIALIZED)
,m_TrafficLightOn(false)
,m_VehicleSightSeeingOn(false)
,m_VisualizationOn(false)
,m_SimulationTimer(new QTimer)
{
m_Scene = new SimulationScene();
m_Scene->setSceneRect(0,0,800,600);
view->setScene(m_Scene);
m_view = view;
connect(m_SimulationTimer,&QTimer::timeout,this,&RoadIntersectionSimulation::updateVehicle);
}
RoadIntersectionSimulation::~RoadIntersectionSimulation()
{
delete m_Scene;
delete m_Generator;
delete m_SimulationTimer;
}
void RoadIntersectionSimulation::startSimulation()
{
if(m_State == SimulationState::INITIALIZED || m_State == SimulationState::PAUSED){
m_SimulationTimer->start(TIME_STEP);
m_Generator->startGenerator();
m_Scene->getController()->startTrafficLightAll();
m_Scene->getController()->turnOnDetector();
m_Scene->showTrafficLight();
m_State = SimulationState::STARTED;
}
if(m_State == SimulationState::STARTED){
return;
}
}
void RoadIntersectionSimulation::initialize(const int &B_NS,
const int &B_SN,
const int &B_WE,
const int &B_EW,
const int &RED_LIGHT,
const int &GREEN_LIGHT,
const int &LEFT_GREEN_LIGHT,
const int &YELLOW_LIGHT,
const GENMETHOD &METh,
const VEHICLEMETHOD &MODE)
{
//Initialize Component
if(m_State == SimulationState::UNINITIALIZED){
if(!m_Scene){
m_Scene = new SimulationScene();
m_Scene->setSceneRect(0,0,800,600);
m_view->setScene(m_Scene);
}
m_Generator = new Generator(m_Scene);
//Give value to components
m_Generator->setTimer(B_NS,B_SN,B_EW,B_WE);
m_Generator->setMethod(METh);
m_Generator->setMode(MODE);
m_Scene->getController()->setLightDuration(GREEN_LIGHT,LEFT_GREEN_LIGHT,YELLOW_LIGHT,RED_LIGHT);
m_Scene->getController()->turnOnLightInteraction();
m_State = SimulationState::INITIALIZED;
}
}
void RoadIntersectionSimulation::initializeFrominput(SimulationInput input)
{
initialize(input.B_NS,
input.B_SN,
input.B_WE,
input.B_EW,
input.RED_LIGHT,
input.GREEN_LIGHT,
input.LEFT_GREEN_LIGHT,
input.YELLOW_LIGHT,
input.METh,
input.MODE);
startSimulation();
if(input.ShowTrafficLight == false){
m_Scene->HideTrafficLight();
}
}
void RoadIntersectionSimulation::stopSimulation()
{
if(m_State == SimulationState::STARTED || m_State == SimulationState::PAUSED){
pauseSimulation();
delete m_Scene;
delete m_Generator;
m_State = SimulationState::UNINITIALIZED;
}
}
void RoadIntersectionSimulation::pauseSimulation()
{
if(m_State == SimulationState::STARTED){
m_SimulationTimer->stop();
//this->disconnect(m_SimulationTimer);
m_Generator->stopGenerator();
m_Scene->getController()->stopTrafficLightAll();
m_Scene->getController()->turnOffDetector();
m_State = SimulationState::PAUSED;
}
}
void RoadIntersectionSimulation::turnOffInteraction()
{
m_Scene->turnOffInteraction();
m_Generator->setInteraction(false);
m_Scene->turnOffDetectors();
}
void RoadIntersectionSimulation::turnOnInteraction()
{
m_Scene->turnOnInteraction();
m_Generator->setInteraction(true);
m_Scene->turnOnDetectors();
}
void RoadIntersectionSimulation::startDemo()
{
startSimulation();
turnOffInteraction();
}
void RoadIntersectionSimulation::updateVehicle()
{
m_Scene->updateScene(VEHICLEMETHOD::SIGHTSEEING);
emit updatedOneFrame();
}
void RoadIntersectionSimulation::autoInitialize()
{
initialize();
startSimulation();
}
SimulationState RoadIntersectionSimulation::State() const
{
return m_State;
}
QPixmap RoadIntersectionSimulation::updatedViewinOneFrame()
{
QPixmap image;
startSimulation();
image = m_Scene->views().at(0)->grab();
pauseSimulation();
return image;
}
void RoadIntersectionSimulation::showRoad()
{
m_Scene->showIntersectionPath(true);
}
void RoadIntersectionSimulation::hideRoad()
{
m_Scene->showIntersectionPath(false);
}
void RoadIntersectionSimulation::showDetectors()
{
m_Scene->showDetectors();
}
void RoadIntersectionSimulation::hideDetectors()
{
m_Scene->hideDetectors();
}
void RoadIntersectionSimulation::showVehiclesVision()
{
m_Scene->showVehiclesVision();
m_Generator->setVisionOn(true);
}
void RoadIntersectionSimulation::hideVehiclesVision()
{
m_Scene->hideVehiclesVision();
m_Generator->setVisionOn(false);
}
void RoadIntersectionSimulation::showTraffic()
{
m_Scene->showTrafficLight();
}
void RoadIntersectionSimulation::hideTraffic()
{
m_Scene->HideTrafficLight();
}
void RoadIntersectionSimulation::turnOnGoThrough()
{
m_Generator->setMode(VEHICLEMETHOD::GO_THROUGH);
m_Scene->setGoThrough(true);
}
void RoadIntersectionSimulation::turnOffGoThrough()
{
m_Generator->setMode(VEHICLEMETHOD::SIGHTSEEING);
m_Scene->setGoThrough(false);
}
void RoadIntersectionSimulation::setGenerationMethod(GENMETHOD method)
{
m_Generator->setMethod(method);
}
int RoadIntersectionSimulation::VehiclesNumber() const
{
return m_Scene->getVehicle().size();
}
SimulationScene *RoadIntersectionSimulation::Scene() const
{
return m_Scene;
}
| 5,926
|
C++
|
.cpp
| 195
| 23.876923
| 104
| 0.66538
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,198
|
trafficdetector.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Entities/trafficdetector.cpp
|
#include "trafficdetector.h"
QRectF TrafficDetector::boundingRect() const
{
return QRectF(0,0,12,static_cast<qreal>(m_detector_length));
}
void TrafficDetector::paint(QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
if(m_is_active){
painter->setPen(QColor("#2ecc71"));
}else{
painter->setPen(QColor("#e74c3c"));
}
painter->drawRect(boundingRect());
painter->setOpacity(0.5);
}
TrafficDetector::TrafficDetector(float length, QGraphicsItem *parent)
:QGraphicsItem(parent)
,m_detector_length(length)
,m_flow(0)
,m_number_of_vehicle(0)
,m_density(0)
,m_saturation_flow_rate(0)
,m_is_active(false)
,m_isOn(true)
{
setTransformOriginPoint(QPointF(15/2,static_cast<qreal>(m_detector_length)/2));
m_timer = new QElapsedTimer;
//m_counter = new QTimer();
}
TrafficDetector::~TrafficDetector()
{
delete m_timer;
}
void TrafficDetector::advance(int phase)
{
Q_UNUSED(phase);
if(m_isOn){
if(this->getNumbersOfVehicles() > 0){
m_is_active = true;
}else{
m_timer->restart();
//qDebug()<<"Hello";
m_is_active = false;
}
update(boundingRect());
}else{
return;
}
// QList<QGraphicsItem *> collding_vehicles = this->collidingItems();
// //qDebug()<<"Size "<<collding_vehicles.size();
// for(int i = 0 ; i < collding_vehicles.size() ; ++i){
// Vehicle *collding = dynamic_cast<Vehicle *>(collding_vehicles.at(i));
// if(collding){
// m_is_active = true;
// }else{
// m_timer->restart();
// //qDebug()<<"Hello";
// m_is_active = false;
// }
// }
// qDebug()<<m_is_active;
// qDebug()<<"Number "<<getNumbersOfVehicles();
// qDebug()<<"Flow "<<getFlow();
// qDebug()<<"Headway"<<getHeadWay();
// qDebug()<<"Density "<<getDensity();
// qDebug()<<"Hello";
}
void TrafficDetector::forward()
{
if(m_isOn){
if(this->getNumbersOfVehicles() > 0){
m_is_active = true;
}else{
m_timer->restart();
//qDebug()<<"Hello";
m_is_active = false;
}
update(boundingRect());
}else{
return;
}
// //qDebug()<<"Size "<<collding_vehicles.size();
// for(int i = 0 ; i < collding_vehicles.size() ; ++i){
// Vehicle *collding = dynamic_cast<Vehicle *>(collding_vehicles.at(i));
// if(collding){
// m_is_active = true;
// }else{
// m_timer->restart();
// //qDebug()<<"Hello";
// m_is_active = false;
// }
// }
}
//bool TrafficDetector::getIs_active() const
//{
// return m_is_active;
//}
QElapsedTimer *TrafficDetector::getTimer() const
{
return m_timer;
}
float TrafficDetector::getFlow() const
{
if(m_is_active){
//qDebug()<<"Number "<<(static_cast<float>(m_timer->elapsed()));
return (getNumbersOfVehicles()/(static_cast<float>(m_timer->elapsed())))*1000;
}else{
return 0;
}
}
bool TrafficDetector::isContainedVehicles() const
{
return m_is_active;
}
int TrafficDetector::getNumbersOfVehicles() const
{
// if(m_is_active){
// QList<QGraphicsItem *> collding_vehicles = this->collidingItems();
// int j = 0;
// for(int i = 0 ; i < collding_vehicles.size() ; ++i){
// Vehicle *collding = dynamic_cast<Vehicle *>(collding_vehicles.at(i));
// if(collding){
// j++;
// }
// }
// return j;
// }else{
// return 0;
// }
QList<QGraphicsItem *> collding_vehicles = this->collidingItems();
int j = 0;
for(int i = 0 ; i < collding_vehicles.size() ; ++i){
Vehicle *collding = dynamic_cast<Vehicle *>(collding_vehicles.at(i));
if(collding){
j++;
}
}
//qDebug()<<"Collided Item: "<<collding_vehicles.size()<<"Vehicles: "<<j
; return j;
}
float TrafficDetector::getDensity() const
{
return getNumbersOfVehicles()/(m_detector_length/m_detector_length);
}
float TrafficDetector::getHeadWay() const
{
if(m_is_active){
// qDebug()<<"Number "<<(m_timer->elapsed());
return ((static_cast<float>(m_timer->elapsed()))/getNumbersOfVehicles())/1000;
}else{
return 0;
}
}
void TrafficDetector::turnOffDisplay()
{
setOpacity(0.0);
}
void TrafficDetector::turnOnDisplay()
{
setOpacity(1.0);
}
void TrafficDetector::turnOn()
{
m_isOn = true;
m_timer->start();
}
void TrafficDetector::turnOff()
{
m_isOn = false;
m_timer->invalidate();
}
//void TrafficDetector::startEngine()
//{
// if(m_counter->isActive()){
// return;
// }else{
// this->connect(m_counter,SIGNAL(timeout()),this,SLOT(forward()));
// m_counter->start(TIME_UNIT);
// }
// m_is_active = true;
//}
//void TrafficDetector::stopEngine()
//{
// this->disconnect(m_counter,SIGNAL(timeout()),this,SLOT(forward()));
// this->m_counter->stop();
// m_is_active = false;
//}
| 5,163
|
C++
|
.cpp
| 190
| 23.5
| 86
| 0.583552
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,199
|
trafficcontroller.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Entities/trafficcontroller.cpp
|
#include "trafficcontroller.h"
TrafficController::TrafficController(QGraphicsItemGroup *parent):QGraphicsItemGroup(parent)
{
//m_state = new QStateMachine();
// ArrageDetector
setAcceptHoverEvents(true);
for(int i = 0 ; i < 12 ; ++i){
m_detector.append(new TrafficDetector(LENGTH));
}
QPointF p1(364,380);
QPointF p2(364-15,380);
QPointF p3(364-30,380);
// Detector 12,11,10
QGraphicsItemGroup *group1 = new QGraphicsItemGroup();
for(int i = 0 ; i < 3 ; ++i){
group1->addToGroup(m_detector.at(i));
}
this->addToGroup(group1);
m_detector.at(0)->setPos(p1);
m_detector.at(1)->setPos(p2);
m_detector.at(2)->setPos(p3);
// Detector 9,8,7
QGraphicsItemGroup *group2 = new QGraphicsItemGroup();
for(int i = 3 ; i < 6 ; ++i){
group2->addToGroup(m_detector.at(i));
}
this->addToGroup(group2);
m_detector.at(3)->setPos(p1);
m_detector.at(4)->setPos(p2);
m_detector.at(5)->setPos(p3);
group2->setRotation(90);
group2->moveBy(628,-30);
// Detector 6,5,4
QGraphicsItemGroup *group3 = new QGraphicsItemGroup();
for(int i = 6 ; i < 9 ; ++i){
group3->addToGroup(m_detector.at(i));
}
this->addToGroup(group3);
m_detector.at(6)->setPos(p1);
m_detector.at(7)->setPos(p2);
m_detector.at(8)->setPos(p3);
group3->setRotation(90);
group3->moveBy(870,-75.5);
// Detector 3,2,1
QGraphicsItemGroup *group4 = new QGraphicsItemGroup();
for(int i = 9 ; i < 12 ; ++i){
group4->addToGroup(m_detector.at(i));
}
this->addToGroup(group4);
m_detector.at(9)->setPos(p1);
m_detector.at(10)->setPos(p2);
m_detector.at(11)->setPos(p3);
group4->moveBy(-49,-243);
//Create Traffic Light
for(int i = 0 ; i < 4 ; ++i){
m_traffic_light.append(new TrafficLight());
m_traffic_light.at(i)->setUpFacilities();
}
//Arrange Traffic Light
//TrafficLight 1
m_traffic_light.at(0)->setPos(400,380);
m_traffic_light.at(0)->setRegion(region::REGION_S_N);
//m_traffic_light->at(0)->setInitialState(STATE_MACHINE::Green_Going_Left);
//TrafficLight 2
m_traffic_light.at(1)->setRotation(90);
m_traffic_light.at(1)->setPos(260,380);
m_traffic_light.at(1)->setRegion(region::REGION_W_E);
//m_traffic_light->at(1)->setInitialState(STATE_MACHINE::Red_Going_Yellow);
//TrafficLight 3
m_traffic_light.at(2)->setPos(250,240);
m_traffic_light.at(2)->setRotation(180);
m_traffic_light.at(2)->setRegion(region::REGION_N_S);
//m_traffic_light->at(2)->setInitialState(STATE_MACHINE::Green_Going_Left);
// m_traffic_light->at(2)->setTransform(QTransform::fromScale(1, -1));
//TrafficLight 4
m_traffic_light.at(3)->setPos(410,230);
m_traffic_light.at(3)->setRotation(270);
m_traffic_light.at(3)->setRegion(region::REGION_E_W);
//m_traffic_light->at(3)->setInitialState(STATE_MACHINE::Red_Going_Yellow);
//m_traffic_light->at(3)->setTransform(QTransform::fromScale(-1, 1));
for(int i = 0 ; i < m_traffic_light.size() ; ++i){
for(int j = 0 ; j < m_traffic_light.at(i)->getLight()->size() ; j++){
m_traffic_light.at(i)->getLight()->at(j)->setScale(0.8);
}
}
for(size_t i = 0 ; i < getDetector().size() ; ++i){
getDetector().at(i)->setOpacity(0);
}
}
TrafficLight *TrafficController::getTrafficLight(region r)
{
for(int i = 0 ; i < m_traffic_light.size() ; ++i){
if(m_traffic_light.at(i)->getRegion() == r){
return m_traffic_light.at(i);
}
}
return nullptr;
}
//void TrafficController::turnTrafficOn()
//{
// if(!m_state){
// return;
// }
// m_state->start();
//}
//void TrafficController::turnTrafficOff()
//{
// if(!m_state){
// return;
// }
// m_state->stop();
//}
void TrafficController::turnOffDetector()
{
for(int i = 0 ; i < m_detector.size() ; ++i){
m_detector.at(i)->turnOff();
}
}
void TrafficController::turnOnDetector()
{
for(int i = 0 ; i < m_detector.size() ; ++i){
m_detector.at(i)->turnOn();
}
}
void TrafficController::showDetector()
{
for(int i = 0 ; i < m_detector.size() ; ++i){
m_detector.at(i)->turnOnDisplay();
}
}
void TrafficController::hideDetector()
{
for(int i = 0 ; i < m_detector.size() ; ++i){
m_detector.at(i)->turnOffDisplay();
}
}
void TrafficController::startTrafficLightAll()
{
for(int i = 0 ; i < m_traffic_light.size() ; ++i){
m_traffic_light.at(i)->startTrafficLight();
m_traffic_light.at(i)->setMode(TRAFFICMODE::HAS_SIGNAL);
}
}
void TrafficController::stopTrafficLightAll()
{
for(int i = 0 ; i < m_traffic_light.size() ; ++i){
m_traffic_light.at(i)->stopTrafficLight();
m_traffic_light.at(i)->setMode(TRAFFICMODE::NO_SIGNAL);
}
}
void TrafficController::manualControl()
{
for(int i = 0 ; i < m_traffic_light.size() ; ++i){
m_traffic_light.at(i)->stopTrafficLight();
m_traffic_light.at(i)->setMode(TRAFFICMODE::HAS_SIGNAL);
}
}
void TrafficController::setLightDuration(const int &green, const int &left, const int &yellow, const int &red)
{
for(int i = 0 ; i < m_traffic_light.size() ; ++i){
m_traffic_light.at(i)->setDuration(left,yellow,green,red);
}
m_traffic_light.at(0)->setInitialState(STATE_MACHINE::Green_Going_Left);
m_traffic_light.at(1)->setInitialState(STATE_MACHINE::Red_Going_Yellow);
m_traffic_light.at(2)->setInitialState(STATE_MACHINE::Green_Going_Left);
m_traffic_light.at(3)->setInitialState(STATE_MACHINE::Red_Going_Yellow);
}
QList<TrafficLight *> TrafficController::getTraffic_light()
{
return m_traffic_light;
}
QList<QElapsedTimer *> *TrafficController::getTimer()
{
QList<QElapsedTimer *> *time = new QList<QElapsedTimer *>();
for(int i = 0 ; i < m_detector.size() ; i++){
time->append(m_detector.at(i)->getTimer());
}
return time;
}
void TrafficController::updateDetectors()
{
for(int i = 0 ; i < m_detector.size() ; ++i){
m_detector.at(i)->forward();
}
}
void TrafficController::turnOffLightInteraction()
{
for(int i = 0 ; i < m_traffic_light.size() ; ++i){
m_traffic_light.at(i)->turnOffInteraction();
}
}
void TrafficController::turnOnLightInteraction()
{
for(int i = 0 ; i < m_traffic_light.size() ; ++i){
m_traffic_light.at(i)->turnOnInteraction();
}
}
QList<TrafficDetector *> TrafficController::getDetector()
{
return m_detector;
}
QList<TrafficDetector *> TrafficController::getDetectorByRegion(region x) const
{
QList<TrafficDetector *> d;
switch (x) {
case region::REGION_S_N :
for(int i = 0 ; i < 3 ; ++i){
d.append(m_detector.at(i));
}
return d;
case region::REGION_W_E :
for(int i = 3 ; i < 6 ; ++i){
d.append(m_detector.at(i));
}
return d;
case region::REGION_N_S :
for(int i = 6 ; i < 9 ; ++i){
d.append(m_detector.at(i));
}
return d;
case region::REGION_E_W :
for(int i = 9 ; i < 12 ; ++i){
d.append(m_detector.at(i));
}
return d;
}
return d;
}
| 7,336
|
C++
|
.cpp
| 228
| 27.008772
| 110
| 0.612334
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,200
|
vehiclesight.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Entities/Vehicle/vehiclesight.cpp
|
#include "vehiclesight.h"
#include "vehicle.h"
VehicleSight::VehicleSight(const QRectF &rec, QGraphicsItem *parent)
:QGraphicsRectItem (rec,parent)
,m_vehicle(dynamic_cast<Vehicle *>(parent))
{
this->setBrush(Qt::NoBrush);
QPen tick;
tick.setWidth(1);
tick.setColor(Qt::black);
this->setPen(tick);
}
Vehicle *VehicleSight::vehicle() const
{
return m_vehicle;
}
| 394
|
C++
|
.cpp
| 16
| 21.5625
| 68
| 0.71618
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,201
|
vehicle.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Entities/Vehicle/vehicle.cpp
|
#include "vehicle.h"
#include "UI/simulationscene.h"
#include <QGraphicsSceneHoverEvent>
//Declear static Macro variable
//static const double Pi = 3.14159265358979323846264338327950288419717;
//static double TwoPi = 2.0*Pi;
Vehicle::Vehicle(QGraphicsItem *parent)
:QGraphicsPixmapItem(parent)
,m_angle(0)
,m_speed(0)
,m_acceleration(ACCER)/*,m_color(qrand()%256,qrand()%256,qrand()%256)*/
,m_point_index(0)
,m_step_count(0)
,m_driving_state(false)
,m_mode(VEHICLEMETHOD::SIGHTSEEING)
,m_Is_deletable(false)
,m_leader(nullptr)
{
//m_internal_timer = new QTimer;
m_sightseeing = new VehicleSight(QRectF(30,5,GAPACCAPANCE * 4,10),this);
m_sightseeing_small = new VehicleSight(QRectF(30,5,GAPACCAPANCE,10),this);
m_sightseeing_small->setPen(QPen(QColor(Qt::red)));
m_sightseeing_small->setOpacity(0);
m_sightseeing->setOpacity(0);
setTransformOriginPoint(10,5);
setAcceptHoverEvents(true);
setFlag(QGraphicsItem::ItemIsMovable);
//this->setCacheMode(QGraphicsItem::ItemCoordinateCache);
setOffset(10,5);
setPixmap(generateImage().scaled(25,13,Qt::KeepAspectRatio,
Qt::TransformationMode::SmoothTransformation));
}
Vehicle::~Vehicle()
{
//qDebug()<<"Delete "<<this->objectName();
delete m_sightseeing;
delete m_sightseeing_small;
//delete m_internal_timer;
}
QRectF Vehicle::boundingRect() const
{
return QRectF(10,5,20,10);
}
QPainterPath Vehicle::shape() const
{
QPainterPath path;
path.addRect(boundingRect());
return path;
}
//void Vehicle::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
//{
// Q_UNUSED(option);
// Q_UNUSED(widget);
// painter->setPen(Qt::NoPen);
// painter->setBrush(m_color);
// painter->drawRect(boundingRect());
//}
void Vehicle::rotate_to_point(QPointF point)
{
QLineF line(pos(),point);
setRotation(-1*line.angle());
}
void Vehicle::extract_coordinate(QPainterPath path)
{
for(double i = 0;i <= 1;i += 0.01){
//m_path_to_follow<<mapToScene(path->path().pointAtPercent(i));
m_path_to_follow<<QPointF(path.pointAtPercent (i));
m_step_count++;
}
//qDebug()<<m_path_to_follow;
}
void Vehicle::setDirection(Direction dir)
{
m_dir = dir;
}
void Vehicle::initialize()
{
m_destination = m_path_to_follow[0];
rotate_to_point(m_destination);
setPos(m_destination);
}
void Vehicle::setRegion(region r)
{
m_region = r;
}
bool Vehicle::is_in_stop_point()
{
if(m_point_index > 34 && m_point_index < 39){
return true;
}else{
return false;
}
}
void Vehicle::reset_speed()
{
m_speed = 0;
}
void Vehicle::decelerate(QPointF rhs)
{
}
void Vehicle::accelerate()
{
m_speed += ACCER;
}
void Vehicle::accelerate(Vehicle *leader)
{
m_acceleration = 3*(leader->getSpeed()-this->getSpeed())/distanceToOtherVehicle(leader);
//qDebug()<<"Acc: "<<m_acceleration;
m_speed += m_acceleration;
}
QList<QPointF> Vehicle::get_path() const
{
return m_path_to_follow;
}
bool Vehicle::Isinthejunction()
{
if(m_point_index > 40){
return true;
}
else{
return false;
}
}
QPointF Vehicle::get_position() const
{
return this->pos ();
}
int Vehicle::get_current_index() const
{
return m_point_index;
}
QPointF Vehicle::get_initial_path() const
{
return m_path_to_follow[0];
}
void Vehicle::stop_advance()
{
m_speed = 0;
}
bool Vehicle::isInsideIntersection()
{
if(m_point_index > 35 && m_point_index < 55){
return true;
}else{
return false;
}
}
qreal Vehicle::getSpeed() const
{
return m_speed;
}
void Vehicle::turnOffInteraction()
{
setAcceptHoverEvents(false);
setFlag(QGraphicsItem::ItemIsMovable,false);
}
void Vehicle::turnOnInteraction()
{
setAcceptHoverEvents(true);
setFlag(QGraphicsItem::ItemIsMovable,true);
}
void Vehicle::advance(int phase)
{
Q_UNUSED(phase)
if(this->is_in_stop_point()){
if(this->isContainedSignal()){
if(!this->ifAllowed()){
stop_advance();
return;
}
}
}
if( m_mode == VEHICLEMETHOD::SIGHTSEEING){
if(hasInfront()){
if(isAboutToCrash()){
stop_advance();
return;
}
accelerate(m_leader);
}else{
m_leader = nullptr;
accelerate();
}
}else{
m_leader = nullptr;
m_acceleration = ACCER;
accelerate();
}
QLineF line(pos(),m_destination);
//qDebug()<<"Length"<<line.length();
if(int(line.length()) <= 1.0){
m_point_index++;
if(m_point_index >= m_path_to_follow.size()){
m_Is_deletable = true;
return;
}
m_destination = m_path_to_follow[m_point_index];
rotate_to_point(m_destination);
}
double theta = rotation();
double dy = m_speed*qSin(qDegreesToRadians(theta));
double dx = m_speed*qCos(qDegreesToRadians(theta));
setPos(x()+dx,y()+dy);
}
void Vehicle::update(const VEHICLEMETHOD &mode)
{
if(this->is_in_stop_point()){
if(this->isContainedSignal()){
if(!this->ifAllowed()){
stop_advance();
return;
}
}
}
if(mode == VEHICLEMETHOD::SIGHTSEEING){
if(hasInfront()){
if(isAboutToCrash()){
stop_advance();
return;
}
accelerate(m_leader);
}else{
m_leader = nullptr;
accelerate();
}
}else{
m_leader = nullptr;
m_acceleration = ACCER;
accelerate();
}
QLineF line(pos(),m_destination);
//qDebug()<<"Length"<<line.length();
if(int(line.length()) <= 1.0){
m_point_index++;
if(m_point_index >= m_path_to_follow.size()){
m_Is_deletable = true;
return;
}
m_destination = m_path_to_follow[m_point_index];
rotate_to_point(m_destination);
}
double theta = rotation();
double dy = m_speed*qSin(qDegreesToRadians(theta));
double dx = m_speed*qCos(qDegreesToRadians(theta));
setPos(x()+dx,y()+dy);
}
Vehicle *Vehicle::getCollding()
{
Vehicle *next = nullptr;
QList<QGraphicsItem *> list_of_collding_vehicle = m_sightseeing->collidingItems();
for(int i = 0 ; i < list_of_collding_vehicle.size() ; ++i){
next = dynamic_cast<Vehicle *>(list_of_collding_vehicle.at(i));
if(next&&(next !=this)){
return next;
}
}
return nullptr;
}
Vehicle *Vehicle::nextVehicle()
{
Vehicle *next = nullptr;
QList<QGraphicsItem *> list_of_collding_vehicle = m_sightseeing->collidingItems();
for(int i = 0 ; i < list_of_collding_vehicle.size() ; ++i){
next = dynamic_cast<Vehicle *>(list_of_collding_vehicle.at(i));
if(next&&(next !=this)){
return next;
}
}
return this;
}
SimulationScene *Vehicle::myScene() const
{
SimulationScene* scene = dynamic_cast<SimulationScene*>(this->scene());
if(scene){
return scene;
}
return nullptr;
}
double Vehicle::distanceToOtherVehicle(QGraphicsItem *v) const
{
return sqrt((v->x() - this->x())*(v->x() - this->x()) + (v->y() - this->y())*(v->y() - this->y()) );
}
void Vehicle::adjustSpeedIntersection()
{
//qDebug()<<"True";
if(isInsideIntersection()){
m_speed -= ACCER/10;
if(qFuzzyCompare(m_speed,0.0)){
accelerate();
}
}else{
accelerate();
}
}
void Vehicle::adjustSpeedIntersection(Vehicle *leader)
{
if(isInsideIntersection()){
m_speed -= ACCER/10;
if(qFuzzyCompare(m_speed,0.0)){
accelerate();
}
}else{
accelerate(leader);
}
}
bool Vehicle::hasInfront()
{
//VehicleSight *next = nullptr;
Vehicle* leader = nullptr;
QList<QGraphicsItem *> list_of_collding_vehicle = m_sightseeing->collidingItems();
for(int i = 0 ; i < list_of_collding_vehicle.size() ; ++i){
leader = dynamic_cast<Vehicle *>(list_of_collding_vehicle.at(i));
if(leader&&(leader !=this)){
m_leader = leader;
this->m_sightseeing->setPen(QPen(QColor(Qt::red)));
//qDebug()<<"True";
return true;
}
}
this->m_sightseeing->setPen(QPen(QColor(Qt::black)));
//m_acceleration = 0.01;
return false;
}
bool Vehicle::isAboutToCrash() const
{
Vehicle* leader = nullptr;
QList<QGraphicsItem *> list_of_collding_vehicle = m_sightseeing_small->collidingItems();
for(int i = 0 ; i < list_of_collding_vehicle.size() ; ++i){
leader = dynamic_cast<Vehicle *>(list_of_collding_vehicle.at(i));
if(leader&&(leader !=this)){
this->m_sightseeing_small->setPen(QPen(QColor(Qt::red)));
//qDebug()<<"True";
//m_sightseeing_small->setOpacity(1);
return true;
}
}
//m_sightseeing_small->setOpacity(0);
return false;
}
void Vehicle::setMode(const VEHICLEMETHOD &mode)
{
m_mode = mode;
}
bool Vehicle::isDeletable() const
{
return m_Is_deletable;
}
//void Vehicle::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
//{
// qDebug()<<"Car's Position: "<<this->pos();
//}
void Vehicle::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
setCursor(Qt::OpenHandCursor);
//QGraphicsItem::hoverEnterEvent(event);
}
void Vehicle::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
setCursor(Qt::ArrowCursor);
}
void Vehicle::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
setCursor(Qt::ClosedHandCursor);
}
QPixmap Vehicle::generateImage() const
{
switch (qrand()%18) {
case 0:
return QPixmap(":/cars/Image/Cars/Asset 1.png");
case 1:
return QPixmap(":/cars/Image/Cars/Asset 2.png");
case 2:
return QPixmap(":/cars/Image/Cars/Asset 3.png");
case 3:
return QPixmap(":/cars/Image/Cars/Asset 4.png");
case 4:
return QPixmap(":/cars/Image/Cars/Asset 5.png");
case 5:
return QPixmap(":/cars/Image/Cars/Asset 6.png");
case 6:
return QPixmap(":/cars/Image/Cars/Asset 7.png");
case 7:
return QPixmap(":/cars/Image/Cars/Asset 8.png");
case 8:
return QPixmap(":/cars/Image/Cars/Asset 9.png");
case 9:
return QPixmap(":/cars/Image/Cars/Asset 10.png");
case 10:
return QPixmap(":/cars/Image/Cars/Asset 11.png");
case 11:
return QPixmap(":/cars/Image/Cars/Asset 12.png");
case 12:
return QPixmap(":/cars/Image/Cars/Asset 13.png");
case 13:
return QPixmap(":/cars/Image/Cars/Asset 14.png");
case 14:
return QPixmap(":/cars/Image/Cars/Asset 15.png");
case 15:
return QPixmap(":/cars/Image/Cars/Asset 16.png");
case 16:
return QPixmap(":/cars/Image/Cars/Asset 17.png");
case 17:
return QPixmap(":/cars/Image/Cars/Asset 18.png");
}
}
Direction Vehicle::getDir() const
{
return m_dir;
}
void Vehicle::setDir(const Direction &dir)
{
m_dir = dir;
}
void Vehicle::turnOnSightSeeing()
{
m_sightseeing->setOpacity(1.0);
}
void Vehicle::turnOffSightSeeing()
{
m_sightseeing->setOpacity(0.0);
}
//void Vehicle::turnOnEngine()
//{
// if(m_internal_timer->isActive()){
// return;
// }else{
// this->connect(m_internal_timer,SIGNAL(timeout()),this,SLOT(forward()));
// m_internal_timer->start(TIME_UNIT);
// }
// m_on_action_state = true;
//}
//void Vehicle::turnOffEngine()
//{
// this->disconnect(m_internal_timer,SIGNAL(timeout()),this,SLOT(forward()));
// m_internal_timer->stop();
// m_on_action_state = false;
//}
bool Vehicle::isContainedSignal() const
{
// QList<QGraphicsItem *> item = scene()->items();
QList<TrafficLight *> light_list = myScene()->getTrafficLight();
// for(int i = 0 ; i < item.size() ; ++i){
// TrafficLight *light = dynamic_cast<TrafficLight *>(item.at(i));
// if(light){
// light_list.append(light);
// }
// }
for(int i = 0 ; i < light_list.size() ; ++i){
if(light_list.at(i)->getMode() == TRAFFICMODE::HAS_SIGNAL){
return true;
}
}
return false;
}
region Vehicle::getRegion() const
{
return m_region;
}
bool Vehicle::ifAllowed() const
{
//QList<QGraphicsItem *> item = scene()->items();
QList<TrafficLight *> light_list = myScene()->getTrafficLight();
// for(int i = 0 ; i < item.size() ; ++i){
// TrafficLight *light = dynamic_cast<TrafficLight *>(item.at(i));
// if(light){
// light_list.append(light);
// }
// }
for(int i = 0 ; i < light_list.size() ; ++i){
if(light_list.at(i)->getRegion() == this->getRegion()){
return light_list.at(i)->checkDir(this->getDir());
}
}
return false;
}
| 13,035
|
C++
|
.cpp
| 475
| 22.374737
| 104
| 0.615606
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,202
|
trafficlight.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Entities/TrafficLight/trafficlight.cpp
|
#include "trafficlight.h"
QRectF TrafficLight::boundingRect() const
{
return QRectF(0,0,WidgetDimension*4,WidgetDimension);
}
void TrafficLight::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setPen(Qt::NoPen);
painter->setRenderHint(QPainter::Antialiasing);
painter->setBrush(QBrush(QColor("#2c3e50")));
painter->drawRoundedRect(boundingRect(),8,8);
//setAcceptHoverEvents(true);
//painter->drawRect(this->boundingRect());
}
TrafficLight::TrafficLight(region re, QGraphicsItem *parent)
:QGraphicsItem(parent)
,m_region(re)
{
}
TrafficLight::TrafficLight(QGraphicsItem *parent)
:QGraphicsItem (parent)
,m_red_duration(0)
,m_left_duration(0)
,m_main_green_duration(0)
,m_yellow_duration(0)
,m_mode(TRAFFICMODE::NO_SIGNAL)
,m_state_machine(new QStateMachine(this))
{
}
TrafficLight::~TrafficLight()
{
}
region TrafficLight::getRegion()
{
return m_region;
}
bool TrafficLight::checkDir(Direction dir)
{
switch (dir) {
case Direction::LEFT_TURNING :
//qDebug()<<"Hello";
return getLeftGreen()->isOn();
case Direction::RIGHT_TURNING :
return getMainGreen()->isOn();
// return true;
case Direction::THROUGH :
return getMainGreen()->isOn();
}
return false;
}
void TrafficLight::setManualControl()
{
for(int i = 0 ; i < m_light->size() ; ++i){
if(i != 3){
m_light->at(i)->turnOff();
}else{
m_light->at(i)->turnOn();
}
}
}
void TrafficLight::setUpFacilities()
{
// Setup light and attach color
m_left_light = new LightWidgetLeft(QColor("#2ecc71"),this);
//this->addToGroup(m_left_light);
m_main_light_green = new LightWidget(QColor("#2ecc71"),this);
//this->addToGroup(m_main_light_green);
m_main_light_green->moveBy(LightSize,0);
m_main_light_yellow = new LightWidget(QColor("#f1c40f"),this);
//this->addToGroup(m_main_light_yellow);
m_main_light_yellow->moveBy(LightSize*2,0);
m_main_light_red = new LightWidget(QColor("#e74c3c"),this);
//this->addToGroup(m_main_light_red);
m_main_light_red->moveBy(LightSize*3,0);
m_light = new QList<LightWidget *>();
m_light->append(m_left_light);
m_light->append(m_main_light_green);
m_light->append(m_main_light_yellow);
m_light->append(m_main_light_red);
setFlag(QGraphicsItem::ItemIsMovable);
}
void TrafficLight::setDuration(const int &left, const int &yellow, const int &green, const int &red)
{
m_red_duration = red;
m_left_duration = left;
m_yellow_duration = yellow;
m_main_green_duration = green;
// setup state to light
// Create main green going to left light state
m_MainGreen_Going_Left = makeState(m_main_light_green,m_main_green_duration);
m_MainGreen_Going_Left->setObjectName("Main Green Going Left");
// Create main left going to green light state
m_Left_Going_Yellow = makeState(m_left_light,m_left_duration);
m_Left_Going_Yellow->setObjectName("Left Going Yellow");
// Create yellow green going to red light state
m_Yellow_Going_Red = makeState(m_main_light_yellow,m_yellow_duration);
m_Yellow_Going_Red->setObjectName("Yellow Going Red");
// Create red green going to yellow light state
m_Red_Going_Yellow = makeState(m_main_light_red,m_red_duration);
m_Red_Going_Yellow->setObjectName("Red Going Yellow");
// Create yellow going to green light state
m_Yellow_Going_Green = makeState(m_main_light_yellow,m_yellow_duration);
m_Yellow_Going_Green->setObjectName("Yellow Going Green");
// Connect these two state : m_MainGreen_Going_Left -> m_Left_Going_Yellow
m_MainGreen_Going_Left->addTransition(m_MainGreen_Going_Left,SIGNAL(finished()),m_Left_Going_Yellow);
// Connect these two state : m_Yellow_Going_Left -> m_Left_Going_Red
m_Left_Going_Yellow->addTransition(m_Left_Going_Yellow,SIGNAL(finished()),m_Yellow_Going_Red);
// Connect these two state : m_Yellow_Going_Red -> m_Red_Going_Yellow
m_Yellow_Going_Red->addTransition(m_Yellow_Going_Red,SIGNAL(finished()),m_Red_Going_Yellow);
// Connect these two state : m_Red_Going_Yellow -> m_Yellow_Going_Green
m_Red_Going_Yellow->addTransition(m_Red_Going_Yellow,SIGNAL(finished()),m_Yellow_Going_Green);
// Connect these two state : m_MainGreen_Going_Left -> m_MainGreen_Going_Left
m_Yellow_Going_Green->addTransition(m_Yellow_Going_Green,SIGNAL(finished()),m_MainGreen_Going_Left);
// Create state machine
m_state_machine->addState(m_MainGreen_Going_Left);
m_state_machine->addState(m_Left_Going_Yellow);
m_state_machine->addState(m_Yellow_Going_Red);
m_state_machine->addState(m_Red_Going_Yellow);
m_state_machine->addState(m_Yellow_Going_Green);
}
void TrafficLight::setInitialState(const STATE_MACHINE &state)
{
switch (state) {
case STATE_MACHINE::Green_Going_Left:
m_state_machine->setInitialState(m_MainGreen_Going_Left);
break;
case STATE_MACHINE::Left_Going_Yellow:
m_state_machine->setInitialState(m_Left_Going_Yellow);
break;
case STATE_MACHINE::Yellow_Going_Red:
m_state_machine->setInitialState(m_Yellow_Going_Red);
break;
case STATE_MACHINE::Red_Going_Yellow:
m_state_machine->setInitialState(m_Red_Going_Yellow);
break;
case STATE_MACHINE::Yellow_Going_Green:
m_state_machine->setInitialState(m_Yellow_Going_Green);
break;
}
}
void TrafficLight::startTrafficLight()
{
if(!m_state_machine){
//qDebug()<<"Case 1";
return;
}else if(m_state_machine->isRunning()){
//qDebug()<<"Case 2";
return;
}else{
//qDebug()<<"Case 3";
m_state_machine->start();
}
}
void TrafficLight::stopTrafficLight()
{
if(!m_state_machine){
//qDebug()<<"Case 1";
return;
}else if(!m_state_machine->isRunning()){
//qDebug()<<"Case 2";
return;
}else{
qDebug()<<"Case 3";
m_state_machine->stop();
}
}
LightWidget *TrafficLight::getMainGreen() const
{
return m_main_light_green;
}
LightWidget *TrafficLight::getMainRed() const
{
return m_main_light_red;
}
LightWidget *TrafficLight::getMainYellow() const
{
return m_main_light_yellow;
}
LightWidget *TrafficLight::getLeftGreen() const
{
return m_left_light;
}
void TrafficLight::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
setCursor(Qt::SizeAllCursor);
}
void TrafficLight::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
setCursor(Qt::ArrowCursor);
}
void TrafficLight::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
setCursor(Qt::SizeAllCursor);
}
QList<LightWidget *> *TrafficLight::getLight() const
{
return m_light;
}
void TrafficLight::setRegion(const region ®ion)
{
m_region = region;
}
TRAFFICMODE TrafficLight::getMode() const
{
return m_mode;
}
void TrafficLight::setMode(const TRAFFICMODE &mode)
{
m_mode = mode;
}
void TrafficLight::turnOffInteraction()
{
setAcceptHoverEvents(false);
setFlag(QGraphicsItem::ItemIsMovable,false);
for(int i = 0 ; i < m_light->size() ; ++i){
m_light->at(i)->TurnOffInteraction();
}
}
void TrafficLight::turnOnInteraction()
{
setAcceptHoverEvents(true);
setFlag(QGraphicsItem::ItemIsMovable,true);
for(int i = 0 ; i < m_light->size() ; ++i){
m_light->at(i)->TurnOnInteraction();
}
}
QState *TrafficLight::makeState(LightWidget *light, int duration, QState *parent)
{
QState *lightState = new QState(parent);
QTimer *timer = new QTimer(lightState);
timer->setInterval(duration);
timer->setSingleShot(true);
QState *timing = new QState(lightState);
QObject::connect(timing,SIGNAL(entered()),light,SLOT(turnOn()));
QObject::connect(timing,SIGNAL(entered()),timer,SLOT(start()));
QObject::connect(timing,SIGNAL(exited()),light,SLOT(turnOff()));
QFinalState *done = new QFinalState(lightState);
timing->addTransition(timer,SIGNAL(timeout()),done);
lightState->setInitialState(timing);
return lightState;
}
//void TrafficLight::mousePressEvent(QGraphicsSceneMouseEvent *event)
//{
// qDebug()<<getRegion();
// qDebug()<<"Position "<<this->mapToScene(event->pos());
//}
//void TrafficLight::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
//{
// setCursor(QCursor(Qt::PointingHandCursor));
//}
| 8,494
|
C++
|
.cpp
| 252
| 29.472222
| 105
| 0.696722
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,203
|
lightwidget.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Entities/TrafficLight/lightwidget.cpp
|
#include "lightwidget.h"
#include "trafficlight.h"
QRectF LightWidget::boundingRect() const
{
return QRectF(0,0,LightSize,LightSize);
}
LightWidget::LightWidget(const QColor &color, QGraphicsItem *parent)
:QGraphicsItem(parent)
,m_color(color)
,m_on(false)
,m_IsClickable(true)
{
setTransformOriginPoint(LightSize/2,LightSize/2);
}
void LightWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
setAcceptHoverEvents(true);
painter->setPen(Qt::NoPen);
painter->setRenderHint(QPainter::Antialiasing);
painter->setBrush(m_color);
painter->drawEllipse(0, 0, this->boundingRect().width(), this->boundingRect().height());
if (!m_on){
setOpacity(0.3);
}else{
setOpacity(1.0);
}
setScale(LightScale);
}
//void LightWidget::setGeometry(const QRectF &rect)
//{
// prepareGeometryChange();
// QGraphicsLayoutItem::setGeometry(rect);
// qDebug()<<"Called";
// setPos(rect.topLeft());
//}
//QSizeF LightWidget::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
//{
// switch (which){
// case Qt::MinimumSize:
// case Qt::PreferredSize:
// return this->boundingRect().size();
// case Qt::MaximumSize:
// return QSizeF(400,400);
// default:
// break;
// }
// return constraint;
//}
QColor LightWidget::getColor() const
{
return m_color;
}
bool LightWidget::isOn() const
{
return m_on;
}
void LightWidget::setOn(bool on)
{
if (on == m_on)
return;
m_on = on;
update(0,0,LightSize,LightSize);
}
void LightWidget::setColor(const QColor &color)
{
m_color = color;
}
void LightWidget::TurnOnInteraction()
{
setAcceptHoverEvents(true);
m_IsClickable = true;
}
void LightWidget::TurnOffInteraction()
{
setAcceptHoverEvents(false);
m_IsClickable = false;
}
void LightWidget::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
//QGraphicsItem::mousePressEvent(event);
Q_UNUSED(event);
if(m_IsClickable){
if(!m_on){
this->turnOn();
if(dynamic_cast<TrafficLight *>(this->parentItem())){
QList<LightWidget *> *widget = (dynamic_cast<TrafficLight *>(this->parentItem()))->getLight();
for(int i = 0 ; i < widget->size() ; i++){
if(widget->at(i) != this){
widget->at(i)->turnOff();
}
}
}
}else{
this->turnOff();
}
}
}
void LightWidget::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
setCursor(Qt::PointingHandCursor);
}
void LightWidget::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
setCursor(QCursor(Qt::ArrowCursor));
}
//void LightWidget::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
//{
// setCursor(QCursor(Qt::PointingHandCursor));
//}
//void LightWidget::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
//{
// setCursor(QCursor(Qt::PointingHandCursor));
//}
void LightWidget::turnOff()
{
setOn(false);
}
void LightWidget::turnOn()
{
setOn(true);
}
| 3,149
|
C++
|
.cpp
| 123
| 21.634146
| 110
| 0.660465
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,204
|
lightwidgetleft.cpp
|
KimangKhenng_Traffic-SImulation-and-Visualization/Entities/TrafficLight/lightwidgetleft.cpp
|
#include "lightwidgetleft.h"
LightWidgetLeft::LightWidgetLeft(const QColor &color, QGraphicsItem *parent)
:LightWidget(color,parent)
{
setAcceptHoverEvents(true);
setTransformOriginPoint(LightSize/2,LightSize/2);
}
void LightWidgetLeft::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
static const QPointF points[3] = {QPointF(0,this->boundingRect().height()/2),QPointF(this->boundingRect().width(),0),QPointF(this->boundingRect().width(),this->boundingRect().height())};
painter->setRenderHint(QPainter::Antialiasing);
painter->setPen(Qt::NoPen);
painter->setBrush(getColor());
painter->drawPolygon(points,3,Qt::OddEvenFill);
painter->scale(0.8,0.8);
if (!isOn()){
setOpacity(0.3);
}else{
setOpacity(1.0);
}
setScale(LightScale);
}
| 883
|
C++
|
.cpp
| 24
| 32.541667
| 190
| 0.716453
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,205
|
commonenum.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/commonenum.h
|
#ifndef COMMONENUM_H
#define COMMONENUM_H
#include <QDebug>
#include <QTimer>
#include <QTime>
#define PARALLEL_OMP 0
#define PARALLEL_CONCURRENT 0
////////////////
#ifndef MAX_S_N
#define MAX_S_N 20
#endif
////////////////
#ifndef MAX_N_S
#define MAX_N_S 20
#endif
///////////////
#ifndef MAX_E_W
#define MAX_E_W 20
#endif
//////////////
#ifndef MAX_W_E
#define MAX_W_E 20
#endif
///////////////
#ifndef TIME_UNIT
#define TIME_UNIT 1/60 // refresh rate 60HZ
#endif
////////////////
/// \brief The Direction enum
enum SimulationState{STARTED,STOPPED,PAUSED,UNINITIALIZED,INITIALIZED};
enum Direction{LEFT_TURNING,THROUGH,RIGHT_TURNING};
enum region{REGION_E_W,REGION_N_S,REGION_W_E,REGION_S_N};
enum GENMETHOD{GEN_3,GEN_5,NO_TURN,ONLY_TURN};
enum TRAFFICMODE{NO_SIGNAL,HAS_SIGNAL};
enum VEHICLEMETHOD{SIGHTSEEING,GO_THROUGH};
enum STATE_MACHINE{Green_Going_Left,Left_Going_Yellow,Yellow_Going_Red,Red_Going_Yellow,Yellow_Going_Green};
struct SimulationInput{
int B_NS = 3500;
int B_SN = 3000;
int B_WE = 3900;
int B_EW = 3600;
int RED_LIGHT = 5000;
int GREEN_LIGHT = 3500;
int LEFT_GREEN_LIGHT = 1500;
int YELLOW_LIGHT = 500;
GENMETHOD METh = GENMETHOD::GEN_3;
VEHICLEMETHOD MODE = VEHICLEMETHOD::SIGHTSEEING;
bool ShowTrafficLight = true;
void trafficEasy()
{
B_NS = 4000;
B_SN = 3500;
B_WE = 3900;
B_EW = 4100;
}
void trafficModerate(){
B_NS = 2500;
B_SN = 2000;
B_WE = 2900;
B_EW = 2500;
}
void trafficBusy(){
B_NS = 1700;
B_SN = 1900;
B_WE = 1900;
B_EW = 1600;
}
void LightingQuick(){
RED_LIGHT = 3000;
GREEN_LIGHT = 2000;
LEFT_GREEN_LIGHT = 1000;
YELLOW_LIGHT = 500;
}
void LightingModerate(){
RED_LIGHT = 5000;
GREEN_LIGHT = 3500;
LEFT_GREEN_LIGHT = 1500;
YELLOW_LIGHT = 500;
}
void LightingLong(){
RED_LIGHT = 7000;
GREEN_LIGHT = 5000;
LEFT_GREEN_LIGHT = 2000;
YELLOW_LIGHT = 500;
}
void ExperimentalCrazy(){
B_NS = 500;
B_SN = 700;
B_WE = 900;
B_EW = 200;
METh = GENMETHOD::GEN_5;
MODE = VEHICLEMETHOD::GO_THROUGH;
ShowTrafficLight = false;
}
void ExperimentalFreeForAll(){
trafficModerate();
LightingModerate();
ShowTrafficLight = false;
}
void random(){
qsrand(static_cast<uint>(QTime(0,0,0).secsTo(QTime::currentTime())));
switch (qrand()%2) {
case 0:
switch (qrand()%3) {
case 0:
trafficEasy();
break;
case 1:
trafficModerate();
break;
case 2:
trafficBusy();
break;
}
switch (qrand()%3) {
case 0:
LightingQuick();
break;
case 1:
LightingModerate();
break;
case 2:
LightingLong();
break;
}
break;
case 1:
switch (qrand()%2) {
case 0:
ExperimentalCrazy();
break;
case 1:
ExperimentalFreeForAll();
break;
}
break;
}
}
};
#endif // COMMONENUM_H
| 3,465
|
C++
|
.h
| 140
| 17.235714
| 108
| 0.52943
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,206
|
intropage.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/intropage.h
|
#ifndef INTROPAGE_H
#define INTROPAGE_H
#include "Utilities/qlightboxwidget.h"
#include <QTimer>
namespace Ui {
class IntroPage;
}
class IntroPage : public QLightBoxWidget
{
Q_OBJECT
public:
explicit IntroPage( QWidget *parent = 0);
// void AutoUpdate(const bool& x);
~IntroPage();
signals:
void PlayClicked();
void ExitClicked();
void AboutClicked();
void HelpClicked();
public slots:
void on_m_PlayButton_clicked();
void on_m_ExitButton_clicked();
void on_m_AboutButton_clicked();
void on_m_HelpButton_clicked();
void repaintWidget();
private:
Ui::IntroPage *ui;
//QTimer *m_timer;
};
#endif // INTROPAGE_H
| 681
|
C++
|
.h
| 30
| 19.4
| 45
| 0.711599
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,207
|
simulationcontrolwidget.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/simulationcontrolwidget.h
|
#ifndef SIMULATIONCONTROLWIDGET_H
#define SIMULATIONCONTROLWIDGET_H
#include "Utilities/roadintersectionsimulation.h"
namespace Ui {
class SimulationControlWidget;
}
class SimulationControlWidget : public QWidget
{
Q_OBJECT
public:
explicit SimulationControlWidget(QWidget *parent = 0);
// void installSimulation(RoadIntersectionSimulation *instance);
~SimulationControlWidget();
private slots:
void on_start_simulation_button_clicked();
void on_random_setup_clicked();
void on_help_setup_button_clicked();
signals:
void inputedReady(double north_south,
double south_north,
double west_east,
double east_west,
double red_ligt,
double green_light,
double left_green);
void helpClicked();
void randomClicked();
private:
Ui::SimulationControlWidget *ui;
// RoadIntersectionSimulation *m_Simulation;
};
#endif // SIMULATIONCONTROLWIDGET_H
| 1,023
|
C++
|
.h
| 32
| 25.28125
| 67
| 0.689093
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,208
|
visualizepanel.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/visualizepanel.h
|
#ifndef VISUALIZEPANEL_H
#define VISUALIZEPANEL_H
#include <QFile>
#include <QDir>
#include <QString>
#include "Utilities/qcustomplot.h"
#include "Entities/trafficcontroller.h"
#define X_NUM_RANG 20;
#define Y_NUM_RANG 20;
#define X_FLOW_MAX 20;
#define Y_FLOW_MAX 20;
#define X_DEN_MAX 10;
#define Y_DEN_MAX 20;
#define X_HEAD_MAX 20;
#define Y_HEAD_MAX 20;
#define RESET_RANGED 20
namespace Ui {
class VisualizePanel;
}
class MainWindow;
class VisualizePanel : public QWidget
{
Q_OBJECT
public:
explicit VisualizePanel(QWidget *parent = nullptr);
//void initialize();
//void setEtimer(QList<QElapsedTimer *> *etimer);
void setController(TrafficController *controller);
~VisualizePanel() override;
//private slots:
// void update_1();
// void update_2();
// void update_3();
// void update_4();
public slots:
void update_all();
private:
void update_1();
void update_2();
void update_3();
void update_4();
void setUpNumberWidget();
void setUpFlowWidget();
void setUpDensityWidget();
void setUpHeadwayWidget();
void update_FLOW();
void update_NUM();
void update_DEN();
void update_HEAD();
int getNumber(const int &x) const;
int getNumberNS() const;
int getNumberSN() const;
int getNumberWE() const;
int getNumberEW() const;
double getFlow(const int &x) const;
double getFlowNS() const;
double getFlowSN() const;
double getFlowWE() const;
double getFlowEW() const;
double getDensity(const int &x) const;
double getDensityNS() const;
double getDensitySN() const;
double getDensityWE() const;
double getDensityEW() const;
double getHeadWay(const int &x) const;
double getHeadWayNS() const;
double getHeadWaySN() const;
double getHeadWayWE() const;
double getHeadWayEW() const;
Ui::VisualizePanel *ui;
QList<QCustomPlot *> m_number_widget;
QList<QCustomPlot *> m_flow_widget;
QList<QCustomPlot *> m_density_widget;
QList<QCustomPlot *> m_headway_widget;
TrafficController *m_controller;
// QList<TrafficDetector *> *m_detector;
QList<QVector<int>> m_number;
QList<QVector<double>> m_flow;
QList<QVector<double>> m_density;
QList<QVector<double>> m_headway;
// QList<QTimer *> *m_timer;
// QList<QElapsedTimer *> *m_etimer;
QList<QFile*> m_queue_size;
// QTextStream numStream;
// QTextStream flowStream;
// QTextStream headwayStream;
};
#endif // VISUALIZEPANEL_H
| 2,500
|
C++
|
.h
| 88
| 25.011364
| 55
| 0.70429
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,209
|
helpwidget.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/helpwidget.h
|
#ifndef HELPWIDGET_H
#define HELPWIDGET_H
#include <QWidget>
#include "Utilities/roadintersectionsimulation.h"
namespace Ui {
class HelpWidget;
}
class HelpWidget : public QWidget
{
Q_OBJECT
public:
explicit HelpWidget(QWidget *parent = 0);
void startDemo();
void stopDemo();
~HelpWidget();
RoadIntersectionSimulation *demo() const;
private slots:
void on_next_button_clicked();
void on_back_button_clicked();
private:
Ui::HelpWidget *ui;
RoadIntersectionSimulation *m_demo;
};
#endif // HELPWIDGET_H
| 549
|
C++
|
.h
| 24
| 19.875
| 49
| 0.746615
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,210
|
graphicsview.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/graphicsview.h
|
#ifndef GRAPHICSVIEW_H
#define GRAPHICSVIEW_H
#include <QGraphicsView>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QWidget>
#include "mainwindow.h"
class GraphicsView : public QGraphicsView
{
public:
GraphicsView(QWidget *parent = nullptr);
void Initializer();
protected:
// Control Mouse wheel to zoom
void wheelEvent(QWheelEvent *event) override;
// void mouseMoveEvent(QMouseEvent *event) override;
// void mouseReleaseEvent(QMouseEvent *event) override;
//virtual void resizeEvent(QResizeEvent *event);
private:
qreal m_min;
qreal m_max;
};
#endif // GRAPHICSVIEW_H
| 623
|
C++
|
.h
| 23
| 24.565217
| 58
| 0.765599
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,211
|
simulationsetup.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/simulationsetup.h
|
#ifndef SIMULATIONSETUP_H
#define SIMULATIONSETUP_H
#include <QWidget>
#include <QRadioButton>
#include "commonenum.h"
namespace Ui {
class SimulationSetup;
}
class SimulationSetup : public QWidget
{
Q_OBJECT
public:
explicit SimulationSetup(QWidget *parent = nullptr);
~SimulationSetup();
private slots:
void on_start_simulation_button_clicked();
void on_random_setup_clicked();
void on_help_setup_button_clicked();
void on_traffic_level_easy_input_clicked();
void on_traffic_mode_moderate_input_clicked();
void on_traffic_mode_busy_input_clicked();
void on_light_quick_input_clicked();
void on_light_moderate_input_clicked();
void on_light_long_input_clicked();
void on_experimental_mode_crazy_clicked();
void on_experimental_free_clicked();
signals:
void inputReady(SimulationInput input);
void onHelpClicked();
void onRandomClicked(SimulationInput input);
private:
Ui::SimulationSetup *ui;
SimulationInput input;
QList<QRadioButton*> trafficButton;
QList<QRadioButton*> lightButton;
};
#endif // SIMULATIONSETUP_H
| 1,108
|
C++
|
.h
| 37
| 26.513514
| 56
| 0.753991
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,212
|
mainwindow.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/mainwindow.h
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <omp.h>
#include <QMainWindow>
#include <QGraphicsSvgItem>
#include <QGLWidget>
#include "commonenum.h"
#include "Entities/Vehicle/vehicle.h"
#include "Utilities/road.h"
#include "simulationscene.h"
#include "Utilities/vehiclesgenerator.h"
#include "Entities/trafficcontroller.h"
namespace Ui {
class MainWindow;
}
class SimulationControl;
//class DataWidget;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
// virtual void resizeEvent(QResizeEvent *event);
virtual void keyPressEvent (QKeyEvent *event);
void set_up_random();
void set_up();
void turnOnSimulationState();
void turnOffSimulationState();
GENMETHOD getCurrentMethod() const;
VEHICLEMETHOD getCurrentVehicleMethod() const;
SimulationScene *scene() const;
TrafficController *getController() const;
bool getSimulate_state() const;
void showTraffic(bool checked);
void set3LaneCheck(const bool& b);
void setGenMethod(const GENMETHOD& gen);
void setGoThroguht(const bool& b);
void setSimMode(const VEHICLEMETHOD& m);
void setTrafficState(const bool& b);
~MainWindow();
public slots:
void check_state();
private slots:
void on_actionExit_triggered();
void on_play_clicked();
void on_back_clicked();
void on_open_simulation_button_clicked();
void on_exit_clicked();
void on_reset_clicked();
void on_pause_clicked();
void on_stop_clicked();
void set_up_demo();
void on_m_road_check_button_toggled(bool checked);
void on_m_detector_button_clicked(bool checked);
void on_m_sightseeing_button_clicked(bool checked);
void on_m_aboutus_button_clicked();
void on_m_manul_control_button_clicked(bool checked);
void on_m_5_lanes_clicked();
void on_m_3_lanes_clicked();
void on_m_no_traffic_clicked(bool checked);
void on_m_no_turn_clicked();
void on_m_go_though_clicked(bool checked);
void on_m_drop_in_clicked();
void on_actionPNG_triggered();
void on_m_tool_panel_check_box_clicked(bool checked);
void on_m_visualize_panel_check_box_clicked(bool checked);
void on_m_back_button_clicked();
void on_m_only_turn_clicked();
private:
void changeVehicleMode(const VEHICLEMETHOD &mode);
Ui::MainWindow *ui;
SimulationScene *m_scene;
bool m_simulate_state;
bool m_traffic_state;
bool m_sightseeing;
bool m_visualize_state;
QTimer *m_machine_state;
//QSplashScreen *m_loading_screen;
//DataWidget *m_data_widget;
TrafficController *m_controller;
//QList<TrafficLight *> *m_traffic_light;
};
#endif // MAINWINDOW_H
| 2,705
|
C++
|
.h
| 83
| 28.710843
| 62
| 0.728489
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,213
|
uimainwindow.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/uimainwindow.h
|
#ifndef UIMAINWINDOW_H
#define UIMAINWINDOW_H
#include "Utilities/roadintersectionsimulation.h"
#include "UI/intropage.h"
#include "UI/simulationsetup.h"
namespace Ui {
class UIMainWindow;
}
class UIMainWindow : public QWidget
{
Q_OBJECT
public:
explicit UIMainWindow(QWidget *parent = 0);
~UIMainWindow();
public slots:
void onExitButtonClicked();
void onAboutButtonClicked();
void onPlayButtonClicked();
void onHelpButtonClicked();
void EnableSimulationButton(const bool& play = true,
const bool& pause = true,
const bool& stop = true,
const bool& restart = true);
void updateStatus();
private slots:
void on_m_about_back_button_clicked();
void on_m_help_back_button_clicked();
void on_m_simulation_back_icon_clicked();
void on_m_setting_back_icon_clicked();
void on_m_simulation_play_button_clicked();
void on_m_simulation_pause_button_clicked();
void on_m_simulation_restart_button_clicked();
void on_m_simulation_stop_button_clicked();
void on_show_road_check_box_stateChanged(int arg1);
void on_show_detectors_check_box_stateChanged(int arg1);
void on_show_vehicles_vision_check_box_stateChanged(int arg1);
void on_show_traffic_light_check_box_stateChanged(int arg1);
void on_m_3_lanes_button_clicked();
void on_m_5_lanes_button_clicked();
void on_m_no_turn_button_clicked();
void on_m_turn_only_button_clicked();
void on_m_go_through_check_box_stateChanged(int arg1);
private:
Ui::UIMainWindow *ui;
RoadIntersectionSimulation *m_Simulation;
RoadIntersectionSimulation *m_Demo;
IntroPage *m_intro_page;
SimulationSetup *m_setup;
int m_time_frame;
};
#endif // UIMAINWINDOW_H
| 1,837
|
C++
|
.h
| 51
| 30
| 66
| 0.700114
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,215
|
simulationscene.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/UI/simulationscene.h
|
#ifndef SIMULATIONSCENE_H
#define SIMULATIONSCENE_H
#include <QGraphicsScene>
#include <QGraphicsSvgItem>
#include <omp.h>
#include <QtConcurrent/QtConcurrent>
#include "Entities/Vehicle/vehicle.h"
#include "Entities/trafficdetector.h"
#include "Entities/trafficcontroller.h"
class SimulationScene: public QGraphicsScene
{
public:
SimulationScene(QGraphicsScene *parent = nullptr);
uint getNumber(const region &x) const;
QList<Vehicle *> getVehicle() const;
QList<Vehicle *> getVehicle(const region &r) const;
TrafficLight* getTrafficLight(const region &r) const;
QList<TrafficLight *> getTrafficLight() const;
QList<TrafficDetector *> getDetector() const;
/*!
* \brief Add vehicle to the simulation scene
* \param vehicle = vehicle to be added
*/
void addVehicle(Vehicle* vehicle);
/*!
* \brief add Detector to the simulation scene
* \param detector to be added
*/
void addDetector(TrafficDetector* detector);
void addLight(TrafficLight* light);
void removeVehicle(Vehicle* ve);
void setGoThrough(bool x);
void resetScene();
void showTrafficLight();
void HideTrafficLight();
void showIntersectionPath(const bool &show);
void showDetectors();
void hideDetectors();
void turnOffDetectors();
void turnOnDetectors();
void showVehiclesVision();
void hideVehiclesVision();
TrafficController *getController() const;
void updateScene(const VEHICLEMETHOD &seeing);
void turnOffInteraction();
void turnOnInteraction();
private:
QList<Vehicle* > m_Vehicles;
TrafficController *m_Controller;
QGraphicsSvgItem *m_path;
//protected:
// virtual void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
};
#endif // SIMULATIONSCENE_H
| 1,784
|
C++
|
.h
| 54
| 29.092593
| 73
| 0.742029
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,217
|
vehiclesgenerator.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/Utilities/vehiclesgenerator.h
|
#ifndef VEHICLESGENERATOR_H
#define VEHICLESGENERATOR_H
#include "Entities/Vehicle/vehicle.h"
#include "Utilities/road.h"
#include "commonenum.h"
///////////////
/// \brief The VehiclesGenerator class
/// FactoryClass For Vehicle Class
/// //////////
class VehiclesGenerator
{
public:
static Vehicle *getLeftTurningVehicle(const region& approach,
const VEHICLEMETHOD& x,
const bool& vision= false,
const bool& interact = true);
static Vehicle *getThroughVehicle(const region& approach,
const int& lane,
const VEHICLEMETHOD& x,
const bool& vision= false,
const bool& interact = true);
static Vehicle *getRightTurningVehicle(const region& approach,
const VEHICLEMETHOD& x,
const bool& vision = false,
const bool& interact = true);
};
#endif // VEHICLESGENERATOR_H
| 1,185
|
C++
|
.h
| 27
| 27.222222
| 72
| 0.496534
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,218
|
road.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/Utilities/road.h
|
#ifndef ROAD_H
#define ROAD_H
#include <QPainterPath>
#include <QTransform>
#include "Entities/TrafficLight/trafficlight.h"
#include "commonenum.h"
class road
{
public:
///////////////////
/// \brief getLeft
/// \param approach = region for vehicle to appear
/// \return Path for vehicle
/// function to return path for vehicle
static QPainterPath getLeft(const region& approach);
static QPainterPath getThrough(const region& approach,const int& lane);
static QPainterPath getRight(const region& approach);
private:
static QPainterPath get_1_1();
static QPainterPath get_1_2();
static QPainterPath get_1_3();
static QPainterPath get_1_4();
static QPainterPath get_1_5();
static QPainterPath get_2_1();
static QPainterPath get_2_2();
static QPainterPath get_2_3();
static QPainterPath get_2_4();
static QPainterPath get_2_5();
static QPainterPath get_3_1();
static QPainterPath get_3_2();
static QPainterPath get_3_3();
static QPainterPath get_3_4();
static QPainterPath get_3_5();
static QPainterPath get_4_1();
static QPainterPath get_4_2();
static QPainterPath get_4_3();
static QPainterPath get_4_4();
static QPainterPath get_4_5();
static QPainterPath draw_1_1();
static QPainterPath draw_1_2();
static QPainterPath draw_1_3();
static QPainterPath draw_1_4();
static QPainterPath draw_1_5();
static QPainterPath draw_2_1();
static QPainterPath draw_2_2();
static QPainterPath draw_2_3();
static QPainterPath draw_2_4();
static QPainterPath draw_2_5();
static QPainterPath draw_3_1();
static QPainterPath draw_3_2();
static QPainterPath draw_3_3();
static QPainterPath draw_3_4();
static QPainterPath draw_3_5();
static QPainterPath draw_4_1();
static QPainterPath draw_4_2();
static QPainterPath draw_4_3();
static QPainterPath draw_4_4();
static QPainterPath draw_4_5();
};
#endif // ROAD_H
| 1,990
|
C++
|
.h
| 60
| 28.933333
| 75
| 0.692427
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,219
|
simulationcontrol.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/Utilities/simulationcontrol.h
|
#ifndef SIMULATIONCONTROL_H
#define SIMULATIONCONTROL_H
#include "UI/mainwindow.h"
#include "Entities/Vehicle/vehicle.h"
#include "Utilities/generator.h"
namespace Ui {
class SimulationControl;
}
class MainWindow;
class SimulationControl : public QWidget
{
Q_OBJECT
public:
explicit SimulationControl(QWidget *parent = nullptr);
~SimulationControl();
void initialize(QWidget *widget);
void stopGenerating();
Generator *generator() const;
void setMethod(const GENMETHOD& m);
private slots:
void on_m_setup_button_clicked();
void on_m_setup_birth_rate_button_clicked();
void on_m_stop_clicked();
void on_m_auto_traffic_clicked();
void on_m_random_birth_clicked();
void on_m_setup_birth_rate_button_3_clicked();
private:
MainWindow *m_w;
Ui::SimulationControl *ui;
QList<QTimer> m_timer;
Generator *m_generator;
};
#endif // SIMULATIONCONTROL_H
| 917
|
C++
|
.h
| 33
| 24.515152
| 58
| 0.742303
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,220
|
roadintersectionsimulation.h
|
KimangKhenng_Traffic-SImulation-and-Visualization/Utilities/roadintersectionsimulation.h
|
#ifndef ROADINTERSECTIONSIMULATION_H
#define ROADINTERSECTIONSIMULATION_H
#include "Utilities/generator.h"
#include <QGraphicsView>
static const float TIME_STEP = 1/60;
class Generator;
class RoadIntersectionSimulation : public QObject
{
Q_OBJECT
public:
RoadIntersectionSimulation(QGraphicsView *view);
~RoadIntersectionSimulation();
void initialize(const int &B_NS = 3500,
const int &B_SN = 3000,
const int &B_WE = 3900,
const int &B_EW = 3600,
const int &RED_LIGHT = 5000,
const int &GREEN_LIGHT = 3500,
const int &LEFT_GREEN_LIGHT = 1500,
const int &YELLOW_LIGHT = 500,
const GENMETHOD &METh = GENMETHOD::GEN_3,
const VEHICLEMETHOD &MODE = VEHICLEMETHOD::SIGHTSEEING);
void startSimulation();
void stopSimulation();
void pauseSimulation();
void turnOffInteraction();
void turnOnInteraction();
void startDemo();
SimulationScene *Scene() const;
SimulationState State() const;
QPixmap updatedViewinOneFrame();
void showRoad();
void hideRoad();
void showDetectors();
void hideDetectors();
void showVehiclesVision();
void hideVehiclesVision();
void showTraffic();
void hideTraffic();
void turnOnGoThrough();
void turnOffGoThrough();
void setGenerationMethod(GENMETHOD method = GENMETHOD::GEN_3);
int VehiclesNumber() const;
public slots:
void updateVehicle();
void autoInitialize();
void initializeFrominput(SimulationInput input);
signals:
void updatedOneFrame();
private:
//Simulation Entities
SimulationScene *m_Scene;
Generator *m_Generator;
SimulationState m_State;
bool m_TrafficLightOn;
bool m_VehicleSightSeeingOn;
bool m_VisualizationOn;
QTimer *m_SimulationTimer;
QGraphicsView *m_view;
};
#endif // ROADINTERSECTIONSIMULATION_H
| 1,982
|
C++
|
.h
| 61
| 25.852459
| 76
| 0.67627
|
KimangKhenng/Traffic-SImulation-and-Visualization
| 37
| 11
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.