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,543,141
|
dockingResource.h
|
shriprem_FWDataViz/src/NPP/dockingResource.h
|
// This file is part of Notepad++ project
// Copyright (C)2006 Jens Lorenz <[email protected]>
// 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 <https://www.gnu.org/licenses/>.
#pragma once
#define DM_NOFOCUSWHILECLICKINGCAPTION L"NOFOCUSWHILECLICKINGCAPTION"
#define IDD_PLUGIN_DLG 103
#define IDC_EDIT1 1000
#define IDB_CLOSE_DOWN 137
#define IDB_CLOSE_UP 138
#define IDD_CONTAINER_DLG 139
#define IDC_TAB_CONT 1027
#define IDC_CLIENT_TAB 1028
#define IDC_BTN_CAPTION 1050
#define DMM_MSG 0x5000
#define DMM_CLOSE (DMM_MSG + 1)
#define DMM_DOCK (DMM_MSG + 2)
#define DMM_FLOAT (DMM_MSG + 3)
#define DMM_DOCKALL (DMM_MSG + 4)
#define DMM_FLOATALL (DMM_MSG + 5)
#define DMM_MOVE (DMM_MSG + 6)
#define DMM_UPDATEDISPINFO (DMM_MSG + 7)
//#define DMM_GETIMAGELIST (DMM_MSG + 8)
//#define DMM_GETICONPOS (DMM_MSG + 9)
#define DMM_DROPDATA (DMM_MSG + 10)
#define DMM_MOVE_SPLITTER (DMM_MSG + 11)
#define DMM_CANCEL_MOVE (DMM_MSG + 12)
#define DMM_LBUTTONUP (DMM_MSG + 13)
#define DMN_FIRST 1050
#define DMN_CLOSE (DMN_FIRST + 1)
//nmhdr.code = DWORD(DMN_CLOSE, 0));
//nmhdr.hwndFrom = hwndNpp;
//nmhdr.idFrom = ctrlIdNpp;
#define DMN_DOCK (DMN_FIRST + 2)
#define DMN_FLOAT (DMN_FIRST + 3)
//nmhdr.code = DWORD(DMN_XXX, int newContainer);
//nmhdr.hwndFrom = hwndNpp;
//nmhdr.idFrom = ctrlIdNpp;
#define DMN_SWITCHIN (DMN_FIRST + 4)
#define DMN_SWITCHOFF (DMN_FIRST + 5)
#define DMN_FLOATDROPPED (DMN_FIRST + 6)
//nmhdr.code = DWORD(DMN_XXX, 0);
//nmhdr.hwndFrom = DockingCont::_hself;
//nmhdr.idFrom = 0;
| 2,507
|
C++
|
.h
| 54
| 44
| 73
| 0.617623
|
shriprem/FWDataViz
| 37
| 6
| 0
|
GPL-2.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,143
|
menuCmdID.h
|
shriprem_FWDataViz/src/NPP/menuCmdID.h
|
// This file is part of Notepad++ project
// Copyright (C)2024 Don HO <[email protected]>
// 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 <https://www.gnu.org/licenses/>.
#pragma once
#define IDM 40000
#define IDM_FILE (IDM + 1000)
// IMPORTANT: If list below is modified, you have to change the value of IDM_FILEMENU_LASTONE and IDM_FILEMENU_EXISTCMDPOSITION
#define IDM_FILE_NEW (IDM_FILE + 1)
#define IDM_FILE_OPEN (IDM_FILE + 2)
#define IDM_FILE_CLOSE (IDM_FILE + 3)
#define IDM_FILE_CLOSEALL (IDM_FILE + 4)
#define IDM_FILE_CLOSEALL_BUT_CURRENT (IDM_FILE + 5)
#define IDM_FILE_SAVE (IDM_FILE + 6)
#define IDM_FILE_SAVEALL (IDM_FILE + 7)
#define IDM_FILE_SAVEAS (IDM_FILE + 8)
#define IDM_FILE_CLOSEALL_TOLEFT (IDM_FILE + 9)
#define IDM_FILE_PRINT (IDM_FILE + 10)
#define IDM_FILE_PRINTNOW 1001
#define IDM_FILE_EXIT (IDM_FILE + 11)
#define IDM_FILE_LOADSESSION (IDM_FILE + 12)
#define IDM_FILE_SAVESESSION (IDM_FILE + 13)
#define IDM_FILE_RELOAD (IDM_FILE + 14)
#define IDM_FILE_SAVECOPYAS (IDM_FILE + 15)
#define IDM_FILE_DELETE (IDM_FILE + 16)
#define IDM_FILE_RENAME (IDM_FILE + 17)
#define IDM_FILE_CLOSEALL_TORIGHT (IDM_FILE + 18)
#define IDM_FILE_OPEN_FOLDER (IDM_FILE + 19)
#define IDM_FILE_OPEN_CMD (IDM_FILE + 20)
#define IDM_FILE_RESTORELASTCLOSEDFILE (IDM_FILE + 21)
#define IDM_FILE_OPENFOLDERASWORSPACE (IDM_FILE + 22)
#define IDM_FILE_OPEN_DEFAULT_VIEWER (IDM_FILE + 23)
#define IDM_FILE_CLOSEALL_UNCHANGED (IDM_FILE + 24)
#define IDM_FILE_CONTAININGFOLDERASWORKSPACE (IDM_FILE + 25)
// IMPORTANT: If list above is modified, you have to change the following values:
// To be updated if new menu item(s) is (are) added in menu "File"
#define IDM_FILEMENU_LASTONE IDM_FILE_CONTAININGFOLDERASWORKSPACE
// 0 based position of command "Exit" including the bars in the file menu
// and without counting "Recent files history" items
// 0 New
// 1 Open...
// 2 Open Containing Folder
// 3 Open Folder as Workspace
// 4 Open in Default Viewer
// 5 Reload from Disk
// 6 Save
// 7 Save As...
// 8 Save a Copy As...
// 9 Save All
//10 Rename...
//11 Close
//12 Close All
//13 Close Multiple Documents
//14 Move to Recycle Bin
//15 --------
//16 Load Session...
//17 Save Session...
//18 --------
//19 Print...
//20 Print Now
//21 --------
//22 Exit
#define IDM_FILEMENU_EXISTCMDPOSITION 22
#define IDM_EDIT (IDM + 2000)
#define IDM_EDIT_CUT (IDM_EDIT + 1)
#define IDM_EDIT_COPY (IDM_EDIT + 2)
#define IDM_EDIT_UNDO (IDM_EDIT + 3)
#define IDM_EDIT_REDO (IDM_EDIT + 4)
#define IDM_EDIT_PASTE (IDM_EDIT + 5)
#define IDM_EDIT_DELETE (IDM_EDIT + 6)
#define IDM_EDIT_SELECTALL (IDM_EDIT + 7)
#define IDM_EDIT_INS_TAB (IDM_EDIT + 8)
#define IDM_EDIT_RMV_TAB (IDM_EDIT + 9)
#define IDM_EDIT_DUP_LINE (IDM_EDIT + 10)
#define IDM_EDIT_TRANSPOSE_LINE (IDM_EDIT + 11)
#define IDM_EDIT_SPLIT_LINES (IDM_EDIT + 12)
#define IDM_EDIT_JOIN_LINES (IDM_EDIT + 13)
#define IDM_EDIT_LINE_UP (IDM_EDIT + 14)
#define IDM_EDIT_LINE_DOWN (IDM_EDIT + 15)
#define IDM_EDIT_UPPERCASE (IDM_EDIT + 16)
#define IDM_EDIT_LOWERCASE (IDM_EDIT + 17)
#define IDM_MACRO_STARTRECORDINGMACRO (IDM_EDIT + 18)
#define IDM_MACRO_STOPRECORDINGMACRO (IDM_EDIT + 19)
#define IDM_EDIT_BEGINENDSELECT (IDM_EDIT + 20)
#define IDM_MACRO_PLAYBACKRECORDEDMACRO (IDM_EDIT + 21)
#define IDM_EDIT_BLOCK_COMMENT (IDM_EDIT + 22)
#define IDM_EDIT_STREAM_COMMENT (IDM_EDIT + 23)
#define IDM_EDIT_TRIMTRAILING (IDM_EDIT + 24)
#define IDM_MACRO_SAVECURRENTMACRO (IDM_EDIT + 25)
#define IDM_EDIT_RTL (IDM_EDIT + 26)
#define IDM_EDIT_LTR (IDM_EDIT + 27)
#define IDM_EDIT_SETREADONLY (IDM_EDIT + 28)
#define IDM_EDIT_FULLPATHTOCLIP (IDM_EDIT + 29)
#define IDM_EDIT_FILENAMETOCLIP (IDM_EDIT + 30)
#define IDM_EDIT_CURRENTDIRTOCLIP (IDM_EDIT + 31)
#define IDM_MACRO_RUNMULTIMACRODLG (IDM_EDIT + 32)
#define IDM_EDIT_CLEARREADONLY (IDM_EDIT + 33)
#define IDM_EDIT_COLUMNMODE (IDM_EDIT + 34)
#define IDM_EDIT_BLOCK_COMMENT_SET (IDM_EDIT + 35)
#define IDM_EDIT_BLOCK_UNCOMMENT (IDM_EDIT + 36)
#define IDM_EDIT_COLUMNMODETIP (IDM_EDIT + 37)
#define IDM_EDIT_PASTE_AS_HTML (IDM_EDIT + 38)
#define IDM_EDIT_PASTE_AS_RTF (IDM_EDIT + 39)
#define IDM_OPEN_ALL_RECENT_FILE (IDM_EDIT + 40)
#define IDM_CLEAN_RECENT_FILE_LIST (IDM_EDIT + 41)
#define IDM_EDIT_TRIMLINEHEAD (IDM_EDIT + 42)
#define IDM_EDIT_TRIM_BOTH (IDM_EDIT + 43)
#define IDM_EDIT_EOL2WS (IDM_EDIT + 44)
#define IDM_EDIT_TRIMALL (IDM_EDIT + 45)
#define IDM_EDIT_TAB2SW (IDM_EDIT + 46)
#define IDM_EDIT_STREAM_UNCOMMENT (IDM_EDIT + 47)
#define IDM_EDIT_COPY_BINARY (IDM_EDIT + 48)
#define IDM_EDIT_CUT_BINARY (IDM_EDIT + 49)
#define IDM_EDIT_PASTE_BINARY (IDM_EDIT + 50)
#define IDM_EDIT_CHAR_PANEL (IDM_EDIT + 51)
#define IDM_EDIT_CLIPBOARDHISTORY_PANEL (IDM_EDIT + 52)
#define IDM_EDIT_SW2TAB_LEADING (IDM_EDIT + 53)
#define IDM_EDIT_SW2TAB_ALL (IDM_EDIT + 54)
#define IDM_EDIT_REMOVEEMPTYLINES (IDM_EDIT + 55)
#define IDM_EDIT_REMOVEEMPTYLINESWITHBLANK (IDM_EDIT + 56)
#define IDM_EDIT_BLANKLINEABOVECURRENT (IDM_EDIT + 57)
#define IDM_EDIT_BLANKLINEBELOWCURRENT (IDM_EDIT + 58)
#define IDM_EDIT_SORTLINES_LEXICOGRAPHIC_ASCENDING (IDM_EDIT + 59)
#define IDM_EDIT_SORTLINES_LEXICOGRAPHIC_DESCENDING (IDM_EDIT + 60)
#define IDM_EDIT_SORTLINES_INTEGER_ASCENDING (IDM_EDIT + 61)
#define IDM_EDIT_SORTLINES_INTEGER_DESCENDING (IDM_EDIT + 62)
#define IDM_EDIT_SORTLINES_DECIMALCOMMA_ASCENDING (IDM_EDIT + 63)
#define IDM_EDIT_SORTLINES_DECIMALCOMMA_DESCENDING (IDM_EDIT + 64)
#define IDM_EDIT_SORTLINES_DECIMALDOT_ASCENDING (IDM_EDIT + 65)
#define IDM_EDIT_SORTLINES_DECIMALDOT_DESCENDING (IDM_EDIT + 66)
#define IDM_EDIT_PROPERCASE_FORCE (IDM_EDIT + 67)
#define IDM_EDIT_PROPERCASE_BLEND (IDM_EDIT + 68)
#define IDM_EDIT_SENTENCECASE_FORCE (IDM_EDIT + 69)
#define IDM_EDIT_SENTENCECASE_BLEND (IDM_EDIT + 70)
#define IDM_EDIT_INVERTCASE (IDM_EDIT + 71)
#define IDM_EDIT_RANDOMCASE (IDM_EDIT + 72)
#define IDM_EDIT_OPENASFILE (IDM_EDIT + 73)
#define IDM_EDIT_OPENINFOLDER (IDM_EDIT + 74)
#define IDM_EDIT_SEARCHONINTERNET (IDM_EDIT + 75)
#define IDM_EDIT_CHANGESEARCHENGINE (IDM_EDIT + 76)
#define IDM_EDIT_REMOVE_CONSECUTIVE_DUP_LINES (IDM_EDIT + 77)
#define IDM_EDIT_SORTLINES_RANDOMLY (IDM_EDIT + 78)
#define IDM_EDIT_REMOVE_ANY_DUP_LINES (IDM_EDIT + 79)
#define IDM_EDIT_SORTLINES_LEXICO_CASE_INSENS_ASCENDING (IDM_EDIT + 80)
#define IDM_EDIT_SORTLINES_LEXICO_CASE_INSENS_DESCENDING (IDM_EDIT + 81)
#define IDM_EDIT_COPY_LINK (IDM_EDIT + 82)
#define IDM_EDIT_SORTLINES_REVERSE_ORDER (IDM_EDIT + 83)
#define IDM_EDIT_INSERT_DATETIME_SHORT (IDM_EDIT + 84)
#define IDM_EDIT_INSERT_DATETIME_LONG (IDM_EDIT + 85)
#define IDM_EDIT_INSERT_DATETIME_CUSTOMIZED (IDM_EDIT + 86)
#define IDM_EDIT_COPY_ALL_NAMES (IDM_EDIT + 87)
#define IDM_EDIT_COPY_ALL_PATHS (IDM_EDIT + 88)
#define IDM_EDIT_BEGINENDSELECT_COLUMNMODE (IDM_EDIT + 89)
#define IDM_EDIT_MULTISELECTALL (IDM_EDIT + 90)
#define IDM_EDIT_MULTISELECTALLMATCHCASE (IDM_EDIT + 91)
#define IDM_EDIT_MULTISELECTALLWHOLEWORD (IDM_EDIT + 92)
#define IDM_EDIT_MULTISELECTALLMATCHCASEWHOLEWORD (IDM_EDIT + 93)
#define IDM_EDIT_MULTISELECTNEXT (IDM_EDIT + 94)
#define IDM_EDIT_MULTISELECTNEXTMATCHCASE (IDM_EDIT + 95)
#define IDM_EDIT_MULTISELECTNEXTWHOLEWORD (IDM_EDIT + 96)
#define IDM_EDIT_MULTISELECTNEXTMATCHCASEWHOLEWORD (IDM_EDIT + 97)
#define IDM_EDIT_MULTISELECTUNDO (IDM_EDIT + 98)
#define IDM_EDIT_MULTISELECTSSKIP (IDM_EDIT + 99)
#define IDM_EDIT_AUTOCOMPLETE (50000 + 0)
#define IDM_EDIT_AUTOCOMPLETE_CURRENTFILE (50000 + 1)
#define IDM_EDIT_FUNCCALLTIP (50000 + 2)
#define IDM_EDIT_AUTOCOMPLETE_PATH (50000 + 6)
#define IDM_EDIT_FUNCCALLTIP_PREVIOUS (50000 + 10)
#define IDM_EDIT_FUNCCALLTIP_NEXT (50000 + 11)
#define IDM_SEARCH (IDM + 3000)
#define IDM_SEARCH_FIND (IDM_SEARCH + 1)
#define IDM_SEARCH_FINDNEXT (IDM_SEARCH + 2)
#define IDM_SEARCH_REPLACE (IDM_SEARCH + 3)
#define IDM_SEARCH_GOTOLINE (IDM_SEARCH + 4)
#define IDM_SEARCH_TOGGLE_BOOKMARK (IDM_SEARCH + 5)
#define IDM_SEARCH_NEXT_BOOKMARK (IDM_SEARCH + 6)
#define IDM_SEARCH_PREV_BOOKMARK (IDM_SEARCH + 7)
#define IDM_SEARCH_CLEAR_BOOKMARKS (IDM_SEARCH + 8)
#define IDM_SEARCH_GOTOMATCHINGBRACE (IDM_SEARCH + 9)
#define IDM_SEARCH_FINDPREV (IDM_SEARCH + 10)
#define IDM_SEARCH_FINDINCREMENT (IDM_SEARCH + 11)
#define IDM_SEARCH_FINDINFILES (IDM_SEARCH + 13)
#define IDM_SEARCH_VOLATILE_FINDNEXT (IDM_SEARCH + 14)
#define IDM_SEARCH_VOLATILE_FINDPREV (IDM_SEARCH + 15)
#define IDM_SEARCH_CUTMARKEDLINES (IDM_SEARCH + 18)
#define IDM_SEARCH_COPYMARKEDLINES (IDM_SEARCH + 19)
#define IDM_SEARCH_PASTEMARKEDLINES (IDM_SEARCH + 20)
#define IDM_SEARCH_DELETEMARKEDLINES (IDM_SEARCH + 21)
#define IDM_SEARCH_MARKALLEXT1 (IDM_SEARCH + 22)
#define IDM_SEARCH_UNMARKALLEXT1 (IDM_SEARCH + 23)
#define IDM_SEARCH_MARKALLEXT2 (IDM_SEARCH + 24)
#define IDM_SEARCH_UNMARKALLEXT2 (IDM_SEARCH + 25)
#define IDM_SEARCH_MARKALLEXT3 (IDM_SEARCH + 26)
#define IDM_SEARCH_UNMARKALLEXT3 (IDM_SEARCH + 27)
#define IDM_SEARCH_MARKALLEXT4 (IDM_SEARCH + 28)
#define IDM_SEARCH_UNMARKALLEXT4 (IDM_SEARCH + 29)
#define IDM_SEARCH_MARKALLEXT5 (IDM_SEARCH + 30)
#define IDM_SEARCH_UNMARKALLEXT5 (IDM_SEARCH + 31)
#define IDM_SEARCH_CLEARALLMARKS (IDM_SEARCH + 32)
#define IDM_SEARCH_GOPREVMARKER1 (IDM_SEARCH + 33)
#define IDM_SEARCH_GOPREVMARKER2 (IDM_SEARCH + 34)
#define IDM_SEARCH_GOPREVMARKER3 (IDM_SEARCH + 35)
#define IDM_SEARCH_GOPREVMARKER4 (IDM_SEARCH + 36)
#define IDM_SEARCH_GOPREVMARKER5 (IDM_SEARCH + 37)
#define IDM_SEARCH_GOPREVMARKER_DEF (IDM_SEARCH + 38)
#define IDM_SEARCH_GONEXTMARKER1 (IDM_SEARCH + 39)
#define IDM_SEARCH_GONEXTMARKER2 (IDM_SEARCH + 40)
#define IDM_SEARCH_GONEXTMARKER3 (IDM_SEARCH + 41)
#define IDM_SEARCH_GONEXTMARKER4 (IDM_SEARCH + 42)
#define IDM_SEARCH_GONEXTMARKER5 (IDM_SEARCH + 43)
#define IDM_SEARCH_GONEXTMARKER_DEF (IDM_SEARCH + 44)
#define IDM_FOCUS_ON_FOUND_RESULTS (IDM_SEARCH + 45)
#define IDM_SEARCH_GOTONEXTFOUND (IDM_SEARCH + 46)
#define IDM_SEARCH_GOTOPREVFOUND (IDM_SEARCH + 47)
#define IDM_SEARCH_SETANDFINDNEXT (IDM_SEARCH + 48)
#define IDM_SEARCH_SETANDFINDPREV (IDM_SEARCH + 49)
#define IDM_SEARCH_INVERSEMARKS (IDM_SEARCH + 50)
#define IDM_SEARCH_DELETEUNMARKEDLINES (IDM_SEARCH + 51)
#define IDM_SEARCH_FINDCHARINRANGE (IDM_SEARCH + 52)
#define IDM_SEARCH_SELECTMATCHINGBRACES (IDM_SEARCH + 53)
#define IDM_SEARCH_MARK (IDM_SEARCH + 54)
#define IDM_SEARCH_STYLE1TOCLIP (IDM_SEARCH + 55)
#define IDM_SEARCH_STYLE2TOCLIP (IDM_SEARCH + 56)
#define IDM_SEARCH_STYLE3TOCLIP (IDM_SEARCH + 57)
#define IDM_SEARCH_STYLE4TOCLIP (IDM_SEARCH + 58)
#define IDM_SEARCH_STYLE5TOCLIP (IDM_SEARCH + 59)
#define IDM_SEARCH_ALLSTYLESTOCLIP (IDM_SEARCH + 60)
#define IDM_SEARCH_MARKEDTOCLIP (IDM_SEARCH + 61)
#define IDM_SEARCH_MARKONEEXT1 (IDM_SEARCH + 62)
#define IDM_SEARCH_MARKONEEXT2 (IDM_SEARCH + 63)
#define IDM_SEARCH_MARKONEEXT3 (IDM_SEARCH + 64)
#define IDM_SEARCH_MARKONEEXT4 (IDM_SEARCH + 65)
#define IDM_SEARCH_MARKONEEXT5 (IDM_SEARCH + 66)
#define IDM_SEARCH_CHANGED_NEXT (IDM_SEARCH + 67)
#define IDM_SEARCH_CHANGED_PREV (IDM_SEARCH + 68)
#define IDM_SEARCH_CLEAR_CHANGE_HISTORY (IDM_SEARCH + 69)
#define IDM_MISC (IDM + 3500)
#define IDM_DOCLIST_FILESCLOSE (IDM_MISC + 1)
#define IDM_DOCLIST_FILESCLOSEOTHERS (IDM_MISC + 2)
#define IDM_DOCLIST_COPYNAMES (IDM_MISC + 3)
#define IDM_DOCLIST_COPYPATHS (IDM_MISC + 4)
#define IDM_VIEW (IDM + 4000)
//#define IDM_VIEW_TOOLBAR_HIDE (IDM_VIEW + 1)
#define IDM_VIEW_TOOLBAR_REDUCE (IDM_VIEW + 2)
#define IDM_VIEW_TOOLBAR_ENLARGE (IDM_VIEW + 3)
#define IDM_VIEW_TOOLBAR_STANDARD (IDM_VIEW + 4)
#define IDM_VIEW_REDUCETABBAR (IDM_VIEW + 5)
#define IDM_VIEW_LOCKTABBAR (IDM_VIEW + 6)
#define IDM_VIEW_DRAWTABBAR_TOPBAR (IDM_VIEW + 7)
#define IDM_VIEW_DRAWTABBAR_INACIVETAB (IDM_VIEW + 8)
#define IDM_VIEW_POSTIT (IDM_VIEW + 9)
#define IDM_VIEW_FOLDALL (IDM_VIEW + 10)
#define IDM_VIEW_DISTRACTIONFREE (IDM_VIEW + 11)
#define IDM_VIEW_LINENUMBER (IDM_VIEW + 12)
#define IDM_VIEW_SYMBOLMARGIN (IDM_VIEW + 13)
#define IDM_VIEW_FOLDERMAGIN (IDM_VIEW + 14)
#define IDM_VIEW_FOLDERMAGIN_SIMPLE (IDM_VIEW + 15)
#define IDM_VIEW_FOLDERMAGIN_ARROW (IDM_VIEW + 16)
#define IDM_VIEW_FOLDERMAGIN_CIRCLE (IDM_VIEW + 17)
#define IDM_VIEW_FOLDERMAGIN_BOX (IDM_VIEW + 18)
#define IDM_VIEW_ALL_CHARACTERS (IDM_VIEW + 19)
#define IDM_VIEW_INDENT_GUIDE (IDM_VIEW + 20)
#define IDM_VIEW_CURLINE_HILITING (IDM_VIEW + 21)
#define IDM_VIEW_WRAP (IDM_VIEW + 22)
#define IDM_VIEW_ZOOMIN (IDM_VIEW + 23)
#define IDM_VIEW_ZOOMOUT (IDM_VIEW + 24)
#define IDM_VIEW_TAB_SPACE (IDM_VIEW + 25)
#define IDM_VIEW_EOL (IDM_VIEW + 26)
#define IDM_VIEW_TOOLBAR_REDUCE_SET2 (IDM_VIEW + 27)
#define IDM_VIEW_TOOLBAR_ENLARGE_SET2 (IDM_VIEW + 28)
#define IDM_VIEW_UNFOLDALL (IDM_VIEW + 29)
#define IDM_VIEW_FOLD_CURRENT (IDM_VIEW + 30)
#define IDM_VIEW_UNFOLD_CURRENT (IDM_VIEW + 31)
#define IDM_VIEW_FULLSCREENTOGGLE (IDM_VIEW + 32)
#define IDM_VIEW_ZOOMRESTORE (IDM_VIEW + 33)
#define IDM_VIEW_ALWAYSONTOP (IDM_VIEW + 34)
#define IDM_VIEW_SYNSCROLLV (IDM_VIEW + 35)
#define IDM_VIEW_SYNSCROLLH (IDM_VIEW + 36)
//#define IDM_VIEW_EDGENONE (IDM_VIEW + 37)
#define IDM_VIEW_DRAWTABBAR_CLOSEBOTTUN (IDM_VIEW + 38)
#define IDM_VIEW_DRAWTABBAR_DBCLK2CLOSE (IDM_VIEW + 39)
#define IDM_VIEW_REFRESHTABAR (IDM_VIEW + 40)
#define IDM_VIEW_WRAP_SYMBOL (IDM_VIEW + 41)
#define IDM_VIEW_HIDELINES (IDM_VIEW + 42)
#define IDM_VIEW_DRAWTABBAR_VERTICAL (IDM_VIEW + 43)
#define IDM_VIEW_DRAWTABBAR_MULTILINE (IDM_VIEW + 44)
//#define IDM_VIEW_DOCCHANGEMARGIN (IDM_VIEW + 45)
#define IDM_VIEW_LWDEF (IDM_VIEW + 46)
#define IDM_VIEW_LWALIGN (IDM_VIEW + 47)
#define IDM_VIEW_LWINDENT (IDM_VIEW + 48)
#define IDM_VIEW_SUMMARY (IDM_VIEW + 49)
#define IDM_VIEW_FOLD (IDM_VIEW + 50)
#define IDM_VIEW_FOLD_1 (IDM_VIEW_FOLD + 1)
#define IDM_VIEW_FOLD_2 (IDM_VIEW_FOLD + 2)
#define IDM_VIEW_FOLD_3 (IDM_VIEW_FOLD + 3)
#define IDM_VIEW_FOLD_4 (IDM_VIEW_FOLD + 4)
#define IDM_VIEW_FOLD_5 (IDM_VIEW_FOLD + 5)
#define IDM_VIEW_FOLD_6 (IDM_VIEW_FOLD + 6)
#define IDM_VIEW_FOLD_7 (IDM_VIEW_FOLD + 7)
#define IDM_VIEW_FOLD_8 (IDM_VIEW_FOLD + 8)
#define IDM_VIEW_UNFOLD (IDM_VIEW + 60)
#define IDM_VIEW_UNFOLD_1 (IDM_VIEW_UNFOLD + 1)
#define IDM_VIEW_UNFOLD_2 (IDM_VIEW_UNFOLD + 2)
#define IDM_VIEW_UNFOLD_3 (IDM_VIEW_UNFOLD + 3)
#define IDM_VIEW_UNFOLD_4 (IDM_VIEW_UNFOLD + 4)
#define IDM_VIEW_UNFOLD_5 (IDM_VIEW_UNFOLD + 5)
#define IDM_VIEW_UNFOLD_6 (IDM_VIEW_UNFOLD + 6)
#define IDM_VIEW_UNFOLD_7 (IDM_VIEW_UNFOLD + 7)
#define IDM_VIEW_UNFOLD_8 (IDM_VIEW_UNFOLD + 8)
#define IDM_VIEW_DOCLIST (IDM_VIEW + 70)
#define IDM_VIEW_SWITCHTO_OTHER_VIEW (IDM_VIEW + 72)
#define IDM_EXPORT_FUNC_LIST_AND_QUIT (IDM_VIEW + 73)
#define IDM_VIEW_DOC_MAP (IDM_VIEW + 80)
#define IDM_VIEW_PROJECT_PANEL_1 (IDM_VIEW + 81)
#define IDM_VIEW_PROJECT_PANEL_2 (IDM_VIEW + 82)
#define IDM_VIEW_PROJECT_PANEL_3 (IDM_VIEW + 83)
#define IDM_VIEW_FUNC_LIST (IDM_VIEW + 84)
#define IDM_VIEW_FILEBROWSER (IDM_VIEW + 85)
#define IDM_VIEW_TAB1 (IDM_VIEW + 86)
#define IDM_VIEW_TAB2 (IDM_VIEW + 87)
#define IDM_VIEW_TAB3 (IDM_VIEW + 88)
#define IDM_VIEW_TAB4 (IDM_VIEW + 89)
#define IDM_VIEW_TAB5 (IDM_VIEW + 90)
#define IDM_VIEW_TAB6 (IDM_VIEW + 91)
#define IDM_VIEW_TAB7 (IDM_VIEW + 92)
#define IDM_VIEW_TAB8 (IDM_VIEW + 93)
#define IDM_VIEW_TAB9 (IDM_VIEW + 94)
#define IDM_VIEW_TAB_NEXT (IDM_VIEW + 95)
#define IDM_VIEW_TAB_PREV (IDM_VIEW + 96)
#define IDM_VIEW_MONITORING (IDM_VIEW + 97)
#define IDM_VIEW_TAB_MOVEFORWARD (IDM_VIEW + 98)
#define IDM_VIEW_TAB_MOVEBACKWARD (IDM_VIEW + 99)
#define IDM_VIEW_IN_FIREFOX (IDM_VIEW + 100)
#define IDM_VIEW_IN_CHROME (IDM_VIEW + 101)
#define IDM_VIEW_IN_EDGE (IDM_VIEW + 102)
#define IDM_VIEW_IN_IE (IDM_VIEW + 103)
#define IDM_VIEW_SWITCHTO_PROJECT_PANEL_1 (IDM_VIEW + 104)
#define IDM_VIEW_SWITCHTO_PROJECT_PANEL_2 (IDM_VIEW + 105)
#define IDM_VIEW_SWITCHTO_PROJECT_PANEL_3 (IDM_VIEW + 106)
#define IDM_VIEW_SWITCHTO_FILEBROWSER (IDM_VIEW + 107)
#define IDM_VIEW_SWITCHTO_FUNC_LIST (IDM_VIEW + 108)
#define IDM_VIEW_SWITCHTO_DOCLIST (IDM_VIEW + 109)
#define IDM_VIEW_TAB_COLOUR_NONE (IDM_VIEW + 110)
#define IDM_VIEW_TAB_COLOUR_1 (IDM_VIEW + 111)
#define IDM_VIEW_TAB_COLOUR_2 (IDM_VIEW + 112)
#define IDM_VIEW_TAB_COLOUR_3 (IDM_VIEW + 113)
#define IDM_VIEW_TAB_COLOUR_4 (IDM_VIEW + 114)
#define IDM_VIEW_TAB_COLOUR_5 (IDM_VIEW + 115)
#define IDM_VIEW_TAB_START (IDM_VIEW + 116)
#define IDM_VIEW_TAB_END (IDM_VIEW + 117)
#define IDM_VIEW_NPC (IDM_VIEW + 130)
#define IDM_VIEW_NPC_CCUNIEOL (IDM_VIEW + 131)
#define IDM_VIEW_GOTO_ANOTHER_VIEW 10001
#define IDM_VIEW_CLONE_TO_ANOTHER_VIEW 10002
#define IDM_VIEW_GOTO_NEW_INSTANCE 10003
#define IDM_VIEW_LOAD_IN_NEW_INSTANCE 10004
#define IDM_VIEW_GOTO_START 10005
#define IDM_VIEW_GOTO_END 10006
#define IDM_FORMAT (IDM + 5000)
#define IDM_FORMAT_TODOS (IDM_FORMAT + 1)
#define IDM_FORMAT_TOUNIX (IDM_FORMAT + 2)
#define IDM_FORMAT_TOMAC (IDM_FORMAT + 3)
#define IDM_FORMAT_ANSI (IDM_FORMAT + 4)
#define IDM_FORMAT_UTF_8 (IDM_FORMAT + 5)
#define IDM_FORMAT_UTF_16BE (IDM_FORMAT + 6)
#define IDM_FORMAT_UTF_16LE (IDM_FORMAT + 7)
#define IDM_FORMAT_AS_UTF_8 (IDM_FORMAT + 8)
#define IDM_FORMAT_CONV2_ANSI (IDM_FORMAT + 9)
#define IDM_FORMAT_CONV2_AS_UTF_8 (IDM_FORMAT + 10)
#define IDM_FORMAT_CONV2_UTF_8 (IDM_FORMAT + 11)
#define IDM_FORMAT_CONV2_UTF_16BE (IDM_FORMAT + 12)
#define IDM_FORMAT_CONV2_UTF_16LE (IDM_FORMAT + 13)
#define IDM_FORMAT_ENCODE (IDM_FORMAT + 20)
#define IDM_FORMAT_WIN_1250 (IDM_FORMAT_ENCODE + 0)
#define IDM_FORMAT_WIN_1251 (IDM_FORMAT_ENCODE + 1)
#define IDM_FORMAT_WIN_1252 (IDM_FORMAT_ENCODE + 2)
#define IDM_FORMAT_WIN_1253 (IDM_FORMAT_ENCODE + 3)
#define IDM_FORMAT_WIN_1254 (IDM_FORMAT_ENCODE + 4)
#define IDM_FORMAT_WIN_1255 (IDM_FORMAT_ENCODE + 5)
#define IDM_FORMAT_WIN_1256 (IDM_FORMAT_ENCODE + 6)
#define IDM_FORMAT_WIN_1257 (IDM_FORMAT_ENCODE + 7)
#define IDM_FORMAT_WIN_1258 (IDM_FORMAT_ENCODE + 8)
#define IDM_FORMAT_ISO_8859_1 (IDM_FORMAT_ENCODE + 9)
#define IDM_FORMAT_ISO_8859_2 (IDM_FORMAT_ENCODE + 10)
#define IDM_FORMAT_ISO_8859_3 (IDM_FORMAT_ENCODE + 11)
#define IDM_FORMAT_ISO_8859_4 (IDM_FORMAT_ENCODE + 12)
#define IDM_FORMAT_ISO_8859_5 (IDM_FORMAT_ENCODE + 13)
#define IDM_FORMAT_ISO_8859_6 (IDM_FORMAT_ENCODE + 14)
#define IDM_FORMAT_ISO_8859_7 (IDM_FORMAT_ENCODE + 15)
#define IDM_FORMAT_ISO_8859_8 (IDM_FORMAT_ENCODE + 16)
#define IDM_FORMAT_ISO_8859_9 (IDM_FORMAT_ENCODE + 17)
//#define IDM_FORMAT_ISO_8859_10 (IDM_FORMAT_ENCODE + 18)
//#define IDM_FORMAT_ISO_8859_11 (IDM_FORMAT_ENCODE + 19)
#define IDM_FORMAT_ISO_8859_13 (IDM_FORMAT_ENCODE + 20)
#define IDM_FORMAT_ISO_8859_14 (IDM_FORMAT_ENCODE + 21)
#define IDM_FORMAT_ISO_8859_15 (IDM_FORMAT_ENCODE + 22)
//#define IDM_FORMAT_ISO_8859_16 (IDM_FORMAT_ENCODE + 23)
#define IDM_FORMAT_DOS_437 (IDM_FORMAT_ENCODE + 24)
#define IDM_FORMAT_DOS_720 (IDM_FORMAT_ENCODE + 25)
#define IDM_FORMAT_DOS_737 (IDM_FORMAT_ENCODE + 26)
#define IDM_FORMAT_DOS_775 (IDM_FORMAT_ENCODE + 27)
#define IDM_FORMAT_DOS_850 (IDM_FORMAT_ENCODE + 28)
#define IDM_FORMAT_DOS_852 (IDM_FORMAT_ENCODE + 29)
#define IDM_FORMAT_DOS_855 (IDM_FORMAT_ENCODE + 30)
#define IDM_FORMAT_DOS_857 (IDM_FORMAT_ENCODE + 31)
#define IDM_FORMAT_DOS_858 (IDM_FORMAT_ENCODE + 32)
#define IDM_FORMAT_DOS_860 (IDM_FORMAT_ENCODE + 33)
#define IDM_FORMAT_DOS_861 (IDM_FORMAT_ENCODE + 34)
#define IDM_FORMAT_DOS_862 (IDM_FORMAT_ENCODE + 35)
#define IDM_FORMAT_DOS_863 (IDM_FORMAT_ENCODE + 36)
#define IDM_FORMAT_DOS_865 (IDM_FORMAT_ENCODE + 37)
#define IDM_FORMAT_DOS_866 (IDM_FORMAT_ENCODE + 38)
#define IDM_FORMAT_DOS_869 (IDM_FORMAT_ENCODE + 39)
#define IDM_FORMAT_BIG5 (IDM_FORMAT_ENCODE + 40)
#define IDM_FORMAT_GB2312 (IDM_FORMAT_ENCODE + 41)
#define IDM_FORMAT_SHIFT_JIS (IDM_FORMAT_ENCODE + 42)
#define IDM_FORMAT_KOREAN_WIN (IDM_FORMAT_ENCODE + 43)
#define IDM_FORMAT_EUC_KR (IDM_FORMAT_ENCODE + 44)
#define IDM_FORMAT_TIS_620 (IDM_FORMAT_ENCODE + 45)
#define IDM_FORMAT_MAC_CYRILLIC (IDM_FORMAT_ENCODE + 46)
#define IDM_FORMAT_KOI8U_CYRILLIC (IDM_FORMAT_ENCODE + 47)
#define IDM_FORMAT_KOI8R_CYRILLIC (IDM_FORMAT_ENCODE + 48)
#define IDM_FORMAT_ENCODE_END IDM_FORMAT_KOI8R_CYRILLIC
//#define IDM_FORMAT_CONVERT 200
#define IDM_LANG (IDM + 6000)
#define IDM_LANGSTYLE_CONFIG_DLG (IDM_LANG + 1)
#define IDM_LANG_C (IDM_LANG + 2)
#define IDM_LANG_CPP (IDM_LANG + 3)
#define IDM_LANG_JAVA (IDM_LANG + 4)
#define IDM_LANG_HTML (IDM_LANG + 5)
#define IDM_LANG_XML (IDM_LANG + 6)
#define IDM_LANG_JS (IDM_LANG + 7)
#define IDM_LANG_PHP (IDM_LANG + 8)
#define IDM_LANG_ASP (IDM_LANG + 9)
#define IDM_LANG_CSS (IDM_LANG + 10)
#define IDM_LANG_PASCAL (IDM_LANG + 11)
#define IDM_LANG_PYTHON (IDM_LANG + 12)
#define IDM_LANG_PERL (IDM_LANG + 13)
#define IDM_LANG_OBJC (IDM_LANG + 14)
#define IDM_LANG_ASCII (IDM_LANG + 15)
#define IDM_LANG_TEXT (IDM_LANG + 16)
#define IDM_LANG_RC (IDM_LANG + 17)
#define IDM_LANG_MAKEFILE (IDM_LANG + 18)
#define IDM_LANG_INI (IDM_LANG + 19)
#define IDM_LANG_SQL (IDM_LANG + 20)
#define IDM_LANG_VB (IDM_LANG + 21)
#define IDM_LANG_BATCH (IDM_LANG + 22)
#define IDM_LANG_CS (IDM_LANG + 23)
#define IDM_LANG_LUA (IDM_LANG + 24)
#define IDM_LANG_TEX (IDM_LANG + 25)
#define IDM_LANG_FORTRAN (IDM_LANG + 26)
#define IDM_LANG_BASH (IDM_LANG + 27)
#define IDM_LANG_FLASH (IDM_LANG + 28)
#define IDM_LANG_NSIS (IDM_LANG + 29)
#define IDM_LANG_TCL (IDM_LANG + 30)
#define IDM_LANG_LISP (IDM_LANG + 31)
#define IDM_LANG_SCHEME (IDM_LANG + 32)
#define IDM_LANG_ASM (IDM_LANG + 33)
#define IDM_LANG_DIFF (IDM_LANG + 34)
#define IDM_LANG_PROPS (IDM_LANG + 35)
#define IDM_LANG_PS (IDM_LANG + 36)
#define IDM_LANG_RUBY (IDM_LANG + 37)
#define IDM_LANG_SMALLTALK (IDM_LANG + 38)
#define IDM_LANG_VHDL (IDM_LANG + 39)
#define IDM_LANG_CAML (IDM_LANG + 40)
#define IDM_LANG_KIX (IDM_LANG + 41)
#define IDM_LANG_ADA (IDM_LANG + 42)
#define IDM_LANG_VERILOG (IDM_LANG + 43)
#define IDM_LANG_AU3 (IDM_LANG + 44)
#define IDM_LANG_MATLAB (IDM_LANG + 45)
#define IDM_LANG_HASKELL (IDM_LANG + 46)
#define IDM_LANG_INNO (IDM_LANG + 47)
#define IDM_LANG_CMAKE (IDM_LANG + 48)
#define IDM_LANG_YAML (IDM_LANG + 49)
#define IDM_LANG_COBOL (IDM_LANG + 50)
#define IDM_LANG_D (IDM_LANG + 51)
#define IDM_LANG_GUI4CLI (IDM_LANG + 52)
#define IDM_LANG_POWERSHELL (IDM_LANG + 53)
#define IDM_LANG_R (IDM_LANG + 54)
#define IDM_LANG_JSP (IDM_LANG + 55)
#define IDM_LANG_COFFEESCRIPT (IDM_LANG + 56)
#define IDM_LANG_JSON (IDM_LANG + 57)
#define IDM_LANG_FORTRAN_77 (IDM_LANG + 58)
#define IDM_LANG_BAANC (IDM_LANG + 59)
#define IDM_LANG_SREC (IDM_LANG + 60)
#define IDM_LANG_IHEX (IDM_LANG + 61)
#define IDM_LANG_TEHEX (IDM_LANG + 62)
#define IDM_LANG_SWIFT (IDM_LANG + 63)
#define IDM_LANG_ASN1 (IDM_LANG + 64)
#define IDM_LANG_AVS (IDM_LANG + 65)
#define IDM_LANG_BLITZBASIC (IDM_LANG + 66)
#define IDM_LANG_PUREBASIC (IDM_LANG + 67)
#define IDM_LANG_FREEBASIC (IDM_LANG + 68)
#define IDM_LANG_CSOUND (IDM_LANG + 69)
#define IDM_LANG_ERLANG (IDM_LANG + 70)
#define IDM_LANG_ESCRIPT (IDM_LANG + 71)
#define IDM_LANG_FORTH (IDM_LANG + 72)
#define IDM_LANG_LATEX (IDM_LANG + 73)
#define IDM_LANG_MMIXAL (IDM_LANG + 74)
#define IDM_LANG_NIM (IDM_LANG + 75)
#define IDM_LANG_NNCRONTAB (IDM_LANG + 76)
#define IDM_LANG_OSCRIPT (IDM_LANG + 77)
#define IDM_LANG_REBOL (IDM_LANG + 78)
#define IDM_LANG_REGISTRY (IDM_LANG + 79)
#define IDM_LANG_RUST (IDM_LANG + 80)
#define IDM_LANG_SPICE (IDM_LANG + 81)
#define IDM_LANG_TXT2TAGS (IDM_LANG + 82)
#define IDM_LANG_VISUALPROLOG (IDM_LANG + 83)
#define IDM_LANG_TYPESCRIPT (IDM_LANG + 84)
#define IDM_LANG_JSON5 (IDM_LANG + 85)
#define IDM_LANG_MSSQL (IDM_LANG + 86)
#define IDM_LANG_GDSCRIPT (IDM_LANG + 87)
#define IDM_LANG_HOLLYWOOD (IDM_LANG + 88)
#define IDM_LANG_GOLANG (IDM_LANG + 89)
#define IDM_LANG_RAKU (IDM_LANG + 90)
#define IDM_LANG_TOML (IDM_LANG + 91)
#define IDM_LANG_EXTERNAL (IDM_LANG + 165)
#define IDM_LANG_EXTERNAL_LIMIT (IDM_LANG + 179)
#define IDM_LANG_USER (IDM_LANG + 180) //46180: Used for translation
#define IDM_LANG_USER_LIMIT (IDM_LANG + 210) //46210: Ajust with IDM_LANG_USER
#define IDM_LANG_USER_DLG (IDM_LANG + 250) //46250: Used for translation
#define IDM_LANG_OPENUDLDIR (IDM_LANG + 300)
#define IDM_LANG_UDLCOLLECTION_PROJECT_SITE (IDM_LANG + 301)
#define IDM_ABOUT (IDM + 7000)
#define IDM_HOMESWEETHOME (IDM_ABOUT + 1)
#define IDM_PROJECTPAGE (IDM_ABOUT + 2)
#define IDM_ONLINEDOCUMENT (IDM_ABOUT + 3)
#define IDM_FORUM (IDM_ABOUT + 4)
//#define IDM_PLUGINSHOME (IDM_ABOUT + 5)
#define IDM_UPDATE_NPP (IDM_ABOUT + 6)
#define IDM_WIKIFAQ (IDM_ABOUT + 7)
//#define IDM_HELP (IDM_ABOUT + 8)
#define IDM_CONFUPDATERPROXY (IDM_ABOUT + 9)
#define IDM_CMDLINEARGUMENTS (IDM_ABOUT + 10)
//#define IDM_ONLINESUPPORT (IDM_ABOUT + 11)
#define IDM_DEBUGINFO (IDM_ABOUT + 12)
#define IDM_SETTING (IDM + 8000)
// #define IDM_SETTING_TAB_SIZE (IDM_SETTING + 1)
// #define IDM_SETTING_TAB_REPLCESPACE (IDM_SETTING + 2)
// #define IDM_SETTING_HISTORY_SIZE (IDM_SETTING + 3)
// #define IDM_SETTING_EDGE_SIZE (IDM_SETTING + 4)
#define IDM_SETTING_IMPORTPLUGIN (IDM_SETTING + 5)
#define IDM_SETTING_IMPORTSTYLETHEMES (IDM_SETTING + 6)
#define IDM_SETTING_TRAYICON (IDM_SETTING + 8)
#define IDM_SETTING_SHORTCUT_MAPPER (IDM_SETTING + 9)
#define IDM_SETTING_REMEMBER_LAST_SESSION (IDM_SETTING + 10)
#define IDM_SETTING_PREFERENCE (IDM_SETTING + 11)
#define IDM_SETTING_OPENPLUGINSDIR (IDM_SETTING + 14)
#define IDM_SETTING_PLUGINADM (IDM_SETTING + 15)
#define IDM_SETTING_SHORTCUT_MAPPER_MACRO (IDM_SETTING + 16)
#define IDM_SETTING_SHORTCUT_MAPPER_RUN (IDM_SETTING + 17)
#define IDM_SETTING_EDITCONTEXTMENU (IDM_SETTING + 18)
#define IDM_TOOL (IDM + 8500)
#define IDM_TOOL_MD5_GENERATE (IDM_TOOL + 1)
#define IDM_TOOL_MD5_GENERATEFROMFILE (IDM_TOOL + 2)
#define IDM_TOOL_MD5_GENERATEINTOCLIPBOARD (IDM_TOOL + 3)
#define IDM_TOOL_SHA256_GENERATE (IDM_TOOL + 4)
#define IDM_TOOL_SHA256_GENERATEFROMFILE (IDM_TOOL + 5)
#define IDM_TOOL_SHA256_GENERATEINTOCLIPBOARD (IDM_TOOL + 6)
#define IDM_TOOL_SHA1_GENERATE (IDM_TOOL + 7)
#define IDM_TOOL_SHA1_GENERATEFROMFILE (IDM_TOOL + 8)
#define IDM_TOOL_SHA1_GENERATEINTOCLIPBOARD (IDM_TOOL + 9)
#define IDM_TOOL_SHA512_GENERATE (IDM_TOOL + 10)
#define IDM_TOOL_SHA512_GENERATEFROMFILE (IDM_TOOL + 11)
#define IDM_TOOL_SHA512_GENERATEINTOCLIPBOARD (IDM_TOOL + 12)
#define IDM_EXECUTE (IDM + 9000)
#define IDM_SYSTRAYPOPUP (IDM + 3100)
#define IDM_SYSTRAYPOPUP_ACTIVATE (IDM_SYSTRAYPOPUP + 1)
#define IDM_SYSTRAYPOPUP_NEWDOC (IDM_SYSTRAYPOPUP + 2)
#define IDM_SYSTRAYPOPUP_NEW_AND_PASTE (IDM_SYSTRAYPOPUP + 3)
#define IDM_SYSTRAYPOPUP_OPENFILE (IDM_SYSTRAYPOPUP + 4)
#define IDM_SYSTRAYPOPUP_CLOSE (IDM_SYSTRAYPOPUP + 5)
#define IDR_WINDOWS_MENU 11000
#define IDM_WINDOW_WINDOWS (IDR_WINDOWS_MENU + 1)
#define IDM_WINDOW_SORT_FN_ASC (IDR_WINDOWS_MENU + 2)
#define IDM_WINDOW_SORT_FN_DSC (IDR_WINDOWS_MENU + 3)
#define IDM_WINDOW_SORT_FP_ASC (IDR_WINDOWS_MENU + 4)
#define IDM_WINDOW_SORT_FP_DSC (IDR_WINDOWS_MENU + 5)
#define IDM_WINDOW_SORT_FT_ASC (IDR_WINDOWS_MENU + 6)
#define IDM_WINDOW_SORT_FT_DSC (IDR_WINDOWS_MENU + 7)
#define IDM_WINDOW_SORT_FS_ASC (IDR_WINDOWS_MENU + 8)
#define IDM_WINDOW_SORT_FS_DSC (IDR_WINDOWS_MENU + 9)
#define IDM_WINDOW_MRU_FIRST (IDR_WINDOWS_MENU + 20)
#define IDM_WINDOW_MRU_LIMIT (IDR_WINDOWS_MENU + 59)
#define IDM_WINDOW_COPY_NAME (IDM_WINDOW_MRU_LIMIT + 1)
#define IDM_WINDOW_COPY_PATH (IDM_WINDOW_MRU_LIMIT + 2)
#define IDR_DROPLIST_MENU 14000
#define IDM_DROPLIST_LIST (IDR_DROPLIST_MENU + 1)
#define IDM_DROPLIST_MRU_FIRST (IDR_DROPLIST_MENU + 20)
| 38,710
|
C++
|
.h
| 599
| 59.776294
| 127
| 0.53099
|
shriprem/FWDataViz
| 37
| 6
| 0
|
GPL-2.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,543,144
|
PluginInterface.h
|
shriprem_FWDataViz/src/NPP/PluginInterface.h
|
// This file is part of Notepad++ project
// Copyright (C)2024 Don HO <[email protected]>
// 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 <https://www.gnu.org/licenses/>.
// For more comprehensive information on plugin communication, please refer to the following resource:
// https://npp-user-manual.org/docs/plugin-communication/
#pragma once
#include "Scintilla.h"
#include "Notepad_plus_msgs.h"
typedef const wchar_t * (__cdecl * PFUNCGETNAME)();
struct NppData
{
HWND _nppHandle = nullptr;
HWND _scintillaMainHandle = nullptr;
HWND _scintillaSecondHandle = nullptr;
};
typedef void (__cdecl * PFUNCSETINFO)(NppData);
typedef void (__cdecl * PFUNCPLUGINCMD)();
typedef void (__cdecl * PBENOTIFIED)(SCNotification *);
typedef LRESULT (__cdecl * PMESSAGEPROC)(UINT Message, WPARAM wParam, LPARAM lParam);
struct ShortcutKey
{
bool _isCtrl = false;
bool _isAlt = false;
bool _isShift = false;
UCHAR _key = 0;
};
const int menuItemSize = 64;
struct FuncItem
{
wchar_t _itemName[menuItemSize] = { '\0' };
PFUNCPLUGINCMD _pFunc = nullptr;
int _cmdID = 0;
bool _init2Check = false;
ShortcutKey *_pShKey = nullptr;
};
typedef FuncItem * (__cdecl * PFUNCGETFUNCSARRAY)(int *);
// You should implement (or define an empty function body) those functions which are called by Notepad++ plugin manager
extern "C" __declspec(dllexport) void setInfo(NppData);
extern "C" __declspec(dllexport) const wchar_t * getName();
extern "C" __declspec(dllexport) FuncItem * getFuncsArray(int *);
extern "C" __declspec(dllexport) void beNotified(SCNotification *);
extern "C" __declspec(dllexport) LRESULT messageProc(UINT Message, WPARAM wParam, LPARAM lParam);
// This API return always true now, since Notepad++ isn't compiled in ANSI mode anymore
extern "C" __declspec(dllexport) BOOL isUnicode();
| 2,368
|
C++
|
.h
| 55
| 41.509091
| 119
| 0.75817
|
shriprem/FWDataViz
| 37
| 6
| 0
|
GPL-2.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,145
|
Docking.h
|
shriprem_FWDataViz/src/NPP/Docking.h
|
// This file is part of Notepad++ project
// Copyright (C)2024 Don HO <[email protected]>
// 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 <https://www.gnu.org/licenses/>.
#pragma once
#include <windows.h>
// ATTENTION : It's a part of interface header, so don't include the others header here
// styles for containers
#define CAPTION_TOP TRUE
#define CAPTION_BOTTOM FALSE
// defines for docking manager
#define CONT_LEFT 0
#define CONT_RIGHT 1
#define CONT_TOP 2
#define CONT_BOTTOM 3
#define DOCKCONT_MAX 4
// mask params for plugins of internal dialogs
#define DWS_ICONTAB 0x00000001 // Icon for tabs are available
#define DWS_ICONBAR 0x00000002 // Icon for icon bar are available (currently not supported)
#define DWS_ADDINFO 0x00000004 // Additional information are in use
#define DWS_USEOWNDARKMODE 0x00000008 // Use plugin's own dark mode
#define DWS_PARAMSALL (DWS_ICONTAB|DWS_ICONBAR|DWS_ADDINFO)
// default docking values for first call of plugin
#define DWS_DF_CONT_LEFT (CONT_LEFT << 28) // default docking on left
#define DWS_DF_CONT_RIGHT (CONT_RIGHT << 28) // default docking on right
#define DWS_DF_CONT_TOP (CONT_TOP << 28) // default docking on top
#define DWS_DF_CONT_BOTTOM (CONT_BOTTOM << 28) // default docking on bottom
#define DWS_DF_FLOATING 0x80000000 // default state is floating
struct tTbData {
HWND hClient = nullptr; // client Window Handle
const wchar_t* pszName = nullptr; // name of plugin (shown in window)
int dlgID = 0; // a funcItem provides the function pointer to start a dialog. Please parse here these ID
// user modifications
UINT uMask = 0; // mask params: look to above defines
HICON hIconTab = nullptr; // icon for tabs
const wchar_t* pszAddInfo = nullptr; // for plugin to display additional informations
// internal data, do not use !!!
RECT rcFloat = {}; // floating position
int iPrevCont = 0; // stores the privious container (toggling between float and dock)
const wchar_t* pszModuleName = nullptr; // it's the plugin file name. It's used to identify the plugin
};
struct tDockMgr {
HWND hWnd = nullptr; // the docking manager wnd
RECT rcRegion[DOCKCONT_MAX] = {{}}; // position of docked dialogs
};
#define HIT_TEST_THICKNESS 20
#define SPLITTER_WIDTH 4
| 2,975
|
C++
|
.h
| 57
| 50.649123
| 129
| 0.715517
|
shriprem/FWDataViz
| 37
| 6
| 0
|
GPL-2.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,146
|
StaticDialog.h
|
shriprem_FWDataViz/src/NPP/StaticDialog.h
|
// This file is part of Notepad++ project
// Copyright (C)2024 Don HO <[email protected]>
// 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 <https://www.gnu.org/licenses/>.
#pragma once
#include "dpiManagerV2.h"
#include "Notepad_plus_msgs.h"
#include "../Darkmode/NPP_Plugin_Darkmode.h"
#include "Window.h"
typedef HRESULT (WINAPI * ETDTProc) (HWND, DWORD);
enum class PosAlign { left, right, top, bottom };
struct DLGTEMPLATEEX
{
WORD dlgVer = 0;
WORD signature = 0;
DWORD helpID = 0;
DWORD exStyle = 0;
DWORD style = 0;
WORD cDlgItems = 0;
short x = 0;
short y = 0;
short cx = 0;
short cy = 0;
// The structure has more fields but are variable length
};
class StaticDialog : public Window
{
public :
virtual ~StaticDialog();
virtual void create(int dialogID, bool isRTL = false, bool msgDestParent = true);
virtual bool isCreated() const {
return (_hSelf != nullptr);
}
void getMappedChildRect(HWND hChild, RECT& rcChild) const;
void getMappedChildRect(int idChild, RECT& rcChild) const;
void redrawDlgItem(const int nIDDlgItem, bool forceUpdate = false) const;
void goToCenter(UINT swpFlags = SWP_SHOWWINDOW);
bool moveForDpiChange();
void display(bool toShow = true, bool enhancedPositioningCheckWhenShowing = false) const;
RECT getViewablePositionRect(RECT testRc) const;
POINT getTopPoint(HWND hwnd, bool isLeft = true) const;
bool isCheckedOrNot(int checkControlID) const
{
return (BST_CHECKED == ::SendMessage(::GetDlgItem(_hSelf, checkControlID), BM_GETCHECK, 0, 0));
}
void setChecked(int checkControlID, bool checkOrNot = true) const
{
::SendDlgItemMessage(_hSelf, checkControlID, BM_SETCHECK, checkOrNot ? BST_CHECKED : BST_UNCHECKED, 0);
}
void setDpi() {
_dpiManager.setDpi(_hSelf);
}
void setPositionDpi(LPARAM lParam, UINT flags = SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE) {
DPIManagerV2::setPositionDpi(lParam, _hSelf, flags);
}
void destroy() override;
DPIManagerV2& dpiManager() { return _dpiManager; }
protected:
RECT _rc{};
DPIManagerV2 _dpiManager;
static intptr_t CALLBACK dlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
virtual intptr_t CALLBACK run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) = 0;
HGLOBAL makeRTLResource(int dialogID, DLGTEMPLATE **ppMyDlgTemplate);
};
| 2,920
|
C++
|
.h
| 74
| 36.743243
| 105
| 0.743626
|
shriprem/FWDataViz
| 37
| 6
| 0
|
GPL-2.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,147
|
control_ids.h
|
shriprem_FWDataViz/src/Resources/control_ids.h
|
#pragma once
#define IDD_VISUALIZER_DOCKPANEL 9000
#define IDC_VIZPANEL_FILETYPE_LABEL 9001
#define IDC_VIZPANEL_FILE_SAMPLES_BTN 9002
#define IDC_VIZPANEL_FILETYPE_CONFIG 9003
#define IDC_VIZPANEL_FILETYPE_SELECT 9004
#define IDC_VIZPANEL_THEME_LABEL 9005
#define IDC_VIZPANEL_THEME_CONFIG 9006
#define IDC_VIZPANEL_THEME_SELECT 9007
#define IDC_VIZPANEL_CLEAR_BTN 9008
#define IDC_VIZPANEL_PREFERENCES_BTN 9009
#define IDB_VIZ_FILE_SAMPLES_BITMAP 9010
#define IDB_VIZ_FILE_CONFIG_BITMAP 9011
#define IDB_VIZ_COLOR_CONFIG_BITMAP 9012
#define IDB_VIZ_INFO_BITMAP 9013
#define IDB_VIZ_MOVE_DOWN_BITMAP 9014
#define IDB_VIZ_MOVE_UP_BITMAP 9015
#define IDB_VIZ_INI_FILES_BITMAP 9016
#define IDB_VIZ_ABOUT_BITMAP 9017
#define IDC_VIZPANEL_FIELD_LABEL 9021
#define IDC_VIZPANEL_FIELD_INFO 9022
#define IDC_VIZPANEL_JUMP_FIELD_BTN 9023
#define IDC_VIZPANEL_EXTRACT_DATA_BTN 9024
#define IDB_VIZ_TOOL_BTN_STD_FIELDS 9041
#define IDI_VIZ_TOOL_BTN_STD_FIELDS 9042
#define IDI_VIZ_TOOL_BTN_FLUENT_FIELDS 9043
#define IDI_VIZ_TOOL_BTN_DARK_FIELDS 9044
#define IDC_VIZPANEL_AUTO_DETECT_FT 9051
#define IDC_VIZPANEL_INFO_BUTTON 9052
#define IDC_VIZPANEL_MCBS_OVERRIDE 9053
#define IDC_VIZPANEL_MCBS_OVERRIDE_IND 9054
#define IDC_VIZPANEL_DEFAULT_BACKGROUND 9055
#define IDC_VIZPANEL_SHOW_CALLTIP 9056
#define IDC_VIZPANEL_ABOUT_BUTTON 9057
#define IDC_VIZPANEL_FILE_INFO_BUTTON 9058
#define IDC_VIZPANEL_FIELD_LEFT_BUTTON 9061
#define IDC_VIZPANEL_FIELD_RIGHT_BUTTON 9062
#define IDC_VIZPANEL_FIELD_COPY_BUTTON 9063
#define IDC_VIZPANEL_FIELD_COPY_TRIM 9064
#define IDC_VIZPANEL_FIELD_PASTE_BUTTON 9065
#define IDC_VIZPANEL_PASTE_LEFT_LABEL 9066
#define IDC_VIZPANEL_PASTE_RPAD_FIELD 9067
#define IDC_VIZPANEL_PASTE_RPAD_INDIC 9068
#define IDC_VIZPANEL_PASTE_RPAD_LABEL 9069
#define IDC_VIZPANEL_PASTE_RIGHT_LABEL 9070
#define IDC_VIZPANEL_PASTE_LPAD_LABEL 9071
#define IDC_VIZPANEL_PASTE_LPAD_FIELD 9072
#define IDC_VIZPANEL_PASTE_LPAD_INDIC 9073
#define IDC_VIZPANEL_FOLDING_GROUP_BOX 9080
#define IDC_VIZPANEL_FOLDING_APPLY_BTN 9081
#define IDC_VIZPANEL_FOLDING_REMOVE_BTN 9082
#define IDC_VIZPANEL_FOLDING_DEFINE_BTN 9083
#define IDC_VIZPANEL_FOLDING_FOLD_BTN 9084
#define IDC_VIZPANEL_FOLDING_TOGGLE_BTN 9085
#define IDC_VIZPANEL_FOLDING_UNFOLD_BTN 9086
#define IDC_VIZPANEL_FOLD_INFO_BUTTON 9087
#define IDD_FILE_TYPE_DEFINER_DIALOG 9100
#define IDC_FWVIZ_DEF_FILE_GROUP_BOX 9101
#define IDC_FWVIZ_DEF_FILE_LIST_BOX 9102
#define IDC_FWVIZ_DEF_FILE_DOWN_BUTTON 9103
#define IDC_FWVIZ_DEF_FILE_UP_BUTTON 9104
#define IDC_FWVIZ_DEF_FILE_DESC_LABEL 9105
#define IDC_FWVIZ_DEF_FILE_DESC_EDIT 9106
#define IDC_FWVIZ_DEF_FILE_EOL_LABEL 9107
#define IDC_FWVIZ_DEF_FILE_EOL_EDIT 9108
#define IDC_FWVIZ_DEF_ADFT_GROUP_LABEL 9110
#define IDC_FWVIZ_DEF_ADFT_INFO_BUTTON 9111
#define IDC_FWVIZ_DEF_ADFT_LINE_LABEL 9112
#define IDC_FWVIZ_DEF_ADFT_REGEX_LABEL 9113
#define IDC_FWVIZ_DEF_ADFT_LINE_EDIT_01 9115
#define IDC_FWVIZ_DEF_ADFT_REGEX_EDT_01 9116
#define IDC_FWVIZ_DEF_ADFT_LINE_EDIT_02 9117
#define IDC_FWVIZ_DEF_ADFT_REGEX_EDT_02 9118
#define IDC_FWVIZ_DEF_ADFT_LINE_EDIT_03 9119
#define IDC_FWVIZ_DEF_ADFT_REGEX_EDT_03 9120
#define IDC_FWVIZ_DEF_FILE_THEME_LABEL 9121
#define IDC_FWVIZ_DEF_FILE_THEME_LIST 9122
#define IDC_FWVIZ_DEF_FILE_ACCEPT_BTN 9123
#define IDC_FWVIZ_DEF_FILE_RESET_BTN 9124
#define IDC_FWVIZ_DEF_FILE_NEW_BTN 9125
#define IDC_FWVIZ_DEF_FILE_CLONE_BTN 9126
#define IDC_FWVIZ_DEF_FILE_DEL_BTN 9127
#define IDC_FWVIZ_DEF_MCBS_CHECKBOX 9128
#define IDC_FWVIZ_DEF_MCBS_INFO_BUTTON 9129
#define IDC_FWVIZ_DEF_REC_GROUP_BOX 9141
#define IDC_FWVIZ_DEF_REC_DOWN_BUTTON 9142
#define IDC_FWVIZ_DEF_REC_UP_BUTTON 9143
#define IDC_FWVIZ_DEF_REC_LIST_BOX 9144
#define IDC_FWVIZ_DEF_REC_DESC_LABEL 9145
#define IDC_FWVIZ_DEF_REC_DESC_EDIT 9146
#define IDC_FWVIZ_DEF_REC_START_LABEL 9147
#define IDC_FWVIZ_DEF_REC_START_EDIT 9148
#define IDC_FWVIZ_DEF_REC_REGEX_LABEL 9149
#define IDC_FWVIZ_DEF_REC_REGEX_EDIT 9150
#define IDC_FWVIZ_DEF_REC_THEME_LABEL 9151
#define IDC_FWVIZ_DEF_REC_THEME_INFOBTN 9153
#define IDC_FWVIZ_DEF_REC_THEME_LIST 9154
#define IDC_FWVIZ_DEF_REC_ACCEPT_BTN 9155
#define IDC_FWVIZ_DEF_REC_RESET_BTN 9156
#define IDC_FWVIZ_DEF_REC_NEW_BTN 9157
#define IDC_FWVIZ_DEF_REC_CLONE_BTN 9158
#define IDC_FWVIZ_DEF_REC_DEL_BTN 9159
#define IDC_FWVIZ_DEF_FIELD_GROUP_BOX 9171
#define IDC_FWVIZ_DEF_FIELD_WIDTHS_TEXT 9172
#define IDC_FWVIZ_DEF_FIELD_WIDTHS_EDIT 9173
#define IDC_FWVIZ_DEF_FIELD_LABELS_TEXT 9174
#define IDC_FWVIZ_DEF_FIELD_LABELS_EDIT 9175
#define IDC_FWVIZ_DEF_FIELD_ACCEPT_BTN 9176
#define IDC_FWVIZ_DEF_FIELD_RESET_BTN 9177
#define IDC_FWVIZ_DEF_SAVE_CONFIG_BTN 9191
#define IDC_FWVIZ_DEF_RESET_BTN 9192
#define IDC_FWVIZ_DEF_BACKUP_LOAD_BTN 9193
#define IDC_FWVIZ_DEF_BACKUP_VIEW_BTN 9194
#define IDC_FWVIZ_DEF_EXTRACT_BTN 9195
#define IDC_FWVIZ_DEF_APPEND_BTN 9196
#define IDC_FWVIZ_DEF_INFO_BUTTON 9197
#define IDC_FWVIZ_FIELD_TYPE_BUTTON 9198
#define IDD_THEME_DEFINER_DIALOG 9200
#define IDC_THEME_DEF_GROUP_BOX 9201
#define IDC_THEME_DEF_LIST_BOX 9202
#define IDC_THEME_DEF_DOWN_BUTTON 9203
#define IDC_THEME_DEF_UP_BUTTON 9204
#define IDC_THEME_DEF_DESC_LABEL 9205
#define IDC_THEME_DEF_DESC_EDIT 9206
#define IDC_THEME_DEF_ACCEPT_BTN 9207
#define IDC_THEME_DEF_RESET_BTN 9208
#define IDC_THEME_DEF_NEW_BTN 9209
#define IDC_THEME_DEF_CLONE_BTN 9210
#define IDC_THEME_DEF_DEL_BTN 9211
#define IDC_THEME_STYLE_GROUP_BOX 9221
#define IDC_THEME_STYLE_PREVIEW_LABEL 9222
#define IDC_THEME_STYLE_DOWN_BUTTON 9223
#define IDC_THEME_STYLE_UP_BUTTON 9224
#define IDC_THEME_STYLE_LIST_BOX 9225
#define IDC_THEME_STYLE_NEW_BTN 9226
#define IDC_THEME_STYLE_CLONE_BTN 9227
#define IDC_THEME_STYLE_DEL_BTN 9228
#define IDC_THEME_STYLE_DEF_ACCEPT_BTN 9241
#define IDC_THEME_STYLE_DEF_RESET_BTN 9242
#define IDC_THEME_DEF_SAVE_CONFIG_BTN 9281
#define IDC_THEME_DEF_RESET_CONFIG_BTN 9282
#define IDC_THEME_DEF_BACKUP_LOAD_BTN 9283
#define IDC_THEME_DEF_BACKUP_VIEW_BTN 9284
#define IDC_THEME_DEF_EXTRACT_BTN 9285
#define IDC_THEME_DEF_APPEND_BTN 9286
#define IDC_THEME_DEF_INFO_BUTTON 9287
#define IDC_THEME_SWATCH_BACK_00 9300
#define IDC_THEME_SWATCH_BACK_01 9301
#define IDC_THEME_SWATCH_BACK_02 9302
#define IDC_THEME_SWATCH_BACK_03 9303
#define IDC_THEME_SWATCH_BACK_04 9304
#define IDC_THEME_SWATCH_BACK_05 9305
#define IDC_THEME_SWATCH_BACK_06 9306
#define IDC_THEME_SWATCH_BACK_07 9307
#define IDC_THEME_SWATCH_BACK_08 9308
#define IDC_THEME_SWATCH_BACK_09 9309
#define IDC_THEME_SWATCH_BACK_10 9310
#define IDC_THEME_SWATCH_BACK_11 9311
#define IDC_THEME_SWATCH_BACK_12 9312
#define IDC_THEME_SWATCH_BACK_13 9313
#define IDC_THEME_SWATCH_BACK_14 9314
#define IDC_THEME_SWATCH_BACK_15 9315
#define IDC_THEME_SWATCH_BACK_16 9316
#define IDC_THEME_SWATCH_BACK_17 9317
#define IDC_THEME_SWATCH_BACK_18 9318
#define IDC_THEME_SWATCH_BACK_19 9319
#define IDC_THEME_SWATCH_BACK_20 9320
#define IDC_THEME_SWATCH_BACK_21 9321
#define IDC_THEME_SWATCH_BACK_22 9322
#define IDC_THEME_SWATCH_BACK_23 9323
#define IDC_THEME_SWATCH_BACK_24 9324
#define IDC_THEME_SWATCH_BACK_25 9325
#define IDC_THEME_SWATCH_BACK_26 9326
#define IDC_THEME_SWATCH_BACK_27 9327
#define IDC_THEME_SWATCH_BACK_28 9328
#define IDC_THEME_SWATCH_BACK_29 9329
#define IDC_THEME_SWATCH_FORE_00 9350
#define IDC_THEME_SWATCH_FORE_01 9351
#define IDC_THEME_SWATCH_FORE_02 9352
#define IDC_THEME_SWATCH_FORE_03 9353
#define IDC_THEME_SWATCH_FORE_04 9354
#define IDC_THEME_SWATCH_FORE_05 9355
#define IDC_THEME_SWATCH_FORE_06 9356
#define IDC_THEME_SWATCH_FORE_07 9357
#define IDC_THEME_SWATCH_FORE_08 9358
#define IDC_THEME_SWATCH_FORE_09 9359
#define IDC_THEME_SWATCH_FORE_10 9360
#define IDC_THEME_SWATCH_FORE_11 9361
#define IDC_THEME_SWATCH_FORE_12 9362
#define IDC_THEME_SWATCH_FORE_13 9363
#define IDC_THEME_SWATCH_FORE_14 9364
#define IDC_THEME_SWATCH_FORE_15 9365
#define IDC_THEME_SWATCH_FORE_16 9366
#define IDC_THEME_SWATCH_FORE_17 9367
#define IDC_THEME_SWATCH_FORE_18 9368
#define IDC_THEME_SWATCH_FORE_19 9369
#define IDC_THEME_SWATCH_FORE_20 9370
#define IDC_THEME_SWATCH_FORE_21 9371
#define IDC_THEME_SWATCH_FORE_22 9372
#define IDC_THEME_SWATCH_FORE_23 9373
#define IDC_THEME_SWATCH_FORE_24 9374
#define IDC_THEME_SWATCH_FORE_25 9375
#define IDC_THEME_SWATCH_FORE_26 9376
#define IDC_THEME_SWATCH_FORE_27 9377
#define IDC_THEME_SWATCH_FORE_28 9378
#define IDC_THEME_SWATCH_FORE_29 9379
#define IDD_FILE_TYPE_EXIM_DIALOG 9400
#define IDC_FTEXIM_EDIT_LABEL 9401
#define IDC_FTEXIM_EDIT_CNTRL 9402
#define IDC_FTEXIM_LOAD_FILE 9403
#define IDC_FTEXIM_SAVE_FILE 9404
#define IDC_FTEXIM_APPEND 9405
#define IDC_FTEXIM_INFO_BUTTON 9406
#define IDD_JUMP_FIELD_DIALOG 9420
#define IDC_JUMP_FIELD_LABEL 9421
#define IDC_JUMP_FIELD_LIST 9422
#define IDC_JUMP_CARET_FLASH_LABEL 9423
#define IDC_JUMP_CARET_FLASH_SLIDER 9424
#define IDC_JUMP_CARET_FLASH_VALUE 9425
#define IDC_JUMP_FIELD_GO_BTN 9426
#define IDC_JUMP_FIELD_PREF_SEQ_NUM 9427
#define IDD_DATA_EXTRACT_DIALOG 9500
#define IDC_DAT_EXT_INFO_BUTTON 9501
#define IDC_DAT_EXT_PREFIX_LABEL 9502
#define IDC_DAT_EXT_RECORD_LABEL 9503
#define IDC_DAT_EXT_FIELD_LABEL 9504
#define IDC_DAT_EXT_FIELD_TRIM 9505
#define IDC_DAT_EXT_SUFFIX_LABEL 9506
#define IDC_DAT_EXT_PAGE_ADD_BUTTON 9507
#define IDC_DAT_EXT_PAGE_DEL_BUTTON 9508
#define IDC_DAT_EXT_PAGE_PREV_BUTTON 9509
#define IDC_DAT_EXT_PAGE_NEXT_BUTTON 9510
#define IDC_DAT_EXT_ITEM_DOWN_BUTTON 9511
#define IDC_DAT_EXT_ITEM_UP_BUTTON 9512
#define IDC_DAT_EXT_EXTRACT_BTN 9513
#define IDC_DAT_EXT_CURRENT_LINE 9514
#define IDC_DAT_EXT_NEW_LINE_TAB_TIP 9515
#define IDC_DAT_EXT_NEW_KEYBOARD_TIP 9516
#define IDC_DAT_EXT_ITEM_SEQ_01 9521
#define IDC_DAT_EXT_ITEM_SEQ_02 9522
#define IDC_DAT_EXT_ITEM_SEQ_03 9523
#define IDC_DAT_EXT_ITEM_SEQ_04 9524
#define IDC_DAT_EXT_ITEM_SEQ_05 9525
#define IDC_DAT_EXT_ITEM_SEQ_06 9526
#define IDC_DAT_EXT_ITEM_SEQ_07 9527
#define IDC_DAT_EXT_ITEM_SEQ_08 9528
#define IDC_DAT_EXT_ITEM_SEQ_09 9529
#define IDC_DAT_EXT_ITEM_SEQ_10 9530
#define IDC_DAT_EXT_ITEM_PREFIX_01 9541
#define IDC_DAT_EXT_ITEM_PREFIX_02 9542
#define IDC_DAT_EXT_ITEM_PREFIX_03 9543
#define IDC_DAT_EXT_ITEM_PREFIX_04 9544
#define IDC_DAT_EXT_ITEM_PREFIX_05 9545
#define IDC_DAT_EXT_ITEM_PREFIX_06 9546
#define IDC_DAT_EXT_ITEM_PREFIX_07 9547
#define IDC_DAT_EXT_ITEM_PREFIX_08 9548
#define IDC_DAT_EXT_ITEM_PREFIX_09 9549
#define IDC_DAT_EXT_ITEM_PREFIX_10 9550
#define IDC_DAT_EXT_ITEM_PREFIX_2 9551
#define IDC_DAT_EXT_ITEM_PREFIX_3 9552
#define IDC_DAT_EXT_ITEM_PREFIX_4 9553
#define IDC_DAT_EXT_ITEM_PREFIX_5 9554
#define IDC_DAT_EXT_ITEM_PREFIX_6 9555
#define IDC_DAT_EXT_ITEM_PREFIX_7 9556
#define IDC_DAT_EXT_ITEM_PREFIX_8 9557
#define IDC_DAT_EXT_ITEM_PREFIX_9 9558
#define IDC_DAT_EXT_ITEM_RECORD_01 9561
#define IDC_DAT_EXT_ITEM_RECORD_02 9562
#define IDC_DAT_EXT_ITEM_RECORD_03 9563
#define IDC_DAT_EXT_ITEM_RECORD_04 9564
#define IDC_DAT_EXT_ITEM_RECORD_05 9565
#define IDC_DAT_EXT_ITEM_RECORD_06 9566
#define IDC_DAT_EXT_ITEM_RECORD_07 9567
#define IDC_DAT_EXT_ITEM_RECORD_08 9568
#define IDC_DAT_EXT_ITEM_RECORD_09 9569
#define IDC_DAT_EXT_ITEM_RECORD_10 9570
#define IDC_DAT_EXT_ITEM_FIELD_01 9581
#define IDC_DAT_EXT_ITEM_FIELD_02 9582
#define IDC_DAT_EXT_ITEM_FIELD_03 9583
#define IDC_DAT_EXT_ITEM_FIELD_04 9584
#define IDC_DAT_EXT_ITEM_FIELD_05 9585
#define IDC_DAT_EXT_ITEM_FIELD_06 9586
#define IDC_DAT_EXT_ITEM_FIELD_07 9587
#define IDC_DAT_EXT_ITEM_FIELD_08 9588
#define IDC_DAT_EXT_ITEM_FIELD_09 9589
#define IDC_DAT_EXT_ITEM_FIELD_10 9590
#define IDC_DAT_EXT_ITEM_SUFFIX_01 9601
#define IDC_DAT_EXT_ITEM_SUFFIX_02 9602
#define IDC_DAT_EXT_ITEM_SUFFIX_03 9603
#define IDC_DAT_EXT_ITEM_SUFFIX_04 9604
#define IDC_DAT_EXT_ITEM_SUFFIX_05 9605
#define IDC_DAT_EXT_ITEM_SUFFIX_06 9606
#define IDC_DAT_EXT_ITEM_SUFFIX_07 9607
#define IDC_DAT_EXT_ITEM_SUFFIX_08 9608
#define IDC_DAT_EXT_ITEM_SUFFIX_09 9609
#define IDC_DAT_EXT_ITEM_SUFFIX_10 9610
#define IDC_DAT_EXT_ITEM_ADD_BTN_01 9621
#define IDC_DAT_EXT_ITEM_ADD_BTN_02 9622
#define IDC_DAT_EXT_ITEM_ADD_BTN_03 9623
#define IDC_DAT_EXT_ITEM_ADD_BTN_04 9624
#define IDC_DAT_EXT_ITEM_ADD_BTN_05 9625
#define IDC_DAT_EXT_ITEM_ADD_BTN_06 9626
#define IDC_DAT_EXT_ITEM_ADD_BTN_07 9627
#define IDC_DAT_EXT_ITEM_ADD_BTN_08 9628
#define IDC_DAT_EXT_ITEM_ADD_BTN_09 9629
#define IDC_DAT_EXT_ITEM_ADD_BTN_10 9630
#define IDC_DAT_EXT_ITEM_DEL_BTN_01 9641
#define IDC_DAT_EXT_ITEM_DEL_BTN_02 9642
#define IDC_DAT_EXT_ITEM_DEL_BTN_03 9643
#define IDC_DAT_EXT_ITEM_DEL_BTN_04 9644
#define IDC_DAT_EXT_ITEM_DEL_BTN_05 9645
#define IDC_DAT_EXT_ITEM_DEL_BTN_06 9646
#define IDC_DAT_EXT_ITEM_DEL_BTN_07 9647
#define IDC_DAT_EXT_ITEM_DEL_BTN_08 9648
#define IDC_DAT_EXT_ITEM_DEL_BTN_09 9649
#define IDC_DAT_EXT_ITEM_DEL_BTN_10 9650
#define IDC_DAT_EXT_TEMPLATE_GROUP 9661
#define IDC_DAT_EXT_TEMPLATE_CURR_ONLY 9662
#define IDC_DAT_EXT_TEMPLATE_LIST_LABEL 9663
#define IDC_DAT_EXT_TEMPLATE_LIST 9664
#define IDC_DAT_EXT_TEMPLATE_NAME_LABEL 9665
#define IDC_DAT_EXT_TEMPLATE_NAME 9666
#define IDC_DAT_EXT_TEMPLATE_SAVE_BTN 9667
#define IDC_DAT_EXT_TEMPLATE_NEW_BTN 9668
#define IDC_DAT_EXT_TEMPLATE_DEL_BTN 9669
#define IDB_DAT_EXT_PLUS_BITMAP 9681
#define IDB_DAT_EXT_MINUS_BITMAP 9682
#define IDB_DAT_EXT_PAGE_ADD_BITMAP 9683
#define IDB_DAT_EXT_PAGE_DEL_BITMAP 9684
#define IDB_DAT_EXT_PAGE_PREV_BITMAP 9685
#define IDB_DAT_EXT_PAGE_NEXT_BITMAP 9686
#define IDD_FIELD_TYPE_DEFINER_DIALOG 9800
#define IDC_FIELD_TYPE_GROUP_BOX 9801
#define IDC_FIELD_TYPE_LIST_BOX 9802
#define IDC_FIELD_TYPE_NEW_BTN 9803
#define IDC_FIELD_TYPE_CLONE_BTN 9804
#define IDC_FIELD_TYPE_DEL_BTN 9805
#define IDC_FIELD_TYPE_DESC_LABEL 9806
#define IDC_FIELD_TYPE_DESC_EDIT 9807
#define IDC_FIELD_TYPE_REGEX_LABEL 9808
#define IDC_FIELD_TYPE_REGEX_EDIT 9809
#define IDC_FIELD_STYLE_DEF_SAVE_BTN 9824
#define IDC_FIELD_STYLE_DEF_RESET_BTN 9825
#define IDC_FIELD_TYPE_INFO_BUTTON 9826
#define IDD_PREFERENCES_DIALOG 9900
#define IDC_PREF_CLEARVIZ_AUTO 9901
#define IDC_PREF_CLEARVIZ_PANEL 9902
#define IDC_PREF_MBCHARS_STATE 9903
#define IDC_PREF_HOP_FIELD_LEFT_EDGE 9904
#define IDC_PREF_FOLD_LINE_GROUP_BOX 9910
#define IDC_PREF_FOLD_LINE_COLOR 9911
#define IDC_PREF_FOLD_LINE_ALPHA_SLIDER 9912
#define IDC_PREF_FOLD_LINE_TRANSPARENT 9913
#define IDC_PREF_FOLD_LINE_OPAQUE 9914
#define IDC_STYLE_DEF_GROUP_BOX 10001
#define IDC_STYLE_DEF_BACK_LABEL 10002
#define IDC_STYLE_DEF_BACK_EDIT 10003
#define IDC_STYLE_DEF_BACKCOLOR 10004
#define IDC_STYLE_DEF_FORE_LABEL 10005
#define IDC_STYLE_DEF_FORE_EDIT 10006
#define IDC_STYLE_DEF_FORECOLOR 10007
#define IDC_STYLE_DEF_BOLD 10008
#define IDC_STYLE_DEF_ITALICS 10009
#define IDC_STYLE_DEF_PREVIEW_LABEL 10010
#define IDC_STYLE_DEF_PREVIEW_BOX 10011
#define IDD_FOLD_STRUCT_DEFINER_DIALOG 10200
#define IDC_FOLD_DEF_FILE_GROUP_BOX 10201
#define IDC_FOLD_DEF_FILE_LIST_BOX 10202
#define IDC_FOLD_DEF_FILE_DOWN_BUTTON 10203
#define IDC_FOLD_DEF_FILE_UP_BUTTON 10204
#define IDC_FOLD_DEF_FILE_TYPE_LABEL 10205
#define IDC_FOLD_DEF_FILE_TYPE_LIST 10206
#define IDC_FOLD_DEF_AUTO_FOLD_APPLY 10207
#define IDC_FOLD_DEF_FILE_ACCEPT_BTN 10208
#define IDC_FOLD_DEF_FILE_RESET_BTN 10209
#define IDC_FOLD_DEF_FILE_NEW_BTN 10210
#define IDC_FOLD_DEF_FILE_CLONE_BTN 10211
#define IDC_FOLD_DEF_FILE_DEL_BTN 10212
#define IDC_FOLD_DEF_HDR_REC_GROUP_BOX 10221
#define IDC_FOLD_DEF_HDR_REC_LIST_BOX 10222
#define IDC_FOLD_DEF_HDR_REC_DOWN_BTN 10223
#define IDC_FOLD_DEF_HDR_REC_UP_BTN 10224
#define IDC_FOLD_DEF_HDR_REC_TYPE_LABEL 10225
#define IDC_FOLD_DEF_HDR_REC_TYPE_LIST 10226
#define IDC_FOLD_DEF_HDR_PRIORITY_LABEL 10227
#define IDC_FOLD_DEF_HDR_PRIORITY_EDIT 10228
#define IDC_FOLD_DEF_HDR_REC_RECURSIVE 10229
#define IDC_FOLD_DEF_HDR_REC_ACCEPT_BTN 10230
#define IDC_FOLD_DEF_HDR_REC_RESET_BTN 10231
#define IDC_FOLD_DEF_HDR_REC_NEW_BTN 10232
#define IDC_FOLD_DEF_HDR_REC_CLONE_BTN 10233
#define IDC_FOLD_DEF_HDR_REC_DEL_BTN 10234
#define IDC_FOLD_IMPLICIT_TRMNTRS_GROUP 10241
#define IDC_FOLD_IMPLICIT_TRMNTRS_LIST 10242
#define IDC_FOLD_EXPLICIT_TRMNTRS_GROUP 10243
#define IDC_FOLD_EXPLICIT_TRMNTRS_LIST 10244
#define IDC_FOLD_EXPLICIT_ENDREC_LABEL 10245
#define IDC_FOLD_EXPLICIT_ENDREC_LIST 10246
#define IDC_FOLD_EXPLICIT_ENDREC_ACCEPT 10247
#define IDC_FOLD_EXPLICIT_ENDREC_RESET 10248
#define IDC_FOLD_EXPLICIT_ENDREC_NEW 10249
#define IDC_FOLD_EXPLICIT_ENDREC_DEL 10250
#define IDC_FOLD_DEF_SAVE_BTN 10261
#define IDC_FOLD_DEF_RESET_BTN 10262
#define IDC_FOLD_DEF_BACKUP_LOAD_BTN 10263
#define IDC_FOLD_DEF_BACKUP_VIEW_BTN 10264
#define IDC_FOLD_DEF_EXTRACT_BTN 10265
#define IDC_FOLD_DEF_APPEND_BTN 10266
#define IDC_FOLD_DEF_INFO_BUTTON 10267
#define IDD_ABOUT_DIALOG 12000
#define IDC_ABOUT_NAME 12001
#define IDC_ABOUT_VERSION 12002
#define IDC_ABOUT_ATTRIBUTION 12003
#define IDC_ABOUT_PROD_URL 12004
#define IDC_ABOUT_BUILD_TIME 12005
| 18,723
|
C++
|
.h
| 415
| 44.06988
| 45
| 0.717863
|
shriprem/FWDataViz
| 37
| 6
| 0
|
GPL-2.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,148
|
SamplesMenuDefs.h
|
shriprem_FWDataViz/src/Resources/SamplesMenuDefs.h
|
#pragma once
#include <string>
using std::wstring;
const enum SampleFileTypes {
SINGLE_REC,
MULTI_REC,
MULTI_LINE
};
struct SampleFileInfo {
SampleFileTypes sample_type;
string display_name;
wstring file_name;
string file_type;
};
const SampleFileInfo gSampleFiles[] =
{
{
SINGLE_REC,
"[Real Data] ⌂ Weather Stations List",
L"ghcnd-stations.txt",
"FT001_WEATHER_STATIONS_LIST"
},
{
SINGLE_REC,
"[Real Data] ☀ Daily Weather Data",
L"AYM00089664.dly",
"FT002_DAILY_WEATHER_DATA"
},
{
SINGLE_REC,
"[Real Data] ☤ ICD-10 Diagnosis Codes",
L"icd10cm_codes_2021.txt",
"FT003_ICD-10_DIAGNOSIS_CODES"
},
{
SINGLE_REC,
"[Real Data] ☣ ICD-10 Order Codes",
L"icd10cm_order_2021.txt",
"FT004_ICD-10_ORDER_CODES"
},
{
SINGLE_REC,
"[Real Data] ₽ ICD-10 Procedure Codes",
L"icd10pcs_codes_2021.txt",
"FT005_ICD-10_PROCEDURE_CODES"
},
{
MULTI_REC,
"[Demo Data - Foldable] Ŧ Treasury IPAC (ANSI) File",
L"IPAC_ANSI.txt",
"FT010_TREASURY_IPAC_FILE"
},
{
MULTI_REC,
"[Mixed Data] ☀ Multiple GSN Daily Weather",
L"MultiGSN.txt",
"FT007_MULTIPLE_GSN_DAILY_WEATHER"
},
{
MULTI_REC,
"[Real Data] ⌂ GSN-Flagged Weather Stations List",
L"ghcnd-stations.txt",
"FT006_GSN-FLAGGED_WEATHER_STATIONS"
},
{
MULTI_REC,
"[Real Data - Foldable] ☣ ICD-10 Billable-Flagged Order Codes",
L"icd10cm_order_2021.txt",
"FT008_ICD-10_BILLABLE-FLAGGED_ORDER_CODES"
},
{
MULTI_REC,
"[Demo Data - Foldable] § Ouroboros Fold Levels",
L"Ouroboros.txt",
"FT012_OUROBOROS_FOLD_LEVELS"
},
{
MULTI_LINE,
"[Demo Data] Ŧ Multi-Line Multi-Byte ĪƤĂĊ File",
L"IPAC_Unicode.txt",
"FT011_MULTI-LINE_MULTI-BYTE_FILE"
},
{
MULTI_LINE,
"[Mixed Data] ☀ Multi-Line GSN Daily Weather",
L"MultiLineGSN.txt",
"FT009_MULTI-LINE_GSN_DAILY_WEATHER"
}
};
| 2,095
|
C++
|
.h
| 89
| 17.921348
| 69
| 0.607794
|
shriprem/FWDataViz
| 37
| 6
| 0
|
GPL-2.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,149
|
localization.h
|
shriprem_FWDataViz/src/Resources/localization.h
|
#pragma once
// Common
#define MENU_PANEL_NAME L"Fixed-Width Data Visualizer"
#define MENU_SHOW_PANEL L"Show FWData&Viz Panel"
#define MENU_CONFIG_FILE_TYPES L"Configure &File Types"
#define MENU_CONFIG_THEMES L"Configure Color &Themes"
#define MENU_FIELD_JUMP L"&Jump to Field"
#define MENU_FIELD_COPY L"Field &Copy"
#define MENU_FIELD_PASTE L"Field &Paste"
#define MENU_FIELD_LEFT L"Hop to &Left edge of the Field"
#define MENU_FIELD_RIGHT L"Hop to &Right edge of the Field"
#define MENU_DATA_EXTRACTION L"&Data Extraction"
#define MENU_DEMO_SINGLE_REC_FILES L"Sample &Single-Record-Type Files"
#define MENU_DEMO_MULTI_REC_FILES L"Sample &Multiple-Record-Type Files"
#define MENU_DEMO_MULTI_LINE_FILES L"Sample M&ultiple-Line Record Files"
#define MENU_ABOUT L"A&bout"
// Fixed Width Data Visualizer Panel
#define VIZ_PANEL_FILETYPE_LABEL L"&File Type:"
#define VIZ_PANEL_THEME_LABEL L"&Visualizer Theme:"
#define VIZ_PANEL_CLEAR_BUTTON L"Cle&ar"
#define VIZ_PANEL_CLOSE L"Clos&e"
#define VIZ_PANEL_PREFERENCES L"Prefere&nces"
#define VIZ_PANEL_AUTO_DETECT_FT L"Auto-detect File Type"
#define VIZ_PANEL_MCBS_OVERRIDE L"Multi-Byte Chars"
#define VIZPANEL_DEFAULT_BACKGROUND L"Default Background"
#define VIZPANEL_SHOW_CALLTIP L"Show Calltip"
#define VIZ_PANEL_FIELD_COPY_TRIM L"Trim Field Copy"
#define VIZ_PANEL_FIELD_LABEL L"Cursor Position Data"
#define VIZ_PANEL_JUMP_FIELD_BTN L"&Jump to Field"
#define VIZ_PANEL_FIELD_COPY_BTN L"Field &Copy"
#define VIZ_PANEL_FIELD_PASTE_BTN L"Field &Paste"
#define VIZ_PANEL_PASTE_LEFT_LABEL L"Left-aligned"
#define VIZ_PANEL_PASTE_RIGHT_LABEL L"Right-aligned"
#define VIZ_PANEL_PASTE_RPAD_LABEL L"&RPAD:"
#define VIZ_PANEL_PASTE_LPAD_LABEL L":&LPAD"
#define VIZ_PANEL_EXTRACT_DATA_BTN L"&Data Extraction"
#define VIZPANEL_FOLD_GROUP_BOX L"Folding"
#define VIZPANEL_FOLD_APPLY_BTN L"Apply"
#define VIZPANEL_FOLD_REAPPLY_BTN L"Re-Apply"
#define VIZPANEL_FOLD_REMOVE_BTN L"Remove"
#define VIZPANEL_FOLD_DEFINE_BTN L"Define…"
#define VIZPANEL_FOLD_FOLD_BTN L"Fold »"
#define VIZPANEL_FOLD_TOGGLE_BTN L"Toggle Line"
#define VIZPANEL_FOLD_UNFOLD_BTN L"Unfold »"
#define VIZ_PANEL_INFO_TIP L"View Readme Online"
#define VIZ_PANEL_FILE_SAMPLES_TIP L"View Sample Files"
#define VIZ_PANEL_FILE_CONFIG_TIP L"Open File Type Metadata Editor"
#define VIZ_PANEL_THEME_CONFIG_TIP L"Open Visualizer Theme Editor"
#define VIZ_PANEL_CLEAR_BTN_TIP L"If \"Auto-detect File Type\" option is:\r\n● Checked: Redo the file type detection and visualization.\r\n● Not checked: Clear the document's fixed-width visualization.\r\n\r\nTo always clear visualization, modify the setting in \"Preferences\"."
#define VIZ_PANEL_FIELD_TRIM_TIP L"When copying a field, trim padding character(s) on either the left or right,\r\nbased on which field edge is closer to the cursor position."
#define VIZ_PANEL_FIELD_LEFT_TIP L"Move cursor to the left edge of the current field.\r\n\r\n● If already at the left edge of the field, the cursor will be moved to the left edge of the preceding field.\r\n\r\nAccessible via keyboard shortcut. See the plugin menu."
#define VIZ_PANEL_FIELD_RIGHT_TIP L"Move cursor to the right edge of the current field.\r\n\r\n● If already at the right edge of the field, the cursor will be moved to the right edge of the following field.\r\n\r\nUse 'Preferences' » 'Hop Right...' to change this behavior.\r\n\r\nAccessible via keyboard shortcut. See the plugin menu."
#define VIZ_PANEL_FLD_ALT_RIGHT_TIP L"Move cursor to the left edge of the following field.\r\n\r\nUse 'Preferences' » 'Hop Right...' to change this behavior.\r\n\r\nAccessible via keyboard shortcut. See the plugin menu."
#define VIZ_PANEL_FIELD_COPY_TIP L"Copy current field data.\r\n\r\n● If \"Trim Field Copy\" option is checked, field data will be trimmed off padding character(s) on either the left or right edge, based on which field edge is closer to the cursor position.\r\n\r\nAccessible via keyboard shortcut. See the plugin menu."
#define VIZ_PANEL_FIELD_PASTE_TIP L"Paste clipboard text into current field, replacing its current contents.\r\n\r\n● Aligned either to the left or the right edge of the field, based on which field edge is closer to the cursor position.\r\n● If the clipboard text is shorter than the field width, it will be paddded on the opposite edge of the aligned edge.\r\n● If the clipboard text is longer, it will be trimmed to the field width.\r\n\r\nAccessible via keyboard shortcut. See the plugin menu."
#define VIZ_PANEL_FIELD_RPAD_TIP L"● When pasting, RPAD character(s) will be used for padding the right edge of the field.\r\n● If copying with \"Trim Field Copy\" option checked, characters on the right edge of the field data that match (the sequence of) the padding character(s) will be trimmed.\r\n● When RPAD is left blank, a space will be used as the padding character."
#define VIZ_PANEL_FIELD_LPAD_TIP L"● When pasting, LPAD character(s) will be used for padding the left edge of the field.\r\n● If copying with \"Trim Field Copy\" option checked, characters on the left edge of the field data that match (the sequence of) the padding character(s) will be trimmed.\r\n● When LPAD is left blank, a space will be used as the padding character."
#define VIZ_PANEL_JUMP_FIELD_TITLE L"Jump to Field"
#define VIZ_PANEL_JUMP_CHANGED_DOC L"The currently active document is of a different File Type.\r\n\r\nUnable to jump to the specified field."
#define VIZ_PANEL_JUMP_CHANGED_REC L"Caret has moved to a different Record Type.\r\n\r\nUnable to jump to the specified field."
#define VIZ_PANEL_DARKMODE_CHANGED L"Please restart Notepad++ to refresh the FWDataViz plugin panel and dialogs with the changed Darkmode settings."
#define VIZ_PANEL_FILE_INFO_TITLE L"Active INI Files"
#define VIZ_PANEL_FILE_INFO_TIP L"\nNOTE: Click the button to refresh the files list"
#define CUR_POS_DATA_BLANK_LINE L"<Blank Line>"
#define CUR_POS_DATA_UNKOWN_REC L"<Unknown Record Type>"
#define CUR_POS_DATA_REC_END L"<Record End>"
#define CUR_POS_DATA_REC_TERM L"<Record Terminator>"
#define CUR_POS_DATA_REC_TYPE L" Record Type: "
#define CUR_POS_DATA_REC_LENGTH L"Record Length: "
#define CUR_POS_DATA_CURR_DEFINED L" [Current/Defined]"
#define CUR_POS_DATA_OVERFLOW L" Overflow!"
#define CUR_POS_DATA_FIELD_LABEL L" Field Label: "
#define CUR_POS_DATA_FIELD_NUM L"Field #"
#define CUR_POS_DATA_FIELD_START L" Field Start: "
#define CUR_POS_DATA_FIELD_WIDTH L" Field Width: "
#define CUR_POS_DATA_FIELD_COL L" Field Column: "
#define CUR_POS_DATA_ANSI_BYTE L" ANSI Byte: "
#define CUR_POS_DATA_UTF8_BYTES L" UTF-8 Bytes: "
// About Dialog
#define ABOUT_DIALOG_TITLE L"About"
#define ABOUT_PLUGIN_NAME L"Fixed Width Data Visualizer Plugin for Notepad++"
#define ABOUT_BTN_LABEL_OK L"&OK"
// Configuration Dialog
#define FWVIZ_DEF_DIALOG_TITLE L"File Type Metadata Editor"
#define FWVIZ_DEF_FILE_GROUP_BOX L"File Type"
#define FWVIZ_DEF_FILE_MOVE_DOWN L"Move down the selected File Type"
#define FWVIZ_DEF_FILE_MOVE_UP L"Move up the selected File Type"
#define FWVIZ_DEF_FILE_DESC_LABEL L"File Type - Label:"
#define FWVIZ_DEF_FILE_EOL_LABEL L"File Type - Records Terminator:"
#define FWVIZ_DEF_MCBS_CHECKBOX L"Multi-byte Character Data"
#define FWVIZ_DEF_ADFT_GROUP_LABEL L"Auto-Detect File Type"
#define FWVIZ_DEF_ADFT_LINE_LABEL L"Line No:"
#define FWVIZ_DEF_ADFT_REGEX_LABEL L"Line Regex:"
#define FWVIZ_DEF_FILE_THEME_LABEL L"File Type - Color Theme:"
#define FWVIZ_DEF_FILE_ACCEPT_BTN L"Accept"
#define FWVIZ_DEF_FILE_RESET_BTN L"Reset"
#define FWVIZ_DEF_FILE_NEW_BTN L"New"
#define FWVIZ_DEF_FILE_CLONE_BTN L"Clone"
#define FWVIZ_DEF_FILE_DEL_BTN L"Delete"
#define FWVIZ_DEF_REC_GROUP_BOX L"File Type » Record Types"
#define FWVIZ_DEF_REC_MOVE_DOWN L"Move down the selected Record Type"
#define FWVIZ_DEF_REC_MOVE_UP L"Move up the selected Record Type"
#define FWVIZ_DEF_REC_DESC_LABEL L"Record Type - Label:"
#define FWVIZ_DEF_REC_START_LABEL L"Record Type - Starts With:"
#define FWVIZ_DEF_REC_REGEX_LABEL L"Record Type - Regex Key:"
#define FWVIZ_DEF_REC_THEME_LABEL L"Record Type - Color Theme:"
#define FWVIZ_DEF_REC_THEME_FROM_FT L"[Use File Type - Color Theme]"
#define FWVIZ_DEF_REC_ACCEPT_BTN L"Accept"
#define FWVIZ_DEF_REC_RESET_BTN L"Reset"
#define FWVIZ_DEF_REC_NEW_BTN L"New"
#define FWVIZ_DEF_REC_CLONE_BTN L"Clone"
#define FWVIZ_DEF_REC_DEL_BTN L"Delete"
#define FWVIZ_DEF_FIELD_GROUP_BOX L"Record Type » Fields"
#define FWVIZ_DEF_FIELD_LABELS_TEXT L"Field Labels:"
#define FWVIZ_DEF_FIELD_WIDTHS_TEXT L"Widths:"
#define FWVIZ_DEF_FIELD_ACCEPT_BTN L"Accept"
#define FWVIZ_DEF_FIELD_RESET_BTN L"Reset"
#define FWVIZ_DEF_FIELD_TYPE_BTN L"&Define Field Types"
#define FWVIZ_DIALOG_SAVE_BTN L"&Save as Primary Configuration"
#define FWVIZ_DIALOG_RESET_BTN L"&Reload Primary Configuration"
#define FWVIZ_DIALOG_BKUP_LOAD_BTN L"&Load Backup Configuration"
#define FWVIZ_DIALOG_BKUP_VIEW_BTN L"&View Backup Folder"
#define FWVIZ_DIALOG_EXTRACT_BTN L"E&xtract Selected File Type Data"
#define FWVIZ_DIALOG_APPEND_BTN L"&Append New File Type Data"
#define FWVIZ_DIALOG_CLOSE_BTN L"&Close"
#define UTILS_REGEX_ERROR L"Invalid Regular Expression"
#define FWVIZ_DIALOG_NUMERIC_TITLE L"Numbers only!"
#define FWVIZ_DIALOG_NUMERIC_MSG L"This edit field will only accept numbers,\r\nwith an optional leading minus sign."
#define FWVIZ_DIALOG_COMMAS_TITLE L"Commas are item separators"
#define FWVIZ_DIALOG_COMMAS_MESSAGE L"The line will be split into multiple items when the 'Accept' button below is clicked."
#define FWVIZ_DISCARD_CHANGES L"Discard changes?"
#define FWVIZ_DEFAULT_OVERWRITE L"Save the Default Configuration changes as the Primary Configuration?"
#define FWVIZ_OPEN_BKUP_CONFIG_DLG L"Open Backup Configuration File"
#define FWVIZ_SAVE_BKUP_CONFIG_DLG L"Save Backup Configuration File"
#define FWVIZ_FT_NEW_ACTION L"Add New File Type"
#define FWVIZ_FT_CLONE_ACTION L"Clone Selected File Type"
#define FWVIZ_FT_APPEND_ACTION L"Append File Type(s)"
#define FWVIZ_FT_LIMIT_ERROR L"Only %i File Types can be defined."
#define FWVIZ_RT_NEW_ACTION L"Add New Record Types"
#define FWVIZ_RT_CLONE_ACTION L"Clone Selected Record Types"
#define FWVIZ_RT_LIMIT_ERROR L"Only %i Record Types can be defined per File Type."
#define FWVIZ_DEF_MCBS_HINT_TITLE L"Multi-byte Character Data"
#define FWVIZ_DEF_MCBS_HINT_TEXT L"1. Check this box only if the file type is likely to contain multi-byte character data.\r\n\r\n2. When this box is checked, field widths will be calculated using character counts. And, TABs will be counted as multiple spaces (or characters).\r\n\r\n3. When this box is unchecked, field widths will be calculated using byte counts.\r\n\r\nClick the (i) icon to view the online documentation."
#define FWVIZ_DEF_ADFT_HINT_TITLE L"ADFT in a Nutshell"
#define FWVIZ_DEF_ADFT_HINT_TEXT L"1. Line Numbers begin at '1', counting forwards from the start of file. Negative line numbers will count backwards from the end of file. Zero and numbers (+ve or -ve) beyond file line count will fail ADFT matching.\r\n\r\n2. ADFT Regexes with no terminating '$' will be used as *starts-with* match. Whereas, those with terminating '$' will be used as *full-line* match. ADFT Regexes will have an implicit caret(^) at the start if it has not been explicitly included.\r\n\r\nClick the (i) icon to view the online ADFT documentation."
#define FWVIZ_DEF_RECTHEME_HINT_HDR L"Record-type Theme"
#define FWVIZ_DEF_RECTHEME_HINT_TXT L"Specify a different color theme than the file-type theme for select-few record types to make them distinctive.\r\n\r\nFor an example, see: 'Transaction Headers' inside the Samples » Treasury IPAC file.\r\n\r\nClick the (i) icon to view the online documentation."
// Style Definition Component
#define STYLE_DEF_GROUP_BOX L"Style Definition"
#define STYLE_DEF_BACK_LABEL L"Back Color:"
#define STYLE_DEF_FORE_LABEL L"Fore Color:"
#define STYLE_DEF_BOLD L"Bold"
#define STYLE_DEF_ITALICS L"Italics"
#define STYLE_DEF_PREVIEW_LABEL L"Output:"
#define STYLE_DEF_HEX_TITLE L"Hexadecimal characters only!"
#define STYLE_DEF_HEX_CHARS_ONLY L"This edit field will only accept characters in the following range: 0-9|A-F|a-f"
// Theme Dialog
#define THEME_DIALOG_TITLE L"Visualizer Theme Editor"
#define THEME_DEF_GROUP_BOX L"Themes"
#define THEME_DEF_MOVE_DOWN L"Move down the selected Theme"
#define THEME_DEF_MOVE_UP L"Move up the selected Theme"
#define THEME_DEF_DESC_LABEL L"Theme - Label:"
#define THEME_DEF_ACCEPT_BTN L"Accept"
#define THEME_DEF_RESET_BTN L"Reset"
#define THEME_DEF_NEW_BTN L"New"
#define THEME_DEF_CLONE_BTN L"Clone"
#define THEME_DEF_DEL_BTN L"Delete"
#define THEME_STYLE_GROUP_BOX L"Theme » Styles"
#define THEME_STYLE_MOVE_DOWN L"Move down the selected Style"
#define THEME_STYLE_MOVE_UP L"Move up the selected Style"
#define THEME_STYLE_CLONE_BTN L"Clone"
#define THEME_STYLE_NEW_BTN L"New"
#define THEME_STYLE_DEL_BTN L"Delete"
#define THEME_STYLE_DEF_ACCEPT_BTN L"Accept"
#define THEME_STYLE_DEF_RESET_BTN L"Reset"
#define THEME_DIALOG_SAVE_BTN L"&Save as Primary Themes File"
#define THEME_DIALOG_RESET_BTN L"&Reload Primary Themes File"
#define THEME_DIALOG_BKUP_LOAD_BTN L"&Load Backup Themes File"
#define THEME_DIALOG_BKUP_VIEW_BTN L"&View Backup Folder"
#define THEME_DIALOG_EXTRACT_BTN L"E&xtract Selected Theme Data"
#define THEME_DIALOG_APPEND_BTN L"&Append New Theme Data"
#define THEME_DIALOG_CLOSE_BTN L"&Close"
#define THEME_DEF_NEW_ACTION L"Add New Theme"
#define THEME_DEF_CLONE_ACTION L"Clone Selected Theme"
#define THEME_DEF_APPEND_ACTION L"Append Theme(s)"
#define THEME_DEF_LIMIT_ERROR L"Only %i Themes can be defined."
#define THEME_STYLE_NEW_ACTION L"Add New Style"
#define THEME_STYLE_CLONE_ACTION L"Clone Selected Style"
#define THEME_STYLE_LIMIT_ERROR L"Only %i Styles can be defined per Theme."
#define THEME_DISCARD_CHANGES L"Discard changes?"
#define THEME_OPEN_BKUP_CONFIG_DLG L"Open Backup Themes File"
#define THEME_SAVE_BKUP_CONFIG_DLG L"Save Backup Themes File"
// Fold Structures Editor Dialog
#define FOLD_STRUCT_DIALOG_TITLE L"Fold Structures Editor"
#define FOLD_DEF_FILE_GROUP_BOX L"Fold Structures"
#define FOLD_DEF_FILE_MOVE_DOWN L"Move down the selected Fold Structure"
#define FOLD_DEF_FILE_MOVE_UP L"Move up the selected Fold Structure"
#define FOLD_DEF_FILE_TYPE_LABEL L"Fold Structure - File Type:"
#define FOLD_DEF_AUTO_FOLD_APPLY L"Automatically apply Fold Structure \t\ton matching files"
#define FOLD_DEF_FILE_ACCEPT_BTN L"Accept"
#define FOLD_DEF_FILE_RESET_BTN L"Reset"
#define FOLD_DEF_FILE_NEW_BTN L"New"
#define FOLD_DEF_FILE_RESET_BTN L"Reset"
#define FOLD_DEF_FILE_CLONE_BTN L"Clone"
#define FOLD_DEF_FILE_DEL_BTN L"Delete"
#define FOLD_DEF_HDR_REC_GROUP_BOX L"Fold Structure » Fold Blocks"
#define FOLD_DEF_HDR_REC_MOVE_DOWN L"Move down the selected Fold Block"
#define FOLD_DEF_HDR_REC_MOVE_UP L"Move up the selected Fold Block"
#define FOLD_DEF_HDR_REC_TYPE_LABEL L"Fold Block - Header Record Type:"
#define FOLD_DEF_HDR_PRIORITY_LABEL L"Fold Block - Priority: "
#define FOLD_DEF_HDR_REC_RECURSIVE L"Recursive Fold Block"
#define FOLD_DEF_HDR_REC_ACCEPT_BTN L"Accept"
#define FOLD_DEF_HDR_REC_RESET_BTN L"Reset"
#define FOLD_DEF_HDR_REC_NEW_BTN L"New"
#define FOLD_DEF_HDR_REC_RESET_BTN L"Reset"
#define FOLD_DEF_HDR_REC_CLONE_BTN L"Clone"
#define FOLD_DEF_HDR_REC_DEL_BTN L"Delete"
#define FOLD_IMPLICIT_TRMNTRS_GROUP L"Fold Block » Implicit Terminators"
#define FOLD_IMPLICIT_END_OF_FILE L"<End of File>"
#define FOLD_EXPLICIT_TRMNTRS_GROUP L"Fold Block » Explicit Terminators"
#define FOLD_EXPLICIT_ENDREC_LABEL L"Explicit Terminator - Record Type:"
#define FOLD_EXPLICIT_ENDREC_ACCEPT L"Accept"
#define FOLD_EXPLICIT_ENDREC_RESET L"Reset"
#define FOLD_EXPLICIT_ENDREC_NEW L"New"
#define FOLD_EXPLICIT_ENDREC_RESET L"Reset"
#define FOLD_EXPLICIT_ENDREC_DEL L"Delete"
#define FOLD_DEF_SAVE_BTN L"&Save as Primary Fold Structs"
#define FOLD_DEF_RESET_BTN L"&Reload Primary Fold Structs"
#define FOLD_DEF_BACKUP_LOAD_BTN L"&Load Backup Fold Structs"
#define FOLD_DEF_BACKUP_VIEW_BTN L"&View Backup Folder"
#define FOLD_DEF_EXTRACT_BTN L"E&xtract Selected Fold Structure"
#define FOLD_DEF_APPEND_BTN L"&Append New Fold Structure"
#define FOLD_DEF_DISCARD_CHANGES L"Discard changes?"
#define FOLD_DEF_OPEN_BKUP_CONFIG L"Open Backup Fold Structures File"
#define FOLD_DEF_SAVE_BKUP_CONFIG L"Save Backup Fold Structures File"
// Define Field Type Dialog
#define FIELD_TYPE_DEF_DLG_TITLE L"Define Field Types"
#define FIELD_TYPE_GROUP_BOX L"Field &Types"
#define FIELD_TYPE_NEW_BTN L"&New"
#define FIELD_TYPE_CLONE_BTN L"&Clone"
#define FIELD_TYPE_DEL_BTN L"&Delete"
#define FIELD_TYPE_DESC_LABEL L"Field Type &Label:"
#define FIELD_TYPE_REGEX_LABEL L"Field &Validation Regex:"
#define FIELD_STYLE_DEF_SAVE_BTN L"&Save"
#define FIELD_STYLE_DEF_RESET_BTN L"&Reset"
// Exim File Type Dialog
#define EXIM_APPEND_FT_TITLE L"Append File Type Metadata"
#define EXIM_EXTRACT_FT_TITLE L"Extract File Type Metadata"
#define EXIM_EDIT_FT_LABEL L"File Type Metadata:"
#define EXIM_APPEND_FT_BTN L"&Append File Type(s)"
#define EXIM_APPEND_THEME_TITLE L"Append Visualizer Theme Data"
#define EXIM_EXTRACT_THEME_TITLE L"Extract Visualizer Theme Data"
#define EXIM_EDIT_THEME_LABEL L"Visualizer Theme Data:"
#define EXIM_APPEND_THEME_BTN L"&Append Theme(s)"
#define EXIM_APPEND_FOLD_TITLE L"Append Fold Structure Data"
#define EXIM_EXTRACT_FOLD_TITLE L"Extract Fold Structure Data"
#define EXIM_EDIT_FOLD_LABEL L"Fold Structure Data:"
#define EXIM_APPEND_FOLD_BTN L"&Append Fold Struct(s)"
#define EXIM_LOAD_FILE_BTN L"&Load from a File"
#define EXIM_SAVE_FILE_BTN L"&Save to a File"
#define EXIM_CLOSE_BTN L"&Close"
#define EXIM_CANCEL_BTN L"&Cancel"
// Preferences Dialog
#define PREFERENCES_DIALOG_TITLE L"Preferences"
#define PREFERENCES_CLEARVIZ_AUTO L"\"Clear\" button click unchecks Auto-detect File Type"
#define PREFERENCES_CLEARVIZ_PANEL L"Closing plugin panel clears visualization"
#define PREFERENCES_MBCHARS_STATE L"Show Multi-byte checkbox in plugin panel"
#define PREFERENCES_HOP_LEFT_EDGE L"Hop Right: Move to the left edge of the following field"
#define PREFERENCES_CLOSE_BTN L"&Close"
#define PREF_CLEARVIZ_AUTO_TIP L"● When this box is unchecked, clicking the \"Clear\" button will redo the auto-file detection, followed by document visualization.\r\n\r\n● When this box is checked, clicking the \"Clear\" button will also uncheck the \"Auto-detect File Type\" checkbox, and also clear the document visualization."
#define PREF_CLEARVIZ_PANEL_TIP L"● Leave this box unchecked if you are only closing the plugin panel for more document viewing area but wish to retain the document visualization.\r\n\r\n● When this box is checked, closing the plugin panel will also clear the document visualization."
#define PREF_MBCHARS_STATE_TIP L"● When this box is checked, the \"Multi-Byte Chars\" 3-state checkbox will be displayed on the plugin panel. The 3-state checkbox is useful for quickly toggling between the single-byte and multi-byte modes of visualization of a document with multi-byte character data."
#define PREF_HOP_RT_LEFT_EDGE_TIP L"● When this box is unchecked, clicking the right \"Field Hop\" button will move cursor to the right edge of the current field. If already at the right edge of the field, the cursor will be moved to the right edge of the following field.\r\n\r\n● When this box is checked, clicking the right \"Field Hop\" button will move cursor to the left edge of the following field."
// Jump Field Dialog
#define JUMP_FIELD_DIALOG_TITLE L"Jump to Field"
#define JUMP_FIELD_SELECT_LABEL L"&Select Field:"
#define JUMP_FIELD_PREF_SEQ_NUM L"Show sequence numbers in the Select Field list"
#define JUMP_LABEL_CARET_FLASH L"Cursor Flash duration (in seconds)"
#define JUMP_FIELD_GO_BTN L"&Jump"
#define JUMP_FIELD_CLOSE_BTN L"&Cancel"
#define JUMP_TIP_CARET_FLASH L"When the cursor is set at its default width of '1', it can be hard to spot the cursor at its new position. To aid quick spotting, the cursor is briefly set to block mode at the destination position.\r\n\r\nSpecify the number of seconds to have the cursor flashing in block mode at the destination position."
// Data Extraction Dialog
#define DATA_EXTRACT_DIALOG_TITLE L"Fixed-Width Data Extraction"
#define DATA_EXTRACT_PREFIX_LABEL L"Prefix Text¹"
#define DATA_EXTRACT_RECORD_LABEL L"Record Type"
#define DATA_EXTRACT_FIELD_LABEL L"Field"
#define DATA_EXTRACT_FIELD_TRIM L"Trim Leading && Trailing Spaces"
#define DATA_EXTRACT_SUFFIX_LABEL L"Suffix Text¹"
#define DATA_EXTRACT_ADD_LINE_ITEM L"Insert Line Item\t[CTRL+Insert]"
#define DATA_EXTRACT_DEL_LINE_ITEM L"Delete Line Item\t[CTRL+Delete]"
#define DATA_EXTRACT_PAGE_PREV L"Previous Page\t[CTRL+Page Up]"
#define DATA_EXTRACT_PAGE_NEXT L"Next Page\t[CTRL+Page Down]"
#define DATA_EXTRACT_PAGE_ADD L"Add Page\t[CTRL+SHIFT+Insert]"
#define DATA_EXTRACT_PAGE_DEL L"Delete Page\t[CTRL+SHIFT+Delete]"
#define DATA_EXTRACT_MOVE_DOWN L"Move down the selected Line Item\t[CTRL+Down Arrow]"
#define DATA_EXTRACT_MOVE_UP L"Move up the selected Line Item\t[CTRL+Up Arrow]"
#define DATA_EXTRACT_EXTRACT_BTN L"E&xtract Data"
#define DATA_EXTRACT_CLOSE_BTN L"&Close"
#define DATA_EXTRACT_TEMPLATE_GROUP L"Reusable Templates"
#define DATA_EXTRACT_TEMPLATE_CURR L"Show only current FileType Templates"
#define DATA_EXTRACT_TEMPLATE_OTHER "[Other] "
#define DATA_EXTRACT_TEMPLATE_LOAD L"Load Template:"
#define DATA_EXTRACT_TEMPLATE_NAME L"Template Name:"
#define DATA_EXTRACT_TEMPLATE_SAVE L"&Save Template"
#define DATA_EXTRACT_TEMPLATE_NEW L"&New"
#define DATA_EXTRACT_TEMPLATE_DEL L"&Delete"
#define DATA_EXTRACT_NEW_LINE_TAB L"Tip¹:\nIn Prefix and Suffix Text boxes,\nuse \\n for New Lines and \\t for TABs."
#define DATA_EXTRACT_KEYBOARD_TIP L"Easy Keyboard Shortcuts"
#define DATA_EXTRACT_DELETE_PROMPT L"Delete Template?"
#define DATA_EXTRACT_INVTEMPL_TITLE L"Invalid Template Name!"
#define DATA_EXTRACT_INVTEMPL_MSG L"\"[\" and \"]\" are disallowed in Template Name."
#define DATA_EXTRACT_CHANGED_DOC L"The currently active document is of a different File Type.\r\n\r\nUnable to proceed with data extraction."
// Info Button Links
#define VIZPANEL_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/README.md"
#define VIZPANEL_FOLD_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/foldable_record_blocks.md"
#define FWVIZ_DEF_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/file_type_config_dialog.md"
#define FWVIZ_DEF_MCBS_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/multibyte_character_data.md"
#define FWVIZ_DEF_ADFT_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/auto_detect_file_type.md"
#define FWVIZ_RT_THEME_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/record_type_theme.md"
#define THEME_DEF_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/theme_config_dialog.md"
#define FOLD_DEF_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/fold_structs_editor.md"
#define CONFIG_APPEND_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/config_append_dialog.md"
#define CONFIG_EXTRACT_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/config_extract_dialog.md"
#define FIELD_TYPE_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/field_type_dialog.md"
#define DATA_EXTRACT_INFO_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/data_extract_dialog.md"
#define DATA_EXTRACT_KEYNAV_README L"https://github.com/shriprem/FWDataViz/blob/master/docs/data_extract_key_shortcuts.md"
| 24,906
|
C++
|
.h
| 326
| 75.104294
| 570
| 0.743138
|
shriprem/FWDataViz
| 37
| 6
| 0
|
GPL-2.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,150
|
FWVIZ_messages.h
|
shriprem_FWDataViz/src/Resources/FWVIZ_messages.h
|
#pragma once
#define FWVIZMSG 0x1000
/// <summary>
/// Used by EximFileTypeDialog to Append File Type / Theme / Fold Struct data
/// </summary>
/// <param name="WPARAM">: 0 - Not Used</param>
/// <param name="LAPRAM">: LPTSTR to the temp file name with data to be appended</param>
#define FWVIZMSG_APPEND_EXIM_DATA (FWVIZMSG + 1)
| 354
|
C++
|
.h
| 8
| 42.875
| 88
| 0.673469
|
shriprem/FWDataViz
| 37
| 6
| 0
|
GPL-2.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,152
|
texmark.cpp
|
jgain_EcoLearn/UnderSim/clh/texmark.cpp
|
/**
* @file
*
* Report the image formats supported by the OpenCL implementation.
*/
#include "clhpp.h"
#include <common/debug_vector.h>
#include <common/debug_unordered_map.h>
#include <string>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <boost/program_options.hpp>
#include "clh.h"
namespace po = boost::program_options;
static po::variables_map processOptions(int argc, char **argv)
{
po::options_description desc("General options");
desc.add_options()
("type", po::value<std::string>()->default_value("CL_FLOAT"), "image data type")
("modifier", po::value<std::string>()->default_value(""), "coordinate modifier");
po::variables_map vm;
po::store(po::command_line_parser(argc, argv)
.style(po::command_line_style::default_style & ~po::command_line_style::allow_guessing)
.options(desc)
.run(), vm);
po::notify(vm);
return vm;
}
int main(int argc, char **argv)
{
auto vm = processOptions(argc, argv);
cl::ImageFormat format(CL_RGBA, CL_FLOAT);
uts::string type = vm["type"].as<std::string>();
#define DO_TYPE(name) else if (type == #name) format.image_channel_data_type = name
if (false) {}
DO_TYPE(CL_FLOAT);
DO_TYPE(CL_HALF_FLOAT);
DO_TYPE(CL_UNORM_INT8);
DO_TYPE(CL_UNORM_INT16);
else
{
std::cerr << "Unknown data type " << type << '\n';
return 1;
}
uts::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
for (const auto &platform : platforms)
{
uts::vector<cl::Device> devices;
platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
for (const auto &device : devices)
{
if (!(device.getInfo<CL_DEVICE_TYPE>() & CL_DEVICE_TYPE_GPU))
continue;
std::cout << device.getInfo<CL_DEVICE_NAME>() << ":\n\n";
cl_context_properties properties[] =
{
CL_CONTEXT_PLATFORM,
(cl_context_properties) platform(),
0
};
cl::Context context(device, properties);
cl::CommandQueue queue(context, device, CL_QUEUE_PROFILING_ENABLE);
const int width = 1024;
const int height = 1024;
const int passes = 20;
const int taps = 9;
cl::Image2D image(context, CL_MEM_READ_ONLY, format, width, height);
cl::Buffer output(context, CL_MEM_READ_WRITE, 4 * sizeof(cl_uint));
uts::unordered_map<uts::string, uts::string> defines;
defines["ADDR_MODIFIER"] = vm["modifier"].as<std::string>();
cl::Program program = CLH::build(context, "texmark.cl", defines, "-cl-nv-maxrregcount=24");
auto kernel = cl::make_kernel<const cl::Image2D &, const cl::Buffer &>(program, "benchmark2d");
uts::vector<cl::Event> events;
events.reserve(passes);
for (int i = 0; i < passes; i++)
{
events.push_back(kernel({queue, {width, height}, {16, 16}}, image, output));
}
queue.finish();
cl_ulong total = 0;
for (int i = 0; i < passes; i++)
{
if (events[i].getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>() != CL_COMPLETE)
{
std::cerr << "WARNING: pass " << i << " did not complete correctly\n";
continue;
}
cl_ulong start, end;
start = events[i].getProfilingInfo<CL_PROFILING_COMMAND_START>();
end = events[i].getProfilingInfo<CL_PROFILING_COMMAND_END>();
total += end - start;
}
double mean = total * 1e-9 / passes;
double rate = width * height * taps / mean;
std::cout << rate * 1e-9 << '\n';
}
}
return 0;
}
| 3,897
|
C++
|
.cpp
| 101
| 29.534653
| 107
| 0.564069
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,153
|
climgformats.cpp
|
jgain_EcoLearn/UnderSim/clh/climgformats.cpp
|
/**
* @file
*
* Report the image formats supported by the OpenCL implementation.
*/
#include "clhpp.h"
#include <common/debug_vector.h>
#include <common/debug_string.h>
#include <iostream>
#include <iomanip>
#include <sstream>
static uts::string orderToString(cl_channel_order order)
{
switch (order)
{
#define CASE(c) case c: return #c; break
CASE(CL_R);
CASE(CL_Rx);
CASE(CL_A);
CASE(CL_INTENSITY);
CASE(CL_LUMINANCE);
CASE(CL_RG);
CASE(CL_RGx);
CASE(CL_RA);
CASE(CL_RGB);
CASE(CL_RGBx);
CASE(CL_RGBA);
CASE(CL_ARGB);
CASE(CL_BGRA);
#undef CASE
default:
{
std::ostringstream out;
out << std::hex << order;
return out.str();
}
}
}
static uts::string typeToString(cl_channel_type type)
{
switch (type)
{
#define CASE(c) case c: return #c; break
CASE(CL_SNORM_INT8);
CASE(CL_SNORM_INT16);
CASE(CL_UNORM_INT8);
CASE(CL_UNORM_INT16);
CASE(CL_UNORM_SHORT_565);
CASE(CL_UNORM_SHORT_555);
CASE(CL_UNORM_INT_101010);
CASE(CL_SIGNED_INT8);
CASE(CL_SIGNED_INT16);
CASE(CL_SIGNED_INT32);
CASE(CL_UNSIGNED_INT8);
CASE(CL_UNSIGNED_INT16);
CASE(CL_UNSIGNED_INT32);
CASE(CL_HALF_FLOAT);
CASE(CL_FLOAT);
#undef CASE
default:
{
std::ostringstream out;
out << std::hex << type;
return out.str();
}
}
}
static void dumpFormats(const uts::vector<cl::ImageFormat> &formats)
{
for (const auto &format : formats)
std::cout << orderToString(format.image_channel_order) << " / "
<< typeToString(format.image_channel_data_type) << "\n";
}
int main()
{
uts::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
for (const auto &platform : platforms)
{
uts::vector<cl::Device> devices;
platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
for (const auto &device : devices)
{
std::cout << device.getInfo<CL_DEVICE_NAME>() << ":\n\n";
cl_context_properties properties[] =
{
CL_CONTEXT_PLATFORM,
(cl_context_properties) platform(),
0
};
cl::Context context(device, properties);
uts::vector<cl::ImageFormat> formats;
std::cout << "2D, read-write:\n";
context.getSupportedImageFormats(CL_MEM_READ_WRITE, CL_MEM_OBJECT_IMAGE2D, &formats);
dumpFormats(formats);
std::cout << "\n3D, read-write:\n";
context.getSupportedImageFormats(CL_MEM_READ_WRITE, CL_MEM_OBJECT_IMAGE3D, &formats);
dumpFormats(formats);
std::cout << "\n";
}
}
return 0;
}
| 2,879
|
C++
|
.cpp
| 103
| 20.514563
| 97
| 0.566269
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,154
|
timer.cpp
|
jgain_EcoLearn/UnderSim/clh/timer.cpp
|
/**
* @file
*
* Timing of OpenCL operations.
*/
#include <memory>
#include <utility>
#include <chrono>
#include <common/timer.h>
#include "clhpp.h"
#include "timer.h"
namespace CLH
{
Timer::Timer(const cl::CommandQueue &queue, const stats::TimeInit &t, double *out)
: stats::TimerBase(t, out)
{
if (stats::isTimingEnabled())
queue.enqueueMarker(&startEvent);
}
Timer::Timer(const cl::CommandQueue &queue, const std::shared_ptr<stats::Time> &t, double *out)
: stats::TimerBase(t, out)
{
if (stats::isTimingEnabled())
queue.enqueueMarker(&startEvent);
}
Timer::Timer(Timer &&other) : stats::TimerBase(std::move(other))
{
if (this != &other)
{
startEvent = std::move(other.startEvent);
stopEvent = std::move(other.stopEvent);
other.startEvent = cl::Event();
other.stopEvent = cl::Event();
}
}
void Timer::stop()
{
if (startEvent() && !stopEvent())
{
const cl::CommandQueue &queue = startEvent.getInfo<CL_EVENT_COMMAND_QUEUE>();
queue.enqueueMarker(&stopEvent);
}
}
Timer::~Timer()
{
if (startEvent())
{
stop();
stopEvent.wait();
// Note: we measure the start for both the endpoint markers
cl_ulong start = startEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>();
cl_ulong end = stopEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>();
std::chrono::duration<cl_ulong, std::nano> duration(end - start);
done(duration);
}
}
} // namespace CLH
| 1,524
|
C++
|
.cpp
| 57
| 22.508772
| 95
| 0.651816
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,155
|
clh.cpp
|
jgain_EcoLearn/UnderSim/clh/clh.cpp
|
/**
* @file
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>
#include "clhpp.h"
#include <iostream>
#include <common/debug_vector.h>
#include <common/debug_string.h>
#include <common/debug_unordered_map.h>
#include <sstream>
#include <utility>
#include <stdexcept>
#include <algorithm>
#include <set>
#include <cstdlib>
#include "clh.h"
#include <common/source2cpp.h>
#include <common/stats.h>
namespace po = boost::program_options;
namespace CLH
{
void addOptions(boost::program_options::options_description &desc)
{
desc.add_options()
(Option::device, boost::program_options::value<std::string>(),
"OpenCL device name")
(Option::cpu, "Use only a CPU device")
(Option::gpu, "Use only a GPU device");
}
// How much we want to use a device: higher is better
static int deviceScore(const cl::Device &device)
{
if (!device())
return -1;
else
{
cl_device_type type = device.getInfo<CL_DEVICE_TYPE>();
if (type & CL_DEVICE_TYPE_GPU)
return 1;
else
return 0;
}
}
cl::Device findDevice(
const boost::program_options::variables_map &vm,
const std::function<uts::string(const cl::Device &)> &deviceFilter)
{
cl::Device ans;
const bool cpuOnly = vm.count(Option::cpu);
const bool gpuOnly = vm.count(Option::gpu);
// Parse device name, if one given
bool haveRequired = false;
uts::string requiredName;
int requiredNum = 0;
if (vm.count(Option::device))
{
requiredName = vm[Option::device].as<std::string>();
uts::string::size_type colon = requiredName.rfind(':');
if (colon != uts::string::npos)
{
// User may have specified a device number
try
{
requiredNum = boost::lexical_cast<unsigned int>(requiredName.substr(colon + 1));
requiredName = requiredName.substr(0, colon - 1);
}
catch (boost::bad_lexical_cast &e)
{
// Ignore
}
}
haveRequired = true;
}
uts::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
for (const cl::Platform &platform : platforms)
{
uts::vector<cl::Device> devices;
cl_device_type type = CL_DEVICE_TYPE_ALL;
platform.getDevices(type, &devices);
for (const cl::Device &device : devices)
{
bool match = true;
const uts::string name = device.getInfo<CL_DEVICE_NAME>();
cl_device_type type = device.getInfo<CL_DEVICE_TYPE>();
if (cpuOnly && !(type & CL_DEVICE_TYPE_CPU))
match = false;
if (gpuOnly && !(type & CL_DEVICE_TYPE_GPU))
match = false;
if (haveRequired)
{
if (name != requiredName)
match = false;
else
{
match = requiredNum == 0;
requiredNum--;
}
}
uts::string reason = deviceFilter(device);
if (!reason.empty())
{
// TODO: create a logging system
stats::print("Skipping device ", device.getInfo<CL_DEVICE_NAME>(), ": ", reason, "\n");
match = false;
}
if (match)
{
if (deviceScore(device) > deviceScore(ans))
ans = device;
}
}
}
return ans;
}
static void CL_CALLBACK contextCallback(const char *msg, const void *ptr, ::size_t cb, void *user)
{
(void) ptr;
(void) cb;
(void) user;
std::cerr << msg << "\n";
}
cl::Context makeContext(const cl::Device &device)
{
const cl::Platform &platform = device.getInfo<CL_DEVICE_PLATFORM>();
cl_context_properties props[3] = {CL_CONTEXT_PLATFORM, (cl_context_properties) platform(), 0};
uts::vector<cl::Device> devices(1, device);
return cl::Context(devices, props, contextCallback);
}
cl::Program build(const cl::Context &context, const uts::vector<cl::Device> &devices,
const uts::string &filename, const uts::unordered_map<uts::string, uts::string> &defines,
const uts::string &options)
{
const uts::unordered_map<uts::string, uts::string> &sourceMap = getSourceMap();
if (!sourceMap.count(filename))
throw std::invalid_argument("No such program " + filename);
const uts::string &source = sourceMap.find(filename)->second;
std::ostringstream s;
for (const auto &i : defines)
{
s << "#define " << i.first << " " << i.second << "\n";
}
s << "#line 1 \"" << filename << "\"\n";
const uts::string header = s.str();
cl::Program::Sources sources(2);
sources[0] = std::make_pair(header.data(), header.length());
sources[1] = std::make_pair(source.data(), source.length());
cl::Program program(context, sources);
try
{
program.build(devices, options.c_str());
}
catch (cl::Error &e)
{
for (const cl::Device &device : devices)
{
const uts::string log = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device);
if (log != "" && log != "\n")
{
std::cerr << "Log for device " << device.getInfo<CL_DEVICE_NAME>() << '\n';
std::cerr << log << '\n';
}
}
throw;
}
return program;
}
cl::Program build(const cl::Context &context,
const uts::string &filename,
const uts::unordered_map<uts::string, uts::string> &defines,
const uts::string &options)
{
uts::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();
return build(context, devices, filename, defines, options);
}
/**
* Return an event that is already signaled as @c CL_COMPLETE.
* This is equivalent to the other form but uses the queue to determine the
* context.
*/
void doneEvent(const cl::CommandQueue &queue, cl::Event *event)
{
if (event != NULL)
{
cl::UserEvent signaled(queue.getInfo<CL_QUEUE_CONTEXT>());
signaled.setStatus(CL_COMPLETE);
*event = signaled;
}
}
cl_int enqueueMarkerWithWaitList(const cl::CommandQueue &queue,
const uts::vector<cl::Event> *events,
cl::Event *event)
{
if (events != NULL && events->empty())
events = NULL; // to avoid having to check for both conditions later
if (events == NULL && event == NULL)
return CL_SUCCESS;
else if (event == NULL)
return queue.enqueueWaitForEvents(*events);
else if (!(queue.getInfo<CL_QUEUE_PROPERTIES>() & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE)
|| (events != NULL && events->size() > 1))
{
/* For the events->size() > 1, out-of-order case this is inefficient
* but correct. Alternatives would be to enqueue a dummy task (which
* would have potentially large overhead to allocate a dummy buffer or
* something), or to create a separate thread to wait for completion of
* the events and signal a user event when done (which would force
* scheduling to round trip via multiple CPU threads).
*
* The implementation in cl.hpp (version 1.2.1) leaks any previous
* reference, so we use a temporary event.
*/
cl::Event tmp;
int status = queue.enqueueMarker(&tmp);
if (status == CL_SUCCESS)
*event = tmp;
return status;
}
else if (events == NULL)
{
doneEvent(queue, event);
}
else
{
// Exactly one input event, so just copy it to the output
if (event != NULL)
*event = (*events)[0];
}
return CL_SUCCESS;
}
cl_int enqueueNDRangeKernel(
const cl::CommandQueue &queue,
const cl::Kernel &kernel,
const cl::NDRange &offset,
const cl::NDRange &global,
const cl::NDRange &local,
const uts::vector<cl::Event> *events,
cl::Event *event)
{
for (std::size_t i = 0; i < global.dimensions(); i++)
if (static_cast<const std::size_t *>(global)[i] == 0)
{
return enqueueMarkerWithWaitList(queue, events, event);
}
int ret = queue.enqueueNDRangeKernel(kernel, offset, global, local, events, event);
return ret;
}
static cl::NDRange makeNDRange(cl_uint dimensions, const std::size_t *sizes)
{
switch (dimensions)
{
case 0: return cl::NDRange();
case 1: return cl::NDRange(sizes[0]);
case 2: return cl::NDRange(sizes[0], sizes[1]);
case 3: return cl::NDRange(sizes[0], sizes[1], sizes[2]);
default: std::abort(); // should never be reached
}
return cl::NDRange(); // should never be reached
}
cl_int enqueueNDRangeKernelSplit(
const cl::CommandQueue &queue,
const cl::Kernel &kernel,
const cl::NDRange &offset,
const cl::NDRange &global,
const cl::NDRange &local,
const uts::vector<cl::Event> *events,
cl::Event *event)
{
/* If no size given, pick a default.
* TODO: get performance hint from CL_KERNEL_PREFERRED_KERNEL_WORK_GROUP_SIZE_MULTIPLE?
*/
if (local.dimensions() == 0)
{
switch (global.dimensions())
{
case 1:
return enqueueNDRangeKernelSplit(queue, kernel, offset, global,
cl::NDRange(256), events, event);
case 2:
return enqueueNDRangeKernelSplit(queue, kernel, offset, global,
cl::NDRange(16, 16), events, event);
case 3:
return enqueueNDRangeKernelSplit(queue, kernel, offset, global,
cl::NDRange(8, 8, 8), events, event);
default:
return enqueueNDRangeKernel(queue, kernel, offset, global, local, events, event);
}
}
const std::size_t *origGlobal = static_cast<const std::size_t *>(global);
const std::size_t *origLocal = static_cast<const std::size_t *>(local);
const std::size_t *origOffset = static_cast<const std::size_t *>(offset);
const std::size_t dims = global.dimensions();
std::size_t main[3], extra[3], extraOffset[3];
for (std::size_t i = 0; i < dims; i++)
{
if (origLocal[i] == 0)
throw cl::Error(CL_INVALID_WORK_GROUP_SIZE, "Local work group size is zero");
main[i] = origGlobal[i] / origLocal[i] * origLocal[i];
extra[i] = origGlobal[i] - main[i];
extraOffset[i] = origOffset[i] + main[i];
}
uts::vector<cl::Event> wait;
for (std::size_t mask = 0; mask < (1U << dims); mask++)
{
std::size_t curOffset[3] = {};
std::size_t curGlobal[3] = {};
std::size_t curLocal[3] = {};
bool use = true;
for (std::size_t i = 0; i < dims; i++)
{
if (mask & (1U << i))
{
curGlobal[i] = extra[i];
curOffset[i] = extraOffset[i];
curLocal[i] = extra[i];
}
else
{
curGlobal[i] = main[i];
curOffset[i] = offset[i];
curLocal[i] = origLocal[i];
}
use &= curGlobal[i] > 0;
}
if (use)
{
wait.push_back(cl::Event());
queue.enqueueNDRangeKernel(kernel,
makeNDRange(dims, curOffset),
makeNDRange(dims, curGlobal),
makeNDRange(dims, curLocal),
events, &wait.back());
}
}
return enqueueMarkerWithWaitList(queue, &wait, event);
}
bool imageFormatSupported(
const cl::Context &context,
cl_mem_flags flags,
cl_mem_object_type image_type,
cl::ImageFormat format)
{
uts::vector<cl::ImageFormat> formats;
context.getSupportedImageFormats(flags, image_type, &formats);
for (auto f : formats)
{
if (f.image_channel_order == format.image_channel_order
&& f.image_channel_data_type == format.image_channel_data_type)
return true;
}
return false;
}
} // namespace CLH
| 12,401
|
C++
|
.cpp
| 357
| 26.439776
| 107
| 0.571904
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,156
|
eco.cpp
|
jgain_EcoLearn/UnderSim/sim/eco.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
// eco.cpp: core classes for controlling ecosystems and plant placement
// author: James Gain
// date: 27 February 2016
#include "eco.h"
// #include "interp.h"
#include <stdlib.h>
#include <math.h>
#include <algorithm>
#include <QDir>
/// PlantGrid
void PlantGrid::initSpeciesTable()
{
speciesTable.clear();
}
void PlantGrid::delGrid()
{
int i, j;
// clear out elements of the vector hierarchy
for(i = 0; i < (int) pgrid.size(); i++)
for(j = 0; j < (int) pgrid[i].pop.size(); j++)
pgrid[i].pop[j].clear();
for(i = 0; i < (int) pgrid.size(); i++)
pgrid[i].pop.clear();
pgrid.clear();
}
void PlantGrid::initGrid()
{
int i, j, s;
delGrid();
// setup empty elements of the vector hierarchy according to the grid dimensions
for(i = 0; i < gx; i++)
for(j = 0; j < gy; j++)
{
PlantPopulation ppop;
for(s = 0; s < maxSpecies; s++)
{
std::vector<Plant> plnts;
ppop.pop.push_back(plnts);
}
pgrid.push_back(ppop);
}
}
bool PlantGrid::isEmpty()
{
bool empty = true;
int i, j, s, pos = 0;
// setup empty elements of the vector hierarchy according to the grid dimensions
for(i = 0; i < gx; i++)
for(j = 0; j < gy; j++)
{
for(s = 0; s < maxSpecies; s++)
{
if(!pgrid[pos].pop[s].empty())
empty = false;
}
pos++;
}
return empty;
}
void PlantGrid::cellLocate(Terrain * ter, int mx, int my, int &cx, int &cy)
{
int tx, ty;
ter->getGridDim(tx, ty);
// find grid bin for plant
cx = (int) (((float) mx / (float) tx) * (float) gx);
cy = (int) (((float) my / (float) ty) * (float) gy);
if(cx >= gx)
cx = gx-1;
if(cy >= gy)
cy = gy-1;
}
void PlantGrid::clearCell(int x, int y)
{
int f = flatten(x, y);
for(int s = 0; s < (int) pgrid[f].pop.size(); s++)
pgrid[f].pop[s].clear();
}
void PlantGrid::placePlant(Terrain * ter, int species, Plant plant)
{
int x, y, cx, cy;
// find plant location on map
ter->toGrid(plant.pos, x, y);
cellLocate(ter, x, y, cx, cy);
// cerr << "loc in " << cx << ", " << cy << " species " << species << endl;
// add plant to relevant population
pgrid[flatten(cx, cy)].pop[species].push_back(plant);
}
void PlantGrid::placePlantExactly(Terrain * ter, int species, Plant plant, int x, int y)
{
pgrid[flatten(x, y)].pop[species].push_back(plant);
}
void PlantGrid::clearRegion(Terrain * ter, Region region)
{
int x, y, sx, sy, ex, ey;
getRegionIndices(ter, region, sx, sy, ex, ey);
for(x = sx; x <= ex; x++)
for(y = sy; y <= ey; y++)
clearCell(x, y); // clear a specific cell in the grid
}
void PlantGrid::pickPlants(Terrain * ter, TypeMap * clusters, int niche, PlantGrid & outgrid)
{
int x, y, s, p, mx, my, sx, sy, ex, ey, f;
Plant plnt;
Region region = clusters->getRegion();
// map region to cells in the grid
getRegionIndices(ter, region, sx, sy, ex, ey);
for(x = sx; x <= ex; x++)
for(y = sy; y <= ey; y++)
{
f = flatten(x, y);
for(s = 0; s < (int) pgrid[f].pop.size(); s++)
for(p = 0; p < (int) pgrid[f].pop[s].size(); p++)
{
plnt = pgrid[f].pop[s][p];
ter->toGrid(plnt.pos, mx, my); // map plant terrain location to cluster map
if((* clusters->getMap())[my][mx] == niche) // niche value on terrain matches the current plant distribution
outgrid.placePlantExactly(ter, s, plnt, x, y);
}
}
}
void PlantGrid::pickAllPlants(Terrain * ter, float offx, float offy, float scf, PlantGrid & outgrid)
{
int x, y, s, p, f;
Plant plnt;
for(x = 0; x < gx; x++)
for(y = 0; y < gy; y++)
{
f = flatten(x, y);
for(s = 0; s < (int) pgrid[f].pop.size(); s++)
for(p = 0; p < (int) pgrid[f].pop[s].size(); p++)
{
plnt = pgrid[f].pop[s][p];
plnt.pos.x *= scf; plnt.pos.z *= scf;
plnt.height *= scf; plnt.canopy *= scf;
plnt.pos.x += offy; plnt.pos.z += offx; // allows more natural layout
outgrid.placePlant(ter, s, plnt);
}
}
}
void PlantGrid::vectoriseByPFT(int pft, std::vector<Plant> &pftPlnts)
{
int x, y, p, s, f;
Plant plnt;
s = (int) pft;
pftPlnts.clear();
for(x = 0; x < gx; x++)
for(y = 0; y < gy; y++)
{
f = flatten(x, y);
if(s < 0 || s > (int) pgrid[f].pop.size())
cerr << "PlantGrid::vectoriseBySpecies: mismatch between requested species and available species" << endl;
for(p = 0; p < (int) pgrid[f].pop[s].size(); p++)
{
plnt = pgrid[f].pop[s][p];
pftPlnts.push_back(plnt);
}
}
}
void PlantGrid::reportNumPlants()
{
int i, j, s, plntcnt, speccnt;
cerr << "grid dimensions = " << gx << " X " << gy << endl;
for(i = 0; i < gx; i++)
for(j = 0; j < gy; j++)
{
plntcnt = 0;
for(s = 0; s < maxSpecies; s++)
{
speccnt = (int) pgrid[flatten(i,j)].pop[s].size();
plntcnt += speccnt;
}
cerr << "count " << i << ", " << j << " = " << plntcnt << endl;
}
}
void PlantGrid::setPopulation(int x, int y, PlantPopulation & pop)
{
pgrid[flatten(x, y)] = pop;
}
PlantPopulation * PlantGrid::getPopulation(int x, int y)
{
return & pgrid[flatten(x, y)];
}
void PlantGrid::getRegionIndices(Terrain * ter, Region region, int &sx, int &sy, int &ex, int &ey)
{
cellLocate(ter, region.x0, region.y0, sx, sy);
cellLocate(ter, region.x1, region.y1, ex, ey);
// cerr << "map = " << region.x0 << ", " << region.y0 << " -> " << region.x1 << ", " << region.y1 << endl;
// cerr << "grid = " << sx << ", " << sy << " -> " << ex << ", " << ey << endl;
}
bool PlantGrid::readPDB(string filename, Biome * biome, Terrain * ter, float &maxtree)
{
ifstream infile;
float rndoff;
int currSpecies, speciesCount;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> speciesCount;
for(int i = 0; i < speciesCount; i++)
{
int numPlants;
float canopyRatio, hghtMin, hghtMax;
infile >> currSpecies;
infile >> hghtMin >> hghtMax >> canopyRatio;
// cerr << "currSpecies = " << currSpecies << " hmin = " << hghtMin << " hmax = " << hghtMax << " cRatio = " << canopyRatio << endl;
if(hghtMax > maxtree)
maxtree = hghtMax;
infile >> numPlants;
for(int j = 0; j < numPlants; j++)
{
Plant p;
float x, y, z, h, r;
// terrain position and plant height
infile >> x >> y >> z >> h >> r;
// convert units to meters and drape onto terrain
p.height = h;
// supplied canopy ratio is actually radius to height (not diameter to height)
p.canopy = r * 2.0f;
rndoff = (float)(rand() % 100) / 100.0f * 0.6f;
p.col = glm::vec4(-0.3f+rndoff, -0.3f+rndoff, -0.3f+rndoff, 1.0f); // randomly vary lightness of plant
if(ter->drapePnt(vpPoint(x, z, y), p.pos)) // project plant onto the terrain
placePlant(ter, currSpecies, p);
}
}
infile.close();
}
else
{
cerr << "Error Mesh::readPDB: unable to open " << filename << endl;
return false;
}
return true;
}
void PlantGrid::inscribeAlpha(Terrain * ter, MapFloat * alpha, float aval, vpPoint p, float rcanopy)
{
int gx, gy, tx, ty, gr;
// convert to grid coordinates
ter->toGrid(p, gx, gy);
ter->getGridDim(tx, ty);
gr = (int) (ter->toGrid(rcanopy/2.0f) + 0.5f);
// bounding box around circle
int sx = max(gx-gr, 0);
int ex = min(gx+gr, tx-1);
int sy = max(gy-gr, 0);
int ey = min(gy+gr, ty-1);
// iterate over square on terrain containing the circle
for(int x = sx; x <= ex; x++)
for(int y = sy; y <= ey; y++)
{
float delx = (float) x-gx;
float dely = (float) y-gy;
float distsq = delx*delx + dely*dely;
if (distsq <= (float) (gr*gr)) // inside the circle
{
if(aval > alpha->get(x, y)) // max of occlusion written
alpha->set(x, y, aval);
}
}
}
void PlantGrid::sunSeeding(Terrain * ter, Biome * biome, MapFloat * alpha)
{
int x, y, s, p, f;
Plant plnt;
for(x = 0; x < gx; x++)
for(y = 0; y < gy; y++)
{
f = flatten(x, y);
for(s = 0; s < (int) pgrid[f].pop.size(); s++)
for(p = 0; p < (int) pgrid[f].pop[s].size(); p++)
{
plnt = pgrid[f].pop[s][p];
inscribeAlpha(ter, alpha, biome->getAlpha(s), plnt.pos, plnt.canopy);
}
}
}
bool PlantGrid::writePDB(string filename, Biome * biome)
{
ofstream outfile;
std::vector<int> activeSpecies;
int writtenPlants = 0;
cerr << "write PDB " << filename << endl;
outfile.open((char *) filename.c_str(), ios_base::out | ios_base::trunc);
if(outfile.is_open())
{
// count number of non-zero element species
for(int s = 0; s < biome->numPFTypes(); s++)
{
int specNum;
bool found = false;
// gather plants belonging to species and derive statistics
for(int i = 0; i < gx; i++)
for(int j = 0; j < gy; j++)
if((int) pgrid[flatten(i,j)].pop[s].size() > 0)
found = true;
if(found)
activeSpecies.push_back(s);
}
outfile << (int) activeSpecies.size() << endl;
for(int k = 0; k < (int) activeSpecies.size(); k++)
{
int numPlants, s;
float canopyRatio, hghtMin, hghtMax;
std::vector<Plant> tpop; tpop.clear();
s = activeSpecies[k];
outfile << s << " ";
canopyRatio = 0.0f; hghtMax = 0.0f; hghtMin = 200.0f;
// gather plants belonging to species and derive statistics
for(int i = 0; i < gx; i++)
for(int j = 0; j < gy; j++)
{
for(int p = 0; p < (int) pgrid[flatten(i,j)].pop[s].size(); p++)
{
Plant plnt = pgrid[flatten(i,j)].pop[s][p];
if(plnt.height < hghtMin)
hghtMin = plnt.height;
if(plnt.height > hghtMax)
hghtMax = plnt.height;
canopyRatio += (plnt.canopy / plnt.height) * 0.5f ;
tpop.push_back(plnt);
}
}
numPlants = (int) tpop.size();
canopyRatio /= (float) numPlants;
outfile << hghtMin << " " << hghtMax << " " << canopyRatio; // << " ";
outfile << endl; // XXX: if errors occur in PDB file, remove this line, and uncomment space above
outfile << numPlants << endl;
for(int j = 0; j < numPlants; j++)
{
Plant plnt = tpop[j];
// terrain position and plant height
float x = plnt.pos.x;
float y = plnt.pos.z;
float z = plnt.pos.y;
float h = plnt.height;
float r = plnt.canopy/2.0f;
outfile << x << " " << y << " " << z << " " << h << " " << r << endl;
writtenPlants++;
}
}
outfile.close();
}
else
{
cerr << "Error Mesh::writePDB: unable to open " << filename << endl;
return false;
}
cerr << "num written plants = " << writtenPlants << endl;
return true;
}
/// PlantShape
void ShapeGrid::genSpherePlant(float trunkheight, float trunkradius, Shape &shape)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkheight;
// trunk - cylinder
idt = glm::mat4(1.0f);
tfm = glm::rotate(idt, glm::radians(-90.0f), rotx);
// extra 0.1 to trunk is to ensure that trunk joins tree properly
shape.genCappedCylinder(trunkradius, trunkradius, trunkheight+0.1f, 3, 1, tfm, false);
// canopy - sphere
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, trunkheight+canopyheight/2.0f, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::scale(tfm, glm::vec3(1.0, canopyheight, 1.0f)); // make sure tree fills 1.0f on a side bounding box
tfm = glm::rotate(tfm, glm::radians(-90.0f), rotx);
#ifdef HIGHRES
shape.genSphere(0.5f, 20, 20, tfm);
#endif
#ifdef LOWRES
shape.genSphere(0.5f, 6, 6, tfm);
#endif
}
void ShapeGrid::genBoxPlant(float trunkheight, float trunkradius, float taper, float scale, Shape &shape)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkheight;
// trunk - cylinder
idt = glm::mat4(1.0f);
tfm = glm::rotate(idt, glm::radians(-90.0f), rotx);
// extra 0.1 to trunk is to ensure that trunk joins tree properly
shape.genCappedCylinder(trunkradius, trunkradius, trunkheight+0.1f, 3, 1, tfm, false);
// canopy - tapered box
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, trunkheight, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(-90.0f), rotx);
shape.genPyramid(1.0f*scale, taper*scale, canopyheight*scale, tfm);
}
void ShapeGrid::genConePlant(float trunkheight, float trunkradius, Shape &shape)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkheight;
// trunk - cylinder
idt = glm::mat4(1.0f);
tfm = glm::rotate(idt, glm::radians(-90.0f), rotx);
// extra 0.1 to trunk is to ensure that trunk joins tree properly
shape.genCappedCylinder(trunkradius, trunkradius, trunkheight+0.1f, 3, 1, tfm, false);
// canopy - cone
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, trunkheight, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(-90.0f), rotx);
#ifdef HIGHRES
shape.genCappedCone(0.5f, canopyheight, 20, 1, tfm, false);
#endif
#ifdef LOWRES
shape.genCappedCone(0.5f, canopyheight, 6, 1, tfm, false);
#endif
}
void ShapeGrid::genInvConePlant(float trunkheight, float trunkradius, Shape &shape)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkheight;
// trunk - cylinder
idt = glm::mat4(1.0f);
tfm = glm::rotate(idt, glm::radians(-90.0f), rotx);
// extra 0.1 to trunk is to ensure that trunk joins tree properly
shape.genCappedCylinder(trunkradius, trunkradius, trunkheight+0.1f, 3, 1, tfm, false);
// canopy - cone
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, 1.0f, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(-270.0f), rotx);
//tfm = glm::translate(tfm, glm::vec3(0.0f, 0.0f, -canopyheight));
#ifdef HIGHRES
shape.genCappedCone(0.5f, canopyheight, 20, 1, tfm, false);
#endif
#ifdef LOWRES
shape.genCappedCone(0.5f, canopyheight, 6, 1, tfm, false);
#endif
}
void ShapeGrid::genUmbrellaPlant(float trunkheight, float trunkradius, Shape &shape)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkheight;
// trunk - cylinder
idt = glm::mat4(1.0f);
tfm = glm::rotate(idt, glm::radians(-90.0f), rotx);
// extra 0.1 to trunk is to ensure that trunk joins tree properly
shape.genCappedCylinder(trunkradius, trunkradius, trunkheight+0.1f, 3, 1, tfm, false);
// canopy - cone
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, 1.0f, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(90.0f), rotx);
#ifdef HIGHRES
shape.genCappedCone(0.5f, canopyheight, 20, 1, tfm, false);
#endif
#ifdef LOWRES
shape.genCappedCone(0.5f, canopyheight, 6, 1, tfm, false);
#endif
}
void ShapeGrid::delGrid()
{
int i, j;
// clear out elements of the vector hierarchy
for(i = 0; i < (int) shapes.size(); i++)
for(j = 0; j < (int) shapes[i].size(); j++)
shapes[i][j].clear();
for(i = 0; i < (int) shapes.size(); i++)
shapes[i].clear();
shapes.clear();
}
void ShapeGrid::initGrid()
{
int i, j, s;
// setup empty elements of the vector hierarchy according to the grid dimensions
for(i = 0; i < gx; i++)
for(j = 0; j < gy; j++)
{
std::vector<Shape> shapevec;
for(s = 0; s < maxSpecies; s++)
{
Shape shape;
shapevec.push_back(shape);
}
shapes.push_back(shapevec);
}
genPlants();
}
void ShapeGrid::genPlants()
{
float trunkheight, trunkradius;
int s;
for(s = 0; s < biome->numPFTypes(); s++)
{
Shape currshape;
PFType * pft = biome->getPFType(s);
currshape.setColour(pft->basecol);
trunkheight = pft->draw_hght; trunkradius = pft->draw_radius;
//genSpherePlant(trunkheight, trunkradius, currshape); // XXX: just for debugging. Remove later and uncomment below switch statement
switch(pft->shapetype)
{
case TreeShapeType::SPHR:
genSpherePlant(trunkheight, trunkradius, currshape);
break;
case TreeShapeType::BOX:
genBoxPlant(trunkheight, trunkradius, pft->draw_box1, pft->draw_box2, currshape);
break;
case TreeShapeType::CONE:
genConePlant(trunkheight, trunkradius, currshape);
break;
case TreeShapeType::INVCONE:
genInvConePlant(trunkheight, trunkradius, currshape);
break;
default:
break;
}
shapes[0][s] = currshape;
}
}
void ShapeGrid::bindPlantsSimplified(Terrain *ter, PlantGrid *esys, std::vector<bool> * plantvis)
{
int x, y, s, p, sx, sy, ex, ey, f;
PlantPopulation * plnts;
int bndplants = 0, culledplants = 0;
int gwidth, gheight;
ter->getGridDim(gwidth, gheight);
Region wholeRegion = Region(0, 0, gwidth - 1, gheight - 1);
esys->getRegionIndices(ter, wholeRegion, sx, sy, ex, ey);
std::vector<std::vector<glm::mat4> > xforms; // transformation to be applied to each instance
std::vector<std::vector<glm::vec4> > colvars; // colour variation to be applied to each instance
for(x = sx; x <= ex; x++)
for(y = sy; y <= ey; y++)
{
plnts = esys->getPopulation(x, y);
for(s = 0; s < (int) plnts->pop.size(); s++) // iterate over plant types
{
std::vector<glm::mat4> xform; // transformation to be applied to each instance
std::vector<glm::vec4> colvar; // colour variation to be applied to each instance
if((* plantvis)[s])
{
for(p = 0; p < (int) plnts->pop[s].size(); p++) // iterate over plant specimens
{
if(plnts->pop[s][p].height > 0.01f) // only display reasonably sized plants
{
// setup transformation for individual plant, including scaling and translation
glm::mat4 idt, tfm;
glm::vec3 trs, sc, rotate_axis = glm::vec3(0.0f, 1.0f, 0.0f);
vpPoint loc = plnts->pop[s][p].pos;
// GLfloat rotate_rad;
/*
if (plnts->pop[s+a][p].iscanopy) // we use a different generator depending on whether we have a canopy or undergrowth plant - keeps rotations the same whether we render undergrowth plants or not
{
rotate_rad = rand_unif(generator_canopy) * glm::pi<GLfloat>() * 2.0f;
}
else
{
rotate_rad = rand_unif(generator_under) * glm::pi<GLfloat>() * 2.0f;
}*/
idt = glm::mat4(1.0f);
trs = glm::vec3(loc.x, loc.y, loc.z);
tfm = glm::translate(idt, trs);
sc = glm::vec3(plnts->pop[s][p].canopy, plnts->pop[s][p].height, plnts->pop[s][p].canopy); // XXX: use this for actual tree models
tfm = glm::scale(tfm, sc);
// tfm = glm::rotate(tfm, rotate_rad, rotate_axis);
xform.push_back(tfm);
colvar.push_back(plnts->pop[s][p].col); // colour variation
bndplants++;
}
else
{
culledplants++;
}
}
}
if (xforms.size() < s + 1)
{
xforms.resize(s + 1);
}
if (colvars.size() < s + 1)
{
colvars.resize(s + 1);
}
xforms[s].insert(xforms[s].end(), xform.begin(), xform.end());
colvars[s].insert(colvars[s].end(), colvar.begin(), colvar.end());
f = flatten(x, y);
shapes[f][s].removeAllInstances();
}
}
for (int i = 0; i < xforms.size(); i++)
{
shapes[0][i].removeAllInstances();
shapes[0][i].bindInstances(nullptr, &xforms[i], &colvars[i]);
}
}
void ShapeGrid::bindPlants(View * view, Terrain * ter, std::vector<bool> * plantvis, PlantGrid * esys, Region region)
{
int x, y, s, p, sx, sy, ex, ey, f;
PlantPopulation * plnts;
int bndplants = 0, culledplants = 0;
int gwidth, gheight;
ter->getGridDim(gwidth, gheight);
Region wholeRegion = Region(0, 0, gwidth - 1, gheight - 1);
esys->getRegionIndices(ter, wholeRegion, sx, sy, ex, ey);
std::vector<std::vector<glm::mat4> > xforms; // transformation to be applied to each instance
std::vector<std::vector<glm::vec4> > colvars; // colour variation to be applied to each instance
for(x = sx; x <= ex; x++)
for(y = sy; y <= ey; y++)
{
plnts = esys->getPopulation(x, y);
for(s = 0; s < (int) plnts->pop.size(); s+=3) // iterate over plant types
{
std::vector<glm::mat4> xform; // transformation to be applied to each instance
std::vector<glm::vec4> colvar; // colour variation to be applied to each instance
for(int a = 0; a < 3; a++)
{
for(p = 0; p < (int) plnts->pop[s+a].size(); p++) // iterate over plant specimens
{
if(plnts->pop[s+a][p].height > 0.01f) // only display reasonably sized plants
{
// setup transformation for individual plant, including scaling and translation
glm::mat4 idt, tfm;
glm::vec3 trs, sc, rotate_axis = glm::vec3(0.0f, 1.0f, 0.0f);
vpPoint loc = plnts->pop[s+a][p].pos;
// GLfloat rotate_rad;
/*
if (plnts->pop[s+a][p].iscanopy) // we use a different generator depending on whether we have a canopy or undergrowth plant - keeps rotations the same whether we render undergrowth plants or not
{
rotate_rad = rand_unif(generator_canopy) * glm::pi<GLfloat>() * 2.0f;
}
else
{
rotate_rad = rand_unif(generator_under) * glm::pi<GLfloat>() * 2.0f;
}*/
idt = glm::mat4(1.0f);
trs = glm::vec3(loc.x, loc.y, loc.z);
tfm = glm::translate(idt, trs);
sc = glm::vec3(plnts->pop[s+a][p].height, plnts->pop[s+a][p].height, plnts->pop[s+a][p].height); // XXX: use this for actual tree models
tfm = glm::scale(tfm, sc);
xform.push_back(tfm);
colvar.push_back(plnts->pop[s+a][p].col); // colour variation
bndplants++;
}
else
{
culledplants++;
}
}
}
if (xforms.size() < s / 3 + 1)
{
xforms.resize(s / 3 + 1);
}
if (colvars.size() < s / 3 + 1)
{
colvars.resize(s / 3 + 1);
}
xforms[s / 3].insert(xforms[s / 3].end(), xform.begin(), xform.end());
colvars[s / 3].insert(colvars[s / 3].end(), colvar.begin(), colvar.end());
f = flatten(x, y);
shapes[f][s / 3].removeAllInstances();
}
}
for (int i = 0; i < xforms.size(); i++)
{
cerr << i << endl;
shapes[0][i].removeAllInstances();
shapes[0][i].bindInstances(nullptr, &xforms[i], &colvars[i]);
}
cerr << "num bound plants = " << bndplants << endl;
cerr << "num culled plants = " << culledplants << endl;
}
void ShapeGrid::drawPlants(std::vector<ShapeDrawData> &drawParams)
{
int x, y, s, f;
ShapeDrawData sdd;
for(s = 0; s < (int) shapes[0].size(); s++) // iterate over plant types
{
sdd = shapes[0][s].getDrawParameters();
sdd.current = false;
drawParams.push_back(sdd);
}
}
/// EcoSystem
EcoSystem::EcoSystem()
{
biome = new Biome();
init();
}
EcoSystem::EcoSystem(Biome * ecobiome)
{
biome = ecobiome;
init();
}
EcoSystem::~EcoSystem()
{
esys.delGrid();
eshapes.delGrid();
for(int i = 0; i < (int) niches.size(); i++)
{
niches[i].delGrid();
}
niches.clear();
}
void EcoSystem::init()
{
esys = PlantGrid(pgdim, pgdim);
eshapes = ShapeGrid(pgdim, pgdim, biome);
// cmap = ConditionsMap();
for(int i = 0; i < maxNiches; i++)
{
PlantGrid pgrid(pgdim, pgdim);
niches.push_back(pgrid);
}
clear();
dirtyPlants = true;
drawPlants = false;
maxtreehght = 0.0f;
srand (time(NULL));
}
void EcoSystem::clear()
{
esys = PlantGrid(pgdim, pgdim);
for(int i = 0; i < (int) niches.size(); i++)
{
niches[i] = PlantGrid(pgdim, pgdim);
}
}
bool EcoSystem::loadNichePDB(string filename, Terrain * ter, int niche)
{
bool success;
// std::cout << "Number of niches: " << niches.size() << std::endl;
success = niches[niche].readPDB(filename, biome, ter, maxtreehght);
if(success)
{
dirtyPlants = true; drawPlants = true;
cerr << "plants loaded for Niche " << niche << endl;
}
return success;
}
bool EcoSystem::saveNichePDB(string filename, int niche)
{
return niches[niche].writePDB(filename, biome);
}
void EcoSystem::pickPlants(Terrain * ter, TypeMap * clusters)
{
Region reg = clusters->getRegion();
esys.clearRegion(ter, reg);
for(int n = 0; n < (int) niches.size(); n++)
{
niches[n].pickPlants(ter, clusters, n, esys);
}
dirtyPlants = true;
}
void EcoSystem::pickAllPlants(Terrain * ter, bool canopyOn, bool underStoreyOn)
{
esys.clear();
for(int n = 0; n < (int) niches.size(); n++)
{
if(n == 0 && canopyOn)
niches[n].pickAllPlants(ter, 0.0f, 0.0f, 1.0f, esys);
if(n > 0 && underStoreyOn)
niches[n].pickAllPlants(ter, 0.0f, 0.0f, 1.0f, esys);
}
dirtyPlants = true;
}
void EcoSystem::sunSeeding(Terrain * ter, Biome * biome, MapFloat * alpha)
{
for(int n = 0; n < (int) niches.size(); n++)
{
getNiche(n)->sunSeeding(ter, biome, alpha);
}
}
void EcoSystem::bindPlantsSimplified(Terrain *ter, std::vector<ShapeDrawData> &drawParams, std::vector<bool> * plantvis)
{
if(dirtyPlants) // plant positions have been updated since the last bindPlants
{
drawPlants = true;
dirtyPlants = false;
eshapes.bindPlantsSimplified(ter, &esys, plantvis);
}
if(drawPlants)
eshapes.drawPlants(drawParams);
}
void EcoSystem::bindPlants(View * view, Terrain * ter, TypeMap * clusters, std::vector<bool> * plantvis, std::vector<ShapeDrawData> &drawParams)
{
cerr << "ecosys bind" << endl;
if(dirtyPlants) // plant positions have been updated since the last bindPlants
{
// t.start();
drawPlants = true;
dirtyPlants = false;
eshapes.bindPlants(view, ter, plantvis, &esys, clusters->getRegion());
}
if(drawPlants)
eshapes.drawPlants(drawParams);
cerr << "end ecosys bind" << endl;
}
| 30,947
|
C++
|
.cpp
| 823
| 28.345079
| 222
| 0.530546
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,160
|
main.cpp
|
jgain_EcoLearn/UnderSim/sim/main.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "glheaders.h"
#include <QApplication>
#include <QGLFormat>
#include <QCoreApplication>
#include <QDesktopWidget>
#include <string>
#include <stdexcept>
#include <utility>
#include <memory>
#include <QTimer>
#include "window.h"
int main(int argc, char *argv[])
{
int run_id, nyears;
SunWindow * sunwindow;
if (argc > 5 || argc < 3)
{
std::cerr << "Usage: sim -sim <data directory> <run id> <number of years>" << std::endl;
std::cerr << "or sim -view <data directory>" << std::endl;
std::cerr << "or sim -sun <data directory> [--ignore-canopy]" << std::endl;
return 1;
}
try
{
QApplication app(argc, argv);
std::string usagestr = argv[1];
std::string datadir = argv[2];
while (datadir.back() == '/')
datadir.pop_back();
Window * window = new Window(datadir);
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedKingdom));
window->resize(window->sizeHint());
window->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored);
window->getView().setForcedFocus(window->getTerrain().getFocus());
if(usagestr == "-sim" || usagestr == "-sun")
{
if(argc == 5)
{
run_id = std::stoi(argv[3]);
nyears = std::stoi(argv[4]);
}
// sunwindow
sunwindow = new SunWindow();
sunwindow->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored);
sunwindow->resize(window->sizeHint());
sunwindow->setOrthoView(window->getGLWidget());
sunwindow->getView().setForcedFocus(window->getTerrain().getFocus());
}
int desktopArea = QApplication::desktop()->width() *
QApplication::desktop()->height();
int widgetArea = window->width() * window->height();
if (((float)widgetArea / (float)desktopArea) < 0.75f)
window->show();
else
window->showMaximized();
if(usagestr == "-sim") // run simulation
{
window->setSunWindow(sunwindow);
window->run_undersim_foolproof(run_id, nyears);
window->close();
QCoreApplication::exit();
}
else
{
if(usagestr == "-sun") // run abiotic component of simulation. This actually includes moisture if not already computed.
{
bool include_canopy = true;
if (argc >= 4) // if there is another argument, we check if it's the ignore-canopy switch and quit with informative message if switch is wrong
{
std::string canopyignore_string = argv[3];
if (canopyignore_string == "--ignore-canopy")
{
include_canopy = false;
}
else
{
std::cout << "Unknown switch " << canopyignore_string << " for option -sun. Known switches are: --ignore-canopy" << std::endl;
QCoreApplication::exit(1);
}
}
window->setSunWindow(sunwindow);
window->run_abiotics_only(include_canopy);
window->close();
QCoreApplication::exit();
}
else
if(usagestr == "-view") // viewing only
{
window->run_undersim_viewer();
int status = app.exec();
return status;
}
}
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
}
| 6,701
|
C++
|
.cpp
| 158
| 34.85443
| 158
| 0.59387
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,161
|
sim.cpp
|
jgain_EcoLearn/UnderSim/sim/sim.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <algorithm>
#include <chrono>
#include <utility>
#include "sim.h"
#include <sys/stat.h>
#include <QLabel>
// #define TESTING
////
// MapSimCell
///
void MapSimCell::delMap()
{
for(int c = 0; c < gx*gy; c++) // empty cells are always sorted
{
smap[c].canopies.clear();
smap[c].roots.clear();
smap[c].seedbank.clear();
}
smap.clear();
}
void MapSimCell::initMap()
{
smap.clear();
smap.resize(gx*gy);
for(int c = 0; c < gx*gy; c++) // empty cells are always sorted
{
smap[c].canopysorted = true;
smap[c].rootsorted = true;
smap[c].growing = false;
smap[c].available = true;
smap[c].seed_chance = 0.0f;
}
resetSeeding();
}
void MapSimCell::resetSeeding()
{
for(int c = 0; c < gx*gy; c++) // empty cells are always sorted
{
smap[c].leftoversun = 0.0f;
smap[c].leftoverwet = 0.0f;
}
}
void MapSimCell::init_countmaps(const std::set<int> &species, int gw, int gh, int tw, int th)
{
closest_distances.clear();
species_counts.clear();
for (auto specidx : species)
{
closest_distances.emplace(std::make_pair<int, ValueGridMap<float> >(std::move(specidx), ValueGridMap<float>(gw, gh, tw, th)));
closest_distances.at(specidx).fill(0.0f);
species_counts.emplace(std::make_pair<int, ValueGridMap<int> >(std::move(specidx), ValueGridMap<int>(gw, gh, tw, th)));
species_counts.at(specidx).fill(0);
}
}
void MapSimCell::toTerGrid(int mx, int my, int &tx, int &ty, Terrain * ter)
{
int dx, dy;
tx = mx / step;
ty = my / step;
// upper bounds check
ter->getGridDim(dx, dy);
tx = std::min(tx, dx-1);
ty = std::min(ty, dy-1);
}
bool MapSimCell::notInSeedbank(int sbidx, int x, int y)
{
bool found = false;
int i = 0;
while(!found && i < (int) get(x,y)->seedbank.size())
{
found = (get(x,y)->seedbank[i] == sbidx);
i++;
}
return !found;
}
// side effects:
// - add seed index sbidx to each cell in the seedbank, in rcanopy radius around px, py
void MapSimCell::inscribeSeeding(int sbidx, int spec_idx, float px, float py, float rcanopy, Terrain * ter)
{
float grx, gry, grcanopy, rmax, distsq, grcanopysq;
// convert to sim grid coordinates
grx = convert(px);
gry = convert(py);
grcanopy = convert(rcanopy);
grcanopysq = grcanopy * grcanopy;
rmax = grcanopy * radius_mult;
float rter = ter->toWorld(rcanopy);
float real_rcanopysq = rter * rter;
// bounding box around circle
for(int x = (int) (grx-rmax); x <= (int) (grx+rmax); x++)
for(int y = (int) (gry-rmax); y <= (int) (gry+rmax); y++)
{
if(ingrid(x,y))
{
float delx = convert_to_tergrid((float) x-grx);
float dely = convert_to_tergrid((float) y-gry);
vpPoint temp = ter->toWorld(delx, dely, 0.0f);
delx = temp.x;
dely = temp.z;
distsq = delx*delx + dely*dely;
if (distsq <= real_rcanopysq)
{
// not already in seedbank and under chm
if(notInSeedbank(sbidx, x, y) && get(x, y)->growing)
{
// add with a probabliity that depends on distance
float d = distsq / real_rcanopysq;
float p = 1.0f;
if(d > 0.6f)
p -= (d - 0.6f) / 0.4f;
if((float) dice->generate() / 1000.0f < p)
get(x,y)->seedbank.push_back(sbidx);
}
float terdist = convert_to_tergrid(sqrt(distsq));
int tx = convert_to_tergrid(x) + 1e-5;
int ty = convert_to_tergrid(y) + 1e-5;
if (terdist < closest_distances.at(spec_idx).get(tx, ty))
{
closest_distances.at(spec_idx).set(tx, ty, terdist);
}
int curr_count = species_counts.at(spec_idx).get(tx, ty);
species_counts.at(spec_idx).set(tx, ty, curr_count + 1);
}
}
}
}
// side effects:
// - set 'growing' and 'available' attributes of SimCell objects
// - establish what plants' canopies and roots intersect each SimCell
void MapSimCell::inscribe(std::list<SimPlant *>::iterator plntidx, float px, float py, float rcanopy, float rroot, bool isStatic, Terrain *ter, Simulation * sim)
{
float grx, gry, grcanopy, grroot, rmax, distsq, grcanopysq, grrootsq;
// assumes that plant index is not already inscribed in the simulation grid
// convert to sim grid coordinates
grx = convert(px);
gry = convert(py);
// also convert from diameter to radius
grcanopy = convert(rcanopy/2.0f);
grroot = convert(rroot/2.0f);
grcanopysq = grcanopy * grcanopy;
grrootsq = grroot * grroot;
rmax = fmax(grroot * radius_mult, grcanopy * radius_mult);
vpPoint pt = ter->toWorld(rcanopy/2.0f, rcanopy/2.0f, rcanopy/2.0f);
float real_rcanopysq = pt.x * pt.x;
pt = ter->toWorld(rroot/2.0f, rroot/2.0f, rroot/2.0f);
float real_rrootsq = pt.x * pt.x;
float tercellsize = ter->getCellExtent();
float distsqmax = fmax(real_rcanopysq, real_rrootsq) * radius_mult * radius_mult;
float distmax = sqrt(distsqmax);
float distsqmax_error = 2.0f * (distmax + tercellsize) * (distmax + tercellsize);
get(grx, gry)->available = false;
get(grx, gry)->growing = false;
for(int x = (int) (grx-rmax); x <= (int) (grx+rmax); x++)
for(int y = (int) (gry-rmax); y <= (int) (gry+rmax); y++)
{
PlntInCell pic;
if(ingrid(x,y)) // cell is in grid
{
pic.hght = 0.0f; // height will be instantiated later on demand
pic.plnt = (* plntidx);
float delx = convert_to_tergrid((float) x-grx);
float dely = convert_to_tergrid((float) y-gry);
vpPoint temp = ter->toWorld(delx, dely, 0.0f);
delx = temp.x;
dely = temp.z;
distsq = delx*delx + dely*dely;
assert(distsq < distsqmax_error);
if (distsq > distsqmax) distsq = distsqmax;
if (!get(x, y)->available)
assert(!get(x, y)->growing);
if (!get(x, y)->available) //if cell is covered by any canopy tree trunks, ignore
{
get(x, y)->growing = false;
continue;
}
if(isStatic) // under a canopy
{
if (distsq > 2.25f + 1e-5)
{
//float expval = std::exp(-distsq / (2 * grcanopysq));
//get(x, y)->seed_chance += (sim->sparams.seedprob * 10) * expval;
get(x, y)->seed_chance += sim->sparams.seedprob * (1 - (distsq / (distsqmax)));
get(x,y)->growing = true;
}
else
{
get(x, y)->available = false;
get(x, y)->growing = false;
}
}
//if(distsq <= grcanopysq)
if (distsq <= real_rcanopysq)
{
get(x,y)->canopies.push_back(pic);
if((int) get(x,y)->canopies.size() > 1)
get(x,y)->canopysorted = false;
}
// if(distsq <= grrootsq)
if(distsq <= real_rrootsq)
{
get(x,y)->roots.push_back(pic);
if((int) get(x,y)->roots.size() > 1)
get(x,y)->rootsorted = false;
}
}
}
}
void MapSimCell::expand(std::list<SimPlant *>::iterator plntidx, float px, float py, float prevrcanopy, float prevrroot, float newrcanopy, float newrroot)
{
float grx, gry, gprevrcanopy, gprevrroot, gnewrcanopy, gnewrroot, rmax, distsq, gprevrcanopysq, gprevrrootsq, gnewrcanopysq, gnewrrootsq;
if(prevrcanopy > newrcanopy)
cerr << "EXPAND: CANOPY INCORRECTLY SHRUNK" << endl;
// convert to sim grid coordinates
grx = convert(px);
gry = convert(py);
gprevrcanopy = convert(prevrcanopy/2.0f);
gprevrroot = convert(prevrroot/2.0f);
gnewrcanopy = convert(newrcanopy/2.0f);
gnewrroot = convert(newrroot/2.0f);
gprevrcanopysq = gprevrcanopy * gprevrcanopy;
gprevrrootsq = gprevrroot * gprevrroot;
gnewrcanopysq = gnewrcanopy * gnewrcanopy;
gnewrrootsq = gnewrroot * gnewrroot;
rmax = fmax(gnewrroot, gnewrcanopy);
for(int x = (int) (grx-rmax); x <= (int) (grx+rmax); x++)
for(int y = (int) (gry-rmax); y <= (int) (gry+rmax); y++)
{
PlntInCell pic;
if(ingrid(x,y))
{
pic.hght = 0.0f; // height will be instantiated later on demand
pic.plnt = (* plntidx);
float delx = (float) x-grx;
float dely = (float) y-gry;
distsq = delx*delx + dely*dely;
if(distsq <= gnewrcanopysq && distsq > gprevrcanopysq)
{
get(x,y)->canopies.push_back(pic);
if((int) get(x,y)->canopies.size() > 1)
get(x,y)->canopysorted = false;
}
if(distsq <= gnewrrootsq && distsq > gprevrrootsq)
{
get(x,y)->roots.push_back(pic);
if((int) get(x,y)->roots.size() > 1)
get(x,y)->rootsorted = false;
}
}
}
}
void MapSimCell::uproot(std::list<SimPlant *>::iterator plntidx, float px, float py, float rcanopy, float rroot, Terrain * ter)
{
float grx, gry, grcanopy, grroot, rmax, distsq, grcanopysq, grrootsq;
std::vector<PlntInCell>::iterator cidx, delidx;
// convert to sim grid coordinates
grx = convert(px);
gry = convert(py);
grcanopy = convert(rcanopy/2.0f);
grroot = convert(rroot/2.0f);
grcanopysq = grcanopy * grcanopy;
grrootsq = grroot * grroot;
rmax = fmax(grroot * radius_mult, grcanopy * radius_mult)+2.0f;
for(int x = (int) (grx-rmax); x <= (int) (grx+rmax); x++)
for(int y = (int) (gry-rmax); y <= (int) (gry+rmax); y++)
{
if(ingrid(x,y)) // cell is in grid
{
// find and remove plntidx from canopies
// assumes it appears only once
bool found = false;
for(cidx = get(x,y)->canopies.begin(); cidx != get(x,y)->canopies.end(); cidx++)
if(cidx->plnt == (* plntidx))
{
if(found)
cerr << "REMOVE CANOPY: MULTIPLE FINDS ON PLANT CANOPY" << endl;
found = true;
delidx = cidx;
}
if(found)
get(x,y)->canopies.erase(delidx);
// find and remove plntidx from roots
// assumes it appears only once
found = false;
for(cidx = get(x,y)->roots.begin(); cidx != get(x,y)->roots.end(); cidx++)
if(cidx->plnt == (* plntidx))
{
if(found)
cerr << "REMOVE ROOT: MULTIPLE FINDS ON PLANT CANOPY" << endl;
found = true;
delidx = cidx;
}
if(found)
get(x,y)->roots.erase(delidx);
}
}
}
float cmpHeight(PlntInCell i, PlntInCell j)
{
return i.hght > j.hght;
}
void MapSimCell::traverse(std::list<SimPlant *> *plntpop, Simulation * sim, Biome * biome, MapFloat * sun, MapFloat * wet, bool seedable)
{
int tx, ty;
// clear sunlight and moisture plant pools
std::list<SimPlant *>::iterator plnt;
for(plnt = plntpop->begin(); plnt != plntpop->end(); plnt++)
{
if((* plnt)->state == PlantSimState::ALIVE)
{
(* plnt)->sunlight = 0.0f;
(* plnt)->water = 0.0f;
(* plnt)->sunlightcnt = 0;
(* plnt)->watercnt = 0;
}
}
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
// sort canopy trees by height if necessary
if(!get(x,y)->canopysorted)
{
// update heights
for(int p = 0; p < (int) get(x,y)->canopies.size(); p++)
get(x,y)->canopies[p].hght = get(x,y)->canopies[p].plnt->height;
std::sort(get(x,y)->canopies.begin(), get(x,y)->canopies.end(), cmpHeight);
get(x,y)->canopysorted = true;
}
toTerGrid(x, y, tx, ty, sim->getTerrain());
float sunlight = sun->get(tx, ty);
// traverse trees by height supplying and reducing sunlight
for(int p = 0; p < (int) smap[flatten(x,y)].canopies.size(); p++)
{
PlantSimState pstate = get(x,y)->canopies[p].plnt->state;
assert(pstate != PlantSimState::DEAD); // dead plants should already be removed from grid
if(pstate == PlantSimState::DEAD)
cerr << "WARNING: DEAD PLANTS IN GRID" << endl;
if(pstate != PlantSimState::STATIC)
{
// cerr << "sunlight = " << sunlight << " at " << (int) x/step << ", " << (int) y/step << endl;
get(x,y)->canopies[p].plnt->sunlight += sunlight;
get(x,y)->canopies[p].plnt->sunlightcnt++;
// reduce sunlight by alpha of current plant. note reciprocal
sunlight *= (1.0f - biome->getAlpha(get(x,y)->canopies[p].plnt->pft));
}
}
// add value to sunlight accumulation for later seeding check
if(seedable)
get(x,y)->leftoversun += sunlight;
// sort root trees by height if necessary
if(!get(x,y)->rootsorted)
{
// update heights
for(int p = 0; p < (int) get(x,y)->roots.size(); p++)
get(x,y)->roots[p].hght = get(x,y)->roots[p].plnt->height;
std::sort(get(x,y)->roots.begin(), get(x,y)->roots.end(), cmpHeight);
get(x,y)->rootsorted = true;
}
float moisture = wet->get(tx, ty);
float watershare;
int livecnt = 0;
// traverse trees by height (proxy for root depth) supplying and reducing moisture
for(int p = 0; p < (int) smap[flatten(x,y)].roots.size(); p++)
{
PlantSimState pstate = get(x,y)->roots[p].plnt->state;
if(pstate == PlantSimState::DEAD)
cerr << "WARNING: DEAD PLANTS IN GRID" << endl;
// plants grab flat min
watershare = fmin(moisture, sim->sparams.moisturedemand);
//if(pstate == PlantSimState::STATIC)
// watershare *= 0.0f;
// watershare = fmin(moisture, biome->getMinIdeal dice = new DiceRoller(0,1000);Moisture(get(x,y)->roots[p].plnt->pft));
get(x,y)->roots[p].plnt->water += watershare;
get(x,y)->roots[p].plnt->watercnt++;
moisture -= watershare;
if(pstate != PlantSimState::STATIC)
livecnt++;
}
// remainder spread equally
if(moisture > 0.0f)
{
if(livecnt > 0)
watershare = moisture / (float) livecnt;
else
watershare = moisture;
// add share of leftover water to water accumulator for later seeding check
if(seedable)
// get(x,y)->leftoverwet += watershare;
get(x,y)->leftoverwet += moisture; // potential water for seed access
for(int p = 0; p < (int) smap[flatten(x,y)].roots.size(); p++)
if(get(x,y)->roots[p].plnt->state != PlantSimState::DEAD)
get(x,y)->roots[p].plnt->water += watershare;
}
}
}
void MapSimCell::establishSeedBank(std::list<SimPlant *> * plntpop, int plntpopsize, Biome * biome, Terrain * ter)
{
int p = 0;
// iterate over every plant, check whether it is a canopy plant and write its species index into the simulation cells
// in a circle that extends out to a multiple of the canopy radius
cerr << "Establishing Seedbank" << endl;
int div = plntpopsize / 5;
// clear sunlight and moisture plant pools
std::list<SimPlant *>::iterator plnt;
for(plnt = plntpop->begin(); plnt != plntpop->end(); plnt++)
{
if((* plnt)->state == PlantSimState::STATIC) // denotes a canopy plant
{
float x, y, h;
//std::cout << "Doing subbiome lookup..." << std::endl;
int sb = biome->getSubBiomeFromSpecies((* plnt)->pft);
int spec_idx = (* plnt)->pft;
//std::cout << "getting x, y location..." << std::endl;
ter->toGrid((* plnt)->pos, x, y, h);
//std::cout << "inscribing seeding..." << std::endl;
inscribeSeeding(sb, spec_idx, x, y, ter->toGrid((* plnt)->canopy * seed_radius_mult), ter);
if (p % div == 0 && p != 0)
{
std::cout << int((float) p / (float) plntpopsize * 100) << "% done" << std::endl;
}
}
p++;
}
}
// testing seeding:
// artificially set values in particular cell
// conversion to and from terrain and mapsimcell grid
// no seeds in non growth areas
// check sub-biome lists correctly compiled over multiple biomes
/*
void MapSimCell::testSeeding(vpPoint pos, Simulation * sim, Terrain * ter, Biome * biome)
{
std::vector<int> noseed_count(4, 0);
float x, y, h;
int grx, gry;
std::vector<SimPlant *> plnts;
// specific point on map
pos.x = 500.0f; pos.z = 200.0f; pos.y = 0.0f;
cerr << "picked terrain location = " << pos.x << ", " << pos.z << endl;
// map to simcell
ter->toGrid(pos, x, y, h);
grx = (int) convert(x);
gry = (int) convert(y);
// set simcell parameters
// assumes testing with Sonoma biome
get(grx, gry)->growing = true;
get(grx, gry)->leftoversun = 12.0f;
get(grx, gry)->leftoverwet = 360.0f;
get(grx, gry)->seedbank.clear();
// two sub-biomes
get(grx, gry)->seedbank.push_back(0);
get(grx, gry)->seedbank.push_back(1);
// call singleSeed
singleSeed(grx, gry, &plnts, sim, ter, biome, noseed_count);
// report final position
if((int) plnts.size() == 1)
{
cerr << "final location = " << plnts[0]->pos.x << ", " << plnts[0]->pos.z << ", terrain y = " << plnts[0]->pos.y << endl;
cerr << "tree height = " << plnts[0]->height << endl;
delete plnts[0];
}
else
{
cerr << "Error MapSimCell::testSeeding: plant not created properly" << endl;
}
}*/
bool MapSimCell::singleSeed(int x, int y, std::list<SimPlant *> * plntpop, Simulation * sim, Terrain * ter, Biome * biome, std::vector<int> &noseed_count)
{
// roll dice to see if a seedling could happen, if so check seedbank and assign viability to possible seeds.
// choose seed randomly weighted by viability
std::vector<float> adaptvals(4);
std::vector<float> seedviability;
std::vector<int> seedspecies;
float totalstr, cumstr, sun, wet, temp, slope;
int sidx, dx, dy;
bool found;
bool seeded = false;
ter->getGridDim(dx, dy);
// cerr << "(" << x << ", " << y << ") " << endl;
// gather understorey plants
for(int b = 0; b < (int) get(x,y)->seedbank.size(); b++)
{
// UNDO
SubBiome * sb = biome->getSubBiome(get(x,y)->seedbank[b]);
for(int u = 0; u < (int) sb->understorey.size(); u++)
seedspecies.push_back(sb->understorey[u]);
for(int o = 0; o < (int) sb->canopies.size(); o++)
seedspecies.push_back(sb->canopies[o]);
// seedspecies.push_back(11);
}
// determine viability of plants
totalstr = 0.0f;
for(int s = 0; s < (int) seedspecies.size(); s++)
{
float str;
int tgx, tgy;
// convert from x, y simcell to tx, ty terrain grid
toTerGrid(x, y, tgx, tgy, sim->getTerrain());
// average sunlight and moisture over growing season
sun = get(x,y)->leftoversun / (float) shortgrowmonths;
wet = get(x,y)->leftoverwet / (float) shortgrowmonths;
//sun = sim->getSunlightMap(shortgrowend)->get(tgx, tgy);
//wet = sim->getMoistureMap(shortgrowend)->get(tgx, tgy);
temp = sim->getTemperature(tgx, tgy, shortgrowend); // use end of growing season
slope = sim->getSlopeMap()->get(tgx, tgy);
str = max(0.0f, biome->viability(seedspecies[s], sun, wet, temp, slope, adaptvals, sim->sparams.viabilityneg));
//str = 1.0f;
str /= pow((float) biome->getPFType(seedspecies[s])->maxage, 1.2f);
totalstr += str;
seedviability.push_back(totalstr);
for (int i = 0; i < adaptvals.size(); i++)
{
if (adaptvals.at(i) <= 0.0f)
noseed_count.at(i) += 1;
}
// cerr << " " << str << "(" << totalstr << ")";
}
// cerr << endl << " str = " << totalstr << endl;
#ifdef TESTING
cerr << "SEEDBANK" << endl;
for(int s = 0; s < (int) seedspecies.size(); s++)
{
cerr << "s: " << seedspecies[s] << " v: " << seedviability[s] << endl;
}
cerr << "total viability = " << totalstr << endl;
#endif
// choose particular seed randomly according to viability
if(totalstr > 0.0f)
{
// first check random suitability of location using totalstr
// plants will thus be more likely to seed in generally more favourable areas
// creating
// / numspecies
float select = (float) dice->generate() / 10000.0f * totalstr;
cumstr = 0.0f; found = false; sidx = 0;
// find particular seed according to random selection
while(!found)
{
cumstr = seedviability[sidx];
if(select <= cumstr)
{
found = true;
}
else
{
sidx++;
if(sidx >= (int) seedviability.size())
found = true;
}
}
#ifdef TESTING
cerr << "RND GEN" << endl;
cerr << "rnd number = " << select << " for entry = " << sidx << endl;
#endif
// cerr << " sidx = " << sidx << endl;
// assign height, random position within cell, and other attribues
if(sidx < (int) seedviability.size())
{
SimPlant * sp = new SimPlant;
float sgx, sgy, rndoff;
float wx, wy, wz;
int pft = seedspecies[sidx];
sp->state = PlantSimState::ALIVE;
sp->age = 1.0f;
// random subgrid position within simcell
rndoff = (float) dice->generate() / 10000.0f;
sgx = (float) x + rndoff;
rndoff = (float) dice->generate() / 10000.0f;
sgy = (float) y + rndoff;
// convert to terrain position
sgx /= (float) step; sgy /= (float) step; // terrain grid
// clamp to terrain grid if necessary
if(sgx > (float) dx)
sgx = (float) dx;
if(sgy > (float) dy)
sgy = (float) dy;
sp->pos = ter->toWorld(sgx, sgy, ter->getHeight(sgy, sgx)); // BUG? note inversion in getHeight
sp->height = biome->growth(pft, 0.0f, seedviability[sidx]); // one years growth in proportion to viability
sp->canopy = 2.0f * biome->allometryCanopy(pft, sp->height); // diameter not radius
sp->root = sp->canopy;
sp->reserves = sim->sparams.reservecapacity;
sp->stress = 0.0f;
rndoff = (float) dice->generate() / 10000.0f * 0.4f;
sp->col = glm::vec4(-0.2f+rndoff, -0.2f+rndoff, -0.2f+rndoff, 1.0f);
sp->pft = pft;
sp->water = 0.0f;
sp->sunlight = 0.0f;
ter->toGrid(sp->pos, wx, wy, wz);
if(wx > dx-1)
wx = dx-1;
if(wy > dy-1)
wy = dy-1;
sp->gx = wx;
sp->gy = wy;
plntpop->push_front(sp);
sim->incrPlantPop();
get(x, y)->growing = false; // no other plants can intersect the trunk
get(x, y)->available = false;
seeded = true;
#ifdef TESTING
cerr << "SEED" << endl;
cerr << "pft = " << sp->pft << " subgrid pos = " << sgx << ", " << sgy << endl;
cerr << "height = " << sp->height << ", canopy = " << sp->canopy << endl;
#endif
}
else
{
cerr << "Error MapSimCell::singleSeed: no sapling generated." << endl;
}
}
seedviability.clear();
seedspecies.clear();
return seeded;
}
void MapSimCell::writeSeedBank(string outfile)
{
std::ofstream ofs(outfile);
ofs << smap.size() << " ";
for (auto &simc : smap)
{
ofs << simc.seedbank.size() << " ";
for (auto &sb : simc.seedbank)
{
ofs << sb << " ";
}
}
}
void MapSimCell::readSeedBank(string infile)
{
std::ifstream ifs(infile);
std::string alldata;
for (auto &sm : smap)
{
sm.seedbank.clear();
}
if (ifs.is_open() && ifs.good())
{
std::getline(ifs, alldata);
}
std::stringstream ss(alldata);
int banksize, nseeds, currseed;
ss >> banksize;
if (smap.size() != banksize)
{
throw std::invalid_argument("Seedbank file " + infile + " is corrupted. Generating new seedbank...");
}
//smap.resize(banksize); // we rather do the assert, since smap is supposed to be the right size already...
int currloc = 0;
while (currloc < banksize && ss.good())
{
ss >> nseeds;
for (int i = 0; i < nseeds; i++)
{
ss >> currseed;
smap.at(currloc).seedbank.push_back(currseed);
}
currloc++;
}
}
void MapSimCell::clamp(int &x, int &y)
{
if(x < 0)
x = 0;
if(x > gx-1)
x = gx-1;
if(y < 0)
y = 0;
if(y > gy-1)
y = gy-1;
}
void MapSimCell::seeding(std::list<SimPlant *> * plntpop, int plntpopsize, Simulation * sim, Terrain * ter, Biome * biome)
{
/*
int count = 0;
for (int y = 0; y < gy; y++)
{
for (int x = 0; x < gx; x++)
{
if (get(x, y)->seed_chance > 1e-4)
{
count++;
}
}
}
std::cout << "seed chance nonzero in " << count << " cells" << std::endl;
*/
int nseed_attempts = 0;
int nseeded = 0;
int nseeded_total = 0;
int size_before = plntpopsize;
std::vector<int> noseed_count(4, 0);
std::vector<int> noseed_count_outside(4, 0);
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
if(get(x, y)->growing) // is cell in a growth zone
{
float seedchance = get(x, y)->seed_chance;
// check chance to seed
//bool seed = dice->generate() < (int) (seedprob * 10000.0f);
bool seed = dice->generate() < (int) (seedchance * 10000.0f);
if(seed)
{
bool seeded = singleSeed(x, y, plntpop, sim, ter, biome, noseed_count_outside);
if (seeded)
nseeded_total++;
}
}
nseeded_total += nseeded;
/*
cerr << "num plants before seeding = " << size_before << std::endl;
cerr << "num plants after seeding = " << plntpopsize << endl;
cerr << "Number seeded in target location, attempted: " << nseeded << ", " << nseed_attempts << std::endl;
cerr << "Total number seeded: " << nseeded_total << std::endl;
cerr << "No seed count due to sun, moisture, temp slope in target area: ";
for (auto &v : noseed_count)
{
cerr << v << " ";
}
cerr << std::endl;
*/
}
/*
void MapSimCell::visualize(QImage * visimg, std::vector<SimPlant *> *plnts)
{
int numplnts = (int) plnts->size();
std::vector<QColor> plntcols;
// create table of random colours
for(int p = 0; p < numplnts; p++)
{
int r = 256;
while(r > 255)
r = std::rand()/(RAND_MAX/255);
int g = 256;
while(g > 255)
g = std::rand()/(RAND_MAX/255);
int b = 256;
while(b > 255)
b = std::rand()/(RAND_MAX/255);
QColor col = QColor(r, g, b);
plntcols.push_back(col);
}
// create image corresponding to MapSim
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
// canopies
for(int i = 0; i < (int) get(x, y)->canopies.size(); i++)
// cerr << "total sun = " << plntpop[p].sunlight << " lightcnt = " << plntpop[p].sunlightcnt << endl;
// cerr << "total water = " << plntpop[p].water << " watercnt = " << plntpop[p].watercnt << endl;
// cerr << "simcell occupancy = " << plntpop[p].sunlightcnt << endl;= (int) get(x, y)->canopies.size()-1; i >= 0; i--)
{
for(int p = 1; p < 10; p++)
for(int q = 1; q < 10; q++)
visimg->setPixelColor(x*10+p, y*10+q, plntcols[get(x, y)->canopies[i].idx]);
}
}
}*/
/*
bool MapSimCell::unitTests(QImage * visimg, Terrain *ter, Simulation * sim)
{
bool valid = true;
std::vector<SimPlant *> testplnts;
SimPlant * plnt1, * plnt2;
plnt1 = new SimPlant;
plnt2 = new SimPlant;
setDim(50, 50, 5);
// test simple placement of single plant, at domain center reaching to boundary
inscribe(testplnts.begin(), 5.0f, 5.0f, 5.0f, 2.0f, false, ter, sim);
plnt1->height = 10.0f;
testplnts.push_back(plnt1);
// add shorter plant in offset from center
inscribe(1, 6.15f, 4.15f, 2.0f, 1.0f, false, ter, sim);
plnt2->height = 5.0f;
testplnts.push_back(plnt2);
// grow shorter plant
expand(1, 6.15f, 4.15f, 2.0f, 1.0f, 3.0f, 1.0f);
visualize(visimg, &testplnts);
if(valid)
valid = validate(&testplnts);
cerr << "validity status = " << valid << endl;
for(int p = 0; p < (int) testplnts.size(); p++)
delete testplnts[p];
return valid;
}*/
/*
bool MapSimCell::validate(std::vector<SimPlant *> *plnts)
{
bool valid = true;
// a given plant index must only appear once per cell
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
// print canopies
cerr << "(" << x << ", " << y << ") = ";
for(int i = 0; i < (int) get(x, y)->canopies.size(); i++)
{
cerr << (int) get(x, y)->canopies[i].idx << " ";
}
cerr << endl;
// canopies
for(int i = 0; i < (int) get(x, y)->canopies.size(); i++)
for(int j = i+1; j < (int) get(x, y)->canopies.size(); j++)
if(get(x, y)->canopies[i].plnt == get(x,y)->canopies[j].plnt)
{
valid = false;
cerr << "MapSimCell validity: duplicate canopy index " << get(x,y)->canopies[i].idx << " at position " << i << " and " << j;
cerr << "in cell " << x << ", " << y << endl;
}
// roots
for(int i = 0; i < (int) get(x, y)->roots.size(); i++)
for(int j = i+1; j < (int) get(x, y)->roots.size(); j++)
if(get(x, y)->roots[i].plnt == get(x,y)->roots[j].plnt)
{
valid = false;
cerr << "MapSimCell validity: duplicate root index at position " << i << " and " << j << endl;
}
}
// static plants do not appear in the canopy list
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
// canopies
for(int i = 0; i < (int) get(x, y)->canopies.size(); i++)
if((* plnts)[get(x, y)->canopies[i].idx]->state == PlantSimState::STATIC)
{
valid = false;
cerr << "MapSimCell validity: static plant " << get(x,y)->canopies[i].idx << " in canopy list at position " << i << endl;
}
}
// sorted is true for all canopy and root lists with less than 2 elements
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
// canopies
if((int) get(x,y)->canopies.size() < 2 && !get(x,y)->canopysorted)
{
valid = false;
cerr << "MapSimCell validity: canopy list of less than 2 marked as unsorted in canopy list at position " << x << " " << y << endl;
}
// roots
if((int) get(x,y)->roots.size() < 2 && !get(x,y)->rootsorted)
{
valid = false;
cerr << "MapSimCell validity: canopy list of less than 2 marked as unsorted in root list at position " << x << " " << y << endl;
}
}
return valid;
}*/
////
// Simulation
///
void Simulation::initSim(int dx, int dy, int subcellfactor)
{
simcells.setDim(dx*subcellfactor, dy*subcellfactor, subcellfactor);
for(int m = 0; m < 12; m++)
{
MapFloat sun, mst;
sun.setDim(dx, dy);
mst.setDim(dx, dy);
sunlight.push_back(sun);
sunlight.back().fill(0.0f);
moisture.push_back(mst);
moisture.back().fill(0.0f);
temperature.push_back(0.0f);
cloudiness.push_back(0.0f);
rainfall.push_back(0.0f);
}
slope.setDim(dx, dy);
sunsim = new SunLight();
dice = new DiceRoller(0,1000);
time = 0.0f;
plntpopsize = 0;
// set simulation parameters to default values
sparams.reservecapacity = def_reservecapacity;
sparams.moisturedemand = def_moisturedemand;
sparams.seeddistmult = def_seeddistmult;
sparams.seedprob = def_seedprob;
sparams.stresswght = def_stresswght;
sparams.mortalitybase = def_mortalitybase;
sparams.viabilityneg = def_viabilityneg;
}
void Simulation::delSim()
{
simcells.delMap();
for(int m = 0; m < 12; m++)
{
sunlight[m].delMap();
moisture[m].delMap();
}
std::list<SimPlant *>::iterator plnt;
for(plnt = plntpop.begin(); plnt != plntpop.end(); plnt++)
delete (* plnt);
plntpop.clear();
temperature.clear();
cloudiness.clear();
rainfall.clear();
slope.delMap();
if(sunsim) delete sunsim;
time = 0.0f;
plntpopsize = 0;
}
void Simulation::clearPass()
{
int dx, dy, subcell;
subcell = simcells.getStep();
simcells.delMap();
std::list<SimPlant *>::iterator plnt;
for(plnt = plntpop.begin(); plnt != plntpop.end(); plnt++)
delete (* plnt);
plntpop.clear();
ter->getGridDim(dx, dy);
simcells.setDim(dx*subcell, dy*subcell, subcell);
time = 0.0f;
plntpopsize = 0;
}
void Simulation::reportSunAverages()
{
int dx, dy;
float sum;
ter->getGridDim(dx, dy);
for(int m = 0; m < 12; m++)
{
sum = 0.0f;
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
sum += sunlight[m].get(x, y);
}
cerr << "sun month " << m << " avg = " << sum / (float) (dx*dy) << endl;
}
}
bool Simulation::death(std::list<SimPlant *>::iterator pind, float stress)
{
int dx, dy;
bool dead = false;
// age and stress factors are combined using a probabilistic apprach
// use constant background mortaility to model age effects
// use bioclamatic envelope and a carbohydrate pool to model stress effects
// immediately cull tree if it is taller than threshold because this means that it
// is no longer strictly undergrowth but now part of the canopy
if((* pind)->height > def_hghtthreshold)
{
dead = true;
}
else
{
// background mortality
float ageFactor = 1.0f / (biome->getPFType((* pind)->pft)->maxage);
float age = 1.0f - pow(sparams.mortalitybase, ageFactor);
// cerr << "maxage = " << biome->getPFType((* currind)->pft)->maxage << " ";
// stress mortality. stress score is remainder after effects of carbohydrate pool accounted for
float p = 1000.0f * (age + sparams.stresswght * stress);
// cerr << "p = " << p << " ";
// test against a uniform random variable in [0,1000]
dead = dice->generate() < (int) p;
}
if(dead) // if plant has died change its state
{
float x, y, h;
int sx, sy;
(* pind)->state = PlantSimState::DEAD;
ter->toGrid((* pind)->pos, x, y, h);
sx = (int) simcells.convert((* pind)->gx);
sy = (int) simcells.convert((* pind)->gy);
simcells.clamp(sx, sy);
simcells.get(sx, sy)->growing = true; // flag mapsimcell location as growable so that a new plant can be placed there
simcells.get(sx, sy)->available = true;
}
return dead;
}
void Simulation::growth(std::list<SimPlant *>::iterator pind, float vitality)
{
PFType * pft;
float x, y, h, prevcanopy, prevroot, newcanopy;
assert((* pind)->state != PlantSimState::DEAD);
if(vitality > 0.0f)
{
// apply growth equation for particular pft moderated by vitality
pft = biome->getPFType((* pind)->pft);
(* pind)->height += biome->growth((* pind)->pft, (* pind)->height, min(vitality, 1.0f));
// use allometries for canopy and root
prevcanopy = (* pind)->canopy;
// due to randomness canopy can actually shrink so check for this
newcanopy = 2.0f * biome->allometryCanopy((* pind)->pft, (* pind)->height);
if(newcanopy > prevcanopy)
(* pind)->canopy = newcanopy;
// (* pind)->canopy = 1.0f * biome->allometryCanopy((* pind)->pft, (* pind)->height);
prevroot = (* pind)->root;
(* pind)->root = (* pind)->canopy * pft->alm_rootmult;
// adjust coverage in simcells accordingly
if((* pind)->canopy > prevcanopy)
{
ter->toGrid((* pind)->pos, x, y, h);
simcells.expand(pind, x, y, ter->toGrid(prevcanopy), ter->toGrid(prevroot), ter->toGrid((* pind)->canopy), ter->toGrid((* pind)->root));
}
// cerr << " * GROWTH by " << vitality << " to new hght " << plntpop[pind].height << " * ";
}
}
void Simulation::simStep(int month)
{
std::vector<float> adaptvals(4);
bool shortgrow;
float x, y, h;
// traverse all cells contributing moisture and sunlight to plant pool
shortgrow = (month >= shortgrowstart || month <= shortgrowend);
simcells.traverse(&plntpop, this, biome, &sunlight[month], &moisture[month], shortgrow);
int ndied = 0;
int ntotal_died = 0;
int p = 0;
// cerr << month << endl;
std::list<SimPlant *>::iterator plnt;
for(plnt = plntpop.begin(); plnt != plntpop.end(); plnt++)
{
float sun, wet, temp, slope, str;
float pool, stress = 0.0f, vitality = 0.0f;
bool died = false;
if((* plnt)->state == PlantSimState::DEAD)
cerr << "WARNING DEAD PLANT IN PLANT POPULATION" << endl;
if((* plnt)->state == PlantSimState::ALIVE)
{
if(month == 11) // check for death and seeding once a year
{
// check for death from old age or stress or simplyt because the plant is too tall
died = death(plnt, (* plnt)->stress);
(* plnt)->stress = 0.0f;
if (died)
{
// remove from simulation grid
ter->toGrid((* plnt)->pos, x, y, h);
simcells.uproot(plnt, x, y, ter->toGrid((* plnt)->canopy), ter->toGrid((* plnt)->root), ter);
// remove from plant population, but make sure iterator remains valid
delete (* plnt);
plnt = plntpop.erase(plnt); // require c++11
plntpopsize--;
ntotal_died++;
}
}
if(!died) // still alive?
{
// cerr << endl << "PLANT " << p << " of " << plntpopsize << endl;
sun = (* plnt)->sunlight / (float) (* plnt)->sunlightcnt; // average sunlight
wet = (* plnt)->water / (float) (* plnt)->watercnt; // average moisture
// cerr << "total sun = " << plntpop[p].sunlight << " lightcnt = " << plntpop[p].sunlightcnt << endl;
// cerr << "total water = " << plntpop[p].water << " watercnt = " << plntpop[p].watercnt << endl;
// cerr << "simcell occupancy = " << plntpop[p].sunlightcnt << endl;
temp = getTemperature((* plnt)->gx, (* plnt)->gy, month);
slope = getSlopeMap()->get((* plnt)->gx, (* plnt)->gy);
str = biome->viability((* plnt)->pft, sun, wet, temp, slope, adaptvals, sparams.viabilityneg);
// account for plant reserve pool
pool = (* plnt)->reserves+str;
// cerr << "pool = " << pool << " ";
if(pool < 0.0f) // potential death due to stress
{
(* plnt)->stress += -1.0f * pool;
pool = 0.0f;
}
else if(pool > sparams.reservecapacity) // reserves are full so growth is possible
{
vitality = pool - sparams.reservecapacity;
pool = sparams.reservecapacity;
}
(* plnt)->reserves = pool;
// cerr << "vitality = " << vitality << " reserves = " << plntpop[p].reserves << " ";
// cerr << "stress = " << plntpop[p].stress << " ";
// use vitality to determine growth based on allometry
// but check if this falls in the growing season
// cerr << "pre-growth" << endl;
if(month >= biome->getPFType((* plnt)->pft)->grow_start || month <= biome->getPFType((* plnt)->pft)->grow_end)
{
growth(plnt, vitality);
}
// cerr << "post-growth" << endl;
(* plnt)->age += 1;
}
}
p++;
}
/*
if (month == 11)
{
cerr << "Number of plants that died at target location: " << ndied << std::endl;
cerr << "Total number of plants that died: " << ntotal_died << std::endl;
}*/
// cerr << endl;
}
Simulation::Simulation(Terrain * terrain, Biome * simbiome, int subcellfactor)
{
int dx, dy;
ter = terrain;
biome = simbiome;
ter->getGridDim(dx, dy);
initSim(dx, dy, subcellfactor);
calcSlope();
}
void Simulation::writeSeedBank(string outfile)
{
simcells.writeSeedBank(outfile);
}
void Simulation::writeMap(std::string filename, const MapFloat &map)
{
int dx, dy;
map.getDim(dx, dy);
std::ofstream ofs(filename);
ofs << dx << " " << dy << std::endl;
for (int y = 0; y < dy; y++)
{
for (int x = 0; x < dx; x++)
{
ofs << map.get(x, y) << " ";
}
}
}
void Simulation::calcCanopyDensity(EcoSystem *eco, MapFloat *density, std::string outfilename)
{
int gw, gh;
ter->getGridDim(gw, gh);
density->setDim(gw, gh);
density->fill((float)1.0f);
auto trim = [gw, gh](int &x, int &y)
{
if (x < 0) x = 0;
if (y < 0) y = 0;
if (x >= gw) x = gw - 1;
if (y >= gh) y = gh - 1;
};
std::vector<Plant> plnts;
for (int pft = 0; pft < biome->numPFTypes(); pft++)
{
float alpha = biome->getAlpha(pft);
eco->getPlants()->vectoriseByPFT(pft, plnts);
for (int p = 0; p < plnts.size(); p++)
{
const vpPoint &pos = plnts[p].pos;
float rad = plnts[p].canopy;
float srx = pos.x - rad;
float sry = pos.z - rad;
vpPoint startpt_r(srx, 0.0f, sry);
float erx = pos.x + rad;
float ery = pos.z + rad;
vpPoint endpt_r(erx, 0.0f, ery);
int sx, ex, sy, ey; // start, end grid locations of possible circular area that intersects plant canopy
int gx, gy; // grid location of current plant
ter->toGrid(startpt_r, sx, sy);
ter->toGrid(endpt_r, ex, ey);
ter->toGrid(pos, gx, gy);
trim(sx, sy), trim(ex, ey);
float canopygridsq = ter->toGrid(plnts[p].canopy);
canopygridsq *= canopygridsq;
for (int y = sy; y <= ey; y++)
{
for (int x = sx; x <= ex; x++)
{
int gridsq = (y - gy) * (y - gy) + (x - gx) * (x - gx);
if (gridsq <= canopygridsq)
{
float prevval = density->get(x, y);
float newval = prevval * (1.0f - alpha);
density->set(x, y, newval);
}
}
}
}
}
// we actually calculated above the amount of light that reaches the ground. Canopy density is the additive inverse of this
for (int y = 0; y < gh; y++)
{
for (int x = 0; x < gw; x++)
{
density->set(x, y, 1.0f - density->get(x, y));
}
}
if (outfilename.size() > 0)
{
writeMap(outfilename, *density);
}
}
void Simulation::calcSunlight(GLSun * glsun, int minstep, int nsamples, bool inclCanopy)
{
Timer t;
t.start();
sunsim->setLatitude(ter->getLatitude());
sunsim->setNorthOrientation(Vector(0.0f, 0.0f, -1.0f));
sunsim->setTerrainDimensions(ter);
MapFloat diffusemap;
std::vector<float> sunhours;
std::cout << "Binding glsun..." << std::endl;
glsun->bind();
std::cout << "projecting sun..." << std::endl;
bool projectenable = true;
int startm = 1, endm = 12, mincr = 1;
if (minstep == 0)
{
projectenable = false;
minstep = 60; // otherwise we have an infinite loop
startm = 1;
endm = 12;
mincr = 1;
}
bool diffuseenable = true;
if (nsamples == 0)
diffuseenable = false;
sunsim->projectSun(ter, sunlight, glsun, sunhours, minstep, startm, endm , mincr, projectenable);
std::cout << "diffusing sun..." << std::endl;
sunsim->diffuseSun(ter, &diffusemap, glsun, nsamples, diffuseenable);
std::cout << "merging sun..." << std::endl;
sunsim->mergeSun(sunlight, &diffusemap, cloudiness, sunhours);
if(inclCanopy)
{
std::cout << "inscribing plants..." << std::endl;
sunsim->applyAlpha(glsun, sunlight);
}
t.stop();
cerr << "SUNLIGHT SIMULATION TOOK " << t.peek() << "s IN TOTAL" << endl;
}
void Simulation::calcMoisture()
{
Timer t;
MoistureSim wet;
t.start();
cerr << "MOISTURE SIM PARAMETERS:" << endl;
cerr << " slope threshold = " << biome->slopethresh << " slope max = " << biome->slopemax << " evaporation = " << biome->evaporation;
cerr << " runofflevel = " << biome->runofflevel << " soilsaturation = " << biome->soilsaturation << " water level = " << biome->waterlevel << endl;
wet.simSoilCycle(ter, &slope, rainfall, biome->slopethresh, biome->slopemax, biome->evaporation,
biome->runofflevel, biome->soilsaturation, biome->waterlevel, moisture);
t.stop();
cerr << "MOISTURE SIMULATION TOOK " << t.peek() << "s IN TOTAL" << endl;
}
bool Simulation::readMonthlyMap(std::string filename, std::vector<MapFloat> &monthly)
{
float val;
ifstream infile;
int gx, gy, dx, dy;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> gx >> gy;
#ifdef STEPFILE
float step;
infile >> step; // new format
#endif
ter->getGridDim(dx, dy);
if((gx != dx) || (gy != dy))
cerr << "Error Simulation::readMonthlyMap: map dimensions do not match terrain" << endl;
for(int m = 0; m < 12; m++)
monthly[m].setDim(gx, gy);
for (int y = 0; y < gy; y++)
for (int x = 0; x < gx; x++)
for(int m = 0; m < 12; m++)
{
infile >> val;
monthly[m].set(x, y, val);
}
infile.close();
return true;
}
else
{
cerr << "Error Simulation::readMonthlyMap: unable to open file" << filename << endl;
return false;
}
}
void Simulation::write_monthly_map_copy(std::string filename, std::vector<MapFloat> &monthly)
{
std::vector<ValueGridMap<float> > mapcopies;
for (auto &mmap : monthly)
{
float rw, rh;
int gw, gh;
mmap.getDim(gw, gh);
rw = gw * 0.9144f;
rh = gh * 0.9144f;
mapcopies.push_back(ValueGridMap<float>());
mapcopies.back().setDim(gw, gh);
mapcopies.back().setDimReal(rw, rh);
for (int y = 0; y < gh; y++)
{
for (int x = 0; x < gw; x++)
{
mapcopies.back().set(x, y, mmap.get(x, y));
}
}
}
data_importer::write_monthly_map<ValueGridMap<float> >(filename, mapcopies);
}
bool Simulation::writeMonthlyMap(std::string filename, std::vector<MapFloat> &monthly)
{
int gx, gy;
ofstream outfile;
monthly[0].getDim(gx, gy);
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
outfile << gx << " " << gy;
#ifdef STEPFILE
outfile << " 0.9144"; // hardcoded step
#endif
outfile << endl;
for (int y = 0; y < gy; y++)
for (int x = 0; x < gx; x++)
for(int m = 0; m < 12; m++)
outfile << monthly[m].get(x, y) << " ";
outfile << endl;
outfile.close();
return true;
}
else
{
cerr << "Error Simulation::writeMonthlyMap:unable to open file " << filename << endl;
return true;
}
}
bool Simulation::readClimate(std::string filename)
{
float elv, val;
ifstream infile;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> elv; // in most cases this should be zero. Only use to offset DEM elevations for temperature
// temperature values
for(int m = 0; m < 12; m++)
{
infile >> val;
temperature[m] = val - elv / 1000.0f * lapserate;
}
// sky clarity
for(int m = 0; m < 12; m++)
{
infile >> val;
cloudiness[m] = 1.0f - val;
}
// rainfall
for(int m = 0; m < 12; m++)
{
infile >> val;
rainfall[m] = val;
}
infile.close();
return true;
}
else
{
cerr << "Error Simulation::readClimate: unable to open file" << filename << endl;
return false;
}
}
void Simulation::setTemperature(std::array<float, 12> temp)
{
temperature.clear();
for (auto &val : temp)
{
temperature.push_back(val);
}
}
void Simulation::setRainfall(std::array<float, 12> rain)
{
rainfall.clear();
for (auto &val : rain)
{
rainfall.push_back(val);
}
}
void Simulation::setCloudiness(std::array<float, 12> cloud)
{
cloudiness.clear();
for (auto &val : cloud)
{
cloudiness.push_back(val);
}
}
float Simulation::getTemperature(int x, int y, int mth)
{
return temperature[mth] - ter->getHeight(x, y) / 1000.0f * lapserate;
}
void Simulation::calcSlope()
{
int dx, dy;
Vector up, n;
// slope is dot product of terrain normal and up vector
up = Vector(0.0f, 1.0f, 0.0f);
ter->getGridDim(dx, dy);
slope.setDim(dx, dy);
slope.fill(0.0f);
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
ter->getNormal(x, y, n);
float rad = acos(up.dot(n));
float deg = RAD2DEG * rad;
slope.set(y, x, deg);
}
}
void Simulation::importCanopy(EcoSystem * eco, std::string seedbank_file, std::string seedchance_filename)
{
auto start_tp = std::chrono::steady_clock::now().time_since_epoch();
std::vector<Plant> plnts;
float x, y, h;
int dx, dy;
hghts.clear();
eco->pickAllPlants(ter); // must gather plants before vectorizing
std::list<SimPlant *>::iterator plnt;
for(plnt = plntpop.begin(); plnt != plntpop.end(); plnt++)
delete (* plnt);
plntpop.clear();
simcells.initMap();
ter->getGridDim(dx, dy);
// cerr << "ter dimensions = " << dx << " X " << dy << endl;
simcells.getDim(dx, dy);
// cerr << "sim map dimensions = " << dx << " X " << dy << endl;
std::set<int> all_specidxes;
// iterate over plant functional types
for(int pft = 0; pft < biome->numPFTypes(); pft++)
{
eco->getPlants()->vectoriseByPFT(pft, plnts);
// cerr << "PFT = " << pft << "numplants = " << (int) plnts.size() << endl;
for(int p = 0; p < (int) plnts.size(); p++)
{
SimPlant * sp = new SimPlant;
sp->state = PlantSimState::STATIC;
sp->age = plnts[p].height / biome->getPFType(pft)->maxhght * (float) biome->getPFType(pft)->maxage;
sp->pos = plnts[p].pos;
// cerr << "POSITION = " << sp.pos.x << ", " << sp.pos.y << endl;
sp->height = plnts[p].height;
hghts.push_back(sp->height);
// cerr << "HEIGHT = " << sp.height << endl;
sp->canopy = plnts[p].canopy;
// cerr << "CANOPY = " << sp.canopy << endl;
sp->root = sp->canopy;
sp->reserves = sparams.reservecapacity;
sp->stress = 0.0f;
sp->col = plnts[p].col;
sp->pft = pft;
sp->water = 0.0f;
sp->sunlight = 0.0f;
plntpop.push_front(sp);
plntpopsize++;
all_specidxes.insert(sp->pft);
// inscribe plant into simcells
// cerr << "TERRAIN CELL SIZE = " << ter->getCellExtent() << endl;
ter->toGrid(sp->pos, x, y, h);
if(x > dx-1)
x = dx-1;
if(y > dy-1)
y = dy-1;
sp->gx = x;
sp->gy = y;
simcells.inscribe(plntpop.begin(), x, y, ter->toGrid(sp->canopy), ter->toGrid(sp->root), true, ter, this);
}
}
float tw, th;
uint gw, gh;
ter->getGridDim(gw, gh);
ter->getTerrainDim(tw, th);
if (seedchance_filename.size() > 0)
{
int simc_gw, simc_gh;
simcells.getDim(simc_gw, simc_gh);
ValueGridMap<float> seedchance_map;
seedchance_map.setDim(int(std::round(tw) + 1e-5f), int(std::round(th) + 1e-5f));
seedchance_map.setDimReal(tw, th);
for (int y = 0; y < simc_gh; y++)
{
for (int x = 0; x < simc_gw; x++)
{
float chance = simcells.get(x, y)->seed_chance;
float tgx = simcells.convert_to_tergrid(x);
float tgy = simcells.convert_to_tergrid(y);
vpPoint pt = ter->toWorld(tgx, tgy, 0);
float ry = pt.z; // vpPoint z is actually y, according to the toWorld conversion above
float rx = pt.x;
if (rx > tw || ry > th || rx < 0 || ry < 0)
{
// get size of terrain grid cells width and height, to see if any out of range coordinates are "too much" out of range
float tercw = tw / gw;
float terch = th / gh;
if (rx >= tw + tercw || ry >= th + terch || rx <= -tercw || ry <= -terch) // converted coords are too much higher than terrain size, so we don't correct them and allow exception to be thrown in set_fromreal function below
std::cerr << "Warning: converted coordinates (" << rx << ", " << ry << ") are larger than terrain real dim (" << tw << ", " << th << ")" << std::endl;
else
{
// probably just a cell that falls partly outside the actual terrain, so we clamp to the terrain width/height
if (rx > tw)
rx = tw - 1e-5f;
else
rx = 1e-5f;
if (ry > th)
ry = th - 1e-5f;
else
ry = 1e-5f;
}
}
seedchance_map.set_fromreal(rx, ry, chance);
}
}
data_importer::write_txt<ValueGridMap<float> >(seedchance_filename, &seedchance_map);
// std::cout << "Done writing seedchance file at " << seedchance_filename << std::endl;
}
simcells.init_countmaps(all_specidxes, gw, gh, tw, th);
// std::cout << "Establishing seed bank..." << std::endl;
bool readsuccess = false;
if (seedbank_file.size() > 0 && static_cast<bool>(std::ifstream(seedbank_file))) // if a seedbank file already exists, we just read it in
{
try
{
simcells.readSeedBank(seedbank_file);
readsuccess = true;
}
catch (std::invalid_argument &e)
{
std::cout << "Invalid seedbank file at " + seedbank_file + ". Simulating new seedbank..." << std::endl;
readsuccess = false;
}
}
if (!readsuccess)
{
simcells.establishSeedBank(&plntpop, plntpopsize, biome, ter);
if (seedbank_file.size() > 0)
{
simcells.writeSeedBank(seedbank_file); // write newly simulated seedbank to a file that can be imported later for faster simulation
#ifndef NDEBUG
std::vector<SimCell> cells = simcells.get_smap();
simcells.readSeedBank(seedbank_file);
std::vector<SimCell> cells2 = simcells.get_smap();
assert(cells.size() == cells2.size());
for (int i = 0; i < cells.size(); i++)
{
for (int j = 0; j < cells.at(i).seedbank.size(); j++)
{
assert(cells.at(i).seedbank.at(j) == cells2.at(i).seedbank.at(j));
}
}
#endif // NDEBUG
}
}
auto end_tp = std::chrono::steady_clock::now().time_since_epoch();
}
void Simulation::exportUnderstory(EcoSystem * eco)
{
for(int n = 0; n < maxNiches; n++)
{
int plntcnt = 0;
int deadcount = 0;
PlantGrid * outplnts = eco->getNiche(n);
outplnts->clear();
plntcnt = 0;
// canopy into niche 0, understory into niche 1
std::list<SimPlant *>::iterator plnt;
for(plnt = plntpop.begin(); plnt != plntpop.end(); plnt++)
{
Plant op;
bool place;
if(n == 0) // only include static plants in niche 0
{
place = ((* plnt)->state == PlantSimState::STATIC);
}
else // only include live plants in niche 1
{
place = ((* plnt)->state == PlantSimState::ALIVE);
}
if(place)
{
float cullhght = biome->getPFType((* plnt)->pft)->minhght;
if ((* plnt)->state != PlantSimState::DEAD && (* plnt)->height >= cullhght)
{
op.canopy = (* plnt)->canopy;
op.col = (* plnt)->col;
op.height = (* plnt)->height;
if(n == 0)
op.pos = (* plnt)->pos;
else
op.pos = vpPoint((* plnt)->pos.x, (* plnt)->pos.y, (* plnt)->pos.z);
outplnts->placePlant(ter, (* plnt)->pft, op);
plntcnt++;
if((* plnt)->state == PlantSimState::DEAD)
cerr << " DEAD";
}
else
{
deadcount++;
}
}
}
// cerr << "niche " << n << " numplants = " << plntcnt << endl;
// cerr << "number of dead plants in niche: " << deadcount << endl;
}
// eco->pickAllPlants(ter); // gather all plants for display
// eco->redrawPlants();
}
bool Simulation::writeAssignSun(std::string filename)
{
int gx, gy;
ofstream outfile;
sunlight[0].getDim(gx, gy);
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
// sunlight
outfile << gx << " " << gy << " " << endl;
for (int x = 0; x < gx; x++)
for (int y = 0; y < gy; y++)
for(int m = 1; m < 2; m++)
outfile << sunlight[m].get(x, y) << " ";
outfile << endl;
// block plant placement
outfile << (gx / 3 * gy / 3) << endl;
cerr << "num trees = " << (gx / 3 * gy / 3) << endl;
int countt = 0;
for (int x = 0; x < gx; x+= 3)
for (int y = 0; y < gy; y+= 3)
{
// random position and size
int rx = x+dice->generate() % 3;
int ry = y+dice->generate() % 3;
if(rx >= gx)
rx = gx-1;
if(ry >= gy)
ry = gy-1;
int re = dice->generate() % 8 + 1;
outfile << rx << " " << ry << " " << re << endl;
countt++;
}
cerr << "actual num trees = " << countt << endl;
outfile << endl;
outfile.close();
return true;
}
else
{
cerr << "Error Simulation::writeMonthlyMap:unable to open file " << filename << endl;
return true;
}
}
void Simulation::pickInfo(int x, int y)
{
cerr << "Sunlight (Hrs): ";
for(int m = 0; m < 12; m++)
cerr << sunlight[m].get(x, y) << " ";
cerr << endl;
cerr << "Slope (rad): " << slope.get(x, y) << endl;
cerr << "Soil Moisture (mm): ";
for(int m = 0; m < 12; m++)
cerr << moisture[m].get(x, y) << " ";
cerr << endl;
cerr << "Temperature (C): ";
for(int m = 0; m < 12; m++)
cerr << getTemperature(x, y, m) << " ";
cerr << endl;
}
void Simulation::printParams()
{
cerr << "Simulation Parameters" << endl;
cerr << "Reserve Capacity = " << sparams.reservecapacity << " Moisture Demand = " << sparams.moisturedemand << " Seed Probability = " << sparams.seedprob << endl;
cerr << "Stress Weight = " << sparams.stresswght << " Mortality Base = " << sparams.mortalitybase << " Viability Neg Range = " << sparams.viabilityneg << endl;
cerr << endl;
}
void Simulation::averageViability(std::vector<float> &targetnums)
{
std::vector<float> adaptvals(4);
std::vector<float> totadaptvals(4);
float totstr, str, sun, wet, temp, slope;
int gx, gy, step, avgcount, wetcount, numover, nonviable;
simcells.getDim(gx, gy);
step = simcells.getStep();
cerr << "Average Viability by Species: " << endl;
// sum viability per species over growing areas of map
for(int s = 0; s < biome->numPFTypes(); s++)
{
totstr = 0.0f;
avgcount = 0;
wetcount = 0; numover = 0; nonviable = 0;
for(int i = 0; i < 4; i++)
totadaptvals[i] = 0.0f;
if(targetnums[s] >= 0.0f)
{
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
if(simcells.get(x, y)->growing)
{
float str;
int tgx, tgy;
// convert from x, y simcell to tx, ty terrain grid
simcells.toTerGrid(x, y, tgx, tgy, ter);
// average sunlight and moisture over growing season
sun = simcells.get(x,y)->leftoversun / (float) shortgrowmonths;
wet = simcells.get(x,y)->leftoverwet / (float) shortgrowmonths;
temp = getTemperature(tgx, tgy, shortgrowend); // use end of growing season
slope = getSlopeMap()->get(tgx, tgy);
str = max(0.0f, biome->viability(s, sun, wet, temp, slope, adaptvals, sparams.viabilityneg));
totstr += str;
for(int i = 0; i < 4; i++)
totadaptvals[i] += adaptvals[i];
avgcount++;
if(adaptvals[1] < 0.0f) // negative wetness
{
if(biome->overWet(s, wet))
numover++;
wetcount++;
}
if(str < 0.5f) // low viability here
{
nonviable++;
}
}
cerr << s << ", " << totstr / (float) avgcount << ", " << totadaptvals[0] / (float) avgcount << ", " << totadaptvals[1] / (float) avgcount << ", " << totadaptvals[2] / (float) avgcount << ", " << totadaptvals[3] / (float) avgcount;
cerr << endl;
cerr << "overwet proportion = " << (float) numover / (float) wetcount << endl;
cerr << "nonviable proportion = " << (float) nonviable / (float) avgcount;
}
cerr << endl;
}
}
float Simulation::plantTarget(std::vector<float> &targetnums)
{
std::vector<int> actualnums;
std::vector<float> avghght;
int canopynums = 0;
float diff = 0.0f, cullhght;
// init count per species
for(int s = 0; s < biome->numPFTypes(); s++)
{
actualnums.push_back(0);
avghght.push_back(0.0f);
}
// canopy into niche 0, understory into niche 1
std::list<SimPlant *>::iterator plnt;
for(plnt = plntpop.begin(); plnt != plntpop.end(); plnt++)
{
cullhght = biome->getPFType((* plnt)->pft)->minhght;
if((* plnt)->state == PlantSimState::ALIVE && (* plnt)->height > cullhght)
{
actualnums[(* plnt)->pft]++;
avghght[(* plnt)->pft] += (* plnt)->height;
}
else
{
if((* plnt)->state == PlantSimState::STATIC)
canopynums++;
}
}
// print different species
// cerr << "Number of Canopy Plant = " << canopynums << endl;
// cerr << "Number of Undergrowth Plant by Species: " << endl;
for(int s = 0; s < biome->numPFTypes(); s++)
if(targetnums[s] >= 0.0f) // in subbiome
{
cerr << biome->getPFType(s)->code << " [" << s << "] = " << actualnums[s];
cerr << " avg. height = " << avghght[s] / (float) actualnums[s] << endl;
cerr << " as proportion = " << (float) actualnums[s] / (float) canopynums << endl;
// cerr << "diff from target " << (float) actualnums[s] / (float) canopynums - targetnums[s] << endl;
}
cerr << endl;
// calculate diff from target
// actual nums need to be converted to a total water available in mmper canopy tree basis for comparison against targetnums
/*
for(int s = 0; s < biome->numPFTypes(); s++)
{
if(targetnums[s] >= 0.0f) // negative results is signal to ignore this species in calculations
diff += fabs((float) actualnums[s] / (float) canopynums - targetnums[s]);
}*/
return diff;
}
void Simulation::simulate(EcoSystem * eco, std::string seedbank_file, std::string seedchance_filename, int delYears)
{
Timer simt;
std::string tmp_filename;
simt.start();
std::vector<float> targetnums;
for(int s = 0; s < biome->numPFTypes(); s++)
targetnums.push_back(1.0f);
// tuned simulation parameters
biome->getPFType(11)->sun.r = 8.0f;
sparams.reservecapacity = 3.0f;
sparams.seedprob = 0.003f;
sparams.stresswght = 1.25f;
sparams.viabilityneg = -0.4f;
// clear undergrowth
clearPass();
importCanopy(eco, seedbank_file, seedchance_filename);
/*
// checkpointing functionality
// commented out because it creates large files and slows simulations
if(chkpnt > 0)
{
tmp_filename = out_filename + "_chk" + std::to_string(chkpnt) + ".pdb";
readCheckPoint(tmp_filename);
}*/
for(int y = 0; y < delYears; y++)
{
Timer simy;
simy.start();
simcells.resetSeeding(); // clear seeding
for(int m = 0; m < 12; m++)
simStep(m);
if(y == 0)
averageViability(targetnums);
simcells.seeding(&plntpop, plntpopsize, this, ter, biome);
simy.stop();
cerr << "YEAR " << y << " took " << simy.peek() << "s" << endl;
// report species numbers and save to checkpoint file
/*
if(y > 0 && y%25 == 0)
{
float res = plantTarget(targetnums);
tmp_filename = out_filename + "_" + std::to_string(y+chkpnt) + ".pdb";
exportUnderstory(eco); // transfer plants from simulation
eco->saveNichePDB(tmp_filename, 1);
}*/
}
// print viability params
// biome->printParams();
simt.stop();
cerr << "simulation took " << simt.peek() << "s" << endl;
}
| 71,305
|
C++
|
.cpp
| 1,833
| 29.142935
| 247
| 0.520331
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,164
|
glwidget.cpp
|
jgain_EcoLearn/UnderSim/sim/glwidget.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "glwidget.h"
#include "eco.h"
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <QGridLayout>
#include <QGLFramebufferObject>
#include <QImage>
#include <QCoreApplication>
#include <QMessageBox>
#include <QInputDialog>
#include <fstream>
using namespace std;
#ifndef GL_MULTISAMPLE
#define GL_MULTISAMPLE 0x809D
#endif
////
// Scene
////
Scene::Scene()
{
view = new View();
terrain = new Terrain();
terrain->initGrid(1024, 1024, 10000.0f, 10000.0f);
view->setForcedFocus(terrain->getFocus());
view->setViewScale(terrain->longEdgeDist());
sim = new Simulation();
eco = new EcoSystem();
biome = new Biome();
int dx, dy;
terrain->getGridDim(dx, dy);
for(TypeMapType t: all_typemaps)
maps[(int) t] = new TypeMap(dx, dy, t);
maps[2]->setRegion(terrain->coverRegion());
moisture = new MapFloat();
illumination = new MapFloat();
temperature = new MapFloat();
chm = new MapFloat();
cdm = new MapFloat();
overlay = TypeMapType::EMPTY;
}
Scene::~Scene()
{
delete view;
delete terrain;
for(TypeMapType t: all_typemaps)
if(maps[(int) t] != nullptr)
{
delete maps[(int) t];
maps[(int) t] = nullptr;
}
delete sim;
delete eco;
delete biome;
delete illumination;
delete moisture;
delete temperature;
delete chm;
delete cdm;
}
////
// GLWidget
////
GLWidget::GLWidget(const QGLFormat& format, string datadir, QWidget *parent)
: QGLWidget(format, parent)
{
this->datadir = datadir;
qtWhite = QColor::fromCmykF(0.0, 0.0, 0.0, 0.0);
vizpopup = new QLabel();
atimer = new QTimer(this);
connect(atimer, SIGNAL(timeout()), this, SLOT(animUpdate()));
rtimer = new QTimer(this);
connect(rtimer, SIGNAL(timeout()), this, SLOT(rotateUpdate()));
glformat = format;
// main design scene
addScene();
// database display and picking scene
addScene();
currscene = 0;
renderer = new PMrender::TRenderer(NULL, "../sim/shaders/");
cmode = ControlMode::VIEW;
viewing = false;
viewlock = false;
decalsbound = false;
focuschange = false;
focusviz = false;
timeron = false;
dbloaded = false;
ecoloaded = false;
inclcanopy = true;
active = true;
scf = 10000.0f;
decalTexture = 0;
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
resize(sizeHint());
setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored);
simvalid = false;
firstsim = false;
glsun = new GLSun(glformat);
}
GLWidget::~GLWidget()
{
delete atimer;
delete rtimer;
if(vizpopup) delete vizpopup;
if (renderer) delete renderer;
if(glsun) delete glsun;
// delete views
for(int i = 0; i < (int) scenes.size(); i++)
delete scenes[i];
if (decalTexture != 0) glDeleteTextures(1, &decalTexture);
}
QSize GLWidget::minimumSizeHint() const
{
return QSize(50, 50);
}
QSize GLWidget::sizeHint() const
{
return QSize(1000, 800);
}
void GLWidget::screenCapture(QImage * capImg, QSize capSize)
{
paintGL();
glFlush();
(* capImg) = grabFrameBuffer();
(* capImg) = capImg->scaled(capSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
}
View * GLWidget::getView()
{
if((int) scenes.size() > 0)
return scenes[currscene]->view;
else
return NULL;
}
Terrain * GLWidget::getTerrain()
{
if((int) scenes.size() > 0)
return scenes[currscene]->terrain;
else
return NULL;
}
TypeMap * GLWidget::getTypeMap(TypeMapType purpose)
{
if((int) scenes.size() > 0)
{
int idx = (int)purpose;
return scenes[currscene]->maps[(int) purpose];
}
else
return NULL;
}
MapFloat * GLWidget::getSunlight(int month)
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim->getSunlightMap(month);
else
return NULL;
}
MapFloat * GLWidget::getSlope()
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim->getSlopeMap();
else
return NULL;
}
MapFloat * GLWidget::getMoisture(int month)
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim->getMoistureMap(month);
else
return NULL;
}
MapFloat * GLWidget::getCanopyHeightModel()
{
if((int) scenes.size() > 0)
return scenes[currscene]->chm;
else
return NULL;
}
MapFloat * GLWidget::getCanopyDensityModel()
{
if((int) scenes.size() > 0)
return scenes[currscene]->cdm;
else
return NULL;
}
PMrender::TRenderer * GLWidget::getRenderer()
{
return renderer;
}
EcoSystem * GLWidget::getEcoSys()
{
if((int) scenes.size() > 0)
return scenes[currscene]->eco;
else
return NULL;
}
Simulation * GLWidget::getSim()
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim;
else
return NULL;
}
void GLWidget::initSceneSim()
{
// assumes terrain and biome already loaded
if((int) scenes.size() > 0)
{
scenes[currscene]->sim = new Simulation(getTerrain(), getBiome(), 5);
}
}
Biome * GLWidget::getBiome()
{
if((int) scenes.size() > 0)
return scenes[currscene]->biome;
else
return NULL;
}
GLSun * GLWidget::getGLSun()
{
return glsun;
}
void GLWidget::refreshOverlay()
{
renderer->updateTypeMapTexture(getTypeMap(scenes[currscene]->overlay), PMrender::TRenderer::typeMapInfo::PAINT, false);
update();
}
void GLWidget::setOverlay(TypeMapType purpose)
{
scenes[currscene]->overlay = purpose;
renderer->updateTypeMapTexture(getTypeMap(scenes[currscene]->overlay), PMrender::TRenderer::typeMapInfo::PAINT, true);
update();
}
TypeMapType GLWidget::getOverlay()
{
return scenes[currscene]->overlay;
}
void GLWidget::bandCanopyHeightTexture(float mint, float maxt)
{
getTypeMap(TypeMapType::CHM)->bandCHMMap(getCanopyHeightModel(), mint*mtoft, maxt*mtoft);
focuschange = true;
}
std::string GLWidget::get_dirprefix()
{
std::cout << "Datadir before fixing: " << datadir << std::endl;
while (datadir.back() == '/')
datadir.pop_back();
std::cout << "Datadir after fixing: " << datadir << std::endl;
int slash_idx = datadir.find_last_of("/");
std::string setname = datadir.substr(slash_idx + 1);
std::string dirprefix = datadir + "/" + setname;
return dirprefix;
}
void GLWidget::loadScene(int curr_canopy)
{
std::cout << "Datadir before fixing: " << datadir << std::endl;
while (datadir.back() == '/')
datadir.pop_back();
std::cout << "Datadir after fixing: " << datadir << std::endl;
int slash_idx = datadir.find_last_of("/");
std::string setname = datadir.substr(slash_idx + 1);
std::string dirprefix = get_dirprefix();
loadScene(dirprefix, curr_canopy);
}
void GLWidget::loadFinScene(int curr_canopy)
{
std::cout << "Datadir before fixing: " << datadir << std::endl;
while (datadir.back() == '/')
datadir.pop_back();
std::cout << "Datadir after fixing: " << datadir << std::endl;
int slash_idx = datadir.find_last_of("/");
std::string setname = datadir.substr(slash_idx + 1);
std::string dirprefix = get_dirprefix();
loadFinScene(dirprefix, curr_canopy);
}
void GLWidget::sim_canopy_sunlight(std::string sunfile)
{
getGLSun()->setScene(getTerrain(), getCanopyHeightModel(), getCanopyDensityModel());
getGLSun()->deriveAlpha(getEcoSys(), getBiome());
cerr << "About to report Alpha Map Stats" << endl;
getGLSun()->alphaMapStats();
auto bt = std::chrono::steady_clock::now().time_since_epoch();
getSim()->calcSunlight(getGLSun(), 15, 50, inclcanopy);
auto et = std::chrono::steady_clock::now().time_since_epoch();
auto t = std::chrono::duration_cast<std::chrono::milliseconds>(et - bt).count();
std::cout << "Time ms: " << t << std::endl;
getSim()->reportSunAverages();
getSim()->writeSunCopy(sunfile);
}
void GLWidget::loadAndSimSunlightMoistureOnly()
{
std::cout << "Datadir before fixing: " << datadir << std::endl;
while (datadir.back() == '/')
datadir.pop_back();
std::cout << "Datadir after fixing: " << datadir << std::endl;
int slash_idx = datadir.find_last_of("/");
std::string setname = datadir.substr(slash_idx + 1);
std::string dirprefix = get_dirprefix();
loadAndSimSunlightMoistureOnly(dirprefix);
}
void GLWidget::loadAndSimSunlightMoistureOnly(std::string dirprefix)
{
simvalid = true;
std::string terfile = dirprefix+".elv";
//std::string pdbfile = dirprefix+".pdb";
std::string pdbfile = dirprefix + "_canopy";
pdbfile += std::to_string(0) + ".pdb";
std::string chmfile = dirprefix+".chm";
std::string cdmfile = dirprefix+".cdm";
std::string sunfile = dirprefix+"_sun.txt";
std::string wetfile = dirprefix+"_wet.txt";
std::string climfile = dirprefix+"_clim.txt";
std::string bmefile = dirprefix+"_biome.txt";
std::string catfile = dirprefix+"_plt.png";
// load terrain
currscene = 0;
getTerrain()->loadElv(terfile);
cerr << "Elevation file loaded" << endl;
scf = getTerrain()->getMaxExtent();
getView()->setForcedFocus(getTerrain()->getFocus());
getView()->setViewScale(getTerrain()->longEdgeDist());
getView()->setDim(0.0f, 0.0f, (float) this->width(), (float) this->height());
getTerrain()->calcMeanHeight();
// match dimensions for empty overlay
int dx, dy;
getTerrain()->getGridDim(dx, dy);
getTypeMap(TypeMapType::PAINT)->matchDim(dx, dy);
getTypeMap(TypeMapType::PAINT)->fill(0);
getTypeMap(TypeMapType::EMPTY)->matchDim(dx, dy);
getTypeMap(TypeMapType::EMPTY)->clear();
if(getCanopyHeightModel()->read(chmfile))
{
cerr << "CHM file loaded" << endl;
loadTypeMap(getCanopyHeightModel(), TypeMapType::CHM);
}
else
{
cerr << "No Canopy Height Model found. Simulation invalidated." << endl;
simvalid = false;
}
if(getCanopyDensityModel()->read(cdmfile))
{
loadTypeMap(getCanopyDensityModel(), TypeMapType::CDM);
cerr << "CDM file loaded" << endl;
}
else
{
cerr << "No Canopy Density Model found. Simulation invalidated." << endl;
simvalid = false;
}
if(getBiome()->read(bmefile))
{
cerr << "Biome file loaded" << endl;
for(int t = 0; t < getBiome()->numPFTypes(); t++)
plantvis.push_back(true);
canopyvis = true;
undervis = true;
/*
// report max plant size
for(int t = 0; t < getBiome()->numPFTypes(); t++)
{
cerr << getBiome()->getPFType(t)->code << " max hght = " << getBiome()->maxGrowthTest(t) << endl;
}
*/
// initialize simulation
initSceneSim();
// read climate parameters
if(!getSim()->readClimate(climfile))
{
simvalid = false;
cerr << "No climate file " << climfile << " found. Simulation invalidated" << endl;
}
else
{
cerr << "Climate file loaded" << endl;
}
// read sunlight, and if that fails simulate it and store results
if(!getSim()->readSun(sunfile))
{
cerr << "No Sunlight file " << sunfile << " found, so simulating sunlight" << endl;
sim_canopy_sunlight(sunfile);
}
else
{
cerr << "Sunlight file loaded" << endl;
}
sun_mth = 0;
loadTypeMap(getSunlight(sun_mth), TypeMapType::SUNLIGHT);
loadTypeMap(getSlope(), TypeMapType::SLOPE);
// read soil moisture, and if that fails simulate it and store results
if(!getSim()->readMoisture(wetfile))
{
cerr << "No Soil moisture file " << wetfile << " found, so simulating soil moisture" << endl;
getSim()->calcMoisture();
getSim()->writeMoisture(wetfile);
}
else
{
cerr << "Soil moisture file loaded" << endl;
}
}
}
void GLWidget::loadSceneWithoutSims(int curr_canopy, std::string chmfile, string output_sunfile)
{
std::cout << "Datadir before fixing: " << datadir << std::endl;
while (datadir.back() == '/')
datadir.pop_back();
std::cout << "Datadir after fixing: " << datadir << std::endl;
int slash_idx = datadir.find_last_of("/");
std::string setname = datadir.substr(slash_idx + 1);
std::string dirprefix = get_dirprefix();
loadSceneWithoutSims(dirprefix, curr_canopy, chmfile, output_sunfile);
}
void GLWidget::loadSceneWithoutSims(std::string dirprefix, int curr_canopy, std::string chmfile, std::string output_sunfile)
{
simvalid = true;
std::string terfile = dirprefix+".elv";
std::string pdbfile = dirprefix + "_canopy";
pdbfile += std::to_string(curr_canopy) + ".pdb";
std::string cdmfile = dirprefix+".cdm";
std::string sunfile = dirprefix+"_sun.txt";
std::string wetfile = dirprefix+"_wet.txt";
std::string climfile = dirprefix+"_clim.txt";
std::string bmefile = dirprefix+"_biome.txt";
std::string catfile = dirprefix+"_plt.png";
// load terrain
currscene = 0;
getTerrain()->loadElv(terfile);
cerr << "Elevation file loaded" << endl;
scf = getTerrain()->getMaxExtent();
getView()->setForcedFocus(getTerrain()->getFocus());
getView()->setViewScale(getTerrain()->longEdgeDist());
getView()->setDim(0.0f, 0.0f, (float) this->width(), (float) this->height());
getTerrain()->calcMeanHeight();
// match dimensions for empty overlay
int dx, dy;
getTerrain()->getGridDim(dx, dy);
getTypeMap(TypeMapType::PAINT)->matchDim(dx, dy);
getTypeMap(TypeMapType::PAINT)->fill(0);
getTypeMap(TypeMapType::EMPTY)->matchDim(dx, dy);
getTypeMap(TypeMapType::EMPTY)->clear();
if(getCanopyHeightModel()->read(chmfile))
{
cerr << "CHM file loaded" << endl;
loadTypeMap(getCanopyHeightModel(), TypeMapType::CHM);
}
else
{
cerr << "No Canopy Height Model found. Simulation invalidated." << endl;
simvalid = false;
}
if(getCanopyDensityModel()->read(cdmfile))
{
loadTypeMap(getCanopyDensityModel(), TypeMapType::CDM);
cerr << "CDM file loaded" << endl;
}
else
{
cerr << "No Canopy Density Model found. Simulation invalidated." << endl;
simvalid = false;
}
if (getBiome()->read_dataimporter(SONOMA_DB_FILEPATH))
{
if (plantvis.size() < getBiome()->numPFTypes())
plantvis.resize(getBiome()->numPFTypes());
cerr << "Biome file load" << endl;
for(int t = 0; t < getBiome()->numPFTypes(); t++)
plantvis[t] = true;
// initialize simulation
initSceneSim();
// read climate parameters
if(!getSim()->readClimate(climfile))
{
simvalid = false;
cerr << "No climate file " << climfile << " found. Simulation invalidated" << endl;
}
sim_canopy_sunlight(output_sunfile);
}
else
{
std::cerr << "Biome file " << bmefile << "does not exist. Simulation invalidated." << endl;
}
focuschange = false;
if(simvalid)
firstsim = true;
}
void GLWidget::loadFinScene(std::string dirprefix, int curr_canopy)
{
simvalid = true;
std::string terfile = dirprefix+".elv";
std::string cpdbfile = dirprefix + "_canopy";
std::string updbfile = dirprefix + "_undergrowth";
cpdbfile += std::to_string(curr_canopy) + ".pdb";
updbfile += std::to_string(curr_canopy) + ".pdb";
std::string chmfile = dirprefix+".chm";
std::string cdmfile = dirprefix+".cdm";
std::string sunfile = dirprefix+"_sun.txt";
std::string wetfile = dirprefix+"_wet.txt";
std::string climfile = dirprefix+"_clim.txt";
std::string bmefile = dirprefix+"_biome.txt";
std::string catfile = dirprefix+"_plt.png";
simvalid = false;
// load terrain
currscene = 0;
getTerrain()->loadElv(terfile);
cerr << "Elevation file loaded" << endl;
scf = getTerrain()->getMaxExtent();
getView()->setForcedFocus(getTerrain()->getFocus());
getView()->setViewScale(getTerrain()->longEdgeDist());
getView()->setDim(0.0f, 0.0f, (float) this->width(), (float) this->height());
getTerrain()->calcMeanHeight();
// match dimensions for empty overlay
int dx, dy;
getTerrain()->getGridDim(dx, dy);
getTypeMap(TypeMapType::PAINT)->matchDim(dx, dy);
getTypeMap(TypeMapType::PAINT)->fill(0);
getTypeMap(TypeMapType::EMPTY)->matchDim(dx, dy);
getTypeMap(TypeMapType::EMPTY)->clear();
if(getCanopyHeightModel()->read(chmfile))
{
cerr << "CHM file loaded" << endl;
loadTypeMap(getCanopyHeightModel(), TypeMapType::CHM);
}
else
{
cerr << "No Canopy Height Model found. Simulation invalidated." << endl;
}
if(getCanopyDensityModel()->read(cdmfile))
{
loadTypeMap(getCanopyDensityModel(), TypeMapType::CDM);
cerr << "CDM file loaded" << endl;
}
else
{
cerr << "No Canopy Density Model found. One will be calculated from the imported canopy trees." << endl;
}
if (getBiome()->read_dataimporter(SONOMA_DB_FILEPATH))
{
if (plantvis.size() < getBiome()->numPFTypes())
plantvis.resize(getBiome()->numPFTypes());
cerr << "Biome file load" << endl;
for(int t = 0; t < getBiome()->numPFTypes(); t++)
plantvis[t] = true;
canopyvis = true;
undervis = true;
initSceneSim();
// read climate parameters
if(!getSim()->readClimate(climfile))
cerr << "No climate file " << climfile << " found." << endl;
// read soil moisture, and if that fails simulate it and store results
if(!getSim()->readMoisture(wetfile))
{
cerr << "No Soil moisture file " << wetfile << " found" << endl;
}
else
{
cerr << "Soil moisture file loaded" << endl;
wet_mth = 0;
loadTypeMap(getMoisture(wet_mth), TypeMapType::WATER);
}
// loading plant distribution
getEcoSys()->setBiome(getBiome());
if(!getEcoSys()->loadNichePDB(cpdbfile, getTerrain()))
std::cerr << "Plant distribution file " << cpdbfile << "does not exist" << endl; // just report but not really an issue
else
std::cerr << "Plant canopy distribution file loaded" << std::endl;
if(!getEcoSys()->loadNichePDB(updbfile, getTerrain(), 1))
std::cerr << "Undergrowth distribution file " << updbfile << " does not exist" << endl; // just report but not really an issue
else
std::cerr << "Plant undergrowth distribution file loaded" << std::endl;
setAllPlantsVis();
focuschange = !focuschange;
getEcoSys()->pickAllPlants(getTerrain(), canopyvis, undervis);
getEcoSys()->redrawPlants();
update();
// read sunlight, and if that fails simulate it and store results
if(!getSim()->readSun(sunfile))
{
cerr << "No Sunlight file " << sunfile << " found" << endl;
}
else
{
cerr << "Sunlight file loaded" << endl;
sun_mth = 0;
loadTypeMap(getSunlight(sun_mth), TypeMapType::SUNLIGHT);
}
loadTypeMap(getSlope(), TypeMapType::SLOPE);
}
else
{
std::cerr << "Biome file " << bmefile << "does not exist." << endl;
focuschange = false;
}
}
void GLWidget::loadScene(std::string dirprefix, int curr_canopy)
{
simvalid = true;
std::string terfile = dirprefix+".elv";
std::string pdbfile = dirprefix + "_canopy";
pdbfile += std::to_string(curr_canopy) + ".pdb";
std::string chmfile = dirprefix+".chm";
std::string cdmfile = dirprefix+".cdm";
std::string sunfile = dirprefix+"_sun.txt";
std::string sunlandfile = dirprefix+"_sun_landscape.txt";
std::string wetfile = dirprefix+"_wet.txt";
std::string climfile = dirprefix+"_clim.txt";
std::string bmefile = dirprefix+"_biome.txt";
std::string catfile = dirprefix+"_plt.png";
// load terrain
currscene = 0;
getTerrain()->loadElv(terfile);
cerr << "Elevation file loaded" << endl;
scf = getTerrain()->getMaxExtent();
getView()->setForcedFocus(getTerrain()->getFocus());
getView()->setViewScale(getTerrain()->longEdgeDist());
getView()->setDim(0.0f, 0.0f, (float) this->width(), (float) this->height());
getTerrain()->calcMeanHeight();
// match dimensions for empty overlay
int dx, dy;
getTerrain()->getGridDim(dx, dy);
getTypeMap(TypeMapType::PAINT)->matchDim(dx, dy);
getTypeMap(TypeMapType::PAINT)->fill(0);
getTypeMap(TypeMapType::EMPTY)->matchDim(dx, dy);
getTypeMap(TypeMapType::EMPTY)->clear();
if(getCanopyHeightModel()->read(chmfile))
{
cerr << "CHM file loaded" << endl;
loadTypeMap(getCanopyHeightModel(), TypeMapType::CHM);
}
else
{
cerr << "No Canopy Height Model found. Simulation invalidated." << endl;
simvalid = false;
}
bool sim_densitymodel = false;
if(getCanopyDensityModel()->read(cdmfile))
{
loadTypeMap(getCanopyDensityModel(), TypeMapType::CDM);
cerr << "CDM file loaded" << endl;
}
else
{
cerr << "No Canopy Density Model found. One will be calculated from the imported canopy trees." << endl;
sim_densitymodel = true;
}
if (getBiome()->read_dataimporter(SONOMA_DB_FILEPATH))
{
if (plantvis.size() < getBiome()->numPFTypes())
plantvis.resize(getBiome()->numPFTypes());
cerr << "Biome file load" << endl;
for(int t = 0; t < getBiome()->numPFTypes(); t++)
plantvis[t] = true;
canopyvis = true;
undervis = true;
// initialize simulation
initSceneSim();
// read climate parameters
if(!getSim()->readClimate(climfile))
{
simvalid = false;
cerr << "No climate file " << climfile << " found. Simulation invalidated" << endl;
}
// read soil moisture, and if that fails simulate it and store results
if(!getSim()->readMoisture(wetfile))
{
cerr << "No Soil moisture file " << wetfile << " found, so simulating soil moisture" << endl;
getSim()->calcMoisture();
getSim()->writeMoisture(wetfile);
}
else
{
cerr << "Soil moisture file loaded" << endl;
}
wet_mth = 0;
loadTypeMap(getMoisture(wet_mth), TypeMapType::WATER);
// loading plant distribution
getEcoSys()->setBiome(getBiome());
if(!getEcoSys()->loadNichePDB(pdbfile, getTerrain()))
{
std::cerr << "Plant distribution file " << pdbfile << "does not exist" << endl; // just report but not really an issue
}
else
{
getEcoSys()->pickAllPlants(getTerrain());
std::cerr << "Plant canopy distribution file loaded" << std::endl;
}
getEcoSys()->redrawPlants();
if (sim_densitymodel)
{
std::cerr << "Computing canopy density model from imported canopy..." << std::endl;
getSim()->calcCanopyDensity(getEcoSys(), getCanopyDensityModel(), cdmfile);
std::cerr << "Done computing canopy density model" << std::endl;
}
std::string simsun_file = inclcanopy ? sunfile : sunlandfile; // if we do not include canopy, we only simulate sunlight based on landscape shadowing
// This is only applicable when running viewer with the -sun option, for sunlight sim only
std::cerr << "Looking for sunfile " << simsun_file << " (include canopy = " << inclcanopy << ")" << std::endl;
// read sunlight, and if that fails simulate it and store results
if(!getSim()->readSun(simsun_file))
{
cerr << "No Sunlight file " << simsun_file << " found, so simulating sunlight" << endl;
sim_canopy_sunlight(simsun_file);
}
else
{
cerr << "Sunlight file loaded" << endl;
}
sun_mth = 0;
loadTypeMap(getSunlight(sun_mth), TypeMapType::SUNLIGHT);
loadTypeMap(getSlope(), TypeMapType::SLOPE);
}
else
{
std::cerr << "Biome file " << bmefile << "does not exist. Simulation invalidated." << endl;
}
focuschange = false;
if(simvalid)
firstsim = true;
}
void GLWidget::saveScene(std::string dirprefix)
{
std::string terfile = dirprefix+".elv";
std::string pdbfile = dirprefix+".pdb";
// load terrain
getTerrain()->saveElv(terfile);
if(!getEcoSys()->saveNichePDB(pdbfile))
cerr << "Error GLWidget::saveScene: saving plane file " << pdbfile << " failed" << endl;
}
void GLWidget::writePaintMap(std::string paintfile)
{
getTypeMap(TypeMapType::PAINT)->saveToPaintImage(paintfile);
}
void GLWidget::addScene()
{
Scene * scene = new Scene();
scene->view->setDim(0.0f, 0.0f, (float) this->width(), (float) this->height());
plantvis.clear();
scenes.push_back(scene);
currscene = (int) scenes.size() - 1;
}
void GLWidget::setScene(int s)
{
if(s >= 0 && s < (int) scenes.size())
{
currscene = s;
getTerrain()->setBufferToDirty();
refreshOverlay();
update();
}
}
void GLWidget::loadDecals()
{
QImage decalImg, t;
// load image
if(!decalImg.load(QCoreApplication::applicationDirPath() + "/../../sim/Icons/manipDecals.png"))
cerr << QCoreApplication::applicationDirPath().toUtf8().constData() << "/../../sim/Icons/manipDecals.png" << " not found" << endl;
// Qt prep image for OpenGL
QImage fixedImage(decalImg.width(), decalImg.height(), QImage::Format_ARGB32);
QPainter painter(&fixedImage);
painter.setCompositionMode(QPainter::CompositionMode_Source);
painter.fillRect(fixedImage.rect(), Qt::transparent);
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
painter.drawImage( 0, 0, decalImg);
painter.end();
t = QGLWidget::convertToGLFormat( fixedImage );
renderer->bindDecals(t.width(), t.height(), t.bits());
decalsbound = true;
}
int GLWidget::loadTypeMap(MapFloat * map, TypeMapType purpose)
{
int numClusters = 0;
switch(purpose)
{
case TypeMapType::EMPTY:
break;
case TypeMapType::PAINT:
break;
case TypeMapType::CATEGORY:
break;
case TypeMapType::SLOPE:
numClusters = getTypeMap(purpose)->convert(map, purpose, 90.0f);
break;
case TypeMapType::WATER:
numClusters = getTypeMap(purpose)->convert(map, purpose, 100.0); // 1000.0f);
break;
case TypeMapType::SUNLIGHT:
numClusters = getTypeMap(purpose)->convert(map, purpose, 13.0f);
break;
case TypeMapType::TEMPERATURE:
numClusters = getTypeMap(purpose)->convert(map, purpose, 20.0f);
break;
case TypeMapType::CHM:
numClusters = getTypeMap(purpose)->convert(map, purpose, mtoft*initmaxt);
break;
case TypeMapType::CDM:
numClusters = getTypeMap(purpose)->convert(map, purpose, 1.0f);
break;
default:
break;
}
return numClusters;
}
void GLWidget::setMap(TypeMapType type, int mth)
{
if(type == TypeMapType::SUNLIGHT)
loadTypeMap(getSunlight(mth), type);
if(type == TypeMapType::WATER)
loadTypeMap(getMoisture(mth), type);
setOverlay(type);
}
void GLWidget::initializeGL()
{
// get context opengl-version
qDebug() << "Widget OpenGl: " << format().majorVersion() << "." << format().minorVersion();
qDebug() << "Context valid: " << context()->isValid();
qDebug() << "Really used OpenGl: " << context()->format().majorVersion() << "." <<
context()->format().minorVersion();
qDebug() << "OpenGl information: VENDOR: " << (const char*)glGetString(GL_VENDOR);
qDebug() << " RENDERDER: " << (const char*)glGetString(GL_RENDERER);
qDebug() << " VERSION: " << (const char*)glGetString(GL_VERSION);
qDebug() << " GLSL VERSION: " << (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
QGLFormat glFormat = QGLWidget::format();
if ( !glFormat.sampleBuffers() )
qWarning() << "Could not enable sample buffers";
qglClearColor(qtWhite.light());
int mu;
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &mu);
cerr << "max texture units = " << mu << endl;
// *** PM Render code - start ***
// To use basic shading: PMrender::TRenderer::BASIC
// To use radianvce scaling: PMrender::TRenderer::RADIANCE_SCALING
PMrender::TRenderer::terrainShadingModel sMod = PMrender::TRenderer::RADIANCE_SCALING;
// set terrain shading model
renderer->setTerrShadeModel(sMod);
// set up light
Vector dl = Vector(0.6f, 1.0f, 0.6f);
dl.normalize();
GLfloat pointLight[3] = { 0.5, 5.0, 7.0}; // side panel + BASIC lighting
GLfloat dirLight0[3] = { dl.i, dl.j, dl.k}; // for radiance lighting
GLfloat dirLight1[3] = { -dl.i, dl.j, -dl.k}; // for radiance lighting
renderer->setPointLight(pointLight[0],pointLight[1],pointLight[2]);
renderer->setDirectionalLight(0, dirLight0[0], dirLight0[1], dirLight0[2]);
renderer->setDirectionalLight(1, dirLight1[0], dirLight1[1], dirLight1[2]);
// initialise renderer/compile shaders
renderer->initShaders();
// set other render parameters
// can set terrain colour for radiance scaling etc - check trenderer.h
// terrain contours
renderer->drawContours(false);
renderer->drawGridlines(false);
// turn on terrain type overlay (off by default); NB you can stil call methods to update terrain type,
renderer->useTerrainTypeTexture(true);
renderer->useConstraintTypeTexture(false);
// use manipulator textures (decal'd)
renderer->textureManipulators(true);
// *** PM Render code - end ***
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_MULTISAMPLE);
glEnable(GL_DEPTH_CLAMP);
glEnable(GL_TEXTURE_2D);
loadDecals();
paintGL();
}
void GLWidget::paintGL()
{
vpPoint mo;
glm::mat4 tfm, idt;
glm::vec3 trs, rot;
uts::vector<ShapeDrawData> drawParams; // to be passed to terrain renderer
Shape shape; // geometry for focus indicator
std::vector<Shape>::iterator sit;
std::vector<glm::mat4> sinst;
std::vector<glm::vec4> cinst;
Timer t;
if(active)
{
t.start();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// note: bindinstances will not work on the first render pass because setup time is needed
if(focuschange && focusviz)
{
ShapeDrawData sdd;
float scale;
GLfloat manipCol[] = {0.325f, 0.235f, 1.0f, 1.0f};
// create shape
shape.clear();
shape.setColour(manipCol);
// place vertical cylinder at view focus
mo = getView()->getFocus();
scale = getView()->getScaleFactor();
idt = glm::mat4(1.0f);
trs = glm::vec3(mo.x, mo.y, mo.z);
rot = glm::vec3(1.0f, 0.0f, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(-90.0f), rot);
shape.genCappedCylinder(scale*armradius, 1.5f*scale*armradius, scale*(manipheight-manipradius), 40, 10, tfm, false);
if(shape.bindInstances(getView(), &sinst, &cinst)) // passing in an empty instance will lead to one being created at the origin
{
sdd = shape.getDrawParameters();
sdd.current = false;
drawParams.push_back(sdd);
}
}
// prepare plants for rendering
if(focuschange)
getEcoSys()->bindPlantsSimplified(getTerrain(), drawParams, &plantvis);
// pass in draw params for objects
renderer->setConstraintDrawParams(drawParams);
// draw terrain and plants
getTerrain()->updateBuffers(renderer);
if(focuschange)
renderer->updateTypeMapTexture(getTypeMap(getOverlay())); // only necessary if the texture is changing dynamically
renderer->draw(getView());
t.stop();
if(timeron)
cerr << "rendering = " << t.peek() << " fps = " << 1.0f / t.peek() << endl;
}
}
void GLWidget::resizeGL(int width, int height)
{
// TO DO: fix resizing
int side = qMin(width, height);
glViewport((width - side) / 2, (height - side) / 2, width, height);
// apply to all views
for(int i = 0; i < (int) scenes.size(); i++)
{
scenes[i]->view->setDim(0.0f, 0.0f, (float) this->width(), (float) this->height());
scenes[i]->view->apply();
}
}
void GLWidget::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_A) // 'A' for animated spin around center point of terrain
{
getView()->startSpin();
rtimer->start(20);
}
if(event->key() == Qt::Key_C) // 'C' to show canopy height model texture overlay
{
setOverlay(TypeMapType::CHM);
}
if(event->key() == Qt::Key_E) // 'E' to remove all texture overlays
{
setOverlay(TypeMapType::EMPTY);
}
if(event->key() == Qt::Key_F) // 'F' to toggle focus stick visibility
{
if(focusviz)
focusviz = false;
else
focusviz = true;
update();
}
if(event->key() == Qt::Key_N) // 'N' to toggle display of canopy trees on or off
{
cerr << "canopy visibility toggled" << endl;
setAllPlantsVis();
canopyvis = !canopyvis; // toggle canopy visibility
getEcoSys()->pickAllPlants(getTerrain(), canopyvis, undervis);
update();
}
if(event->key() == Qt::Key_P) // 'P' to toggle plant visibility
{
cerr << "plant visibility toggled" << endl;
setAllPlantsVis();
focuschange = !focuschange;
getEcoSys()->pickAllPlants(getTerrain(), canopyvis, undervis);
update();
}
if(event->key() == Qt::Key_R) // 'R' to show temperature texture overlay
{
setOverlay(TypeMapType::TEMPERATURE);
}
if(event->key() == Qt::Key_S) // 'S' to show sunlight texture overlay
{
sun_mth++;
if(sun_mth >= 12)
sun_mth = 0;
loadTypeMap(getSunlight(sun_mth), TypeMapType::SUNLIGHT);
setOverlay(TypeMapType::SUNLIGHT);
}
if(event->key() == Qt::Key_T) // 'T' to show slope texture overlay
{
loadTypeMap(getSlope(), TypeMapType::SLOPE);
setOverlay(TypeMapType::SLOPE);
}
if(event->key() == Qt::Key_U) // 'U' toggle undergrowth display on/off
{
setAllPlantsVis();
undervis = !undervis; // toggle canopy visibility
getEcoSys()->pickAllPlants(getTerrain(), canopyvis, undervis);
update();
}
if(event->key() == Qt::Key_V) // 'V' for top-down view
{
getTerrain()->setMidFocus();
getView()->setForcedFocus(getTerrain()->getFocus());
getView()->topdown();
update();
}
if(event->key() == Qt::Key_W) // 'W' to show water texture overlay
{
wet_mth++;
if(wet_mth >= 12)
wet_mth = 0;
loadTypeMap(getMoisture(wet_mth), TypeMapType::WATER);
setOverlay(TypeMapType::WATER);
}
// '1'-'9' make it so that only plants of that functional type are visible
if(event->key() == Qt::Key_0)
{
cerr << "KEY 0" << endl;
int p = 0;
setSinglePlantVis(p);
cerr << "single species visibility " << p << endl;
}
if(event->key() >= Qt::Key_1 && event->key() <= Qt::Key_9)
{
int p = (int) event->key() - (int) Qt::Key_1 + 1;
setSinglePlantVis(p);
cerr << "single species visibility " << p << endl;
}
if(event->key() == Qt::Key_ParenRight)
{
cerr << "KEY )" << endl;
int p = 10;
setSinglePlantVis(p);
cerr << "single species visibility " << p << endl;
}
if(event->key() == Qt::Key_Exclam)
{
cerr << "KEY !" << endl;
int p = 11;
setSinglePlantVis(p);
cerr << "single species visibility " << p << endl;
}
if(event->key() == Qt::Key_At)
{
cerr << "KEY @" << endl;
int p = 12;
setSinglePlantVis(p);
cerr << "single species visibility " << p << endl;
}
if(event->key() == Qt::Key_NumberSign)
{
cerr << "KEY #" << endl;
int p = 13;
setSinglePlantVis(p);
cerr << "single species visibility " << p << endl;
}
if(event->key() == Qt::Key_Dollar)
{
cerr << "KEY $" << endl;
int p = 14;
setSinglePlantVis(p);
cerr << "single species visibility " << p << endl;
}
if(event->key() == Qt::Key_Percent)
{
cerr << "KEY %" << endl;
int p = 15;
setSinglePlantVis(p);
cerr << "single species visibility " << p << endl;
}
if(event->key() == Qt::Key_Ampersand)
{
cerr << "KEY &" << endl;
int p = 16;
setSinglePlantVis(p);
cerr << "single species visibility " << p << endl;
}
}
void GLWidget::setAllPlantsVis()
{
for(int i = 0; i < (int) plantvis.size(); i++)
plantvis[i] = true;
}
void GLWidget::setCanopyVis(bool vis)
{
setAllPlantsVis();
canopyvis = vis; // toggle canopy visibility
getEcoSys()->pickAllPlants(getTerrain(), canopyvis, undervis);
update();
}
void GLWidget::setUndergrowthVis(bool vis)
{
setAllPlantsVis();
undervis = vis;
getEcoSys()->pickAllPlants(getTerrain(), canopyvis, undervis);
update();
}
void GLWidget::setAllSpecies(bool vis)
{
for(int i = 0; i < (int) plantvis.size(); i++)
plantvis[i] = vis;
getEcoSys()->pickAllPlants(getTerrain(), canopyvis, undervis);
update();
}
void GLWidget::setSinglePlantVis(int p)
{
if(p < (int) plantvis.size())
{
for(int i = 0; i < (int) plantvis.size(); i++)
plantvis[i] = false;
plantvis[p] = true;
getEcoSys()->pickAllPlants(getTerrain(), canopyvis, undervis);
update();
}
else
{
cerr << "non-valid pft and so unable to toggle visibility" << endl;
}
}
void GLWidget::toggleSpecies(int p, bool vis)
{
if(p < (int) plantvis.size())
{
plantvis[p] = vis;
getEcoSys()->pickAllPlants(getTerrain(), canopyvis, undervis);
update();
}
else
{
cerr << "non-valid pft and so unable to toggle visibility" << endl;
}
}
void GLWidget::run_undersim_only(int curr_run, int nyears)
{
while (datadir.back() == '/')
datadir.pop_back();
std::string out_filename = get_dirprefix() + "_undergrowth";
out_filename += std::to_string(curr_run); // + ".pdb";
std::string out_filename_over = get_dirprefix() + "_overgrowth";
out_filename_over += std::to_string(curr_run) + ".pdb";
std::string seedbank_file = get_dirprefix() + "_seedbank" + std::to_string(curr_run) + ".sdb";
std::string seedchance_file = get_dirprefix() + "_seedchance" + std::to_string(curr_run) + ".txt";
out_filename += ".pdb";
if (simvalid)
{
if(firstsim)
{
std::cout << "Importing canopy..." << std::endl;
getSim()->importCanopy(getEcoSys(), seedbank_file, seedchance_file); // transfer plants to simulation
std::cout << "Done importing canopy" << std::endl;
firstsim = false;
}
// strictly only needs to be done on the first simulation run
if (nyears > 0)
{
getSim()->simulate(getEcoSys(), seedbank_file, seedchance_file, nyears);
getSim()->exportUnderstory(getEcoSys()); // transfer plants from simulation
this->getEcoSys()->saveNichePDB(out_filename, 1);
}
else
{
std::cout << "No simulation done because specified number of years is not greater than zero" << std::endl;
}
}
}
void GLWidget::mousePressEvent(QMouseEvent *event)
{
float nx, ny;
vpPoint pnt;
int x = event->x(); int y = event->y();
float W = (float) width(); float H = (float) height();
update(); // ensure this viewport is current for unproject
// control view orientation with right mouse button or ctrl/alt modifier key and left mouse
if(!viewlock && (event->modifiers() == Qt::MetaModifier || event->modifiers() == Qt::AltModifier || event->buttons() == Qt::RightButton))
{
// arc rotate in perspective mode
// convert to [0,1] X [0,1] domain
nx = (2.0f * (float) x - W) / W;
ny = (H - 2.0f * (float) y) / H;
lastPos = event->pos();
getView()->startArcRotate(nx, ny);
viewing = true;
}
lastPos = event->pos();
}
void GLWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
// set the focus for arcball rotation
// pick point on terrain or zero plane if outside the terrain bounds
vpPoint pnt;
int sx, sy;
sx = event->x(); sy = event->y();
if(!viewlock && ((event->modifiers() == Qt::MetaModifier && event->buttons() == Qt::LeftButton) || (event->modifiers() == Qt::AltModifier && event->buttons() == Qt::LeftButton) || event->buttons() == Qt::RightButton))
{
getView()->apply();
if(getTerrain()->pick(sx, sy, getView(), pnt))
{
if(!decalsbound)
loadDecals();
vpPoint pickpnt = pnt;
getView()->setAnimFocus(pickpnt);
getTerrain()->setFocus(pickpnt);
cerr << "Pick Point = " << pickpnt.x << ", " << pickpnt.y << ", " << pickpnt.z << endl;
focuschange = true; focusviz = true;
atimer->start(10);
}
// ignores pick if terrain not intersected, should possibly provide error message to user
}
}
void GLWidget::pickInfo(int x, int y)
{
std::string catName;
cerr << endl;
cerr << "*** PICK INFO ***" << endl;
cerr << "location: " << x << ", " << y << endl;
// getSim()->pickInfo(x, y);
cerr << "Canopy Height (m): " << getCanopyHeightModel()->get(x, y) * 0.3048f << endl;
cerr << "Canopy Density: " << getCanopyDensityModel()->get(x, y) << endl;
cerr << "Sunlight: " << getSunlight(sun_mth)->get(x,y) << endl;
cerr << "Moisture: " << getMoisture(wet_mth)->get(x,y) << endl;
}
void GLWidget::mouseReleaseEvent(QMouseEvent *event)
{
viewing = false;
if(event->button() == Qt::LeftButton && cmode == ControlMode::VIEW) // info on terrain cell
{
vpPoint pnt;
int sx, sy;
sx = event->x(); sy = event->y();
if(getTerrain()->pick(sx, sy, getView(), pnt))
{
int x, y;
getTerrain()->toGrid(pnt, x, y);
pickInfo(x, y);
}
}
}
void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
float nx, ny, W, H;
int x = event->x();
int y = event->y();
W = (float) width();
H = (float) height();
// control view orientation with right mouse button or ctrl modifier key and left mouse
if(!viewlock && ((event->modifiers() == Qt::MetaModifier && event->buttons() == Qt::LeftButton) || (event->modifiers() == Qt::AltModifier && event->buttons() == Qt::LeftButton) || event->buttons() == Qt::RightButton))
{
// convert to [0,1] X [0,1] domain
nx = (2.0f * (float) x - W) / W;
ny = (H - 2.0f * (float) y) / H;
getView()->arcRotate(nx, ny);
update();
lastPos = event->pos();
}
}
void GLWidget::wheelEvent(QWheelEvent * wheel)
{
float del;
QPoint pix = wheel->pixelDelta();
QPoint deg = wheel->angleDelta();
if(!viewlock)
{
if(!pix.isNull()) // screen resolution tracking, e.g., from magic mouse
{
del = (float) pix.y() * 10.0f;
getView()->incrZoom(del);
update();
}
else if(!deg.isNull()) // mouse wheel instead
{
del = (float) deg.y() * 2.5f;
getView()->incrZoom(del);
update();
}
}
}
void GLWidget::animUpdate()
{
if(getView()->animate())
update();
}
void GLWidget::rotateUpdate()
{
if(getView()->spin())
update();
}
| 47,865
|
C++
|
.cpp
| 1,343
| 29.400596
| 221
| 0.611033
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,165
|
main_sunsim.cpp
|
jgain_EcoLearn/UnderSim/sim/main_sunsim.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "glheaders.h"
#include <QApplication>
#include <QGLFormat>
#include <QCoreApplication>
#include <QDesktopWidget>
#include <string>
#include <stdexcept>
#include <utility>
#include <memory>
#include <QTimer>
#include "window.h"
struct functor_callback
{
Window *window;
int nruns; // for now, this is obsolete: we will re-run the entire program for successive placements for different canopy placements
int run_id;
int nyears;
std::string chmfile;
std::string output_file;
void operator() ()
{
// window->run_sunsim_only(chmfile, output_file);
QCoreApplication::exit();
}
};
int main(int argc, char *argv[])
{
if (argc != 4)
{
std::cerr << "Usage: sunsim <data directory> <chm file> <output filename>" << std::endl;
return 1;
}
try
{
QApplication app(argc, argv);
std::string datadir = argv[1];
while (datadir.back() == '/')
datadir.pop_back();
std::string chmfile = argv[2];
std::string output_file = argv[3];
Window * window = new Window(datadir);
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedKingdom));
window->resize(window->sizeHint());
window->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored);
window->getView().setForcedFocus(window->getTerrain().getFocus());
// sunwindow
SunWindow * sunwindow = new SunWindow();
sunwindow->resize(window->sizeHint());
sunwindow->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored);
sunwindow->setOrthoView(window->getGLWidget());
sunwindow->getView().setForcedFocus(window->getTerrain().getFocus());
//sunwindow->show();
int desktopArea = QApplication::desktop()->width() *
QApplication::desktop()->height();
int widgetArea = window->width() * window->height();
if (((float)widgetArea / (float)desktopArea) < 0.75f)
window->show();
else
window->showMaximized();
window->setSunWindow(sunwindow);
functor_callback func;
func.window = window;
func.nruns = 1;
func.chmfile = chmfile;
func.output_file = output_file;
QTimer::singleShot(1000, func);
/*
window->run_undersim_foolproof();
return 0;
*/
int status = app.exec();
return status;
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
}
| 5,523
|
C++
|
.cpp
| 137
| 35.80292
| 137
| 0.649823
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,166
|
stroke.cpp
|
jgain_EcoLearn/UnderSim/sim/stroke.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
/* file: stroke.cpp
author: (c) James Gain, 2006
project: ScapeSketch - sketch-based design of procedural landscapes
notes: Forming 2d mouse input into strokes for sketch and gesture purposes
changes:
*/
#include "stroke.h"
#include "shape.h"
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <list>
#include <algorithm>
///
/// GENERAL PROJECTION ROUTINES
///
void planeProject(View * view, uts::vector<vpPoint> * from, uts::vector<vpPoint> * to, Plane * projPlane)
{
uts::vector<vpPoint> copy; // <from> and <to> may be the same so this requires some care
float tval;
Vector dirn;
vpPoint p, cop;
// project stroke onto plane
cop = view->getCOP();
for(int i = 0; i < (int) from->size(); i++)
{
dirn.diff(cop, (* from)[i]);
if(projPlane->rayPlaneIntersect(cop, dirn, tval))
{
dirn.mult(tval);
dirn.pntplusvec(cop, &p);
copy.push_back(p);
}
}
to->clear();
(* to) = copy;
}
// assumes <from> and <to> strokes are not the same
void screenProject(View * view, uts::vector<vpPoint> * from, uts::vector<vpPoint> * to)
{
vpPoint vcop, pcop, proj;
Vector vdir, pdir;
Plane vplane;
to->clear();
// set up projection plane
vcop = view->getCOP();
vdir = view->getDir();
vdir.mult(0.2f); // not too close for precision reasons
vdir.pntplusvec(vcop, &pcop);
vdir.normalize();
vplane.formPlane(pcop, vdir);
// apply projection
for(int i = 0; i < (int) from->size(); i++)
{
pdir.diff(vcop, (* from)[i]);
if(vplane.rayPlaneIntersect(vcop, pdir, proj))
to->push_back(proj);
}
}
void drapeProject(uts::vector<vpPoint> * from, uts::vector<vpPoint> * to, Terrain * ter)
{
int i;
uts::vector<vpPoint> copy;
vpPoint dpnt;
// drape onto the landscape
for(i = 0; i < (int) from->size(); i++)
{
ter->drapePnt((* from)[i], dpnt);
copy.push_back(dpnt); // add draped point to list
}
to->clear();
(* to) = copy;
copy.clear();
}
void dropProject(uts::vector<vpPoint> * from, uts::vector<vpPoint> * to)
{
int i;
vpPoint dpnt;
uts::vector<vpPoint> copy;
// zero y-coordinate
for(i = 0; i < (int) from->size(); i++)
{
dpnt = (* from)[i];
dpnt.y = 0.0f;
copy.push_back(dpnt); // add dropped point to list
}
to->clear();
(* to) = copy;
copy.clear();
}
bool terrainProject(uts::vector<vpPoint> * from, uts::vector<vpPoint> * to, View * view, Terrain * ter)
{
bool onterrain = false;
uts::vector<vpPoint> copy; // <from> and <to> may be the same so this requires some care
Vector dirn;
vpPoint p, cop;
// project stroke onto plane
cop = view->getCOP();
// cerr << "cop = " << cop.x << ", " << cop.y << ", " << cop.z << endl;
for(int i = 0; i < (int) from->size(); i++)
{
dirn.diff(cop, (* from)[i]);
if(ter->rayIntersect(cop, dirn, p))
{
// cerr << "from " << (* from)[i].x << ", " << (* from)[i].y << ", " << (* from)[i].z;
// cerr << " to " << p.x << ", " << p.y << ", " << p.z << endl;
copy.push_back(p);
onterrain = true;
}
}
to->clear();
(* to) = copy;
copy.clear();
return onterrain;
}
bool terrainProject(vpPoint &fromPnt, vpPoint &toPnt, View * view, Terrain * ter)
{
Vector dirn;
vpPoint p, cop;
// project stroke onto plane
cop = view->getCOP();
dirn.diff(cop, fromPnt);
if(ter->rayIntersect(cop, dirn, p))
{
toPnt = p;
return true;
}
else
{
return false;
}
}
bool testFragmentAttach(uts::vector<vpPoint> * from, uts::vector<vpPoint> * into, float diftol, bool bothends, int &inds, int &inde, float &closeness)
{
Vector sep;
vpPoint s, e;
float currmin, vals, vale, mins = 1000000.0f, mine = 1000000.0f;
bool isattached, ats, ate;
int i, rangetol;
// find closest point on <to> stroke to start and end of <from> stroke
s = from->front(); e = from->back();
for(i = 0; i < (int) into->size(); i++)
{
sep.diff((* into)[i], s);
currmin = sep.sqrdlength();
if(currmin < mins)
{
mins = currmin;
inds = i;
}
sep.diff((* into)[i], e);
currmin = sep.sqrdlength();
if(currmin < mine)
{
mine = currmin;
inde = i;
}
}
// check if these closest points are within tolerance
vals = sqrt(mins); vale = sqrt(mine);
ats = (vals < diftol);
ate = (vale < diftol);
if(!ats)
inds = -1;
if(!ate)
inde = -1;
rangetol = (int) (0.01f * (float) into->size()) + 10;
/*
cerr << "into size = " << into->size()-1 << endl;
cerr << "range tol = " << rangetol << endl;
cerr << "ats = " << ats << ", vals = " << vals << ", inds = " << inds << endl;
cerr << "ate = " << ate << ", vale = " << vale << ", inde = " << inde << endl;
*/
if(bothends)
{
isattached = ats && ate;
}
else
{
isattached = ats && ate;
if(!isattached) // also allow endpoint to endpoint
{
if(ats)
{
isattached = (inds < rangetol) || (inds > (int) into->size()-rangetol);
if(inds < rangetol)
inds = 0;
if(inds > (int) into->size()-rangetol)
inds = (int) into->size()-1;
}
if(ate)
{
isattached = (inde < rangetol) || (inde > (int) into->size()-rangetol);
if(inde < rangetol)
inde = 0;
if(inde > (int) into->size()-rangetol)
inde = (int) into->size()-1;
}
}
}
closeness = vals + vale;
return isattached;
}
bool inFill(uts::vector<vpPoint> * from, uts::vector<vpPoint> * into, float diftol, bool bothends, bool closed)
{
uts::vector<vpPoint> copy;
Vector vfrom, vinto;
vpPoint s, e;
float close;
bool ats, ate, isforward, overseam = false;
int i, inds, inde, rubstart, rubend;
if(testFragmentAttach(from, into, diftol, bothends, inds, inde, close))
{
ats = inds != -1; ate = inde != -1;
vinto.diff(into->front(), into->back());
vinto.normalize();
if(ats && ate) // replace section of curve
{
isforward = (inds < inde); // determine relative direction of <from> and <into> strokes
if(isforward)
{
rubstart = inds;
rubend = inde;
}
else
{
rubstart = inde;
rubend = inds;
}
if(closed) // specific to closed curves
overseam = ((float) (rubend - rubstart) / (float) into->size() > 0.5f); // always overwrite the smallest section of curve if it is a loop
}
else // join end to end
{
/*
// not at all robust
// determine relative direction of <from> and <into> using vectors from their start to end
vfrom.diff(from->front(), from->back());
vfrom.normalize();
isforward = (vinto.dot(vfrom) >= 0.0f);
*/
if(ats)
{
isforward = (inds != 0);
if(isforward) // two strokes are aligned so discard from inds on
{
rubstart = inds;
rubend = (int) into->size();
}
else // two strokes are misaligned so discard upto inds
{
rubstart = -1;
rubend = inds;
}
}
else
{
isforward = (inde == 0);
if(isforward) // two strokes are aligned so discard upto inde
{
rubstart = -1;
rubend = inde;
}
else // two strokes are misaligned so discard from inde on
{
rubstart = inde;
rubend = (int) into->size();
}
}
}
// interleave old curve and new curve sections into copy vector
if(overseam) // shift the seam and chop off the start and end. Can only be <true> if curve is closed.
{
for(i = rubstart; i <= rubend; i++)
copy.push_back((* into)[i]);
if(!isforward)
{
for(i = 0; i < (int) from->size(); i++)
copy.push_back((* from)[i]);
}
else
{
for(i = (int) from->size() - 1; i >= 0; i--)
copy.push_back((* from)[i]);
}
}
else // insert into an existing section of the curve
{
for(i = 0; i <= rubstart; i++)
copy.push_back((* into)[i]);
if(isforward)
{
for(i = 0; i < (int) from->size(); i++)
copy.push_back((* from)[i]);
}
else
{
for(i = (int) from->size() - 1; i >= 0; i--)
copy.push_back((* from)[i]);
}
for(i = rubend; i < (int) into->size(); i++)
copy.push_back((* into)[i]);
}
into->clear();
(* into) = copy;
return true;
}
else
return false;
}
bool locateIntersect(uts::vector<vpPoint> * strk, int &begin, int &end)
{
int i, j;
vpPoint e1[2], e2[2];
for(i = 0; i < (int) strk->size() - 2; i++)
{
e1[0] = (* strk)[i]; e1[1] = (* strk)[i+1];
for(j = i+2; j < (int) strk->size(); j++)
{
e2[0] = (* strk)[j];
if(j == (int) strk->size()-1) // wrap around
e2[1] = (* strk)[0];
else
e2[1] = (* strk)[j+1];
if(lineCrossing(e1, e2))
{
begin = i; end = j;
return true;
}
}
}
return false;
}
void excise(uts::vector<vpPoint> * strk, int begin, int end)
{
uts::vector<vpPoint>::iterator siter, eiter;
siter = strk->begin(); eiter = strk->begin();
siter += begin; eiter += (end+1);
strk->erase(siter, eiter);
// printf("excised from %d to %d, size before = %d, size after = %d", begin, end, bsize, esize);
}
///
/// ValueCurve
///
float ValueCurve::posOnSegment(int seg, float t) const
{
float sqt, h0, h1, h2, h3, v;
float p0, p1, m0, m1;
if(t < 0.0f-pluszero || t > 1.0f+pluszero || seg < 0 || seg > (int) splinerep.size() - 2)
{
// cerr << "Error ValueCurve::posOnSegment: out of bounds. t = " << t << " seg = " << seg << " out of " << (int) splinerep.size()-2 << endl;
return 0.0f;
}
else
{
sqt = (1.0f - t) * (1.0f - t);
// basis functions
h0 = (1.0f + 2.0f * t) * sqt; // (1+2t)(1-t)^2
h1 = t * sqt; // t (1-t)^2
h2 = t * t * (3.0f - 2.0f * t); // t^2 (3-2t)
h3 = t * t * (t - 1.0f); // t^2 (t-1)
// control points and tangents
p0 = splinerep[seg];
m0 = splinetan[seg];
p1 = splinerep[seg+1];
m1 = splinetan[seg+1];
// calculate point on curve
v = h0 * p0 + h1 * m0 + h2 * p1 + h3 * m1;
return v;
}
}
void ValueCurve::create(uts::vector<float> * tvals, uts::vector<float> * vvals)
{
sampling = 30; // number of samples between locators
vals = (* vvals);
params = (* tvals);
deriveCurve();
}
void ValueCurve::flatCaps()
{
if((int) splinetan.size() >= 2)
{
splinetan[0] = 0.0f;
splinetan[(int) splinetan.size() - 1] = 0.0f;
}
}
float ValueCurve::getPoint(float t) const
{
int seg;
float loct;
bool found = false;
// determine segment, using a search initially
seg = 0;
while(!found && seg < (int) params.size()-1)
{
seg++;
if(params[seg]+pluszero >= t)
{
found = true; seg--;
}
}
if(!found) // end of curve
{
loct = 1.0f;
seg = (int) params.size()-2;
}
else
{
loct = (t - params[seg]) / (params[seg+1] - params[seg]);
clamp(loct);
}
return posOnSegment(seg, loct);
}
void ValueCurve::deriveTangents()
{
float tan;
splinetan.clear();
for(int i = 0; i < (int) splinerep.size(); i++)
{
// tan = (cp[i+1] - cp[i]) / 2 + (cp[i] - cp[i-1]) / 2
// The curve is extended as piecewise constant past the ends
int a = std::max(i-1, 0);
int b = std::min(i+1, (int) splinerep.size()-1);
tan = 0.5f * (splinerep[b] - splinerep[a]);
splinetan.push_back(tan);
}
}
void ValueCurve::deriveVerts(int tnum)
{
float tsep = 1.0f / (float) tnum;
float t, v;
BoundRect lbr, hbr;
vals.clear();
deriveTangents();
for(int i = 0; i < (int) splinerep.size()-1; i++)
{
// baset = params[i]; delt = params[i+1] - params[i];
// create points within the current segment
for(t = 0.0f; t < 1.0f-pluszero; t+= tsep)
{
v = posOnSegment(i, t);
vals.push_back(v);
}
}
// add last point
v = posOnSegment((int) splinerep.size()-2, 1.0f);
vals.push_back(v);
}
void ValueCurve::deriveCurve()
{
Vector sepvec;
vpPoint p;
if((int) vals.size() > 0)
splinerep = vals;
// now recreate the vertices according to the new control points
deriveTangents();
deriveVerts(sampling);
}
///
/// BrushCurve
///
void BrushCurve::create(vpPoint start, View * view, Terrain * ter)
{
vpPoint pnt;
sampling = ter->samplingDist();
if(terrainProject(start, pnt, view, ter))
{
pnt.y = 0.0f;
vertsrep.push_back(pnt);
updateIndex = 0;
update.includePnt(pnt);
enclose.includePnt(pnt);
created = true;
}
}
bool BrushCurve::isCreated() const
{
return created;
}
void BrushCurve::addPoint(View * view, Terrain * ter, vpPoint pnt)
{
int j, nums;
vpPoint start, end, pos;
float t, len, delt;
Vector del;
uts::vector<vpPoint> newverts;
if(terrainProject(pnt, end, view, ter))
{
if(!created)
{
create(pnt, view, ter);
}
else
{
end.y = 0.0f;
start = vertsrep[(int) vertsrep.size()-1];
// update bounding boxes
update.reset();
enclose.includePnt(end);
update.includePnt(start);
update.includePnt(end);
// linearly subsample each segment
del.diff(start, end);
len = del.length();
updateIndex = (int) vertsrep.size();
if(len > sampling) // longer than expected interval between points
{
// number of subsamples
nums = (int) ceil(len / sampling);
delt = 1.0f / (float) nums;
for(j = 1; j < nums; j++) // start point already part of curve
{
t = j * delt;
pos.affinecombine(1.0f-t, start, t, end);
vertsrep.push_back(pos);
}
}
else
{
vertsrep.push_back(end);
}
}
}
}
Region BrushCurve::getBound(BoundRect &bnd, Terrain * ter, float radius)
{
int dx, dy;
Region reg;
bnd.expand(radius);
ter->getGridDim(dx, dy);
// convert to terrain coordinates
reg.x0 = (int) ter->toGrid(bnd.min.x);
if(reg.x0 < 0) reg.x0 = 0;
reg.y0 = (int) ter->toGrid(bnd.min.z);
if(reg.y0 < 0) reg.y0 = 0;
reg.x1 = (int) ter->toGrid(bnd.max.x);
if(reg.x1 > dx) reg.x1 = dx;
reg.y1 = (int) ter->toGrid(bnd.max.z);
if(reg.y1 > dy) reg.y1 = dy;
return reg;
}
Region BrushCurve::encloseBound(Terrain * ter, float radius)
{
BoundRect bnd;
bnd = enclose;
return getBound(bnd, ter, radius);
}
Region BrushCurve::updateBound(Terrain * ter, float radius)
{
BoundRect bnd;
bnd = update;
return getBound(bnd, ter, radius);
}
///
/// Curve3D
///
bool Curve3D::posOnSegment(int seg, float t, vpPoint & p) const
{
float sqt, h0, h1, h2, h3;
vpPoint p0, p1;
Vector m0, m1;
if(t < 0.0f-pluszero || t > 1.0f+pluszero || seg < 0 || seg > (int) splinerep.size() - 2)
{
cerr << "posOnSegment error: out of bounds. t = " << t << " seg = " << seg << endl;
return false;
}
else
{
sqt = (1.0f - t) * (1.0f - t);
// basis functions
h0 = (1.0f + 2.0f * t) * sqt; // (1+2t)(1-t)^2
h1 = t * sqt; // t (1-t)^2
h2 = t * t * (3.0f - 2.0f * t); // t^2 (3-2t)
h3 = t * t * (t - 1.0f); // t^2 (t-1)
// control points and tangents
p0 = splinerep[seg];
m0 = splinetan[seg];
p1 = splinerep[seg+1];
m1 = splinetan[seg+1];
// calculate point on curve
p.x = h0 * p0.x + h1 * m0.i + h2 * p1.x + h3 * m1.i;
p.y = h0 * p0.y + h1 * m0.j + h2 * p1.y + h3 * m1.j;
p.z = h0 * p0.z + h1 * m0.k + h2 * p1.z + h3 * m1.k;
return true;
}
}
void Curve3D::subsample(uts::vector<vpPoint> * strk)
{
uts::vector<vpPoint> tmp;
Vector del;
vpPoint prev, curr, pos;
float len, t, delt;
int i, j, nums;
for(i = 0; i < (int) strk->size()-1; i++)
{
prev = (* strk)[i]; curr = (* strk)[i+1]; prev.y = 0.0f; curr.y = 0.0f;
del.diff(prev, curr);
len = del.length();
if(len > 0.1f * sep) // longer than expected interval between points
{
// number of subsamples
nums = (int) ceil(len / (0.2f * sep));
delt = 1.0f / nums;
for(j = 0; j < nums; j++)
{
t = j * delt;
pos.affinecombine(1.0f-t, (* strk)[i], t, (* strk)[i+1]);
tmp.push_back(pos);
}
}
else
{
tmp.push_back((* strk)[i]);
}
}
tmp.push_back((* strk)[(int) strk->size()-1]);
strk->clear();
(* strk) = tmp;
}
bool Curve3D::create(uts::vector<vpPoint> * strk, View * view, Terrain * ter)
{
float tx, ty;
sep = ter->smoothingDist(); // separation between control point
ter->getTerrainDim(tx, ty);
farbound = (tx*tx+ty*ty)+100.0f;
sampling = ter->samplingDist();
highstep = 6;
leafstep = 25;
created = terrainProject(strk, &vertsrep, view, ter);
// for testing
/*
vertsrep.clear();
vertsrep.push_back(vpPoint(-0.3, 0.0, -0.3));
vertsrep.push_back(vpPoint(0.0, 0.0, 0.0));
vertsrep.push_back(vpPoint(0.3, 0.0, 0.3));
drapeProject(&vertsrep, &vertsrep, ter); */
if((int) vertsrep.size() > 1)
{
deriveCurve(ter, true);
// cerr << "number curve samples = " << (int) vertsrep.size() << endl;
// cerr << "sep = " << sep << ", sampling = " << sampling << endl;
drapeProject(&vertsrep, &vertsrep, ter); // project back onto landscape
}
return created;
}
bool Curve3D::nonProjCreate(uts::vector<vpPoint> * strk, Terrain * ter)
{
float tx, ty, errbnd;
int i;
sep = 5.0f * ter->smoothingDist(); // separation between control point
ter->getTerrainDim(tx, ty);
farbound = (tx*tx+ty*ty)+100.0f;
sampling = 10.0f * ter->samplingDist();
errbnd = ter->samplingDist();
highstep = 6;
leafstep = 25;
//cerr << "stroke size = " << (int) strk->size() << endl;
vertsrep = (* strk); // copy stroke directly to vertices without requiring projection
//cerr << "vertsrep size = " << (int) vertsrep.size() << endl;
if((int) vertsrep.size() > 1)
{
deriveCurve(ter, false);
//drapeProject(&vertsrep, &vertsrep, ter); // project back onto landscape
// for(int i = 0; i < (int) vertsrep.size(); i++)
// vertsrep[i].y = 0.0f;
// clamp to terrain bounds, which may be exceeded due to smoothing
for(i = 0; i < (int) vertsrep.size(); i++)
{
if(vertsrep[i].x < errbnd) vertsrep[i].x = errbnd;
if(vertsrep[i].z < errbnd) vertsrep[i].z = errbnd;
if(vertsrep[i].x > tx - errbnd) vertsrep[i].x = tx - errbnd;
if(vertsrep[i].z > ty - errbnd) vertsrep[i].z = ty - errbnd;
}
created = true;
}
else
{
created = false;
}
return created;
}
void Curve3D::recreate(Terrain * ter)
{
if((int) vertsrep.size() > 1)
{
deriveCurve(ter, true);
drapeProject(&vertsrep, &vertsrep, ter); // project back onto landscape
}
}
bool Curve3D::isCreated() const
{
return created;
}
bool Curve3D::mergeStroke(uts::vector<vpPoint> * strk, uts::vector<vpPoint> * prj, View * view, Terrain * ter, bool &merge, float tol)
{
uts::vector<vpPoint> frag, tmp;
bool pass;
// project fragment onto landscape
merge = false;
pass = terrainProject(strk, &frag, view, ter);
if(pass)
{
subsample(&frag); // introduce more vertices as needed by linear interpolation
if(inFill(&frag, &vertsrep, tol, false, false)) // merge fragment with existing curve
{
// to do - test and fix foldover and out of bound errors
deriveCurve(ter, true);
drapeProject(&vertsrep, &vertsrep, ter); // project back onto landscape
(* prj) = vertsrep;
merge = true;
}
}
return pass;
}
void Curve3D::genGL(View * view, Shape * shape, float radius)
{
shape->genCylinderCurve(vertsrep, radius, 10.0f * sampling, 10);
}
void Curve3D::adjustHeights(Terrain * ter, ValueCurve hcurve)
{
drapeProject(&vertsrep, &vertsrep, ter);
}
vpPoint Curve3D::getPoint(float t) const
{
int seg;
float segt, loct;
vpPoint pnt;
if((int) vertsrep.size() > 1)
{
// determine segment, using even subdivision of t across all segments
segt = t; clamp(segt);
segt *= (float) ((int) (vertsrep.size()-1));
seg = (int) floor(segt);
loct = segt - (float) seg; // local param within segment
// linearly interpolate vertices
pnt.x = (1.0f - loct) * vertsrep[seg].x + loct * vertsrep[seg+1].x;
pnt.y = (1.0f - loct) * vertsrep[seg].y + loct * vertsrep[seg+1].y;
pnt.z = (1.0f - loct) * vertsrep[seg].z + loct * vertsrep[seg+1].z;
}
else
{
if((int) vertsrep.size() == 1)
pnt = vertsrep[0];
else
pnt = vpPoint(0.0f, 0.0f, 0.0f);
}
return pnt;
}
void Curve3D::getSeg(float t, vpPoint &s0, vpPoint &s1)
{
int seg;
if((int) vertsrep.size() > 1)
{
seg = getSegIdx(t);
if(seg < (int) vertsrep.size() - 1)
{
s0 = vertsrep[seg]; s1 = vertsrep[seg+1];
}
else
{
s0 = vertsrep[seg]; s1 = vertsrep[seg];
}
}
}
int Curve3D::getSegIdx(float t)
{
int seg = 0;
float segt;
if((int) vertsrep.size() > 1)
{
// determine segment, using even subdivision of t across all segments
segt = t; clamp(segt);
segt *= (float) (numPoints()-1);
seg = (int) floor(segt);
}
return seg;
}
Vector Curve3D::getDirn(float t) const
{
int seg, last;
float segt;
vpPoint p0, p1;
Vector delv;
// determine segment, using even subdivision of t across all segments
if((int) vertsrep.size() > 1)
{
segt = t;
segt *= (float) ((int) (vertsrep.size()-1));
seg = (int) floor(segt);
if(seg < (int) vertsrep.size()-1)
{
p0 = vertsrep[seg];
p1 = vertsrep[seg+1];
}
else
{
last = (int) vertsrep.size()-1;
p0 = vertsrep[last-1];
p1 = vertsrep[last];
}
delv.diff(p0, p1);
delv.normalize();
}
else
{
delv = Vector(0.0f, 0.0f, 0.0f);
}
return delv;
}
void Curve3D::closest(vpPoint p, float & t, float & dist, vpPoint &cpnt, Vector &cdirn) const
{
float cdist, delt, nearfar, nfc;
vpPoint currpnt, npnt;
Vector del;
float dx, dz;
int i, j, k, vmin, vmax, lmax, bestk = 0;
dist = farbound; t = -1.0f;
if((int) vertsrep.size() > 0)
{
delt = 1.0f / (float) ((int) vertsrep.size()-1);
// find the box whose farthest point is closest
nearfar = farbound;
for(i = 0; i < (int) highsegboxes.size(); i++)
{
nfc = highsegboxes[i].farthest(p);
if(nfc < nearfar)
nearfar = nfc;
}
// only check boxes whose nearest point is closer than nearfar
for(i = 0; i < (int) highsegboxes.size(); i++)
{
if(highsegboxes[i].nearest(p) <= nearfar)
{
// update nearfar against leaf boxes
lmax = std::min(highstep*(i+1), (int) leafsegboxes.size());
// lmax = highstep*(i+1);
for(j = highstep * i; j < lmax; j++)
{
nfc = leafsegboxes[j].farthest(p);
if(nfc < nearfar)
nearfar = nfc;
}
// now check contents of leaf boxes if within nearfar
for(j = highstep * i; j < lmax; j++)
{
if(leafsegboxes[j].nearest(p) <= nearfar)
{
// find range of vertices corresponding to this segment
vmin = j * leafstep;
vmax = std::min(vmin + leafstep, (int) vertsrep.size());
// find closest point on shadow in x-z plane
for(k = vmin; k < vmax; k++)
{
currpnt = vertsrep[k];
dx = p.x - currpnt.x;
dz = p.z - currpnt.z;
cdist = dx * dx + dz * dz;
if(cdist < dist)
{
dist = cdist;
bestk = k;
}
}
}
}
}
}
/*
// slow alternative - useful for testing
// find closest point on shadow in x-z plane
for(j = 0; j < (int) vertsrep.size(); j++)
{
currpnt = vertsrep[j];
dx = p.x - currpnt.x;
dz = p.z - currpnt.z;
cdist = dx * dx + dz * dz;
if(cdist < dist)
{
dist = cdist;
bestk = j;
}
}
*/
t = delt * (float) bestk;
cpnt = vertsrep[bestk];
if(bestk < (int) vertsrep.size()-1)
{
npnt = vertsrep[bestk+1];
cdirn.diff(cpnt, npnt);
}
else
{
npnt = vertsrep[bestk-2];
cdirn.diff(npnt, cpnt);
}
cdirn.normalize();
dist = sqrt(dist);
}
}
void Curve3D::closestToRay(vpPoint cop, Vector dirn, float & t, float & dist) const
{
float cdist, delt, tval;
vpPoint currpnt;
int j, bestj = 0;
dist = farbound; t = -1.0f;
if((int) vertsrep.size() > 0)
{
delt = 1.0f / (float) ((int) vertsrep.size()-1);
// slow approach - exhaustive testing
for(j = 0; j < (int) vertsrep.size(); j++)
{
currpnt = vertsrep[j];
rayPointDist(cop, dirn, currpnt, tval, cdist);
if(cdist < dist)
{
dist = cdist;
bestj = j;
}
}
t = delt * (float) bestj;
}
}
bool Curve3D::testIntersect(Curve3D * dstcurve, uts::vector<float> &srct, uts::vector<float> &dstt)
{
int i, j, dis, die;
vpPoint pnt, c[2], x[2];
Vector dirn;
float dist, st, dt, tol, delt;
bool cross = false;
tol = 2.0f * sampling;
st = 0.0f; delt = 1.0f / (float) (numPoints()-1);
for(i = 0; i < numPoints()-1; i++)
{
// test closeness of approach
dstcurve->closest(vertsrep[i], dt, dist, pnt, dirn);
if(dist < tol) // test segment crossing
{
// test in surrounding area
getSeg(st, c[0], c[1]);
c[0].y = c[0].z; c[1].y = c[1].z;
dis = dstcurve->getSegIdx(dt-0.05f);
die = dstcurve->getSegIdx(dt+0.05f);
for(j = dis; j < die; j++)
{
x[0] = (* dstcurve->getVerts())[j];
x[1] = (* dstcurve->getVerts())[j+1];
x[0].y = x[0].z; x[1].y = x[1].z;
if(lineCrossing(c,x)) // intersection detected
{
srct.push_back(st);
dstt.push_back(dt);
cross = true;
}
}
}
st += delt;
}
return cross;
}
bool Curve3D::testSelfIntersect(uts::vector<float> &srct, uts::vector<float> &dstt)
{
int i, j, dis, die;
vpPoint c[2], x[2];
Vector dirn;
float sqdist, st, dt, tol, sqtol, delt;
bool cross = false;
tol = 2.0f * sampling; sqtol = tol*tol;
st = 0.0f; delt = 1.0f / (float) (numPoints()-1);
for(i = 0; i < numPoints()-1; i++)
{
for(j = i+10; j < numPoints()-1; j++)
{
dt = j*delt;
dirn.diff(vertsrep[i], vertsrep[j]);
sqdist = dirn.sqrdlength();
if(sqdist < sqtol) // test segment crossing
{
// test in surrounding area
getSeg(st, c[0], c[1]);
c[0].y = c[0].z; c[1].y = c[1].z;
dis = getSegIdx(dt-0.05f);
die = getSegIdx(dt+0.05f);
for(j = dis; j < die; j++)
{
x[0] = vertsrep[j];
x[1] = vertsrep[j+1];
x[0].y = x[0].z; x[1].y = x[1].z;
if(lineCrossing(c,x)) // intersection detected
{
srct.push_back(st);
dstt.push_back(dt);
cross = true;
}
}
}
}
st += delt;
}
return cross;
}
bool Curve3D::closeApproach(Curve3D * dstcurve, uts::vector<float> &srct, uts::vector<float> &dstt, float tol)
{
int i;
vpPoint spnt, dpnt;
Vector dirn;
float et[2], st, dt, dist;
bool close = false;
et[0] = 0.0f; et[1] = 1.0f;
// src endpoints
for(i = 0; i < 2; i++)
{
spnt = getPoint(et[i]);
dstcurve->closest(spnt, dt, dist, dpnt, dirn);
if(dist < tol)
{
srct.push_back(et[i]); dstt.push_back(dt); close = true;
}
}
// dst endpoints
for(i = 0; i < 2; i++)
{
dpnt = dstcurve->getPoint(et[i]);
closest(dpnt, st, dist, spnt, dirn);
if(dist < tol)
{
srct.push_back(st); dstt.push_back(et[i]); close = true;
}
}
return close;
}
void Curve3D::dragPin(float t, vpPoint tpnt, float trange)
{
Vector del, trx;
int i, vstart, vend, off;
float s;
//ValueCurve interpcurve;
off = (int) (trange * (float) numPoints());
del.diff(getPoint(t), tpnt); del.j = 0.0f; trx = del;
// ramp up to full translate
vend = getSegIdx(t); vend = std::min(numPoints()-1, vend); vstart = std::max(0, vend - off);
if(vstart == vend) // special case for first point in curve
{
trx = del;
trx.pntplusvec(vertsrep[vstart], &vertsrep[vstart]);
}
else
{
for(i = vstart; i <= vend; i++)
{
s = (float) (i - vstart) / (float) (vend - vstart);
trx = del; trx.mult(s);
trx.pntplusvec(vertsrep[i], &vertsrep[i]);
}
}
// ramp down from full translate
vstart = std::min(numPoints()-1, vend+1); vend = std::min(numPoints()-1, vstart + off);
for(i = vstart; i <= vend; i++)
{
s = 1.0f - (float) (i - vstart) / (float) (vend - vstart + 1);
trx = del; trx.mult(s);
trx.pntplusvec(vertsrep[i], &vertsrep[i]);
}
}
float Curve3D::remap(float t, bool left) const
{
int seg;
float segt, loct, val;
if((int) remapleft.size() > 0 && (int) remapright.size() > 0)
{
// determine segment, using even subdivision of t across all segments
segt = t; clamp(segt);
segt *= (float) ((int) (vertsrep.size()-1));
seg = (int) floor(segt);
loct = segt - (float) seg; // local param within segment
// linearly interpolate remap elements
if(left)
val = (1.0f - loct) * remapleft[seg] + loct * remapleft[seg+1];
else
val = (1.0f - loct) * remapright[seg] + loct * remapright[seg+1];
}
else
{
cerr << "Error Curve3D::ramp: param remap not yet created" << endl;
val = 0.0f;
}
return val;
}
void Curve3D::genParamRemap(ValueCurve * distleft, ValueCurve * distright)
{
int i, k;
float theta, kap, slen, slensq, nval, lerp, t, dleft, dright, delt, errt = 1.0f, etol = 0.01f;
uts::vector<float> newmapleft, newmapright;
Vector prevseg, nextseg, norm, orthog;
remapleft.clear(); remapright.clear();
// remap has initial arclength parametrization
delt = 1.0f / (float) ((int) vertsrep.size()-1);
for(i = 0; i < (int) vertsrep.size(); i++)
{
t = delt * (float) i;
remapleft.push_back(t); remapright.push_back(t);
}
// iteratively refine remap, until it stops changing or number of allowed iterations is exceeded
// refine left and right remappings simultaneously, to save curvature computations
k = 0;
while(errt > etol && k < 5)
{
newmapleft.clear(); newmapright.clear();
// use curvature to revise param map
newmapleft.push_back(0.0f); newmapright.push_back(0.0f);
for(i = 1; i < (int) remapleft.size()-1; i++)
{
dleft = distleft->getPoint(remapleft[i]);
dright = distright->getPoint(remapright[i]);
// calculate curvature
prevseg.diff(vertsrep[i-1], vertsrep[i]); prevseg.j = 0.0f;
nextseg.diff(vertsrep[i], vertsrep[i+1]); nextseg.j = 0.0f;
// cerr << "seg-1 = " << prevseg.i << ", " << prevseg.j << ", " << prevseg.k;
// cerr << " seg+1 = " << nextseg.i << ", " << nextseg.j << ", " << nextseg.k;
slen = nextseg.length();
// cerr << " len seg-1 = " << slen;
// slen = prevseg.length();
// cerr << " len seg+1 = " << slen;
slensq = slen * slen;
prevseg.normalize(); nextseg.normalize();
theta = acosf(prevseg.dot(nextseg));
// cerr << " theta = " << theta;
// precision issues
kap = sqrtf(2.0f * slensq * (1.0f - cosf(theta))) / slen;
/*
orthog = Vector(nextseg.i - prevseg.i, 0.0f, nextseg.k - prevseg.k);
kap = orthog.length() / nextseg.length();*/
/*
prevseg.normalize(); nextseg.normalize();
theta = acosf(prevseg.dot(nextseg));
if(theta > PI / 4.0f)
cerr << "Error large direction change" << endl;
*/
// calculate sidedness
norm.i = -1.0f * prevseg.k; norm.k = prevseg.i; // rotate by 90 degrees
if(norm.dot(nextseg) < 0.0f)
kap *= -1.0f;
// cerr << dleft << " ";
// left side of curve
// cerr << " " << kap;
if(kap <= 0.0f) // expansion or identity
{
newmapleft.push_back(newmapleft[i-1]+delt);
// cerr << " x ";
}
else if(kap < 1.0f / dleft) // contraction
{
lerp = 1.0f - kap * dleft;
newmapleft.push_back(newmapleft[i-1]+lerp*delt);
// cerr << " rc [" << kap << "]";
}
else // vanishing point
{
newmapleft.push_back(newmapleft[i-1]);
// cerr << " rv [" << kap << "]";
}
// right side of curve
kap *= -1.0f;
if(kap <= 0.0f) // expansion or identity
{
newmapright.push_back(newmapright[i-1]+delt);
}
else if(kap < 1.0f / dright) // contraction
{
lerp = 1.0f - kap * dright;
newmapright.push_back(newmapright[i-1]+lerp*delt);
// cerr << " lc [" << kap << "]";
}
else // vanishing point
{
newmapright.push_back(newmapright[i-1]);
// cerr << " lv [" << kap << "]";
}
// cerr << endl;
}
newmapleft.push_back(newmapleft[(int) newmapleft.size()-1]+delt);
newmapright.push_back(newmapright[(int) newmapright.size()-1]+delt);
cerr << endl;
// cerr << "newmapleft end = " << newmapleft[(int) newmapleft.size()-1] << endl;
// cerr << "newmapright end = " << newmapleft[(int) newmapleft.size()-1] << endl;
// normalize parameters back to [0,1]
nval = newmapleft[(int) newmapleft.size()-1];
for(i = 0; i < (int) newmapleft.size(); i++)
newmapleft[i] /= nval;
nval = newmapright[(int) newmapright.size()-1];
for(i = 0; i < (int) newmapright.size(); i++)
newmapright[i] /= nval;
// calculate param differences
errt = 0.0f;
for(i = 0; i < (int) remapleft.size(); i++)
errt += fabs(remapleft[i] - newmapleft[i]);
for(i = 0; i < (int) remapright.size(); i++)
errt += fabs(remapright[i] - newmapright[i]);
cerr << "iteration #" << k << " errt = " << errt << endl;
// newmaps become remaps
remapleft = newmapleft;
remapright = newmapright;
k++;
}
cerr << "iterations = " << k << " errt = " << errt << endl;
}
void Curve3D::redrape(Terrain * ter)
{
drapeProject(&vertsrep, &vertsrep, ter);
}
BoundRect Curve3D::boundingBox(float t0, float t1) const
{
BoundRect nbox;
vpPoint p;
int i, t0ind, t1ind;
float tincr;
if(t0 < pluszero && t1 > 1.0f-pluszero) // use cached bounding box
{
return bbox;
}
else // derive new bounding box
{
// use t values to index correct start and end of vertsrep
tincr = 1.0f / (float) vertsrep.size();
t0ind = (int) (t0 * tincr);
t1ind = (int) (t1 * tincr) + 1;
for(i = t0ind; i <= t1ind; i++)
{
p = vertsrep[i];
nbox.includePnt(p);
}
return nbox;
}
}
void Curve3D::deriveTangents()
{
Vector tan1, tan2;
splinetan.clear();
for(int i = 0; i < (int) splinerep.size(); i++)
{
// first and last cp are special cases
if(i == 0)
{
tan1.diff(splinerep[i], splinerep[i+1]);
tan1.mult(0.5f);
splinetan.push_back(tan1);
}
else if(i == (int) splinerep.size()-1)
{
tan2.diff(splinerep[i-1], splinerep[i]);
tan2.mult(0.5f);
splinetan.push_back(tan2);
}
else
{
// tan = (cp[i+1] - cp[i]) / 2 + (cp[i] - cp[i-1]) / 2
tan1.diff(splinerep[i], splinerep[i+1]);
tan1.mult(0.5f);
tan2.diff(splinerep[i-1], splinerep[i]);
tan2.mult(0.5f);
tan1.add(tan2);
splinetan.push_back(tan1);
}
}
}
void Curve3D::deriveVerts(bool extend)
{
int i;
float dsep = 0.025f;
float t;
vpPoint p;
BoundRect lbr, hbr;
uts::vector<vpPoint> denserep;
// create a densely sampled representation of the curve
for(int i = 0; i < (int) splinerep.size()-1; i++)
{
// create points within the current segment
for(t = 0.0f; t < 1.0f-pluszero; t+= dsep)
{
posOnSegment(i, t, p);
denserep.push_back(p);
}
}
// add last point
posOnSegment((int) splinerep.size()-2, 1.0f, p);
denserep.push_back(p);
// reparametrize according to a set distance between points, to provide an arc length parametrization
reparametrize(&denserep, &vertsrep, sampling, extend);
// build bounding box and hierarchical bounding volume
leafsegboxes.clear(); highsegboxes.clear();
bbox.reset();
for(i = 0; i < (int) vertsrep.size(); i++)
{
p = vertsrep[i];
bbox.includePnt(p); hbr.includePnt(p); lbr.includePnt(p);
if(i != 0 && i % leafstep == 0)
{
if((i / leafstep) % highstep == 0)
{
highsegboxes.push_back(hbr);
hbr.reset();
hbr.includePnt(p); // new box start where the previous ended
}
leafsegboxes.push_back(lbr);
lbr.reset();
lbr.includePnt(p); // new box start where the previous ended
}
}
// push final hbv boxes if they have not already been pushed
if(!hbr.empty())
highsegboxes.push_back(hbr);
if(!lbr.empty())
leafsegboxes.push_back(lbr);
/*
cerr << "num segments = " << (int) splinerep.size()-1 << endl;
cerr << "num verts = " << (int) vertsrep.size() << endl;
cerr << "num high segment boxes = " << (int) highsegboxes.size() << endl;
cerr << "num leaf segment boxes = " << (int) leafsegboxes.size() << endl;
for(i = 0; i < (int) highsegboxes.size(); i++)
{
cerr << "HIGH SEG BOX " << i << endl;
cerr << "min = (" << highsegboxes[i].min.x << ", " << highsegboxes[i].min.z << ")" << endl;
cerr << "max = (" << highsegboxes[i].max.x << ", " << highsegboxes[i].max.z << ")" << endl;
}
for(i = 0; i < (int) leafsegboxes.size(); i++)
{
cerr << "LEAF SEG BOX " << i << endl;
cerr << "min = (" << leafsegboxes[i].min.x << ", " << leafsegboxes[i].min.z << ")" << endl;
cerr << "max = (" << leafsegboxes[i].max.x << ", " << leafsegboxes[i].max.z << ")" << endl;
}
// cerr << "curve bbox derived" << endl;
// cerr << bbox.minx << ", " << bbox.minz << " -> " << bbox.maxx << ", " << bbox.maxz << endl;
*/
/*
cerr << "VERTS" << endl;
p = vertsrep[(int) vertsrep.size() -2];
cerr << "pen = " << p.x << ", " << p.y << ", " << p.z << endl;
p = vertsrep[(int) vertsrep.size() -1];
cerr << "end = " << p.x << ", " << p.y << ", " << p.z << endl;*/
}
vpPoint Curve3D::circSegIntersect(vpPoint c, float r, vpPoint f1, vpPoint f2)
{
vpPoint p, i1, i2, s1, s2;
float dx, dy, drsq, det, com, comsq, sgn;
Vector sepvec, segvec;
// intersection of segment with circle whose radius is seglen
// guaranteed to have one solution
s1 = vpPoint(f1.x - c.x, 0.0f, f1.z - c.z);
s2 = vpPoint(f2.x - c.x, 0.0f, f2.z - c.z);
dx = s2.x - s1.x;
dy = s2.z - s1.z;
drsq = dx*dx + dy*dy;
det = s1.x * s2.z - s2.x * s1.z;
comsq = (r*r*drsq-det*det);
if(comsq <= 0.0f)
{
cerr << "no intersection in Curve3D::reparametrize" << endl;
p = f2;
}
else
{
com = sqrt(comsq);
if(dy < 0.0f)
sgn = -1.0f;
else
sgn = 1.0f;
i1.x = (det * dy + sgn * dx * com) / drsq + c.x;
i1.y = 0.0f;
i1.z = (-1.0f * det * dx + fabs(dy) * com) / drsq + c.z;
i2.x = (det * dy - sgn * dx * com) / drsq + c.x;
i2.y = 0.0f;
i2.z = (-1.0f * det * dx - fabs(dy) * com) / drsq + c.z;
/*
cerr << "seglen = " << seglen << ", seplen = " << seplen << endl;
cerr << "i1 = " << i1.x << ", " << i1.z << endl;
cerr << "i2 = " << i2.x << ", " << i2.z << endl;
cerr << "f = " << f.x << ", " << f.z << endl;
cerr << "f1 = " << f1.x << ", " << f1.z << endl;
cerr << "f2 = " << f2.x << ", " << f2.z << endl;
*/
// choose correct intersection
sepvec.diff(c, i1); sepvec.normalize();
segvec.diff(f1, f2); segvec.normalize();
// cerr << "dotprod = " << sepvec.dot(segvec) << endl;
if(sepvec.dot(segvec) >= 0.0f)
p = i1;
else
p = i2;
}
return p;
}
void Curve3D::reparametrize(uts::vector<vpPoint> * in, uts::vector<vpPoint> * out, float vsep, bool extend)
{
Vector sepvec, segvec;
vpPoint p, p1, p2, f, f1, f2;
float arclen = 0.0f, seglen, seplen;
int i, numseg;
out->clear();
if((int) in->size() >= 2)
{
// determine current arc length of polyline
for(i = 1; i < (int) in->size(); i++)
{
p1 = (* in)[i-1]; p1.y = 0.0f; p2 = (* in)[i]; p2.y = 0.0f;
sepvec.diff(p1, p2);
arclen += sepvec.length();
}
// divide polyline into sections of vsep length or less
numseg = (int) ceil(arclen / vsep);
seglen = arclen / (float) numseg;
p = (* in)[0]; out->push_back(p); // cp at start of curve
for(i = 1; i < (int) in->size(); i++)
{
f = p; f.y = 0.0f;
p1 = (* in)[i-1]; f1 = p1; f1.y = 0.0f;
p2 = (* in)[i]; f2 = p2; f2.y = 0.0f;
sepvec.diff(f, f2); seplen = sepvec.length();
while(seplen >= seglen) // place point on this segment
{
p = circSegIntersect(f, seglen, f1, f2);
out->push_back(p);
// possibly further subdivision of this segment required
f = p; f.y = 0.0f; p1 = p; f1 = f;
sepvec.diff(f, f2); seplen = sepvec.length();
}
}
// extrapolate final cp to ensure segment is of correct length
if(extend)
p = circSegIntersect(f, seglen, f1, f2);
else
p = (* in)[(int) in->size()-1];
out->push_back(p); // cp at end of curve
// test segment lengths and report any that diverge from the ideal
for(i = 0; i < (int) out->size()-1; i++)
{
f1 = (* out)[i]; f1.y = 0.0f; f2 = (* out)[i+1]; f2.y = 0.0f;
sepvec.diff(f1, f2);
seplen = sepvec.length();
if(extend)
if(fabs(seplen - seglen) > 0.001f)
{
cerr << "seg " << i+1 << " of " << (int) out->size()-1 << " has len = " << seplen << " instead of " << seglen << endl;
}
}
}
}
void Curve3D::deriveCurve(Terrain * ter, bool extend)
{
if((int) vertsrep.size() > 1)
{
reparametrize(&vertsrep, &splinerep, sep, extend);
drapeProject(&splinerep, &splinerep, ter); // project cp back onto landscape
deriveTangents();
deriveVerts(extend);
}
}
///
/// BrushStroke
///
vpPoint BrushStroke::addMousePnt(View * view, Terrain * ter, int x, int y)
{
vpPoint pnt;
view->projectingPoint(x, y, pnt);
fragment.push_back(pnt);
shadow.addPoint(view, ter, pnt);
return pnt;
}
void BrushStroke::clearFragment()
{
fragment.clear();
shadow.clear();
}
///
/// Fragment
///
vpPoint Fragment::addMousePnt(View * view, int x, int y)
{
vpPoint pnt, ppnt, mpnt;
Vector dirn;
view->projectingRay(x, y, pnt, dirn);
dirn.mult(200.0f);
dirn.pntplusvec(pnt, &ppnt);
// push along projecting ray into scene
frag.push_back(ppnt);
view->inscreenPoint(x, y, mpnt);
mouse.push_back(mpnt);
return pnt;
}
void Fragment::genGL(View * view, Shape * s)
{
float w = 0.2f;
float col[4] = {0.325f, 0.235f, 1.0f, 1.0f};
s->setColour(col);
s->genCurve(frag, view, w, 0.5f, false, false, false);
}
bool Fragment::degenerate()
{
return ((int) frag.size() <= 2);
}
bool Fragment::testLoop(float tol)
{
Vector sep;
bool isclosed;
sep.diff(frag.front(), frag.back());
isclosed = (sep.length() < tol);
return isclosed;
}
void Fragment::screenBounds(uts::vector<vpPoint> * strk)
{
screenMin = vpPoint(10000000.0f, 10000000.0f, 0.0f);
screenMax = vpPoint(-10000000.0f, -10000000.0f, 0.0f);
for(int i = 0; i < (int) strk->size(); i++)
{
if((* strk)[i].x < screenMin.x)
screenMin.x = (* strk)[i].x;
if((* strk)[i].x > screenMax.x)
screenMax.x = (* strk)[i].x;
if((* strk)[i].y < screenMin.y)
screenMin.y = (* strk)[i].y;
if((* strk)[i].y > screenMax.y)
screenMax.y = (* strk)[i].y;
}
}
float Fragment::screenDiag()
{
Vector diag;
screenBounds(&frag);
diag.diff(screenMin, screenMax);
return diag.length();
}
///
/// Stroke
///
/*
bool Stroke::crossing(Stroke *cross, int thresh)
{
bool xoverlap, yoverlap;
int i, j, numcrossings = 0;
vpPoint c[2], x[2];
uts::vector<vpPoint> scratch;
// naive O(n^2) test of each segment against all segments in the crossing stroke
// but does use inscreen bounding boxes for acceleration
// project and bound strokes in the current screen as necessary
if(!isinscreen)
setProximity();
if(!cross->isinscreen)
{
// form bounding box in screen space
screenProject(&currview, &cross->fragment, &scratch);
cross->screenBounds(&scratch);
cross->isinscreen = false;
}
// check for overlap in x
xoverlap = true;
if(screenMin.x < cross->screenMin.x)
{
if(cross->screenMin.x > screenMax.x)
xoverlap = false;
}
else
{
if(screenMin.x > cross->screenMax.x)
xoverlap = false;
}
yoverlap = true;
// check for overlap in y
if(screenMin.y < cross->screenMin.y)
{
if(cross->screenMin.y > screenMax.y)
yoverlap = false;
}
else
{
if(screenMin.y > cross->screenMax.y)
yoverlap = false;
}
//xoverlap = ((cross->screenMin.x > screenMin.x && cross->screenMin.x < screenMax.x)
// || (cross->screenMax.x > screenMin.x && cross->screenMax.x < screenMax.x)); // overlap in x
//yoverlap = ((cross->screenMin.y > screenMin.y && cross->screenMin.y < screenMax.y)
// || (cross->screenMax.y > screenMin.y && cross->screenMax.y < screenMax.y)); // overlap in y
if(xoverlap && yoverlap)
{
// test every part of the two strokes against each other
for(i = 0; i < (int) scratch.size()-1; i++)
{
c[0] = scratch[i]; c[1] = scratch[i+1];
for(j = 0; j < (int) inscreen.size()-1; j++)
{
x[0] = inscreen[j]; x[1] = inscreen[j+1];
if(lineCrossing(c, x)) // intersection detected
numcrossings++;
}
}
}
return(numcrossings >= thresh);
}
*/
void Stroke::screenBounds(uts::vector<vpPoint> * strk)
{
screenMin = vpPoint(10000000.0f, 10000000.0f, 0.0f);
screenMax = vpPoint(-10000000.0f, -10000000.0f, 0.0f);
for(int i = 0; i < (int) strk->size(); i++)
{
if((* strk)[i].x < screenMin.x)
screenMin.x = (* strk)[i].x;
if((* strk)[i].x > screenMax.x)
screenMax.x = (* strk)[i].x;
if((* strk)[i].y < screenMin.y)
screenMin.y = (* strk)[i].y;
if((* strk)[i].y > screenMax.y)
screenMax.y = (* strk)[i].y;
}
}
bool Stroke::hasCurve() const
{
return shadow.isCreated();
}
void Stroke::setProximity()
{
// project stroke onto the current screen
// printf("projected stroke size = %d\n", (int) projected.size());
screenProject(&currview, shadow.getVerts(), &inscreen);
// form bounding box in screen space
screenBounds(&inscreen);
isinscreen = true;
}
void Stroke::genGL(View * view, Shape * s, float radius)
{
if(hasCurve())
shadow.genGL(view, s, radius);
}
bool Stroke::mergeShadow(View * view, Terrain * ter, Fragment * frag, bool & mrg, float tol, bool brushstroke)
{
bool pass;
mrg = false;
if(brushstroke)
shadow.clear();
// check to see that fragment has more than one point
if((int) frag->getFragVec()->size() == 0)
{
// cerr << "Error Stroke::mergeShadow: stroke is empty" << endl;
return false;
}
if((int) frag->getFragVec()->size() <= 2)
{
if(!brushstroke)
{
// cerr << "Error Stroke::mergeShadow: too few mouse points in stroke" << endl;
return false;
}
else // special cases for brush strokes
{
pass = shadow.create(frag->getFragVec(), view, ter);
return pass;
}
}
if(!shadow.isCreated()) // new stroke so shadow not created yet
{
pass = shadow.create(frag->getFragVec(), view, ter);
if(!brushstroke)
frag->clear();
}
else // otherwise merge into existing stroke
{
// project stroke onto the current screen
screenProject(&currview, &projected, &inscreen);
pass = shadow.mergeStroke(frag->getFragVec(), &projected, view, ter, mrg, tol);
}
return pass;
}
void Stroke::adjustHeights(Terrain * ter, ValueCurve hcurve)
{
if(hasCurve())
shadow.adjustHeights(ter, hcurve);
}
void Stroke::redrape(Terrain * ter)
{
if(hasCurve())
shadow.redrape(ter);
}
vpPoint Stroke::getPoint(float t) const
{
float ct;
if(hasCurve())
{
ct = t;
clamp(ct);
return shadow.getPoint(ct);
}
else
return vpPoint(0.0f, 0.0f, 0.0f);
}
float Stroke::getAngle(float t) const
{
Vector delv;
delv = getDirn(t);
return -1.0f * RAD2DEG * atan2(delv.k, delv.i);
}
Vector Stroke::getDirn(float t) const
{
Vector delv;
vpPoint p, delp;
float ct;
ct = t;
clamp(ct);
if(hasCurve())
{
delv = shadow.getDirn(ct);
/*
p = shadow->getPoint(ct);
if(ct >= 0.98f)
{
delp = shadow->getPoint(ct-0.02f);
delv.diff(delp, p);
}
else
{
delp = shadow->getPoint(ct+0.02f);
delv.diff(p, delp);
}
delv.normalize();*/
return delv;
}
else
return Vector(0.0f, 0.0f, 0.0f);
}
void Stroke::closestToPnt(vpPoint p, float & t, float & dist) const
{
Vector sdirn, pdirn, norm;
vpPoint sp, pp;
if(hasCurve())
{
shadow.closest(p, t, dist, sp, sdirn);
/*
if(fabs(sdirn.i) <= pluszero && fabs(sdirn.j) <= pluszero && fabs(sdirn.k) <= pluszero)
{
cerr << "Error Stroke::closest: zero dirn vector" << endl;
cerr << "p = " << p.x << ", " << p.y << ", " << p.z << endl;
cerr << "t = " << t << endl;
cerr << "sdirn = " << sdirn.i << ", " << sdirn.j << ", " << sdirn.k << endl;
}*/
norm.i = -1.0f * sdirn.k; norm.j = 0.0f; norm.k = sdirn.i; // rotate by 90 degrees
if(fabsf(norm.i) < pluszero && fabsf(norm.k) < pluszero)
cerr << "error (Stroke::closest): degenerate direction vector" << endl;
norm.normalize();
sp.y = 0.0f;
pp = p; pp.y = 0.0f;
pdirn.diff(sp, pp); // from stroke point to query point
pdirn.normalize();
if(norm.dot(pdirn) >= 0.0f) // right-sided pnt
dist *= -1.0f;
}
else
{
t = -1.0f;
dist = 0.0f;
}
}
void Stroke::closestToRay(vpPoint cop, Vector dirn, float & t, float & dist) const
{
if(hasCurve())
{
shadow.closestToRay(cop, dirn, t, dist);
}
else
{
t = -1.0f;
dist = 0.0f;
}
}
BoundRect Stroke::boundingBox(float t0, float t1) const
{
BoundRect cb;
if(hasCurve())
return shadow.boundingBox(t0, t1);
else
{
// cerr << "Error (Stroke::boundingBox): curve not properly intialized" << endl;
cb.min = vpPoint(0.0f, 0.0f, 0.0f);
cb.max = vpPoint(0.0f, 0.0f, 0.0f);
return cb;
}
}
void Stroke::printEndpoints()
{
vpPoint pnt;
pnt = getPoint(0.0f);
cerr << "start = " << pnt.x << ", " << pnt.y << ", " << pnt.z << endl;
pnt = getPoint(1.0f);
cerr << "end = " << pnt.x << ", " << pnt.y << ", " << pnt.z << endl;
}
| 57,881
|
C++
|
.cpp
| 1,810
| 23.903315
| 153
| 0.511662
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,168
|
typemap.cpp
|
jgain_EcoLearn/UnderSim/sim/typemap.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
//
// TypeMap
//
#include "typemap.h"
#include "vecpnt.h"
#include "grass.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <time.h>
#include <QFileInfo>
#include <QLabel>
/*
Perceptually uniform colourmaps from:
http://peterkovesi.com/projects/colourmaps/
*/
using namespace std;
// Sonoma County Colours
float hardwood[] = {0.749f, 0.815f, 0.611f, 1.0f};
float conifer[] = {0.812f, 0.789f, 0.55f, 1.0f};
float mixed[] = {0.552f, 0.662f, 0.533f, 1.0f};
float riparian[] = {0.4f, 0.6f, 0.6f, 1.0f};
float nonnative[] = {0.7, 0.6, 0.4, 1.0f};
float sliver[] = {0.652f, 0.762f, 0.633f, 1.0f};
float shrubery[] = {0.882f, 0.843f, 0.713f, 1.0f};
float ripshrub[] = {0.509f, 0.67f, 0.584f, 1.0f};
float herb[] = {0.75f, 0.7f, 0.7f, 1.0f};
float herbwet[] = {0.623f, 0.741f, 0.825f, 1.0f};
float aquatic[] = {0.537f, 0.623f, 0.752f, 1.0f};
float salt[] = {0.727f, 0.763f, 0.534f, 1.0f};
float barrenland[] = {0.818f, 0.801f, 0.723f, 1.0f};
float agriculture[] = {0.894f, 0.913f, 0.639f, 1.0f};
float wet[] = {0.737f, 0.823f, 0.952f, 1.0f};
float developed[] = {0.5f, 0.4f, 0.5f, 1.0f};
// palette colours
float freecol[] = {0.755f, 0.645f, 0.538f, 1.0f};
float sparseshrub[] = {0.814f, 0.853f, 0.969f, 1.0f};
float sparsemed[] = {0.727f, 0.763f, 0.834f, 1.0f};
float sparsetall[] = {0.537f, 0.623f, 0.752f, 1.0f};
float denseshrub[] = {0.749f, 0.815f, 0.611f, 1.0f};
float densemed[] = {0.552f, 0.662f, 0.533f, 1.0f};
float densetall[] = {0.300f, 0.515f, 0.1f, 1.0f};
// default colours
float barren[] = {0.818f, 0.801f, 0.723f, 1.0f}; // 1
float ravine[] = {0.755f, 0.645f, 0.538f, 1.0f}; // 2
float canyon[] = {0.771f, 0.431f, 0.351f, 1.0f}; // 3
float grassland[] = {0.552f, 0.662f, 0.533f, 1.0f}; // 4
float pasture[] = {0.894f, 0.913f, 0.639f, 1.0f}; // 5
float foldhills[] = {0.727f, 0.763f, 0.534f, 1.0f}; // 6
float orchard[] = {0.749f, 0.815f, 0.611f, 1.0f}; // 7
float evergreenforest[] = {0.300f, 0.515f, 0.0f, 1.0f}; // 8
float otherforest[] = {0.552f, 0.662f, 0.533f, 1.0f}; // 9
float woodywetland[] = {0.509f, 0.67f, 0.584f, 1.0f}; // 10
float herbwetland[] = {0.623f, 0.741f, 0.825f, 1.0f}; // 11
float frillbank[] = {0.4f, 0.6f, 0.6f, 1.0f}; // 12
float shrub[] = {0.882f, 0.843f, 0.713f, 1.0f}; // 13
float flatinterest[] = {0.812f, 0.789f, 0.55f, 1.0f}; // 14
float water[] = {0.737f, 0.823f, 0.952f, 1.0f}; // 15
float special[] = {0.4f, 0.4f, 0.4f, 1.0f}; // 16
float extra[] = {0.5f, 0.4f, 0.5f, 1.0f}; // 17
float realwater[] = {0.537f, 0.623f, 0.752f, 1.0f}; // 18
float boulders[] = {0.671f, 0.331f, 0.221f, 1.0f}; // 19
TypeMap::TypeMap(TypeMapType purpose)
{
tmap = new MemMap<int>;
setPurpose(purpose);
}
TypeMap::TypeMap(int w, int h, TypeMapType purpose)
{
tmap = new MemMap<int>;
matchDim(w, h);
setPurpose(purpose);
}
TypeMap::~TypeMap()
{
delete tmap;
for(int i = 0; i < (int) colmap.size(); i++)
delete [] colmap[i];
colmap.clear();
}
void TypeMap::clear()
{
tmap->fill(0);
}
void TypeMap::initPaletteColTable()
{
GLfloat *col;
for(int i = 0; i < 32; i++) // set all colours in table to black initially
{
col = new GLfloat[4];
col[0] = col[1] = col[2] = 0.0f; col[3] = 1.0f;
colmap.push_back(col);
}
numSamples = 7;
colmap[0] = freecol;
colmap[1] = sparseshrub;
colmap[2] = sparsemed;
colmap[3] = sparsetall;
colmap[4] = denseshrub;
colmap[5] = densemed;
colmap[6] = densetall;
}
void TypeMap::initCategoryColTable()
{
GLfloat *col;
for(int i = 0; i < 32; i++) // set all colours in table to black initially
{
col = new GLfloat[4];
col[0] = col[1] = col[2] = 0.0f; col[3] = 1.0f;
colmap.push_back(col);
}
// entry 0 is reserved as transparent
numSamples = 16;
colmap[1] = hardwood;
colmap[2] = conifer;
colmap[3] = mixed;
colmap[4] = riparian;
colmap[5] = nonnative;
colmap[6] = sliver;
colmap[7] = shrubery;
colmap[8] = ripshrub;
colmap[9] = herb;
colmap[10] = herbwet;
colmap[11] = aquatic;
colmap[12] = salt;
colmap[13] = barrenland;
colmap[14] = agriculture;
colmap[15] = wet;
colmap[16] = developed;
}
void TypeMap::initNaturalColTable()
{
GLfloat *col;
for(int i = 0; i < 32; i++) // set all colours in table to black initially
{
col = new GLfloat[4];
col[0] = col[1] = col[2] = 0.0f; col[3] = 1.0f;
colmap.push_back(col);
}
// saturated prime colours and combos
/*
(colmap[1])[0] = 1.0f; // red
(colmap[2])[1] = 1.0f; // green
(colmap[3])[2] = 1.0f; // blue
(colmap[4])[1] = 1.0f; (colmap[4])[2] = 1.0f; // cyan
(colmap[5])[0] = 1.0f; (colmap[5])[1] = 1.0f; // yellow
(colmap[6])[0] = 1.0f; (colmap[6])[2] = 1.0f; // magenta
(colmap[7])[0] = 0.5f; (colmap[7])[1] = 0.5f; (colmap[7])[2] = 0.5f; // grey
(colmap[8])[1] = 0.5f; (colmap[8])[2] = 0.5f; // teal
*/
numSamples = 20;
// default
//colmap[0] = c0;
colmap[1] = barren;
colmap[2] = ravine;
colmap[3] = canyon;
colmap[4] = grassland;
colmap[5] = pasture;
colmap[6] = foldhills;
colmap[7] = orchard;
colmap[8] = woodywetland;
colmap[9] = otherforest;
colmap[10] = woodywetland;
colmap[11] = herbwetland;
colmap[12] = frillbank;
colmap[13] = shrub;
colmap[14] = flatinterest;
colmap[15] = water;
colmap[16] = special;
colmap[17] = extra;
colmap[18] = realwater;
colmap[19] = boulders;
}
void TypeMap::initPerceptualColTable(std::string colmapfile, int samples, float truncend)
{
GLfloat *col;
float r[256], g[256], b[256];
ifstream infile;
string valstr, line;
int i, pos, step;
if(samples < 3 || samples > 32)
cerr << "Error: sampling of colour map must be in the range [3,32]" << endl;
for(i = 0; i < 32; i++) // set all colours in table to black initially
{
col = new GLfloat[4];
col[0] = col[1] = col[2] = 0.0f; col[3] = 1.0f;
colmap.push_back(col);
}
// input is a csv file, with 256 RGB entries, one on each line
// note that this is not robust to format errors in the input file
infile.open((char *) colmapfile.c_str(), ios_base::in);
if(infile.is_open())
{
i = 0;
while(std::getline(infile, line))
{
std::size_t prev = 0, pos;
// red component
pos = line.find_first_of(",", prev);
valstr = line.substr(prev, pos-prev);
istringstream isr(valstr);
isr >> r[i];
prev = pos+1;
// green component
pos = line.find_first_of(",", prev);
valstr = line.substr(prev, pos-prev);
istringstream isg(valstr);
isg >> g[i];
prev = pos+1;
// blue component
valstr = line.substr(prev, std::string::npos);
istringstream isb(valstr);
isb >> b[i];
i++;
}
infile.close();
}
// now sample the colour map at even intervals according to the number of samples
// first and last samples map to the beginning and end of the scale
step = (int) ((256.0f * truncend) / (float) (samples-1));
pos = 0;
for(i = 1; i <= samples; i++)
{
colmap[i][0] = (GLfloat) r[pos]; colmap[i][1] = (GLfloat) g[pos]; colmap[i][2] = (GLfloat) b[pos];
pos += step;
}
numSamples = samples+1;
}
void TypeMap::clipRegion(Region ®)
{
if(reg.x0 < 0) reg.x0 = 0;
if(reg.y0 < 0) reg.y0 = 0;
if(reg.x1 > width()) reg.x1 = width();
if(reg.y1 > height()) reg.y1 = height();
}
void TypeMap::matchDim(int w, int h)
{
int mx, my;
mx = tmap->width();
my = tmap->height();
// if dimensions don't match then reallocate
if(w != mx || h != my)
{
dirtyreg = Region(0, 0, w, h);
tmap->allocate(Region(0, 0, w, h));
tmap->fill(0); // set to empty type
}
}
void TypeMap::replaceMap(MemMap<int> * newmap)
{
assert(tmap->width() == newmap->width());
assert(tmap->height() == newmap->height());
for (int y = 0; y < tmap->height(); y++)
for (int x = 0; x < tmap->width(); x++)
(* tmap)[y][x] = (* newmap)[y][x];
}
void TypeMap::bandCHMMap(MapFloat * chm, float mint, float maxt)
{
int tp;
float val;
if(maxt > mint)
{
for (int x = 0; x < tmap->width(); x++)
for (int y = 0; y < tmap->height(); y++)
{
val = chm->get(y, x);
// discretise into ranges of height values
if(val <= 0.0f) // transparent
{
tp = 1;
}
else if(val <= mint) // black
{
tp = 2;
}
else if(val >= maxt) // red
{
tp = numSamples+2;
}
else // green range
{
tp = (int) ((val-mint) / (maxt-mint+pluszero) * (numSamples-1))+2;
}
(* tmap)[y][x] = tp;
}
}
}
int TypeMap::load(const uts::string &filename, TypeMapType purpose)
{
MemMap<mask_tag> mask;
int tp, maxtp = 0; // mintp = 100;
int width, height;
ifstream infile;
float val, maxval = 0.0f, range;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> width >> height;
// cerr << "width = " << width << " height = " << height << endl;
matchDim(width, height);
// convert to internal type map format
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
switch(purpose)
{
case TypeMapType::EMPTY: // do nothing
break;
case TypeMapType::PAINT:
infile >> tp;
break;
case TypeMapType::CATEGORY:
infile >> tp;
tp++;
break;
case TypeMapType::SLOPE:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of slope values
range = 90.0f; // maximum slope is 90 degrees
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::WATER:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of water values
range = 100.0f;
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::SUNLIGHT:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
range = 12.0f; // hours of sunlight
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::TEMPERATURE:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of temperature values
range = 20.0f; //10
// clamp values to range, temperature is bidrectional
if(val < -range) val = -range;
if(val > range) val = range;
tp = (int) ((val+range) / (2.0f*range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::CHM:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of height values
range = 75.0f; // maximum tree height in feet
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::CDM:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
range = 1.0f; // maximum density
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::SUITABILITY:
break;
default:
break;
}
(* tmap)[y][x] = tp;
if(tp > maxtp)
maxtp = tp;
/*
if(tp < mintp)
mintp = tp;
*/
}
}
infile.close();
// cerr << "maxtp = " << maxtp << endl;
// cerr << "mintp = " << mintp << endl;
}
else
{
cerr << "Error TypeMap::loadTxt: unable to open file" << filename << endl;
}
return maxtp;
}
bool TypeMap::loadCategoryImage(const uts::string &filename)
{
int width, height;
QImage img(QString::fromStdString(filename)); // load image from file
QFileInfo check_file(QString::fromStdString(filename));
if(!(check_file.exists() && check_file.isFile()))
return false;
// set internal storage dimensions
width = img.width();
height = img.height();
matchDim(width, height);
// convert to internal type map format
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
{
QColor col = img.pixelColor(x, y);
int r, g, b;
col.getRgb(&r, &g, &b); // all channels store the same info so just use red
(* tmap)[y][x] = r - 100; // convert greyscale colour to category index
}
return true;
}
void TypeMap::setWater(MapFloat * wet, float wetthresh)
{
int gx, gy;
wet->getDim(gx, gy);
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
if(wet->get(x, y) >= wetthresh)
{
(* tmap)[y][x] = 0;
}
}
}
int TypeMap::convert(MapFloat * map, TypeMapType purpose, float range)
{
int tp, maxtp = 0;
int width, height;
float val, maxval = 0.0f;
map->getDim(width, height);
matchDim(width, height);
// convert to internal type map format
int mincm, maxcm;
mincm = 100; maxcm = -1;
for(int x = 0; x < width; x++)
for(int y = 0; y < height; y++)
{
tp = 0;
switch(purpose)
{
case TypeMapType::EMPTY: // do nothing
break;
case TypeMapType::PAINT: // do nothing
break;
case TypeMapType::CATEGORY: // do nothing, since categories are integers not floats
break;
case TypeMapType::SLOPE:
val = map->get(x, y);
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
break;
case TypeMapType::WATER:
val = map->get(x, y);
if(val > maxval)
maxval = val;
// discretise into ranges of water values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
break;
case TypeMapType::SUNLIGHT:
val = map->get(x, y);
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
break;
case TypeMapType::TEMPERATURE:
val = map->get(x, y);
if(val > maxval)
maxval = val;
// discretise into ranges of temperature values
// clamp values to range, temperature is bidrectional
if(val < -range) val = -range;
if(val > range) val = range;
tp = (int) ((val+range) / (2.0f*range+pluszero) * (numSamples-2)) + 1;
break;
case TypeMapType::CHM:
val = map->get(y, x);
if(val > maxval)
maxval = val;
// discretise into ranges of tree height values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
if(tp < mincm)
mincm = tp;
if(tp > maxcm)
maxcm = tp;
break;
case TypeMapType::CDM:
val = map->get(y, x);
if(val > maxval)
maxval = val;
// discretise into ranges of tree density values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
if(tp < mincm)
mincm = tp;
if(tp > maxcm)
maxcm = tp;
break;
case TypeMapType::SUITABILITY:
val = map->get(x, y);
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
break;
default:
break;
}
(* tmap)[y][x] = tp;
if(tp > maxtp)
maxtp = tp;
}
/*
if(purpose == TypeMapType::CDM)
{
cerr << "Minimum colour value = " << mincm << endl;
cerr << "Maxiumum colour value = " << maxcm << endl;
}*/
return maxtp;
}
void TypeMap::save(const uts::string &filename)
{
ofstream outfile;
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
outfile << width() << " " << height() << endl;
// dimensions
for (int x = 0; x < width(); x++)
for (int y = 0; y < height(); y++)
{
outfile << get(x, y) << " ";
}
outfile.close();
}
else
{
cerr << "Error TypeMap::save: unable to write to file" << endl;
}
}
void TypeMap::saveToPaintImage(const uts::string &filename)
{
unsigned char * mask = new unsigned char[tmap->width()*tmap->height()];
int i = 0;
cerr << "paint file: " << filename << endl;
//mask.resize(tmap->width()*tmap->height(), 0.0f);
for (int x = 0; x < tmap->width(); x++)
for (int y = 0; y < tmap->height(); y++)
{
switch((*tmap)[x][y]) // check order
{
case 0:
mask[i] = 0;
break;
case 1: // sparse low
mask[i] = 38;
break;
case 2: // sparse med
mask[i] = 76;
break;
case 3: // sparse tall
mask[i] = 115;
break;
case 4: // dense low
mask[i] = 153;
break;
case 5: // dense med
mask[i] = 191;
break;
case 6: // dense tall
mask[i] = 230;
break;
default:
mask[i] = 0;
}
i++;
}
// use QT image save functions
QImage img;
img = QImage(mask, tmap->width(), tmap->height(), QImage::Format_Grayscale8);
img.save(QString::fromStdString(filename), "PNG", 100);
delete [] mask;
}
void TypeMap::setPurpose(TypeMapType purpose)
{
usage = purpose;
switch(usage)
{
case TypeMapType::EMPTY:
initPaletteColTable();
break;
case TypeMapType::PAINT:
initPaletteColTable();
break;
case TypeMapType::CATEGORY:
initCategoryColTable();
break;
case TypeMapType::SLOPE:
initPerceptualColTable("../../../../data/colourmaps/linear_kry_5-95_c72_n256.csv", 10);
break;
case TypeMapType::WATER:
initPerceptualColTable("../../../../data/colourmaps/linear_blue_95-50_c20_n256.csv", 10);
break;
case TypeMapType::SUNLIGHT:
initPerceptualColTable("../../../../data/colourmaps/linear_kry_5-95_c72_n256.csv", 10);
break;
case TypeMapType::TEMPERATURE:
initPerceptualColTable("../../../../data/colourmaps/diverging_bwr_55-98_c37_n256.csv", 10);
break;
case TypeMapType::CHM:
// initPerceptualColTable("../colourmaps/linear_ternary-green_0-46_c42_n256.csv", 20);
initPerceptualColTable("../../../../data/colourmaps/linear_green_5-95_c69_n256.csv", 20);
// replace 0 with natural terrain colour
colmap[1][0] = 0.7f; colmap[1][1] = 0.6f; colmap[1][2] = 0.5f; // transparent
colmap[2][0] = 0.0f; colmap[2][1] = 0.0f; colmap[2][2] = 1.0f; // black
colmap[numSamples+2][0] = 1.0f; colmap[numSamples+2][1] = 0.0f; colmap[numSamples+2][2] = 0.0f; // red
break;
case TypeMapType::CDM:
initPerceptualColTable("../../../../data/colourmaps/linear_green_5-95_c69_n256.csv", 20);
// replace 0 with natural terrain colour
colmap[1][0] = 0.7f; colmap[1][1] = 0.6f; colmap[1][2] = 0.5f;
break;
case TypeMapType::SUITABILITY:
initPerceptualColTable("../../../../data/colourmaps/linear_gow_60-85_c27_n256.csv", 20, 0.8f);
// initPerceptualColTable("../../colourmaps/isoluminant_cgo_70_c39_n256.csv", 10);
break;
default:
break;
}
}
void TypeMap::resetType(int ind)
{
// wipe all previous occurrences of ind
#pragma omp parallel for
for(int j = 0; j < tmap->height(); j++)
for(int i = 0; i < tmap->width(); i++)
if((* tmap)[j][i] == ind)
(* tmap)[j][i] = 0;
dirtyreg.x0 = 0; dirtyreg.y0 = 0;
dirtyreg.x1 = tmap->width(); dirtyreg.y1 = tmap->height();
}
void TypeMap::setColour(int ind, GLfloat * col)
{
for(int i = 0; i < 4; i++)
colmap[ind][i] = col[i];
}
| 25,839
|
C++
|
.cpp
| 703
| 26.035562
| 114
| 0.481536
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,169
|
moisture.cpp
|
jgain_EcoLearn/UnderSim/sim/moisture.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "moisture.h"
#include "waterfill.h"
#include <iostream>
using namespace std;
float MoistureSim::slopeImpact(float slope, float slopethresh, float slopemax, float runofflimit)
{
float revrunoff;
if(slope < slopethresh) // max absorption for slopes below threshold
revrunoff = runofflimit;
else if(slope > slopemax) // complete runoff for slopes above slope max
revrunoff = 0.0f;
else // otherwise linearly interpolate
{
revrunoff = (1.0f - (slope - slopethresh) / (slopemax - slopethresh)) * runofflimit;
}
return revrunoff;
}
void MoistureSim::simSoilCycle(Terrain * ter, MapFloat * terslope, std::vector<float> precipitation, float slopethresh, float slopemax, float evaporation, float runofflimit, float soilsaturation, float riverlevel, std::vector<MapFloat> & wsh)
{
/* Algorithm:
* Per pixel:
* Init resorvoir to 50% capacity by soil type
* Init excess_m to 0
* Iterate 2 or 3 times (to achieve equilibrium)
* Per month (m)
* res_p += (1-w_e) * P_m - w_t
* run flow simulation with excess_m
* if res_p < w_s
* res_p = min(w_s, res_p + flow_p)
* if res_p >= w_s
* mark as standing water
* else
* excess_m+1,m+2,m+3 += 1/3 (res_p - w_s)
* res_p = w_s
* if flow_p > 0
* mark as standing water
* moisture_p = min(w_s, res_p + w_t)
* where w_e = proportion of evaporation, P_m is precipitation per month, w_s = maximum available water saturation by soil type
* w_t = monthly transpiration
*/
std::vector<float> reservoir, transpiration;
std::vector<std::vector<uint>> excess;
int dx, dy;
terslope->getDim(dx, dy);
cerr << "image size = " << dx << " by " << dy << endl;
QImage wfimg = QImage(dx, dy, QImage::Format_RGB32);
QImage fpimg = QImage(dx, dy, QImage::Format_RGB32);
WaterFill wf, fp; // water network, flood plain
int i, j, x, y, t, p;
bool flood;
float wval, flow, onsoil, insoil, runoff, plain, groundwater, avgexcess, slope, sloperunoff, avgslope, avgrunoff;
int minmnth[12], maxmnth[12], floodcount, excesscount;
// calculate transpiration levels to achieve equilibrium for each terrain pixel, because of dependence on slope
// sum of min runofflimit, monthly non-evaporated precipitation
transpiration.resize(dy*dy, 0.0f);
avgrunoff = 0.0f; avgslope = 0.0f;
cerr << "slopeImpact at " << slopethresh << " = " << slopeImpact(slopethresh, slopethresh, slopemax, runofflimit) << endl;
cerr << "slopeImpact at " << slopemax << " = " << slopeImpact(slopemax, slopethresh, slopemax, runofflimit) << endl;
cerr << "slopeImpact at " << 25.0f << " = " << slopeImpact(25.0f, slopethresh, slopemax, runofflimit) << endl;
cerr << "PRECIPITATION: ";
for(i = 0; i < 12; i++)
cerr << precipitation[i] << " ";
cerr << endl;
float minslope = 90.0f, maxslope = 0.0f;
for(p = 0; p < dx * dy; p++)
{
x = p%dx;
y = p/dx;
slope = terslope->get(x, y);
if(slope < minslope)
minslope = slope;
if(slope > maxslope)
maxslope = slope;
sloperunoff = slopeImpact(slope, slopethresh, slopemax, runofflimit);
avgrunoff += sloperunoff;
avgslope += slope;
for(i = 0; i < 12; i++)
transpiration[p] += min(sloperunoff, (1.0f - evaporation) * precipitation[i]);
}
cerr << "average slope = " << avgslope / ((float) dx * dy) << endl;
cerr << "average runoff = " << avgrunoff / ((float) dx * dy) << endl;
// water fill parameters
float riverreach = 50.0f; // weighting for how far water table expands out around rivers
float slopeweight = 1.0f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to widen
float flowpowerterm = 0.5f; // power term applied to flow result
/*
// for alpine
#ifdef ALPINEBIOME
riverreach = 50.0f; // weighting for how far water table expands out around rivers
slopeweight = 1.0f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to widen
#endif
// for savannah
#ifdef SAVANNAHBIOME
riverreach = 100.0f; // weighting for how far water table expands out around rivers
slopeweight = 0.9f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to widen
#endif
// for canyon
#ifdef CANYONBIOME
riverreach = 50.0f; // weighting for how far water table expands out around rivers
slopeweight = 1.4f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to wide
#endif
// for mediterrainean style canyon
#ifdef CANYONWETBIOME
riverreach = 50.0f; // weighting for how far water table expands out around rivers
slopeweight = 1.4f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to wide
#endif
// for med
#ifdef MEDBIOME
riverreach = 50.0f; // weighting for how far water table expands out around rivers
slopeweight = 1.0f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to widen
#endif
*/
// initialise water flow field
cerr << "waterflow: set terrain" << endl;
wf.setTerrain(ter);
// initialise terrain-based moisture values
reservoir.resize(dx*dy, 0.2 * soilsaturation);
// reservoir.resize(dx*dy, 0.0f); // no initial water
for(i = 0; i < 12; i++)
{
std::vector<uint> noexcess;
noexcess.resize(dx*dy, 0);
excess.push_back(noexcess);
minmnth[i] = 1000; maxmnth[i] = 0;
}
for(t = 0; t < 2; t++) // simulation needs to be run twice to ensure proper settings for early months
{
cerr << "iteration " << t << endl;
floodcount = 0; excesscount = 0; avgexcess = 0.0f;
for(i = 0; i < 12; i++) // calculate soil moisture per month
{
wf.setAbsorbsion(riverlevel);
wf.reset();
wf.compute(); // seed flow computation with water seepage values
wf.compute();
wf.expandRivers(riverreach, slopeweight); // only flood plain has expanded river influence
for(p = 0; p < dx * dy; p++)
{
onsoil = (1.0f - evaporation) * precipitation[i];
x = p%dx;
y = p/dx;
slope = terslope->get(x, y);
sloperunoff = slopeImpact(slope, slopethresh, slopemax, runofflimit);
insoil = min(onsoil, sloperunoff);
runoff = max(0.0f, onsoil - insoil);
reservoir[p] += insoil - (transpiration[p] / 12.0f); // monthly rainfall-transpiration cycle
// reservoir[p] = max(0.0f, reservoir[p]);
// get flow sim values
// infiltrate extra water from the flood plain
flood = wf.isFlowingWater(y, x); // x, y
if(flood)
{
floodcount++;
plain = 0.0f;
}
else
{
plain = wf.riverMoisture(y, x); // x, y
}
groundwater = reservoir[p];
if(plain > 0.5f) // pixel is in the expansion area of the river so increase soil moisture
{
excesscount++;
avgexcess += plain;
// groundwater = 1000.0f; // for visual feedback on floodplain area
groundwater = min(soilsaturation, groundwater + plain * soilsaturation);
}
if(runoff > 0.0f) // rainfall exceeds soil capacity so spread exceess over subsequent months
{
for(j = 1; j < 6; j++)
excess[(i+j)%12][p] += (int) (runoff / 5.0f * 0.1); // 0.1 scale factor for GC sim convert to metres
excess[i][p] = 0;
}
// set moisture
if(flood)
wval = 2000.0f; // standing water so set to very high saturation value
else
wval = max(0.0f, groundwater);
if(t == 1) // store on second run
{
wsh[i].set(x, y, wval);
// assign wval
if(wval < minmnth[i])
minmnth[i] = wval;
if(wval > maxmnth[i])
maxmnth[i] = wval;
}
}
/*
if(t == 1)
{
wsh.setMin(i+1, minmnth[i]);
wsh.setMax(i+1, maxmnth[i]);
}*/
cerr << "Month " << i << " Finished" << endl;
cerr << "Flooded proportion = " << (float) floodcount / (float) (dx * dy) << endl;
}
cerr << "Avg Flooding Proportion = " << (float) floodcount / (12.0f * (float) (dx * dy)) << endl;
cerr << "Avg Excess Proportion = " << (float) excesscount / (12.0f * (float) (dx * dy)) << endl;
cerr << "Avg Excess = " << avgexcess / (float) excesscount << endl;
}
}
bool MoistureSim::constantValidation(MapFloat * terslope, std::vector<MapFloat> &wsh, int precipitation)
{
int dx, dy;
terslope->getDim(dx, dy);
for(int i = 0; i < 12; i++)
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
if( wsh[i].get(x, y) != precipitation)
{
cerr << "MoisuterSim::constantValidation: moisture value " << wsh[i].get(x, y) << " at " << x << ", " << y << " instead of " << precipitation << endl;
return false;
}
return true;
}
| 10,773
|
C++
|
.cpp
| 235
| 36.944681
| 242
| 0.565553
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,171
|
window.cpp
|
jgain_EcoLearn/UnderSim/sim/window.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "glwidget.h"
#include "window.h"
#include "vecpnt.h"
#include "common/str.h"
#include <cmath>
#include <string>
using namespace std;
////
// SunWindow
///
QSize SunWindow::sizeHint() const
{
return QSize(1000, 1000);
}
void SunWindow::setOrthoView(GLWidget * ortho)
{
QWidget *mainWidget = new QWidget;
QGridLayout *mainLayout = new QGridLayout;
orthoView = ortho;
setCentralWidget(mainWidget);
mainLayout->setColumnStretch(0, 1);
// signal to slot connections
connect(orthoView->getGLSun(), SIGNAL(signalRepaintAllGL()), this, SLOT(repaintAllGL()));
mainLayout->addWidget(orthoView->getGLSun(), 0, 0);
mainWidget->setLayout(mainLayout);
setWindowTitle(tr("EcoSun"));
}
void SunWindow::repaintAllGL()
{
if(orthoView->getGLSun() != NULL)
orthoView->getGLSun()->repaint();
}
////
// Window
///
QSize Window::sizeHint() const
{
return QSize(1000, 1000);
}
Window::Window(string datadir)
{
QWidget *mainWidget = new QWidget;
QGridLayout *mainLayout = new QGridLayout;
int dx, dy;
float sx, sy;
// default rendering parameters, set using text entry
// mirrors TRenderer settings
// grid params
gridIntensity = 0.8f; // 80% of base colour
gridSepX = 2500.0f; // separation of grid lines, depends on how input data is scaled
gridSepZ = 2500.0f; //
gridWidth = 1.5f; // in pixels?
// contour params
contourSep = 25.f; // separation (Y direction) depends on how input data is normalized
numContours = 1.0f / contourSep;
contourWidth = 1.0f; // in pixels ?
contourIntensity = 1.2f; // 130% of base colour
// radiance scaling parameters
radianceTransition = 0.2f;
radianceEnhance = 3.0f;
// map parameters
sunMonth = 1;
wetMonth = 1;
tempMonth = 1;
setCentralWidget(mainWidget);
mainLayout->setColumnStretch(0, 0);
mainLayout->setColumnStretch(1, 0);
mainLayout->setColumnStretch(2, 1);
// render panel
renderPanel = new QWidget;
QVBoxLayout *renderLayout = new QVBoxLayout;
// Grid Line Widgets
QGroupBox *gridGroup = new QGroupBox(tr("Grid Lines"));
QCheckBox * checkGridLines = new QCheckBox(tr("Show Grid Lines"));
checkGridLines->setChecked(false);
QLabel *gridSepXLabel = new QLabel(tr("Grid Sep X:"));
gridSepXEdit = new QLineEdit;
gridSepXEdit->setFixedWidth(60);
// gridSepXEdit->setValidator(new QDoubleValidator(0.0, 500000.0, 2, gridSepXEdit));
gridSepXEdit->setInputMask("0000.0");
QLabel *gridSepZLabel = new QLabel(tr("Grid Sep Z:"));
gridSepZEdit = new QLineEdit;
gridSepZEdit->setFixedWidth(60);
// gridSepZEdit->setValidator(new QDoubleValidator(0.0, 500000.0, 2, gridSepZEdit));
gridSepZEdit->setInputMask("0000.0");
QLabel *gridWidthLabel = new QLabel(tr("Grid Line Width:"));
gridWidthEdit = new QLineEdit;
gridWidthEdit->setFixedWidth(60);
// gridWidthEdit->setValidator(new QDoubleValidator(0.0, 10.0, 2, gridWidthEdit));
gridWidthEdit->setInputMask("0.0");
QLabel *gridIntensityLabel = new QLabel(tr("Grid Intensity:"));
gridIntensityEdit = new QLineEdit;
gridIntensityEdit->setFixedWidth(60);
// gridIntensityEdit->setValidator(new QDoubleValidator(0.0, 2.0, 2, gridIntensityEdit));
gridIntensityEdit->setInputMask("0.0");
// set initial grid values
gridSepXEdit->setText(QString::number(gridSepX, 'g', 2));
gridSepZEdit->setText(QString::number(gridSepZ, 'g', 2));
gridWidthEdit->setText(QString::number(gridWidth, 'g', 2));
gridIntensityEdit->setText(QString::number(gridIntensity, 'g', 2));
QGridLayout *gridLayout = new QGridLayout;
gridLayout->addWidget(checkGridLines, 0, 0);
gridLayout->addWidget(gridSepXLabel, 1, 0);
gridLayout->addWidget(gridSepXEdit, 1, 1);
gridLayout->addWidget(gridSepZLabel, 2, 0);
gridLayout->addWidget(gridSepZEdit, 2, 1);
gridLayout->addWidget(gridWidthLabel, 3, 0);
gridLayout->addWidget(gridWidthEdit, 3, 1);
gridLayout->addWidget(gridIntensityLabel, 4, 0);
gridLayout->addWidget(gridIntensityEdit, 4, 1);
gridGroup->setLayout(gridLayout);
// Contour Widgets
QGroupBox *contourGroup = new QGroupBox(tr("Contours"));
QCheckBox * checkContours = new QCheckBox(tr("Show Contours"));
checkContours->setChecked(false);
QLabel *contourSepLabel = new QLabel(tr("Contour Sep:"));
contourSepEdit = new QLineEdit;
contourSepEdit->setFixedWidth(60);
//contourSepEdit->setValidator(new QDoubleValidator(0.0, 10000.0, 2, contourSepEdit));
contourSepEdit->setInputMask("000.0");
QLabel *contourWidthLabel = new QLabel(tr("Contour Line Width:"));
contourWidthEdit = new QLineEdit;
// contourWidthEdit->setValidator(new QDoubleValidator(0.0, 10.0, 2, contourWidthEdit));
contourWidthEdit->setInputMask("0.0");
contourWidthEdit->setFixedWidth(60);
QLabel *contourIntensityLabel = new QLabel(tr("Contour Intensity:"));
contourIntensityEdit = new QLineEdit;
contourIntensityEdit->setFixedWidth(60);
contourIntensityEdit->setInputMask("0.0");
// set initial contour values
contourSepEdit->setText(QString::number(contourSep, 'g', 2));
contourWidthEdit->setText(QString::number(contourWidth, 'g', 2));
contourIntensityEdit->setText(QString::number(contourIntensity, 'g', 2));
QGridLayout *contourLayout = new QGridLayout;
contourLayout->addWidget(checkContours, 0, 0);
contourLayout->addWidget(contourSepLabel, 1, 0);
contourLayout->addWidget(contourSepEdit, 1, 1);
contourLayout->addWidget(contourWidthLabel, 2, 0);
contourLayout->addWidget(contourWidthEdit, 2, 1);
contourLayout->addWidget(contourIntensityLabel, 3, 0);
contourLayout->addWidget(contourIntensityEdit, 3, 1);
contourGroup->setLayout(contourLayout);
// Radiance
QGroupBox *radianceGroup = new QGroupBox(tr("Radiance"));
QLabel *radianceEnhanceLabel = new QLabel(tr("Radiance Enhancement:"));
radianceEnhanceEdit = new QLineEdit;
radianceEnhanceEdit->setFixedWidth(60);
radianceEnhanceEdit->setInputMask("0.0");
// set initial radiance values
radianceEnhanceEdit->setText(QString::number(radianceEnhance, 'g', 2));
QGridLayout *radianceLayout = new QGridLayout;
radianceLayout->addWidget(radianceEnhanceLabel, 0, 0);
radianceLayout->addWidget(radianceEnhanceEdit, 0, 1);
radianceGroup->setLayout(radianceLayout);
// map display
QGroupBox *mapGroup = new QGroupBox(tr("Maps"));
QGridLayout *mapLayout = new QGridLayout;
sunMapRadio = new QRadioButton(tr("Sunlight mth"));
wetMapRadio = new QRadioButton(tr("Moisture mth"));
chmMapRadio = new QRadioButton(tr("Canopy Height"));
noMapRadio = new QRadioButton(tr("None"));
sunMapEdit = new QLineEdit;
sunMapEdit->setFixedWidth(60);
sunMapEdit->setInputMask("00");
sunMapEdit->setText(QString::number(sunMonth, 'i', 1));
wetMapEdit = new QLineEdit;
wetMapEdit->setFixedWidth(60);
wetMapEdit->setInputMask("00");
wetMapEdit->setText(QString::number(wetMonth, 'i', 1));
mapLayout->addWidget(sunMapRadio, 0, 0);
mapLayout->addWidget(sunMapEdit, 0, 1);
mapLayout->addWidget(wetMapRadio, 1, 0);
mapLayout->addWidget(wetMapEdit, 1, 1);
mapLayout->addWidget(chmMapRadio, 3, 0);
mapLayout->addWidget(noMapRadio, 4, 0);
mapGroup->setLayout(mapLayout);
renderLayout->addWidget(gridGroup);
renderLayout->addWidget(contourGroup);
renderLayout->addWidget(radianceGroup);
renderLayout->addWidget(mapGroup);
// plant panel
plantPanel = new QWidget;
QVBoxLayout *plantLayout = new QVBoxLayout;
// global plant parameters
QGroupBox *globalGroup = new QGroupBox(tr("Global"));
QGridLayout *globalLayout = new QGridLayout;
checkCanopy = new QCheckBox(tr("Show Canopy Plants"));
checkCanopy->setChecked(true);
checkUndergrowth = new QCheckBox(tr("Show Undergrowth Plants"));
checkUndergrowth->setChecked(true);
globalLayout->addWidget(checkCanopy, 0, 0);
globalLayout->addWidget(checkUndergrowth, 1, 0);
globalGroup->setLayout(globalLayout);
// per species plant parameters
QGroupBox *speciesGroup = new QGroupBox(tr("Per Species"));
QGridLayout *speciesLayout = new QGridLayout;
checkS0 = new QCheckBox(tr("Species 0"));
checkS0->setChecked(true);
checkS1 = new QCheckBox(tr("Species 1"));
checkS1->setChecked(true);
checkS2 = new QCheckBox(tr("Species 2"));
checkS2->setChecked(true);
checkS3 = new QCheckBox(tr("Species 3"));
checkS3->setChecked(true);
checkS4 = new QCheckBox(tr("Species 4"));
checkS4->setChecked(true);
checkS5 = new QCheckBox(tr("Species 5"));
checkS5->setChecked(true);
checkS6 = new QCheckBox(tr("Species 6"));
checkS6->setChecked(true);
checkS7 = new QCheckBox(tr("Species 7"));
checkS7->setChecked(true);
checkS8 = new QCheckBox(tr("Species 8"));
checkS8->setChecked(true);
checkS9 = new QCheckBox(tr("Species 9"));
checkS9->setChecked(true);
checkS10 = new QCheckBox(tr("Species 10"));
checkS10->setChecked(true);
checkS11 = new QCheckBox(tr("Species 11"));
checkS11->setChecked(true);
checkS12 = new QCheckBox(tr("Species 12"));
checkS12->setChecked(true);
checkS13 = new QCheckBox(tr("Species 13"));
checkS13->setChecked(true);
checkS14 = new QCheckBox(tr("Species 14"));
checkS14->setChecked(true);
checkS15 = new QCheckBox(tr("Species 15"));
checkS15->setChecked(true);
QPushButton * plantsOn = new QPushButton(tr("All Visible"));
QPushButton * plantsOff = new QPushButton(tr("None Visible"));;
speciesLayout->addWidget(checkS0, 0, 0);
speciesLayout->addWidget(checkS1, 1, 0);
speciesLayout->addWidget(checkS2, 2, 0);
speciesLayout->addWidget(checkS3, 3, 0);
speciesLayout->addWidget(checkS4, 4, 0);
speciesLayout->addWidget(checkS5, 5, 0);
speciesLayout->addWidget(checkS6, 6, 0);
speciesLayout->addWidget(checkS7, 7, 0);
speciesLayout->addWidget(checkS8, 8, 0);
speciesLayout->addWidget(checkS9, 9, 0);
speciesLayout->addWidget(checkS10, 10, 0);
speciesLayout->addWidget(checkS11, 11, 0);
speciesLayout->addWidget(checkS12, 12, 0);
speciesLayout->addWidget(checkS13, 13, 0);
speciesLayout->addWidget(checkS14, 14, 0);
speciesLayout->addWidget(checkS15, 15, 0);
speciesLayout->addWidget(plantsOn, 16, 0);
speciesLayout->addWidget(plantsOff, 17, 0);
speciesGroup->setLayout(speciesLayout);
plantLayout->addWidget(globalGroup);
plantLayout->addWidget(speciesGroup);
// OpenGL widget
// Specify an OpenGL 3.2 format.
QGLFormat glFormat;
glFormat.setVersion( 4, 1 );
glFormat.setProfile( QGLFormat::CoreProfile );
glFormat.setSampleBuffers( false );
perspectiveView = new GLWidget(glFormat, datadir);
getView().setForcedFocus(getTerrain().getFocus());
getView().setViewScale(getTerrain().longEdgeDist());
getTerrain().getGridDim(dx, dy);
getTerrain().getTerrainDim(sx, sy);
perspectiveView->getGLSun()->setScene(&getTerrain(), NULL, NULL);
numGridX = 1.0f / gridSepX;
numGridZ = 1.0f / gridSepZ;
// signal to slot connections
connect(perspectiveView, SIGNAL(signalRepaintAllGL()), this, SLOT(repaintAllGL()));
connect(gridSepXEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(gridSepZEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(gridWidthEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(gridIntensityEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(contourSepEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(contourWidthEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(contourIntensityEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(radianceEnhanceEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(radianceEnhanceEdit, SIGNAL(returnPressed()), this, SLOT(lineEditChange()));
connect(sunMapEdit, SIGNAL(returnPressed()), this, SLOT(lineEditChange()));
connect(wetMapEdit, SIGNAL(returnPressed()), this, SLOT(lineEditChange()));
// map radio buttons
connect(sunMapRadio, SIGNAL(toggled(bool)), this, SLOT(mapChange(bool)));
connect(wetMapRadio, SIGNAL(toggled(bool)), this, SLOT(mapChange(bool)));
connect(chmMapRadio, SIGNAL(toggled(bool)), this, SLOT(mapChange(bool)));
connect(noMapRadio, SIGNAL(toggled(bool)), this, SLOT(mapChange(bool)));
// display switches
connect(plantsOn, SIGNAL(clicked()), this, SLOT(allPlantsOn()));
connect(plantsOff, SIGNAL(clicked()), this, SLOT(allPlantsOff()));
connect(checkContours, SIGNAL(stateChanged(int)), this, SLOT(showContours(int)));
connect(checkGridLines, SIGNAL(stateChanged(int)), this, SLOT(showGridLines(int)));
connect(checkCanopy, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkUndergrowth, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS0, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS1, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS2, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS3, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS4, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS5, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS6, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS7, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS8, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS9, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS10, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS11, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS12, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS13, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS14, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
connect(checkS15, SIGNAL(stateChanged(int)), this, SLOT(plantChange(int)));
renderPanel->setLayout(renderLayout);
plantPanel->setLayout(plantLayout);
mainLayout->addWidget(renderPanel, 0, 0, Qt::AlignTop);
mainLayout->addWidget(plantPanel, 0, 1, Qt::AlignTop);
mainLayout->addWidget(perspectiveView, 0, 2);
createActions();
createMenus();
mainWidget->setLayout(mainLayout);
setWindowTitle(tr("UnderSim"));
mainWidget->setMouseTracking(true);
setMouseTracking(true);
renderPanel->hide();
plantPanel->hide();
perspectiveView->getRenderer()->setGridParams(numGridX, numGridZ, gridWidth, gridIntensity);
perspectiveView->getRenderer()->setContourParams(numContours, contourWidth, contourIntensity);
perspectiveView->getRenderer()->setRadianceScalingParams(radianceEnhance);
}
void Window::run_abiotics_only(bool include_canopy)
{
sunwindow->show();
sunwindow->repaint();
perspectiveView->setIncludeCanopy(include_canopy);
perspectiveView->loadScene(0);
repaintAllGL();
sunwindow->hide();
perspectiveView->hide();
}
void Window::run_undersim_viewer()
{
perspectiveView->loadFinScene(0);
repaintAllGL();
}
void Window::run_undersim_foolproof(int run_id, int nyears)
{
sunwindow->show();
sunwindow->repaint();
perspectiveView->setIncludeCanopy(true);
perspectiveView->loadScene(run_id);
repaintAllGL();
sunwindow->hide();
perspectiveView->run_undersim_only(run_id, nyears);
perspectiveView->hide();
}
void Window::scaleRenderParams(float scale)
{
gridSepX = scale / 5.0f; // separation of grid lines, depends on how input data is scaled
gridSepZ = scale / 5.0f;
numGridX = 1.0f / gridSepX;
numGridZ = 1.0f / gridSepZ;
gridSepXEdit->setText(QString::number(gridSepX, 'g', 2));
gridSepZEdit->setText(QString::number(gridSepZ, 'g', 2));
contourSep = scale / 100.f; // separation (Y direction) depends on how input data is normalized
numContours = 1.0f / contourSep;
contourSepEdit->setText(QString::number(contourSep, 'g', 2));
perspectiveView->getRenderer()->setGridParams(numGridX, numGridZ, gridWidth, gridIntensity);
perspectiveView->getRenderer()->setContourParams(numContours, contourWidth, contourIntensity);
perspectiveView->getRenderer()->setRadianceScalingParams(radianceEnhance);
}
void Window::keyPressEvent(QKeyEvent *e)
{
// pass to render window
perspectiveView->keyPressEvent(e);
}
void Window::mouseMoveEvent(QMouseEvent *event)
{
QWidget *child=childAt(event->pos());
QGLWidget *glwidget = qobject_cast<QGLWidget *>(child);
if(glwidget) {
QMouseEvent *glevent=new QMouseEvent(event->type(),glwidget->mapFromGlobal(event->globalPos()),event->button(),event->buttons(),event->modifiers());
QCoreApplication::postEvent(glwidget,glevent);
}
}
void Window::repaintAllGL()
{
perspectiveView->repaint();
}
void Window::showRenderOptions()
{
renderPanel->setVisible(showRenderAct->isChecked());
}
void Window::showPlantOptions()
{
plantPanel->setVisible(showPlantAct->isChecked());
}
void Window::showContours(int show)
{
perspectiveView->getRenderer()->drawContours(show == Qt::Checked);
repaintAllGL();
}
void Window::showGridLines(int show)
{
perspectiveView->getRenderer()->drawGridlines(show == Qt::Checked);
repaintAllGL();
}
void Window::allPlantsOn()
{
perspectiveView->setAllSpecies(true);
checkS0->setChecked(true);
checkS1->setChecked(true);
checkS2->setChecked(true);
checkS3->setChecked(true);
checkS4->setChecked(true);
checkS5->setChecked(true);
checkS6->setChecked(true);
checkS7->setChecked(true);
checkS8->setChecked(true);
checkS9->setChecked(true);
checkS10->setChecked(true);
checkS11->setChecked(true);
checkS12->setChecked(true);
checkS13->setChecked(true);
checkS14->setChecked(true);
checkS15->setChecked(true);
}
void Window::allPlantsOff()
{
perspectiveView->setAllSpecies(false);
checkS0->setChecked(false);
checkS1->setChecked(false);
checkS2->setChecked(false);
checkS3->setChecked(false);
checkS4->setChecked(false);
checkS5->setChecked(false);
checkS6->setChecked(false);
checkS7->setChecked(false);
checkS8->setChecked(false);
checkS9->setChecked(false);
checkS10->setChecked(false);
checkS11->setChecked(false);
checkS12->setChecked(false);
checkS13->setChecked(false);
checkS14->setChecked(false);
checkS15->setChecked(false);
}
void Window::plantChange(int show)
{
bool vis = (bool) show;
if(sender() == checkCanopy)
perspectiveView->setCanopyVis(vis);
if(sender() == checkUndergrowth)
perspectiveView->setUndergrowthVis(vis);
if(sender() == checkS0)
perspectiveView->toggleSpecies(0, vis);
if(sender() == checkS1)
perspectiveView->toggleSpecies(1, vis);
if(sender() == checkS2)
perspectiveView->toggleSpecies(2, vis);
if(sender() == checkS3)
perspectiveView->toggleSpecies(3, vis);
if(sender() == checkS4)
perspectiveView->toggleSpecies(4, vis);
if(sender() == checkS5)
perspectiveView->toggleSpecies(5, vis);
if(sender() == checkS6)
perspectiveView->toggleSpecies(6, vis);
if(sender() == checkS7)
perspectiveView->toggleSpecies(7, vis);
if(sender() == checkS8)
perspectiveView->toggleSpecies(8, vis);
if(sender() == checkS9)
perspectiveView->toggleSpecies(9, vis);
if(sender() == checkS10)
perspectiveView->toggleSpecies(10, vis);
if(sender() == checkS11)
perspectiveView->toggleSpecies(11, vis);
if(sender() == checkS12)
perspectiveView->toggleSpecies(12, vis);
if(sender() == checkS13)
perspectiveView->toggleSpecies(13, vis);
if(sender() == checkS14)
perspectiveView->toggleSpecies(14, vis);
if(sender() == checkS15)
perspectiveView->toggleSpecies(15, vis);
}
void Window::lineEditChange()
{
bool ok;
float val;
int ival;
float tx, ty, hr;
tx = 1.0f; ty = 1.0f; // to fix when scale added
hr = 1.0f;
if(sender() == gridSepXEdit)
{
val = gridSepXEdit->text().toFloat(&ok);
if(ok)
{
gridSepX = val;
numGridX = tx / gridSepX; // convert separation to num grid lines
}
}
if(sender() == gridSepZEdit)
{
val = gridSepZEdit->text().toFloat(&ok);
if(ok)
{
gridSepZ = val;
numGridZ = ty / gridSepZ;
}
}
if(sender() == gridWidthEdit)
{
val = gridWidthEdit->text().toFloat(&ok);
if(ok)
{
gridWidth = val;
}
}
if(sender() == gridIntensityEdit)
{
val = gridIntensityEdit->text().toFloat(&ok);
if(ok)
{
gridIntensity = val;
}
}
if(sender() == contourSepEdit)
{
val = contourSepEdit->text().toFloat(&ok);
if(ok)
{
contourSep = val;
numContours = hr / contourSep;
}
}
if(sender() == contourWidthEdit)
{
val = contourWidthEdit->text().toFloat(&ok);
if(ok)
{
contourWidth = val;
}
}
if(sender() == contourIntensityEdit)
{
val = contourIntensityEdit->text().toFloat(&ok);
if(ok)
{
contourIntensity = val;
}
}
if(sender() == radianceEnhanceEdit)
{
val = radianceEnhanceEdit->text().toFloat(&ok);
if(ok)
{
radianceEnhance = val;
}
}
if(sender() == sunMapEdit)
{
ival = sunMapEdit->text().toInt(&ok);
if(ok)
{
sunMonth = ival;
if(sunMonth < 1)
sunMonth = 1;
if(sunMonth > 12)
sunMonth = 12;
}
if(sunMapRadio->isChecked())
perspectiveView->setMap(TypeMapType::SUNLIGHT, sunMonth-1);
}
if(sender() == wetMapEdit)
{
ival = wetMapEdit->text().toInt(&ok);
if(ok)
{
wetMonth = ival;
if(wetMonth < 1)
wetMonth = 1;
if(wetMonth > 12)
wetMonth = 12;
}
if(wetMapRadio->isChecked())
perspectiveView->setMap(TypeMapType::WATER, wetMonth-1);
}
// cerr << "val entered " << val << endl;
// without this the renderer defaults back to factory settings at certain stages - very wierd bug
perspectiveView->getRenderer()->setGridParams(numGridX, numGridZ, gridWidth, gridIntensity);
perspectiveView->getRenderer()->setContourParams(numContours, contourWidth, contourIntensity);
perspectiveView->getRenderer()->setRadianceScalingParams(radianceEnhance);
repaintAllGL();
}
void Window::mapChange(bool on)
{
if(sunMapRadio->isChecked() && on)
perspectiveView->setMap(TypeMapType::SUNLIGHT, sunMonth-1);
if(wetMapRadio->isChecked() && on)
perspectiveView->setMap(TypeMapType::WATER, wetMonth-1);
if(chmMapRadio->isChecked() && on)
perspectiveView->setOverlay(TypeMapType::CHM);
if(noMapRadio->isChecked() && on)
perspectiveView->setOverlay(TypeMapType::EMPTY);
}
void Window::createActions()
{
showRenderAct = new QAction(tr("Show Terrain Options"), this);
showRenderAct->setCheckable(true);
showRenderAct->setChecked(false);
showRenderAct->setStatusTip(tr("Hide/Show Rendering Options"));
connect(showRenderAct, SIGNAL(triggered()), this, SLOT(showRenderOptions()));
showPlantAct = new QAction(tr("Show Plant Options"), this);
showPlantAct->setCheckable(true);
showPlantAct->setChecked(false);
showPlantAct->setStatusTip(tr("Hide/Show Plant Options"));
connect(showPlantAct, SIGNAL(triggered()), this, SLOT(showPlantOptions()));
}
void Window::createMenus()
{
viewMenu = menuBar()->addMenu(tr("&View"));
viewMenu->addAction(showRenderAct);
viewMenu->addAction(showPlantAct);
}
| 27,446
|
C++
|
.cpp
| 678
| 35.457227
| 156
| 0.692481
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,172
|
sun.cpp
|
jgain_EcoLearn/UnderSim/sim/sun.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "sun.h"
#include "dice_roller.h"
#define GLM_FORCE_RADIANS
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtx/rotate_vector.hpp>
#define AXIS_TILT 0.408407f
const float SunLight::_axis_tilt = AXIS_TILT;
const float SunLight::_monthly_axis_tilt = (AXIS_TILT)/3.f;
const float SunLight::_half_day_in_minutes = 720.0f;
const float SunLight::_quarter_day_in_minutes = SunLight::_half_day_in_minutes/2.0f;
const float SunLight::_3_quarters_day_in_minutes = SunLight::_half_day_in_minutes + SunLight::_quarter_day_in_minutes;
const float avgtransmit = 0.45f; // proportion of light blocked by leaves
////
// SunScene
////
SunScene::SunScene()
{
view = new View();
terrain = new Terrain();
terrain->initGrid(1024, 1024, 10000.0f, 10000.0f);
view->setForcedFocus(terrain->getFocus());
view->setViewScale(terrain->longEdgeDist());
view->setViewType(ViewState::ORTHOGONAL);
float tx, ty;
terrain->getTerrainDim(tx, ty);
view->setOrthoViewExtent(tx,ty);
alpha = nullptr;
}
SunScene::~SunScene()
{
delete view;
if(alpha)
delete alpha;
}
////
// GLSun
////
GLSun::GLSun(const QGLFormat& format, QWidget *parent)
: QGLWidget(format, parent)
{
qtWhite = QColor::fromCmykF(0.0, 0.0, 0.0, 0.0);
renderer = new PMrender::TRenderer(NULL, "../sim/shaders/");
scene = new SunScene();
setFocusPolicy(Qt::StrongFocus);
resize(sizeHint());
renderPass = 1;
sun = new CanopyShape(0.75f, 1.0f);
}
GLSun::~GLSun()
{
if(renderer) delete renderer;
if(scene) delete scene;
if(sun) delete sun;
}
QSize GLSun::minimumSizeHint() const
{
return QSize(50, 50);
}
QSize GLSun::sizeHint() const
{
return QSize(2000, 2000);
}
void GLSun::colToCoord(QColor col, int &gx, int &gy)
{
int r, g, b, idx, dx, dy;
getTerrain()->getGridDim(dx, dy);
col.getRgb(&r, &g, &b);
// assumes 8-bits per colour channel
idx = (r * 65536) + (g * 256) + b;
// then derive grid coordinates
gx = (int) (idx / dy);
gy = idx - gx * dy;
}
void GLSun::calcVisibility(MapFloat * sunvis, float timestep)
{
QImage baseImg, canImg;
int dx, dy, gx, gy;
MapFloat mask; // check off wether a gridpoint is visible
// north = (0,0,-1), west = (-1,0,0), east = (1,0,0), south = (0, 0, 1)
sunvis->getDim(dx, dy);
mask.setDim(dx, dy);
mask.fill(0.0f);
for(int qx = 0; qx < orthodiv; qx++)
for(int qy = 0; qy < orthodiv; qy++)
{
getView()->setOrthoQuadrant(qx, qy);
// first pass: terrain indices
renderPass = 1;
paintGL();
glFlush();
baseImg = grabFrameBuffer();
// second pass: // delete terrain; alpha-blended canopies
renderPass = 2;
paintGL();
glFlush();
canImg = grabFrameBuffer();
// first use exact location for incrementing
for(int x = 0; x < baseImg.width(); x++)
for(int y = 0; y < baseImg.height(); y++)
{
QColor col = baseImg.pixelColor(x, y);
colToCoord(col, gx, gy);
if(gx < dx && gy < dy) // not the background
{
if(mask.get(gx, gy) < 0.5f) // not already incremented
{
qreal r, g, b;
QColor viscol = canImg.pixelColor(x, y);
viscol.getRgbF(&r, &g, &b); // all channels store the same info so just use red
sunvis->set(gx, gy, sunvis->get(gx, gy) + (float) r * timestep);
mask.set(gx, gy, 1.0f);
}
}
}
// now do a pass on the neighbours for hole filling
for(int x = 0; x < baseImg.width(); x++)
for(int y = 0; y < baseImg.height(); y++)
{
QColor col = baseImg.pixelColor(x, y);
colToCoord(col, gx, gy);
if(gx < dx && gy < dy) // not the background
{
qreal r, g, b;
QColor viscol = canImg.pixelColor(x, y);
viscol.getRgbF(&r, &g, &b); // all channels store the same info so just use red
for(int i = std::max(0, gx-2); i <= std::min(dx-1, gx+2); i++)
for(int j = std::max(0, gy-2); j <= std::min(dy-1, gy+2); j++)
{
if(mask.get(i, j) < 0.5f)
{
sunvis->set(i, j, sunvis->get(i, j) + (float) r * timestep);
mask.set(i, j, 1.0f);
}
}
}
}
}
}
View * GLSun::getView()
{
return scene->view;
}
Terrain * GLSun::getTerrain()
{
return scene->terrain;
}
MapFloat * GLSun::getCanopyHeight()
{
return scene->chght;
}
MapFloat * GLSun::getCanopyDensity()
{
return scene->cdense;
}
MapFloat * GLSun::getAlpha()
{
return scene->alpha;
}
PMrender::TRenderer * GLSun::getRenderer()
{
return renderer;
}
void GLSun::setScene(Terrain * ter, MapFloat * ch, MapFloat * cd)
{
float tx, ty;
int dx, dy;
scene->terrain = ter;
scene->chght = ch;
scene->cdense = cd;
getView()->setForcedFocus(getTerrain()->getFocus());
getView()->setViewScale(getTerrain()->longEdgeDist());
getTerrain()->calcMeanHeight();
getTerrain()->setBufferToDirty();
getTerrain()->getTerrainDim(tx, ty);
getView()->setOrthoViewExtent(tx,ty);
getTerrain()->getGridDim(dx, dy);
if(scene->alpha == nullptr)
scene->alpha = new MapFloat();
scene->alpha->setDim(dx, dy);
update();
}
void GLSun::deriveAlpha(EcoSystem *eco, Biome * biome)
{
getAlpha()->fill(0.0f);
eco->sunSeeding(getTerrain(), biome, getAlpha());
}
void GLSun::alphaMapStats()
{
int dx, dy;
float avgalpha = 0.0f, a;
int cntalpha = 0;
cerr << "**** ALPHA MAP STATS ***" << endl;
if(getAlpha() != nullptr)
{
getAlpha()->getDim(dx, dy);
cerr << "Alpha dim = " << dx << ", " << dy << endl;
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
a = getAlpha()->get(x, y);
if(a > 0.0f)
{
avgalpha += a;
cntalpha++;
}
}
cerr << "Average alpha = " << avgalpha / (float) cntalpha << " with nonzero of " << cntalpha << " from " << dx*dy << endl;
cerr << "with percentage coverage = " << (float) cntalpha / (float) (dx*dy) << endl;
}
else
{
cerr << "alpha map does not exist" << endl;
}
}
void GLSun::bind()
{
if(sun)
delete sun;
sun = new CanopyShape(0.75, getTerrain()->getCellExtent());
}
void GLSun::initializeGL()
{
// get context opengl-version
qDebug() << "Widget OpenGl: " << format().majorVersion() << "." << format().minorVersion();
qDebug() << "Context valid: " << context()->isValid();
qDebug() << "Really used OpenGl: " << context()->format().majorVersion() << "." <<
context()->format().minorVersion();
qDebug() << "OpenGl information: VENDOR: " << (const char*)glGetString(GL_VENDOR);
qDebug() << " RENDERDER: " << (const char*)glGetString(GL_RENDERER);
qDebug() << " VERSION: " << (const char*)glGetString(GL_VERSION);
qDebug() << " GLSL VERSION: " << (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
QGLFormat glFormat = QGLWidget::format();
if ( !glFormat.sampleBuffers() )
qWarning() << "Could not enable sample buffers";
qglClearColor(qtWhite.light());
int mu;
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &mu);
cerr << "max texture units = " << mu << endl;
// *** PM REnder code - start ***
PMrender::TRenderer::terrainShadingModel sMod = PMrender::TRenderer::SUN;
// set terrain shading model
renderer->setTerrShadeModel(sMod);
// set up light
Vector dl = Vector(0.6f, 1.0f, 0.6f);
dl.normalize();
// initialise renderer/compile shaders
renderer->initShaders();
// set other render parameters
// can set terrain colour for radiance scaling etc - check trenderer.h
// terrain contours
renderer->drawContours(false);
renderer->drawGridlines(false);
// turn on terrain type overlay (off by default); NB you can stil call methods to update terrain type,
renderer->useTerrainTypeTexture(true);
renderer->useConstraintTypeTexture(false);
// use manipulator textures (decal'd)
renderer->textureManipulators(false);
// *** PM REnder code - end ***
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glDisable(GL_MULTISAMPLE);
glDisable(GL_DEPTH_CLAMP);
glEnable(GL_TEXTURE_2D);
paintGL(); // complete initialization
}
void GLSun::paintGL()
{
uts::vector<ShapeDrawData> drawParams; // to be passed to terrain renderer
drawParams.clear();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// no longer use CHM
// UNDO
// if(sun)
// sun->drawCanopy(drawParams);
// pass in draw params and render
renderer->setConstraintDrawParams(drawParams);
getTerrain()->updateBuffers(renderer);
renderer->drawSun(getView(), renderPass);
}
void GLSun::resizeGL(int width, int height)
{
// TO DO: fix resizing
int side = qMin(width, height);
glViewport((width - side) / 2, (height - side) / 2, width, height);
}
////
// CanopyShape
///
void CanopyShape::genCanopyBox(float trunkratio, float cellscale)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkratio;
GLfloat basecol[4] = {0.0f, 0.0f, 0.0f, 0.0f};
canopybox->setColour(basecol);
// canopy - tapered box
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, trunkratio, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(-90.0f), rotx);
canopybox->genPyramid(cellscale * 1.0f, cellscale * 1.0f, canopyheight, tfm);
}
void CanopyShape::bindCanopy(Terrain * ter, View * view, MapFloat * hght, MapFloat *dnsty)
{
int dx, dy, bndplants = 0;
std::vector<glm::mat4> xform; // transformation to be applied to each instance
std::vector<glm::vec4> colvar; // colour variation to be applied to each instance
float rndoff;
xform.clear();
colvar.clear();
ter->getGridDim(dx, dy);
DiceRoller * dice = new DiceRoller(-400,400);
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
float h = hght->get(x, y);
h = h * 0.3048f; // convert feet to metres
// float d = dnsty->get(x, y);
// stop using density because it is not available from pipeline
// mean density is 0.91, add random variation of +- 0.4
// rndoff = (float) dice->generate() / 10000.0f;
float d = (0.91f + rndoff) * dnsty->get(x, y);
// previously used #define avgtransmit
if(h > 1.0f)
{
// setup transformation for individual plant, including scaling and translation
glm::mat4 idt, tfm;
glm::vec3 trs, sc;
vpPoint loc = ter->toWorld(y, x, ter->getHeight(x, y)); // center of cell
idt = glm::mat4(1.0f);
trs = glm::vec3(loc.x, loc.y, loc.z);
tfm = glm::translate(idt, trs); // translate to correct position
sc = glm::vec3(1.0f, h, 1.0f); // scale to correct tree height
tfm = glm::scale(tfm, sc);
xform.push_back(tfm);
colvar.push_back(glm::vec4(0.0f, 0.0f, 0.0f, d));
// d is the blocking density of the canopy, adjusted to allow some light through beyond what can be seen from the ground
// avgtransmit is calculated as the average transmission factor for sonoma tree species.
bndplants++;
}
}
std::cout << "binding " << bndplants << " instances..." << std::endl;
if(!canopybox->bindInstances(nullptr, &xform, &colvar))
cerr << "CanopyShape::bindCanopies: binding failed" << endl;
std::cout << "finished binding instances" << std::endl;
delete dice;
}
void CanopyShape::drawCanopy(std::vector<ShapeDrawData> &drawParams)
{
ShapeDrawData sdd;
sdd = canopybox->getDrawParameters();
sdd.current = false;
drawParams.push_back(sdd);
}
////
// HemSample
///
// Efficient sampling of the hemisphere based on the Hammersley Point Set
// http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html
float HemSample::radicalInverse_VdC(uint bits)
{
bits = (bits << 16u) | (bits >> 16u);
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
return float(bits) * 2.3283064365386963e-10; // / 0x100000000
}
void HemSample::hammersley2d(uint i, uint N, float &u, float &v)
{
u = (float) i / (float) N;
v = radicalInverse_VdC(i);
}
void HemSample::convertUniform(float u, float v, Vector &dirn)
{
float phi = v * 2.0 * PI;
float cosTheta = 1.0 - u;
float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
dirn = Vector(cos(phi) * sinTheta, cosTheta, sin(phi) * sinTheta);
}
void HemSample::getSample(int s, int totSamples, Vector &dirn)
{
float u, v;
hammersley2d((uint) s, (uint) totSamples, u, v);
convertUniform(u, v, dirn);
}
////
// SunLight
////
SunLight::SunLight()
{
tx = 0; ty = 0;
month = 0; time = 0;
latitude = 0;
setNorthOrientation(Vector(0.0, 0.0, -1.0f));
refreshSun();
genSphereSun();
}
SunLight::~SunLight()
{
}
// Various conversion helper routines
float SunLight::minutesToAngle(float minutes)
{
return ((_half_day_in_minutes - minutes) / _half_day_in_minutes) * M_PI;
}
/*
float SunLight::getAxisTiltAngle(int mnth)
{
return -_axis_tilt + ((float) std::abs(6 - mnth) * _monthly_axis_tilt);
}*/
float SunLight::getAxisTiltAngle(float mnth)
{
return -_axis_tilt + (std::fabs(6.0 - mnth) * _monthly_axis_tilt);
}
float SunLight::latitudeToAngle(float lat)
{
return -lat / (180.0f / M_PI);
}
void SunLight::splitTilt(int time_of_day, float & pitch, float & roll)
{
float f_time_of_day ((float) time_of_day);
// Pitch
{
if(time_of_day <= _half_day_in_minutes) // Before midday
pitch = 1.0f - ((f_time_of_day/_half_day_in_minutes) * 2);
else // After midday
pitch = -1 + (((f_time_of_day-_half_day_in_minutes)/_half_day_in_minutes) * 2);
}
// Roll
{
if(time_of_day < (_quarter_day_in_minutes))
roll = (f_time_of_day/_quarter_day_in_minutes) * 1.0f;
else if(f_time_of_day >= _quarter_day_in_minutes && f_time_of_day <= _3_quarters_day_in_minutes)
roll = 1 - (((f_time_of_day-_quarter_day_in_minutes)/_half_day_in_minutes)*2.0f);
else // 6 pm -> midnight
roll = -1 + ((f_time_of_day - _3_quarters_day_in_minutes) / _quarter_day_in_minutes);
}
}
void SunLight::refreshSun()
{
// First calculate some orientations we need values we need
glm::vec3 east_orientation = glm::rotateY(north, (float)M_PI_2);
glm::vec3 true_north_orientation = glm::rotate(north, glm::radians((float) (-latitude)), east_orientation); // is sign correct here?
int sun_trajectory_radius(500000);
float max_axis_tilt(SunLight::getAxisTiltAngle(month));
float day_angle(SunLight::minutesToAngle((float) time));
glm::vec3 cp_tn_and_east (glm::normalize(glm::cross(true_north_orientation, east_orientation)));
// First calculate the sun position at midday during the equinox
glm::vec3 sun_position ( ((float)sun_trajectory_radius) * cp_tn_and_east );
// Now take into consideration axis tilt based on the month
sun_position = glm::rotate( sun_position, -max_axis_tilt, east_orientation ); // PITCH
// Now rotate around true north for the day
sun_position = glm::rotate(sun_position, day_angle, true_north_orientation);
// Now align to the center of the terrain (i.e the center of the terrain is at the latitude specified)
// sun_position += glm::vec3(center.x, center.y, center.z);
sunpos = vpPoint(sun_position[0], sun_position[1], sun_position[2]);
}
void SunLight::genSphereSun()
{
glm::mat4 idt;
// simple unit diameter sphere
idt = glm::mat4(1.0f);
GLfloat suncol[] = {1.0f, 1.0f, 0.0f, 1.0f};
sunRender.genSphere(20.0f, 20, 20, idt);
sunRender.setColour(suncol);
}
void SunLight::bindDiffuseSun(View * view, Terrain * ter)
{
std::vector<glm::mat4> xform; // transformation to be applied to each instance
std::vector<glm::vec4> colvar; // colour variation to be applied to each instance
HemSample hem;
xform.clear();
colvar.clear();
for(int t = 0; t < 100; t++)
{
// setup transformation for individual sun
glm::mat4 idt, tfm;
glm::vec3 trs, sc;
Vector sundir;
vpPoint termid, loc;
hem.getSample(t, 100, sundir);
sundir.mult(400.0f);
ter->getMidPoint(termid);
loc = vpPoint(termid.x+sundir.i, termid.y+sundir.j, termid.z+sundir.k);
//cerr << "sundir = " << sundir.i << " " << sundir.j << " " << sundir.k << endl;
idt = glm::mat4(1.0f);
trs = glm::vec3(loc.x+center.x, loc.y+center.y, loc.z+center.z);
tfm = glm::translate(idt, trs);
xform.push_back(tfm);
glm::vec4 col = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f); // no colour variation
colvar.push_back(col); // colour variation
}
if(!sunRender.bindInstances(view, &xform, &colvar))
cerr << "SUN BINDING FAILED" << endl;
}
void SunLight::bindSun(View * view)
{
std::vector<glm::mat4> xform; // transformation to be applied to each instance
std::vector<glm::vec4> colvar; // colour variation to be applied to each instance
xform.clear();
colvar.clear();
float tothours = 0.0f;
for(int t = 0; t < 1440; t+= 1)
{
// setup transformation for individual sun
glm::mat4 idt, tfm;
glm::vec3 trs, sc;
setTime(t);
Vector sundir = Vector(sunpos.x, sunpos.y, sunpos.z);
sundir.normalize();
sundir.mult(400.0f);
vpPoint loc = vpPoint(sundir.i, sundir.j, sundir.k);
//cerr << "sundir = " << sundir.i << " " << sundir.j << " " << sundir.k << endl;
if(loc.y > 0.0f)
tothours += (1.0 / 60.0f);
idt = glm::mat4(1.0f);
trs = glm::vec3(loc.x+center.x, loc.y+center.y, loc.z+center.z);
tfm = glm::translate(idt, trs);
xform.push_back(tfm);
glm::vec4 col = glm::vec4(abs((float) t - 720.0f) / -1400.0f, abs((float) t - 720.0f) / -1400.0f, abs((float) t - 720.0f) / -1400.0f, 0.0f); // midday is peak colour, all others are darker
colvar.push_back(col); // colour variation
}
if(!sunRender.bindInstances(view, &xform, &colvar))
cerr << "SUN BINDING FAILED" << endl;
cerr << "TOTAL HOURS OF SUNLIGHT = " << tothours << endl;
}
void SunLight::drawSun(std::vector<ShapeDrawData> &drawParams)
{
ShapeDrawData sdd;
sdd = sunRender.getDrawParameters();
sdd.current = false;
drawParams.push_back(sdd);
}
void SunLight::diffuseSun(Terrain * ter, MapFloat * diffusemap, GLSun * glsun, int numSamples, bool enable)
{
//int numSamples = 100;
int dx, dy;
Timer tmm;
HemSample hem;
ter->getGridDim(dx, dy);
diffusemap->setDim(dx, dy);
diffusemap->fill(0.0f);
tmm.start();
if (enable)
{
for(int s = 0; s < numSamples; s++) // hemisphere samples
{
Vector sunvec;
hem.getSample(s, numSamples, sunvec);
if(sunvec.j > 0.0f) // above the horizon
{
glsun->getView()->sundir(sunvec);
glsun->calcVisibility(diffusemap, 1.0f);
}
}
// normalization
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
diffusemap->set(x, y, diffusemap->get(x, y) / (float) numSamples);
}
}
tmm.stop();
cerr << "Diffuse sampling complete in " << tmm.peek() << " seconds" << endl;
}
void SunLight::projectSun(Terrain * ter, std::vector<MapFloat> &sunmaps, GLSun * glsun, std::vector<float> &sunhours, int minutestep, int startm, int endm, int mincr, bool enable)
{
float tothours;
int dx, dy;
vpPoint gridpos, xsectpos;
Vector sunvec;
float hourstep = (float) minutestep / 60.0f;
Timer tmm;
float tstep, tx, ty;
ter->getGridDim(dx, dy);
ter->getTerrainDim(tx, ty);
tstep = 1.0f * tx / (float) dx;
sunhours.clear();
int month_incr = mincr;
int start_month = startm;
int end_month = endm;
for(int m = start_month; m <= end_month; m += month_incr) // months of the year
{
tothours = 0.0f;
sunmaps[m-1].fill(0.0f);
// for(int d = 0; d < 2; d++)
// {
int d = 1;
setMonth((float) m + ((float) (d-1) / 30.0f));
tmm.start();
for(int t = 0; t < 1440; t+= minutestep)
{
setTime(t);
// cerr << "zoom dist = " << glsun->getView()->getZoom() << endl;
// cerr << "sunpos " << sunpos.x << ", " << sunpos.y << ", " << sunpos.z << endl;
if(sunpos.y > 0.0f) // above the horizon
{
if (enable)
{
sunvec = Vector(sunpos.x, sunpos.y, sunpos.z);
sunvec.normalize();
glsun->getView()->sundir(sunvec);
glsun->calcVisibility(&sunmaps[m-1], hourstep);
}
tothours += hourstep; // sun above horizon
}
}
// }
tmm.stop();
cerr << "Month " << m << " Sunlight Pass Complete in " << tmm.peek() << " seconds" << endl;
cerr << "with " << tothours << " of sunlight" << endl;
sunhours.push_back(tothours);
}
}
void SunLight::mergeSun(std::vector<MapFloat> &sunmaps, MapFloat * diffusemap, std::vector<float> cloudiness, std::vector<float> sunhours)
{
int dx, dy;
float direct, diffuse;
diffusemap->getDim(dx, dy);
for(int m = 0; m < 12; m++) // months of the year
{
blurSun(sunmaps[m], 2, 2);
blurSun((* diffusemap), 2, 2);
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
// direct sunlight portion
direct = sunmaps[m].get(x, y) * (1.0f - cloudiness[m]);
// diffuse sunlight portion
diffuse = diffusemap->get(x, y) * cloudiness[m] * sunhours[m];
sunmaps[m].set(x, y, direct+diffuse);
}
// cerr << "Cloudiness for month " << m << " is " << cloudiness[m] << " and sun hours are " << sunhours[m] << endl;
}
}
void SunLight::applyAlpha(GLSun * sun, std::vector<MapFloat> &sunmaps)
{
int dx, dy;
// apply previously derived alpha map
sun->getAlpha()->getDim(dx, dy);
// do radial smoothing. Note this changes the alpha map
radialBlur((* sun->getAlpha()), 15);
for(int m = 0; m < 12; m++) // months of the year
{
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
sunmaps[m].set(x, y, sunmaps[m].get(x, y) * (1.0f - sun->getAlpha()->get(x, y)));
// if(sun->getAlpha()->get(x, y) > 0.1f)
// sunmaps[m].set(x, y, 0.0f);
}
}
void SunLight::radialBlur(MapFloat &map, int radius)
{
MapFloat newmap;
int filterwidth = radius+1;
int sqrrad = radius * radius;
int dx, dy;
map.getDim(dx, dy);
newmap.setDim(dx, dy);
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
float avg = 0.0f;
int cnt = 0;
for(int cx = x-filterwidth; cx <= x+filterwidth; cx++)
for(int cy = y-filterwidth; cy <= y+filterwidth; cy++)
{
int r = (cx-x) * (cx-x) + (cy-y) * (cy-y);
// within radius and within bounds
if(r <= sqrrad && cx >= 0 && cx < dx && cy >= 0 && cy < dy)
{
avg += map.get(cx, cy);
cnt++;
}
}
newmap.set(x,y, avg / (float) cnt);
}
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
map.set(x, y, newmap.get(x, y));
}
void SunLight::blurSun(MapFloat &map, int filterwidth, int passes)
{
float filterarea;
MapFloat newmap;
filterarea = (float) ((filterwidth*2+1)*(filterwidth*2+1));
int dx, dy;
map.getDim(dx, dy);
newmap.setDim(dx, dy);
for(int i = 0; i < passes; i++)
{
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
float avg = 0.0f;
for(int cx = x-filterwidth; cx <= x+filterwidth; cx++)
for(int cy = y-filterwidth; cy <= y+filterwidth; cy++)
{
if(cx < 0 || cx >= dx || cy < 0 || cy >= dy)
avg += map.get(x, y);
else
avg += map.get(cx, cy);
}
newmap.set(x,y, avg / filterarea);
}
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
map.set(x, y, newmap.get(x, y));
}
}
| 27,248
|
C++
|
.cpp
| 736
| 29.599185
| 196
| 0.565013
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,173
|
grass.cpp
|
jgain_EcoLearn/UnderSim/sim/grass.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "grass.h"
#include "dice_roller.h"
bool MapFloat::read(std::string filename)
{
float val;
ifstream infile;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> gx >> gy;
initMap();
for (int x = 0; x < gx; x++)
{
for (int y = 0; y < gy; y++)
{
infile >> val;
set(x, y, val);
}
}
infile.close();
return true;
}
else
{
cerr << "Error TypeMap::loadTxt: unable to open file" << filename << endl;
return false;
}
}
| 1,601
|
C++
|
.cpp
| 47
| 28.829787
| 85
| 0.565526
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,174
|
vecpnt.cpp
|
jgain_EcoLearn/UnderSim/sim/vecpnt.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
// file: vecpnt.cpp
// author: James Gain
// project: Interactive Sculpting (1997+)
// notes: Basic vector and point arithmetic library. Inlined for efficiency.
// changes: included helpful geometry routines (2006)
#include "vecpnt.h"
#include <stdio.h>
#include <iostream>
using namespace std;
void Plane::formPlane(vpPoint pnt, Vector norm)
{
n = norm;
n.normalize();
d = -1.0f * (n.i * pnt.x + n.j * pnt.y + n.k * pnt.z);
}
bool Plane::formPlane(vpPoint * tri)
{
Vector v1, v2, zero;
v1.diff(tri[0], tri[1]);
v2.diff(tri[0], tri[2]);
v1.normalize();
v2.normalize();
n.cross(v1, v2);
zero = Vector(0.0f, 0.0f, 0.0f);
if(n == zero)
return false;
n.normalize();
d = -1.0f * (n.i * tri[0].x + n.j * tri[0].y + n.k * tri[0].z);
return true;
}
bool Plane::rayPlaneIntersect(vpPoint start, Vector dirn, float & tval)
{
Vector svec;
double num, den;
// this approach can be numerically unstable for oblique intersections
svec.pntconvert(start);
num = (double) (d + svec.dot(n));
den = (double) dirn.dot(n);
if(den == 0.0f) // dirn parallel to plane
if(num == 0.0f) // ray lies in plane
tval = 0.0f;
else
return false;
else
tval = (float) (-1.0f * num/den);
return true;
}
bool Plane::rayPlaneIntersect(vpPoint start, Vector dirn, vpPoint & intersect)
{
Vector svec, dvec;
double num, den;
float tval;
svec.pntconvert(start);
num = (double) (d + svec.dot(n));
den = (double) dirn.dot(n);
if(den == 0.0f) // dirn parallel to plane
if(num == 0.0f) // ray lies in plane
tval = 0.0f;
else
return false;
else
tval = (float) (-1.0f * num/den);
dvec = dirn;
dvec.mult(tval);
dvec.pntplusvec(start, &intersect);
return true;
}
bool Plane::side(vpPoint pnt)
{
return ((pnt.x * n.i + pnt.y * n.j + pnt.z * n.k + d) >= 0.0f);
}
float Plane::dist(vpPoint pnt)
{
return fabs(pnt.x * n.i + pnt.y * n.j + pnt.z * n.k + d);
}
float Plane::height(vpPoint pnt)
{
// B.y = -A.x - C.z - D
return (n.i * pnt.x + n.k * pnt.z + d) / (n.j * -1.0f);
}
void Plane::projectPnt(vpPoint pnt, vpPoint * proj)
{
Vector svec;
float tval;
svec.pntconvert(pnt);
tval = -1.0f * (d + svec.dot(n));
svec = n;
svec.mult(tval);
svec.pntplusvec(pnt, proj);
}
/*
void Plane::drawPlane()
{
float frontCol[] = { 0.0f, 0.0f, 1.0f, 1.0f };
float backCol[] = { 0.0f, 1.0f, 0.0f, 1.0f };
// generate origin
glBegin(GL_POLYGON);
glEnd();
} */
///
/// BoundRect
///
// optimized method: Williams et al, "An Efficient and Robust RayñBox Intersection Algorithm",
// Journal of Graphics Tools
/*
bool BBox::rayBoxIntersect(Ray r, float t0, float t1)
{
float tmin, tmax, tymin, tymax, tzmin, tzmax;
vpPoint bounds[2];
bounds[0] = min;
bounds[1] = max;
tmin = (bounds[r.sign[0]].x - r.origin.x) * r.inv_direction.i;
tmax = (bounds[1-r.sign[0]].x - r.origin.x) * r.inv_direction.i;
tymin = (bounds[r.sign[1]].y - r.origin.y) * r.inv_direction.j;
tymax = (bounds[1-r.sign[1]].y - r.origin.y) * r.inv_direction.j;
if ( (tmin > tymax) || (tymin > tmax) )
return false;
if (tymin > tmin)
tmin = tymin;
if (tymax < tmax)
tmax = tymax;
tzmin = (bounds[r.sign[2]].z - r.origin.z) * r.inv_direction.k;
tzmax = (bounds[1-r.sign[2]].z - r.origin.z) * r.inv_direction.k;
if ( (tmin > tzmax) || (tzmin > tmax) )
return false;
if (tzmin > tmin)
tmin = tzmin;
if (tzmax < tmax)
tmax = tzmax;
return ( (tmin < t1) && (tmax > t0) );
}*/
float BoundRect::nearest(vpPoint p) const
{
float dx, dz, near;
// quadrant based appraoch
if(p.x < min.x)
{
dx = p.x - min.x; dx *= dx;
if(p.z < min.z)
{
dz = p.z - min.z; dz *= dz;
}
else
{
if(p.z > max.z)
{
dz = p.z - max.z; dz *= dz;
}
else // between minz and maxz
{
dz = 0.0f;
}
}
}
else
{
if(p.x > max.x)
{
dx = p.x - max.x; dx *= dx;
if(p.z < min.z)
{
dz = p.z - min.z; dz *= dz;
}
else
{
if(p.z > max.z)
{
dz = p.z - max.z; dz *= dz;
}
else // between minz and maxz
{
dz = 0.0f;
}
}
}
else // inside
{
dx = 0.0f;
if(p.z < min.z)
{
dz = p.z - min.z; dz *= dz;
}
else
{
if(p.z > max.z)
{
dz = p.z - max.z; dz *= dz;
}
else // completely inside
{
dz = 0.0f;
}
}
}
}
near = dx + dz;
return near;
// return sqrt(near);
}
float BoundRect::farthest(vpPoint p) const
{
float dminx, dmaxx, dminz, dmaxz, far;
far = std::numeric_limits<float>::max();
dminx = min.x - p.x; dminx *= dminx;
dmaxx = max.x - p.x; dmaxx *= dmaxx;
dminz = min.z - p.z; dminz *= dminz;
dmaxz = max.z - p.z; dmaxz *= dmaxz;
if(dminx > dmaxx)
far = dminx;
else
far = dmaxx;
if(dminz > dmaxz)
far += dminz;
else
far += dmaxz;
return far;
// return sqrt(far);
}
/*
void BoundRect::test()
{
min.x = 0.0f; min.z = 0.0f;
max.x = 1.0f; max.z = 1.0f;
cerr << "Testing BoundRect" << endl;
cerr << "near (-0.5, 0.0) = " << nearest(vpPoint(-0.5, 1.0, 0.0)) << endl; // expect 0.5
cerr << "far (-0.5, 0.0) = " << farthest(vpPoint(-0.5, 1.0, 0.0)) << endl; // expect 1.80278
cerr << "near (0.2, 1.5) = " << nearest(vpPoint(0.2, -1.0, 1.5)) << endl; // expect 0.5
cerr << "far (0.2, 1.5) = " << farthest(vpPoint(0.2, -1.0, 1.5)) << endl; // expect 1.7
cerr << "near (1.5, 1.5) = " << nearest(vpPoint(1.5, 0.0, 1.5)) << endl; // expect 0.707107
cerr << "far (1.5, 1.5) = " << farthest(vpPoint(1.5, 0.0, 1.5)) << endl; // expect 2.12132
cerr << "near (0.5, 0.5) = " << nearest(vpPoint(0.5, 1.0, 0.5)) << endl; // expect 0.0
cerr << "far (0.5, 0.5) = " << farthest(vpPoint(0.5, 1.0, 0.5)) << endl; // expect 0.0
}
*/
void rayPointDist(vpPoint start, Vector dirn, vpPoint query, float &tval, float &dist)
{
float den;
vpPoint closest;
Vector closevec;
den = dirn.sqrdlength();
if(den == 0.0f) // not a valid line segmen
dist = -1.0f;
else
{
// get parameter value of closest poin
tval = dirn.i * (query.x - start.x) + dirn.j * (query.y - start.y) + dirn.k * (query.z - start.z);
tval /= den;
// find closest point on line
closevec = dirn;
closevec.mult(tval);
closevec.pntplusvec(start, &closest);
closevec.diff(query, closest);
dist = closevec.length();
}
}
bool lineCrossing(vpPoint * e1, vpPoint * e2)
{
float a1, b1, c1, a2, b2, c2;
// form implicit equations for the two lines
a1 = e1[0].y - e1[1].y; b1 = e1[1].x - e1[0].x; c1 = -1.0f * (a1*e1[0].x + b1*e1[0].y);
a2 = e2[0].y - e2[1].y; b2 = e2[1].x - e2[0].x; c2 = -1.0f * (a2*e2[0].x + b2*e2[0].y);
// now test crossing by difference of signs method
if((a1*e2[0].x+b1*e2[0].y+c1)*(a1*e2[1].x+b1*e2[1].y+c1) < 0.0f) // on opposite sides of e1
if((a2*e1[0].x+b2*e1[0].y+c2)*(a2*e1[1].x+b2*e1[1].y+c2) < 0.0f) // on opposite sides of e2
return true;
return false;
}
void clamp(float & t)
{
if(t > 1.0f+minuszero)
t = 1.0f+minuszero;
if(t < 0.0f)
t = 0.0f;
}
| 8,919
|
C++
|
.cpp
| 293
| 24.194539
| 106
| 0.524548
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,175
|
trenderer.cpp
|
jgain_EcoLearn/UnderSim/sim/trenderer.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "trenderer.h"
#include <cassert>
#include <fstream>
#include <sstream>
#include <algorithm>
namespace PMrender {
// create and update heightmap texture
// this sets the heightmap texture; if dimensions have changed, mesh+normals are rebuilt
// if force == draw, then we a rebuild will take place - use to manage changed data from synthesis
void TRenderer::updateHeightMap(int wd, int ht, float scx, float scy, const float* data, bool force)
{
if (data == NULL)
{
std::cerr << "TRenderer::updateHeightMapTexture - NULL pointer for heightmap?";
return;
}
assert(wd != 0 && ht != 0);
if (width == wd && height == ht && !force) // nothing to do - make sure binding is intact
{
//std::cerr << "rebind heightmap texture\n";
if (heightmapTexture == 0)
{
std::cerr << "Error! Heighmap texture undefined!\n";
}
glActiveTexture(htmapTexUnit); CE();
glBindTexture(GL_TEXTURE_2D, heightmapTexture); CE();
return;
}
// if grid dimensions have changed:
if(heightmapTexture != 0 && (width != wd || height != ht))
{
// std::cerr << "- Delete texture\n";
glDeleteTextures(1, &heightmapTexture); CE();
heightmapTexture = 0;
}
if (heightmapTexture == 0) // create texture if it does not exist
{
// std::cerr << "- Create texture\n";
glGenTextures(1, &heightmapTexture); CE();
glActiveTexture(htmapTexUnit); CE();
glBindTexture(GL_TEXTURE_2D, heightmapTexture ); CE();
glTexImage2D(GL_TEXTURE_2D, 0,GL_R32F, wd, ht, 0,GL_RED, GL_FLOAT, (GLfloat*)data); CE();
// no filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
}
else // otherwise sub in new texture data
{
// std::cerr << " - sub texture\n";
glActiveTexture(htmapTexUnit); CE();
glBindTexture(GL_TEXTURE_2D, heightmapTexture ); CE();
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, wd, ht, GL_RED, GL_FLOAT, (GLfloat*)data); CE();
}
// test all values for lowest terrain height:
terrainBase = 1000000.0; // +infinity
for (int i = 0; i < wd*ht; i++)
terrainBase = std::min(terrainBase, data[i]);
// std::cout << "Terrain BAse: " << terrainBase << std::endl;
width = wd;
height = ht;
scalex = scx;
scaley = scy;
// rebuild VAO and everything else if this was first image or new
// dimensions or data in heightmap has changed
deleteTerrainOpenGLbuffers();
prepareTerrainGeometry(); // set up VBO, IBO, FBO etc
prepareWalls(); // build capping walls for terrain
generateNormalTexture(); // generate new normals and set up texture unit
}
// utility function to write out colour (RGB) buffer as PPM image
void TRenderer::savePPMImage(const std::string filename, unsigned char *buffer, int w, int h)
{
ofstream ofs;
ofs.open(filename.c_str(), std::ios::binary);
if (!ofs)
{
std::cerr<< "TRenderer::savePPMImage - unable to open file for writing: " << filename << std::endl;
return;
}
// write header:
ofs << "P6\n" << w << " " << h << "\n255\n";
// write data:
ofs.write((char*)buffer, w*h*3);
if (!ofs)
std::cerr<< "TRenderer::savePPMImage - error occured when writing file " << filename << std::endl;
ofs.close();
}
// load test data set; returns width and height of terrain and
// the texture id of the single channel texture that stores it
// the texture unit to which this should be bound is also passed in
GLuint TRenderer::loadTest(const std::string &filename, GLenum texUnit, int &wd, int &ht)
{
int i;
GLfloat *buffer = NULL;
float biggest = 0.0f;
std::ifstream infile;
infile.open(filename.c_str(), std::ios_base::in);
if(infile.is_open() && !infile.eof())
{
infile >> wd;
infile >> ht;
buffer = new GLfloat [wd*ht];
GLfloat *ptr = buffer;
for (i = 0; i < wd*ht; i++)
{
infile >> *ptr;
biggest = std::max(*ptr, biggest);
ptr++;
}
infile.close();
}
else
{
std::cerr << "TRenderer::loadTest: file not found" << filename << std::endl;
infile.close();
return 0;
}
std::cerr << "Maxx Z value = " << biggest << std::endl;
// create texture for heightmap
GLuint htId;
glGenTextures(1, &htId); CE();
glActiveTexture(texUnit); CE();
glBindTexture(GL_TEXTURE_2D, htId ); CE();
glTexImage2D(GL_TEXTURE_2D, 0,GL_R32F, wd, ht, 0,GL_RED, GL_FLOAT, buffer); CE();
// no filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
if (buffer) delete [] buffer;
return htId;
}
GLuint TRenderer::addShader(const std::string& shadName, const char *frag, const char *vert) // add a new shader to the collection
{
bool ok = false;
PMrender::shaderProgram *ns = new PMrender::shaderProgram(frag, vert);
ns->compileAndLink();
if (!ok)
{
std::cerr << "addShader failed for shader = " << shadName << std::endl;
return 0;
}
else
{
shaders[shadName] = ns;
return ns->getProgramID();
}
}
void TRenderer::makeXwall(int atY, GLuint &vao, GLuint&vbo, GLuint& ibo, GLfloat *verts, GLuint *indices, bool reverse)
{
int vidx = 0, x, y;
y = atY; // create wall at y = atY;
for (x = 0; x < width; x++, vidx++)
{
// positions: z wil be offset from height texture in the shader
verts[5*vidx] = (float) x / (float) (width - 1) * scalex;
//verts[5*vidx+1] = 1.0f - ((float) y / (float) (height - 1)) - 0.5f;
//verts[5*vidx+2] = 0.0f;
verts[5*vidx+1] = 0.0f;
verts[5*vidx+2] = /* 1.0f - */ ((float) y / (float) (height - 1)) * scaley;
// texture coordinates
verts[5*vidx+3] = (float) (x+0.5f) / (float) (width);
verts[5*vidx+4] = (float) (y+0.5f) / (float) (height);
// positions: z will remain 0 - bottom edge of bottom wall, fixed to base plane
// use negative text coords to signal this in shader
verts[5*vidx + 5*width] = verts[5*vidx];
verts[5*vidx+1 + 5*width] = verts[5*vidx+1];
verts[5*vidx+2 + 5*width] = verts[5*vidx+2];
// texture coordinates
verts[5*vidx+3 + 5*width] = -1.0f;
verts[5*vidx+4 + 5*width] = -1.0f;
indices[2*vidx] = (reverse ? width-1-x: x);
indices[2*vidx+1] = (reverse ? 2*width-1-x: x+width);
}
glGenVertexArrays(1, &vao); CE();
glBindVertexArray(vao); CE();
// set up vertex buffer an copy in data
glGenBuffers(1, &vbo); CE();
glBindBuffer(GL_ARRAY_BUFFER, vbo); CE();
glBufferData(GL_ARRAY_BUFFER, 5*sizeof(GLfloat)*width*2, verts, GL_STATIC_DRAW); CE();
// enable position attribute
glEnableVertexAttribArray(0); CE();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(0)); CE();
// enable texture coord attribute
const int sz = 3*sizeof(GLfloat);
glEnableVertexAttribArray(1); CE();
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(sz) ); CE();
// set up index buffer
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); CE();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*2*width, indices, GL_STATIC_DRAW); CE();
// unbind everything and clean up
glBindBuffer(GL_ARRAY_BUFFER, 0); CE();
glBindVertexArray(0); CE();
}
void TRenderer::makeYwall(int atX, GLuint &vao, GLuint&vbo, GLuint& ibo, GLfloat *verts, GLuint *indices, bool reverse)
{
int vidx = 0, x, y;
x = atX; // create vertical wall at x = atX;
for (y = 0; y < height; y++, vidx++)
{
// positions: z wil be offset from height texture in the shader
verts[5*vidx] = (float) x / (float) (width - 1) * scalex;
//verts[5*vidx+1] = 1.0f - ((float) y / (float) (height - 1)) - 0.5f;
//verts[5*vidx+2] = 0.0f;
verts[5*vidx+1] = 0.0f;
verts[5*vidx+2] = /*1.0f -*/ ((float) y / (float) (height - 1)) * scaley;
// texture coordinates
verts[5*vidx+3] = (float) (x+0.5f) / (float) (width);
verts[5*vidx+4] = (float) (y+0.5f) / (float) (height);
// positions: z will remain 0 - bottome edge of bottom wall, fixed to base plane
// use negative text coords to signal this in shader
verts[5*vidx + 5*height] = verts[5*vidx];
verts[5*vidx+1 + 5*height] = verts[5*vidx+1];
verts[5*vidx+2 + 5*height] = verts[5*vidx+2];
// texture coordinates
verts[5*vidx+3 + 5*width] = -1.0f;
verts[5*vidx+4 + 5*width] = -1.0f;
indices[2*vidx] = (reverse ? height-1-y: y);
indices[2*vidx+1] = (reverse ? 2*height-1-y: y+height);
}
glGenVertexArrays(1, &vao); CE();
glBindVertexArray(vao); CE();
// set up vertex buffer an copy in data
glGenBuffers(1, &vbo); CE();
glBindBuffer(GL_ARRAY_BUFFER, vbo); CE();
glBufferData(GL_ARRAY_BUFFER, 5*sizeof(GLfloat)*height*2, verts, GL_STATIC_DRAW); CE();
// enable position attribute
glEnableVertexAttribArray(0); CE();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(0)); CE();
// enable texture coord attribute
const int sz = 3*sizeof(GLfloat);
glEnableVertexAttribArray(1); CE();
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(sz) ); CE();
// set up index buffer
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); CE();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*2*height, indices, GL_STATIC_DRAW); CE();
// unbind everything and clean up
glBindBuffer(GL_ARRAY_BUFFER, 0); CE();
glBindVertexArray(0); CE();
}
void TRenderer::makeBase(GLuint &vao, GLuint&vbo, GLuint& ibo, GLfloat *verts, GLuint *indices)
{
float coords[4][2] = { {0.0f, 0.0f}, {scalex, 0.0f}, {0.0f, scaley}, {scalex, scaley}};
for (int vidx = 0; vidx < 4; vidx++)
{
verts[5*vidx] = coords[vidx][0];
verts[5*vidx+1] = 0.0f; // y=0, ground plane
verts[5*vidx+2] = coords[vidx][1];
verts[5*vidx+3] = -1.0f; // tex coords: these verts are NOT displaced in shader...
verts[5*vidx+4] = -1.0f;
}
// ensure correct strip winding: normal must point down into ground plane, y=0: N=(0,-1,0)
indices[0] = 1; indices[1] = 3; indices[2] = 0; indices[3] = 2;
// standard VAO/VBO setup
glGenVertexArrays(1, &vao); CE();
glBindVertexArray(vao); CE();
// set up vertex buffer an copy in data
glGenBuffers(1, &vbo); CE();
glBindBuffer(GL_ARRAY_BUFFER, vbo); CE();
glBufferData(GL_ARRAY_BUFFER, 5*sizeof(GLfloat)*4, verts, GL_STATIC_DRAW); CE();
// enable position attribute
glEnableVertexAttribArray(0); CE();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(0)); CE();
// enable texture coord attribute
const int sz = 3*sizeof(GLfloat);
glEnableVertexAttribArray(1); CE();
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(sz) ); CE();
// set up index buffer
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); CE();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*4, indices, GL_STATIC_DRAW); CE();
// unbind everything and clean up
glBindBuffer(GL_ARRAY_BUFFER, 0); CE();
glBindVertexArray(0); CE();
}
bool TRenderer::prepareWalls(void)
{
GLfloat *vertexStorage;
GLuint *indexStorage;
// max space required across both vert/horiz walls - we'll re-use this array
int vertexStorageSize = std::max(width,height)*2*5; // 5 float attribs per vertex
int indexStorageSize = std::max(width,height)*2;
vertexStorage = new GLfloat [vertexStorageSize]; // 4 walls: top, bottom, left, right
if (vertexStorage == NULL)
{
std::cerr << "prepareWalls: vertex allocation failed for " << vertexStorageSize <<
" vertices\n";
return false;
}
indexStorage = new GLuint [indexStorageSize];
if (indexStorage == NULL)
{
std::cerr << "prepareWalls: index buffer allocation failed\n";
return false;
}
makeXwall(height-1, vaoWalls[0], vboWalls[0], iboWalls[0], vertexStorage, indexStorage, false);
normalWalls[0] = glm::vec3(0.0f, 0.0f, 1.0f); wallDrawEls[0] = 2*width;
makeXwall(0, vaoWalls[1], vboWalls[1], iboWalls[1], vertexStorage, indexStorage, true);
normalWalls[1] = glm::vec3(0.0f, 0.0f, -1.0f); wallDrawEls[1] = 2*width;
makeYwall(0, vaoWalls[2], vboWalls[2], iboWalls[2], vertexStorage, indexStorage, false);
normalWalls[2] = glm::vec3(-1.0f, 0.0f, 0.0f); wallDrawEls[2] = 2*height;
makeYwall(width-1, vaoWalls[3], vboWalls[3], iboWalls[3], vertexStorage, indexStorage, true);
normalWalls[3] = glm::vec3(1.0f, 0.0f, 0.0f); wallDrawEls[3] = 2*height;
makeBase(vaoWalls[4], vboWalls[4], iboWalls[4], vertexStorage, indexStorage);
normalWalls[4] = glm::vec3(0.0f, -1.0f, 0.0f); wallDrawEls[4] = 4;
delete [] vertexStorage;
delete [] indexStorage;
return true;
}
// creates a VBO, IBO and an encapsulating VAO to represent terrain geometry, set up
// texture for normal map computation
bool TRenderer::prepareTerrainGeometry(void)
{
GLfloat *vertexStorage;
GLuint *indexStorage;
vertexStorage = new GLfloat [width*height*5];
if (vertexStorage == NULL)
{
std::cerr << "prepareTerrainGeometry: vertex allocation failed for " << (width*height) <<
" vertices\n";
return false;
}
int vidx = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++, vidx++)
{
// positions: z wil be offset from height texture in the shader
vertexStorage[5*vidx] = (float) x / (float) (width - 1) * scalex;
//vertexStorage[5*vidx+1] = 1.0f - ((float) y / (float) (height - 1)) - 0.5f;
//vertexStorage[5*vidx+2] = 0.0f;
vertexStorage[5*vidx+1] = 0.0f;
vertexStorage[5*vidx+2] = /* 1.0f - */ (float) y / (float) (height - 1) * scaley;
// texture coordinates
vertexStorage[5*vidx+3] = (float) x / (float) (width-1);
vertexStorage[5*vidx+4] = (float) y / (float) (height-1);
}
}
int numStripsRequired = height - 1;
int numDegensRequired = 2 * (numStripsRequired - 1);
int verticesPerStrip = 2 * width;
indexSize = verticesPerStrip * numStripsRequired + numDegensRequired;
indexStorage = new GLuint [indexSize];
if (indexStorage == NULL)
{
std::cerr << "prepareTerrainGeometry: index buffer allocation failed\n";
return false;
}
int offset = 0;
for (int y = 0; y < height - 1; y++)
{
if (y > 0) // Degenerate begin: repeat first vertex
indexStorage[offset++] = (GLuint) (y * width);
for (int x = 0; x < width; x++)
{
// One part of the strip
indexStorage[offset++] = (GLuint) ((y * width) + x);
indexStorage[offset++] = (GLuint) (((y + 1) * width) + x);
}
if (y < height - 2) // Degenerate end: repeat last vertex
indexStorage[offset++] = (GLuint) (((y + 1) * width) + (width - 1));
}
// generate index array: set up for triangle strips with degeneraret tris linking strips
glGenVertexArrays(1, &vaoTerrain); CE();
glBindVertexArray(vaoTerrain); CE();
// set up vertex buffer an copy in data
glGenBuffers(1, &vboTerrain); CE();
glBindBuffer(GL_ARRAY_BUFFER, vboTerrain); CE();
glBufferData(GL_ARRAY_BUFFER, 5*sizeof(GLfloat)*width*height, vertexStorage, GL_STATIC_DRAW); CE();
// enable position attribute
glEnableVertexAttribArray(0); CE();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(0)); CE();
// enable texture coord attribute
const int sz = 3*sizeof(GLfloat);
glEnableVertexAttribArray(1); CE();
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(sz) ); CE();
// set up index buffer
glGenBuffers(1, &iboTerrain);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboTerrain); CE();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*indexSize, indexStorage, GL_STATIC_DRAW); CE();
// unbind everything and clean up
delete [] vertexStorage;
delete [] indexStorage;
glBindBuffer(GL_ARRAY_BUFFER, 0); CE();
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); CE();
glBindVertexArray(0); CE();
//set up screen quad for screen rendering
glGenVertexArrays(1, &vaoScreenQuad); CE();
glBindVertexArray(vaoScreenQuad); CE();
glGenBuffers(1, &vboScreenQuad); CE();
glBindBuffer(GL_ARRAY_BUFFER, vboScreenQuad); CE();
glBufferData(GL_ARRAY_BUFFER, sizeof(screenQuad), screenQuad, GL_STATIC_DRAW); CE();
// enable position attribute
//glEnableVertexAttribArray(0); CE();
//glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)(0)); CE();
// enable position attribute
glEnableVertexAttribArray(0); CE();
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(GLfloat), (void*)(0)); CE();
// enable texture coord attribute
const int sz2 = 2*sizeof(GLfloat);
glEnableVertexAttribArray(1); CE();
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(GLfloat), (void*)(sz2) ); CE();
glBindBuffer(GL_ARRAY_BUFFER, 0); CE();
glBindVertexArray(0); CE();
// create an FBO for normal map rendering
glGenFramebuffers(1, &fboNormalMap); CE();
glBindFramebuffer(GL_FRAMEBUFFER, fboNormalMap); CE();
// create texture target for normal map computation
glActiveTexture(normalMapTexUnit); // normal map is bound to this TIU
glGenTextures(1, &normalTexture); CE();
glBindTexture(GL_TEXTURE_2D, normalTexture); CE();
// set up texture state.
// Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA16F, width, height, 0,GL_RGBA, GL_FLOAT, 0); CE();
// no filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
// configure FBO
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, normalTexture, 0); CE();
// Set the list of draw buffers.
GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, DrawBuffers); CE(); // "1" is the size of DrawBuffers
// Always check that our framebuffer is ok
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cerr << "Normal map FBO initialisation failed\n";
return false;
}
// unbind FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
return true;
}
void TRenderer::generateNormalTexture(void)
{
glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); CE();
glDisable(GL_DEPTH_TEST); CE();
glDisable(GL_CULL_FACE); CE();
glClear(GL_COLOR_BUFFER_BIT); CE();
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport); // save current viewport
// reset current viewport
glViewport(0,0,width, height); CE();
std::string shaderName = "normalShader";
GLuint programID = (*shaders[shaderName]).getProgramID();
glUseProgram(programID); CE();
GLfloat imgDims[2] = {float(width), float(height)};
GLuint locDims = glGetUniformLocation(programID, "imgSize"); CE();
glUniform2fv(locDims, 1, imgDims); CE();
GLuint textur = glGetUniformLocation(programID, "htMap"); CE();
glUniform1i(textur, (GLint)(htmapTexUnit - GL_TEXTURE0)); CE(); // assumes heightmap texture is bound to this TIU
// pass in scale
GLfloat terDims[2] = {float(scalex), float(scaley)};
GLuint scDims = glGetUniformLocation(programID, "scale"); CE();
glUniform2fv(scDims, 1, terDims); CE();
// Render to our framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, fboNormalMap); CE();
// set shader program to normal map gen
glBindVertexArray(vaoScreenQuad); CE();
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); CE();
// unbind everthing
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
glBindVertexArray(0); CE();
glUseProgram(0); CE();
// reset viewport
glViewport(viewport[0],viewport[1],viewport[2],viewport[3]);
}
// ******* Radiance Scaling setup **************
// rebuild buffer for viewport of vWd X vHt size
bool TRenderer::initRadianceScalingBuffers(int vWd, int vHt)
{
// get viewport size - every time this changes we'll have to rebuild the textures
_w = vWd;
_h = vHt;
// Create & Configure FBO: final composite
glGenFramebuffers(1, &fboRSOutput); CE();
// std::cout << "Framebuffer2 ID = " << fboRSOutput << std::endl;
glBindFramebuffer(GL_FRAMEBUFFER, fboRSOutput); CE();
// set up final compositon buffer for radiance scaling
glActiveTexture(rsDestTexUnit); CE();
glGenTextures(1, &destTexture); CE();
glBindTexture(GL_TEXTURE_2D, destTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA8, _w, _h, 0,GL_RGBA, GL_UNSIGNED_BYTE, 0); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); CE();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, destTexture, 0); CE();
GLenum DestBuffer[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, DestBuffer); CE();
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cerr << "RS FBO (output) - initialisation: failed\n";
return false;
}
// unbind FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
// ****************************************************************************************************
// create an FBO for rendering output
glGenFramebuffers(1, &fboRadScaling); CE();
glBindFramebuffer(GL_FRAMEBUFFER, fboRadScaling); CE();
// std::cout << "Framebuffer1 ID = " << fboRadScaling << std::endl;
// ****** depth texture:: ********************
glGenTextures(1, &depthTexture); CE();
glBindTexture(GL_TEXTURE_2D, depthTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24, _w, _h, 0,GL_DEPTH_COMPONENT, GL_FLOAT, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// ****** gradient texture:: *******************
glActiveTexture(rsGradTexUnit);
glGenTextures(1, &gradTexture); CE();
glBindTexture(GL_TEXTURE_2D, gradTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA16F, _w, _h, 0,GL_RGBA, GL_FLOAT, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// ****** screenspace normal texture:: ********************
glActiveTexture(rsNormTexUnit);
glGenTextures(1, &normTexture); CE();
glBindTexture(GL_TEXTURE_2D, normTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA16F, _w, _h, 0,GL_RGBA, GL_FLOAT, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// ****** colour texture:: ********************
glActiveTexture(rsColTexUnit);
glGenTextures(1, &colTexture); CE();
glBindTexture(GL_TEXTURE_2D, colTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA8, _w, _h, 0,GL_RGBA, GL_UNSIGNED_BYTE, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// configure FBO: intermediate
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0); CE();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, gradTexture, 0); CE();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, normTexture, 0); CE();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, colTexture, 0); CE();
// Set the list of draw buffers.
GLenum DrawBuffers[3] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
glDrawBuffers(3, DrawBuffers); CE(); // "3" is the size of DrawBuffers
// Always check that our framebuffer is ok
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cerr << "RS FBO initialisation: failed\n";
return false;
}
// unbind FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
// ******************************************************************************************************
// create FBO for manipulator transparency overlay; requires depth buffer and colour attachment
glGenFramebuffers(1, &fboManipLayer); CE();
glBindFramebuffer(GL_FRAMEBUFFER, fboManipLayer); CE();
// std::cout << "FramebufferN ID = " << fboManipLayer << std::endl;
// ****** manipulator depth texture:: ********************
glActiveTexture(manipTranspTexUnit);
glGenTextures(1, &manipDepthTexture); CE();
glBindTexture(GL_TEXTURE_2D, manipDepthTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24, _w, _h, 0,GL_DEPTH_COMPONENT, GL_FLOAT, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// ****** manipulator colour texture:: ********************
glGenTextures(1, &manipTranspTexture); CE();
glBindTexture(GL_TEXTURE_2D, manipTranspTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA8, _w, _h, 0,GL_RGBA, GL_UNSIGNED_BYTE, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, manipDepthTexture, 0); CE();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, manipTranspTexture, 0); CE();
// Set the list of draw buffers.
GLenum mDrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, mDrawBuffers); CE(); // "1" is the size of DrawBuffers
// Always check that our framebuffer is ok
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cerr << "manip FBO initialisation: failed\n";
return false;
}
// unbind FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
return true;
}
// update radiance scaling FBO textures/attachments if viewport has changed size
// vwd and vht are current viewport width and height, resp.
// render conext
void TRenderer::updateRadianceScalingBuffers(int vwd, int vht)
{
if (shadModel != RADIANCE_SCALING)
return;
if (_w == 0 || _h == 0 || vwd != _w || vht != _h)
{
// std::cerr << "Delete old rad scaling buffer\n";
// clean old Radiance scaling FBO data if required
deleteFBOrscalingBuffers();
//std::cerr << "Calling Rad scaling...\n";
initRadianceScalingBuffers(vwd, vht);
//std::cerr << "Done\n";
}
}
// create data for instance
void TRenderer::initInstanceData(void)
{
vboTerrain = iboTerrain = vaoTerrain = 0;
for (int i = 0; i < 5; i++)
{
vboWalls[i] = 0;
iboWalls[i] = 0;
vaoWalls[i] = 0;
}
normalTexture = fboNormalMap = vaoScreenQuad = 0;
depthTexture = gradTexture = normTexture = colTexture = destTexture = 0;
manipDepthTexture = manipTranspTexture = 0;
typeMapTexture = 0;
constraintTexture = 0;
heightmapTexture = 0;
decalTexture = 0;
vboScreenQuad = 0;
fboRadScaling = 0;
fboRSOutput = 0;
fboManipLayer = 0;
typeBuffer = NULL;
// texture units reserved for rendering:
htmapTexUnit = GL_TEXTURE0;
normalMapTexUnit = GL_TEXTURE1;
rsGradTexUnit = GL_TEXTURE2;
rsNormTexUnit = GL_TEXTURE3;
rsColTexUnit = GL_TEXTURE4;
rsDestTexUnit = GL_TEXTURE5;
typemapTexUnit = GL_TEXTURE6;
decalTexUnit = GL_TEXTURE7;
constraintTexUnit = GL_TEXTURE8;
manipTranspTexUnit = GL_TEXTURE9;
width = height = 0;
scalex = scaley = 0.0f;
indexSize = 0;
_w = _h = 0;
terrainBase = 1000000.0; // +infinity (well kind of ...)
// default colours
terMatDiffuse = glm::vec4(0.7f, 0.6f, 0.5f, 1.0f); // colour of terrain
terMatSpec = glm::vec4(0.2f, 0.2f, 0.2f, 1.0f);
terMatAmbient = glm::vec4(0.3f, 0.3f, 0.3f, 1.0f);
lightDiffuseColour = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f); // colour of light
lightSpecColour = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f);
lightAmbientColour = glm::vec4(0.4f, 0.4f, 0.4f, 1.0f);
shinySpec = 5.0f; // specular power
// default colour: radiance scaling
terSurfColour = glm::vec4(0.7f, 0.6f, 0.5f, 1.0f);
// default camera
viewMx = glm::lookAt(glm::vec3(2.0f, 3.0f, 3.0f), glm::vec3(0.0f,0.0f,0.0f), glm::vec3(0.0, 1.0f, 0.0f));
MVmx = viewMx; // glm::mat4(1.0f); Model mx = Id
normalMatrix = glm::transpose(glm::inverse(glm::mat3(MVmx))); // glm::mat3(1.0f);
//normalMatrix = glm::mat3(1.0f);
if(shadModel == SUN)
projMx = glm::ortho(-500.0f, 500.0f, -500.0f, 500.0f, -10000.0f, 10000.0f);
else
projMx = glm::frustum(-8.0f*ACTUAL_ASPECT, 8.0f*ACTUAL_ASPECT, -8.0f, 8.0f, 50.0f, 100000.0f);
MVP = projMx * MVmx;
}
TRenderer::TRenderer(QGLWidget *drawTo, const std::string& dir)
{
canvas = drawTo;
shaderDir = dir;
shadersReady = false;
contours = true; // contours on by default
gridlines = true; //draw gridlines by default
contoursWall = true; //draw contours on side walls
gridlinesWall = true; // draw gridlines on side walls
terrainTypeTexture = false; // turn off terrain type texture by default
constraintTypeTexture = false; // turn off constraint type texture by default
shadModel = RADIANCE_SCALING; // RADIANCE_SCALING; // BASIC
manipulatorTextures = false; // do not texture manipulators by default
drawOutOfBounds = false; // shade out of bound heights
drawHiddenManipulators = false; // do/do not draw hidden manipulators
terrainBasePad = 50.0; // 50 metre padding from lowest point to avoid flat terrains having tiny side walls
// lights
pointLight = glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
directionalLight[0] = glm::vec4(0.0f, 1.0f, 0.0f, 0.0f);
directionalLight[1] = glm::vec4(0.5f, 0.5f, 0.0f, 0.0f);
// values for drawing contours/gridlines
gridColFactor = 0.7f; // 70% of base colour
gridXsep = 2.0f; // separation of griod lines, depends on how input data is scaled
gridZsep = 2.0f;
gridThickness = 1.0f;
contourSep = 70.0f; // separation (Y direction) depends on how input data is normalized
contourThickness = 0.5f;
contourColFactor = 1.3f; // 130% of base colour
outOfBoundsColour = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f); // red shading for our of bounds colour
outOfBoundsWeight = 0.2f;
outOfBoundsMean = 0.0f;
outOfBoundsOffset = 0.0f;
manipAlpha = 0.4f; // manipulator blend factor for hidden manipulators
// radiance scaling parameters
RSinvertCurvature = false;
RStransition = 0.2f;
RSenhance = 0.5f;
initInstanceData();
}
void TRenderer::deleteTerrainOpenGLbuffers(void)
{
// delete old VAO etc
if (vboTerrain != 0) glDeleteBuffers(1, &vboTerrain); CE();
if (iboTerrain != 0) glDeleteBuffers(1, &iboTerrain); CE();
if (vaoTerrain != 0) glDeleteVertexArrays(1, &vaoTerrain); CE();
if (normalTexture != 0) glDeleteTextures(1, &normalTexture); CE();
if (fboNormalMap != 0) glDeleteFramebuffers(1, &fboNormalMap); CE();
if (vaoScreenQuad != 0) glDeleteVertexArrays(1, &vaoScreenQuad); CE();
if (vboScreenQuad != 0) glDeleteBuffers(1, &vboScreenQuad); CE();
for (int i = 0; i < 5; i++)
{
if (vboWalls[i] != 0) glDeleteBuffers(1, &vboWalls[i]); CE();
if (iboWalls[i] != 0) glDeleteBuffers(1, &iboWalls[i]); CE();
if (vaoWalls[i] != 0) glDeleteVertexArrays(1, &vaoWalls[i]); CE();
}
}
void TRenderer::deleteFBOrscalingBuffers(void)
{
// Radiance scaling FBO data
if (depthTexture !=0) glDeleteTextures(1, &depthTexture); CE();
if (gradTexture !=0) glDeleteTextures(1, &gradTexture); CE();
if (normTexture !=0) glDeleteTextures(1, &normTexture); CE();
if (colTexture !=0) glDeleteTextures(1, &colTexture); CE();
if (destTexture != 0) glDeleteTextures(1, &destTexture); CE();
if (manipTranspTexture != 0) glDeleteTextures(1, &manipTranspTexture); CE();
if (manipDepthTexture != 0) glDeleteTextures(1, &manipDepthTexture); CE();
if (fboRadScaling != 0) glDeleteFramebuffers(1, &fboRadScaling); CE();
if (fboRSOutput != 0) glDeleteFramebuffers(1, &fboRSOutput); CE();
if (fboManipLayer != 0) glDeleteFramebuffers(1, &fboManipLayer); CE();
}
void TRenderer::destroyInstanceData(void)
{
if (typeBuffer != NULL) delete [] typeBuffer;
if (typeMapTexture != 0) glDeleteTextures(1, &typeMapTexture); CE();
if (heightmapTexture != 0) glDeleteTextures(1, &heightmapTexture); CE();
if (constraintTexture != 0) glDeleteTextures(1, &constraintTexture); CE();
deleteTerrainOpenGLbuffers();
deleteFBOrscalingBuffers();
}
TRenderer::~TRenderer()
{
if (decalTexture != 0) glDeleteTextures(1, &decalTexture);
// delete shaders
std::map<std::string, shaderProgram*>::iterator it = shaders.begin();
while (it != shaders.end() )
{ delete (*it).second; it++; }
destroyInstanceData();
}
// load in a new heightfield with accompanying terrain type map.
void TRenderer::loadTerrainData(const float* data, int wd, int ht, float scx, float scy,
TypeMap* paintMap, TypeMap* constraintMap)
{
if (!shadersReady)
std::cerr << "Shaders not yet compiled!!!!\n";
// clean up existing data:
destroyInstanceData();
// create new data for this instance
initInstanceData();
// create height map textures and geometry
updateHeightMap(wd, ht, scx, scy, data, true);
// set up terrain type colour map (if provided)
if (paintMap) updateTypeMapTexture(paintMap, PAINT);
if (constraintMap) updateTypeMapTexture(constraintMap, CONSTRAINT);
}
// the typ emap can be either a PAINT map (for painting on types) or an CONSTRAINT map
// for painting on freezing or other constraints.
void TRenderer::updateTypeMapTexture(TypeMap* tmap, typeMapInfo tinfo, bool force)
{
if (tmap == NULL)
{
// std::cerr << "TRenderer::updateTypeMapTexture - tmap is NULL\n";
return;
}
MemMap<int> *tm = tmap->getMap();
if (tm == NULL)
{
// std::cerr << "TRenderer::updateTypeMapTexture - Map buffer is NULL, map ignored\n";
return;
}
Region R = tmap->getRegion();
int wd = tm->width();
int ht = tm->height();
const int* ptr = (int*)tm->get();
std::vector<GLfloat *> *ct = tmap->getColourTable();
int Rwidth = R.x1 - R.x0; // region bounds from [R.x0, R.x1)
int Rheight = R.y1 - R.y0;
int xoff = R.x0;
int yoff = R.y0;
int index;
bool initTexture = false;
// width and height of terrain must match the width and height of type map buffer
// assert(wd == width && ht == height);
// texturing ops affect this texture unit
GLenum texUnit = GL_TEXTURE0;
GLuint *texId = NULL;
switch (tinfo)
{
case PAINT:
texUnit = typemapTexUnit;
texId = &typeMapTexture;
break;
case CONSTRAINT:
texUnit = constraintTexUnit;
texId = &constraintTexture;
break;
default: std::cerr << "TRenderer::updateTypeMapTexture - Illegal type map mode!\n"; return;
}
glActiveTexture(texUnit); CE();
// if grid dimensions have changed:
if(*texId != 0 && force)
{
/*
cerr << "tmap = " << wd << ", " << ht << endl;
cerr << "terrain = " << width << ", " << height << endl;
cerr << "updating texture width and height" << endl;*/
glDeleteTextures(1, texId); CE();
*texId = 0;
}
if (*texId == 0) // internal typeMap texture not allocated yet
{
// allocate subbuffer: this is used to avoid mem allocation each time this method is called (frequently)
//std::cout << "Region: " << R.x0 << "," << R.y0 << "," << R.x1 << "," << R.y1 << "\n";
if(typeBuffer != NULL)
delete [] typeBuffer;
typeBuffer = new GLfloat [width*height*4];
if (typeBuffer == NULL)
{
std::cerr << "TRenderer::updateTypeMapTexture - typeBuffer could not be allocated\n";
return;
}
glGenTextures(1, texId); CE();
glBindTexture(GL_TEXTURE_2D, *texId); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
initTexture = true;
xoff = yoff = 0;
Rwidth = wd;
Rheight = ht; // copy in whole buffer region, not sub-window
}
else // need to sub in region - bind texture first
{
glBindTexture(GL_TEXTURE_2D, *texId); CE();
}
// build colour buffer for texture:
int cnt = 0;
int colIdx;
//std::cout << "Width, Height = " << Rwidth << "," << Rheight << std::endl;
for (int i = 0; i < Rheight; i++)
for (int j = 0; j < Rwidth; j++)
{
index = (yoff + i)*wd + (xoff + j);
colIdx = ptr[index];
if (colIdx == 0 && tinfo != CONSTRAINT) // background should be used - use terMatDiffuse; for CONSTRAINT, ignore
{
//std::cout << "BG col at [" << i << "," << j << "]\n";
//std::cout << "Ter Colour=[" << terMatDiffuse[0] << "," <<
// terMatDiffuse[1] << "," << terMatDiffuse[2] << "," << terMatDiffuse[3] << "]\n";
typeBuffer[4*cnt] = terMatDiffuse[0];
typeBuffer[4*cnt+1] = terMatDiffuse[1];
typeBuffer[4*cnt+2] = terMatDiffuse[2];
typeBuffer[4*cnt+3] = terMatDiffuse[3];
}
else
{
typeBuffer[4*cnt] = (*ct)[ colIdx ][0];
typeBuffer[4*cnt+1] = (*ct)[ colIdx ][1];
typeBuffer[4*cnt+2] = (*ct)[ colIdx ][2];
typeBuffer[4*cnt+3] = (*ct)[ colIdx ][3];
//std::cout << "Map Colour=[" << typeBuffer[4*cnt] << "," <<
// typeBuffer[4*cnt + 1] << "," << typeBuffer[4*cnt + 2] << "," << typeBuffer[4*cnt + 3] << "]\n";
}
cnt++;
}
//std::cout << "Buffer built...\n";
if (initTexture)
{
//std::cout << "Overlay texture created at full resolution\n";
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA8, Rwidth, Rheight, 0,GL_RGBA, GL_FLOAT, typeBuffer); CE();
}
else
{
//std::cout << "Overlay textured sub'd\n";
glTexSubImage2D(GL_TEXTURE_2D, 0, xoff, yoff, Rwidth, Rheight, GL_RGBA, GL_FLOAT, typeBuffer); CE();
}
//std::cout << "Overlay created\n";
}
// initialise renderer - compile shaders etc This must be called before any other operations on the
// renderer.
void TRenderer::initShaders(void)
{
// set up shaders for loading and compilation
if (shadersReady) return; // already compiled
shaderProgram *s;
s = new shaderProgram();
s->setShaderSources(std::string("basic.frag"), std::string("basic.vert"));
shaders["basicShader"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("genNormal.frag"), std::string("genNormal.vert"));
shaders["normalShader"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("phong.frag"), std::string("phong.vert"));
shaders["phong"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("rad_scaling_pass1.frag"), std::string("rad_scaling_pass1.vert"));
shaders["rscale1"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("rad_scaling_pass2.frag"), std::string("rad_scaling_pass2.vert"));
shaders["rscale2"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("phongRS.frag"), std::string("phongRS.vert"));
shaders["phongRS"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("phongRSmanip.frag"), std::string("phongRSmanip.vert"));
shaders["phongRSmanip"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("sun.frag"), std::string("sun.vert"));
shaders["sunShader"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("canopy.frag"), std::string("canopy.vert"));
shaders["canopyShader"] = s;
std::cout << "Compiling shaders...\n";
std::map<std::string, shaderProgram*>::iterator it = shaders.begin();
while (it != shaders.end() )
{
std::cout << " -- shader: " << (*it).first << " -- ";
(void)((*it).second)->compileAndLink();
std::cout << "ID = " << ((*it).second)->getProgramID() << std::endl;
it++;
}
shadersReady = true;
std::cout << "done!\n";
}
void TRenderer::bindDecals(int width, int height, unsigned char * buffer)
{
GLint maxtexunits;
GLint boundtexunit;
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxtexunits);
std::cout << "maximum texture units: " << maxtexunits << std::endl;
// bind texture
glEnable(GL_TEXTURE_2D);
glActiveTexture(decalTexUnit); CE();
glGenTextures( 1, &decalTexture ); CE();
glBindTexture( GL_TEXTURE_2D, decalTexture ); CE();
// int off = 56 * width * 4 + 767 * 4;
// cerr << "width = " << width << ", height = " << height << endl;
// cerr << "decal buffer [0][0] = " << (int) buffer[0] << ", " << (int) buffer[1] << ", " << (int) buffer[2] << ", " << (int) buffer[3] << endl;
// cerr << "decal buffer [767][56] = " << (int) buffer[off] << ", " << (int) buffer[off+1] << ", " << (int) buffer[off+2] << ", " << (int) buffer[off+3] << endl;
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); CE(); // ? is this actually working
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); CE();
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); CE();
// deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
}
void TRenderer::draw(View * view)
{
if (!shadersReady) // not compiled!
{
std::cerr << "Shaders not built before draw() call - compiling...\n";
initShaders();
}
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
//std::cout << "Viewport chk - [" << viewport[0] << "," << viewport[1] << "," << viewport[3] << "," << viewport[3] << "]\n";
// render at 2X resolution for later linear downsampling (basic anti-aliasing)
updateRadianceScalingBuffers(2*viewport[2], 2*viewport[3]);
// Set the clear color to white
glClearColor( 1.0f, 1.0f, 1.0f, 1.0f ); CE();
glEnable(GL_DEPTH_TEST); CE();
glDepthMask(GL_TRUE); CE();
glDepthFunc(GL_LEQUAL); CE();
glDepthRange(0.0f, 1.0f); CE();
glEnable(GL_CULL_FACE); CE();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CE();
//glEnable(GL_DEPTH_CLAMP);
// configure shading params.
// ************************* Terrain Setup & render code *****************************************
normalMatrix = view->getNormalMtx();
MVP = view->getMatrix();
MVmx = view->getViewMtx();
projMx = view->getProjMtx();
std::string shaderName;
if (shadModel == BASIC) // basic Phong
shaderName = "basicShader";
else if(shadModel == RADIANCE_SCALING)
shaderName = "rscale1";
else // sun shading
shaderName = "sunShader";
GLuint programID = (*shaders[shaderName]).getProgramID();
glUseProgram(programID); CE();
glUniformMatrix3fv(glGetUniformLocation(programID, "normMx"), 1, GL_FALSE, glm::value_ptr(normalMatrix)); CE();
glUniformMatrix4fv(glGetUniformLocation(programID, "MV"), 1, GL_FALSE, glm::value_ptr(MVmx)); CE();
glUniformMatrix4fv(glGetUniformLocation(programID, "MVproj"), 1, GL_FALSE, glm::value_ptr(MVP)); CE();
glm::vec4 lightPos = MVmx * pointLight; // map light pos into camera space
// configure texturing: region texture overlay
if (terrainTypeTexture == false)
{
glUniform1i(glGetUniformLocation(programID, "useRegionTexture"), 0); CE(); // turn texture off
}
else if (typeMapTexture != 0)
{
glUniform1i(glGetUniformLocation(programID, "useRegionTexture"), 1); CE(); // draw region texture
GLuint rtex = glGetUniformLocation(programID, "overlayTexture"); CE();
glUniform1i(rtex, (GLint)(typemapTexUnit - GL_TEXTURE0)); CE(); // texture unit for region overlay
}
else
{
glUniform1i(glGetUniformLocation(programID, "useRegionTexture"), 0); CE(); // region texture not yet defined
}
// configure texturing: constraint texture overlay
if (constraintTypeTexture == false)
{
glUniform1i(glGetUniformLocation(programID, "useConstraintTexture"), 0); CE(); // turn texture off
}
else if (constraintTexture != 0)
{
glUniform1i(glGetUniformLocation(programID, "useConstraintTexture"), 1); CE(); // draw constraint texture
GLuint rtex = glGetUniformLocation(programID, "constraintTexture"); CE();
glUniform1i(rtex, (GLint)(constraintTexUnit - GL_TEXTURE0)); CE(); // texture unit for constraint overlay
}
else
{
glUniform1i(glGetUniformLocation(programID, "useConstraintTexture"), 0); CE(); // region texture not yet defined
}
// contouring and grids
glUniform1i(glGetUniformLocation(programID, "drawContours"), (int)(contours ? 1 : 0) ); CE(); // draw contours
glUniform1i(glGetUniformLocation(programID, "drawGridLines"), (int)(gridlines ? 1 : 0) ); CE(); // draw grdlines
glUniform1i(glGetUniformLocation(programID, "drawWallContours"), (int)(contoursWall ? 1 : 0) ); CE(); // draw wall contours
glUniform1i(glGetUniformLocation(programID, "drawWallGridLines"), (int)(gridlinesWall ? 1 : 0) ); CE(); // draw wall contours
// change shading for out of bounds heights
glUniform1i(glGetUniformLocation(programID, "drawOutOfBounds"), (int)(drawOutOfBounds ? 1 : 0) ); CE(); // draw wall contours
glUniform1f(glGetUniformLocation(programID, "outBoundsBlend"), outOfBoundsWeight); CE();
glUniform1f(glGetUniformLocation(programID, "outBoundsMax"), outOfBoundsMean + outOfBoundsOffset); CE();
glUniform1f(glGetUniformLocation(programID, "outBoundsMin"), outOfBoundsMean - outOfBoundsOffset); CE();
glUniform4fv(glGetUniformLocation(programID, "outBoundsCol"), 1, glm::value_ptr(outOfBoundsColour) ); CE();
// set contouring params (not implemented in BASIC at the moment...)
glUniform1f(glGetUniformLocation(programID, "gridX"), gridXsep); CE();
glUniform1f(glGetUniformLocation(programID, "gridZ"), gridZsep); CE();
glUniform1f(glGetUniformLocation(programID, "gridColFactor"), gridColFactor); CE();
glUniform1f(glGetUniformLocation(programID, "gridThickness"), gridThickness); CE();
glUniform1f(glGetUniformLocation(programID, "contourSep"), contourSep); CE();
glUniform1f(glGetUniformLocation(programID, "contourColFactor"), contourColFactor); CE();
glUniform1f(glGetUniformLocation(programID, "contourThickness"), contourThickness); CE();
// pass light and colours to shader
if (shadModel == BASIC)
{
glUniform4fv(glGetUniformLocation(programID, "lightpos"), 1, glm::value_ptr(lightPos)); CE();
// set colours
glUniform4fv(glGetUniformLocation(programID, "matDiffuse"), 1, glm::value_ptr(terMatDiffuse) ); CE();
glUniform4fv(glGetUniformLocation(programID, "matAmbient"), 1, glm::value_ptr(terMatAmbient) ); CE();
glUniform4fv(glGetUniformLocation(programID, "matSpec"), 1, glm::value_ptr(terMatSpec) ); CE();
glUniform4fv(glGetUniformLocation(programID, "diffuseCol"), 1, glm::value_ptr(lightDiffuseColour) ); CE();
glUniform4fv(glGetUniformLocation(programID, "ambientCol"), 1, glm::value_ptr(lightAmbientColour) ); CE();
glUniform4fv(glGetUniformLocation(programID, "specularCol"), 1, glm::value_ptr(lightSpecColour) ); CE();
glUniform1f(glGetUniformLocation(programID, "shiny"), shinySpec); CE();
}
else if(shadModel == RADIANCE_SCALING) // radiance scaling
{
// map side wall lights into camera space; lights at corners of terrain, moved along diagonal
glm::vec4 LP1 = MVmx * glm::vec4(2.0*scalex, 0.5, 2.0*scaley, 1.0);
glm::vec4 LP2 = MVmx * glm::vec4(-scalex, 0.5, -scaley, 1.0);
glUniform4fv(glGetUniformLocation(programID, "ptLightPos1"), 1, glm::value_ptr(LP1) ); CE();
glUniform4fv(glGetUniformLocation(programID, "ptLightPos2"), 1, glm::value_ptr(LP2) ); CE();
glUniform4fv(glGetUniformLocation(programID, "surfColour"), 1, glm::value_ptr(terSurfColour) ); CE();
}
else if(shadModel == SUN) // sun simulator
{
glUniform1f(glGetUniformLocation(programID, "terdim"), (float) (width)); CE();
}
//pass height and normal map to shader
GLuint textur = glGetUniformLocation(programID, "htMap"); CE();
glUniform1i(textur, (GLint)(htmapTexUnit - GL_TEXTURE0)); CE(); // assumes texture unit 0 is bound to heightmap texture
GLuint textur2 = glGetUniformLocation(programID, "normalMap"); CE();
glUniform1i(textur2, (GLint)(normalMapTexUnit - GL_TEXTURE0)); CE(); // assumes texture unit 1 is bound to normal map texture
// draw terrain:
if (shadModel == RADIANCE_SCALING)
{
GLfloat depthClear = 1.0f;
GLfloat colClear[4] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat manipLayerClear[4] = {0.0f, 0.0f, 0.0f, 0.0f};
GLfloat gradClear[4] = {0.0f, 0.0f, 0.0f, 0.0f};
GLfloat normClear[4] = {0.0f, 0.0f, 0.0f, 0.0f};
// clear manipulator transparency FBO
glBindFramebuffer(GL_FRAMEBUFFER, fboManipLayer); CE();
glViewport(0,0,_w, _h); CE(); // draw into entire frame
// clear frame buffer depth/textures
glClearBufferfv(GL_DEPTH, 0, &depthClear);
glClearBufferfv(GL_COLOR, 0, manipLayerClear);
// Render to RS FBO; clear buffers first
glBindFramebuffer(GL_FRAMEBUFFER, fboRadScaling); CE();
glViewport(0,0,_w, _h); CE(); // draw into entire frame
// clear frame buffer depth/textures
glClearBufferfv(GL_DEPTH, 0, &depthClear);
glClearBufferfv(GL_COLOR, 0, gradClear); // may be able to ignore this one - gradTexture?
glClearBufferfv(GL_COLOR, 1, normClear); // this has to be set to (0,0,0) for RS shader to work
glClearBufferfv(GL_COLOR, 2, colClear);
}
else
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CE();
}
glUniform1i(glGetUniformLocation(programID, "drawWalls"), 0); CE(); // do NOT draw walls
glBindVertexArray(vaoTerrain); CE();
glDrawElements(GL_TRIANGLE_STRIP, indexSize, GL_UNSIGNED_INT, 0); CE();
// *** draw capping walls ***
// --- move base up/down to avoid edits to surface which 'punch through' base
glUniform1f(glGetUniformLocation(programID, "terrainBase"), terrainBase); CE();
glUniform1f(glGetUniformLocation(programID, "terrainBasePad"), terrainBasePad); CE();
glUniform1i(glGetUniformLocation(programID, "drawWalls"), 1); // draw walls - ignore normal map lookup
GLuint loc = glGetUniformLocation(programID, "normalWall");
// turn off region layer texturing for walls:
glUniform1i(glGetUniformLocation(programID, "useRegionTexture"), 0); CE(); // always off for walls!
for (int i = 0; i < 5; i++)
{
glUniform3fv(loc, 1, glm::value_ptr(normalWalls[i])); CE();
glBindVertexArray(vaoWalls[i]); CE();
glDrawElements(GL_TRIANGLE_STRIP, wallDrawEls[i], GL_UNSIGNED_INT, 0); CE();
}
// **************************** draw manipulators/constraints with phong **********************************
if (shadModel == RADIANCE_SCALING)
{
programID = (*shaders["phongRS"]).getProgramID();
}
else if (shadModel == SUN)
{
programID = (*shaders["canopyShader"]).getProgramID();
}
else
{
programID = (*shaders["phong"]).getProgramID();
}
drawManipulators(programID);
// draw second pass for manipulator transparency (not supported in BASIC mode)
if (shadModel == RADIANCE_SCALING)
{
programID = (*shaders["phongRSmanip"]).getProgramID();
glBindFramebuffer(GL_FRAMEBUFFER, fboManipLayer); CE();
glViewport(0,0,_w, _h); CE();
drawManipulators(programID, true);
}
// reset frame buffer buffer etc
if (shadModel == RADIANCE_SCALING)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); // reset viewport to system setting
}
// **************************** radiance scaling pass 2 ****************************************************
if (shadModel == RADIANCE_SCALING)
{
glDisable(GL_DEPTH_TEST); CE(); // not required for screen aligned quad
// Render to our composition framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, fboRSOutput); CE();
glViewport(0,0,_w, _h); // draw into entire frame
shaderName = "rscale2";
programID = (*shaders[shaderName]).getProgramID();
//std::cout << "Shader ID (RScaling) = " << programID << std::endl;
glUseProgram(programID); CE();
//glClearColor( 0.5f, 0.0f, 0.0f, 1.0f ); CE();
glClear(GL_COLOR_BUFFER_BIT); CE();
// set image size to allow tex coordinate gen per rasterized quad fragment
GLfloat imgDims[2] = {float(_w), float(_h)};
GLuint locDims = glGetUniformLocation(programID, "imgSize"); CE();
glUniform2fv(locDims, 1, imgDims); CE();
// light is directional - specified in ***** WORLD space ******
// map DIRECTIONAL light(s) into camera space
for (int i = 0; i < 2; i++)
{
std::ostringstream oss;
oss << "lightPos" << i;
glm::vec3 dlight = normalMatrix * glm::vec3(directionalLight[i][0], directionalLight[i][1], directionalLight[i][2]);
lightPos = glm::vec4(dlight[0], dlight[1], dlight[2], 0.0f);
glUniform4fv(glGetUniformLocation(programID, oss.str().c_str()), 1, glm::value_ptr(lightPos)); CE();
}
// use lambertian lighting and params for RS calculation
GLuint dispmode = glGetUniformLocation(programID, "display"); CE();
glUniform1i(dispmode, 0); CE();
GLuint RSenabled = glGetUniformLocation(programID, "enabled"); CE();
glUniform1i(RSenabled, 1); CE();
GLuint invertCurvature = glGetUniformLocation(programID, "invert"); CE();
glUniform1i(invertCurvature, (RSinvertCurvature ? 1: 0)); CE();
GLuint enhancement = glGetUniformLocation(programID, "enhancement"); CE();
glUniform1f(enhancement, RSenhance); CE();
GLuint transition = glGetUniformLocation(programID, "transition"); CE();
glUniform1f(transition, RStransition); CE();
GLuint swidth = glGetUniformLocation(programID, "sw"); CE();
glUniform1f(swidth, (float)(1.0/_w) ); CE();
GLuint sheight = glGetUniformLocation(programID, "sh"); CE();
glUniform1f(sheight, (float)(1.0/_h) ); CE();
// configure FBO textures for render ops
GLuint textur = glGetUniformLocation(programID, "grad"); CE();
glUniform1i(textur, (GLuint)(rsGradTexUnit - GL_TEXTURE0) ); CE();
textur = glGetUniformLocation(programID, "norm"); CE();
glUniform1i(textur, (GLuint)(rsNormTexUnit - GL_TEXTURE0) ); CE();
textur = glGetUniformLocation(programID, "colormap"); CE();
glUniform1i(textur, (GLuint)(rsColTexUnit - GL_TEXTURE0) ); CE();
textur = glGetUniformLocation(programID, "manipTTexture"); CE(); // manipulator transparency
glUniform1i(textur, (GLuint)(manipTranspTexUnit - GL_TEXTURE0) ); CE();
// draw screeen aligned quad to compose RS calculations
glBindVertexArray(vaoScreenQuad); CE();
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); CE();
// unbind everthing
glBindVertexArray(0); CE();
// bind draw buffer (system
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); CE();
// bind read buffer (fbo)
glBindFramebuffer(GL_READ_FRAMEBUFFER, fboRSOutput); CE();
// set draw buffer
glDrawBuffer(GL_BACK);
// blit to the default framebuffer/back_buffer
glBlitFramebuffer(0, 0, _w, _h,
viewport[0], viewport[1], viewport[0] + viewport[2], viewport[1] + viewport[3], GL_COLOR_BUFFER_BIT, GL_LINEAR);
//std::cout << "Blit target: [" << viewport[0] << "," << viewport[1] << "," <<
//viewport[0] + viewport[2] << "," << viewport[1] + viewport[3] << "]\n";
// reset viewport to system setting
glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
glUseProgram(0); CE();
}
void TRenderer::drawSun(View * view, int renderPass)
{
if (!shadersReady) // not compiled!
{
std::cerr << "Shaders not built before draw() call - compiling...\n";
initShaders();
}
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
// render at 2X resolution for later linear downsampling (basic anti-aliasing)
updateRadianceScalingBuffers(2*viewport[2], 2*viewport[3]);
// Set the clear color to white
glClearColor( 1.0f, 1.0f, 1.0f, 1.0f ); CE();
glEnable(GL_DEPTH_TEST); CE();
glDepthMask(GL_TRUE); CE();
glDepthFunc(GL_LEQUAL); CE();
glDepthRange(0.0f, 1.0f); CE();
glEnable(GL_CULL_FACE); CE();
if(renderPass == 2) // enable blending
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CE();
// configure shading params.
// ************************* Terrain Setup & render code *****************************************
normalMatrix = view->getNormalMtx();
MVP = view->getMatrix();
MVmx = view->getViewMtx();
projMx = view->getProjMtx();
std::string shaderName;
shaderName = "sunShader";
GLuint programID = (*shaders[shaderName]).getProgramID();
glUseProgram(programID); CE();
glUniform1i(glGetUniformLocation(programID, "drawCanopies"), renderPass-1); CE(); // whether or not to use indexed colours
// PHASE 1: Draw Terrain
glUniformMatrix3fv(glGetUniformLocation(programID, "normMx"), 1, GL_FALSE, glm::value_ptr(normalMatrix)); CE();
glUniformMatrix4fv(glGetUniformLocation(programID, "MV"), 1, GL_FALSE, glm::value_ptr(MVmx)); CE();
glUniformMatrix4fv(glGetUniformLocation(programID, "MVproj"), 1, GL_FALSE, glm::value_ptr(MVP)); CE();
glUniform1f(glGetUniformLocation(programID, "terdim"), (float) (width)); CE();
// pass height and normal map to shader
GLuint textur = glGetUniformLocation(programID, "htMap"); CE();
glUniform1i(textur, (GLint)(htmapTexUnit - GL_TEXTURE0)); CE(); // assumes texture unit 0 is bound to heightmap texture
GLuint textur2 = glGetUniformLocation(programID, "normalMap"); CE();
glUniform1i(textur2, (GLint)(normalMapTexUnit - GL_TEXTURE0)); CE(); // assumes texture unit 1 is bound to normal map texture
// draw terrain:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CE();
glUniform1i(glGetUniformLocation(programID, "drawWalls"), 0); CE(); // do NOT draw walls
glBindVertexArray(vaoTerrain); CE();
glDrawElements(GL_TRIANGLE_STRIP, indexSize, GL_UNSIGNED_INT, 0); CE();
// PHASE 2: Draw capping walls
// --- move base up/down to avoid edits to surface which 'punch through' base
glUniform1f(glGetUniformLocation(programID, "terrainBase"), terrainBase); CE();
glUniform1f(glGetUniformLocation(programID, "terrainBasePad"), terrainBasePad); CE();
glUniform1i(glGetUniformLocation(programID, "drawWalls"), 1); // draw walls - ignore normal map lookup
GLuint loc = glGetUniformLocation(programID, "normalWall");
// turn off region layer texturing for walls:
glUniform1i(glGetUniformLocation(programID, "useRegionTexture"), 0); CE(); // always off for walls!
for (int i = 0; i < 5; i++)
{
glUniform3fv(loc, 1, glm::value_ptr(normalWalls[i])); CE();
glBindVertexArray(vaoWalls[i]); CE();
glDrawElements(GL_TRIANGLE_STRIP, wallDrawEls[i], GL_UNSIGNED_INT, 0); CE();
}
// PHASE 3: Draw canopies
// draw alpha blended canopies
if(renderPass == 2)
{
// disable depth writes so that more than one canopy can block sunlight
glDepthMask(GL_FALSE); CE();
programID = (*shaders["canopyShader"]).getProgramID();
drawManipulators(programID);
// revert to previous settings
glDepthMask(GL_TRUE); CE();
}
glUseProgram(0); CE();
}
// **************************** draw manipulators/constraints with phong **********************************
void TRenderer::drawManipulators(GLuint programID, bool drawToFB)
{
glUseProgram(programID); CE();
// use textured manipulators (decals)?
if (shadModel == RADIANCE_SCALING)
{
glUniform1i(glGetUniformLocation(programID, "useTexturing"), (manipulatorTextures ? 1:0) ); CE();
if (manipulatorTextures)
{
GLuint mtex = glGetUniformLocation(programID, "decalTexture"); CE();
glUniform1i(mtex, (GLint)(decalTexUnit - GL_TEXTURE0)); CE(); // texture unit for manipulators
}
}
for (int i = 0; i < (int)manipDrawCallData.size(); i++)
{
float alpha = 1.0f;
if (drawToFB) // used when drawing frame for manipulator transparanecy blending
{
// draw transparent manipulator - current only
if (shadModel == RADIANCE_SCALING)
{
if (manipDrawCallData[i].current && drawHiddenManipulators == true)
alpha = manipAlpha;
else
alpha = 0.0f;
glUniform1f(glGetUniformLocation(programID, "manipAlpha"), alpha ); CE();
}
}
// we have something to draw...
glUniformMatrix4fv(glGetUniformLocation(programID, "MV"), 1, GL_FALSE, glm::value_ptr(MVmx) ); CE();
glUniformMatrix4fv(glGetUniformLocation(programID, "MVproj"), 1, GL_FALSE, glm::value_ptr(MVP) ); CE();
glUniformMatrix3fv(glGetUniformLocation(programID, "normMx"), 1, GL_FALSE, glm::value_ptr(normalMatrix)); CE();
//glUniformMatrix3fv(glGetUniformLocation(programID, "normMx"), 1, GL_FALSE, glm::value_ptr(glm::mat3(1.0f))); CE();
glm::vec4 MatDiffuse = glm::vec4(manipDrawCallData[i].diffuse[0], manipDrawCallData[i].diffuse[1],
manipDrawCallData[i].diffuse[2], manipDrawCallData[i].diffuse[3]); // diffuse colour of manipulator
//cerr << "BASE COLOUR: " << manipDrawCallData[i].diffuse[0] << " " << manipDrawCallData[i].diffuse[1] << " " <<
// manipDrawCallData[i].diffuse[2] << " " << manipDrawCallData[i].diffuse[3] << endl;
glm::vec4 MatAmbient = glm::vec4(manipDrawCallData[i].ambient[0], manipDrawCallData[i].ambient[1],
manipDrawCallData[i].ambient[2], manipDrawCallData[i].ambient[3]); // ambient colour of manipulator
glm::vec4 MatSpecular = glm::vec4(manipDrawCallData[i].specular[0], manipDrawCallData[i].specular[1],
manipDrawCallData[i].specular[2], manipDrawCallData[i].specular[3]); // JG: ambient colour of manipulator
glm::vec4 lightDiffuseColour = glm::vec4(0.2f, 0.2f, 0.2f, 1.0f); // colour of light
glm::vec4 lightAmbientColour = glm::vec4(0.8f, 0.8f, 0.8f, 1.0f);
// set colours and light
glUniform4fv(glGetUniformLocation(programID, "matDiffuse"), 1, glm::value_ptr(MatDiffuse) ); CE();
glUniform4fv(glGetUniformLocation(programID, "matAmbient"), 1, glm::value_ptr(MatAmbient) ); CE();
glUniform4fv(glGetUniformLocation(programID, "matSpec"), 1, glm::value_ptr(MatSpecular) ); CE();
glUniform4fv(glGetUniformLocation(programID, "lightPos"), 1, glm::value_ptr(pointLight)); CE();
glUniform4fv(glGetUniformLocation(programID, "diffuseCol"), 1, glm::value_ptr(lightDiffuseColour) ); CE();
glUniform4fv(glGetUniformLocation(programID, "ambientCol"), 1, glm::value_ptr(lightAmbientColour) ); CE();
glUniform4fv(glGetUniformLocation(programID, "specularCol"), 1, glm::value_ptr(lightSpecColour) ); CE();
glUniform1f(glGetUniformLocation(programID, "shiny"), shinySpec); CE();
glBindVertexArray(manipDrawCallData[i].VAO); CE();
glDrawElementsInstanced(GL_TRIANGLES, manipDrawCallData[i].indexBufSize, GL_UNSIGNED_INT, (void*)(0), manipDrawCallData[i].numInstances); CE();
//glDrawElements(GL_TRIANGLES, manipDrawCallData[i].indexBufSize, GL_UNSIGNED_INT, (void*)(0)); CE();
glBindVertexArray(0); CE();
}
// unbind vao
glBindVertexArray(0); CE();
}
} // end of namespace PMrender
| 69,033
|
C++
|
.cpp
| 1,412
| 42.861898
| 165
| 0.645393
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,176
|
terrain.cpp
|
jgain_EcoLearn/UnderSim/sim/terrain.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
// terrain.h: model for terrain. Responsible for storage and display of heightfield terrain data
// author: James Gain
// date: 17 December 2012
#include <GL/glew.h>
#include "terrain.h"
#include <sstream>
#include <common/debug_string.h>
#include <common/terragen.h>
#include <streambuf>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <utility>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
using namespace std;
void Terrain::toGrid(vpPoint p, float & x, float & y, float & h) const
{
int gx, gy;
float tx, ty, convx, convy;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
convx = (float) (gx-1) / tx;
convy = (float) (gy-1) / ty;
x = p.x * convx;
y = p.z * convy;
h = p.y;
if(scaleOn)
h *= scfac;
}
void Terrain::toGrid(vpPoint p, int &x, int &y) const
{
int gx, gy;
float tx, ty, convx, convy;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
convx = (float) (gx-1) / tx;
convy = (float) (gy-1) / ty;
x = (int) (p.x * convx);
y = (int) (p.z * convy);
}
float Terrain::toGrid(float wdist) const
{
int gx, gy;
float tx, ty, conv;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
conv = (float) (gx-1) / tx;
return wdist * conv;
}
vpPoint Terrain::toWorld(float x, float y, float h) const
{
int gx, gy;
float tx, ty, convx, convy;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
convx = tx / (float) (gx-1);
convy = ty / (float) (gy-1);
return vpPoint(x * convx, h, y * convy);
}
vpPoint Terrain::toWorld(int x, int y, float h) const
{
int gx, gy;
float tx, ty, convx, convy;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
convx = tx / (float) (gx-1);
convy = ty / (float) (gy-1);
return vpPoint((float) x * convx, h, (float) y * convy);
}
float Terrain::toWorld(float gdist) const
{
int gx, gy;
float tx, ty, conv;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
conv = tx / (float) (gx-1);
return gdist * conv;
}
bool Terrain::inWorldBounds(vpPoint p) const
{
return (p.x >= 0.0f && p.x <= dimx && p.z >= 0.0f && p.z <= dimy);
}
bool Terrain::inSynthBounds(vpPoint p) const
{
return (p.x >= 0.0f-synthx && p.x <= dimx+synthx && p.z >= 0.0f-synthy && p.z <= dimy+synthy);
}
void Terrain::init(int dx, int dy, float sx, float sy)
{
grid.allocate(Region(0, 0, dx, dy));
setTerrainDim(sx, sy);
setFocus(vpPoint(sx/2.0f, grid[dy/2-1][dx/2-1], sy/2.0f));
scfac = 1.0f;
// init accel structure
spherestep = 8;
numspx = (grid.width()-1) / spherestep + 1; numspy = (grid.height()-1) / spherestep + 1;
for(int i = 0; i < numspx; i++)
{
std::vector<AccelSphere> sphrow;
for(int j = 0; j < numspy; j++)
{
AccelSphere sph;
sphrow.push_back(sph);
}
boundspheres.push_back(sphrow);
}
bufferState = BufferState::REALLOCATE;
accelValid = false;
scaleOn = false;
}
void Terrain::initGrid(int dx, int dy, float sx, float sy)
{
init(dx, dy, sx, sy);
grid.fill(0.0f);
}
void Terrain::delGrid()
{
grid.clear();
if(boundspheres.size() > 0)
{
for(int i = 0; i < (int) boundspheres.size(); i++)
boundspheres[i].clear();
boundspheres.clear();
}
bufferState = BufferState::REALLOCATE;
accelValid = false;
}
void Terrain::clipRegion(Region ®)
{
if(reg.x0 < 0) reg.x0 = 0;
if(reg.y0 < 0) reg.y0 = 0;
if(reg.x1 > grid.width()) reg.x1 = grid.width();
if(reg.y1 > grid.height()) reg.y1 = grid.height();
}
void Terrain::setMidFocus()
{
int dx, dy;
float sx, sy;
getGridDim(dx, dy);
getTerrainDim(sx, sy);
if(dx > 0 && dy > 0)
setFocus(vpPoint(sx/2.0f, grid[dy/2-1][dx/2-1], sy/2.0f));
else
setFocus(vpPoint(0.0f, 0.0f, 0.0f));
}
void Terrain::getMidPoint(vpPoint & mid)
{
int dx, dy;
float sx, sy;
getGridDim(dx, dy);
getTerrainDim(sx, sy);
if(dx > 0 && dy > 0)
mid = vpPoint(sx/2.0f, grid[dy/2-1][dx/2-1], sy/2.0f);
else
mid = vpPoint(0.0f, 0.0f, 0.0f);
}
void Terrain::getGridDim(int & dx, int & dy) const
{
dx = grid.width();
dy = grid.height();
}
void Terrain::getGridDim(uint & dx, uint & dy)
{
dx = (uint) grid.width();
dy = (uint) grid.height();
}
void Terrain::getTerrainDim(float &tx, float &ty) const
{
tx = dimx; ty = dimy;
}
void Terrain::setTerrainDim(float tx, float ty)
{
int gx, gy;
getGridDim(gx, gy);
dimx = tx; dimy = ty;
// calc allowable synth border
synthx = (0.5f / (float) (gx-1) + pluszero) * dimx;
synthy = (0.5f / (float) (gy-1) + pluszero) * dimy;
}
float Terrain::samplingDist()
{
int dx, dy;
float tx, ty;
getGridDim(dx, dy);
getTerrainDim(tx, ty);
return (0.5f * std::min(tx, ty)) / (float) (std::max(dx,dy)-1); // separation between vertices, about 2-3 vertices per grid cell
}
float Terrain::smoothingDist()
{
return 30.0f * samplingDist(); // about 10 grid points per curve segment
}
float Terrain::longEdgeDist()
{
float tx, ty;
getTerrainDim(tx, ty);
return std::max(tx, ty);
}
const float * Terrain::getGridData(int & dx, int & dy)
{
int i, j;
getGridDim(dx, dy);
if(scaleOn)
{
scaledgrid.allocate(Region(0, 0, grid.width(), grid.height()));
for(j = 0; j < grid.height(); j++)
for(i = 0; i < grid.width(); i++)
scaledgrid[j][i] = grid[j][i] * scfac;
return scaledgrid.get();
}
else
{
return grid.get();
}
}
float Terrain::getHeight(int x, int y)
{
return grid[x][y];
}
float Terrain::getFlatHeight(int idx)
{
int x, y, dx, dy;
getGridDim(dx, dy);
x = idx % dx;
y = idx / dx;
return grid[x][y];
}
void Terrain::getNormal(int x, int y, Vector & norm)
{
vpPoint x1, x2, y1, y2;
int dx, dy;
Vector dfdx, dfdy;
getGridDim(dx, dy);
// x-positions
if(x > 0)
x1 = toWorld(x-1, y, getHeight(x-1, y));
else
x1 = toWorld(x, y, getHeight(x, y));
if(x < dx-1)
x2 = toWorld(x+1, y, getHeight(x+1, y));
else
x2 = toWorld(x, y, getHeight(x, y));
// y-positions
if(y > 0)
y1 = toWorld(x, y-1, getHeight(x, y-1));
else
y1 = toWorld(x, y, getHeight(x, y));
if(y < dy-1)
y2 = toWorld(x, y+1, getHeight(x, y+1));
else
y2 = toWorld(x, y, getHeight(x, y));
// cross pattern
dfdx.diff(x1, x2);
dfdy.diff(y1, y2);
dfdx.normalize();
dfdy.normalize();
norm.cross(dfdx, dfdy);
norm.mult(-1.0f); // JGBUG - may be wrong direction
norm.normalize();
}
float Terrain::getCellExtent()
{
return dimx / (float) grid.width();
}
void Terrain::updateBuffers(PMrender::TRenderer * renderer) const
{
const int width = grid.width();
const int height = grid.height();
float scx, scy;
getTerrainDim(scx, scy);
glewExperimental = GL_TRUE;
if(!glewSetupDone)
{
GLenum err = glewInit();
if (GLEW_OK != err)
{
std::cerr<< "GLEW: initialization failed\n\n";
}
glewSetupDone = true;
}
if (bufferState == BufferState::REALLOCATE || bufferState == BufferState::DIRTY )
renderer->updateHeightMap(width, height, scx, scy, (GLfloat*)grid.get(), true);
else
renderer->updateHeightMap(width, height, scx, scy, (GLfloat*)grid.get());
bufferState = BufferState::CLEAN;
}
void Terrain::draw(View * view, PMrender::TRenderer *renderer) const
{
updateBuffers(renderer);
// call draw function
renderer->draw(view);
}
void Terrain::buildSphereAccel()
{
int si, sj, i, j, imin, imax, jmin, jmax;
float rad, sqlen;
vpPoint p, c, b1, b2;
Vector del;
// cerr << "numspx = " << numspx << ", numspy = " << numspy << endl;
for(si = 0; si < numspx; si++)
for(sj = 0; sj < numspy; sj++)
{
imin = si*spherestep; imax = std::min(imin+spherestep, grid.width());
jmin = sj*spherestep; jmax = std::min(jmin+spherestep, grid.height());
// cerr << "(" << si << ", " << sj << ") = " << "i: " << imin << " - " << imax << " j: " << jmin << " - " << jmax << endl;
// center point
b1 = toWorld(imin, jmin, grid[jmin][imin]);
b2 = toWorld(imax, jmax, grid[jmax-1][imax-1]);
c.affinecombine(0.5f, b1, 0.5f, b2);
// update radius
rad = 0.0f;
for(j = jmin; j < jmax; j++)
for(i = imin; i < imax; i++)
{
p = toWorld(i, j, grid[j][i]);
del.diff(c, p);
sqlen = del.sqrdlength();
if(sqlen > rad)
rad = sqlen;
}
boundspheres[si][sj].center = c;
boundspheres[si][sj].radius = sqrtf(rad);
}
accelValid = true;
}
bool Terrain::rayIntersect(vpPoint start, Vector dirn, vpPoint & p)
{
int i, j, si, sj, imin, imax, jmin, jmax;
vpPoint currp;
float besttval, tval, dist;
bool found = false;
float tol = dimx / (float) (grid.width()-1); // set world space detection tolerance to approx half gap between grid points
besttval = 100000000.0f;
if(!accelValid)
buildSphereAccel();
// bounding sphere accel structure
for(si = 0; si < numspx; si++)
for(sj = 0; sj < numspy; sj++)
{
rayPointDist(start, dirn, boundspheres[si][sj].center, tval, dist);
if(dist <= boundspheres[si][sj].radius) // intersects enclosing sphere so test enclosed points
{
imin = si*spherestep; imax = std::min(imin+spherestep, grid.width());
jmin = sj*spherestep; jmax = std::min(jmin+spherestep, grid.height());
// check ray against grid points
for(j = jmin; j < jmax; j++)
for(i = imin; i < imax; i++)
{
currp = toWorld(i, j, grid[j][i]);
rayPointDist(start, dirn, currp, tval, dist);
if(dist < tol)
{
found = true;
if(tval < besttval)
{
besttval = tval;
p = currp;
}
}
}
}
}
return found;
}
bool Terrain::pick(int sx, int sy, View * view, vpPoint & p)
{
vpPoint start;
Vector dirn;
cerr << "sx = " << sx << ", sy = " << sy << endl;
// find ray params from viewpoint through screen <sx, sy>
view->projectingRay(sx, sy, start, dirn);
return rayIntersect(start, dirn, p);
}
bool Terrain::drapePnt(vpPoint pnt, vpPoint & drape)
{
float x, y, h, drapeh, u, v, h0, h1, ux, uy;
int cx, cy, dx, dy;
getGridDim(dx, dy);
toGrid(pnt, x, y, h); // locate point on base domain
// test whether point is in bounds
ux = (float) (dx-1) - pluszero;
uy = (float) (dy-1) - pluszero;
if(x < pluszero || y < pluszero || x > ux || y > uy)
return false;
// index of grid cell
cx = (int) floor(x);
cy = (int) floor(y);
// get parametric coordinates within grid cell
u = (x - (float) cx);
v = (y - (float) cy);
// bilinear interpolation
h0 = (1.0f - u) * grid[cy][cx] + u * grid[cy][cx+1];
h1 = (1.0f - u) * grid[cy+1][cx] + u * grid[cy+1][cx];
drapeh = (1.0f - v) * h0 + v * h1;
// this could be implemented using ray-triangle intersection
// but it would be much less efficient
drape = toWorld(x, y, drapeh);
return true;
}
void Terrain::loadTer(const uts::string &filename)
{
float sx, sy, step;
int dx, dy;
grid.read(filename);
dx = grid.width(); dy = grid.height();
step = grid.step();
sx = (float) grid.width() * step;
sy = (float) grid.height() * step;
init(dx, dy, sx, sy);
}
void Terrain::loadElv(const uts::string &filename)
{
float step, lat;
int dx, dy;
float val;
ifstream infile;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> dx >> dy;
infile >> step;
infile >> lat;
delGrid();
init(dx, dy, (float) dx * step, (float) dy * step);
latitude = lat;
for (int x = 0; x < dx; x++)
{
for (int y = 0; y < dy; y++)
{
infile >> val;
grid[x][y] = val * 0.3048f; // convert from feet to metres
}
}
setMidFocus();
infile.close();
}
else
{
cerr << "Error Terrain::loadElv:unable to open file " << filename << endl;
}
}
void Terrain::saveTer(const uts::string &filename)
{
grid.write(filename);
}
void Terrain::saveElv(const uts::string &filename)
{
float step;
int gx, gy;
float val;
ofstream outfile;
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
getGridDim(gx, gy);
step = grid.step();
outfile << gx << " " << gy << " " << step << " " << latitude << endl;
for (int x = 0; x < gx; x++)
{
for (int y = 0; y < gy; y++)
{
outfile << grid[x][y] << " ";
}
}
outfile << endl;
outfile.close();
}
else
{
cerr << "Error Terrain::loadElv:unable to open file " << filename << endl;
}
}
void Terrain::calcMeanHeight()
{
int i, j, cnt = 0;
hghtmean = 0.0f;
for(j = 0; j < grid.height(); j++)
for(i = 0; i < grid.width(); i++)
{
hghtmean += grid[j][i];
cnt++;
}
hghtmean /= (float) cnt;
}
void Terrain::getHeightBounds(float &minh, float &maxh)
{
int i, j;
float hght;
maxh = -10000000.0f;
minh = 100000000.0;
for(j = 0; j < grid.height(); j++)
for(i = 0; i < grid.width(); i++)
{
hght = grid[j][i];
if(hght < minh)
minh = hght;
if(hght > maxh)
maxh = hght;
}
}
| 15,326
|
C++
|
.cpp
| 519
| 23.379576
| 134
| 0.550657
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,177
|
pft.cpp
|
jgain_EcoLearn/UnderSim/sim/pft.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
// #include <fstream>
#include "pft.h"
////
// Viability
///
float Viability::eval(float val, float neg)
{
// evaluate exponential. Power term introduces flat top
float s = log(0.2f) / pow(r/2.0, 4.5f);
float v = pow(M_E, s * pow(fabs(val-c), 4.5f));
// adjust to include negative viability for stress purposes
v *= 1.0-neg;
v += neg;
return v;
}
////
// Biome
///
void Biome::categoryNameLookup(int idx, std::string &catName)
{
if(idx >= 1 && idx <= (int) catTable.size())
catName = catTable[idx-1]; // categories start at 1, whereas table is indexed from 0
else
catName = "OutOfCategoryTableRange";
}
float Biome::getMinIdealMoisture(int i)
{
float c, r;
char cmin, cmax;
pftypes[i].wet.getValues(cmin, cmax, c, r);
return c - 0.5f * r; // minimum water needed for survival
}
int Biome::getSubBiomeFromSpecies(int species)
{
if(subLookup[species] == -1)
{
cerr << "Error Biome::getSubBiomeFromSpecies: species " << species << " is not in the canopy list of any sub-biome" << endl;
return 0;
}
return subLookup[species];
}
float Biome::allometryCanopy(int pft, float height)
{
/*
// allometry-based approach
float radius;
if(pft == 0)
{
radius = 4.0f * height;
}
else
{
radius = exp(pftypes[pft].alm_a + pftypes[pft].alm_b * log(height)); // r = e ** (a + b ln(h))
}*/
// model-based approach
int vueid;
float radius = 0.0f;
if(pft == 0)
{
radius = 4.0f * height;
}
else
{
if(cdata != nullptr)
radius = cdata->modelsamplers.at(pft).sample_rh_ratio(height, &vueid) * height;
}
return radius;
}
float Biome::maxGrowthTest(int pft)
{
float hght = 0.0f;
// run mini growth simulation
for(int a = 0; a < pftypes[pft].maxage; a++)
for(int g = 0; g < pftypes[pft].grow_months; g++)
hght += growth(pft, hght, 1.0f);
return hght;
}
float Biome::growthfn(float t)
{
// sigmoidal-like (smoothstep) function for growth, accounting for maximum tree age and height
// bounds checks
if(t < 0.0f)
{
cerr << "Error Biome::growthfn: age is below zero" << endl;
return 0.0f;
}
if(t > 1.0f)
{
return 1.0f;
cerr << "Error Biome::growthfn: age is above maximum" << endl;
}
return t*t*(3.0f - 2.0f*t);
}
float Biome::invgrowthfn(float h)
{
// inverse of sigmoidal-like (smoothstep) function
// bounds checks
if(h < 0.0f)
{
cerr << "Error Biome::invgrowthfn: height is below zero" << endl;
return 0.0f;
}
if(h > 1.0f)
{
return 1.0f;
cerr << "Error Biome::invgrowthfn: height is above maximum" << endl;
}
return 0.5f - sinf(asinf(1.0f - 2.0f*h)/3.0f);
}
float Biome::growth(int pft, float currhght, float viability)
{
float hghtnorm, hghtincr, agenominal, ageincr;
ageincr = 1.0f / (float) (pftypes[pft].maxage * pftypes[pft].grow_months); // month in growing season as a proportion of overall growth lifespan
// find normalized nominal age on sigmoidal growth curve
// this does not correspond to actual age because of potentially stunted growth
hghtnorm = currhght / pftypes[pft].maxhght;
agenominal = invgrowthfn(hghtnorm);
hghtincr = pftypes[pft].maxhght * (growthfn(agenominal+ageincr) - growthfn(agenominal));
return hghtincr * viability;
}
float Biome::viability(int pft, float sunlight, float moisture, float temperature, float slope, std::vector<float> &adaptvals, float negval)
{
float val[4], vmin;
val[0] = pftypes[pft].sun.eval(sunlight, negval);
val[1] = pftypes[pft].wet.eval(moisture, negval);
val[2] = pftypes[pft].temp.eval(temperature, negval);
val[3] = pftypes[pft].slope.eval(slope, negval);
if (adaptvals.size() != 4)
adaptvals.resize(4);
memcpy(adaptvals.data(), val, sizeof(float) * 4);
// the least satisfied resource dominates, so find min value
vmin = val[0];
for(int i = 1; i < 4; i++)
vmin = fmin(vmin, val[i]);
return vmin;
}
bool Biome::overWet(int pft, float moisture)
{
return moisture > pftypes[pft].wet.c;
}
bool Biome::read_dataimporter(std::string cdata_fpath)
{
// data_importer::common_data cdata = data_importer::common_data(cdata_fpath);
cdata = new data_importer::common_data(cdata_fpath);
return read_dataimporter((* cdata));
}
float Biome::cullHght(int id)
{
float hght = 0.0f;
switch(id)
{
case 0:
hght = 0.05f;
break;
case 1:
hght = 0.1f;
break;
case 2:
hght = 0.1f;
break;
case 3:
hght = 0.1f;
break;
case 4:
hght = 0.1f;
break;
case 5:
hght = 0.2f;
break;
case 6:
hght = 0.1f;
break;
case 7:
hght = 0.25f;
break;
case 8:
hght = 0.25f;
break;
case 9:
hght = 0.25f;
break;
case 10:
hght = 0.25f;
break;
case 11:
hght = 0.25f;
break;
case 12:
hght = 0.25f;
break;
case 13:
hght = 0.25f;
break;
case 14:
hght = 0.3f;
break;
case 15:
hght = 0.2f;
break;
default:
hght = 0.1f;
break;
}
return hght;
}
bool Biome::read_dataimporter(data_importer::common_data &cdata)
{
pftypes.clear();
PFType pft;
int maxspec_id = -1;
// cerr << "--- BIOME READ FROM DATABASE ---" << endl;
for (auto &sppair : cdata.canopy_and_under_species)
{
data_importer::species &spec = sppair.second;
pft.code = spec.name;
for (int i = 0; i < 4; i++)
pft.basecol[i] = spec.basecol[i];
pft.draw_hght = spec.draw_hght;
pft.draw_radius = spec.draw_radius;
pft.draw_box1 = spec.draw_box1;
pft.draw_box2 = spec.draw_box2;
switch (spec.shapetype)
{
case (data_importer::treeshape::BOX):
pft.shapetype = TreeShapeType::BOX;
break;
case (data_importer::treeshape::CONE):
pft.shapetype = TreeShapeType::CONE;
break;
case (data_importer::treeshape::SPHR):
pft.shapetype = TreeShapeType::SPHR;
break;
case (data_importer::treeshape::INVCONE):
pft.shapetype = TreeShapeType::INVCONE;
break;
default:
assert(false);
break;
}
// cerr << "PFT " << pft.code << " shape type = " << pft.shapetype << endl;
pft.maxage = spec.maxage;
pft.maxhght = spec.maxhght;
pft.alpha = spec.alpha;
pft.sun.setValues(' ', ' ', spec.sun.c, spec.sun.r);
pft.wet.setValues(' ', ' ', spec.wet.c, spec.wet.r);
pft.temp.setValues(' ', ' ', spec.temp.c, spec.temp.r);
pft.slope.setValues(' ', ' ', spec.slope.c, spec.slope.r);
/*
cerr << pft.code << " " << "sun (" << spec.sun.c << ", " << spec.sun.r << ")" << " wet (" << spec.wet.c << ", " << spec.wet.r << ") ";
cerr << "slope (" << spec.slope.c << ", " << spec.slope.r << endl;
cerr << "alpha = " << pft.alpha << endl;
cerr << "age = " << pft.maxage << endl;
*/
pft.grow_start = spec.grow_start;
pft.grow_end = spec.grow_end;
pft.grow_months = spec.grow_months;
pft.alm_a = spec.a;
pft.alm_b = spec.b;
pft.alm_rootmult = 1.0f;
pft.grow_m = spec.grow_m;
pft.grow_c1 = spec.grow_c1;
pft.grow_c2 = spec.grow_c2;
pft.minhght = cullHght((int) pftypes.size());
pftypes.push_back(pft);
if (sppair.first > maxspec_id)
maxspec_id = sppair.first;
}
slopethresh = cdata.soil_info.slopethresh;
slopemax = cdata.soil_info.slopemax;
evaporation = cdata.soil_info.evap;
runofflevel = cdata.soil_info.runofflim;
soilsaturation = cdata.soil_info.soilsat;
waterlevel = cdata.soil_info.riverlevel;
subLookup.resize(maxspec_id + 1, -1);
for (const std::pair<int, data_importer::sub_biome> &sb : cdata.subbiomes_all_species)
{
SubBiome sbadd;
for (const data_importer::species_encoded &spec : sb.second.species)
{
if (spec.canopy)
subLookup[spec.id] = sb.first;
if (spec.canopy)
sbadd.canopies.push_back(spec.id);
else
sbadd.understorey.push_back(spec.id);
}
#ifndef NDEBUG
auto has_dupl = [](const std::vector<int> &vec, bool ignore = false, int ignoreval = -1)
{
for (int i = 0; i < vec.size(); i++)
{
for (int j = i + 1; j < vec.size(); j++)
{
if ((!ignore || (vec[i] != ignoreval)) && (vec[i] == vec[j]))
{
std::cerr << vec[i] << ", " << vec[j] << std::endl;
return true;
}
}
}
return false;
};
assert(!has_dupl(sbadd.canopies));
assert(!has_dupl(sbadd.understorey));
#endif
subTable.push_back(sbadd);
}
return true;
}
void Biome::sunmapping(PFType &pft, char cmin, char cmax)
{
float c, r, fmin, fmax;
// shade tolerance mapping
switch(cmin)
{
case 'L':
fmin = shadeLow;
break;
case 'M':
fmin = shadeMedium;
break;
case 'H':
fmin = shadeHigh;
break;
default:
cerr << "Biome::sunmapping: unrecognized shade code." << cmin << endl;
break;
}
// sun tolerance mapping
switch(cmax)
{
case 'L':
fmax = scorchLow;
break;
case 'M':
fmax = scorchMedium;
break;
case 'H':
fmax = scorchHigh;
break;
default:
cerr << "Biome::sunmapping: unrecognized scorch code." << cmax << endl;
break;
}
c = (fmax - fmin) / 2.0f + fmin;
r = (fmax - fmin);
pft.sun.setValues(cmin, cmax, c, r);
}
void Biome::wetmapping(PFType &pft, char cmin, char cmax)
{
float c, r, fmin, fmax;
// drought tolerance mapping
switch(cmin)
{
case 'L':
fmin = droughtLow;
break;
case 'M':
fmin = droughtMedium;
break;
case 'H':
fmin = droughtHigh;
break;
default:
cerr << "Biome::wetmapping: unrecognized moisture code." << endl;
break;
}
// flood tolerance mapping
switch(cmax)
{
case 'L':
fmax = floodLow;
break;
case 'M':
fmax = floodMedium;
break;
case 'H':
fmax = floodHigh;
break;
default:
cerr << "Biome::wetmapping: unrecognized moisture code." << endl;
break;
}
c = (fmax - fmin) / 2.0f + fmin;
r = (fmax - fmin);
pft.wet.setValues(cmin, cmax, c, r);
}
void Biome::tempmapping(PFType &pft, char cmin)
{
float c, r, fmin, fmax;
char cmax = 'E';
// lower temperature tolerance mapping
switch(cmin)
{
case 'L':
fmin = coldLow;
break;
case 'M':
fmin = coldMedium;
break;
case 'H':
fmin = coldHigh;
break;
case 'V': // very low cold tolerance
fmin = coldVeryLow;
break;
default:
cerr << "Biome::wetmapping: unrecognized temperature code." << endl;
break;
}
fmax = 35.0f; // fixed upper bound
c = (fmax - fmin) / 2.0f + fmin;
r = (fmax - fmin);
pft.temp.setValues(cmin, cmax, c, r);
}
void Biome::slopemapping(PFType &pft, char cmax)
{
float c, r, fmin, fmax;
char cmin = 'E';
// upper slope tolerance mapping
switch(cmax)
{
case 'M':
fmax = steepMedium;
break;
case 'H':
fmax = steepHigh;
break;
default:
cerr << "Biome::slopemapping: unrecognized slope code." << endl;
break;
}
fmin = -5.0f; // fixed lower bound
c = (fmax - fmin) / 2.0f + fmin;
r = (fmax - fmin);
pft.slope.setValues(cmin, cmax, c, r);
}
bool Biome::read(const std::string &filename)
{
int nb, nc, ns;
ifstream infile;
char cmin, cmax;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> name;
// cerr << "--- BIOME READ FROM FILE ---" << endl;
// plant functional types
infile >> nb; // number of pft
subLookup.resize(0);
subLookup.resize(nb, -1);
for(int t = 0; t < nb; t++)
{
PFType pft;
string shapestr;
infile >> pft.code >> pft.basecol[0] >> pft.basecol[1] >> pft.basecol[2] >> pft.draw_hght >> pft.draw_radius >> pft.draw_box1 >> pft.draw_box2;
infile >> shapestr;
if(shapestr == "SPHR")
pft.shapetype = TreeShapeType::SPHR;
else if(shapestr == "BOX")
pft.shapetype = TreeShapeType::BOX;
else if(shapestr == "CONE")
pft.shapetype = TreeShapeType::CONE;
else
cerr << "Error Biome::read: malformed shape type" << endl;
pft.basecol[3] = 1.0f;
infile >> pft.maxage;
infile >> pft.maxhght;
infile >> pft.alpha;
//cerr << pft.maxage << " " << pft.alpha << " ";
// viability response values
infile >> cmin >> cmax;
//cerr << cmin << " " << cmax << " ";
sunmapping(pft, cmin, cmax);
infile >> cmin >> cmax;
//cerr << cmin << " " << cmax << " ";
wetmapping(pft, cmin, cmax);
infile >> cmin;
//cerr << cmin << " ";
tempmapping(pft, cmin);
infile >> cmax;
//cerr << cmax << " ";
slopemapping(pft, cmax);
//< growth parameters
infile >> pft.growth_period;
//cerr << pft.growth_period << " ";
switch(pft.growth_period)
{
case 'S': // short growing season December to May
pft.grow_start = shortgrowstart;
pft.grow_end = shortgrowend;
pft.grow_months = shortgrowmonths;
break;
case 'L': // long growing season September to May
pft.grow_start = longgrowstart;
pft.grow_end = longgrowend;
pft.grow_months = longgrowmonths;
break;
default:
cerr << "Biome::read: incorrect growth period code in file" << endl;
// error message
break;
}
//< allometry parameters
infile >> pft.allometry_code;
//cerr << pft.allometry_code << " ";
switch(pft.allometry_code)
{
case 'A':
pft.alm_a = -0.584012589f;
pft.alm_b = 0.923859482f;
break;
case 'B':
pft.alm_a = -1.524125074f;
pft.alm_b = 0.976098575f;
break;
case 'C':
pft.alm_a = -1.8185f;
pft.alm_b = 1.1471f;
break;
case 'D':
pft.alm_a = -0.728451431f;
pft.alm_b = 0.656991006f;
break;
/*
case 'E':
pft.alm_a = 0.5f;
pft.alm_b = 0.0f;
break;*/
default:
cerr << "Biome::read: incorrect allometry code in file" << endl;
break;
}
pft.alm_rootmult = 1.0f;
infile >> pft.grow_m >> pft.grow_c1 >> pft.grow_c2;
//cerr << pft.grow_m << " " << pft.grow_c1 << " " << pft.grow_c2 << endl;
pft.minhght = cullHght((int) pftypes.size());
pftypes.push_back(pft);
}
// sub-biome names and species
infile >> ns; // number of categories
for(int s = 0; s < ns; s++)
{
SubBiome sb;
int over, under, spec;
infile >> sb.code;
infile >> over;
for(int o = 0; o < over; o++)
{
infile >> spec;
sb.canopies.push_back(spec);
subLookup[spec] = s;
std::cout << "For " << sb.code << ", adding subbiome " << s << " to lookup for canopy species " << spec << std::endl;
}
infile >> under;
for(int u = 0; u < under; u++)
{
infile >> spec;
sb.understorey.push_back(spec);
}
subTable.push_back(sb);
}
// category names
infile >> nc; // number of categories
for(int c = 0; c < nc; c++)
{
std::string str;
infile >> str;
catTable.push_back(str);
}
// soil moisture parameters
infile >> slopethresh;
infile >> slopemax;
infile >> evaporation;
infile >> runofflevel;
infile >> soilsaturation;
infile >> waterlevel;
infile.close();
return true;
}
else
{
cerr << "Error Biome::read: unable to open file" << filename << endl;
return false;
}
}
bool Biome::write(const std::string &filename)
{
ofstream outfile;
float c, r;
char cmin, cmax;
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
outfile << name << endl;
// plant functional types
outfile << numPFTypes() << endl;
for (int t = 0; t < numPFTypes(); t++)
{
outfile << pftypes[t].code << " " << pftypes[t].basecol[0] << " " << pftypes[t].basecol[1] << " " << pftypes[t].basecol[2] << " ";
outfile << pftypes[t].draw_hght << " " << pftypes[t].draw_radius << " " << pftypes[t].draw_box1 << " " << pftypes[t].draw_box2 << " ";
switch(pftypes[t].shapetype)
{
case TreeShapeType::SPHR:
outfile << "SPHR";
break;
case TreeShapeType::BOX:
outfile << "BOX";
break;
case TreeShapeType::CONE:
outfile << "CONE";
break;
}
outfile << endl;
// viability response values
outfile << pftypes[t].maxage << " " << pftypes[t].maxhght << " " << pftypes[t].alpha << " ";
pftypes[t].sun.getValues(cmin, cmax, c, r);
outfile << cmin << " " << cmax << " ";
pftypes[t].wet.getValues(cmin, cmax, c, r);
outfile << cmin << " " << cmax << " ";
pftypes[t].temp.getValues(cmin, cmax, c, r);
outfile << cmin << " ";
pftypes[t].slope.getValues(cmin, cmax, c, r);
outfile << cmax << " ";
//< growth and allometry parameters
outfile << pftypes[t].growth_period << " " << pftypes[t].allometry_code << " ";
outfile << pftypes[t].grow_m << " " << pftypes[t].grow_c1 << " " << pftypes[t].grow_c2 << endl;
}
// sub-biomes
outfile << (int) subTable.size() << endl;
for(int s = 0; s < (int) subTable.size(); s++)
{
outfile << subTable[s].code << " ";
int over = (int) subTable[s].canopies.size();
outfile << over << " ";
for(int o = 0; o < over; o++)
{
outfile << subTable[s].canopies[o] << " ";
}
int under = (int) subTable[s].understorey.size();
outfile << under << " ";
for(int u = 0; u < under; u++)
{
outfile << subTable[s].understorey[u] << " ";
}
outfile << endl;
}
// category names
outfile << (int) catTable.size() << endl;
for(int c = 0; c < (int) catTable.size(); c++)
outfile << catTable[c] << endl;
// soil moisture parameters
outfile << slopethresh << " ";
outfile << slopemax << " ";
outfile << evaporation << " ";
outfile << runofflevel << " ";
outfile << soilsaturation << " ";
outfile << waterlevel << endl;
outfile.close();
return true;
}
else
{
cerr << "Error Biome::write: unable to open file " << filename << endl;
return false;
}
}
void Biome::printParams()
{
char cmin, cmax;
float c, r;
for (int t = 0; t < numPFTypes(); t++)
{
cerr << pftypes[t].code << " [" << t << "]: " << endl;
// viability response values
pftypes[t].sun.getValues(cmin, cmax, c, r);
cerr << " sun: " << c << " " << r << endl;
pftypes[t].wet.getValues(cmin, cmax, c, r);
cerr << " wet: " << c << " " << r << endl;
pftypes[t].temp.getValues(cmin, cmax, c, r);
cerr << " temp: " << c << " " << r << endl;
pftypes[t].slope.getValues(cmin, cmax, c, r);
cerr << " slope: " << c << " " << r << endl << endl;
}
}
| 22,425
|
C++
|
.cpp
| 708
| 23.323446
| 155
| 0.518368
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,179
|
shape.cpp
|
jgain_EcoLearn/UnderSim/sim/shape.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
// constraint.cpp:
// author: James Gain
// date: 5 November 2013
// 21 January 2013 - curve constraints
#include <GL/glew.h>
#include "shape.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
//
// Shape
//
void Shape::setColour(GLfloat * col)
{
int i;
for(i = 0; i < 4; i++)
diffuse[i] = col[i];
for(i = 0; i < 3; i++)
ambient[i] = diffuse[i] * 0.75f;
ambient[3] = diffuse[3];
for(i = 0; i < 3; i++)
specular[i] = std::min(1.0f, diffuse[i] * 1.25f);
specular[3] = diffuse[3];
}
void Shape::genCylinder(float radius, float height, int slices, int stacks, glm::mat4x4 trm)
{
int i, j, base;
float a, x, y, h = 0.0f;
float stepa = PI2 / (float) slices;
float stepz = height / (float) stacks;
glm::vec4 p;
glm::vec3 v;
base = int(verts.size()) / 8;
for(i = 0; i <= stacks; i++)
{
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, h, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(x, y, 0.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
if(i > 0)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base+j);
indices.push_back(base-slices+j+1); indices.push_back(base+j+1); indices.push_back(base+j);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base+j);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+j);
}
}
a += stepa;
}
base += slices;
h += stepz;
}
}
void Shape::genCappedCylinder(float startradius, float endradius, float height, int slices, int stacks, glm::mat4x4 trm, bool clip)
{
int i, j, base;
float a, x, y, h = 0.0f, radius;
float stepa = PI2 / (float) slices;
float stepz = height / (float) stacks;
float stepr = (endradius - startradius) / (float) (stacks);
glm::vec4 p;
glm::vec3 v;
base = int(verts.size()) / 8;
radius = startradius;
for(i = 0; i <= stacks; i++)
{
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, h, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(x, y, 0.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
if(i > 0)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base+j);
indices.push_back(base-slices+j+1); indices.push_back(base+j+1); indices.push_back(base+j);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base+j);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+j);
}
}
a += stepa;
}
base += slices;
h += stepz;
radius += stepr;
}
// cap base
// lid center and rim
p = trm * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, -1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a = 0.0f; radius = startradius;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, 0.0f, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, -1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a += stepa;
}
// face indices
base += slices;
for (j = 0; j < slices; j++)
{
if(j < slices-1)
{
indices.push_back(base-slices+j+1);indices.push_back(base-slices+j); indices.push_back(base);
}
else // wrap
{
indices.push_back(base-slices); indices.push_back(base-slices+j);indices.push_back(base);
}
}
base++;
// cap lid
// lid center and rim
p = trm * glm::vec4(0.0f, 0.0f, height, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, 1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a = 0.0f; radius = endradius;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, height, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, 1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a += stepa;
}
// face indices
base += slices;
for (j = 0; j < slices; j++)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base);
}
}
}
void Shape::genCappedCone(float startradius, float height, int slices, int stacks, glm::mat4x4 trm, bool clip)
{
int i, j, base;
float endradius = 0.001f;
float a, x, y, h = 0.0f, radius;
float stepa = PI2 / (float) slices;
float stepz = height / (float) stacks;
float stepr = (endradius - startradius) / (float) (stacks);
glm::vec4 p;
glm::vec3 v;
base = int(verts.size()) / 8;
radius = startradius;
for(i = 0; i <= stacks; i++)
{
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, h, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(x, y, 0.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
if(i > 0)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base+j);
indices.push_back(base-slices+j+1); indices.push_back(base+j+1); indices.push_back(base+j);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base+j);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+j);
}
}
a += stepa;
}
base += slices;
h += stepz;
radius += stepr;
}
// cap base
// lid center and rim
p = trm * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, -1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a = 0.0f; radius = startradius;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, 0.0f, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, -1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a += stepa;
}
// face indices
base += slices;
for (j = 0; j < slices; j++)
{
if(j < slices-1)
{
indices.push_back(base-slices+j+1);indices.push_back(base-slices+j); indices.push_back(base);
}
else // wrap
{
indices.push_back(base-slices); indices.push_back(base-slices+j);indices.push_back(base);
}
}
}
void Shape::genPyramid(float baselen, float toplen, float height, glm::mat4x4 trm)
{
int i, base;
Vector v;
glm::vec4 p;
glm::vec3 n;
// base verts
vpPoint b[4];
b[0] = vpPoint(-baselen/2.0f, -baselen/2.0f, 0.0f);
b[1] = vpPoint(baselen/2.0f, -baselen/2.0f, 0.0f);
b[2] = vpPoint(baselen/2.0f, baselen/2.0f, 0.0f);
b[3] = vpPoint(-baselen/2.0f, baselen/2.0f, 0.0f);
// top verts
vpPoint t[4];
t[0] = vpPoint(-toplen/2.0f, -toplen/2.0f, height);
t[1] = vpPoint(toplen/2.0f, -toplen/2.0f, height);
t[2] = vpPoint(toplen/2.0f, toplen/2.0f, height);
t[3] = vpPoint(-toplen/2.0f, toplen/2.0f, height);
base = int(verts.size()) / 8;
// base vertices
v = Vector(0.0f, 0.0f, -1.0f);
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(b[i].x, b[i].y, b[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
// counterclockwise winding
indices.push_back(base+1); indices.push_back(base+0); indices.push_back(base+2);
indices.push_back(base+0); indices.push_back(base+3); indices.push_back(base+2);
base += 4;
// top vertices
v = Vector(0.0f, 0.0f, 1.0f);
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(t[i].x, t[i].y, t[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
indices.push_back(base+2); indices.push_back(base+0); indices.push_back(base+1);
indices.push_back(base+3); indices.push_back(base+0); indices.push_back(base+2);
base += 4;
// side vertices: -y
v = Vector(0.0f, -height, baselen-toplen);
v.normalize();
vpPoint s[4];
s[0] = b[0]; s[1] = b[1]; s[2] = t[1]; s[3] = t[0];
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(s[i].x, s[i].y, s[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
indices.push_back(base+2); indices.push_back(base+0); indices.push_back(base+1);
indices.push_back(base+3); indices.push_back(base+0); indices.push_back(base+2);
base += 4;
// side vertices: +y
v = Vector(0.0f, height, baselen-toplen);
v.normalize();
s[0] = b[2]; s[1] = b[3]; s[2] = t[3]; s[3] = t[2];
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(s[i].x, s[i].y, s[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
indices.push_back(base+2); indices.push_back(base+0); indices.push_back(base+1);
indices.push_back(base+3); indices.push_back(base+0); indices.push_back(base+2);
base += 4;
// side vertices: +x
v = Vector(height, 0.0f, baselen-toplen);
v.normalize();
s[0] = b[1]; s[1] = b[2]; s[2] = t[2]; s[3] = t[1];
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(s[i].x, s[i].y, s[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
indices.push_back(base+2); indices.push_back(base+0); indices.push_back(base+1);
indices.push_back(base+3); indices.push_back(base+0); indices.push_back(base+2);
base += 4;
// side vertices: -x
v = Vector(-height, 0.0f, baselen-toplen);
v.normalize();
s[0] = b[3]; s[1] = b[0]; s[2] = t[0]; s[3] = t[3];
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(s[i].x, s[i].y, s[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
indices.push_back(base+2); indices.push_back(base+0); indices.push_back(base+1);
indices.push_back(base+3); indices.push_back(base+0); indices.push_back(base+2);
base += 4;
}
void Shape::genSphereVert(float radius, float lat, float lon, glm::mat4x4 trm)
{
float la, lo, x, y, z;
glm::vec4 p;
glm::vec3 v;
la = PI+PI*lat;
lo = PI2*lon;
// this is unoptimized
x = cosf(lo)*sinf(la)*radius;
y = sinf(lo)*sinf(la)*radius;
z = cosf(la)*radius;
// apply transformation
p = trm * glm::vec4(x, y, z, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(x, y, z));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
}
void Shape::genSphere(float radius, int slices, int stacks, glm::mat4x4 trm)
{
int lat, lon, base;
float plat, plon;
// doesn't produce very evenly sized triangles, tend to cluster at poles
base = int(verts.size()) / 8;
for(lat = 0; lat <= stacks; lat++)
{
for(lon = 0; lon < slices; lon++)
{
plat = (float) lat / (float) stacks;
plon = (float) lon / (float) slices;
genSphereVert(radius, plat, plon, trm);
if(lat > 0)
{
if(lon < slices-1)
{
indices.push_back(base-slices+lon); indices.push_back(base-slices+lon+1); indices.push_back(base+lon);
indices.push_back(base-slices+lon+1); indices.push_back(base+lon+1); indices.push_back(base+lon);
}
else // wrap
{
indices.push_back(base-slices+lon); indices.push_back(base-slices); indices.push_back(base+lon);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+lon);
}
}
}
base += slices;
}
}
void Shape::genTest()
{
clear();
// single triangle
verts.push_back(-1.0f); verts.push_back(0.0f); verts.push_back(-1.0f); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(0.0f); verts.push_back(-1.0f); verts.push_back(0.0f); // normal
verts.push_back(-1.0f); verts.push_back(0.0f); verts.push_back(1.0f); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(0.0f); verts.push_back(-1.0f); verts.push_back(0.0f); // normal
verts.push_back(1.0f); verts.push_back(0.0f); verts.push_back(1.0f); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(0.0f); verts.push_back(-1.0f); verts.push_back(0.0f); // normal
indices.push_back(0);
indices.push_back(1);
indices.push_back(2);
}
void Shape::genCurve(std::vector<vpPoint> &curve, View * view, float thickness, float tol, bool closed, bool offset, bool viewadapt)
{
// Double the number of vertices actually required. Consider compacting later.
// This needs the view class because thickening happens orthogonal to the view direction
int i, j, lim, numv;
vpPoint s, e, p[4], m[4], os, oe, c;
Vector v, n, pv, pn, eye, negeye, off;
float width = thickness;
bool firstseg = true;
numv = int(verts.size()) / 8;
if((int) curve.size() > 0)
{
eye = view->getDir(); eye.normalize();
negeye = eye; negeye.mult(-1.0f); off = negeye; off.mult(0.005f);
if(closed)
lim = (int) curve.size();
else
lim = (int) curve.size()-1;
s = curve[0];
for(i = 0; i < lim; i++)
{
// current segment
if(closed)
e = curve[(i+1)%lim];
else
e = curve[i+1];
if(offset) // shift points closer to the viewpoint
{
// shift higher above terrain
off = Vector(0.0f, 0.001f, 0.0f);
// c = view->getCOP();
// off.diff(os, c); off.normalize(); off.mult(0.001f);
off.pntplusvec(s, &os);
off.pntplusvec(e, &oe);
}
else
{
os = s; oe = e;
}
v.diff(os, oe);
if(v.length() > tol) // ignore points that are too close together
{
v.normalize();
// find vector orthogonal to segment but parallel to the viewing plane
n.cross(v, eye);
n.normalize();
if(viewadapt) // consider distance from viewpoint
{
// broken - fix if needed
c = view->getCOP();
off.diff(c, os);
n.mult(width * (65.0f * off.length()));
}
else
n.mult(width);
// construct line quad vertices
n.pntplusvec(oe, &p[1]);
n.pntplusvec(os, &p[0]);
n.mult(-1.0f);
n.pntplusvec(os, &p[3]);
n.pntplusvec(oe, &p[2]);
// find normal
n = negeye;
for(j = 0; j < 4; j++)
{
verts.push_back(p[j].x); verts.push_back(p[j].y); verts.push_back(p[j].z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.i); verts.push_back(n.j); verts.push_back(n.k); // normal
}
indices.push_back(numv+0); indices.push_back(numv+1); indices.push_back(numv+3);
indices.push_back(numv+2); indices.push_back(numv+3); indices.push_back(numv+1);
numv += 4;
// mitres to previous segment
if(firstseg)
{
if(closed)
{
// calculate thickening for closing the loop
s = curve[(int) curve.size()-1]; e = curve[0];
v.diff(os, oe);
v.normalize();
n.cross(v, eye);
n.normalize();
if(viewadapt)
{
c = view->getCOP();
off.diff(c, os);
n.mult(width * (65.0f * off.length()));
}
else
n.mult(width);
n.pntplusvec(os, &m[0]);
n.mult(-1.0f);
n.pntplusvec(os, &m[1]);
m[2] = p[0]; m[3] = p[3];
n = negeye;
for(j = 0; j < 4; j++)
{
verts.push_back(m[j].x); verts.push_back(m[j].y); verts.push_back(m[j].z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.i); verts.push_back(n.j); verts.push_back(n.k); // normal
}
indices.push_back(numv+0); indices.push_back(numv+1); indices.push_back(numv+3);
indices.push_back(numv+2); indices.push_back(numv+3); indices.push_back(numv+1);
numv += 4;
}
firstseg = false;
}
else
{
// m[1] and m[2] already stored from previous iteration
m[0] = p[0]; m[3] = p[3];
n = negeye;
verts.push_back(os.x); verts.push_back(os.y); verts.push_back(os.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.i); verts.push_back(n.j); verts.push_back(n.k); // normal
for(j = 0; j < 4; j++)
{
verts.push_back(m[j].x); verts.push_back(m[j].y); verts.push_back(m[j].z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.i); verts.push_back(n.j); verts.push_back(n.k); // normal
}
indices.push_back(numv+0); indices.push_back(numv+2); indices.push_back(numv+1);
indices.push_back(numv+0); indices.push_back(numv+4); indices.push_back(numv+3);
numv += 5;
}
m[1] = p[1];
m[2] = p[2];
s = e;
}
}
}
}
void Shape::genCylinderCurve(std::vector<vpPoint> &curve, float radius, float tol, int slices)
{
int i, j, lim, base;
vpPoint s, e;
Vector v, vfin, vstart, vrot;
glm::mat4x4 idt, tfm;
glm::vec3 trs, n, rot;
float angle, a, x, y, stepa = PI2 / (float) slices;
glm::vec4 p;
base = int(verts.size()) / 8;
if((int) curve.size() > 1)
{
lim = (int) curve.size()-1;
s = curve[0]; s.y += 0.05f;
for(i = 0; i < lim; i++)
{
e = curve[i+1]; e.y += 0.05f;
v.diff(s, e);
if(i == 0) // base stack
{
// translate to s
idt = glm::mat4(1.0f);
trs = glm::vec3(s.x, s.y, s.z);
tfm = glm::translate(idt, trs);
// azimuth rotation
vfin = v;
vfin.j = 0.0f; vfin.normalize();
angle = RAD2DEG * atan2(vfin.k, vfin.i);
if(angle < 0.0f)
angle += 360.0f;
rot = glm::vec3(0.0f, -1.0f, 0.0f);
tfm = glm::rotate(tfm, glm::radians(angle), rot);
// elevation rotation
/*
v.normalize();
rot = glm::vec3(-1.0f, 0.0f, 0.0f);
angle = RAD2DEG * acosf(v.dot(vfin));
tfm = glm::rotate(tfm, glm::radians(angle), rot);*/
// create cylinder from s to e
// genCylinder(radius, v.length(), slices, 1, tfm);
// single cylinder stack linking to previous stack as necessary
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
p = tfm * glm::vec4(0.0f, y, x, 1.0f);
n = glm::mat3(tfm) * glm::normalize(glm::vec3(0.0f, y, x));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
a -= stepa;
}
base += slices;
}
else
{
if(v.length() > tol || i == lim-1) // ignore points that are too close together, except for last segment
{
// translate to e
idt = glm::mat4(1.0f);
trs = glm::vec3(e.x, e.y, e.z);
tfm = glm::translate(idt, trs);
// azimuth rotation
vfin = v;
vfin.j = 0.0f; vfin.normalize();
angle = RAD2DEG * atan2(vfin.k, vfin.i);
if(angle < 0.0f)
angle += 360.0f;
rot = glm::vec3(0.0f, -1.0f, 0.0f);
tfm = glm::rotate(tfm, glm::radians(angle), rot);
// elevation rotation
/*
v.normalize();
rot = glm::vec3(-1.0f, 0.0f, 1.0f);
angle = RAD2DEG * acosf(v.dot(vfin));
tfm = glm::rotate(tfm, glm::radians(angle), rot);*/
// single cylinder stack linking to previous stack as necessary
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
p = tfm * glm::vec4(0.0f, y, x, 1.0f);
n = glm::mat3(tfm) * glm::normalize(glm::vec3(0.0f, y, x));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
if(i > 0)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base+j);
indices.push_back(base-slices+j+1); indices.push_back(base+j+1); indices.push_back(base+j);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base+j);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+j);
}
}
a -= stepa;
}
base += slices;
s = e;
}
}
}
}
}
void Shape::genDashedCylinderCurve(std::vector<vpPoint> &curve, float radius, float tol, float dashlen, int slices)
{
int i, j, lim, base;
vpPoint s, e;
Vector v, vfin, vstart, vrot;
glm::mat4x4 idt, tfm;
glm::vec3 trs, n, rot;
float angle, a, x, y, stepa = PI2 / (float) slices, dashaccum = 0.0f;
glm::vec4 p;
bool dashon = true;
base = int(verts.size()) / 8;
if((int) curve.size() > 1)
{
lim = (int) curve.size()-1;
s = curve[0]; s.y += 0.05f;
for(i = 0; i < lim; i++)
{
e = curve[i+1]; e.y += 0.05f;
v.diff(s, e);
if(i == 0) // base stack
{
// translate to s
idt = glm::mat4(1.0f);
trs = glm::vec3(s.x, s.y, s.z);
tfm = glm::translate(idt, trs);
// azimuth rotation
vfin = v;
vfin.j = 0.0f; vfin.normalize();
angle = RAD2DEG * atan2(vfin.k, vfin.i);
if(angle < 0.0f)
angle += 360.0f;
rot = glm::vec3(0.0f, -1.0f, 0.0f);
tfm = glm::rotate(tfm, glm::radians(angle), rot);
// single cylinder stack linking to subsequent stacks as necessary
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
p = tfm * glm::vec4(0.0f, y, x, 1.0f);
n = glm::mat3(tfm) * glm::normalize(glm::vec3(0.0f, y, x));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
a -= stepa;
}
base += slices;
}
else
{
if(v.length() > tol || i == lim-1) // ignore points that are too close together, except for last segment
{
dashaccum += v.length();
if(dashaccum >= dashlen) // toggle whether or not to draw dash
{
dashon = !dashon;
dashaccum = 0.0f;
}
// TO DO: cap cylinder
// translate to e
idt = glm::mat4(1.0f);
trs = glm::vec3(e.x, e.y, e.z);
tfm = glm::translate(idt, trs);
// azimuth rotation
vfin = v;
vfin.j = 0.0f; vfin.normalize();
angle = RAD2DEG * atan2(vfin.k, vfin.i);
if(angle < 0.0f)
angle += 360.0f;
rot = glm::vec3(0.0f, -1.0f, 0.0f);
tfm = glm::rotate(tfm, glm::radians(angle), rot);
// elevation rotation
/*
v.normalize();
rot = glm::vec3(-1.0f, 0.0f, 1.0f);
angle = RAD2DEG * acosf(v.dot(vfin));
tfm = glm::rotate(tfm, angle, rot);*/
// single cylinder stack linking to previous stack as necessary
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
p = tfm * glm::vec4(0.0f, y, x, 1.0f);
n = glm::mat3(tfm) * glm::normalize(glm::vec3(0.0f, y, x));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
if(i > 0 && dashon)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base+j);
indices.push_back(base-slices+j+1); indices.push_back(base+j+1); indices.push_back(base+j);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base+j);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+j);
}
}
a -= stepa;
}
base += slices;
s = e;
}
}
}
}
}
void Shape::genSphereCurve(std::vector<vpPoint> &curve, float thickness)
{
int i;
glm::mat4 tfm, idt;
glm::vec3 trs;
// assume view transformations are set up correctly
if((int) curve.size() > 0)
{
for(i = 0; i < (int) curve.size(); i++)
{
idt = glm::mat4(1.0f);
trs = glm::vec3(curve[i].x, curve[i].y, curve[i].z);
tfm = glm::translate(idt, trs);
genSphere(thickness, 10, 10, tfm);
}
}
}
ShapeDrawData Shape::getDrawParameters()
{
ShapeDrawData sdd;
sdd.VAO = vaoConstraint;
for(int i = 0; i < 4; i++)
sdd.diffuse[i] = diffuse[i];
for(int i = 0; i < 4; i++)
sdd.specular[i] = specular[i];
for(int i = 0; i < 4; i++)
sdd.ambient[i] = ambient[i];
sdd.indexBufSize = (int) indices.size();
sdd.numInstances = numInstances;
sdd.texID = 0;
sdd.current = false; // default setting
return sdd;
}
bool Shape::bindInstances(View * view, std::vector<glm::mat4> * iforms, std::vector<glm::vec4> * icols)
{
if((int) indices.size() > 0 && ((int) iforms->size() == (int) icols->size()))
{
if (vboConstraint != 0)
{
glDeleteVertexArrays(1, &vaoConstraint);
glDeleteBuffers(1, &vboConstraint);
glDeleteBuffers(1, &iboConstraint);
glDeleteBuffers(1, &iBuffer);
glDeleteBuffers(1, &cBuffer);
vaoConstraint = 0;
vboConstraint = 0;
iboConstraint = 0;
iBuffer = 0;
cBuffer = 0;
}
// vao
glGenVertexArrays(1, &vaoConstraint);
glBindVertexArray(vaoConstraint);
// vbo
// set up vertex buffer and copy in data
glGenBuffers(1, &vboConstraint);
glBindBuffer(GL_ARRAY_BUFFER, vboConstraint);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*(int) verts.size(), (GLfloat *) &verts[0], GL_STATIC_DRAW);
// ibo
glGenBuffers(1, &iboConstraint);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboConstraint);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*(int) indices.size(), (GLuint *) &indices[0], GL_STATIC_DRAW);
// enable position attribute
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), (void*)(0));
// enable texture coord attribute
const int sz = 3*sizeof(GLfloat);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), (void*)(sz) );
// enable normals
const int nz = 5*sizeof(GLfloat);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), (void*)(nz) );
// we need a full mat4 because the plant dimensions (non-uniform scale) as well as position are being instanced
glGenBuffers(1, &iBuffer); // create a vertex buffer object for plant transform instancing
glBindBuffer(GL_ARRAY_BUFFER, iBuffer);
if((int) iforms->size() > 0) // load instance data
{
numInstances = (int) iforms->size();
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::mat4) * numInstances, (GLfloat *) & (* iforms)[0], GL_DYNAMIC_DRAW);
}
else // create a single instance
{
numInstances = 1;
std::vector<glm::mat4> tmpform;
glm::mat4 idt = glm::mat4(1.0f);
tmpform.push_back(idt);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::mat4) * numInstances, (GLfloat *) &tmpform[0], GL_DYNAMIC_DRAW);
}
glBindBuffer(GL_ARRAY_BUFFER, iBuffer);
for (unsigned int i = 0; i < 4 ; i++) {
glEnableVertexAttribArray(3 + i);
glVertexAttribPointer(3 + i, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4),
(const GLvoid*)(sizeof(GLfloat) * i * 4));
glVertexAttribDivisor(3 + i, 1);
}
glGenBuffers(1, &cBuffer); // create a vertex buffer object for plant colour instancing
glBindBuffer(GL_ARRAY_BUFFER, cBuffer);
// colour buffer to allow subtle variations in plant colour
if((int) icols->size() > 0)
{
numInstances = (int) icols->size();
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4) * numInstances, (GLfloat *) & (* icols)[0], GL_DYNAMIC_DRAW);
}
else // a single colour instance, with no change to the underlying colour
{
numInstances = 1;
std::vector<glm::vec4> tmpcol;
glm::vec4 idt = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
tmpcol.push_back(idt);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4) * numInstances, (GLfloat *) &tmpcol[0], GL_DYNAMIC_DRAW);
}
glBindBuffer(GL_ARRAY_BUFFER, cBuffer);
glEnableVertexAttribArray(7);
glVertexAttribPointer(7, 4, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)0); // stride may need adjusting here
// glVertexAttribPointer(7, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), (const GLvoid*)0);
glVertexAttribDivisor(7, 1);
glBindVertexArray(0);
return true;
}
else
{
// cerr << "indices = " << (int) indices.size() << " iforms = " << (int) iforms->size() << " icols = " << (int) icols->size() << endl;
return false;
}
}
| 39,773
|
C++
|
.cpp
| 924
| 31.19697
| 142
| 0.502299
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,181
|
waterfill.cpp
|
jgain_EcoLearn/UnderSim/sim/waterfill.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "waterfill.h"
#include "terrain.h"
#include <QPoint>
#include <iostream>
#include <stack>
#include <queue>
#include <set>
void WaterFill::setTerrain(Terrain* t)
{
terrain = t;
}
bool WaterFill::isFlowingWater(uint x, uint y)
{
uint w, h;
terrain->getGridDim(w, h);
return flow[x+y*w] >absorbsion;
}
float WaterFill::riverMoisture(uint x, uint y)
{
uint w, h;
terrain->getGridDim(w, h);
return float(river_side[x + y*w]) / float(absorbsion);
}
struct Pass
{
Pass(){}
Pass (uint rid, uint did, float h) : rcv_id{rid}, donnor_id{did}, height{h}{}
uint rcv_id; // hight part
uint donnor_id; // low part (root)
float height;
};
bool operator < (const Pass& a, const Pass& b) {if(a.height == b.height) return a.donnor_id < b.donnor_id; else return a.height < b.height;}
template<class T, int n>
static void shuffle(T* vec)
{
for(int i = n-1; i>=1; --i)
{
int j = rand() % (i+1);
std::swap(vec[i], vec[j]);
}
}
void WaterFill::compute(uint step)
{
uint dx, dy;
terrain->getGridDim(dx, dy);
flow.resize(dx * dy+1, 0);
lakes.resize(dx * dy, 0.0);
uint s_alloc = dx * dy;
std::vector<uint> rcv(s_alloc, s_alloc);
std::vector<uint> donnor_start(s_alloc+1, 0);
std::vector<uint> donnor_end(s_alloc+1);
std::vector<uint> donnors(s_alloc);
std::vector<uint> parse_order;
parse_order.reserve(s_alloc);
std::vector<bool> in_resolve_stack(s_alloc, false);
std::vector<uint> catchement_root(s_alloc, (uint)(-1));
std::vector<uint> to_resolve, loc_min;
std::vector<Pass> catchement_pass(s_alloc);
std::set<Pass> wait_passes;
std::vector<std::set<Pass>::iterator> catchement_wait_pass(s_alloc, wait_passes.end());
QPoint shift [4];
shift[0] = QPoint(-1, 0);
shift[1] = QPoint(1, 0);
shift[2] = QPoint(0, -1);
shift[3] = QPoint(0, 1);
for(uint x = 0; x< dx; ++x)
for(uint y = 0; y< dy; ++y)
{
// get lowest neighbor
QPoint p(x, y);
QPoint nb = p;
double this_h = (double) terrain->getHeight((int) x, (int) y);
double h = this_h;
shuffle<QPoint, 4>(shift);
for(int j =0; j<4; ++j)
{
QPoint cur = p + shift[j];
if(cur.x()<0.0 || cur.x() >= (int) dx || cur.y()<0.0 || cur.y() >= (int) dy)
continue;
double ch = (double) terrain->getHeight((int) cur.x(), (int) cur.y());
if(h > ch)
{
nb = cur;
h = ch;
}
}
uint cur_id = x + y * dx;
if(nb != p)
rcv[cur_id] = nb.x() + nb.y() * dx;
else
{
catchement_root[cur_id] = cur_id;
// add external local min as to resolve
if(x == 0 || y == 0 || x == dx-1 || y == dy-1)
{
to_resolve.push_back(cur_id);
in_resolve_stack[cur_id] = true;
catchement_pass[cur_id].height = this_h;
catchement_pass[cur_id].donnor_id = cur_id;
catchement_pass[cur_id].rcv_id = cur_id;
}
}
}
// compute donnors
for(uint id : rcv)
++donnor_start[id];
uint total = 0;
for(uint& c : donnor_start)
{
uint tmp = c;
c = total;
total += tmp;
}
donnor_end = donnor_start;
for(uint i = 0; i< s_alloc; ++i)
donnors[donnor_end[rcv[i]]++] = i;
// first upstream parse to mark catchments
std::stack<uint> parse_stack;
//local min are stored as donnors of the last element
for(uint i = donnor_start[s_alloc]; i <donnors.size(); ++i)
parse_stack.push(donnors[i]);
while(!parse_stack.empty())
{
uint cur = parse_stack.top();
parse_stack.pop();
uint root = catchement_root[cur];
for(uint c = donnor_start[cur]; c<donnor_end[cur]; ++c)
{
uint d = donnors[c];
catchement_root[d] = root;
parse_stack.push(d);
}
}
// add all passes toward the boudary
std::vector<uint> to_parse(2*dx+2*dy);
for(uint i =0; i<dx; ++i)
{
to_parse.push_back(i);
to_parse.push_back(dx * (dy-1) + i);
}
for(uint i =0; i< dy; ++i)
{
to_parse.push_back(i*dx);
to_parse.push_back((i+1)*dx-1);
}
for(uint id : to_parse)
{
double ch = (double) terrain->getFlatHeight((int) id);
uint root = catchement_root[id];
if(!in_resolve_stack[root])
{
std::set<Pass>::iterator pass_it = catchement_wait_pass[root];
if(pass_it == wait_passes.end())
{
catchement_wait_pass[root] = wait_passes.insert(Pass(root, root, ch)).first;
}
else if(pass_it->height > ch)
{
wait_passes.erase(pass_it);
catchement_wait_pass[root] = wait_passes.insert(Pass(root, root, ch)).first;
}
}
}
loc_min = to_resolve;
uint n_step = 0;
// loop while there are some un-resolved catchments
while(true)
{
// parse all curent catchments and update passes
for(uint i = 0; i<to_resolve.size(); ++i)
{
uint cur_loc_min = to_resolve[i];
// parse catchment.
parse_stack.push(cur_loc_min);
while(!parse_stack.empty())
{
uint cur = parse_stack.top();
// this parse order is supposed to be correct with respect to drainage
parse_order.push_back(cur);
parse_stack.pop();
for(uint c = donnor_start[cur]; c<donnor_end[cur]; ++c)
{
uint d = donnors[c];
parse_stack.push(d);
}
QPoint p(cur%dx, cur/dx);
double ch = terrain->getHeight((int) p.x(), (int) p.y());
shuffle<QPoint, 4>(shift);
for(int j =0; j<4; ++j)
{
QPoint nb = p + shift[j];
if(nb.x()<0.0 || nb.x() >= (int) dx || nb.y()<0.0 || nb.y() >= (int) dy)
continue;
uint nb_id = nb.x() + nb.y() * dx;
uint nb_root = catchement_root[nb_id];
if(!in_resolve_stack[nb_root])
{
std::set<Pass>::iterator pass_it = catchement_wait_pass[nb_root];
if(pass_it == wait_passes.end())
{
catchement_wait_pass[nb_root] = wait_passes.insert(Pass(cur, nb_root, ch)).first;
}
else if(pass_it->height > ch)
{
wait_passes.erase(pass_it);
catchement_wait_pass[nb_root] = wait_passes.insert(Pass(cur, nb_root, ch)).first;
}
}
}
}
}
if(n_step++ == step)
break;
// save min pass.
if(wait_passes.empty())
break;
std::set<Pass>::iterator min_pass_it = wait_passes.begin();
Pass& pass = catchement_pass[min_pass_it->donnor_id];
pass = *min_pass_it;
wait_passes.erase(min_pass_it);
// pass higth is the higher along the path
pass.height = std::max(pass.height, catchement_pass[catchement_root[pass.rcv_id]].height);
// add to stack
in_resolve_stack[pass.donnor_id] = true;
to_resolve.resize(1);
to_resolve.front() = pass.donnor_id;
}
// compute drainage along reverse parse order
for(int i = 0; i< (int) flow.size(); ++i)
flow[i] = inflow[i]+1;
for(int i = (int)s_alloc-1; i>=0; --i)
{
uint id = parse_order[i];
if(id == catchement_root[id])
{
Pass& p = catchement_pass[id];
if(p.donnor_id != p.rcv_id)
flow[p.rcv_id]+=flow[id];
}
flow[rcv[id]]+=flow[id];
}
flow.resize(flow.size()-1);
// std::vector<uint> dbg_pass;
// std::vector<uint> dbg_l_min;
// std::vector<uint> dbg_crests;
// and lakes
for(uint i = 0; i< lakes.size(); ++i)
{
uint root = catchement_root[i];
const Pass& p = catchement_pass[root];
// if(i == root)
// dbg_l_min.push_back(p.donnor_id);
// if(p.donnor_id == p.rcv_id)
// continue;
// if(i == root)
// {
// dbg_pass.push_back(p.rcv_id);
// }
double h = terrain->getFlatHeight(i);
lakes[i] = std::max(0.0, p.height - h);
if(p.height > h)
flow[i] = flow[root];
}
// for(uint i : dbg_pass)
// lakes[i] = -1.0;
// for(uint i : dbg_l_min)
// lakes[i] = -2.0;
// for(uint i : dbg_crests)
// lakes[i] = -3.0;
}
void WaterFill::expandRivers(float max_moisture_factor, float slope_effect)
{
std::vector<uint> newFlow(flow.size(), 0);
int dx, dy;
terrain->getGridDim(dx, dy);
float cell_width = std::sqrt(terrain->getCellArea());
for(uint i =0; i<flow.size(); ++i)
{
// compute actual drainage
uint f = flow[i];
float drainage = float(f) * precipitation * terrain->getCellArea();
float river_width = std::sqrt(drainage) * river_width_constant;
int i_width = std::floor(river_width/2 / cell_width);
int p_x = ((int) i)%dx;
int p_y = ((int) i)/dx;
for(int x = std::max(0, p_x - i_width); x <= std::min(dx-1, p_x+i_width); ++x)
for(int y = std::max(0, p_y - i_width); y <= std::min(dy-1, p_y+i_width); ++y)
{
float tx = float(p_x-x);
float ty = float(p_y-y);
if(tx*tx+ty*ty <= float(i_width*i_width))
{
uint& nf = newFlow[x+dx*y];
nf = std::max(f, nf);
}
}
}
flow = newFlow;
river_side = std::vector<uint>(flow.size(), 0);
for(uint i =0; i<newFlow.size(); ++i)
{
// compute actual drainage
uint f = newFlow[i];
if(f<absorbsion)
continue;
float drainage = float(f) * precipitation * terrain->getCellArea();
float river_width = std::sqrt(drainage) * river_width_constant * max_moisture_factor;
float normalized = river_width/2 / cell_width;
int i_width = std::ceil(normalized);
int p_x = ((int) i)%dx;
int p_y = ((int) i)/dx;
float p_h = terrain->getFlatHeight(i);
for(int x = std::max(0, p_x - i_width); x <= std::min(dx-1, p_x+i_width); ++x)
for(int y = std::max(0, p_y - i_width); y <= std::min(dy-1, p_y+i_width); ++y)
{
float tx = float(p_x-x);
float ty = float(p_y-y);
float h = terrain->getHeight(x, y);
float d = std::sqrt(float(tx*tx+ty*ty));
// float sdx = dx*terrain->scale().x();
// float sdy = dy*terrain->scale().y();
float sdx = tx*terrain->getCellExtent();
float sdy = ty*terrain->getCellExtent();
float sd = std::sqrt(float(sdx*sdx+sdy*sdy));
//float slope = std::max(0.0f, h-p_h) / d;
float slope = (h-p_h) /sd ;
float moisture = std::max(0.0f, normalized - d*(1.0f + slope_effect * slope)) / normalized ;
uint& nf = flow[x+dx*y];
nf = std::max(uint(moisture * float(absorbsion)) , nf);
uint& rs = river_side[x+dx*y];
rs = std::max(uint(moisture * float(absorbsion)) , rs);
}
}
}
void WaterFill::reset()
{
uint dx, dy;
terrain->getGridDim(dx, dy);
inflow = std::vector<uint>(dx * dy+1, 0);
}
void WaterFill::addWaterInflow(uint x, uint y, int delta)
{
uint dx, dy;
terrain->getGridDim(dx, dy);
uint& inf = inflow[x+y*dx];
if(inf == 0 && delta > 0)
delta = absorbsion+1;
inf = std::max(0, (int)inf + delta);
}
void WaterFill::smartWaterInflow(uint x, uint y)
{
uint dx, dy;
terrain->getGridDim(dx, dy);
uint& inf = inflow[x+y*dx];
uint fl = flow[x+y*dx];
if(inf == 0) inf = absorbsion+1;
else
{
float river_w = std::sqrt(double(inf+fl)*precipitation)*river_width_constant+1.0;
// std::cerr << "New flow: " << inf << std::endl;
inf = uint(river_w*river_w / precipitation/river_width_constant/river_width_constant - (float)fl);
}
// std::cerr << "New flow: " << inf << std::endl;
}
| 13,904
|
C++
|
.cpp
| 383
| 27.180157
| 140
| 0.510421
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,182
|
descriptor.cpp
|
jgain_EcoLearn/UnderSim/sim/descriptor.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems (Undergrowth simulator)
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "descriptor.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
// #include <sstream>
using namespace std;
bool MapDescriptor::read(std::string filename)
{
ifstream infile;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> gx >> gy;
initMap();
for (int x = 0; x < gx; x++)
{
for (int y = 0; y < gy; y++)
{
SampleDescriptor sd;
infile >> sd.slope;
infile >> sd.moisture[0] >> sd.moisture[1];
infile >> sd.sunlight[0] >> sd.sunlight[1];
infile >> sd.temperature[0] >> sd.temperature[1];
infile >> sd.age;
set(x, y, sd);
}
}
infile.close();
return true;
}
else
{
cerr << "Error MapDescriptor::read: unable to open file" << filename << endl;
return false;
}
}
bool MapDescriptor::write(std::string filename)
{
ofstream outfile;
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
outfile << gx << " " << gy << endl;
for (int x = 0; x < gx; x++)
for (int y = 0; y < gy; y++)
{
SampleDescriptor sd = get(x, y);
outfile << sd.slope << " ";
outfile << sd.moisture[0] << " " << sd.moisture[1] << " ";
outfile << sd.sunlight[0] << " " << sd.sunlight[1] << " ";
outfile << sd.temperature[0] << " " << sd.temperature[1] << " ";
outfile << sd.age << " ";
}
outfile.close();
return true;
}
else
{
cerr << "Error MapDescriptor::write: unable to write file" << filename << endl;
return false;
}
}
| 2,808
|
C++
|
.cpp
| 81
| 27.567901
| 87
| 0.52965
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,184
|
exrrewrite.cpp
|
jgain_EcoLearn/UnderSim/common/exrrewrite.cpp
|
#include <iostream>
#include <algorithm>
#include <common/debug_vector.h>
#include <utility>
#include <memory>
#include <cstddef>
#include <thread>
#include <boost/program_options.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <ImfFrameBuffer.h>
#include <ImfInputFile.h>
#include <ImfOutputFile.h>
#include <ImfChannelList.h>
//#include <omp.h>
#include "region.h"
namespace po = boost::program_options;
namespace
{
namespace Option
{
/** @name Tokens for the option parser @{ */
static const char *inputFile() { return "input"; }
static const char *outputFile() { return "output"; }
static const char *resolution() { return "resolution"; }
static const char *region() { return "region"; }
static const char *origin() { return "origin"; }
static const char *help() { return "help"; }
/** @} */
} // namespace Option
} // anonymous namespace
static void usage(std::ostream &o, const po::options_description desc)
{
o << "Usage: exrrewrite [options] input.exr output.exr\n\n";
o << desc;
}
static po::variables_map processOptions(int argc, char **argv)
{
po::positional_options_description positional;
positional.add(Option::inputFile(), 1);
positional.add(Option::outputFile(), 1);
po::options_description desc("General options");
desc.add_options()
(Option::resolution(), po::value<float>(), "set spatial resolution (metres per sample)")
(Option::region(), po::value<std::string>(), "pick out a region (x0,y0,width,height)")
(Option::origin(), po::value<std::string>(), "set new region origin (x,y)")
(Option::help(), "show help");
po::options_description hidden("Hidden options");
hidden.add_options()
(Option::inputFile(), po::value<std::string>(), "input file")
(Option::outputFile(), po::value<std::string>(), "output file");
po::options_description all("All options");
all.add(desc);
all.add(hidden);
try
{
po::variables_map vm;
po::store(po::command_line_parser(argc, argv)
.style(po::command_line_style::default_style & ~po::command_line_style::allow_guessing)
.options(all)
.positional(positional)
.run(), vm);
po::notify(vm);
if (vm.count(Option::help()))
{
usage(std::cout, desc);
std::exit(0);
}
if (!vm.count(Option::inputFile()))
throw po::error("Input file must be specified");
if (!vm.count(Option::outputFile()))
throw po::error("Output file must be specified");
return vm;
}
catch (po::error &e)
{
std::cerr << e.what() << "\n\n";
usage(std::cerr, desc);
std::exit(1);
}
}
static Region parseRegion(const std::string &spec)
{
namespace qi = boost::spirit::qi;
auto p = spec.begin();
Region region;
bool success = qi::parse(p, spec.end(), (qi::int_ >> ',' >> qi::int_ >> ',' >> qi::uint_ >> ',' >> qi::uint_ ), region);
if (!success || p != spec.end())
throw std::runtime_error("Unexpected token at '" + std::string(p, spec.end()) + "'");
// Spec contains width and height, not x1 and y1
region.x1 += region.x0;
region.y1 += region.y0;
return region;
}
static std::pair<int, int> parseCorner(const std::string &spec)
{
namespace qi = boost::spirit::qi;
auto p = spec.begin();
std::pair<int, int> corner;
bool success = qi::parse(p, spec.end(), (qi::int_ >> ',' >> qi::int_), corner);
if (!success || p != spec.end())
throw std::runtime_error("Unexpected token at '" + std::string(p, spec.end()) + "'");
return corner;
}
static std::size_t typeToSize(Imf::PixelType type)
{
switch (type)
{
case Imf::UINT: return sizeof(std::uint32_t);
case Imf::HALF: return sizeof(std::uint16_t);
case Imf::FLOAT: return sizeof(float);
default:
throw std::runtime_error("Unknown pixel type");
}
}
int main(int argc, char **argv)
{
try
{
po::variables_map vm = processOptions(argc, argv);
//Imf::setGlobalThreadCount(omp_get_max_threads());
Imf::Header header;
std::ptrdiff_t stride;
Region inRegion;
Region keepRegion;
uts::vector<std::unique_ptr<char[]> > buffers;
{
Imf::InputFile in(vm[Option::inputFile()].as<std::string>().c_str());
Imf::FrameBuffer fb;
header = in.header();
Imath::Box2i &dw = header.dataWindow();
inRegion = Region(dw.min.x, dw.min.y, dw.max.x + 1, dw.max.y + 1);
stride = inRegion.width();
const std::size_t pixels = inRegion.pixels();
const std::ptrdiff_t bias = -(inRegion.y0 * stride + inRegion.x0);
if (vm.count(Option::region()))
{
keepRegion = parseRegion(vm[Option::region()].as<std::string>());
if (keepRegion.empty())
throw std::runtime_error("Cannot specify an empty region to keep");
if (!inRegion.contains(keepRegion))
throw std::runtime_error("Region to keep extends outside data window");
}
else
keepRegion = inRegion;
const auto &channels = header.channels();
for (auto i = channels.begin(); i != channels.end(); ++i)
{
const auto &channel = i.channel();
std::size_t pixelSize = typeToSize(channel.type);
std::unique_ptr<char[]> data(new char[pixelSize * pixels]);
fb.insert(i.name(), Imf::Slice(
channel.type,
data.get() + bias * pixelSize,
pixelSize,
pixelSize * stride));
buffers.emplace_back(std::move(data));
}
in.setFrameBuffer(fb);
in.readPixels(keepRegion.y0, keepRegion.y1 - 1);
}
Region outRegion = keepRegion;
if (vm.count(Option::origin()))
{
std::pair<int, int> corner = parseCorner(vm[Option::origin()].as<std::string>());
outRegion.x0 = corner.first;
outRegion.y0 = corner.second;
outRegion.x1 = corner.first + keepRegion.width();
outRegion.y1 = corner.second + keepRegion.height();
}
{
Imf::FrameBuffer fb;
header.compression() = Imf::ZIP_COMPRESSION;
Imath::Box2i &dw = header.dataWindow();
dw.min.x = outRegion.x0;
dw.min.y = outRegion.y0;
dw.max.x = outRegion.x1 - 1;
dw.max.y = outRegion.y1 - 1;
header.displayWindow() = dw;
Imf::FrameBuffer outFb;
const auto &channels = header.channels();
int pos = 0;
// coordinates of first element in each buffer
int x0 = inRegion.x0 + (outRegion.x0 - keepRegion.x0);
int y0 = inRegion.y0 + (outRegion.y0 - keepRegion.y0);
const std::ptrdiff_t bias = -(y0 * stride + x0);
for (auto i = channels.begin(); i != channels.end(); ++i, ++pos)
{
const auto &channel = i.channel();
std::size_t pixelSize = typeToSize(channel.type);
fb.insert(i.name(), Imf::Slice(
channel.type,
buffers[pos].get() + bias * pixelSize,
pixelSize,
pixelSize * stride));
}
Imf::OutputFile out(vm[Option::outputFile()].as<std::string>().c_str(), header);
out.setFrameBuffer(fb);
out.writePixels(outRegion.height());
}
}
catch (std::exception &e)
{
std::cerr << e.what() << '\n';
}
return 0;
}
| 7,946
|
C++
|
.cpp
| 207
| 29.599034
| 124
| 0.56267
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,185
|
heighttool.cpp
|
jgain_EcoLearn/UnderSim/common/heighttool.cpp
|
#include <stdexcept>
#include <cstddef>
#include <map>
#include <common/debug_string.h>
#include <common/debug_vector.h>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#include <boost/spirit/include/qi.hpp>
#include "str.h"
#include "map.h"
#include "map_rgba.h"
#include "initialize.h"
namespace po = boost::program_options;
namespace
{
namespace Option
{
/** @name Tokens for the option parser @{ */
static const char *inputFile() { return "input"; }
static const char *outputFile() { return "output"; }
static const char *resolution() { return "resolution"; }
static const char *addHeight() { return "add-height"; }
static const char *setMask() { return "set-mask"; }
static const char *getMask() { return "get-mask"; }
static const char *filterType() { return "filter-type"; }
static const char *zeroType() { return "zero-type"; }
static const char *addBorder() { return "add-border"; }
static const char *shade() { return "shade"; }
static const char *help() { return "help"; }
/** @} */
} // namespace Option
} // anonymous namespace
static void usage(std::ostream &o, const po::options_description desc)
{
o << "Usage: heighttool [options] input.exr output.exr\n\n";
o << desc;
}
static po::variables_map processOptions(int argc, char **argv)
{
po::positional_options_description positional;
positional.add(Option::inputFile(), 1);
positional.add(Option::outputFile(), 1);
po::options_description desc("General options");
desc.add_options()
(Option::resolution(), po::value<float>(), "set spatial resolution (metres per sample)")
(Option::addHeight(), po::value<float>(), "increment all heights by this amount")
(Option::getMask(), po::value<std::string>(), "generate visualization of the type mask")
(Option::setMask(), po::value<std::string>(), "adds terrain type information")
(Option::filterType(), po::value<int>(), "flatten all terrain except for one type")
(Option::zeroType(), po::value<int>(), "set a specific type for all pixels with zero height")
(Option::addBorder(), po::value<std::string>(), "add zero-height borders (left,top,right,bottom)")
(Option::shade(), po::value<std::string>(), "render the terrain to file")
(Option::help(), "show help");
po::options_description hidden("Hidden options");
hidden.add_options()
(Option::inputFile(), po::value<std::string>(), "input file")
(Option::outputFile(), po::value<std::string>(), "output file");
po::options_description all("All options");
all.add(desc);
all.add(hidden);
try
{
po::variables_map vm;
po::store(po::command_line_parser(argc, argv)
.style(po::command_line_style::default_style & ~po::command_line_style::allow_guessing)
.options(all)
.positional(positional)
.run(), vm);
po::notify(vm);
if (vm.count(Option::help()))
{
usage(std::cout, desc);
std::exit(0);
}
if (!vm.count(Option::inputFile()))
throw po::error("Input file must be specified");
bool needOutput =
vm.count(Option::resolution())
|| vm.count(Option::addHeight())
|| vm.count(Option::setMask());
if (needOutput && !vm.count(Option::outputFile()))
throw po::error("Output file must be specified");
return vm;
}
catch (po::error &e)
{
std::cerr << e.what() << "\n\n";
usage(std::cerr, desc);
std::exit(1);
}
}
static MemMap<height_and_mask_tag> addBorder(
const MemMap<height_and_mask_tag> &map,
const std::string &spec)
{
namespace qi = boost::spirit::qi;
auto p = spec.begin();
std::vector<int> borders;
bool success = qi::parse(p, spec.end(), (qi::uint_ >> ',' >> qi::uint_ >> ',' >> qi::uint_ >> ',' >> qi::uint_ ), borders);
if (!success || p != spec.end())
throw std::runtime_error("Unexpected token at '" + std::string(p, spec.end()) + "'");
Region r = map.region();
Region outRegion(r.x0 - borders[0], r.y0 - borders[1], r.x1 + borders[2], r.y1 + borders[3]);
MemMap<height_and_mask_tag> out(outRegion);
out.setStep(map.step());
out.fill(MapTraits<height_and_mask_tag>::type{0.0f, MapTraits<mask_tag>::all});
for (int y = r.y0; y < r.y1; y++)
for (int x = r.x0; x < r.x1; x++)
out[y][x] = map[y][x];
return out;
}
static void getMask(const MemMap<height_and_mask_tag> &map, const std::string &filename)
{
typedef MapTraits<rgba_tag>::type color;
typedef MapTraits<mask_tag>::type mask_t;
const color empty = {{0.0f, 0.0f, 0.0f, 0.0f}};
const uts::vector<color> &palette = MapTraits<rgba_tag>::colorPalette();
const mask_t valid = (mask_t(1) << palette.size()) - 1;
const Region &r = map.region();
MemMap<rgba_tag> out(r);
std::size_t rangeErrors = 0;
#pragma omp parallel for schedule(static) reduction(+:rangeErrors)
for (int y = r.y0; y < r.y1; y++)
for (int x = r.x0; x < r.x1; x++)
{
auto present = ~map[y][x].mask;
if (~present == 0)
out[y][x] = empty;
else
{
if (present & ~valid)
rangeErrors++;
// Average together the palette entries
std::array<float, 4> sum = {};
int n = 0;
for (std::size_t i = 0; i < palette.size(); i++)
{
if ((present >> i) & 1)
{
n++;
for (int j = 0; j < 4; j++)
sum[j] += palette[i][j];
}
}
if (n > 1)
for (int j = 0; j < 4; j++)
sum[j] /= n;
out[y][x] = sum;
}
}
if (rangeErrors > 0)
std::cerr << "Warning: unsupported terrain type. Extend the palette.\n";
out.write(filename);
}
static void setMask(MemMap<height_and_mask_tag> &map, const std::string &filename)
{
if (endsWith(filename, ".exr"))
{
MemMap<mask_tag> mask(filename);
Region update = mask.region() & map.region();
if (update.empty())
throw std::runtime_error("Mask image does not intersect the exemplar");
if (!mask.region().contains(map.region()))
std::cerr << "Warning: mask image does not completely cover the exemplar\n";
#pragma omp parallel for
for (int y = update.y0; y < update.y1; y++)
for (int x = update.x0; x < update.x1; x++)
map[y][x].mask = mask[y][x];
}
else
{
typedef MapTraits<mask_tag>::type mask_t;
MemMap<rgba_tag> paint(filename);
if (!paint.region().contains(map.region()))
{
/* Special case: if the sizes match but not the offset, ignore the offset */
if (paint.region().width() == map.region().width()
&& paint.region().height() == map.region().height())
paint.translateTo(map.region().x0, map.region().y0);
else
throw std::runtime_error("Mask image does not cover the exemplar");
}
colorsToMasks(map.region(), paint,
[&map] (int x, int y, mask_t mask) { map[y][x].mask = mask; });
}
}
static void filterType(MemMap<height_and_mask_tag> &map, const int type)
{
typedef MapTraits<mask_tag>::type mask_t;
#pragma omp parallel for
for (int y = map.region().y0; y < map.region().y1; y++)
for (int x = map.region().x0; x < map.region().x1; x++)
{
mask_t present = ~map[y][x].mask;
if (!(present & (mask_t(1) << type)))
map[y][x].height = 0.0f;
}
}
static void zeroType(MemMap<height_and_mask_tag> &map, const int type)
{
if (type < 0 || type >= MapTraits<mask_tag>::numTypes)
throw std::runtime_error("Type " + std::to_string(type) + " is out of range");
const Region r = map.region();
typedef MapTraits<mask_tag>::type mask_t;
mask_t mask = ~((mask_t(1) << type) - 1);
#pragma omp parallel for
for (int y = r.y0; y < r.y1; y++)
for (int x = r.x0; x < r.x1; x++)
if (map[y][x].height == 0.0f)
map[y][x].mask = mask;
}
static MemMap<gray_tag> shade(const MemMap<height_and_mask_tag> &in)
{
const double azimuth = 1.75 * M_PI;
const double altitude = 0.25 * M_PI;
const double sinAltitude = sin(altitude);
const double cosAltitude = cos(altitude);
// The 8 is a normalization factor for the filter kernel
const double scale = 1.0 / (8.0 * in.step());
const Region r = in.region();
MemMap<gray_tag> out(r);
out.setStep(in.step());
out.fill(0.0f);
#pragma omp parallel for
for (int y = r.y0 + 1; y < r.y1 - 1; y++)
for (int x = r.x0 + 1; x < r.x1 - 1; x++)
{
double dx = (in[y - 1][x - 1].height + 2 * in[y][x - 1].height + in[y + 1][x - 1].height)
- (in[y + 1][x - 1].height + 2 * in[y][x + 1].height + in[y + 1][x + 1].height);
dx *= scale;
double dy = (in[y - 1][x - 1].height + 2 * in[y - 1][x].height + in[y - 1][x + 1].height)
- (in[y + 1][x - 1].height + 2 * in[y + 1][x].height + in[y + 1][x + 1].height);
dy *= scale;
double g2 = dx * dx + dy * dy;
double aspect = atan2(dy, dx);
double cang = (sinAltitude - cosAltitude * sqrt(g2) * sin(aspect - azimuth))
/ sqrt(1.0 + g2);
if (cang < 0.0)
cang = 0.0;
out[y][x] = cang;
}
return out;
}
int main(int argc, char **argv)
{
utsInitialize();
try
{
po::variables_map vm = processOptions(argc, argv);
MemMap<height_and_mask_tag> map;
const uts::string inputFile = vm[Option::inputFile()].as<std::string>();
map.read(inputFile);
if (vm.count(Option::resolution()))
map.setStep(vm[Option::resolution()].as<float>());
if (vm.count(Option::addBorder()))
map = addBorder(map, vm[Option::addBorder()].as<std::string>());
if (vm.count(Option::addHeight()))
{
float add = vm[Option::addHeight()].as<float>();
for (int y = 0; y < map.height(); y++)
for (int x = 0; x < map.width(); x++)
map[y][x].height += add;
}
if (vm.count(Option::setMask()))
setMask(map, vm[Option::setMask()].as<std::string>());
if (vm.count(Option::getMask()))
getMask(map, vm[Option::getMask()].as<std::string>());
if (vm.count(Option::filterType()))
filterType(map, vm[Option::filterType()].as<int>());
if (vm.count(Option::zeroType()))
zeroType(map, vm[Option::zeroType()].as<int>());
if (vm.count(Option::shade()))
{
const uts::string filename = vm[Option::shade()].as<std::string>();
MemMap<gray_tag> shaded = shade(map);
shaded.write(filename);
}
if (vm.count(Option::outputFile()))
{
const uts::string outputFile = vm[Option::outputFile()].as<std::string>();
map.write(outputFile);
}
}
catch (std::exception &e)
{
std::cerr << e.what() << '\n';
return 1;
}
}
| 11,636
|
C++
|
.cpp
| 289
| 31.910035
| 127
| 0.548798
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,186
|
region.cpp
|
jgain_EcoLearn/UnderSim/common/region.cpp
|
/**
* @file
*
* Data structure representing a rectangular region of 2D space.
*/
#include <cassert>
#include <algorithm>
#include "region.h"
Region::Region()
: x0(0), y0(0), x1(0), y1(0)
{
}
Region::Region(int x0, int y0, int x1, int y1)
: x0(x0), y0(y0), x1(x1), y1(y1)
{
assert(x0 <= x1);
assert(y0 <= y1);
}
Region Region::operator|(const Region &other) const
{
// Empty regions need special treatment, because otherwise they are
// treated as containing the point (0, 0).
if (empty())
return other;
else if (other.empty())
return *this;
else
return Region(
std::min(x0, other.x0), std::min(y0, other.y0),
std::max(x1, other.x1), std::max(y1, other.y1));
}
Region &Region::operator|=(const Region &other)
{
return *this = *this | other;
}
Region Region::operator&(const Region &other) const
{
Region ans = *this;
return ans &= other;
}
Region &Region::operator&=(const Region &other)
{
x0 = std::max(x0, other.x0);
y0 = std::max(y0, other.y0);
x1 = std::min(x1, other.x1);
y1 = std::min(y1, other.y1);
if (empty())
{
x0 = 0;
y0 = 0;
x1 = 0;
y1 = 0;
}
return *this;
}
bool Region::operator==(const Region &other) const
{
return x0 == other.x0 && y0 == other.y0 && x1 == other.x1 && y1 == other.y1;
}
bool Region::operator!=(const Region &other) const
{
return !(*this == other);
}
int Region::width() const
{
return x1 - x0;
}
int Region::height() const
{
return y1 - y0;
}
bool Region::empty() const
{
return x0 >= x1 || y0 >= y1;
}
std::size_t Region::pixels() const
{
return empty() ? 0 : std::size_t(width()) * height();
}
Region Region::dilate(int border) const
{
Region out;
if (!empty())
{
out.x0 = x0 - border;
out.x1 = x1 + border;
out.y0 = y0 - border;
out.y1 = y1 + border;
if (out.empty())
out = Region(); // make it the canonical empty region
}
return out;
}
Region Region::erode(int border) const
{
return dilate(-border);
}
bool Region::contains(const Region &other) const
{
if (other.empty())
return true;
else
return x0 <= other.x0 && y0 <= other.y0 && x1 >= other.x1 && y1 >= other.y1;
}
| 2,312
|
C++
|
.cpp
| 104
| 18.307692
| 84
| 0.588504
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,187
|
map2exr.cpp
|
jgain_EcoLearn/UnderSim/common/map2exr.cpp
|
#include <iostream>
#include <locale>
#include <stdexcept>
#include "debug_string.h"
#include "map.h"
#include "initialize.h"
static void usage()
{
std::cerr << "Usage: map2exr input.map output.exr\n";
}
static MemMap<height_tag> loadMap(const uts::string &filename)
{
std::ifstream in(filename);
if (!in)
throw std::runtime_error("Could not open " + filename);
MemMap<height_tag> ans;
try
{
in.imbue(std::locale::classic());
in.exceptions(std::ios::failbit | std::ios::badbit);
int R, C;
in >> C >> R;
if (R <= 0 || C <= 0)
throw std::runtime_error("dimensions are invalid");
ans.allocate({0, 0, R, C});
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++)
in >> ans[r][c];
in.close();
}
catch (std::runtime_error &e)
{
throw std::runtime_error("Failed to read " + filename + ": " + e.what());
}
return std::move(ans);
}
int main(int argc, char **argv)
{
utsInitialize();
try
{
if (argc != 3)
{
usage();
return 1;
}
MemMap<height_tag> m = loadMap(argv[1]);
m.write(argv[2]);
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
}
| 1,335
|
C++
|
.cpp
| 55
| 18.254545
| 81
| 0.523511
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,192
|
utsclassify.cpp
|
jgain_EcoLearn/UnderSim/common/utsclassify.cpp
|
/**
* @file
*
* Automatically classifies terrain types.
*/
#include <boost/program_options.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <string>
#include <algorithm>
#include <utility>
#include <limits>
#include <random>
#include <cmath>
#include <sstream>
#include <svm.h>
#include <eigen3/Eigen/Core>
#include <common/map.h>
#include <common/maputils.h>
#include <common/debug_vector.h>
#include <common/initialize.h>
#include <common/progress.h>
#include <common/mathutils.h>
namespace po = boost::program_options;
static constexpr int NTYPES = std::numeric_limits<MapTraits<mask_tag>::type>::digits;
typedef MapTraits<mask_tag>::type mask_t;
typedef MapTraits<height_tag>::type height_t;
namespace
{
namespace Option
{
/** @name Tokens for the option parser @{ */
static const char *exemplar() { return "exemplar"; }
static const char *inputFile() { return "input"; }
static const char *outputFile() { return "output"; }
static const char *featureSize() { return "feature-size"; }
static const char *maxSamples() { return "max-samples"; }
static const char *cross() { return "cross"; }
static const char *explore() { return "explore"; }
static const char *regions() { return "regions"; }
static const char *width() { return "width"; }
static const char *height() { return "height"; }
static const char *help() { return "help"; }
/** @} */
} // namespace Option
} // anonymous namespace
static void usage(std::ostream &o, const po::options_description desc)
{
o << "Usage: utsclassify [options] exemplar.exr [...] -i input.exr [-o output.exr]\n\n";
o << desc;
}
static po::variables_map processOptions(int argc, char **argv)
{
po::positional_options_description positional;
positional.add(Option::exemplar(), -1);
po::options_description desc("General options");
desc.add_options()
("input,i", po::value<std::string>()->required(), "input file")
("output,o", po::value<std::string>(), "output file [same as input]")
(Option::featureSize(), po::value<float>()->default_value(2000.0f), "maximum feature size (metres)")
(Option::maxSamples(), po::value<int>()->default_value(1000), "maximum samples per type for training")
(Option::cross(), po::value<int>(), "report result of N-way cross-validation")
(Option::explore(), "explore the parameter space")
(Option::regions(), po::value<std::string>(), "list of corners for regions to predict (x,y+x,y...)")
(Option::width(), po::value<int>()->default_value(1024), "width for regions specified with --regions")
(Option::height(), po::value<int>()->default_value(1024), "height for regions specified with --regions")
(Option::help(), "show help");
po::options_description hidden("Hidden options");
hidden.add_options()
(Option::exemplar(), po::value<std::vector<std::string>>()->composing(), "exemplars");
po::options_description all("All options");
all.add(desc);
all.add(hidden);
try
{
po::variables_map vm;
po::store(po::command_line_parser(argc, argv)
.style(po::command_line_style::default_style & ~po::command_line_style::allow_guessing)
.options(all)
.positional(positional)
.run(), vm);
po::notify(vm);
if (vm.count(Option::help()))
{
usage(std::cout, desc);
std::exit(0);
}
/* Using ->required() on the option gives an unhelpful message */
if (!vm.count(Option::exemplar()))
{
std::cerr << "At least one exemplar file must be specified.\n\n";
usage(std::cerr, desc);
std::exit(1);
}
return vm;
}
catch (po::error &e)
{
std::cerr << e.what() << "\n\n";
usage(std::cerr, desc);
std::exit(1);
}
}
static int reflect(int x, int size)
{
while (x < 0) x += 2 * size;
while (x >= 2 * size)
x -= 2 * size;
if (x >= size)
x = 2 * size - 1 - x;
return x;
}
// Weights taken from http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=pyrup#pyrup
// TODO: unify with code in database.cpp
static constexpr float gaussian5[5] = {1.0f / 16.0f, 4.0f / 16.0f, 6.0f / 16.0f, 4.0f / 16.0f, 1.0f / 16.0f};
/**
* Apply a 1D 5-tap Gaussian smoothing filter. Borders are handled by
* reflection.
*/
static void smooth1D(
const MapTraits<height_tag>::type *in,
MapTraits<height_tag>::type *out,
int size,
int step)
{
for (int x = 0; x < size; x++)
{
int xi = x - 2 * step;
MapTraits<height_tag>::type sum = 0;
for (int i = 0; i < 5; i++, xi += step)
sum += gaussian5[i] * in[reflect(xi, size)];
out[x] = sum;
}
}
/**
* Applies a 5x5 Gaussian smoothing filter. Borders are handled by
* reflection. Samples are spaced @a step apart.
*
* @note It is tempting to consider making this an in-place transformation (or
* at least allowing in-place transformations. It will @em almost work, but
* the vertical reflection will cause issues.
*/
static MemMap<height_tag> smooth(const MemMap<height_tag> &in, int step)
{
typedef MapTraits<height_tag>::type height_t;
Region r = in.region();
MemMap<height_tag> out(r);
out.setStep(in.step());
int W = r.width();
int H = r.height();
constexpr int WINDOW = 5;
// Horizontally filtered rows
uts::vector<height_t> rows[WINDOW];
for (int i = 0; i < WINDOW; i++)
rows[i].resize(W);
for (int phase = 0; phase < step; phase++)
{
// Prime the pipeline
for (int y = 0; y < WINDOW - 1; y++)
{
int yi = reflect(phase + (y - WINDOW / 2) * step, H);
const height_t *inRow = in.get() + yi * W;
smooth1D(inRow, rows[y].data(), W, step);
}
// Do vertical smoothing
for (int y = phase; y < H; y += step)
{
int yi = reflect(y + WINDOW / 2 * step, H);
const height_t *inRow = in.get() + yi * W;
smooth1D(inRow, rows[WINDOW - 1].data(), W, step);
height_t *outRow = out.get() + y * r.width();
for (int x = 0; x < W; x++)
{
height_t sum = 0;
for (int i = 0; i < WINDOW; i++)
sum += gaussian5[i] * rows[i][x];
outRow[x] = sum;
}
// Move up the rows
for (int i = 1; i < WINDOW; i++)
rows[i - 1].swap(rows[i]);
}
}
return out;
}
/**
* Generate multiresolution noise measures from a heightmap. The returned
* matrix has one column per element of @a in, and @a levels rows. The
* elements are ordered from fine to coarse. The first @a skip octaves
* are skipped.
*
* @note The input map is destroyed in the process.
*/
static Eigen::MatrixXf featureVectors(
MemMap<height_tag> &&in,
const uts::vector<Region> ®ions,
int levels, int skip)
{
std::size_t pixels = 0;
for (const Region &r : regions)
pixels += r.pixels();
Eigen::MatrixXf features(levels, pixels);
for (int i = 0; i < skip; i++)
in = smooth(in, 1 << i);
for (int i = 0; i < levels; i++)
{
MemMap<height_tag> smoothed = smooth(in, 1 << (i + skip));
std::size_t startPixel = 0;
for (const Region &r : regions)
{
#pragma omp parallel for schedule(static)
for (int y = r.y0; y < r.y1; y++)
{
std::size_t p = startPixel + (y - r.y0) * r.width();
for (int x = r.x0; x < r.x1; x++, p++)
{
float delta = in[y][x] - smoothed[y][x];
features(i, p) = delta * delta;
}
}
startPixel += r.pixels();
}
in = std::move(smoothed);
}
in.clear(); // contains garbage, might as well free the memory
return features;
}
struct Exemplar
{
MemMap<height_tag> heights;
MemMap<mask_tag> masks;
explicit Exemplar(const MemMap<height_and_mask_tag> &hm)
{
std::tie(heights, masks) = demultiplex(hm);
}
};
struct TerrainType
{
int index;
std::size_t samples = 0;
std::size_t keepSamples = 0;
};
/// Deletes an svm_model
struct ModelDelete
{
void operator()(svm_model *model) const
{
svm_free_and_destroy_model(&model);
}
};
/**
* Loads the exemplars from disk and demultiplexes them.
*
* @param first, last A forward iterator range of strings containing filenames.
* @param step Step size of the input file.
*
* @throw std::runtime_error if any of the exemplars has a bad step size relative to @a step.
* @throw std::exception if an exception is thrown on loading
*/
template<typename ForwardIterator>
static uts::vector<Exemplar> loadExemplars(
ForwardIterator first, ForwardIterator last, float step)
{
uts::vector<Exemplar> exemplars;
exemplars.reserve(std::distance(first, last));
for (auto i = first; i != last; ++i)
{
const std::string &filename = *i;
MemMap<height_and_mask_tag> hm(filename);
if (hm.step() <= 0)
throw std::runtime_error(filename + ": unknown resolution");
if (!isPower2Ratio(hm.step(), step))
throw std::runtime_error(filename + ": step size is not a power of two times input step size");
exemplars.emplace_back(hm);
}
return exemplars;
}
/**
* Returns a list of usable terrain types based on the exemplars.
*
* @param first, last A forward iterator range of exemplars.
* @param maxSamples Upper bound for @c keepSamples
*/
template<typename ForwardIterator>
uts::vector<TerrainType> getTypes(
ForwardIterator first, ForwardIterator last, std::size_t maxSamples)
{
TerrainType types[NTYPES];
for (int i = 0; i < NTYPES; i++)
types[i].index = i;
for (auto i = first; i != last; ++i)
{
const Exemplar &exemplar = *i;
std::size_t pixels = exemplar.heights.region().pixels();
for (std::size_t i = 0; i < pixels; i++)
{
mask_t mask = exemplar.masks.get()[i];
if (mask != MapTraits<mask_tag>::all)
{
mask_t present = ~mask;
for (int j = 0; j < NTYPES; j++)
if ((present >> j) & 1)
{
types[j].samples++;
}
}
}
}
uts::vector<TerrainType> ans;
for (int i = 0; i < NTYPES; i++)
if (types[i].samples >= 20)
{
types[i].keepSamples = std::min(maxSamples, types[i].samples);
ans.push_back(types[i]);
}
return ans;
}
/**
* Extract feature vectors and label from the exemplars.
*
* @param first, last Iterator range over the exemplars
* @param levels Size of each feature vector
* @param maxStep Largest step size amongst exemplars
* @param types Valid terrain types and their counts
* @param[out] featurePtrs Feature vectors per sample
* @param[out] labels Terrain type id corresponding to each feature
*
* @return Scaling factors per feature
*
* @note The exemplars are destroyed in the process.
*/
template<typename ForwardIterator>
static Eigen::VectorXf getTrainData(
ForwardIterator first, ForwardIterator last,
int levels,
float maxStep,
uts::vector<TerrainType> types,
const uts::vector<struct svm_node *> &featurePtrs,
uts::vector<double> &labels)
{
int nextSample = 0;
std::mt19937 engine;
Eigen::VectorXf biggest = Eigen::VectorXf::Zero(levels);
for (auto e = first; e != last; ++e)
{
Exemplar &exemplar = *e;
const Region full = exemplar.masks.region();
std::size_t pixels = full.pixels();
int skip = (int) std::round(std::log2(maxStep / exemplar.masks.step()));
Eigen::MatrixXf f = featureVectors(std::move(exemplar.heights), {full}, levels, skip);
for (std::size_t i = 0; i < pixels; i++)
{
mask_t mask = exemplar.masks.get()[i];
if (mask != MapTraits<mask_tag>::all)
{
biggest = biggest.cwiseMax(f.col(i));
mask_t present = ~mask;
for (TerrainType &t : types)
if ((present >> t.index) & 1)
{
// Decide whether to retain this sample
bool keep;
if (t.keepSamples == t.samples)
keep = true;
else
{
std::bernoulli_distribution dist(t.keepSamples / (double) t.samples);
keep = dist(engine);
}
if (keep)
{
for (int k = 0; k < levels; k++)
{
featurePtrs[nextSample][k].index = k;
featurePtrs[nextSample][k].value = f(k, i);
}
labels[nextSample] = t.index;
nextSample++;
t.keepSamples--;
}
t.samples--;
}
}
}
}
// Scale all training features to [0, 1] range
Eigen::VectorXf scale = Eigen::VectorXf::Constant(levels, 1.0f).cwiseQuotient(biggest);
for (auto feature : featurePtrs)
for (int j = 0; j < levels; j++)
feature[j].value *= scale(j);
return scale;
}
static struct svm_parameter makeParameters(const svm_problem &problem, int numTypes)
{
struct svm_parameter parameter = {};
parameter.svm_type = C_SVC;
parameter.kernel_type = RBF;
parameter.gamma = 256.0 / numTypes; // tuned
parameter.cache_size = 512; // in MB
parameter.eps = 0.001; // svm-train default
parameter.C = 1024.0; // tuned
parameter.shrinking = 1; // svm-train default
const char *error = svm_check_parameter(&problem, ¶meter);
if (error != nullptr)
{
throw std::runtime_error(error);
}
return parameter;
}
static uts::vector<Region> parseRegions(const std::string &spec, int width, int height)
{
namespace qi = boost::spirit::qi;
uts::vector<Region> out;
uts::vector<std::pair<int, int> > positions;
auto first = spec.begin();
bool success = qi::parse(first, spec.end(), (qi::int_ >> ',' >> qi::int_) % '+', positions);
if (!success || first != spec.end())
throw std::runtime_error("Unexpected token at '" + std::string(first, spec.end()) + "'");
for (const auto &pos : positions)
{
Region r(pos.first, pos.second, pos.first + width, pos.second + height);
out.push_back(r);
}
return out;
}
static MemMap<height_and_mask_tag> predict(
MemMap<height_tag> &&in,
const uts::vector<Region> ®ions,
struct svm_model *model,
int levels,
float maxStep,
const Eigen::VectorXf &scale)
{
const Region full = in.region();
MemMap<height_and_mask_tag> out(full);
out.setStep(in.step());
// Copy the heights, before featureVectors destroys them
#pragma omp parallel for schedule(static)
for (int y = full.y0; y < full.y1; y++)
for (int x = full.x0; x < full.x1; x++)
out[y][x].height = in[y][x];
int skip = (int) std::round(std::log2(maxStep / in.step()));
Eigen::MatrixXf f = featureVectors(std::move(in), regions, levels, skip);
std::size_t pixels = 0;
for (const Region &r : regions)
pixels += r.pixels();
ProgressDisplay<> progress(pixels);
std::size_t startPixel = 0;
for (const Region &r : regions)
{
#pragma omp parallel for schedule(dynamic,1)
for (int y = r.y0; y < r.y1; y++)
{
std::size_t p = startPixel + (y - r.y0) * r.width();
uts::vector<svm_node> node(levels + 1);
node[levels].index = -1;
for (int i = 0; i < levels; i++)
node[i].index = i;
for (int x = r.x0; x < r.x1; x++, p++)
{
for (int i = 0; i < levels; i++)
node[i].value = f(i, p) * scale(i);
int t = (int) svm_predict(model, node.data());
assert(t >= 0 && t < NTYPES);
out[y][x].mask = ~(mask_t(1) << t);
}
progress += r.width();
}
startPixel += r.pixels();
}
return out;
}
static void print_svm_empty(const char *string)
{
// Do nothing, to suppress output
}
static double crossValidate(const svm_problem &problem, const svm_parameter ¶meter, int N)
{
std::size_t numSamples = problem.l;
std::vector<double> target(numSamples);
svm_cross_validation(&problem, ¶meter, N, target.data());
std::size_t right = 0;
for (std::size_t i = 0; i < numSamples; i++)
{
if (target[i] == problem.y[i])
right++;
}
return (double) right / (double) numSamples;
}
static void explore(const svm_problem &problem, svm_parameter parameter, int N, int numTypes)
{
for (int lC = 10; lC <= 16; lC++)
for (int lG = 3; lG <= 9; lG++)
{
parameter.C = std::exp2(lC);
parameter.gamma = std::exp2(lG) / numTypes;
double ratio = crossValidate(problem, parameter, N);
std::cout << "C = 2^" << lC << " g = 2^" << lG << " / " << numTypes << ": " << ratio * 100.0 << "%\n";
}
}
int main(int argc, char **argv)
{
utsInitialize();
try
{
po::variables_map vm = processOptions(argc, argv);
svm_set_print_string_function(print_svm_empty);
float featureSize = vm[Option::featureSize()].as<float>();
std::size_t maxSamples = vm[Option::maxSamples()].as<int>();
MemMap<height_tag> in(vm[Option::inputFile()].as<std::string>());
if (in.step() <= 0)
throw std::runtime_error("Input file has unknown resolution");
Region full = in.region();
uts::vector<Region> regions;
if (vm.count(Option::regions()))
{
regions = parseRegions(
vm[Option::regions()].as<std::string>(),
vm[Option::width()].as<int>(),
vm[Option::height()].as<int>());
for (const Region &r : regions)
{
if (!full.contains(r))
{
std::ostringstream msg;
msg << "Region (" << r.x0 << ", " << r.y0 << ")(" << r.x1 << ", " << r.y1
<< ") not contained in (" << full.x0 << ", " << full.y0 << ")(" << full.x1 << ", " << full.y1 << ")";
throw std::runtime_error(msg.str());
}
}
}
else
regions.push_back(full);
const std::vector<std::string> &exemplarFilenames = vm[Option::exemplar()].as<std::vector<std::string> >();
uts::vector<Exemplar> exemplars = loadExemplars(exemplarFilenames.begin(), exemplarFilenames.end(), in.step());
// Determine the coarsest of the exemplars and the input, which
// determines which octaves can be used in training.
float maxStep = in.step();
for (const auto &e : exemplars)
maxStep = std::max(maxStep, e.heights.step());
int levels = std::floor(std::log2(featureSize / maxStep)) + 1;
levels = std::max(levels, 1);
levels = std::min(levels, 24); // danger of integer overflow beyond this, and no good reason for it
std::vector<TerrainType> types = getTypes(exemplars.begin(), exemplars.end(), maxSamples);
std::size_t numSamples = 0;
for (const auto &t : types)
numSamples += t.keepSamples;
// libsvm takes number of training elements as an int
if (numSamples > std::numeric_limits<int>::max())
{
throw std::runtime_error("Too many samples for libsvm");
}
uts::vector<double> labels(numSamples);
uts::vector<struct svm_node> features(numSamples * (levels + 1));
uts::vector<struct svm_node *> featurePtrs(numSamples);
for (std::size_t i = 0; i < numSamples; i++)
{
featurePtrs[i] = &features[i * (levels + 1)];
featurePtrs[i][levels].index = -1;
}
Eigen::VectorXf scale =
getTrainData(exemplars.begin(), exemplars.end(), levels, maxStep,
types, featurePtrs, labels);
struct svm_problem problem;
problem.l = numSamples;
problem.y = labels.data();
problem.x = featurePtrs.data();
struct svm_parameter parameter = makeParameters(problem, types.size());
if (vm.count(Option::cross()))
{
int N = vm[Option::cross()].as<int>();
if (vm.count(Option::explore()))
{
explore(problem, parameter, N, types.size());
}
else
{
double ratio = crossValidate(problem, parameter, N);
std::cout << "Cross-validation: " << ratio * 100.0 << "% accuracy\n";
}
return 0;
}
else if (vm.count(Option::explore()))
{
throw std::runtime_error("--explore requires --cross");
}
struct svm_model *modelPtr = svm_train(&problem, ¶meter);
std::unique_ptr<svm_model, ModelDelete> model(modelPtr);
std::cout << "Training complete, nSV = " << model->l << '\n';
MemMap<height_and_mask_tag> out =
predict(std::move(in), regions, model.get(), levels, maxStep, scale);
std::string outFilename;
if (vm.count(Option::outputFile()))
outFilename = vm[Option::outputFile()].as<std::string>();
else
outFilename = vm[Option::inputFile()].as<std::string>();
out.write(outFilename);
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
| 22,389
|
C++
|
.cpp
| 605
| 29.046281
| 125
| 0.564108
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,193
|
map_rgba.cpp
|
jgain_EcoLearn/UnderSim/common/map_rgba.cpp
|
/**
* @file
*
* Specialization of @ref MapTraits for color images.
*/
#include <cmath>
#include <ImfFrameBuffer.h>
#include <thread>
#include "map.h"
#include "map_rgba.h"
#include "str.h"
#include <Magick++.h>
static constexpr Magick::Quantum getQuantumRange()
{
using namespace Magick; // otherwise the macro breaks
return QuantumRange;
}
static Magick::Quantum floatToQuantum(float x)
{
if (!(x >= 0.0f)) // also catches NaN
x = 0.0f;
if (x > 1.0f)
x = 1.0f;
return static_cast<Magick::Quantum>(std::round(x * getQuantumRange()));
}
bool MapTraits<gray_tag>::customRead(MemMap<gray_tag> &out, const uts::string &filename)
{
if (endsWith(filename, ".exr"))
return false; // use OpenEXR for EXR images (default path)
Magick::Image image(filename);
// This is needed to make the grayscale conversion happen in linear space
image.image()->intensity = MagickCore::Rec709LuminancePixelIntensityMethod;
image.colorSpace(Magick::GRAYColorspace);
Region r(0, 0, image.columns(), image.rows());
out.allocate(r);
image.write(0, 0, r.x1, r.y1, "I", Magick::FloatPixel, out.get());
return true;
}
bool MapTraits<gray_tag>::customWrite(const MemMap<gray_tag> &in, const uts::string &filename,
const Region ®ion)
{
if (endsWith(filename, ".exr"))
return false;
const Region &r = in.region();
Magick::Image image(Magick::Geometry(r.width(), r.height()), Magick::Color(0, 0, 0, 0));
image.colorSpace(Magick::RGBColorspace);
Magick::Pixels view(image);
Magick::PixelPacket *pixels = view.set(0, 0, r.width(), r.height());
for (int y = r.y0; y < r.y1; y++)
for (int x = r.x0; x < r.x1; x++, pixels++)
{
Magick::Quantum v = floatToQuantum(in[y][x]);
pixels->red = v;
pixels->green = v;
pixels->blue = v;
pixels->opacity = 0;
}
view.sync();
/* Convert to sRGB. This shouldn't be necessary, but without it, the PNG
* encoder writes linear values but stores a gAMA chunk of 1/2.2.
*/
image.colorSpace(Magick::sRGBColorspace);
image.write(filename);
return true;
}
void MapTraits<gray_tag>::prepareFrameBuffer(Imf::FrameBuffer &fb, const io_type *base, std::size_t width)
{
MapTraits<height_tag>::prepareFrameBuffer(fb, base, width);
}
bool MapTraits<rgba_tag>::customRead(MemMap<rgba_tag> &out, const uts::string &filename)
{
if (endsWith(filename, ".exr"))
return false; // use OpenEXR for EXR images (default path)
Magick::Image image(filename);
image.colorSpace(Magick::RGBColorspace);
Region r(0, 0, image.columns(), image.rows());
out.allocate(r);
image.write(0, 0, r.x1, r.y1, "RGBA", Magick::FloatPixel, out.get());
return true;
}
bool MapTraits<rgba_tag>::customWrite(const MemMap<rgba_tag> &in, const uts::string &filename,
const Region ®ion)
{
if (endsWith(filename, ".exr"))
return false;
const Region &r = in.region();
Magick::Image image(Magick::Geometry(r.width(), r.height()), Magick::Color(0, 0, 0, getQuantumRange()));
image.colorSpace(Magick::RGBColorspace);
Magick::Pixels view(image);
Magick::PixelPacket *pixels = view.set(0, 0, r.width(), r.height());
for (int y = r.y0; y < r.y1; y++)
for (int x = r.x0; x < r.x1; x++, pixels++)
{
pixels->red = floatToQuantum(in[y][x][0]);
pixels->green = floatToQuantum(in[y][x][1]);
pixels->blue = floatToQuantum(in[y][x][2]);
// ImageMagick uses reverse alpha
pixels->opacity = getQuantumRange() - floatToQuantum(in[y][x][3]);
}
view.sync();
/* Convert to sRGB. The ImageMagick decoder doesn't understand that gamma=1
* means a linear image, so we have to write an sRGB image. Many other decoders
* are also unlikely to get this right.
*/
image.colorSpace(Magick::sRGBColorspace);
image.write(filename);
return true;
}
void MapTraits<rgba_tag>::prepareFrameBuffer(Imf::FrameBuffer &fb, const io_type *base, std::size_t width)
{
fb.insert("R", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][0]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("G", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][1]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("B", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][2]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("A", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][3]),
sizeof(io_type), sizeof(io_type) * width));
}
const uts::vector<MapTraits<rgba_tag>::type> &MapTraits<rgba_tag>::colorPalette()
{
static const uts::vector<type> palette{
{{ 0.0f, 0.0f, 0.0f, 1.0f }},
{{ 0.0f, 0.0f, 1.0f, 1.0f }},
{{ 0.0f, 1.0f, 0.0f, 1.0f }},
{{ 1.0f, 0.0f, 0.0f, 1.0f }},
{{ 1.0f, 1.0f, 0.0f, 1.0f }},
{{ 1.0f, 1.0f, 1.0f, 1.0f }},
{{ 1.0f, 0.0f, 1.0f, 1.0f }},
{{ 0.0f, 1.0f, 1.0f, 1.0f }}
};
return palette;
}
| 5,371
|
C++
|
.cpp
| 133
| 33.857143
| 108
| 0.609279
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,194
|
progress.cpp
|
jgain_EcoLearn/UnderSim/common/progress.cpp
|
/**
* @file
*
* A thread-safe progress meter, modelled on boost::progress_display.
*/
#include "progress.h"
template class ProgressDisplay<std::uint64_t>;
| 161
|
C++
|
.cpp
| 7
| 21.142857
| 69
| 0.736842
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,196
|
maputils.cpp
|
jgain_EcoLearn/UnderSim/common/maputils.cpp
|
/**
* @file
*
* Some utility functions for dealing with maps.
*/
#include <utility>
#include "map.h"
#include "maputils.h"
std::pair<MemMap<height_tag>, MemMap<mask_tag> >
demultiplex(const MemMap<height_and_mask_tag> &in)
{
std::pair<MemMap<height_tag>, MemMap<mask_tag> > out;
const Region region = in.region();
auto &height = out.first;
height.allocate(region);
height.setStep(in.step());
auto &mask = out.second;
mask.allocate(region);
mask.setStep(in.step());
#pragma omp parallel for schedule(static) default(none) shared(in, height, mask)
for (int y = region.y0; y < region.y1; y++)
for (int x = region.x0; x < region.x1; x++)
{
height[y][x] = in[y][x].height;
mask[y][x] = in[y][x].mask;
}
return out;
}
| 809
|
C++
|
.cpp
| 28
| 24.428571
| 80
| 0.623711
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,197
|
terragen.cpp
|
jgain_EcoLearn/UnderSim/common/terragen.cpp
|
/**
* @file
*
* Terragen format import and export.
* @see http://www.planetside.co.uk/terragen/dev/tgterrain.html
*/
#include <fstream>
#include <algorithm>
#include <limits>
#include <cstring>
#include <utility>
#include <stdexcept>
#include <locale>
#include <cstdint>
#include <cmath>
#include <common/debug_string.h>
#include "map.h"
/// Reads a binary little-endian float
static float readFloat(std::istream &in)
{
static_assert(std::numeric_limits<float>::is_iec559 && sizeof(float) == 4, "float is not IEEE-754 compliant");
unsigned char data[4];
std::uint32_t host = 0;
float out;
in.read(reinterpret_cast<char *>(data), 4);
for (int i = 0; i < 4; i++)
host |= std::uint32_t(data[i]) << (i * 8);
std::memcpy(&out, &host, sizeof(out));
return out;
}
/// Writes a binary little-endian float
static void writeFloat(std::ostream &out, float f)
{
static_assert(std::numeric_limits<float>::is_iec559 && sizeof(float) == 4, "float is not IEEE-754 compliant");
std::uint32_t host;
unsigned char data[4];
std::memcpy(&host, &f, sizeof(host));
for (int i = 0; i < 4; i++)
data[i] = (host >> (i * 8)) & 0xff;
out.write(reinterpret_cast<char *>(data), 4);
}
/// Reads a binary little-endian 16-bit unsigned int
static std::uint16_t readUint16(std::istream &in)
{
unsigned char data[2];
in.read(reinterpret_cast<char *>(data), 2);
return data[0] | (std::uint16_t(data[1]) << 8);
}
/// Writes a binary little-endian 16-bit unsigned int
static void writeUint16(std::ostream &out, std::uint16_t v)
{
unsigned char data[2];
data[0] = v & 0xff;
data[1] = v >> 8;
out.write(reinterpret_cast<char *>(data), 2);
}
/// Reads a binary little-endian 16-bit signed int
static std::int16_t readInt16(std::istream &in)
{
return static_cast<std::int16_t>(readUint16(in));
}
/// Writes a binary little-endian 16-bit signed int
static void writeInt16(std::ostream &out, std::int16_t v)
{
writeUint16(out, static_cast<std::uint16_t>(v));
}
MemMap<height_tag> readTerragen(const uts::string &filename)
{
std::ifstream in(filename, std::ios::binary);
if (!in)
throw std::runtime_error("Could not open " + filename);
MemMap<height_tag> ans;
try
{
in.imbue(std::locale::classic());
in.exceptions(std::ios::failbit | std::ios::badbit | std::ios::eofbit);
char signature[16];
in.read(signature, 16);
if (uts::string(signature, 16) != "TERRAGENTERRAIN ")
{
throw std::runtime_error("signature did not match");
}
int width = -1;
int height = -1;
float step = 0.0f;
while (true)
{
// Markers are aligned to 4-byte boundaries
auto pos = in.tellg();
if (pos & 3)
in.seekg(4 - (pos & 3), std::ios::cur);
char markerData[4];
in.read(markerData, 4);
uts::string marker(markerData, 4);
if (marker == "XPTS")
width = readUint16(in);
else if (marker == "YPTS")
height = readUint16(in);
else if (marker == "SIZE")
width = height = readUint16(in) + 1;
else if (marker == "SCAL")
{
float stepX = readFloat(in);
float stepY = readFloat(in);
float stepZ = readFloat(in);
if (stepY != stepX || stepZ != stepX)
{
std::cerr << "stepX = " << stepX << " stepY = " << stepY << " stepZ = " << stepZ << std::endl;
// throw std::runtime_error("SCAL values are not all equal");
}
else if (stepX <= 0.0f)
throw std::runtime_error("SCAL value is negative");
step = stepX;
}
else if (marker == "CRAD")
readFloat(in); // radius of planet
else if (marker == "CRVM")
in.ignore(4);
else if (marker == "ALTW")
{
if (step == 0.0f)
{
std::cerr << "Warning: no scale found. Using spec default of 30\n";
step = 30.0f;
}
float heightScale = readInt16(in) / 65536.0f;
float baseHeight = readInt16(in);
if (width <= 0 || height <= 0)
throw std::runtime_error("ALTW found before dimensions");
ans.setStep(step);
ans.allocate({0, 0, width, height});
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
float h = readInt16(in);
h = baseHeight + heightScale * h;
h = h * step;
ans[y][x] = h;
}
}
else if (marker == "EOF ")
break;
else
throw std::runtime_error("unexpected chunk `" + marker + "'");
}
}
catch (std::runtime_error &e)
{
throw std::runtime_error("Failed to read " + filename + ": " + e.what());
}
return ans;
}
void writeTerragen(const uts::string &filename, const MemMap<height_tag> &map, const Region ®ion)
{
try
{
if (region.width() >= 65536 || region.height() >= 65536)
throw std::runtime_error("Region is too large for Terragen format");
if (region.empty())
throw std::runtime_error("Empty region cannot be written to Terragen format");
if (map.step() <= 0.0f)
throw std::runtime_error("Map with zero step cannot be written to Terragen format");
float minHeight = std::numeric_limits<float>::infinity();
float maxHeight = -std::numeric_limits<float>::infinity();
// #pragma omp parallel for schedule(static) reduction(min:minHeight) reduction(max:maxHeight)
for (int y = region.y0; y < region.y1; y++)
for (int x = region.x0; x < region.x1; x++)
{
float h = map[y][x];
minHeight = std::min(minHeight, h);
maxHeight = std::max(maxHeight, h);
}
if (!std::isfinite(minHeight) || !std::isfinite(maxHeight))
throw std::runtime_error("Non-finite heights cannot be written to Terragen format");
float baseHeight = std::round((minHeight + maxHeight) * 0.5 / map.step());
if (baseHeight < INT16_MIN || baseHeight > INT16_MAX)
throw std::runtime_error("Heights are too large for Terragen format");
float heightScale = std::max(
(minHeight / map.step() - baseHeight) * 65536 / INT16_MIN,
(maxHeight / map.step() - baseHeight) * 65536 / INT16_MAX);
heightScale = std::ceil(heightScale);
if (heightScale > INT16_MAX)
throw std::runtime_error("Height range is too large for Terragen format");
std::ofstream out(filename, std::ios::binary);
if (!out)
throw std::runtime_error("Could not open file");
out.imbue(std::locale::classic());
out.exceptions(std::ios::failbit | std::ios::badbit);
out.write("TERRAGENTERRAIN ", 16);
out.write("SIZE", 4);
writeUint16(out, std::min(region.width(), region.height()) - 1);
writeUint16(out, 0); // padding
out.write("XPTS", 4);
writeUint16(out, region.width());
writeUint16(out, 0); // padding
out.write("YPTS", 4);
writeUint16(out, region.height());
writeUint16(out, 0); // padding
out.write("SCAL", 4);
writeFloat(out, map.step());
writeFloat(out, map.step());
writeFloat(out, map.step());
out.write("ALTW", 4);
writeInt16(out, std::int16_t(heightScale));
writeInt16(out, std::int16_t(baseHeight));
float scale = 65536.0f / (map.step() * heightScale);
float bias = -baseHeight * 65536.0f / heightScale;
for (int y = region.y0; y < region.y1; y++)
for (int x = region.x0; x < region.x1; x++)
{
float h = map[y][x] * scale + bias;
writeInt16(out, std::int16_t(std::round(h)));
}
if (region.pixels() & 1)
writeInt16(out, 0); // padding
out.write("EOF ", 4);
out.close();
}
catch (std::runtime_error &e)
{
throw std::runtime_error("Failed to write " + filename + ": " + e.what());
}
}
| 8,594
|
C++
|
.cpp
| 223
| 29.345291
| 114
| 0.546053
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,198
|
gdal2exr.cpp
|
jgain_EcoLearn/UnderSim/common/gdal2exr.cpp
|
#include <iostream>
#include <locale>
#include <common/debug_string.h>
#include <common/debug_vector.h>
#include <stack>
#include <stdexcept>
#include <cstdint>
#include <limits>
#include <cstring>
#include <cmath>
#include <boost/program_options.hpp>
#include "map.h"
#include "initialize.h"
#include "gdal_priv.h"
#include "cpl_conv.h"
#include "ogr_spatialref.h"
namespace po = boost::program_options;
namespace
{
namespace Option
{
static const char *inputFile() { return "input"; }
static const char *outputFile() { return "output"; }
static const char *forceStep() { return "force-step"; }
static const char *noClip() { return "no-clip"; }
static const char *noOrigin() { return "no-origin"; }
static const char *region() { return "region"; }
static const char *help() { return "help"; }
} // namespace Option
} // anonymous namespace
class GDALDeleter
{
public:
void operator()(GDALDataset *dataset) const
{
if (dataset != nullptr)
GDALClose(dataset);
}
};
static MemMap<height_tag> loadMap(const uts::string &filename, const po::variables_map &vm, float &noData)
{
const std::unique_ptr<GDALDataset, GDALDeleter> dataset((GDALDataset *) GDALOpen(filename.c_str(), GA_ReadOnly));
if (!dataset)
throw std::runtime_error("Could not open " + filename);
MemMap<height_tag> ans;
try
{
// importFromWkt uses a char** instead of const char **
char * projectionName = const_cast<char *>(dataset->GetProjectionRef());
OGRSpatialReference srs;
// Note: this updates projectionName to point past-the-end of the WKT
srs.importFromWkt(&projectionName);
float step;
if (!vm.count(Option::forceStep()))
{
double transform[6];
if (dataset->GetGeoTransform(transform) != CE_None)
throw std::runtime_error("No step size found in file or on command line");
double scale;
if (srs.IsGeographic())
{
/* For now assume this means degrees, and ignore the fact that
* X will have a different scale to Y. The value of 111120 is based
* on a nautical mile being 1852m.
*/
scale = 111120;
}
else
{
char *unitNameChar;
scale = srs.GetLinearUnits(&unitNameChar);
uts::string unitName(unitNameChar);
if (unitName.empty() || unitName == "unknown")
throw std::runtime_error("No units provided");
}
double xstep = hypot(transform[1], transform[4]) * scale;
double ystep = hypot(transform[2], transform[5]) * scale;
if (std::fabs(xstep - ystep) > 1e-6 * std::max(xstep, ystep))
throw std::runtime_error("Pixels are not square: " + std::to_string(xstep) + " x " + std::to_string(ystep));
step = xstep;
}
else
step = vm[Option::forceStep()].as<float>();
const int width = dataset->GetRasterXSize();
const int height = dataset->GetRasterYSize();
const int numBands = dataset->GetRasterCount();
if (numBands < 1)
throw std::runtime_error("No data");
GDALRasterBand *band = dataset->GetRasterBand(1);
uts::string unitType = band->GetUnitType();
if (unitType != "" && unitType != "m")
throw std::runtime_error("Unknown unit type: " + unitType);
ans.allocate({0, 0, width, height});
ans.setStep(step);
CPLErr status = band->RasterIO(GF_Read, 0, 0, width, height, (void *) ans.get(),
width, height, GDT_Float32, 0, 0);
if (status != CE_None)
throw std::runtime_error("RasterIO failed");
noData = band->GetNoDataValue();
// RasterIO gives raw values, prior to scale+bias
double scale = band->GetScale();
double offset = band->GetOffset();
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
ans[y][x] = float(ans[y][x] * scale + offset);
// Compute x value of central meridian
if (srs.GetUTMZone() != 0)
{
double falseEasting = srs.GetProjParm(SRS_PP_FALSE_EASTING, 500000.0);
double transform[6];
if (dataset->GetGeoTransform(transform) == CE_None)
{
double x = (falseEasting - transform[0]) / transform[1];
std::cout << "Central meridian is at X = " << int(std::round(x)) << '\n';
}
}
}
catch (std::runtime_error &e)
{
throw std::runtime_error("Failed to read " + filename + ": " + e.what());
}
return ans;
}
namespace { struct count_tag{}; }
static Region dataRegion(const MemMap<height_tag> &heights, float noData)
{
// Code hasn't been adapted to handle arbitrary origins yet
assert(heights.region().x0 == 0);
assert(heights.region().y0 == 0);
int W = heights.width();
int H = heights.height();
uts::vector<int> upCount(W + 1, 0); // number of valid entries upwards from here
Region best;
std::size_t bestArea = 0;
std::stack<std::pair<int, int> > st;
for (int y1 = 0; y1 < H; y1++)
{
while (!st.empty())
st.pop();
st.emplace(-1, -1);
for (int x = 0; x <= W; x++)
{
int u;
if (x == W || heights[y1][x] == noData)
u = 0;
else
u = upCount[x] + 1;
upCount[x] = u;
while (u < st.top().first)
{
Region test(st.top().second, y1 - st.top().first + 1, x, y1 + 1);
std::size_t area = std::size_t(test.width()) * test.height();
if (area > bestArea)
{
bestArea = area;
best = test;
}
st.pop();
}
st.emplace(u, x);
}
}
return best;
}
static void usage(std::ostream &o, const po::options_description desc)
{
o << "Usage: gdal2exr [options] input.tif output.exr\n";
o << desc;
}
static po::variables_map processOptions(int argc, char **argv)
{
po::positional_options_description positional;
positional.add(Option::inputFile(), 1);
positional.add(Option::outputFile(), 1);
po::options_description desc("General options");
desc.add_options()
(Option::forceStep(), po::value<float>(), "override step size extracted from file")
(Option::noClip(), "do not clip the image to exclude missing data")
(Option::noOrigin(), "do not move data to start at the origin")
(Option::region(), po::value<std::string>(), "Subregion to extract (x:y:w:h)")
(Option::help(), "show help");
po::options_description hidden("Hidden options");
hidden.add_options()
(Option::inputFile(), po::value<std::string>()->required(), "input file")
(Option::outputFile(), po::value<std::string>()->required(), "output file");
po::options_description all("All options");
all.add(desc);
all.add(hidden);
try
{
po::variables_map vm;
po::store(po::command_line_parser(argc, argv)
.style(po::command_line_style::default_style & ~po::command_line_style::allow_guessing)
.options(all)
.positional(positional)
.run(), vm);
po::notify(vm);
if (vm.count(Option::help()))
{
usage(std::cout, desc);
std::exit(0);
}
return vm;
}
catch (po::error &e)
{
std::cerr << e.what() << "\n\n";
usage(std::cerr, desc);
std::exit(1);
}
}
int main(int argc, char **argv)
{
utsInitialize();
try
{
GDALAllRegister();
po::variables_map vm = processOptions(argc, argv);
float noData;
MemMap<height_tag> m = loadMap(vm[Option::inputFile()].as<std::string>(), vm, noData);
Region region = m.region();
if (!vm.count(Option::noClip()))
region = dataRegion(m, noData);
if (vm.count(Option::region()))
{
// TODO: make robust!
int x, y, w, h;
std::sscanf(vm[Option::region()].as<std::string>().c_str(),
"%d:%d:%d:%d", &x, &y, &w, &h);
if (x < 0 || w <= 0 || x + w > region.width()
|| y < 0 || h <= 0 || y + h > region.height())
{
std::cerr << "--" << Option::region() << " values are out of range\n";
return 1;
}
region.x0 += x;
region.y0 += y;
region.x1 = region.x0 + w;
region.y1 = region.y0 + h;
}
if (!vm.count(Option::noOrigin()))
{
m.translateTo(m.region().x0 - region.x0,
m.region().y0 - region.y0);
// Translate the region to the origin
region.x1 -= region.x0;
region.y1 -= region.y0;
region.x0 = 0;
region.y0 = 0;
}
m.write(vm[Option::outputFile()].as<std::string>(), region);
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
}
| 9,450
|
C++
|
.cpp
| 258
| 27.620155
| 124
| 0.542549
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,199
|
map.cpp
|
jgain_EcoLearn/UnderSim/common/map.cpp
|
/**
* @file
*
* Classes for 2D arrays of data.
*/
#include <ImfFrameBuffer.h>
#include <ImfInputFile.h>
#include <ImfFloatAttribute.h>
#include <algorithm>
#include <string>
#include <utility>
#include <cassert>
#include "map.h"
#include "str.h"
#include "terragen.h"
#include "obj.h"
namespace detail
{
float getOpenEXRStep(const Imf::InputFile &in)
{
const Imf::FloatAttribute *s = in.header().findTypedAttribute<Imf::FloatAttribute>("heightMapResolution");
if (s != NULL)
return s->value();
else
return 0.0f;
}
uts::string mapArrayFilename(const uts::string &prefix, int slice)
{
return prefix + "-" + std::to_string(slice) + ".exr";
}
void writeFrameBuffer(const uts::string &filename, float step, const Imf::FrameBuffer &fb,
const Region ®ion)
{
Imath::Box2i window({region.x0, region.y0}, {region.x1 - 1, region.y1 - 1});
Imf::Header header(window, window);
if (step != 0.0f)
header.insert("heightMapResolution", Imf::FloatAttribute(step));
header.compression() = Imf::ZIP_COMPRESSION;
for (auto i = fb.begin(); i != fb.end(); ++i)
header.channels().insert(i.name(), Imf::Channel(i.slice().type));
Imf::OutputFile out(filename.c_str(), header);
out.setFrameBuffer(fb);
out.writePixels(region.height());
}
} // namespace detail
/**********************************************************************/
void MapTraits<height_tag>::prepareFrameBuffer(Imf::FrameBuffer &fb, const io_type *base, std::size_t width)
{
fb.insert("Y", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(const_cast<io_type *>(base)),
sizeof(io_type), sizeof(io_type) * width));
}
bool MapTraits<height_tag>::customRead(MemMap<height_tag> &out, const uts::string &filename)
{
if (endsWith(filename, ".ter"))
{
out = readTerragen(filename);
return true;
}
else
return false;
}
bool MapTraits<height_tag>::customWrite(
const MemMap<height_tag> &out, const uts::string &filename, const Region ®ion)
{
if (endsWith(filename, ".ter"))
{
writeTerragen(filename, out, region);
return true;
}
else if (endsWith(filename, ".obj"))
{
writeOBJ(filename, out, region);
return true;
}
else
return false;
}
void MapTraits<distance_field_tag>::prepareFrameBuffer(Imf::FrameBuffer &fb, const io_type *base, std::size_t width)
{
fb.insert("dist", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0].dist),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("param", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0].param),
sizeof(io_type), sizeof(io_type) * width));
}
constexpr MapTraits<mask_tag>::type MapTraits<mask_tag>::all;
constexpr MapTraits<mask_tag>::type MapTraits<mask_tag>::none;
constexpr int MapTraits<mask_tag>::numTypes;
void MapTraits<mask_tag>::prepareFrameBuffer(Imf::FrameBuffer &fb, const io_type *base, std::size_t width)
{
fb.insert("mask", Imf::Slice(Imf::UINT, reinterpret_cast<char *>(const_cast<io_type *>(base)),
sizeof(io_type), sizeof(io_type) * width));
}
void MapTraits<height_and_mask_tag>::prepareFrameBuffer(Imf::FrameBuffer &fb, const io_type *base, std::size_t width)
{
fb.insert("Y", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0].height),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("mask", Imf::Slice(Imf::UINT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0].mask),
sizeof(io_type), sizeof(io_type) * width));
}
bool MapTraits<height_and_mask_tag>::customRead(MemMap<height_and_mask_tag> &out, const uts::string &filename)
{
if (endsWith(filename, ".ter"))
{
MemMap<height_tag> heights = readTerragen(filename);
out.allocate(heights.region());
out.setStep(heights.step());
const Region &r = heights.region();
#pragma omp parallel for schedule(static)
for (int y = r.y0; y < r.y1; y++)
for (int x = r.x0; x < r.x1; x++)
{
out[y][x].height = heights[y][x];
out[y][x].mask = MapTraits<mask_tag>::all;
}
return true;
}
else
return false;
}
bool MapTraits<height_and_mask_tag>::customWrite(
const MemMap<height_and_mask_tag> &out, const uts::string &filename, const Region ®ion)
{
if (endsWith(filename, ".ter") || endsWith(filename, ".obj"))
{
MemMap<height_tag> tmp(region);
tmp.setStep(out.step());
#pragma omp parallel for schedule(static)
for (int y = region.y0; y < region.y1; y++)
for (int x = region.x0; x < region.x1; x++)
tmp[y][x] = out[y][x].height;
tmp.write(filename);
return true;
}
else
return false;
}
void MapTraits<appearance_tag>::prepareFrameBuffer(Imf::FrameBuffer &fb, const io_type *base, std::size_t width)
{
static_assert(APPEARANCE_MODES == 4, "Need to update for new APPEARANCE_MODES");
fb.insert("R", Imf::Slice(Imf::UINT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][0]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("G", Imf::Slice(Imf::UINT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][1]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("B", Imf::Slice(Imf::UINT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][2]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("appearance.3", Imf::Slice(Imf::UINT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][3]),
sizeof(io_type), sizeof(io_type) * width));
}
void MapTraits<appearance_tag>::convert(type in, io_type &out)
{
std::copy(begin(in), end(in), begin(out));
}
void MapTraits<appearance_tag>::convert(io_type in, type &out)
{
std::copy(begin(in), end(in), begin(out));
}
void MapTraits<coords_tag>::prepareFrameBuffer(Imf::FrameBuffer &fb, const io_type *base, std::size_t width)
{
fb.insert("R", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0].flat[0]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("G", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0].flat[1]),
sizeof(io_type), sizeof(io_type) * width));
}
void MapTraits<coords_offset_tag>::prepareFrameBuffer(Imf::FrameBuffer &fb, const io_type *base, std::size_t width)
{
// This can't chain to MapTraits<coords_tag>, because sizeof(io_type) is different
fb.insert("R", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0].flat[0]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("G", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0].flat[1]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("B", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0].offset),
sizeof(io_type), sizeof(io_type) * width));
}
/**********************************************************************/
int MapRegion::width() const
{
return region_.width();
}
int MapRegion::height() const
{
return region_.height();
}
const Region &MapRegion::region() const
{
return region_;
}
void MapRegion::setRegion(const Region &newRegion)
{
region_ = newRegion;
}
void MapRegion::translateTo(int x, int y)
{
setRegion(Region(x, y, x + region_.width(), y + region_.height()));
}
/**********************************************************************/
float MapBase::step() const
{
return step_;
}
void MapBase::setStep(float step)
{
assert(step >= 0.0f);
step_ = step;
}
/**********************************************************************/
int MapArrayBase::arraySize() const
{
return step_.size();
}
float MapArrayBase::step(int slice) const
{
assert(0 <= slice && slice < arraySize());
return step_[slice];
}
const uts::vector<float> &MapArrayBase::step() const
{
return step_;
}
void MapArrayBase::reserveStep(int newSize)
{
step_.reserve(newSize);
}
void MapArrayBase::resizeStep(int newSize)
{
if (std::size_t(newSize) != step_.size())
{
step_.resize(newSize);
step_.shrink_to_fit();
}
}
void MapArrayBase::setStep(int slice, float step)
{
assert(0 <= slice && slice < arraySize());
step_[slice] = step;
}
void MapArrayBase::setStep(const MapArrayBase &other)
{
assert(other.step_.size() == step_.size());
step_ = other.step_;
}
void MapArrayBase::setStep(uts::vector<float> &&step)
{
assert(step.size() == step_.size());
step_ = std::move(step);
}
/**********************************************************************/
void Map::allocate(const Region ®ion)
{
assert(region.x0 <= region.x1);
assert(region.y0 <= region.y1);
if (this->region().width() != region.width()
|| this->region().height() != region.height())
allocateImpl(region.width(), region.height());
setRegion(region);
}
void Map::clear()
{
allocate(Region());
setStep(0.0f);
}
std::tuple<Region, float> Map::fileDimensions(const uts::string &filename)
{
Imf::InputFile in(filename.c_str());
auto dw = in.header().dataWindow();
Region r(dw.min.x, dw.min.y, dw.max.x + 1, dw.max.y + 1);
float step = detail::getOpenEXRStep(in);
return std::make_tuple(r, step);
}
/**********************************************************************/
void MapArray::allocate(const Region ®ion, int arraySize)
{
assert(region.x0 <= region.x1);
assert(region.y0 <= region.y1);
reserveStep(arraySize);
if (arraySize != this->arraySize()
|| region.width() != this->region().width()
|| region.height() != this->region().height())
{
allocateImpl(region.width(), region.height(), arraySize);
resizeStep(arraySize);
}
setRegion(region);
}
void MapArray::clear()
{
allocate(Region(), 0);
}
/**********************************************************************/
template class MemMap<height_tag>;
template class MemMap<distance_field_tag>;
template class MemMap<mask_tag>;
template class MemMap<height_and_mask_tag>;
template class MemMap<appearance_tag>;
template class MemMap<coords_tag>;
template class MemMap<coords_offset_tag>;
template class MemMap<height_constraint_tag>;
template class MemMapArray<height_tag>;
template class MemMapArray<appearance_tag>;
template class MemMapArray<coords_tag>;
template class MemMapArray<coords_offset_tag>;
| 10,938
|
C++
|
.cpp
| 300
| 31.22
| 117
| 0.605875
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,200
|
initialize.cpp
|
jgain_EcoLearn/UnderSim/common/initialize.cpp
|
/**
* @file
*
* Startup code that must be called by @c main.
*/
#include <thread>
#include <eigen3/Eigen/Core>
#include <ImfThreading.h>
#include "initialize.h"
void utsInitialize()
{
Eigen::initParallel();
Imf::setGlobalThreadCount(std::thread::hardware_concurrency());
}
| 287
|
C++
|
.cpp
| 14
| 18.5
| 67
| 0.723247
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,201
|
color2gray.cpp
|
jgain_EcoLearn/UnderSim/common/color2gray.cpp
|
#include <stdexcept>
#include <array>
#include <cstddef>
#include <type_traits>
#include <ImfFrameBuffer.h>
#include "map.h"
#include "map_rgba.h"
#include "initialize.h"
int main(int argc, char **argv)
{
utsInitialize();
if (argc != 3)
{
std::cerr << "Usage: color2gray input.exr output.exr\n";
return 1;
}
try
{
MemMap<gray_tag> in;
in.read(argv[1]);
in.write(argv[2]);
}
catch (std::exception &e)
{
std::cerr << e.what() << '\n';
return 1;
}
}
| 545
|
C++
|
.cpp
| 28
| 14.964286
| 64
| 0.568932
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,202
|
palette.cpp
|
jgain_EcoLearn/EcoSynth/viewer/palette.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected]) and K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
// constraint.cpp: various user generated constraints for ultimate terrain synthesis
// author: James Gain
// date: 5 November 2013
// 21 January 2013 - curve constraints
#include <GL/glew.h>
#include <cassert>
#include <cmath>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "timer.h"
#include "palette.h"
#include "fill.h"
#include "eco.h"
#include <QtWidgets>
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "glwidget.h"
/*
GLfloat manipCol[] = {0.325f, 0.235f, 1.0f, 1.0f};
//GLfloat manipCol[] = {0.406f, 0.294f, 1.0f, 1.0f};
GLfloat curveCol[] = {0.243f, 0.176f, 0.75f, 1.0f};
GLfloat blockedCol[] = {0.5f, 0.5f, 0.8f, 1.0f};
//GLfloat blockedCol[] = {0.325f, 0.235f, 1.0f, 1.0f};
*/
using namespace std;
//
// Palette
//
BrushPalette::BrushPalette(TypeMap *typemap, int nentries, QWidget *parent)
: palette_base(typemap, nentries, parent)
{
}
void BrushPalette::typeSelect()
{
typeSelectMode(ControlMode::PAINTLEARN);
}
/*
void BrushPalette::typeSelectSpecies()
{
// TO DO - deal with the case that one of the palette entries is in selection mode
for(int i = 0; i < nentries; i++)
{
if(sender() == selector[i])
{
cerr << "index " << i << " selected" << std::endl;
currSel = i;
glparent->setCtrlMode(ControlMode::PAINTSPECIES); // activate paint mode
}
}
setActivePalette();
cerr << "currently selected brush = " << (int) typeSel[currSel] << ", with index " << currSel << endl;
}
*/
void SpeciesPalette::enable_brush(int idx)
{
if (idx < nentries)
selector[idx]->setEnabled(true);
}
void SpeciesPalette::disable_brush(int idx)
{
if (idx < nentries)
selector[idx]->setEnabled(false);
}
SpeciesPalette::SpeciesPalette(TypeMap *typemap, const std::vector<int> &species_ids, QWidget *parent)
: palette_base(typemap, species_ids, parent)
{
idx_to_id = species_ids;
for (int i = 0; i < species_ids.size(); i++)
{
id_to_idx[species_ids.at(i)] = i;
}
}
int SpeciesPalette::getDrawTypeIndex()
{
return currSel;
}
void SpeciesPalette::typeSelect()
{
typeSelectMode(ControlMode::PAINTSPECIES);
}
//
// BrushCursor
//
void BrushCursor::genBrushRing(View * view, Terrain * terrain, float brushradius, bool dashed)
{
uts::vector<vpPoint> ring;
int steps, j;
float a, stepa, tol, tx, ty;
vpPoint pnt;
// shape.clear();
terrain->getTerrainDim(tx, ty);
tol = 0.001f * std::max(tx, ty);
// draw ring to indicate extent of brush stroke
// generate vertices for ring and drop onto terrain
if(active)
{
a = 0.0f;
steps = 1000;
stepa = PI2 / (float) steps;
for(j = 0; j < steps+1; j++)
{
pnt.x = pos.x + cosf(a) * brushradius;
if(pnt.x >= tx-tolzero) pnt.x = tx-tolzero;
if(pnt.x <= tolzero) pnt.x = tolzero;
pnt.y = 1.0f;
pnt.z = pos.z + sinf(a) * brushradius;
if(pnt.z >= ty-tolzero) pnt.z = ty-tolzero;
if(pnt.z <= tolzero) pnt.z = tolzero;
ring.push_back(pnt);
a += stepa;
}
drapeProject(&ring, &ring, terrain);
// add height offset to all ring positions
for(j = 0; j < (int) ring.size(); j++)
ring[j].y += hghtoffset;
if(dashed)
shape.genDashedCylinderCurve(ring, manipradius * 0.5f * view->getScaleFactor(), tol, manipradius * view->getScaleFactor(), 10);
else
shape.genCylinderCurve(ring, manipradius * 0.5f * view->getScaleFactor(), tol, 10);
}
}
void BrushCursor::cursorUpdate(View * view, Terrain * terrain, int x, int y)
{
vpPoint frompnt, topnt;
view->projectingPoint(x, y, frompnt);
if(terrainProject(frompnt, topnt, view, terrain))
{
pos = topnt;
active = true;
}
else
{
active = false;
}
}
/// getters and setters for brush radii
void BrushCursor::setRadius(float rad)
{
radius = rad;
}
//
// BrushPaint
//
BrushPaint::BrushPaint(Terrain * ter, BrushType btype)
{
terrain = ter;
brushtype = btype;
drawing = false;
}
void BrushPaint::paintMap(TypeMap * pmap, float radius)
{
int dx, dy, si, sj, ei, ej;
float inr, h, ox, oy, irad;
vpPoint p;
terrain->getGridDim(dx, dy);
pmap->matchDim(dx, dy);
// apply stroke to type map by setting index values out to a certain radius around the stroke
irad = terrain->toGrid(radius);
inr = irad * irad;
// convert to grid coordinates
terrain->toGrid(currpnt, ox, oy, h);
// bound by edge of map
si = (int) (ox - irad); if(si < 0) si = 0;
ei = (int) (ox + irad + 0.5f); if(ei >= dx) ei = dx-1;
sj = (int) (oy - irad); if(sj < 0) sj = 0;
ej = (int) (oy + irad + 0.5f); if(ej >= dy) ej = dy-1;
#pragma omp parallel for
for(int j = sj; j <= ej; j++)
for(int i = si; i <= ei; i++)
{
float cx, cy;
cx = ox - (float) i; cx *= cx;
cy = oy - (float) j; cy *= cy;
if(cx + cy <= inr) // inside region
(* pmap->getMap())[j][i] = (int) brushtype;
}
}
void BrushPaint::addMousePnt(View * view, TypeMap * pmap, int x, int y, float radius)
{
Region reg;
bool valid;
vpPoint prjpnt, terpnt;
int dx, dy;
// Timer t;
// t.start();
// capture mouse point projected onto terrain
// must capture current and previous point for cases where updates are not immediate and the mouse has travelled some distance
// instead of drawing spheres onto the terrain, draw capsules in this case
view->projectingPoint(x, y, prjpnt);
valid = terrainProject(prjpnt, terpnt, view, terrain);
if(valid)
{
if(!drawing) // first point in the stroke
{
prevpnt = terpnt;
currpnt = terpnt;
drawing = true;
}
else
{
prevpnt = currpnt;
currpnt = terpnt;
}
// set bounding region to surround the points and their offset radius
// bnd.reset();
bnd.includePnt(currpnt);
bnd.includePnt(prevpnt);
BoundRect locbnd;
locbnd = bnd;
locbnd.expand(radius);
terrain->getGridDim(dx, dy);
// convert to terrain coordinates
reg.x0 = (int) terrain->toGrid(locbnd.min.x);
if(reg.x0 < 0) reg.x0 = 0;
reg.y0 = (int) terrain->toGrid(locbnd.min.z);
if(reg.y0 < 0) reg.y0 = 0;
reg.x1 = (int) terrain->toGrid(locbnd.max.x);
if(reg.x1 > dx) reg.x1 = dx;
reg.y1 = (int) terrain->toGrid(locbnd.max.z);
if(reg.y1 > dy) reg.y1 = dy;
paintMap(pmap, radius); // render to paint map
pmap->setRegion(reg);
// t.stop();
// cerr << "Brush time = " << t.peek() << endl;
}
}
void BrushPaint::startStroke()
{
bnd.reset();
}
void BrushPaint::finStroke()
{
drawing = false;
}
| 8,067
|
C++
|
.cpp
| 257
| 26.229572
| 139
| 0.605053
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,203
|
test_specassign.cpp
|
jgain_EcoLearn/EcoSynth/viewer/test_specassign.cpp
|
#include "canopy_placement/basic_types.h"
#include "canopy_placement/species_assign.h"
#include "canopy_placement/misc.h"
#include "canopy_placement/extract_png.h"
#include <functional>
#include <algorithm>
int main(int argc, char * argv [])
{
int width, height;
int mwidth, mheight;
std::vector<basic_tree> trees;
read_pdb("/home/konrad/PhDStuff/spacing_pipeline_out.pdb", trees);
std::vector<float> chm_data = get_image_data_8bit("/home/konrad/PhDStuff/chm_pipeline_out.png", width, height)[0];
std::vector<float> mflow_data = get_image_data_48bit("/home/konrad/PhDStuff/H10mflow.png", mwidth, mheight)[0];
for (auto &v : mflow_data)
{
if (v > 5000)
{
v = 5000;
}
}
if (width != mwidth || height != mheight)
{
throw std::runtime_error("Width and/or height of CHM and mflow data don't match. Aborting.");
}
std::vector<basic_tree*> tree_ptrs(trees.size());
int i = 0;
for (auto &tree : trees)
{
tree_ptrs[i] = &tree;
i++;
}
std::vector<float *> adapt_maps_data = {chm_data.data(), mflow_data.data()};
std::vector<bool> adapt_maps_ownership = {false, false};
std::vector<bool> row_major = {true, true};
std::vector< std::vector<std::function<float(float)> > > adapt_maps_per_species = {
{ [](float val) { return val/30; }, [](float val) { return 1000/val;} },
{ [](float val) { return 30/val; }, [](float val){ return val/1000; }},
{ [](float val) { return 30/val; }, [](float val){ return 1000/val; }}
};
int nspecies = 3;
auto specassign = species_assign(tree_ptrs, nspecies, width, height, adapt_maps_data, adapt_maps_ownership, row_major, adapt_maps_per_species);
specassign.assign_species();
std::vector< std::vector<basic_tree *> > trees_sorted(specassign.get_nspecies());
for (auto &tptr : tree_ptrs)
{
trees_sorted[tptr->species].push_back(tptr);
}
write_pdb("/home/konrad/PhDStuff/H10pipeline_assigntest.pdb", trees_sorted);
return 0;
}
| 2,062
|
C++
|
.cpp
| 51
| 35.196078
| 147
| 0.638319
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,204
|
ipc.cpp
|
jgain_EcoLearn/EcoSynth/viewer/ipc.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
// ipc.cpp: class for controlling interprocess communication with TensorFlow sketching process using ZeroMQ
// author: James Gain
// date: 7 January 2019
#include <string>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "ipc.h"
using namespace std;
IPC::IPC()
{
// Prepare context and socket
context = new zmq::context_t(1);
socket = new zmq::socket_t((* context), ZMQ_REQ);
//socket->connect("tcp://137.158.59.252:5555");
//socket->connect("tcp://localhost:5555");
//socket->connect("tcp://192.168.101.251:5555");
socket->connect("tcp://127.0.1.1:5555"); // for the local machine
//socket->connect("tcp://137.158.60.235:5555"); // for the other machine
cerr << "IPC: finished connection" << endl;
}
static int s_interrupted = 0;
static void s_signal_handler (int signal_value)
{
s_interrupted = 1;
}
static void s_catch_signals (void)
{
struct sigaction action;
action.sa_handler = s_signal_handler;
action.sa_flags = 0;
sigemptyset (&action.sa_mask);
sigaction (SIGINT, &action, NULL);
sigaction (SIGTERM, &action, NULL);
}
void IPC::composeTransmission(TypeMap * tmap, unsigned char * cmap, unsigned short sktch, unsigned short hght, int x, int y, int scale)
{
// transmission structure
// r,g,b layers are interleaved
// msb is first then lsb second
// r-channel holds terrain heights
// g-channel holds paint map
int yoffset = tmap->height()/scale;
int pos = (x * yoffset + y) * 2 * 3;
// sep into upper and lower byte
unsigned char upper, lower;
// pack terrain height
lower = (hght&0xFF); //extract first byte
upper = ((hght>>8)&0xFF); //extract second byte
cmap[pos] = lower;
cmap[pos+1] = upper;
// pack sketch map
lower = (sktch&0xFF); //extract first byte
upper = ((sktch>>8)&0xFF); //extract second byte
cmap[pos+2] = lower;
cmap[pos+3] = upper;
cmap[pos+4] = 0;
cmap[pos+5] = 0;
}
unsigned short IPC::decomposeTransmission(MapFloat * fmap, unsigned char * cmap, int x, int y, int upsample_factor)
{
// only one channel (green) needed, because of greyscale.
// int loffset = ((tmap->width() * tmap->height()) / 16) * 2 * 3;
int yoffset = fmap->height()/upsample_factor;
int loc = (x * yoffset + y) * 2 * 3;
unsigned short tval = (unsigned short) cmap[loc+3]; // green bits
tval = (tval << 8);
tval += (unsigned short) cmap[loc+2];
return tval;
// return (int) cmap[loc];
}
void IPC::send(TypeMap * tmap, Terrain * ter, int scale_down)
{
// data transmission format width * height * 3 * uint16 at 4m per cell sampling
// potential issues with data formats
// downsample tmap to scale_down (was 4meters) per cell resolution
int csize = ((tmap->width() * tmap->height()) / (scale_down * scale_down)) * 3 * 2;
unsigned char * cmap = new unsigned char[csize];
// downsample tmap according to majority type in 4x4 area
int ecnt, scnt, dcnt;
for(int x = 0; x < tmap->width(); x+=scale_down)
for(int y = 0; y < tmap->height(); y+=scale_down) // this increment value was originally 4...I assumed that it was the scaling down factor?
{
ecnt = 0; scnt = 0; dcnt = 0;
for(int i = 0; i < scale_down; i++)
for(int j = 0; j < scale_down; j++)
{
int paint = tmap->get(y+j, x+i);
switch(paint)
{
case 0:
ecnt++;
break;
case 1:
scnt++;
break;
case 2:
dcnt++;
break;
default:
ecnt++;
break;
}
}
// ?? order of x, y in getHeight
unsigned int hght = (unsigned int) (ter->getHeight(x, y) / (3000.0f / mtoft) * 65535.0f);
// cerr << " " << ter->getHeight(x, y) << " " << hght;
// set according to highest count
if((ecnt > scnt) && (ecnt > dcnt))
{
composeTransmission(tmap, cmap, 0, hght, x/scale_down, y/scale_down, scale_down);
}
else
{
if(scnt > dcnt)
composeTransmission(tmap, cmap, 32768, hght, x/scale_down, y/scale_down, scale_down);
else
composeTransmission(tmap, cmap, 65535, hght, x/scale_down, y/scale_down, scale_down);
}
}
// send data using zeroMQ
zmq::message_t outward (csize);
memcpy (outward.data (), cmap, csize);
try
{
socket->send (outward, 0);
}
catch(zmq::error_t& e)
{
cerr << "send failed: " << e.what() << endl;
}
if (s_interrupted)
{
cerr << "interrupt received" << endl;
}
delete cmap;
}
void IPC::receive(MapFloat * fmap, int scale)
{
zmq::message_t request;
// wait for image from TensorFlow server
socket->recv(&request);
cerr << "msg decode phase" << endl;
// decode and repack image into tmap
int csize = ((fmap->width() * fmap->height()) / (scale * scale)) * 3 * 2;
unsigned char * cmap = (unsigned char *) request.data();
// report message size
// cerr << "message size " << (int) request.size() << " expected " << csize << endl;
fmap->fill(0.0f);
// set block of <scale> pixels to the same value since TensorFlow output is downsampled
for(int x = 0; x < fmap->width() / scale; x++)
for(int y = 0; y < fmap->height() / scale; y++)
{
unsigned short tval = decomposeTransmission(fmap, cmap, x, y, scale);
// if(tval != 0)
// cerr << " " << tval;
//if(tval > 65000)
for(int i = x*scale; i < x*scale+scale; i++) // upsample to scale x scale block of pixels
for(int j = y*scale; j < y*scale+scale; j++)
//fmap->set(i, j, 35.0f); // tall tree value at the moment, connect to heights later
//fmap->set(i, j, i); // just to test the display of CHM (remove ASAP)
fmap->set(i, j, tval);
}
}
void IPC::receive_only(MapFloat *fmap)
{
zmq::message_t request;
// wait for image from TensorFlow server
socket->recv(&request);
cerr << "msg decode phase" << endl;
cerr << "msg width, height (elements): " << fmap->width() << ", " << fmap->height() << std::endl;
// decode and repack image into tmap
int csize = (fmap->width() * fmap->height()) * 3 * 2;
unsigned char * cmap = (unsigned char *) request.data();
// report message size
// cerr << "message size " << (int) request.size() << " expected " << csize << endl;
fmap->fill(0.0f);
for(int x = 0; x < fmap->width(); x++)
for(int y = 0; y < fmap->height(); y++)
{
unsigned short tval = decomposeTransmission(fmap, cmap, x, y, 1);
fmap->set(x, y, tval);
}
}
/*
void IPC::receive_only(MapFloat * fmap)
{
zmq::message_t request;
// wait for image from TensorFlow server
socket->recv(&request);
cerr << "msg decode phase" << endl;
// decode and repack image into tmap
int csize = ((fmap->width() * fmap->height())) * 3 * 2;
unsigned char * cmap = (unsigned char *) request.data();
// report message size
// cerr << "message size " << (int) request.size() << " expected " << csize << endl;
fmap->fill(0.0f);
// set block of 4 pixels to the same value since TensorFlow output is downsampled
for(int x = 0; x < fmap->width(); x++)
for(int y = 0; y < fmap->height(); y++)
{
unsigned short tval = decomposeTransmission(fmap, cmap, x, y);
// if(tval != 0)
// cerr << " " << tval;
//if(tval > 65000)
for(int i = x*1; i < x*1+1; i++) // upsample to 1x1 block of pixels
for(int j = y*1; j < y*1+1; j++)
//fmap->set(i, j, 35.0f); // tall tree value at the moment, connect to heights later
//fmap->set(i, j, i); // just to test the display of CHM (remove ASAP)
fmap->set(i, j, tval);
}
}
*/
| 9,367
|
C++
|
.cpp
| 234
| 32.452991
| 148
| 0.560123
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,205
|
eco.cpp
|
jgain_EcoLearn/EcoSynth/viewer/eco.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected]) and K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
// eco.cpp: core classes for controlling ecosystems and plant placement
// author: James Gain and K.P. Kapp
// date: 27 February 2016
#include "eco.h"
#include "common/basic_types.h"
// #include "interp.h"
#include <stdlib.h>
#include <math.h>
#include <algorithm>
#include <random>
#include <chrono>
#include <QDir>
// Mediterrainean Biome PFT colours
GLfloat MedMNEcol[] = {0.173f, 0.290f, 0.055f, 1.0f}; // Black Pine (ID 12)
GLfloat MedTBScol[] = {0.498f, 0.258f, 0.094f, 1.0f}; // European Beech (ID 13) {0.498f, 0.208f, 0.094f, 1.0f};
GLfloat MedIBScol[] = {0.573f, 0.600f, 0.467f, 1.0f}; // Silver Birch (ID 14)
GLfloat MedTBEcol[] = {0.376f, 0.443f, 0.302f, 1.0f}; // Holly Oak (ID 15)
GLfloat MedMSEBcol[] = {0.164f, 0.164f, 0.09f, 1.0f}; // Kermes Oak Shrub (ID 16)
GLfloat MedMSENcol[] = {0.678f, 0.624f, 0.133f, 1.0f}; // Juniper Shrub (ID 17)
GLfloat MedITBScol[] = {0.561f, 0.267f, 0.376f, 1.0f}; // Trea of Heaven invader species (ID 18)
// Mediterrainean Biome PFT colours
GLfloat AlpTNEcol[] = {0.173f, 0.290f, 0.055f, 1.0f}; // Black Pine (ID 12)
GLfloat AlpTBScol[] = {0.498f, 0.258f, 0.094f, 1.0f}; // European Beech (ID 13) {0.498f, 0.208f, 0.094f, 1.0f};
GLfloat AlpTBEcol[] = {0.376f, 0.443f, 0.302f, 1.0f}; // Holly Oak (ID 15)
GLfloat AlpTScol[] = {0.573f, 0.600f, 0.467f, 1.0f}; // Medlar
GLfloat AlpBNEcol[] = {0.514f, 0.682f, 0.588f, 1.0f}; // Scotch Pine
GLfloat AlpBNScol[] = {0.698f, 0.718f, 0.447f, 1.0f}; // Larch
GLfloat AlpBBScol[] = {0.573f, 0.600f, 0.467f, 1.0f}; // Silver Birch
GLfloat AlpBScol[] = {0.608f, 0.933f, 0.780f, 1.0f}; // Dogwood Shrub
// GLfloat AlpBScol[] = {0.778f, 0.624f, 0.133f, 1.0f}; // Dogwood Shrub 155 238 199
// Savannah Biome PFT colours
GLfloat SavPBEcol[] = {0.608f, 0.684f, 0.133f, 1.0f}; // Tamarind
GLfloat SavPBRcol[] = {0.473f, 0.500f, 0.427f, 1.0f}; // Acacia
GLfloat SavPBEScol[] = {0.164f, 0.164f, 0.09f, 1.0f}; // African Boxwood
GLfloat SavPBRScol[] = {0.476f, 0.543f, 0.402f, 1.0f}; // Arrow Poisin
GLfloat SavAEcol[] = {0.598f, 0.358f, 0.194f, 1.0f}; // Tree Aloe
/// PlantGrid
void PlantGrid::initSpeciesTable()
{
speciesTable.clear();
#ifdef MEDBIOME
std::vector<SubSpecies> submap;
SubSpecies sub;
// MNE
sub.name = "AtlasCedar"; sub.chance = 200;
submap.push_back(sub);
sub.name = "LebanonCedar"; sub.chance = 200;
submap.push_back(sub);
sub.name = "SeaPine"; sub.chance = 300;
submap.push_back(sub);
sub.name = "StonePine"; sub.chance = 300;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// TBS
sub.name = "EuropeanBeech"; sub.chance = 400;
submap.push_back(sub);
sub.name = "Chestnut"; sub.chance = 400;
submap.push_back(sub);
sub.name = "CutleafBeech"; sub.chance = 200;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// IBS
sub.name = "GreyAlder"; sub.chance = 1000;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// TBE
sub.name = "HolmOak"; sub.chance = 300;
submap.push_back(sub);
sub.name = "CorkOak"; sub.chance = 500;
submap.push_back(sub);
sub.name = "EnglishYew"; sub.chance = 200;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// MSEB
sub.name = "Lentisk"; sub.chance = 500;
submap.push_back(sub);
sub.name = "Myrtle"; sub.chance = 500;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// MSEN
sub.name = "Juniper"; sub.chance = 400;
submap.push_back(sub);
sub.name = "Broom"; sub.chance = 200;
submap.push_back(sub);
sub.name = "Tamarisk"; sub.chance = 400;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// **
// ITBS
/*
sub.name = "NONE"; sub.chance = 1000;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
*/
numSubSpecies = 16;
/*
speciesTable.push_back("StonePine_S");
speciesTable.push_back("StonePine_M");
speciesTable.push_back("StonePine_L");
speciesTable.push_back("EuropeanBeech_S");
speciesTable.push_back("EuropeanBeech_M");
speciesTable.push_back("EuropeanBeech_L");
speciesTable.push_back("GreyAlder_S");
speciesTable.push_back("GreyAlder_M");
speciesTable.push_back("GreyAlder_L");
speciesTable.push_back("CorkOak_S");
speciesTable.push_back("CorkOak_M");
speciesTable.push_back("CorkOak_L");
speciesTable.push_back("Lentisk_S");
speciesTable.push_back("Lentisk_M");
speciesTable.push_back("Lentisk_L");
speciesTable.push_back("SpanishBroom_S");
speciesTable.push_back("SpanishBroom_M");
speciesTable.push_back("SpanishBroom_L");
*/
#endif
#ifdef ALPINEBIOME
std::vector<SubSpecies> submap;
SubSpecies sub;
// TNE
sub.name = "AustrianPine"; sub.chance = 800;
submap.push_back(sub);
sub.name = "StonePine"; sub.chance = 200;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// TBS
sub.name = "EuropeanBeech"; sub.chance = 600;
submap.push_back(sub);
sub.name = "Chestnut"; sub.chance = 200;
submap.push_back(sub);
sub.name = "CutleafBeech"; sub.chance = 200;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// NONE - needs to be skipped
sub.name = "None"; sub.chance = 1000;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// TBE
sub.name = "HolmOak"; sub.chance = 400;
submap.push_back(sub);
sub.name = "CorkOak"; sub.chance = 200;
submap.push_back(sub);
sub.name = "EnglishYew"; sub.chance = 400;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// TS
sub.name = "SavinJuniper"; sub.chance = 400;
submap.push_back(sub);
sub.name = "Medlar"; sub.chance = 600;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// BNE
sub.name = "ScotchPine"; sub.chance = 600;
submap.push_back(sub);
sub.name = "NorwaySpruce"; sub.chance = 400;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// BNS
sub.name = "Larch"; sub.chance = 1000;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// BBS
sub.name = "Ash"; sub.chance = 600;
submap.push_back(sub);
sub.name = "Birch"; sub.chance = 400;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// BS
sub.name = "Dogwood"; sub.chance = 400;
submap.push_back(sub);
sub.name = "Hazel"; sub.chance = 300;
submap.push_back(sub);
sub.name = "Hawthorn"; sub.chance = 300;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
numSubSpecies = 18;
#endif
#ifdef SAVANNAHBIOME
std::vector<SubSpecies> submap;
SubSpecies sub;
// PBE
sub.name = "AfricanMahogany"; sub.chance = 300;
submap.push_back(sub);
sub.name = "WildPeach"; sub.chance = 300;
submap.push_back(sub);
sub.name = "Tamarind"; sub.chance = 400;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// PBR
sub.name = "Acacia"; sub.chance = 600;
submap.push_back(sub);
sub.name = "Baobob"; sub.chance = 100;
submap.push_back(sub);
sub.name = "SandpiperFig"; sub.chance = 300;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// PBES
sub.name = "Carissa"; sub.chance = 400;
submap.push_back(sub);
sub.name = "WildPear"; sub.chance = 200;
submap.push_back(sub);
sub.name = "AfricanBoxwood"; sub.chance = 400;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// PBRS
sub.name = "ArrowPoisin"; sub.chance = 1000;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
// AE
sub.name = "TreeAloe"; sub.chance = 500;
submap.push_back(sub);
sub.name = "DragonTree"; sub.chance = 200;
submap.push_back(sub);
sub.name = "BottleTree"; sub.chance = 300;
submap.push_back(sub);
speciesTable.push_back(submap);
submap.clear();
numSubSpecies = 13;
#endif
}
void PlantGrid::delGrid()
{
int i, j;
// clear out elements of the vector hierarchy
for(i = 0; i < (int) pgrid.size(); i++)
for(j = 0; j < (int) pgrid[i].pop.size(); j++)
pgrid[i].pop[j].clear();
for(i = 0; i < (int) pgrid.size(); i++)
{
pgrid[i].pop.clear();
// sgrid[i].clear();
}
pgrid.clear();
// sgrid.clear();
}
void PlantGrid::initGrid()
{
int i, j, s;
delGrid();
// setup empty elements of the vector hierarchy according to the grid dimensions
for(i = 0; i < gx; i++)
for(j = 0; j < gy; j++)
{
PlantPopulation ppop;
// std::vector<AnalysisPoint> apnt;
for(s = 0; s < maxSpecies; s++)
{
std::vector<Plant> plnts;
ppop.pop.push_back(plnts);
}
pgrid.push_back(ppop);
// sgrid.push_back(apnt);
}
}
bool PlantGrid::isEmpty()
{
bool empty = true;
int i, j, s, pos = 0;
// setup empty elements of the vector hierarchy according to the grid dimensions
for(i = 0; i < gx; i++)
for(j = 0; j < gy; j++)
{
for(s = 0; s < maxSpecies; s++)
{
if(!pgrid[pos].pop[s].empty())
empty = false;
}
pos++;
}
return empty;
}
void PlantGrid::cellLocate(Terrain * ter, int mx, int my, int &cx, int &cy)
{
int tx, ty;
ter->getGridDim(tx, ty);
// find grid bin for plant
cx = (int) (((float) mx / (float) tx) * (float) gx);
cy = (int) (((float) my / (float) ty) * (float) gy);
if(cx >= gx)
cx = gx-1;
if(cy >= gy)
cy = gy-1;
}
void PlantGrid::clearCell(int x, int y)
{
int f = flatten(x, y);
for(int s = 0; s < (int) pgrid[f].pop.size(); s++)
{
pgrid[f].pop[s].clear();
}
}
void PlantGrid::placePlant(Terrain * ter, int species, Plant plant)
{
int x, y, cx, cy;
// find plant location on map
ter->toGrid(plant.pos, x, y);
cellLocate(ter, x, y, cx, cy);
// cerr << "loc in " << cx << ", " << cy << " species " << species << endl;
/*
std::cout << "Adding xy tree " << plant.pos.z << ", " << plant.pos.x << " ";
std::cout << "with species " << species << ", at flat grid loc " << flatten(cx, cy) << " ";
std::cout << " at index " << pgrid[flatten(cx, cy)].pop[species].size() << std::endl;
*/
// add plant to relevant population
pgrid[flatten(cx, cy)].pop[species].push_back(plant);
}
void PlantGrid::placePlantExactly(Terrain * ter, int species, Plant plant, int x, int y)
{
pgrid[flatten(x, y)].pop[species].push_back(plant);
}
void PlantGrid::clearRegion(Terrain * ter, Region region)
{
int x, y, sx, sy, ex, ey;
getRegionIndices(ter, region, sx, sy, ex, ey);
for(x = sx; x <= ex; x++)
for(y = sy; y <= ey; y++)
clearCell(x, y); // clear a specific cell in the grid
}
void PlantGrid::clearAllPlants(Terrain *ter)
{
int gw, gh;
ter->getGridDim(gw, gh);
Region wholeRegion(0, 0, gw - 1, gh - 1);
clearRegion(ter, wholeRegion);
}
void PlantGrid::pickPlants(Terrain * ter, TypeMap * clusters, int niche, PlantGrid & outgrid)
{
int x, y, s, p, mx, my, sx, sy, ex, ey, f;
Plant plnt;
Region region = clusters->getRegion();
// map region to cells in the grid
getRegionIndices(ter, region, sx, sy, ex, ey);
// cerr << "region = " << region.x0 << ", " << region.y0 << " -> " << region.x1 << ", " << region.y1 << endl;
// cerr << "s = " << sx << ", " << sy << " -> " << ex << ", " << ey << endl;
for(x = sx; x <= ex; x++)
for(y = sy; y <= ey; y++)
{
f = flatten(x, y);
for(s = 0; s < (int) pgrid[f].pop.size(); s++)
for(p = 0; p < (int) pgrid[f].pop[s].size(); p++)
{
plnt = pgrid[f].pop[s][p];
ter->toGrid(plnt.pos, mx, my); // map plant terrain location to cluster map
if((* clusters->getMap())[my][mx] == niche) // niche value on terrain matches the current plant distribution
outgrid.placePlantExactly(ter, s, plnt, x, y);
}
}
}
void PlantGrid::pickAllPlants(Terrain * ter, float offx, float offy, float scf, PlantGrid & outgrid)
{
int x, y, s, p, f;
Plant plnt;
int cnt = 0;
for(x = 0; x < gx; x++)
for(y = 0; y < gy; y++)
{
f = flatten(x, y);
for(s = 0; s < (int) pgrid[f].pop.size(); s++)
for(p = 0; p < (int) pgrid[f].pop[s].size(); p++)
{
plnt = pgrid[f].pop[s][p];
plnt.pos.x *= scf; plnt.pos.z *= scf;
plnt.height *= scf; plnt.canopy *= scf;
plnt.pos.x += offy; plnt.pos.z += offx; // allows more natural layout
outgrid.placePlant(ter, s, plnt);
cnt++;
}
}
cerr << "Picked " << cnt << " plants" << endl;
}
void PlantGrid::vectoriseByPFT(int pft, std::vector<Plant> &pftPlnts)
{
int x, y, p, s, f;
Plant plnt;
s = (int) pft;
pftPlnts.clear();
for(x = 0; x < gx; x++)
for(y = 0; y < gy; y++)
{
f = flatten(x, y);
if(s < 0 || s > (int) pgrid[f].pop.size())
cerr << "PlantGrid::vectoriseBySpecies: mismatch between requested species and available species" << endl;
for(p = 0; p < (int) pgrid[f].pop[s].size(); p++)
{
plnt = pgrid[f].pop[s][p];
pftPlnts.push_back(plnt);
}
}
}
/*
void PlantGrid::burnGrass(GrassSim * grass, Terrain * ter, float scale)
{
int x, y, s, p, f;
Plant plnt;
float invscf, tx, ty;
ter->getTerrainDim(tx, ty);
invscf = scale / tx;
int nburned = 0;
for(x = 0; x < gx; x++)
for(y = 0; y < gy; y++)
{
f = flatten(x, y);
for(s = 0; s < (int) pgrid[f].pop.size(); s++)
for(p = 0; p < (int) pgrid[f].pop[s].size(); p++)
{
// get plant
plnt = pgrid[f].pop[s][p];
// apply radial burn of grass heights
// XXX: here, x and z were swapped, i.e. the call was previously grass->burnInPlant(plnt.pos.x*invscf, plnt.pos.z*invscf, 0.5f*plnt.canopy*invscf);
// this is because in the grass sim, xy locations of trees were swapped
grass->burnInPlant(plnt.pos.z*invscf, plnt.pos.x*invscf, 0.5f*plnt.canopy*invscf);
nburned++;
}
}
std::cout << "Number of plants burned: " << nburned << std::endl;
}
*/
void PlantGrid::reportNumPlants()
{
int i, j, s, plntcnt, speccnt;
cerr << "grid dimensions = " << gx << " X " << gy << endl;
for(i = 0; i < gx; i++)
for(j = 0; j < gy; j++)
{
plntcnt = 0;
for(s = 0; s < maxSpecies; s++)
{
speccnt = (int) pgrid[flatten(i,j)].pop[s].size();
plntcnt += speccnt;
}
cerr << "count " << i << ", " << j << " = " << plntcnt << endl;
}
}
void PlantGrid::setPopulation(int x, int y, PlantPopulation & pop)
{
pgrid[flatten(x, y)] = pop;
}
PlantPopulation * PlantGrid::getPopulation(int x, int y)
{
return & pgrid[flatten(x, y)];
}
/*
std::vector<AnalysisPoint> * PlantGrid::getSynthPoints(int x, int y)
{
return &sgrid[flatten(x, y)];
}*/
void PlantGrid::getRegionIndices(Terrain * ter, Region region, int &sx, int &sy, int &ex, int &ey)
{
cellLocate(ter, region.x0, region.y0, sx, sy);
cellLocate(ter, region.x1, region.y1, ex, ey);
// cerr << "map = " << region.x0 << ", " << region.y0 << " -> " << region.x1 << ", " << region.y1 << endl;
// cerr << "grid = " << sx << ", " << sy << " -> " << ex << ", " << ey << endl;
}
bool PlantGrid::readPDB(string filename, Terrain * ter, float &maxtree)
{
ifstream infile;
int numSpecies;
float rndoff;
int currSpecies;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> numSpecies;
for(int i = 0; i < numSpecies; i++)
{
int specName, numPlants;
float canopyRatio, hghtMin, hghtMax;
infile >> specName;
// This should actually be a string but HL provides a number that depends on the plant database
// hardcoded as first species in mediterranean list at 12
currSpecies = specName - specOffset;
infile >> hghtMin >> hghtMax >> canopyRatio;
// cerr << "currSpecies = " << currSpecies << " hmin = " << hghtMin << " hmax = " << hghtMax << " cRatio = " << canopyRatio << endl;
if(hghtMax > maxtree)
maxtree = hghtMax;
infile >> numPlants;
for(int j = 0; j < numPlants; j++)
{
Plant p;
float x, y, z, h, r;
// terrain position and plant height
infile >> x >> y >> z >> h >> r;
// convert units to meters and drape onto terrain
p.height = h;
// supplied canopy ratio is actually radius to height (not diameter to height)
p.canopy = r * 2.0f;
rndoff = (float)(rand() % 100) / 100.0f * 0.6f;
p.col = glm::vec4(-0.3f+rndoff, -0.3f+rndoff, -0.3f+rndoff, 1.0f); // randomly vary lightness of plant
if(ter->drapePnt(vpPoint(x, z, y), p.pos)) // project plant onto the terrain
{
placePlant(ter, currSpecies, p);
// cerr << "P" << j << ": " << p.pos.x << " " << p.pos.y << " " << p.pos.z << endl;
// cerr << "h = " << p.height << " c = " << p.canopy << endl;
}
}
}
infile.close();
}
else
{
cerr << "Error Mesh::readPDB: unable to open " << filename << endl;
return false;
}
return true;
}
bool PlantGrid::writePDB(string filename)
{
ofstream outfile;
int writtenPlants = 0, numSeedlings = 0;
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
outfile << numSubSpecies*3 << endl;
for(int s = 0; s < maxSpecies; s++)
{
int numPlants;
float canopyRatio, hghtMin, hghtMax;
std::vector<Plant> lpop;
lpop.clear();
hghtMin = 1000000.0f;
hghtMax = 0.0f;
canopyRatio = 0.0f;
// collect all species in this category
for(int i = 0; i < gx; i++)
for(int j = 0; j < gy; j++)
{
for(int p = 0; p < (int) pgrid[flatten(i,j)].pop[s].size(); p++)
{
Plant plnt = pgrid[flatten(i,j)].pop[s][p];
if(plnt.height < hghtMin)
hghtMin = plnt.height;
if(plnt.height > hghtMax)
hghtMax = plnt.height;
canopyRatio += (plnt.canopy / plnt.height) * 0.5f ;
// average canopy to height ratio?
lpop.push_back(plnt);
}
}
// convert height range in meters to cm
numPlants = (int) lpop.size();
canopyRatio /= (float) numPlants;
// now assign to subspecies
int numSub = (int) speciesTable[s/3].size();
cerr << "numSub = " << numSub << endl;
for(int b = 0; b < numSub; b++)
{
std::vector<Plant> tpop; tpop.clear();
std::vector<Plant> spop; spop.clear();
if(b != numSub-1)
{
for(auto p: lpop)
{
if(rand()%1000 < speciesTable[s/3][b].chance)
tpop.push_back(p);
else
spop.push_back(p);
}
}
else
{
tpop = lpop;
}
// count only those plants over a height of 1
numPlants = 0;
for(int k = 0; k < (int) tpop.size(); k++)
{
Plant plnt = tpop[k];
if(plnt.height > 0.01f)
numPlants++;
else
numSeedlings++;
}
std::string postfix;
if(s%3 == 0)
postfix = "_S";
else if(s%3 == 1)
postfix = "_M";
else
postfix = "_L";
outfile << speciesTable[s/3][b].name + postfix << endl;
if(numPlants > 0)
outfile << hghtMin << " " << hghtMax << " " << canopyRatio << endl;
else
outfile << 0 << " " << 0 << " " << 1.0f << endl;
outfile << numPlants << endl;
for(int k = 0; k < (int) tpop.size(); k++)
{
Plant plnt = tpop[k];
// terrain position and plant height
float x = plnt.pos.x;
float y = plnt.pos.z;
float z = plnt.pos.y;
float h = plnt.height;
float r = 1.0f;
if(h > 0.01f)
outfile << x << " " << y << " " << z << " " << h << " " << r << endl;
}
writtenPlants += numPlants;
lpop.clear();
lpop = spop;
}
}
cerr << "num seedlings = " << numSeedlings << " vs. full plants = " << writtenPlants << endl;
outfile.close();
}
else
{
cerr << "Error Mesh::writePDB: unable to open " << filename << endl;
return false;
}
cerr << "num written plants = " << writtenPlants << endl;
return true;
}
/// PlantShape
void ShapeGrid::genSpherePlant(float trunkheight, float trunkradius, Shape &shape)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkheight;
// trunk - cylinder
idt = glm::mat4(1.0f);
tfm = glm::rotate(idt, glm::radians(-90.0f), rotx);
// extra 0.1 to trunk is to ensure that trunk joins tree properly
shape.genCappedCylinder(trunkradius, trunkradius, trunkheight+0.1, 3, 1, tfm, false);
// canopy - sphere
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, trunkheight+canopyheight/2.0f, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::scale(tfm, glm::vec3(1.0, canopyheight, 1.0f)); // make sure tree fills 1.0f on a side bounding box
tfm = glm::rotate(tfm, glm::radians(-90.0f), rotx);
#ifdef HIGHRES
shape.genSphere(0.5f, 20, 20, tfm);
#endif
#ifdef LOWRES
shape.genSphere(0.5f, 6, 6, tfm);
#endif
}
void ShapeGrid::genBoxPlant(float trunkheight, float trunkradius, float taper, float scale, Shape &shape)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkheight;
// trunk - cylinder
idt = glm::mat4(1.0f);
tfm = glm::rotate(idt, glm::radians(-90.0f), rotx);
// extra 0.1 to trunk is to ensure that trunk joins tree properly
shape.genCappedCylinder(trunkradius, trunkradius, trunkheight+0.1, 3, 1, tfm, false);
// canopy - tapered box
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, trunkheight, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(-90.0f), rotx);
shape.genPyramid(1.0f*scale, taper*scale, canopyheight*scale, tfm);
}
void ShapeGrid::genConePlant(float trunkheight, float trunkradius, Shape &shape)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkheight;
// trunk - cylinder
idt = glm::mat4(1.0f);
tfm = glm::rotate(idt, glm::radians(-90.0f), rotx);
// extra 0.1 to trunk is to ensure that trunk joins tree properly
shape.genCappedCylinder(trunkradius, trunkradius, trunkheight+0.1f, 3, 1, tfm, false);
// canopy - cone
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, trunkheight, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(-90.0f), rotx);
#ifdef HIGHRES
shape.genCappedCone(0.5f, canopyheight, 20, 1, tfm, false);
#endif
#ifdef LOWRES
shape.genCappedCone(0.5f, canopyheight, 6, 1, tfm, false);
#endif
}
void ShapeGrid::genInvConePlant(float trunkheight, float trunkradius, Shape &shape)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkheight;
// trunk - cylinder
idt = glm::mat4(1.0f);
tfm = glm::rotate(idt, glm::radians(-90.0f), rotx);
// extra 0.1 to trunk is to ensure that trunk joins tree properly
shape.genCappedCylinder(trunkradius, trunkradius, trunkheight+0.1f, 3, 1, tfm, false);
// canopy - cone
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, 1.0f, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(-270.0f), rotx);
//tfm = glm::translate(tfm, glm::vec3(0.0f, 0.0f, -canopyheight));
#ifdef HIGHRES
shape.genCappedCone(0.5f, canopyheight, 20, 1, tfm, false);
#endif
#ifdef LOWRES
shape.genCappedCone(0.5f, canopyheight, 6, 1, tfm, false);
#endif
}
void ShapeGrid::genUmbrellaPlant(float trunkheight, float trunkradius, Shape &shape)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkheight;
// trunk - cylinder
idt = glm::mat4(1.0f);
tfm = glm::rotate(idt, glm::radians(-90.0f), rotx);
// extra 0.1 to trunk is to ensure that trunk joins tree properly
shape.genCappedCylinder(trunkradius, trunkradius, trunkheight+0.1f, 3, 1, tfm, false);
// canopy - cone
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, 1.0f, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(90.0f), rotx);
#ifdef HIGHRES
shape.genCappedCone(0.5f, canopyheight, 20, 1, tfm, false);
#endif
#ifdef LOWRES
shape.genCappedCone(0.5f, canopyheight, 6, 1, tfm, false);
#endif
}
void ShapeGrid::delGrid()
{
int i, j;
// clear out elements of the vector hierarchy
for(i = 0; i < (int) shapes.size(); i++)
for(j = 0; j < (int) shapes[i].size(); j++)
shapes[i][j].clear();
for(i = 0; i < (int) shapes.size(); i++)
shapes[i].clear();
shapes.clear();
}
void ShapeGrid::initGrid()
{
int i, j, s;
// setup empty elements of the vector hierarchy according to the grid dimensions
for(i = 0; i < gx; i++)
for(j = 0; j < gy; j++)
{
std::vector<Shape> shapevec;
for(s = 0; s < maxSpecies / 3; s++)
{
Shape shape;
shapevec.push_back(shape);
}
shapes.push_back(shapevec);
}
if (SYMBOLIC_RENDERER)
genPlants();
}
void ShapeGrid::genPlants()
{
float trunkheight, trunkradius;
int x, y, s, f;
f = flatten(x, y);
for(s = 0; s < biome->numPFTypes(); s++)
{
Shape currshape;
PFType * pft = biome->getPFType(s);
currshape.setColour(pft->basecol);
trunkheight = pft->draw_hght; trunkradius = pft->draw_radius;
//genSpherePlant(trunkheight, trunkradius, currshape); // XXX: just for debugging. Remove later and uncomment below switch statement
switch(pft->shapetype)
{
case TreeShapeType::SPHR:
genSpherePlant(trunkheight, trunkradius, currshape);
break;
case TreeShapeType::BOX:
genBoxPlant(trunkheight, trunkradius, pft->draw_box1, pft->draw_box2, currshape);
break;
case TreeShapeType::CONE:
genConePlant(trunkheight, trunkradius, currshape);
break;
case TreeShapeType::INVCONE:
genInvConePlant(trunkheight, trunkradius, currshape);
break;
default:
break;
}
shapes[0][s] = currshape;
}
}
/*
void ShapeGrid::genPlants()
{
float trunkheight, trunkradius;
int x, y, s, f;
for(x = 0; x < gx; x++)
for(y = 0; y < gy; y++)
{
f = flatten(x, y);
for(s = 0; s < biome->numPFTypes(); s++)
{
Shape currshape;
PFType * pft = biome->getPFType(s);
currshape.setColour(pft->basecol);
trunkheight = pft->draw_hght; trunkradius = pft->draw_radius;
switch(pft->shapetype)
{
case TreeShapeType::SPHR:
genSpherePlant(trunkheight, trunkradius, currshape);
break;
case TreeShapeType::BOX:
genBoxPlant(trunkheight, trunkradius, pft->draw_box1, pft->draw_box2, currshape);
break;
case TreeShapeType::CONE:
genConePlant(trunkheight, trunkradius, currshape);
break;
default:
break;
}
shapes[f][s] = currshape;
}
}
#ifdef ALPINEBIOME
switch((FunctionalPlantType) s)
{
case FunctionalPlantType::ALPTNE: //< Alpine Temperate Needle-Leaved Evergreen
// sphere, med green, short trunk, h:w = 0.25
currshape.setColour(AlpTNEcol);
trunkheight = 0.1f; trunkradius = 0.07f;
genSpherePlant(trunkheight, trunkradius, currshape);
break;
case FunctionalPlantType::ALPTBS: //< Alpine Temperate Broad-leaved Summergreen
// tapered box, autum red, short trunk
currshape.setColour(AlpTBScol);
trunkheight = 0.1f; trunkradius = 0.1f;
genBoxPlant(trunkheight, trunkradius, 0.75f, 0.8f, currshape);
break;
case FunctionalPlantType::NONE:
// SKIP
break;
case FunctionalPlantType::ALPTBE: //< Alpine Temperate Broad-leaved Evergreen
// sphere, medium green, medium trunk
currshape.setColour(AlpTBEcol);
trunkheight = 0.1f; trunkradius = 0.07f;
genSpherePlant(trunkheight, trunkradius, currshape);
break;
case FunctionalPlantType::ALPTS: //< Alpine Temperate Shrub
// squat cone, dark green, medium trunk
currshape.setColour(AlpTScol);
trunkheight = 0.15f; trunkradius = 0.1f;
genConePlant(trunkheight, trunkradius, currshape);
break;
case FunctionalPlantType::ALPBNE: //< Alpine Boreal Needle-leaved Evergreen
// elongated sphere, dark green
currshape.setColour(AlpBNEcol);
trunkheight = 0.1f; trunkradius = 0.07f;
genSpherePlant(trunkheight, trunkradius, currshape);
break;
case FunctionalPlantType::ALPBNS: //< Alpine Boreal Need-leaved Summergreen
// box, yellowy green
currshape.setColour(AlpBNScol);
trunkheight = 0.1f; trunkradius = 0.1f;
genBoxPlant(trunkheight, trunkradius, 0.75f, 1.0f, currshape);
break;
case FunctionalPlantType::ALPBBS: //< Alpine Boreal Broad-leaved Summergreen
// sphere, silvery green
currshape.setColour(AlpBBScol);
trunkheight = 0.1f; trunkradius = 0.1f;
genSpherePlant(trunkheight, trunkradius, currshape);
break;
case FunctionalPlantType::ALPBS: //< Alpine Boreal Shrub
// squat cone, light greeny yellow, short trunk
currshape.setColour(AlpBScol);
trunkheight = 0.05f; trunkradius = 0.07f;
genConePlant(trunkheight, trunkradius, currshape);
break;
default:
break;
}
#endif
}
*/
void ShapeGrid::bindPlantsSimplified(Terrain *ter, PlantGrid *esys)
{
std::default_random_engine generator_canopy;
std::default_random_engine generator_under;
std::uniform_real_distribution<GLfloat> rand_unif;
int x, y, s, p, sx, sy, ex, ey, f;
PlantPopulation * plnts;
int bndplants = 0, culledplants = 0;
int gwidth, gheight;
ter->getGridDim(gwidth, gheight);
Region wholeRegion = Region(0, 0, gwidth - 1, gheight - 1);
esys->getRegionIndices(ter, wholeRegion, sx, sy, ex, ey);
std::vector<std::vector<glm::mat4> > xforms; // transformation to be applied to each instance
std::vector<std::vector<glm::vec4> > colvars; // colour variation to be applied to each instance
for(x = sx; x <= ex; x++)
for(y = sy; y <= ey; y++)
{
plnts = esys->getPopulation(x, y);
// cerr << "cat 0, species 0, num = " << (int) plnts->pop[0].size() << endl;
for(s = 0; s < (int) plnts->pop.size(); s+=3) // iterate over plant types
{
std::vector<glm::mat4> xform; // transformation to be applied to each instance
std::vector<glm::vec4> colvar; // colour variation to be applied to each instance
// cerr << "plants for " << s/3 << " visible" << endl;
for(int a = 0; a < 3; a++)
{
// cerr << "num plants = " << (int) plnts->pop[s+a].size() << endl;
for(p = 0; p < (int) plnts->pop[s+a].size(); p++) // iterate over plant specimens
{
if(plnts->pop[s+a][p].height > 0.01f) // only display reasonably sized plants
{
// setup transformation for individual plant, including scaling and translation
glm::mat4 idt, tfm;
glm::vec3 trs, sc, rotate_axis = glm::vec3(0.0f, 1.0f, 0.0f);
vpPoint loc = plnts->pop[s+a][p].pos;
GLfloat rotate_rad;
if (plnts->pop[s+a][p].iscanopy) // we use a different generator depending on whether we have a canopy or undergrowth plant - keeps rotations the same whether we render undergrowth plants or not
{
rotate_rad = rand_unif(generator_canopy) * glm::pi<GLfloat>() * 2.0f;
}
else
{
rotate_rad = rand_unif(generator_under) * glm::pi<GLfloat>() * 2.0f;
}
idt = glm::mat4(1.0f);
trs = glm::vec3(loc.x, loc.y, loc.z);
tfm = glm::translate(idt, trs);
if (SYMBOLIC_RENDERER)
sc = glm::vec3(plnts->pop[s+a][p].canopy, plnts->pop[s+a][p].height, plnts->pop[s+a][p].canopy); // XXX: use this for symbolic renderer
else
sc = glm::vec3(plnts->pop[s+a][p].height, plnts->pop[s+a][p].height, plnts->pop[s+a][p].height); // XXX: use this for actual tree models
// cerr << loc.x << ", " << loc.y << ", " << loc.z << ", " << plnts->pop[s][p].canopy << ", " << plnts->pop[s][p].height << ", " << plnts->pop[s][s].col[0] << endl;
tfm = glm::scale(tfm, sc);
tfm = glm::rotate(tfm, rotate_rad, rotate_axis);
xform.push_back(tfm);
colvar.push_back(plnts->pop[s+a][p].col); // colour variation
// cerr << "col = " << plnts->pop[s+a][p].col.r << " " << plnts->pop[s+a][p].col.g << " " << plnts->pop[s+a][p].col.b << " " << plnts->pop[s+a][p].col.a << endl;
bndplants++;
}
else
{
culledplants++;
}
}
// cerr << "cat " << s+a << " has " << (int) plnts->pop[s+a].size() << " plants" << endl;
}
if (xforms.size() < s / 3 + 1)
{
xforms.resize(s / 3 + 1);
}
if (colvars.size() < s / 3 + 1)
{
colvars.resize(s / 3 + 1);
}
xforms[s / 3].insert(xforms[s / 3].end(), xform.begin(), xform.end());
colvars[s / 3].insert(colvars[s / 3].end(), colvar.begin(), colvar.end());
f = flatten(x, y);
shapes[f][s / 3].removeAllInstances();
/*
// now bind buffers for the shape associated with this species
f = flatten(x, y);
// cerr << "bind to f = " << f << " s = " << s << " xform size = " << (int) xform.size() << endl;
if((int) xform.size() > 0)
{
// cerr << "xform size = " << (int) xform.size() << " colvar size = " << (int) colvar.size() << endl;
//std::cout << "Binding instance for index: " << s/3 << std::endl;
//shapes[f][s/3].bindInstances(nullptr, &xform, &colvar);
// {
// cerr << "BINDING FAILED" << endl;
// }
}
else
{
//shapes[f][s/3].removeAllInstances();
}
*/
}
}
for (int i = 0; i < xforms.size(); i++)
{
shapes[0][i].removeAllInstances();
shapes[0][i].bindInstances(nullptr, &xforms[i], &colvars[i]);
}
cerr << "num bound plants = " << bndplants << endl;
cerr << "num culled plants = " << culledplants << endl;
}
void ShapeGrid::bindPlants(View * view, Terrain * ter, bool * plantvis, PlantGrid * esys, Region region)
{
int x, y, s, p, sx, sy, ex, ey, f;
PlantPopulation * plnts;
int bndplants = 0, culledplants = 0;
esys->getRegionIndices(ter, region, sx, sy, ex, ey);
cerr << "bind: " << sx << ", " << sy << " -> " << ex << ", " << ey << endl;
for(x = sx; x <= ex; x++)
for(y = sy; y <= ey; y++)
{
plnts = esys->getPopulation(x, y);
// cerr << "cat 0, species 0, num = " << (int) plnts->pop[0].size() << endl;
for(s = 0; s < (int) plnts->pop.size(); s+=3) // iterate over plant types
{
std::vector<glm::mat4> xform; // transformation to be applied to each instance
std::vector<glm::vec4> colvar; // colour variation to be applied to each instance
xform.clear();
colvar.clear();
if(plantvis[s/3])
{
// cerr << "plants for " << s/3 << " visible" << endl;
for(int a = 0; a < 3; a++)
{
// cerr << "num plants = " << (int) plnts->pop[s+a].size() << endl;
for(p = 0; p < (int) plnts->pop[s+a].size(); p++) // iterate over plant specimens
{
if(plnts->pop[s+a][p].height > 0.1f) // only display reasonably sized plants
{
// setup transformation for individual plant, including scaling and translation
glm::mat4 idt, tfm;
glm::vec3 trs, sc;
vpPoint loc = plnts->pop[s+a][p].pos;
idt = glm::mat4(1.0f);
trs = glm::vec3(loc.x, loc.y, loc.z);
tfm = glm::translate(idt, trs);
sc = glm::vec3(plnts->pop[s+a][p].canopy, plnts->pop[s+a][p].height, plnts->pop[s+a][p].canopy);
// cerr << loc.x << ", " << loc.y << ", " << loc.z << ", " << plnts->pop[s][p].canopy << ", " << plnts->pop[s][p].height << ", " << plnts->pop[s][s].col[0] << endl;
tfm = glm::scale(tfm, sc);
xform.push_back(tfm);
colvar.push_back(plnts->pop[s+a][p].col); // colour variation
// cerr << "col = " << plnts->pop[s+a][p].col.r << " " << plnts->pop[s+a][p].col.g << " " << plnts->pop[s+a][p].col.b << " " << plnts->pop[s+a][p].col.a << endl;
bndplants++;
}
else
{
culledplants++;
}
}
// cerr << "cat " << s+a << " has " << (int) plnts->pop[s+a].size() << " plants" << endl;
}
}
// now bind buffers for the shape associated with this species
f = flatten(x, y);
// cerr << "bind to f = " << f << " s = " << s << " xform size = " << (int) xform.size() << endl;
if((int) xform.size() > 0)
{
// cerr << "xform size = " << (int) xform.size() << " colvar size = " << (int) colvar.size() << endl;
shapes[f][s/3].bindInstances(view, &xform, &colvar);
// {
// cerr << "BINDING FAILED" << endl;
// }
}
}
}
cerr << "num bound plants = " << bndplants << endl;
cerr << "num culled plants = " << culledplants << endl;
}
void ShapeGrid::drawPlants(std::vector<ShapeDrawData> &drawParams)
{
int x, y, s, f;
ShapeDrawData sdd;
/*
for(x = 0; x < gx; x++)
for(y = 0; y < gy; y++)
{
f = flatten(x, y);
for(s = 0; s < (int) shapes[f].size(); s++) // iterate over plant types
{
sdd = shapes[f][s].getDrawParameters();
sdd.current = false;
drawParams.push_back(sdd);
}
}
*/
for(s = 0; s < (int) shapes[0].size(); s++) // iterate over plant types
{
sdd = shapes[0][s].getDrawParameters();
sdd.current = false;
drawParams.push_back(sdd);
}
}
/// EcoSystem
EcoSystem::EcoSystem()
{
biome = new Biome();
init();
}
EcoSystem::EcoSystem(Biome * ecobiome)
{
biome = ecobiome;
init();
}
EcoSystem::~EcoSystem()
{
esys.delGrid();
eshapes.delGrid();
for(int i = 0; i < (int) niches.size(); i++)
{
niches[i].delGrid();
}
niches.clear();
// if(synthesizer != nullptr)
// delete synthesizer;
}
void EcoSystem::init()
{
esys = PlantGrid(pgdim, pgdim);
eshapes = ShapeGrid(pgdim, pgdim, biome);
// cmap = ConditionsMap();
for(int i = 0; i < maxNiches; i++)
{
PlantGrid pgrid(pgdim, pgdim);
niches.push_back(pgrid);
}
clear();
dirtyPlants = true;
drawPlants = false;
maxtreehght = 0.0f;
srand (time(NULL));
// synthesizer = nullptr;
}
void EcoSystem::clear()
{
esys = PlantGrid(pgdim, pgdim);
eshapes = ShapeGrid(pgdim, pgdim, biome);
for(int i = 0; i < (int) niches.size(); i++)
{
niches[i] = PlantGrid(pgdim, pgdim);
}
}
bool EcoSystem::loadNichePDB(string filename, Terrain * ter, int niche)
{
bool success;
success = niches[niche].readPDB(filename, ter, maxtreehght);
if(success)
{
dirtyPlants = true; drawPlants = true;
cerr << "plants loaded for Niche " << niche << endl;
}
return success;
}
bool EcoSystem::saveNichePDB(string filename, int niche)
{
return niches[niche].writePDB(filename);
}
void EcoSystem::pickPlants(Terrain * ter, TypeMap * clusters)
{
Region reg = clusters->getRegion();
esys.clearRegion(ter, reg);
for(int n = 0; n < (int) niches.size(); n++)
{
niches[n].pickPlants(ter, clusters, n, esys);
}
// esys.reportNumPlants();
dirtyPlants = true;
}
void EcoSystem::placePlant(Terrain *ter, const Plant &plant, int species)
{
esys.placePlant(ter, species, plant);
}
// TODO: consider letting the basic_tree have real-world coordinates, rather than grid coords?
// TODO: check if basic_tree still needs its height converted from feet to meters
void EcoSystem::placePlant(Terrain *ter, const basic_tree &tree, bool canopy)
{
// these colours are just temporary for now
//const GLfloat *colours[] = {MedMNEcol, MedTBScol, MedIBScol, MedITBScol, MedMSEBcol, MedMSENcol};
const GLfloat colours [] [4] = { {1.0f, 0.0f, 0.0f, 1.0f}, {0.0f, 1.0f, 0.0f, 1.0f} };
//float h = ter->getHeight(tree.x, tree.y);
float h = ter->getHeightFromReal(tree.x, tree.y);
//vpPoint pos = ter->toWorld(tree.y, tree.x, h); // h is not affected by this function
vpPoint pos(tree.y, h, tree.x);
//const GLfloat *coldata = colours[(int)tree.species];
const GLfloat *coldata;
if (canopy)
coldata = biome->get_species_colour(tree.species); // XXX: have to make sure that this is the species id, not the index...
else
{
coldata = biome->get_species_colour(tree.species);
}
glm::vec4 colour(coldata[0], coldata[1], coldata[2], coldata[3]);
/*
if (canopy && (fmod(pos.x / 0.9144f, 0.5f) < 1e-4 || fmod(pos.z / 0.9144f, 0.5f) < 1e-4))
{
std::cout << "Middle of cell encountered " << std::endl;
}
if (canopy)
{
std::cout << "Adding canopytree xy: " << pos.x << ", " << pos.z << std::endl;
}
*/
Plant plnt = {pos, tree.height, tree.radius * 2, colour, canopy}; //XXX: not sure if I should multiply radius by 2 here - according to scaling info in the renderer, 'radius' is actually the diameter, as far as I can see (and visual results also imply this)
esys.placePlant(ter, ((int)tree.species) * 3, plnt); // FIXME, XXX: I don't think we should be multiplying by 3 here...
}
void EcoSystem::placeManyPlants(Terrain *ter, const std::vector<basic_tree> &trees, bool canopy)
{
for (auto &tr : trees)
{
placePlant(ter, tr, canopy);
}
}
void EcoSystem::clearAllPlants(Terrain *ter)
{
esys.clearAllPlants(ter);
}
void EcoSystem::pickAllPlants(Terrain * ter)
{
esys.clear();
for(int n = 0; n < (int) niches.size(); n++)
{
niches[n].pickAllPlants(ter, 0.0f, 0.0f, 1.0f, esys);
cerr << "for niche " << n << endl;
}
dirtyPlants = true;
}
void EcoSystem::bindPlantsSimplified(Terrain *ter, std::vector<ShapeDrawData> &drawParams)
{
if(dirtyPlants) // plant positions have been updated since the last bindPlants
{
// t.start();
drawPlants = true;
dirtyPlants = false;
//eshapes.bindPlants(nullptr, ter, plantvis, &esys, clusters->getRegion());
eshapes.bindPlantsSimplified(ter, &esys);
}
if(drawPlants)
eshapes.drawPlants(drawParams);
}
void EcoSystem::bindPlants(View * view, Terrain * ter, TypeMap * clusters, bool * plantvis, std::vector<ShapeDrawData> &drawParams)
{
// Timer t;
// bool timing;
// timing = dirtyPlants;
if(dirtyPlants) // plant positions have been updated since the last bindPlants
{
// t.start();
drawPlants = true;
dirtyPlants = false;
eshapes.bindPlants(view, ter, plantvis, &esys, clusters->getRegion());
}
if(drawPlants)
eshapes.drawPlants(drawParams);
/*
if(timing)
{
t.stop();
cerr << "plant binding takes " << t.peek() << "s" << endl;
}*/
}
| 50,210
|
C++
|
.cpp
| 1,287
| 29.431235
| 260
| 0.529687
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,206
|
convertpaintingdialog.cpp
|
jgain_EcoLearn/EcoSynth/viewer/convertpaintingdialog.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "convertpaintingdialog.h"
#include "ui_convertpaintingdialog.h"
ConvertPaintingDialog::ConvertPaintingDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ConvertPaintingDialog)
{
ui->setupUi(this);
}
void ConvertPaintingDialog::get_values(int &from, int &to)
{
std::string fromstr = ui->comboBoxFrom->currentText().toStdString();
std::string tostr = ui->comboBoxTo->currentText().toStdString();
from = -1, to = -1;
if (fromstr == "Void")
from = 0;
else if (fromstr == "Sparse")
from = 1;
else if (fromstr == "Dense")
from = 2;
if (tostr == "Void")
to = 0;
else if (tostr == "Sparse")
to = 1;
else if (tostr == "Dense")
to = 2;
}
ConvertPaintingDialog::~ConvertPaintingDialog()
{
delete ui;
}
| 1,752
|
C++
|
.cpp
| 49
| 32.204082
| 82
| 0.628538
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,207
|
main.cpp
|
jgain_EcoLearn/EcoSynth/viewer/main.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected]) and K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <GL/glew.h>
#include "glheaders.h"
#include <QApplication>
#include <QGLFormat>
#include <QCoreApplication>
#include <QDesktopWidget>
#include <string>
#include <stdexcept>
#include <utility>
#include <memory>
#include "window.h"
int main(int argc, char *argv[])
{
std::cout << "Shader base directory: " << SHADER_BASEDIR << std::endl;
Window *window;
try
{
QApplication app(argc, argv);
if (argc == 2 || argc == 4)
{
int scale_size;
try
{
scale_size = std::stoi(argv[1]);
if (scale_size == 0 || scale_size % 256 != 0)
{
// will be caught by the inner catch statement here anyway
throw std::invalid_argument("First argument (scale size) needs to be a nonzero integer divisible by 256");
}
}
catch (std::invalid_argument &e)
{
throw std::invalid_argument("First argument (scale size) needs to be a nonzero integer divisible by 256");
}
window = new Window(scale_size);
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedKingdom));
window->resize(window->sizeHint());
window->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored);
window->getView().setForcedFocus(window->getTerrain().getFocus());
//window->setAttribute(Qt::WA_DeleteOnClose);
int desktopArea = QApplication::desktop()->width() *
QApplication::desktop()->height();
int widgetArea = window->width() * window->height();
if (((float)widgetArea / (float)desktopArea) < 0.75f)
window->show();
else
window->showMaximized();
}
else
{
std::cout << "Usage: viewer <scale size: int> [--config <configuration file name>]" << std::endl;
return 1;
}
if (argc == 4)
{
std::string cfgfilename;
if (strcmp(argv[2], "--config"))
{
throw std::invalid_argument(std::string("unknown switch: ") + std::string(argv[1]));
}
else
{
cfgfilename = argv[3];
window->loadConfig(cfgfilename);
}
//window->loadConfig(); // just testing config load for now, still have to write parser
}
#ifndef PAINTCONTROL
// sunwindow
SunWindow * sunwindow = new SunWindow();
sunwindow->resize(window->sizeHint());
sunwindow->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored);
sunwindow->setOrthoView(window->getGLWidget());
sunwindow->getView().setForcedFocus(window->getTerrain().getFocus());
sunwindow->show();
#endif
#ifndef PAINTCONTROL
window->setSunWindow(sunwindow);
#endif
int status = app.exec();
//cudaDeviceReset();
return status;
}
catch (std::exception &e)
{
std::cerr << "Exception caught in main" << std::endl;
//cudaDeviceReset();
std::cerr << e.what() << std::endl;
return 1;
}
}
| 6,213
|
C++
|
.cpp
| 149
| 35.268456
| 126
| 0.614888
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,208
|
synth.cpp
|
jgain_EcoLearn/EcoSynth/viewer/synth.cpp
|
// synth.h: generate plant distributions interactively. Recoded from Harry Longs original generator.
// author: James Gain
// date: 1 August 2016
#include "synth.h"
#include "eco.h"
#include <radialDistribution/reproducer/file_utils.h>
#include <radialDistribution/reproducer/analysis_point.h>
#include <radialDistribution/reproducer/utils.h>
#include <radialDistribution/reproducer/distribution_factory.h>
#include <math.h>
#include <iostream>
#include <chrono>
#include <QStringList>
#include <thread>
#include <QDebug>
#include <cstdint>
#include <random>
using namespace std;
random_device rd;
/* The state must be seeded so that it is not everywhere zero. */
uint64_t s[2] = { (uint64_t(rd()) << 32) ^ (rd()),
(uint64_t(rd()) << 32) ^ (rd()) };
uint64_t curRand;
uint8_t bit = 63;
uint64_t xorshift128plus(void) {
uint64_t x = s[0];
uint64_t const y = s[1];
s[0] = y;
x ^= x << 23; // a
s[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c
return s[1] + y;
}
/// copy constructor
Distribution::Distribution(Distribution const& other)
{
inputdir = other.inputdir;
analyzeconfig = other.analyzeconfig;
loaded_pair_correlations = other.loaded_pair_correlations;
loaded_category_properties = other.loaded_category_properties;
empty = other.empty;
}
bool Distribution::operator==(Distribution &other)
{
return subsetEqual(other);
}
bool Distribution::equiv(const float &a, const float &b, int precision)
{
return fabs(a - b) < max(a, 1.0f) * pow(0.1,precision);
}
bool Distribution::subsetEqual(Distribution & other, bool subset)
{
// compare headers
if(empty != other.empty) return false;
if(analyzeconfig.r_min != other.analyzeconfig.r_min) return false;
if(analyzeconfig.r_max != other.analyzeconfig.r_max) return false;
if(analyzeconfig.r_diff != other.analyzeconfig.r_diff) return false;
if(analyzeconfig.analysis_window_height != other.analyzeconfig.analysis_window_height) return false;
if(analyzeconfig.analysis_window_width != other.analyzeconfig.analysis_window_width) return false;
if(subset)
{
if((int) analyzeconfig.priority_sorted_category_ids.size() > (int) other.analyzeconfig.priority_sorted_category_ids.size())
return false;
}
else
{
if((int) analyzeconfig.priority_sorted_category_ids.size() != (int) other.analyzeconfig.priority_sorted_category_ids.size())
return false;
for(int i = 0; i < (int) analyzeconfig.priority_sorted_category_ids.size(); i++)
if(analyzeconfig.priority_sorted_category_ids[i] != other.analyzeconfig.priority_sorted_category_ids[i])
return false;
}
// compare categories
if(subset)
{
if((int) getCategories().size() > (int) other.getCategories().size())
return false;
}
else
{
if((int) getCategories().size() != (int) other.getCategories().size())
return false;
}
for(auto it: getCategories())
{
if(other.getCategories().find(it.first) == other.getCategories().end())
return false;
CategoryProperties cat = other.getCategories().find(it.first)->second;
if(it.second.m_header.category_id != cat.m_header.category_id)
return false;
if(it.second.m_header.bin_size != cat.m_header.bin_size)
return false;
if(it.second.m_header.n_points != cat.m_header.n_points)
return false;
// priority not used so ignore
// if(it.second.m_header.priority != cat.m_header.priority)
// return false;
if(it.second.m_header.height_to_radius_multiplier != cat.m_header.height_to_radius_multiplier)
return false;
if(it.second.m_header.height_to_root_size_multiplier != cat.m_header.height_to_root_size_multiplier)
return false;
/*
cerr << "DEPENDENT IDS" << endl;
for(auto in: it.second.m_header.category_dependent_ids)
cerr << in << " ";
cerr << "RADIUS: " << it.second.m_header.radius_properties.min << " " << it.second.m_header.radius_properties.max << " " << it.second.m_header.radius_properties.avg << " " << it.second.m_header.radius_properties.standard_dev << endl;
cerr << "HEIGHT: " << it.second.m_header.height_properties.min << " " << it.second.m_header.height_properties.max << " " << it.second.m_header.height_properties.avg << " " << it.second.m_header.height_properties.standard_dev << endl;
cerr << "ROOT: " << it.second.m_header.root_size_properties.min << " " << it.second.m_header.root_size_properties.max << " " << it.second.m_header.root_size_properties.avg << " " << it.second.m_header.root_size_properties.standard_dev << endl;
*/
}
// compare correlations
if(!correlationsEqual(other, subset))
return false;
return true;
}
bool Distribution::correlationsEqual(Distribution &other, bool subset)
{
if(subset)
{
if((int) loaded_pair_correlations.size() > (int) other.loaded_pair_correlations.size())
return false;
}
else
{
if((int) loaded_pair_correlations.size() != (int) other.loaded_pair_correlations.size())
return false;
}
for(auto it: loaded_pair_correlations)
{
if(other.getCorrelations().find(it.first) == other.getCorrelations().end())
return false;
const RadialDistribution corr = other.getCorrelations().find(it.first)->second;
if(!equiv(it.second.getMinimum(), corr.getMinimum()))
return false;
if(!equiv(it.second.getMaximum(), corr.getMaximum()))
return false;
// if(!equiv(it.second.m_within_radius_distribution, corr.m_within_radius_distribution))
// return false;
if(!equiv(it.second.m_less_than_half_shaded_distribution, corr.m_less_than_half_shaded_distribution))
return false;
if(!equiv(it.second.m_more_than_half_shaded_distribution, corr.m_more_than_half_shaded_distribution))
return false;
if(!equiv(it.second.m_fully_shaded_distribution, corr.m_fully_shaded_distribution))
return false;
if(!equiv(it.second.m_past_rmax_distribution, corr.m_past_rmax_distribution))
return false;
if((int) it.second.m_data.size() != (int) corr.m_data.size())
return false;
for(auto in: it.second.m_data)
{
float a = it.second.m_data.find(in.first)->second;
float b = corr.m_data.find(in.first)->second;
if(!equiv(a, b))
return false;
}
}
return true;
}
void Distribution::summaryDisplay()
{
cerr << "CATEGORIES: ";
for(auto it: analyzeconfig.priority_sorted_category_ids)
cerr << it << " ";
cerr << endl;
for(auto it: loaded_category_properties)
{
cerr << it.first << ": ";
cerr << "NUM PLANTS = " << it.second.m_header.n_points;
cerr << ", HEIGHT = " << it.second.m_header.height_properties.avg << endl;
}
cerr << endl;
}
int Distribution::getNumMajorPlants()
{
int numplnts = 0;
// summaryDisplay();
if(!empty)
{
for(auto it: loaded_category_properties)
{
if(it.second.m_header.height_properties.avg > 1000.0f)
numplnts += it.second.m_header.n_points;
}
}
return numplnts;
}
void Distribution::display()
{
cerr << "EMPTY = " << empty << endl;
cerr << inputdir.toStdString() << endl;
cerr << analyzeconfig.r_min << " " << analyzeconfig.r_max << " " << analyzeconfig.r_diff << endl;
cerr << analyzeconfig.analysis_window_width << " " << analyzeconfig.analysis_window_height << endl;
for(auto it: analyzeconfig.priority_sorted_category_ids)
cerr << it << " ";
cerr << endl;
cerr << "NUM CORRELATIONS = " << (int) loaded_pair_correlations.size() << endl;
for(auto it: loaded_pair_correlations)
{
cerr << "(" << it.first.first << ", " << it.first.second << ") ";
cerr << "min " << it.second.getMinimum() << " max " << it.second.getMaximum() << " ";
cerr << " outrad " << it.second.m_past_rmax_distribution << endl;
cerr << "( " << it.second.m_header.reference_id << ", " << it.second.m_header.destination_id << ") " << it.second.m_header.requires_optimization << endl;
cerr << (int) it.second.m_data.size() << ": ";
for(auto in: it.second.m_data)
cerr << in.second << " ";
cerr << endl;
}
cerr << "NUM CATEGORIES = " << (int) loaded_category_properties.size() << endl;
for(auto it: loaded_category_properties)
{
cerr << it.first << ": " << it.second.m_header.category_id << " " << it.second.m_header.bin_size << " ";
cerr << "n points = " << it.second.m_header.n_points;
cerr << " priority = " << it.second.m_header.priority << " htor = " << it.second.m_header.height_to_radius_multiplier << " " << endl;
cerr << it.second.m_header.height_to_root_size_multiplier << endl;
cerr << "DEPENDENT IDS" << endl;
for(auto in: it.second.m_header.category_dependent_ids)
cerr << in << " ";
cerr << endl;
cerr << "RADIUS: " << it.second.m_header.radius_properties.min << " " << it.second.m_header.radius_properties.max << " " << it.second.m_header.radius_properties.avg << " " << it.second.m_header.radius_properties.standard_dev << endl;
cerr << "HEIGHT: " << it.second.m_header.height_properties.min << " " << it.second.m_header.height_properties.max << " " << it.second.m_header.height_properties.avg << " " << it.second.m_header.height_properties.standard_dev << endl;
cerr << "ROOT: " << it.second.m_header.root_size_properties.min << " " << it.second.m_header.root_size_properties.max << " " << it.second.m_header.root_size_properties.avg << " " << it.second.m_header.root_size_properties.standard_dev << endl;
}
cerr << endl;
}
bool Distribution::write(string writedir)
{
// create directory structure
QString base_directory = QString::fromStdString(writedir);
// Init the base directory
if(!base_directory.endsWith("/"))
base_directory.append("/");
QString m_base_dir = base_directory;
QString m_radial_distribution_dir, m_category_properties_dir, m_csv_dir;
if(!FileUtils::init_directory_structure(m_base_dir, m_radial_distribution_dir, m_category_properties_dir, m_csv_dir))
{
std::cerr << "An error occured whilst creating the directory structure..." << std::endl;
return false;
}
// analysis configuration file
QString generic_filename(FileUtils::_CONFIGURATION_FILENAME);
// Write bin file
{
QString output_filename(m_base_dir);
output_filename.append(generic_filename);
analyzeconfig.write(output_filename.toStdString());
}
// Write CSV file
{
QString output_filename(m_csv_dir);
output_filename.append(generic_filename).append(".csv");
analyzeconfig.writeToCSV(output_filename.toStdString());
}
// category properties
QString m_output_bin_dir = m_category_properties_dir;
QString m_output_hr_dir = m_csv_dir;
for(auto cprop: loaded_category_properties)
{
CategoryProperties category_properties = cprop.second;
int category_id(category_properties.m_header.category_id);
QString filename("category_");
filename.append(QString::number(category_id));
// category_properties.m_header.category_dependent_ids = m_category_dependencies;
// Write category properties file
{
QString output_filename(m_output_bin_dir);
output_filename.append(filename).append(FileUtils::_CATEGORY_PROPERTIES_EXT);
category_properties.write(output_filename.toStdString());
}
// human readable
{
QString output_filename(m_output_hr_dir);
output_filename.append(filename).append("_properties").append(".csv");
category_properties.writeToCSV(output_filename.toStdString());
}
}
m_output_bin_dir = m_radial_distribution_dir;
m_output_hr_dir = m_csv_dir;
// radial distributions
for(auto lpair: loaded_pair_correlations)
{
RadialDistribution radial_distribution = lpair.second;
int reference_category_id(radial_distribution.m_header.reference_id);
int target_category_id(radial_distribution.m_header.destination_id);
// int reference_category_id(lpair.first.first);
// int target_category_id(lpair.first.second);
// cerr << "ref:targ " << reference_category_id << ": " << target_category_id << " in lpair " << lpair.first.first << ": " << lpair.first.second << endl;
// std::pair<int,int> pair(radial_distribution.m_header.reference_id, radial_distribution.m_header.destination_id);
// loaded_pair_correlations.insert(std::pair<std::pair<int,int>, RadialDistribution>(pair, radial_distribution));
QString filename("category_");
filename.append(QString::number(reference_category_id)).append("_and_").append(QString::number(target_category_id));
// check for empty radial distribution
// radial_distribution.printToConsole();
// Write rad file
{
QString output_filename(m_output_bin_dir);
output_filename.append(filename).append(FileUtils::_RADIAL_DISTRIBUTION_EXT);
radial_distribution.write(output_filename.toStdString());
}
// Write CSV file
{
QString output_filename(m_output_hr_dir);
output_filename.append(filename).append("_pair_correlation").append(".csv");
radial_distribution.writeToCSV(output_filename.toStdString());
}
}
std::string filename(m_base_dir.append(FileUtils::_TIMESTAMP_FILENAME).toStdString());
unsigned long m_timestamp( std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count());
// Write timestamp file
std::ofstream file;
file.open(filename);
if(file.is_open())
file << m_timestamp << "\n";
file.close();
return true;
}
bool Distribution::read(string rootdir, Terrain * ter, CategorySizes & catsizes)
{
// cerr << "rootdir is " << rootdir << endl;
inputdir = rootdir.c_str();
// Load various aspects of a distribution from the source directory, including histograms within and between categories and all category metadata
if(!FileUtils::check_directory_structure(inputdir))
{
cerr << "Distribution::read: Incorrect directory structure in " << inputdir.toStdString() << endl;
return false;
}
analyzeconfig = AnalysisConfiguration(FileUtils::get_configuration_file(inputdir).toStdString());
// Load category properties
std::vector<QString> category_properties_files(FileUtils::get_category_properties_files(inputdir));
for(QString category_property_file : category_properties_files)
{
CategoryProperties category_property(category_property_file.toStdString());
loaded_category_properties.insert(std::pair<int, CategoryProperties>(category_property.m_header.category_id, category_property));
}
#ifdef VALIDATE
if(rootdir == string("/home/james/Desktop/medResample/7"))
cerr << "Priority: ";
#endif
// Check all necessary category properties files were there
for(auto it(analyzeconfig.priority_sorted_category_ids.begin()); it != analyzeconfig.priority_sorted_category_ids.end(); it++)
{
if(loaded_category_properties.find(*it) == loaded_category_properties.end())
{
std::cerr << "Distribution::read: Missing category properties file for category " << *it << std::endl;
return false;
}
#ifdef VALIDATE
if(rootdir == string("/home/james/Desktop/medResample/7"))
cerr << (* it) << " ";
#endif
CategoryProperties &prop = loaded_category_properties.find(*it)->second;
// update size header info
// cerr << "hght avg = " << prop.m_header.height_properties.avg << " sdv = " << prop.m_header.height_properties.standard_dev << endl;
// cerr << "hght min = " << prop.m_header.height_properties.min << " max = " << prop.m_header.height_properties.max << endl;
bool ignore = (prop.m_header.height_properties.avg <= 2); // && (prop.m_header.height_properties.standard_dev < pluszero);
if(!ignore) // has at least one element
{
if(catsizes.find(* it) == catsizes.end()) // category not found so add it
{
AggregateSizeProperties aggsize;
aggsize.n = 1; aggsize.totalHeight = (float) prop.m_header.height_properties.avg;
aggsize.heightToCanopyRadius = prop.m_header.height_to_radius_multiplier;
#ifdef VALIDATE
if(rootdir == string("/home/james/Desktop/medResample/7"))
{
cerr << "adding cateogory " << (* it) << " with CanopyRatio " << aggsize.heightToCanopyRadius << endl;
cerr << "standard deviation = " << prop.m_header.height_properties.standard_dev << endl;
}
#endif
catsizes[(* it)] = aggsize;
}
else // category exists so update average plant size
{
catsizes[(* it)].n += 1;
catsizes[(* it)].totalHeight += (float) prop.m_header.height_properties.avg;
catsizes[(* it)].heightToCanopyRadius += prop.m_header.height_to_radius_multiplier;
}
}
}
#ifdef VALIDATE
if(rootdir == string("/home/james/Desktop/medResample/7"))
cerr << endl;
#endif
// create pair correlations
std::vector<std::pair<int,int> > required_pair_correlations;
for(auto reference_category(analyzeconfig.priority_sorted_category_ids.begin()); reference_category != analyzeconfig.priority_sorted_category_ids.end(); reference_category++)
{
for(auto target_category(std::find(analyzeconfig.priority_sorted_category_ids.begin(), analyzeconfig.priority_sorted_category_ids.end(), *reference_category));
target_category != analyzeconfig.priority_sorted_category_ids.end(); target_category++)
{
required_pair_correlations.push_back(std::pair<int,int>(*reference_category, *target_category));
#ifdef VALIDATE
if(rootdir == string("/home/james/Desktop/medResample/7"))
cerr << *reference_category << ": " << *target_category << endl;
#endif
}
}
// Load radial distributions
std::vector<QString> radial_distribution_files(FileUtils::get_radial_distribution_files(inputdir));
for(QString radial_distribution_file : radial_distribution_files)
{
RadialDistribution radial_distribution(radial_distribution_file.toStdString());
// if(rootdir == string("/home/james/Desktop/medResample/7"))
// radial_distribution.printToConsole();
std::pair<int,int> pair(radial_distribution.m_header.reference_id, radial_distribution.m_header.destination_id);
loaded_pair_correlations.insert(std::pair<std::pair<int,int>, RadialDistribution>(pair, radial_distribution));
}
// Check all necessary pair correlations were loaded
for(auto it(required_pair_correlations.begin()); it != required_pair_correlations.end(); it++)
{
if(loaded_pair_correlations.find(*it) == loaded_pair_correlations.end())
{
std::cerr << "Distribution::read: Missing pair correlation for category pair [" << it->first << "," << it->second << "]" << std::endl;
// exit(1);
// create empty pair correlation to compensate
}
}
empty = false;
return true;
}
/// MultiDistributionReproducer
#define SPATIAL_HASHMAP_CELL_WIDTH 10
#define SPATIAL_HASHMAP_CELL_HEIGHT 10
/////////////////////////////////////////////////////////////////////////////////
MultiDistributionReproducer::MultiDistributionReproducer(ConditionsMap * cmap,
ReproductionConfiguration reproduction_settings, AnalysisConfiguration analysis_configuration,
GeneratedPointsProperties * outGeneratedPointProperties) :
m_cmap(cmap), m_reproduction_configuration(reproduction_settings),
m_spatial_point_storage(m_reproduction_configuration.width, m_reproduction_configuration.height), m_analysis_configuration(analysis_configuration),
m_generated_points_properties(outGeneratedPointProperties), m_dice_roller(0,RAND_MAX)
{
// Initialize the point properties tracker
SizeProperties size_properties;
// placeholder for now. Will need to create a global categories hierarchy TO DO
for(auto it(cmap->getSamplingDatabase()->getCategorySizes().begin()); it != cmap->getSamplingDatabase()->getCategorySizes().end(); it++)
{
size_properties.heightToCanopyRadius = it->second.heightToCanopyRadius;
// std::cerr << "CR " << it->first << " " << size_properties.heightToCanopyRadius << std::endl;
size_properties.minHeight = -1;
size_properties.maxHeight = -1;
m_generated_points_properties->emplace(it->first, size_properties);
}
movecycles = 2;
}
void MultiDistributionReproducer::setRepConfig(ReproductionConfiguration &rep)
{
m_reproduction_configuration.height = rep.height;
m_reproduction_configuration.width = rep.width;
}
void MultiDistributionReproducer::setSubSynthArea(int startx, int starty, int extentx, int extenty)
{
subsynth.startx = startx;
subsynth.starty = starty;
subsynth.extentx = extentx;
subsynth.extenty = extenty;
}
void MultiDistributionReproducer::clearPoints(std::vector<AnalysisPoint> * toclear)
{
for(auto pnt: (* toclear))
{
m_taken_points.removePoint(pnt.getCenter());
m_spatial_point_storage.removePoint(pnt);
}
m_placed_categories.clear();
}
bool MultiDistributionReproducer::testCleared(int startx, int starty, int extentx, int extenty)
{
bool isempty = true;
int takencount = 0;
// look for points in the identified area in m_taken_points and m_spatial_point_storage
// should be empty
// check if taken point falls in region
for(auto msp = m_taken_points.begin(); msp != m_taken_points.end(); msp++)
{
if(msp->first.first >= startx && msp->first.first < startx+extentx && msp->first.second >= starty && msp->first.second < starty+extenty)
{
// in region so count
takencount++;
isempty = false;
}
}
if(!isempty)
cerr << "Error MultiDistributionReproducer::testCleared: " << takencount << " points remain in cleared area" << endl;
return isempty;
}
void MultiDistributionReproducer::profileRndGen(int count)
{
Timer t;
t.start();
for(int i = 0; i < count; i++)
{
// getRandomPoint(15002);
}
t.stop();
cerr << "Time for " << count << " random point generations = " << t.peek() << "s" << endl;
}
AnalysisPoint MultiDistributionReproducer::getRandomStep(const AnalysisPoint & refpnt, int cid)
{
int x, y;
int dx, dy, dh;
QPoint position;
bool fin = false;
int max_attempts = 100, attempts = 0;
int maxstep = 6; // * binsize;
while(!fin)
{
dx = rand() % maxstep; dy = rand() % maxstep;
// x = refpnt.x()+dx; y = refpnt.y()+dy;
if(!m_cmap->lookupSynthDistrib(x, y)->isEmpty()) // hit an empty part so skip
{
position = QPoint(x, y);
fin = !m_taken_points.containsPoint(position) && (m_cmap->lookupSynthDistrib(x, y)->getCategories().find(cid) != m_cmap->lookupSynthDistrib(x, y)->getCategories().end());
}
attempts++; rndcount++;
if(attempts > max_attempts)
fin = true;
}
if(attempts > max_attempts)
{
cerr << "Error getRandomStep: too many attempts at placement" << endl;
// exit(0);
}
// now look up height range in category properties
CategoryProperties m_active_cp = m_cmap->lookupSynthDistrib(x, y)->getCategories().find(cid)->second;
// set height randomly in range, with uniform distribution
int minrange = m_active_cp.m_header.height_properties.min;
int maxrange = m_active_cp.m_header.height_properties.max;
int range = maxrange-minrange;
int height;
if(range == 0) // to avoid the error that results from div by zero
height = minrange;
else
{
// dh = ;
// height = refpnt.height() + dh; minrange + m_dice_roller.generate() % range; // calculate small increment in +- 10% range
}
return AnalysisPoint(m_active_cp.m_header.category_id, position, height*m_active_cp.m_header.height_to_radius_multiplier,
height*m_active_cp.m_header.height_to_root_size_multiplier, height);
}
AnalysisPoint MultiDistributionReproducer::getRandomPoint(int cid)
{
// replaces PointFactory functions, which require the category to be set before the position is determined
// This is not possible under the ConditionMap approach because categories are looked up based on position
int x, y;
// int m_width = m_reproduction_configuration.width;
// int m_height = m_reproduction_configuration.height;
// get random position
QPoint position;
bool fin = false;
int max_attempts = 10000, attempts = 0;
while(!fin)
{
// position = QPoint(subsynth.startx+m_dice_roller.generate()%(subsynth.extentx-1), subsynth.starty+m_dice_roller.generate()%(subsynth.extenty-1));
position = QPoint(subsynth.startx+rand()%(subsynth.extentx-1), subsynth.starty+rand()%(subsynth.extenty-1));
// position = QPoint(subsynth.startx+xorshift128plus()%(subsynth.extentx-1), subsynth.starty+xorshift128plus()%(subsynth.extenty-1));
x = position.x(); y = position.y();
//cerr << "pos = " << x << ", " << y << endl;
if(!m_cmap->lookupSynthDistrib(x, y)->isEmpty()) // hit an empty part so skip
{
fin = !m_taken_points.containsPoint(position) && (m_cmap->lookupSynthDistrib(x, y)->getCategories().find(cid) != m_cmap->lookupSynthDistrib(x, y)->getCategories().end());
}
attempts++; rndcount++;
if(attempts > max_attempts)
fin = true;
}
if(attempts > max_attempts)
{
cerr << "Too many attempts at placement" << endl;
// exit(0);
}
// now look up height range in category properties
//if(m_cmap->lookupSynthDistrib(x, y)->getCategories().find(cid) == m_cmap->lookupSynthDistrib(x, y)->getCategories().end())
// cerr << "CID " << cid << " not found in categories" << endl;
CategoryProperties m_active_cp = m_cmap->lookupSynthDistrib(x, y)->getCategories().find(cid)->second;
// set height randomly in range, with uniform distribution
int minrange = m_active_cp.m_header.height_properties.min;
int maxrange = m_active_cp.m_header.height_properties.max;
int range = maxrange-minrange;
int height;
/*
if(range == 0) // to avoid the error that results from div by zero
height = minrange;
else
// height = minrange + m_dice_roller.generate() % range;
height = minrange + rand() % range;
// height = minrange + xorshift128plus() % range;
// set to average
// height = m_active_cp.m_header.height_properties.avg;
*/
if(range == 0) // to avoid the error that results from div by zero
{
height = minrange;
}
else // generate height according to mean and standard deviation, using a normal distribution
{
std::normal_distribution<double> distribution(m_active_cp.m_header.height_properties.avg, m_active_cp.m_header.height_properties.standard_dev);
height = distribution(generator);
// clamp to range
if(height < minrange)
height = minrange;
if(height > maxrange)
height = maxrange;
// cerr << "avg = " << m_active_cp.m_header.height_properties.avg << " dev = " << m_active_cp.m_header.height_properties.standard_dev << " res = " << height << endl;
// cerr << "min = " << m_active_cp.m_header.height_properties.min << " max = " << m_active_cp.m_header.height_properties.max << endl;
}
return AnalysisPoint(m_active_cp.m_header.category_id, position, height*m_active_cp.m_header.height_to_radius_multiplier,
height*m_active_cp.m_header.height_to_root_size_multiplier, height);
// The point_factory seems to use a histogram based approach for height but it may not be correctly hooked up on the analysis side
// Need to ask HL about this
}
/*
void MultiDistributionReproducer::reportTiming()
{
cerr << "Density Initialisation = " << inittime << "s" << endl;
cerr << "Moves = " << movetime << "s" << endl;
cerr << "Random Gen Calls = " << rndcount << endl;
cerr << "Area based time = " << t1time << "s" << endl;
cerr << "Random Point time = " << t2time << "s" << endl;
cerr << "Accel point validity time = " << t3time << "s" << endl;
cerr << "Calc strength time = " << t4time << "s" << endl;
cerr << "Add Dest time = " << t5time << "s" << endl;
}*/
void MultiDistributionReproducer::startPointGeneration(GeneratedPoints & genpnts, int numcycles)
{
// std::chrono::high_resolution_clock::time_point start_time = std::chrono::high_resolution_clock::now();
// std::chrono::high_resolution_clock::time_point end_time;
movecycles = numcycles;
int total_point_count(0);
#ifdef VALIDATE
strcnt = 0;
strsum = 0.0f;
xsect = 0;
zerocnt = 0;
quickcnt = 0;
#endif
// m_cmap->summaryDisplayDescriptor(0,0);
// m_cmap->summaryDisplayDescriptor(99700, 84200);
// m_cmap->summaryDisplayDescriptor(50000, 50000);
// for(auto it(m_analysis_configuration.priority_sorted_category_ids.begin()); it != m_analysis_configuration.priority_sorted_category_ids.end(); it++)
for(auto it: m_cmap->getSamplingDatabase()->getGlobalPriority())
{
//if(it >= 18000)
// std::cerr << "Inserting points for category " << it << "..." << std::endl;
generate_points(it);
if(m_active_category_points.size() > 0)
{
genpnts[m_active_category_points.at(0).getCategoryId()] = m_active_category_points;
total_point_count += m_active_category_points.size();
}
m_active_category_points.clear();
}
#ifdef VALIDATE
if(strcnt > 0)
{
cerr << strcnt << " avg synthqual = " << strsum / (float) strcnt << endl;
cerr << "number of trunk intersects = " << xsect << " / " << strcnt << "; zero strength intersects = " << zerocnt << " / " << xsect;
cerr << "; quick check passes = " << quickcnt << " / " << zerocnt << endl;
}
#endif
// end_time = std::chrono::high_resolution_clock::now();
// auto duration (std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count());
// std::cout << "Simulation over! " << std::endl
// << "\t Source density: " << (((float)m_radial_distribution.m_properties.n_reference_points)/m_radial_distribution.m_properties.analysed_area) << std::endl
// << "\t Output density: " << ((float)m_destination_points->size())/(m_settings.width*m_settings.height) << std::endl
// << "\t Calculation time: " << duration << " ms." << std::endl
// << "\t Total points: " << total_point_count << std::endl;
}
void MultiDistributionReproducer::generate_points(int cid)
{
Timer t;
int sx, sy, ex, ey;
// divide subsynth area up into local cells
m_cmap->getCoord(subsynth.startx, subsynth.starty, sx, sy);
m_cmap->getCoord(subsynth.startx+subsynth.extentx, subsynth.starty+subsynth.extenty, ex, ey);
// locsynth = subsynth;
/*
int cellextent = (int) (subsynth.extentx / (ex-sx));
cerr << "subsynth" << endl;
cerr << "start = " << subsynth.startx << ", " << subsynth.starty << " extent = " << subsynth.extentx << ", " << subsynth.extenty << endl;
cerr << "map start = " << sx << ", " << sy << " map extent = " << ex-sx << ", " << ey-sy << endl;
cerr << "cell extent = " << cellextent << endl;
*/
// t.start();
matching_density_initialize(cid);
// t.stop(); inittime += t.peek();
// t.start();
generate_points_through_random_moves(cid);
// t.stop(); movetime += t.peek();
/*
for(int x = 0; x < sx-ex; x++)
for(int y = 0; y < sy-ey; y++)
{
// map to local start and extent
locsynth.startx = subsynth.startx + x * cellextent;
locsynth.starty = subsynth.starty + y * cellextent;
locsynth.extentx = cellextent;
locsynth.extenty = cellextent;
// t.start();
matching_density_initialize(cid);
// t.stop(); inittime += t.peek();
// t.start();
generate_points_through_random_moves(cid);
// t.stop(); movetime += t.peek();
}
*/
}
int MultiDistributionReproducer::canopyIntersect(const AnalysisPoint & refpnt)
{
std::vector<AnalysisPoint> reachpnts(m_spatial_point_storage.getPossibleReachablePoints(refpnt, m_analysis_configuration.r_max));
int xsectcnt = 0;
QLineF line;
line.setP1(refpnt.getCenter());
std::vector<AnalysisPoint> existing_points;
// select out only those points that have the same distribution, otherwise creates issues with order of plant generation
for(auto it: reachpnts)
{
// if(m_cmap->equivDescriptor(m_cmap->getSynthDescriptor(refpnt.getCenter().x(), refpnt.getCenter().y()),
// m_cmap->getSynthDescriptor(it.getCenter().x(), it.getCenter().y())))
existing_points.push_back(it);
}
const float refpntrad = refpnt.getRadius();
for(const AnalysisPoint & existpnt : existing_points)
{
line.setP2(existpnt.getCenter());
// const float existpntrad = existpnt.getRadius();
float distance = line.length();
if(distance < refpntrad)
xsectcnt++;
}
#ifdef VALIDATE
if(xsectcnt > 0) // now test if strength is zero
{
bool discard;
if(calculate_strength(refpnt) < pluszero)
{
zerocnt++;
bool needs_check;
accelerated_point_validity_check(refpnt, needs_check);
if(!needs_check)
quickcnt++;
}
}
#endif
return xsectcnt;
}
void MultiDistributionReproducer::cacheReachablePoints(const AnalysisPoint & refpnt, std::vector<AnalysisPoint> & reachpnts)
{
reachpnts = m_spatial_point_storage.getPossibleReachablePoints(refpnt, m_analysis_configuration.r_max);
}
bool MultiDistributionReproducer::canopyIntersectFree(const AnalysisPoint & refpnt, std::vector<AnalysisPoint> & reachpnts)
{
QLineF line;
line.setP1(refpnt.getCenter());
const float refpntrad = refpnt.getRadius();
for(const AnalysisPoint & existpnt : reachpnts)
{
line.setP2(existpnt.getCenter());
float distance = line.length();
if(distance < refpntrad)
return false;
}
return true;
}
void MultiDistributionReproducer::generate_points_through_random_moves(int cid)
{
DiceRoller dice_roller(0,1000);
int n_accepted_moves(0), n_refused_moves(0);
#ifdef VALIDATE
radcnt = 0;
radsum = 0;
avgsum = 0;
devsum = 0;
minsum = 0;
maxsum = 0;
#endif
for(int selected_point_index(0); selected_point_index < (int) m_active_category_points.size(); selected_point_index++)
{
// std::cerr << "s = " << selected_point_index << " / " << m_active_category_points.size() << std::endl;
AnalysisPoint & selected_point(m_active_category_points.at(selected_point_index));
/*
if(selected_point_index == 0)
{
if(!m_cmap->lookupSynthDistrib(selected_point.getCenter().x(), selected_point.getCenter().y())->isEmpty())
{
m_cmap->summaryDisplayDescriptor(selected_point.getCenter().x(), selected_point.getCenter().y());
m_cmap->lookupSynthDistrib(selected_point.getCenter().x(), selected_point.getCenter().y())->summaryDisplay();
}
}*/
#ifdef VALIDATE
if(selected_point_index == 0)
{
// cerr << "CID " << cid << " distribution" << endl;
// m_cmap->lookupSynthDistrib(selected_point.getCenter().x(), selected_point.getCenter().y())->display();
}
#endif
// double source_point_strength = std::max(0.000001, calculate_strength(selected_point) );
float source_point_strength = calculate_strength(selected_point);
AnalysisPoint highest_scoring_dest_point;
float highest_strength(-1);
for(int i(0); i < movecycles; i++)
{
/*********************
* DESTINATION POINT *
*********************/
// AnalysisPoint random_dest_point = getRandomPoint(selected_point.getHeight());
AnalysisPoint random_dest_point = getRandomPoint(cid); // vary both position and height, necessary because species height ranges change with position
// will need to check validity of new position, move only within current category boundaries? TO DO
// Calculate strength
float destination_point_strength = calculate_strength(random_dest_point);
// std::cout << "Random destination point strength: " << destination_point_strength << std::endl;
if(destination_point_strength > highest_strength)
{
highest_scoring_dest_point = random_dest_point;
highest_strength = destination_point_strength;
}
}
float acceptance_ratio(highest_strength/source_point_strength);
// std::cerr << "Acceptance ratio: " << acceptance_ratio << std::endl;
if(ProbabilisticUtils::returnTrueWithProbability(acceptance_ratio, dice_roller))
//if(ProbabilisticUtils::returnTrueWithProbabilitySupplied(acceptance_ratio, rand()%1000))
{
n_accepted_moves++;
move_point(selected_point, highest_scoring_dest_point);
#ifdef VALIDATE
strsum -= source_point_strength;
strsum += highest_strength;
radsum += highest_scoring_dest_point.getHeight();
CategoryProperties m_active_cp = m_cmap->lookupSynthDistrib(selected_point.getCenter().x(), selected_point.getCenter().y())->getCategories().find(cid)->second;
avgsum += m_active_cp.m_header.height_properties.avg;
devsum += m_active_cp.m_header.height_properties.standard_dev;
minsum += m_active_cp.m_header.height_properties.min;
maxsum += m_active_cp.m_header.height_properties.max;
radcnt++;
#endif
}
else
{
n_refused_moves++;
#ifdef VALIDATE
radsum += selected_point.getHeight();
CategoryProperties m_active_cp = m_cmap->lookupSynthDistrib(selected_point.getCenter().x(), selected_point.getCenter().y())->getCategories().find(cid)->second;
avgsum += m_active_cp.m_header.height_properties.avg;
devsum += m_active_cp.m_header.height_properties.standard_dev;
minsum += m_active_cp.m_header.height_properties.min;
maxsum += m_active_cp.m_header.height_properties.max;
radcnt++;
#endif
}
// std::cerr << ((((float)points_processed)/m_active_category_points.size()) * 100) << "%" << std::endl;
}
#ifdef VALIDATE
if(radcnt > 0)
{
cerr << "CID " << cid << " : num plants = " << radcnt << " avg height = " << (float) radsum / (float) radcnt << " vs. expected height = " << (float) minsum / (float) radcnt << " " << (float) avgsum / (float) radcnt << " " << (float) maxsum / (float) radcnt << endl;
cerr << " avg stdev = " << (float) devsum / (float) radcnt << endl;
}
#endif
// std::cerr << "Accepted moves: " << n_accepted_moves << " | Refused moves: " << n_refused_moves << std::endl;
}
int MultiDistributionReproducer::areaBasedPointCount(int cid)
{
int a_points = 0, num_areas = 0, num_empty = 0;
int sx, sy, ex, ey;
Distribution * distrib;
// over region in question and for particular category, find point proportionality using area based approach
// m_cmap->getCoord(m_reproduction_configuration.width, m_reproduction_configuration.height, ex, ey);
// TO DO - remove iteration since this should only be a single cell
m_cmap->getCoord(subsynth.startx, subsynth.starty, sx, sy);
m_cmap->getCoord(subsynth.startx+subsynth.extentx, subsynth.starty+subsynth.extenty, ex, ey);
for(int x = sx; x < ex; x++)
for(int y = sy; y < ey; y++)
{
// distrib = m_cmap->lookupDirectDistribFast(x, y);
distrib = m_cmap->lookupDirectDistrib(x, y);
if(!distrib->isEmpty())
{
auto cat = distrib->getCategories().find(cid);
if(cat != distrib->getCategories().end())
{
a_points += cat->second.m_header.n_points;
//if(x == 0 && y == 0 && cid == 17002)
//if(cid == 17002 && m_cmap->getDescriptor(x, y).age == 50)
// cerr << cat->second.m_header.n_points << endl;
}
}
num_areas++;
}
/*
if(cid == 18000)
{
cerr << "CID: " << cid << endl;
cerr << "a_point = " << a_points << endl;
cerr << "subsynth extent = " << subsynth.extentx << " X " << subsynth.extenty << endl;
cerr << "window extent = " << m_analysis_configuration.analysis_window_width << " X " << m_analysis_configuration.analysis_window_height << endl;
cerr << "analysis config = " << m_analysis_configuration.r_min << ", " << m_analysis_configuration.r_max << ", " << m_analysis_configuration.r_diff << endl;
cerr << "calc points = " << a_points * (((float) (subsynth.extentx*subsynth.extenty)) / ((float) num_areas * m_analysis_configuration.analysis_window_width * m_analysis_configuration.analysis_window_height)) << endl;
cerr << "ANALYSIS AREA = " << m_analysis_configuration.analysis_window_width * m_analysis_configuration.analysis_window_height << endl;
cerr << "SYNTHESIS AREA = " << ((long) subsynth.extentx* (long) subsynth.extenty) << endl;
cerr << "SCALE RATIO = " << 1000.0f * (((float) (subsynth.extentx*subsynth.extenty)) / ((float) num_areas * m_analysis_configuration.analysis_window_width * m_analysis_configuration.analysis_window_height)) << endl;
cerr << "num areas = " << num_areas << endl;
cerr << endl;
}
*/
float syntharea = (float) subsynth.extentx * (float) subsynth.extenty;
float analysisarea = (float) num_areas * (float) m_analysis_configuration.analysis_window_width * (float) m_analysis_configuration.analysis_window_height;
return (int) ((float) a_points * syntharea / analysisarea);
}
////
//// VARIATION METHODS FOR TESTING SYNTHESIS ALTERNATIVES
///
int MultiDistributionReproducer::variantPlaceNoHits(int cid)
{
int n_points = areaBasedPointCount(cid);
m_active_category_points.clear();
while((int) m_active_category_points.size() < n_points)
{
AnalysisPoint random_point = getRandomPoint(cid);
add_destination_point(random_point);
}
return n_points;
}
int MultiDistributionReproducer::variantPlaceNoTrunks(int cid)
{
int i = 0, fails = 0;
int n_points = areaBasedPointCount(cid);
m_active_category_points.clear();
while((int) m_active_category_points.size() < n_points)
{
AnalysisPoint random_point = getRandomPoint(cid);
std::vector<AnalysisPoint> reachpnts;
cacheReachablePoints(random_point, reachpnts);
bool placed = false;
if(canopyIntersectFree(random_point, reachpnts))
{
add_destination_point(random_point);
i = 0; // reset failure counter
}
else
{
i++;
if(i >= placethresh) // have failed to find a valid placement after threshold attempts
{ // so just place
#ifdef VALIDATE
if(canopyIntersect(random_point) > 0)
xsect++;
strsum += calculate_strength(random_point);
strcnt++;
#endif
add_destination_point(random_point);
i = 0; // reset failure counter
fails++;
}
}
}
if(fails > 0)
std::cerr << "Failed to achieve placement " << fails << " / " << n_points << std::endl;
return n_points;
}
int MultiDistributionReproducer::variantPlaceFull(int cid)
{
int i = 0, fails = 0;
bool needs_check;
int n_points = areaBasedPointCount(cid);
m_active_category_points.clear();
while((int) m_active_category_points.size() < n_points)
{
AnalysisPoint random_point = getRandomPoint(cid);
std::vector<AnalysisPoint> reachpnts;
cacheReachablePoints(random_point, reachpnts);
bool placed = false;
if(canopyIntersectFree(random_point, reachpnts))
{
// Attempt accelerated point validity check
accelerated_point_validity_check(random_point, needs_check);
// note that this version of calculate_strength should be robust to not finding point within radius
if((!needs_check) || (needs_check && calculate_strength(random_point, reachpnts) > 0.0)) // pluzero might be better
{
#ifdef VALIDATE
if(canopyIntersect(random_point) > 0)
xsect++;
strsum += calculate_strength(random_point);
strcnt++;
#endif
add_destination_point(random_point);
i = 0; // reset failure counter
placed = true;
}
}
if(!placed)
{
i++;
if(i >= placethresh) // have failed to find a nonzero strength or valid placement
{ // so just place
#ifdef VALIDATE
if(canopyIntersect(random_point) > 0)
xsect++;
strsum += calculate_strength(random_point);
strcnt++;
#endif
add_destination_point(random_point);
i = 0; // reset failure counter
fails++;
}
}
}
if(fails > 0)
std::cerr << "Failed to achieve placement " << fails << " / " << n_points << std::endl;
return n_points;
}
void MultiDistributionReproducer::variantMoveStep(int cid)
{
DiceRoller dice_roller(0,1000);
int n_accepted_moves(0), n_refused_moves(0);
#ifdef VALIDATE
radcnt = 0;
radsum = 0;
avgsum = 0;
devsum = 0;
minsum = 0;
maxsum = 0;
#endif
for(int selected_point_index(0); selected_point_index < (int) m_active_category_points.size(); selected_point_index++)
{
AnalysisPoint & selected_point(m_active_category_points.at(selected_point_index));
float source_point_strength = calculate_strength(selected_point);
AnalysisPoint highest_scoring_dest_point;
float highest_strength(-1);
for(int i(0); i < movecycles; i++)
{
/*********************
* DESTINATION POINT *
*********************/
// AnalysisPoint random_dest_point = getRandomPoint(selected_point.getHeight());
AnalysisPoint random_dest_point;
// choose between jump or step here
if(ProbabilisticUtils::returnTrueWithProbability(jumpchance, dice_roller))
{
// jump
random_dest_point = getRandomPoint(cid);
}
else
{
// step in random direction by two bin widths and alter radius up or down by 20% of height range
random_dest_point = getRandomStep(selected_point, cid);
}
float destination_point_strength = calculate_strength(random_dest_point);
if(destination_point_strength > highest_strength)
{
highest_scoring_dest_point = random_dest_point;
highest_strength = destination_point_strength;
}
}
float acceptance_ratio(highest_strength/source_point_strength);
if(ProbabilisticUtils::returnTrueWithProbability(acceptance_ratio, dice_roller))
//if(ProbabilisticUtils::returnTrueWithProbabilitySupplied(acceptance_ratio, rand()%1000))
{
n_accepted_moves++;
move_point(selected_point, highest_scoring_dest_point);
#ifdef VALIDATE
strsum -= source_point_strength;
strsum += highest_strength;
radsum += highest_scoring_dest_point.getHeight();
CategoryProperties m_active_cp = m_cmap->lookupSynthDistrib(selected_point.getCenter().x(), selected_point.getCenter().y())->getCategories().find(cid)->second;
avgsum += m_active_cp.m_header.height_properties.avg;
devsum += m_active_cp.m_header.height_properties.standard_dev;
minsum += m_active_cp.m_header.height_properties.min;
maxsum += m_active_cp.m_header.height_properties.max;
radcnt++;
#endif
}
else
{
n_refused_moves++;
#ifdef VALIDATE
radsum += selected_point.getHeight();
CategoryProperties m_active_cp = m_cmap->lookupSynthDistrib(selected_point.getCenter().x(), selected_point.getCenter().y())->getCategories().find(cid)->second;
avgsum += m_active_cp.m_header.height_properties.avg;
devsum += m_active_cp.m_header.height_properties.standard_dev;
minsum += m_active_cp.m_header.height_properties.min;
maxsum += m_active_cp.m_header.height_properties.max;
radcnt++;
#endif
}
}
}
void MultiDistributionReproducer::variantMoveHeightSep(int cid)
{
}
////
////
int MultiDistributionReproducer::matching_density_initialize(int cid)
{
int i(0);
bool needs_check;
int fails = 0;
int n_points = areaBasedPointCount(cid);
/*
if(cid == 15000)
{
cerr << "cat " << cid << " expected points = " << n_points << endl;
}*/
/*
if(!m_cmap->lookupSynthDistrib(selected_point.getCenter().x(), selected_point.getCenter().y())->isEmpty())
{
m_cmap->summaryDisplayDescriptor(selected_point.getCenter().x(), selected_point.getCenter().y());
m_cmap->lookupSynthDistrib(selected_point.getCenter().x(), selected_point.getCenter().y())->summaryDisplay();
}*/
// m_placed_categories.clear();
// m_generated_points_properties->clear();
m_active_category_points.clear();
// std::cerr << "n point = " << n_points << std::endl;
while((int) m_active_category_points.size() < n_points)
{
AnalysisPoint random_point = getRandomPoint(cid);
std::vector<AnalysisPoint> reachpnts;
cacheReachablePoints(random_point, reachpnts);
bool placed = false;
if(canopyIntersectFree(random_point, reachpnts))
{
// Attempt accelerated point validity check
accelerated_point_validity_check(random_point, needs_check);
if((!needs_check) || (needs_check && calculate_strength(random_point, reachpnts) > 0.0)) // pluzero might be better
{
#ifdef VALIDATE
if(canopyIntersect(random_point) > 0)
xsect++;
strsum += calculate_strength(random_point);
strcnt++;
#endif
add_destination_point(random_point);
i = 0; // reset failure counter
placed = true;
}
}
if(!placed)
{
i++;
if(i >= placethresh) // have failed to find a nonzero strength or valid placement
{ // so just place
#ifdef VALIDATE
if(canopyIntersect(random_point) > 0)
xsect++;
strsum += calculate_strength(random_point);
strcnt++;
#endif
add_destination_point(random_point);
i = 0; // reset failure counter
fails++;
}
}
}
if(fails > 0)
{
std::cerr << "Failed to achieve placement " << fails << " / " << n_points << std::endl;
// AnalysisPoint random_point = getRandomPoint(cid);
// calculate_strength_verbose(random_point);
}
return n_points;
}
void MultiDistributionReproducer::move_point(AnalysisPoint & point, AnalysisPoint & new_location)
{
m_taken_points.removePoint(point.getCenter());
m_spatial_point_storage.removePoint(point);
point = new_location;
// Add
m_taken_points.insertPoint(point.getCenter());
m_spatial_point_storage.addPoint(point);
}
void MultiDistributionReproducer::add_destination_point(const AnalysisPoint & point)
{
m_taken_points.insertPoint(point.getCenter());
m_active_category_points.push_back(point); // Update the active category points vector
m_spatial_point_storage.addPoint(point);
// Check min/max
SizeProperties & props((*m_generated_points_properties)[point.getCategoryId()]);
int point_height(point.getHeight());
if(props.maxHeight == -1 || point.getHeight() > props.maxHeight)
props.maxHeight = point_height;
if(props.minHeight == -1 || point.getHeight() < props.minHeight)
props.minHeight = point_height;
}
void MultiDistributionReproducer::remove_destination_point(const AnalysisPoint & point, int this_category_points_index)
{
m_taken_points.removePoint(point.getCenter());
m_active_category_points.erase(m_active_category_points.begin()+this_category_points_index); // Update the active category points vector
m_spatial_point_storage.removePoint(point);
}
void MultiDistributionReproducer::accelerated_point_validity_check(const AnalysisPoint & reference_point, bool & needs_check)
{
// add current category to set if it isn't already there
m_placed_categories.insert(reference_point.getCategoryId()); // assuming it has the correct category at this point
for(auto cat: m_placed_categories) // iterate over categories belonging to point already placed, although not all categories may actually appear in surrounding points
{
accelerated_point_validity_check(reference_point, cat, needs_check);
if(needs_check)
return;
}
/*
// Check pair correlations for this point and other points present and check if any are equal to zero
for(auto it(m_all_generated_points.begin()); it != m_all_generated_points.end(); it++)
{
accelerated_point_validity_check(reference_point, it->first, needs_check);
if(needs_check)
return;
}
// With itself
accelerated_point_validity_check(reference_point, m_point_factory.getActiveCategoryId(), needs_check);*/
}
void MultiDistributionReproducer::accelerated_point_validity_check(const AnalysisPoint & reference_point, int queried_category, bool & needs_check)
{
needs_check = true;
if(m_cmap->lookupSynthDistrib(reference_point.getCenter().x(), reference_point.getCenter().y())->getCategories().find(reference_point.getCategoryId())->second.m_header.category_dependent_ids.size() > 0) // dependent categories
{
// std::cerr << "is dependent on other categories" << std::endl;
return;
}
const RadialDistribution * distribution = get_radial_distribution(reference_point, queried_category, reference_point.getCategoryId());
if(distribution != nullptr && distribution->getMinimum() == 0) // < pluszero) // tolerance is introduced here because mass transport interpolation introduces some numerical error
{
return;
}
// If we got here, point is valid
needs_check = false;
}
float MultiDistributionReproducer::calculate_strength(const AnalysisPoint & reference_point)
{
//std::vector<AnalysisPoint> possible_reachable_points(m_spatial_point_storage.getPossibleReachablePoints(reference_point, m_analysis_configuration.r_max));
std::vector<AnalysisPoint> possible_reachable_points;
cacheReachablePoints(reference_point, possible_reachable_points);
return calculate_strength(reference_point, possible_reachable_points);
}
float MultiDistributionReproducer::calculate_strength(const AnalysisPoint & candidate_point, const std::vector<AnalysisPoint> & reachable_points)
{
float strength(1.0f);
QLineF line;
line.setP1(candidate_point.getCenter());
std::vector<AnalysisPoint> existing_points;
// select out only those points that have the same distribution, otherwise causes issues with matches not being satisfied
for(auto it: reachable_points)
{
if(m_cmap->equivDescriptor(m_cmap->getSynthDescriptor(candidate_point.getCenter().x(), candidate_point.getCenter().y()),
m_cmap->getSynthDescriptor(it.getCenter().x(), it.getCenter().y())))
existing_points.push_back(it);
}
// if((int) existing_points.size() != (int) reachable_points.size())
// boundcount++;
CategoryProperties category_properties (m_cmap->lookupSynthDistrib(candidate_point.getCenter().x(), candidate_point.getCenter().y())->getCategories().find(candidate_point.getCategoryId())->second);
std::set<int> dependent_category_ids(category_properties.m_header.category_dependent_ids);
bool dependencyMet = (dependent_category_ids.size() == 0);
const float candidatePointRadius = candidate_point.getRadius();
for(const AnalysisPoint & existing_point : existing_points)
{
line.setP2(existing_point.getCenter());
float distance = line.length();
// perform strong canopy intersection test here
if(distance < candidatePointRadius)
{
strength = 0;
return strength;
}
// Get the pair correlation
const RadialDistribution * radial_distribution( get_radial_distribution(candidate_point, existing_point.getCategoryId(), candidate_point.getCategoryId()) );
if(radial_distribution != nullptr) // if there is no correlation then strength is ignored
{
const float existingPointRadius = existing_point.getRadius();
if(distance > existingPointRadius+candidatePointRadius)
{
distance -= (existingPointRadius+candidatePointRadius);
// distance = (float) sqrt(distance); //?
int r_bracket ( RadialDistributionUtils::getRBracket(distance, m_analysis_configuration.r_min, m_analysis_configuration.r_diff) );
if(r_bracket < m_analysis_configuration.r_max)
{
float r(radial_distribution->m_data.find(r_bracket)->second);
strength *= r;
}
}
else // Shaded
{
// assumes candidatePointRadius < existingPointsRadius because it is a smaller plant
// But actually this may not be the case, depending on canopy spread
dependencyMet = dependencyMet || std::find(dependent_category_ids.begin(), dependent_category_ids.end(), existing_point.getCategoryId()) != dependent_category_ids.end();
//?
if(distance > existingPointRadius) // Less than half shaded
{
strength *= radial_distribution->m_less_than_half_shaded_distribution;
}
else if (distance > existingPointRadius - candidatePointRadius) // More than half, less than full
{
strength *= radial_distribution->m_more_than_half_shaded_distribution;
}
else // Fully shaded
{
strength *= radial_distribution->m_fully_shaded_distribution;
}
}
if(strength == 0) // Optimization. It will always be zero
return strength;
}
}
//return dependencyMet ? strength : 0;
return strength;
}
const RadialDistribution * MultiDistributionReproducer::get_radial_distribution(const AnalysisPoint & reference_point, int reference_category, int target_category)
{
// auto pair_correlation_it (m_pair_correlations.find(std::pair<int,int>(reference_category, target_category)));
auto pair_correlation_it (m_cmap->lookupSynthDistrib(reference_point.getCenter().x(), reference_point.getCenter().y())->getCorrelations().find(std::pair<int,int>(reference_category, target_category)));
// if( pair_correlation_it == m_pair_correlations.end())
if( pair_correlation_it == m_cmap->lookupSynthDistrib(reference_point.getCenter().x(), reference_point.getCenter().y())->getCorrelations().end())
{
// std::cerr << "FAILED TO FIND PAIR CORRELATION DATA! between " << reference_category << " and " << target_category << std::endl;
// now allowed simply ignore
return nullptr;
}
return &pair_correlation_it->second;
}
| 61,647
|
C++
|
.cpp
| 1,313
| 39.093679
| 274
| 0.635489
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,209
|
speciesColoursWindow.cpp
|
jgain_EcoLearn/EcoSynth/viewer/speciesColoursWindow.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "speciesColoursWindow.h"
#include <QLabel>
#include <QPixmap>
#include <QGridLayout>
SpeciesColoursWindow::SpeciesColoursWindow(QWidget *parent, const data_importer::common_data &cdata)
: QWidget(parent, Qt::Window)
{
QGridLayout *gridLayout = new QGridLayout;
int rowidx = 0;
for (auto &specpair : cdata.canopy_and_under_species)
{
const data_importer::species &spec = specpair.second;
int id = specpair.first;
std::string name = spec.name;
float r = spec.basecol[0];
float g = spec.basecol[1];
float b = spec.basecol[2];
QLabel *idlabel = new QLabel(std::to_string(id).c_str());
QLabel *namelabel = new QLabel(name.c_str());
QLabel *colourLabel = new QLabel;
QPixmap colimage(30, 30);
colimage.fill(QColor(r * 255, g * 255, b * 255));
colourLabel->setPixmap(colimage);
gridLayout->addWidget(idlabel, rowidx, 0);
gridLayout->addWidget(namelabel, rowidx, 1);
gridLayout->addWidget(colourLabel, rowidx, 2);
rowidx++;
}
setLayout(gridLayout);
}
void SpeciesColoursWindow::display()
{
this->show();
}
void SpeciesColoursWindow::hide()
{
this->hide();
}
| 2,178
|
C++
|
.cpp
| 57
| 33.789474
| 100
| 0.642315
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,210
|
sim.cpp
|
jgain_EcoLearn/EcoSynth/viewer/sim.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <algorithm>
#include "sim.h"
#include "data_importer/data_importer.h"
#include "ClusterMatrices.h"
#include <QLabel>
////
// MapSimCell
///
void MapSimCell::initMap()
{
smap.clear();
smap.resize(gx*gy);
for(int c = 0; c < gx*gy; c++) // empty cells are always sorted
{
smap[c].canopysorted = true;
smap[c].rootsorted = true;
}
}
void MapSimCell::inscribe(int plntidx, float px, float py, float rcanopy, float rroot)
{
float grx, gry, grcanopy, grroot, rmax, distsq, grcanopysq, grrootsq;
// assumes that plant index is not already inscribed in the simulation grid
// convert to sim grid coordinates
grx = convert(px);
gry = convert(py);
grcanopy = convert(rcanopy);
grroot = convert(rroot);
grcanopysq = grcanopy * grcanopy;
grrootsq = grroot * grroot;
rmax = fmax(grroot, grcanopy);
for(int x = (int) grx-rmax; x <= (int) grx+rmax; x++)
for(int y = (int) gry-rmax; y <= (int) gry+rmax; y++)
{
PlntInCell pic;
if(ingrid(x,y))
{
pic.hght = 0.0f; // height will be instantiated later on demand
pic.idx = plntidx;
float delx = (float) x-grx;
float dely = (float) y-gry;
distsq = delx*delx + dely*dely;
if(distsq <= grcanopysq)
{
get(x,y)->canopies.push_back(pic);
if((int) get(x,y)->canopies.size() > 1)
get(x,y)->canopysorted = false;
}
if(distsq <= grrootsq)
{
get(x,y)->roots.push_back(pic);
if((int) get(x,y)->roots.size() > 1)
get(x,y)->rootsorted = false;
}
}
}
}
void MapSimCell::expand(int plntidx, float px, float py, float prevrcanopy, float prevrroot, float newrcanopy, float newrroot)
{
float grx, gry, gprevrcanopy, gprevrroot, gnewrcanopy, gnewrroot, rmax, distsq, gprevrcanopysq, gprevrrootsq, gnewrcanopysq, gnewrrootsq;
// assumes that plant index is not already inscribed in the simulation grid
// convert to sim grid coordinates
grx = convert(px);
gry = convert(py);
gprevrcanopy = convert(prevrcanopy);
gprevrroot = convert(prevrroot);
gnewrcanopy = convert(newrcanopy);
gnewrroot = convert(newrroot);
gprevrcanopysq = gprevrcanopy * gprevrcanopy;
gprevrrootsq = gprevrroot * gprevrroot;
gnewrcanopysq = gnewrcanopy * gnewrcanopy;
gnewrrootsq = gnewrroot * gnewrroot;
rmax = fmax(gnewrroot, gnewrcanopy);
for(int x = (int) grx-rmax; x <= (int) grx+rmax; x++)
for(int y = (int) gry-rmax; y <= (int) gry+rmax; y++)
{
PlntInCell pic;
if(ingrid(x,y))
{
pic.hght = 0.0f; // height will be instantiated later on demand
pic.idx = plntidx;
float delx = (float) x-grx;
float dely = (float) y-gry;
distsq = delx*delx + dely*dely;
if(distsq <= gnewrcanopysq && distsq > gprevrcanopysq)
{
get(x,y)->canopies.push_back(pic);
if((int) get(x,y)->canopies.size() > 1)
get(x,y)->canopysorted = false;
}
if(distsq <= gnewrrootsq && distsq > gprevrrootsq)
{
get(x,y)->roots.push_back(pic);
if((int) get(x,y)->roots.size() > 1)
get(x,y)->rootsorted = false;
}
}
}
}
float cmpHeight(PlntInCell i, PlntInCell j)
{
return i.hght > j.hght;
}
void MapSimCell::traverse(std::vector<SimPlant> *plnts, Biome * biome, MapFloat * sun, MapFloat * wet)
{
plntpop = plnts;
// clear sunlight and moisture plant pools
for(int p = 0; p < (int) plntpop->size(); p++)
{
SimPlant * plnt = &(* plntpop)[p];
if(plnt->state == PlantSimState::ALIVE)
{
plnt->sunlight = 0.0f;
plnt->water = 0.0f;
plnt->sunlightcnt = 0;
plnt->watercnt = 0;
}
}
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
// sort canopy trees by height if necessary
if(!get(x,y)->canopysorted)
{
// update heights
for(int p = 0; p < (int) get(x,y)->canopies.size(); p++)
get(x,y)->canopies[p].hght = (* plntpop)[get(x,y)->canopies[p].idx].height;
std::sort(get(x,y)->canopies.begin(), get(x,y)->canopies.end(), cmpHeight);
get(x,y)->canopysorted = true;
}
// JGFIX - flag empty cells as possible seeding candidates
float sunlight = sun->get(x/step, y/step);
// traverse trees by height supplying and reducing sunlight
for(int p = 0; p < (int) smap[flatten(x,y)].canopies.size(); p++)
{
if((* plntpop)[get(x,y)->canopies[p].idx].state != PlantSimState::DEAD)
{
(* plntpop)[get(x,y)->canopies[p].idx].sunlight += sunlight;
(* plntpop)[get(x,y)->canopies[p].idx].sunlightcnt++;
// reduce sunlight by alpha of current plant
sunlight *= biome->getAlpha((* plntpop)[get(x,y)->canopies[p].idx].pft);
}
}
// sort root trees by height if necessary
if(!get(x,y)->rootsorted)
{
// update heights
for(int p = 0; p < (int) get(x,y)->roots.size(); p++)
get(x,y)->roots[p].hght = (* plntpop)[get(x,y)->roots[p].idx].height;
std::sort(get(x,y)->roots.begin(), get(x,y)->roots.end(), cmpHeight);
get(x,y)->rootsorted = true;
}
float moisture = wet->get(x/step, y/step);
float watershare;
int livecnt = 0;
// traverse trees by height (proxy for root depth) supplying and reducing moisture
for(int p = 0; p < (int) smap[flatten(x,y)].roots.size(); p++)
{
if((* plntpop)[get(x,y)->roots[p].idx].state != PlantSimState::DEAD)
{ // plants grab min ideal
watershare = fmin(moisture, biome->getMinIdealMoisture((* plntpop)[get(x,y)->roots[p].idx].pft));
(* plntpop)[get(x,y)->roots[p].idx].water += watershare;
(* plntpop)[get(x,y)->roots[p].idx].watercnt++;
moisture -= watershare;
livecnt++;
}
}
// remainder spread equally
if(moisture > 0.0f)
{
watershare = moisture / (float) livecnt;
for(int p = 0; p < (int) smap[flatten(x,y)].roots.size(); p++)
if((* plntpop)[get(x,y)->roots[p].idx].state != PlantSimState::DEAD)
(* plntpop)[get(x,y)->roots[p].idx].water += watershare;
}
}
}
void MapSimCell::visualize(QImage * visimg, std::vector<SimPlant> *plnts)
{
int numplnts = (int) plnts->size();
std::vector<QColor> plntcols;
// create table of random colours
for(int p = 0; p < numplnts; p++)
{
int r = 256;
while(r > 255)
r = std::rand()/(RAND_MAX/255);
int g = 256;
while(g > 255)
g = std::rand()/(RAND_MAX/255);
int b = 256;
while(b > 255)
b = std::rand()/(RAND_MAX/255);
QColor col = QColor(r, g, b);
plntcols.push_back(col);
}
// create image corresponding to MapSim
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
// canopies
for(int i = 0; i < (int) get(x, y)->canopies.size(); i++)
{
for(int p = 1; p < 10; p++)
for(int q = 1; q < 10; q++)
visimg->setPixelColor(x*10+p, y*10+q, plntcols[get(x, y)->canopies[i].idx]);
}
// roots
/*
for(int i = 0; i < (int) get(x, y)->roots.size(); i++)
{
}*/
}
}
bool MapSimCell::unitTests(QImage * visimg)
{
bool valid = true;
std::vector<SimPlant> testplnts;
SimPlant plnt;
setDim(50, 50, 5);
// test simple placement of single plant, at domain center reaching to boundary
inscribe(0, 5.0f, 5.0f, 5.0f, 2.0f);
plnt.height = 10.0f;
testplnts.push_back(plnt);
// add shorter plant in center
inscribe(1, 6.15f, 4.15f, 2.0f, 1.0f);
plnt.height = 5.0f;
testplnts.push_back(plnt);
// grow shorter plant
expand(1, 6.15f, 4.15f, 2.0f, 1.0f, 3.0f, 1.0f);
visualize(visimg, &testplnts);
PlntInCell p;
p.idx = 2;
get(0,0)->canopies.push_back(p);
get(0,0)->canopies.push_back(p);
if(valid)
valid = validate(&testplnts);
cerr << "validity status = " << valid << endl;
return valid;
}
bool MapSimCell::validate(std::vector<SimPlant> *plnts)
{
bool valid = true;
// a given plant index must only appear once per cell
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
// canopies
for(int i = 0; i < (int) get(x, y)->canopies.size(); i++)
for(int j = i+1; j < (int) get(x, y)->canopies.size(); j++)
if(get(x, y)->canopies[i].idx == get(x,y)->canopies[j].idx)
{
valid = false;
cerr << "MapSimCell validity: duplicate canopy index " << get(x,y)->canopies[i].idx << " at position " << i << " and " << j << endl;
}
// roots
for(int i = 0; i < (int) get(x, y)->roots.size(); i++)
for(int j = i+1; j < (int) get(x, y)->roots.size(); j++)
if(get(x, y)->roots[i].idx == get(x,y)->roots[j].idx)
{
valid = false;
cerr << "MapSimCell validity: duplicate root index " << get(x,y)->roots[i].idx << " at position " << i << " and " << j << endl;
}
}
// static plants do not appear in the canopy list
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
// canopies
for(int i = 0; i < (int) get(x, y)->canopies.size(); i++)
if((* plnts)[get(x, y)->canopies[i].idx].state == PlantSimState::STATIC)
{
valid = false;
cerr << "MapSimCell validity: static plant " << get(x,y)->canopies[i].idx << " in canopy list at position " << i << endl;
}
}
// sorted is true for all canopy and root lists with less than 2 elements
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
// canopies
if((int) get(x,y)->canopies.size() < 2 && !get(x,y)->canopysorted)
{
valid = false;
cerr << "MapSimCell validity: canopy list of less than 2 marked as unsorted in canopy list at position " << x << " " << y << endl;
}
// roots
if((int) get(x,y)->roots.size() < 2 && !get(x,y)->rootsorted)
{
valid = false;
cerr << "MapSimCell validity: canopy list of less than 2 marked as unsorted in root list at position " << x << " " << y << endl;
}
}
return valid;
}
////
// Simulation
///
void Simulation::initSim(int dx, int dy, int subcellfactor)
{
simcells.setDim(dx*subcellfactor, dy*subcellfactor, subcellfactor);
for(int m = 0; m < 12; m++)
{
MapFloat sun, mst, sunland;
sun.setDim(dx, dy);
mst.setDim(dx, dy);
sunland.setDim(dx, dy);
sunlight.push_back(sun);
landsun.push_back(sunland);
moisture.push_back(mst);
temperature.push_back(0.0f);
cloudiness.push_back(0.0f);
rainfall.push_back(0.0f);
}
slope.setDim(dx, dy);
sunsim = new SunLight();
dice = new DiceRoller(0,1000);
time = 0.0f;
}
void Simulation::delSim()
{
simcells.delMap();
for(int m = 0; m < 12; m++)
{
sunlight[m].delMap();
moisture[m].delMap();
}
plntpop.clear();
temperature.clear();
cloudiness.clear();
rainfall.clear();
slope.delMap();
if(sunsim) delete sunsim;
time = 0.0f;
}
bool Simulation::death(int pind, float stress)
{
bool dead;
// age and stress factors are combined using a probabilistic apprach
// use constant background mortaility to model age effects
// use bioclamatic envelope and a carbohydrate pool to model stress effects
// background mortality
float ageFactor = 1.0f / biome->getPFType(plntpop[pind].pft)->maxage;
float age = 1.0f - pow(0.05f, ageFactor);
// stress mortality. stress score is remainder after effects of carbohydrate pool accounted for
float p = 1000.0f * (age + stress);
// test against a uniform random variable in [0,1000]
dead = dice->generate() < (int) p;
if(dead) // if plant has died change its state
plntpop[pind].state = PlantSimState::DEAD;
return dead;
}
void Simulation::growth(int pind, float vitality)
{
PFType * pft;
if(vitality > 0.0f) // also check month range to see if it falls in growing season
{
// apply growth equation for particular pft moderated by vitality
pft = biome->getPFType(plntpop[pind].pft);
float maxgrowth = pft->grow_m * (pft->grow_c1 + exp(pft->grow_c2)) / (float) (5 * pft->grow_months); // scale from 5 years down to 1 month
plntpop[pind].height += vitality * maxgrowth;
// use allometries for canopy and root
plntpop[pind].canopy = exp(pft->alm_c1 + pft->alm_m * log(plntpop[pind].height)); // r = e ** (c1 + m ln(h))
plntpop[pind].root = plntpop[pind].canopy * pft->alm_rootmult;
}
}
void Simulation::simStep(int month)
{
// traverse all cells contributing moisture and sunlight to plant pool
// simcells.traverse(plntpop);
// calculate viability
for(int p = 0; p < (int) plntpop.size(); p++)
{
float sun, wet, temp, slope, str;
float pool, stress = 0.0f, vitality = 0.0f;
sun = plntpop[p].sunlight / (float) plntpop[p].sunlightcnt; // average sunlight
wet = plntpop[p].water / (float) plntpop[p].watercnt; // average moisture
temp = getTemperature(plntpop[p].gx, plntpop[p].gy, month);
slope = getSlopeMap()->get(plntpop[p].gx, plntpop[p].gy);
str = biome->viability(plntpop[p].pft, sun, wet, temp, slope);
// account for plant reserve pool
pool = plntpop[p].reserves+str;
if(pool < 0.0f) // potential death due to stress
{
stress = -1.0f * pool;
pool = 0.0f;
}
else if(pool > reservecapacity) // reserves are full so growth is possible
{
vitality = pool - reservecapacity;
pool = reservecapacity;
}
plntpop[p].reserves = pool;
// run growth, death, seeding processes
if(!death(p, stress)) // check for death from old age or stress
{
// use vitality to determine growth based on allometry
// but check if this falls in the growing season
growth(p, vitality);
plntpop[p].age += 1;
}
}
}
Simulation::Simulation(Terrain * terrain, Biome * simbiome, int subcellfactor)
{
int dx, dy;
set_terrain(terrain);
biome = simbiome;
ter->getGridDim(dx, dy);
initSim(dx, dy, subcellfactor);
calcSlope();
set_rocks();
}
void Simulation::set_terrain(Terrain *terrain)
{
ter = terrain;
calcSlope(); // all we need for slopemap is terrain, so we can compute it so long...?
}
/*
*
* calculates where there should be rocks, based on slope.
* REQUIRED: slope map
*/
void Simulation::set_rocks()
{
int tx, ty;
int dx, dy;
slope.getDim(dx, dy);
ter->getGridDim(tx, ty);
if (dx * dy <= 0 || dx != tx || dy != ty)
{
throw std::runtime_error("Slope map needs to be computed first before the rock map can be computed");
}
rocks.setDim(dx, dy);
for (int y = 0; y < dy; y++)
{
for (int x = 0; x < dx; x++)
{
if (slope.get(x, y) > 40.0f)
rocks.set(x, y, 1.0f);
else
rocks.set(x, y, 0.0f);
}
}
}
MapFloat * Simulation::get_rocks()
{
return &rocks;
}
void Simulation::calcSunlight(GLSun * glsun, int minutestep, int nsamples)
{
Timer t;
t.start();
sunsim->setLatitude(ter->getLatitude());
sunsim->setNorthOrientation(Vector(0.0f, 0.0f, -1.0f));
sunsim->setTerrainDimensions(ter);
MapFloat diffusemap;
std::vector<float> sunhours;
glsun->bind();
sunsim->projectSun(ter, sunlight, glsun, sunhours, minutestep);
sunsim->diffuseSun(ter, &diffusemap, glsun, nsamples);
sunsim->mergeSun(sunlight, &diffusemap, cloudiness, sunhours);
t.stop();
cerr << "SUNLIGHT SIMULATION TOOK " << t.peek() << "s IN TOTAL" << endl;
}
/*
void Simulation::calc_adaptsun(const std::vector<basic_tree> &trees, const data_importer::common_data &cdata)
{
int dx, dy;
average_adaptsun.getDim(dx, dy);
{
int lx, ly;
average_landsun.getDim(lx, ly);
if (dx != lx || dy != ly)
{
average_adaptsun.setDim(lx, ly);
dx = lx, dy = ly;
}
}
float *datbegin = average_adaptsun.data();
memcpy(datbegin, average_landsun.data(), sizeof(float) * dx * dy);
auto trim = [](int &v, int dim) { if (v < 0) v = 0; if (v >= dim) v = dim - 1; };
for (auto &t : trees)
{
int sx = (t.x - t.radius);
int ex = (t.x + t.radius);
int sy = (t.y - t.radius);
int ey = (t.y + t.radius);
trim(sx, dx);
trim(ex, dx);
trim(sy, dy);
trim(ey, dy);
int maxradsq = t.radius * t.radius;
for (int y = sy; y <= ey; y++)
{
for (int x = sx; x < ex; x++)
{
int d = (t.x - x) * (t.x - x) + (t.y - y) * (t.y - y);
if (d <= maxradsq)
{
float alpha = cdata.canopy_and_under_species.at(t.species).alpha;
average_adaptsun.set(x, y, average_adaptsun.get(x, y) * (1.0f - alpha));
}
}
}
}
}
*/
void Simulation::calc_adaptsun(const std::vector<basic_tree> &trees, const data_importer::common_data &cdata, float rw, float rh)
{
int dx, dy;
average_adaptsun.getDim(dx, dy);
{
int lx, ly;
average_landsun.getDim(lx, ly);
if (dx != lx || dy != ly)
{
average_adaptsun.setDim(lx, ly);
dx = lx, dy = ly;
}
}
float *datbegin = average_adaptsun.data();
memcpy(datbegin, average_landsun.data(), sizeof(float) * dx * dy);
auto alphamap = create_alphamap(trees, cdata, rw, rh);
for (int y = 0; y < dy; y++)
{
for (int x = 0; x < dx; x++)
{
average_adaptsun.set(x, y, average_adaptsun.get(x, y) * (1.0f - alphamap.get(x, y)));
}
}
}
int Simulation::inscribe_alpha(const basic_tree &plnt, float plntalpha, ValueGridMap<float> &alphamap)
{
const xy<int> gridcoords = alphamap.togrid_safe(plnt.x, plnt.y);
const xy<int> gridstart = alphamap.togrid_safe(plnt.x - plnt.radius, plnt.y - plnt.radius);
const xy<int> gridend = alphamap.togrid_safe(plnt.x + plnt.radius, plnt.y + plnt.radius);
const int gridrad = alphamap.togrid_safe(plnt.radius, plnt.radius).x;
float avggdist = 0.0f;
int nwrite = 0;
for (int x = gridstart.x; x <= gridend.x; x++)
{
for (int y = gridstart.y; y <= gridend.y; y++)
{
float griddist = (x - gridcoords.x) * (x - gridcoords.x) + (y - gridcoords.y) * (y - gridcoords.y);
if (griddist <= ((float) gridrad * gridrad) && alphamap.get(x, y) < plntalpha)
{
alphamap.set(x, y, plntalpha);
nwrite++;
avggdist += sqrt(griddist);
}
}
}
/*
if (nwrite == 0)
{
std::cout << "no writes made. gridrad: " << gridrad << ", ";
std::cout << "avg griddist: " << avggdist << ", ";
std::cout << "gridstart: " << gridstart.x << ", " << gridstart.y << std::endl;
}
*/
return nwrite;
}
ValueGridMap<float> Simulation::create_alphamap(const std::vector<basic_tree> &trees, const data_importer::common_data &cdata, float rw, float rh)
{
ValueGridMap<float> alphamap;
alphamap.setDim(average_landsun);
alphamap.setDimReal(rw, rh);
alphamap.fill(0.0f);
for (const auto &plnt : trees)
{
float alpha = cdata.canopy_and_under_species.at(plnt.species).alpha;
int nwrite = inscribe_alpha(plnt, alpha, alphamap);
//if (nwrite == 0)
// std::cout << "Number of cells written with alpha " << alpha << ": " << nwrite << std::endl;
}
int gw, gh;
alphamap.getDim(gw, gh);
int smrad = 15;
auto alphamap_copy = alphamap;
for (int y = 0; y < gh; y++)
{
for (int x = 0; x < gw; x++)
{
int count = 0;
float sum = 0.0f;
int sx = common_funcs::trimret(0, gw - 1, x - smrad);
int ex = common_funcs::trimret(0, gw - 1, x + smrad);
int sy = common_funcs::trimret(0, gh - 1, y - smrad);
int ey = common_funcs::trimret(0, gh - 1, y + smrad);
for (int cx = sx; cx <= ex; cx++)
{
for (int cy = sy; cy <= ey; cy++)
{
int gdist = (cx - x) * (cx - x) + (cy - y) * (cy - y);
if (gdist <= smrad * smrad)
{
count++;
sum += alphamap_copy.get(cx, cy);
}
}
}
if (count > 0)
{
sum /= count;
alphamap.set(x, y, sum);
}
else // impossible for count == 0, so throw error
{
throw std::runtime_error("In Simulation::create_alphamap, count is zero in smoothing. It cannot be. This indicates a bug");
}
}
}
return alphamap;
}
void Simulation::calcSunlightSelfShadowOnly(GLSun *glsun)
{
Timer t;
t.start();
sunsim->setLatitude(ter->getLatitude());
sunsim->setNorthOrientation(Vector(0.0f, 0.0f, -1.0f));
sunsim->setTerrainDimensions(ter);
MapFloat diffusemap;
std::vector<float> sunhours;
//glsun->bind();
sunsim->projectSunSelfShadowOnly(ter, sunlight, glsun, sunhours, 30);
t.stop();
cerr << "SUNLIGHT SIMULATION TOOK " << t.peek() << "s IN TOTAL" << endl;
}
void Simulation::calcMoisture()
{
Timer t;
MoistureSim wet;
t.start();
// alpine params
// wet.simSoilCycle(ter, &slope, rainfall, 10.0f, (float) slope, 0.25f, 120.0f, 200.0f, 15000.0f, moisture);
// savannah params
// wet.simSoilCycle(ter, &slope, rainfall, 20.0f, (float) slope, 0.3f, 180.0f, 300.0f, 120000.0f, moisture);
// canyon params
// wet.simSoilCycle(ter, &slope, rainfall, 5.0f, (float) slope, 0.5f, 50.0f, 100.0f, 10000.0f, moisture);
// wet canyon params
// wet.simSoilCycle(ter, &slope, rainfall, 5.0f, (float) slope, 0.5f, 100.0f, 180.0f, 5000.0f, moisture);
// med params
// wet.simSoilCycle(ter, &slope, rainfall, 5.0f, (float) slope, 0.25f, 100.0f, 180.0f, 5000.0f, moisture);
wet.simSoilCycle(ter, &slope, rainfall, biome->slopethresh, biome->slopemax, biome->evaporation,
biome->runofflevel, biome->soilsaturation, biome->waterlevel, moisture);
t.stop();
cerr << "MOISTURE SIMULATION TOOK " << t.peek() << "s IN TOTAL" << endl;
}
void Simulation::calc_average_monthly_map(std::vector<MapFloat> &mmap, MapFloat &avgmap)
{
int sizex, sizey;
mmap[0].getDim(sizex, sizey);
avgmap.setDim(sizex, sizey);
avgmap.fill(0.0f);
for (int m = 0; m < 12; m++)
{
for (int x = 0; x < sizex; x++)
{
for (int y = 0; y < sizey; y++)
{
avgmap.set(x, y, avgmap.get(x, y) + mmap[m].get(x, y));
}
}
}
for (int x = 0; x < sizex; x++)
{
for (int y = 0; y < sizey; y++)
{
avgmap.set(x, y, avgmap.get(x, y) / 12.0f);
}
}
}
void Simulation::calc_average_sunlight_map()
{
calc_average_monthly_map(sunlight, average_sunlight);
}
void Simulation::calc_average_landsun_map()
{
calc_average_monthly_map(landsun, average_landsun);
}
void Simulation::calc_average_moisture_map()
{
calc_average_monthly_map(moisture, average_moisture);
}
void Simulation::calc_temperature_map()
{
int xsize, ysize;
ter->getGridDim(xsize, ysize);
temperate_mapfloat.setDim(xsize, ysize);
float avg_temp = 0.0f;
for (auto &t : temperature)
{
avg_temp += t;
}
avg_temp /= 12.0f;
for (int x = 0; x < xsize; x++)
{
for (int y = 0; y < ysize; y++)
{
float val = avg_temp - ter->getHeight(x, y) / 1000.0f * lapserate;
temperate_mapfloat.set(x, y, val);
}
}
}
void Simulation::copy_temperature_map(const ValueGridMap<float> &tempmap)
{
int xsize, ysize;
tempmap.getDim(xsize, ysize);
temperate_mapfloat.setDim(xsize, ysize);
memcpy(temperate_mapfloat.data(), tempmap.data(), sizeof(float) * xsize * ysize);
}
bool Simulation::readSun(std::string filename)
{
bool result = readMonthlyMap(filename, sunlight);
if (result)
calc_average_sunlight_map();
return result;
}
bool Simulation::readLandscapeSun(std::string filename)
{
bool result = readMonthlyMap(filename, landsun);
if (result)
calc_average_landsun_map(); // this is probably obsolete and slows down the interface - ditto for readSun
return result;
}
void Simulation::copy_map(const ValueGridMap<float> &srcmap, abiotic_factor f)
{
MapFloat *dest;
if (f == abiotic_factor::SUN)
{
dest = &average_landsun;
average_adaptsun.setDim(srcmap);
}
else if (f == abiotic_factor::MOISTURE)
{
dest = &average_moisture;
}
else return;
int xsize, ysize;
srcmap.getDim(xsize, ysize);
dest->setDim(xsize, ysize);
memcpy(dest->data(), srcmap.data(), sizeof(float) * xsize * ysize);
if (f == abiotic_factor::SUN)
{
memcpy(average_adaptsun.data(), srcmap.data(), sizeof(float) * xsize * ysize);
}
}
bool Simulation::readMoisture(std::string filename)
{
bool result = readMonthlyMap(filename, moisture);
calc_average_moisture_map();
return result;
}
bool Simulation::readMonthlyMap(std::string filename, std::vector<MapFloat> &monthly)
{
float val;
ifstream infile;
int gx, gy, dx, dy;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> gx >> gy;
ter->getGridDim(dx, dy);
if((gx != dx) || (gy != dy))
cerr << "Error Simulation::readMonthlyMap: map dimensions do not match terrain" << endl;
for(int m = 0; m < 12; m++)
monthly[m].setDim(gx, gy);
for (int y = 0; y < gy; y++)
for (int x = 0; x < gx; x++)
for(int m = 0; m < 12; m++)
{
infile >> val;
monthly[m].set(x, y, val);
}
infile.close();
return true;
}
else
{
cerr << "Error Simulation::readMonthlyMap: unable to open file" << filename << endl;
return false;
}
}
bool Simulation::writeMonthlyMap(std::string filename, std::vector<MapFloat> &monthly)
{
int gx, gy;
ofstream outfile;
monthly[0].getDim(gx, gy);
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
outfile << gx << " " << gy << " " << 0.9144 << endl;
for (int y = 0; y < gy; y++)
for (int x = 0; x < gx; x++)
for(int m = 0; m < 12; m++)
outfile << monthly[m].get(x, y) << " ";
outfile << endl;
outfile.close();
return true;
}
else
{
cerr << "Error Simulation::writeMonthlyMap:unable to open file " << filename << endl;
return true;
}
}
bool Simulation::readClimate(std::string filename)
{
float elv, val;
ifstream infile;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> elv;
// temperature values
for(int m = 0; m < 12; m++)
{
infile >> val;
temperature[m] = val - elv / 1000.0f * lapserate;
}
// sky clarity
for(int m = 0; m < 12; m++)
{
infile >> val;
cloudiness[m] = 1.0f - val;
}
// rainfall
for(int m = 0; m < 12; m++)
{
infile >> val;
rainfall[m] = val;
}
infile.close();
return true;
}
else
{
cerr << "Error Simulation::readClimate: unable to open file" << filename << endl;
return false;
}
}
float Simulation::getTemperature(int x, int y, int mth)
{
return temperature[mth] - ter->getHeight(x, y) / 1000.0f * lapserate;
}
void Simulation::calcSlope()
{
int dx, dy;
Vector up, n;
// slope is dot product of terrain normal and up vector
up = Vector(0.0f, 1.0f, 0.0f);
ter->getGridDim(dx, dy);
slope.setDim(dx, dy);
slope.fill(0.0f);
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
ter->getNormal(x, y, n);
float rad = acos(up.dot(n));
float deg = RAD2DEG * rad;
slope.set(y, x, deg);
//slope.set(x, y, deg);
}
}
void Simulation::importCanopy(EcoSystem * eco)
{
std::vector<Plant> plnts;
eco->pickAllPlants(ter); // must gather plants before vectorizing
plntpop.clear();
// iterate over plant functional types
for(int pft = 0; pft < biome->numPFTypes(); pft++)
{
eco->getPlants()->vectoriseByPFT(pft, plnts);
for(int p = 0; p < (int) plnts.size(); p++)
{
SimPlant sp;
sp.state = PlantSimState::STATIC;
sp.age = 0.0f; // PFTSTATS: derive from height via pft allometry
sp.pos = plnts[p].pos;
sp.height = plnts[p].height;
sp.canopy = plnts[p].canopy;
sp.root = 1.0f; // PFTSTATS: derive from height via pft allometry
sp.reserves = reservecapacity;
sp.col = plnts[p].col;
sp.pft = pft;
sp.water = 0.0f;
sp.sunlight = 0.0f;
plntpop.push_back(sp);
}
}
}
void Simulation::exportUnderstory(EcoSystem * eco)
{
for(int n = 0; n < 2; n++)
{
PlantGrid * outplnts = eco->getNiche(n);
outplnts->clear();
// canopy into niche 0, understory into niche 1
for(int p = 0; p < (int) plntpop.size(); p++)
{
Plant op;
bool place;
if(n == 0) // only include static plants in niche 0
place = (plntpop[p].state == PlantSimState::STATIC);
else // only include live plants in niche 1
place = (plntpop[p].state == PlantSimState::ALIVE);
if(place)
{
op.canopy = plntpop[p].canopy;
op.col = plntpop[p].col;
op.height = plntpop[p].height;
op.pos = plntpop[p].pos;
outplnts->placePlant(ter, plntpop[p].pft, op);
}
}
}
eco->pickAllPlants(ter); // gather all plants for display
}
bool Simulation::writeAssignSun(std::string filename)
{
int gx, gy;
ofstream outfile;
sunlight[0].getDim(gx, gy);
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
// sunlight
outfile << gx << " " << gy << " " << endl;
for (int x = 0; x < gx; x++)
for (int y = 0; y < gy; y++)
for(int m = 1; m < 2; m++)
outfile << sunlight[m].get(x, y) << " ";
outfile << endl;
// block plant placement
outfile << (gx / 3 * gy / 3) << endl;
cerr << "num trees = " << (gx / 3 * gy / 3) << endl;
int countt = 0;
for (int x = 0; x < gx; x+= 3)
for (int y = 0; y < gy; y+= 3)
{
// random position and size
int rx = x+dice->generate() % 3;
int ry = y+dice->generate() % 3;
if(rx >= gx)
rx = gx-1;
if(ry >= gy)
ry = gy-1;
int re = dice->generate() % 8 + 1;
outfile << rx << " " << ry << " " << re << endl;
countt++;
}
cerr << "actual num trees = " << countt << endl;
outfile << endl;
outfile.close();
return true;
}
else
{
cerr << "Error Simulation::writeMonthlyMap:unable to open file " << filename << endl;
return true;
}
}
void Simulation::pickInfo(int x, int y)
{
cerr << "Sunlight (Hrs): ";
//for(int m = 0; m < 12; m++)
// cerr << sunlight[m].get(x, y) << " ";
cerr << endl;
cerr << "Slope (rad): " << slope.get(x, y) << endl;
cerr << "Soil Moisture (mm): ";
for(int m = 0; m < 12; m++)
cerr << moisture[m].get(x, y) << " ";
cerr << endl;
cerr << "Temperature (C): ";
for(int m = 0; m < 12; m++)
cerr << getTemperature(x, y, m) << " ";
cerr << endl;
}
void Simulation::simulate(int delYears)
{
for(int y = 0; y < delYears; y++)
for(int m = 0; m < 12; m++)
simStep(m);
}
| 35,352
|
C++
|
.cpp
| 1,006
| 26.759443
| 156
| 0.536418
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,211
|
clusters.cpp
|
jgain_EcoLearn/EcoSynth/viewer/clusters.cpp
|
#include "clusters.h"
#include "grass.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
void Clusters::mapColours()
{
int maxval, maxind;
colmapping.resize((int) climits.size(), 0);
// put all cluster indices in a list
std::list<int> indices;
for(int i = 0; i < (int) climits.size(); i++)
indices.push_back(i);
// cluster 0 always maps to water
colmapping[0] = 1;
indices.remove(0);
/*
maxval = 0;
for(auto ind: indices)
{
if(climits[ind].avg.moisture[0] > maxval)
{
maxval = climits[ind].avg.moisture[0];
maxind = ind;
}
}
if(maxval > 1000)
{
colmapping[maxind] = 1;
indices.remove(maxind);
}*/
// A moisture rich cluster with avg moisture exceeding 200
maxval = 0;
for(auto ind: indices)
{
if(climits[ind].avg.moisture[0] > maxval)
{
maxval = climits[ind].avg.moisture[0];
maxind = ind;
}
}
if(maxval > 200)
{
colmapping[maxind] = 2;
indices.remove(maxind);
}
// The cluster with the steepest average slope
maxval = 0;
for(auto ind: indices)
{
if(climits[ind].avg.slope > maxval)
{
maxval = climits[ind].avg.slope;
maxind = ind;
}
}
if(maxval > 0)
{
colmapping[maxind] = 3;
indices.remove(maxind);
}
// The cluster with the highest average sunlight
maxval = 0;
for(auto ind: indices)
{
if(climits[ind].avg.sunlight[0] > maxval)
{
maxval = climits[ind].avg.sunlight[0];
maxind = ind;
}
}
if(maxval > 0)
{
colmapping[maxind] = 4;
indices.remove(maxind);
}
// The cluster with the lowest average sunlight
maxval = 20;
for(auto ind: indices)
{
if(climits[ind].avg.sunlight[0] < maxval)
{
maxval = climits[ind].avg.sunlight[0];
maxind = ind;
}
}
if(maxval < 5)
{
colmapping[maxind] = 5;
indices.remove(maxind);
}
// The remaining cluster with the highest temperature
maxval = 0;
for(auto ind: indices)
{
if(climits[ind].avg.temperature[1] > maxval)
{
maxval = climits[ind].avg.temperature[1];
maxind = ind;
}
}
if(maxval > 10)
{
colmapping[maxind] = 6;
indices.remove(maxind);
}
/*
// alpine colour assignment for X clusters
colmapping[0] = ;
colmapping[1] = ;
colmapping[2] = ;
etc
*/
// assign all other clusters with sequential values
int i = 7;
for(auto ind: indices)
{
colmapping[ind] = i;
i++;
}
// print out mapping table
cerr << "Colour Mapping Table" << endl;
for(auto col: colmapping)
cerr << col << " ";
cerr << endl;
}
bool Clusters::inBounds(int cidx, SampleDescriptor sd)
{
if(sd.slope < climits[cidx].min.slope || sd.slope > climits[cidx].max.slope)
return false;
if(sd.moisture[0] < climits[cidx].min.moisture[0] || sd.moisture[0] > climits[cidx].max.moisture[0])
return false;
if(sd.moisture[1] < climits[cidx].min.moisture[1] || sd.moisture[1] > climits[cidx].max.moisture[1])
return false;
if(sd.temperature[0] < climits[cidx].min.temperature[0] || sd.temperature[0] > climits[cidx].max.temperature[0])
return false;
if(sd.temperature[1] < climits[cidx].min.temperature[1] || sd.temperature[1] > climits[cidx].max.temperature[1])
return false;
if(sd.sunlight[0] < climits[cidx].min.sunlight[0] || sd.sunlight[0] > climits[cidx].max.sunlight[0])
return false;
if(sd.sunlight[1] < climits[cidx].min.sunlight[1] || sd.sunlight[1] > climits[cidx].max.sunlight[1])
return false;
// ignore age
return true;
}
bool Clusters::clipToBounds(int cidx, SampleDescriptor &sd)
{
if(inBounds(cidx, sd))
return true;
else
{
// clip
if(sd.slope < climits[cidx].min.slope)
sd.slope = climits[cidx].min.slope;
if(sd.slope > climits[cidx].max.slope)
sd.slope = climits[cidx].max.slope;
// TO DO: moisture can be more permissive due to local variation
if(sd.moisture[0] < climits[cidx].min.moisture[0])
sd.moisture[0] = climits[cidx].min.moisture[0];
if(sd.moisture[0] > climits[cidx].max.moisture[0])
sd.moisture[0] = climits[cidx].max.moisture[0];
if(sd.moisture[1] < climits[cidx].min.moisture[1])
sd.moisture[1] = climits[cidx].min.moisture[1];
if(sd.moisture[1] > climits[cidx].max.moisture[1])
sd.moisture[1] = climits[cidx].max.moisture[1];
if(sd.temperature[0] < climits[cidx].min.temperature[0])
sd.temperature[0] = climits[cidx].min.temperature[0];
if(sd.temperature[0] > climits[cidx].max.temperature[0])
sd.temperature[0] = climits[cidx].max.temperature[0];
if(sd.temperature[1] < climits[cidx].min.temperature[1])
sd.temperature[1] = climits[cidx].min.temperature[1];
if(sd.temperature[1] > climits[cidx].max.temperature[1])
sd.temperature[1] = climits[cidx].max.temperature[1];
if(sd.sunlight[0] < climits[cidx].min.sunlight[0])
sd.sunlight[0] = climits[cidx].min.sunlight[0];
if(sd.sunlight[0] > climits[cidx].max.sunlight[0])
sd.sunlight[0] = climits[cidx].max.sunlight[0];
if(sd.sunlight[1] < climits[cidx].min.sunlight[1])
sd.sunlight[1] = climits[cidx].min.sunlight[1];
if(sd.sunlight[1] > climits[cidx].max.sunlight[1])
sd.sunlight[1] = climits[cidx].max.sunlight[1];
}
return false;
}
bool Clusters::clipToMapBounds(int x, int y, SampleDescriptor &sd)
{
int cidx = clsmap->get(x, y); // lookup cluster index
clipToBounds(cidx, sd);
}
void Clusters::display()
{
int i = 0;
for(auto cit: climits)
{
cerr << "Cluster: " << i << endl;
cerr << "Slope: min " << cit.min.slope << ", max " << cit.max.slope << ", avg " << cit.avg.slope << endl;
cerr << "June Temp: min " << cit.min.temperature[1] << ", max " << cit.max.temperature[1] << ", avg " << cit.avg.temperature[1] << endl;
cerr << "Dec Temp: min " << cit.min.temperature[0] << ", max " << cit.max.temperature[0] << ", avg " << cit.avg.temperature[0] << endl;
cerr << "June Moisture: min " << cit.min.moisture[1] << ", max " << cit.max.moisture[1] << ", avg " << cit.avg.moisture[1] << endl;
cerr << "Dec Moisture: min " << cit.min.moisture[0] << ", max " << cit.max.moisture[0] << ", avg " << cit.avg.moisture[0] << endl;
cerr << "June Illumination: min " << cit.min.sunlight[1] << ", max " << cit.max.sunlight[1] << ", avg " << cit.avg.sunlight[1] << endl;
cerr << "Dec Illumination: min " << cit.min.sunlight[0] << ", max " << cit.max.sunlight[0] << ", avg " << cit.avg.sunlight[0] << endl;
cerr << endl;
i++;
}
}
bool Clusters::read(Terrain * ter, std::string clsname, std::string mapname)
{
ifstream infile;
int cidx;
// cluster 0 for open water
ConditionBounds cw;
cw.min.moisture[0] = 2000; cw.max.moisture[0] = 2000; cw.avg.moisture[0] = 2000;
cw.min.moisture[1] = 2000; cw.max.moisture[1] = 2000; cw.avg.moisture[1] = 2000;
climits.push_back(cw);
infile.open((char *) clsname.c_str(), ios_base::in);
if(infile.is_open())
{
int numclusters;
infile >> numclusters;
for(int i = 0; i < numclusters; i++)
{
ConditionBounds cb;
infile >> cidx;
if(i != cidx)
{
cerr << "Error ClusterLimits::read: corrupted file " << clsname << endl;
infile.close();
return false;
}
infile >> cb.min.temperature[1] >> cb.max.temperature[1] >> cb.avg.temperature[1];
infile >> cb.min.temperature[0] >> cb.max.temperature[0] >> cb.avg.temperature[0];
infile >> cb.min.moisture[1] >> cb.max.moisture[1] >> cb.avg.moisture[1];
infile >> cb.min.moisture[0] >> cb.max.moisture[0] >> cb.avg.moisture[0];
infile >> cb.min.sunlight[1] >> cb.max.sunlight[1] >> cb.avg.sunlight[1];
infile >> cb.min.sunlight[0] >> cb.max.sunlight[0] >> cb.avg.sunlight[0];
infile >> cb.min.slope >> cb.max.slope >> cb.avg.slope;
cb.min.age = 0; cb.max.age = 1000; cb.avg.age = 300; // even though these values should not be used
/*
if(i == 3)
{
cb.avg.slope = 0.0f;
cb.avg.temperature[0] = 12;
cb.avg.temperature[1] = 28;
cb.avg.moisture[0] = 119;
cb.avg.moisture[1] = 160;
cb.avg.sunlight[0] = 6;
cb.avg.sunlight[1] = 14;
cb.avg.age = 100;
}*/
climits.push_back(cb);
}
mapColours();
infile.close();
// now also read map
cerr << "mapname = " << mapname << endl;
// set dimensions to match terrain
int dx, dy;
ter->getGridDim(dx, dy);
clsmap->matchDim(dx, dy);
clsmap->load(mapname, TypeMapType::CLUSTER);
return true;
}
else
return false;
}
| 9,550
|
C++
|
.cpp
| 268
| 27.776119
| 144
| 0.564638
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,212
|
palette_base.cpp
|
jgain_EcoLearn/EcoSynth/viewer/palette_base.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected]) and K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "palette_base.h"
#include "glwidget.h"
#include <QDir>
#include <QGridLayout>
palette_base::palette_base(TypeMap *typemap, const std::vector<int> &btypes, QWidget *parent)
: QWidget(parent), /*nentries((int)*std::max_element(btypes.begin(), btypes.end()) + 1)*/ nentries(btypes.size()), selector(new QPushButton * [btypes.size()]),
typeSel(new BrushType [btypes.size()])
{
glparent = (GLWidget *) parent;
setAttribute(Qt::WA_StaticContents);
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
tmap = typemap;
addBrushes(btypes);
}
palette_base::palette_base(TypeMap *typemap, int nentries, QWidget *parent)
: QWidget(parent), nentries(nentries), selector(new QPushButton * [nentries]),
typeSel(new BrushType [nentries])
{
QDir basedir = QString(SRC_BASEDIR);
glparent = (GLWidget *) parent;
setAttribute(Qt::WA_StaticContents);
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
tmap = typemap;
//if(!activeImg.load(QCoreApplication::applicationDirPath() + "/../../viewer/Icons/activeIcon.png"))
// cerr << QCoreApplication::applicationDirPath().toUtf8().constData() << "/../../viewer/Icons/activeIcon.png" << " not found" << endl;
if(!activeImg.load(basedir.filePath("Icons/activeIcon.png")))
cerr << basedir.filePath("Icons/activeIcon.png").toStdString() << " not found" << endl;
// create as many colour buttons as needed up to limit of PALETTE_ENTRIES
QGridLayout *mainLayout = new QGridLayout;
mainLayout->setColumnStretch(0, 0);
mainLayout->setColumnStretch(1, 0);
// mainLayout->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
int row, col;
for(int i = 0; i < nentries; i++)
{
selector[i] = new QPushButton(this);
// which column should palette entry be placed in
switch(i)
{
case 0: row = 0; col = 0;
break;
case 1: row = 1; col = 0;
break;
case 2: row = 2; col = 0;
break;
default:
break;
}
currSel = i;
setDrawType((BrushType)i);
selector[i]->setIconSize(activeImg.size());
selector[i]->setFixedSize(activeImg.size());
// selector[i]->setMaximumSize(activeImg.size());
// selector[i]->setMinimumSize(activeImg.size());
// cerr << "image size = " << (int) activeImg.size().height() << " X " << (int) activeImg.size().width() << endl;
selector[i]->setIconSize(activeImg.size()*1.25f);
selector[i]->setFixedSize(activeImg.size()*1.25f);
selector[i]->setFocusPolicy(Qt::NoFocus);
connect(selector[i], &QPushButton::clicked, this, &palette_base::typeSelect);
mainLayout->addWidget(selector[i], row, col, Qt::AlignCenter);
}
currSel = 0; setActivePalette();
QLabel myLabel;
myLabel.setPixmap(QPixmap::fromImage(activeImg));
myLabel.show();
mainLayout->addWidget(&myLabel, nentries/2+1, 0);
setLayout(mainLayout);
setFocusPolicy(Qt::StrongFocus);
}
QSize palette_base::sizeHint() const
{
return QSize(80, 200);
}
void palette_base::setDrawType(BrushType btype)
{
GLfloat * col;
int r, g, b;
QString qss, qss2;
typeSel[currSel] = btype;
// set colour
col = tmap->getColour((int) btype);
r = (int) (col[0] * 255.0f);
g = (int) (col[1] * 255.0f);
b = (int) (col[2] * 255.0f);
qss = QString("* { background-color: rgb(%1,%2,%3) }").arg(r).arg(g).arg(b);
//qss2 = QString("QPushButton:disabled { background-color:gray }");
qss2 = QString("QPushButton:disabled { border-image: url(../Icons/activeEraseIcon.png) 0 0 0 0 stretch stretch; }");
qss += qss2;
selector[currSel]->setStyleSheet(qss);
selector[currSel]->show();
}
void palette_base::setActivePalette()
{
for(int i = 0; i < nentries; i++)
if (selector[i])
{
if(i == currSel)
selector[currSel]->setIcon(QPixmap::fromImage(activeImg));
else
selector[i]->setIcon(QIcon());
}
}
void palette_base::deactiveSelection()
{
for(int i = 0; i < nentries; i++)
if (selector[i])
{
selector[i]->setIcon(QIcon());
}
}
void palette_base::addBrushes(const std::vector<int> &btypes)
{
QDir basedir = QString(SRC_BASEDIR);
if(!activeImg.load(basedir.filePath("Icons/activeIcon.png")))
{
cerr << basedir.filePath("Icons/activeIcon.png").toStdString() << " not found" << endl;
}
QGridLayout *mainLayout = new QGridLayout;
mainLayout->setColumnStretch(0, 0);
mainLayout->setColumnStretch(1, 0);
// mainLayout->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
int row, col;
row = 0;
col = 0;
/*
for (int i = 0; i < nentries; i++)
{
selector[i] = nullptr;
}
*/
for (int i = 0; i < nentries; i++)
{
selector[i] = nullptr;
//int i = (int)bt;
selector[i] = new QPushButton(this);
/*
// which column should palette entry be placed in
switch(i)
{
case 0: row = 0; col = 0;
break;
case 1: row = 1; col = 0;
break;
case 2: row = 2; col = 0;
break;
}
*/
currSel = i;
// FIXME: this statement below is done differently than in the case of the other palette (the one for painting dense/sparse veg regions...)
// Find a more consistent way of assigning an identity to the draw type
//setDrawType((BrushType) (i - (int)BrushType::SPEC1));
// we assign straight from the 0 to nentries index here. This works because the typemap colour table is also initialized according to this indexing scheme (check usage of the tmap member).
setDrawType((BrushType)btypes.at(i));
selector[i]->setIconSize(activeImg.size());
selector[i]->setFixedSize(activeImg.size());
// selector[i]->setMaximumSize(activeImg.size());
// selector[i]->setMinimumSize(activeImg.size());
// cerr << "image size = " << (int) activeImg.size().height() << " X " << (int) activeImg.size().width() << endl;
selector[i]->setIconSize(activeImg.size()*1.25f);
selector[i]->setFixedSize(activeImg.size()*1.25f);
selector[i]->setFocusPolicy(Qt::NoFocus);
connect(selector[i], &QPushButton::clicked, this, &palette_base::typeSelect);
mainLayout->addWidget(selector[i], row, col, Qt::AlignCenter);
row++;
if (row > 3)
{
row = 0;
col++;
}
}
currSel = 0; setActivePalette();
QLabel myLabel;
myLabel.setPixmap(QPixmap::fromImage(activeImg));
myLabel.show();
mainLayout->addWidget(&myLabel, nentries/2+1, 0);
setLayout(mainLayout);
setFocusPolicy(Qt::StrongFocus);
}
void palette_base::typeSelectMode(ControlMode mode)
{
// TO DO - deal with the case that one of the palette entries is in selection mode
for(int i = 0; i < nentries; i++)
{
if(sender() == selector[i])
{
currSel = i;
glparent->setCtrlMode(mode); // activate paint mode
}
}
setActivePalette();
cerr << "currently selected brush = " << (int) typeSel[currSel] << endl;
}
| 8,336
|
C++
|
.cpp
| 211
| 33.222749
| 196
| 0.620114
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,213
|
specpalette_window.cpp
|
jgain_EcoLearn/EcoSynth/viewer/specpalette_window.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "specpalette_window.h"
#include "palette.h"
#include <QVBoxLayout>
specpalette_window::specpalette_window(QWidget *parent, SpeciesPalette *specpal)
: QWidget(parent, Qt::Window), specpal(specpal)
{
QVBoxLayout *specpal_layout = new QVBoxLayout;
specpal_layout->addWidget(specpal);
show();
setLayout(specpal_layout);
}
void specpalette_window::add_widget(QWidget *w)
{
layout()->addWidget(w);
}
void specpalette_window::enable_species(int id)
{
specpal->enable_brush(id);
}
void specpalette_window::disable_species(int id)
{
specpal->disable_brush(id);
}
int specpalette_window::id_to_idx(int id)
{
return specpal->id_to_idx.at(id);
}
int specpalette_window::idx_to_id(int idx)
{
return specpal->idx_to_id.at(idx);
}
| 1,714
|
C++
|
.cpp
| 50
| 31.98
| 82
| 0.67411
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,214
|
glwidget.cpp
|
jgain_EcoLearn/EcoSynth/viewer/glwidget.cpp
|
// Authors: K.P. Kapp and J.E. Gain
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected]) and J.E. Gain ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "glwidget.h"
#include "eco.h"
#include "window.h"
#include "data_importer/extract_png.h"
#include "canopy_placement/gpu_procs.h"
#include "canopy_placement/canopy_placer.h"
#include "species_optim/species_assign_exp.h"
#include "ClusterMatrices.h"
#include "specselect_window.h"
#include "histcomp_window.h"
#include <data_importer/AbioticMapper.h>
#include <UndergrowthRefiner.h>
#include <common/custom_exceptions.h>
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <thread>
#include <fstream>
#include <QGridLayout>
#include <QGLFramebufferObject>
#include <QImage>
#include <QCoreApplication>
#include <QMessageBox>
#include <QInputDialog>
#include <QDir>
using layerspec = ClusterMatrices::layerspec;
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
static std::string get_errstring(GLuint errcode)
{
switch (errcode)
{
case (GL_NO_ERROR):
return "no error";
break;
case (GL_INVALID_ENUM):
return "INVALID_ENUM";
break;
case (GL_INVALID_VALUE):
return "INVALID_VALUE";
break;
case (GL_INVALID_OPERATION):
return "INVALID_OPERATION";
break;
case (GL_INVALID_FRAMEBUFFER_OPERATION):
return "GL_INVALID_FRAMEBUFFER_OPERATION";
break;
case (GL_OUT_OF_MEMORY):
return "GL_OUT_OF_MEMORY";
break;
case (GL_STACK_OVERFLOW):
return "GL_STACK_OVERFLOW";
break;
case (GL_STACK_UNDERFLOW):
return "GL_STACK_UNDERFLOW";
break;
default:
return "Unknown error";
break;
}
}
#define GL_ERRCHECK(show_noerr) \
{ \
GLenum errcode = glGetError(); \
if (errcode != GL_NO_ERROR) \
{ \
std::cout << "GL error in file " << __FILE__ << ", line " << __LINE__ << ": " << get_errstring(errcode) << std::endl; \
} \
else if (show_noerr) \
{ \
std::cout << "No GL errors on record in file " << __FILE__ << ", line " << __LINE__ << std::endl; \
} \
}
using namespace std;
static int nspacingsteps = 1; // to illustrate the difference between different numbers of iterations for the canopy placement.
// Add a GUI control for this later?
std::vector<int> get_canopyspecs(std::string dbname)
{
data_importer::common_data cdata(dbname);
std::vector<int> specs;
for (auto &p : cdata.all_species)
{
specs.push_back(p.first);
}
return specs;
}
#ifndef GL_MULTISAMPLE
#define GL_MULTISAMPLE 0x809D
#endif
////
// Scene
////
Scene::Scene()
{
view = new View();
terrain = new Terrain();
terrain->initGrid(1024, 1024, 10000.0f, 10000.0f);
view->setForcedFocus(terrain->getFocus());
view->setViewScale(terrain->longEdgeDist());
sim = new Simulation();
eco = new EcoSystem();
biome = new Biome();
int dx, dy;
terrain->getGridDim(dx, dy);
for(TypeMapType t: all_typemaps)
maps[(int) t] = new TypeMap(dx, dy, t);
maps[2]->setRegion(terrain->coverRegion());
grass = new GrassSim();
moisture = new MapFloat();
illumination = new MapFloat();
temperature = new MapFloat();
chm = new MapFloat();
cdm = new MapFloat();
chm_cpl = new basic_types::MapFloat();
}
Scene::~Scene()
{
delete view;
delete terrain;
for(TypeMapType t: all_typemaps)
if(maps[(int) t] != nullptr)
{
delete maps[(int) t];
maps[(int) t] = nullptr;
}
delete sim;
delete eco;
delete biome;
delete grass;
delete illumination;
delete moisture;
delete temperature;
delete chm;
delete cdm;
}
////
// GLWidget
////
GLWidget::GLWidget(const QGLFormat& format, int scale_size, QWidget *parent)
: QGLWidget(format, parent), prj_src_dir(PRJ_SRC_DIR), db_pathname(std::string(PRJ_SRC_DIR) + "/ecodata/sonoma.db"), plant_sqldb_name(db_pathname), cdata(plant_sqldb_name),
scale_size(scale_size), sceneloaded(false), undergrowth_sampled(false)
{
assign_times = 0;
qtWhite = QColor::fromCmykF(0.0, 0.0, 0.0, 0.0);
vizpopup = new QLabel();
atimer = new QTimer(this);
connect(atimer, SIGNAL(timeout()), this, SLOT(animUpdate()));
rtimer = new QTimer(this);
connect(rtimer, SIGNAL(timeout()), this, SLOT(rotateUpdate()));
connect(this, SIGNAL(signalRepaintAllFromThread()), this, SLOT(repaint()));
// main design scene
addScene();
// database display and picking scene
addScene();
currscene = 0;
renderer = new PMrender::TRenderer(NULL, "../viewer/shaders/");
palette = new BrushPalette(getTypeMap(TypeMapType::PAINT), 3, this);
all_possible_species = cdata.all_species;
species_infomap = cdata.all_species; // TODO: species_infomap starts as all species selected - need to do so accordingly for checkboxes
int i = 0;
for (auto &p : all_possible_species)
{
allcanopy_idx_to_id.push_back(p.first);
allcanopy_id_to_idx[p.first] = i;
i++;
}
// the values of specbrushes isn't being used currently - just the vector's size is being used
std::vector<int> specbrushes;
for (auto &p : all_possible_species)
{
specbrushes.push_back(p.second.idx);
}
species_palette = new SpeciesPalette(getTypeMap(TypeMapType::SPECIES), specbrushes, this);
setRadius(250.0f);
cmode = ControlMode::VIEW;
viewing = false;
viewlock = false;
decalsbound = false;
focuschange = false;
focusviz = false;
timeron = false;
dbloaded = false;
ecoloaded = false;
scf = 10000.0f;
decalTexture = 0;
//spacer = nullptr;
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
resize(sizeHint());
setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored);
glsun = new GLSun(format);
ipc = new IPC();
ipc_received_raw = new MapFloat();
nspecies = 5;
species_percentages = std::vector<float> (nspecies, 1.0f / nspecies); // find a better way to initialize this!!
//genOpenglTexturesForTrees();
std::cerr << "GLWidget construction done" << std::endl;
}
void GLWidget::repaint()
{
report_cudamem("GPU memory in use before repaint: ");
QGLWidget::repaint();
report_cudamem("GPU memory in use after repaint: ");
}
GLWidget::~GLWidget()
{
if (spacer)
delete spacer;
delete atimer;
delete rtimer;
if(vizpopup) delete vizpopup;
if (renderer) delete renderer;
if (specassign_ptr)
specassign_ptr.reset(nullptr);
// delete views
for(int i = 0; i < (int) scenes.size(); i++)
delete scenes[i];
if (decalTexture != 0) glDeleteTextures(1, &decalTexture);
delete ipc;
delete ipc_received_raw;
}
void GLWidget::set_clusterfilenames(std::vector<std::string> cluster_filenames)
{
this->cluster_filenames = cluster_filenames;
if (cluster_filenames.size() > 0)
init_undersynth();
}
QSize GLWidget::minimumSizeHint() const
{
return QSize(50, 50);
}
QSize GLWidget::sizeHint() const
{
return QSize(1000, 800);
}
void GLWidget::screenCapture(QImage * capImg, QSize capSize)
{
paintGL();
glFlush();
(* capImg) = grabFrameBuffer();
(* capImg) = capImg->scaled(capSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
}
View * GLWidget::getView()
{
if((int) scenes.size() > 0)
return scenes[currscene]->view;
else
return NULL;
}
Terrain * GLWidget::getTerrain()
{
if((int) scenes.size() > 0)
return scenes[currscene]->terrain;
else
return NULL;
}
TypeMap * GLWidget::getTypeMap(TypeMapType purpose)
{
if((int) scenes.size() > 0)
return scenes[currscene]->maps[(int) purpose];
else
return NULL;
}
MapFloat * GLWidget::getSunlight(int month)
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim->getSunlightMap(month);
else
return NULL;
}
MapFloat * GLWidget::getSunlight()
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim->get_average_sunlight_map();
else
return NULL;
}
MapFloat * GLWidget::getSlope()
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim->getSlopeMap();
else
return NULL;
}
MapFloat * GLWidget::getMoisture(int month)
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim->getMoistureMap(month);
else
return NULL;
}
MapFloat * GLWidget::getMoisture()
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim->get_average_moisture_map();
else
return NULL;
}
MapFloat *GLWidget::getTemperature()
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim->get_temperature_map();
else
return NULL;
}
basic_types::MapFloat * GLWidget::getPlacerCanopyHeightModel()
{
if((int) scenes.size() > 0)
return scenes[currscene]->chm_cpl;
else
return NULL;
}
MapFloat * GLWidget::getCanopyHeightModel()
{
if((int) scenes.size() > 0)
return scenes[currscene]->chm;
else
return NULL;
}
MapFloat * GLWidget::getCanopyDensityModel()
{
if((int) scenes.size() > 0)
return scenes[currscene]->cdm;
else
return NULL;
}
PMrender::TRenderer * GLWidget::getRenderer()
{
return renderer;
}
void GLWidget::genOpenglTexturesForTrees()
{
//getEcoSys()->genOpenglTextures();
}
EcoSystem * GLWidget::getEcoSys()
{
if((int) scenes.size() > 0)
return scenes[currscene]->eco;
else
return NULL;
}
Simulation * GLWidget::getSim()
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim;
else
return NULL;
}
void GLWidget::initSceneSim()
{
// assumes terrain and biome already loaded
if((int) scenes.size() > 0)
{
scenes[currscene]->sim = new Simulation(getTerrain(), getBiome(), 5);
}
}
Biome * GLWidget::getBiome()
{
if((int) scenes.size() > 0)
return scenes[currscene]->biome;
else
return NULL;
}
GLSun * GLWidget::getGLSun()
{
return glsun;
}
GrassSim * GLWidget::getGrass()
{
if((int) scenes.size() > 0)
return scenes[currscene]->grass;
else
return NULL;
}
void GLWidget::init_underspacer()
{
int gw, gh;
float rw, rh;
canopyshading_temp.getDim(gw, gh);
canopyshading_temp.getDimReal(rw, rh);
std::cout << "Sunlight map gw, gh: " << gw << ", " << gh << std::endl;
std::cout << "Sunlight map rw, rh: " << rw << ", " << rh << std::endl;
abiotic_maps_package amaps_temp(amaps_ptr->wet, canopyshading_temp, amaps_ptr->temp, amaps_ptr->slope);
}
void GLWidget::setCtrlMode(ControlMode mode)
{
if(mode == ControlMode::PAINTECO)
{
if(dbloaded && ecoloaded)
cmode = mode;
}
else
{
cmode = mode;
if (cmode == ControlMode::PAINTLEARN)
{
species_palette->deactiveSelection();
setRadius(getLearnBrushRadius());
signalEnableSpecSelect();
}
else if (cmode == ControlMode::PAINTSPECIES)
{
palette->deactiveSelection();
setRadius(getSpeciesBrushRadius());
signalDisableSpecSelect();
adapt_species_changed();
}
}
}
void GLWidget::setMode(ControlMode mode)
{
if (cmode == ControlMode::PAINTLEARN)
palette->deactiveSelection();
if (cmode == ControlMode::PAINTSPECIES)
species_palette->deactiveSelection();
switch(mode)
{
case ControlMode::VIEW:
cmode = mode;
setOverlay(TypeMapType::CATEGORY);
break;
case ControlMode::PAINTLEARN:
cmode = mode;
setOverlay(TypeMapType::PAINT);
break;
case ControlMode::PAINTECO:
if(dbloaded && ecoloaded) // can only change to this mode if database and ecosystem are loaded
{
cmode = mode;
setOverlay(TypeMapType::PAINT);
}
break;
case ControlMode::PAINTSPECIES:
cmode = mode;
setOverlay(TypeMapType::SPECIES);
break;
default:
break;
}
update();
}
void GLWidget::convert_painting(BrushType from, BrushType to)
{
TypeMap *tmap = getTypeMap(TypeMapType::PAINT);
int fromi, toi;
switch (from)
{
case BrushType::FREE:
fromi = 0;
break;
case BrushType::SPARSETALL:
case BrushType::SPARSEMED:
case BrushType::SPARSESHRUB:
fromi = 1;
break;
case BrushType::DENSETALL:
case BrushType::DENSEMED:
case BrushType::DENSESHRUB:
fromi = 2;
break;
default:
return;
}
switch (to)
{
case BrushType::FREE:
toi = 0;
break;
case BrushType::SPARSETALL:
case BrushType::SPARSEMED:
case BrushType::SPARSESHRUB:
toi = 1;
break;
case BrushType::DENSETALL:
case BrushType::DENSEMED:
case BrushType::DENSESHRUB:
toi = 2;
break;
default:
return;
}
tmap->replace_value(fromi, toi);
//send_drawing();
}
void GLWidget::refreshOverlay()
{
renderer->updateTypeMapTexture(getTypeMap(scenes[currscene]->overlay), PMrender::TRenderer::typeMapInfo::PAINT, false);
update();
}
void GLWidget::setOverlay(TypeMapType purpose)
{
scenes[currscene]->overlay = purpose;
renderer->updateTypeMapTexture(getTypeMap(scenes[currscene]->overlay), PMrender::TRenderer::typeMapInfo::PAINT, true);
update();
}
TypeMapType GLWidget::getOverlay()
{
return scenes[currscene]->overlay;
}
void GLWidget::init_undersynth()
{
undersynth_init = true;
undersynth = std::unique_ptr<UndergrowthRefiner>(new UndergrowthRefiner(cluster_filenames,
*amaps_ptr,
{},
cdata));
}
void GLWidget::set_underspace_viabbase(float viabbase)
{
std::cout << "Setting viability base to " << viabbase << std::endl;
}
void GLWidget::set_underspace_radmult(float radmult)
{
std::cout << "Setting radius multiplier to " << radmult << std::endl;
}
void GLWidget::setSpecPerc(float perc)
{
specperc = perc;
}
float GLWidget::getSpecPerc()
{
return specperc;
}
void GLWidget::setRadius(float rad)
{
float brushradius = rad;
if (cmode == ControlMode::PAINTLEARN)
{
learnbrush_rad = brushradius;
}
else if (cmode == ControlMode::PAINTSPECIES)
{
specbrush_rad = brushradius;
}
brushcursor.setRadius(brushradius);
update();
}
const data_importer::common_data &GLWidget::get_cdata()
{
return cdata;
}
float GLWidget::getRadius()
{
return brushcursor.getRadius();
}
float GLWidget::getLearnBrushRadius()
{
return learnbrush_rad;
}
void GLWidget::setLearnBrushRadius(float rad)
{
learnbrush_rad = rad;
if (cmode == ControlMode::PAINTLEARN)
{
setRadius(learnbrush_rad);
}
}
void GLWidget::species_added(int id)
{
if (species_infomap.count(id) == 0)
species_infomap.insert({ id, all_possible_species.at(id) });
// only if scene has been loaded already, do we reset specassign ptr. This is
// because we cannot set it without a loaded scene, and it gets reset anyway when
// a scene gets loaded (see GLWidget::loadScene)
if (sceneloaded)
species_changed = true;
//reset_specassign_ptr();
// TODO: re-enable species paint button here
}
void GLWidget::species_removed(int id)
{
if (species_infomap.count(id) > 0)
species_infomap.erase(id);
if (sceneloaded)
species_changed = true;
//reset_specassign_ptr();
// TODO: disable species paint button here
}
float GLWidget::getSpeciesBrushRadius()
{
return specbrush_rad;
}
void GLWidget::setSpeciesBrushRadius(float rad)
{
specbrush_rad = rad;
if (cmode == ControlMode::PAINTSPECIES)
{
setRadius(specbrush_rad);
}
}
void GLWidget::bandCanopyHeightTexture(float mint, float maxt)
{
getTypeMap(TypeMapType::CHM)->bandCHMMapEric(getCanopyHeightModel(), mint*mtoft, maxt*mtoft);
focuschange = true;
}
void GLWidget::grow_grass()
{
getGrass()->matchDim(getTerrain(), 10000.0f, 1);
getGrass()->setConditions(getSim()->get_average_moisture_map(), getSim()->get_average_landsun_map(), getSim()->get_average_landsun_map(), getSim()->get_temperature_map());
getGrass()->grow(getTerrain(), canopytrees, cdata, scf);
}
MapFloat *GLWidget::get_rocks()
{
if((int) scenes.size() > 0)
return scenes[currscene]->sim->get_rocks();
else
return NULL;
}
void GLWidget::set_clustermap()
{
//MapFloat *grass = getGrass()->get_data();
//MapFloat *rocks = get_rocks();
/*
MapFloat *wet = getSim()->get_average_moisture_map();
MapFloat *sun = getSim()->get_adaptsun();
MapFloat *slope = getSim()->getSlopeMap();
MapFloat *temp = getSim()->get_temperature_map();
*/
const auto &clmap = undersynth->get_clustermaps().get_clustermap();
int gw, gh;
clmap.getDim(gw, gh);
clustermap.setDim(gw, gh);
for (int y = 0; y < gh; y++)
{
for (int x = 0; x < gw; x++)
{
clustermap.set(x, y, clmap.get(x, y));
/*
clustermap.set(x, y, clptr_temp->get_cluster_idx_from_values(wet->get(x, y),
sun->get(x, y),
temp->get(x, y),
slope->get(x, y)));
*/
}
}
}
void GLWidget::set_clusterdensitymap()
{
const auto &clmap = undersynth->get_clustermaps().get_clustermap();
int gw, gh;
clmap.getDim(gw, gh);
clusterdensitymap.setDim(gw, gh);
clusterdensitymap.fill((float)-1.0f);
for (int y = 0; y < gh; y++)
{
for (int x = 0; x < gw; x++)
{
int idx = clmap.get(x, y);
if (idx >= 0)
{
float density = undersynth->get_model().get_region_density(idx);
if (density < 0.0f)
{
std::cerr << "Abnormal density found in GLWidget::set_clusterdensitymap" << std::endl;
}
clusterdensitymap.set(x, y, density);
}
}
}
}
void GLWidget::set_pretty_map()
{
MapFloat *grass = getGrass()->get_data();
MapFloat *rocks = get_rocks();
MapFloat *wet = getMoisture();
int tx, ty;
getTerrain()->getGridDim(tx, ty);
int dx, dy;
grass->getDim(dx, dy);
if (dx != tx || dy != ty)
{
throw std::runtime_error("Grass map dimensions not equal to terrain dimensions. Terrain gw, gh: " + std::to_string(tx) + ", " + std::to_string(ty) + ". Grass map: " + std::to_string(dx) + ", " + std::to_string(dy));
}
rocks->getDim(dx, dy);
if (dx != tx || dy != ty)
{
// rock dimensions not equal to terrain dimension, possibly due to rock map not being initialized yet.
// so we initialize
getSim()->set_rocks();
rocks->getDim(dx, dy);
// if it's still not equal in dimension, throw error
if (dx != tx || dy != ty)
throw std::runtime_error("Rock map dimensions not equal to terrain dimensions. Terrain gw, gh: " + std::to_string(tx) + ", " + std::to_string(ty) + ". Rock map: " + std::to_string(dx) + ", " + std::to_string(dy));
}
wet->getDim(dx, dy);
if (dx != tx || dy != ty)
{
throw std::runtime_error("Moisture map dimensions not equal to terrain dimensions. Terrain gw, gh: " + std::to_string(tx) + ", " + std::to_string(ty) + ". Moisture map: " + std::to_string(dx) + ", " + std::to_string(dy));
}
pretty_map_painted.setDim(dx, dy);
for (int y = 0; y < dy; y++)
{
for (int x = 0; x < dx; x++)
{
if (rocks->get(x, y) > 0.0f)
pretty_map_painted.set(x, y, 1.0f);
else if (grass->get(x, y) > 1.0f)
pretty_map_painted.set(x, y, 2.0f + grass->get(x, y));
else if (wet->get(x, y) > 100.0f)
pretty_map_painted.set(x, y, 2.0f + MAXGRASSHGHT + 1.0f + wet->get(x, y));
else
pretty_map_painted.set(x, y, 0.0f);
}
}
pretty_map = pretty_map_painted;
const int add_const = 1000000; // TODO: Define this constant somewhere, where it can be used also by the trenderer file
for (int y = 0; y < dy; y++)
{
for (int x = 0; x < dx; x++)
{
float prevval = pretty_map_painted.get(x, y);
auto tmap_ptr = getTypeMap(TypeMapType::PAINT);
int painttype = tmap_ptr->get(x, y); // this is a bit of a hard-coded value. Try to use proper enums?
if (painttype == 1)
{
pretty_map_painted.set(x, y, prevval + add_const);
}
else if (painttype == 2)
{
pretty_map_painted.set(x, y, prevval + add_const * 2);
}
}
}
}
void GLWidget::loadScene(std::string dirprefix)
{
sceneloaded = false;
bool simvalid = true;
bool terloaded = false, wetloaded = false, sunloaded = false;
QFileInfo finfo(QString(dirprefix.c_str()));
base_dirname = finfo.absolutePath().toStdString();
while (base_dirname.back() == '/')
base_dirname.pop_back();
int curr_counter = 0;
pipeout_dirname = base_dirname + "/pipe_out" + std::to_string(curr_counter);
QDir pipedir;
while (!pipedir.mkdir(pipeout_dirname.c_str()))
{
curr_counter++;
pipeout_dirname = base_dirname + "/pipe_out" + std::to_string(curr_counter);
}
logfile_ofs = std::ofstream(pipeout_dirname + "/" + "log");
std::string terfile = dirprefix+".elv";
std::string pdbfile = dirprefix+".pdb";
std::string chmfile = dirprefix+".chm";
std::string cdmfile = dirprefix+".cdm";
std::string sunfile = dirprefix+"_sun.txt";
std::string landsun_file = dirprefix+"_sun_landscape.txt";
std::string wetfile = dirprefix+"_wet.txt";
std::string climfile = dirprefix+"_clim.txt";
std::string bmefile = dirprefix+"_biome.txt";
std::string catfile = dirprefix+"_plt.png";
std::string slopefile = dirprefix+"_slope.txt";
std::string grassparamsfile = dirprefix + "_grass_params.txt";
// load terrain
currscene = 0;
cerr << "Elevation file load" << endl;
getTerrain()->loadElv(terfile);
scf = getTerrain()->getMaxExtent();
getView()->setForcedFocus(getTerrain()->getFocus());
getView()->setViewScale(getTerrain()->longEdgeDist());
getView()->setDim(0.0f, 0.0f, (float) this->width(), (float) this->height());
getTerrain()->calcMeanHeight();
getTerrain()->updateBuffers(renderer); // NB - set terrain width and height in renderer.
int scale_down = get_terscale_down(scale_size);
// match dimensions for empty overlay
int dx, dy;
getTerrain()->getGridDim(dx, dy);
ipc_received_raw->setDim(dx / scale_down, dy / scale_down);
cerr << "terrain dimensions = " << dx << " " << dy << endl;
getTypeMap(TypeMapType::EMPTY)->matchDim(dx, dy);
getTypeMap(TypeMapType::PAINT)->matchDim(dx, dy);
getTypeMap(TypeMapType::PAINT)->fill((int) BrushType::FREE);
getTypeMap(TypeMapType::PRETTY_PAINTED)->matchDim(dx, dy);
if (dx * dy > 0)
{
getSim()->set_terrain(getTerrain());
terloaded = true;
}
else
throw runtime_error("Could not import terrain, or imported terrain is invalid (either width or height is zero)");
// Region R = getTypeMap(TypeMapType::PAINT)->getRegion();
// cerr << "R: " << R.x0 << " " << R.x1 << " " << R.y0 << " " << R.y1 << endl;
std::cout << "Loading canopy density model..." << std::endl;
if(getCanopyDensityModel()->read(cdmfile))
{
loadTypeMap(getCanopyDensityModel(), TypeMapType::CDM);
cerr << "CDM file load" << endl;
}
else
{
cerr << "No Canopy Density Model found. Simulation invalidated." << endl;
simvalid = false;
}
std::cout << "Loading canopy height model..." << std::endl;
if(getCanopyHeightModel()->read(chmfile))
{
cerr << "CHM file load" << endl;
loadTypeMap(getCanopyHeightModel(), TypeMapType::CHM);
}
else
{
cerr << "No Canopy Height Model found. Simulation invalidated." << endl;
simvalid = false;
}
int chmw, chmh;
getCanopyHeightModel()->getDim(chmw, chmh);
getPlacerCanopyHeightModel()->setDim(chmw, chmh);
//#ifndef PAINTCONTROL
//if(getBiome()->read(bmefile))
if (getBiome()->read_dataimporter(prj_src_dir + "/ecodata/sonoma.db"))
{
amaps_ptr = unique_ptr<abiotic_maps_package>(new abiotic_maps_package(base_dirname, abiotic_maps_package::suntype::LANDSCAPE_ONLY, abiotic_maps_package::aggr_type::AVERAGE));
if (plantvis.size() < getBiome()->numPFTypes())
plantvis.resize(getBiome()->numPFTypes());
cerr << "Biome file load" << endl;
for(int t = 0; t < getBiome()->numPFTypes(); t++)
plantvis[t] = true;
std::cerr << "Running GLWidget::initSceneSim..." << std::endl;
// initialize simulation
//initSceneSim();
std::cerr << "Reading climate parameters..." << std::endl;
// read climate parameters
if(!getSim()->readClimate(climfile))
{
simvalid = false;
cerr << "No climate file " << climfile << " found. Simulation invalidated" << endl;
}
std::cerr << "Computing temperature map..." << std::endl;
getSim()->calc_temperature_map(); // put this inside the readClimate function?
getSim()->copy_map(amaps_ptr->sun, abiotic_factor::SUN);
sunloaded = true;
sun_mth = 0;
//loadTypeMap(getSunlight(sun_mth), TypeMapType::SUNLIGHT);
loadTypeMap(getSlope(), TypeMapType::SLOPE);
getSim()->copy_map(amaps_ptr->wet, abiotic_factor::MOISTURE);
wetloaded = true;
std::cerr << "Calculating average moisture map..." << std::endl;
wet_mth = 0;
loadTypeMap(getMoisture(), TypeMapType::WATER);
// read landscape category data
if(getTypeMap(TypeMapType::CATEGORY)->loadCategoryImage(catfile))
{
cerr << "Region usage file load" << endl;
}
else
{
simvalid = false;
cerr << "No land usage category image " << catfile << " found. Simulation invalidated" << endl;
}
// loading plant distribution
getEcoSys()->setBiome(getBiome());
getEcoSys()->pickAllPlants(getTerrain());
getEcoSys()->redrawPlants();
auto vparams = data_importer::read_grass_viability(grassparamsfile);
getGrass()->set_viability_params(vparams);
if (terloaded && sunloaded && wetloaded)
{
float rw, rh;
getTerrain()->getGridDim(dx, dy);
getTerrain()->getTerrainDim(rw, rh);
std::cout << "Terrain grid dimensions: " << dx << ", " << dy << std::endl;
std::cout << "Terrain real dimensions: " << rw << ", " << rh << std::endl;
std::cout << "growing grass..." << std::endl;
grow_grass();
std::cout << "setting pretty map..." << std::endl;
set_pretty_map();
std::cout << "done" << std::endl;
}
}
else
{
std::cerr << "Biome file " << bmefile << "does not exist. Simulation invalidated." << endl;
}
//#endif
// focuschange = true;
setOverlay(TypeMapType::PAINT);
getTerrain()->setBufferToDirty(); // force render reload, so that we have a valid initial texture
sceneloaded = true;
float tw, th;
getTerrain()->getTerrainDim(tw, th);
setPlantsVisibility(true);
}
void GLWidget::reset_specassign_ptr()
{
std::map<int, ValueMap<float> > drawmap;
std::map<int, ValueMap<bool > > draw_indicator;
std::map<int, int> convertmap_idxtoid;
bool first = true;
// if we have assigned species previously, we wish to preserve the previous drawing maps.
// so we copy them to temporary ones, declared above
if (specassign_ptr)
{
first = false;
specassign_ptr->get_mult_maps(drawmap, draw_indicator);
for (auto &p : drawmap)
{
// just making sure that the maps correspond in terms of species indexes...
assert(draw_indicator.count(p.first) > 0);
// we need to keep track of which id each index represents for the specassign_ptr that is about to be reset,
// so that we can assign the right map to the appropriate species index for the new specassign_ptr
convertmap_idxtoid[p.first] = specidxes.at(p.first);
}
}
specassign_ptr.reset(nullptr);
//data_importer::common_data cdata(db_pathname);
int chmw, chmh;
MapFloat *chm = getCanopyHeightModel();
chm->getDim(chmw, chmh);
MapFloat *tempmap = getTemperature();
MapFloat *slopemap = getSlope();
MapFloat *wetmap = getSim()->get_average_moisture_map();
MapFloat *sunmap = getSim()->get_average_landsun_map();
ValueMap<float> tempvmap(chmw, chmh);
ValueMap<float> slopevmap(chmw, chmh);
ValueMap<float> wetvmap(chmw, chmh);
ValueMap<float> sunvmap(chmw, chmh);
ValueMap<float> chmvmap(chmw, chmh);
tempvmap.fill(tempmap->data());
slopevmap.fill(slopemap->data());
wetvmap.fill(wetmap->data());
sunvmap.fill(sunmap->data());
chmvmap.fill(chm->data());
std::vector<ValueMap<float> > vmaps = {tempvmap, slopevmap, wetvmap, sunvmap};
specidxes.clear();
allspecs.clear();
std::vector<float> max_heights;
auto get_ideal = [] (const data_importer::viability &viab)
{
return (viab.cmin + viab.cmax) / 2.0f;
};
auto get_tolerance = [] (const data_importer::viability &viab)
{
return (viab.cmax - viab.cmin) / 2.0f;
};
std::vector<int> incl_canopyspecs;
for (auto &p : species_infomap)
{
incl_canopyspecs.push_back(p.first);
}
specidxes.clear();
specassign_id_to_idx.clear();
allspecs.clear();
int count = 0;
for (const std::pair<int, data_importer::species> &sppair : cdata.all_species)
{
// if we cannot find this species in which canopy species we wish to include, we skip it
if (std::find(incl_canopyspecs.begin(), incl_canopyspecs.end(), sppair.first) == incl_canopyspecs.end())
{
continue;
}
data_importer::viability tempviab = sppair.second.temp;
data_importer::viability slopeviab = sppair.second.slope;
data_importer::viability wetviab = sppair.second.wet;
data_importer::viability sunviab = sppair.second.sun;
std::vector<suit_func> funcs = {
suit_func(get_ideal(tempviab), get_tolerance(tempviab)),
suit_func(get_ideal(slopeviab), get_tolerance(slopeviab)),
suit_func(get_ideal(wetviab), get_tolerance(wetviab)),
suit_func(get_ideal(sunviab), get_tolerance(sunviab))
};
specidxes.push_back(sppair.first);
specassign_id_to_idx[sppair.first] = count;
allspecs.push_back(species(funcs, sppair.second.maxhght, 0));
max_heights.push_back(sppair.second.maxhght);
count++;
}
specassign_ptr = std::unique_ptr<species_assign>(new species_assign(chmvmap, vmaps, allspecs, max_heights));
std::map<int, ValueMap<float> > newdrawmap;
std::map<int, ValueMap<bool> > newindic_map;
specassign_ptr->get_mult_maps(newdrawmap, newindic_map);
// if species has been assigned previously, we move the old drawing maps to new ones
// that use indices that correspond with the new specassign_ptr
if (!first)
{
for (auto &p : drawmap)
{
// convert old indices to new ones for the new ptr
int id = convertmap_idxtoid.at(p.first);
int newidx;
try
{
newidx = specassign_id_to_idx.at(id);
}
catch (std::out_of_range &e)
{
// in this case, a species present in the previous ptr was removed from the current one.
// It will therefore not have a place in the new ptr's map
continue;
}
// we std::move to save memory/performance, since the maps can potentially be quite big
newdrawmap.at(newidx) = std::move(p.second);
newindic_map.at(newidx) = std::move(draw_indicator.at(p.first));
}
specassign_ptr->set_mult_maps(newdrawmap, newindic_map);
}
}
void GLWidget::saveScene(std::string dirprefix)
{
if (!sceneloaded)
return;
std::string terfile = dirprefix+".elv";
std::string canopyfile = dirprefix+"_canopy.pdb";
std::string undergrowthfile = dirprefix + "_undergrowth.pdb";
std::string grassfile = dirprefix + "_grass.txt";
std::string litfile = dirprefix + "_litterfall.txt";
getTerrain()->saveElv(terfile, 0.3048);
if (canopytrees.size() > 0)
{
data_importer::write_pdb(canopyfile, canopytrees.data(), canopytrees.data() + canopytrees.size());
data_importer::write_txt<MapFloat>(grassfile, getGrass()->get_data());
data_importer::write_txt<MapFloat>(litfile, getGrass()->get_litterfall_data());
}
if (underplants.size() > 0)
data_importer::write_pdb(undergrowthfile, underplants.data(), underplants.data() + underplants.size());
}
void GLWidget::writePlants(std::string plantfile)
{
if(!dbloaded || !ecoloaded) // an ecosystem database must be present
{
// display message to prompt user
QMessageBox::information(
this,
tr("EcoSys"),
tr("There are no plants to save.") );
}
else
{
getEcoSys()->getPlants()->writePDB(plantfile);
}
}
void GLWidget::writePaintMap(std::string paintfile)
{
getTypeMap(TypeMapType::PAINT)->saveToPaintImage(paintfile);
}
void GLWidget::writeCanopyHeightModel(std::string chmfile)
{
getTypeMap(TypeMapType::CHM)->saveToGreyscaleImage(chmfile, 250.0f, true);
}
void GLWidget::addScene()
{
Scene * scene = new Scene();
scene->view->setDim(0.0f, 0.0f, (float) this->width(), (float) this->height());
std::fill(plantvis.begin(), plantvis.end(), false);
//for(int t = 0; t < maxpftypes; t++)
// plantvis[t] = false;
scenes.push_back(scene);
currscene = (int) scenes.size() - 1;
}
void GLWidget::setScene(int s)
{
if(s >= 0 && s < (int) scenes.size())
{
currscene = s;
getTerrain()->setBufferToDirty();
getTerrain()->setAccelInValid();
refreshOverlay();
update();
}
}
void GLWidget::loadDecals()
{
QDir src_basedir = QString(SRC_BASEDIR);
QImage decalImg, t;
if(!decalImg.load(src_basedir.filePath("Icons/manipDecals.png")))
cerr << src_basedir.filePath("Icons/manipDecals.png").toStdString() << " not found" << endl;
// Qt prep image for OpenGL
QImage fixedImage(decalImg.width(), decalImg.height(), QImage::Format_ARGB32);
QPainter painter(&fixedImage);
painter.setCompositionMode(QPainter::CompositionMode_Source);
painter.fillRect(fixedImage.rect(), Qt::transparent);
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
painter.drawImage( 0, 0, decalImg);
painter.end();
// probe fixedImage
// cerr << "Decal alpha channel = " << fixedImage.hasAlphaChannel() << endl;
// QRgb pix = fixedImage.pixel(84, 336);
// cerr << "Decal[84][336] = " << (int) qRed(pix) << ", " << (int) qGreen(pix) << ", " << (int) qBlue(pix) << ", " << (int) qAlpha(pix) << endl;
// t = QGLWidget::convertToGLFormat( fixedImage );
t = QGLWidget::convertToGLFormat( fixedImage );
renderer->bindDecals(t.width(), t.height(), t.bits());
decalsbound = true;
}
void GLWidget::loadTypeMap(const QImage &img, TypeMapType purpose)
{
getTypeMap(purpose)->load(img, purpose);
}
void GLWidget::import_drawing(const QImage &img)
{
int w, h;
w = img.width();
h = img.height();
int gw, gh;
getTerrain()->getGridDim(gw, gh);
if (w == gw && h == gh)
{
loadTypeMap(img, TypeMapType::PAINT);
//send_drawing();
}
}
int GLWidget::loadTypeMap(MapFloat * map, TypeMapType purpose)
{
int numClusters = 0;
switch(purpose)
{
case TypeMapType::EMPTY:
break;
case TypeMapType::PAINT:
break;
case TypeMapType::CATEGORY:
break;
case TypeMapType::SLOPE:
numClusters = getTypeMap(purpose)->convert(map, purpose, 90.0f);
break;
case TypeMapType::WATER:
numClusters = getTypeMap(purpose)->convert(map, purpose, 100.0); // 1000.0f);
break;
case TypeMapType::SUNLIGHT:
numClusters = getTypeMap(purpose)->convert(map, purpose, 13.0f);
break;
case TypeMapType::TEMPERATURE:
numClusters = getTypeMap(purpose)->convert(map, purpose, 20.0f);
break;
case TypeMapType::CHM:
numClusters = getTypeMap(purpose)->convert(map, purpose, mtoft*initmaxt);
break;
case TypeMapType::CDM:
numClusters = getTypeMap(purpose)->convert(map, purpose, 1.0f);
break;
case TypeMapType::GRASS:
numClusters = getTypeMap(purpose)->convert(map, purpose, MAXGRASSHGHT);
break;
case TypeMapType::PRETTY_PAINTED:
numClusters = getTypeMap(purpose)->convert(map, purpose, 0);
break;
case TypeMapType::PRETTY:
numClusters = getTypeMap(purpose)->convert(map, purpose, 0);
break;
case TypeMapType::CLUSTER:
numClusters = getTypeMap(purpose)->convert(map, purpose, 0);
break;
case TypeMapType::CLUSTERDENSITY:
numClusters = getTypeMap(purpose)->convert(map, purpose, 0);
break;
default:
break;
}
return numClusters;
}
void GLWidget::floodSea(Terrain * ter, MapFloat * wet, float sealevel, float seaval)
{ char * cmap;
int dx, dy, p = 0;
const float * grid = ter->getGridData(dx, dy);
for(int i = 0; i < dx; i++)
for(int j = 0; j < dy; j++)
{
if(grid[p] <= sealevel)
wet->set(j, i, seaval);
p++;
}
}
void GLWidget::initializeGL()
{
// get context opengl-version
qDebug() << "Widget OpenGl: " << format().majorVersion() << "." << format().minorVersion();
qDebug() << "Context valid: " << context()->isValid();
qDebug() << "Really used OpenGl: " << context()->format().majorVersion() << "." <<
context()->format().minorVersion();
qDebug() << "OpenGl information: VENDOR: " << (const char*)glGetString(GL_VENDOR);
qDebug() << " RENDERDER: " << (const char*)glGetString(GL_RENDERER);
qDebug() << " VERSION: " << (const char*)glGetString(GL_VERSION);
qDebug() << " GLSL VERSION: " << (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
QGLFormat glFormat = QGLWidget::format();
if ( !glFormat.sampleBuffers() )
qWarning() << "Could not enable sample buffers";
qglClearColor(qtWhite.light());
int mu;
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &mu);
cerr << "max texture units = " << mu << endl;
// *** PM REnder code - start ***
// To use basic shading: PMrender::TRenderer::BASIC
// To use radianvce scaling: PMrender::TRenderer::RADIANCE_SCALING
PMrender::TRenderer::terrainShadingModel sMod = PMrender::TRenderer::RADIANCE_SCALING;
// set terrain shading model
renderer->setTerrShadeModel(sMod);
// set up light
Vector dl = Vector(0.6f, 1.0f, 0.6f);
dl.normalize();
GLfloat pointLight[3] = { 0.5, 5.0, 7.0}; // side panel + BASIC lighting
GLfloat dirLight0[3] = { dl.i, dl.j, dl.k}; // for radiance lighting
GLfloat dirLight1[3] = { -dl.i, dl.j, -dl.k}; // for radiance lighting
renderer->setPointLight(pointLight[0],pointLight[1],pointLight[2]);
renderer->setDirectionalLight(0, dirLight0[0], dirLight0[1], dirLight0[2]);
renderer->setDirectionalLight(1, dirLight1[0], dirLight1[1], dirLight1[2]);
// initialise renderer/compile shaders
renderer->initShaders();
// set other render parameters
// can set terrain colour for radiance scaling etc - check trenderer.h
// terrain contours
renderer->drawContours(false);
renderer->drawGridlines(false);
// turn on terrain type overlay (off by default); NB you can stil call methods to update terrain type,
renderer->useTerrainTypeTexture(true);
renderer->useConstraintTypeTexture(false);
// use manipulator textures (decal'd)
renderer->textureManipulators(true);
// *** PM REnder code - end ***
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_MULTISAMPLE);
glEnable(GL_DEPTH_CLAMP);
glEnable(GL_TEXTURE_2D);
loadDecals();
glsun->init_gl();
}
void GLWidget::paintGL()
{
vpPoint mo;
glm::mat4 tfm, idt;
glm::vec3 trs, rot;
uts::vector<ShapeDrawData> drawParams; // to be passed to terrain renderer
Shape shape; // geometry for focus indicator
std::vector<Shape>::iterator sit;
std::vector<glm::mat4> sinst;
std::vector<glm::vec4> cinst;
Timer t;
t.start();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if(focuschange && focusviz)
{
ShapeDrawData sdd;
float scale;
char * cmap;
GLfloat manipCol[] = {0.325f, 0.235f, 1.0f, 1.0f};
// create shape
shape.clear();
shape.setColour(manipCol);
// place vertical cylinder at view focus
mo = getView()->getFocus();
scale = getView()->getScaleFactor();
idt = glm::mat4(1.0f);
trs = glm::vec3(mo.x, mo.y, mo.z);
rot = glm::vec3(1.0f, 0.0f, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(-90.0f), rot);
shape.genCappedCylinder(scale*armradius, 1.5f*scale*armradius, scale*(manipheight-manipradius), 40, 10, tfm, false);
if(shape.bindInstances(getView(), &sinst, &cinst)) // passing in an empty instance will lead to one being created at the origin
{
sdd = shape.getDrawParameters();
sdd.current = false;
drawParams.push_back(sdd);
}
}
if(cmode == ControlMode::PAINTLEARN)
{
std::vector<GLfloat> bcol(4);
memcpy(bcol.data(), getTypeMap(TypeMapType::PAINT)->getColour((int) palette->getDrawType()), sizeof(float) * 4);
ShapeDrawData sdd;
brushcursor.shape.clear();
brushcursor.setBrushColour(getTypeMap(TypeMapType::PAINT)->getColour((int) palette->getDrawType()));
brushcursor.genBrushRing(getView(), getTerrain(), getRadius(), false);
if(brushcursor.shape.bindInstances(getView(), &sinst, &cinst))
{
sdd = brushcursor.shape.getDrawParameters();
sdd.current = false;
sdd.brush = true;
drawParams.push_back(sdd);
}
}
else if (cmode == ControlMode::PAINTSPECIES)
{
ShapeDrawData sdd;
brushcursor.shape.clear();
brushcursor.setBrushColour(getTypeMap(TypeMapType::SPECIES)->getColour((int) species_palette->getDrawType()));
//brushcursor.setBrushColour(getTypeMap(TypeMapType::PAINT)->getColour((int) palette->getDrawType()));
brushcursor.genBrushRing(getView(), getTerrain(), getRadius(), false);
if(brushcursor.shape.bindInstances(getView(), &sinst, &cinst))
{
sdd = brushcursor.shape.getDrawParameters();
sdd.current = false;
sdd.brush = true;
drawParams.push_back(sdd);
}
}
if(focuschange)
{
// visualization of random hemispheric sampling
/*
SunLight * sun = new SunLight();
sun->bindDiffuseSun(getView(), getTerrain());
sun->drawSun(drawParams);
delete sun;
*/
// visualization of occluding canopy
/*
CanopyShape * suncanopy = new CanopyShape(0.5, getTerrain()->getCellExtent());
suncanopy->bindCanopy(getTerrain(), getView(), getCanopyHeightModel(), getCanopyDensityModel());
suncanopy->drawCanopy(drawParams);
delete suncanopy;*/
}
if (focuschange)
{
getEcoSys()->bindPlantsSimplified(getTerrain(), drawParams);
int nonzero_count = 0;
for (auto &dp : drawParams)
{
if (dp.VAO > 0)
nonzero_count++;
}
}
// pass in draw params for objects
renderer->setConstraintDrawParams(drawParams);
// draw terrain and plants
getTerrain()->updateBuffers(renderer);
if(focuschange)
renderer->updateTypeMapTexture(getTypeMap(getOverlay())); // only necessary if the texture is changing dynamically
renderer->draw(getView());
t.stop();
if(timeron)
cerr << "rendering = " << t.peek() << " fps = " << 1.0f / t.peek() << endl;
}
void GLWidget::resizeGL(int width, int height)
{
int side = qMin(width, height);
glViewport(0, 0, width, height);
// cerr << "GL: " << (int) width << " " << (int) height << " WINDOW " << this->width() << " " << this->height() << endl;
// apply to all views
for(int i = 0; i < (int) scenes.size(); i++)
{
// cerr << "VIEW RESIZED" << endl;
//scenes[i]->view->setDim((float) ((width - side) / 2), (float) ((height - side) / 2), (float) side, (float) side);
scenes[i]->view->setDim(0.0f, 0.0f, (float) this->width(), (float) this->height());
scenes[i]->view->apply();
}
}
void GLWidget::doCanopyPlacement()
{
MapFloat *chm = getCanopyHeightModel(); // TODO: scale CHM data from the 0 to 65535 range to 0 to 400
getPlacerCanopyHeightModel()->clone(*chm);
signalCanopyPlacementStart();
signalUpdateProgress(0);
if (chm) // doing this test might not be safe enough. Test for nonzero width, height too?
{
if (spacer)
{
delete spacer;
}
int minspec = species_assigned.calcmin();
int maxspec = species_assigned.calcmax();
std::cout << "Min species, max species: " << minspec << ", " << maxspec << std::endl;
int gw, gh;
getTerrain()->getGridDim(gw, gh);
auto bt = std::chrono::steady_clock::now().time_since_epoch();
memcpy(getPlacerCanopyHeightModel()->data(), getCanopyHeightModel()->data(), sizeof(float) * ipc_scaling.intscale * ipc_scaling.intscale * ipc_scaling.srcw * ipc_scaling.srch);
spacer = new canopy_placer(getPlacerCanopyHeightModel(), &species_assigned, species_infomap, cdata);
int max_iters = 5;
// this block of code emulates spacer->optimise(5)
spacer->init_optim();
for (int i = 0; i < max_iters; i++)
{
signalUpdateProgress((static_cast<float>(i) / max_iters) * 100);
spacer->iteration();
}
auto et = std::chrono::steady_clock::now().time_since_epoch();
auto placetime = std::chrono::duration_cast<std::chrono::milliseconds>(et - bt).count();
/*
spacer->eliminate_proxims();
*/
signalUpdateProgress(100);
spacer->update_treesholder();
std::cout << "Time to finish canopy placement (without duplicate checking): " << placetime << " ms" << std::endl;
//spacer->optimise(5); // this function call is emulated by the above code
float rw, rh;
getTerrain()->getTerrainDim(rw, rh);
canopytrees = spacer->get_trees_basic_rw_coords();
canopy_placer::erase_duplicates(canopytrees, rw, rh);
//spacer->erase_duplicates_fast(canopytrees, rw, rh);
//canopytrees = spacer->get_trees_basic();
canopytrees_indices = true;
et = std::chrono::steady_clock::now().time_since_epoch();
placetime = std::chrono::duration_cast<std::chrono::milliseconds>(et - bt).count();
std::cout << "Time to finish canopy placement (with duplicate checking): " << placetime << " ms" << std::endl;
// FIXME: canopy_placer::convert_trees_species needs to check if we already have indices or real species ids
spacer->convert_trees_species(canopy_placer::spec_convert::TO_ID);
auto realw_coords_trees = spacer->get_trees_basic_rw_coords();
spacer->convert_trees_species(canopy_placer::spec_convert::TO_IDX);
std::string canopyoutfile = pipeout_dirname + "/canopytrees_" + std::to_string(nspecassign) + "_" + std::to_string(nchmfiles) + ".pdb";
std::cout << "Done running canopy placement. Number of trees: " << canopytrees.size() << std::endl;
}
if (spacer)
{
delete spacer;
spacer = nullptr;
}
// why don't we clear plants here...?
redrawPlants(false, layerspec::CANOPY, clearplants::NO); // canopy trees get placed into the EcoSystem object here, so that it can be rendered in the interface
}
void GLWidget::read_pdb_canopy(std::string pathname)
{
canopytrees = data_importer::read_pdb(pathname);
canopytrees_indices = false;
// calculate quick and dirty canopy shading, based on just reducing grass height under each
// tree based on its alpha value, then smoothing
calc_fast_canopyshading();
if (undersynth_init)
{
if (!gpusample)
update_canopyshading_undersynth();
else
undersynth->update_sunmap(amaps_ptr->sun);
}
else if (cluster_filenames.size() > 0)
init_undersynth();
redrawPlants(false, layerspec::ALL, clearplants::YES);
repaint();
}
bool GLWidget::hasSceneLoaded()
{
return sceneloaded;
}
void GLWidget::read_pdb_undergrowth(std::string pathname)
{
underplants = data_importer::read_pdb(pathname);
redrawPlants(false, layerspec::ALL, clearplants::YES);
repaint();
}
void GLWidget::doSpeciesAssignment()
{
if (!specassign_ptr)
{
reset_specassign_ptr();
}
adapt_species_changed();
specassign_ptr->assign();
species_assigned = specassign_ptr->get_assigned();
for (auto iter = species_assigned.begin(); iter != species_assigned.end(); advance(iter, 1))
{
if (*iter > -1)
{
*iter = specidxes.at(*iter);
}
}
// FIXME: See FIXME in GLWidget::mouseReleaseEvent, at the statement similar to the one below
getTypeMap(TypeMapType::SPECIES)->convert(&species_assigned,
TypeMapType::SPECIES,
65535);
if (memory_scarce)
specassign_ptr.reset(nullptr);
}
void GLWidget::adapt_species_changed()
{
if (species_changed)
{
reset_specassign_ptr();
species_changed = false;
}
}
void GLWidget::setSpeciesPercentages(const std::vector<float> &perc)
{
species_percentages = perc;
}
void GLWidget::convert_canopytrees_to_real_species()
{
if (canopytrees_indices)
for (auto &ct : canopytrees)
{
ct.species = specidxes.at(ct.species);
}
canopytrees_indices = false;
}
void GLWidget::convert_canopytrees_to_indices()
{
if (!canopytrees_indices)
for (auto &ct : canopytrees)
{
for (int i = 0; i < specidxes.size(); i++)
{
if (specidxes.at(i) == ct.species)
{
ct.species = i;
}
}
}
canopytrees_indices = true;
}
void GLWidget::redrawPlants(bool repaint_here, layerspec layer, clearplants clr)
{
report_cudamem("GPU memory in use at start of redrawPlants: ");
if (clr == clearplants::YES)
getEcoSys()->clearAllPlants(getTerrain());
bool placecanopy = layer == layerspec::CANOPY || layer == layerspec::ALL;
bool placeunder = layer == layerspec::UNDERGROWTH || layer == layerspec::ALL;
if (show_canopy && placecanopy)
{
bool prevset = canopytrees_indices;
convert_canopytrees_to_real_species();
getEcoSys()->placeManyPlants(getTerrain(), canopytrees, true);
if (prevset)
convert_canopytrees_to_indices();
}
if (synth_undergrowth && show_undergrowth && placeunder)
{
getEcoSys()->placeManyPlants(getTerrain(), underplants, false);
}
getEcoSys()->redrawPlants();
if (repaint_here)
{
GL_ERRCHECK(false);
repaint();
GL_ERRCHECK(false); // TODO: figure out why we get a GL error here. It does not seem to affect the output, but it needs to be checked still
}
report_cudamem("GPU memory in use at end of redrawPlants: ");
}
void GLWidget::update_canopyshading_undersynth()
{
undersynth->update_canopytrees(canopytrees, canopyshading_temp);
}
void GLWidget::import_canopyshading(std::string canopyshading)
{
canopyshading_temp = data_importer::average_mmap<ValueGridMap<float>, ValueGridMap<float>>(data_importer::read_monthly_map<ValueGridMap<float> >(canopyshading));
float rw, rh;
getTerrain()->getTerrainDim(rw, rh);
canopyshading_temp.setDimReal(rw, rh);
if (undersynth_init && !gpusample)
update_canopyshading_undersynth();
else if (undersynth_init && gpusample)
{
undersynth->update_sunmap(amaps_ptr->sun);
}
}
void GLWidget::doFastUndergrowthSampling()
{
canopycalc.lock();
if (canopytrees.size() == 0)
{
QMessageBox info(this);
info.setText("No canopy trees from which to sample undergrowth");
info.exec();
canopycalc.unlock();
return;
}
if (undersynth_init)
{
signalUndergrowthSampleStart();
auto progresssignal = [this](int val) {signalUpdateProgress(val); };
undersynth->set_progress_callback(progresssignal);
auto bt = std::chrono::steady_clock::now().time_since_epoch();
if (!gpusample)
underplants = undersynth->sample_undergrowth();
else
{
bool convert_back = false;
if (canopytrees_indices)
{
convert_back = true;
convert_canopytrees_to_real_species();
}
underplants = undersynth->sample_undergrowth_gpu(canopytrees);
for (auto &up : underplants)
up.radius = cdata.modelsamplers.at(up.species).sample_rh_ratio(up.height) * up.height;
if (convert_back)
convert_canopytrees_to_indices();
}
auto et = std::chrono::steady_clock::now().time_since_epoch();
std::cout << "Redrawing plants..." << std::endl;
redrawPlants(false, layerspec::ALL, clearplants::YES); // undergrowth plants get placed into the EcoSystem object here, so that it can be rendered in the interface
// repaint again, since we now also have the undergrowth plants
signalRepaintAllFromThread();
int time = std::chrono::duration_cast<std::chrono::milliseconds>(et - bt).count();
std::cout << "Time taken for undergrowth sampling: " << time << " ms" << std::endl;
undergrowth_sampled = true;
}
else
{
std::cout << "Undersynth object not initialized. Cannot do undergrowth sampling. " << std::endl;
QMessageBox errdialog(this);
errdialog.setText("Undersynth object not initialized. Cannot do undergrowth sampling.\nDid you import a clusterfile already?");
errdialog.exec();
}
canopycalc.unlock();
}
void GLWidget::doUndergrowthSynthesisPart(int startrow, int endrow, int startcol, int endcol)
{
throw not_implemented("GLWidget::doUndergrowthSynthesisPart not implemented");
}
void GLWidget::doUndergrowthSynthesis()
{
canopycalc.lock();
signalUndergrowthRefineStart();
auto signalfunc = [this](int val)
{
this->signalUpdateProgress(val);
};
bool convert_back = false;
if (canopytrees_indices)
{
convert_back = true;
convert_canopytrees_to_real_species();
}
calc_fast_canopyshading();
update_canopyshading_undersynth();
if (convert_back)
{
convert_canopytrees_to_indices();
}
undersynth->set_undergrowth(underplants);
undersynth->set_progress_callback(signalfunc);
undersynth->refine();
underplants = undersynth->get_undergrowth();
redrawPlants(false, layerspec::ALL, clearplants::YES); // plants get placed into the EcoSystem object here
set_pretty_map(); // resetting the entire pretty map might be a little slow. Find alternative?
loadTypeMap(&pretty_map_painted, TypeMapType::PRETTY_PAINTED);
loadTypeMap(&pretty_map, TypeMapType::PRETTY);
signalRepaintAllFromThread();
canopycalc.unlock();
}
void GLWidget::doUndergrowthSynthesisCallback()
{
if (!undergrowth_sampled || underplants.size() == 0)
{
QMessageBox info(this);
info.setText("Undergrowth should be sampled first before refinement can be done");
info.exec();
return;
}
std::thread t(&GLWidget::doUndergrowthSynthesis, this);
t.detach();
}
void GLWidget::doCanopyPlacementAndSpeciesAssignment()
{
// we use a mutex here, so that only one thread can use all GPU resources required
// in this function
std::cout << "Waiting for mutex to unlock..." << std::endl;
canopycalc.lock();
report_cudamem("Memory in use before canopy placement and species assignment function: ");
std::cout << "Thread locked mutex" << std::endl;
auto bt = std::chrono::steady_clock::now().time_since_epoch();
// reset state that indicates if undergrowth sampled or not (because if canopy changes, undergrowth will also change)
undergrowth_sampled = false;
getEcoSys()->clearAllPlants(getTerrain());
underplants.clear();
canopytrees.clear();
report_cudamem("Memory in use before species assignment: ");
doSpeciesAssignment();
report_cudamem("Memory in use after species assignment: ");
doCanopyPlacement();
// since this function can be called from a thread, we use a separate signal for
// repainting (so that user can look at updated maps and canopy while undergrowth synthesizes
signalRepaintAllFromThread();
std::cout << "Calculating fast canopyshading..." << std::endl;
// calculate quick and dirty canopy shading, based on just reducing grass height under each
// tree based on its alpha value, then smoothing
// The function calc_fast_canoyshading call below can be a bit slow on larger landscapes.
// Calculating canopyshading here is more for the sunlight texture overlay. If GPU sampling of
// undergrowth will be utilised, then sunlight shading will be calculated on the GPU anyway, for
// use by the undergrowth sampling algorithm. Uncomment the if statement below, "if (!gpusample)",
// to compute canopytree shading only if CPU sampling of undergrowth will be done.
// TODO: use the sunlight calculation function from gpusample.cu instead of this function for a fast
// computation of sunlight, taking into account tree shade.
//if (!gpusample)
calc_fast_canopyshading();
convert_canopytrees_to_real_species();
if (undersynth_init)
{
if (!gpusample)
update_canopyshading_undersynth();
else
undersynth->update_sunmap(amaps_ptr->sun);
}
else if (cluster_filenames.size() > 0)
{
// FIXME: this needs to be initialized before doing first canopy placement.
// Create new ctor for UndergrowthSampler class, which does not require
// canopytrees
init_undersynth();
}
convert_canopytrees_to_indices();
// calculate grass based on updated canopy
std::string grassfilename = pipeout_dirname + "/grass_" + std::to_string(nspecassign) + "_" + std::to_string(nchmfiles) + ".txt";
std::string litterfilename = pipeout_dirname + "/litterfall_" + std::to_string(nspecassign) + "_" + std::to_string(nchmfiles) + ".txt";
ngrassfiles++;
// setting conditions is cheap - simply a pointer assignment, so we do it just in case...
getGrass()->setConditions(getSim()->get_average_moisture_map(), getSim()->get_average_adaptsun_map(), getSim()->get_average_landsun_map(), getSim()->get_temperature_map());
std::cout << "Growing grass..." << std::endl;
getGrass()->grow(getTerrain(), canopytrees, cdata, scf);
set_pretty_map(); // resetting the entire pretty map might be a little slow. Find alternative?
loadTypeMap(&pretty_map_painted, TypeMapType::PRETTY_PAINTED);
loadTypeMap(&pretty_map, TypeMapType::PRETTY);
auto et = std::chrono::steady_clock::now().time_since_epoch();
int time = std::chrono::duration_cast<std::chrono::milliseconds>(et - bt).count();
std::cout << "Time taken for canopy placement and species assignment: " << time << std::endl;
report_cudamem("Memory in use after canopy placement and species assignment function: ");
std::cout << "Signalling repaint all from thread..." << std::endl;
std::cout << "Thread unlocking mutex..." << std::endl;
canopycalc.unlock();
std::cout << "Mutex unlocked" << std::endl;
}
void GLWidget::report_cudamem(std::string msg) const
{
size_t freemem, totalmem, inuse;
gpuErrchk(cudaMemGetInfo(&freemem, &totalmem));
inuse = totalmem - freemem;
inuse /= 1024 * 1024;
std::cout << msg << " " << inuse << "MB" << std::endl;
}
void GLWidget::reset_common_maps()
{
std::cout << "Setting clustermaps..." << std::endl;
// set maps that indicate where different abiotic clusters are, and what the required plant densities are for each cluster
set_clustermap();
set_clusterdensitymap();
loadTypeMap(&clustermap, TypeMapType::CLUSTER);
loadTypeMap(&clusterdensitymap, TypeMapType::CLUSTERDENSITY);
std::cout << "Setting pretty map..." << std::endl;
// set the map that contains indicators for grass, rivers and rock (requires grass simulation to be finished)
set_pretty_map(); // resetting the entire pretty map might be a little slow. Find alternative?
loadTypeMap(&pretty_map_painted, TypeMapType::PRETTY_PAINTED);
loadTypeMap(&pretty_map, TypeMapType::PRETTY);
}
void GLWidget::calc_fast_canopyshading()
{
float rw, rh;
getTerrain()->getTerrainDim(rw, rh);
//calculate updated sunlight based on new canopy trees (quick and dirty)
getSim()->calc_adaptsun(canopytrees, cdata, rw, rh);
MapFloat *adaptsun = getSim()->get_adaptsun();
// do some smoothing on the fast canopy shading calculation
int dx, dy, dx2, dy2;
canopyshading_temp.getDim(dx, dy);
adaptsun->getDim(dx2, dy2);
if (dx != dx2 || dy != dy2)
{
canopyshading_temp.setDim(dx2, dy2);
canopyshading_temp.setDimReal(rw, rh);
}
//smooth_uniform_radial(15, adaptsun->data(), adaptsun->data(), dx2, dy2);
memcpy(canopyshading_temp.data(), adaptsun->data(), sizeof(float) * dx2 * dy2);
}
void GLWidget::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_A) // 'A' for animated spin around center point of terrain
{
// change focal point to center
getTerrain()->setMidFocus();
getView()->setForcedFocus(getTerrain()->getFocus());
getView()->startSpin();
rtimer->start(20);
}
if(event->key() == Qt::Key_C) // 'C' to show canopy height model texture overlay
{
setOverlay(TypeMapType::CHM);
redrawPlants(true, layerspec::ALL, clearplants::YES);
}
if(event->key() == Qt::Key_D) // 'D' switch to painting overlay
{
setOverlay(TypeMapType::PAINT);
}
if(event->key() == Qt::Key_E) // 'E' to remove all texture overlays
{
cerr << "overlay changed to empty" << endl;
setOverlay(TypeMapType::EMPTY);
refreshOverlay();
}
if(event->key() == Qt::Key_F) // 'F' to toggle focus stick visibility
{
if(focusviz)
focusviz = false;
else
focusviz = true;
update();
}
if(event->key() == Qt::Key_I) // 'I' for close ueval screencap
{
cerr << "image capture: close up" << endl;
getTerrain()->setMidFocus();
getView()->setForcedFocus(getTerrain()->getFocus());
getView()->closeview();
QImage cap;
screenCapture(&cap, QSize(500,500));
cap.save(QCoreApplication::applicationDirPath() + "/../close.png");
update();
}
if (event->key() == Qt::Key_J)
{
loadTypeMap(getGrass()->get_data(), TypeMapType::GRASS);
setOverlay(TypeMapType::GRASS);
}
if (event->key() == Qt::Key_L)
{
setOverlay(TypeMapType::PRETTY_PAINTED);
}
if (event->key() == Qt::Key_M)
{
setOverlay(TypeMapType::SPECIES);
}
if (event->key() == Qt::Key_N)
{
show_undergrowth = !show_undergrowth;
redrawPlants();
}
if (event->key() == Qt::Key_O)
{
std::thread t(&GLWidget::doUndergrowthSynthesisPart, this, 0, 40, 0, 40);
t.detach();
}
if(event->key() == Qt::Key_P) // 'P' to toggle plant visibility
{
if(focuschange)
focuschange = false;
else
focuschange = true;
update();
}
if(event->key() == Qt::Key_R) // 'R' to show temperature texture overlay
{
loadTypeMap(getSlope(), TypeMapType::SLOPE);
setOverlay(TypeMapType::SLOPE);
}
if(event->key() == Qt::Key_S) // 'S' to show sunlight texture overlay
{
int gw, gh;
canopyshading_temp.getDim(gw, gh);
MapFloat *sun = new MapFloat;
sun->setDim(gw, gh);
memcpy(sun->data(), canopyshading_temp.data(), sizeof(float) * gw * gh);
loadTypeMap(sun, TypeMapType::SUNLIGHT);
setOverlay(TypeMapType::SUNLIGHT);
delete sun;
}
if(event->key() == Qt::Key_T) // 'T' to show slope texture overlay
{
loadTypeMap(getSim()->get_temperature_map(), TypeMapType::TEMPERATURE);
setOverlay(TypeMapType::TEMPERATURE);
}
if(event->key() == Qt::Key_V) // 'V' for top-down view
{
cerr << "top down view" << endl;
getTerrain()->setMidFocus();
getView()->setForcedFocus(getTerrain()->getFocus());
getView()->topdown();
update();
}
if(event->key() == Qt::Key_W) // 'W' to show water texture overlay
{
wet_mth++;
if(wet_mth >= 12)
wet_mth = 0;
//loadTypeMap(getMoisture(wet_mth), TypeMapType::WATER);
loadTypeMap(getSim()->get_average_moisture_map(), TypeMapType::WATER);
setOverlay(TypeMapType::WATER);
}
if (event->key() == Qt::Key_X)
{
setOverlay(TypeMapType::PRETTY);
}
if (event->key() == Qt::Key_Y)
{
show_canopy = !show_canopy;
redrawPlants();
}
/*
* // Currently, showing the clusters and their densities on the landscape is not implemented, since we would
* // have to provide for both the GPU and CPU version.
* // TODO: refactor so that clusters are computed once, before synthesizing undergrowth, on the GPU so that it is
* // done fast, and also so that clusters are available to the interface without synthesizing undergrowth
if (event->key() == Qt::Key_Z)
{
setOverlay(TypeMapType::CLUSTER);
}
if (event->key() == Qt::Key_0)
{
setOverlay(TypeMapType::CLUSTERDENSITY);
}
*/
}
void GLWidget::mousePressEvent(QMouseEvent *event)
{
float nx, ny;
vpPoint pnt;
int x = event->x(); int y = event->y();
float W = (float) width(); float H = (float) height();
update(); // ensure this viewport is current for unproject
// control view orientation with right mouse button or ctrl/alt modifier key and left mouse
if(!viewlock && (event->modifiers() == Qt::AltModifier || event->buttons() == Qt::RightButton))
{
// arc rotate in perspective mode
// convert to [0,1] X [0,1] domain
nx = (2.0f * (float) x - W) / W;
ny = (H - 2.0f * (float) y) / H;
lastPos = event->pos();
getView()->startArcRotate(nx, ny);
viewing = true;
}
else if (!viewlock && (event->modifiers() == Qt::ControlModifier))
{
vpPoint frompnt, topnt;
getView()->projectingPoint(x, y, frompnt);
terrainProject(frompnt, topnt, getView(), getTerrain());
getView()->setForcedLocation(topnt.x, topnt.y + 2.0f, topnt.z);
lastPos = event->pos();
update();
}
else if (!viewlock && (event->modifiers() == Qt::ShiftModifier))
{
lastPos = event->pos();
}
else
{
if(cmode == ControlMode::PAINTLEARN) // painting types onto terrain
{
//if(getOverlay() != TypeMapType::PAINT)
// setOverlay(TypeMapType::PAINT);
brush.startStroke();
// normal brush drawing
brush = BrushPaint(getTerrain(), palette->getDrawType());
// writes values to the grid representing the painting. Refer to the brushtype variable for info on these values.
// when the image gets written in the writePaintMap function (then saveToPaintImage) these values get converted to 0, 127, or 255, from 0, 1, or 2.
//brush.addMousePnt(getView(), getTypeMap(getOverlay()), x, y, getRadius());
//renderer->updateTypeMapTexture(getTypeMap(getOverlay()));
brush.addMousePnt(getView(), getTypeMap(TypeMapType::PAINT), x, y, getRadius());
//renderer->updateTypeMapTexture(getTypeMap(TypeMapType::PAINT));
renderer->updateTypeMapTexture(getTypeMap(getOverlay()));
// getEcoSys()->pickPlants(getTerrain(), getTypeMap(overlay));
update();
}
else if (cmode == ControlMode::PAINTSPECIES && !memory_scarce) // we don't do species painting with memory-scarce landscapes
{
std::cout << "Entering mousepressevent for paintspecies..." << std::endl;
brush.startStroke();
// normal brush drawing
brush = BrushPaint(getTerrain(), (BrushType)species_palette->getDrawType());
// writes values to the grid representing the painting. Refer to the brushtype variable for info on these values.
// when the image gets written in the writePaintMap function (then saveToPaintImage) these values get converted to 0, 127, or 255, from 0, 1, or 2.
//brush.addMousePnt(getView(), getTypeMap(getOverlay()), x, y, getRadius());
//renderer->updateTypeMapTexture(getTypeMap(getOverlay()));
specassign_ptr->clear_brushstroke_data();
brush.addMousePnt(getView(), getTypeMap(TypeMapType::SPECIES), x, y, getRadius());
//renderer->updateTypeMapTexture(getTypeMap(TypeMapType::SPECIES));
renderer->updateTypeMapTexture(getTypeMap(getOverlay()));
//int specidx = (int)species_palette->getDrawType() - (int)BrushType::SPEC1;
int specid = (int)species_palette->getDrawType();
//int specid = allcanopy_idx_to_id.at(specidx);
int specopt_idx = specassign_id_to_idx.at(specid);
update_species_brushstroke(x, y, getRadius(), specopt_idx);
// getEcoSys()->pickPlants(getTerrain(), getTypeMap(overlay));
update();
std::cout << "Done with mousepressevent for paintspecies" << std::endl;
}
}
lastPos = event->pos();
}
void GLWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
// set the focus for arcball rotation
// pick point on terrain or zero plane if outside the terrain bounds
vpPoint pnt;
int sx, sy;
sx = event->x(); sy = event->y();
if(!viewlock && ((event->modifiers() == Qt::MetaModifier && event->buttons() == Qt::LeftButton) || (event->modifiers() == Qt::AltModifier && event->buttons() == Qt::LeftButton) || event->buttons() == Qt::RightButton))
{
getView()->apply();
if(getTerrain()->pick(sx, sy, getView(), pnt))
{
if(!decalsbound)
loadDecals();
vpPoint pickpnt = pnt;
getView()->setAnimFocus(pickpnt);
getTerrain()->setFocus(pickpnt);
cerr << "Pick Point = " << pickpnt.x << ", " << pickpnt.y << ", " << pickpnt.z << endl;
focuschange = true; //focusviz = true;
atimer->start(10);
}
// ignores pick if terrain not intersected, should possibly provide error message to user
}
if(!viewlock && event->buttons() == Qt::LeftButton) // provide info on terrain
{
if(getTerrain()->pick(sx, sy, getView(), pnt))
{
if(!decalsbound)
loadDecals();
// TO DO: depending on viewing mode, may find sample in DB or value from terrain
// getEcoSys()->displayCursorSampleDB(getTerrain(), pnt);
}
}
}
void GLWidget::setPlantsVisibility(bool visible)
{
focuschange = visible;
}
void GLWidget::setCanopyVisibility(bool visible)
{
show_canopy = visible;
}
void GLWidget::setUndergrowthVisibility(bool visible)
{
show_undergrowth = visible;
}
void GLWidget::pickInfo(int x, int y)
{
std::string catName;
int gw, gh;
bool canopyshading = false;
canopyshading_temp.getDim(gw, gh);
if (gw > 0 && gh > 0)
{
canopyshading = true;
}
cerr << endl;
cerr << "*** PICK INFO ***" << endl;
cerr << "location: " << x << ", " << y << endl;
Simulation *sim = getSim();
if (sim->hasTerrain())
{
sim->pickInfo(x, y);
cerr << "Elevation (m): " << getTerrain()->getHeight(x, y) << std::endl;
cerr << "Canopy Height (m): " << getCanopyHeightModel()->get(x, y) * 0.3048f << endl;
if (canopyshading)
cerr << "Canopy shading: " << canopyshading_temp.get(x, y) << endl;
}
}
int GLWidget::get_terscale_down(int req_dim)
{
int terw, terh;
getTerrain()->getGridDim(terw, terh);
float scf_w = terw / (float)req_dim;
float scf_h = terh / (float)req_dim;
//assert(abs(scf_h - scf_w) < 1e-3); // for now, assume that scf_w and scf_h must be the same. TODO: allow to be different
//assert(abs(scf_h - round(scf_h)) < 1e-3); // assume scale factor is an int
int scale_down = int(round(scf_h));
return scale_down;
}
void GLWidget::write_chmfiles()
{
std::string chmout = pipeout_dirname + "/chm_" + std::to_string(nspecassign) + "_" + std::to_string(nchmfiles) + ".txt";
std::string chmout_upsampled = pipeout_dirname + "/chm_upsampled_" + std::to_string(nspecassign) + "_" + std::to_string(nchmfiles) + ".txt";
data_importer::write_txt(chmout, ipc_received_raw);
data_importer::write_txt(chmout_upsampled, getCanopyHeightModel());
}
void GLWidget::set_ipc_scaling()
{
// get dimensions of output received from neural net
ipc_received_raw->getDim(ipc_scaling.srcw, ipc_scaling.srch);
// get terrain dimensions and required scaling factor for neural net input
getTerrain()->getGridDim(ipc_scaling.terw, ipc_scaling.terh);
float wscale = ipc_scaling.terw / (float)ipc_scaling.srcw;
float hscale = ipc_scaling.terh / (float)ipc_scaling.srch;
assert(abs(wscale - hscale) < 1e-3); // for now, assume that hscale and wscale must be the same. TODO: allow to be different
assert(abs(wscale - round(wscale)) < 1e-3); // also only allow integer scaling sizes, for now. TODO: allow float scaling sizes...
ipc_scaling.intscale = round(wscale);
}
void GLWidget::set_specassign_chm(MapFloat *chm)
{
if (!specassign_ptr)
return;
int w, h;
chm->getDim(w, h);
ValueMap<float> tempchm;
tempchm.setDim(*chm);
//memcpy(tempchm.data(), getCanopyHeightModel()->data(), sizeof(float) * ipc_scaling.intscale * ipc_scaling.intscale * ipc_scaling.srcw * ipc_scaling.srch);
memcpy(tempchm.data(), getCanopyHeightModel()->data(), sizeof(float) * w * h);
report_cudamem("GPU memory in use before specassign_ptr->set_chm: ");
specassign_ptr->set_chm(tempchm);
report_cudamem("GPU memory in use after specassign_ptr->set_chm: ");
}
void GLWidget::correct_chm_scaling()
{
MapFloat *chm = getCanopyHeightModel(); // TODO: scale CHM data from the 0 to 65535 range to 0 to 400
float *chmdata = chm->data();
// FIXME: remove this hack, together with the corresponding loop below
float max_height = 0.0f;
for (int i = 0; i < chm->width() * chm->height(); i++)
{
chmdata[i] *= 400.0f / 65535.0f;
if (chmdata[i] < 1.0f)
{
chmdata[i] = 0.0f;
}
if (chmdata[i] > max_height) max_height = chmdata[i];
}
std::cout << "Maximum height: " << max_height << std::endl;
}
void GLWidget::send_and_receive_nnet()
{
Timer t;
t.start();
// send inputs to neural net
int scale_down = get_terscale_down(scale_size); // get the scaling down factor to have image fit into neural net - FIXME: this must actually be 4 always, but we just use this now for experimentation with smaller landscapes
std::cout << "Sending input to neural net..." << std::endl;
ipc->send(getTypeMap(TypeMapType::PAINT), getTerrain(), scale_down);
std::cout << "Waiting for response from neural net..." << std::endl;
// wait to receive neural net outputs
ipc->receive_only(ipc_received_raw);
//ipc->receive(getCanopyHeightModel());
std::cout << "Setting scaling factor for nnet..." << std::endl;
// set scaling factor for neural net output
set_ipc_scaling();
report_cudamem("GPU memory in use before bilinear upsample: ");
std::cout << "Upsampling neural net output..." << std::endl;
// upsample chm we obtained from neural net by the appropriate factor (should be 4, see comment at top of function)
bilinear_upsample_colmajor_allocate_gpu(ipc_received_raw->data(), getCanopyHeightModel()->data(), ipc_scaling.srcw, ipc_scaling.srch, ipc_scaling.intscale); // TODO: Make this upsample factor a class variable or constant or something
report_cudamem("GPU memory in use after bilinear upsample: ");
correct_chm_scaling();
// set CHM for species assignment. Find a quicker way to do this...?
set_specassign_chm(getCanopyHeightModel());
//getTypeMap(TypeMapType::CHM)->convert(getCanopyHeightModel(), TypeMapType::CHM, mtoft*initmaxt);
cerr << "typemap size: " << getTypeMap(TypeMapType::CHM)->width() << ", " << getTypeMap(TypeMapType::CHM)->height() << std::endl;
cerr << "CHM size: " << getCanopyHeightModel()->width() << ", " << getCanopyHeightModel()->height() << std::endl;
t.stop();
cerr << "Time for data send and receive " << t.peek() << endl;
}
void GLWidget::send_drawing()
{
report_cudamem("GPU memory in use at start of send_drawing: ");
nundergrowthfiles = 0;
// update map on terrain, based on latest brushstroke
std::cout << "Setting buffer to dirty..." << std::endl;
getTerrain()->setBufferToDirty();
std::cout << "Setting paint region..." << std::endl;
getTypeMap(TypeMapType::PAINT)->setRegion(getTerrain()->coverRegion());
std::cout << "Updating typemap texture..." << std::endl;
report_cudamem("GPU memory in use before updateTypeMapTexture: ");
renderer->updateTypeMapTexture(getTypeMap(getOverlay())); // update the map we see in the interface, based on the lastest brushstroke
report_cudamem("GPU memory in use after updateTypeMapTexture: ");
nchmfiles++;
// getEcoSys()->synth(getTerrain(), scf, 2, getTypeMap(TypeMapType::PAINT));
//if (!specassign_ptr)
// reset_specassign_ptr();
std::cout << "Sending and receiving from nnet..." << std::endl;
report_cudamem("GPU memory in use before send_and_receive_nnet: ");
send_and_receive_nnet();
report_cudamem("GPU memory in use after send_and_receive_nnet: ");
getTypeMap(TypeMapType::CHM)->convert(getCanopyHeightModel(), TypeMapType::CHM, 400); // XXX: use loadTypeMap instead
renderer->updateTypeMapTexture(getTypeMap(getOverlay()));
report_cudamem("GPU memory in use before doCanopyPlacementAndSpeciesAssignment: ");
std::thread thrd(&GLWidget::doCanopyPlacementAndSpeciesAssignment, this);
thrd.detach();
}
void GLWidget::mouseReleaseEvent(QMouseEvent *event)
{
//renderer->updateTypeMapTexture(getTypeMap(TypeMapType::PAINT));
viewing = false;
if(event->button() == Qt::LeftButton && cmode == ControlMode::PAINTLEARN)
{
brush.finStroke();
//send_drawing();
}
if(event->button() == Qt::LeftButton && cmode == ControlMode::VIEW) // info on terrain cell
{
vpPoint pnt;
int sx, sy;
sx = event->x(); sy = event->y();
if (getTerrain()->pick(sx, sy, getView(), pnt))
{
int x, y;
getTerrain()->toGrid(pnt, x, y);
pickInfo(x, y);
}
}
if (event->button() == Qt::LeftButton && cmode == ControlMode::PAINTSPECIES)
{
brush.finStroke();
optimise_species_brushstroke("");
nspecassign++;
}
}
void GLWidget::optimise_species_brushstroke(std::string outfile)
{
canopycalc.lock();
signalSpeciesOptimStart();
auto progupdate = [this](int val) { signalUpdateProgress(val); };
specassign_ptr->set_progress_func(progupdate);
int spec_idx;
int specid = (int)species_palette->getDrawType();
//int specid = allcanopy_idx_to_id.at(specidx);
//spec_idx = (int)btype - (int)BrushType::SPEC1;
spec_idx = specassign_id_to_idx.at(specid);
specassign_ptr->optimise_brushstroke(spec_idx, getSpecPerc(), outfile);
specassign_ptr->clear_brushstroke_data();
canopycalc.unlock();
}
void GLWidget::reset_filecounts()
{
nundergrowthfiles = 0;
}
void GLWidget::update_prettypaint(int x, int y, float radius)
{
float fgx, fgy, fgh;
int gx, gy, gh;
float irad, sqirad;
int sx, ex, sy, ey;
int dx, dy;
vpPoint prjpnt, terpnt;
getView()->projectingPoint(x, y, prjpnt);
bool valid = terrainProject(prjpnt, terpnt, getView(), getTerrain());
getTerrain()->toGrid(terpnt, fgx, fgy, fgh);
gx = fgx; gy = fgy; gh = fgh;
irad = getTerrain()->toGrid(radius);
getTerrain()->getGridDim(dx, dy);
sqirad = irad * irad;
sx = gx - irad;
sy = gy - irad;
ey = gx + irad;
ey = gy + irad;
sx = sx < 0 ? 0 : (sx >= dx ? dx - 1 : sx);
ex = ex < 0 ? 0 : (ex >= dx ? dx - 1 : ex);
sy = sy < 0 ? 0 : (sy >= dx ? dx - 1 : sy);
ey = ey < 0 ? 0 : (ey >= dx ? dx - 1 : ey);
TypeMap *tmap = getTypeMap(TypeMapType::PRETTY_PAINTED);
#pragma omp parallel for
for (int cx = sx; cx <= ex; cx++)
{
for (int cy = sy; cy <= ey; cy++)
{
float diffx = cx - fgx; diffx *= diffx;
float diffy = cy - fgy; diffy *= diffy;
if (diffx + diffy <= sqirad)
{
BrushType btype = brush.getBrushType();
int ibtype = (int)btype;
float prevval = pretty_map_painted.get(cx, cy);
int prevcat = prevval / 1000000;
pretty_map_painted.set(cx, cy, prevval - prevcat * 1000000); // first remove the class encoded into the value of the pretty map
pretty_map_painted.set(cx, cy, pretty_map_painted.get(cx, cy) + ibtype * 1000000); // now add the new class given by the current brush
tmap->set(cx, cy, pretty_map_painted.get(cx, cy)); // update type map directly also, instead of using the loadTypeMap function to do everything each time
}
}
}
}
void GLWidget::update_species_brushstroke(int x, int y, float radius, int specie)
{
float fgx, fgy, fgh;
int gx, gy, gh;
float irad, sqirad;
int sx, ex, sy, ey;
int dx, dy;
vpPoint prjpnt, terpnt;
getView()->projectingPoint(x, y, prjpnt);
bool valid = terrainProject(prjpnt, terpnt, getView(), getTerrain());
getTerrain()->toGrid(terpnt, fgx, fgy, fgh);
gx = fgx; gy = fgy; gh = fgh;
irad = getTerrain()->toGrid(radius);
std::swap(gx, gy); // have to swap these, since landscape xy's are the other way around
specassign_ptr->add_drawn_circle(gx, gy, irad, 1.0f, specie);
}
void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
float nx, ny, W, H;
int x = event->x();
int y = event->y();
W = (float) width();
H = (float) height();
// control view orientation with right mouse button or ctrl modifier key and left mouse
if(!viewlock && ((event->modifiers() == Qt::MetaModifier && event->buttons() == Qt::LeftButton) || (event->modifiers() == Qt::AltModifier && event->buttons() == Qt::LeftButton) || event->buttons() == Qt::RightButton))
{
// convert to [0,1] X [0,1] domain
nx = (2.0f * (float) x - W) / W;
ny = (H - 2.0f * (float) y) / H;
getView()->arcRotate(nx, ny);
update();
lastPos = event->pos();
}
else if (!viewlock && ((event->buttons() & (Qt::RightButton | Qt::LeftButton)) && event->modifiers() == Qt::ShiftModifier))
{
vpPoint frompnt, topnt1, topnt2;
getView()->projectingPoint(lastPos.x(), lastPos.y(), frompnt);
terrainProject(frompnt, topnt1, getView(), getTerrain());
getView()->projectingPoint(x, y, frompnt);
terrainProject(frompnt, topnt2, getView(), getTerrain());
//std::cout << "Terrain point: " << topnt.x << ", " << topnt.z << std::endl;
getView()->startPan(topnt1.x, topnt1.z);
getView()->pan(topnt2.x, topnt2.z);
lastPos = event->pos();
update();
}
else if(event->buttons() == Qt::LeftButton && cmode == ControlMode::PAINTLEARN)
{
brush.addMousePnt(getView(), getTypeMap(TypeMapType::PAINT), x, y, getRadius());
renderer->updateTypeMapTexture(getTypeMap(getOverlay())); // update the current map shown
update_prettypaint(x, y, getRadius());
update();
}
else if (event->buttons() == Qt::LeftButton && cmode == ControlMode::PAINTSPECIES)
{
brush.addMousePnt(getView(), getTypeMap(TypeMapType::SPECIES), x, y, getRadius());
renderer->updateTypeMapTexture(getTypeMap(getOverlay())); // update the current map shown
int specid = (int)species_palette->getDrawType();
int specopt_idx = specassign_id_to_idx.at(specid);
update_species_brushstroke(x, y, getRadius(), specopt_idx);
update();
}
if(!(event->buttons() == Qt::AllButtons) && (cmode == ControlMode::PAINTLEARN || cmode == ControlMode::PAINTSPECIES)) // show brush outline, whether or not the mouse is down
{
// show brush
brushcursor.cursorUpdate(getView(), getTerrain(), x, y);
update();
}
}
void GLWidget::wheelEvent(QWheelEvent * wheel)
{
float del;
QPoint pix = wheel->pixelDelta();
QPoint deg = wheel->angleDelta();
if(!viewlock)
{
if(!pix.isNull()) // screen resolution tracking, e.g., from magic mouse
{
del = (float) pix.y() * 30.0f;
getView()->incrZoom(del);
update();
}
else if(!deg.isNull()) // mouse wheel instead
{
del = (float) -deg.y() * 30.0f;
getView()->incrZoom(del);
update();
}
}
}
void GLWidget::animUpdate()
{
if(getView()->animate())
update();
}
void GLWidget::rotateUpdate()
{
if(getView()->spin())
update();
}
void GLWidget::initCHM(int w, int h)
{
getCanopyHeightModel()->setDim(w, h);
getCanopyHeightModel()->initMap();
getPlacerCanopyHeightModel()->setDim(w, h);
getPlacerCanopyHeightModel()->initMap();
}
| 92,145
|
C++
|
.cpp
| 2,404
| 31.671381
| 237
| 0.625398
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,215
|
stroke.cpp
|
jgain_EcoLearn/EcoSynth/viewer/stroke.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
/* file: stroke.cpp
author: (c) James Gain, 2006
project: ScapeSketch - sketch-based design of procedural landscapes
notes: Forming 2d mouse input into strokes for sketch and gesture purposes
changes:
*/
#include "stroke.h"
#include "shape.h"
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <list>
#include <algorithm>
///
/// GENERAL PROJECTION ROUTINES
///
void planeProject(View * view, uts::vector<vpPoint> * from, uts::vector<vpPoint> * to, Plane * projPlane)
{
uts::vector<vpPoint> copy; // <from> and <to> may be the same so this requires some care
float tval;
Vector dirn;
vpPoint p, cop;
// project stroke onto plane
cop = view->getCOP();
for(int i = 0; i < (int) from->size(); i++)
{
dirn.diff(cop, (* from)[i]);
if(projPlane->rayPlaneIntersect(cop, dirn, tval))
{
dirn.mult(tval);
dirn.pntplusvec(cop, &p);
copy.push_back(p);
}
}
to->clear();
(* to) = copy;
}
// assumes <from> and <to> strokes are not the same
void screenProject(View * view, uts::vector<vpPoint> * from, uts::vector<vpPoint> * to)
{
vpPoint vcop, pcop, proj;
Vector vdir, pdir;
Plane vplane;
to->clear();
// set up projection plane
vcop = view->getCOP();
vdir = view->getDir();
vdir.mult(0.2f); // not too close for precision reasons
vdir.pntplusvec(vcop, &pcop);
vdir.normalize();
vplane.formPlane(pcop, vdir);
// apply projection
for(int i = 0; i < (int) from->size(); i++)
{
pdir.diff(vcop, (* from)[i]);
if(vplane.rayPlaneIntersect(vcop, pdir, proj))
to->push_back(proj);
}
}
void drapeProject(uts::vector<vpPoint> * from, uts::vector<vpPoint> * to, Terrain * ter)
{
int i;
uts::vector<vpPoint> copy;
vpPoint dpnt;
// drape onto the landscape
for(i = 0; i < (int) from->size(); i++)
{
ter->drapePnt((* from)[i], dpnt);
copy.push_back(dpnt); // add draped point to list
}
to->clear();
(* to) = copy;
copy.clear();
}
void dropProject(uts::vector<vpPoint> * from, uts::vector<vpPoint> * to)
{
int i;
vpPoint dpnt;
uts::vector<vpPoint> copy;
// zero y-coordinate
for(i = 0; i < (int) from->size(); i++)
{
dpnt = (* from)[i];
dpnt.y = 0.0f;
copy.push_back(dpnt); // add dropped point to list
}
to->clear();
(* to) = copy;
copy.clear();
}
bool terrainProject(uts::vector<vpPoint> * from, uts::vector<vpPoint> * to, View * view, Terrain * ter)
{
bool onterrain = false;
uts::vector<vpPoint> copy; // <from> and <to> may be the same so this requires some care
Vector dirn;
vpPoint p, cop;
// project stroke onto plane
cop = view->getCOP();
// cerr << "cop = " << cop.x << ", " << cop.y << ", " << cop.z << endl;
for(int i = 0; i < (int) from->size(); i++)
{
dirn.diff(cop, (* from)[i]);
if(ter->rayIntersect(cop, dirn, p))
{
// cerr << "from " << (* from)[i].x << ", " << (* from)[i].y << ", " << (* from)[i].z;
// cerr << " to " << p.x << ", " << p.y << ", " << p.z << endl;
copy.push_back(p);
onterrain = true;
}
}
to->clear();
(* to) = copy;
copy.clear();
return onterrain;
}
bool terrainProject(vpPoint &fromPnt, vpPoint &toPnt, View * view, Terrain * ter)
{
Vector dirn;
vpPoint p, cop;
// project stroke onto plane
cop = view->getCOP();
dirn.diff(cop, fromPnt);
if(ter->rayIntersect(cop, dirn, p))
{
toPnt = p;
return true;
}
else
{
return false;
}
}
bool testFragmentAttach(uts::vector<vpPoint> * from, uts::vector<vpPoint> * into, float diftol, bool bothends, int &inds, int &inde, float &closeness)
{
Vector sep;
vpPoint s, e;
float currmin, vals, vale, mins = 1000000.0f, mine = 1000000.0f;
bool isattached, ats, ate;
int i, rangetol;
// find closest point on <to> stroke to start and end of <from> stroke
s = from->front(); e = from->back();
for(i = 0; i < (int) into->size(); i++)
{
sep.diff((* into)[i], s);
currmin = sep.sqrdlength();
if(currmin < mins)
{
mins = currmin;
inds = i;
}
sep.diff((* into)[i], e);
currmin = sep.sqrdlength();
if(currmin < mine)
{
mine = currmin;
inde = i;
}
}
// check if these closest points are within tolerance
vals = sqrt(mins); vale = sqrt(mine);
ats = (vals < diftol);
ate = (vale < diftol);
if(!ats)
inds = -1;
if(!ate)
inde = -1;
rangetol = (int) (0.01f * (float) into->size()) + 10;
/*
cerr << "into size = " << into->size()-1 << endl;
cerr << "range tol = " << rangetol << endl;
cerr << "ats = " << ats << ", vals = " << vals << ", inds = " << inds << endl;
cerr << "ate = " << ate << ", vale = " << vale << ", inde = " << inde << endl;
*/
if(bothends)
{
isattached = ats && ate;
}
else
{
isattached = ats && ate;
if(!isattached) // also allow endpoint to endpoint
{
if(ats)
{
isattached = (inds < rangetol) || (inds > (int) into->size()-rangetol);
if(inds < rangetol)
inds = 0;
if(inds > (int) into->size()-rangetol)
inds = (int) into->size()-1;
}
if(ate)
{
isattached = (inde < rangetol) || (inde > (int) into->size()-rangetol);
if(inde < rangetol)
inde = 0;
if(inde > (int) into->size()-rangetol)
inde = (int) into->size()-1;
}
}
}
closeness = vals + vale;
return isattached;
}
bool inFill(uts::vector<vpPoint> * from, uts::vector<vpPoint> * into, float diftol, bool bothends, bool closed)
{
uts::vector<vpPoint> copy;
Vector vfrom, vinto;
vpPoint s, e;
float close;
bool ats, ate, isforward, overseam = false;
int i, inds, inde, rubstart, rubend;
if(testFragmentAttach(from, into, diftol, bothends, inds, inde, close))
{
ats = inds != -1; ate = inde != -1;
vinto.diff(into->front(), into->back());
vinto.normalize();
if(ats && ate) // replace section of curve
{
isforward = (inds < inde); // determine relative direction of <from> and <into> strokes
if(isforward)
{
rubstart = inds;
rubend = inde;
}
else
{
rubstart = inde;
rubend = inds;
}
if(closed) // specific to closed curves
overseam = ((float) (rubend - rubstart) / (float) into->size() > 0.5f); // always overwrite the smallest section of curve if it is a loop
}
else // join end to end
{
/*
// not at all robust
// determine relative direction of <from> and <into> using vectors from their start to end
vfrom.diff(from->front(), from->back());
vfrom.normalize();
isforward = (vinto.dot(vfrom) >= 0.0f);
*/
if(ats)
{
isforward = (inds != 0);
if(isforward) // two strokes are aligned so discard from inds on
{
rubstart = inds;
rubend = (int) into->size();
}
else // two strokes are misaligned so discard upto inds
{
rubstart = -1;
rubend = inds;
}
}
else
{
isforward = (inde == 0);
if(isforward) // two strokes are aligned so discard upto inde
{
rubstart = -1;
rubend = inde;
}
else // two strokes are misaligned so discard from inde on
{
rubstart = inde;
rubend = (int) into->size();
}
}
}
// interleave old curve and new curve sections into copy vector
if(overseam) // shift the seam and chop off the start and end. Can only be <true> if curve is closed.
{
for(i = rubstart; i <= rubend; i++)
copy.push_back((* into)[i]);
if(!isforward)
{
for(i = 0; i < (int) from->size(); i++)
copy.push_back((* from)[i]);
}
else
{
for(i = (int) from->size() - 1; i >= 0; i--)
copy.push_back((* from)[i]);
}
}
else // insert into an existing section of the curve
{
for(i = 0; i <= rubstart; i++)
copy.push_back((* into)[i]);
if(isforward)
{
for(i = 0; i < (int) from->size(); i++)
copy.push_back((* from)[i]);
}
else
{
for(i = (int) from->size() - 1; i >= 0; i--)
copy.push_back((* from)[i]);
}
for(i = rubend; i < (int) into->size(); i++)
copy.push_back((* into)[i]);
}
into->clear();
(* into) = copy;
return true;
}
else
return false;
}
bool locateIntersect(uts::vector<vpPoint> * strk, int &begin, int &end)
{
int i, j;
vpPoint e1[2], e2[2];
for(i = 0; i < (int) strk->size() - 2; i++)
{
e1[0] = (* strk)[i]; e1[1] = (* strk)[i+1];
for(j = i+2; j < (int) strk->size(); j++)
{
e2[0] = (* strk)[j];
if(j == (int) strk->size()-1) // wrap around
e2[1] = (* strk)[0];
else
e2[1] = (* strk)[j+1];
if(lineCrossing(e1, e2))
{
begin = i; end = j;
return true;
}
}
}
return false;
}
void excise(uts::vector<vpPoint> * strk, int begin, int end)
{
uts::vector<vpPoint>::iterator siter, eiter;
siter = strk->begin(); eiter = strk->begin();
siter += begin; eiter += (end+1);
strk->erase(siter, eiter);
// printf("excised from %d to %d, size before = %d, size after = %d", begin, end, bsize, esize);
}
///
/// ValueCurve
///
float ValueCurve::posOnSegment(int seg, float t) const
{
float sqt, h0, h1, h2, h3, v;
float p0, p1, m0, m1;
if(t < 0.0f-pluszero || t > 1.0f+pluszero || seg < 0 || seg > (int) splinerep.size() - 2)
{
// cerr << "Error ValueCurve::posOnSegment: out of bounds. t = " << t << " seg = " << seg << " out of " << (int) splinerep.size()-2 << endl;
return 0.0f;
}
else
{
sqt = (1.0f - t) * (1.0f - t);
// basis functions
h0 = (1.0f + 2.0f * t) * sqt; // (1+2t)(1-t)^2
h1 = t * sqt; // t (1-t)^2
h2 = t * t * (3.0f - 2.0f * t); // t^2 (3-2t)
h3 = t * t * (t - 1.0f); // t^2 (t-1)
// control points and tangents
p0 = splinerep[seg];
m0 = splinetan[seg];
p1 = splinerep[seg+1];
m1 = splinetan[seg+1];
// calculate point on curve
v = h0 * p0 + h1 * m0 + h2 * p1 + h3 * m1;
return v;
}
}
void ValueCurve::create(uts::vector<float> * tvals, uts::vector<float> * vvals)
{
sampling = 30; // number of samples between locators
vals = (* vvals);
params = (* tvals);
deriveCurve();
}
void ValueCurve::flatCaps()
{
if((int) splinetan.size() >= 2)
{
splinetan[0] = 0.0f;
splinetan[(int) splinetan.size() - 1] = 0.0f;
}
}
float ValueCurve::getPoint(float t) const
{
int seg;
float loct;
bool found = false;
// determine segment, using a search initially
seg = 0;
while(!found && seg < (int) params.size()-1)
{
seg++;
if(params[seg]+pluszero >= t)
{
found = true; seg--;
}
}
if(!found) // end of curve
{
loct = 1.0f;
seg = (int) params.size()-2;
}
else
{
loct = (t - params[seg]) / (params[seg+1] - params[seg]);
clamp(loct);
}
return posOnSegment(seg, loct);
}
void ValueCurve::deriveTangents()
{
float tan;
splinetan.clear();
for(int i = 0; i < (int) splinerep.size(); i++)
{
// tan = (cp[i+1] - cp[i]) / 2 + (cp[i] - cp[i-1]) / 2
// The curve is extended as piecewise constant past the ends
int a = std::max(i-1, 0);
int b = std::min(i+1, (int) splinerep.size()-1);
tan = 0.5f * (splinerep[b] - splinerep[a]);
splinetan.push_back(tan);
}
}
void ValueCurve::deriveVerts(int tnum)
{
float tsep = 1.0f / (float) tnum;
float t, v;
BoundRect lbr, hbr;
vals.clear();
deriveTangents();
for(int i = 0; i < (int) splinerep.size()-1; i++)
{
// baset = params[i]; delt = params[i+1] - params[i];
// create points within the current segment
for(t = 0.0f; t < 1.0f-pluszero; t+= tsep)
{
v = posOnSegment(i, t);
vals.push_back(v);
}
}
// add last point
v = posOnSegment((int) splinerep.size()-2, 1.0f);
vals.push_back(v);
}
void ValueCurve::deriveCurve()
{
Vector sepvec;
vpPoint p;
if((int) vals.size() > 0)
splinerep = vals;
// now recreate the vertices according to the new control points
deriveTangents();
deriveVerts(sampling);
}
///
/// BrushCurve
///
void BrushCurve::create(vpPoint start, View * view, Terrain * ter)
{
vpPoint pnt;
sampling = ter->samplingDist();
if(terrainProject(start, pnt, view, ter))
{
pnt.y = 0.0f;
vertsrep.push_back(pnt);
updateIndex = 0;
update.includePnt(pnt);
enclose.includePnt(pnt);
created = true;
}
}
bool BrushCurve::isCreated() const
{
return created;
}
void BrushCurve::addPoint(View * view, Terrain * ter, vpPoint pnt)
{
int j, nums;
vpPoint start, end, pos;
float t, len, delt;
Vector del;
uts::vector<vpPoint> newverts;
if(terrainProject(pnt, end, view, ter))
{
if(!created)
{
create(pnt, view, ter);
}
else
{
end.y = 0.0f;
start = vertsrep[(int) vertsrep.size()-1];
// update bounding boxes
update.reset();
enclose.includePnt(end);
update.includePnt(start);
update.includePnt(end);
// linearly subsample each segment
del.diff(start, end);
len = del.length();
updateIndex = (int) vertsrep.size();
if(len > sampling) // longer than expected interval between points
{
// number of subsamples
nums = (int) ceil(len / sampling);
delt = 1.0f / (float) nums;
for(j = 1; j < nums; j++) // start point already part of curve
{
t = j * delt;
pos.affinecombine(1.0f-t, start, t, end);
vertsrep.push_back(pos);
}
}
else
{
vertsrep.push_back(end);
}
}
}
}
Region BrushCurve::getBound(BoundRect &bnd, Terrain * ter, float radius)
{
int dx, dy;
Region reg;
bnd.expand(radius);
ter->getGridDim(dx, dy);
// convert to terrain coordinates
reg.x0 = (int) ter->toGrid(bnd.min.x);
if(reg.x0 < 0) reg.x0 = 0;
reg.y0 = (int) ter->toGrid(bnd.min.z);
if(reg.y0 < 0) reg.y0 = 0;
reg.x1 = (int) ter->toGrid(bnd.max.x);
if(reg.x1 > dx) reg.x1 = dx;
reg.y1 = (int) ter->toGrid(bnd.max.z);
if(reg.y1 > dy) reg.y1 = dy;
return reg;
}
Region BrushCurve::encloseBound(Terrain * ter, float radius)
{
BoundRect bnd;
bnd = enclose;
return getBound(bnd, ter, radius);
}
Region BrushCurve::updateBound(Terrain * ter, float radius)
{
BoundRect bnd;
bnd = update;
return getBound(bnd, ter, radius);
}
///
/// Curve3D
///
bool Curve3D::posOnSegment(int seg, float t, vpPoint & p) const
{
float sqt, h0, h1, h2, h3;
vpPoint p0, p1;
Vector m0, m1;
if(t < 0.0f-pluszero || t > 1.0f+pluszero || seg < 0 || seg > (int) splinerep.size() - 2)
{
cerr << "posOnSegment error: out of bounds. t = " << t << " seg = " << seg << endl;
return false;
}
else
{
sqt = (1.0f - t) * (1.0f - t);
// basis functions
h0 = (1.0f + 2.0f * t) * sqt; // (1+2t)(1-t)^2
h1 = t * sqt; // t (1-t)^2
h2 = t * t * (3.0f - 2.0f * t); // t^2 (3-2t)
h3 = t * t * (t - 1.0f); // t^2 (t-1)
// control points and tangents
p0 = splinerep[seg];
m0 = splinetan[seg];
p1 = splinerep[seg+1];
m1 = splinetan[seg+1];
// calculate point on curve
p.x = h0 * p0.x + h1 * m0.i + h2 * p1.x + h3 * m1.i;
p.y = h0 * p0.y + h1 * m0.j + h2 * p1.y + h3 * m1.j;
p.z = h0 * p0.z + h1 * m0.k + h2 * p1.z + h3 * m1.k;
return true;
}
}
void Curve3D::subsample(uts::vector<vpPoint> * strk)
{
uts::vector<vpPoint> tmp;
Vector del;
vpPoint prev, curr, pos;
float len, t, delt;
int i, j, nums;
for(i = 0; i < (int) strk->size()-1; i++)
{
prev = (* strk)[i]; curr = (* strk)[i+1]; prev.y = 0.0f; curr.y = 0.0f;
del.diff(prev, curr);
len = del.length();
if(len > 0.1f * sep) // longer than expected interval between points
{
// number of subsamples
nums = (int) ceil(len / (0.2f * sep));
delt = 1.0f / nums;
for(j = 0; j < nums; j++)
{
t = j * delt;
pos.affinecombine(1.0f-t, (* strk)[i], t, (* strk)[i+1]);
tmp.push_back(pos);
}
}
else
{
tmp.push_back((* strk)[i]);
}
}
tmp.push_back((* strk)[(int) strk->size()-1]);
strk->clear();
(* strk) = tmp;
}
bool Curve3D::create(uts::vector<vpPoint> * strk, View * view, Terrain * ter)
{
float tx, ty;
sep = ter->smoothingDist(); // separation between control point
ter->getTerrainDim(tx, ty);
farbound = (tx*tx+ty*ty)+100.0f;
sampling = ter->samplingDist();
highstep = 6;
leafstep = 25;
created = terrainProject(strk, &vertsrep, view, ter);
// for testing
/*
vertsrep.clear();
vertsrep.push_back(vpPoint(-0.3, 0.0, -0.3));
vertsrep.push_back(vpPoint(0.0, 0.0, 0.0));
vertsrep.push_back(vpPoint(0.3, 0.0, 0.3));
drapeProject(&vertsrep, &vertsrep, ter); */
if((int) vertsrep.size() > 1)
{
deriveCurve(ter, true);
// cerr << "number curve samples = " << (int) vertsrep.size() << endl;
// cerr << "sep = " << sep << ", sampling = " << sampling << endl;
drapeProject(&vertsrep, &vertsrep, ter); // project back onto landscape
}
return created;
}
bool Curve3D::nonProjCreate(uts::vector<vpPoint> * strk, Terrain * ter)
{
float tx, ty, errbnd;
int i;
sep = 5.0f * ter->smoothingDist(); // separation between control point
ter->getTerrainDim(tx, ty);
farbound = (tx*tx+ty*ty)+100.0f;
sampling = 10.0f * ter->samplingDist();
errbnd = ter->samplingDist();
highstep = 6;
leafstep = 25;
//cerr << "stroke size = " << (int) strk->size() << endl;
vertsrep = (* strk); // copy stroke directly to vertices without requiring projection
//cerr << "vertsrep size = " << (int) vertsrep.size() << endl;
if((int) vertsrep.size() > 1)
{
deriveCurve(ter, false);
//drapeProject(&vertsrep, &vertsrep, ter); // project back onto landscape
// for(int i = 0; i < (int) vertsrep.size(); i++)
// vertsrep[i].y = 0.0f;
// clamp to terrain bounds, which may be exceeded due to smoothing
for(i = 0; i < (int) vertsrep.size(); i++)
{
if(vertsrep[i].x < errbnd) vertsrep[i].x = errbnd;
if(vertsrep[i].z < errbnd) vertsrep[i].z = errbnd;
if(vertsrep[i].x > tx - errbnd) vertsrep[i].x = tx - errbnd;
if(vertsrep[i].z > ty - errbnd) vertsrep[i].z = ty - errbnd;
}
created = true;
}
else
{
created = false;
}
return created;
}
void Curve3D::recreate(Terrain * ter)
{
if((int) vertsrep.size() > 1)
{
deriveCurve(ter, true);
// cerr << "number curve samples = " << (int) vertsrep.size() << endl;
// cerr << "sep = " << sep << ", sampling = " << sampling << endl;
drapeProject(&vertsrep, &vertsrep, ter); // project back onto landscape
}
}
bool Curve3D::isCreated() const
{
return created;
}
bool Curve3D::mergeStroke(uts::vector<vpPoint> * strk, uts::vector<vpPoint> * prj, View * view, Terrain * ter, bool &merge, float tol)
{
uts::vector<vpPoint> frag, tmp;
bool pass;
// project fragment onto landscape
merge = false;
pass = terrainProject(strk, &frag, view, ter);
if(pass)
{
subsample(&frag); // introduce more vertices as needed by linear interpolation
if(inFill(&frag, &vertsrep, tol, false, false)) // merge fragment with existing curve
{
// to do - test and fix foldover and out of bound errors
deriveCurve(ter, true);
drapeProject(&vertsrep, &vertsrep, ter); // project back onto landscape
(* prj) = vertsrep;
merge = true;
}
}
return pass;
}
void Curve3D::genGL(View * view, Shape * shape, float radius)
{
shape->genCylinderCurve(vertsrep, radius, 10.0f * sampling, 10);
}
void Curve3D::adjustHeights(Terrain * ter, ValueCurve hcurve)
{
drapeProject(&vertsrep, &vertsrep, ter);
}
vpPoint Curve3D::getPoint(float t) const
{
int seg;
float segt, loct;
vpPoint pnt;
if((int) vertsrep.size() > 1)
{
// determine segment, using even subdivision of t across all segments
segt = t; clamp(segt);
segt *= (float) ((int) (vertsrep.size()-1));
seg = (int) floor(segt);
loct = segt - (float) seg; // local param within segment
// linearly interpolate vertices
pnt.x = (1.0f - loct) * vertsrep[seg].x + loct * vertsrep[seg+1].x;
pnt.y = (1.0f - loct) * vertsrep[seg].y + loct * vertsrep[seg+1].y;
pnt.z = (1.0f - loct) * vertsrep[seg].z + loct * vertsrep[seg+1].z;
}
else
{
if((int) vertsrep.size() == 1)
pnt = vertsrep[0];
else
pnt = vpPoint(0.0f, 0.0f, 0.0f);
}
return pnt;
}
void Curve3D::getSeg(float t, vpPoint &s0, vpPoint &s1)
{
int seg;
if((int) vertsrep.size() > 1)
{
seg = getSegIdx(t);
if(seg < (int) vertsrep.size() - 1)
{
s0 = vertsrep[seg]; s1 = vertsrep[seg+1];
}
else
{
s0 = vertsrep[seg]; s1 = vertsrep[seg];
}
}
}
int Curve3D::getSegIdx(float t)
{
int seg = 0;
float segt;
if((int) vertsrep.size() > 1)
{
// determine segment, using even subdivision of t across all segments
segt = t; clamp(segt);
segt *= (float) (numPoints()-1);
seg = (int) floor(segt);
}
return seg;
}
Vector Curve3D::getDirn(float t) const
{
int seg, last;
float segt;
vpPoint p0, p1;
Vector delv;
// determine segment, using even subdivision of t across all segments
if((int) vertsrep.size() > 1)
{
segt = t;
segt *= (float) ((int) (vertsrep.size()-1));
seg = (int) floor(segt);
if(seg < (int) vertsrep.size()-1)
{
p0 = vertsrep[seg];
p1 = vertsrep[seg+1];
}
else
{
last = (int) vertsrep.size()-1;
p0 = vertsrep[last-1];
p1 = vertsrep[last];
}
delv.diff(p0, p1);
delv.normalize();
}
else
{
delv = Vector(0.0f, 0.0f, 0.0f);
}
return delv;
}
void Curve3D::closest(vpPoint p, float & t, float & dist, vpPoint &cpnt, Vector &cdirn) const
{
float cdist, delt, nearfar, nfc;
vpPoint currpnt, npnt;
Vector del;
float dx, dz;
int i, j, k, vmin, vmax, lmax, bestk = 0;
dist = farbound; t = -1.0f;
if((int) vertsrep.size() > 0)
{
delt = 1.0f / (float) ((int) vertsrep.size()-1);
// find the box whose farthest point is closest
nearfar = farbound;
for(i = 0; i < (int) highsegboxes.size(); i++)
{
nfc = highsegboxes[i].farthest(p);
if(nfc < nearfar)
nearfar = nfc;
}
// only check boxes whose nearest point is closer than nearfar
for(i = 0; i < (int) highsegboxes.size(); i++)
{
if(highsegboxes[i].nearest(p) <= nearfar)
{
// update nearfar against leaf boxes
lmax = std::min(highstep*(i+1), (int) leafsegboxes.size());
// lmax = highstep*(i+1);
for(j = highstep * i; j < lmax; j++)
{
nfc = leafsegboxes[j].farthest(p);
if(nfc < nearfar)
nearfar = nfc;
}
// now check contents of leaf boxes if within nearfar
for(j = highstep * i; j < lmax; j++)
{
if(leafsegboxes[j].nearest(p) <= nearfar)
{
// find range of vertices corresponding to this segment
vmin = j * leafstep;
vmax = std::min(vmin + leafstep, (int) vertsrep.size());
// find closest point on shadow in x-z plane
for(k = vmin; k < vmax; k++)
{
currpnt = vertsrep[k];
dx = p.x - currpnt.x;
dz = p.z - currpnt.z;
cdist = dx * dx + dz * dz;
if(cdist < dist)
{
dist = cdist;
bestk = k;
}
}
}
}
}
}
/*
// slow alternative - useful for testing
// find closest point on shadow in x-z plane
for(j = 0; j < (int) vertsrep.size(); j++)
{
currpnt = vertsrep[j];
dx = p.x - currpnt.x;
dz = p.z - currpnt.z;
cdist = dx * dx + dz * dz;
if(cdist < dist)
{
dist = cdist;
bestk = j;
}
}
*/
t = delt * (float) bestk;
cpnt = vertsrep[bestk];
if(bestk < (int) vertsrep.size()-1)
{
npnt = vertsrep[bestk+1];
cdirn.diff(cpnt, npnt);
}
else
{
npnt = vertsrep[bestk-2];
cdirn.diff(npnt, cpnt);
}
cdirn.normalize();
dist = sqrt(dist);
}
}
void Curve3D::closestToRay(vpPoint cop, Vector dirn, float & t, float & dist) const
{
float cdist, delt, tval;
vpPoint currpnt;
int j, bestj = 0;
dist = farbound; t = -1.0f;
if((int) vertsrep.size() > 0)
{
delt = 1.0f / (float) ((int) vertsrep.size()-1);
// slow approach - exhaustive testing
for(j = 0; j < (int) vertsrep.size(); j++)
{
currpnt = vertsrep[j];
rayPointDist(cop, dirn, currpnt, tval, cdist);
if(cdist < dist)
{
dist = cdist;
bestj = j;
}
}
t = delt * (float) bestj;
}
}
bool Curve3D::testIntersect(Curve3D * dstcurve, uts::vector<float> &srct, uts::vector<float> &dstt)
{
int i, j, dis, die;
vpPoint pnt, c[2], x[2];
Vector dirn;
float dist, st, dt, tol, delt;
bool cross = false;
tol = 2.0f * sampling;
st = 0.0f; delt = 1.0f / (float) (numPoints()-1);
for(i = 0; i < numPoints()-1; i++)
{
// test closeness of approach
dstcurve->closest(vertsrep[i], dt, dist, pnt, dirn);
if(dist < tol) // test segment crossing
{
// test in surrounding area
getSeg(st, c[0], c[1]);
c[0].y = c[0].z; c[1].y = c[1].z;
dis = dstcurve->getSegIdx(dt-0.05f);
die = dstcurve->getSegIdx(dt+0.05f);
for(j = dis; j < die; j++)
{
x[0] = (* dstcurve->getVerts())[j];
x[1] = (* dstcurve->getVerts())[j+1];
x[0].y = x[0].z; x[1].y = x[1].z;
if(lineCrossing(c,x)) // intersection detected
{
srct.push_back(st);
dstt.push_back(dt);
cross = true;
}
}
}
st += delt;
}
return cross;
}
bool Curve3D::testSelfIntersect(uts::vector<float> &srct, uts::vector<float> &dstt)
{
int i, j, dis, die;
vpPoint c[2], x[2];
Vector dirn;
float sqdist, st, dt, tol, sqtol, delt;
bool cross = false;
tol = 2.0f * sampling; sqtol = tol*tol;
st = 0.0f; delt = 1.0f / (float) (numPoints()-1);
for(i = 0; i < numPoints()-1; i++)
{
for(j = i+10; j < numPoints()-1; j++)
{
dt = j*delt;
dirn.diff(vertsrep[i], vertsrep[j]);
sqdist = dirn.sqrdlength();
if(sqdist < sqtol) // test segment crossing
{
// test in surrounding area
getSeg(st, c[0], c[1]);
c[0].y = c[0].z; c[1].y = c[1].z;
dis = getSegIdx(dt-0.05f);
die = getSegIdx(dt+0.05f);
for(j = dis; j < die; j++)
{
x[0] = vertsrep[j];
x[1] = vertsrep[j+1];
x[0].y = x[0].z; x[1].y = x[1].z;
if(lineCrossing(c,x)) // intersection detected
{
srct.push_back(st);
dstt.push_back(dt);
cross = true;
}
}
}
}
st += delt;
}
return cross;
}
bool Curve3D::closeApproach(Curve3D * dstcurve, uts::vector<float> &srct, uts::vector<float> &dstt, float tol)
{
int i;
vpPoint spnt, dpnt;
Vector dirn;
float et[2], st, dt, dist;
bool close = false;
et[0] = 0.0f; et[1] = 1.0f;
// src endpoints
for(i = 0; i < 2; i++)
{
spnt = getPoint(et[i]);
dstcurve->closest(spnt, dt, dist, dpnt, dirn);
if(dist < tol)
{
srct.push_back(et[i]); dstt.push_back(dt); close = true;
}
}
// dst endpoints
for(i = 0; i < 2; i++)
{
dpnt = dstcurve->getPoint(et[i]);
closest(dpnt, st, dist, spnt, dirn);
if(dist < tol)
{
srct.push_back(st); dstt.push_back(et[i]); close = true;
}
}
return close;
}
void Curve3D::dragPin(float t, vpPoint tpnt, float trange)
{
Vector del, trx;
int i, vstart, vend, off;
float s;
//ValueCurve interpcurve;
off = (int) (trange * (float) numPoints());
del.diff(getPoint(t), tpnt); del.j = 0.0f; trx = del;
// ramp up to full translate
vend = getSegIdx(t); vend = std::min(numPoints()-1, vend); vstart = std::max(0, vend - off);
if(vstart == vend) // special case for first point in curve
{
trx = del;
trx.pntplusvec(vertsrep[vstart], &vertsrep[vstart]);
}
else
{
for(i = vstart; i <= vend; i++)
{
s = (float) (i - vstart) / (float) (vend - vstart);
trx = del; trx.mult(s);
trx.pntplusvec(vertsrep[i], &vertsrep[i]);
}
}
// ramp down from full translate
vstart = std::min(numPoints()-1, vend+1); vend = std::min(numPoints()-1, vstart + off);
for(i = vstart; i <= vend; i++)
{
s = 1.0f - (float) (i - vstart) / (float) (vend - vstart + 1);
trx = del; trx.mult(s);
trx.pntplusvec(vertsrep[i], &vertsrep[i]);
}
}
float Curve3D::remap(float t, bool left) const
{
int seg;
float segt, loct, val;
if((int) remapleft.size() > 0 && (int) remapright.size() > 0)
{
// determine segment, using even subdivision of t across all segments
segt = t; clamp(segt);
segt *= (float) ((int) (vertsrep.size()-1));
seg = (int) floor(segt);
loct = segt - (float) seg; // local param within segment
// linearly interpolate remap elements
if(left)
val = (1.0f - loct) * remapleft[seg] + loct * remapleft[seg+1];
else
val = (1.0f - loct) * remapright[seg] + loct * remapright[seg+1];
}
else
{
cerr << "Error Curve3D::ramp: param remap not yet created" << endl;
val = 0.0f;
}
return val;
}
void Curve3D::genParamRemap(ValueCurve * distleft, ValueCurve * distright)
{
int i, k;
float theta, kap, slen, slensq, nval, lerp, t, dleft, dright, delt, errt = 1.0f, etol = 0.01f;
uts::vector<float> newmapleft, newmapright;
Vector prevseg, nextseg, norm, orthog;
remapleft.clear(); remapright.clear();
// remap has initial arclength parametrization
delt = 1.0f / (float) ((int) vertsrep.size()-1);
for(i = 0; i < (int) vertsrep.size(); i++)
{
t = delt * (float) i;
remapleft.push_back(t); remapright.push_back(t);
}
// iteratively refine remap, until it stops changing or number of allowed iterations is exceeded
// refine left and right remappings simultaneously, to save curvature computations
k = 0;
while(errt > etol && k < 5)
{
newmapleft.clear(); newmapright.clear();
// use curvature to revise param map
newmapleft.push_back(0.0f); newmapright.push_back(0.0f);
for(i = 1; i < (int) remapleft.size()-1; i++)
{
dleft = distleft->getPoint(remapleft[i]);
dright = distright->getPoint(remapright[i]);
// calculate curvature
prevseg.diff(vertsrep[i-1], vertsrep[i]); prevseg.j = 0.0f;
nextseg.diff(vertsrep[i], vertsrep[i+1]); nextseg.j = 0.0f;
// cerr << "seg-1 = " << prevseg.i << ", " << prevseg.j << ", " << prevseg.k;
// cerr << " seg+1 = " << nextseg.i << ", " << nextseg.j << ", " << nextseg.k;
slen = nextseg.length();
// cerr << " len seg-1 = " << slen;
// slen = prevseg.length();
// cerr << " len seg+1 = " << slen;
slensq = slen * slen;
prevseg.normalize(); nextseg.normalize();
theta = acosf(prevseg.dot(nextseg));
// cerr << " theta = " << theta;
// precision issues
kap = sqrtf(2.0f * slensq * (1.0f - cosf(theta))) / slen;
/*
orthog = Vector(nextseg.i - prevseg.i, 0.0f, nextseg.k - prevseg.k);
kap = orthog.length() / nextseg.length();*/
/*
prevseg.normalize(); nextseg.normalize();
theta = acosf(prevseg.dot(nextseg));
if(theta > PI / 4.0f)
cerr << "Error large direction change" << endl;
*/
// calculate sidedness
norm.i = -1.0f * prevseg.k; norm.k = prevseg.i; // rotate by 90 degrees
if(norm.dot(nextseg) < 0.0f)
kap *= -1.0f;
// cerr << dleft << " ";
// left side of curve
// cerr << " " << kap;
if(kap <= 0.0f) // expansion or identity
{
newmapleft.push_back(newmapleft[i-1]+delt);
// cerr << " x ";
}
else if(kap < 1.0f / dleft) // contraction
{
lerp = 1.0f - kap * dleft;
newmapleft.push_back(newmapleft[i-1]+lerp*delt);
// cerr << " rc [" << kap << "]";
}
else // vanishing point
{
newmapleft.push_back(newmapleft[i-1]);
// cerr << " rv [" << kap << "]";
}
// right side of curve
kap *= -1.0f;
if(kap <= 0.0f) // expansion or identity
{
newmapright.push_back(newmapright[i-1]+delt);
}
else if(kap < 1.0f / dright) // contraction
{
lerp = 1.0f - kap * dright;
newmapright.push_back(newmapright[i-1]+lerp*delt);
// cerr << " lc [" << kap << "]";
}
else // vanishing point
{
newmapright.push_back(newmapright[i-1]);
// cerr << " lv [" << kap << "]";
}
// cerr << endl;
}
newmapleft.push_back(newmapleft[(int) newmapleft.size()-1]+delt);
newmapright.push_back(newmapright[(int) newmapright.size()-1]+delt);
cerr << endl;
// cerr << "newmapleft end = " << newmapleft[(int) newmapleft.size()-1] << endl;
// cerr << "newmapright end = " << newmapleft[(int) newmapleft.size()-1] << endl;
// normalize parameters back to [0,1]
nval = newmapleft[(int) newmapleft.size()-1];
for(i = 0; i < (int) newmapleft.size(); i++)
newmapleft[i] /= nval;
nval = newmapright[(int) newmapright.size()-1];
for(i = 0; i < (int) newmapright.size(); i++)
newmapright[i] /= nval;
// calculate param differences
errt = 0.0f;
for(i = 0; i < (int) remapleft.size(); i++)
errt += fabs(remapleft[i] - newmapleft[i]);
for(i = 0; i < (int) remapright.size(); i++)
errt += fabs(remapright[i] - newmapright[i]);
cerr << "iteration #" << k << " errt = " << errt << endl;
// newmaps become remaps
remapleft = newmapleft;
remapright = newmapright;
k++;
}
cerr << "iterations = " << k << " errt = " << errt << endl;
}
void Curve3D::redrape(Terrain * ter)
{
drapeProject(&vertsrep, &vertsrep, ter);
}
BoundRect Curve3D::boundingBox(float t0, float t1) const
{
BoundRect nbox;
vpPoint p;
int i, t0ind, t1ind;
float tincr;
if(t0 < pluszero && t1 > 1.0f-pluszero) // use cached bounding box
{
return bbox;
}
else // derive new bounding box
{
// use t values to index correct start and end of vertsrep
tincr = 1.0f / (float) vertsrep.size();
t0ind = (int) (t0 * tincr);
t1ind = (int) (t1 * tincr) + 1;
for(i = t0ind; i <= t1ind; i++)
{
p = vertsrep[i];
nbox.includePnt(p);
}
return nbox;
}
}
void Curve3D::deriveTangents()
{
Vector tan1, tan2;
splinetan.clear();
for(int i = 0; i < (int) splinerep.size(); i++)
{
// first and last cp are special cases
if(i == 0)
{
tan1.diff(splinerep[i], splinerep[i+1]);
tan1.mult(0.5f);
splinetan.push_back(tan1);
}
else if(i == (int) splinerep.size()-1)
{
tan2.diff(splinerep[i-1], splinerep[i]);
tan2.mult(0.5f);
splinetan.push_back(tan2);
}
else
{
// tan = (cp[i+1] - cp[i]) / 2 + (cp[i] - cp[i-1]) / 2
tan1.diff(splinerep[i], splinerep[i+1]);
tan1.mult(0.5f);
tan2.diff(splinerep[i-1], splinerep[i]);
tan2.mult(0.5f);
tan1.add(tan2);
splinetan.push_back(tan1);
}
}
}
void Curve3D::deriveVerts(bool extend)
{
int i;
float dsep = 0.025f;
float t;
vpPoint p;
BoundRect lbr, hbr;
uts::vector<vpPoint> denserep;
// create a densely sampled representation of the curve
for(int i = 0; i < (int) splinerep.size()-1; i++)
{
// create points within the current segment
for(t = 0.0f; t < 1.0f-pluszero; t+= dsep)
{
posOnSegment(i, t, p);
denserep.push_back(p);
}
}
// add last point
posOnSegment((int) splinerep.size()-2, 1.0f, p);
denserep.push_back(p);
// reparametrize according to a set distance between points, to provide an arc length parametrization
reparametrize(&denserep, &vertsrep, sampling, extend);
// build bounding box and hierarchical bounding volume
leafsegboxes.clear(); highsegboxes.clear();
bbox.reset();
for(i = 0; i < (int) vertsrep.size(); i++)
{
p = vertsrep[i];
bbox.includePnt(p); hbr.includePnt(p); lbr.includePnt(p);
if(i != 0 && i % leafstep == 0)
{
if((i / leafstep) % highstep == 0)
{
highsegboxes.push_back(hbr);
hbr.reset();
hbr.includePnt(p); // new box start where the previous ended
}
leafsegboxes.push_back(lbr);
lbr.reset();
lbr.includePnt(p); // new box start where the previous ended
}
}
// push final hbv boxes if they have not already been pushed
if(!hbr.empty())
highsegboxes.push_back(hbr);
if(!lbr.empty())
leafsegboxes.push_back(lbr);
/*
cerr << "num segments = " << (int) splinerep.size()-1 << endl;
cerr << "num verts = " << (int) vertsrep.size() << endl;
cerr << "num high segment boxes = " << (int) highsegboxes.size() << endl;
cerr << "num leaf segment boxes = " << (int) leafsegboxes.size() << endl;
for(i = 0; i < (int) highsegboxes.size(); i++)
{
cerr << "HIGH SEG BOX " << i << endl;
cerr << "min = (" << highsegboxes[i].min.x << ", " << highsegboxes[i].min.z << ")" << endl;
cerr << "max = (" << highsegboxes[i].max.x << ", " << highsegboxes[i].max.z << ")" << endl;
}
for(i = 0; i < (int) leafsegboxes.size(); i++)
{
cerr << "LEAF SEG BOX " << i << endl;
cerr << "min = (" << leafsegboxes[i].min.x << ", " << leafsegboxes[i].min.z << ")" << endl;
cerr << "max = (" << leafsegboxes[i].max.x << ", " << leafsegboxes[i].max.z << ")" << endl;
}
// cerr << "curve bbox derived" << endl;
// cerr << bbox.minx << ", " << bbox.minz << " -> " << bbox.maxx << ", " << bbox.maxz << endl;
*/
/*
cerr << "VERTS" << endl;
p = vertsrep[(int) vertsrep.size() -2];
cerr << "pen = " << p.x << ", " << p.y << ", " << p.z << endl;
p = vertsrep[(int) vertsrep.size() -1];
cerr << "end = " << p.x << ", " << p.y << ", " << p.z << endl;*/
}
vpPoint Curve3D::circSegIntersect(vpPoint c, float r, vpPoint f1, vpPoint f2)
{
vpPoint p, i1, i2, s1, s2;
float dx, dy, drsq, det, com, comsq, sgn;
Vector sepvec, segvec;
// intersection of segment with circle whose radius is seglen
// guaranteed to have one solution
s1 = vpPoint(f1.x - c.x, 0.0f, f1.z - c.z);
s2 = vpPoint(f2.x - c.x, 0.0f, f2.z - c.z);
dx = s2.x - s1.x;
dy = s2.z - s1.z;
drsq = dx*dx + dy*dy;
det = s1.x * s2.z - s2.x * s1.z;
comsq = (r*r*drsq-det*det);
if(comsq <= 0.0f)
{
cerr << "no intersection in Curve3D::reparametrize" << endl;
p = f2;
}
else
{
com = sqrt(comsq);
if(dy < 0.0f)
sgn = -1.0f;
else
sgn = 1.0f;
i1.x = (det * dy + sgn * dx * com) / drsq + c.x;
i1.y = 0.0f;
i1.z = (-1.0f * det * dx + fabs(dy) * com) / drsq + c.z;
i2.x = (det * dy - sgn * dx * com) / drsq + c.x;
i2.y = 0.0f;
i2.z = (-1.0f * det * dx - fabs(dy) * com) / drsq + c.z;
/*
cerr << "seglen = " << seglen << ", seplen = " << seplen << endl;
cerr << "i1 = " << i1.x << ", " << i1.z << endl;
cerr << "i2 = " << i2.x << ", " << i2.z << endl;
cerr << "f = " << f.x << ", " << f.z << endl;
cerr << "f1 = " << f1.x << ", " << f1.z << endl;
cerr << "f2 = " << f2.x << ", " << f2.z << endl;
*/
// choose correct intersection
sepvec.diff(c, i1); sepvec.normalize();
segvec.diff(f1, f2); segvec.normalize();
// cerr << "dotprod = " << sepvec.dot(segvec) << endl;
if(sepvec.dot(segvec) >= 0.0f)
p = i1;
else
p = i2;
}
return p;
}
void Curve3D::reparametrize(uts::vector<vpPoint> * in, uts::vector<vpPoint> * out, float vsep, bool extend)
{
Vector sepvec, segvec;
vpPoint p, p1, p2, f, f1, f2;
float arclen = 0.0f, seglen, seplen;
int i, numseg;
out->clear();
if((int) in->size() >= 2)
{
// determine current arc length of polyline
for(i = 1; i < (int) in->size(); i++)
{
p1 = (* in)[i-1]; p1.y = 0.0f; p2 = (* in)[i]; p2.y = 0.0f;
sepvec.diff(p1, p2);
arclen += sepvec.length();
}
// divide polyline into sections of vsep length or less
numseg = (int) ceil(arclen / vsep);
seglen = arclen / (float) numseg;
p = (* in)[0]; out->push_back(p); // cp at start of curve
for(i = 1; i < (int) in->size(); i++)
{
f = p; f.y = 0.0f;
p1 = (* in)[i-1]; f1 = p1; f1.y = 0.0f;
p2 = (* in)[i]; f2 = p2; f2.y = 0.0f;
sepvec.diff(f, f2); seplen = sepvec.length();
while(seplen >= seglen) // place point on this segment
{
p = circSegIntersect(f, seglen, f1, f2);
out->push_back(p);
// possibly further subdivision of this segment required
f = p; f.y = 0.0f; p1 = p; f1 = f;
sepvec.diff(f, f2); seplen = sepvec.length();
}
}
// extrapolate final cp to ensure segment is of correct length
if(extend)
p = circSegIntersect(f, seglen, f1, f2);
else
p = (* in)[(int) in->size()-1];
out->push_back(p); // cp at end of curve
// test segment lengths and report any that diverge from the ideal
for(i = 0; i < (int) out->size()-1; i++)
{
f1 = (* out)[i]; f1.y = 0.0f; f2 = (* out)[i+1]; f2.y = 0.0f;
sepvec.diff(f1, f2);
seplen = sepvec.length();
if(extend)
if(fabs(seplen - seglen) > 0.001f)
{
cerr << "seg " << i+1 << " of " << (int) out->size()-1 << " has len = " << seplen << " instead of " << seglen << endl;
}
}
}
}
void Curve3D::deriveCurve(Terrain * ter, bool extend)
{
if((int) vertsrep.size() > 1)
{
reparametrize(&vertsrep, &splinerep, sep, extend);
drapeProject(&splinerep, &splinerep, ter); // project cp back onto landscape
deriveTangents();
deriveVerts(extend);
}
}
///
/// BrushStroke
///
vpPoint BrushStroke::addMousePnt(View * view, Terrain * ter, int x, int y)
{
vpPoint pnt;
view->projectingPoint(x, y, pnt);
fragment.push_back(pnt);
shadow.addPoint(view, ter, pnt);
return pnt;
}
void BrushStroke::clearFragment()
{
fragment.clear();
shadow.clear();
}
///
/// Fragment
///
vpPoint Fragment::addMousePnt(View * view, int x, int y)
{
vpPoint pnt, ppnt, mpnt;
Vector dirn;
view->projectingRay(x, y, pnt, dirn);
dirn.mult(200.0f);
dirn.pntplusvec(pnt, &ppnt);
// push along projecting ray into scene
frag.push_back(ppnt);
view->inscreenPoint(x, y, mpnt);
mouse.push_back(mpnt);
return pnt;
}
void Fragment::genGL(View * view, Shape * s)
{
float w = 0.2f;
float col[4] = {0.325f, 0.235f, 1.0f, 1.0f};
s->setColour(col);
s->genCurve(frag, view, w, 0.5f, false, false, false);
}
bool Fragment::degenerate()
{
return ((int) frag.size() <= 2);
}
bool Fragment::testLoop(float tol)
{
Vector sep;
bool isclosed;
sep.diff(frag.front(), frag.back());
isclosed = (sep.length() < tol);
return isclosed;
}
void Fragment::screenBounds(uts::vector<vpPoint> * strk)
{
screenMin = vpPoint(10000000.0f, 10000000.0f, 0.0f);
screenMax = vpPoint(-10000000.0f, -10000000.0f, 0.0f);
for(int i = 0; i < (int) strk->size(); i++)
{
if((* strk)[i].x < screenMin.x)
screenMin.x = (* strk)[i].x;
if((* strk)[i].x > screenMax.x)
screenMax.x = (* strk)[i].x;
if((* strk)[i].y < screenMin.y)
screenMin.y = (* strk)[i].y;
if((* strk)[i].y > screenMax.y)
screenMax.y = (* strk)[i].y;
}
}
float Fragment::screenDiag()
{
Vector diag;
screenBounds(&frag);
diag.diff(screenMin, screenMax);
return diag.length();
}
///
/// Stroke
///
/*
bool Stroke::crossing(Stroke *cross, int thresh)
{
bool xoverlap, yoverlap;
int i, j, numcrossings = 0;
vpPoint c[2], x[2];
uts::vector<vpPoint> scratch;
// naive O(n^2) test of each segment against all segments in the crossing stroke
// but does use inscreen bounding boxes for acceleration
// project and bound strokes in the current screen as necessary
if(!isinscreen)
setProximity();
if(!cross->isinscreen)
{
// form bounding box in screen space
screenProject(&currview, &cross->fragment, &scratch);
cross->screenBounds(&scratch);
cross->isinscreen = false;
}
// check for overlap in x
xoverlap = true;
if(screenMin.x < cross->screenMin.x)
{
if(cross->screenMin.x > screenMax.x)
xoverlap = false;
}
else
{
if(screenMin.x > cross->screenMax.x)
xoverlap = false;
}
yoverlap = true;
// check for overlap in y
if(screenMin.y < cross->screenMin.y)
{
if(cross->screenMin.y > screenMax.y)
yoverlap = false;
}
else
{
if(screenMin.y > cross->screenMax.y)
yoverlap = false;
}
//xoverlap = ((cross->screenMin.x > screenMin.x && cross->screenMin.x < screenMax.x)
// || (cross->screenMax.x > screenMin.x && cross->screenMax.x < screenMax.x)); // overlap in x
//yoverlap = ((cross->screenMin.y > screenMin.y && cross->screenMin.y < screenMax.y)
// || (cross->screenMax.y > screenMin.y && cross->screenMax.y < screenMax.y)); // overlap in y
if(xoverlap && yoverlap)
{
// test every part of the two strokes against each other
for(i = 0; i < (int) scratch.size()-1; i++)
{
c[0] = scratch[i]; c[1] = scratch[i+1];
for(j = 0; j < (int) inscreen.size()-1; j++)
{
x[0] = inscreen[j]; x[1] = inscreen[j+1];
if(lineCrossing(c, x)) // intersection detected
numcrossings++;
}
}
}
return(numcrossings >= thresh);
}
*/
void Stroke::screenBounds(uts::vector<vpPoint> * strk)
{
screenMin = vpPoint(10000000.0f, 10000000.0f, 0.0f);
screenMax = vpPoint(-10000000.0f, -10000000.0f, 0.0f);
for(int i = 0; i < (int) strk->size(); i++)
{
if((* strk)[i].x < screenMin.x)
screenMin.x = (* strk)[i].x;
if((* strk)[i].x > screenMax.x)
screenMax.x = (* strk)[i].x;
if((* strk)[i].y < screenMin.y)
screenMin.y = (* strk)[i].y;
if((* strk)[i].y > screenMax.y)
screenMax.y = (* strk)[i].y;
}
}
bool Stroke::hasCurve() const
{
return shadow.isCreated();
}
void Stroke::setProximity()
{
// project stroke onto the current screen
// printf("projected stroke size = %d\n", (int) projected.size());
screenProject(&currview, shadow.getVerts(), &inscreen);
// form bounding box in screen space
screenBounds(&inscreen);
isinscreen = true;
}
void Stroke::genGL(View * view, Shape * s, float radius)
{
if(hasCurve())
shadow.genGL(view, s, radius);
}
bool Stroke::mergeShadow(View * view, Terrain * ter, Fragment * frag, bool & mrg, float tol, bool brushstroke)
{
bool pass;
mrg = false;
if(brushstroke)
shadow.clear();
// check to see that fragment has more than one point
if((int) frag->getFragVec()->size() == 0)
{
// cerr << "Error Stroke::mergeShadow: stroke is empty" << endl;
return false;
}
if((int) frag->getFragVec()->size() <= 2)
{
if(!brushstroke)
{
// cerr << "Error Stroke::mergeShadow: too few mouse points in stroke" << endl;
return false;
}
else // special cases for brush strokes
{
pass = shadow.create(frag->getFragVec(), view, ter);
return pass;
}
}
if(!shadow.isCreated()) // new stroke so shadow not created yet
{
pass = shadow.create(frag->getFragVec(), view, ter);
if(!brushstroke)
frag->clear();
}
else // otherwise merge into existing stroke
{
// project stroke onto the current screen
screenProject(&currview, &projected, &inscreen);
pass = shadow.mergeStroke(frag->getFragVec(), &projected, view, ter, mrg, tol);
}
return pass;
}
void Stroke::adjustHeights(Terrain * ter, ValueCurve hcurve)
{
if(hasCurve())
shadow.adjustHeights(ter, hcurve);
}
void Stroke::redrape(Terrain * ter)
{
if(hasCurve())
shadow.redrape(ter);
}
vpPoint Stroke::getPoint(float t) const
{
float ct;
if(hasCurve())
{
ct = t;
clamp(ct);
return shadow.getPoint(ct);
}
else
return vpPoint(0.0f, 0.0f, 0.0f);
}
float Stroke::getAngle(float t) const
{
Vector delv;
delv = getDirn(t);
return -1.0f * RAD2DEG * atan2(delv.k, delv.i);
}
Vector Stroke::getDirn(float t) const
{
Vector delv;
vpPoint p, delp;
float ct;
ct = t;
clamp(ct);
if(hasCurve())
{
delv = shadow.getDirn(ct);
/*
p = shadow->getPoint(ct);
if(ct >= 0.98f)
{
delp = shadow->getPoint(ct-0.02f);
delv.diff(delp, p);
}
else
{
delp = shadow->getPoint(ct+0.02f);
delv.diff(p, delp);
}
delv.normalize();*/
return delv;
}
else
return Vector(0.0f, 0.0f, 0.0f);
}
void Stroke::closestToPnt(vpPoint p, float & t, float & dist) const
{
Vector sdirn, pdirn, norm;
vpPoint sp, pp;
if(hasCurve())
{
shadow.closest(p, t, dist, sp, sdirn);
/*
if(fabs(sdirn.i) <= pluszero && fabs(sdirn.j) <= pluszero && fabs(sdirn.k) <= pluszero)
{
cerr << "Error Stroke::closest: zero dirn vector" << endl;
cerr << "p = " << p.x << ", " << p.y << ", " << p.z << endl;
cerr << "t = " << t << endl;
cerr << "sdirn = " << sdirn.i << ", " << sdirn.j << ", " << sdirn.k << endl;
}*/
norm.i = -1.0f * sdirn.k; norm.j = 0.0f; norm.k = sdirn.i; // rotate by 90 degrees
if(fabsf(norm.i) < pluszero && fabsf(norm.k) < pluszero)
cerr << "error (Stroke::closest): degenerate direction vector" << endl;
norm.normalize();
sp.y = 0.0f;
pp = p; pp.y = 0.0f;
pdirn.diff(sp, pp); // from stroke point to query point
pdirn.normalize();
if(norm.dot(pdirn) >= 0.0f) // right-sided pnt
dist *= -1.0f;
}
else
{
t = -1.0f;
dist = 0.0f;
}
}
void Stroke::closestToRay(vpPoint cop, Vector dirn, float & t, float & dist) const
{
if(hasCurve())
{
shadow.closestToRay(cop, dirn, t, dist);
}
else
{
t = -1.0f;
dist = 0.0f;
}
}
BoundRect Stroke::boundingBox(float t0, float t1) const
{
BoundRect cb;
if(hasCurve())
return shadow.boundingBox(t0, t1);
else
{
// cerr << "Error (Stroke::boundingBox): curve not properly intialized" << endl;
cb.min = vpPoint(0.0f, 0.0f, 0.0f);
cb.max = vpPoint(0.0f, 0.0f, 0.0f);
return cb;
}
}
void Stroke::printEndpoints()
{
vpPoint pnt;
pnt = getPoint(0.0f);
cerr << "start = " << pnt.x << ", " << pnt.y << ", " << pnt.z << endl;
pnt = getPoint(1.0f);
cerr << "end = " << pnt.x << ", " << pnt.y << ", " << pnt.z << endl;
}
| 58,002
|
C++
|
.cpp
| 1,812
| 23.934327
| 153
| 0.511369
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,216
|
typemap.cpp
|
jgain_EcoLearn/EcoSynth/viewer/typemap.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected]) and K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
//
// TypeMap
//
#include "data_importer/data_importer.h"
#include "palette.h"
#include "typemap.h"
#include "vecpnt.h"
#include "grass.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <time.h>
#include <QFileInfo>
#include <QLabel>
#include <QImage>
#include <QRgb>
/*
Perceptually uniform colourmaps from:
http://peterkovesi.com/projects/colourmaps/
*/
using namespace std;
// Sonoma County Colours
float hardwood[] = {0.749f, 0.815f, 0.611f, 1.0f};
float conifer[] = {0.812f, 0.789f, 0.55f, 1.0f};
float mixed[] = {0.552f, 0.662f, 0.533f, 1.0f};
float riparian[] = {0.4f, 0.6f, 0.6f, 1.0f};
float nonnative[] = {0.7, 0.6, 0.4, 1.0f};
float sliver[] = {0.652f, 0.762f, 0.633f, 1.0f};
float shrubery[] = {0.882f, 0.843f, 0.713f, 1.0f};
float ripshrub[] = {0.509f, 0.67f, 0.584f, 1.0f};
float herb[] = {0.75f, 0.7f, 0.7f, 1.0f};
float herbwet[] = {0.623f, 0.741f, 0.825f, 1.0f};
float aquatic[] = {0.537f, 0.623f, 0.752f, 1.0f};
float salt[] = {0.727f, 0.763f, 0.534f, 1.0f};
float barrenland[] = {0.818f, 0.801f, 0.723f, 1.0f};
float agriculture[] = {0.894f, 0.913f, 0.639f, 1.0f};
float wet[] = {0.737f, 0.823f, 0.952f, 1.0f};
float developed[] = {0.5f, 0.4f, 0.5f, 1.0f};
// Patterson's USGS Natural Map Colours
/*
// video colours
float barren[] = {0.818f, 0.801f, 0.723f, 1.0f}; // 1
float ravine[] = {0.755f, 0.645f, 0.538f, 1.0f}; // 2
float canyon[] = {0.771f, 0.431f, 0.351f, 1.0f}; // 3
float grassland[] = {0.75f, 0.7f, 0.7f, 1.0f}; // 4
float pasture[] = {0.894f, 0.913f, 0.639f, 1.0f}; // 5
float foldhills[] = {0.727f, 0.763f, 0.534f, 1.0f}; // 6
float orchard[] = {0.749f, 0.815f, 0.611f, 1.0f}; // 7
float evergreenforest[] = {0.812f, 0.789f, 0.55f, 1.0f}; // 8
float otherforest[] = {0.552f, 0.662f, 0.533f, 1.0f}; // 9
float woodywetland[] = {0.509f, 0.67f, 0.584f, 1.0f}; // 10
float herbwetland[] = {0.623f, 0.741f, 0.825f, 1.0f}; // 11
float frillbank[] = {0.4f, 0.6f, 0.6f, 1.0f}; // 12
float shrub[] = {0.882f, 0.843f, 0.713f, 1.0f}; // 13
float flatinterest[] = {0.300f, 0.515f, 0.0f, 1.0f}; // 14
float water[] = {0.737f, 0.823f, 0.952f, 1.0f}; // 15
float special[] = {0.4f, 0.4f, 0.4f, 1.0f}; // 16
float extra[] = {0.5f, 0.4f, 0.5f, 1.0f}; // 17
float realwater[] = {0.537f, 0.623f, 0.752f, 1.0f}; // 18
float boulders[] = {0.671f, 0.331f, 0.221f, 1.0f}; // 19
*/
/*
// quilt fig colours
float a1[] = {0.627f, 0.627f, 0.666f, 1.0f}; // 18 - 160 160 170
float a2[] = {0.771f, 0.431f, 0.351f, 1.0f}; // 3 - 196 110 90
float a3[] = {0.458, 0.518f, 0.439f, 1.0f}; // 7 mod - 117 132 112
float a4[] = {0.486, 0.415f, 0.317f, 1.0f}; // 17 mod - 124 106 81
float a5[] = {0.755f, 0.645f, 0.538f, 1.0f}; // 2 - 193 164 137
float a6[] = {0.812f, 0.789f, 0.55f, 1.0f}; // 14 - 207 201 140
float a7[] = {0.552f, 0.662f, 0.533f, 1.0f}; // 9 - 141 169 136
float a8[] = {0.305f, 0.541f, 0.384f, 1.0f}; // 8 mod - 78 138 98
float a9[] = {0.4f, 0.6f, 0.6f, 1.0f}; // 12 - 102 153 153
float q1[] = {0.818f, 0.801f, 0.723f, 1.0f}; // 1
float q2[] = {0.75f, 0.7f, 0.7f, 1.0f}; // 4
float q3[] = {0.894f, 0.913f, 0.639f, 1.0f}; // 5
float q4[] = {0.727f, 0.763f, 0.534f, 1.0f}; // 6
float q5[] = {0.509f, 0.67f, 0.584f, 1.0f}; // 10
float q6[] = {0.623f, 0.741f, 0.825f, 1.0f}; // 11
float q7[] = {0.882f, 0.843f, 0.713f, 1.0f}; // 13
float q8[] = {0.737f, 0.823f, 0.952f, 1.0f}; // 15
float q9[] = {0.4f, 0.4f, 0.4f, 1.0f}; // 16
float q10[] = {0.671f, 0.331f, 0.221f, 1.0f}; // 19
*/
/*
// replication fig colours
float a1[] = {0.627f, 0.627f, 0.666f, 1.0f}; // 18 - 160 160 170
float a2[] = {0.771f, 0.431f, 0.351f, 1.0f}; // 3 - 196 110 90
float a3[] = {0.458, 0.518f, 0.439f, 1.0f}; // 7 mod - 117 132 112
float a4[] = {0.486, 0.415f, 0.317f, 1.0f}; // 17 mod - 124 106 81
float a5[] = {0.755f, 0.645f, 0.538f, 1.0f}; // 2 - 193 164 137
float a6[] = {0.812f, 0.789f, 0.55f, 1.0f}; // 14 - 207 201 140
float a7[] = {0.588f, 0.521f, 0.443f, 1.0f}; // 9 - (GC walls) 150 133 113
float a8[] = {0.305f, 0.541f, 0.384f, 1.0f}; // 8 mod - 78 138 98
float a9[] = {0.4f, 0.6f, 0.6f, 1.0f}; // 12 - 102 153 153
float q1[] = {0.823f, 0.639f, 0.56f, 1.0f}; // 1 - (GC tops) 175 136 119
float q2[] = {0.75f, 0.7f, 0.7f, 1.0f}; // 4
float q3[] = {0.894f, 0.913f, 0.639f, 1.0f}; // 5
float q4[] = {0.727f, 0.763f, 0.534f, 1.0f}; // 6
float q5[] = {0.509f, 0.67f, 0.584f, 1.0f}; // 10
float q6[] = {0.623f, 0.741f, 0.825f, 1.0f}; // 11
float q7[] = {0.882f, 0.843f, 0.713f, 1.0f}; // 13
float q8[] = {0.737f, 0.823f, 0.952f, 1.0f}; // 15
float q9[] = {0.4f, 0.4f, 0.4f, 1.0f}; // 16
float q10[] = {0.671f, 0.331f, 0.221f, 1.0f}; // 19
*/
/*
// coherence fig colours
float a1[] = {0.627f, 0.627f, 0.666f, 1.0f}; // 18 - 160 160 170
float a2[] = {0.771f, 0.431f, 0.351f, 1.0f}; // 3 - 196 110 90
float a3[] = {0.458, 0.518f, 0.439f, 1.0f}; // 7 mod - 117 132 112
float a4[] = {0.486, 0.415f, 0.317f, 1.0f}; // 17 mod - 124 106 81
float a5[] = {0.755f, 0.645f, 0.538f, 1.0f}; // 2 - 193 164 137
float a6[] = {0.812f, 0.789f, 0.55f, 1.0f}; // 14 - 207 201 140
float a7[] = {0.588f, 0.521f, 0.443f, 1.0f}; // 9 - (GC walls) 150 133 113
float a8[] = {0.305f, 0.541f, 0.384f, 1.0f}; // 8 mod - 78 138 98
float a9[] = {0.4f, 0.6f, 0.6f, 1.0f}; // 12 - 102 153 153
float q1[] = {0.823f, 0.639f, 0.56f, 1.0f}; // 1 - (GC tops) 175 136 119
float q2[] = {0.75f, 0.7f, 0.7f, 1.0f}; // 4
float q3[] = {0.772f, 0.702f, 0.345f, 1.0f}; // (vegas gold) 197 179 88
float q4[] = {0.727f, 0.763f, 0.534f, 1.0f}; // 6
float q5[] = {0.509f, 0.67f, 0.584f, 1.0f}; // 10
float q6[] = {0.623f, 0.741f, 0.825f, 1.0f}; // 11
float q7[] = {0.882f, 0.843f, 0.713f, 1.0f}; // 13
float q8[] = {0.737f, 0.823f, 0.952f, 1.0f}; // 15
float q9[] = {0.552f, 0.662f, 0.533f, 1.0f}; // (formerly greyland)
float q10[] = {0.429f, 0.498f, 0.602f, 1.0f}; // (real water)
*/
/*
// banner fig colours
float a1[] = {0.812f, 0.789f, 0.55f, 1.0f}; // 18 - 160 176 178
float a2[] = {0.771f, 0.431f, 0.351f, 1.0f}; // 3 - 196 110 90
float a3[] = {0.458, 0.518f, 0.439f, 1.0f}; // 7 mod - 117 132 112
float a4[] = {0.486, 0.415f, 0.317f, 1.0f}; // 17 mod - 124 106 81
float a5[] = {0.755f, 0.645f, 0.538f, 1.0f}; // 2 - 193 164 137
float a6[] = {0.627f, 0.69f, 0.7f, 1.0f}; // 14 - 207 201 140
float a7[] = {0.588f, 0.521f, 0.443f, 1.0f}; // 9 - (GC walls) 150 133 113
float a8[] = {0.305f, 0.541f, 0.384f, 1.0f}; // 8 mod - 78 138 98
float a9[] = {0.4f, 0.6f, 0.6f, 1.0f}; // 12 - 102 153 153
float q1[] = {0.823f, 0.639f, 0.56f, 1.0f}; // 1 - (GC tops) 175 136 119
float q2[] = {0.757f, 0.701f, 0.423f, 1.0f}; // 193 179 108
float q3[] = {0.772f, 0.702f, 0.345f, 1.0f}; // (vegas gold) 197 179 88
float q4[] = {0.618f, 0.649f, 0.454f, 1.0f}; // (darken foldhills)
float q5[] = {0.737f, 0.823f, 0.952f, 1.0f}; // 10
float q6[] = {0.623f, 0.741f, 0.825f, 1.0f}; // 11
float q7[] = {0.882f, 0.843f, 0.713f, 1.0f}; // 13
float q8[] = {0.509f, 0.67f, 0.584f, 1.0f}; // 15
float q9[] = {0.552f, 0.662f, 0.533f, 1.0f}; // (formerly greyland)
float q10[] = {0.429f, 0.498f, 0.602f, 1.0f}; // (real water)
*/
/*
// default colours
float barren[] = {0.818f, 0.801f, 0.723f, 1.0f}; // 1
float ravine[] = {0.755f, 0.645f, 0.538f, 1.0f}; // 2
float canyon[] = {0.771f, 0.431f, 0.351f, 1.0f}; // 3
float grassland[] = {0.75f, 0.7f, 0.7f, 1.0f}; // 4
float pasture[] = {0.894f, 0.913f, 0.639f, 1.0f}; // 5
float foldhills[] = {0.727f, 0.763f, 0.534f, 1.0f}; // 6
float orchard[] = {0.749f, 0.815f, 0.611f, 1.0f}; // 7
float evergreenforest[] = {0.300f, 0.515f, 0.0f, 1.0f}; // 8
float otherforest[] = {0.552f, 0.662f, 0.533f, 1.0f}; // 9
float woodywetland[] = {0.509f, 0.67f, 0.584f, 1.0f}; // 10
float herbwetland[] = {0.623f, 0.741f, 0.825f, 1.0f}; // 11
float frillbank[] = {0.4f, 0.6f, 0.6f, 1.0f}; // 12
float shrub[] = {0.882f, 0.843f, 0.713f, 1.0f}; // 13
float flatinterest[] = {0.812f, 0.789f, 0.55f, 1.0f}; // 14
float water[] = {0.737f, 0.823f, 0.952f, 1.0f}; // 15
float special[] = {0.4f, 0.4f, 0.4f, 1.0f}; // 16
float extra[] = {0.5f, 0.4f, 0.5f, 1.0f}; // 17
float realwater[] = {0.537f, 0.623f, 0.752f, 1.0f}; // 18
float boulders[] = {0.671f, 0.331f, 0.221f, 1.0f}; // 19
*/
// palette colours
float freecol[] = {0.755f, 0.645f, 0.538f, 1.0f};
float sparseshrub[] = {0.814f, 0.853f, 0.969f, 1.0f};
float sparsemed[] = {0.727f, 0.763f, 0.834f, 1.0f};
float sparsetall[] = {0.537f, 0.623f, 0.752f, 1.0f};
float denseshrub[] = {0.749f, 0.815f, 0.611f, 1.0f};
float densemed[] = {0.552f, 0.662f, 0.533f, 1.0f};
float densetall[] = {0.300f, 0.515f, 0.1f, 1.0f};
float basic_red[] = {1.0f, 0.0f, 0.0f, 1.0f};
float basic_green[] = {0.0f, 1.0f, 0.0f, 1.0f};
float basic_blue[] = {0.0f, 0.0f, 1.0f, 1.0f};
float denseveg[] = {freecol[0] * 0.25f + 0.0f, freecol[1] * 0.25f + 0.5f * 0.75f, freecol[2] * 0.25f + 0.0f, 1.0f};
float sparseveg[] = {freecol[0] * 0.65f + 0.0f, freecol[1] * 0.65f + 0.5f * 0.35f, freecol[2] * 0.65f + 0.0f, 1.0f};
/*
float rock[] = {0.4f, 0.4f, 0.4f, 1.0f};
float sand[] = {0.89f, 0.74f, 0.513f}; // {0.772f, 0.702f, 0.345f, 1.0f};
float grass[] = {0.552f, 0.662f, 0.533f, 1.0f};
float watery[] = {0.537f, 0.623f, 0.752f, 1.0f};
float blank[] = {1.0f, 1.0f, 1.0f, 1.0f};
// lilac
float younger[] = {0.797f, 0.703f, 0.785f}; // {0.818f, 0.801f, 0.723f, 1.0f};
float older[] = {0.647f, 0.553f, 0.635f}; // {0.572f, 0.560f, 0.506f, 1.0f};
// green shades
float sparser[] = {0.729f, 0.89f, 0.824f}; // {0.717f, 0.860f, 0.692f, 1.0f};
float denser[] = {0.583f, 0.712f, 0.659f}; // {0.552f, 0.662f, 0.533f, 1.0f};
// orange
float similar[] = {1.0f, 0.89f, 0.792f}; // {0.872f, 0.430f, 0.287f, 1.0f};
float variable[] = {0.8f, 0.712f, 0.634f}; // {0.671f, 0.331f, 0.221f, 1.0f};
float heal[] = {0.749f, 0.5f, 0.5f, 1.0f};
float distribution[] = {0.849f, 0.915f, 0.711f, 1.0f}; // {0.749f, 0.815f, 0.611f, 1.0f};
*/
// default colours
float barren[] = {0.818f, 0.801f, 0.723f, 1.0f}; // 1
float ravine[] = {0.755f, 0.645f, 0.538f, 1.0f}; // 2
float canyon[] = {0.771f, 0.431f, 0.351f, 1.0f}; // 3
float grassland[] = {0.552f, 0.662f, 0.533f, 1.0f}; // 4
float pasture[] = {0.894f, 0.913f, 0.639f, 1.0f}; // 5
float foldhills[] = {0.727f, 0.763f, 0.534f, 1.0f}; // 6
float orchard[] = {0.749f, 0.815f, 0.611f, 1.0f}; // 7
float evergreenforest[] = {0.300f, 0.515f, 0.0f, 1.0f}; // 8
float otherforest[] = {0.552f, 0.662f, 0.533f, 1.0f}; // 9
float woodywetland[] = {0.509f, 0.67f, 0.584f, 1.0f}; // 10
float herbwetland[] = {0.623f, 0.741f, 0.825f, 1.0f}; // 11
float frillbank[] = {0.4f, 0.6f, 0.6f, 1.0f}; // 12
float shrub[] = {0.882f, 0.843f, 0.713f, 1.0f}; // 13
float flatinterest[] = {0.812f, 0.789f, 0.55f, 1.0f}; // 14
float water[] = {0.737f, 0.823f, 0.952f, 1.0f}; // 15
float special[] = {0.4f, 0.4f, 0.4f, 1.0f}; // 16
float extra[] = {0.5f, 0.4f, 0.5f, 1.0f}; // 17
float realwater[] = {0.537f, 0.623f, 0.752f, 1.0f}; // 18
float boulders[] = {0.671f, 0.331f, 0.221f, 1.0f}; // 19
// cluster colours
float c0[] = {0.537f, 0.623f, 0.752f, 1.0f}; // water
float c1[] = {0.509f, 0.67f, 0.584f, 1.0f}; // high moisture
//float c0[] = {0.755f, 0.645f, 0.538f, 1.0f};
//float c1[] = {0.89f, 0.74f, 0.513f};
float c2[] = {0.671f, 0.331f, 0.221f, 1.0f}; // rock for high slope
//float c3[] = {0.8f, 0.712f, 0.634f};
float c3[] = {0.647f, 0.553f, 0.635f};
//float c3[] = {0.894f, 0.913f, 0.639f, 1.0f}; // high sun
float c4[] = {0.552f, 0.662f, 0.533f, 1.0f}; // low sun
float c5[] = {0.771f, 0.431f, 0.351f, 1.0f};
//float c6[] = {0.749f, 0.815f, 0.611f, 1.0f};
// float c6[] = {0.4f, 0.6f, 0.6f, 1.0f};
float c6[] = {0.749f, 0.5f, 0.5f, 1.0f};
//float c7[] = {0.623f, 0.741f, 0.825f, 1.0f};
float c7[] = {0.812f, 0.789f, 0.55f, 1.0f};
float c8[] = {0.727f, 0.763f, 0.534f, 1.0f};
//float c9[] = {0.300f, 0.515f, 0.0f, 1.0f};
float c9[] = {0.8f, 0.712f, 0.634f};
float c10[] = {0.882f, 0.843f, 0.713f, 1.0f};
float c11[] = {0.755f, 0.645f, 0.538f, 1.0f};
float c12[] = {0.8f, 0.712f, 0.634f};
float c13[] = {0.647f, 0.553f, 0.635f};
float c14[] = {0.89f, 0.74f, 0.513f};
TypeMap::TypeMap(TypeMapType purpose)
{
tmap = new MemMap<int>;
setPurpose(purpose);
}
TypeMap::TypeMap(int w, int h, TypeMapType purpose)
{
tmap = new MemMap<int>;
matchDim(w, h);
setPurpose(purpose);
}
TypeMap::~TypeMap()
{
delete tmap;
for(int i = 0; i < (int) colmap.size(); i++)
delete [] colmap[i];
colmap.clear();
if (cdata_ptr)
delete cdata_ptr;
}
void TypeMap::clear()
{
tmap->fill(0);
}
void TypeMap::replace_value(int orig, int newval)
{
int w = width();
int h = height();
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
int to = get(x, y);
if (to == orig)
set(x, y, newval);
}
}
}
void TypeMap::initPaletteColTable()
{
GLfloat *col;
for(int i = 0; i < 32; i++) // set all colours in table to black initially
{
col = new GLfloat[4];
col[0] = col[1] = col[2] = 0.0f; col[3] = 1.0f;
colmap.push_back(col);
}
numSamples = 3; //really? should be 3...?
colmap[0] = freecol;
colmap[1] = sparseveg;
colmap[2] = denseveg;
}
void TypeMap::initSpeciesColTable(std::string dbname)
{
data_importer::common_data cdata(dbname);
GLfloat *col;
for(int i = 0; i < 32; i++) // set all colours in table to black initially
{
col = new GLfloat[4];
col[0] = col[1] = col[2] = 0.0f; col[3] = 1.0f;
colmap.push_back(col);
}
//numSamples = 3;
numSamples = cdata.all_species.size();
/*
colmap[0] = sparsemed;
colmap[1] = densemed;
colmap[2] = sparseshrub;
colmap[0] = basic_red;
colmap[1] = basic_green;
colmap[2] = basic_blue;
*/
std::map<int, data_importer::species>::iterator speciter = cdata.all_species.begin();
for (int i = 0; i < cdata.all_species.size(); i++, advance(speciter, 1))
{
assert(speciter->first < 32);
for (int j = 0; j < 3; j++)
colmap[speciter->first][j] = speciter->second.basecol[j];
}
}
void TypeMap::initCategoryColTable()
{
GLfloat * col;
for(int i = 0; i < 32; i++) // set all colours in table to black initially
{
col = new GLfloat[4];
col[0] = col[1] = col[2] = 0.0f; col[3] = 1.0f;
colmap.push_back(col);
}
// entry 0 is reserved as transparent
numSamples = 16;
colmap[1] = hardwood;
colmap[2] = conifer;
colmap[3] = mixed;
colmap[4] = riparian;
colmap[5] = nonnative;
colmap[6] = sliver;
colmap[7] = shrubery;
colmap[8] = ripshrub;
colmap[9] = herb;
colmap[10] = herbwet;
colmap[11] = aquatic;
colmap[12] = salt;
colmap[13] = barrenland;
colmap[14] = agriculture;
colmap[15] = wet;
colmap[16] = developed;
}
void TypeMap::initNaturalColTable()
{
GLfloat * col;
for(int i = 0; i < 32; i++) // set all colours in table to black initially
{
col = new GLfloat[4];
col[0] = col[1] = col[2] = 0.0f; col[3] = 1.0f;
colmap.push_back(col);
}
// saturated prime colours and combos
/*
(colmap[1])[0] = 1.0f; // red
(colmap[2])[1] = 1.0f; // green
(colmap[3])[2] = 1.0f; // blue
(colmap[4])[1] = 1.0f; (colmap[4])[2] = 1.0f; // cyan
(colmap[5])[0] = 1.0f; (colmap[5])[1] = 1.0f; // yellow
(colmap[6])[0] = 1.0f; (colmap[6])[2] = 1.0f; // magenta
(colmap[7])[0] = 0.5f; (colmap[7])[1] = 0.5f; (colmap[7])[2] = 0.5f; // grey
(colmap[8])[1] = 0.5f; (colmap[8])[2] = 0.5f; // teal
*/
numSamples = 20;
// default
//colmap[0] = c0;
colmap[1] = barren;
colmap[2] = ravine;
colmap[3] = canyon;
colmap[4] = grassland;
colmap[5] = pasture;
colmap[6] = foldhills;
colmap[7] = orchard;
colmap[8] = woodywetland;
colmap[9] = otherforest;
colmap[10] = woodywetland;
colmap[11] = herbwetland;
colmap[12] = frillbank;
colmap[13] = shrub;
colmap[14] = flatinterest;
colmap[15] = water;
colmap[16] = special;
colmap[17] = extra;
colmap[18] = realwater;
colmap[19] = boulders;
}
void TypeMap::initPerceptualColTable(std::string colmapfile, int samples, float truncend)
{
GLfloat *col;
float r[256], g[256], b[256];
ifstream infile;
string valstr, line;
int i, pos, step;
if(samples < 3 || samples > 32)
cerr << "Error: sampling of colour map must be in the range [3,32]" << endl;
for(i = 0; i < 32; i++) // set all colours in table to black initially
{
col = new GLfloat[4];
col[0] = col[1] = col[2] = 0.0f; col[3] = 1.0f;
colmap.push_back(col);
}
// input is a csv file, with 256 RGB entries, one on each line
// note that this is not robust to format errors in the input file
infile.open((char *) colmapfile.c_str(), ios_base::in);
if(infile.is_open())
{
i = 0;
while(std::getline(infile, line))
{
std::size_t prev = 0, pos;
// red component
pos = line.find_first_of(",", prev);
valstr = line.substr(prev, pos-prev);
istringstream isr(valstr);
isr >> r[i];
prev = pos+1;
// green component
pos = line.find_first_of(",", prev);
valstr = line.substr(prev, pos-prev);
istringstream isg(valstr);
isg >> g[i];
prev = pos+1;
// blue component
valstr = line.substr(prev, std::string::npos);
istringstream isb(valstr);
isb >> b[i];
i++;
}
infile.close();
}
else
{
std::cout << "WARNING: Could not find perceptual colour table at " << colmapfile << std::endl;
}
// now sample the colour map at even intervals according to the number of samples
// first and last samples map to the beginning and end of the scale
step = (int) ((256.0f * truncend) / (float) (samples-1));
pos = 0;
for(i = 1; i <= samples; i++)
{
colmap[i][0] = (GLfloat) r[pos]; colmap[i][1] = (GLfloat) g[pos]; colmap[i][2] = (GLfloat) b[pos];
pos += step;
}
numSamples = samples+1;
}
void TypeMap::clipRegion(Region ®)
{
if(reg.x0 < 0) reg.x0 = 0;
if(reg.y0 < 0) reg.y0 = 0;
if(reg.x1 > width()) reg.x1 = width();
if(reg.y1 > height()) reg.y1 = height();
}
void TypeMap::matchDim(int w, int h)
{
int mx, my;
mx = tmap->width();
my = tmap->height();
// if dimensions don't match then reallocate
if(w != mx || h != my)
{
dirtyreg = Region(0, 0, w, h);
tmap->allocate(Region(0, 0, w, h));
tmap->fill(0); // set to empty type
}
}
void TypeMap::replaceMap(MemMap<int> * newmap)
{
assert(tmap->width() == newmap->width());
assert(tmap->height() == newmap->height());
for (int y = 0; y < tmap->height(); y++)
for (int x = 0; x < tmap->width(); x++)
(* tmap)[y][x] = (* newmap)[y][x];
}
void TypeMap::bandCHMMap(MapFloat * chm, float mint, float maxt)
{
int tp;
float val;
if(maxt > mint)
{
for (int x = 0; x < tmap->width(); x++)
for (int y = 0; y < tmap->height(); y++)
{
val = chm->get(y, x);
// discretise into ranges of height values
if(val <= 0.0f) // transparent
{
tp = 1;
}
else if(val <= mint) // black
{
tp = 2;
}
else if(val >= maxt) // red
{
tp = numSamples+2;
}
else // green range
{
tp = (int) ((val-mint) / (maxt-mint+pluszero) * (numSamples-1))+2;
}
(* tmap)[y][x] = tp;
}
}
}
void TypeMap::bandCHMMapEric(MapFloat * chm, float mint, float maxt)
{
int tp;
float val;
if(maxt > mint)
{
for (int x = 0; x < tmap->width(); x++)
for (int y = 0; y < tmap->height(); y++)
{
val = chm->get(y, x);
// discretise into ranges of height values
if(val <= mint || val >= maxt) // transparent
{
tp = 1;
}
else
{
tp = 2;
}
(* tmap)[y][x] = tp;
}
}
}
int TypeMap::load(const QImage &img, TypeMapType purpose)
{
int tp, maxtp = 0; // mintp = 100;
int width, height;
float val, maxval = 0.0f, range;
width = img.width();
height = img.height();
matchDim(width, height);
// convert to internal type map format
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
QColor col = img.pixelColor(x, y);
int ival = col.red();
switch(purpose)
{
case TypeMapType::EMPTY: // do nothing
break;
case TypeMapType::CATEGORY:
tp = ival;
tp++;
break;
case TypeMapType::SLOPE:
val = ival;
if(val > maxval)
maxval = val;
// discretise into ranges of slope values
range = 90.0f; // maximum slope is 90 degrees
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::WATER:
val = ival;
if(val > maxval)
maxval = val;
// discretise into ranges of water values
range = 100.0f;
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::SUNLIGHT:
val = ival;
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
range = 12.0f; // hours of sunlight
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::TEMPERATURE:
val = ival;
if(val > maxval)
maxval = val;
// discretise into ranges of temperature values
range = 20.0f; //10
// clamp values to range, temperature is bidrectional
if(val < -range) val = -range;
if(val > range) val = range;
tp = (int) ((val+range) / (2.0f*range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::CHM:
val = ival;
if(val > maxval)
maxval = val;
// discretise into ranges of height values
range = 75.0f; // maximum tree height in feet
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::CDM:
val = ival;
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
range = 1.0f; // maximum density
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::SUITABILITY:
break;
case TypeMapType::PAINT:
{
int sparsemin = 100, sparsemax = 150;
int densemin = 200;
if (img.depth() == 16)
{
sparsemin *= 256;
sparsemax *= 256;
densemin *= 256;
}
if (ival >= sparsemin && ival <= sparsemax)
tp = 1;
else if (ival >= densemin)
tp = 2;
else
tp = 0;
break;
}
default:
break;
}
(* tmap)[y][x] = tp;
if(tp > maxtp)
maxtp = tp;
/*
if(tp < mintp)
mintp = tp;
*/
}
}
// cerr << "maxtp = " << maxtp << endl;
// cerr << "mintp = " << mintp << endl;
return maxtp;
}
int TypeMap::load(const uts::string &filename, TypeMapType purpose)
{
MemMap<mask_tag> mask;
int tp, maxtp = 0; // mintp = 100;
int width, height;
ifstream infile;
float val, maxval = 0.0f, range;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> width >> height;
// cerr << "width = " << width << " height = " << height << endl;
matchDim(width, height);
// convert to internal type map format
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
switch(purpose)
{
case TypeMapType::EMPTY: // do nothing
break;
case TypeMapType::PAINT:
infile >> tp;
break;
case TypeMapType::CATEGORY:
infile >> tp;
tp++;
break;
case TypeMapType::SLOPE:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of slope values
range = 90.0f; // maximum slope is 90 degrees
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::WATER:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of water values
range = 100.0f;
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::SUNLIGHT:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
range = 12.0f; // hours of sunlight
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::TEMPERATURE:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of temperature values
range = 20.0f; //10
// clamp values to range, temperature is bidrectional
if(val < -range) val = -range;
if(val > range) val = range;
tp = (int) ((val+range) / (2.0f*range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::CHM:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of height values
range = 75.0f; // maximum tree height in feet
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::CDM:
infile >> val;
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
range = 1.0f; // maximum density
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-1))+1;
break;
case TypeMapType::SUITABILITY:
break;
default:
break;
}
(* tmap)[y][x] = tp;
if(tp > maxtp)
maxtp = tp;
/*
if(tp < mintp)
mintp = tp;
*/
}
}
infile.close();
// cerr << "maxtp = " << maxtp << endl;
// cerr << "mintp = " << mintp << endl;
}
else
{
cerr << "Error TypeMap::loadTxt: unable to open file" << filename << endl;
}
return maxtp;
}
bool TypeMap::loadCategoryImage(const uts::string &filename)
{
int width, height;
QImage img(QString::fromStdString(filename)); // load image from file
QFileInfo check_file(QString::fromStdString(filename));
if(!(check_file.exists() && check_file.isFile()))
return false;
// set internal storage dimensions
width = img.width();
height = img.height();
matchDim(width, height);
// convert to internal type map format
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
{
QColor col = img.pixelColor(x, y);
int r, g, b;
col.getRgb(&r, &g, &b); // all channels store the same info so just use red
(* tmap)[y][x] = r - 100; // convert greyscale colour to category index
}
return true;
}
void TypeMap::setWater(MapFloat * wet, float wetthresh)
{
int gx, gy;
wet->getDim(gx, gy);
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
if(wet->get(x, y) >= wetthresh)
{
(* tmap)[y][x] = 0;
}
}
}
int TypeMap::convert(MapFloat * map, TypeMapType purpose, float range)
{
int species_count = 0;
int tp, maxtp = 0;
int width, height;
float val, maxval = 0.0f;
map->getDim(width, height);
matchDim(width, height);
// convert to internal type map format
int mincm, maxcm;
mincm = 100; maxcm = -1;
for(int x = 0; x < width; x++)
for(int y = 0; y < height; y++)
{
tp = 0;
switch(purpose)
{
case TypeMapType::EMPTY: // do nothing
break;
case TypeMapType::PAINT: // do nothing
break;
case TypeMapType::CATEGORY: // do nothing, since categories are integers not floats
break;
case TypeMapType::SLOPE:
val = map->get(x, y);
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
break;
case TypeMapType::WATER:
val = map->get(y, x);
if(val > maxval)
maxval = val;
// discretise into ranges of water values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
break;
case TypeMapType::SUNLIGHT:
val = map->get(y, x);
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
break;
case TypeMapType::TEMPERATURE:
val = map->get(y, x);
if(val > maxval)
maxval = val;
// discretise into ranges of temperature values
// clamp values to range, temperature is bidrectional
if(val < -range) val = -range;
if(val > range) val = range;
tp = (int) ((val+range) / (2.0f*range+pluszero) * (numSamples-2)) + 1;
break;
case TypeMapType::CHM:
val = map->get(y, x);
if(val > maxval)
maxval = val;
// discretise into ranges of tree height values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range)
{
val = range;
//std::cout << "clamping value to range (upper): " << range << std::endl;
}
//tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
tp = (int) (val / (range+pluszero) * 256) + 1; // I am assuming we are not categorising this? Multiplying by 400 here will bring the heights back to their proper values in feet
if(tp < mincm)
mincm = tp;
if(tp > maxcm)
maxcm = tp;
break;
case TypeMapType::CDM:
val = map->get(y, x);
if(val > maxval)
maxval = val;
// discretise into ranges of tree density values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
if(tp < mincm)
mincm = tp;
if(tp > maxcm)
maxcm = tp;
break;
case TypeMapType::SUITABILITY:
val = map->get(y, x);
if(val > maxval)
maxval = val;
// discretise into ranges of illumination values
// clamp values to range
if(val < 0.0f) val = 0.0f;
if(val > range) val = range;
tp = (int) (val / (range+pluszero) * (numSamples-2)) + 1;
break;
case TypeMapType::GRASS:
tp = (int)(map->get(x, y) / MAXGRASSHGHT * 255.0f);
break;
case TypeMapType::PRETTY_PAINTED:
tp = (int)(map->get(x, y));
break;
case TypeMapType::PRETTY:
tp = (int)(map->get(x, y));
break;
case TypeMapType::SPECIES:
tp = (int)(map->get(x, y)) + 1;
if (tp >= 0)
species_count++;
break;
case TypeMapType::CLUSTER:
tp = (int)(map->get(y, x));
break;
case TypeMapType::CLUSTERDENSITY:
tp = (int)((map->get(y, x))) / 20.0f;
break;
default:
break;
}
(* tmap)[y][x] = tp;
if(tp > maxtp)
maxtp = tp;
}
if(purpose == TypeMapType::CDM)
{
cerr << "Minimum colour value = " << mincm << endl;
cerr << "Maxiumum colour value = " << maxcm << endl;
}
if (purpose == TypeMapType::SPECIES)
{
cerr << "Proportion of landscape assigned to species: " << species_count / ((float)width * height) << std::endl;
}
return maxtp;
}
void TypeMap::save(const uts::string &filename)
{
ofstream outfile;
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
outfile << width() << " " << height() << endl;
// dimensions
for (int x = 0; x < width(); x++)
for (int y = 0; y < height(); y++)
{
outfile << get(x, y) << " ";
}
outfile.close();
}
else
{
cerr << "Error TypeMap::save: unable to write to file" << endl;
}
}
void TypeMap::saveToGreyscaleImage(const uts::string &filename, float maxrange, bool row_major)
{
std::vector<unsigned char> mask;
std::cout << "Size of greyscale image: " << tmap->width() << ", " << tmap->height() << std::endl;
mask.resize(tmap->width()*tmap->height(), 0);
for (int x = 0; x < tmap->width(); x++)
for (int y = 0; y < tmap->height(); y++)
{
int i = row_major ? y * tmap->width() + x : x * tmap->height() + y;
//std::cout << (* tmap)[tmap->height()-y-1][x] << " ";
//mask[i] = (uint8_t)(((float) (* tmap)[tmap->height()-y-1][x] / maxrange) * 255.0f);
mask[i] = (uint8_t)(((float) (* tmap)[y][x] / maxrange) * 255.0f);
}
std::cout << std::endl;
std::cout << "Writing CHM output image as: " << filename << std::endl;
QImage img;
img = QImage(mask.data(), tmap->width(), tmap->height(), QImage::Format_Grayscale8);
if (!img.save(QString::fromStdString(filename), "PNG", 100))
{
std::cout << "Failed to write CHM image" << std::endl;
}
//OutImage outimg;
//outimg.write(filename, tmap->width(), tmap->height(), mask);
}
void TypeMap::saveToPaintImage(const uts::string &filename)
{
unsigned char * mask = new unsigned char[tmap->width()*tmap->height()];
int i = 0;
cerr << "paint file: " << filename << endl;
//mask.resize(tmap->width()*tmap->height(), 0.0f);
for (int x = 0; x < tmap->width(); x++)
for (int y = 0; y < tmap->height(); y++)
{
switch((*tmap)[x][y]) // check order
{
case 0:
mask[i] = 0;
break;
case 1: // sparse (this was previously 1)
mask[i] = 127;
break;
case 2: // dense (this was previously 2)
mask[i] = 255;
break;
default:
mask[i] = 0;
}
i++;
}
// use QT image save functions
QImage img;
img = QImage(mask, tmap->width(), tmap->height(), QImage::Format_Grayscale8);
img.save(QString::fromStdString(filename), "PNG", 100);
delete [] mask;
}
void TypeMap::setPurpose(TypeMapType purpose)
{
std::string coldir = COLMAP_DIR;
usage = purpose;
switch(usage)
{
case TypeMapType::EMPTY:
initPaletteColTable();
break;
case TypeMapType::PAINT:
initPaletteColTable();
break;
case TypeMapType::CATEGORY:
initCategoryColTable();
break;
case TypeMapType::SLOPE:
initPerceptualColTable(coldir + "/linear_kry_5-95_c72_n256.csv", 10);
break;
case TypeMapType::WATER:
initPerceptualColTable(coldir + "/linear_blue_95-50_c20_n256.csv", 10);
break;
case TypeMapType::SUNLIGHT:
initPerceptualColTable(coldir + "/linear_kry_5-95_c72_n256.csv", 10);
break;
case TypeMapType::TEMPERATURE:
initPerceptualColTable(coldir + "/diverging_bwr_55-98_c37_n256.csv", 10);
break;
case TypeMapType::CHM:
// initPerceptualColTable(coldir + "/linear_ternary-green_0-46_c42_n256.csv", 20);
initPerceptualColTable(coldir + "/linear_green_5-95_c69_n256.csv", 20);
// replace 0 with natural terrain colour
colmap[1][0] = 0.7f; colmap[1][1] = 0.6f; colmap[1][2] = 0.5f; // transparent
colmap[2][0] = 0.0f; colmap[2][1] = 0.0f; colmap[2][2] = 1.0f; // black
colmap[numSamples+2][0] = 1.0f; colmap[numSamples+2][1] = 0.0f; colmap[numSamples+2][2] = 0.0f; // red
break;
case TypeMapType::CDM:
initPerceptualColTable(coldir + "/linear_green_5-95_c69_n256.csv", 20);
// replace 0 with natural terrain colour
colmap[1][0] = 0.7f; colmap[1][1] = 0.6f; colmap[1][2] = 0.5f;
break;
case TypeMapType::SUITABILITY:
initPerceptualColTable(coldir + "/linear_gow_60-85_c27_n256.csv", 20, 0.8f);
// initPerceptualColTable(coldir + "/isoluminant_cgo_70_c39_n256.csv", 10);
break;
case TypeMapType::SPECIES:
initSpeciesColTable(std::string(PRJ_SRC_DIR) + "/ecodata/sonoma.db");
break;
default:
break;
}
}
void TypeMap::resetType(int ind)
{
// wipe all previous occurrences of ind
#pragma omp parallel for
for(int j = 0; j < tmap->height(); j++)
for(int i = 0; i < tmap->width(); i++)
if((* tmap)[j][i] == ind)
(* tmap)[j][i] = 0;
dirtyreg.x0 = 0; dirtyreg.y0 = 0;
dirtyreg.x1 = tmap->width(); dirtyreg.y1 = tmap->height();
}
void TypeMap::setColour(int ind, GLfloat * col)
{
for(int i = 0; i < 4; i++)
colmap[ind][i] = col[i];
}
| 45,331
|
C++
|
.cpp
| 1,124
| 30.474199
| 197
| 0.4783
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,217
|
moisture.cpp
|
jgain_EcoLearn/EcoSynth/viewer/moisture.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "moisture.h"
#include "waterfill.h"
#include <iostream>
using namespace std;
float MoistureSim::slopeImpact(float slope, float slopethresh, float slopemax, float runofflimit)
{
float revrunoff;
if(slope < slopethresh) // max absorption for slopes below threshold
revrunoff = runofflimit;
else if(slope > slopemax) // complete runoff for slopes above slope max
revrunoff = 0.0f;
else // otherwise linearly interpolate
{
revrunoff = (1.0f - (slope - slopethresh) / (slopemax - slopethresh)) * runofflimit;
}
return revrunoff;
}
void MoistureSim::simSoilCycle(Terrain * ter, MapFloat * terslope, std::vector<float> precipitation, float slopethresh, float slopemax, float evaporation, float runofflimit, float soilsaturation, float riverlevel, std::vector<MapFloat> & wsh)
{
/* Algorithm:
* Per pixel:
* Init resorvoir to 50% capacity by soil type
* Init excess_m to 0
* Iterate 2 or 3 times (to achieve equilibrium)
* Per month (m)
* res_p += (1-w_e) * P_m - w_t
* run flow simulation with excess_m
* if res_p < w_s
* res_p = min(w_s, res_p + flow_p)
* if res_p >= w_s
* mark as standing water
* else
* excess_m+1,m+2,m+3 += 1/3 (res_p - w_s)
* res_p = w_s
* if flow_p > 0
* mark as standing water
* moisture_p = min(w_s, res_p + w_t)
* where w_e = proportion of evaporation, P_m is precipitation per month, w_s = maximum available water saturation by soil type
* w_t = monthly transpiration
*/
std::vector<float> reservoir, transpiration;
std::vector<std::vector<uint>> excess;
int dx, dy;
terslope->getDim(dx, dy);
cerr << "image size = " << dx << " by " << dy << endl;
QImage wfimg = QImage(dx, dy, QImage::Format_RGB32);
QImage fpimg = QImage(dx, dy, QImage::Format_RGB32);
WaterFill wf, fp; // water network, flood plain
int i, j, x, y, t, p;
bool flood;
float wval, flow, onsoil, insoil, runoff, plain, groundwater, avgexcess, slope, sloperunoff, avgslope, avgrunoff;
int minmnth[12], maxmnth[12], floodcount, excesscount;
// calculate transpiration levels to achieve equilibrium for each terrain pixel, because of dependence on slope
// sum of min runofflimit, monthly non-evaporated precipitation
transpiration.resize(dy*dy, 0.0f);
avgrunoff = 0.0f; avgslope = 0.0f;
cerr << "slopeImpact at " << slopethresh << " = " << slopeImpact(slopethresh, slopethresh, slopemax, runofflimit) << endl;
cerr << "slopeImpact at " << slopemax << " = " << slopeImpact(slopemax, slopethresh, slopemax, runofflimit) << endl;
cerr << "slopeImpact at " << 25.0f << " = " << slopeImpact(25.0f, slopethresh, slopemax, runofflimit) << endl;
cerr << "PRECIPITATION: ";
for(i = 0; i < 12; i++)
cerr << precipitation[i] << " ";
cerr << endl;
float minslope = 90.0f, maxslope = 0.0f;
for(p = 0; p < dx * dy; p++)
{
x = p%dx;
y = p/dx;
slope = terslope->get(x, y);
if(slope < minslope)
minslope = slope;
if(slope > maxslope)
maxslope = slope;
sloperunoff = slopeImpact(slope, slopethresh, slopemax, runofflimit);
avgrunoff += sloperunoff;
avgslope += slope;
for(i = 0; i < 12; i++)
transpiration[p] += min(sloperunoff, (1.0f - evaporation) * precipitation[i]);
}
cerr << "average slope = " << avgslope / ((float) dx * dy) << endl;
cerr << "average runoff = " << avgrunoff / ((float) dx * dy) << endl;
// water fill parameters
float riverreach = 50.0f; // weighting for how far water table expands out around rivers
float slopeweight = 1.0f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to widen
float flowpowerterm = 0.5f; // power term applied to flow result
/*
// for alpine
#ifdef ALPINEBIOME
riverreach = 50.0f; // weighting for how far water table expands out around rivers
slopeweight = 1.0f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to widen
#endif
// for savannah
#ifdef SAVANNAHBIOME
riverreach = 100.0f; // weighting for how far water table expands out around rivers
slopeweight = 0.9f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to widen
#endif
// for canyon
#ifdef CANYONBIOME
riverreach = 50.0f; // weighting for how far water table expands out around rivers
slopeweight = 1.4f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to wide
#endif
// for mediterrainean style canyon
#ifdef CANYONWETBIOME
riverreach = 50.0f; // weighting for how far water table expands out around rivers
slopeweight = 1.4f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to wide
#endif
// for med
#ifdef MEDBIOME
riverreach = 50.0f; // weighting for how far water table expands out around rivers
slopeweight = 1.0f; // how much impact slope has on river expansion, > 1 to narrow, < 1 to widen
#endif
*/
// initialise water flow field
cerr << "waterflow: set terrain" << endl;
wf.setTerrain(ter);
// initialise terrain-based moisture values
// reservoir.resize(dx*dy, 0.5 * soilsaturation);
reservoir.resize(dx*dy, 0.0f); // no initial water
for(i = 0; i < 12; i++)
{
std::vector<uint> noexcess;
noexcess.resize(dx*dy, 0);
excess.push_back(noexcess);
minmnth[i] = 1000; maxmnth[i] = 0;
}
for(t = 0; t < 2; t++) // simulation needs to be run twice to ensure proper settings for early months
{
cerr << "iteration " << t << endl;
floodcount = 0; excesscount = 0; avgexcess = 0.0f;
for(i = 0; i < 12; i++) // calculate soil moisture per month
{
wf.setAbsorbsion(riverlevel);
wf.reset();
wf.compute(); // seed flow computation with water seepage values
// canyon inflow
// wf.smartWaterInflow(1020, 939); // 964
// wf.smartWaterInflow(1020, 939); // 964
// wf.smartWaterInflow(1002, 931); // 949
// canyon wet inflow
// wf.smartWaterInflow(1020, 939); // 964
// wf.smartWaterInflow(1020, 939); // 964
// wf.smartWaterInflow(1002, 931); // 949
wf.compute();
wf.expandRivers(riverreach, slopeweight); // only flood plain has expanded river influence
for(p = 0; p < dx * dy; p++)
{
onsoil = (1.0f - evaporation) * precipitation[i];
x = p%dx;
y = p/dx;
slope = terslope->get(x, y);
sloperunoff = slopeImpact(slope, slopethresh, slopemax, runofflimit);
insoil = min(onsoil, sloperunoff);
runoff = max(0.0f, onsoil - insoil);
reservoir[p] += insoil - (transpiration[p] / 12.0f); // monthly rainfall-transpiration cycle
// reservoir[p] = max(0.0f, reservoir[p]);
// get flow sim values
// infiltrate extra water from the flood plain
flood = wf.isFlowingWater(y, x); // x, y
if(flood)
{
floodcount++;
plain = 0.0f;
}
else
{
plain = wf.riverMoisture(y, x); // x, y
}
groundwater = reservoir[p];
if(plain > 0.5f) // pixel is in the expansion area of the river so increase soil moisture
{
excesscount++;
avgexcess += plain;
// groundwater = 1000.0f; // for visual feedback on floodplain area
groundwater = min(soilsaturation, groundwater + plain * soilsaturation);
}
if(runoff > 0.0f) // rainfall exceeds soil capacity so spread exceess over subsequent months
{
for(j = 1; j < 6; j++)
excess[(i+j)%12][p] += (int) (runoff / 5.0f * 0.1); // 0.1 scale factor for GC sim convert to metres
excess[i][p] = 0;
}
// set moisture
if(flood)
wval = 2000.0f; // standing water so set to very high saturation value
else
wval = max(0.0f, groundwater);
if(t == 1) // store on second run
{
wsh[i].set(x, y, wval);
// assign wval
if(wval < minmnth[i])
minmnth[i] = wval;
if(wval > maxmnth[i])
maxmnth[i] = wval;
}
}
/*
if(t == 1)
{
wsh.setMin(i+1, minmnth[i]);
wsh.setMax(i+1, maxmnth[i]);
}*/
cerr << "Month " << i << " Finished" << endl;
cerr << "Flooded proportion = " << (float) floodcount / (float) (dx * dy) << endl;
}
cerr << "Avg Flooding Proportion = " << (float) floodcount / (12.0f * (float) (dx * dy)) << endl;
cerr << "Avg Excess Proportion = " << (float) excesscount / (12.0f * (float) (dx * dy)) << endl;
cerr << "Avg Excess = " << avgexcess / (float) excesscount << endl;
}
}
bool MoistureSim::constantValidation(MapFloat * terslope, std::vector<MapFloat> &wsh, int precipitation)
{
int dx, dy;
terslope->getDim(dx, dy);
for(int i = 0; i < 12; i++)
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
if( wsh[i].get(x, y) != precipitation)
{
cerr << "MoisuterSim::constantValidation: moisture value " << wsh[i].get(x, y) << " at " << x << ", " << y << " instead of " << precipitation << endl;
return false;
}
return true;
}
| 11,418
|
C++
|
.cpp
| 243
| 36.794239
| 243
| 0.550311
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,218
|
ConfigReader.cpp
|
jgain_EcoLearn/EcoSynth/viewer/ConfigReader.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "ConfigReader.h"
#include <fstream>
#include <sstream>
ConfigReader::ConfigReader(std::string filename)
: filename(filename), has_read(false)
{
params.scene_dirname.clear();
params.clusterdata_filenames.clear();
params.canopy_filename.clear();
params.undergrowth_filename.clear();
params.ctrlmode = ControlMode::VIEW;
params.render_canopy = false;
params.render_undergrowth = false;
}
bool ConfigReader::read()
{
using namespace rapidjson;
std::string contents;
std::ifstream ifs(filename);
std::stringstream sstr;
if (!ifs.is_open())
{
std::cout << "Could not open file at " << filename << std::endl;
return false;
}
else
{
sstr << ifs.rdbuf();
contents = sstr.str();
std::cout << "json contents: " << std::endl;
std::cout << contents << std::endl;
std::cout << "Parsing..." << std::endl;
jsondoc.Parse(contents.c_str());
std::cout << "Done parsing json file at " << filename << std::endl;
std::cout << "Document is object? " << jsondoc.IsObject() << std::endl;
params.scene_dirname = "";
Value::ConstMemberIterator iter = jsondoc.FindMember("scene_dirname");
if (iter != jsondoc.MemberEnd())
params.scene_dirname = iter->value.GetString();
std::cout << "Scene dirname: " << params.scene_dirname << std::endl;
params.clusterdata_filenames.clear();
iter = jsondoc.FindMember("clusterdata_filenames");
if (iter != jsondoc.MemberEnd())
{
for (const auto &fname : iter->value.GetArray())
{
params.clusterdata_filenames.push_back(fname.GetString());
}
}
params.canopy_filename = "";
iter = jsondoc.FindMember("canopy_filename");
if (iter != jsondoc.MemberEnd())
{
params.canopy_filename = iter->value.GetString();
}
params.undergrowth_filename = "";
iter = jsondoc.FindMember("undergrowth_filename");
if (iter != jsondoc.MemberEnd())
{
params.undergrowth_filename = iter->value.GetString();
}
params.ctrlmode = ControlMode::VIEW;
iter = jsondoc.FindMember("ctrlmode");
if (iter != jsondoc.MemberEnd())
{
if (!strcmp(iter->value.GetString(), "VIEW"))
params.ctrlmode = ControlMode::VIEW;
else if (!strcmp(iter->value.GetString(), "PAINTLEARN"))
params.ctrlmode = ControlMode::PAINTLEARN;
else if (!strcmp(iter->value.GetString(), "PAINTSPECIES"))
params.ctrlmode = ControlMode::PAINTSPECIES;
else
params.ctrlmode = ControlMode::VIEW;
}
params.render_canopy = false;
iter = jsondoc.FindMember("render_canopy");
if (iter != jsondoc.MemberEnd())
{
params.render_canopy = iter->value.GetBool();
}
params.render_undergrowth = false;
iter = jsondoc.FindMember("render_undergrowth");
if (iter != jsondoc.MemberEnd())
{
params.render_undergrowth = iter->value.GetBool();
}
}
has_read = true;
return true;
}
configparams ConfigReader::get_params()
{
if (!has_read)
std::cout << "Warning: ConfigReader::get_params() called without successful read!" << std::endl;
return params;
}
| 4,405
|
C++
|
.cpp
| 115
| 31.156522
| 104
| 0.599813
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,219
|
window.cpp
|
jgain_EcoLearn/EcoSynth/viewer/window.cpp
|
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected]) and K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "ConfigReader.h"
#include "glwidget.h"
#include "window.h"
#include "vecpnt.h"
#include "common/str.h"
#include "specselect_window.h"
#include "convertpaintingdialog.h"
#include <cuda_runtime.h>
#include <cmath>
#include <string>
#include <functional>
#include <QProgressBar>
#include <QImage>
using namespace std;
////
// SunWindow
///
QSize SunWindow::sizeHint() const
{
return QSize(800, 800);
}
void SunWindow::setOrthoView(GLWidget * ortho)
{
QWidget *mainWidget = new QWidget;
QGridLayout *mainLayout = new QGridLayout;
orthoView = ortho;
setCentralWidget(mainWidget);
mainLayout->setColumnStretch(0, 1);
// signal to slot connections
connect(orthoView->getGLSun(), SIGNAL(signalRepaintAllGL()), this, SLOT(repaintAllGL()));
mainLayout->addWidget(orthoView->getGLSun(), 0, 0);
mainWidget->setLayout(mainLayout);
setWindowTitle(tr("EcoSun"));
}
void SunWindow::repaintAllGL()
{
orthoView->getGLSun()->repaint();
}
////
// Window
///
void Window::addSpecRadSlider(QVBoxLayout *layout, const QString &label,
float startValue, int scale, float low, float high)
{
const float defaultValue = startValue;
const int defaultScaled = int(std::round(defaultValue * (float) scale));
radlabel = new QLabel(label);
species_palette_window->add_widget(radlabel);
specradslider = new QSlider(Qt::Horizontal);
specradslider->setMinimum(int(std::ceil(low * scale)));
specradslider->setMaximum(int(std::floor(high * scale)));
specradslider->setPageStep(200);
specradslider->setSingleStep(1);
specradslider->setTracking(true);
specradslider->setValue(defaultScaled);
const float invScale = 1.0f / scale;
connect(specradslider, &QSlider::valueChanged, [this, invScale] (int newValue)
{
perspectiveView->setSpeciesBrushRadius(newValue * invScale);
repaintAllGL();
});
species_palette_window->add_widget(specradslider);
}
void Window::addLearnRadSlider(QVBoxLayout *layout, const QString &label,
float startValue, int scale, float low, float high)
{
const float defaultValue = startValue;
//const int defaultScaled = int(std::round(defaultValue * (float) scale) / perspectiveView->getView()->getScaleConst());
const int defaultScaled = int(std::round(defaultValue * (float) scale));
radlabel = new QLabel(label);
layout->addWidget(radlabel);
radslider = new QSlider(Qt::Horizontal);
radslider->setMinimum(int(std::ceil(low * scale)));
radslider->setMaximum(int(std::floor(high * scale)));
radslider->setPageStep(200);
radslider->setSingleStep(1);
radslider->setTracking(true);
radslider->setValue(defaultScaled);
const float invScale = 1.0f / scale;
connect(radslider, &QSlider::valueChanged, [this, invScale] (int newValue)
{
perspectiveView->setLearnBrushRadius(newValue * invScale);
//perspectiveView->setRadius(newValue * invScale);
//radslider->setValue(perspectiveView->getRadius() / invScale); // seriously?
repaintAllGL();
});
layout->addWidget(radslider);
}
void Window::addPercSlider(QVBoxLayout *layout, const QString &label, int startval)
{
perclabel = new QLabel(label);
//layout->addWidget(perclabel);
species_palette_window->add_widget(perclabel);
percslider = new QSlider(Qt::Horizontal);
percslider->setMinimum(0);
percslider->setMaximum(100);
percslider->setPageStep(10);
percslider->setSingleStep(1);
percslider->setTracking(true);
percslider->setValue(startval);
perspectiveView->setSpecPerc(startval / 100.0f);
connect(percslider, &QSlider::valueChanged, [this] (int val) {
perspectiveView->setSpecPerc(val / 100.0f);
repaintAllGL();
});
//layout->addWidget(percslider);
species_palette_window->add_widget(percslider);
}
QSlider *Window::addSpeciesSlider(QVBoxLayout *layout, const QString &label, float startValue, int scale, float low, float high)
{
const float defaultValue = startValue;
const int defaultScaled = int(std::round(defaultValue * (float) scale));
QLabel *newlabel = new QLabel(label);
layout->addWidget(newlabel);
QHBoxLayout *horiz_layout = new QHBoxLayout();
QCheckBox *checkbox = new QCheckBox();
horiz_layout->addWidget(checkbox);
QSlider *newslider = new QSlider(Qt::Horizontal);
newslider->setMinimum(int(std::ceil(low * scale)));
newslider->setMaximum(int(std::floor(high * scale)));
newslider->setPageStep(200);
newslider->setSingleStep(1);
newslider->setTracking(true);
newslider->setValue(defaultScaled);
const float invScale = 1.0f / scale;
connect(newslider, &QSlider::sliderReleased, this, &Window::speciesSliderCallback);
horiz_layout->addWidget(newslider);
layout->addLayout(horiz_layout);
speciesSliders.push_back(newslider);
speciesCheckBoxes.push_back(checkbox);
return newslider;
}
void Window::showLoadLandscapeDialog()
{
QMessageBox mbox;
mbox.setText("Scene not loaded yet. Load one first at File -> Load Scene");
mbox.exec();
}
bool Window::checkAndLoadLandscapeDialog()
{
if (!perspectiveView->hasSceneLoaded())
{
showLoadLandscapeDialog();
return false;
}
return true;
}
void Window::speciesSliderCallback()
{
QSlider *sender_slider = (QSlider *)sender();
assert(sender());
int target;
std::vector<QSlider *> checked_sliders;
bool sender_checked = false;
for (int i = 0; i < speciesSliders.size(); i++)
{
auto sl_ptr = speciesSliders[i];
auto check_ptr = speciesCheckBoxes[i];
if (check_ptr->isChecked())
{
if (sl_ptr == sender_slider)
{
sender_checked = true;
}
checked_sliders.push_back(sl_ptr);
}
}
if (checked_sliders.size() == 0 || checked_sliders.size() == speciesSliders.size()) // change all other sliders if none, or all are checked
{
changeAllSpeciesSliders(sender_slider);
return;
}
else
{
if (checked_sliders.size() == 1 && sender_checked) // only one checked, and this is the slider we changed (change all others)
{
changeAllSpeciesSliders(sender_slider);
return;
}
else if (!sender_checked) // one or more sliders are checked, but one we changing is not checked
{
changeSpeciesSliders(checked_sliders, sender_slider);
}
else // if the sender has been checked, and one or more others have been checked
{
for (int i = 0; i < checked_sliders.size(); i++)
{
if (checked_sliders[i] == sender_slider)
{
checked_sliders.erase(std::next(checked_sliders.begin(), i));
break;
}
}
changeSpeciesSliders(checked_sliders, sender_slider);
}
}
int newsum = sender_slider->value();
for (int i = 0; i < speciesSliders.size(); i++)
{
auto sl = speciesSliders[i];
if (sl == sender_slider)
{
newsum = sl->value();
target = (i + 1) % speciesSliders.size();
break;
}
}
}
void Window::species_added(int id)
{
perspectiveView->species_added(id);
//int idx = perspectiveView->get_index_from_speciesid(id);
int idx = species_palette_window->id_to_idx(id);
species_palette_window->enable_species(idx);
}
void Window::species_removed(int id)
{
perspectiveView->species_removed(id);
int idx = species_palette_window->id_to_idx(id);
species_palette_window->disable_species(idx);
}
void Window::changeSpeciesSliders(std::vector<QSlider *> other_sliders, QSlider *sender_slider)
{
int newsum = 0;
//int newsum = sender_slider->value();
for (auto &sl : speciesSliders)
{
newsum += sl->value();
}
int diff = 100 - newsum;
float capacity = 0.0f;
for (auto other_sl : other_sliders)
{
if (diff > 0)
capacity += 100 - other_sl->value();
else if (diff < 0)
capacity += other_sl->value();
}
if (capacity < abs(diff))
{
float adjustment = sign(diff) * (abs(diff) - capacity);
sender_slider->setValue(sender_slider->value() + adjustment);
diff = sign(diff) * capacity;
}
while (newsum != 100)
{
std::vector<int> rm_idxes;
newsum = 0;
for (auto &sl : speciesSliders)
{
newsum += sl->value();
}
diff = 100 - newsum;
int ndiv = other_sliders.size();
if (ndiv == 0)
{
int new_senderval = sender_slider->value() + diff;
assert(new_senderval <= 100 && new_senderval >= 0);
sender_slider->setValue(new_senderval);
return;
}
int modulo = diff % ndiv;
int change = diff / ndiv;
for (int i = other_sliders.size() - 1; i >= 0; i--)
{
int newval;
if (i < abs(modulo))
{
newval = other_sliders[i]->value() + change + sign(modulo);
}
else
{
newval = other_sliders[i]->value() + change;
}
if (newval < 0)
{
other_sliders[i]->setValue(0);
rm_idxes.push_back(i);
}
else if (newval > 100)
{
other_sliders[i]->setValue(100);
rm_idxes.push_back(i);
}
else
other_sliders[i]->setValue(newval);
}
for (auto idx : rm_idxes)
{
other_sliders.erase(std::next(other_sliders.begin(), idx));
}
}
std::vector<float> species_percentages;
for (auto &spsl : speciesSliders)
{
species_percentages.push_back(spsl->value() / 100.0f);
}
perspectiveView->setSpeciesPercentages(species_percentages);
}
void Window::changeAllSpeciesSliders(QSlider *sender_slider)
{
std::vector<QSlider *> other_sliders;
for (auto &sl : speciesSliders)
{
if (sl != sender_slider)
other_sliders.push_back(sl);
}
changeSpeciesSliders(other_sliders, sender_slider);
}
void Window::speciesSliderCallbackChangeAll()
{
QSlider *sender_slider = (QSlider *)sender();
assert(sender());
changeAllSpeciesSliders(sender_slider);
}
QSize Window::sizeHint() const
{
return QSize(1000, 800);
}
Window::Window(int scale_size)
{
mainWidget = new QWidget;
mainLayout = new QGridLayout;
int dx, dy;
float sx, sy;
// default rendering parameters, set using text entry
// mirrors TRenderer settings
// grid params
gridIntensity = 0.8f; // 80% of base colour
gridSepX = 2500.0f; // separation of grid lines, depends on how input data is scaled
gridSepZ = 2500.0f; //
gridWidth = 1.5f; // in pixels?
// contour params
contourSep = 25.f; // separation (Y direction) depends on how input data is normalized
numContours = 1.0f / contourSep;
contourWidth = 1.0f; // in pixels ?
contourIntensity = 1.2f; // 130% of base colour
// radiance scaling parameters
radianceTransition = 0.2f;
radianceEnhance = 3.0f;
setCentralWidget(mainWidget);
mainLayout->setColumnStretch(0, 0);
mainLayout->setColumnStretch(1, 1);
mainLayout->setColumnStretch(2, 0);
// render panel
renderPanel = new QWidget;
renderLayout = new QVBoxLayout;
// Grid Line Widgets
QGroupBox *gridGroup = new QGroupBox(tr("Grid Lines"));
QCheckBox * checkGridLines = new QCheckBox(tr("Show Grid Lines"));
checkGridLines->setChecked(false);
QLabel *gridSepXLabel = new QLabel(tr("Grid Sep X:"));
gridSepXEdit = new QLineEdit;
// gridSepXEdit->setValidator(new QDoubleValidator(0.0, 500000.0, 2, gridSepXEdit));
gridSepXEdit->setInputMask("0000.0");
QLabel *gridSepZLabel = new QLabel(tr("Grid Sep Z:"));
gridSepZEdit = new QLineEdit;
// gridSepZEdit->setValidator(new QDoubleValidator(0.0, 500000.0, 2, gridSepZEdit));
gridSepZEdit->setInputMask("0000.0");
QLabel *gridWidthLabel = new QLabel(tr("Grid Line Width:"));
gridWidthEdit = new QLineEdit;
// gridWidthEdit->setValidator(new QDoubleValidator(0.0, 10.0, 2, gridWidthEdit));
gridWidthEdit->setInputMask("0.0");
QLabel *gridIntensityLabel = new QLabel(tr("Grid Intensity:"));
gridIntensityEdit = new QLineEdit;
// gridIntensityEdit->setValidator(new QDoubleValidator(0.0, 2.0, 2, gridIntensityEdit));
gridIntensityEdit->setInputMask("0.0");
// set initial grid values
gridSepXEdit->setText(QString::number(gridSepX, 'g', 2));
gridSepZEdit->setText(QString::number(gridSepZ, 'g', 2));
gridWidthEdit->setText(QString::number(gridWidth, 'g', 2));
gridIntensityEdit->setText(QString::number(gridIntensity, 'g', 2));
QGridLayout *gridLayout = new QGridLayout;
gridLayout->addWidget(checkGridLines, 0, 0);
gridLayout->addWidget(gridSepXLabel, 1, 0);
gridLayout->addWidget(gridSepXEdit, 1, 1);
gridLayout->addWidget(gridSepZLabel, 2, 0);
gridLayout->addWidget(gridSepZEdit, 2, 1);
gridLayout->addWidget(gridWidthLabel, 3, 0);
gridLayout->addWidget(gridWidthEdit, 3, 1);
gridLayout->addWidget(gridIntensityLabel, 4, 0);
gridLayout->addWidget(gridIntensityEdit, 4, 1);
gridGroup->setLayout(gridLayout);
// Contour Widgets
QGroupBox *contourGroup = new QGroupBox(tr("Contours"));
QCheckBox * checkContours = new QCheckBox(tr("Show Contours"));
checkContours->setChecked(false);
QLabel *contourSepLabel = new QLabel(tr("Contour Sep:"));
contourSepEdit = new QLineEdit;
//contourSepEdit->setValidator(new QDoubleValidator(0.0, 10000.0, 2, contourSepEdit));
contourSepEdit->setInputMask("000.0");
QLabel *contourWidthLabel = new QLabel(tr("Contour Line Width:"));
contourWidthEdit = new QLineEdit;
// contourWidthEdit->setValidator(new QDoubleValidator(0.0, 10.0, 2, contourWidthEdit));
contourWidthEdit->setInputMask("0.0");
QLabel *contourIntensityLabel = new QLabel(tr("Contour Intensity:"));
contourIntensityEdit = new QLineEdit;
contourIntensityEdit->setInputMask("0.0");
// set initial contour values
contourSepEdit->setText(QString::number(contourSep, 'g', 2));
contourWidthEdit->setText(QString::number(contourWidth, 'g', 2));
contourIntensityEdit->setText(QString::number(contourIntensity, 'g', 2));
QGridLayout *contourLayout = new QGridLayout;
contourLayout->addWidget(checkContours, 0, 0);
contourLayout->addWidget(contourSepLabel, 1, 0);
contourLayout->addWidget(contourSepEdit, 1, 1);
contourLayout->addWidget(contourWidthLabel, 2, 0);
contourLayout->addWidget(contourWidthEdit, 2, 1);
contourLayout->addWidget(contourIntensityLabel, 3, 0);
contourLayout->addWidget(contourIntensityEdit, 3, 1);
contourGroup->setLayout(contourLayout);
// Radiance
QGroupBox *radianceGroup = new QGroupBox(tr("Radiance"));
QLabel *radianceEnhanceLabel = new QLabel(tr("Radiance Enhancement:"));
radianceEnhanceEdit = new QLineEdit;
radianceEnhanceEdit->setInputMask("0.0");
// set initial radiance values
radianceEnhanceEdit->setText(QString::number(radianceEnhance, 'g', 2));
QGridLayout *radianceLayout = new QGridLayout;
radianceLayout->addWidget(radianceEnhanceLabel, 0, 0);
radianceLayout->addWidget(radianceEnhanceEdit, 0, 1);
radianceGroup->setLayout(radianceLayout);
renderLayout->addWidget(gridGroup);
renderLayout->addWidget(contourGroup);
renderLayout->addWidget(radianceGroup);
// right-hand panel for pallete
palLayout = new QVBoxLayout;
specpalLayout = new QVBoxLayout;
// OpenGL widget
// Specify an OpenGL 3.2 format.
QGLFormat glFormat;
glFormat.setVersion( 4, 1 );
glFormat.setProfile( QGLFormat::CoreProfile );
glFormat.setSampleBuffers( false );
perspectiveView = new GLWidget(glFormat, scale_size);
getView().setForcedFocus(getTerrain().getFocus());
getView().setViewScale(getTerrain().longEdgeDist());
getTerrain().getGridDim(dx, dy);
getTerrain().getTerrainDim(sx, sy);
perspectiveView->getGLSun()->setScene(&getTerrain(), NULL, NULL);
std::cerr << "done" << std::endl;
numGridX = 1.0f / gridSepX;
numGridZ = 1.0f / gridSepZ;
// Palette Widget
palLayout->addWidget(perspectiveView->getPalette());
SpeciesPalette * specpal = perspectiveView->getSpeciesPalette();
specpalLayout->addWidget(perspectiveView->getSpeciesPalette());
species_palette_window = new specpalette_window(this, specpal);
progress_bar_window = new QWidget(this, Qt::Window);
QVBoxLayout *progress_layout = new QVBoxLayout();
QVBoxLayout *cplace_layout = new QVBoxLayout();
QVBoxLayout *qundergrowth_layout = new QVBoxLayout();
QVBoxLayout *undersynth_layout = new QVBoxLayout();
QLabel *cplace_label = new QLabel("Canopy Placement");
cplace_layout->addWidget(cplace_label);
QLabel *qundergrowth_label = new QLabel("Quick Undergrowth Synthesis");
qundergrowth_layout->addWidget(qundergrowth_label);
QLabel *undersynth_label = new QLabel("Undergrowth Synthesis");
undersynth_layout->addWidget(undersynth_label);
canopy_placement_progress = new QProgressBar();
//canopy_placement_progress->setWindowFlags(Qt::Window);
canopy_placement_progress->setMinimum(0);
canopy_placement_progress->setMaximum(5);
canopy_placement_progress->setFixedWidth(200);
//canopy_placement_progress->show();
cplace_layout->addWidget(canopy_placement_progress);
cplace_layout->setSpacing(10);
quick_undergrowth_progress = new QProgressBar();
quick_undergrowth_progress->setMinimum(0);
quick_undergrowth_progress->setMaximum(100);
quick_undergrowth_progress->setFixedWidth(200);
qundergrowth_layout->addWidget(quick_undergrowth_progress);
qundergrowth_layout->setSpacing(10);
undersynth_progress = new QProgressBar();
undersynth_progress->setMinimum(0);
undersynth_progress->setMaximum(100);
undersynth_progress->setFixedWidth(200);
undersynth_layout->addWidget(undersynth_progress);
undersynth_layout->setSpacing(10);
currsynth_label = new QLabel("Canopy placement");
synth_progress = new QProgressBar();
synth_progress->setMinimum(0);
synth_progress->setMaximum(100);
synth_progress->setFixedWidth(200);
progress_layout->addWidget(currsynth_label);
progress_layout->addWidget(synth_progress);
progress_bar_window->setLayout(progress_layout);
progress_bar_window->show();
connect(perspectiveView, SIGNAL(signalCanopyPlacementStart()), this, SLOT(set_canopy_label()));
connect(perspectiveView, SIGNAL(signalSpeciesOptimStart()), this, SLOT(set_species_optim_label()));
connect(perspectiveView, SIGNAL(signalUndergrowthSampleStart()), this, SLOT(set_undersample_label()));
connect(perspectiveView, SIGNAL(signalUndergrowthRefineStart()), this, SLOT(set_underrefine_label()));
// signal to slot connections
connect(perspectiveView, SIGNAL(signalRepaintAllGL()), this, SLOT(repaintAllGL()));
connect(gridSepXEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(gridSepZEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(gridWidthEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(gridIntensityEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(contourSepEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(contourWidthEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(contourIntensityEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(radianceEnhanceEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChange()));
connect(radianceEnhanceEdit, SIGNAL(returnPressed()), this, SLOT(lineEditChange()));
connect(perspectiveView, SIGNAL(signalUpdateCanopyPlacementProgress(int)), canopy_placement_progress, SLOT(setValue(int)));
connect(perspectiveView, SIGNAL(signalUpdateQuickUndergrowthProgress(int)), quick_undergrowth_progress, SLOT(setValue(int)));
connect(perspectiveView, SIGNAL(signalUpdateUndergrowthProgress(int)), undersynth_progress, SLOT(setValue(int)));
connect(perspectiveView, SIGNAL(signalUpdateProgress(int)), synth_progress, SLOT(setValue(int)));
//connect(minTreeEdit, SIGNAL(editingFinished()), this, SLOT(treeEditChange()));
//connect(maxTreeEdit, SIGNAL(editingFinished()), this, SLOT(treeEditChange()));
// display switches
connect(checkContours, SIGNAL(stateChanged(int)), this, SLOT(showContours(int)));
connect(checkGridLines, SIGNAL(stateChanged(int)), this, SLOT(showGridLines(int)));
renderPanel->setLayout(renderLayout);
mainLayout->addWidget(renderPanel, 0, 0, Qt::AlignTop);
mainLayout->addWidget(perspectiveView, 0, 1, 10, 1);
mainLayout->addLayout(palLayout, 0, 2, Qt::AlignTop);
procdrawingButton = new QPushButton("Process drawing");
mainLayout->addWidget(procdrawingButton, 2, 2, Qt::AlignVCenter);
sampleUndergrowthButton = new QPushButton("Sample undergrowth");
mainLayout->addWidget(sampleUndergrowthButton, 3, 2, Qt::AlignTop);
createActions();
createMenus();
mainWidget->setLayout(mainLayout);
setWindowTitle(tr("EcoLearn"));
mainWidget->setMouseTracking(true);
setMouseTracking(true);
renderPanel->hide();
perspectiveView->getRenderer()->setGridParams(numGridX, numGridZ, gridWidth, gridIntensity);
perspectiveView->getRenderer()->setContourParams(numContours, contourWidth, contourIntensity);
perspectiveView->getRenderer()->setRadianceScalingParams(radianceEnhance);
specwindow = new specselect_window(std::string(PRJ_SRC_DIR) + "/ecodata/sonoma.db", this);
specwindow->show();
connect(perspectiveView, &GLWidget::signalDisableSpecSelect, specwindow, &specselect_window::disable);
connect(perspectiveView, &GLWidget::signalEnableSpecSelect, specwindow, &specselect_window::enable);
connect(procdrawingButton, SIGNAL(clicked()), perspectiveView, SLOT(send_drawing()));
connect(sampleUndergrowthButton, SIGNAL(clicked()), this, SLOT(doFastUndergrowthSampling()));
procdrawingButton->setEnabled(false);
sampleUndergrowthButton->setEnabled(false);
std::cerr << "Window construction done" << std::endl;
//connect(QApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(cleanup()));
}
void Window::scaleRenderParams(float scale)
{
gridSepX = scale / 5.0f; // separation of grid lines, depends on how input data is scaled
gridSepZ = scale / 5.0f;
numGridX = 1.0f / gridSepX;
numGridZ = 1.0f / gridSepZ;
gridSepXEdit->setText(QString::number(gridSepX, 'g', 2));
gridSepZEdit->setText(QString::number(gridSepZ, 'g', 2));
contourSep = scale / 100.f; // separation (Y direction) depends on how input data is normalized
numContours = 1.0f / contourSep;
contourSepEdit->setText(QString::number(contourSep, 'g', 2));
perspectiveView->getRenderer()->setGridParams(numGridX, numGridZ, gridWidth, gridIntensity);
perspectiveView->getRenderer()->setContourParams(numContours, contourWidth, contourIntensity);
perspectiveView->getRenderer()->setRadianceScalingParams(radianceEnhance);
}
void Window::keyPressEvent(QKeyEvent *e)
{
/*
if (e->key() == Qt::Key_Escape)
close();
else
QWidget::keyPressEvent(e);
*/
// pass to render window
perspectiveView->keyPressEvent(e);
}
void Window::mouseMoveEvent(QMouseEvent *event)
{
QWidget *child=childAt(event->pos());
QGLWidget *glwidget = qobject_cast<QGLWidget *>(child);
if(glwidget) {
QMouseEvent *glevent=new QMouseEvent(event->type(),glwidget->mapFromGlobal(event->globalPos()),event->button(),event->buttons(),event->modifiers());
QCoreApplication::postEvent(glwidget,glevent);
}
}
void Window::repaintAllGL()
{
perspectiveView->repaint();
}
void Window::set_canopy_label()
{
currsynth_label->setText("Canopy placement");
progress_bar_window->repaint();
}
void Window::set_species_optim_label()
{
currsynth_label->setText("Species optimisation");
progress_bar_window->repaint();
}
void Window::set_undersample_label()
{
currsynth_label->setText("Undergrowth sampling");
progress_bar_window->repaint();
}
void Window::set_underrefine_label()
{
currsynth_label->setText("Undergrowth refinement");
progress_bar_window->repaint();
}
void Window::cleanup()
{
}
void Window::openTerrain()
{
std::string valid_files = "16-bit PNG image (*.png);;Terragen File (*.ter);;Ascii Elevation File (*.elv)";
//valid_files += ";;16-bit PNG image (*.png)";
bool valid = false;
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Terrain File"),
"~/",
tr(valid_files.c_str()));
if (!fileName.isEmpty())
{
std::string infile = fileName.toUtf8().constData();
// use file extension to determine action
if(endsWith(infile, ".ter")) // terragen file format
{
getTerrain().loadTer(infile); valid = true;
}
else if(endsWith(infile, ".elv")) // simple ascii heightfield
{
getTerrain().loadElv(infile); valid = true;
}
else if (endsWith(infile, ".png")) // load terrain from 16-bit PNG image
{
getTerrain().loadPng(infile); valid = true;
int w, h;
getTerrain().getGridDim(w, h);
getGLWidget()->initCHM(w, h);
}
if(valid)
{
getView().setForcedFocus(getTerrain().getFocus());
getView().setViewScale(getTerrain().longEdgeDist());
getTerrain().calcMeanHeight();
getTerrain().updateBuffers(perspectiveView->getRenderer()); // NB - sets width and height for terrain, otherwise crash
repaintAllGL();
}
else
{
cerr << "Error Window::open: attempt to open unrecognized file format" << endl;
}
}
}
void Window::importDrawing()
{
QString pathname = QFileDialog::getOpenFileName(this, tr("Import drawing"), QString(), "*.png");
if (!pathname.isEmpty())
{
QImage img(pathname);
perspectiveView->import_drawing(img);
}
}
void Window::openScene()
{
// Ecosystem files are bundled in a directory, which the user specifies.
QString dirName = QFileDialog::getExistingDirectory(this, tr("Open Landscape Scene"),
QString(),
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
openScene(dirName.toStdString(), true);
// if scene load was successful, enable other function of interface
if (perspectiveView->hasSceneLoaded())
{
for (auto ptr : enableAtLandscapeLoad)
ptr->setEnabled(true);
}
}
void Window::openScene(std::string dirName, bool import_cluster_dialog)
{
if (dirName.size() > 0)
{
QDir indir(dirName.c_str());
QString lastseg = indir.dirName();
std::string dirstr = dirName;
std::string segstr = lastseg.toUtf8().constData();
// use last component of directory structure as ecosystem name
scenedirname = dirstr + "/" + segstr;
#ifndef PAINTCONTROL
sunwindow->show();
sunwindow->repaint();
sunwindow->hide();
#endif
bool firstscene = !perspectiveView->hasSceneLoaded();
perspectiveView->sunwindow = sunwindow;
perspectiveView->loadScene(scenedirname);
auto ter = perspectiveView->getTerrain();
float tx, ty;
ter->getTerrainDim(tx, ty);
float tm = std::min(tx, ty);
float startval = tm / 40.0f;
float endval = tm / 4.0f;
perspectiveView->setRadius((startval + endval) / 2.0f);
perspectiveView->setLearnBrushRadius(perspectiveView->getRadius());
perspectiveView->setSpeciesBrushRadius(perspectiveView->getRadius());
if (firstscene)
{
addLearnRadSlider(palLayout, tr("Active Brush Size"), perspectiveView->getRadius(), 1, tm / 40.0f, tm / 4.0f);
addSpecRadSlider(specpalLayout, tr("Active Brush Size"), perspectiveView->getRadius(), 1, tm / 40.0f, tm / 4.0f);
addPercSlider(specpalLayout, tr("Required species percentage"), 50);
}
if (import_cluster_dialog)
showImportClusterFiles();
procdrawingButton->setEnabled(true);
sampleUndergrowthButton->setEnabled(true);
repaintAllGL();
}
}
void Window::loadConfig(std::string configfilename)
{
ConfigReader reader(configfilename);
bool success = reader.read();
if (!success)
return;
loadConfig(reader.get_params());
}
void Window::loadConfig(configparams params)
{
if (params.scene_dirname.size() == 0)
return;
else
openScene(params.scene_dirname, false);
if (params.clusterdata_filenames.size() > 0)
importClusterFiles(params.clusterdata_filenames);
if (params.canopy_filename.size() > 0)
perspectiveView->read_pdb_canopy(params.canopy_filename);
if (params.undergrowth_filename.size() > 0)
perspectiveView->read_pdb_undergrowth(params.undergrowth_filename);
switch (params.ctrlmode)
{
case ControlMode::CMEND:
params.ctrlmode = ControlMode::VIEW;
// don't call break here, we want to this go on to the default case
default:
perspectiveView->setCtrlMode(params.ctrlmode);
}
perspectiveView->setPlantsVisibility(true);
perspectiveView->setCanopyVisibility(params.render_canopy);
perspectiveView->setUndergrowthVisibility(params.render_undergrowth);
}
void Window::saveScene()
{
if(!scenedirname.empty()) // save directly if we already have a file name
{
perspectiveView->saveScene(scenedirname);
}
else
saveAsScene();
}
void Window::saveAsScene()
{
if (!perspectiveView->hasSceneLoaded())
{
QMessageBox mbox;
mbox.setText("Cannot save scene - no scene loaded yet");
mbox.exec();
return;
}
QFileDialog::Options options;
QString selectedFilter;
// use file open dialog but convert to a directory
QString scenedir = QFileDialog::getSaveFileName(this,
tr("Save Scene"),
"~/",
tr(""),
&selectedFilter,
options);
if (!scenedir.isEmpty())
{
scenedirname = scenedir.toUtf8().constData();
QDir dir(scenedir);
if (!dir.exists()) // create directory if it doesn't already exist
{
dir.mkpath(".");
}
scenedirname += "/" + dir.dirName().toStdString();
saveScene();
}
}
void Window::saveAsPaint()
{
QFileDialog::Options options;
QString selectedFilter;
QString paintfile = QFileDialog::getSaveFileName(this,
tr("Save PaintMap As"),
"~/",
tr("Image Files (*.png)"),
&selectedFilter,
options);
if (!paintfile.isEmpty())
{
std::string paintfilename = paintfile.toStdString();
if (!endsWith(paintfilename, ".png"))
{
paintfilename += ".png";
}
perspectiveView->writePaintMap(paintfilename);
}
}
void Window::saveAsCHM()
{
QFileDialog::Options options;
QString selectedFilter;
QString chmfile = QFileDialog::getSaveFileName(this,
tr("Save CHM As"),
"~/",
tr("Image Files (*.png)"),
&selectedFilter,
options);
if (!chmfile.isEmpty())
{
std::string chmfilename = chmfile.toStdString();
if (!endsWith(chmfilename, ".png"))
{
chmfilename += ".png";
}
perspectiveView->writePaintMap(chmfilename);
}
}
void Window::showRenderOptions()
{
renderPanel->setVisible(showRenderAct->isChecked());
}
void Window::showContours(int show)
{
perspectiveView->getRenderer()->drawContours(show == Qt::Checked);
repaintAllGL();
}
void Window::showGridLines(int show)
{
perspectiveView->getRenderer()->drawGridlines(show == Qt::Checked);
repaintAllGL();
}
void Window::lineEditChange()
{
bool ok;
float val;
float tx, ty, hr;
//QLineEdit* sender = dynamic_cast<QLineEdit*> sender();
//getTerrain().getTerrainDim(tx, ty);
tx = 1.0f; ty = 1.0f; // to fix when scale added
hr = 1.0f;
if(sender() == gridSepXEdit)
{
val = gridSepXEdit->text().toFloat(&ok);
if(ok)
{
gridSepX = val;
numGridX = tx / gridSepX; // convert separation to num grid lines
}
}
if(sender() == gridSepZEdit)
{
val = gridSepZEdit->text().toFloat(&ok);
if(ok)
{
gridSepZ = val;
numGridZ = ty / gridSepZ;
}
}
if(sender() == gridWidthEdit)
{
val = gridWidthEdit->text().toFloat(&ok);
if(ok)
{
gridWidth = val;
}
}
if(sender() == gridIntensityEdit)
{
val = gridIntensityEdit->text().toFloat(&ok);
if(ok)
{
gridIntensity = val;
}
}
if(sender() == contourSepEdit)
{
val = contourSepEdit->text().toFloat(&ok);
if(ok)
{
contourSep = val;
numContours = hr / contourSep;
}
}
if(sender() == contourWidthEdit)
{
val = contourWidthEdit->text().toFloat(&ok);
if(ok)
{
contourWidth = val;
}
}
if(sender() == contourIntensityEdit)
{
val = contourIntensityEdit->text().toFloat(&ok);
if(ok)
{
contourIntensity = val;
}
}
if(sender() == radianceEnhanceEdit)
{
val = radianceEnhanceEdit->text().toFloat(&ok);
if(ok)
{
radianceEnhance = val;
}
}
cerr << "val entered " << val << endl;
// without this the renderer defaults back to factory settings at certain stages - very wierd bug
perspectiveView->getRenderer()->setGridParams(numGridX, numGridZ, gridWidth, gridIntensity);
perspectiveView->getRenderer()->setContourParams(numContours, contourWidth, contourIntensity);
perspectiveView->getRenderer()->setRadianceScalingParams(radianceEnhance);
repaintAllGL();
}
void Window::treeEditChange()
{
bool ok;
float val;
if(sender() == minTreeEdit)
{
val = minTreeEdit->text().toFloat(&ok);
if(ok)
{
minTree = val;
}
}
if(sender() == maxTreeEdit)
{
val = maxTreeEdit->text().toFloat(&ok);
if(ok)
{
maxTree = val;
}
}
cerr << "val entered " << val << endl;
// adjust canopy height texture render
perspectiveView->bandCanopyHeightTexture(minTree, maxTree);
repaintAllGL();
}
void Window::createActions()
{
openSceneAct = new QAction(tr("&OpenScene"), this);
openSceneAct->setShortcuts(QKeySequence::Open);
openSceneAct->setStatusTip(tr("Open an ecosystem scene directory"));
connect(openSceneAct, SIGNAL(triggered()), this, SLOT(openScene()));
/*
* // Removing import of only terrain, not scene. Will make interface more complicated.
* // Can be added at a later stage if necessary
openTerrainAct = new QAction(tr("OpenTerrain"), this);
openTerrainAct->setStatusTip(tr("Open an existing terrain file"));
connect(openTerrainAct, SIGNAL(triggered()), this, SLOT(openTerrain()));
*/
/*
* // Removing normal save without specifying directory, because it can accidentally overwrite
* // an existing scene easily. Safer to use "Save Scene as", which creates a new directory or overwrites
* // if explicitly specified
saveSceneAct = new QAction(tr("&Save Scene"), this);
saveSceneAct->setShortcuts(QKeySequence::Save);
saveSceneAct->setStatusTip(tr("Save the ecosystem scene"));
connect(saveSceneAct, SIGNAL(triggered()), this, SLOT(saveScene()));
*/
saveSceneAsAct = new QAction(tr("Save Scene as"), this);
saveSceneAsAct->setStatusTip(tr("Save the ecosystem scene under a new name"));
connect(saveSceneAsAct, SIGNAL(triggered()), this, SLOT(saveAsScene()));
saveSceneAsAct->setEnabled(false);
savePaintAsAct = new QAction(tr("Save PaintMap as"), this);
savePaintAsAct->setStatusTip(tr("Save the paint map under a new name"));
connect(savePaintAsAct, SIGNAL(triggered()), this, SLOT(saveAsPaint()));
savePaintAsAct->setEnabled(false);
saveCHMAsAct = new QAction(tr("Save CHM as"), this);
saveCHMAsAct->setStatusTip(tr("Save the CHM under a new name"));
connect(saveCHMAsAct, SIGNAL(triggered()), this, SLOT(saveAsCHM()));
saveCHMAsAct->setEnabled(false);
showRenderAct = new QAction(tr("Show Render Options"), this);
showRenderAct->setCheckable(true);
showRenderAct->setChecked(false);
showRenderAct->setStatusTip(tr("Hide/Show Rendering Options"));
connect(showRenderAct, SIGNAL(triggered()), this, SLOT(showRenderOptions()));
showRenderAct->setEnabled(true); // this option can be triggered without a scene being loaded
importCanopyAct = new QAction(tr("Import canopy"), this);
connect(importCanopyAct, SIGNAL(triggered()), this, SLOT(showImportCanopy()));
importCanopyAct->setEnabled(false);
importUndergrowthAct = new QAction(tr("Import undergrowth"), this);
connect(importUndergrowthAct, SIGNAL(triggered()), this, SLOT(showImportUndergrowth()));
importUndergrowthAct->setEnabled(false);
importClusterfilesAct = new QAction(tr("Import cluster files"), this);
connect(importClusterfilesAct, SIGNAL(triggered()), this, SLOT(showImportClusterFiles()));
importClusterfilesAct->setEnabled(false);
doCompleteUndergrowthSynthesisAct = new QAction(tr("Do complete undergrowth synthesis"), this);
connect(doCompleteUndergrowthSynthesisAct, SIGNAL(triggered()), this, SLOT(doUndergrowthSynthesis()));
doCompleteUndergrowthSynthesisAct->setEnabled(false);
importDrawingAct = new QAction(tr("Import drawing..."), this);
connect(importDrawingAct, SIGNAL(triggered()), this, SLOT(importDrawing()));
importDrawingAct->setEnabled(false);
convertPaintingAct = new QAction(tr("Convert painting..."), this);
connect(convertPaintingAct, SIGNAL(triggered()), this, SLOT(convertPainting()));
convertPaintingAct->setEnabled(false);
processDrawingAct = new QAction(tr("Process drawing"), this);
connect(processDrawingAct, SIGNAL(triggered()), perspectiveView, SLOT(send_drawing()));
processDrawingAct->setEnabled(false);
viewSpeciesColoursAct = new QAction(tr("Species colours"), this);
connect(viewSpeciesColoursAct, SIGNAL(triggered()), this, SLOT(showSpeciesColours()));
viewSpeciesColoursAct->setEnabled(true); // this option can be triggered without a scene being loaded
// we create a vector of actions to be enabled when a landscape is loaded
std::vector<QAction *> tempvec = {
saveSceneAsAct,
savePaintAsAct,
saveCHMAsAct,
importCanopyAct,
importUndergrowthAct,
importClusterfilesAct,
//doCompleteUndergrowthSynthesisAct, // keeping this disabled for now, since it's quite slow
importDrawingAct,
convertPaintingAct,
processDrawingAct
};
enableAtLandscapeLoad = tempvec;
}
void Window::doFastUndergrowthSampling()
{
perspectiveView->doFastUndergrowthSampling();
}
void Window::doUndergrowthSynthesis()
{
perspectiveView->doUndergrowthSynthesisCallback();
}
void Window::showImportCanopyshading()
{
QString filename = QFileDialog::getOpenFileName(this, tr("Import canopy shading from file"), scenedirname.c_str(), tr("*.txt"));
if (!filename.isEmpty())
{
perspectiveView->import_canopyshading(filename.toStdString());
}
}
void Window::showImportClusterFiles()
{
//QStringList fname_list_temp = QFileDialog::getOpenFileNames(this, tr("Import cluster files"), scenedirname.c_str(), tr("*.clm"));
QStringList fname_list_temp = QFileDialog::getOpenFileNames(this, tr("Import cluster files"), QString(), tr("*.clm"));
auto fname_list_qstr = fname_list_temp.toStdList();
std::vector<std::string> fname_list;
for (auto &qstr : fname_list_qstr)
{
fname_list.push_back(qstr.toStdString());
}
importClusterFiles(fname_list);
}
void Window::importClusterFiles(std::vector<std::string> fname_list)
{
std::vector<std::string> clusterfiles;
for (auto &fname : fname_list)
{
QFileInfo finfo(fname.c_str());
if (finfo.isDir())
{
QDir dir(fname.c_str());
QStringList dirlist_temp = dir.entryList(QStringList() << "*.clm", QDir::Files);
auto dirlist = dirlist_temp.toStdList();
for (auto &clfile : dirlist)
{
clusterfiles.push_back(clfile.toStdString());
}
}
else
{
clusterfiles.push_back(fname);
}
}
std::cout << "Imported cluster files: " << std::endl;
for (auto &fname : clusterfiles)
{
std::cout << fname << std::endl;
}
perspectiveView->set_clusterfilenames(clusterfiles);
}
void Window::showImportCanopy()
{
QString filename = QFileDialog::getOpenFileName(this, tr("Import canopy from PDB file"), scenedirname.c_str(), tr("*.pdb"));
if (!filename.isEmpty())
{
perspectiveView->read_pdb_canopy(filename.toStdString());
}
}
void Window::convertPainting()
{
ConvertPaintingDialog d;
if (d.exec() == QDialog::Accepted)
{
int from, to;
d.get_values(from, to);
BrushType tp_from, tp_to;
switch (from)
{
case 0:
tp_from = BrushType::FREE;
break;
case 1:
tp_from = BrushType::SPARSETALL;
break;
case 2:
tp_from = BrushType::DENSETALL;
break;
default:
return;
}
switch (to)
{
case 0:
tp_to = BrushType::FREE;
break;
case 1:
tp_to = BrushType::SPARSETALL;
break;
case 2:
tp_to = BrushType::DENSETALL;
break;
default:
return;
}
perspectiveView->convert_painting(tp_from, tp_to);
}
else
{
}
}
void Window::hide_all_ctrlwindows()
{
}
void Window::showImportUndergrowth()
{
QString filename = QFileDialog::getOpenFileName(this, tr("Import undergrowth from PDB file"), scenedirname.c_str(), tr("*.pdb"));
if (!filename.isEmpty())
{
perspectiveView->read_pdb_undergrowth(filename.toStdString());
}
}
void Window::showSpeciesColours()
{
const auto &cdata = perspectiveView->get_cdata();
if (specColoursWindow)
delete specColoursWindow;
specColoursWindow = new SpeciesColoursWindow(this, cdata);
specColoursWindow->display();
}
void Window::createMenus()
{
// File menu
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openSceneAct);
fileMenu->addAction(saveSceneAsAct);
fileMenu->addAction(savePaintAsAct);
fileMenu->addAction(saveCHMAsAct);
// View menu
viewMenu = menuBar()->addMenu(tr("&View"));
viewMenu->addAction(showRenderAct);
viewMenu->addAction(viewSpeciesColoursAct);
// Import menu
importMenu = menuBar()->addMenu(tr("&Import"));
importMenu->addAction(importCanopyAct);
importMenu->addAction(importUndergrowthAct);
importMenu->addAction(importDrawingAct);
importMenu->addAction(importClusterfilesAct);
// Actions menu
actionMenu = menuBar()->addMenu(tr("&Actions"));
actionMenu->addAction(convertPaintingAct);
actionMenu->addAction(doCompleteUndergrowthSynthesisAct);
}
| 48,708
|
C++
|
.cpp
| 1,227
| 32.533007
| 156
| 0.651564
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,220
|
sun.cpp
|
jgain_EcoLearn/EcoSynth/viewer/sun.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "sun.h"
#define GLM_FORCE_RADIANS
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtx/rotate_vector.hpp>
#define AXIS_TILT 0.408407f
const float SunLight::_axis_tilt = AXIS_TILT;
const float SunLight::_monthly_axis_tilt = (AXIS_TILT)/3.f;
const float SunLight::_half_day_in_minutes = 720.0f;
const float SunLight::_quarter_day_in_minutes = SunLight::_half_day_in_minutes/2.0f;
const float SunLight::_3_quarters_day_in_minutes = SunLight::_half_day_in_minutes + SunLight::_quarter_day_in_minutes;
////
// SunScene
////
SunScene::SunScene()
{
view = new View();
terrain = new Terrain();
terrain->initGrid(1024, 1024, 10000.0f, 10000.0f);
view->setForcedFocus(terrain->getFocus());
view->setViewScale(terrain->longEdgeDist());
view->setViewType(ViewState::ORTHOGONAL);
float tx, ty;
terrain->getTerrainDim(tx, ty);
view->setOrthoViewExtent(tx,ty);
}
SunScene::~SunScene()
{
delete view;
// delete terrain;
}
////
// GLSun
////
GLSun::GLSun(const QGLFormat& format, QWidget *parent)
: QGLWidget(format, parent)
{
qtWhite = QColor::fromCmykF(0.0, 0.0, 0.0, 0.0);
renderer = new PMrender::TRenderer(NULL, "../viewer/shaders/");
scene = new SunScene();
setFocusPolicy(Qt::StrongFocus);
resize(sizeHint());
renderPass = 1;
sun = new CanopyShape(0.75f, 1.0f);
}
GLSun::~GLSun()
{
if(renderer) delete renderer;
if(scene) delete scene;
if(sun) delete sun;
}
QSize GLSun::minimumSizeHint() const
{
return QSize(50, 50);
}
QSize GLSun::sizeHint() const
{
return QSize(2000, 2000);
}
void GLSun::nullifySun()
{
if (sun)
delete sun;
sun = nullptr;
}
void GLSun::colToCoord(QColor col, int &gx, int &gy)
{
int r, g, b, idx, dx, dy;
getTerrain()->getGridDim(dx, dy);
col.getRgb(&r, &g, &b);
// assumes 8-bits per colour channel
idx = (r * 65536) + (g * 256) + b;
// then derive grid coordinates
gx = (int) (idx / dy);
gy = idx - gx * dy;
}
void SunLight::projectSunSelfShadowOnly(Terrain * ter, std::vector<MapFloat> &sunmaps, GLSun * glsun, std::vector<float> &sunhours, int minutestep)
{
float tothours;
int dx, dy;
vpPoint gridpos, xsectpos;
Vector sunvec;
float hourstep = (float) minutestep / 60.0f;
Timer tmm;
float tstep, tx, ty;
ter->getGridDim(dx, dy);
ter->getTerrainDim(tx, ty);
tstep = 1.0f * tx / (float) dx;
sunhours.clear();
for(int m = 1; m <= 12; m++) // months of the year
{
tothours = 0.0f;
setMonth(m);
sunmaps[m-1].fill(0.0f);
tmm.start();
for(int t = 0; t < 1440; t+= minutestep)
{
setTime(t);
// cerr << "sunpos " << sunpos.x << ", " << sunpos.y << ", " << sunpos.z << endl;
if(sunpos.y > 0.0f) // above the horizon
{
sunvec = Vector(sunpos.x, sunpos.y, sunpos.z);
sunvec.normalize();
glsun->getView()->sundir(sunvec);
glsun->calcVisibilitySelfShadowOnly(&sunmaps[m-1], hourstep);
tothours += hourstep; // sun above horizon
}
}
tmm.stop();
cerr << "Month " << m << " Sunlight Pass Complete in " << tmm.peek() << " seconds" << endl;
cerr << "with " << tothours << " of sunlight" << endl;
sunhours.push_back(tothours);
}
}
void GLSun::calcVisibilitySelfShadowOnly(MapFloat * sunvis, float timestep)
{
QImage baseImg, canImg;
int dx, dy, gx, gy;
MapFloat mask; // check off wether a gridpoint is visible
// north = (0,0,-1), west = (-1,0,0), east = (1,0,0), south = (0, 0, 1)
sunvis->getDim(dx, dy);
mask.setDim(dx, dy);
mask.fill(0.0f);
for(int qx = 0; qx < orthodiv; qx++)
for(int qy = 0; qy < orthodiv; qy++)
{
getView()->setOrthoQuadrant(qx, qy);
// first pass: terrain indices
renderPass = 1;
paintGL();
glFlush();
baseImg = grabFrameBuffer();
for(int x = 0; x < baseImg.width(); x++)
for(int y = 0; y < baseImg.height(); y++)
{
QColor col = baseImg.pixelColor(x, y);
colToCoord(col, gx, gy);
if(gx < dx && gy < dy) // not the background
if(mask.get(gx, gy) < 0.5f) // not already incremented
{
qreal r, g, b;
//QColor viscol = canImg.pixelColor(x, y);
//viscol.getRgbF(&r, &g, &b); // all channels store the same info so just use red
sunvis->set(gx, gy, sunvis->get(gx, gy) + (float) timestep);
mask.set(gx, gy, 1.0f);
}
}
}
}
void GLSun::calcVisibility(MapFloat * sunvis, float timestep)
{
QImage baseImg, canImg;
int dx, dy, gx, gy;
MapFloat mask; // check off wether a gridpoint is visible
// north = (0,0,-1), west = (-1,0,0), east = (1,0,0), south = (0, 0, 1)
sunvis->getDim(dx, dy);
mask.setDim(dx, dy);
mask.fill(0.0f);
for(int qx = 0; qx < orthodiv; qx++)
for(int qy = 0; qy < orthodiv; qy++)
{
getView()->setOrthoQuadrant(qx, qy);
// first pass: terrain indices
renderPass = 1;
paintGL();
glFlush();
baseImg = grabFrameBuffer();
// second pass: alpha-blended canopies
renderPass = 2;
paintGL();
glFlush();
canImg = grabFrameBuffer();
for(int x = 0; x < baseImg.width(); x++)
for(int y = 0; y < baseImg.height(); y++)
{
QColor col = baseImg.pixelColor(x, y);
colToCoord(col, gx, gy);
if(gx < dx && gy < dy) // not the background
if(mask.get(gx, gy) < 0.5f) // not already incremented
{
qreal r, g, b;
QColor viscol = canImg.pixelColor(x, y);
viscol.getRgbF(&r, &g, &b); // all channels store the same info so just use red
sunvis->set(gx, gy, sunvis->get(gx, gy) + (float) r * timestep);
mask.set(gx, gy, 1.0f);
}
}
}
}
View * GLSun::getView()
{
return scene->view;
}
Terrain * GLSun::getTerrain()
{
return scene->terrain;
}
MapFloat * GLSun::getCanopyHeight()
{
return scene->chght;
}
MapFloat * GLSun::getCanopyDensity()
{
return scene->cdense;
}
PMrender::TRenderer * GLSun::getRenderer()
{
return renderer;
}
void GLSun::setScene(Terrain * ter, MapFloat * ch, MapFloat * cd)
{
float tx, ty;
int dx, dy;
scene->terrain = ter;
scene->chght = ch;
scene->cdense = cd;
getView()->setForcedFocus(getTerrain()->getFocus());
getView()->setViewScale(getTerrain()->longEdgeDist());
getTerrain()->calcMeanHeight();
getTerrain()->setBufferToDirty();
getTerrain()->setAccelInValid();
getTerrain()->getTerrainDim(tx, ty);
getView()->setOrthoViewExtent(tx,ty);
getTerrain()->getGridDim(dx, dy);
update();
}
void GLSun::bind()
{
if(sun)
delete sun;
sun = new CanopyShape(0.75, getTerrain()->getCellExtent());
// must come after CanopyHeight and CanopyDensity are defined
sun->bindCanopy(getTerrain(), getView(), getCanopyHeight(), getCanopyDensity());
}
void GLSun::init_gl()
{
initializeGL();
}
void GLSun::initializeGL()
{
// get context opengl-version
qDebug() << "Widget OpenGl: " << format().majorVersion() << "." << format().minorVersion();
qDebug() << "Context valid: " << context()->isValid();
qDebug() << "Really used OpenGl: " << context()->format().majorVersion() << "." <<
context()->format().minorVersion();
qDebug() << "OpenGl information: VENDOR: " << (const char*)glGetString(GL_VENDOR);
qDebug() << " RENDERDER: " << (const char*)glGetString(GL_RENDERER);
qDebug() << " VERSION: " << (const char*)glGetString(GL_VERSION);
qDebug() << " GLSL VERSION: " << (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
QGLFormat glFormat = QGLWidget::format();
if ( !glFormat.sampleBuffers() )
qWarning() << "Could not enable sample buffers";
qglClearColor(qtWhite.light());
int mu;
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &mu);
cerr << "max texture units = " << mu << endl;
// *** PM REnder code - start ***
PMrender::TRenderer::terrainShadingModel sMod = PMrender::TRenderer::SUN;
// set terrain shading model
renderer->setTerrShadeModel(sMod);
// set up light
Vector dl = Vector(0.6f, 1.0f, 0.6f);
dl.normalize();
// initialise renderer/compile shaders
renderer->initShaders();
// set other render parameters
// can set terrain colour for radiance scaling etc - check trenderer.h
// terrain contours
renderer->drawContours(false);
renderer->drawGridlines(false);
// turn on terrain type overlay (off by default); NB you can stil call methods to update terrain type,
renderer->useTerrainTypeTexture(true);
renderer->useConstraintTypeTexture(false);
// use manipulator textures (decal'd)
renderer->textureManipulators(false);
// *** PM REnder code - end ***
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glDisable(GL_MULTISAMPLE);
glDisable(GL_DEPTH_CLAMP);
glEnable(GL_TEXTURE_2D);
}
void GLSun::paintGL()
{
uts::vector<ShapeDrawData> drawParams; // to be passed to terrain renderer
drawParams.clear();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if(sun)
sun->drawCanopy(drawParams);
// pass in draw params and render
renderer->setConstraintDrawParams(drawParams);
getTerrain()->updateBuffers(renderer);
renderer->drawSun(getView(), renderPass);
}
void GLSun::resizeGL(int width, int height)
{
// TO DO: fix resizing
int side = qMin(width, height);
glViewport((width - side) / 2, (height - side) / 2, width, height);
}
////
// CanopyShape
///
void CanopyShape::genCanopyBox(float trunkratio, float cellscale)
{
glm::mat4 idt, tfm;
glm::vec3 trs, rotx;
float canopyheight;
rotx = glm::vec3(1.0f, 0.0f, 0.0f);
canopyheight = 1.0f - trunkratio;
GLfloat basecol[4] = {0.0f, 0.0f, 0.0f, 0.0f};
canopybox->setColour(basecol);
// canopy - tapered box
idt = glm::mat4(1.0f);
trs = glm::vec3(0.0f, trunkratio, 0.0f);
tfm = glm::translate(idt, trs);
tfm = glm::rotate(tfm, glm::radians(-90.0f), rotx);
canopybox->genPyramid(cellscale * 1.0f, cellscale * 1.0f, canopyheight, tfm);
}
void CanopyShape::bindCanopy(Terrain * ter, View * view, MapFloat * hght, MapFloat *dnsty)
{
int dx, dy, bndplants = 0;
std::vector<glm::mat4> xform; // transformation to be applied to each instance
std::vector<glm::vec4> colvar; // colour variation to be applied to each instance
xform.clear();
colvar.clear();
ter->getGridDim(dx, dy);
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
float h = hght->get(x, y);
h = h * 0.3048f; // convert feet to metres
float d = dnsty->get(x, y);
if(h > 1.0f)
{
// setup transformation for individual plant, including scaling and translation
glm::mat4 idt, tfm;
glm::vec3 trs, sc;
vpPoint loc = ter->toWorld(y, x, ter->getHeight(x, y)); // center of cell
idt = glm::mat4(1.0f);
trs = glm::vec3(loc.x, loc.y, loc.z);
tfm = glm::translate(idt, trs); // translate to correct position
sc = glm::vec3(1.0f, h, 1.0f); // scale to correct tree height
tfm = glm::scale(tfm, sc);
xform.push_back(tfm);
colvar.push_back(glm::vec4(0.0f, 0.0f, 0.0f, d*0.8f)); // d is the blocking density of the canopy, adjusted to allow some light through beyond what can be seen from the ground
// this density scaling factor may need to be species dependent
bndplants++;
}
}
if(!canopybox->bindInstances(view, &xform, &colvar))
cerr << "CanopyShape::bindCanopies: binding failed" << endl;
}
void CanopyShape::drawCanopy(std::vector<ShapeDrawData> &drawParams)
{
ShapeDrawData sdd;
sdd = canopybox->getDrawParameters();
sdd.current = false;
drawParams.push_back(sdd);
}
////
// HemSample
///
// Efficient sampling of the hemisphere based on the Hammersley Point Set
// http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html
float HemSample::radicalInverse_VdC(uint bits)
{
bits = (bits << 16u) | (bits >> 16u);
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
return float(bits) * 2.3283064365386963e-10; // / 0x100000000
}
void HemSample::hammersley2d(uint i, uint N, float &u, float &v)
{
u = (float) i / (float) N;
v = radicalInverse_VdC(i);
}
void HemSample::convertUniform(float u, float v, Vector &dirn)
{
float phi = v * 2.0 * PI;
float cosTheta = 1.0 - u;
float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
dirn = Vector(cos(phi) * sinTheta, cosTheta, sin(phi) * sinTheta);
}
void HemSample::getSample(int s, int totSamples, Vector &dirn)
{
float u, v;
hammersley2d((uint) s, (uint) totSamples, u, v);
convertUniform(u, v, dirn);
}
////
// SunLight
////
SunLight::SunLight()
{
tx = 0; ty = 0;
month = 0; time = 0;
latitude = 0;
setNorthOrientation(Vector(0.0, 0.0, -1.0f));
refreshSun();
genSphereSun();
}
SunLight::~SunLight()
{
}
// Various conversion helper routines
float SunLight::minutesToAngle(float minutes)
{
return ((_half_day_in_minutes - minutes) / _half_day_in_minutes) * M_PI;
}
float SunLight::getAxisTiltAngle(int mnth)
{
return -_axis_tilt + ((float) std::abs(6 - mnth) * _monthly_axis_tilt);
}
float SunLight::latitudeToAngle(float lat)
{
return -lat / (180.0f / M_PI);
}
void SunLight::splitTilt(int time_of_day, float & pitch, float & roll)
{
float f_time_of_day ((float) time_of_day);
// Pitch
{
if(time_of_day <= _half_day_in_minutes) // Before midday
pitch = 1.0f - ((f_time_of_day/_half_day_in_minutes) * 2);
else // After midday
pitch = -1 + (((f_time_of_day-_half_day_in_minutes)/_half_day_in_minutes) * 2);
}
// Roll
{
if(time_of_day < (_quarter_day_in_minutes))
roll = (f_time_of_day/_quarter_day_in_minutes) * 1.0f;
else if(f_time_of_day >= _quarter_day_in_minutes && f_time_of_day <= _3_quarters_day_in_minutes)
roll = 1 - (((f_time_of_day-_quarter_day_in_minutes)/_half_day_in_minutes)*2.0f);
else // 6 pm -> midnight
roll = -1 + ((f_time_of_day - _3_quarters_day_in_minutes) / _quarter_day_in_minutes);
}
}
void SunLight::refreshSun()
{
// First calculate some orientations we need values we need
glm::vec3 east_orientation = glm::rotateY(north, (float)M_PI_2);
glm::vec3 true_north_orientation = glm::rotate(north, glm::radians((float) (-latitude)), east_orientation); // is sign correct here?
int sun_trajectory_radius(500000);
float max_axis_tilt(SunLight::getAxisTiltAngle(month));
float day_angle(SunLight::minutesToAngle((float) time));
glm::vec3 cp_tn_and_east (glm::normalize(glm::cross(true_north_orientation, east_orientation)));
// First calculate the sun position at midday during the equinox
glm::vec3 sun_position ( ((float)sun_trajectory_radius) * cp_tn_and_east );
// Now take into consideration axis tilt based on the month
sun_position = glm::rotate( sun_position, -max_axis_tilt, east_orientation ); // PITCH
// Now rotate around true north for the day
sun_position = glm::rotate(sun_position, day_angle, true_north_orientation);
// Now align to the center of the terrain (i.e the center of the terrain is at the latitude specified)
// sun_position += glm::vec3(center.x, center.y, center.z);
sunpos = vpPoint(sun_position[0], sun_position[1], sun_position[2]);
}
void SunLight::genSphereSun()
{
glm::mat4 idt;
// simple unit diameter sphere
idt = glm::mat4(1.0f);
GLfloat suncol[] = {1.0f, 1.0f, 0.0f, 1.0f};
sunRender.genSphere(20.0f, 20, 20, idt);
sunRender.setColour(suncol);
}
void SunLight::bindDiffuseSun(View * view, Terrain * ter)
{
std::vector<glm::mat4> xform; // transformation to be applied to each instance
std::vector<glm::vec4> colvar; // colour variation to be applied to each instance
HemSample hem;
xform.clear();
colvar.clear();
for(int t = 0; t < 100; t++)
{
// setup transformation for individual sun
glm::mat4 idt, tfm;
glm::vec3 trs, sc;
Vector sundir;
vpPoint termid, loc;
hem.getSample(t, 100, sundir);
sundir.mult(400.0f);
ter->getMidPoint(termid);
loc = vpPoint(termid.x+sundir.i, termid.y+sundir.j, termid.z+sundir.k);
//cerr << "sundir = " << sundir.i << " " << sundir.j << " " << sundir.k << endl;
idt = glm::mat4(1.0f);
trs = glm::vec3(loc.x+center.x, loc.y+center.y, loc.z+center.z);
tfm = glm::translate(idt, trs);
xform.push_back(tfm);
glm::vec4 col = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f); // no colour variation
colvar.push_back(col); // colour variation
}
if(!sunRender.bindInstances(view, &xform, &colvar))
cerr << "SUN BINDING FAILED" << endl;
}
void SunLight::bindSun(View * view)
{
std::vector<glm::mat4> xform; // transformation to be applied to each instance
std::vector<glm::vec4> colvar; // colour variation to be applied to each instance
xform.clear();
colvar.clear();
float tothours = 0.0f;
for(int t = 0; t < 1440; t+= 1)
{
// setup transformation for individual sun
glm::mat4 idt, tfm;
glm::vec3 trs, sc;
setTime(t);
Vector sundir = Vector(sunpos.x, sunpos.y, sunpos.z);
sundir.normalize();
sundir.mult(400.0f);
vpPoint loc = vpPoint(sundir.i, sundir.j, sundir.k);
//cerr << "sundir = " << sundir.i << " " << sundir.j << " " << sundir.k << endl;
if(loc.y > 0.0f)
tothours += (1.0 / 60.0f);
idt = glm::mat4(1.0f);
trs = glm::vec3(loc.x+center.x, loc.y+center.y, loc.z+center.z);
tfm = glm::translate(idt, trs);
xform.push_back(tfm);
glm::vec4 col = glm::vec4(abs((float) t - 720.0f) / -1400.0f, abs((float) t - 720.0f) / -1400.0f, abs((float) t - 720.0f) / -1400.0f, 0.0f); // midday is peak colour, all others are darker
colvar.push_back(col); // colour variation
}
if(!sunRender.bindInstances(view, &xform, &colvar))
cerr << "SUN BINDING FAILED" << endl;
cerr << "TOTAL HOURS OF SUNLIGHT = " << tothours << endl;
}
void SunLight::drawSun(std::vector<ShapeDrawData> &drawParams)
{
ShapeDrawData sdd;
sdd = sunRender.getDrawParameters();
sdd.current = false;
drawParams.push_back(sdd);
}
void SunLight::diffuseSun(Terrain * ter, MapFloat * diffusemap, GLSun * glsun, int numSamples)
{
//int numSamples = 100;
int dx, dy;
Timer tmm;
HemSample hem;
ter->getGridDim(dx, dy);
diffusemap->setDim(dx, dy);
diffusemap->fill(0.0f);
tmm.start();
for(int s = 0; s < numSamples; s++) // hemisphere samples
{
Vector sunvec;
hem.getSample(s, numSamples, sunvec);
if(sunvec.j > 0.0f) // above the horizon
{
glsun->getView()->sundir(sunvec);
glsun->calcVisibility(diffusemap, 1.0f);
}
}
// normalization
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
diffusemap->set(x, y, diffusemap->get(x, y) / (float) numSamples);
}
tmm.stop();
cerr << "Diffuse sampling complete in " << tmm.peek() << " seconds" << endl;
}
void SunLight::projectSun(Terrain * ter, std::vector<MapFloat> &sunmaps, GLSun * glsun, std::vector<float> &sunhours, int minutestep)
{
float tothours;
int dx, dy;
vpPoint gridpos, xsectpos;
Vector sunvec;
float hourstep = (float) minutestep / 60.0f;
Timer tmm;
float tstep, tx, ty;
ter->getGridDim(dx, dy);
ter->getTerrainDim(tx, ty);
tstep = 1.0f * tx / (float) dx;
sunhours.clear();
for(int m = 1; m <= 12; m++) // months of the year
{
tothours = 0.0f;
setMonth(m);
sunmaps[m-1].fill(0.0f);
tmm.start();
for(int t = 0; t < 1440; t+= minutestep)
{
setTime(t);
// cerr << "sunpos " << sunpos.x << ", " << sunpos.y << ", " << sunpos.z << endl;
if(sunpos.y > 0.0f) // above the horizon
{
sunvec = Vector(sunpos.x, sunpos.y, sunpos.z);
sunvec.normalize();
glsun->getView()->sundir(sunvec);
glsun->calcVisibility(&sunmaps[m-1], hourstep);
tothours += hourstep; // sun above horizon
}
std::cout << "Done with minute " << t << std::endl;
}
tmm.stop();
cerr << "Month " << m << " Sunlight Pass Complete in " << tmm.peek() << " seconds" << endl;
cerr << "with " << tothours << " of sunlight" << endl;
sunhours.push_back(tothours);
}
}
void SunLight::mergeSun(std::vector<MapFloat> &sunmaps, MapFloat * diffusemap, std::vector<float> cloudiness, std::vector<float> sunhours)
{
int dx, dy;
float direct, diffuse;
diffusemap->getDim(dx, dy);
for(int m = 0; m < 12; m++) // months of the year
{
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
// direct sunlight portion
direct = sunmaps[m].get(x, y) * (1.0f - cloudiness[m]);
// diffuse sunlight portion
diffuse = diffusemap->get(x, y) * cloudiness[m] * sunhours[m];
sunmaps[m].set(x, y, direct+diffuse);
}
// cerr << "Cloudiness for month " << m << " is " << cloudiness[m] << " and sun hours are " << sunhours[m] << endl;
}
}
| 23,831
|
C++
|
.cpp
| 644
| 30.40528
| 196
| 0.591238
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,221
|
grass.cpp
|
jgain_EcoLearn/EcoSynth/viewer/grass.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "grass.h"
#include "dice_roller.h"
#include "terrain.h"
#include "eco.h"
#include "data_importer/data_importer.h"
#include <fstream>
#include <iostream>
bool MapFloat::read(std::string filename)
{
float val;
ifstream infile;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> gx >> gy;
initMap();
for (int x = 0; x < gx; x++)
{
for (int y = 0; y < gy; y++)
{
infile >> val;
set(x, y, val);
}
}
infile.close();
return true;
}
else
{
cerr << "Error TypeMap::loadTxt: unable to open file" << filename << endl;
return false;
}
}
void GrassSim::convertCoord(Terrain * ter, int x, int y, int & sx, int & sy, int &ex, int &ey)
{
int dx, dy, gx, gy;
ter->getGridDim(dx, dy);
grasshght.getDim(gx, gy);
int cellx = gx / dx;
int celly = gy / dy;
sx = cellx * x; sy = celly * y;
ex = sx+cellx; ey = sy+celly;
}
GrassSim::GrassSim(Terrain *ter)
{
matchDim(ter, 1000.0f, 2);
}
void GrassSim::matchDim(Terrain *ter, float scale, int mult)
{
int gx, gy;
float tx, ty;
// get grid dimensions from terrain for simulation parameters
ter->getGridDim(gx, gy);
ter->getTerrainDim(tx, ty);
// set number of grass cells
grasshght.setDim(gx * mult, gy * mult);
scx = tx / (float) (gx * mult); scy = ty / (float) (gy * mult);
hscx = 0.5f * scx; hscy = 0.5f * scy;
cerr << "grass cell dimensions = " << scx << " X " << scy << endl;
//cerr << "scale = " << scale << " mult = " << mult << endl;
litterfall_density.setDim(gx * mult, gy * mult);
litterfall_density.fill(0.0f);
}
bool GrassSim::write_litterfall(std::string filename)
{
data_importer::write_txt<MapFloat>(filename, &litterfall_density, scx);
}
void GrassSim::set_viability_params(const std::map<string, data_importer::grass_viability> &viability_params)
{
viability = viability_params;
}
float GrassSim::suitability(float inval, float absmin, float innermin, float innermax, float absmax)
{
if(inval >= absmin && inval <= absmax)
{
if(inval < innermin) // lead in interpolation
return ((float) (inval - absmin)) / ((float) (innermin - absmin));
if(inval > innermax) // lead out interpolation
return 1.0f - ((float) (inval - innermax)) / ((float) (absmax - innermax));
return 1.0f; // prime range
}
else // out of survival range
{
return 0.0f;
}
}
void GrassSim::toGrassGrid(float x, float y, int &i, int &j)
{
int gx, gy;
grasshght.getDim(gx, gy);
i = (int) (x / scx);
j = (int) (y / scy);
if(i < 0)
i = 0;
if(j < 0)
j = 0;
if(i >= gx)
i = gx-1;
if(j >= gy)
j = gy-1;
}
void GrassSim::toTerrain(int i, int j, float &x, float &y)
{
x = (float) i * scx + hscx;
y = (float) j * scy + hscy;
}
void GrassSim::burnInPlant(float x, float y, float r, float alpha)
{
float nx = x-r, ny = y-r, fx = x+r, fy = y+r;
vpPoint tree, grass;
tree = vpPoint(x, y, 0.0f);
// map corners to grass grid positions
int ni, fi, nj, fj;
toGrassGrid(nx, ny, ni, nj);
toGrassGrid(fx, fy, fi, fj);
// iterate top left corner to bottom right corner
for(int i = ni; i <= fi; i++)
for(int j = nj; j <= fj; j++)
{
float wght, d, tx, ty;
toTerrain(i, j, tx, ty);
grass = vpPoint(tx, ty, 0.0f);
d = tree.dist(grass); // how far is the grass sample from the tree trunk
if(d <= r) // linearly interpolate grass height from trunk to canopy radius
{
wght = d / r;
wght *= 1.0f - alpha; // account for plant alpha
//wght = 0.0f;
grasshght.set(i, j, grasshght.get(i, j) * wght);
//grasshght.set(i, j, MAXGRASSHGHT * 0.9f);
float openground = 1.0f - litterfall_density.get(i, j);
litterfall_density.set(i, j, 1.0f - wght * openground);
}
}
}
void GrassSim::smooth_general(int filterwidth, int passes, bool noblank, MapFloat &srcdest)
{
int gx, gy;
float filterarea;
MapFloat newgrasshght;
srcdest.getDim(gx, gy);
newgrasshght.setDim(gx, gy);
filterarea = (float) ((filterwidth*2+1)*(filterwidth*2+1));
for(int i = 0; i < passes; i++)
{
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
if(noblank || srcdest.get(x,y) > 0.0f)
{
float avg = 0.0f;
for(int cx = x-filterwidth; cx <= x+filterwidth; cx++)
for(int cy = y-filterwidth; cy <= y+filterwidth; cy++)
{
if(cx < 0 || cx >= gx || cy < 0 || cy >= gy)
avg += srcdest.get(x, y);
else
avg += srcdest.get(cx, cy);
}
newgrasshght.set(x,y, avg / filterarea);
}
else
{
newgrasshght.set(x, y, 0.0f);
}
}
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
srcdest.set(x, y, newgrasshght.get(x, y));
if(i%25 == 0)
cerr << i << " smoothing iterations" << endl;
}
}
void GrassSim::smooth(int filterwidth, int passes, bool noblank)
{
int gx, gy;
float filterarea;
MapFloat newgrasshght;
grasshght.getDim(gx, gy);
newgrasshght.setDim(gx, gy);
filterarea = (float) ((filterwidth*2+1)*(filterwidth*2+1));
for(int i = 0; i < passes; i++)
{
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
if(noblank || grasshght.get(x,y) > 0.0f)
{
float avg = 0.0f;
for(int cx = x-filterwidth; cx <= x+filterwidth; cx++)
for(int cy = y-filterwidth; cy <= y+filterwidth; cy++)
{
if(cx < 0 || cx >= gx || cy < 0 || cy >= gy)
avg += grasshght.get(x, y);
else
avg += grasshght.get(cx, cy);
}
newgrasshght.set(x,y, avg / filterarea);
}
else
{
newgrasshght.set(x, y, 0.0f);
}
}
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
grasshght.set(x, y, newgrasshght.get(x, y));
if(i%25 == 0)
cerr << i << " smoothing iterations" << endl;
}
}
void GrassSim::grow(Terrain * ter, std::vector<basic_tree> &trees, const data_importer::common_data &cdata, float scale)
{
if (has_backup)
{
grasshght = backup_grass;
}
else
{
int dx, dy, gx, gy;
bool bare = false;
DiceRoller roller(0,RAND_MAX);
ter->getGridDim(dx, dy);
grasshght.getDim(gx, gy);
cerr << "grass-sim: initial grass height" << endl;
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
int sx, sy, ex, ey;
// rocky areas have zero grass heights
/*
bare = (* painted->getMap())[y][x] == (int) BrushType::ROCK; // TO DO - water type may be added later
*/
// alpine settings
/*
float suitval = suitability(illumination.get(x,y), 1.0f, 6.5f, 10.0f, 15.0f); // illumination
suitval = min(suitval, suitability(moisture.get(x,y), 20.0f, 100.0f, 10000.0f, 10000.0f)); // moisture
suitval = min(suitval, suitability(temperature.get(x,y), 0.0f, 10.0f, 22.0f, 40.0f)); // temperature
*/
// savannah settings
/*
float suitval = suitability(illumination.get(x,y), 1.0f, 6.5f, 10.0f, 15.0f); // illumination
suitval = min(suitval, suitability(moisture.get(x,y), 20.0f, 200.0f, 10000.0f, 10000.0f)); // moisture
suitval = min(suitval, suitability(temperature.get(x,y), 5.0f, 15.0f, 22.0f, 40.0f)); // temperature
*/
// canyon settings
/*
float suitval = suitability(illumination.get(x,y), 1.0f, 6.5f, 10.0f, 15.0f); // illumination
suitval = min(suitval, suitability(moisture.get(x,y), 50.0f, 200.0f, 10000.0f, 10000.0f)); // moisture
suitval = min(suitval, suitability(temperature.get(x,y), 5.0f, 15.0f, 22.0f, 40.0f)); // temperature
*/
/*
// med settings
float suitval = suitability(illumination->get(x,y), 2.0f, 6.5f, 12.0f, 16.0f); // illumination original
//float suitval = suitability(illumination->get(x,y), 2000.0f, 2300.0f, 2500.0f, 2600.0f); // illumination
suitval = min(suitval, suitability(moisture->get(x,y), 20.0f, 100.0f, 10000.0f, 10000.0f)); // moisture original
//suitval = min(suitval, suitability(moisture->get(x,y), 5.0f, 100.0f, 1000.0f, 1500.0f)); // moisture
//suitval = min(suitval, suitability(temperature->get(x,y), 5.0f, 15.0f, 22.0f, 40.0f)); // temperature original
suitval = min(suitval, suitability(temperature->get(x,y), 5.0f, 15.0f, 22.0f, 40.0f)); // temperature
*/
auto sunv = viability["sunlight"];
auto wetv = viability["moisture"];
auto tempv = viability["temperature"];
float suitval = suitability(illumination->get(x,y), sunv.absmin, sunv.innermin, sunv.innermax, sunv.absmax); // illumination original
//float suitval = suitability(illumination->get(x,y), 2000.0f, 2300.0f, 2500.0f, 2600.0f); // illumination
suitval = min(suitval, suitability(moisture->get(x,y), wetv.absmin, wetv.innermin, wetv.innermax, wetv.absmax)); // moisture original
//suitval = min(suitval, suitability(moisture->get(x,y), 5.0f, 100.0f, 1000.0f, 1500.0f)); // moisture
//suitval = min(suitval, suitability(temperature->get(x,y), 5.0f, 15.0f, 22.0f, 40.0f)); // temperature original
suitval = min(suitval, suitability(temperature->get(x,y), tempv.absmin, tempv.innermin, tempv.innermax, tempv.absmax)); // temperature
// if(x%100==0 && y%100==0)
// cerr << suitval << " ";
// a terrain cell covers multiple grass cells, so calculate coverage
convertCoord(ter, x, y, sx, sy, ex, ey);
// cerr << "sx, sy = " << sx << ", " << sy << " -> ex, ey = " << ex << ", " << ey << endl;
for(int cx = sx; cx < ex; cx++)
for(int cy = sy; cy < ey; cy++)
{
float hght = 0.0f;
if(!bare) // lookup terrain conditions, value is minimum of all terrain condition ranges
{
hght = suitval * MAXGRASSHGHT;
}
grasshght.set(cx, cy, hght); // set grass height
}
}
cerr << "grass-sim: smoothing" << endl;
// smooth(2, 300, true); // alpine smooth
smooth(2, 50, true); // med smooth
// smooth(2, 50, true); // savannah smooth
// smooth(2, 50, true); // canyon smooth
cerr << "grass-sim: random variation" << endl;
float rndvar;
// rndvar = 0.1; // alpine variation
// rndvar = 0.3; // savannah variation
rndvar = 0.1; // canyon variation
// one pass of random variation
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
if(grasshght.get(x, y) > 0.0f)
{
float h = grasshght.get(x, y);
h *= (1.0f + rndvar * (float) (roller.generate()%2000-1000) / 1000.0f);
if(h > MAXGRASSHGHT)
h = MAXGRASSHGHT;
grasshght.set(x, y, h);
}
// a few passes to smooth out the noise and make it less local
// smooth(2, 10, true);
cerr << "grass-sim: water burn" << endl;
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
int sx, sy, ex, ey;
float river = 300.0f; // savannah
if(moisture->get(x,y) > river) // river so remove grass
{
// a terrain cell covers multiple grass cells, so calculate coverage
convertCoord(ter, x, y, sx, sy, ex, ey);
for(int cx = sx; cx < ex; cx++)
for(int cy = sy; cy < ey; cy++)
{
grasshght.set(cx, cy, 0.0f); // set grass height to zero
}
}
}
// some more smoothing to blend water edges
smooth(2, 50, false);
backup_grass = grasshght;
has_backup = true;
}
cerr << "grass-sim: plant burn" << endl;
// iterate over plants in the ecosystem, burning in their circles on the grass, depending on the plant alpha and distance from the plant center
// TO DO - add plant alpha, test burn in fully
//ecs->getPlants()->burnGrass(this, ter, scale);
burnGrass(ter, trees, cdata, scale);
smooth(2, 2, false);
smooth_general(5, 2, true, litterfall_density);
}
void GrassSim::burnGrass(Terrain *ter, const std::vector<basic_tree> &trees, const data_importer::common_data &cdata, float scale)
{
float invscf, tx, ty;
ter->getTerrainDim(tx, ty);
invscf = scale / tx;
int nburned = 0;
litterfall_density.fill(0.0f);
for (auto &tree : trees)
{
float alpha = cdata.canopy_and_under_species.at(tree.species).alpha;
burnInPlant(tree.x * invscf, tree.y * invscf, tree.radius * invscf, alpha);
nburned++;
}
std::cout << "Number of plants burned: " << nburned << std::endl;
}
void GrassSim::setConditions(MapFloat * wetfile, MapFloat * sunfile, MapFloat *landsun_file, MapFloat * tempfile)
{
moisture = wetfile;
illumination = sunfile;
temperature = tempfile;
landsun = landsun_file;
}
| 15,652
|
C++
|
.cpp
| 379
| 30.973615
| 150
| 0.519761
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,222
|
trenderer.cpp
|
jgain_EcoLearn/EcoSynth/viewer/trenderer.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "trenderer.h"
#include <cassert>
#include <fstream>
#include <sstream>
#include <algorithm>
namespace PMrender {
// create and update heightmap texture
// this sets the heightmap texture; if dimensions have changed, mesh+normals are rebuilt
// if force == draw, then we a rebuild will take place - use to manage changed data from synthesis
void TRenderer::updateHeightMap(int wd, int ht, float scx, float scy, const float* data, bool force)
{
if (data == NULL)
{
std::cerr << "TRenderer::updateHeightMapTexture - NULL pointer for heightmap?";
return;
}
assert(wd != 0 && ht != 0);
if (width == wd && height == ht && !force) // nothing to do - make sure binding is intact
{
//std::cerr << "rebind heightmap texture\n";
if (heightmapTexture == 0)
{
std::cerr << "Error! Heighmap texture undefined!\n";
}
glActiveTexture(htmapTexUnit); CE();
glBindTexture(GL_TEXTURE_2D, heightmapTexture); CE();
return;
}
// if grid dimensions have changed:
if(heightmapTexture != 0 && (width != wd || height != ht))
{
// std::cerr << "- Delete texture\n";
glDeleteTextures(1, &heightmapTexture); CE();
heightmapTexture = 0;
}
if (heightmapTexture == 0) // create texture if it does not exist
{
// std::cerr << "- Create texture\n";
glGenTextures(1, &heightmapTexture); CE();
glActiveTexture(htmapTexUnit); CE();
glBindTexture(GL_TEXTURE_2D, heightmapTexture ); CE();
glTexImage2D(GL_TEXTURE_2D, 0,GL_R32F, wd, ht, 0,GL_RED, GL_FLOAT, (GLfloat*)data); CE();
// no filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
}
else // otherwise sub in new texture data
{
// std::cerr << " - sub texture\n";
glActiveTexture(htmapTexUnit); CE();
glBindTexture(GL_TEXTURE_2D, heightmapTexture ); CE();
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, wd, ht, GL_RED, GL_FLOAT, (GLfloat*)data); CE();
}
// test all values for lowest terrain height:
terrainBase = 1000000.0; // +infinity
for (int i = 0; i < wd*ht; i++)
terrainBase = std::min(terrainBase, data[i]);
// std::cout << "Terrain BAse: " << terrainBase << std::endl;
width = wd;
height = ht;
scalex = scx;
scaley = scy;
// rebuild VAO and everything else if this was first image or new
// dimensions or data in heightmap has changed
deleteTerrainOpenGLbuffers();
prepareTerrainGeometry(); // set up VBO, IBO, FBO etc
prepareWalls(); // build capping walls for terrain
generateNormalTexture(); // generate new normals and set up texture unit
}
// utility function to write out colour (RGB) buffer as PPM image
void TRenderer::savePPMImage(const std::string filename, unsigned char *buffer, int w, int h)
{
ofstream ofs;
ofs.open(filename.c_str(), std::ios::binary);
if (!ofs)
{
std::cerr<< "TRenderer::savePPMImage - unable to open file for writing: " << filename << std::endl;
return;
}
// write header:
ofs << "P6\n" << w << " " << h << "\n255\n";
// write data:
ofs.write((char*)buffer, w*h*3);
if (!ofs)
std::cerr<< "TRenderer::savePPMImage - error occured when writing file " << filename << std::endl;
ofs.close();
}
// load test data set; returns width and height of terrain and
// the texture id of the single channel texture that stores it
// the texture unit to which this should be bound is also passed in
GLuint TRenderer::loadTest(const std::string &filename, GLenum texUnit, int &wd, int &ht)
{
int i;
GLfloat *buffer = NULL;
float biggest = 0.0f;
std::ifstream infile;
infile.open(filename.c_str(), std::ios_base::in);
if(infile.is_open() && !infile.eof())
{
infile >> wd;
infile >> ht;
buffer = new GLfloat [wd*ht];
GLfloat *ptr = buffer;
for (i = 0; i < wd*ht; i++)
{
infile >> *ptr;
biggest = std::max(*ptr, biggest);
ptr++;
}
infile.close();
}
else
{
std::cerr << "TRenderer::loadTest: file not found" << filename << std::endl;
infile.close();
return 0;
}
std::cerr << "Maxx Z value = " << biggest << std::endl;
// create texture for heightmap
GLuint htId;
glGenTextures(1, &htId); CE();
glActiveTexture(texUnit); CE();
glBindTexture(GL_TEXTURE_2D, htId ); CE();
glTexImage2D(GL_TEXTURE_2D, 0,GL_R32F, wd, ht, 0,GL_RED, GL_FLOAT, buffer); CE();
// no filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
if (buffer) delete [] buffer;
return htId;
}
GLuint TRenderer::addShader(const std::string& shadName, const char *frag, const char *vert) // add a new shader to the collection
{
bool ok = false;
PMrender::shaderProgram *ns = new PMrender::shaderProgram(frag, vert);
ns->compileAndLink();
if (!ok)
{
std::cerr << "addShader failed for shader = " << shadName << std::endl;
return 0;
}
else
{
shaders[shadName] = ns;
return ns->getProgramID();
}
}
void TRenderer::makeXwall(int atY, GLuint &vao, GLuint&vbo, GLuint& ibo, GLfloat *verts, GLuint *indices, bool reverse)
{
int vidx = 0, x, y;
y = atY; // create wall at y = atY;
for (x = 0; x < width; x++, vidx++)
{
// positions: z wil be offset from height texture in the shader
verts[5*vidx] = (float) x / (float) (width - 1) * scalex;
//verts[5*vidx+1] = 1.0f - ((float) y / (float) (height - 1)) - 0.5f;
//verts[5*vidx+2] = 0.0f;
verts[5*vidx+1] = 0.0f;
verts[5*vidx+2] = /* 1.0f - */ ((float) y / (float) (height - 1)) * scaley;
// texture coordinates
verts[5*vidx+3] = (float) (x+0.5f) / (float) (width);
verts[5*vidx+4] = (float) (y+0.5f) / (float) (height);
// positions: z will remain 0 - bottom edge of bottom wall, fixed to base plane
// use negative text coords to signal this in shader
verts[5*vidx + 5*width] = verts[5*vidx];
verts[5*vidx+1 + 5*width] = verts[5*vidx+1];
verts[5*vidx+2 + 5*width] = verts[5*vidx+2];
// texture coordinates
verts[5*vidx+3 + 5*width] = -1.0f;
verts[5*vidx+4 + 5*width] = -1.0f;
indices[2*vidx] = (reverse ? width-1-x: x);
indices[2*vidx+1] = (reverse ? 2*width-1-x: x+width);
}
glGenVertexArrays(1, &vao); CE();
glBindVertexArray(vao); CE();
// set up vertex buffer an copy in data
glGenBuffers(1, &vbo); CE();
glBindBuffer(GL_ARRAY_BUFFER, vbo); CE();
glBufferData(GL_ARRAY_BUFFER, 5*sizeof(GLfloat)*width*2, verts, GL_STATIC_DRAW); CE();
// enable position attribute
glEnableVertexAttribArray(0); CE();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(0)); CE();
// enable texture coord attribute
const int sz = 3*sizeof(GLfloat);
glEnableVertexAttribArray(1); CE();
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(sz) ); CE();
// set up index buffer
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); CE();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*2*width, indices, GL_STATIC_DRAW); CE();
// unbind everything and clean up
glBindBuffer(GL_ARRAY_BUFFER, 0); CE();
glBindVertexArray(0); CE();
}
void TRenderer::makeYwall(int atX, GLuint &vao, GLuint&vbo, GLuint& ibo, GLfloat *verts, GLuint *indices, bool reverse)
{
int vidx = 0, x, y;
x = atX; // create vertical wall at x = atX;
for (y = 0; y < height; y++, vidx++)
{
// positions: z wil be offset from height texture in the shader
verts[5*vidx] = (float) x / (float) (width - 1) * scalex;
//verts[5*vidx+1] = 1.0f - ((float) y / (float) (height - 1)) - 0.5f;
//verts[5*vidx+2] = 0.0f;
verts[5*vidx+1] = 0.0f;
verts[5*vidx+2] = /*1.0f -*/ ((float) y / (float) (height - 1)) * scaley;
// texture coordinates
verts[5*vidx+3] = (float) (x+0.5f) / (float) (width);
verts[5*vidx+4] = (float) (y+0.5f) / (float) (height);
// positions: z will remain 0 - bottome edge of bottom wall, fixed to base plane
// use negative text coords to signal this in shader
verts[5*vidx + 5*height] = verts[5*vidx];
verts[5*vidx+1 + 5*height] = verts[5*vidx+1];
verts[5*vidx+2 + 5*height] = verts[5*vidx+2];
// texture coordinates
verts[5*vidx+3 + 5*width] = -1.0f;
verts[5*vidx+4 + 5*width] = -1.0f;
indices[2*vidx] = (reverse ? height-1-y: y);
indices[2*vidx+1] = (reverse ? 2*height-1-y: y+height);
}
glGenVertexArrays(1, &vao); CE();
glBindVertexArray(vao); CE();
// set up vertex buffer an copy in data
glGenBuffers(1, &vbo); CE();
glBindBuffer(GL_ARRAY_BUFFER, vbo); CE();
glBufferData(GL_ARRAY_BUFFER, 5*sizeof(GLfloat)*height*2, verts, GL_STATIC_DRAW); CE();
// enable position attribute
glEnableVertexAttribArray(0); CE();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(0)); CE();
// enable texture coord attribute
const int sz = 3*sizeof(GLfloat);
glEnableVertexAttribArray(1); CE();
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(sz) ); CE();
// set up index buffer
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); CE();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*2*height, indices, GL_STATIC_DRAW); CE();
// unbind everything and clean up
glBindBuffer(GL_ARRAY_BUFFER, 0); CE();
glBindVertexArray(0); CE();
}
void TRenderer::makeBase(GLuint &vao, GLuint&vbo, GLuint& ibo, GLfloat *verts, GLuint *indices)
{
float coords[4][2] = { {0.0f, 0.0f}, {scalex, 0.0f}, {0.0f, scaley}, {scalex, scaley}};
for (int vidx = 0; vidx < 4; vidx++)
{
verts[5*vidx] = coords[vidx][0];
verts[5*vidx+1] = 0.0f; // y=0, ground plane
verts[5*vidx+2] = coords[vidx][1];
verts[5*vidx+3] = -1.0f; // tex coords: these verts are NOT displaced in shader...
verts[5*vidx+4] = -1.0f;
}
// ensure correct strip winding: normal must point down into ground plane, y=0: N=(0,-1,0)
indices[0] = 1; indices[1] = 3; indices[2] = 0; indices[3] = 2;
// standard VAO/VBO setup
glGenVertexArrays(1, &vao); CE();
glBindVertexArray(vao); CE();
// set up vertex buffer an copy in data
glGenBuffers(1, &vbo); CE();
glBindBuffer(GL_ARRAY_BUFFER, vbo); CE();
glBufferData(GL_ARRAY_BUFFER, 5*sizeof(GLfloat)*4, verts, GL_STATIC_DRAW); CE();
// enable position attribute
glEnableVertexAttribArray(0); CE();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(0)); CE();
// enable texture coord attribute
const int sz = 3*sizeof(GLfloat);
glEnableVertexAttribArray(1); CE();
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(sz) ); CE();
// set up index buffer
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); CE();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*4, indices, GL_STATIC_DRAW); CE();
// unbind everything and clean up
glBindBuffer(GL_ARRAY_BUFFER, 0); CE();
glBindVertexArray(0); CE();
}
bool TRenderer::prepareWalls(void)
{
GLfloat *vertexStorage;
GLuint *indexStorage;
// max space required across both vert/horiz walls - we'll re-use this array
int vertexStorageSize = std::max(width,height)*2*5; // 5 float attribs per vertex
int indexStorageSize = std::max(width,height)*2;
vertexStorage = new GLfloat [vertexStorageSize]; // 4 walls: top, bottom, left, right
if (vertexStorage == NULL)
{
std::cerr << "prepareWalls: vertex allocation failed for " << vertexStorageSize <<
" vertices\n";
return false;
}
indexStorage = new GLuint [indexStorageSize];
if (indexStorage == NULL)
{
std::cerr << "prepareWalls: index buffer allocation failed\n";
return false;
}
makeXwall(height-1, vaoWalls[0], vboWalls[0], iboWalls[0], vertexStorage, indexStorage, false);
normalWalls[0] = glm::vec3(0.0f, 0.0f, 1.0f); wallDrawEls[0] = 2*width;
makeXwall(0, vaoWalls[1], vboWalls[1], iboWalls[1], vertexStorage, indexStorage, true);
normalWalls[1] = glm::vec3(0.0f, 0.0f, -1.0f); wallDrawEls[1] = 2*width;
makeYwall(0, vaoWalls[2], vboWalls[2], iboWalls[2], vertexStorage, indexStorage, false);
normalWalls[2] = glm::vec3(-1.0f, 0.0f, 0.0f); wallDrawEls[2] = 2*height;
makeYwall(width-1, vaoWalls[3], vboWalls[3], iboWalls[3], vertexStorage, indexStorage, true);
normalWalls[3] = glm::vec3(1.0f, 0.0f, 0.0f); wallDrawEls[3] = 2*height;
makeBase(vaoWalls[4], vboWalls[4], iboWalls[4], vertexStorage, indexStorage);
normalWalls[4] = glm::vec3(0.0f, -1.0f, 0.0f); wallDrawEls[4] = 4;
delete [] vertexStorage;
delete [] indexStorage;
return true;
}
// creates a VBO, IBO and an encapsulating VAO to represent terrain geometry, set up
// texture for normal map computation
bool TRenderer::prepareTerrainGeometry(void)
{
GLfloat *vertexStorage;
GLuint *indexStorage;
vertexStorage = new GLfloat [width*height*5];
if (vertexStorage == NULL)
{
std::cerr << "prepareTerrainGeometry: vertex allocation failed for " << (width*height) <<
" vertices\n";
return false;
}
int vidx = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++, vidx++)
{
// positions: z wil be offset from height texture in the shader
vertexStorage[5*vidx] = (float) x / (float) (width - 1) * scalex;
//vertexStorage[5*vidx+1] = 1.0f - ((float) y / (float) (height - 1)) - 0.5f;
//vertexStorage[5*vidx+2] = 0.0f;
vertexStorage[5*vidx+1] = 0.0f;
vertexStorage[5*vidx+2] = /* 1.0f - */ (float) y / (float) (height - 1) * scaley;
// texture coordinates
vertexStorage[5*vidx+3] = (float) x / (float) (width-1);
vertexStorage[5*vidx+4] = (float) y / (float) (height-1);
}
}
int numStripsRequired = height - 1;
int numDegensRequired = 2 * (numStripsRequired - 1);
int verticesPerStrip = 2 * width;
indexSize = verticesPerStrip * numStripsRequired + numDegensRequired;
indexStorage = new GLuint [indexSize];
if (indexStorage == NULL)
{
std::cerr << "prepareTerrainGeometry: index buffer allocation failed\n";
return false;
}
int offset = 0;
for (int y = 0; y < height - 1; y++)
{
if (y > 0) // Degenerate begin: repeat first vertex
indexStorage[offset++] = (GLuint) (y * width);
for (int x = 0; x < width; x++)
{
// One part of the strip
indexStorage[offset++] = (GLuint) ((y * width) + x);
indexStorage[offset++] = (GLuint) (((y + 1) * width) + x);
}
if (y < height - 2) // Degenerate end: repeat last vertex
indexStorage[offset++] = (GLuint) (((y + 1) * width) + (width - 1));
}
// generate index array: set up for triangle strips with degeneraret tris linking strips
glGenVertexArrays(1, &vaoTerrain); CE();
glBindVertexArray(vaoTerrain); CE();
// set up vertex buffer an copy in data
glGenBuffers(1, &vboTerrain); CE();
glBindBuffer(GL_ARRAY_BUFFER, vboTerrain); CE();
glBufferData(GL_ARRAY_BUFFER, 5*sizeof(GLfloat)*width*height, vertexStorage, GL_STATIC_DRAW); CE();
// enable position attribute
glEnableVertexAttribArray(0); CE();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(0)); CE();
// enable texture coord attribute
const int sz = 3*sizeof(GLfloat);
glEnableVertexAttribArray(1); CE();
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (void*)(sz) ); CE();
// set up index buffer
glGenBuffers(1, &iboTerrain);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboTerrain); CE();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*indexSize, indexStorage, GL_STATIC_DRAW); CE();
// unbind everything and clean up
delete [] vertexStorage;
delete [] indexStorage;
glBindBuffer(GL_ARRAY_BUFFER, 0); CE();
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); CE();
glBindVertexArray(0); CE();
//set up screen quad for screen rendering
glGenVertexArrays(1, &vaoScreenQuad); CE();
glBindVertexArray(vaoScreenQuad); CE();
glGenBuffers(1, &vboScreenQuad); CE();
glBindBuffer(GL_ARRAY_BUFFER, vboScreenQuad); CE();
glBufferData(GL_ARRAY_BUFFER, sizeof(screenQuad), screenQuad, GL_STATIC_DRAW); CE();
// enable position attribute
//glEnableVertexAttribArray(0); CE();
//glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)(0)); CE();
// enable position attribute
glEnableVertexAttribArray(0); CE();
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(GLfloat), (void*)(0)); CE();
// enable texture coord attribute
const int sz2 = 2*sizeof(GLfloat);
glEnableVertexAttribArray(1); CE();
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(GLfloat), (void*)(sz2) ); CE();
glBindBuffer(GL_ARRAY_BUFFER, 0); CE();
glBindVertexArray(0); CE();
// create an FBO for normal map rendering
glGenFramebuffers(1, &fboNormalMap); CE();
glBindFramebuffer(GL_FRAMEBUFFER, fboNormalMap); CE();
// create texture target for normal map computation
glActiveTexture(normalMapTexUnit); // normal map is bound to this TIU
glGenTextures(1, &normalTexture); CE();
glBindTexture(GL_TEXTURE_2D, normalTexture); CE();
// set up texture state.
// Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA16F, width, height, 0,GL_RGBA, GL_FLOAT, 0); CE();
// no filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
// configure FBO
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, normalTexture, 0); CE();
// Set the list of draw buffers.
GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, DrawBuffers); CE(); // "1" is the size of DrawBuffers
// Always check that our framebuffer is ok
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cerr << "Normal map FBO initialisation failed\n";
return false;
}
// unbind FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
return true;
}
void TRenderer::generateNormalTexture(void)
{
glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); CE();
glDisable(GL_DEPTH_TEST); CE();
glDisable(GL_CULL_FACE); CE();
glClear(GL_COLOR_BUFFER_BIT); CE();
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport); // save current viewport
// reset current viewport
glViewport(0,0,width, height); CE();
std::string shaderName = "normalShader";
GLuint programID = (*shaders[shaderName]).getProgramID();
glUseProgram(programID); CE();
GLfloat imgDims[2] = {float(width), float(height)};
GLuint locDims = glGetUniformLocation(programID, "imgSize"); CE();
glUniform2fv(locDims, 1, imgDims); CE();
GLuint textur = glGetUniformLocation(programID, "htMap"); CE();
glUniform1i(textur, (GLint)(htmapTexUnit - GL_TEXTURE0)); CE(); // assumes heightmap texture is bound to this TIU
// pass in scale
GLfloat terDims[2] = {float(scalex), float(scaley)};
GLuint scDims = glGetUniformLocation(programID, "scale"); CE();
glUniform2fv(scDims, 1, terDims); CE();
// Render to our framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, fboNormalMap); CE();
// set shader program to normal map gen
glBindVertexArray(vaoScreenQuad); CE();
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); CE();
// unbind everthing
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
glBindVertexArray(0); CE();
glUseProgram(0); CE();
// reset viewport
glViewport(viewport[0],viewport[1],viewport[2],viewport[3]);
}
// ******* Radiance Scaling setup **************
// rebuild buffer for viewport of vWd X vHt size
bool TRenderer::initRadianceScalingBuffers(int vWd, int vHt)
{
// get viewport size - every time this changes we'll have to rebuild the textures
_w = vWd;
_h = vHt;
// Create & Configure FBO: final composite
glGenFramebuffers(1, &fboRSOutput); CE();
// std::cout << "Framebuffer2 ID = " << fboRSOutput << std::endl;
glBindFramebuffer(GL_FRAMEBUFFER, fboRSOutput); CE();
// set up final compositon buffer for radiance scaling
glActiveTexture(rsDestTexUnit); CE();
glGenTextures(1, &destTexture); CE();
glBindTexture(GL_TEXTURE_2D, destTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA8, _w, _h, 0,GL_RGBA, GL_UNSIGNED_BYTE, 0); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); CE();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, destTexture, 0); CE();
GLenum DestBuffer[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, DestBuffer); CE();
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cerr << "RS FBO (output) - initialisation: failed\n";
return false;
}
// unbind FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
// ****************************************************************************************************
// create an FBO for rendering output
glGenFramebuffers(1, &fboRadScaling); CE();
glBindFramebuffer(GL_FRAMEBUFFER, fboRadScaling); CE();
// std::cout << "Framebuffer1 ID = " << fboRadScaling << std::endl;
// ****** depth texture:: ********************
glGenTextures(1, &depthTexture); CE();
glBindTexture(GL_TEXTURE_2D, depthTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24, _w, _h, 0,GL_DEPTH_COMPONENT, GL_FLOAT, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// ****** gradient texture:: *******************
glActiveTexture(rsGradTexUnit);
glGenTextures(1, &gradTexture); CE();
glBindTexture(GL_TEXTURE_2D, gradTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA16F, _w, _h, 0,GL_RGBA, GL_FLOAT, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// ****** screenspace normal texture:: ********************
glActiveTexture(rsNormTexUnit);
glGenTextures(1, &normTexture); CE();
glBindTexture(GL_TEXTURE_2D, normTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA16F, _w, _h, 0,GL_RGBA, GL_FLOAT, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// ****** colour texture:: ********************
glActiveTexture(rsColTexUnit);
glGenTextures(1, &colTexture); CE();
glBindTexture(GL_TEXTURE_2D, colTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA8, _w, _h, 0,GL_RGBA, GL_UNSIGNED_BYTE, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// configure FBO: intermediate
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0); CE();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, gradTexture, 0); CE();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, normTexture, 0); CE();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, colTexture, 0); CE();
// Set the list of draw buffers.
GLenum DrawBuffers[3] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
glDrawBuffers(3, DrawBuffers); CE(); // "3" is the size of DrawBuffers
// Always check that our framebuffer is ok
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cerr << "RS FBO initialisation: failed\n";
return false;
}
// unbind FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
// ******************************************************************************************************
// create FBO for manipulator transparency overlay; requires depth buffer and colour attachment
glGenFramebuffers(1, &fboManipLayer); CE();
glBindFramebuffer(GL_FRAMEBUFFER, fboManipLayer); CE();
// std::cout << "FramebufferN ID = " << fboManipLayer << std::endl;
// ****** manipulator depth texture:: ********************
glActiveTexture(manipTranspTexUnit);
glGenTextures(1, &manipDepthTexture); CE();
glBindTexture(GL_TEXTURE_2D, manipDepthTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24, _w, _h, 0,GL_DEPTH_COMPONENT, GL_FLOAT, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// ****** manipulator colour texture:: ********************
glGenTextures(1, &manipTranspTexture); CE();
glBindTexture(GL_TEXTURE_2D, manipTranspTexture); CE();
// - Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA8, _w, _h, 0,GL_RGBA, GL_UNSIGNED_BYTE, 0); CE();
// - linear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CE();
// - deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, manipDepthTexture, 0); CE();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, manipTranspTexture, 0); CE();
// Set the list of draw buffers.
GLenum mDrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, mDrawBuffers); CE(); // "1" is the size of DrawBuffers
// Always check that our framebuffer is ok
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cerr << "manip FBO initialisation: failed\n";
return false;
}
// unbind FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
return true;
}
// update radiance scaling FBO textures/attachments if viewport has changed size
// vwd and vht are current viewport width and height, resp.
// render conext
void TRenderer::updateRadianceScalingBuffers(int vwd, int vht)
{
if (shadModel != RADIANCE_SCALING)
return;
if (_w == 0 || _h == 0 || vwd != _w || vht != _h)
{
// std::cerr << "Delete old rad scaling buffer\n";
// clean old Radiance scaling FBO data if required
deleteFBOrscalingBuffers();
//std::cerr << "Calling Rad scaling...\n";
initRadianceScalingBuffers(vwd, vht);
//std::cerr << "Done\n";
}
}
// create data for instance
void TRenderer::initInstanceData(void)
{
vboTerrain = iboTerrain = vaoTerrain = 0;
for (int i = 0; i < 5; i++)
{
vboWalls[i] = 0;
iboWalls[i] = 0;
vaoWalls[i] = 0;
}
normalTexture = fboNormalMap = vaoScreenQuad = 0;
depthTexture = gradTexture = normTexture = colTexture = destTexture = 0;
manipDepthTexture = manipTranspTexture = 0;
typeMapTexture = 0;
constraintTexture = 0;
heightmapTexture = 0;
decalTexture = 0;
vboScreenQuad = 0;
fboRadScaling = 0;
fboRSOutput = 0;
fboManipLayer = 0;
typeBuffer = NULL;
// texture units reserved for rendering:
htmapTexUnit = GL_TEXTURE0;
normalMapTexUnit = GL_TEXTURE1;
rsGradTexUnit = GL_TEXTURE2;
rsNormTexUnit = GL_TEXTURE3;
rsColTexUnit = GL_TEXTURE4;
rsDestTexUnit = GL_TEXTURE5;
typemapTexUnit = GL_TEXTURE6;
decalTexUnit = GL_TEXTURE7;
constraintTexUnit = GL_TEXTURE8;
manipTranspTexUnit = GL_TEXTURE9;
width = height = 0;
scalex = scaley = 0.0f;
indexSize = 0;
_w = _h = 0;
terrainBase = 1000000.0; // +infinity (well kind of ...)
// default colours
terMatDiffuse = glm::vec4(0.7f, 0.6f, 0.5f, 1.0f); // colour of terrain
terMatSpec = glm::vec4(0.2f, 0.2f, 0.2f, 1.0f);
terMatAmbient = glm::vec4(0.3f, 0.3f, 0.3f, 1.0f);
lightDiffuseColour = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f); // colour of light
lightSpecColour = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f);
lightAmbientColour = glm::vec4(0.4f, 0.4f, 0.4f, 1.0f);
shinySpec = 5.0f; // specular power
// default colour: radiance scaling
terSurfColour = glm::vec4(0.7f, 0.6f, 0.5f, 1.0f);
// default camera
viewMx = glm::lookAt(glm::vec3(2.0f, 3.0f, 3.0f), glm::vec3(0.0f,0.0f,0.0f), glm::vec3(0.0, 1.0f, 0.0f));
MVmx = viewMx; // glm::mat4(1.0f); Model mx = Id
normalMatrix = glm::transpose(glm::inverse(glm::mat3(MVmx))); // glm::mat3(1.0f);
//normalMatrix = glm::mat3(1.0f);
if(shadModel == SUN)
projMx = glm::ortho(-500.0f, 500.0f, -500.0f, 500.0f, -10000.0f, 10000.0f);
else
projMx = glm::frustum(-8.0f*ACTUAL_ASPECT, 8.0f*ACTUAL_ASPECT, -8.0f, 8.0f, 50.0f, 100000.0f);
MVP = projMx * MVmx;
}
TRenderer::TRenderer(QGLWidget *drawTo, const std::string& dir)
{
canvas = drawTo;
shaderDir = dir;
shadersReady = false;
contours = true; // contours on by default
gridlines = true; //draw gridlines by default
contoursWall = true; //draw contours on side walls
gridlinesWall = true; // draw gridlines on side walls
terrainTypeTexture = false; // turn off terrain type texture by default
constraintTypeTexture = false; // turn off constraint type texture by default
shadModel = RADIANCE_SCALING; // RADIANCE_SCALING; // BASIC
manipulatorTextures = false; // do not texture manipulators by default
drawOutOfBounds = false; // shade out of bound heights
drawHiddenManipulators = false; // do/do not draw hidden manipulators
terrainBasePad = 50.0; // 50 metre padding from lowest point to avoid flat terrains having tiny side walls
// lights
pointLight = glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
directionalLight[0] = glm::vec4(0.0f, 1.0f, 0.0f, 0.0f);
directionalLight[1] = glm::vec4(0.5f, 0.5f, 0.0f, 0.0f);
// values for drawing contours/gridlines
gridColFactor = 0.7f; // 70% of base colour
gridXsep = 2.0f; // separation of griod lines, depends on how input data is scaled
gridZsep = 2.0f;
gridThickness = 1.0f;
contourSep = 70.0f; // separation (Y direction) depends on how input data is normalized
contourThickness = 0.5f;
contourColFactor = 1.3f; // 130% of base colour
outOfBoundsColour = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f); // red shading for our of bounds colour
outOfBoundsWeight = 0.2f;
outOfBoundsMean = 0.0f;
outOfBoundsOffset = 0.0f;
manipAlpha = 0.4f; // manipulator blend factor for hidden manipulators
// radiance scaling parameters
RSinvertCurvature = false;
RStransition = 0.2f;
RSenhance = 0.5f;
initInstanceData();
}
void TRenderer::deleteTerrainOpenGLbuffers(void)
{
// delete old VAO etc
if (vboTerrain != 0) glDeleteBuffers(1, &vboTerrain); CE();
if (iboTerrain != 0) glDeleteBuffers(1, &iboTerrain); CE();
if (vaoTerrain != 0) glDeleteVertexArrays(1, &vaoTerrain); CE();
if (normalTexture != 0) glDeleteTextures(1, &normalTexture); CE();
if (fboNormalMap != 0) glDeleteFramebuffers(1, &fboNormalMap); CE();
if (vaoScreenQuad != 0) glDeleteVertexArrays(1, &vaoScreenQuad); CE();
if (vboScreenQuad != 0) glDeleteBuffers(1, &vboScreenQuad); CE();
for (int i = 0; i < 5; i++)
{
if (vboWalls[i] != 0) glDeleteBuffers(1, &vboWalls[i]); CE();
if (iboWalls[i] != 0) glDeleteBuffers(1, &iboWalls[i]); CE();
if (vaoWalls[i] != 0) glDeleteVertexArrays(1, &vaoWalls[i]); CE();
}
}
void TRenderer::deleteFBOrscalingBuffers(void)
{
// Radiance scaling FBO data
if (depthTexture !=0) glDeleteTextures(1, &depthTexture); CE();
if (gradTexture !=0) glDeleteTextures(1, &gradTexture); CE();
if (normTexture !=0) glDeleteTextures(1, &normTexture); CE();
if (colTexture !=0) glDeleteTextures(1, &colTexture); CE();
if (destTexture != 0) glDeleteTextures(1, &destTexture); CE();
if (manipTranspTexture != 0) glDeleteTextures(1, &manipTranspTexture); CE();
if (manipDepthTexture != 0) glDeleteTextures(1, &manipDepthTexture); CE();
if (fboRadScaling != 0) glDeleteFramebuffers(1, &fboRadScaling); CE();
if (fboRSOutput != 0) glDeleteFramebuffers(1, &fboRSOutput); CE();
if (fboManipLayer != 0) glDeleteFramebuffers(1, &fboManipLayer); CE();
}
void TRenderer::destroyInstanceData(void)
{
if (typeBuffer != NULL) delete [] typeBuffer;
if (typeMapTexture != 0) glDeleteTextures(1, &typeMapTexture); CE();
if (heightmapTexture != 0) glDeleteTextures(1, &heightmapTexture); CE();
if (constraintTexture != 0) glDeleteTextures(1, &constraintTexture); CE();
deleteTerrainOpenGLbuffers();
deleteFBOrscalingBuffers();
}
TRenderer::~TRenderer()
{
if (decalTexture != 0) glDeleteTextures(1, &decalTexture);
// delete shaders
std::map<std::string, shaderProgram*>::iterator it = shaders.begin();
while (it != shaders.end() )
{ delete (*it).second; it++; }
destroyInstanceData();
}
// load in a new heightfield with accompanying terrain type map.
void TRenderer::loadTerrainData(const float* data, int wd, int ht, float scx, float scy,
TypeMap* paintMap, TypeMap* constraintMap)
{
if (!shadersReady)
std::cerr << "Shaders not yet compiled!!!!\n";
// clean up existing data:
destroyInstanceData();
// create new data for this instance
initInstanceData();
// create height map textures and geometry
updateHeightMap(wd, ht, scx, scy, data, true);
// set up terrain type colour map (if provided)
if (paintMap) updateTypeMapTexture(paintMap, PAINT);
if (constraintMap) updateTypeMapTexture(constraintMap, CONSTRAINT);
}
// the typ emap can be either a PAINT map (for painting on types) or an CONSTRAINT map
// for painting on freezing or other constraints.
void TRenderer::updateTypeMapTexture(TypeMap* tmap, typeMapInfo tinfo, bool force)
{
if (tmap == NULL)
{
std::cerr << "TRenderer::updateTypeMapTexture - tmap is NULL\n";
return;
}
MemMap<int> *tm = tmap->getMap();
if (tm == NULL)
{
std::cerr << "TRenderer::updateTypeMapTexture - Map buffer is NULL, map ignored\n";
return;
}
Region R = tmap->getRegion();
// cerr << "R: " << R.x0 << " " << R.x1 << " " << R.y0 << " " << R.y1 << endl;
int wd = tm->width();
int ht = tm->height();
const int* ptr = (int*)tm->get();
std::vector<GLfloat *> *ct = tmap->getColourTable();
int Rwidth = R.x1 - R.x0; // region bounds from [R.x0, R.x1)
int Rheight = R.y1 - R.y0;
int xoff = R.x0;
int yoff = R.y0;
int index;
bool initTexture = false;
// width and height of terrain must match the width and height of type map buffer
// assert(wd == width && ht == height);
// texturing ops affect this texture unit
GLenum texUnit = GL_TEXTURE0;
GLuint *texId = NULL;
switch (tinfo)
{
case PAINT:
texUnit = typemapTexUnit;
texId = &typeMapTexture;
break;
case CONSTRAINT:
texUnit = constraintTexUnit;
texId = &constraintTexture;
break;
default: std::cerr << "TRenderer::updateTypeMapTexture - Illegal type map mode!\n"; return;
}
glActiveTexture(texUnit); CE();
// if grid dimensions have changed:
if(*texId != 0 && force)
{
/*
cerr << "tmap = " << wd << ", " << ht << endl;
cerr << "terrain = " << width << ", " << height << endl;
cerr << "updating texture width and height" << endl;*/
glDeleteTextures(1, texId); CE();
*texId = 0;
}
if (*texId == 0) // internal typeMap texture not allocated yet
{
// allocate subbuffer: this is used to avoid mem allocation each time this method is called (frequently)
// std::cout << "Region: " << R.x0 << "," << R.y0 << "," << R.x1 << "," << R.y1 << "\n";
if (typeBuffer != NULL)
delete [] typeBuffer;
typeBuffer = new GLfloat [width*height*4];
if (typeBuffer == NULL)
{
std::cerr << "TRenderer::updateTypeMapTexture - typeBuffer could not be allocated\n";
return;
}
glGenTextures(1, texId); CE();
glBindTexture(GL_TEXTURE_2D, *texId); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); CE();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
initTexture = true;
xoff = yoff = 0;
Rwidth = wd;
Rheight = ht; // copy in whole buffer region, not sub-window
}
else // need to sub in region - bind texture first
{
glBindTexture(GL_TEXTURE_2D, *texId); CE();
}
// build colour buffer for texture:
int cnt = 0;
int colIdx;
// std::cout << "Width, Height = " << Rwidth << "," << Rheight << std::endl;
int species_count = 0;
int transparent_count = 0;
int cutoff_count = 0;
GLfloat paintcol [4];
paintcol[3] = 1.0f;
for (int i = 0; i < Rheight; i++)
for (int j = 0; j < Rwidth; j++)
{
index = (yoff + i)*wd + (xoff + j);
colIdx = ptr[index];
if (colIdx == 0 && tinfo != CONSTRAINT && tmap->getPurpose() != TypeMapType::CLUSTER) // background should be used - use terMatDiffuse; for CONSTRAINT, ignore
{
//std::cout << "BG col at [" << i << "," << j << "]\n";
//std::cout << "Ter Colour=[" << terMatDiffuse[0] << "," <<
// terMatDiffuse[1] << "," << terMatDiffuse[2] << "," << terMatDiffuse[3] << "]\n";
typeBuffer[4*cnt] = terMatDiffuse[0];
typeBuffer[4*cnt+1] = terMatDiffuse[1];
typeBuffer[4*cnt+2] = terMatDiffuse[2];
typeBuffer[4*cnt+3] = terMatDiffuse[3];
cutoff_count++;
}
else if (tmap->getPurpose() == TypeMapType::CHM)
{
if (colIdx > 1) // if the CHM value is nonzero (had to make it 1, since it the minimum is one
{
typeBuffer[4 * cnt] = 0.0f;
typeBuffer[4 * cnt + 1] = colIdx / 256.0f;
typeBuffer[4 * cnt + 2] = 0.0f;
typeBuffer[4 * cnt + 3] = 1.0f;
}
else // if the CHM is zero (or 1 in this case) meaning there are no plants present in this location, display the landscape texture
{
typeBuffer[4*cnt] = terMatDiffuse[0];
typeBuffer[4*cnt+1] = terMatDiffuse[1];
typeBuffer[4*cnt+2] = terMatDiffuse[2];
typeBuffer[4*cnt+3] = terMatDiffuse[3];
}
}
else if (tmap->getPurpose() == TypeMapType::GRASS)
{
if (colIdx > 0) // if the grass height is nonzero (had to make it 1, since it the minimum is one (not sure about this...check)
{
typeBuffer[4 * cnt] = 0.0f;
typeBuffer[4 * cnt + 1] = colIdx / 255.0f;
typeBuffer[4 * cnt + 2] = 0.0f;
typeBuffer[4 * cnt + 3] = 1.0f;
}
else // if the grass height is zero, display the landscape texture
{
typeBuffer[4*cnt] = terMatDiffuse[0];
typeBuffer[4*cnt+1] = terMatDiffuse[1];
typeBuffer[4*cnt+2] = terMatDiffuse[2];
typeBuffer[4*cnt+3] = terMatDiffuse[3];
}
}
else if (tmap->getPurpose() == TypeMapType::PRETTY_PAINTED)
{
int cat = colIdx / 1000000;
colIdx -= cat * 1000000;
if (colIdx >= 2 && colIdx <= 2 + MAXGRASSHGHT)
{
float p = (colIdx - 2) / (MAXGRASSHGHT);
typeBuffer[4 * cnt] = 0.0f * p + terMatDiffuse[0] * (1 - p);
typeBuffer[4 * cnt + 1] = 0.5f * p + terMatDiffuse[1] * (1 - p);
typeBuffer[4 * cnt + 2] = 0.0f * p + terMatDiffuse[2] * (1 - p);
typeBuffer[4 * cnt + 3] = 1.0f * p + terMatDiffuse[3] * (1 - p);
}
else if (colIdx == 1)
{
typeBuffer[4 * cnt] = 127.0f / 255.0f;
typeBuffer[4 * cnt + 1] = 127.0f / 255.0f;
typeBuffer[4 * cnt + 2] = 127.0f / 255.0f;
typeBuffer[4 * cnt + 3] = 1.0f;
}
else if (colIdx > 3 + MAXGRASSHGHT)
{
typeBuffer[4 * cnt] = 0.0f;
typeBuffer[4 * cnt + 1] = 0.0f;
typeBuffer[4 * cnt + 2] = 70.0f / 255.0f;
typeBuffer[4 * cnt + 3] = 1.0f;
}
else
{
typeBuffer[4*cnt] = terMatDiffuse[0];
typeBuffer[4*cnt+1] = terMatDiffuse[1];
typeBuffer[4*cnt+2] = terMatDiffuse[2];
typeBuffer[4*cnt+3] = terMatDiffuse[3];
}
float paintp = 0.0f;
if (cat > 0)
paintp = 0.35f;
if (cat == 1)
{
paintcol[1] = 0.5f;
paintcol[0] = paintcol[2] = 0.0f;
}
else if (cat == 2)
{
paintcol[1] = 0.5f;
paintcol[0] = paintcol[2] = 0.0f;
paintp = 0.75f;
}
paintcol[3] = 1.0f;
for (int i = 0; i < 3; i++)
{
typeBuffer[4*cnt + i] = typeBuffer[4 * cnt + i] * (1 - paintp) + paintcol[i] * paintp;
}
}
else if (tmap->getPurpose() == TypeMapType::PRETTY)
{
if (colIdx >= 2 && colIdx <= 2 + MAXGRASSHGHT)
{
float p = (colIdx - 2) / (MAXGRASSHGHT);
typeBuffer[4 * cnt] = 0.0f * p + terMatDiffuse[0] * (1 - p);
typeBuffer[4 * cnt + 1] = 0.5f * p + terMatDiffuse[1] * (1 - p);
typeBuffer[4 * cnt + 2] = 0.0f * p + terMatDiffuse[2] * (1 - p);
typeBuffer[4 * cnt + 3] = 1.0f * p + terMatDiffuse[3] * (1 - p);
}
else if (colIdx == 1)
{
typeBuffer[4 * cnt] = 127.0f / 255.0f;
typeBuffer[4 * cnt + 1] = 127.0f / 255.0f;
typeBuffer[4 * cnt + 2] = 127.0f / 255.0f;
typeBuffer[4 * cnt + 3] = 1.0f;
}
else if (colIdx > 3 + MAXGRASSHGHT)
{
typeBuffer[4 * cnt] = 0.0f;
typeBuffer[4 * cnt + 1] = 0.0f;
typeBuffer[4 * cnt + 2] = 70.0f / 255.0f;
typeBuffer[4 * cnt + 3] = 1.0f;
}
else
{
typeBuffer[4*cnt] = terMatDiffuse[0];
typeBuffer[4*cnt+1] = terMatDiffuse[1];
typeBuffer[4*cnt+2] = terMatDiffuse[2];
typeBuffer[4*cnt+3] = terMatDiffuse[3];
}
}
else if (tmap->getPurpose() == TypeMapType::SPECIES)
{
if (colIdx >= 1) // FIXME: species at index 0 (and no species at all) will be ignored now
{
int total = 256 * 256 * 256;
int incr = total / 30;
int value = colIdx * incr;
int r = value % 256;
int g = ((value - r) / 256) % 256;
int b = (((value - r) / 256) - g) / 256 % 256;
typeBuffer[4*cnt] = r / (float)255.1f;
typeBuffer[4*cnt + 1] = g / (float)255.1f;
typeBuffer[4*cnt + 2] = b / (float)255.1f;
typeBuffer[4*cnt + 3] = 1.0f;
/*
typeBuffer[4*cnt] = 1.0f;
typeBuffer[4*cnt + 1] = 1.0f;
typeBuffer[4*cnt + 2] = 1.0f;
typeBuffer[4*cnt + 3] = 1.0f;
*/
species_count++;
}
else
{
typeBuffer[4*cnt] = terMatDiffuse[0];
typeBuffer[4*cnt+1] = terMatDiffuse[1];
typeBuffer[4*cnt+2] = terMatDiffuse[2];
typeBuffer[4*cnt+3] = terMatDiffuse[3];
transparent_count++;
}
}
else if (tmap->getPurpose() == TypeMapType::CLUSTER)
{
int r, g, b, a;
float cr, cg, cb, ca;
int incr = 50;
int totval = colIdx * incr;
if (colIdx >= 0)
{
b = totval / (256 * 256) % 256;
g = (totval / 256) % 256;
r = totval % 256;
cr = r / (float)255.1f;;
cb = b / (float)255.1f;;
cg = g / (float)255.1f;;
ca = 1.0f;
}
else
{
cr = terMatDiffuse[0];
cg = terMatDiffuse[1];
cb = terMatDiffuse[2];
ca = terMatDiffuse[3];
}
typeBuffer[4*cnt] = cr;
typeBuffer[4*cnt + 1] = cg;
typeBuffer[4*cnt + 2] = cb;
typeBuffer[4*cnt + 3] = ca;
}
else if (tmap->getPurpose() == TypeMapType::CLUSTERDENSITY)
{
float r, g = 0.0f, b = 0.0f, a = 1.0f;
if (colIdx < 0)
{
r = terMatDiffuse[0];
g = terMatDiffuse[1];
b = terMatDiffuse[2];
a = terMatDiffuse[3];
//r = g = b = 255.0f;
}
else
{
r = colIdx * 1.5f / 255.1f;
}
typeBuffer[4*cnt] = r;
typeBuffer[4*cnt + 1] = g;
typeBuffer[4*cnt + 2] = b;
typeBuffer[4*cnt + 3] = a;
}
else
{
typeBuffer[4*cnt] = (*ct)[ colIdx ][0];
typeBuffer[4*cnt+1] = (*ct)[ colIdx ][1];
typeBuffer[4*cnt+2] = (*ct)[ colIdx ][2];
typeBuffer[4*cnt+3] = (*ct)[ colIdx ][3];
//std::cout << "Map Colour=[" << typeBuffer[4*cnt] << "," <<
// typeBuffer[4*cnt + 1] << "," << typeBuffer[4*cnt + 2] << "," << typeBuffer[4*cnt + 3] << "]\n";
}
cnt++;
}
/*
std::cout << "Proportion covered by species in renderer: " << species_count / (Rwidth * (float)Rheight) << std::endl;
std::cout << "Proportion transparent for species in renderer: " << transparent_count / (Rwidth * (float)Rheight) << std::endl;
std::cout << "Proportion cutoff from species data in renderer: " << cutoff_count / (Rwidth * (float)Rheight) << std::endl;
*/
//std::cout << "Buffer built...\n";
if (initTexture)
{
//std::cout << "Overlay texture created at full resolution\n";
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA8, Rwidth, Rheight, 0,GL_RGBA, GL_FLOAT, typeBuffer); CE();
}
else
{
//std::cout << "Overlay textured sub'd\n";
glTexSubImage2D(GL_TEXTURE_2D, 0, xoff, yoff, Rwidth, Rheight, GL_RGBA, GL_FLOAT, typeBuffer); CE();
}
//std::cout << "Overlay created\n";
}
// initialise renderer - compile shaders etc This must be called before any other operations on the
// renderer.
void TRenderer::initShaders(void)
{
// set up shaders for loading and compilation
if (shadersReady) return; // already compiled
shaderProgram *s;
s = new shaderProgram();
s->setShaderSources(std::string("basic.frag"), std::string("basic.vert"));
shaders["basicShader"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("genNormal.frag"), std::string("genNormal.vert"));
shaders["normalShader"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("phong.frag"), std::string("phong.vert"));
shaders["phong"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("rad_scaling_pass1.frag"), std::string("rad_scaling_pass1.vert"));
shaders["rscale1"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("rad_scaling_pass2.frag"), std::string("rad_scaling_pass2.vert"));
shaders["rscale2"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("phongRS.frag"), std::string("phongRS.vert"));
shaders["phongRS"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("phongRSmanip.frag"), std::string("phongRSmanip.vert"));
shaders["phongRSmanip"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("sun.frag"), std::string("sun.vert"));
shaders["sunShader"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("canopy.frag"), std::string("canopy.vert"));
shaders["canopyShader"] = s;
s = new shaderProgram();
s->setShaderSources(std::string("phongRStextures.frag"), std::string("phongRStextures.vert"));
shaders["phongRStextures"] = s;
std::cout << "Compiling shaders...\n";
std::map<std::string, shaderProgram*>::iterator it = shaders.begin();
while (it != shaders.end() )
{
std::cout << " -- shader: " << (*it).first << " -- ";
(void)((*it).second)->compileAndLink();
std::cout << "ID = " << ((*it).second)->getProgramID() << std::endl;
it++;
}
shadersReady = true;
std::cout << "done!\n";
}
void TRenderer::bindDecals(int width, int height, unsigned char * buffer)
{
GLint maxtexunits;
GLint boundtexunit;
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxtexunits);
std::cout << "maximum texture units: " << maxtexunits << std::endl;
// bind texture
glEnable(GL_TEXTURE_2D);
glActiveTexture(decalTexUnit); CE();
glGetIntegerv(GL_TEXTURE_BINDING_2D, &boundtexunit);
glGenTextures( 1, &decalTexture ); CE();
glBindTexture( GL_TEXTURE_2D, decalTexture ); CE();
// int off = 56 * width * 4 + 767 * 4;
// cerr << "width = " << width << ", height = " << height << endl;
// cerr << "decal buffer [0][0] = " << (int) buffer[0] << ", " << (int) buffer[1] << ", " << (int) buffer[2] << ", " << (int) buffer[3] << endl;
// cerr << "decal buffer [767][56] = " << (int) buffer[off] << ", " << (int) buffer[off+1] << ", " << (int) buffer[off+2] << ", " << (int) buffer[off+3] << endl;
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); CE(); // ? is this actually working
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); CE();
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); CE();
// deal with out of array access
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
}
void TRenderer::draw(View * view)
{
if (!shadersReady) // not compiled!
{
std::cerr << "Shaders not built before draw() call - compiling...\n";
initShaders();
}
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
//std::cout << "Viewport chk - [" << viewport[0] << "," << viewport[1] << "," << viewport[3] << "," << viewport[3] << "]\n";
// render at 2X resolution for later linear downsampling (basic anti-aliasing)
updateRadianceScalingBuffers(2*viewport[2], 2*viewport[3]);
// Set the clear color to white
glClearColor( 1.0f, 1.0f, 1.0f, 1.0f ); CE();
glEnable(GL_DEPTH_TEST); CE();
glDepthMask(GL_TRUE); CE();
glDepthFunc(GL_LEQUAL); CE();
glDepthRange(0.0f, 1.0f); CE();
glEnable(GL_CULL_FACE); CE();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CE();
//glEnable(GL_DEPTH_CLAMP);
// configure shading params.
// ************************* Terrain Setup & render code *****************************************
normalMatrix = view->getNormalMtx();
MVP = view->getMatrix();
MVmx = view->getViewMtx();
projMx = view->getProjMtx();
std::string shaderName;
if (shadModel == BASIC) // basic Phong
shaderName = "basicShader";
else if(shadModel == RADIANCE_SCALING)
shaderName = "rscale1";
else // sun shading
shaderName = "sunShader";
GLuint programID = (*shaders[shaderName]).getProgramID();
glUseProgram(programID); CE();
glUniformMatrix3fv(glGetUniformLocation(programID, "normMx"), 1, GL_FALSE, glm::value_ptr(normalMatrix)); CE();
glUniformMatrix4fv(glGetUniformLocation(programID, "MV"), 1, GL_FALSE, glm::value_ptr(MVmx)); CE();
glUniformMatrix4fv(glGetUniformLocation(programID, "MVproj"), 1, GL_FALSE, glm::value_ptr(MVP)); CE();
glm::vec4 lightPos = MVmx * pointLight; // map light pos into camera space
// configure texturing: region texture overlay
if (terrainTypeTexture == false)
{
glUniform1i(glGetUniformLocation(programID, "useRegionTexture"), 0); CE(); // turn texture off
}
else if (typeMapTexture != 0)
{
glUniform1i(glGetUniformLocation(programID, "useRegionTexture"), 1); CE(); // draw region texture
GLuint rtex = glGetUniformLocation(programID, "overlayTexture"); CE();
glUniform1i(rtex, (GLint)(typemapTexUnit - GL_TEXTURE0)); CE(); // texture unit for region overlay
}
else
{
glUniform1i(glGetUniformLocation(programID, "useRegionTexture"), 0); CE(); // region texture not yet defined
}
// configure texturing: constraint texture overlay
if (constraintTypeTexture == false)
{
glUniform1i(glGetUniformLocation(programID, "useConstraintTexture"), 0); CE(); // turn texture off
}
else if (constraintTexture != 0)
{
glUniform1i(glGetUniformLocation(programID, "useConstraintTexture"), 1); CE(); // draw constraint texture
GLuint rtex = glGetUniformLocation(programID, "constraintTexture"); CE();
glUniform1i(rtex, (GLint)(constraintTexUnit - GL_TEXTURE0)); CE(); // texture unit for constraint overlay
}
else
{
glUniform1i(glGetUniformLocation(programID, "useConstraintTexture"), 0); CE(); // region texture not yet defined
}
// contouring and grids
glUniform1i(glGetUniformLocation(programID, "drawContours"), (int)(contours ? 1 : 0) ); CE(); // draw contours
glUniform1i(glGetUniformLocation(programID, "drawGridLines"), (int)(gridlines ? 1 : 0) ); CE(); // draw grdlines
glUniform1i(glGetUniformLocation(programID, "drawWallContours"), (int)(contoursWall ? 1 : 0) ); CE(); // draw wall contours
glUniform1i(glGetUniformLocation(programID, "drawWallGridLines"), (int)(gridlinesWall ? 1 : 0) ); CE(); // draw wall contours
// change shading for out of bounds heights
glUniform1i(glGetUniformLocation(programID, "drawOutOfBounds"), (int)(drawOutOfBounds ? 1 : 0) ); CE(); // draw wall contours
glUniform1f(glGetUniformLocation(programID, "outBoundsBlend"), outOfBoundsWeight); CE();
glUniform1f(glGetUniformLocation(programID, "outBoundsMax"), outOfBoundsMean + outOfBoundsOffset); CE();
glUniform1f(glGetUniformLocation(programID, "outBoundsMin"), outOfBoundsMean - outOfBoundsOffset); CE();
glUniform4fv(glGetUniformLocation(programID, "outBoundsCol"), 1, glm::value_ptr(outOfBoundsColour) ); CE();
// set contouring params (not implemented in BASIC at the moment...)
glUniform1f(glGetUniformLocation(programID, "gridX"), gridXsep); CE();
glUniform1f(glGetUniformLocation(programID, "gridZ"), gridZsep); CE();
glUniform1f(glGetUniformLocation(programID, "gridColFactor"), gridColFactor); CE();
glUniform1f(glGetUniformLocation(programID, "gridThickness"), gridThickness); CE();
glUniform1f(glGetUniformLocation(programID, "contourSep"), contourSep); CE();
glUniform1f(glGetUniformLocation(programID, "contourColFactor"), contourColFactor); CE();
glUniform1f(glGetUniformLocation(programID, "contourThickness"), contourThickness); CE();
// pass light and colours to shader
if (shadModel == BASIC)
{
glUniform4fv(glGetUniformLocation(programID, "lightpos"), 1, glm::value_ptr(lightPos)); CE();
// set colours
glUniform4fv(glGetUniformLocation(programID, "matDiffuse"), 1, glm::value_ptr(terMatDiffuse) ); CE();
glUniform4fv(glGetUniformLocation(programID, "matAmbient"), 1, glm::value_ptr(terMatAmbient) ); CE();
glUniform4fv(glGetUniformLocation(programID, "matSpec"), 1, glm::value_ptr(terMatSpec) ); CE();
glUniform4fv(glGetUniformLocation(programID, "diffuseCol"), 1, glm::value_ptr(lightDiffuseColour) ); CE();
glUniform4fv(glGetUniformLocation(programID, "ambientCol"), 1, glm::value_ptr(lightAmbientColour) ); CE();
glUniform4fv(glGetUniformLocation(programID, "specularCol"), 1, glm::value_ptr(lightSpecColour) ); CE();
glUniform1f(glGetUniformLocation(programID, "shiny"), shinySpec); CE();
}
else if(shadModel == RADIANCE_SCALING) // radiance scaling
{
// map side wall lights into camera space; lights at corners of terrain, moved along diagonal
glm::vec4 LP1 = MVmx * glm::vec4(2.0*scalex, 0.5, 2.0*scaley, 1.0);
glm::vec4 LP2 = MVmx * glm::vec4(-scalex, 0.5, -scaley, 1.0);
glUniform4fv(glGetUniformLocation(programID, "ptLightPos1"), 1, glm::value_ptr(LP1) ); CE();
glUniform4fv(glGetUniformLocation(programID, "ptLightPos2"), 1, glm::value_ptr(LP2) ); CE();
glUniform4fv(glGetUniformLocation(programID, "surfColour"), 1, glm::value_ptr(terSurfColour) ); CE();
}
else if(shadModel == SUN) // sun simulator
{
glUniform1f(glGetUniformLocation(programID, "terdim"), (float) (width)); CE();
}
//pass height and normal map to shader
GLuint textur = glGetUniformLocation(programID, "htMap"); CE();
glUniform1i(textur, (GLint)(htmapTexUnit - GL_TEXTURE0)); CE(); // assumes texture unit 0 is bound to heightmap texture
GLuint textur2 = glGetUniformLocation(programID, "normalMap"); CE();
glUniform1i(textur2, (GLint)(normalMapTexUnit - GL_TEXTURE0)); CE(); // assumes texture unit 1 is bound to normal map texture
// draw terrain:
if (shadModel == RADIANCE_SCALING)
{
GLfloat depthClear = 1.0f;
GLfloat colClear[4] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat manipLayerClear[4] = {0.0f, 0.0f, 0.0f, 0.0f};
GLfloat gradClear[4] = {0.0f, 0.0f, 0.0f, 0.0f};
GLfloat normClear[4] = {0.0f, 0.0f, 0.0f, 0.0f};
// clear manipulator transparency FBO
glBindFramebuffer(GL_FRAMEBUFFER, fboManipLayer); CE();
glViewport(0,0,_w, _h); CE(); // draw into entire frame
// clear frame buffer depth/textures
glClearBufferfv(GL_DEPTH, 0, &depthClear);
glClearBufferfv(GL_COLOR, 0, manipLayerClear);
// Render to RS FBO; clear buffers first
glBindFramebuffer(GL_FRAMEBUFFER, fboRadScaling); CE();
glViewport(0,0,_w, _h); CE(); // draw into entire frame
// clear frame buffer depth/textures
glClearBufferfv(GL_DEPTH, 0, &depthClear);
glClearBufferfv(GL_COLOR, 0, gradClear); // may be able to ignore this one - gradTexture?
glClearBufferfv(GL_COLOR, 1, normClear); // this has to be set to (0,0,0) for RS shader to work
glClearBufferfv(GL_COLOR, 2, colClear);
}
else
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CE();
}
glUniform1i(glGetUniformLocation(programID, "drawWalls"), 0); CE(); // do NOT draw walls
glBindVertexArray(vaoTerrain); CE();
glDrawElements(GL_TRIANGLE_STRIP, indexSize, GL_UNSIGNED_INT, 0); CE();
// *** draw capping walls ***
// --- move base up/down to avoid edits to surface which 'punch through' base
glUniform1f(glGetUniformLocation(programID, "terrainBase"), terrainBase); CE();
glUniform1f(glGetUniformLocation(programID, "terrainBasePad"), terrainBasePad); CE();
glUniform1i(glGetUniformLocation(programID, "drawWalls"), 1); // draw walls - ignore normal map lookup
GLuint loc = glGetUniformLocation(programID, "normalWall");
// turn off region layer texturing for walls:
glUniform1i(glGetUniformLocation(programID, "useRegionTexture"), 0); CE(); // always off for walls!
for (int i = 0; i < 5; i++)
{
glUniform3fv(loc, 1, glm::value_ptr(normalWalls[i])); CE();
glBindVertexArray(vaoWalls[i]); CE();
glDrawElements(GL_TRIANGLE_STRIP, wallDrawEls[i], GL_UNSIGNED_INT, 0); CE();
}
// **************************** draw manipulators/constraints with phong **********************************
if (shadModel == RADIANCE_SCALING)
{
programID = (*shaders["phongRS"]).getProgramID();
}
else if (shadModel == SUN)
{
programID = (*shaders["canopyShader"]).getProgramID();
}
else
{
programID = (*shaders["phong"]).getProgramID();
}
// for tree models, etc.
if (SYMBOLIC_RENDERER)
programID = (*shaders["phongRS"]).getProgramID();
else
programID = (*shaders["phongRStextures"]).getProgramID();
drawManipulatorsInstanced(programID);
// for brush
programID = (*shaders["phongRS"]).getProgramID();
drawManipulators(programID, false, true);
// draw second pass for manipulator transparency (not supported in BASIC mode)
if (shadModel == RADIANCE_SCALING)
{
// for tree models, etc.
if (SYMBOLIC_RENDERER)
programID = (*shaders["phongRS"]).getProgramID();
else
programID = (*shaders["phongRStextures"]).getProgramID();
glBindFramebuffer(GL_FRAMEBUFFER, fboManipLayer); CE();
glViewport(0,0,_w, _h); CE();
drawManipulatorsInstanced(programID, true);
// for brush
programID = (*shaders["phongRSmanip"]).getProgramID();
glBindFramebuffer(GL_FRAMEBUFFER, fboManipLayer); CE();
glViewport(0,0,_w, _h); CE();
drawManipulators(programID, true, true);
}
// reset frame buffer buffer etc
if (shadModel == RADIANCE_SCALING)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0); CE();
glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); // reset viewport to system setting
}
// **************************** radiance scaling pass 2 ****************************************************
if (shadModel == RADIANCE_SCALING)
{
glDisable(GL_DEPTH_TEST); CE(); // not required for screen aligned quad
// Render to our composition framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, fboRSOutput); CE();
glViewport(0,0,_w, _h); // draw into entire frame
shaderName = "rscale2";
programID = (*shaders[shaderName]).getProgramID();
//std::cout << "Shader ID (RScaling) = " << programID << std::endl;
glUseProgram(programID); CE();
//glClearColor( 0.5f, 0.0f, 0.0f, 1.0f ); CE();
glClear(GL_COLOR_BUFFER_BIT); CE();
// set image size to allow tex coordinate gen per rasterized quad fragment
GLfloat imgDims[2] = {float(_w), float(_h)};
GLuint locDims = glGetUniformLocation(programID, "imgSize"); CE();
glUniform2fv(locDims, 1, imgDims); CE();
// light is directional - specified in ***** WORLD space ******
// map DIRECTIONAL light(s) into camera space
for (int i = 0; i < 2; i++)
{
std::ostringstream oss;
oss << "lightPos" << i;
glm::vec3 dlight = normalMatrix * glm::vec3(directionalLight[i][0], directionalLight[i][1], directionalLight[i][2]);
lightPos = glm::vec4(dlight[0], dlight[1], dlight[2], 0.0f);
glUniform4fv(glGetUniformLocation(programID, oss.str().c_str()), 1, glm::value_ptr(lightPos)); CE();
}
// use lambertian lighting and params for RS calculation
GLuint dispmode = glGetUniformLocation(programID, "display"); CE();
glUniform1i(dispmode, 0); CE();
GLuint RSenabled = glGetUniformLocation(programID, "enabled"); CE();
glUniform1i(RSenabled, 1); CE();
GLuint invertCurvature = glGetUniformLocation(programID, "invert"); CE();
glUniform1i(invertCurvature, (RSinvertCurvature ? 1: 0)); CE();
GLuint enhancement = glGetUniformLocation(programID, "enhancement"); CE();
glUniform1f(enhancement, RSenhance); CE();
GLuint transition = glGetUniformLocation(programID, "transition"); CE();
glUniform1f(transition, RStransition); CE();
GLuint swidth = glGetUniformLocation(programID, "sw"); CE();
glUniform1f(swidth, (float)(1.0/_w) ); CE();
GLuint sheight = glGetUniformLocation(programID, "sh"); CE();
glUniform1f(sheight, (float)(1.0/_h) ); CE();
// configure FBO textures for render ops
GLuint textur = glGetUniformLocation(programID, "grad"); CE();
glUniform1i(textur, (GLuint)(rsGradTexUnit - GL_TEXTURE0) ); CE();
textur = glGetUniformLocation(programID, "norm"); CE();
glUniform1i(textur, (GLuint)(rsNormTexUnit - GL_TEXTURE0) ); CE();
textur = glGetUniformLocation(programID, "colormap"); CE();
glUniform1i(textur, (GLuint)(rsColTexUnit - GL_TEXTURE0) ); CE();
textur = glGetUniformLocation(programID, "manipTTexture"); CE(); // manipulator transparency
glUniform1i(textur, (GLuint)(manipTranspTexUnit - GL_TEXTURE0) ); CE();
// draw screeen aligned quad to compose RS calculations
glBindVertexArray(vaoScreenQuad); CE();
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); CE();
// unbind everthing
glBindVertexArray(0); CE();
// bind draw buffer (system
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); CE();
// bind read buffer (fbo)
glBindFramebuffer(GL_READ_FRAMEBUFFER, fboRSOutput); CE();
// set draw buffer
glDrawBuffer(GL_BACK);
// blit to the default framebuffer/back_buffer
glBlitFramebuffer(0, 0, _w, _h,
viewport[0], viewport[1], viewport[0] + viewport[2], viewport[1] + viewport[3], GL_COLOR_BUFFER_BIT, GL_LINEAR);
//std::cout << "Blit target: [" << viewport[0] << "," << viewport[1] << "," <<
//viewport[0] + viewport[2] << "," << viewport[1] + viewport[3] << "]\n";
// reset viewport to system setting
glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
glUseProgram(0); CE();
}
void TRenderer::drawSun(View * view, int renderPass)
{
if (!shadersReady) // not compiled!
{
std::cerr << "Shaders not built before draw() call - compiling...\n";
initShaders();
}
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
// render at 2X resolution for later linear downsampling (basic anti-aliasing)
updateRadianceScalingBuffers(2*viewport[2], 2*viewport[3]);
// Set the clear color to white
glClearColor( 1.0f, 1.0f, 1.0f, 1.0f ); CE();
glEnable(GL_DEPTH_TEST); CE();
glDepthMask(GL_TRUE); CE();
glDepthFunc(GL_LEQUAL); CE();
glDepthRange(0.0f, 1.0f); CE();
glEnable(GL_CULL_FACE); CE();
if(renderPass == 2) // enable blending
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CE();
// configure shading params.
// ************************* Terrain Setup & render code *****************************************
normalMatrix = view->getNormalMtx();
MVP = view->getMatrix();
MVmx = view->getViewMtx();
projMx = view->getProjMtx();
std::string shaderName;
shaderName = "sunShader";
GLuint programID = (*shaders[shaderName]).getProgramID();
glUseProgram(programID); CE();
glUniform1i(glGetUniformLocation(programID, "drawCanopies"), renderPass-1); CE(); // whether or not to use indexed colours
// PHASE 1: Draw Terrain
glUniformMatrix3fv(glGetUniformLocation(programID, "normMx"), 1, GL_FALSE, glm::value_ptr(normalMatrix)); CE();
glUniformMatrix4fv(glGetUniformLocation(programID, "MV"), 1, GL_FALSE, glm::value_ptr(MVmx)); CE();
glUniformMatrix4fv(glGetUniformLocation(programID, "MVproj"), 1, GL_FALSE, glm::value_ptr(MVP)); CE();
glUniform1f(glGetUniformLocation(programID, "terdim"), (float) (width)); CE();
// pass height and normal map to shader
GLuint textur = glGetUniformLocation(programID, "htMap"); CE();
glUniform1i(textur, (GLint)(htmapTexUnit - GL_TEXTURE0)); CE(); // assumes texture unit 0 is bound to heightmap texture
GLuint textur2 = glGetUniformLocation(programID, "normalMap"); CE();
glUniform1i(textur2, (GLint)(normalMapTexUnit - GL_TEXTURE0)); CE(); // assumes texture unit 1 is bound to normal map texture
// draw terrain:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CE();
glUniform1i(glGetUniformLocation(programID, "drawWalls"), 0); CE(); // do NOT draw walls
glBindVertexArray(vaoTerrain); CE();
glDrawElements(GL_TRIANGLE_STRIP, indexSize, GL_UNSIGNED_INT, 0); CE();
// PHASE 2: Draw capping walls
// --- move base up/down to avoid edits to surface which 'punch through' base
glUniform1f(glGetUniformLocation(programID, "terrainBase"), terrainBase); CE();
glUniform1f(glGetUniformLocation(programID, "terrainBasePad"), terrainBasePad); CE();
glUniform1i(glGetUniformLocation(programID, "drawWalls"), 1); // draw walls - ignore normal map lookup
GLuint loc = glGetUniformLocation(programID, "normalWall");
// turn off region layer texturing for walls:
glUniform1i(glGetUniformLocation(programID, "useRegionTexture"), 0); CE(); // always off for walls!
for (int i = 0; i < 5; i++)
{
glUniform3fv(loc, 1, glm::value_ptr(normalWalls[i])); CE();
glBindVertexArray(vaoWalls[i]); CE();
glDrawElements(GL_TRIANGLE_STRIP, wallDrawEls[i], GL_UNSIGNED_INT, 0); CE();
}
// PHASE 3: Draw canopies
// draw alpha blended canopies
if(renderPass == 2)
{
// disable depth writes so that more than one canopy can block sunlight
glDepthMask(GL_FALSE); CE();
programID = (*shaders["canopyShader"]).getProgramID();
drawManipulatorsInstanced(programID);
// revert to previous settings
glDepthMask(GL_TRUE); CE();
}
glUseProgram(0); CE();
}
// **************************** draw manipulators/constraints with phong **********************************
void TRenderer::drawManipulatorsInstanced(GLuint programID, bool drawToFB)
{
glUseProgram(programID); CE();
// use textured manipulators (decals)?
if (shadModel == RADIANCE_SCALING)
{
glUniform1i(glGetUniformLocation(programID, "useTexturing"), (manipulatorTextures ? 1:0) ); CE();
if (manipulatorTextures)
{
GLuint mtex = glGetUniformLocation(programID, "decalTexture"); CE();
glUniform1i(mtex, (GLint)(decalTexUnit - GL_TEXTURE0)); CE(); // texture unit for manipulators
}
}
for (int i = 0; i < (int)manipDrawCallData.size(); i++)
{
float alpha = 1.0f;
if (drawToFB) // used when drawing frame for manipulator transparanecy blending
{
// draw transparent manipulator - current only
if (shadModel == RADIANCE_SCALING)
{
if (manipDrawCallData[i].current && drawHiddenManipulators == true)
alpha = manipAlpha;
else
alpha = 0.0f;
glUniform1f(glGetUniformLocation(programID, "manipAlpha"), alpha ); CE();
}
}
// we have something to draw...
glUniformMatrix4fv(glGetUniformLocation(programID, "MV"), 1, GL_FALSE, glm::value_ptr(MVmx) ); CE();
glUniformMatrix4fv(glGetUniformLocation(programID, "MVproj"), 1, GL_FALSE, glm::value_ptr(MVP) ); CE();
glUniformMatrix3fv(glGetUniformLocation(programID, "normMx"), 1, GL_FALSE, glm::value_ptr(normalMatrix)); CE();
//glUniformMatrix3fv(glGetUniformLocation(programID, "normMx"), 1, GL_FALSE, glm::value_ptr(glm::mat3(1.0f))); CE();
glm::vec4 MatDiffuse = glm::vec4(manipDrawCallData[i].diffuse[0], manipDrawCallData[i].diffuse[1],
manipDrawCallData[i].diffuse[2], manipDrawCallData[i].diffuse[3]); // diffuse colour of manipulator
//cerr << "BASE COLOUR: " << manipDrawCallData[i].diffuse[0] << " " << manipDrawCallData[i].diffuse[1] << " " <<
// manipDrawCallData[i].diffuse[2] << " " << manipDrawCallData[i].diffuse[3] << endl;
glm::vec4 MatAmbient = glm::vec4(manipDrawCallData[i].ambient[0], manipDrawCallData[i].ambient[1],
manipDrawCallData[i].ambient[2], manipDrawCallData[i].ambient[3]); // ambient colour of manipulator
glm::vec4 MatSpecular = glm::vec4(manipDrawCallData[i].specular[0], manipDrawCallData[i].specular[1],
manipDrawCallData[i].specular[2], manipDrawCallData[i].specular[3]); // JG: ambient colour of manipulator
glm::vec4 lightDiffuseColour = glm::vec4(0.2f, 0.2f, 0.2f, 1.0f); // colour of light
glm::vec4 lightAmbientColour = glm::vec4(0.8f, 0.8f, 0.8f, 1.0f);
miscTextures = manipDrawCallData[i].textures;
std::vector<int> active_texids;
miscTexturesStartingLocation = 10;
for (int texi = 0; texi < miscTextures.size(); texi++)
{
if (miscTextures[texi] > 0)
{
glActiveTexture(GL_TEXTURE0 + miscTexturesStartingLocation + texi);
glBindTexture(GL_TEXTURE_2D, miscTextures[texi]);
}
active_texids.push_back(miscTexturesStartingLocation + texi);
}
miscTextures.clear(); // just a temporary container for now - can actually just use manipDrawCallData[i].textures directly
// set colours and light
glUniform4fv(glGetUniformLocation(programID, "matDiffuse"), 1, glm::value_ptr(MatDiffuse) ); CE();
glUniform4fv(glGetUniformLocation(programID, "matAmbient"), 1, glm::value_ptr(MatAmbient) ); CE();
glUniform4fv(glGetUniformLocation(programID, "matSpec"), 1, glm::value_ptr(MatSpecular) ); CE();
glUniform4fv(glGetUniformLocation(programID, "lightPos"), 1, glm::value_ptr(pointLight)); CE();
glUniform4fv(glGetUniformLocation(programID, "diffuseCol"), 1, glm::value_ptr(lightDiffuseColour) ); CE();
glUniform4fv(glGetUniformLocation(programID, "ambientCol"), 1, glm::value_ptr(lightAmbientColour) ); CE();
glUniform4fv(glGetUniformLocation(programID, "specularCol"), 1, glm::value_ptr(lightSpecColour) ); CE();
glUniform1f(glGetUniformLocation(programID, "shiny"), shinySpec); CE();
GLint loc = 0;
loc = glGetUniformLocation(programID, "texs");
glUniform1iv(loc, active_texids.size(), (int *)active_texids.data()); CE();
glBindVertexArray(manipDrawCallData[i].VAO); CE();
glDrawElementsInstanced(GL_TRIANGLES, manipDrawCallData[i].indexBufSize, GL_UNSIGNED_INT, (void*)(0), manipDrawCallData[i].numInstances); CE();
//glDrawElements(GL_TRIANGLES, manipDrawCallData[i].indexBufSize, GL_UNSIGNED_INT, (void*)(0)); CE();
glBindVertexArray(0); CE();
}
// unbind vao
glBindVertexArray(0); CE();
}
void TRenderer::drawManipulators(GLuint programID, bool drawToFB, bool brush)
{
glUseProgram(programID); CE();
// use textured manipulators (decals)?
if (shadModel == RADIANCE_SCALING)
{
glUniform1i(glGetUniformLocation(programID, "useTexturing"), (manipulatorTextures ? 1:0) ); CE();
if (manipulatorTextures)
{
GLuint mtex = glGetUniformLocation(programID, "decalTexture"); CE();
glUniform1i(mtex, (GLint)(decalTexUnit - GL_TEXTURE0)); CE(); // texture unit for manipulators
}
}
for (int i = 0; i < (int)manipDrawCallData.size(); i++)
{
if (manipDrawCallData[i].brush != brush)
continue;
float alpha = 1.0f;
if (drawToFB) // used when drawing frame for manipulator transparanecy blending
{
// draw transparent manipulator - current only
if (shadModel == RADIANCE_SCALING)
{
if (manipDrawCallData[i].current && drawHiddenManipulators == true)
alpha = manipAlpha;
else
alpha = 0.0f;
glUniform1f(glGetUniformLocation(programID, "manipAlpha"), alpha ); CE();
}
}
// we have something to draw...
glUniformMatrix4fv(glGetUniformLocation(programID, "MV"), 1, GL_FALSE, glm::value_ptr(MVmx) ); CE();
glUniformMatrix4fv(glGetUniformLocation(programID, "MVproj"), 1, GL_FALSE, glm::value_ptr(MVP) ); CE();
glUniformMatrix3fv(glGetUniformLocation(programID, "normMx"), 1, GL_FALSE, glm::value_ptr(normalMatrix)); CE();
//glUniformMatrix3fv(glGetUniformLocation(programID, "normMx"), 1, GL_FALSE, glm::value_ptr(glm::mat3(1.0f))); CE();
glm::vec4 MatDiffuse = glm::vec4(manipDrawCallData[i].diffuse[0], manipDrawCallData[i].diffuse[1],
manipDrawCallData[i].diffuse[2], manipDrawCallData[i].diffuse[3]); // diffuse colour of manipulator
//cerr << "BASE COLOUR: " << manipDrawCallData[i].diffuse[0] << " " << manipDrawCallData[i].diffuse[1] << " " <<
// manipDrawCallData[i].diffuse[2] << " " << manipDrawCallData[i].diffuse[3] << endl;
glm::vec4 MatAmbient = glm::vec4(manipDrawCallData[i].ambient[0], manipDrawCallData[i].ambient[1],
manipDrawCallData[i].ambient[2], manipDrawCallData[i].ambient[3]); // ambient colour of manipulator
glm::vec4 MatSpecular = glm::vec4(manipDrawCallData[i].specular[0], manipDrawCallData[i].specular[1],
manipDrawCallData[i].specular[2], manipDrawCallData[i].specular[3]); // JG: ambient colour of manipulator
glm::vec4 lightDiffuseColour = glm::vec4(0.2f, 0.2f, 0.2f, 1.0f); // colour of light
glm::vec4 lightAmbientColour = glm::vec4(0.8f, 0.8f, 0.8f, 1.0f);
miscTextures = manipDrawCallData[i].textures;
std::vector<int> active_texids;
miscTexturesStartingLocation = 10;
for (int texi = 0; texi < miscTextures.size(); texi++)
{
if (miscTextures[texi] > 0)
{
glActiveTexture(GL_TEXTURE0 + miscTexturesStartingLocation + texi);
glBindTexture(GL_TEXTURE_2D, miscTextures[texi]);
}
active_texids.push_back(miscTexturesStartingLocation + texi);
}
miscTextures.clear(); // just a temporary container for now - can actually just use manipDrawCallData[i].textures directly
// set colours and light
glUniform4fv(glGetUniformLocation(programID, "matDiffuse"), 1, glm::value_ptr(MatDiffuse) ); CE();
glUniform4fv(glGetUniformLocation(programID, "matAmbient"), 1, glm::value_ptr(MatAmbient) ); CE();
glUniform4fv(glGetUniformLocation(programID, "matSpec"), 1, glm::value_ptr(MatSpecular) ); CE();
glUniform4fv(glGetUniformLocation(programID, "lightPos"), 1, glm::value_ptr(pointLight)); CE();
glUniform4fv(glGetUniformLocation(programID, "diffuseCol"), 1, glm::value_ptr(lightDiffuseColour) ); CE();
glUniform4fv(glGetUniformLocation(programID, "ambientCol"), 1, glm::value_ptr(lightAmbientColour) ); CE();
glUniform4fv(glGetUniformLocation(programID, "specularCol"), 1, glm::value_ptr(lightSpecColour) ); CE();
glUniform1f(glGetUniformLocation(programID, "shiny"), shinySpec); CE();
GLint loc = 0;
loc = glGetUniformLocation(programID, "texs");
glUniform1iv(loc, active_texids.size(), (int *)active_texids.data()); CE();
glBindVertexArray(manipDrawCallData[i].VAO); CE();
//glDrawElementsInstanced(GL_TRIANGLES, manipDrawCallData[i].indexBufSize, GL_UNSIGNED_INT, (void*)(0), manipDrawCallData[i].numInstances); CE();
glDrawElements(GL_TRIANGLES, manipDrawCallData[i].indexBufSize, GL_UNSIGNED_INT, (void*)(0)); CE();
glBindVertexArray(0); CE();
}
// unbind vao
glBindVertexArray(0); CE();
}
} // end of namespace PMrender
| 83,655
|
C++
|
.cpp
| 1,737
| 41.217041
| 165
| 0.627565
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,223
|
terrain.cpp
|
jgain_EcoLearn/EcoSynth/viewer/terrain.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
// terrain.h: model for terrain. Responsible for storage and display of heightfield terrain data
// author: James Gain
// date: 17 December 2012
#include <GL/glew.h>
#include "terrain.h"
#include <sstream>
#include <common/debug_string.h>
#include <common/terragen.h>
#include <streambuf>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <utility>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
#include "data_importer/extract_png.h"
using namespace std;
void Terrain::toGrid(vpPoint p, float & x, float & y, float & h) const
{
int gx, gy;
float tx, ty, convx, convy;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
convx = (float) (gx-1) / tx;
convy = (float) (gy-1) / ty;
x = p.x * convx;
y = p.z * convy;
h = p.y;
if(scaleOn)
h *= scfac;
}
void Terrain::toGrid(vpPoint p, int &x, int &y) const
{
int gx, gy;
float tx, ty, convx, convy;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
convx = (float) (gx-1) / tx;
convy = (float) (gy-1) / ty;
x = (int) (p.x * convx);
y = (int) (p.z * convy);
}
float Terrain::toGrid(float wdist) const
{
int gx, gy;
float tx, ty, conv;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
conv = (float) (gx-1) / tx;
return wdist * conv;
}
vpPoint Terrain::toWorld(float x, float y, float h) const
{
int gx, gy;
float tx, ty, convx, convy;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
convx = tx / (float) (gx-1);
convy = ty / (float) (gy-1);
return vpPoint(x * convx, h, y * convy);
}
vpPoint Terrain::toWorld(int x, int y, float h) const
{
int gx, gy;
float tx, ty, convx, convy;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
convx = tx / (float) (gx-1);
convy = ty / (float) (gy-1);
return vpPoint((float) x * convx, h, (float) y * convy);
}
float Terrain::toWorld(float gdist) const
{
int gx, gy;
float tx, ty, conv;
getGridDim(gx, gy);
getTerrainDim(tx, ty);
conv = tx / (float) (gx-1);
return gdist * conv;
}
bool Terrain::inWorldBounds(vpPoint p) const
{
return (p.x >= 0.0f && p.x <= dimx && p.z >= 0.0f && p.z <= dimy);
}
bool Terrain::inSynthBounds(vpPoint p) const
{
return (p.x >= 0.0f-synthx && p.x <= dimx+synthx && p.z >= 0.0f-synthy && p.z <= dimy+synthy);
}
void Terrain::init(int dx, int dy, float sx, float sy)
{
grid.allocate(Region(0, 0, dx, dy));
grid.fill(0.0f);
setTerrainDim(sx, sy);
setFocus(vpPoint(sx/2.0f, grid[dy/2-1][dx/2-1], sy/2.0f));
scfac = 1.0f;
// init accel structure
spherestep = 8;
numspx = (grid.width()-1) / spherestep + 1; numspy = (grid.height()-1) / spherestep + 1;
for(int i = 0; i < numspx; i++)
{
std::vector<AccelSphere> sphrow;
for(int j = 0; j < numspy; j++)
{
AccelSphere sph;
sphrow.push_back(sph);
}
boundspheres.push_back(sphrow);
}
bufferState = BufferState::REALLOCATE;
accelValid = false;
scaleOn = false;
}
void Terrain::initGrid(int dx, int dy, float sx, float sy)
{
init(dx, dy, sx, sy);
grid.fill(0.0f);
}
void Terrain::delGrid()
{
grid.clear();
if(boundspheres.size() > 0)
{
for(int i = 0; i < (int) boundspheres.size(); i++)
boundspheres[i].clear();
boundspheres.clear();
}
bufferState = BufferState::REALLOCATE;
accelValid = false;
}
void Terrain::clipRegion(Region ®)
{
if(reg.x0 < 0) reg.x0 = 0;
if(reg.y0 < 0) reg.y0 = 0;
if(reg.x1 > grid.width()) reg.x1 = grid.width();
if(reg.y1 > grid.height()) reg.y1 = grid.height();
}
void Terrain::setMidFocus()
{
int dx, dy;
float sx, sy;
getGridDim(dx, dy);
getTerrainDim(sx, sy);
if(dx > 0 && dy > 0)
setFocus(vpPoint(sx/2.0f, grid[dy/2-1][dx/2-1], sy/2.0f));
else
setFocus(vpPoint(0.0f, 0.0f, 0.0f));
}
void Terrain::getMidPoint(vpPoint & mid)
{
int dx, dy;
float sx, sy;
getGridDim(dx, dy);
getTerrainDim(sx, sy);
if(dx > 0 && dy > 0)
mid = vpPoint(sx/2.0f, grid[dy/2-1][dx/2-1], sy/2.0f);
else
mid = vpPoint(0.0f, 0.0f, 0.0f);
}
void Terrain::getGridDim(int & dx, int & dy) const
{
dx = grid.width();
dy = grid.height();
}
void Terrain::getGridDim(uint & dx, uint & dy)
{
dx = (uint) grid.width();
dy = (uint) grid.height();
}
void Terrain::getTerrainDim(float &tx, float &ty) const
{
tx = dimx; ty = dimy;
}
void Terrain::setTerrainDim(float tx, float ty)
{
int gx, gy;
getGridDim(gx, gy);
dimx = tx; dimy = ty;
// calc allowable synth border
synthx = (0.5f / (float) (gx-1) + pluszero) * dimx;
synthy = (0.5f / (float) (gy-1) + pluszero) * dimy;
}
float Terrain::samplingDist()
{
int dx, dy;
float tx, ty;
getGridDim(dx, dy);
getTerrainDim(tx, ty);
return (0.5f * std::min(tx, ty)) / (float) (std::max(dx,dy)-1); // separation between vertices, about 2-3 vertices per grid cell
}
float Terrain::smoothingDist()
{
return 30.0f * samplingDist(); // about 10 grid points per curve segment
}
float Terrain::longEdgeDist()
{
float tx, ty;
getTerrainDim(tx, ty);
return std::max(tx, ty);
}
const float * Terrain::getGridData(int & dx, int & dy)
{
int i, j;
getGridDim(dx, dy);
if(scaleOn)
{
scaledgrid.allocate(Region(0, 0, grid.width(), grid.height()));
for(j = 0; j < grid.height(); j++)
for(i = 0; i < grid.width(); i++)
scaledgrid[j][i] = grid[j][i] * scfac;
return scaledgrid.get();
}
else
{
return grid.get();
}
}
float Terrain::getHeight(int x, int y)
{
return grid[x][y];
}
float Terrain::getFlatHeight(int idx)
{
int x, y, dx, dy;
getGridDim(dx, dy);
x = idx % dx;
y = idx / dx;
return grid[x][y];
}
float Terrain::getHeightFromReal(float x, float y)
{
int gx, gy;
toGrid(vpPoint(x, 0, y), gx, gy);
return grid[gx][gy];
}
void Terrain::getNormal(int x, int y, Vector & norm)
{
vpPoint x1, x2, y1, y2;
int dx, dy;
Vector dfdx, dfdy;
getGridDim(dx, dy);
// x-positions
if(x > 0)
x1 = toWorld(x-1, y, getHeight(x-1, y));
else
x1 = toWorld(x, y, getHeight(x, y));
if(x < dx-1)
x2 = toWorld(x+1, y, getHeight(x+1, y));
else
x2 = toWorld(x, y, getHeight(x, y));
// y-positions
if(y > 0)
y1 = toWorld(x, y-1, getHeight(x, y-1));
else
y1 = toWorld(x, y, getHeight(x, y));
if(y < dy-1)
y2 = toWorld(x, y+1, getHeight(x, y+1));
else
y2 = toWorld(x, y, getHeight(x, y));
// cross pattern
dfdx.diff(x1, x2);
dfdy.diff(y1, y2);
dfdx.normalize();
dfdy.normalize();
norm.cross(dfdx, dfdy);
norm.mult(-1.0f); // JGBUG - may be wrong direction
norm.normalize();
}
float Terrain::getCellExtent()
{
return dimx / (float) grid.width();
}
void Terrain::updateBuffers(PMrender::TRenderer * renderer) const
{
const int width = grid.width();
const int height = grid.height();
float scx, scy;
getTerrainDim(scx, scy);
glewExperimental = GL_TRUE;
if(!glewSetupDone)
{
GLenum err = glewInit();
if (GLEW_OK != err)
{
std::cerr<< "GLEW: initialization failed\n\n";
}
glewSetupDone = true;
}
if (bufferState == BufferState::REALLOCATE || bufferState == BufferState::DIRTY )
renderer->updateHeightMap(width, height, scx, scy, (GLfloat*)grid.get(), true);
else
renderer->updateHeightMap(width, height, scx, scy, (GLfloat*)grid.get());
bufferState = BufferState::CLEAN;
}
void Terrain::draw(View * view, PMrender::TRenderer *renderer) const
{
updateBuffers(renderer);
// call draw function
renderer->draw(view);
}
void Terrain::buildSphereAccel()
{
int si, sj, i, j, imin, imax, jmin, jmax;
float rad, sqlen;
vpPoint p, c, b1, b2;
Vector del;
// cerr << "numspx = " << numspx << ", numspy = " << numspy << endl;
for(si = 0; si < numspx; si++)
for(sj = 0; sj < numspy; sj++)
{
imin = si*spherestep; imax = std::min(imin+spherestep, grid.width());
jmin = sj*spherestep; jmax = std::min(jmin+spherestep, grid.height());
// cerr << "(" << si << ", " << sj << ") = " << "i: " << imin << " - " << imax << " j: " << jmin << " - " << jmax << endl;
// center point
b1 = toWorld(imin, jmin, grid[jmin][imin]);
b2 = toWorld(imax, jmax, grid[jmax-1][imax-1]);
c.affinecombine(0.5f, b1, 0.5f, b2);
// update radius
rad = 0.0f;
for(j = jmin; j < jmax; j++)
for(i = imin; i < imax; i++)
{
p = toWorld(i, j, grid[j][i]);
del.diff(c, p);
sqlen = del.sqrdlength();
if(sqlen > rad)
rad = sqlen;
}
boundspheres[si][sj].center = c;
boundspheres[si][sj].radius = sqrtf(rad);
}
accelValid = true;
}
bool Terrain::rayIntersect(vpPoint start, Vector dirn, vpPoint & p)
{
int i, j, si, sj, imin, imax, jmin, jmax;
vpPoint currp;
float besttval, tval, dist;
bool found = false;
float tol = dimx / (float) (grid.width()-1); // set world space detection tolerance to approx half gap between grid points
besttval = 100000000.0f;
if(!accelValid)
buildSphereAccel();
// bounding sphere accel structure
for(si = 0; si < numspx; si++)
for(sj = 0; sj < numspy; sj++)
{
rayPointDist(start, dirn, boundspheres[si][sj].center, tval, dist);
if(dist <= boundspheres[si][sj].radius) // intersects enclosing sphere so test enclosed points
{
imin = si*spherestep; imax = std::min(imin+spherestep, grid.width());
jmin = sj*spherestep; jmax = std::min(jmin+spherestep, grid.height());
// check ray against grid points
for(j = jmin; j < jmax; j++)
for(i = imin; i < imax; i++)
{
currp = toWorld(i, j, grid[j][i]);
rayPointDist(start, dirn, currp, tval, dist);
if(dist < tol)
{
found = true;
if(tval < besttval)
{
besttval = tval;
p = currp;
}
}
}
}
}
return found;
}
bool Terrain::pick(int sx, int sy, View * view, vpPoint & p)
{
vpPoint start;
Vector dirn;
cerr << "sx = " << sx << ", sy = " << sy << endl;
// find ray params from viewpoint through screen <sx, sy>
view->projectingRay(sx, sy, start, dirn);
return rayIntersect(start, dirn, p);
}
bool Terrain::drapePnt(vpPoint pnt, vpPoint & drape)
{
float x, y, h, drapeh, u, v, h0, h1, ux, uy;
int cx, cy, dx, dy;
getGridDim(dx, dy);
toGrid(pnt, x, y, h); // locate point on base domain
// test whether point is in bounds
ux = (float) (dx-1) - pluszero;
uy = (float) (dy-1) - pluszero;
if(x < pluszero || y < pluszero || x > ux || y > uy)
return false;
// index of grid cell
cx = (int) floor(x);
cy = (int) floor(y);
// get parametric coordinates within grid cell
u = (x - (float) cx);
v = (y - (float) cy);
// bilinear interpolation
h0 = (1.0f - u) * grid[cy][cx] + u * grid[cy][cx+1];
h1 = (1.0f - u) * grid[cy+1][cx] + u * grid[cy+1][cx];
drapeh = (1.0f - v) * h0 + v * h1;
// this could be implemented using ray-triangle intersection
// but it would be much less efficient
drape = toWorld(x, y, drapeh);
return true;
}
void Terrain::loadTer(const uts::string &filename)
{
float sx, sy, step;
int dx, dy;
grid.read(filename);
dx = grid.width(); dy = grid.height();
step = grid.step();
sx = (float) grid.width() * step;
sy = (float) grid.height() * step;
init(dx, dy, sx, sy);
}
void Terrain::loadElv(const uts::string &filename)
{
float step, lat;
int dx, dy;
float val;
ifstream infile;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> dx >> dy;
infile >> step;
infile >> lat;
delGrid();
init(dx, dy, (float) dx * step, (float) dy * step);
latitude = lat;
for (int y = 0; y < dy; y++)
{
for (int x = 0; x < dx; x++)
{
infile >> val;
grid[x][y] = val * 0.3048f; // convert from feet to metres
}
}
setMidFocus();
infile.close();
}
else
{
cerr << "Error Terrain::loadElv:unable to open file " << filename << endl;
}
}
void Terrain::loadPng(const uts::string &filename)
{
int width, height;
auto png_data = get_image_data_48bit(filename, width, height);
if (png_data.size() == 0)
{
cerr << "Error Terrain::loadPng: unable to open file " << filename << endl;
return;
}
// we assume that the heightfield is a grayscale image, so the first channel will contain the necessary height info
std::vector<float> heights = png_data[0];
float vert_units = 0.3048f;
float horiz_units = vert_units * 3;
delGrid(); // not sure why I have to do this - just saw it is being done in loadElv (investigate why)
init(width, height, (float) width * horiz_units, (float) height * horiz_units);
latitude = 0.0f; // keeping it like this for now - maybe separate latitude and terrain loading??
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// the png is imported in row-major order
int idx = y * width + x;
grid[x][y] = heights[idx] * vert_units;
}
}
setMidFocus(); // again, not really sure why I have to do this, but keep it for now
}
void Terrain::saveTer(const uts::string &filename)
{
grid.write(filename);
}
void Terrain::saveElv(const uts::string &filename, float unit)
{
float step;
int gx, gy;
float val;
ofstream outfile;
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
getGridDim(gx, gy);
step = grid.step();
std::cout << "Step size: " << step << std::endl;
outfile << gx << " " << gy << " " << step << " " << latitude << endl;
for (int x = 0; x < gx; x++)
{
for (int y = 0; y < gy; y++)
{
outfile << grid[x][y] / unit << " ";
}
outfile << endl;
}
outfile << endl;
outfile.close();
}
else
{
cerr << "Error Terrain::loadElv:unable to open file " << filename << endl;
}
}
void Terrain::calcMeanHeight()
{
int i, j, cnt = 0;
hghtmean = 0.0f;
for(j = 0; j < grid.height(); j++)
for(i = 0; i < grid.width(); i++)
{
hghtmean += grid[j][i];
cnt++;
}
hghtmean /= (float) cnt;
}
void Terrain::getHeightBounds(float &minh, float &maxh)
{
int i, j;
float hght;
maxh = -10000000.0f;
minh = 100000000.0;
for(j = 0; j < grid.height(); j++)
for(i = 0; i < grid.width(); i++)
{
hght = grid[j][i];
if(hght < minh)
minh = hght;
if(hght > maxh)
maxh = hght;
}
}
| 16,751
|
C++
|
.cpp
| 556
| 24.001799
| 134
| 0.555832
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,224
|
pft.cpp
|
jgain_EcoLearn/EcoSynth/viewer/pft.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected]) and K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
// #include <fstream>
#include "pft.h"
#include "data_importer/data_importer.h"
////
// Viability
///
float Viability::eval(float val)
{
if(val < o1)
return -1.0f;
else if(val < z1)
return -1.0f + (val-o1) / (z1-o1);
else if(val < i1)
return (val-z1) / (i1-z1);
else if(val < i2)
return 1.0f;
else if(val < z2)
return (z2-val) / (z2-i2);
else if(val < o2)
return -1.0f + (o2-val) / (o2-z2);
else
return -1.0f;
}
////
// Biome
///
void Biome::categoryNameLookup(int idx, std::string &catName)
{
if(idx >= 1 && idx <= (int) catTable.size())
catName = catTable[idx-1]; // categories start at 1, whereas table is indexed from 0
else
catName = "OutOfCategoryTableRange";
}
float Biome::viability(int pft, float sunlight, float moisture, float temperature, float slope)
{
float val[4], vmin;
val[0] = pftypes[pft].sun.eval(sunlight);
val[1] = pftypes[pft].wet.eval(moisture);
val[2] = pftypes[pft].temp.eval(temperature);
val[3] = pftypes[pft].slope.eval(slope);
// the least satisfied resource dominates, so find min value
vmin = val[0];
for(int i = 1; i < 4; i++)
vmin = fmin(vmin, val[i]);
return vmin;
}
bool Biome::read_dataimporter(std::string cdata_fpath)
{
data_importer::common_data cdata = data_importer::common_data(cdata_fpath);
return read_dataimporter(cdata);
}
GLfloat *Biome::get_species_colour(int specid)
{
return pftypes.at(specid).basecol;
}
bool Biome::read_dataimporter(data_importer::common_data &cdata)
{
pftypes.clear();
PFType pft;
for (auto &sppair : cdata.canopy_and_under_species)
{
data_importer::species &spec = sppair.second;
pft.code = spec.name;
for (int i = 0; i < 4; i++)
pft.basecol[i] = spec.basecol[i];
pft.draw_hght = spec.draw_hght;
pft.draw_radius = spec.draw_radius;
pft.draw_box1 = spec.draw_box1;
pft.draw_box2 = spec.draw_box2;
switch (spec.shapetype)
{
case (data_importer::treeshape::BOX):
pft.shapetype = TreeShapeType::BOX;
break;
case (data_importer::treeshape::CONE):
pft.shapetype = TreeShapeType::CONE;
break;
case (data_importer::treeshape::SPHR):
pft.shapetype = TreeShapeType::SPHR;
break;
case (data_importer::treeshape::INVCONE):
pft.shapetype = TreeShapeType::INVCONE;
break;
default:
assert(false);
break;
}
pftypes.push_back(pft);
}
slopethresh = cdata.soil_info.slopethresh;
slopemax = cdata.soil_info.slopemax;
evaporation = cdata.soil_info.evap;
runofflevel = cdata.soil_info.runofflim;
soilsaturation = cdata.soil_info.soilsat;
waterlevel = cdata.soil_info.riverlevel;
return true;
}
bool Biome::read(const std::string &filename)
{
int nb, nc;
ifstream infile;
float o1, o2, z1, z2, i1, i2;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> name;
// plant functional types
infile >> nb; // number of pft
for(int t = 0; t < nb; t++)
{
PFType pft;
string shapestr;
infile >> pft.code >> pft.basecol[0] >> pft.basecol[1] >> pft.basecol[2] >> pft.draw_hght >> pft.draw_radius >> pft.draw_box1 >> pft.draw_box2;
infile >> shapestr;
if(shapestr == "SPHR")
pft.shapetype = TreeShapeType::SPHR;
else if(shapestr == "BOX")
pft.shapetype = TreeShapeType::BOX;
else if(shapestr == "CONE")
pft.shapetype = TreeShapeType::CONE;
else if (shapestr == "INVCONE")
pft.shapetype = TreeShapeType::INVCONE;
else
cerr << "Error Biome::read: malformed shape type" << endl;
pft.basecol[3] = 1.0f;
pftypes.push_back(pft);
// viability response values
infile >> o1 >> z1 >> i1 >> i2 >> z2 >> o2;
pft.sun.setValues(o1, o2, z1, z2, i1, i2);
infile >> o1 >> z1 >> i1 >> i2 >> z2 >> o2;
pft.wet.setValues(o1, o2, z1, z2, i1, i2);
infile >> o1 >> z1 >> i1 >> i2 >> z2 >> o2;
pft.temp.setValues(o1, o2, z1, z2, i1, i2);
infile >> o1 >> z1 >> i1 >> i2 >> z2 >> o2;
pft.slope.setValues(o1, o2, z1, z2, i1, i2);
//infile >> pft.alpha;
//infile >> pft.maxage;
//< growth parameters
/*
infile >> pft.grow_months;
infile >> pft.grow_m >> pft.grow_c1 >> pft.grow_c2;
//< allometry parameters
infile >> pft.alm_m >> pft.alm_c1;
infile >> pft.alm_rootmult;*/
}
// category names
infile >> nc; // number of categories
for(int c = 0; c < nc; c++)
{
std::string str;
infile >> str;
catTable.push_back(str);
}
// soil moisture parameters
infile >> slopethresh;
infile >> slopemax;
infile >> evaporation;
infile >> runofflevel;
infile >> soilsaturation;
infile >> waterlevel;
infile.close();
return true;
}
else
{
cerr << "Error Biome::read: unable to open file" << filename << endl;
return false;
}
}
bool Biome::write(const std::string &filename)
{
ofstream outfile;
float o1, o2, z1, z2, i1, i2;
outfile.open((char *) filename.c_str(), ios_base::out);
if(outfile.is_open())
{
outfile << name << endl;
// plant functional types
outfile << numPFTypes() << endl;
for (int t = 0; t < numPFTypes(); t++)
{
outfile << pftypes[t].code << " " << pftypes[t].basecol[0] << " " << pftypes[t].basecol[1] << " " << pftypes[t].basecol[2] << " ";
outfile << pftypes[t].draw_hght << " " << pftypes[t].draw_radius << " " << pftypes[t].draw_box1 << " " << pftypes[t].draw_box2 << " ";
switch(pftypes[t].shapetype)
{
case TreeShapeType::SPHR:
outfile << "SPHR";
break;
case TreeShapeType::BOX:
outfile << "BOX";
break;
case TreeShapeType::CONE:
outfile << "CONE";
break;
case TreeShapeType::INVCONE:
outfile << "INVCONE";
break;
}
outfile << endl;
// viability response values
pftypes[t].sun.getValues(o1, o2, z1, z2, i1, i2);
outfile << o1 << " " << z1 << " " << i1 << " " << i2 << " " << z2 << " " << o2 << " ";
pftypes[t].wet.getValues(o1, o2, z1, z2, i1, i2);
outfile << o1 << " " << z1 << " " << i1 << " " << i2 << " " << z2 << " " << o2 << " ";
pftypes[t].temp.getValues(o1, o2, z1, z2, i1, i2);
outfile << o1 << " " << z1 << " " << i1 << " " << i2 << " " << z2 << " " << o2 << " ";
pftypes[t].slope.getValues(o1, o2, z1, z2, i1, i2);
outfile << o1 << " " << z1 << " " << i1 << " " << i2 << " " << z2 << " " << o2 << " ";
outfile << pftypes[t].alpha << " " << pftypes[t].maxage << endl;
//< growth parameters
/*
outfile << pftypes[t].grow_months << " ";
outfile << pftypes[t].grow_m << " " << pftypes[t].grow_c1 << " " << pftypes[t].grow_c2 << " ";
//< allometry parameters
outfile << pftypes[t].alm_m << " " << pftypes[t].alm_c1 << " ";
outfile << pftypes[t].alm_rootmult << endl;*/
}
// category names
outfile << (int) catTable.size() << endl;
for(int c = 0; c < (int) catTable.size(); c++)
outfile << catTable[c] << endl;
// soil moisture parameters
outfile << slopethresh << " ";
outfile << slopemax << " ";
outfile << evaporation << " ";
outfile << runofflevel << " ";
outfile << soilsaturation << " ";
outfile << waterlevel << endl;
outfile.close();
return true;
}
else
{
cerr << "Error Biome::write: unable to open file " << filename << endl;
return false;
}
}
| 9,571
|
C++
|
.cpp
| 260
| 28.407692
| 155
| 0.526089
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,226
|
shape.cpp
|
jgain_EcoLearn/EcoSynth/viewer/shape.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
// constraint.cpp:
// author: James Gain
// date: 5 November 2013
// 21 January 2013 - curve constraints
#include <GL/glew.h>
#include "shape.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
//
// Shape
//
void Shape::setColour(GLfloat * col)
{
int i;
for(i = 0; i < 4; i++)
diffuse[i] = col[i];
for(i = 0; i < 3; i++)
ambient[i] = diffuse[i] * 0.75f;
ambient[3] = diffuse[3];
for(i = 0; i < 3; i++)
specular[i] = std::min(1.0f, diffuse[i] * 1.25f);
specular[3] = diffuse[3];
}
std::vector<GLuint> Shape::getModelTextures()
{
return modelTextures;
}
void Shape::genCylinder(float radius, float height, int slices, int stacks, glm::mat4x4 trm)
{
int i, j, base;
float a, x, y, h = 0.0f;
float stepa = PI2 / (float) slices;
float stepz = height / (float) stacks;
glm::vec4 p;
glm::vec3 v;
base = int(verts.size()) / 8;
for(i = 0; i <= stacks; i++)
{
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, h, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(x, y, 0.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
if(i > 0)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base+j);
indices.push_back(base-slices+j+1); indices.push_back(base+j+1); indices.push_back(base+j);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base+j);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+j);
}
}
a += stepa;
}
base += slices;
h += stepz;
}
}
void Shape::genCappedCylinder(float startradius, float endradius, float height, int slices, int stacks, glm::mat4x4 trm, bool clip)
{
int i, j, base;
float a, x, y, h = 0.0f, radius;
float stepa = PI2 / (float) slices;
float stepz = height / (float) stacks;
float stepr = (endradius - startradius) / (float) (stacks);
glm::vec4 p;
glm::vec3 v;
base = int(verts.size()) / 8;
radius = startradius;
for(i = 0; i <= stacks; i++)
{
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, h, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(x, y, 0.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
if(i > 0)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base+j);
indices.push_back(base-slices+j+1); indices.push_back(base+j+1); indices.push_back(base+j);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base+j);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+j);
}
}
a += stepa;
}
base += slices;
h += stepz;
radius += stepr;
}
// cap base
// lid center and rim
p = trm * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, -1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a = 0.0f; radius = startradius;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, 0.0f, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, -1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a += stepa;
}
// face indices
base += slices;
for (j = 0; j < slices; j++)
{
if(j < slices-1)
{
indices.push_back(base-slices+j+1);indices.push_back(base-slices+j); indices.push_back(base);
}
else // wrap
{
indices.push_back(base-slices); indices.push_back(base-slices+j);indices.push_back(base);
}
}
base++;
// cap lid
// lid center and rim
p = trm * glm::vec4(0.0f, 0.0f, height, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, 1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a = 0.0f; radius = endradius;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, height, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, 1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a += stepa;
}
// face indices
base += slices;
for (j = 0; j < slices; j++)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base);
}
}
}
void Shape::genCappedCone(float startradius, float height, int slices, int stacks, glm::mat4x4 trm, bool clip)
{
int i, j, base;
float endradius = 0.001f;
float a, x, y, h = 0.0f, radius;
float stepa = PI2 / (float) slices;
float stepz = height / (float) stacks;
float stepr = (endradius - startradius) / (float) (stacks);
glm::vec4 p;
glm::vec3 v;
base = int(verts.size()) / 8;
radius = startradius;
for(i = 0; i <= stacks; i++)
{
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, h, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(x, y, 0.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
if(i > 0)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base+j);
indices.push_back(base-slices+j+1); indices.push_back(base+j+1); indices.push_back(base+j);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base+j);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+j);
}
}
a += stepa;
}
base += slices;
h += stepz;
radius += stepr;
}
// cap base
// lid center and rim
p = trm * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, -1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a = 0.0f; radius = startradius;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
// apply transformation
p = trm * glm::vec4(x, y, 0.0f, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(0.0f, 0.0f, -1.0f));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
a += stepa;
}
// face indices
base += slices;
for (j = 0; j < slices; j++)
{
if(j < slices-1)
{
indices.push_back(base-slices+j+1);indices.push_back(base-slices+j); indices.push_back(base);
}
else // wrap
{
indices.push_back(base-slices); indices.push_back(base-slices+j);indices.push_back(base);
}
}
}
void Shape::genPyramid(float baselen, float toplen, float height, glm::mat4x4 trm)
{
int i, base;
Vector v;
glm::vec4 p;
glm::vec3 n;
// base verts
vpPoint b[4];
b[0] = vpPoint(-baselen/2.0f, -baselen/2.0f, 0.0f);
b[1] = vpPoint(baselen/2.0f, -baselen/2.0f, 0.0f);
b[2] = vpPoint(baselen/2.0f, baselen/2.0f, 0.0f);
b[3] = vpPoint(-baselen/2.0f, baselen/2.0f, 0.0f);
// top verts
vpPoint t[4];
t[0] = vpPoint(-toplen/2.0f, -toplen/2.0f, height);
t[1] = vpPoint(toplen/2.0f, -toplen/2.0f, height);
t[2] = vpPoint(toplen/2.0f, toplen/2.0f, height);
t[3] = vpPoint(-toplen/2.0f, toplen/2.0f, height);
base = int(verts.size()) / 8;
// base vertices
v = Vector(0.0f, 0.0f, -1.0f);
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(b[i].x, b[i].y, b[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
// counterclockwise winding
indices.push_back(base+1); indices.push_back(base+0); indices.push_back(base+2);
indices.push_back(base+0); indices.push_back(base+3); indices.push_back(base+2);
base += 4;
// top vertices
v = Vector(0.0f, 0.0f, 1.0f);
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(t[i].x, t[i].y, t[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
indices.push_back(base+2); indices.push_back(base+0); indices.push_back(base+1);
indices.push_back(base+3); indices.push_back(base+0); indices.push_back(base+2);
base += 4;
// side vertices: -y
v = Vector(0.0f, -height, baselen-toplen);
v.normalize();
vpPoint s[4];
s[0] = b[0]; s[1] = b[1]; s[2] = t[1]; s[3] = t[0];
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(s[i].x, s[i].y, s[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
indices.push_back(base+2); indices.push_back(base+0); indices.push_back(base+1);
indices.push_back(base+3); indices.push_back(base+0); indices.push_back(base+2);
base += 4;
// side vertices: +y
v = Vector(0.0f, height, baselen-toplen);
v.normalize();
s[0] = b[2]; s[1] = b[3]; s[2] = t[3]; s[3] = t[2];
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(s[i].x, s[i].y, s[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
indices.push_back(base+2); indices.push_back(base+0); indices.push_back(base+1);
indices.push_back(base+3); indices.push_back(base+0); indices.push_back(base+2);
base += 4;
// side vertices: +x
v = Vector(height, 0.0f, baselen-toplen);
v.normalize();
s[0] = b[1]; s[1] = b[2]; s[2] = t[2]; s[3] = t[1];
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(s[i].x, s[i].y, s[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
indices.push_back(base+2); indices.push_back(base+0); indices.push_back(base+1);
indices.push_back(base+3); indices.push_back(base+0); indices.push_back(base+2);
base += 4;
// side vertices: -x
v = Vector(-height, 0.0f, baselen-toplen);
v.normalize();
s[0] = b[3]; s[1] = b[0]; s[2] = t[0]; s[3] = t[3];
for(i = 0; i < 4; i++)
{
p = trm * glm::vec4(s[i].x, s[i].y, s[i].z, 1.0f);
n = glm::mat3(trm) * glm::normalize(glm::vec3(v.i, v.j, v.k));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z);
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
}
indices.push_back(base+2); indices.push_back(base+0); indices.push_back(base+1);
indices.push_back(base+3); indices.push_back(base+0); indices.push_back(base+2);
base += 4;
}
void Shape::genSphereVert(float radius, float lat, float lon, glm::mat4x4 trm)
{
float la, lo, x, y, z;
glm::vec4 p;
glm::vec3 v;
la = PI+PI*lat;
lo = PI2*lon;
// this is unoptimized
x = cosf(lo)*sinf(la)*radius;
y = sinf(lo)*sinf(la)*radius;
z = cosf(la)*radius;
// apply transformation
p = trm * glm::vec4(x, y, z, 1.0f);
v = glm::mat3(trm) * glm::normalize(glm::vec3(x, y, z));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(v.x); verts.push_back(v.y); verts.push_back(v.z); // normal
}
void Shape::genSphere(float radius, int slices, int stacks, glm::mat4x4 trm)
{
int lat, lon, base;
float plat, plon;
// doesn't produce very evenly sized triangles, tend to cluster at poles
base = int(verts.size()) / 8;
for(lat = 0; lat <= stacks; lat++)
{
for(lon = 0; lon < slices; lon++)
{
plat = (float) lat / (float) stacks;
plon = (float) lon / (float) slices;
genSphereVert(radius, plat, plon, trm);
if(lat > 0)
{
if(lon < slices-1)
{
indices.push_back(base-slices+lon); indices.push_back(base-slices+lon+1); indices.push_back(base+lon);
indices.push_back(base-slices+lon+1); indices.push_back(base+lon+1); indices.push_back(base+lon);
}
else // wrap
{
indices.push_back(base-slices+lon); indices.push_back(base-slices); indices.push_back(base+lon);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+lon);
}
}
}
base += slices;
}
}
void Shape::genTest()
{
clear();
// single triangle
verts.push_back(-1.0f); verts.push_back(0.0f); verts.push_back(-1.0f); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(0.0f); verts.push_back(-1.0f); verts.push_back(0.0f); // normal
verts.push_back(-1.0f); verts.push_back(0.0f); verts.push_back(1.0f); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(0.0f); verts.push_back(-1.0f); verts.push_back(0.0f); // normal
verts.push_back(1.0f); verts.push_back(0.0f); verts.push_back(1.0f); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(0.0f); verts.push_back(-1.0f); verts.push_back(0.0f); // normal
indices.push_back(0);
indices.push_back(1);
indices.push_back(2);
}
void Shape::genCurve(std::vector<vpPoint> &curve, View * view, float thickness, float tol, bool closed, bool offset, bool viewadapt)
{
// Double the number of vertices actually required. Consider compacting later.
// This needs the view class because thickening happens orthogonal to the view direction
int i, j, lim, numv;
vpPoint s, e, p[4], m[4], os, oe, c;
Vector v, n, pv, pn, eye, negeye, off;
float width = thickness;
bool firstseg = true;
numv = int(verts.size()) / 8;
if((int) curve.size() > 0)
{
eye = view->getDir(); eye.normalize();
negeye = eye; negeye.mult(-1.0f); off = negeye; off.mult(0.005f);
//glBegin(GL_QUADS);
if(closed)
lim = (int) curve.size();
else
lim = (int) curve.size()-1;
s = curve[0];
for(i = 0; i < lim; i++)
{
// current segment
if(closed)
e = curve[(i+1)%lim];
else
e = curve[i+1];
if(offset) // shift points closer to the viewpoint
{
// shift higher above terrain
off = Vector(0.0f, 0.001f, 0.0f);
// c = view->getCOP();
// off.diff(os, c); off.normalize(); off.mult(0.001f);
off.pntplusvec(s, &os);
off.pntplusvec(e, &oe);
}
else
{
os = s; oe = e;
}
v.diff(os, oe);
if(v.length() > tol) // ignore points that are too close together
{
v.normalize();
// find vector orthogonal to segment but parallel to the viewing plane
n.cross(v, eye);
n.normalize();
if(viewadapt) // consider distance from viewpoint
{
// broken - fix if needed
c = view->getCOP();
off.diff(c, os);
n.mult(width * (65.0f * off.length()));
}
else
n.mult(width);
// construct line quad vertices
n.pntplusvec(oe, &p[1]);
n.pntplusvec(os, &p[0]);
n.mult(-1.0f);
n.pntplusvec(os, &p[3]);
n.pntplusvec(oe, &p[2]);
// find normal
n = negeye;
for(j = 0; j < 4; j++)
{
verts.push_back(p[j].x); verts.push_back(p[j].y); verts.push_back(p[j].z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.i); verts.push_back(n.j); verts.push_back(n.k); // normal
}
indices.push_back(numv+0); indices.push_back(numv+1); indices.push_back(numv+3);
indices.push_back(numv+2); indices.push_back(numv+3); indices.push_back(numv+1);
numv += 4;
// mitres to previous segment
if(firstseg)
{
if(closed)
{
// calculate thickening for closing the loop
s = curve[(int) curve.size()-1]; e = curve[0];
v.diff(os, oe);
v.normalize();
n.cross(v, eye);
n.normalize();
if(viewadapt)
{
c = view->getCOP();
off.diff(c, os);
n.mult(width * (65.0f * off.length()));
}
else
n.mult(width);
n.pntplusvec(os, &m[0]);
n.mult(-1.0f);
n.pntplusvec(os, &m[1]);
m[2] = p[0]; m[3] = p[3];
n = negeye;
for(j = 0; j < 4; j++)
{
verts.push_back(m[j].x); verts.push_back(m[j].y); verts.push_back(m[j].z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.i); verts.push_back(n.j); verts.push_back(n.k); // normal
}
indices.push_back(numv+0); indices.push_back(numv+1); indices.push_back(numv+3);
indices.push_back(numv+2); indices.push_back(numv+3); indices.push_back(numv+1);
numv += 4;
}
firstseg = false;
}
else
{
// m[1] and m[2] already stored from previous iteration
m[0] = p[0]; m[3] = p[3];
n = negeye;
verts.push_back(os.x); verts.push_back(os.y); verts.push_back(os.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.i); verts.push_back(n.j); verts.push_back(n.k); // normal
for(j = 0; j < 4; j++)
{
verts.push_back(m[j].x); verts.push_back(m[j].y); verts.push_back(m[j].z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.i); verts.push_back(n.j); verts.push_back(n.k); // normal
}
indices.push_back(numv+0); indices.push_back(numv+2); indices.push_back(numv+1);
indices.push_back(numv+0); indices.push_back(numv+4); indices.push_back(numv+3);
numv += 5;
}
m[1] = p[1];
m[2] = p[2];
s = e;
}
}
}
}
void Shape::genCylinderCurve(std::vector<vpPoint> &curve, float radius, float tol, int slices)
{
int i, j, lim, base;
vpPoint s, e;
Vector v, vfin, vstart, vrot;
glm::mat4x4 idt, tfm;
glm::vec3 trs, n, rot;
float angle, a, x, y, stepa = PI2 / (float) slices;
glm::vec4 p;
base = int(verts.size()) / 8;
if((int) curve.size() > 1)
{
lim = (int) curve.size()-1;
s = curve[0]; s.y += 0.05f;
for(i = 0; i < lim; i++)
{
e = curve[i+1]; e.y += 0.05f;
v.diff(s, e);
if(i == 0) // base stack
{
// translate to s
idt = glm::mat4(1.0f);
trs = glm::vec3(s.x, s.y, s.z);
tfm = glm::translate(idt, trs);
// azimuth rotation
vfin = v;
vfin.j = 0.0f; vfin.normalize();
angle = RAD2DEG * atan2(vfin.k, vfin.i);
if(angle < 0.0f)
angle += 360.0f;
rot = glm::vec3(0.0f, -1.0f, 0.0f);
tfm = glm::rotate(tfm, glm::radians(angle), rot);
// elevation rotation
/*
v.normalize();
rot = glm::vec3(-1.0f, 0.0f, 0.0f);
angle = RAD2DEG * acosf(v.dot(vfin));
tfm = glm::rotate(tfm, glm::radians(angle), rot);*/
// create cylinder from s to e
// genCylinder(radius, v.length(), slices, 1, tfm);
// single cylinder stack linking to previous stack as necessary
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
p = tfm * glm::vec4(0.0f, y, x, 1.0f);
n = glm::mat3(tfm) * glm::normalize(glm::vec3(0.0f, y, x));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
a -= stepa;
}
base += slices;
}
else
{
if(v.length() > tol || i == lim-1) // ignore points that are too close together, except for last segment
{
// translate to e
idt = glm::mat4(1.0f);
trs = glm::vec3(e.x, e.y, e.z);
tfm = glm::translate(idt, trs);
// azimuth rotation
vfin = v;
vfin.j = 0.0f; vfin.normalize();
angle = RAD2DEG * atan2(vfin.k, vfin.i);
if(angle < 0.0f)
angle += 360.0f;
rot = glm::vec3(0.0f, -1.0f, 0.0f);
tfm = glm::rotate(tfm, glm::radians(angle), rot);
// elevation rotation
/*
v.normalize();
rot = glm::vec3(-1.0f, 0.0f, 1.0f);
angle = RAD2DEG * acosf(v.dot(vfin));
tfm = glm::rotate(tfm, glm::radians(angle), rot);*/
// single cylinder stack linking to previous stack as necessary
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
p = tfm * glm::vec4(0.0f, y, x, 1.0f);
n = glm::mat3(tfm) * glm::normalize(glm::vec3(0.0f, y, x));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
if(i > 0)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base+j);
indices.push_back(base-slices+j+1); indices.push_back(base+j+1); indices.push_back(base+j);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base+j);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+j);
}
}
a -= stepa;
}
base += slices;
s = e;
}
}
}
}
}
void Shape::genDashedCylinderCurve(std::vector<vpPoint> &curve, float radius, float tol, float dashlen, int slices)
{
int i, j, lim, base;
vpPoint s, e;
Vector v, vfin, vstart, vrot;
glm::mat4x4 idt, tfm;
glm::vec3 trs, n, rot;
float angle, a, x, y, stepa = PI2 / (float) slices, dashaccum = 0.0f;
glm::vec4 p;
bool dashon = true;
base = int(verts.size()) / 8;
if((int) curve.size() > 1)
{
lim = (int) curve.size()-1;
s = curve[0]; s.y += 0.05f;
for(i = 0; i < lim; i++)
{
e = curve[i+1]; e.y += 0.05f;
v.diff(s, e);
if(i == 0) // base stack
{
// translate to s
idt = glm::mat4(1.0f);
trs = glm::vec3(s.x, s.y, s.z);
tfm = glm::translate(idt, trs);
// azimuth rotation
vfin = v;
vfin.j = 0.0f; vfin.normalize();
angle = RAD2DEG * atan2(vfin.k, vfin.i);
if(angle < 0.0f)
angle += 360.0f;
rot = glm::vec3(0.0f, -1.0f, 0.0f);
tfm = glm::rotate(tfm, glm::radians(angle), rot);
// single cylinder stack linking to subsequent stacks as necessary
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
p = tfm * glm::vec4(0.0f, y, x, 1.0f);
n = glm::mat3(tfm) * glm::normalize(glm::vec3(0.0f, y, x));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
a -= stepa;
}
base += slices;
}
else
{
if(v.length() > tol || i == lim-1) // ignore points that are too close together, except for last segment
{
dashaccum += v.length();
if(dashaccum >= dashlen) // toggle whether or not to draw dash
{
dashon = !dashon;
dashaccum = 0.0f;
}
// TO DO: cap cylinder
// translate to e
idt = glm::mat4(1.0f);
trs = glm::vec3(e.x, e.y, e.z);
tfm = glm::translate(idt, trs);
// azimuth rotation
vfin = v;
vfin.j = 0.0f; vfin.normalize();
angle = RAD2DEG * atan2(vfin.k, vfin.i);
if(angle < 0.0f)
angle += 360.0f;
rot = glm::vec3(0.0f, -1.0f, 0.0f);
tfm = glm::rotate(tfm, glm::radians(angle), rot);
// elevation rotation
/*
v.normalize();
rot = glm::vec3(-1.0f, 0.0f, 1.0f);
angle = RAD2DEG * acosf(v.dot(vfin));
tfm = glm::rotate(tfm, angle, rot);*/
// single cylinder stack linking to previous stack as necessary
a = 0.0f;
for (j = 0; j < slices; j++)
{
x = cosf(a) * radius;
y = sinf(a) * radius;
p = tfm * glm::vec4(0.0f, y, x, 1.0f);
n = glm::mat3(tfm) * glm::normalize(glm::vec3(0.0f, y, x));
verts.push_back(p.x); verts.push_back(p.y); verts.push_back(p.z); // position
verts.push_back(0.0f); verts.push_back(0.0f); // texture coordinates
verts.push_back(n.x); verts.push_back(n.y); verts.push_back(n.z); // normal
if(i > 0 && dashon)
{
if(j < slices-1)
{
indices.push_back(base-slices+j); indices.push_back(base-slices+j+1);indices.push_back(base+j);
indices.push_back(base-slices+j+1); indices.push_back(base+j+1); indices.push_back(base+j);
}
else // wrap
{
indices.push_back(base-slices+j); indices.push_back(base-slices); indices.push_back(base+j);
indices.push_back(base-slices); indices.push_back(base); indices.push_back(base+j);
}
}
a -= stepa;
}
base += slices;
s = e;
}
}
}
}
}
void Shape::genSphereCurve(std::vector<vpPoint> &curve, float thickness)
{
int i;
glm::mat4 tfm, idt;
glm::vec3 trs;
// assume view transformations are set up correctly
if((int) curve.size() > 0)
{
for(i = 0; i < (int) curve.size(); i++)
{
idt = glm::mat4(1.0f);
trs = glm::vec3(curve[i].x, curve[i].y, curve[i].z);
tfm = glm::translate(idt, trs);
genSphere(thickness, 10, 10, tfm);
}
}
}
ShapeDrawData Shape::getDrawParameters()
{
ShapeDrawData sdd;
sdd.VAO = vaoConstraint;
for(int i = 0; i < 4; i++)
sdd.diffuse[i] = diffuse[i];
for(int i = 0; i < 4; i++)
sdd.specular[i] = specular[i];
for(int i = 0; i < 4; i++)
sdd.ambient[i] = ambient[i];
sdd.indexBufSize = (int) indices.size();
sdd.numInstances = numInstances;
sdd.texID = 0;
sdd.current = false; // default setting
sdd.textures = modelTextures;
sdd.brush = brush;
return sdd;
}
void Shape::setBrush(bool isbrush)
{
brush = isbrush;
}
bool Shape::bindInstances(View * view, std::vector<glm::mat4> * iforms, std::vector<glm::vec4> * icols)
{
if((int) indices.size() > 0 && ((int) iforms->size() == (int) icols->size()))
{
if (vboConstraint != 0)
{
glDeleteVertexArrays(1, &vaoConstraint);
glDeleteBuffers(1, &vboConstraint);
glDeleteBuffers(1, &iboConstraint);
glDeleteBuffers(1, &iBuffer);
glDeleteBuffers(1, &cBuffer);
glDeleteBuffers(1, &texidBuffer);
vaoConstraint = 0;
vboConstraint = 0;
iboConstraint = 0;
iBuffer = 0;
cBuffer = 0;
}
// vao
glGenVertexArrays(1, &vaoConstraint);
glBindVertexArray(vaoConstraint);
// vbo
// set up vertex buffer and copy in data
glGenBuffers(1, &vboConstraint);
glBindBuffer(GL_ARRAY_BUFFER, vboConstraint);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*(int) verts.size(), (GLfloat *) &verts[0], GL_STATIC_DRAW);
// ibo
glGenBuffers(1, &iboConstraint);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboConstraint);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*(int) indices.size(), (GLuint *) &indices[0], GL_STATIC_DRAW);
// enable position attribute
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), (void*)(0));
// enable texture coord attribute
const int sz = 3*sizeof(GLfloat);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), (void*)(sz) );
// enable normals
const int nz = 5*sizeof(GLfloat);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), (void*)(nz) );
// we need a full mat4 because the plant dimensions (non-uniform scale) as well as position are being instanced
glGenBuffers(1, &iBuffer); // create a vertex buffer object for plant transform instancing
glBindBuffer(GL_ARRAY_BUFFER, iBuffer);
if((int) iforms->size() > 0) // load instance data
{
numInstances = (int) iforms->size();
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::mat4) * numInstances, (GLfloat *) & (* iforms)[0], GL_DYNAMIC_DRAW);
}
else // create a single instance
{
numInstances = 1;
std::vector<glm::mat4> tmpform;
glm::mat4 idt = glm::mat4(1.0f);
tmpform.push_back(idt);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::mat4) * numInstances, (GLfloat *) &tmpform[0], GL_DYNAMIC_DRAW);
}
glBindBuffer(GL_ARRAY_BUFFER, iBuffer);
for (unsigned int i = 0; i < 4 ; i++) {
glEnableVertexAttribArray(3 + i);
glVertexAttribPointer(3 + i, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4),
(const GLvoid*)(sizeof(GLfloat) * i * 4));
glVertexAttribDivisor(3 + i, 1);
}
glGenBuffers(1, &cBuffer); // create a vertex buffer object for plant colour instancing
glBindBuffer(GL_ARRAY_BUFFER, cBuffer);
// colour buffer to allow subtle variations in plant colour
if((int) icols->size() > 0)
{
numInstances = (int) icols->size();
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4) * numInstances, (GLfloat *) & (* icols)[0], GL_DYNAMIC_DRAW);
}
else // a single colour instance, with no change to the underlying colour
{
numInstances = 1;
std::vector<glm::vec4> tmpcol;
glm::vec4 idt = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
tmpcol.push_back(idt);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4) * numInstances, (GLfloat *) &tmpcol[0], GL_DYNAMIC_DRAW);
}
glBindBuffer(GL_ARRAY_BUFFER, cBuffer);
glEnableVertexAttribArray(7);
glVertexAttribPointer(7, 4, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)0); // stride may need adjusting here
// glVertexAttribPointer(7, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), (const GLvoid*)0);
glVertexAttribDivisor(7, 1);
glGenBuffers(1, &texidBuffer);
glBindBuffer(GL_ARRAY_BUFFER, texidBuffer);
if (texidxes.size() > 0)
glBufferData(GL_ARRAY_BUFFER, sizeof(GLuint) * texidxes.size(), (GLint*)texidxes.data(), GL_DYNAMIC_DRAW);
else
{
texidxes = std::vector<int>(numInstances, -1);
glBufferData(GL_ARRAY_BUFFER, sizeof(int) * numInstances, (int *)texidxes.data(), GL_DYNAMIC_DRAW);
}
glEnableVertexAttribArray(8);
glVertexAttribIPointer(8, 1, GL_INT, 0, (const GLvoid *)0);
//glVertexAttribDivisor(8, 1);
glBindVertexArray(0);
return true;
}
else
{
return false;
}
}
| 40,462
|
C++
|
.cpp
| 947
| 30.99472
| 132
| 0.504978
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,227
|
specselect_window.cpp
|
jgain_EcoLearn/EcoSynth/viewer/specselect_window.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "specselect_window.h"
#include "window.h"
#include <QVBoxLayout>
specselect_window::specselect_window(data_importer::common_data cdata, Window *parent)
: QWidget(parent, Qt::Window)
{
auto allspecs = cdata.all_species;
QVBoxLayout *lyout = new QVBoxLayout();
for (auto &p : allspecs)
{
int specid = p.first;
cboxes[specid] = new QCheckBox(QString::fromStdString(std::to_string(specid)));
cboxes[specid]->setChecked(true);
connect(cboxes[specid], &QCheckBox::stateChanged, this, &specselect_window::statechanged);
lyout->addWidget(cboxes[specid]);
}
this->setLayout(lyout);
connect(this, &specselect_window::species_added, parent, &Window::species_added);
connect(this, &specselect_window::species_removed, parent, &Window::species_removed);
}
specselect_window::specselect_window(string dbname, Window *parent)
: specselect_window(data_importer::common_data(dbname), parent)
{
}
void specselect_window::add_widget(QWidget *w)
{
this->layout()->addWidget(w);
}
void specselect_window::statechanged(int state)
{
QCheckBox *sender = dynamic_cast<QCheckBox *>(QObject::sender());
assert(sender);
Qt::CheckState chst = (Qt::CheckState)state;
if (chst == Qt::Checked)
{
for (auto &p : cboxes)
{
int id = p.first;
if (p.second == sender)
{
species_added(id);
return;
}
}
}
else if (chst == Qt::Unchecked)
{
for (auto &p : cboxes)
{
int id = p.first;
if (p.second == sender)
{
species_removed(id);
return;
}
}
}
else
{
assert(false);
}
}
void specselect_window::disable()
{
for (auto &p : cboxes)
{
QCheckBox *b = p.second;
b->setEnabled(false);
}
}
void specselect_window::enable()
{
for (auto &p : cboxes)
{
QCheckBox *b = p.second;
b->setEnabled(true);
}
}
| 3,020
|
C++
|
.cpp
| 97
| 25.649485
| 98
| 0.604467
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,228
|
fill.cpp
|
jgain_EcoLearn/EcoSynth/viewer/fill.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 J.E. Gain ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
/* file: fill.cpp
author: (c) James Gain, 2009
project: ScapeSketch - sketch-based design of procedural landscapes
notes: scan-line polygon fill
changes:
*/
#include "fill.h"
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <list>
//////////////////////////////
/// SCAN-LINE POLYGON FILL ///
/// UNATTRIBUTED FROM WEB ////
//////////////////////////////
struct intPoint
{
int x,y;
};
class intPointArray
{
public:
std::vector<intPoint> pt;
};
class Node
{
public:
Node():yUpper(-500),xIntersect(-500.0),dxPerScan(0.0){ };
int yUpper;
float xIntersect,dxPerScan;
};
class EdgeTbl
{
public:
void buildTable (const intPointArray &, int, int);
int yNext (int, std::vector<intPoint>);
void makeEdgeRecord (intPoint,intPoint,int);
std::vector<std::list<Node> > Edges;
};
/// EDGE TABLE METHODS ///
void insertEdge (std::list<Node>& orderedList, const Node& item)
{
std::list<Node>::iterator curr = orderedList.begin(), stop = orderedList.end();
while ((curr != stop) && ((*curr).xIntersect < item.xIntersect))
curr++;
orderedList.insert(curr,item);
}
int EdgeTbl::yNext (int k, std::vector<intPoint> p)
{
int j;
// next subscript in polygon
if ((k+1) > ((int) p.size()-1))
j = 0;
else
j = k+1;
while (p[k].y == p[j].y)
if ((j+1) > ((int) p.size()-1))
j = 0;
else
j++;
return (p[j].y);
}
void EdgeTbl::makeEdgeRecord (intPoint lower, intPoint upper, int yComp)
{
Node n;
n.dxPerScan = (float)(upper.x-lower.x)/(upper.y-lower.y);
n.xIntersect = lower.x;
if (upper.y < yComp) // edge shortening for non-extrema
n.yUpper = upper.y-1;
else
n.yUpper = upper.y;
// clip to lower edge
if(lower.y < 0)
{
n.xIntersect = lower.x + n.dxPerScan * (0-lower.y);
lower.y = 0;
}
insertEdge (Edges[lower.y],n);
}
void EdgeTbl::buildTable (const intPointArray& Poly, int dimx, int dimy)
{
intPoint v1,v2;
int i, yPrev;
// cerr << "poly size = " << (int) Poly.pt.size() << endl;
// cerr << "dimx = " << dimx << endl;
// cerr << "dimy = " << dimy << endl;
yPrev = Poly.pt[Poly.pt.size()-2].y;
v1.x = Poly.pt[Poly.pt.size()-1].x;
v1.y = Poly.pt[Poly.pt.size()-1].y;
for (i = 0; i < (int) Poly.pt.size(); i++)
{
// cerr << "i = " << i << endl;
v2 = Poly.pt[i];
if (v1.y != v2.y)
{
// if(v1.y < 0 ||
// check to see if outside bounds of map above and below
if(!((v1.y < 0 && v2.y < 0) || (v1.y > dimy-1 && v2.y > dimy-1)))
{
// non horizontal edge
if (v1.y < v2.y)
makeEdgeRecord (v1,v2,yNext(i,Poly.pt)); //up edge
else
makeEdgeRecord (v2,v1,yPrev); // down edge
yPrev = v1.y;
}
}
v1 = v2;
}
}
/// AEL ROUTINES ///
void buildAEL (std::list<Node> &AEL, std::list<Node> ET)
{
std::list<Node>::iterator iter;
iter = ET.begin();
// every Edge table list has a "empty" node at front
iter++;
while (iter != ET.end())
{
insertEdge (AEL,*iter);
iter++;
}
}
void fillScan (int y, std::list<Node> L, Terrain * ter, TypeMap * tmap, int brushtype)
{
int dimx, dimy;
// want to pull off pairs of x values from adjacent
// nodes in the list - the y value = scan line
std::list<Node>::iterator iter1 = L.begin(), iter2;
int x1, x2, i;
ter->getGridDim(dimx, dimy);
while (iter1 != L.end())
{
iter2 = iter1;
iter2++;
x1 = (int)(*iter1).xIntersect;
x2 = (int)(*iter2).xIntersect;
// allow for drawing outside the map bounds to left and right
if(x1 < 0) x1 = 0;
if(x2 > dimx - 1) x2 = dimx-1;
for(i = x1; i <= x2; i++)
(* tmap->getMap())[y][i] = brushtype;
// move on to next pair of nodes
iter1 = iter2;
iter1++;
}
}
void fillMaskScan (int y, std::list<Node> L, Terrain * ter, MemMap<bool> * mask)
{
int dimx, dimy;
// want to pull off pairs of x values from adjacent
// nodes in the list - the y value = scan line
std::list<Node>::iterator iter1 = L.begin(), iter2;
int x1, x2, i;
ter->getGridDim(dimx, dimy);
while (iter1 != L.end())
{
iter2 = iter1;
iter2++;
x1 = (int)(*iter1).xIntersect;
x2 = (int)(*iter2).xIntersect;
// allow for drawing outside the map bounds to left and right
if(x1 < 0) x1 = 0;
if(x2 > dimx - 1) x2 = dimx-1;
for(i = x1; i <= x2; i++)
(* mask)[y][i] = true;
// move on to next pair of nodes
iter1 = iter2;
iter1++;
}
}
void updateAEL (int y, std::list<Node>& L)
{
// delete completed edges
// update the xIntersect field
std::list<Node>::iterator iter = L.begin();
while (iter != L.end())
if (y >= (*iter).yUpper)
L.erase(iter++);
else
{
(*iter).xIntersect += (*iter).dxPerScan;
iter++;
}
}
void resortAEL (std::list<Node>& L)
{
Node n;
std::list<Node> L1;
std::list<Node>::iterator iter = L.begin();
// create a new list from the old
// note that the sort command for a list would
// need us to overload the comparisons operators in the
// Node class. This is probably just as simple
while (iter != L.end())
{
insertEdge (L1,*iter);
L.erase(iter++);
}
L = L1;
}
void scanLoopFill(std::vector<vpPoint> * loop, Terrain * ter, TypeMap * tmap, int brushtype)
{
std::vector<int> x, y;
int i, j, k;
EdgeTbl EdgeTable;
std::list<Node> AEL;
intPoint pnt, prev;
intPointArray P;
bool hori = false;
std::list<Node> EmptyList; // an empty list
Node EmptyNode; // an empty node
int dimx, dimy;
ter->getGridDim(dimx, dimy);
for(k = 0; k < (int) loop->size(); k++)
{
ter->toGrid((* loop)[k], i, j);
x.push_back(i);
y.push_back(j);
}
for(i = 0; i < (int) x.size(); i++)
{
pnt.x = (GLint) x[i];
pnt.y = (GLint) y[i];
if(i==0) // no vertices yet
{
P.pt.push_back(pnt);
}
else
{
if(!(pnt.x == P.pt.back().x && pnt.y == P.pt.back().y)) // skip over duplicates
{
if(pnt.y == P.pt.back().y) // skip intermediate points on horizontal edge
{
hori = true;
}
else
{
if(hori) // go back and push the last point on the horizontal edge
{
prev.x = (GLint) x[i-1];
prev.y = (GLint) y[i-1];
P.pt.push_back(prev);
hori = false;
}
P.pt.push_back(pnt);
}
}
}
}
EmptyList.push_front(EmptyNode); // an empty list
// build the edge table - need the window size
for (i = 0; i < dimy; i++)
EdgeTable.Edges.push_back(EmptyList);
EdgeTable.buildTable(P, dimx, dimy);
for (int scanLine = 0; scanLine < dimy; scanLine++)
{
buildAEL (AEL,EdgeTable.Edges[scanLine]);
if (!AEL.empty())
{
fillScan(scanLine,AEL,ter,tmap,brushtype);
updateAEL (scanLine,AEL);
resortAEL(AEL);
}
}
// clear memory before exitin
for(i = 0; i < dimy; i++)
EdgeTable.Edges[i].clear();
EdgeTable.Edges.clear();
AEL.clear();
}
void scanLoopMaskFill(std::vector<vpPoint> * loop, Terrain * ter, MemMap<bool> * mask)
{
std::vector<int> x, y;
int i, j, k;
EdgeTbl EdgeTable;
std::list<Node> AEL;
intPoint pnt, prev;
intPointArray P;
bool hori = false;
std::list<Node> EmptyList; // an empty list
Node EmptyNode; // an empty node
int dimx, dimy;
ter->getGridDim(dimx, dimy);
for(k = 0; k < (int) loop->size(); k++)
{
ter->toGrid((* loop)[k], i, j);
x.push_back(i);
y.push_back(j);
}
for(i = 0; i < (int) x.size(); i++)
{
pnt.x = (GLint) x[i];
pnt.y = (GLint) y[i];
if(i==0) // no vertices yet
{
P.pt.push_back(pnt);
}
else
{
if(!(pnt.x == P.pt.back().x && pnt.y == P.pt.back().y)) // skip over duplicates
{
if(pnt.y == P.pt.back().y) // skip intermediate points on horizontal edge
{
hori = true;
}
else
{
if(hori) // go back and push the last point on the horizontal edge
{
prev.x = (GLint) x[i-1];
prev.y = (GLint) y[i-1];
P.pt.push_back(prev);
hori = false;
}
P.pt.push_back(pnt);
}
}
}
}
EmptyList.push_front(EmptyNode); // an empty list
// build the edge table - need the window size
for (i = 0; i < dimy; i++)
EdgeTable.Edges.push_back(EmptyList);
EdgeTable.buildTable(P, dimx, dimy);
for (int scanLine = 0; scanLine < dimy; scanLine++)
{
buildAEL (AEL,EdgeTable.Edges[scanLine]);
if (!AEL.empty())
{
fillMaskScan(scanLine,AEL,ter,mask);
updateAEL (scanLine,AEL);
resortAEL(AEL);
}
}
// clear memory before exitin
for(i = 0; i < dimy; i++)
EdgeTable.Edges[i].clear();
EdgeTable.Edges.clear();
AEL.clear();
}
| 10,850
|
C++
|
.cpp
| 362
| 22.740331
| 92
| 0.523481
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,229
|
histcomp_window.cpp
|
jgain_EcoLearn/EcoSynth/viewer/histcomp_window.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "histcomp_window.h"
#include <iostream>
#include <sstream>
#include <QMouseEvent>
#include <QRect>
histcomp_window::histcomp_window(CompType ctype)
: QLabel(), clicklabel(new QLabel(this, Qt::Window)), curr_selected_id(-1), ctype(ctype)
{
clicklabel->setWindowFlag(Qt::ToolTip);
clicklabel->setHidden(true);
}
void histcomp_window::mouseReleaseEvent(QMouseEvent *ev)
{
std::cout << "Mouserelease event in histcomp_window" << std::endl;
QPoint pt(ev->localPos().x(), ev->localPos().y());
std::string labeltext;
std::stringstream ss;
int selected_id;
int idx = 0;
for (histcomp_window::histinfo &h : hists)
{
if (h.loc_coords.contains(pt))
{
selected_id = idx;
if (curr_selected_id == selected_id)
{
selected_id = -1;
curr_selected_id = -1;
break;
}
else
{
if (ctype == CompType::SIZE)
{
ss << "Species: " << h.spec1.id << "\nNumber synthesized: " << h.spec1.nsynth << "\n";
curr_selected_id = selected_id;
}
else
{
std::string understr = " (undergrowth";
std::string canopystr = " (canopy";
if (ctype == CompType::UNDERUNDER)
{
understr = "";
canopystr = "";
}
ss << "Species" << understr << ": " << h.spec1.id << "\nNumber synthesized: " << h.spec1.nsynth << "\n";
if (h.spec2.id >= 0 && h.spec2.nsynth >= 0)
{
ss << "Species" << canopystr << ": " << h.spec2.id << "\nNumber synthesized: " << h.spec2.nsynth << "\n";
}
ss << "Number of elements: " << h.refcount << "\n";
//std::cout << p.second.nsynth << " synthesized for species " << p.first << std::endl;
curr_selected_id = selected_id;
//std::cout << "Appending to string" << std::endl;
}
}
//std::cout << "Click inside species rect" << std::endl;
}
else
{
//std::cout << "Click outside species rect " << r.x() << ", " << r.y() << ", " << r.width() << ", " << r.height() << std::endl;
}
idx++;
}
labeltext = ss.str();
if (curr_selected_id == -1)
{
clicklabel->setHidden(true);
}
else
{
clicklabel->move(ev->globalX(), ev->globalY());
clicklabel->setText(labeltext.c_str());
clicklabel->show();
}
}
/*
void histcomp_window::mouseReleaseEvent(QMouseEvent *ev)
{
std::cout << "Mouserelease event in histcomp_window" << std::endl;
QPoint pt(ev->localPos().x(), ev->localPos().y());
std::string labeltext;
std::stringstream ss(labeltext);
int selected_id;
for (auto &p : speciesinfo)
{
if (p.second.loc_coords.contains(pt))
{
selected_id = p.first;
if (curr_selected_id == selected_id)
{
selected_id = -1;
curr_selected_id = -1;
break;
}
else
{
ss << "Species: " << curr_selected_id << "\nNumber synthesized: " << p.second.nsynth << "\n";
std::cout << p.second.nsynth << " synthesized for species " << p.first << std::endl;
curr_selected_id = selected_id;
}
//std::cout << "Click inside species rect" << std::endl;
}
else
{
QRect &r = p.second.loc_coords;
//std::cout << "Click outside species rect " << r.x() << ", " << r.y() << ", " << r.width() << ", " << r.height() << std::endl;
}
}
if (curr_selected_id == -1)
{
clicklabel->setHidden(true);
}
else
{
clicklabel->move(ev->globalX(), ev->globalY());
clicklabel->setText(labeltext.c_str());
clicklabel->show();
}
}
*/
void histcomp_window::set_species_info(int id, int nsynth, const QRect &loc_coords)
{
if (!speciesinfo.count(id))
{
speciesinfo[id] = {id, nsynth, {loc_coords} };
}
else
{
speciesinfo.at(id).loc_coords.push_back(loc_coords);
}
}
void histcomp_window::set_hist_info(int id1, int nsynth1, int id2, int nsynth2, int refcount, QRect loc_coords)
{
histinfo h = { {id1, nsynth1}, {id2, nsynth2}, refcount, loc_coords };
hists.push_back(h);
}
void histcomp_window::set_hist_info(int id, int nsynth, int refcount, QRect loc_coords)
{
histinfo h = { {id, nsynth}, {-1, -1}, refcount, loc_coords };
hists.push_back(h);
}
void histcomp_window::closeEvent(QCloseEvent *event)
{
if (clicklabel->isVisible())
{
clicklabel->setHidden(true);
}
QLabel::closeEvent(event);
hists.clear();
speciesinfo.clear();
}
| 6,010
|
C++
|
.cpp
| 172
| 26.598837
| 139
| 0.523793
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,230
|
interp.cpp
|
jgain_EcoLearn/EcoSynth/viewer/interp.cpp
|
#include "interp.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <cassert>
#include <limits>
#include <math.h>
using namespace std;
float Interpolator::max(const Histogram& h)
{
float ans = std::numeric_limits<float>::min();
for(float f : h)
ans = std::max(ans, f);
return ans;
}
float Interpolator::min(const Histogram& h)
{
float ans = std::numeric_limits<float>::max();
for(float f : h)
ans = std::min(ans, f);
return ans;
}
void Interpolator::cumsum(const Histogram& h, Histogram& h_cumsum)
{
h_cumsum.resize(h.size()+1);
h_cumsum[0] = 0;
for(uint i=0; i<h.size(); ++i)
h_cumsum[i+1] = h_cumsum[i] + h[i];
}
void Interpolator::diff(const Histogram& h, Histogram& h_diff)
{
h_diff.resize(h.size()-1);
for(uint i=0; i<h.size()-1; ++i)
h_diff[i] = h[i+1] - h[i];
}
float Interpolator::get_fibre(const Histogram& h, const float x)
{
int imin = -1;
int imax = -1;
for(imax=h.size() - 1; imax>=0; --imax)
{
if(h[imax] <= x)
{
imax = imax+1;
break;
}
}
for(imin=0; imin<int(h.size()); ++imin)
{
if(h[imin] >= x)
{
imin = imin-1;
break;
}
}
if(imin == -1 || imax == -1)
{
return 0;
}
if(imin == int(h.size()) || imax == int(h.size()))
{
return h.size()-1;
}
if(imin == imax)
{
return imin; // Should not happend
}
float t = (x - h[imin]) / (h[imax] - h[imin]);
float ans = (1.0 - t) * imin + t * imax;
return ans;
}
void Interpolator::normalize(Histogram& h)
{
float max_val = max(h);
float min_val = min(h);
for(float& f : h)
{
f = (f-min_val) / (max_val - min_val);
}
}
void Interpolator::denormalize(Histogram& h, float min_val, float max_val)
{
for(float& f : h)
{
f = f* (max_val - min_val) + min_val;
}
}
void Interpolator::invert(const Histogram& h, Histogram& h_inv, const uint nb_steps)
{
h_inv.resize(nb_steps);
float max_val = max(h);
float min_val = min(h);
for(uint i=0; i<nb_steps; ++i)
{
float x = float(i) / (nb_steps-1);
x = x*(max_val - min_val) + min_val;
h_inv[i] = get_fibre(h, x);
}
}
void Interpolator::interpolate_linear(const Histogram& h0, const Histogram& h1, Histogram& ht, const float t)
{
assert(h0.size() == h1.size());
uint size = h0.size();
ht.resize(size);
for(uint i = 0; i<size; ++i)
{
ht[i] = (1.0f - t) * h0[i] + t * h1[i];
}
}
void Interpolator::interpolate_icdf(const Histogram& h0, const Histogram& h1, Histogram& ht, const float t)
{
// Preliminary checks
assert(h0.size() == h1.size());
uint size = h0.size();
// Cumulated sums computation
Histogram h0_cumsum;
cumsum(h0, h0_cumsum);
Histogram h1_cumsum;
cumsum(h1, h1_cumsum);
// Cumulated sums extremal values backup (for further interpolation)
float min_h0_cumsum = min(h0_cumsum);
float max_h0_cumsum = max(h0_cumsum);
float min_h1_cumsum = min(h1_cumsum);
float max_h1_cumsum = max(h1_cumsum);
// Cumulated sums normalization
normalize(h0_cumsum);
normalize(h1_cumsum);
uint nb_steps = MT_STEPS*size; // Number of steps used for computing inverse. Note : This has a big influence on the final result precision.
// Cumulated sums inversion
Histogram h0_cumsum_invert;
invert(h0_cumsum, h0_cumsum_invert, nb_steps);
Histogram h1_cumsum_invert;
invert(h1_cumsum, h1_cumsum_invert, nb_steps);
// Inverted cumulated sums linear interpolation
Histogram ht_cumsum_invert;
interpolate_linear(h0_cumsum_invert, h1_cumsum_invert, ht_cumsum_invert, t);
// Interpolated inverse inversion (back to regular representation)
Histogram ht_cumsum;
invert(ht_cumsum_invert, ht_cumsum, size+1);
normalize(ht_cumsum);
// Resulting interpolated cumulated sum de-normalization
float ht_min = (1.0-t)*min_h0_cumsum + t*min_h1_cumsum;
float ht_max = (1.0-t)*max_h0_cumsum + t*max_h1_cumsum;
denormalize(ht_cumsum, ht_min, ht_max);
// Result differentiation (i.e. de-accumulation)
diff(ht_cumsum, ht);
}
void Interpolator::radToHist(AnalysisConfiguration &anconfig, RadialDistribution rad, Histogram & hist)
{
// assumes bins in RadialDistribution histogram are indexed from 0
int numbins = rad.m_data.size()+3;
hist.clear();
hist.resize(numbins, 0.0f);
hist[0] = rad.m_less_than_half_shaded_distribution;
hist[1] = rad.m_more_than_half_shaded_distribution;
hist[2] = rad.m_fully_shaded_distribution;
int i = 3;
for(auto rit: rad.m_data)
{
hist[i] = rit.second;
i++;
}
}
void Interpolator::histToRad(AnalysisConfiguration &anconfig, Histogram hist, RadialDistribution & rad)
{
// other params of for rad also need setting
rad.m_less_than_half_shaded_distribution = hist[0];
rad.m_more_than_half_shaded_distribution = hist[1];
rad.m_fully_shaded_distribution = hist[2];
int i = 3;
for(int r = anconfig.r_min; r < anconfig.r_max; r += anconfig.r_diff)
{
rad.m_data.insert(std::make_pair(r, hist[i]));
i++;
}
}
void Interpolator::histPos(Histogram & hist)
{
for(int i = 0; i < (int) hist.size(); i++)
{
if(hist[i] < 0.0f)
{
if(hist[i] < -1.0f)
cerr << "WARNING: highly negative histogram bin" << endl;
hist[i] = 0.0f;
}
}
}
void Interpolator::interp(std::vector<int> global_priority, Distribution &d0, Distribution &d1, Distribution &dout, const float t)
{
std::vector<int> combined_priority; // combined category priority list
dout.setEmpty(true);
dout.getCategories().clear();
dout.getCorrelations().clear();
if(!d0.isEmpty())
dout.setAnalysisConfig(d0.getAnalysisConfig());
else
dout.setAnalysisConfig(d1.getAnalysisConfig());
// cerr << "GLOBAL PRIORITY LIST" << endl;
// combine categories of d0 and d1 into a single sorted priority list, using global priority to determine order
for(auto cit: global_priority)
{
// cerr << cit << " ";
if(d0.getCategories().find(cit) != d0.getCategories().end() || d1.getCategories().find(cit) != d1.getCategories().end())
combined_priority.push_back(cit);
}
// cerr << endl;
// iterate in priority order
for(std::vector<int>::iterator op = combined_priority.begin(); op != combined_priority.end(); op++)
{
std::vector<int>::iterator ip = combined_priority.begin();
bool fin = false;
// test correlations in priority order up to and including the current category
while(!fin)
{
bool d0found = false, d1found = false;
RadialDistribution r0, r1;
// test for interaction
std::pair<int, int> key = std::make_pair((* ip), (* op));
if(d0.getCorrelations().find(key) != d0.getCorrelations().end())
{
r0 = d0.getCorrelations().find(key)->second;
d0found = true;
}
if(d1.getCorrelations().find(key) != d1.getCorrelations().end())
{
r1 = d1.getCorrelations().find(key)->second;
d1found = true;
}
RadialDistribution outrad;
if(d0found && d1found)
{
// cerr << (*op) << ": " << (* ip) << " both found" << endl;
// convert pairwise interaction to histogram
Histogram h0; radToHist(d0.getAnalysisConfig(), r0, h0);
Histogram h1; radToHist(d1.getAnalysisConfig(), r1, h1);
// Optimal transport interpolation
Histogram hout;
interpolate_icdf(h0, h1, hout, t);
histPos(hout);
// convert interpolation back to radial distribution
histToRad(d0.getAnalysisConfig(), hout, outrad);
outrad.m_shaded_ratio = (int) (t * (float) r1.m_shaded_ratio + (1.0f-t) * (float) r0.m_shaded_ratio + 0.5f);
outrad.m_header.reference_id = (* ip);
outrad.m_header.destination_id = (* op);
outrad.m_past_rmax_distribution = t * r1.m_past_rmax_distribution + (1.0f-t) * r0.m_past_rmax_distribution; // just interpolate this bin since it is a catch all category
// ignore requires_optimization field of m_header since it doesn't seem to be used
// cerr << "r0.pastr = " << r0.m_past_rmax_distribution << ", r1.pastr = " << r1.m_past_rmax_distribution << ", outr.pastr = " << outrad.m_past_rmax_distribution << endl;
outrad.calculate_min_max();
}
else if(d0found)
{
// cerr << (*op) << ": " << (* ip) << " only d0 found" << endl;
outrad = RadialDistribution(r0.m_header, r0.m_shaded_ratio, r0.m_less_than_half_shaded_distribution,
r0.m_more_than_half_shaded_distribution,
r0.m_fully_shaded_distribution,
r0.m_past_rmax_distribution,
r0.m_data);
outrad.calculate_min_max();
}
else if(d1found)
{
// cerr << (*op) << ": " << (* ip) << " only d1 found" << endl;
// outrad = r1;
outrad = RadialDistribution(r1.m_header, r1.m_shaded_ratio, r1.m_less_than_half_shaded_distribution,
r1.m_more_than_half_shaded_distribution,
r1.m_fully_shaded_distribution,
r1.m_past_rmax_distribution,
r1.m_data);
outrad.calculate_min_max();
}
if(d0found || d1found) // if missing in both then leave as empty
{
if(dout.getCorrelations().find(key) != dout.getCorrelations().end())
{
cerr << "Error Interpolator::interp: correlation already exists" << endl;
exit(1);
}
dout.getCorrelations().insert(std::make_pair(key, outrad));
}
fin = (ip == op);
ip++;
}
bool c0found, c1found;
// interpolate category data here, principally the number of points
c0found = d0.getCategories().find((*op)) != d0.getCategories().end();
c1found = d1.getCategories().find((*op)) != d1.getCategories().end();
int n0 = 0, n1 = 0;
float hght0 = 0.0f, hght1 = 0.0f, root0 = 0.0f, root1 = 0.0f;
float hmin0 = 0.0f, hmin1 = 0.0f, hmax0 = 0.0f, hmax1 = 0.0f;
float havg0 = 0.0f, havg1 = 0.0f, hdev0 = 0.0f, hdev1 = 0.0f;
CategoryProperties::Histogram hempty;
if(c0found)
{
// create and populate dout category
dout.getCategories()[(*op)] = d0.getCategories().find((* op))->second;
for(auto dit: d0.getCategories().find((* op))->second.m_header.category_dependent_ids)
dout.getCategories().find((*op))->second.m_header.category_dependent_ids.insert(dit);
n0 = d0.getCategories().find((*op))->second.m_header.n_points;
hght0 = d0.getCategories().find((*op))->second.m_header.height_to_radius_multiplier;
root0 = d0.getCategories().find((*op))->second.m_header.height_to_root_size_multiplier;
hmin0 = (float) d0.getCategories().find((*op))->second.m_header.height_properties.min;
hmax0 = (float) d0.getCategories().find((*op))->second.m_header.height_properties.max;
havg0 = d0.getCategories().find((*op))->second.m_header.height_properties.avg;
hdev0 = d0.getCategories().find((*op))->second.m_header.height_properties.standard_dev;
}
if(c1found)
{
if(!c0found)
{
dout.getCategories()[(*op)] = d1.getCategories().find((* op))->second;
}
/*
else // add any additional dependencies
{
for(auto dit: d1.getCategories().find((* op))->second.m_header.category_dependent_ids)
dout.getCategories().find((*op))->second.m_header.category_dependent_ids.insert(dit);
}*/
for(auto dit: d1.getCategories().find((* op))->second.m_header.category_dependent_ids)
dout.getCategories().find((*op))->second.m_header.category_dependent_ids.insert(dit);
n1 = d1.getCategories().find((*op))->second.m_header.n_points;
hght1 = d1.getCategories().find((*op))->second.m_header.height_to_radius_multiplier;
root1 = d1.getCategories().find((*op))->second.m_header.height_to_root_size_multiplier;
hmin1 = (float) d1.getCategories().find((*op))->second.m_header.height_properties.min;
hmax1 = (float) d1.getCategories().find((*op))->second.m_header.height_properties.max;
havg1 = d1.getCategories().find((*op))->second.m_header.height_properties.avg;
hdev1 = d1.getCategories().find((*op))->second.m_header.height_properties.standard_dev;
}
if(c0found || c1found)
{
// intepolate number of points and other header properties
dout.getCategories().find((*op))->second.m_header.n_points = (int) ((t * (float) n1) + (1-t) * (float) n0 + 0.5f);
dout.getCategories().find((*op))->second.m_header.height_to_radius_multiplier = t * hght1 + (1-t) * hght0;
dout.getCategories().find((*op))->second.m_header.height_to_root_size_multiplier = t * root1 + (1-t) * root0;
dout.getCategories().find((*op))->second.m_header.height_properties.min = (int) (t * hmin1 + (1-t) * hmin0 + 0.5f);
dout.getCategories().find((*op))->second.m_header.height_properties.max = (int) (t * hmax1 + (1-t) * hmax0 + 0.5f);
dout.getCategories().find((*op))->second.m_header.height_properties.avg = t * havg1 + (1-t) * havg0;
dout.getCategories().find((*op))->second.m_header.height_properties.standard_dev = t * hdev1 + (1-t) * hdev0;
dout.setEmpty(false);
}
// no change to m_header.priority since this is not used anyway
// TO DO this might cause problems on save and load?
}
}
| 14,583
|
C++
|
.cpp
| 344
| 33.424419
| 186
| 0.579074
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,231
|
test_canopy_placement.cpp
|
jgain_EcoLearn/EcoSynth/viewer/tests/test_canopy_placement.cpp
|
#include "canopy_placement/gpu_procs.h"
#include "data_importer.h"
#include <string>
#include "canopy_placement/basic_types.h"
#include <sqlite3.h>
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
void test_local_maxima_find()
{
std::cerr << "test_find_local_maxima_gpu: " << std::endl;
if (test_find_local_maxima_gpu(verbosity::ALL))
{
std::cerr << "PASS" << std::endl;
}
else
{
std::cerr << "FAIL" << std::endl;
}
}
void remove_files_containing(std::string containing)
{
}
std::string get_next_filename(std::string basename, std::string directory)
{
using namespace boost::filesystem;
path p(directory);
if (!boost::filesystem::is_directory(p))
{
throw std::invalid_argument("Directory must be passed to get_next_filename");
}
int nexist = 0;
for (auto &entry : boost::make_iterator_range(directory_iterator(p), {}))
{
std::string exist_filename = entry.path().filename().string();
if (exist_filename.find(basename) != std::string::npos)
{
nexist++;
}
//std::cout << entry.path().string() << std::endl;
//std::cout << newp.string() << std::endl;
}
std::string full_basename = basename + std::to_string(nexist) + ".txt";
full_basename = (p / full_basename).string();
return full_basename;
}
void write_array_to_file(std::string out_file, const std::vector<uint32_t> &values, int width, int height)
{
ValueMap<uint32_t> outmap;
outmap.setDim(width, height);
memcpy(outmap.data(), values.data(), sizeof(uint32_t) * width * height);
data_importer::write_txt(out_file, &outmap);
}
int main(int argc, char * argv [])
{
using namespace basic_types;
if (argc != 3)
{
std::cout << "Usage: canopy_placement <dataset directory> <database filename>" << std::endl;
return 1;
}
std::string test_texture_out_filename_base = "texture_test_out";
data_importer::common_data simdata(argv[2]);
data_importer::data_dir ddir(argv[1], simdata);
int nsims = ddir.required_simulations.size();
std::map<int, data_importer::species> all_species = simdata.all_species;
int width, height;
MapFloat chm = data_importer::load_txt< MapFloat >(ddir.chm_fname);
MapFloat dem = data_importer::load_elv< MapFloat >(ddir.dem_fname);
//for (auto &biome_fname : ddir.biome_fnames)
for (int i = 0; i < 1; i++)
{
std::string test_texture_out_filename = get_next_filename(test_texture_out_filename_base, argv[1]);
std::string canopy_fname = ddir.canopy_fnames[i];
std::string species_fname = ddir.species_fnames[i];
ValueMap<int> species = data_importer::load_txt< ValueMap<int> >(species_fname);
//std::vector<species_params> all_params = data_importer::read_species_params(biome_fname);
canopy_placer placer(&chm, &species, all_species);
//placer.optimise(20);
chm.getDim(width, height);
placer.init_optim();
for (int i = 0; i < 50; i++)
{
placer.iteration();
std::vector<uint32_t> out_values;
//placer.get_chm_rendered_texture(out_values);
//write_array_to_file(test_texture_out_filename, out_values, width, height);
placer.check_duplicates();
}
//placer.final_adjustments_gpu();
placer.write_chm_data_to_file(test_texture_out_filename);
placer.save_to_file(canopy_fname, dem.data());
}
return 0;
}
| 3,549
|
C++
|
.cpp
| 94
| 31.840426
| 107
| 0.639091
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,232
|
main.cpp
|
jgain_EcoLearn/EcoSynth/undersample/main.cpp
|
#include <canopy_placement/gl_wrapper.h>
#include <data_importer.h>
#include <canopy_placement/basic_types.h>
#include <canopy_placement/gpu_procs.h>
#include <chrono>
#include <random>
int main(int argc, char * argv [])
{
const int w = 128;
const int h = 128;
std::default_random_engine generator(std::chrono::steady_clock::now().time_since_epoch().count());
std::uniform_int_distribution<int> unif_w(0, w - 1);
std::uniform_int_distribution<int> unif_h(0, h - 1);
std::uniform_int_distribution<int> unif_treeh(5, 50);
std::uniform_int_distribution<int> unif_species(0, 2);
std::vector<int> default_species = {5, 7, 9};
const int ntrees = 400;
std::vector<float> chmdata(128 * 128, 100.0f / 0.3048f);
gl_wrapper gl_object(chmdata.data(), 128, 128);
std::vector<mosaic_tree> trees;
std::map<int, std::vector<mosaic_tree> > treemap;
if (argc == 1)
{
for (int i = 0; i < ntrees; i++)
{
int x = unif_w(generator);
int y = unif_h(generator);
int h = unif_treeh(generator);
int r = h * 0.2f;
r = r > 0 ? r : 1;
auto newtree = mosaic_tree(x, y, r, h, true);
int species = default_species[unif_species(generator)];
newtree.species = species;
treemap[species].push_back(newtree);
}
}
else
{
std::string pdb_filename = argv[1];
std::map<int, std::vector<MinimalPlant> > plantmap;
data_importer::read_pdb(pdb_filename, plantmap);
std::map<int, std::vector<mosaic_tree> > treemap;
data_importer::minimaltree_to_othertree(plantmap, treemap);
for (auto &spectrees : treemap)
{
for (auto &tree : spectrees.second)
{
trees.push_back(mosaic_tree(tree.x, tree.y, tree.radius, tree.height, true));
trees.back().species = spectrees.first;
}
}
}
int r = 10;
int g = 0;
int b = 0;
std::vector < std::vector<int> > colors;
colors = { {255, 0, 0}, {255, 255, 0}, {255, 0, 255}, {0, 255, 0}, {0, 0, 255}, {0, 255, 255} };
int curr_col_idx = 0;
std::set<int> colors_assigned;
for (auto &spectrees : treemap)
{
auto result = colors_assigned.insert(spectrees.first);
for (auto &tree : spectrees.second)
{
auto &currcol = colors[curr_col_idx];
trees.push_back(tree);
trees.back().r = currcol[0];
trees.back().g = currcol[1];
trees.back().b = currcol[2];
trees.back().a = 255;
tree.b = 1;
tree.r = tree.g = 0;
tree.a = 255;
}
if (result.second)
{
curr_col_idx++;
}
}
gl_object.build_chm_instanced(trees.begin(), trees.end());
auto colordata = gl_object.get_color_id_data();
ValueMap<uint32_t> writemap;
writemap.setDim(128, 128);
memcpy(writemap.data(), colordata.data(), sizeof(uint32_t) * w * h);
data_importer::write_txt("/home/konrad/undersample_map_all.txt", &writemap);
for (auto &spectrees : treemap)
{
int species = spectrees.first;
gl_object.build_chm_instanced(spectrees.second.begin(), spectrees.second.end());
colordata = gl_object.get_color_id_data();
memcpy(writemap.data(), colordata.data(), sizeof(uint32_t) * w * h);
ValueMap<float> writefloatmap;
writefloatmap.setDim(w, h);
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
writefloatmap.set(x, y, (float)writemap.get(x, y));
}
}
ValueMap<float> smoothmap;
smoothmap.setDim(w, h);
for (auto &val : writefloatmap)
{
val -= 255;
}
data_importer::write_txt("/home/konrad/undersample_map_species" + std::to_string(species) + ".txt", &writemap);
smooth_uniform_radial(15, writefloatmap.data(), smoothmap.data(), w, h);
data_importer::write_txt("/home/konrad/undersample_map_species" + std::to_string(species) + "_smoothed.txt", &smoothmap);
}
std::cout << colordata[50 * 128 + 50] << std::endl;
return 0;
}
| 4,270
|
C++
|
.cpp
| 113
| 29.548673
| 129
| 0.568665
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,233
|
map_rgba.cpp
|
jgain_EcoLearn/EcoSynth/common/map_rgba.cpp
|
/**
* @file
*
* Specialization of @ref MapTraits for color images.
*/
#include <cmath>
#include <Magick++.h>
#include <ImfFrameBuffer.h>
#include <thread>
#include "map.h"
#include "map_rgba.h"
#include "str.h"
static constexpr Magick::Quantum getQuantumRange()
{
using namespace Magick; // otherwise the macro breaks
return QuantumRange;
}
static Magick::Quantum floatToQuantum(float x)
{
if (!(x >= 0.0f)) // also catches NaN
x = 0.0f;
if (x > 1.0f)
x = 1.0f;
return static_cast<Magick::Quantum>(std::round(x * getQuantumRange()));
}
bool MapTraits<gray_tag>::customRead(MemMap<gray_tag> &out, const uts::string &filename)
{
if (endsWith(filename, ".exr"))
return false; // use OpenEXR for EXR images (default path)
Magick::Image image(filename);
// This is needed to make the grayscale conversion happen in linear space
image.image()->intensity = MagickCore::Rec709LuminancePixelIntensityMethod;
image.colorSpace(Magick::GRAYColorspace);
Region r(0, 0, image.columns(), image.rows());
out.allocate(r);
image.write(0, 0, r.x1, r.y1, "I", Magick::FloatPixel, out.get());
return true;
}
bool MapTraits<gray_tag>::customWrite(const MemMap<gray_tag> &in, const uts::string &filename,
const Region ®ion)
{
if (endsWith(filename, ".exr"))
return false;
const Region &r = in.region();
Magick::Image image(Magick::Geometry(r.width(), r.height()), Magick::Color(0, 0, 0, 0));
image.colorSpace(Magick::RGBColorspace);
Magick::Pixels view(image);
Magick::PixelPacket *pixels = view.set(0, 0, r.width(), r.height());
for (int y = r.y0; y < r.y1; y++)
for (int x = r.x0; x < r.x1; x++, pixels++)
{
Magick::Quantum v = floatToQuantum(in[y][x]);
pixels->red = v;
pixels->green = v;
pixels->blue = v;
pixels->opacity = 0;
}
view.sync();
/* Convert to sRGB. This shouldn't be necessary, but without it, the PNG
* encoder writes linear values but stores a gAMA chunk of 1/2.2.
*/
image.colorSpace(Magick::sRGBColorspace);
image.write(filename);
return true;
}
void MapTraits<gray_tag>::prepareFrameBuffer(Imf::FrameBuffer &fb, const io_type *base, std::size_t width)
{
MapTraits<height_tag>::prepareFrameBuffer(fb, base, width);
}
bool MapTraits<rgba_tag>::customRead(MemMap<rgba_tag> &out, const uts::string &filename)
{
if (endsWith(filename, ".exr"))
return false; // use OpenEXR for EXR images (default path)
Magick::Image image(filename);
image.colorSpace(Magick::RGBColorspace);
Region r(0, 0, image.columns(), image.rows());
out.allocate(r);
image.write(0, 0, r.x1, r.y1, "RGBA", Magick::FloatPixel, out.get());
return true;
}
bool MapTraits<rgba_tag>::customWrite(const MemMap<rgba_tag> &in, const uts::string &filename,
const Region ®ion)
{
if (endsWith(filename, ".exr"))
return false;
const Region &r = in.region();
Magick::Image image(Magick::Geometry(r.width(), r.height()), Magick::Color(0, 0, 0, getQuantumRange()));
image.colorSpace(Magick::RGBColorspace);
Magick::Pixels view(image);
Magick::PixelPacket *pixels = view.set(0, 0, r.width(), r.height());
for (int y = r.y0; y < r.y1; y++)
for (int x = r.x0; x < r.x1; x++, pixels++)
{
pixels->red = floatToQuantum(in[y][x][0]);
pixels->green = floatToQuantum(in[y][x][1]);
pixels->blue = floatToQuantum(in[y][x][2]);
// ImageMagick uses reverse alpha
pixels->opacity = getQuantumRange() - floatToQuantum(in[y][x][3]);
}
view.sync();
/* Convert to sRGB. The ImageMagick decoder doesn't understand that gamma=1
* means a linear image, so we have to write an sRGB image. Many other decoders
* are also unlikely to get this right.
*/
image.colorSpace(Magick::sRGBColorspace);
image.write(filename);
return true;
}
void MapTraits<rgba_tag>::prepareFrameBuffer(Imf::FrameBuffer &fb, const io_type *base, std::size_t width)
{
fb.insert("R", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][0]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("G", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][1]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("B", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][2]),
sizeof(io_type), sizeof(io_type) * width));
fb.insert("A", Imf::Slice(Imf::FLOAT, reinterpret_cast<char *>(&const_cast<io_type *>(base)[0][3]),
sizeof(io_type), sizeof(io_type) * width));
}
const uts::vector<MapTraits<rgba_tag>::type> &MapTraits<rgba_tag>::colorPalette()
{
static const uts::vector<type> palette{
{{ 0.0f, 0.0f, 0.0f, 1.0f }},
{{ 0.0f, 0.0f, 1.0f, 1.0f }},
{{ 0.0f, 1.0f, 0.0f, 1.0f }},
{{ 1.0f, 0.0f, 0.0f, 1.0f }},
{{ 1.0f, 1.0f, 0.0f, 1.0f }},
{{ 1.0f, 1.0f, 1.0f, 1.0f }},
{{ 1.0f, 0.0f, 1.0f, 1.0f }},
{{ 0.0f, 1.0f, 1.0f, 1.0f }}
};
return palette;
}
| 5,371
|
C++
|
.cpp
| 133
| 33.857143
| 108
| 0.609279
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,234
|
kmeans.cpp
|
jgain_EcoLearn/EcoSynth/kmeans/src/kmeans.cpp
|
#include "kmeans.h"
// #include <QObject>
// #include <QTimer>
//#include <QVector2D>
#include <iostream>
#include <fstream>
#include <chrono>
#include <random>
// uncomment to disable assert()
// #define NDEBUG
#include <cassert>
using namespace std;
bool kMeans::close(int k, std::vector<std::array<float,kMeans::ndim>> &clusters, float tol)
{
//QVector2D w1, w2;
for(int i = 0; i < k; i++)
for(int j = i+1; j < k; j++)
{
if(sqrtf(kdist(clusters[i], clusters[j])) < tol)
return true;
}
return false;
}
void kMeans::search(std::vector<std::array<float,kMeans::ndim>> &features, int &k, std::vector<int> &assigns, std::vector<std::array<float,kMeans::ndim>> &clusters)
{
bool fin = false;
float currdiff, bestdiff, globaldiff;
std::vector<int> bestassigns, currassigns;
std::vector<std::array<float,kMeans::ndim>> bestclusters, currclusters;
globaldiff = numeric_limits<float>::max();
// test for all k in the allowable range
for(int c = 1; c < kmax; c++)
{
bestdiff = numeric_limits<float>::max();
// run k-means repeatedly choosing the best result
for(int r = 0; r < kreps; r++)
{
currdiff = cluster(features, c, currassigns, currclusters);
if(currdiff < bestdiff && !close(c, currclusters, 0.06f)) // ignores clusters that are too close together
{
bestdiff = currdiff;
bestassigns = currassigns;
bestclusters = currclusters;
}
}
if(bestdiff < globaldiff)
{
k = c;
assigns = bestassigns;
clusters = bestclusters;
}
}
}
float kMeans::kdist(std::array<float,kMeans::ndim> f1, std::array<float,kMeans::ndim> f2)
{
float diff = 0.0f;
for(int e = 0; e < kMeans::ndim; e++)
diff += powf(f1[e] - f2[e], 2);
return diff;
}
float kMeans::cluster(std::vector<std::array<float,kMeans::ndim>> &features, int k, std::vector<int> &assigns, std::vector<std::array<float,kMeans::ndim>> &clusters)
{
// randomly choose k-elements as means, avoiding repetition
// Forgy initialization
std::vector<int> kindices;
std::default_random_engine generator(std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count()));
std::uniform_int_distribution<int> distribution(std::uniform_int_distribution<int>(0, (int) features.size()-1));
std::vector<int> prevassigns;
float diff = 0.0f, bestdist;
int i = 0;
bool converged;
std::vector<int> rndseeds;
// cerr << "feature size = " << (int) features.size() << endl;
clusters.clear();
rndseeds.assign(knumseeds, -1);
assert((int) features.size() > knumseeds); // otherwise we cannot draw a unique sufficient seeds
// randomly choose starting cluster
// uses a variant of kmeans++: choose knumseeds random samples, from these select the one furthest from any of the existing seeds
for(int c = 0; c < k; c++)
{
int rnd, bidx;
// cerr << "k = " << k << endl;
for(int r = 0; r < knumseeds; r++)
{
bool valid = false;
while(!valid) // repeat draw until we get a number that isn't an existing seed
{
rnd = distribution.operator()(generator);
valid = true;
for(int e = 0; e < c; e++)
if(kindices[e] == rnd)
valid = false;
}
rndseeds[r] = rnd;
// cerr << rnd << endl;
}
// find furthest candidate
bestdist = 0.0f; bidx = rndseeds[0];
for(int r = 0; r < knumseeds; r++)
{
float shortdist = numeric_limits<float>::max();
// what is the shortest distance to an existing seed?
for(int i = 0; i < c; i++)
{
float dist = sqrtf(kdist(features[rndseeds[r]], clusters[i]));
if(dist < shortdist)
shortdist = dist;
}
if(shortdist > bestdist)
{
bidx = rndseeds[r];
bestdist = shortdist;
}
}
kindices.push_back(bidx);
clusters.push_back(features[bidx]);
}
assigns.clear();
assigns.assign(features.size(), 0);
prevassigns.assign(features.size(), 0);
// repeat until convergence threshold is reached or a maximum number of iterations
converged = false;
while(!converged && i < kmaxiter)
{
std::cout << "Iteration " << i << " of " << kmaxiter << std::endl;
// partition by assigning to closest mean
for(int f = 0; f < (int) features.size(); f++)
{
float bestdist = numeric_limits<float>::max(), currdist;
int cidx = 0;
for(int c = 0; c < k; c++)
{
currdist = kdist(features[f], clusters[c]);
if(currdist < bestdist)
{
bestdist = currdist;
cidx = c;
}
}
assigns[f] = cidx;
}
// update the new means
for(int c = 0; c < k; c++)
{
int kcount = 0;
for(int e = 0; e < kMeans::ndim; e++)
clusters[c][e] = 0.0f;
for(int f = 0; f < (int) features.size(); f++)
{
if(assigns[f] == c) // member of the current cluster so include in centroid
{
for(int e = 0; e < kMeans::ndim; e++)
clusters[c][e] += features[f][e];
kcount++;
}
}
for(int e = 0; e < kMeans::ndim; e++)
clusters[c][e] /= (float) kcount;
}
// check whether assignment of features to clusters is stable
converged = true;
for(int f = 0; f < (int) features.size(); f++)
{
if(prevassigns[f] != assigns[f])
converged = false;
prevassigns[f] = assigns[f];
}
i++;
}
// std::cerr << "converged after " << i << " iterations" << std::endl;
for(int f = 0; f < features.size(); f++)
diff += kdist(features[f], clusters[assigns[f]]);
diff /= (float) features.size();
// std::cerr << "with diff " << diff << std::endl;
return diff;
}
bool kMeans::unitTest(int numclusters)
{
std::default_random_engine generator(std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count()));
std::uniform_int_distribution<int> distribution(std::uniform_int_distribution<int>(0, 100000));
std::vector<std::array<float,kMeans::ndim>> features, seeds, clusters;
std::vector<int> assigns;
float diff = 0.0f;
int k;
bool fin;
// randomly generate numclusters seeds, each with a seperation of at least 0.1
for(int c = 0; c < numclusters; c++)
{
int i = 0;
std::array<float,kMeans::ndim> currseed;
fin = false;
while(!fin && i < 100)
{
// float dist, mindist, rnd;
// generate random seed in [0,2] X 4
for(int e = 0; e < kMeans::ndim; e++)
currseed[e] = 2.0f * ((float) distribution.operator()(generator) / 100000.0f);
seeds.push_back(currseed);
if(close(c, seeds, 0.1f))
seeds.pop_back();
else
fin = true;
i++;
}
if(i == 100)
{
std::cerr << "Error kMeansUnitTest: random seed assignment failed for seed " << c << std::endl;
return false;
}
}
// create a feature vector with points randomly offset from the initial seeds
for(int c = 0; c < numclusters; c++)
for(int f = 0; f < 100; f++) // number set sufficiencly high that random distribution will tend to the correct mean
{
std::array<float, kMeans::ndim> rndf = seeds[c];
for(int e = 0; e < kMeans::ndim; e++)
{
// generate random number in range [-0.01, 0.01]
float rndnum = 0.02f * ((float) distribution.operator()(generator) / 100000.0f) - 0.01f;
rndf[e] = seeds[c][e] + rndnum;
}
features.push_back(rndf);
}
// run kmeans
search(features, k, assigns, clusters);
// print out seeds
std::cerr << "SEEDS (#" << numclusters << ")" << std::endl;
for(int c = 0; c < numclusters; c++)
cerr << seeds[c][0] << " " << seeds[c][1] << " " << seeds[c][2] << " " << seeds[c][3] << std::endl;
// print out clusters
std::cerr << std::endl << "CLUSTERS (#" << k << ")" << std::endl;
for(int c = 0; c < k; c++)
std::cerr << clusters[c][0] << " " << clusters[c][1] << " " << clusters[c][2] << " " << clusters[c][3] << std::endl;
std::cerr << std::endl;
/*
for(int i = 0; i < k; i++)
for(int j = i+1; j < k; j++)
{
std::cerr << "dist c" << i << " to c" << j << " = " << sqrtf(kdist(clusters[i], clusters[j])) << std::endl;
}
*/
// test difference between cluster means and seeds
if(k != numclusters)
{
std::cerr << "Error kMeansUnitTest: number of found clusters " << k << " != actual clusters " << numclusters << std::endl;
return false;
}
else // test difference between seeds and clusters
{
int idx;
float cdiff, diff, bestdiff;
std::vector<bool> picked;
picked.assign(k, false);
// seeds and clusters may be in any order, so find closest match by distance
cdiff = 0.0f;
for(int c = 0; c < k; c++)
{
bestdiff = numeric_limits<float>::max(); idx = -1;
for(int s = 0; s < k; s++)
if(!picked[s])
{
diff = sqrtf(kdist(seeds[s], clusters[c]));
if(diff < bestdiff)
{
bestdiff = diff;
idx = s;
}
}
if(idx == -1)
std::cerr << "kMeansUnitTest: error in seed to cluster matching" << std::endl;
picked[idx] = true;
cdiff += sqrtf(kdist(seeds[idx], clusters[c]));
}
cdiff = cdiff / (float) k;
std::cerr << "kMeansUnitTest: average distance from true cluster centers = " << cdiff << std::endl;
if(cdiff > ktesttol)
{
std::cerr << "Error kMeansUnitTest: average dist " << cdiff << " above threshold of " << ktesttol << std::endl;
return false;
}
}
return true;
}
| 11,035
|
C++
|
.cpp
| 283
| 28.508834
| 165
| 0.524986
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,235
|
main.cpp
|
jgain_EcoLearn/EcoSynth/kmeans/src/main.cpp
|
#include "kmeans.h"
int main(int argc, char **argv)
{
kMeans * km = new kMeans();
km->unitTest(5);
// km->search(); // to perform an actual clustering, will need to pass in a feature vector with data to be clustered. The assigns (mapping from each feature to a cluster id) and clusters (cluster centers) and num cluster k will be returned.
return 1;
}
| 380
|
C++
|
.cpp
| 8
| 43
| 244
| 0.705556
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,236
|
data_importer.cpp
|
jgain_EcoLearn/data_importer/data_importer.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include <data_importer/data_importer.h>
#include <common/basic_types.h>
#include <vector>
#include <string>
#include <algorithm>
#include <stdexcept>
#include <fstream>
#include <iostream>
#include <cmath>
#include <numeric>
#include <map>
#include <sstream>
#include <string>
#include <cassert>
#include <sqlite3.h>
const std::array<std::string, 12> months_arr = {"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"};
std::map<std::string, int> make_monthmap()
{
std::map<std::string, int> monthmap;
for (int i = 0; i < months_arr.size(); i++)
{
monthmap[months_arr[i]] = i;
}
return monthmap;
}
const std::map<std::string, int> monthmap = make_monthmap();
void data_importer::modelset::add_model(treemodel model)
{
int count = 0;
for (auto &m : models)
{
if (model.hmin < m.hmin)
{
models.insert(std::next(models.begin(), count), model);
break;
//return;
}
count++;
}
//models.push_back(model); // if we return, instead of break above, use this code
// if we break, instead of return above, use this code
if (count == models.size())
{
models.push_back(model);
}
vueid_to_ratio[model.vueid] = model.whratio / 2.0f;
//setup_ranges(); // if we want the object ready after sql import, this has to happen...
}
void data_importer::modelset::setup_ranges()
{
ranges.clear();
selections.clear();
samplemap.clear();
for (int i = 0; i < models.size(); i++)
{
add_to_ranges(i);
}
setup_selections();
// setup samplemap
for (int i = 1; i < ranges.size(); i++)
{
float cand;
if ((cand = ranges[i] - ranges[i - 1]) < minrange)
{
minrange = cand;
}
}
// let's make binsize 1.0f - if
// we can enforce that range borders are integers, we will not have bins that stride
// range borders
//binsize = 1.0f;
binsize = minrange;
nbins = std::ceil(ranges.back() - ranges.front()) / binsize;
//float binsize = minrange / 5.0f;
//int nbins = std::ceil((ranges.back() - ranges.front()) / binsize);
/*
if (nbins > 200)
{
nbins = 200;
binsize = (ranges.back() - ranges.front()) / nbins;
}
*/
samplemap.resize(nbins);
int curridx = 0;
samplemap.at(0) = curridx;
for (int i = 1; i < nbins; i++)
{
if (i * binsize >= ranges.at(curridx + 1) - 1e-4f) // curridx + 1, because ranges[curr_idx + 1] corresponds to selections[curr_idx]
{
curridx++;
if (i * binsize >= ranges.at(curridx + 1) - 1e-4)
{
throw std::runtime_error("binsize too big in modelset::setup_ranges");
}
}
samplemap.at(i) = curridx;
}
}
float data_importer::modelset::sample_rh_ratio(float height, int *vuemodel)
{
int vm = sample_selection_robust(height);
if (vuemodel)
{
*vuemodel = vm;
}
return vueid_to_ratio.at(vm);
}
int data_importer::modelset::sample_selection_robust(float height)
{
std::vector<int> *sel;
//binsize = (ranges.back() - ranges.front()) / nbins;
int idx = height / binsize;
if (idx >= samplemap.size() || height > ranges.back())
{
throw std::runtime_error("height out of range in modelset::sample_selection");
}
int selidx = -1;
if (idx < samplemap.size() - 1)
{
if (samplemap.at(idx) != samplemap.at(idx + 1))
{
if (height > ranges.at(samplemap.at(idx + 1)))
{
selidx = samplemap.at(idx + 1);
}
}
if (selidx == -1)
selidx = samplemap.at(idx);
}
else
selidx = samplemap.back();
sel = &selections.at(selidx);
// std::cout << "selection size: " << sel->size() << std::endl;
int randidx = rand() % sel->size();
return sel->at(randidx);
}
// this function makes the assumption that each bin has size 1.0f
int data_importer::modelset::sample_selection_fast(float height)
{
throw std::runtime_error("modelset::sample_selection_fast not implemented");
std::vector<int> *sel;
//float binsize = (ranges.back() - ranges.front()) / nbins;
int idx = height - ranges.front();
if (idx >= samplemap.size() || height > ranges.back())
{
throw std::runtime_error("height out of range in modelset::sample_selection");
}
int selidx = samplemap.at(idx);
sel = &selections.at(selidx);
int randidx = rand() % sel->size();
return sel->at(randidx);
}
int data_importer::modelset::sample_selection_simple(float height)
{
throw std::runtime_error("modelset::sample_selection_simple not implemented");
int selidx = -1;
for (int i = 1; i < ranges.size(); i++)
{
if (height < ranges.at(i))
{
selidx = i;
break;
}
}
if (selidx == -1 || height < ranges.at(0))
{
throw std::runtime_error("height out of range in modelset::sample_selection_simple");
}
auto &sel = selections.at(selidx);
int randidx = rand() % sel.size();
return sel.at(randidx);
}
void data_importer::modelset::add_to_ranges(int midx)
{
auto &m = models.at(midx);
int minidx = -1;
for (int i = 0; i < ranges.size(); i++)
{
if (fabs(ranges[i] - m.hmin) < 1e-4f)
{
// this model's hmin already coincides with another range border. So we don't add this division
minidx = i;
break;
}
else if (m.hmin < ranges[i])
{
// the division at ranges[i] is the smallest div bigger than this m.hmin. Insert before it
minidx = i;
ranges.insert(std::next(ranges.begin(), i), m.hmin);
break;
}
}
if (minidx == -1)
{
//if (ranges.size() > 0)
// throw std::runtime_error("minimum value leaves a gap in ranges, in data_importer::modelset::setup_ranges");
ranges.push_back(m.hmin);
ranges.push_back(m.hmax);
//selections.push_back({midx});
}
else
{
int maxidx = -1;
for (int i = minidx + 1; i < ranges.size(); i++)
{
bool found = false;
if (fabs(ranges[i] - m.hmax) < 1e-4f)
{
found = true;
}
else if (m.hmax < ranges[i])
{
ranges.insert(std::next(ranges.begin(), i), m.hmax);
//selections.insert(std::next(selections.begin(), i - 1), {});
found = true;
}
//selections.at(i - 1).push_back(midx);
if (found)
{
maxidx = i;
break;
}
}
if (maxidx == -1)
{
ranges.push_back(m.hmax);
//selections.push_back({midx});
}
}
}
void data_importer::modelset::setup_selections()
{
selections.clear();
for (int i = 0; i < ranges.size() - 1; i++)
{
selections.push_back({});
float min = ranges[i];
float max = ranges[i + 1];
for (treemodel &m : models)
{
if (m.hmin + 1e-2f < max && m.hmax - 1e-2f > min) // allowing for quite a large margin of error here...
{
selections.back().push_back(m.vueid);
}
}
}
}
using namespace basic_types;
void data_importer::eliminate_outliers(MapFloat &data)
{
int width, height;
data.getDim(width, height);
float mean = std::accumulate(data.begin(), data.end(), 0.0f);
mean = mean / (width * height);
float stddev = std::accumulate(data.begin(), data.end(), 0.0f, [&mean](float &sum, float &val) { return sum + (val - mean) * (val - mean); });
stddev = sqrt(stddev / (width * height));
std::for_each(data.begin(), data.end(), [&mean, &stddev](float &val) { if (val > mean + 3 * stddev) val = mean; });
}
std::vector<basic_tree> data_importer::read_pdb(std::string filename)
{
std::map<int, std::vector<MinimalPlant> > retvec;
if (!read_pdb(filename, retvec))
{
throw std::runtime_error("File " + filename + " not found in data_importer::read_pdb");
}
else
{
return data_importer::minimal_to_basic(retvec);
}
}
bool data_importer::read_pdb(std::string filename, std::map<int, std::vector<MinimalPlant> > &retvec)
{
//std::vector< std::vector<basic_plant> > retvec;
std::ifstream infile;
int numcat, skip;
infile.open(filename, std::ios_base::in);
if(infile.is_open())
{
// list of prioritized categories, not all of which are used in a particular sandbox
infile >> numcat;
for(int c = 0; c < numcat; c++)
{
float junk;
int cat;
int nplants;
infile >> cat;
for (int i = 0; i < 3; i++)
infile >> junk; // skip minheight, maxheight, and avgCanopyRadToHeightRatio
infile >> nplants;
retvec[cat].resize(nplants);
for (int plnt_idx = 0; plnt_idx < nplants; plnt_idx++)
{
float x, y, z, radius, height;
infile >> x >> y >> z;
infile >> height;
infile >> radius;
MinimalPlant plnt = {x, y, height, radius, false, cat};
retvec[cat][plnt_idx] = plnt;
}
}
std::cerr << std::endl;
infile.close();
return true;
}
else
return false;
}
static std::string get_name_from_line(std::string line)
{
std::stringstream sstr(line);
std::string name;
std::getline(sstr, name, ' ');
return name;
}
static species_params parse_species_line(std::string line, std::string name)
{
std::vector<float> locs, width_scales;
std::stringstream sstr = std::stringstream(line);
std::string astr, bstr, percstr;
std::getline(sstr, astr, ' ');
std::getline(sstr, bstr, ' ');
std::getline(sstr, percstr, ' ');
float a, b, perc;
a = std::stof(astr);
b = std::stof(bstr);
perc = std::stof(percstr);
int i = 0;
for (; sstr.good(); i++)
{
float location, width_scale;
std::string token;
std::getline(sstr, token, ' ');
int mod = i % 2;
switch(mod)
{
case (0):
location = atof(token.c_str());
locs.push_back(location);
break;
case (1):
width_scale = atof(token.c_str());
width_scales.push_back(width_scale);
break;
default:
break;
}
}
while (locs.size() > width_scales.size())
{
locs.pop_back();
}
while (width_scales.size() > locs.size())
{
width_scales.pop_back();
}
return species_params(name, a, b, locs, width_scales, perc);
}
static void assign_viability(data_importer::viability &sp_vb, const data_importer::viability &vb)
{
sp_vb.cmax = vb.cmax;
sp_vb.cmin = vb.cmin;
sp_vb.c = (vb.cmax + vb.cmin) / 2.0f;
sp_vb.r = vb.cmax - vb.cmin;
}
static int sql_callback_common_data_monthlies(void *write_info, int argc, char **argv, char **colnames)
{
data_importer::common_data *common = (data_importer::common_data *)write_info;
int monthidx;
float rainfall, temperature, cloudiness;
for (int i = 0; i < argc; i++)
{
std::string valstr;
std::string colstr;
if (argv[i])
{
valstr = argv[i];
}
else
{
valstr = "NULL";
}
colstr = colnames[i];
if (colstr == "Month_ID")
{
monthidx = std::stoi(valstr);
}
else if (colstr == "Rainfall")
{
rainfall = std::stof(valstr);
}
else if (colstr == "Temperature")
{
temperature = std::stof(valstr);
}
else if (colstr == "Cloudiness")
{
cloudiness = std::stof(valstr);
}
}
common->rainfall[monthidx] = rainfall;
common->temperature[monthidx] = temperature;
common->cloudiness[monthidx] = cloudiness;
return 0;
}
static int sql_callback_common_data_biome_stats(void *write_info, int argc, char ** argv, char **colnames)
{
data_importer::common_data *common = (data_importer::common_data *)write_info;
std::string statname;
float value;
for (int i = 0; i < argc; i++)
{
std::string valstr;
std::string colstr;
if (argv[i])
{
valstr = argv[i];
}
else
{
valstr = "NULL";
}
colstr = colnames[i];
if (colstr == "Biome_stat_name")
{
statname = valstr;
}
else if (colstr == "Value")
{
value = std::stof(valstr);
}
}
if (statname == "Slope threshold")
{
common->soil_info.slopethresh = value;
}
else if (statname == "Slope maximum")
{
common->soil_info.slopemax = value;
}
else if (statname == "Evaporation rate")
{
common->soil_info.evap = value;
}
else if (statname == "Runoff limit")
{
common->soil_info.runofflim = value;
}
else if (statname == "Soil saturation limit")
{
common->soil_info.soilsat = value;
}
else if (statname == "Riverlevel")
{
common->soil_info.riverlevel = value;
}
else if (statname == "Latitude")
{
common->latitude = value;
}
else if (statname == "Temp lapse rate")
{
common->temp_lapse_rate = value;
}
return 0;
}
static int sql_callback_common_data_subbiomes(void *write_info, int argc, char ** argv, char **colnames)
{
data_importer::common_data *common = (data_importer::common_data *)write_info;
data_importer::sub_biome sb;
for (int i = 0; i < argc; i++)
{
std::string valstr;
std::string colstr;
if (argv[i])
{
valstr = argv[i];
}
else
{
valstr = "NULL";
}
colstr = colnames[i];
if (colstr == "Sub_biome_ID")
{
sb.id = std::stoi(valstr);
}
else if (colstr == "Value")
{
sb.name = valstr;
}
}
common->subbiomes[sb.id] = sb;
common->subbiomes_all_species[sb.id] = sb;
return 0;
}
static int sql_callback_common_data_subbiomes_species(void *write_info, int argc, char ** argv, char **colnames)
{
data_importer::common_data *common = (data_importer::common_data *)write_info;
int sb_id, tree_id;
for (int i = 0; i < argc; i++)
{
std::string valstr;
std::string colstr;
if (argv[i])
{
valstr = argv[i];
}
else
{
valstr = "NULL";
}
colstr = colnames[i];
if (colstr == "Sub_biome_ID")
{
sb_id = std::stoi(valstr);
}
else if (colstr == "Tree_ID")
{
tree_id = std::stoi(valstr);
}
}
data_importer::sub_biome &sb = common->subbiomes[sb_id];
data_importer::species_encoded sp;
sp.id = tree_id;
sb.species.insert(sp);
return 0;
}
static int sql_callback_common_data_subbiomes_all_species(void *write_info, int argc, char ** argv, char **colnames)
{
data_importer::common_data *common = (data_importer::common_data *)write_info;
int sb_id, tree_id;
bool canopy;
for (int i = 0; i < argc; i++)
{
std::string valstr;
std::string colstr;
if (argv[i])
{
valstr = argv[i];
}
else
{
valstr = "NULL";
}
colstr = colnames[i];
if (colstr == "Sub_biome_ID")
{
sb_id = std::stoi(valstr);
}
else if (colstr == "Tree_ID")
{
tree_id = std::stoi(valstr);
}
else if (colstr == "Canopy")
{
int canopyval = std::stoi(valstr);
if (canopyval)
{
//std::cout << "Encountered canopy species" << std::endl;
canopy = true;
}
else
canopy = false;
}
}
data_importer::sub_biome &sb = common->subbiomes_all_species[sb_id];
data_importer::species_encoded sp;
sp.id = tree_id;
sp.canopy = canopy;
auto insert_result = sb.species.insert(sp);
if (!insert_result.second)
{
auto sp_iter = sb.species.find(sp);
assert(canopy || sp_iter->canopy);
std::cout << "Inserting canopy species" << std::endl;
data_importer::species_encoded sp = *sp_iter;
sb.species.erase(sp_iter);
sp.canopy = true;
sb.species.insert(sp);
}
return 0;
}
static int sql_callback_common_data_models(void *write_info, int argc, char ** argv, char **colnames)
{
data_importer::common_data *common = (data_importer::common_data *)write_info;
int tree_id;
data_importer::treemodel model;
for (int i = 0; i < argc; i++)
{
std::string valstr;
std::string colstr;
if (argv[i])
{
valstr = argv[i];
}
else
{
valstr = "NULL";
}
colstr = colnames[i];
if (colstr == "vueid")
{
model.vueid = std::stoi(valstr);
}
else if (colstr == "Tree_ID")
{
tree_id = std::stoi(valstr);
}
else if (colstr == "hmin")
{
model.hmin = std::stof(valstr);
}
else if (colstr == "hmax")
{
model.hmax = std::stof(valstr);
}
else if (colstr == "prob")
{
model.prob = std::stof(valstr);
}
else if (colstr == "modheight")
{
model.modheight = std::stof(valstr);
}
else if (colstr == "whratio")
{
model.whratio = std::stof(valstr);
}
else if (colstr == "modname")
{
model.modname = valstr;
}
}
if (common->canopy_and_under_species.at(tree_id).maxhght < model.hmax)
{
std::cout << "WARNING: maximum height (" << model.hmax << ") for model " << model.vueid << " is higher than maximum height for species " << tree_id << ", which is " << common->canopy_and_under_species.at(tree_id).maxhght << std::endl;
}
common->modelsamplers[tree_id].add_model(model);
}
static int sql_callback_common_data_species(void *write_info, int argc, char ** argv, char **colnames)
{
//std::cout << "Processing row in sql_callback_common_data_species" << std::endl;
data_importer::common_data *common = (data_importer::common_data *)write_info;
int tree_idx;
float a, b;
data_importer::viability sun, moisture, temp, slope;
float trunkrad;
for (int i = 0; i < argc; i++)
{
std::string valstr;
std::string colstr;
if (argv[i])
{
valstr = argv[i];
}
else
{
valstr = "NULL";
}
colstr = colnames[i];
if (colstr == "Tree_ID")
{
tree_idx = std::stoi(valstr);
}
else if (colstr == "canopy")
{
if (valstr != "Y")
{
return 0; // we only look at canopy species. If not a canopy species, return, not writing
// the current row to the data struct
}
}
else if (colstr == "a")
{
a = std::stof(valstr);
}
else if (colstr == "b")
{
b = std::stof(valstr);
}
else if (colstr == "shadeval")
{
sun.cmin = std::stof(valstr);
}
else if (colstr == "sunval")
{
sun.cmax = std::stof(valstr);
}
else if (colstr == "droughtval")
{
moisture.cmin = std::stof(valstr);
}
else if (colstr == "floodval")
{
float val = std::stof(valstr);
moisture.cmax = std::stof(valstr);
}
else if (colstr == "coldval")
{
temp.cmin = std::stof(valstr);
temp.cmax = 35.0f;
}
else if (colstr == "slopeval")
{
slope.cmax = std::stof(valstr);
slope.cmin = 0.0f;
}
else if (colstr == "Max_trunk_radius")
{
trunkrad = std::stof(valstr);
}
}
data_importer::species sp;
sp.idx = tree_idx;
sp.a = a;
sp.b = b;
sp.max_trunk_radius = trunkrad;
assign_viability(sp.sun, sun);
assign_viability(sp.wet, moisture);
assign_viability(sp.temp, temp);
assign_viability(sp.slope, slope);
auto result = common->all_species.insert({sp.idx, sp});
assert(result.second); // Each species should only be inserted once. If it already exists in the map
// there is a bug
return 0;
}
static int sql_callback_common_data_all_species(void *write_info, int argc, char ** argv, char **colnames)
{
data_importer::common_data *common = (data_importer::common_data *)write_info;
int tree_idx;
float a, b;
float alpha, maxage, maxheight;
char grow_period;
int grow_start, grow_end;
float grow_m, grow_c1, grow_c2;
float draw_color [4];
float draw_height;
float draw_radius, draw_box1, draw_box2;
std::string name;
data_importer::treeshape draw_shape;
data_importer::viability sun, temp, moisture, slope;
float trunkrad;
bool iscanopy;
for (int i = 0; i < argc; i++)
{
std::string valstr;
std::string colstr;
if (argv[i])
{
valstr = argv[i];
}
else
{
valstr = "NULL";
}
colstr = colnames[i];
if (colstr == "Tree_ID")
{
tree_idx = std::stoi(valstr);
}
/*
else if (colstr == "canopy")
{
if (valstr != "Y")
{
return 0; // we only look at canopy species. If not a canopy species, return, not writing
// the current row to the data struct NOT IN THIS CASE
}
}
*/
else if (colstr == "a")
{
a = std::stof(valstr);
}
else if (colstr == "b")
{
b = std::stof(valstr);
}
else if (colstr == "maxage")
{
maxage = std::stof(valstr);
}
else if (colstr == "maxheight")
{
maxheight = std::stof(valstr);
}
else if (colstr == "alpha")
{
alpha = std::stof(valstr);
}
else if (colstr == "Growth_ID")
{
grow_period = valstr[0];
}
else if (colstr == "Start_month")
{
grow_start = std::stoi(valstr);
}
else if (colstr == "End_month")
{
grow_end = std::stoi(valstr);
}
else if (colstr == "grow_m")
{
grow_m = std::stof(valstr);
}
else if (colstr == "grow_c1")
{
grow_c1 = std::stof(valstr);
}
else if (colstr == "grow_c2")
{
grow_c2 = std::stof(valstr);
}
else if (colstr == "base_col_red")
{
draw_color[0] = std::stof(valstr);
}
else if (colstr == "base_col_green")
{
draw_color[1] = std::stof(valstr);
}
else if (colstr == "base_col_blue")
{
draw_color[2] = std::stof(valstr);
}
else if (colstr == "draw_height")
{
draw_height = std::stof(valstr);
}
else if (colstr == "draw_radius")
{
draw_radius = std::stof(valstr);
}
else if (colstr == "draw_box1")
{
draw_box1 = std::stof(valstr);
}
else if (colstr == "draw_box2")
{
draw_box2 = std::stof(valstr);
}
else if (colstr == "draw_shape")
{
if (valstr == "CONE")
{
draw_shape = data_importer::treeshape::CONE;
}
else if (valstr == "SPHR")
{
draw_shape = data_importer::treeshape::SPHR;
}
else if (valstr == "BOX")
{
draw_shape = data_importer::treeshape::BOX;
}
else if (valstr == "INVCONE")
{
draw_shape = data_importer::treeshape::INVCONE;
}
}
else if (colstr == "common_name")
{
name = valstr;
}
else if (colstr == "shadeval")
{
sun.cmin = std::stof(valstr);
}
else if (colstr == "sunval")
{
sun.cmax = std::stof(valstr);
}
else if (colstr == "droughtval")
{
moisture.cmin = std::stof(valstr);
}
else if (colstr == "floodval")
{
moisture.cmax = std::stof(valstr);
}
else if (colstr == "coldval")
{
temp.cmin = std::stof(valstr);
temp.cmax = 35.0f;
}
else if (colstr == "slopeval")
{
slope.cmax = std::stof(valstr);
slope.cmin = 0.0f;
}
else if (colstr == "Max_trunk_radius")
{
trunkrad = std::stof(valstr);
}
else if (colstr == "canopy")
{
if (valstr == "Y")
iscanopy = true;
else
iscanopy = false;
}
}
data_importer::species sp;
sp.idx = tree_idx;
sp.a = a;
sp.b = b;
sp.maxage = maxage;
sp.maxhght = maxheight;
sp.alpha = alpha;
sp.growth_period = grow_period;
sp.grow_start = grow_start;
sp.grow_end = grow_end;
if (grow_start > grow_end)
sp.grow_months = grow_end + 12 - grow_start + 1;
else
sp.grow_months = grow_end - grow_start + 1;
sp.grow_m = grow_m;
sp.grow_c1 = grow_c1;
sp.grow_c2 = grow_c2;
sp.basecol[0] = draw_color[0], sp.basecol[1] = draw_color[1], sp.basecol[2] = draw_color[2];
sp.basecol[3] = 1.0f;
sp.draw_hght = draw_height;
sp.draw_radius = draw_radius;
sp.draw_box1 = draw_box1;
sp.draw_box2 = draw_box2;
sp.name = name;
sp.max_trunk_radius = trunkrad;
sp.shapetype = draw_shape;
assign_viability(sp.slope, slope);
assign_viability(sp.sun, sun);
assign_viability(sp.temp, temp);
assign_viability(sp.wet, moisture);
auto result = common->canopy_and_under_species.insert({sp.idx, sp});
assert(result.second); // Each species should only be inserted once. If it already exists in the map
// there is a bug
if (iscanopy) // insert into the canopy species-only map also
{
result = common->all_species.insert({sp.idx, sp});
assert(result.second);
}
return 0;
}
static int sql_callback_common_data_check_tables(void *junk, int argc, char ** argv, char **colnames)
{
for (int i = 0; i < argc; i++)
{
std::string value;
if (argv[i])
value = argv[i];
else
value = "NULL";
std::cout << colnames[i] << ": " << value << std::endl;
}
std::cout << std::endl;
}
static void sql_err_handler(sqlite3 *db, int errcode, char * errmsg)
{
if (errcode != SQLITE_OK)
{
std::cout << "SQL error: " << errmsg << std::endl;
sqlite3_free(errmsg);
sqlite3_close(db);
throw std::runtime_error("SQL SELECT statment error");
}
}
data_importer::common_data::common_data(std::string db_filename)
{
sqlite3 *db;
int errcode;
std::cout << "Opening database file at " << db_filename << std::endl;
errcode = sqlite3_open(db_filename.c_str(), &db);
if (errcode)
{
std::string errstr = std::string("Cannot open database file at ") + db_filename;
sqlite3_close(db);
throw std::runtime_error(errstr.c_str());
}
char * errmsg;
errcode = sqlite3_exec(db, "SELECT Tree_ID, \
common_name, \
scientific_name, \
form, \
canopy, \
maxage, \
maxheight, \
alpha, \
species.Growth_ID as Growth_ID, \
species.Allometry_ID as Allometry_ID, \
grow_m, \
grow_c1, \
grow_c2, \
base_col_red, \
base_col_green, \
base_col_blue, \
draw_height, \
draw_radius, \
draw_box1, \
draw_box2, \
draw_shape, \
a, \
b, \
Start_month, \
End_month, \
shadeTolLow.value as shadeval, \
sunTolUpper.value as sunval, \
droughtTolLow.value as droughtval, \
floodTolUpper.value as floodval, \
coldTolLow.value as coldval, \
slopeTolUpper.value as slopeval \
FROM species INNER JOIN allometry ON species.Allometry_ID = allometry.Allometry_ID \
INNER JOIN growth ON species.Growth_ID = growth.Growth_ID \
INNER JOIN shadeTolLow ON species.shade_tol_lower = shadeTolLow.shade_tol_lower \
INNER JOIN sunTolUpper ON species.sun_tol_upper = sunTolUpper.sun_tol_upper \
INNER JOIN droughtTolLow ON species.drought_tol_lower = droughtTolLow.drought_tol_lower \
INNER JOIN floodTolUpper ON species.flood_tol_upper = floodTolUpper.flood_tol_upper \
INNER JOIN coldTolLow ON species.cold_tol_lower = coldTolLow.cold_tol_lower \
INNER JOIN slopeTolUpper ON species.slope_tol_upper = slopeTolUpper.slope_tol_upper",
sql_callback_common_data_all_species,
this,
&errmsg);
sql_err_handler(db, errcode, errmsg);
errcode = sqlite3_exec(db, "SELECT modelMapping.vueid as vueid, \
modelMapping.Tree_ID as Tree_ID, \
hmin, hmax, prob, modheight, modname, whratio \
FROM modelDetails INNER JOIN modelMapping ON modelDetails.vueid = modelMapping.vueid",
sql_callback_common_data_models, this, &errmsg);
sql_err_handler(db, errcode, errmsg);
for (auto &p : modelsamplers)
p.second.setup_ranges(); // can actually call setup_selections here, instead of this
errcode = sqlite3_exec(db, "SELECT * FROM monthlies", sql_callback_common_data_monthlies, this, &errmsg);
sql_err_handler(db, errcode, errmsg);
errcode = sqlite3_exec(db, "SELECT * FROM biome_stats", sql_callback_common_data_biome_stats, this, &errmsg);
sql_err_handler(db, errcode, errmsg);
errcode = sqlite3_exec(db, "SELECT * FROM subBiomes", sql_callback_common_data_subbiomes, this, &errmsg);
sql_err_handler(db, errcode, errmsg);
errcode = sqlite3_exec(db, "SELECT Sub_biome_ID, Tree_ID FROM subBiomesMapping WHERE Canopy = 1",
sql_callback_common_data_subbiomes_species,
this,
&errmsg);
sql_err_handler(db, errcode, errmsg);
errcode = sqlite3_exec(db, "SELECT * FROM subBiomesMapping",
sql_callback_common_data_subbiomes_all_species,
this,
&errmsg);
sql_err_handler(db, errcode, errmsg);
sqlite3_close(db);
for (auto &subb : subbiomes)
{
int subcode = subb.first;
sub_biome sbiome = subb.second;
for (auto spec_enc : sbiome.species)
{
int speccode = spec_enc.id;
canopyspec_to_subbiome[speccode] = subcode;
}
}
}
std::vector<basic_tree> data_importer::minimal_to_basic(const std::map<int, std::vector<MinimalPlant> > &plants)
{
std::vector<basic_tree> trees;
for (auto &speccls : plants)
{
int spec = speccls.first;
const std::vector<MinimalPlant> &specplants = speccls.second;
for (const auto &ctree : specplants)
{
float x, y, radius, height;
x = ctree.x;
y = ctree.y;
radius = ctree.r;
basic_tree newtree(x, y, radius, ctree.h);
newtree.species = spec;
trees.push_back(newtree);
}
}
return trees;
}
std::map<std::string, data_importer::grass_viability> data_importer::read_grass_viability(std::string filename)
{
auto get_viability = [](std::stringstream &sstr, grass_viability &v) {
sstr >> v.absmin;
sstr >> v.innermin;
sstr >> v.innermax;
sstr >> v.absmax;
};
std::ifstream ifs(filename);
if (!ifs.is_open())
{
throw std::invalid_argument("Could not open grass viability parameters file at " + filename);
}
std::string line;
std::map<std::string, grass_viability> vs;
bool moisture_good = false, sun_good = false, temp_good = false;
for (int i = 0; i < 3; i++)
{
std::getline(ifs, line);
std::stringstream sstr(line);
std::string token;
sstr >> token;
for (auto &ch : token)
ch = tolower(ch);
if (token == "moisture")
{
moisture_good = true;
}
else if (token == "sunlight")
{
sun_good = true;
}
else if (token == "temperature")
{
temp_good = true;
}
else
{
throw std::invalid_argument("Error parsing grass viability file at " + filename);
}
get_viability(sstr, vs[token]);
}
if (!(temp_good && sun_good && moisture_good))
{
throw std::invalid_argument("Error importing grass viability file at " + filename);
}
return vs;
}
| 36,596
|
C++
|
.cpp
| 1,156
| 22.378028
| 242
| 0.514309
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,237
|
extract_png.cpp
|
jgain_EcoLearn/data_importer/extract_png.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include <libpng16/png.h>
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <algorithm>
#include <cstring>
#include "extract_png.h"
using namespace std;
static int width, height;
static png_bytep *row_pointers;
static png_byte nchannels_byte;
static png_byte color_type_byte;
static png_byte bit_depth_byte;
bool read_png_file(char *filename) {
FILE *fp = fopen(filename, "rb");
if (!fp)
{
cout << "Could not open file at " << filename << endl;
return false;
}
png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png) abort();
png_infop info = png_create_info_struct(png);
if(!info) abort();
if(setjmp(png_jmpbuf(png))) abort();
png_init_io(png, fp);
png_read_info(png, info);
width = png_get_image_width(png, info);
height = png_get_image_height(png, info);
color_type_byte = png_get_color_type(png, info);
bit_depth_byte = png_get_bit_depth(png, info);
nchannels_byte = png_get_channels(png, info);
cout << "bit depth of image: " << (uint32_t)bit_depth_byte << endl;
cout << "number of channels: " << (uint32_t)nchannels_byte << endl;
cout << "Width, height: " << width << ", " << height << endl;
if(bit_depth_byte == 16)
{
png_set_swap(png);
}
if(color_type_byte == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png);
if(png_get_valid(png, info, PNG_INFO_tRNS))
png_set_tRNS_to_alpha(png);
switch (color_type_byte)
{
case(PNG_COLOR_TYPE_RGB):
cout << "Color type is RGB" << endl;
break;
default:
break;
}
png_read_update_info(png, info);
row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * height);
for(int y = 0; y < height; y++) {
row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png,info));
}
png_read_image(png, row_pointers);
bool not_all_equal = false;
for (int i = 0; i < width * 6; i += 6)
{
uint32_t prev_val = (uint32_t)*(uint16_t *)&row_pointers[0][i];
for (int row = 1; row < height; row++)
{
uint32_t val = (uint32_t)*(uint16_t *)&row_pointers[row][i];
if (val != prev_val)
{
not_all_equal = true;
}
prev_val = val;
}
}
fclose(fp);
return true;
}
uint8_t ** make_row_ptrs(const std::vector<uint16_t> &data, int width, int height)
{
uint8_t **row_ptrs = (uint8_t**)malloc(height * sizeof(uint8_t*));
for (int row = 0; row < height; row++)
{
row_ptrs[row] = (uint8_t*)((uint16_t*)data.data() + 3*width * row);
}
return row_ptrs;
}
int write_png(std::string img_path, const std::vector<uint16_t> &data, int width, int height)
{
FILE *fp = fopen(img_path.c_str(), "wb");
if (!fp)
return 1;
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
return 1;
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
return 1;
if (setjmp(png_jmpbuf(png_ptr)))
return 1;
png_init_io(png_ptr, fp);
png_set_IHDR(
png_ptr,
info_ptr,
width, height,
16,
PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT
);
png_write_info(png_ptr, info_ptr);
uint8_t ** row_ptrs = make_row_ptrs(data, width, height);
for (int row = 0; row < height; row++)
{
for (int i = 0; i < width * 6; i += 2)
{
swap(row_ptrs[row][i], row_ptrs[row][i + 1]);
//uint32_t val = (uint32_t)*(uint16_t *)&row_ptrs[row][i];
}
}
png_write_image(png_ptr, row_ptrs);
png_write_end(png_ptr, NULL);
bool not_all_equal = false;
for (int i = 0; i < width * 6; i += 6)
{
uint32_t prev_val = (uint32_t)*(uint16_t *)&row_ptrs[0][i];
for (int row = 1; row < height; row++)
{
uint32_t val = (uint32_t)*(uint16_t *)&row_ptrs[row][i];
if (val != prev_val)
{
not_all_equal = true;
}
prev_val = val;
}
}
free(row_ptrs);
fclose(fp);
return 0;
}
int write_png(std::string img_path, const std::vector<float> &data, int width, int height)
{
vector<uint16_t> img_data = create_img_data(data);
return write_png(img_path, img_data, width, height);
}
int write_png(std::string img_path, const float *data, int width, int height)
{
vector<uint16_t> img_data = create_img_data(data, width * height);
return write_png(img_path, img_data, width, height);
}
vector<vector<uint16_t> > get_image_vals_48bit(const char * img_path_param, int string_len, int &img_width, int &img_height)
{
char * img_path = (char *)malloc(sizeof(char) * string_len);
memcpy(img_path, img_path_param, string_len * sizeof(char));
if (!read_png_file(img_path))
{
return {};
}
img_width = width;
img_height = height;
vector< vector<uint16_t> > vecs((uint32_t)nchannels_byte, vector<uint16_t>(width * height));
//vector<uint16_t> vals(width * height);
uint8_t *row_ptr;
int stride = (uint32_t)nchannels_byte * (uint32_t)bit_depth_byte / 8; //number of bytes per pixel
//cout << "stride: " << stride << endl;
for (int row = 0; row < height; row++)
{
row_ptr = row_pointers[row];
for (int col = 0; col < width; col++)
{
uint16_t val;
for (int channel = 0; channel < (uint32_t)nchannels_byte; channel++)
{
uint8_t *val_ptr = (uint8_t*)row_ptr + col * stride + channel * (uint32_t)bit_depth_byte / 8;
val = *((uint16_t *)val_ptr);
vecs[channel][width * row + col] = val;
}
}
}
for(int y = 0; y < height; y++) {
free(row_pointers[y]);
}
free(row_pointers);
free(img_path);
return vecs;
}
vector<vector<uint8_t> > get_image_vals_8bit(const char * img_path_param, int string_len, int &img_width, int &img_height)
{
char * img_path = (char *)malloc(sizeof(char) * string_len);
memcpy(img_path, img_path_param, string_len * sizeof(char));
if (!read_png_file(img_path))
{
return {};
}
img_width = width;
img_height = height;
vector< vector<uint8_t> > vecs((uint32_t)nchannels_byte, vector<uint8_t>(width * height));
//vector<uint16_t> vals(width * height);
uint8_t *row_ptr;
int stride = (uint32_t)nchannels_byte * (uint32_t)bit_depth_byte / 8; //number of bytes per pixel
//cout << "stride: " << stride << endl;
for (int row = 0; row < height; row++)
{
row_ptr = row_pointers[row];
for (int col = 0; col < width; col++)
{
uint8_t val;
for (int channel = 0; channel < (uint32_t)nchannels_byte; channel++)
{
uint8_t *val_ptr = (uint8_t*)row_ptr + col * stride + channel * (uint32_t)bit_depth_byte / 8;
val = *((uint8_t *)val_ptr);
vecs[channel][width * row + col] = val;
}
}
}
for(int y = 0; y < height; y++) {
free(row_pointers[y]);
}
free(row_pointers);
free(img_path);
return vecs;
}
vector<uint16_t> create_img_data(const vector<float> &data)
{
vector<uint16_t> img_data(3 * data.size());
for (int i = 0; i < data.size(); i++)
{
for (int channel = 0; channel < 3; channel++)
{
img_data[i * 3 + channel] = static_cast<uint16_t>(data[i]);
}
}
return img_data;
}
vector<uint16_t> create_img_data(const float *data, int size)
{
vector<uint16_t> img_data(3 * size);
for (int i = 0; i < size; i++)
{
for (int channel = 0; channel < 3; channel++)
{
img_data[i * 3 + channel] = static_cast<uint16_t>(data[i]);
}
}
return img_data;
}
vector<vector<float> > get_image_data_48bit(string img_path, int &img_width, int &img_height)
{
vector< vector<uint16_t> > vecs = get_image_vals_48bit(img_path.c_str(), img_path.size() + 1, img_width, img_height);
if (vecs.size() == 0)
{
return {};
}
vector<vector<float> > fvecs(vecs.size(), vector<float>(vecs[0].size()));
auto cast_for_transform = [](const uint16_t &val) { return static_cast<float>(val); };
for (int i = 0; i < fvecs.size(); i++)
{
int zero_count = 0;
uint32_t value_sum = 0;
for (auto &v : vecs[i])
{
if (v == 0)
zero_count++;
value_sum += v;
}
transform(vecs[i].begin(), vecs[i].end(), fvecs[i].begin(), cast_for_transform);
}
return fvecs;
}
vector<vector<float> > get_image_data_8bit(string img_path, int &img_width, int &img_height)
{
vector< vector<uint8_t> > vecs = get_image_vals_8bit(img_path.c_str(), img_path.size() + 1, img_width, img_height);
if (vecs.size() == 0)
{
return {};
}
vector<vector<float> > fvecs(vecs.size(), vector<float>(vecs[0].size()));
auto cast_for_transform = [](const uint8_t &val) { return static_cast<float>(val); };
for (int i = 0; i < fvecs.size(); i++)
{
int zero_count = 0;
uint32_t value_sum = 0;
for (auto &v : vecs[i])
{
if (v == 0)
zero_count++;
value_sum += v;
}
transform(vecs[i].begin(), vecs[i].end(), fvecs[i].begin(), cast_for_transform);
}
return fvecs;
}
/*
int main(int argc, char *argv[]) {
if(argc != 2)
{
std::cout << "usage: ./libpng_test <input_file>" << std::endl;
exit(1);
}
int string_len = 0;
char * ch = argv[1];
while (*(ch++) != '\0' && string_len < 512)
{
string_len++;
}
if (string_len == 512)
{
std::cout << "string argument must be less than 512 characters" << std::endl;
exit(1);
}
string_len++;
vector<uint16_t> vals = get_image_vals_48bit(argv[1], string_len);
for (int i = 0; i < width / 2; i++)
{
cout << (uint32_t)vals[i] << " ";
}
cout << endl;
return 0;
}
*/
| 10,455
|
C++
|
.cpp
| 338
| 27.159763
| 124
| 0.612135
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,238
|
convert_to_bin.cpp
|
jgain_EcoLearn/data_importer/convert_to_bin.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "AbioticMapper.h"
#include "data_importer.h"
void convert_ifnot_bin(std::string fname)
{
if (!data_importer::data_dir::is_binary(fname))
{
auto mmap = data_importer::read_monthly_map<ValueGridMap<float> >(fname);
std::string binfname = fname.substr(0, fname.size() - 3);
binfname += "bin";
data_importer::write_monthly_map_binary(binfname, mmap);
}
}
int main(int argc, char * argv [])
{
if (argc != 2)
{
std::cout << "Usage: convert_to_bin <dirname>" << std::endl;
return 1;
}
data_importer::data_dir ddir(argv[1]);
convert_ifnot_bin(ddir.temp_fname);
convert_ifnot_bin(ddir.sun_fname);
convert_ifnot_bin(ddir.wet_fname);
return 0;
}
| 1,617
|
C++
|
.cpp
| 44
| 34.636364
| 82
| 0.654952
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,239
|
AbioticMapper.cpp
|
jgain_EcoLearn/data_importer/AbioticMapper.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "AbioticMapper.h"
#include "common/basic_types.h"
#include "data_importer/data_importer.h"
#include "data_importer/map_procs.h"
#include <chrono>
abiotic_maps_package::abiotic_maps_package(const ValueGridMap<float> &wet,
const ValueGridMap<float> &sun,
const ValueGridMap<float> &temp,
const ValueGridMap<float> &slope)
: wet(wet), sun(sun), temp(temp), slope(slope)
{
validate_maps();
}
// TODO: let the caller optionally give a monthly, or average filename for moisture and sunlight
abiotic_maps_package::abiotic_maps_package(std::string wet_fname, std::string sun_fname, std::string temp_fname, std::string slope_fname, aggr_type aggr)
{
if (aggr == aggr_type::AVERAGE)
{
slope = data_importer::load_txt<ValueGridMap<float> >(slope_fname);
std::map<std::string, ValueGridMap<float> *> datas;
std::map<std::string, std::string> fnames;
std::vector<std::string> types = {"temp", "sun", "wet"};
fnames["temp"] = temp_fname;
fnames["sun"] = sun_fname;
fnames["wet"] = wet_fname;
datas["temp"] = &temp;
datas["sun"] = &sun;
datas["wet"] = &wet;
for (auto &tp : types)
{
std::string fname = fnames[tp];
auto bt = std::chrono::steady_clock::now().time_since_epoch();
std::vector<ValueGridMap<float> > vec;
if (fname.substr(fname.size() - 3, 3) == "bin")
vec = data_importer::read_monthly_map_binary<ValueGridMap<float> >(fname);
else if (fname.substr(fname.size() - 3, 3) == "txt")
vec = data_importer::read_monthly_map<ValueGridMap<float> >(fname);
else
throw std::invalid_argument(tp + " name argument " + fname + " has an unknown extension");
auto et = std::chrono::steady_clock::now().time_since_epoch();
std::cout << "Time for reading " << tp << " data: " << std::chrono::duration_cast<std::chrono::milliseconds>(et - bt).count() << std::endl;
//temp = average_monthly_data_hostcall(tempvec, w, h, rw, rh);
*datas[tp] = average_monthly_data_hostcall(vec);
auto finet = std::chrono::steady_clock::now().time_since_epoch();
//last_rw = rw, last_rh = rh, last_w = w, last_h = h;
std::cout << "Time for averaging " << tp << " data: " << std::chrono::duration_cast<std::chrono::milliseconds>(finet - et).count() << std::endl;
}
}
else
{
int monthidx = static_cast<int>(aggr);
slope = data_importer::load_txt<ValueGridMap<float> >(slope_fname);
temp = data_importer::read_monthly_map<ValueGridMap<float>>(temp_fname).at(monthidx);
wet = data_importer::read_monthly_map<ValueGridMap<float>>(wet_fname).at(monthidx);
sun = data_importer::read_monthly_map<ValueGridMap<float>>(sun_fname).at(monthidx);
}
validate_maps();
}
abiotic_maps_package::abiotic_maps_package(data_importer::data_dir targetdir, suntype sun, aggr_type aggr)
: abiotic_maps_package(targetdir.wet_fname, sun == suntype::CANOPY ? targetdir.sun_tree_fname : targetdir.sun_fname, targetdir.temp_fname, targetdir.slope_fname, aggr)
{}
void abiotic_maps_package::validate_maps()
{
wet.getDimReal(rw, rh);
wet.getDim(gw, gh);
if (fabs(rw) < 1e-5f || fabs(rh) < 1e-5f)
{
throw std::runtime_error("Moisture abiotic map does not have a step parameter");
}
sun.getDimReal(rw, rh);
if (fabs(rw) < 1e-5f || fabs(rh) < 1e-5f)
{
throw std::runtime_error("Sunlight abiotic map does not have a step parameter");
}
temp.getDimReal(rw, rh);
if (fabs(rw) < 1e-5f || fabs(rh) < 1e-5f)
{
throw std::runtime_error("Temperature abiotic map does not have a step parameter");
}
slope.getDimReal(rw, rh);
if (fabs(rw) < 1e-5f || fabs(rh) < 1e-5f)
{
throw std::runtime_error("Slope abiotic map does not have a step parameter");
}
if (!slope.eqdim(temp) || !slope.eqdim(sun) || !slope.eqdim(wet))
{
throw std::runtime_error("Some abiotic maps are not equal in terms of grid or real size");
}
}
| 5,137
|
C++
|
.cpp
| 108
| 41.240741
| 171
| 0.620841
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,241
|
validate_canopytree_mod.cpp
|
jgain_EcoLearn/tests/validator/validate_canopytree_mod.cpp
|
#include "ClusterMatrices.h"
int main(int argc, char * argv [])
{
std::string targetdir, db_pathname, pdb_pathname;
if (argc < 3 || argc > 4)
{
std::cout << "Usage: validate_addremove <targetdir> <db pathname> [pdb pathname]" << std::endl;
return 1;
}
else if (argc >= 3)
{
targetdir = argv[1];
db_pathname = argv[2];
if (argc == 4)
{
pdb_pathname = argv[3];
}
}
abiotic_maps_package amaps(targetdir, abiotic_maps_package::suntype::CANOPY, abiotic_maps_package::aggr_type::APRIL);
data_importer::data_dir ddir(targetdir, 1);
std::vector<basic_tree> canopytrees, underplants;
canopytrees = data_importer::read_pdb(ddir.canopy_fnames.at(0));
if (pdb_pathname.size() > 0)
{
underplants = data_importer::read_pdb(pdb_pathname);
}
else
{
underplants = data_importer::read_pdb(ddir.undergrowth_fnames.at(0));
}
ClusterMatrices::test_canopytree_add_remove({"/home/konrad/PhDStuff/clusters1024/S4500-4500-1024-1_distribs.clm"}, targetdir, amaps, db_pathname, canopytrees, underplants, ClusterMatrices::layerspec::CANOPY);
return 0;
}
| 1,192
|
C++
|
.cpp
| 33
| 30.090909
| 212
| 0.642671
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,242
|
validate_underdensity.cpp
|
jgain_EcoLearn/tests/validator/validate_underdensity.cpp
|
#include "ClusterMatrices.h"
#include "data_importer.h"
int main(int argc, char * argv [])
{
/*
auto canopytrees = data_importer::read_pdb("/home/konrad/PhDStuff/abioticfixed/S4500-4500-1024/S4500-4500-1024_canopy0.pdb");
abiotic_maps_package amaps(data_importer::data_dir("/home/konrad/PhDStuff/abioticfixed/S4500-4500-1024/"), abiotic_maps_package::suntype::LANDSCAPE_ONLY, abiotic_maps_package::aggr_type::APRIL);
std::unique_ptr<ClusterMatrices> clptr = ClusterMatrices::CreateClusterMatrices({"/home/konrad/PhDStuff/data/clusters_test_1024.clm"}, "/home/konrad/PhDStuff/abioticfixed/S4500-4500-1024/", amaps, "/home/konrad/EcoSynth/ecodata/sonoma.db", &canopytrees);
auto plnthashmap = clptr->sample_from_probmap(nullptr);
auto plnts = clptr->get_sampled_plants();
data_importer::write_pdb("/home/konrad/PhDStuff/undergrowth_test1.pdb", plnts.data(), plnts.data() + plnts.size());
*/
}
| 926
|
C++
|
.cpp
| 13
| 67.538462
| 258
| 0.745055
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,243
|
main.cpp
|
jgain_EcoLearn/tests/validator/main.cpp
|
#include <iostream>
#include <experimental/filesystem>
#include "validator.h"
#include "data_importer.h"
#include <ctype.h>
#include <cassert>
void print_result(std::string category, int result)
{
std::cout << category << ": ";
if (result > 0)
{
std::cout << "SUCCESS";
}
else if (result == 0)
{
std::cout << "FAIL";
}
else if (result < 0)
{
std::cout << "NOT TESTED";
}
std::cout << std::endl;
}
int main(int argc, char * argv [])
{
std::map<int, std::vector<std::string> > pdb_filenames;
std::string datadir, dbpathname;
if (argc > 5 || argc < 4)
{
std::cout << "Usage: main <pdb descr> <data directory> <db filename> --pipeout_num" << std::endl;
return 1;
}
else if (argc == 4)
{
datadir = argv[2];
pdb_filenames[-1].push_back(std::string(argv[1]));
dbpathname = argv[3];
}
else if (argc == 5 && std::string(argv[4]) == "--pipeout_num")
{
using namespace std::experimental::filesystem;
datadir = argv[2];
dbpathname = argv[3];
path pipepath_base = path(datadir);
pipepath_base /= path("pipe_out");
bool validspec = false;
std::string containsstr;
if (std::string(argv[1]) == "canopy")
{
validspec = true;
}
else if (std::string(argv[1]) == "undergrowth_quick")
{
validspec = true;
}
else if (std::string (argv[1]) == "undergrowth")
{
validspec = true;
}
else
{
std::cout << "Usage: main <pdb descr> <data directory> --pipeout_num" << std::endl;
throw std::invalid_argument("pdb descr parameter must be either 'canopy' or 'undergrowth' if --pipeout_num is given");
}
containsstr = argv[1];
try
{
for (auto &f : directory_iterator(datadir))
{
path p = f.path();
path pname = p.filename();
std::string pstr = pname.string();
std::string numstr;
while (isdigit(pstr.back()))
{
numstr.insert(numstr.begin(), pstr.back());
pstr.pop_back();
}
if (pstr == "pipe_out")
{
int num = std::stoi(numstr);
try
{
for (auto &fp : directory_iterator(p))
{
std::string fpname = fp.path().filename().string();
if (fpname.find(containsstr) != std::string::npos)
{
if (fp.path().filename().extension().string() == ".pdb")
pdb_filenames[num].push_back(fp.path().string());
}
}
}
catch (v1::__cxx11::filesystem_error &e)
{
throw v1::__cxx11::filesystem_error(std::string(std::string(e.what()) + "\nAdditional info: error when opening directory " + p.string()).c_str(), std::make_error_code(std::errc::no_such_file_or_directory));
}
}
}
}
catch (v1::__cxx11::filesystem_error &e)
{
throw v1::__cxx11::filesystem_error(std::string(std::string(e.what()) + "\nAdditional info: error when opening directory " + datadir).c_str(), std::make_error_code(std::errc::no_such_file_or_directory));
}
}
else
{
std::cout << "Usage: main <pdb descr> <data directory> <db pathname> --pipeout_num" << std::endl;
}
/*
for (auto &f : pdb_filenames)
{
std::cout << f << std::endl;
}
*/
//validator v("/home/konrad/pipeline_canopytrees1.pdb", "/home/konrad/PhDStuff/data/analyse_specassign0");
std::vector<std::string> fail_fnames;
data_importer::common_data cdata(dbpathname);
data_importer::modelset &mset = cdata.modelsamplers.at(15);
int vueid = mset.sample_selection_fast(60.0f);
printf("vueid selected for species id %d at height %f\n", 15, 60.0f);
return 0;
for (auto &p: pdb_filenames)
{
if (p.first > -1)
{
std::cout << "Validation for pipeline output " << p.first << ": " << std::endl;
}
else
{
assert(pdb_filenames.size() == 1);
std::cout << "Validation for pdb file: ";
}
for (auto &fname : p.second)
{
std::cout << "------------------------------" << std::endl;
std::cout << fname << std::endl;
validator v(fname, datadir);
bool valid = true;
if (!v.validate_bounds()) valid = false;
if (!v.validate_intersect()) valid = false;
if (!v.validate_water(false)) valid = false;
if (!valid) fail_fnames.push_back(fname);
print_result("WATER", v.water_isvalid());
print_result("BOUNDS", v.bounds_isvalid());
print_result("INTERSECT", v.intersect_isvalid());
if (v.bounds_isvalid() == 0)
{
v.analyse_boundsfailure();
}
}
std::cout << "------------------------------" << std::endl;
}
if (fail_fnames.size() > 0)
{
std::cout << "Following pdb files had problems: " << std::endl;
for (auto &fname : fail_fnames)
{
std::cout << fname << std::endl;
}
}
else
{
std::cout << "All succeeded" << std::endl;
}
return 0;
}
| 5,746
|
C++
|
.cpp
| 167
| 24.005988
| 231
| 0.485426
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,244
|
validate_addremove.cpp
|
jgain_EcoLearn/tests/validator/validate_addremove.cpp
|
#include "ClusterMatrices.h"
#include "data_importer.h"
int main(int argc, char * argv [])
{
std::string targetdir, db_pathname, pdb_pathname;
if (argc < 3 || argc > 4)
{
std::cout << "Usage: validate_addremove <targetdir> <db pathname> [pdb pathname]" << std::endl;
return 1;
}
else if (argc >= 3)
{
targetdir = argv[1];
db_pathname = argv[2];
if (argc == 4)
{
pdb_pathname = argv[3];
}
}
abiotic_maps_package amaps(targetdir, abiotic_maps_package::suntype::CANOPY, abiotic_maps_package::aggr_type::APRIL);
data_importer::data_dir ddir(targetdir, 1);
std::vector<basic_tree> canopytrees, underplants;
canopytrees = data_importer::read_pdb(ddir.canopy_fnames.at(0));
if (pdb_pathname.size() > 0)
{
underplants = data_importer::read_pdb(pdb_pathname);
}
else
{
underplants = data_importer::read_pdb(ddir.undergrowth_fnames.at(0));
}
ClusterMatrices::test_add_remove({"/home/konrad/PhDStuff/clusters1024/S4500-4500-1024-1_distribs.clm"}, targetdir, amaps, db_pathname, canopytrees, underplants, ClusterMatrices::layerspec::CANOPY);
}
| 1,194
|
C++
|
.cpp
| 33
| 30.272727
| 201
| 0.644156
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,245
|
validator.cpp
|
jgain_EcoLearn/tests/validator/validator.cpp
|
#include "validator.h"
#include "canopy_placement/basic_types.h"
#include "data_importer.h"
validator::validator(std::string pdbfilename, std::string datadir)
: validator(data_importer::read_pdb(pdbfilename), datadir)
{
}
validator::validator(const std::vector<basic_tree> &plants, std::string datadir)
: plants(plants), bounds_valid(-1), water_valid(-1), intersect_valid(-1), slope_valid(-1)
{
data_importer::data_dir ddir(datadir, 1);
moisture = data_importer::read_monthly_map<ValueGridMap<float> >(ddir.wet_fname);
sun = data_importer::read_monthly_map<ValueGridMap<float> >(ddir.sun_fname);
temp = data_importer::read_monthly_map<ValueGridMap<float> >(ddir.temp_fname);
dem = data_importer::load_elv<ValueGridMap<float> >(ddir.dem_fname);
chm = data_importer::load_txt<ValueGridMap<float> >(ddir.chm_fname);
moisture_avg = data_importer::average_mmap<ValueGridMap<float>, ValueGridMap<float> >(moisture);
sun_avg = data_importer::average_mmap<ValueGridMap<float>, ValueGridMap<float> >(sun);
temp_avg = data_importer::average_mmap<ValueGridMap<float>, ValueGridMap<float> >(temp);
}
int validator::validate_bounds()
{
float width, height;
dem.getDimReal(width, height);
bounds_valid = 1;
for (auto &plnt : plants)
{
if (!is_within_landscape(plnt.x, plnt.y))
{
bounds_valid = 0;
return 0;
}
}
return bounds_valid;
}
int validator::validate_water(bool monthly_validate)
{
water_valid = 1;
for (auto &plnt : plants)
{
if (monthly_validate)
{
for (auto &vgmap : moisture)
{
if (vgmap.get_fromreal(plnt.x, plnt.y) > 1999.0f) // 2000.0f is supposed to be standing water (check waterfill program, in the MoistureSim::simSoilCycle function)
{
water_valid = 0;
return 0;
}
}
}
else
{
if (moisture_avg.get_fromreal(plnt.x, plnt.y) > 1999.0f)
{
water_valid = 0;
return 0;
}
}
}
return water_valid;
}
int validator::validate_intersect()
{
intersect_valid = 1;
float sq_trunksize = 0.2f * 0.2f;
for (int i = 0; i < plants.size(); i++)
{
for (int j = i + 1; j < plants.size(); j++)
{
const basic_tree &plnt1 = plants.at(i);
const basic_tree &plnt2 = plants.at(j);
float dsq = (plnt1.x - plnt2.x) * (plnt1.x - plnt2.x) + (plnt1.y - plnt2.y) * (plnt1.y - plnt2.y);
if (dsq < sq_trunksize)
{
intersect_valid = 0;
return 0;
}
}
}
return intersect_valid;
}
int validator::water_isvalid()
{
return water_valid;
}
int validator::bounds_isvalid()
{
return bounds_valid;
}
std::vector<basic_tree> validator::analyse_boundsfailure()
{
std::vector<basic_tree> outplants;
for (auto &plnt : plants)
{
if (!is_within_landscape(plnt.x, plnt.y))
{
outplants.push_back(plnt);
}
}
float w, h;
dem.getDimReal(w, h);
std::cout << "Out of bound plants for landscape " << w << " x " << h << ": " << std::endl;
for (auto &op : outplants)
{
std::cout << op.x << ", " << op.y << ", " << op.radius << std::endl;
}
std::cout << "Number of out of bound plants: " << outplants.size() << std::endl;
return outplants;
}
int validator::intersect_isvalid()
{
return intersect_valid;
}
bool validator::is_within(float min, float max, float val)
{
return val >= min && val <= max;
}
bool validator::is_within(float min1, float min2, float max1, float max2, float val1, float val2)
{
return is_within(min1, max1, val1) && is_within(min2, max2, val2);
}
bool validator::is_within_landscape(float x, float y)
{
float width, height;
dem.getDimReal(width, height);
return is_within(0.0f, 0.0f, width, height, x, y);
}
| 4,047
|
C++
|
.cpp
| 128
| 25.328125
| 179
| 0.598512
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,246
|
validate_commondata.cpp
|
jgain_EcoLearn/tests/validator/validate_commondata.cpp
|
#include "data_importer.h"
#include <fstream>
#include <chrono>
int main(int argc, char * argv [])
{
if (argc != 3)
{
std::cout << "Usage: validate_commondata <db pathname> <output_pathname>" << std::endl;
return 1;
}
std::string dbpathname = argv[1];
std::string output_pathname = argv[2];
data_importer::common_data cdata(dbpathname);
std::ofstream ofs(output_pathname);
srand(std::chrono::steady_clock::now().time_since_epoch().count());
for (int i = 0; i < 10000; i++)
{
int specid = rand() % 16;
float height = (rand() % 9500 + 500) / 10000.0f * cdata.canopy_and_under_species.at(specid).maxhght;
int vueid;
float radius = cdata.modelsamplers.at(specid).sample_rh_ratio(height, &vueid) * height;
std::string buf;
buf.resize(256);
int nchar = sprintf((char *)buf.data(), "%d %f %f %d %f", specid, height, radius, vueid, radius * 2 / height);
buf.resize(nchar);
//printf("--------------------------------------\n");
ofs << buf << std::endl;
}
return 0;
}
| 1,112
|
C++
|
.cpp
| 30
| 30.933333
| 118
| 0.573694
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,247
|
validate_clusterfile.cpp
|
jgain_EcoLearn/tests/validator/validate_clusterfile.cpp
|
#include "data_importer.h"
#include "ClusterMatrices.h"
int main(int argc, char * argv [])
{
ClusterMatrices::AllClusterInfo clinfo = ClusterMatrices::import_clusterinfo({"/home/konrad/PhDStuff/data/clusters1024.clm"}, "/home/konrad/EcoSynth/ecodata/sonoma.db");
std::cout << "Number of clusters in all_distribs vector: " << clinfo.all_distribs.at(0).size() << std::endl;
clinfo.print_densities();
return 0;
}
| 429
|
C++
|
.cpp
| 9
| 44.555556
| 173
| 0.724221
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,248
|
rw_sampler.cpp
|
jgain_EcoLearn/tests/validator/rw_sampler.cpp
|
#include "rw_sampler.h"
#include <iostream>
int main(int argc, char * argv [])
{
rw_sampler rws = rw_sampler({2.0, 5.0, 8.2, 9.3});
bool success = rws.test_sample();
if (success)
{
std::cout << "SUCCESS: RW sampler passed test" << std::endl;
}
else
std::cout << "FAIL: RW sampler failed test" << std::endl;
return 0;
}
| 364
|
C++
|
.cpp
| 14
| 21.785714
| 68
| 0.584527
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,249
|
main_read.cpp
|
jgain_EcoLearn/tests/test_binary_readwrite/main_read.cpp
|
#include "../data_importer/data_importer.h"
#include <chrono>
int main(int argc, char * argv [])
{
std::string mapname = "/home/konrad/PhDStuff/S1000-1000-3072_sun_landscape.txt";
std::string mapold = "/home/konrad/PhDStuff/abioticfixed/S1000-1000-3072/S1000-1000-3072_wet.txt";
std::string bininname = "/home/konrad/PhDStuff/binwet_out.bin";
auto bt = std::chrono::steady_clock::now().time_since_epoch();
auto mmap = data_importer::read_monthly_map_binary<ValueGridMap<float> >(bininname);
auto et = std::chrono::steady_clock::now().time_since_epoch();
std::cout << "Time to read file " << bininname << " (ms): " << std::chrono::duration_cast<std::chrono::milliseconds>(et - bt).count() << std::endl;
bt = std::chrono::steady_clock::now().time_since_epoch();
auto mmap_avg = data_importer::average_mmap<ValueGridMap<float> >(mmap);
et = std::chrono::steady_clock::now().time_since_epoch();
std::cout << "Time to average monthly map: " << std::chrono::duration_cast<std::chrono::milliseconds>(et - bt).count() << std::endl;
/*
bt = std::chrono::steady_clock::now().time_since_epoch();
auto mmap2 = data_importer::read_monthly_map<ValueGridMap<float> >(mapold);
et = std::chrono::steady_clock::now().time_since_epoch();
std::cout << "Time to read file " << mapold << " (ms): " << std::chrono::duration_cast<std::chrono::milliseconds>(et - bt).count() << std::endl;
*/
//data_importer::write_monthly_map(mapname, mmap);
return 0;
}
| 1,467
|
C++
|
.cpp
| 24
| 58.583333
| 148
| 0.691228
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,250
|
main.cpp
|
jgain_EcoLearn/tests/test_binary_readwrite/main.cpp
|
#include "../data_importer/data_importer.h"
int main(int argc, char * argv [])
{
std::string mapname = "/home/konrad/PhDStuff/abioticfixed/S1000-1000-3072/S1000-1000-3072_wet.txt";
std::string outname = "/home/konrad/PhDStuff/binwet_out.bin";
auto mmap = data_importer::read_monthly_map<ValueGridMap<float> >(mapname);
data_importer::write_monthly_map_binary(outname, mmap);
return 0;
}
| 398
|
C++
|
.cpp
| 9
| 42
| 100
| 0.749347
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,251
|
test_add2.cpp
|
jgain_EcoLearn/tests/test_hashmap/src/test_add2.cpp
|
#include "PlantSpatialHashmap.h"
int main(int argc, char * argv [])
{
PlantSpatialHashmap map(10.0f, 10.0f, 100.0f, 100.0f);
if (map.test_add())
{
return 0;
}
else
return 1;
}
| 214
|
C++
|
.cpp
| 11
| 15
| 58
| 0.59204
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,252
|
test_add1.cpp
|
jgain_EcoLearn/tests/test_hashmap/src/test_add1.cpp
|
#include "PlantSpatialHashmap.h"
int main(int argc, char * argv [])
{
PlantSpatialHashmap map(10.0f, 10.0f, 90.0f, 90.0f);
if (map.test_add())
{
return 0;
}
else
return 1;
}
| 185
|
C++
|
.cpp
| 11
| 14.818182
| 53
| 0.680233
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,253
|
constants.cpp
|
jgain_EcoLearn/common/constants.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "constants.h"
#include "cluster_distribs/src/HistogramDistrib.h"
#include "cluster_distribs/src/HistogramMatrix.h"
HistogramDistrib::Metadata HistogramMatrix::global_canopy_metadata = {
5.0f, // maxdist
3, // nreserved_bins
5, // nreal_bins
8, // ntotal_bins
5.0f / 5 // binwidth
};
HistogramDistrib::Metadata HistogramMatrix::global_under_metadata = {
5.0f, // maxdist
3, // nreserved_bins
5, // nreal_bins
8, // ntotal_bins
5.0f / 5 // binwidth
};
| 1,459
|
C++
|
.cpp
| 36
| 37.805556
| 82
| 0.638478
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,254
|
custom_exceptions.cpp
|
jgain_EcoLearn/common/custom_exceptions.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "custom_exceptions.h"
const char * not_implemented::what() const noexcept
{
return message.c_str();
}
not_implemented::not_implemented(std::string message)
: message(message)
{
}
| 1,142
|
C++
|
.cpp
| 28
| 38.714286
| 82
| 0.643243
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,255
|
main.cpp
|
jgain_EcoLearn/data_preproc/grass_sim/main.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "grass_sim.h"
#include "data_importer.h"
#include <iostream>
#include <map>
int main(int argc, char * argv []) {
bool use_treeshade = false;
if (argc < 2 || argc > 3)
{
std::cout << "Usage: grass_sim <data directory> [--use_treeshade]" << std::endl;
return 1;
}
if (argc == 3)
{
if (strcmp(argv[2], "--use_treeshade"))
{
std::cout << "Usage: grass_sim <data directory> [--use_treeshade]" << std::endl;
return 1;
}
use_treeshade = true;
}
data_importer::data_dir ddir(argv[1], 1);
std::string shade_filename;
if (use_treeshade)
shade_filename = ddir.sun_tree_fname;
else
shade_filename = ddir.sun_fname;
ValueGridMap<float> ter = data_importer::load_elv<ValueGridMap<float> >(ddir.dem_fname);
std::map<int, std::vector<MinimalPlant> > minplants;
data_importer::read_pdb(ddir.canopy_fnames[0], minplants);
std::vector<basic_tree> trees = data_importer::minimal_to_basic(minplants);
std::vector<basic_tree *> treeptrs;
for (auto &tr : trees)
treeptrs.push_back(&tr);
std::vector<MapFloat> moisture, sunlight, temperature;
moisture = data_importer::read_monthly_map<MapFloat>(ddir.wet_fname);
sunlight = data_importer::read_monthly_map<MapFloat>(shade_filename);
temperature = data_importer::read_monthly_map<MapFloat>(ddir.temp_fname);
auto viability_params = data_importer::read_grass_viability(ddir.grass_params_fname);
std::cout << "Constructing grass sim object..." << std::endl;
GrassSim gsim(ter, 2);
gsim.setConditions(&moisture[5], &sunlight[5], &temperature[5]);
gsim.set_viability_params(viability_params);
std::cout << "Running grass simulation..." << std::endl;
gsim.grow(ter, treeptrs);
std::cout << "All done" << std::endl;
gsim.write(ddir.grass_fname);
//std::cout << "Hello, World!" << std::endl;
return 0;
}
| 2,913
|
C++
|
.cpp
| 68
| 38.147059
| 92
| 0.636107
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,256
|
grass_sim.cpp
|
jgain_EcoLearn/data_preproc/grass_sim/grass_sim.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "grass_sim.h"
#include "../../viewer/canopy_placement/basic_types.h"
//#include "outimage.h"
//#include "dice_roller.h"
#include <canopy_placement/basic_types.h>
#include <chrono>
#include <random>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
bool MapFloat::read(std::string filename)
{
float val;
ifstream infile;
infile.open((char *) filename.c_str(), ios_base::in);
if(infile.is_open())
{
infile >> gx >> gy;
initMap();
for (int x = 0; x < gx; x++)
{
for (int y = 0; y < gy; y++)
{
infile >> val;
set(x, y, val);
}
}
infile.close();
return true;
}
else
{
cerr << "Error TypeMap::loadTxt: unable to open file" << filename << endl;
return false;
}
}
void GrassSim::convertCoord(int x, int y, int &sx, int &sy, int &ex, int &ey)
{
sx = cellmult * x; sy = cellmult * y;
ex = sx+cellmult; ey = sy+cellmult;
}
GrassSim::GrassSim(ValueGridMap<float> &ter, int cellmult)
{
this->cellmult = cellmult;
//matchDim(ter, 1000.0f, 2);
matchDim(ter, cellmult);
}
void GrassSim::matchDim(ValueGridMap<float> &ter, int cellmult)
{
int gx, gy;
float rx, ry;
// get grid dimensions from terrain for simulation parameters
//ter->getGridDim(gx, gy);
ter.getDim(gx, gy);
ter.getDimReal(rx, ry);
// set number of grass cells
grasshght.setDim(gx * cellmult, gy * cellmult);
scx = rx / (float) (gx * cellmult); scy = ry / (float) (gy * cellmult);
//hscx = 0.5f * scx; hscy = 0.5f * scy;
}
float GrassSim::suitability(float inval, float absmin, float innermin, float innermax, float absmax)
{
if(inval >= absmin && inval <= absmax)
{
if(inval < innermin) // lead in interpolation
return ((float) (inval - absmin)) / ((float) (innermin - absmin));
if(inval > innermax) // lead out interpolation
return 1.0f - ((float) (inval - innermax)) / ((float) (absmax - innermax));
return 1.0f; // prime range
}
else // out of survival range
{
return 0.0f;
}
}
void GrassSim::toGrassGrid(float x, float y, int &i, int &j)
{
int gx, gy;
grasshght.getDim(gx, gy);
i = (int) (x / scx);
j = (int) (y / scy);
if(i < 0)
i = 0;
if(j < 0)
j = 0;
if(i >= gx)
i = gx-1;
if(j >= gy)
j = gy-1;
}
void GrassSim::toTerrain(int i, int j, float &x, float &y)
{
x = (float) i * scx + 0.5f * scx;
y = (float) j * scy + 0.5f * scy;
}
void GrassSim::burnInPlant(float x, float y, float r)
{
float nx = x-r, ny = y-r, fx = x+r, fy = y+r;
//vpPoint tree, grass;
//tree = vpPoint(x, y, 0.0f);
// map corners to grass grid positions
int ni, fi, nj, fj;
toGrassGrid(nx, ny, ni, nj);
toGrassGrid(fx, fy, fi, fj);
// iterate top left corner to bottom right corner
for(int i = ni; i <= fi; i++)
for(int j = nj; j <= fj; j++)
{
float wght, d, tx, ty;
toTerrain(i, j, tx, ty);
//grass = vpPoint(tx, ty, 0.0f);
//d = tree.dist(grass); // how far is the grass sample from the tree trunk
float dx = tx - x, dy = ty - y;
d = sqrt(dx * dx + dy * dy);
if(d <= r) // linearly interpolate grass height from trunk to canopy radius
{
wght = d / r;
//wght = 0.0f;
grasshght.set(i, j, grasshght.get(i, j) * wght);
}
}
}
void GrassSim::smooth(int filterwidth, int passes, bool noblank)
{
int gx, gy;
float filterarea;
MapFloat newgrasshght;
grasshght.getDim(gx, gy);
newgrasshght.setDim(gx, gy);
filterarea = (float) ((filterwidth*2+1)*(filterwidth*2+1));
for(int i = 0; i < passes; i++)
{
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
if(noblank || grasshght.get(x,y) > 0.0f)
{
float avg = 0.0f;
for(int cx = x-filterwidth; cx <= x+filterwidth; cx++)
for(int cy = y-filterwidth; cy <= y+filterwidth; cy++)
{
if(cx < 0 || cx >= gx || cy < 0 || cy >= gy)
avg += grasshght.get(x, y);
else
avg += grasshght.get(cx, cy);
}
newgrasshght.set(x,y, avg / filterarea);
}
else
{
newgrasshght.set(x, y, 0.0f);
}
}
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
grasshght.set(x, y, newgrasshght.get(x, y));
if(i%25 == 0)
cerr << i << " smoothing iterations" << endl;
}
}
void GrassSim::grow(ValueGridMap<float> &ter, const std::vector<basic_tree *> &plnt_pointers)
{
if (!conditions_set)
{
throw std::runtime_error("Error: set abiotic conditions first before running grass simulation");
}
if (!params_set)
{
throw std::runtime_error("Error: set grass viability parameters first before running grass simulation");
}
int dx, dy, gx, gy;
bool bare = false;
//DiceRoller roller(0,RAND_MAX);
std::default_random_engine gen;
std::uniform_int_distribution<int> unif_int(0, RAND_MAX);
ter.getDim(dx, dy);
grasshght.getDim(gx, gy);
cerr << "grass-sim: initial grass height" << endl;
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
int sx, sy, ex, ey;
// rocky areas have zero grass heights
/*
bare = (* painted->getMap())[y][x] == (int) BrushType::ROCK; // TO DO - water type may be added later
*/
// alpine settings
/*
float suitval = suitability(illumination.get(x,y), 1.0f, 6.5f, 10.0f, 15.0f); // illumination
suitval = min(suitval, suitability(moisture.get(x,y), 20.0f, 100.0f, 10000.0f, 10000.0f)); // moisture
suitval = min(suitval, suitability(temperature.get(x,y), 0.0f, 10.0f, 22.0f, 40.0f)); // temperature
*/
// savannah settings
/*
float suitval = suitability(illumination.get(x,y), 1.0f, 6.5f, 10.0f, 15.0f); // illumination
suitval = min(suitval, suitability(moisture.get(x,y), 20.0f, 200.0f, 10000.0f, 10000.0f)); // moisture
suitval = min(suitval, suitability(temperature.get(x,y), 5.0f, 15.0f, 22.0f, 40.0f)); // temperature
*/
// canyon settings
/*
float suitval = suitability(illumination.get(x,y), 1.0f, 6.5f, 10.0f, 15.0f); // illumination
suitval = min(suitval, suitability(moisture.get(x,y), 50.0f, 200.0f, 10000.0f, 10000.0f)); // moisture
suitval = min(suitval, suitability(temperature.get(x,y), 5.0f, 15.0f, 22.0f, 40.0f)); // temperature
*/
// med settings
//float suitval = suitability(illumination->get(x,y), 1.0f, 6.5f, 12.0f, 15.0f); // illumination original
//float suitval = suitability(illumination->get(x,y), 2000.0f, 2300.0f, 2500.0f, 2600.0f); // illumination
//suitval = min(suitval, suitability(moisture->get(x,y), 20.0f, 100.0f, 10000.0f, 10000.0f)); // moisture original
//suitval = min(suitval, suitability(moisture->get(x,y), 20.0f, 100.0f, 1000.0f, 1500.0f)); // moisture
//suitval = min(suitval, suitability(temperature->get(x,y), 5.0f, 15.0f, 22.0f, 40.0f)); // temperature original
//suitval = min(suitval, suitability(temperature->get(x,y), 2.5f, 15.0f, 22.0f, 40.0f)); // temperature
auto &mv = viability_params["moisture"];
auto &sv = viability_params["sunlight"];
auto &tv = viability_params["temperature"];
float moisture_suit = suitability(moisture->get(x,y), mv.absmin, mv.innermin, mv.innermax, mv.absmax);
float temp_suit = suitability(temperature->get(x,y), tv.absmin, tv.innermin, tv.innermax, tv.absmax);
float sun_suit = suitability(illumination->get(x,y), sv.absmin, sv.innermin, sv.innermax, sv.absmax);
float suitval = min(moisture_suit, min(temp_suit, sun_suit));
//if (suitval == 0)
// std::cout << "moisture, temp, sun: " << moisture_suit << ", " << temp_suit << ", " << sun_suit << std::endl;
// if(x%100==0 && y%100==0)
// cerr << suitval << " ";
// a terrain cell covers multiple grass cells, so calculate coverage
convertCoord(x, y, sx, sy, ex, ey);
// cerr << "sx, sy = " << sx << ", " << sy << " -> ex, ey = " << ex << ", " << ey << endl;
for(int cx = sx; cx < ex; cx++)
for(int cy = sy; cy < ey; cy++)
{
float hght = 0.0f;
if(!bare) // lookup terrain conditions, value is minimum of all terrain condition ranges
{
hght = suitval * MAXGRASSHGHT;
}
grasshght.set(cx, cy, hght); // set grass height
}
}
cerr << "grass-sim: smoothing" << endl;
// smooth(2, 300, true); // alpine smooth
smooth(2, 50, true); // med smooth
// smooth(2, 50, true); // savannah smooth
// smooth(2, 50, true); // canyon smooth
cerr << "grass-sim: random variation" << endl;
float rndvar;
// rndvar = 0.1; // alpine variation
// rndvar = 0.3; // savannah variation
rndvar = 0.1; // canyon variation
// one pass of random variation
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
if(grasshght.get(x, y) > 0.0f)
{
float h = grasshght.get(x, y);
//h *= (1.0f + rndvar * (float) (roller.generate()%2000-1000) / 1000.0f);
h *= (1.0f + rndvar * (float) (unif_int(gen) % 2000 - 1000) / 1000.0f);
if(h > MAXGRASSHGHT)
h = MAXGRASSHGHT;
grasshght.set(x, y, h);
}
// a few passes to smooth out the noise and make it less local
// smooth(2, 10, true);
cerr << "grass-sim: water burn" << endl;
for(int x = 0; x < dx; x++)
for(int y = 0; y < dy; y++)
{
int sx, sy, ex, ey;
float river = 300.0f; // savannah
if(moisture->get(x,y) > river) // river so remove grass
{
// a terrain cell covers multiple grass cells, so calculate coverage
convertCoord(x, y, sx, sy, ex, ey);
for(int cx = sx; cx < ex; cx++)
for(int cy = sy; cy < ey; cy++)
{
grasshght.set(cx, cy, 0.0f); // set grass height to zero
}
}
}
// some more smoothing to blend water edges
smooth(2, 50, false);
cerr << "grass-sim: plant burn" << endl;
// iterate over plants in the ecosystem, burning in their circles on the grass, depending on the plant alpha and distance from the plant center
// TO DO - add plant alpha, test burn in fully
//ecs->getPlants()->burnGrass(this, ter, scale);
burnGrass(plnt_pointers);
smooth(2, 2, false);
}
void GrassSim::burnGrass(const std::vector<basic_tree *> &plnt_pointers)
{
for (const auto &plntptr : plnt_pointers)
{
burnInPlant(plntptr->x, plntptr->y, plntptr->radius);
}
}
void GrassSim::set_viability_params(const std::map<string, data_importer::grass_viability> &viability_params)
{
this->viability_params = viability_params;
params_set = true;
}
void GrassSim::setConditions(MapFloat * wetfile, MapFloat * sunfile, MapFloat * tempfile)
{
moisture = wetfile;
illumination = sunfile;
temperature = tempfile;
conditions_set = true;
}
bool GrassSim::write(std::string filename)
{
data_importer::write_txt<MapFloat>(filename, &grasshght);
}
/*
bool GrassSim::write(std::string filename)
{
// convert grass simulation to greyscale in [0,1] range
std::vector<float> normhght;
float h;
int gx, gy;
grasshght.getDim(gx, gy);
for(int x = 0; x < gx; x++)
for(int y = 0; y < gy; y++)
{
h = grasshght.get(x, gy-1-y) / MAXGRASSHGHT;
if(h > 1.0f)
h = 1.0f;
if(h < 0.0f)
h = 0.0f;
normhght.push_back(h);
}
OutImage outimg;
return outimg.write(filename, gx, gy, normhght);
}
*/
| 13,759
|
C++
|
.cpp
| 351
| 30.68661
| 147
| 0.543596
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,257
|
compute_normals.cpp
|
jgain_EcoLearn/data_preproc/slope_compute/compute_normals.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#define GLM_ENABLE_EXPERIMENTAL
#include "common/basic_types.h"
#include "data_importer.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/ext.hpp>
#include <glm/gtx/string_cast.hpp>
glm::vec3 get_normal(int x, int y, const ValueMap<float> &heights, float xunit, float yunit)
{
int width, height;
heights.getDim(width, height);
int xsub = -1, xadd = 1;
int ysub = -1, yadd = 1;
if (x == 0)
{
xsub = 0;
}
else if (x == width - 1)
{
xadd = 0;
}
if (y == 0)
{
ysub = 0;
}
else if (y == height - 1)
{
yadd = 0;
}
float zh0 = heights.get(x + xsub, y);
float zh1 = heights.get(x + xadd, y);
float zv0 = heights.get(x, y + ysub);
float zv1 = heights.get(x, y + yadd);
glm::vec3 hcross = glm::vec3(2 * xunit, 0.0f, zh1 - zh0);
glm::vec3 vcross = glm::vec3(0.0f, 2 * yunit, zv1 - zv0);
return glm::normalize(glm::cross(hcross, vcross));
}
ValueGridMap<float> compute_slopes(const ValueGridMap<float> &heights, float xunit, float yunit)
{
int width, height;
heights.getDim(width, height);
ValueGridMap<float> slopes;
slopes.setDim(heights);
slopes.setDimReal(heights);
glm::vec3 up = glm::vec3(0.0f, 0.0f, 1.0f);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
glm::vec3 normal = get_normal(x, y, heights, xunit, yunit);
assert(normal[2] >= 0.0f);
float dotprod = glm::dot(up, normal);
float slope = std::acos(dotprod);
float slope_degr = slope / (2 * M_PI) * 360.0f;
slopes.set(x, y, slope_degr);
}
}
return slopes;
}
int main(int argc, char * argv [])
{
if (argc != 2)
{
std::cout << "Usage: slope_compute <data directory>" << std::endl;
return 1;
}
data_importer::data_dir ddir(argv[1]);
const float xunit = 0.3048 * 3;
const float yunit = 0.3048 * 3;
ValueGridMap<float> heights = data_importer::load_elv<ValueGridMap<float> >(ddir.dem_fname);
ValueGridMap<float> slopes = compute_slopes(heights, xunit, yunit);
data_importer::write_txt(ddir.slope_fname, &slopes);
return 0;
}
| 3,239
|
C++
|
.cpp
| 94
| 29.680851
| 96
| 0.602753
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,258
|
main.cpp
|
jgain_EcoLearn/data_preproc/temp_compute/main.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "data_importer.h"
#include "common/basic_types.h"
#include <algorithm>
#include <cmath>
void compute_temp(const ValueGridMap<float> &input, std::array<float, 12> basetemps, float alttemp, std::vector<ValueGridMap<float> > &output)
{
if (output.size() != 12)
{
output.resize(12);
}
std::for_each(output.begin(), output.end(), [&input](ValueGridMap<float> &outmap){
outmap.setDim(input);
outmap.setDimReal(input);
});
int width, height;
input.getDim(width, height);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
for (int m = 0; m < 12; m++)
{
float temp = input.get(x, y) / 1000.0f * (-fabs(alttemp)) + basetemps[m];
output[m].set(x, y, temp);
}
}
}
}
int main(int argc, char * argv [])
{
if (argc != 3)
{
//std::cout << "usage: temp_compute <DEM elv> <climate file> <lapse rate temp> <OUTPUT txt>" << std::endl;
std::cout << "usage: temp_compute <data directory> <db filename>" << std::endl;
return 1;
}
data_importer::common_data simdata(argv[2]);
data_importer::data_dir ddir(argv[1]);
ValueGridMap<float> dem = data_importer::load_elv< ValueGridMap<float> >(ddir.dem_fname);
//std::vector<float> temps = data_importer::read_temperature(ddir.clim_fname);
//float basetemp = std::stof(argv[2]);
//float alttemp = std::stof(argv[2]);
float alttemp = simdata.temp_lapse_rate;
std::cout << "Temp lapse rate: " << alttemp << std::endl;
std::vector<ValueGridMap<float> > tempmap;
compute_temp(dem, simdata.temperature, alttemp, tempmap);
//data_importer::write_txt(argv[4], &tempmap);
data_importer::write_monthly_map(ddir.temp_fname, tempmap);
return 0;
}
| 2,785
|
C++
|
.cpp
| 69
| 35.449275
| 142
| 0.612509
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,543,259
|
main.cpp
|
jgain_EcoLearn/data_preproc/tests/sunlight_sim/main.cpp
|
/*******************************************************************************
*
* EcoSynth - Data-driven Authoring of Large-Scale Ecosystems
* Copyright (C) 2020 K.P. Kapp ([email protected])
*
* 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 Lesser 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 <https://www.gnu.org/licenses/>.
*
********************************************************************************/
#include "terrain.h"
#include "sunsim.h"
#include "extract_png.h"
#include "basic_types.h"
#include "data_importer.h"
#include <vector>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <chrono>
int main(int argc, char * argv [])
{
//int w = 500, h = 500;
//std::vector<float> data(w * h, 0.0f);
if (argc != 3)
{
std::cout << "usage: sunlight_sim <dem filename> <db filename>" << std::endl;
}
std::string dem_filename = argv[1];
std::string db_filename = argv[2];
data_importer::common_data biomedata(db_filename);
float latitude = biomedata.latitude;
//float latitude = 0.0f;
std::cout << "Latitude: " << latitude << std::endl;
int w, h;
//std::vector<float> data = get_image_data_48bit(argv[1], w, h)[0];
//std::vector<float> data = load_elv(argv[1], w, h);
auto data = data_importer::load_elv< ValueGridMap<float> >(dem_filename);
float minval = *std::min_element(data.begin(), data.end());
std::for_each(data.begin(), data.end(), [&minval](float &val) { val -= minval; /*val *= 0.3048;*/ });
std::cout << "done importing data" << std::endl;
glm::vec3 north(0, 0, -1);
//data.getDim(w, h);
//terrain ter(data.data(), w, h, glm::vec3(0, 0, -1));
terrain ter(data, north, latitude);
auto begin_time = std::chrono::steady_clock::now().time_since_epoch();
sunsim sim(ter, true, 6000, 6000);
sim.renderblock(true);
auto end_time = std::chrono::steady_clock::now().time_since_epoch();
auto total_time = end_time - begin_time;
std::cout << "Sunlight simulation took " << std::chrono::duration_cast<std::chrono::milliseconds>(total_time).count() / 1000.0f << " seconds" << std::endl;
//sim.write_shaded_png_8bit("/home/konrad/shading_test.png");
//sim.write_shaded_monthly_txt("/home/konrad/monthly_sunmap_test.txt");
sim.write_shaded_monthly_txt("/home/konrad/PhDStuff/data/test_sunsim_out.txt", 0.9144f);
return 0;
}
| 2,933
|
C++
|
.cpp
| 65
| 41.523077
| 159
| 0.635121
|
jgain/EcoLearn
| 35
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:45:34 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.