├── .gitignore ├── IPSM.pro ├── LICENSE ├── README.md ├── StreetGraph.cpp ├── StreetGraph.h ├── TensorField.cpp ├── TensorField.h ├── heightmap.png ├── main.cpp ├── mainwindow.cpp ├── mainwindow.h ├── mainwindow.ui └── watermap.png /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | 6 | # Precompiled Headers 7 | *.gch 8 | *.pch 9 | 10 | # Compiled Dynamic libraries 11 | *.so 12 | *.dylib 13 | *.dll 14 | 15 | # Fortran module files 16 | *.mod 17 | 18 | # Compiled Static libraries 19 | *.lai 20 | *.la 21 | *.a 22 | *.lib 23 | 24 | # Executables 25 | *.exe 26 | *.out 27 | *.app 28 | 29 | # Backup files 30 | *~ 31 | 32 | # Qt files 33 | *.user 34 | -------------------------------------------------------------------------------- /IPSM.pro: -------------------------------------------------------------------------------- 1 | #------------------------------------------------- 2 | # 3 | # Project created by QtCreator 2015-12-03T14:36:34 4 | # 5 | #------------------------------------------------- 6 | 7 | QT += core gui 8 | 9 | greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 10 | 11 | TARGET = IPSM 12 | TEMPLATE = app 13 | 14 | 15 | SOURCES += main.cpp\ 16 | mainwindow.cpp \ 17 | TensorField.cpp \ 18 | StreetGraph.cpp 19 | 20 | HEADERS += mainwindow.h \ 21 | TensorField.h \ 22 | StreetGraph.h 23 | 24 | FORMS += mainwindow.ui 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | 342 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Interactive Procedural Street Modeling 2 | 3 | Qt project for Interactive Procedural Street Modeling 4 | 5 | This project is a C++ implementation of [this paper](http://www.peterwonka.net/Publications/pdfs/2008.SG.Chen.InteractiveProceduralStreetModeling.pdf) on procedural street generation. 6 | It is a school project for my Complex Modeling class. 7 | -------------------------------------------------------------------------------- /StreetGraph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "StreetGraph.h" 9 | 10 | StreetGraph::StreetGraph(QPointF bottomLeft, QPointF topRight, TensorField *field, float distSeparation, QObject *parent) : 11 | QObject(parent), mTensorField(field), mBottomLeft(bottomLeft), mTopRight(topRight), mSeparationDistance(distSeparation) 12 | { 13 | mRegionSize.rwidth() = (topRight-bottomLeft).x(); 14 | mRegionSize.rheight() = (topRight-bottomLeft).y(); 15 | mLastNodeID = 0; 16 | mLastRoadID = 0; 17 | mSeedInitMethod = 0; 18 | mDrawNodes = false; 19 | } 20 | 21 | void StreetGraph::createRandomSeedList(int numberOfSeeds, bool append) 22 | { 23 | if(!append) 24 | { 25 | mSeeds.clear(); 26 | } 27 | qsrand(QDateTime::currentDateTime().toTime_t()); 28 | for(int i=0 ; i < numberOfSeeds ; i++) 29 | { 30 | float randX = qrand()/(float)RAND_MAX; 31 | float randY = qrand()/(float)RAND_MAX; 32 | QPointF seed(mBottomLeft.x() + randX*mRegionSize.width(), 33 | mBottomLeft.y() + randY*mRegionSize.height()); 34 | mSeeds.push_back(seed); 35 | } 36 | } 37 | 38 | void StreetGraph::createDensityConstrainedSeedList(int numberOfSeeds, bool append) 39 | { 40 | if(!append) 41 | { 42 | mSeeds.clear(); 43 | } 44 | qsrand(QDateTime::currentDateTime().toTime_t()); 45 | for(int i=0 ; i < numberOfSeeds ; i++) 46 | { 47 | int counter = 0; 48 | bool pointIsValid = false; 49 | QPointF seed; 50 | while(!pointIsValid && counter < 10) 51 | { 52 | float randX = qrand()/(float)RAND_MAX; 53 | float randY = qrand()/(float)RAND_MAX; 54 | seed = QPointF(mBottomLeft.x() + randX*mRegionSize.width(), 55 | mBottomLeft.y() + randY*mRegionSize.height()); 56 | pointIsValid = pointRespectSeedSeparationDistance(seed,mSeparationDistance); 57 | counter++; 58 | } 59 | if(pointIsValid) 60 | { 61 | mSeeds.push_back(seed); 62 | } 63 | } 64 | } 65 | 66 | int StreetGraph::createGridSeedList(double separationDistance, bool append) 67 | { 68 | if(!append) 69 | { 70 | mSeeds.clear(); 71 | } 72 | int Nv = (int)(mRegionSize.height()/separationDistance); 73 | int Nu = (int)(mRegionSize.width()/separationDistance); 74 | QPointF origin(separationDistance/2.0f,separationDistance/2.0f); 75 | for(int i=0 ; iisFieldFilled())) 124 | { 125 | qCritical()<<"computeMajorHyperstreamlines(): Tensor field is empty"; 126 | return; 127 | } 128 | // Generate the seeds 129 | createRandomSeedList(500, false); 130 | 131 | QSize fieldSize = mTensorField->getFieldSize(); 132 | for(int k=0 ; kgetMajorEigenVector(i,j); 166 | if(QVector2D::dotProduct(majorDirection,currentDirection) < 0) 167 | { 168 | majorDirection *= -1; 169 | } 170 | QPointF nextPosition = currentPosition + (step*majorDirection).toPointF(); 171 | stopGrowth = boundaryStoppingCondition(nextPosition) 172 | || degeneratePointStoppingCondition(i,j) 173 | || loopStoppingCondition(nextPosition,road.segments); 174 | currentPosition = nextPosition; 175 | } 176 | } 177 | } 178 | 179 | void StreetGraph::computeStreetGraph(bool clearStorage) 180 | { 181 | if(clearStorage) 182 | { 183 | clearStoredStreetGraph(); 184 | } 185 | if(mTensorField == NULL) 186 | { 187 | qCritical()<<"ERROR: Tensor field is empty"; 188 | return; 189 | } 190 | // Generate the seeds 191 | generateSeedListWithUIMethod(); 192 | 193 | bool majorGrowth = true; 194 | for(int k=0 ; kgetFieldSize(); 307 | 308 | // The road contains also the position of its extreme nodes 309 | // Start from the node position 310 | QPointF currentPosition = startNode.position; 311 | // Holds wether road stopped because it was too long or not 312 | bool tooLong = false; 313 | bool stopGrowth = false; 314 | int preventInfiniteLoop = 0; 315 | while(!stopGrowth && preventInfiniteLoop < 1000) 316 | { 317 | QVector2D currentDirection; 318 | if(preventInfiniteLoop != 0) 319 | { 320 | currentDirection = QVector2D(currentPosition-road.segments.last()); 321 | } 322 | road.segments.push_back(currentPosition); 323 | int i = round((currentPosition.y()-mBottomLeft.y())/mRegionSize.height()* 324 | (fieldSize.height()-1)); 325 | int j = round((currentPosition.x()-mBottomLeft.x())/mRegionSize.width()* 326 | (fieldSize.width()-1)); 327 | QVector2D majorDirection; 328 | if(growInMajorDirection) 329 | { 330 | majorDirection = mTensorField->getMajorEigenVector(i,j); 331 | } 332 | else 333 | { 334 | majorDirection = mTensorField->getMinorEigenVector(i,j); 335 | } 336 | // First condition is to not grow backwards 337 | // Second condition is applicable only at the beginning. 338 | // It allows to grow the road in the 2 opposite directions 339 | if(QVector2D::dotProduct(majorDirection,currentDirection) < 0 340 | || (preventInfiniteLoop == 0 && growInOppositeDirection)) 341 | { 342 | majorDirection *= -1; 343 | } 344 | QPointF nextPosition = currentPosition + (step*majorDirection).toPointF(); 345 | if(useExceedLenStopCond) 346 | { 347 | tooLong = exceedingLengthStoppingCondition(road.segments); 348 | } 349 | stopGrowth = boundaryStoppingCondition(nextPosition) 350 | || degeneratePointStoppingCondition(i,j) 351 | || loopStoppingCondition(nextPosition,road.segments) 352 | || tooLong; 353 | currentPosition = nextPosition; 354 | preventInfiniteLoop++; 355 | } 356 | 357 | // Fill road lengths 358 | road.pathLength = computePathLength(road.segments); 359 | road.straightLength = computeStraightLength(road.segments); 360 | 361 | // Connect Nodes and Roads 362 | Node& node2 = mNodes[++mLastNodeID]; 363 | node2.ID = mLastNodeID; 364 | node2.position = road.segments.last(); 365 | node2.connectedNodeIDs.push_back(startNode.ID); 366 | node2.connectedRoadIDs.push_back(road.ID); 367 | startNode.connectedNodeIDs.push_back(node2.ID); 368 | road.nodeID2 = node2.ID; 369 | 370 | if(tooLong) 371 | { 372 | // Replant a seed only if it's not too close from another seed 373 | if(pointRespectSeedSeparationDistance(road.segments.last(),mSeparationDistance/4.0f)) 374 | { 375 | mSeeds.push_back(node2.position); 376 | } 377 | } 378 | return node2; 379 | } 380 | 381 | Node& StreetGraph::growRoadAndConnect(Road& road, Node& startNode, bool growInMajorDirection, 382 | bool growInOppositeDirection, bool useExceedLenStopCond) 383 | { 384 | // Grow a road starting from this node using the tensor eigen vector 385 | // until one of the condition is reached 386 | float step = mRegionSize.height()/100.0f; // Should be function of curvature 387 | QSize fieldSize = mTensorField->getFieldSize(); 388 | 389 | // The road contains also the position of its extreme nodes 390 | // Start from the node position 391 | QPointF currentPosition = startNode.position; 392 | // Road meeting 393 | bool meetOtherRoad = false; 394 | int metRoadID, closestPointID; 395 | QPointF intersectionPoint; 396 | // Holds wether road stopped because it was too long or not 397 | bool tooLong = false; 398 | bool stopGrowth = false; 399 | int preventInfiniteLoop = 0; 400 | while(!stopGrowth && preventInfiniteLoop < 1000) 401 | { 402 | QVector2D currentDirection; 403 | if(preventInfiniteLoop != 0) 404 | { 405 | currentDirection = QVector2D(currentPosition-road.segments.last()); 406 | } 407 | road.segments.push_back(currentPosition); 408 | int i = round((currentPosition.y()-mBottomLeft.y())/mRegionSize.height()* 409 | (fieldSize.height()-1)); 410 | int j = round((currentPosition.x()-mBottomLeft.x())/mRegionSize.width()* 411 | (fieldSize.width()-1)); 412 | QVector2D majorDirection; 413 | if(growInMajorDirection) 414 | { 415 | majorDirection = mTensorField->getMajorEigenVector(i,j); 416 | } 417 | else 418 | { 419 | majorDirection = mTensorField->getMinorEigenVector(i,j); 420 | } 421 | // First condition is to not grow backwards 422 | // Second condition is applicable only at the beginning. 423 | // It allows to grow the road in the 2 opposite directions 424 | if(QVector2D::dotProduct(majorDirection,currentDirection) < 0 425 | || (preventInfiniteLoop == 0 && growInOppositeDirection)) 426 | { 427 | majorDirection *= -1; 428 | } 429 | QPointF nextPosition = currentPosition + (step*majorDirection).toPointF(); 430 | if(useExceedLenStopCond) 431 | { 432 | tooLong = exceedingLengthStoppingCondition(road.segments); 433 | } 434 | meetOtherRoad = meetsAnotherRoadAndFindIntersection(road.ID, nextPosition, metRoadID, 435 | closestPointID, intersectionPoint); 436 | stopGrowth = boundaryStoppingCondition(nextPosition) 437 | || degeneratePointStoppingCondition(i,j) 438 | || loopStoppingCondition(nextPosition,road.segments) 439 | || tooLong 440 | || meetOtherRoad; 441 | currentPosition = nextPosition; 442 | preventInfiniteLoop++; 443 | } 444 | 445 | // Connect Nodes and Roads 446 | if(meetOtherRoad) 447 | { 448 | Road &metRoad = mRoads[metRoadID]; 449 | int secondNodeID = -1; 450 | if(closestPointID == 0) 451 | { 452 | road.nodeID2 = metRoad.nodeID1; 453 | secondNodeID = metRoad.nodeID1; 454 | startNode.connectedNodeIDs.push_back(metRoad.nodeID1); 455 | } 456 | else if(closestPointID == metRoad.segments.size()-1) 457 | { 458 | road.nodeID2 = metRoad.nodeID2; 459 | secondNodeID = metRoad.nodeID2; 460 | startNode.connectedNodeIDs.push_back(metRoad.nodeID2); 461 | } 462 | else 463 | { 464 | Node& node2 = mNodes[++mLastNodeID]; 465 | node2.ID = mLastNodeID; 466 | // node2.position = metRoad.segments[closestPointID]; 467 | node2.position = intersectionPoint; 468 | node2.connectedNodeIDs.push_back(startNode.ID); 469 | node2.connectedRoadIDs.push_back(road.ID); 470 | road.segments.push_back(node2.position); 471 | road.nodeID2 = startNode.ID; 472 | startNode.connectedNodeIDs.push_back(node2.ID); 473 | secondNodeID = node2.ID; 474 | // TODO: Separate the crossed road in 2, and reconnect everything 475 | } 476 | 477 | // Fill road lengths 478 | road.pathLength = computePathLength(road.segments); 479 | road.straightLength = computeStraightLength(road.segments); 480 | 481 | return mNodes[secondNodeID]; 482 | } 483 | else 484 | { 485 | // Create a new node on last point of the road 486 | Node& node2 = mNodes[++mLastNodeID]; 487 | node2.ID = mLastNodeID; 488 | node2.position = road.segments.last(); 489 | node2.connectedNodeIDs.push_back(startNode.ID); 490 | node2.connectedRoadIDs.push_back(road.ID); 491 | startNode.connectedNodeIDs.push_back(node2.ID); 492 | road.nodeID2 = node2.ID; 493 | 494 | if(tooLong) 495 | { 496 | mSeeds.push_back(node2.position); 497 | } 498 | // Fill road lengths 499 | road.pathLength = computePathLength(road.segments); 500 | road.straightLength = computeStraightLength(road.segments); 501 | 502 | return node2; 503 | } 504 | } 505 | 506 | 507 | void StreetGraph::generateStreetGraph() 508 | { 509 | // Compute the street graph 510 | computeStreetGraph3(true); 511 | // computeMajorHyperstreamlines(true); 512 | 513 | drawStreetGraph(mDrawNodes, false); 514 | } 515 | 516 | QPixmap StreetGraph::drawStreetGraph(bool showNodes, bool showSeeds) 517 | { 518 | // Draw it in an image 519 | QSize imageSize(512,512); 520 | QImage pixmap(imageSize, QImage::Format_ARGB32); 521 | pixmap.fill(QColor::fromRgb(230,230,230)); 522 | 523 | if(mTensorField->isWatermapLoaded()) 524 | { 525 | QString filename = mTensorField->getWatermapFilename(); 526 | mWatermap = QImage(filename); 527 | if(mWatermap.isNull()) 528 | { 529 | qCritical()<<"applyWaterMap(): File "< 0) 537 | { 538 | pixmap.setPixel(j,i, mWatermap.pixel(j,i)); 539 | } 540 | } 541 | } 542 | } 543 | 544 | if(!(mTensorField->isFieldFilled())) 545 | { 546 | qCritical()<<"drawStreetGraph(): Tensor field is empty"; 547 | return QPixmap::fromImage(pixmap); 548 | } 549 | 550 | QPainter painter(&pixmap); 551 | 552 | QPen penRoad(Qt::yellow); 553 | penRoad.setWidth(2); 554 | QPen penRoadBlack(Qt::black); 555 | penRoadBlack.setWidth(4); 556 | QPen penNode(Qt::red); 557 | penNode.setWidth(3); 558 | QPen penSeed(Qt::darkGreen); 559 | penSeed.setWidth(4); 560 | 561 | // Draw two times in different colors to create 562 | // a road effect 563 | painter.setPen(penRoadBlack); 564 | drawRoads(painter, imageSize); 565 | painter.setPen(penRoad); 566 | drawRoads(painter, imageSize); 567 | 568 | NodeMapIterator itn = mNodes.begin(), itn_end = mNodes.end(); 569 | 570 | // Draw the nodes 571 | if(showNodes) 572 | { 573 | for(; itn != itn_end ; itn++) 574 | { 575 | painter.setPen(penNode); 576 | QPointF a = itn->position; 577 | a.rx() *= imageSize.width()/mRegionSize.width(); 578 | a.ry() *= imageSize.height()/mRegionSize.height(); 579 | a.ry() = imageSize.height() - a.y(); 580 | painter.drawPoint(a); 581 | } 582 | } 583 | // Draw the seeds 584 | if(showSeeds) 585 | { 586 | for(int i=0 ; i & currentSegments = mRoads[i].segments; 606 | if((&(mRoads[i]) != &road) && currentSegments.size() !=0) 607 | { 608 | //1st check: If the point is farther than mDistSeparation 609 | // from both ends, it can't intersect 610 | if(QVector2D(roadEnd - currentSegments.first()).length() > mSeparationDistance 611 | && QVector2D(roadEnd - currentSegments.last()).length() > mSeparationDistance) 612 | { 613 | intersectedRoadID = -1; 614 | closestPointID = -1; 615 | return false; 616 | } 617 | else 618 | { 619 | // 2nd check: If the last point is as close as the minimal distance 620 | // from the road, consider that it meets the road. 621 | // Returns the road ID 622 | for(int j=0 ; j mDistSeparation 647 | // && QVector2D(roadEnd - currentSegments.last()).length() > mDistSeparation) 648 | const QVector& currentSegments = mRoads[i].segments; 649 | bool isConnectedRoad = false; 650 | QVector& connectedRoadIDs = mNodes[mRoads[roadID].nodeID1].connectedRoadIDs; 651 | for(int k=0 ; ksegments.size() ; i++) 697 | { 698 | QPointF a = itr->segments[i-1]; 699 | QPointF b = itr->segments[i]; 700 | a.rx() *= imageSize.width()/mRegionSize.width(); 701 | a.ry() *= imageSize.height()/mRegionSize.height(); 702 | a.ry() = imageSize.height() - a.y(); 703 | b.rx() *= imageSize.width()/mRegionSize.width(); 704 | b.ry() *= imageSize.height()/mRegionSize.height(); 705 | b.ry() = imageSize.height() - b.y(); 706 | painter.drawLine(a,b); 707 | } 708 | } 709 | } 710 | 711 | void StreetGraph::clearStoredStreetGraph() 712 | { 713 | mNodes.clear(); 714 | mRoads.clear(); 715 | mLastNodeID = 0; 716 | mLastRoadID = 0; 717 | } 718 | 719 | void StreetGraph::setDrawNodes(bool drawNodes) 720 | { 721 | if(drawNodes != mDrawNodes) 722 | { 723 | mDrawNodes = drawNodes; 724 | drawStreetGraph(mDrawNodes,false); 725 | } 726 | } 727 | 728 | void StreetGraph::setSeparationDistance(double separationDistance) 729 | { 730 | mSeparationDistance = separationDistance; 731 | } 732 | 733 | bool StreetGraph::boundaryStoppingCondition(QPointF nextPosition) 734 | { 735 | if(nextPosition.x() <= mBottomLeft.x() 736 | || nextPosition.x() >= mTopRight.x() 737 | || nextPosition.y() <= mBottomLeft.y() 738 | || nextPosition.y() >= mTopRight.y()) 739 | { 740 | return true; 741 | } 742 | return false; 743 | } 744 | 745 | bool StreetGraph::degeneratePointStoppingCondition(int i, int j) 746 | { 747 | if(isDegenerate(mTensorField->getTensor(i,j))) 748 | { 749 | return true; 750 | } 751 | return false; 752 | } 753 | 754 | bool StreetGraph::loopStoppingCondition(QPointF nextPosition, const QVector& segments) 755 | { 756 | // TODO : Look for a better way to compare 757 | // It needs a larger span (maybe function of dSeperation) 758 | if(isFuzzyEqual(nextPosition.x(),segments.first().x()) 759 | && isFuzzyEqual(nextPosition.y(),segments.first().y())) 760 | { 761 | return true; 762 | } 763 | return false; 764 | } 765 | 766 | bool StreetGraph::exceedingLengthStoppingCondition(const QVector& segments) 767 | { 768 | if(computePathLength(segments) > mSeparationDistance) 769 | { 770 | return true; 771 | } 772 | return false; 773 | } 774 | 775 | bool StreetGraph::exceedingDensityStoppingCondition() 776 | { 777 | Q_UNIMPLEMENTED(); 778 | return false; 779 | } 780 | 781 | std::ostream& operator<<(std::ostream& out, const Road r) 782 | { 783 | out<<"Road type = "; 784 | out<<(r.type == Principal ? "Principal" : "Secondary"); 785 | out<::const_iterator it = r.segments.begin(), it_end = r.segments.end(); 788 | for(; it != it_end ; it++) 789 | { 790 | out<<"("<x()<<","<y()<<")"<& segments) 809 | { 810 | float length = 0; 811 | for(int i=1 ; i& segments) 819 | { 820 | return QVector2D(segments[0]-segments[segments.size()-1]).length(); 821 | } 822 | 823 | float det2D(QPointF V1, QPointF V2) 824 | { 825 | return V1.x()*V2.y() - V1.y()*V2.x(); 826 | } 827 | 828 | float detPointLine(QPointF A, QPointF B, QPointF M) 829 | { 830 | return det2D(B-A,M-A); 831 | } 832 | 833 | QPointF computeIntersectionPoint(QPointF A, QPointF B, QPointF C, QPointF D) 834 | { 835 | QPointF out; 836 | float denominator = det2D(B-A,D-C); 837 | if(isFuzzyNull(denominator)) 838 | { 839 | return QPointF(); 840 | } 841 | else 842 | { 843 | out.setX(det2D(QPointF(det2D(A,B),det2D(C,D)),QPointF(A.x()-B.x(),C.x()-D.x()))); 844 | out.setY(det2D(QPointF(det2D(A,B),det2D(C,D)),QPointF(A.y()-B.y(),C.y()-D.y()))); 845 | out /= denominator; 846 | if(QPointF::dotProduct(out-A,B-A) > 0 && QPointF::dotProduct(out-B,A-B) > 0) 847 | { 848 | return out; 849 | } 850 | else 851 | { 852 | return QPointF(); 853 | } 854 | } 855 | } 856 | -------------------------------------------------------------------------------- /StreetGraph.h: -------------------------------------------------------------------------------- 1 | #ifndef STREETGRAPH_H 2 | #define STREETGRAPH_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "TensorField.h" 10 | 11 | struct Node; 12 | 13 | enum RoadType { 14 | Principal, 15 | Secondary 16 | }; 17 | 18 | // Structure to store a road 19 | struct Road { 20 | int ID; 21 | QVector segments; 22 | int nodeID1; 23 | int nodeID2; 24 | RoadType type; 25 | float straightLength; 26 | float pathLength; 27 | }; 28 | 29 | // Structure to store an intersection (node) 30 | struct Node { 31 | int ID; 32 | QPointF position; 33 | QVector connectedNodeIDs; 34 | QVector connectedRoadIDs; 35 | }; 36 | 37 | // Convenience typedefs 38 | typedef QMap::iterator NodeMapIterator; 39 | typedef QMap::iterator RoadMapIterator; 40 | 41 | class StreetGraph : public QObject 42 | { 43 | Q_OBJECT 44 | public: 45 | // Construct a StreetGraph object within limits passed 46 | explicit StreetGraph(QPointF bottomLeft, QPointF topRight, TensorField * field, float distSeparation, QObject *parent = 0); 47 | 48 | // Create a random seed list 49 | void createRandomSeedList(int numberOfSeeds, bool append); 50 | 51 | // Create a random seed list that respect a certain density 52 | void createDensityConstrainedSeedList(int numberOfSeeds, bool append); 53 | 54 | // Create a list of seeds spread in a grid pattern on the region 55 | int createGridSeedList(double separationDistance, bool append); 56 | 57 | // Create a list of seeds following the method asked by the user in the UI 58 | void generateSeedListWithUIMethod(); 59 | 60 | // Returns wether the point is too close from one of the existing seeds 61 | bool pointRespectSeedSeparationDistance(QPointF point, float separationDistance); 62 | 63 | // Compute the major hyperstreamlines from the stored tensor field 64 | void computeMajorHyperstreamlines(bool clearStorage); 65 | 66 | // Compute the street graph from the stored tensor field 67 | void computeStreetGraph(bool clearStorage); 68 | void computeStreetGraph2(bool clearStorage); 69 | void computeStreetGraph3(bool clearStorage); 70 | // 1 : doesn't check for segments being too long. Doesn't replant seeds 71 | // 2 : Checks for segments being too long. Replants seeds 72 | // 3 : Seeds grow in both directions 73 | 74 | // Grow a road until it leaves the field, is too long, or other stopping condition 75 | Node& growRoad(Road& road, Node& startNode, bool growInMajorDirection, bool growInOppositeDirection, bool useExceedLenStopCond); 76 | 77 | // Grow a road and connects it to the first road it crosses 78 | Node& growRoadAndConnect(Road& road, Node& startNode, bool growInMajorDirection, bool growInOppositeDirection, bool useExceedLenStopCond); 79 | 80 | // Draw an image with major hyperstreamlines 81 | QPixmap drawStreetGraph(bool showNodes, bool showSeeds); 82 | 83 | // Draw the road network using the painter 84 | void drawRoads(QPainter& painter, QSize imageSize); 85 | 86 | // Clear the stored street graph (Nodes, Roads) 87 | // Warning: Doesn't clear the seed list 88 | void clearStoredStreetGraph(); 89 | 90 | // Set the tensor field to compute street graph from 91 | void setTensorField(TensorField * field) {mTensorField = field;} 92 | 93 | signals: 94 | 95 | // Fired when a new image is drawn 96 | void newStreetGraphImage(QPixmap); 97 | 98 | public slots: 99 | 100 | // Main function : compute and draw the street graph 101 | void generateStreetGraph(); 102 | // Change method to initialize seeds 103 | void changeSeedInitMethod(int index) {mSeedInitMethod = index;} 104 | // Set the variable for drawing nodes or not 105 | void setDrawNodes(bool drawNodes); 106 | // Set the density variable 107 | void setSeparationDistance(double separationDistance); 108 | 109 | private: 110 | 111 | // 1st condition: Reaching boundary 112 | bool boundaryStoppingCondition(QPointF nextPosition); 113 | // 2nd condition: Reaching a degenerate point 114 | bool degeneratePointStoppingCondition(int i, int j); 115 | // 3rd condition: Returning to origin 116 | bool loopStoppingCondition(QPointF nextPosition, const QVector &segments); 117 | // 4th condition: Exceeding user-defined max length 118 | bool exceedingLengthStoppingCondition(const QVector& segments); 119 | // 5th condition: Too close to other hyperstreamline 120 | bool exceedingDensityStoppingCondition(); 121 | // Check if road is meeting another one. Find the closest point of the met road 122 | bool meetsAnotherRoad(Road &road, int &intersectedRoadID, int &closestPointID, float minDistance); 123 | // Check if road is meeting another one. Find the intersection of the two meeting road. 124 | // The intersection isn't necessarily a point of the met road, unlike in meetsAnotherRoad(). 125 | bool meetsAnotherRoadAndFindIntersection(int roadID, QPointF nextPosition, int &intersectedRoadID, 126 | int &closestPointID, QPointF &intersectionPoint); 127 | 128 | 129 | // Tensor field 130 | TensorField * mTensorField; 131 | // Container for nodes 132 | QMap mNodes; 133 | // Container for roads 134 | QMap mRoads; 135 | // Container for seeds 136 | QVector mSeeds; 137 | // Height and width of the region 138 | QSizeF mRegionSize; 139 | // Coordinates of the bottom left point 140 | QPointF mBottomLeft; 141 | // Coordinates of the top right point 142 | QPointF mTopRight; 143 | // Last IDs for Nodes and Roads 144 | int mLastNodeID; 145 | int mLastRoadID; 146 | // Distance for road density 147 | float mSeparationDistance; 148 | // Watermap 149 | QImage mWatermap; 150 | // Method to use for seed initialization 151 | int mSeedInitMethod; 152 | // Holds if nodes should be drawn in the street graph image 153 | bool mDrawNodes; 154 | 155 | }; 156 | 157 | // Overloads writing Road to std stream 158 | std::ostream& operator<<(std::ostream& out, const Road r); 159 | // Overloads writing Node to std stream 160 | std::ostream& operator<<(std::ostream& out, const Node n); 161 | // Overloads writing QPointF to std stream 162 | std::ostream& operator<<(std::ostream& out, const QPointF p); 163 | 164 | // Compute the length of a road 165 | float computePathLength(const QVector& segments); 166 | // Compute the length between the 2 endpoints of a road 167 | float computeStraightLength(const QVector& segments); 168 | // Compute det(AB, AM) which determines if M is in, on the left, 169 | // or on the right of AB 170 | float detPointLine(QPointF A, QPointF B, QPointF M); 171 | // Compute determinant of V1 and V2 (2x2 matrix) 172 | float det2D(QPointF V1, QPointF V2); 173 | // Find the intersection point between segments AB and CD. 174 | // If there isn't, a null QPointF is returned 175 | QPointF computeIntersectionPoint(QPointF A, QPointF B, QPointF C, QPointF D); 176 | 177 | #endif // STREETGRAPH_H 178 | -------------------------------------------------------------------------------- /TensorField.cpp: -------------------------------------------------------------------------------- 1 | #include "TensorField.h" 2 | #include "math.h" 3 | #include "iostream" 4 | #include "eigen3/Eigen/Dense" 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | 13 | TensorField::TensorField(QSize fieldSize, QObject *parent) : 14 | QObject(parent), mFieldSize(fieldSize) 15 | { 16 | mData.resize(fieldSize.height()); 17 | for(int i=0 ; i < fieldSize.height() ; i++) 18 | { 19 | mData[i].resize(fieldSize.width()); 20 | } 21 | mFieldIsFilled = false; 22 | mEigenIsComputed = false; 23 | mWaterMapIsLoaded = false; 24 | } 25 | 26 | QVector4D TensorField::getTensor(int i, int j) 27 | { 28 | return mData[i][j]; 29 | } 30 | 31 | void TensorField::setTensor(int i, int j, QVector4D tensor) 32 | { 33 | mData[i][j] = tensor; 34 | } 35 | 36 | void TensorField::setFieldSize(QSize fieldSize) 37 | { 38 | mFieldSize = fieldSize; 39 | mData.resize(fieldSize.height()); 40 | for(int i=0 ; i < fieldSize.height() ; i++) 41 | { 42 | mData[i].resize(fieldSize.width()); 43 | } 44 | mFieldIsFilled = false; 45 | } 46 | 47 | void TensorField::applyWaterMap(QString filename) 48 | { 49 | QImage waterMap = QImage(filename); 50 | if(waterMap.isNull()) 51 | { 52 | qCritical()<<"applyWaterMap(): File "< 0) 65 | { 66 | mData[mFieldSize.height()-1-i][j] = QVector4D(0,0,0,0); 67 | } 68 | } 69 | } 70 | mWatermapFilename = filename; 71 | mWaterMapIsLoaded = true; 72 | } 73 | 74 | void TensorField::fillGridBasisField(float theta, float l) 75 | { 76 | for(int i=0; ifillGridBasisField(theta, direction.length()); 114 | } 115 | 116 | void TensorField::fillHeightBasisField(QString filename) 117 | { 118 | QImage mHeightMap = QImage(filename); 119 | if(mHeightMap.isNull()) 120 | { 121 | qCritical()<<"fillHeightBasisField(): File "<setFieldSize(mHeightMap.size()); 125 | QRgb currentPixel, nextPixelHoriz, nextPixelVert; 126 | QVector2D grad; 127 | float theta, r; 128 | // Origin is top-left in the image 129 | // Origin is bottom-left in the tensor matrix 130 | // We have to swap the vertical axis 131 | for(int i=0; isetFieldSize(mHeightMap.size()); 174 | QImage mapSobelX, mapSobelY; 175 | QColor pixSobelX, pixSobelY; 176 | float theta, r; 177 | 178 | mapSobelX = applySobelX(mHeightMap); 179 | mapSobelY = applySobelY(mHeightMap); 180 | 181 | for(int i=0; iapplyWaterMap(filename); 237 | 238 | this->computeTensorsEigenDecomposition(); 239 | this->exportEigenVectorsImage(true, true); 240 | } 241 | 242 | void TensorField::generateGridTensorField() 243 | { 244 | this->fillGridBasisField(M_PI/3, 1); 245 | 246 | this->computeTensorsEigenDecomposition(); 247 | this->exportEigenVectorsImage(true, true); 248 | } 249 | 250 | void TensorField::generateHeightmapTensorField() 251 | { 252 | QString filename = QFileDialog::getOpenFileName(0, QString("Open Image")); 253 | if(filename.isEmpty()) 254 | { 255 | return; 256 | } 257 | this->fillHeightBasisField(filename); 258 | 259 | this->computeTensorsEigenDecomposition(); 260 | this->exportEigenVectorsImage(true, true); 261 | } 262 | 263 | void TensorField::generateMultiRotationTensorField() 264 | { 265 | this->fillRotatingField(); 266 | 267 | this->computeTensorsEigenDecomposition(); 268 | this->exportEigenVectorsImage(true, true); 269 | } 270 | 271 | void TensorField::generateRadialTensorField() 272 | { 273 | this->fillRadialBasisField(QPointF(0.5,0.5)); 274 | 275 | this->computeTensorsEigenDecomposition(); 276 | this->exportEigenVectorsImage(true, true); 277 | } 278 | 279 | void TensorField::outputTensorField() 280 | { 281 | for(int i=0; i > mDataSmooth; 300 | mDataSmooth = mData; 301 | 302 | for(int i=1; icomputeTensorsEigenDecomposition(); 314 | this->exportEigenVectorsImage(true, true); 315 | 316 | } 317 | 318 | QPixmap TensorField::exportEigenVectorsImage(bool drawVector1, bool drawVector2, 319 | QColor color1, QColor color2) 320 | { 321 | int imageSize = 512; 322 | QPixmap pixmap(imageSize,imageSize); 323 | pixmap.fill(); 324 | 325 | if(!mFieldIsFilled) 326 | { 327 | qCritical()<<"exportEigenVectorsImage(): Tensor field is empty"; 328 | return pixmap; 329 | } 330 | 331 | QPainter painter(&pixmap); 332 | QPen pen1(color1); 333 | QPen pen2(color2); 334 | 335 | float dv = imageSize/(float)mFieldSize.height(); 336 | float du = imageSize/(float)mFieldSize.width(); 337 | QVector2D origin(du/2.0f, dv/2.0f); 338 | 339 | int numberOfTensorsToDisplay = 32; 340 | int scaleI = mFieldSize.height()/numberOfTensorsToDisplay; 341 | int scaleJ = mFieldSize.width()/numberOfTensorsToDisplay; 342 | 343 | for(int i=0; igetEigenVectors(i,j)); 457 | } 458 | 459 | QVector2D TensorField::getMinorEigenVector(int i, int j) 460 | { 461 | return getSecondVector(this->getEigenVectors(i,j)); 462 | } 463 | 464 | 465 | 466 | 467 | /** ******************** */ 468 | /** Non-member Functions */ 469 | /** ******************** */ 470 | 471 | 472 | 473 | void roundVector2D(QVector2D& vec) 474 | { 475 | vec.setX(round(vec.x())); 476 | vec.setY(round(vec.y())); 477 | } 478 | 479 | QVector2D getFirstVector(QVector4D matrix) 480 | { 481 | return QVector2D(matrix.x(),matrix.y()); 482 | } 483 | 484 | QVector2D getSecondVector(QVector4D matrix) 485 | { 486 | return QVector2D(matrix.z(),matrix.w()); 487 | } 488 | 489 | QVector4D getTensorEigenVectors(QVector4D tensor) 490 | { 491 | if(!isSymetricalAndTraceless(tensor)) 492 | { 493 | qCritical()<<"getTensorEigenVectors(): The tensor must be traceless and symetrical"; 494 | return QVector4D(); 495 | } 496 | if(isDegenerate(tensor)) 497 | { 498 | return QVector4D(0,0,0,0); 499 | } 500 | if(isFuzzyEqual(tensor.x(), 1) && isFuzzyEqual(tensor.y(), 0)) 501 | { 502 | return QVector4D(1,0,0,1); 503 | } 504 | Eigen::Matrix2f m(2,2); 505 | m(0,0) = tensor.x(); 506 | m(1,0) = tensor.y(); 507 | m(0,1) = tensor.z(); 508 | m(1,1) = tensor.w(); 509 | 510 | Eigen::EigenSolver es(m); 511 | QVector2D vec1(es.eigenvectors().col(0).real()[0],es.eigenvectors().col(0).real()[1]); 512 | QVector2D vec2(es.eigenvectors().col(1).real()[0],es.eigenvectors().col(1).real()[1]); 513 | QVector2D val(es.eigenvalues()[0].real(),es.eigenvalues()[1].real()); 514 | if(isFuzzyEqual(val.x(), fmax(val.x(),val.y()))) 515 | { 516 | return QVector4D(vec1.x(), vec1.y(),vec2.x(), vec2.y()); 517 | } 518 | else 519 | { 520 | return QVector4D(vec2.x(), vec2.y(),vec1.x(), vec1.y()); 521 | } 522 | } 523 | 524 | QVector2D getTensorEigenValues(QVector4D tensor) 525 | { 526 | if(isDegenerate(tensor)) 527 | { 528 | return QVector2D(0,0); 529 | } 530 | if(isFuzzyEqual(tensor.x(), 1) && isFuzzyEqual(tensor.y(), 0)) 531 | { 532 | return QVector2D(1,-1); 533 | } 534 | Eigen::Matrix2f m(2,2); 535 | m(0,0) = tensor.x(); 536 | m(1,0) = tensor.y(); 537 | m(0,1) = tensor.z(); 538 | m(1,1) = tensor.w(); 539 | Eigen::EigenSolver es(m); 540 | return QVector2D(es.eigenvalues()[0].real(),es.eigenvalues()[1].real()); 541 | } 542 | 543 | QVector2D getTensorMajorEigenVector(QVector4D tensor) 544 | { 545 | return getFirstVector(getTensorEigenVectors(tensor)); 546 | } 547 | 548 | QVector2D getTensorMinorEigenVector(QVector4D tensor) 549 | { 550 | return getSecondVector(getTensorEigenVectors(tensor)); 551 | } 552 | 553 | QImage applySobelX(QImage map) 554 | { 555 | QSize size; 556 | size = map.size(); 557 | QImage sobelX(size,QImage::Format_RGB32); 558 | sobelX.fill(0); 559 | float kii[9], mii[9]; 560 | kii[0] = -1.0f; 561 | kii[1] = 0.0f; 562 | kii[2] = 1.0f; 563 | kii[3] = -2.0f; 564 | kii[4] = 0.0f; 565 | kii[5] = 2.0f; 566 | kii[6] = -1.0f; 567 | kii[7] = 0.0f; 568 | kii[8] = 1.0f; 569 | 570 | QMatrix3x3 kernel(kii); 571 | 572 | for (int i=1; i 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | // Epsilon for float comparison 16 | #define FLOAT_COMPARISON_EPSILON 1e-5 17 | 18 | class TensorField : public QObject 19 | { 20 | Q_OBJECT 21 | public: 22 | explicit TensorField(QSize fieldsize = QSize(256,256), QObject *parent = 0); 23 | 24 | /** Getters and Setters **/ 25 | 26 | // Get the Tensor at index (i,j) 27 | QVector4D getTensor(int i, int j); 28 | // Set the Tensor at index (i,j) 29 | void setTensor(int i, int j, QVector4D tensor); 30 | 31 | // Get the tensor field size 32 | QSize getFieldSize() {return this->mFieldSize;} 33 | // Set the tensor field size 34 | void setFieldSize(QSize fieldSize); 35 | 36 | // Returns whether the field has been filled with non-zero values 37 | bool isFieldFilled() {return mFieldIsFilled;} 38 | 39 | // Returns whether the field has been filled with non-zero values 40 | bool isWatermapLoaded() {return mWaterMapIsLoaded;} 41 | 42 | // Returns whether the field has been filled with non-zero values 43 | QString getWatermapFilename() {return mWatermapFilename;} 44 | 45 | /** General Use Functions */ 46 | 47 | // Changes the stored tensor field and put tensor to null 48 | // in areas where there is water 49 | void applyWaterMap(QString filename); 50 | // Generate a grid basis field from a 2D vector 51 | // Don't normalize the vector as this function 52 | // integrates the vector's norm in the tensor 53 | void fillGridBasisField(QVector2D direction); 54 | // Generate a grid basis function from an angle and an amplitude. 55 | // There is no direction, so theta and theta + pi give the same result 56 | void fillGridBasisField(float theta, float l); 57 | // Generate a heightmap basis function from a filename 58 | void fillHeightBasisField(QString filename); 59 | // Same thing, using a sobel filter to approximate the gradient 60 | void fillHeightBasisFieldSobel(QString filename); 61 | // Generate a radial basis field 62 | // The center coordinates must be in [0,1], considering that 63 | // The bottom left corner of the image is (0,0) and bottom right 64 | // corner is (1,0) 65 | void fillRadialBasisField(QPointF center); 66 | // Test function to check the different angles 67 | void fillRotatingField(); 68 | 69 | // Output the tensor field to QDebug 70 | void outputTensorField(); 71 | 72 | // Display the tensor field with 2 vectors per point 73 | QPixmap exportEigenVectorsImage(bool drawVector1 = true, bool drawVector2 = false, 74 | QColor color1 = Qt::blue, QColor color2 = Qt::red); 75 | 76 | // Returns the major and minor eigenvectors of the tensor at index (i,j). 77 | // They are normalized, then multiplied by their respective eigenvalue. 78 | // Warning : This only works if the tensor is traceless, real and symmetrical 79 | QVector4D getEigenVectors(int i, int j); 80 | // Returns the major and minor eigenvalues of the tensor at index (i,j). 81 | // Warning : This only works if the tensor is traceless, real and symmetrical 82 | QVector2D getEigenValues(int i, int j); 83 | // Returns the major eigenvector of the tensor at index (i,j). 84 | // It is normalized, then multiplied by its eigenvalue. 85 | // Warning : This only works if the tensor is traceless, real and symmetrical 86 | QVector2D getMajorEigenVector(int i, int j); 87 | // Returns the minor eigenvector of the tensor at index (i,j). 88 | // It is normalized, then multiplied by its eigenvalue. 89 | // Warning : This only works if the tensor is traceless, real and symmetrical 90 | QVector2D getMinorEigenVector(int i, int j); 91 | 92 | 93 | signals: 94 | 95 | // Fired when a new tensor field image is created 96 | void newTensorFieldImage(QPixmap); 97 | 98 | public slots: 99 | 100 | // Get a filename for watermap, store it for future display 101 | // and call the function to apply the watermap 102 | void actionAddWatermap(); 103 | // Generates a grid tensor field with default parameters 104 | void generateGridTensorField(); 105 | // Generates a tensor field from a heightmap 106 | void generateHeightmapTensorField(); 107 | // Generates a multi-rotation tensor field (linear variation) 108 | void generateMultiRotationTensorField(); 109 | // Generates a radial tensor field with default parameters 110 | void generateRadialTensorField(); 111 | // Compute the eigen vectors and values of each tensor in the field, 112 | // and store them internally. 113 | // Return the number of degenerate points (null eigenvectors) 114 | int computeTensorsEigenDecomposition(); 115 | // Tensor field smoothing using a Gaussian filter 116 | void smoothTensorField(); 117 | 118 | private: 119 | 120 | // Tensor field 121 | // A tensor is stored with a QVector4D. 122 | // The coordinates are as follows: 123 | // | x z | 124 | // | y w | 125 | // A traceless, real, symmetrical tensor is of the form: 126 | // | a b | 127 | // | b -a | 128 | QVector > mData; 129 | // Eigen vectors of each tensor matrix 130 | QVector > mEigenVectors; 131 | // Eigen values of each tensor matrix 132 | QVector > mEigenValues; 133 | // Holds wether the field has been initialized with non-zero values 134 | bool mFieldIsFilled; 135 | // Holds wether the eigen vectors and values has been computed 136 | bool mEigenIsComputed; 137 | // Holds wether a watermap has been loaded 138 | bool mWaterMapIsLoaded; 139 | // Filename of the watermap 140 | QString mWatermapFilename; 141 | // Field size 142 | QSize mFieldSize; 143 | }; 144 | 145 | 146 | /** Non-member Functions */ 147 | 148 | 149 | // Round a 2D vector 150 | void roundVector2D(QVector2D &vec); 151 | // Returns whether floating point value a is considered equal to 0 152 | bool isFuzzyNull(float a); 153 | // Returns wether floating point value a and b are considered equal 154 | bool isFuzzyEqual(float a, float b); 155 | 156 | // Get the first vector of the 2x2 matrix 157 | QVector2D getFirstVector(QVector4D matrix); 158 | // Get the second vector of the 2x2 matrix 159 | QVector2D getSecondVector(QVector4D matrix); 160 | 161 | // Returns the normalized major and minor eigenvectors of the passed tensor 162 | // The first column vector is the one associated with the maximum eigenvalue 163 | // Warning : This only works if the tensor is traceless, real and symmetrical 164 | QVector4D getTensorEigenVectors(QVector4D tensor); 165 | // Returns the major and minor eigenvalues of the passed tensor. 166 | // The maximum eigenvalue is first, and the minimum is second 167 | // Warning : This only works if the tensor is traceless, real and symmetrical 168 | QVector2D getTensorEigenValues(QVector4D tensor); 169 | // Returns the normalized major eigenvector of the passed tensor. 170 | // Warning : This only works if the tensor is traceless, real and symmetrical 171 | QVector2D getTensorMajorEigenVector(QVector4D tensor); 172 | // Returns the normalized minor eigenvector of the passed tensor. 173 | // Warning : This only works if the tensor is traceless, real and symmetrical 174 | QVector2D getTensorMinorEigenVector(QVector4D tensor); 175 | // Returns the image created by applying Sobel filter on x 176 | QImage applySobelX(QImage map); 177 | // Returns the image created by applying Sobel filter on y 178 | QImage applySobelY(QImage map); 179 | // Returns the sum of elements of a matrix 3x3 180 | int sumMat3D(QMatrix3x3 matrix, QMatrix3x3 kernel); 181 | 182 | // Returns whether the tensor is real, symmetrical and traceless, or not 183 | bool isSymetricalAndTraceless(QVector4D tensor); 184 | // Returns whether the tensor is degenerate or not 185 | bool isDegenerate(QVector4D tensor); 186 | 187 | 188 | 189 | #endif // TENSORFIELD_H 190 | -------------------------------------------------------------------------------- /heightmap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthieuheitz/IPSM/d820df82dbc47e0c4079265165144f475eb878bd/heightmap.png -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include "mainwindow.h" 2 | #include 3 | 4 | int main(int argc, char *argv[]) 5 | { 6 | QApplication a(argc, argv); 7 | MainWindow w; 8 | w.show(); 9 | 10 | return a.exec(); 11 | } 12 | -------------------------------------------------------------------------------- /mainwindow.cpp: -------------------------------------------------------------------------------- 1 | #include "mainwindow.h" 2 | #include "ui_mainwindow.h" 3 | 4 | MainWindow::MainWindow(QWidget *parent) : 5 | QMainWindow(parent), 6 | ui(new Ui::MainWindow) 7 | { 8 | ui->setupUi(this); 9 | double separationDistance = 10; 10 | mTensorFieldSize = QSize(32,32); 11 | mTensorField = new TensorField(mTensorFieldSize); 12 | mStreetGraph = new StreetGraph(QPointF(0,0), QPointF(100,100),mTensorField,separationDistance); 13 | 14 | ui->comboBoxSeedInit->addItem("Regular Grid"); 15 | ui->comboBoxSeedInit->addItem("Random distribution"); 16 | ui->comboBoxSeedInit->addItem("Controlled random distribution"); 17 | 18 | ui->spinBoxDensity->setRange(0, 100); 19 | ui->spinBoxDensity->setValue(separationDistance); 20 | 21 | QObject::connect(ui->buttonAddWatermap, SIGNAL(clicked()), 22 | mTensorField, SLOT(actionAddWatermap())); 23 | QObject::connect(ui->buttonGenerateGridTF, SIGNAL(clicked()), 24 | mTensorField, SLOT(generateGridTensorField())); 25 | QObject::connect(ui->buttonGenerateMultiRotTF, SIGNAL(clicked()), 26 | mTensorField, SLOT(generateMultiRotationTensorField())); 27 | QObject::connect(ui->buttonGenerateRadialTF, SIGNAL(clicked()), 28 | mTensorField, SLOT(generateRadialTensorField())); 29 | QObject::connect(ui->buttonGenerateHeightmapTF, SIGNAL(clicked()), 30 | mTensorField, SLOT(generateHeightmapTensorField())); 31 | QObject::connect(ui->buttonSmoothTF, SIGNAL(clicked()), 32 | mTensorField, SLOT(smoothTensorField())); 33 | QObject::connect(mTensorField, SIGNAL(newTensorFieldImage(QPixmap)), 34 | ui->labelTensorFieldDisplay,SLOT(setPixmap(QPixmap))); 35 | QObject::connect(ui->buttonGeneratePrincipalRG, SIGNAL(clicked()), 36 | mStreetGraph, SLOT(generateStreetGraph())); 37 | QObject::connect(mStreetGraph, SIGNAL(newStreetGraphImage(QPixmap)), 38 | ui->labelRoadmapDisplay, SLOT(setPixmap(QPixmap))); 39 | QObject::connect(ui->checkBoxShowNodes, SIGNAL(toggled(bool)), 40 | mStreetGraph, SLOT(setDrawNodes(bool))); 41 | QObject::connect(ui->spinBoxDensity, SIGNAL(valueChanged(double)), 42 | mStreetGraph, SLOT(setSeparationDistance(double))); 43 | QObject::connect(ui->comboBoxSeedInit, SIGNAL(currentIndexChanged(int)), 44 | mStreetGraph, SLOT(changeSeedInitMethod(int))); 45 | } 46 | 47 | MainWindow::~MainWindow() 48 | { 49 | delete ui; 50 | } 51 | 52 | 53 | void MainWindow::displayVectorFieldImage(QPixmap image) 54 | { 55 | ui->labelTensorFieldDisplay->setPixmap(image); 56 | } 57 | 58 | void MainWindow::keyPressEvent(QKeyEvent *event) 59 | { 60 | if (event->key()==Qt::Key_Escape) 61 | exit(0); 62 | } 63 | -------------------------------------------------------------------------------- /mainwindow.h: -------------------------------------------------------------------------------- 1 | #ifndef MAINWINDOW_H 2 | #define MAINWINDOW_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include "TensorField.h" 9 | #include "StreetGraph.h" 10 | 11 | namespace Ui { 12 | class MainWindow; 13 | } 14 | 15 | class MainWindow : public QMainWindow 16 | { 17 | Q_OBJECT 18 | 19 | public: 20 | explicit MainWindow(QWidget *parent = 0); 21 | ~MainWindow(); 22 | 23 | protected: 24 | void keyPressEvent(QKeyEvent *event); 25 | 26 | private slots: 27 | void displayVectorFieldImage(QPixmap image); 28 | 29 | private: 30 | Ui::MainWindow *ui; 31 | TensorField * mTensorField; 32 | QSize mTensorFieldSize; 33 | StreetGraph * mStreetGraph; 34 | }; 35 | 36 | #endif // MAINWINDOW_H 37 | -------------------------------------------------------------------------------- /mainwindow.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | MainWindow 4 | 5 | 6 | 7 | 0 8 | 0 9 | 794 10 | 615 11 | 12 | 13 | 14 | Interactive Procedural Street Modeling 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Qt::Horizontal 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 12 32 | 75 33 | true 34 | 35 | 36 | 37 | Tensor field 38 | 39 | 40 | Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter 41 | 42 | 43 | 44 | 45 | 46 | 47 | Show nodes 48 | 49 | 50 | 51 | 52 | 53 | 54 | Add Watermap 55 | 56 | 57 | 58 | 59 | 60 | 61 | Qt::Vertical 62 | 63 | 64 | 65 | 20 66 | 40 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | Qt::Horizontal 75 | 76 | 77 | 78 | 79 | 80 | 81 | Smooth TF 82 | 83 | 84 | 85 | 86 | 87 | 88 | Generate Radial TF 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | Global 98 | 99 | 100 | true 101 | 102 | 103 | 104 | 105 | 106 | 107 | Local 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | Generate Multi-rotationTF 117 | 118 | 119 | 120 | 121 | 122 | 123 | Seed Initialization Method 124 | 125 | 126 | 127 | 128 | 129 | 130 | Generate Principal Road Graph 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 12 142 | 75 143 | true 144 | 145 | 146 | 147 | Street graph 148 | 149 | 150 | 151 | 152 | 153 | 154 | Average Road Interval 155 | 156 | 157 | 158 | 159 | 160 | 161 | Generate Heightmap TF 162 | 163 | 164 | 165 | 166 | 167 | 168 | Generate Grid TF 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | Actions 195 | 196 | 197 | 198 | 199 | 200 | 201 | Tensor Field 202 | 203 | 204 | 205 | 206 | 207 | 208 | Roadmap 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 0 218 | 0 219 | 794 220 | 24 221 | 222 | 223 | 224 | 225 | 226 | TopToolBarArea 227 | 228 | 229 | false 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | -------------------------------------------------------------------------------- /watermap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/matthieuheitz/IPSM/d820df82dbc47e0c4079265165144f475eb878bd/watermap.png --------------------------------------------------------------------------------