shaderMutator.cpp 23.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps  *
* version 0.1                                                                  *
* Copyright (C) 2009-2011, IGG Team, LSIIT, University of Strasbourg           *
*                                                                              *
* This library is free software; you can redistribute it and/or modify it      *
* under the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation; either version 2.1 of the License, or (at your     *
* option) any later version.                                                   *
*                                                                              *
* This library is distributed in the hope that it will be useful, but WITHOUT  *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or        *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License  *
* for more details.                                                            *
*                                                                              *
* You should have received a copy of the GNU Lesser General Public License     *
* along with this library; if not, write to the Free Software Foundation,      *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.           *
*                                                                              *
* Web site: http://cgogn.u-strasbg.fr/                                         *
* Contact information: cgogn@unistra.fr                                        *
*                                                                              *
*******************************************************************************/

#include "Utils/shaderMutator.h"

namespace CGoGN
{

namespace Utils
{

33

34 35 36 37 38 39
/***********************************************
 *
 * 		Public Section
 *
 ***********************************************/

40

41 42 43 44 45 46 47 48 49 50 51
ShaderMutator::ShaderMutator(const std:: string& shaderName, const std::string& vertShaderSrc, const std::string& fragShaderSrc, const std::string& geomShaderSrc)
{
	// Store the shader name
	m_shaderName = shaderName;

	// Store the shader source codes
	m_vShaderMutation = vertShaderSrc;
	m_fShaderMutation = fragShaderSrc;
	m_gShaderMutation = geomShaderSrc;
}

52
bool ShaderMutator::containsVariableDeclaration(shaderSrcType srcType, const std::string& variableName)
53
{
54
	bool result = false;
55

56 57 58 59 60
	switch (srcType)
	{
		case VERTEX_SHADER :
			result = srcContainsVariableDeclaration(variableName, m_vShaderMutation);
			break;
61

62 63 64
		case FRAGMENT_SHADER :
			result = srcContainsVariableDeclaration(variableName, m_fShaderMutation);
			break;
65

66 67 68
		case GEOMETRY_SHADER :
			result = srcContainsVariableDeclaration(variableName, m_gShaderMutation);
			break;
69 70
	}

71
	return result;
72 73
}

Maire Nicolas's avatar
Maire Nicolas committed
74
bool ShaderMutator::setMinShadingLanguageVersion(shaderSrcType srcType, int version)
75
{
Maire Nicolas's avatar
Maire Nicolas committed
76 77
	bool result = false;

78
	switch (srcType)
79
	{
80
		case VERTEX_SHADER :
Maire Nicolas's avatar
Maire Nicolas committed
81
			result = srcSetMinShadingLanguageVersion(version, m_vShaderMutation);
82
			break;
83

84
		case FRAGMENT_SHADER :
Maire Nicolas's avatar
Maire Nicolas committed
85
			result = srcSetMinShadingLanguageVersion(version, m_fShaderMutation);
86
			break;
87

88
		case GEOMETRY_SHADER :
Maire Nicolas's avatar
Maire Nicolas committed
89
			result = srcSetMinShadingLanguageVersion(version, m_gShaderMutation);
90
			break;
91
	}
Maire Nicolas's avatar
Maire Nicolas committed
92 93

	return result;
94 95
}

Maire Nicolas's avatar
Maire Nicolas committed
96
bool ShaderMutator::changeIntConstantValue(shaderSrcType srcType, const std::string& constantName, int newVal)
97
{
98
	switch (srcType)
99
	{
100
		case VERTEX_SHADER :
101
			if (!srcChangeIntConstantValue(newVal, constantName, m_vShaderMutation))
102 103 104 105 106 107 108 109 110
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::changeIntConstantValue : "
				<< "Unable to change int constant value in vertex shader of "
				<< m_shaderName
				<< ". Constant declaration not found"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
111
				return false;
112 113 114 115
			}
			break;

		case FRAGMENT_SHADER :
116
			if (!srcChangeIntConstantValue(newVal, constantName, m_fShaderMutation))
117 118 119 120 121 122 123 124 125
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::changeIntConstantValue : "
				<< "Unable to change int constant value in fragment shader of "
				<< m_shaderName
				<< ". Constant declaration not found"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
126
				return false;
127 128 129 130
			}
			break;

		case GEOMETRY_SHADER :
131
			if (!srcChangeIntConstantValue(newVal, constantName, m_gShaderMutation))
132 133 134 135 136 137 138 139 140
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::changeIntConstantValue : "
				<< "Unable to change int constant value in geometry shader of "
				<< m_shaderName
				<< ". Constant declaration not found"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
141
				return false;
142 143
			}
			break;
144
	}
Maire Nicolas's avatar
Maire Nicolas committed
145 146

	return true;
147 148
}

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 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 195 196 197 198 199 200 201
bool ShaderMutator::changeFloatConstantValue(shaderSrcType srcType, const std::string& constantName, float newVal)
{
	switch (srcType)
	{
		case VERTEX_SHADER :
			if (!srcChangeFloatConstantValue(newVal, constantName, m_vShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::changeFloatConstantValue : "
				<< "Unable to change float constant value in vertex shader of "
				<< m_shaderName
				<< ". Constant declaration not found"
				<< CGoGNendl;

				return false;
			}
			break;

		case FRAGMENT_SHADER :
			if (!srcChangeFloatConstantValue(newVal, constantName, m_fShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::changeFloatConstantValue : "
				<< "Unable to change float constant value in fragment shader of "
				<< m_shaderName
				<< ". Constant declaration not found"
				<< CGoGNendl;

				return false;
			}
			break;

		case GEOMETRY_SHADER :
			if (!srcChangeFloatConstantValue(newVal, constantName, m_gShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::changeFloatConstantValue : "
				<< "Unable to change float constant value in geometry shader of "
				<< m_shaderName
				<< ". Constant declaration not found"
				<< CGoGNendl;

				return false;
			}
			break;
	}

	return true;
}

Maire Nicolas's avatar
Maire Nicolas committed
202
bool ShaderMutator::insertCodeBeforeMainFunction(shaderSrcType srcType, const std::string& insertedCode)
203
{
204
	switch (srcType)
205
	{
206 207 208 209 210 211 212 213 214 215 216
		case VERTEX_SHADER :
			if (!srcInsertCodeBeforeMainFunction(insertedCode, m_vShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeBeforeMainFunction : "
				<< "Unable to insert source code in vertex shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
217
				return false;
218 219 220 221 222 223 224 225 226 227 228 229 230 231
			}
			break;

		case FRAGMENT_SHADER :
			if (!srcInsertCodeBeforeMainFunction(insertedCode, m_fShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeBeforeMainFunction : "
				<< "Unable to insert source code in fragment shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
232
				return false;
233 234 235 236 237 238 239 240 241 242 243 244 245 246
			}
			break;

		case GEOMETRY_SHADER :
			if (!srcInsertCodeBeforeMainFunction(insertedCode, m_gShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeBeforeMainFunction : "
				<< "Unable to insert source code in geometry shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
247
				return false;
248 249
			}
			break;
250
	}
Maire Nicolas's avatar
Maire Nicolas committed
251 252

	return true;
253 254
}

Maire Nicolas's avatar
Maire Nicolas committed
255
bool ShaderMutator::insertCodeAtMainFunctionBeginning(shaderSrcType srcType, const std::string& insertedCode)
256
{
257
	switch (srcType)
258
	{
259 260 261 262 263 264 265 266 267 268 269
		case VERTEX_SHADER :
			if (!srcInsertCodeAtMainFunctionBeginning(insertedCode, m_vShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionBeginnning : "
				<< "Unable to insert source code in vertex shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
270
				return false;
271 272 273 274 275 276 277 278 279 280 281 282 283 284
			}
			break;

		case FRAGMENT_SHADER :
			if (!srcInsertCodeAtMainFunctionBeginning(insertedCode, m_fShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionBeginnning : "
				<< "Unable to insert source code in fragment shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
285
				return false;
286 287 288 289 290 291 292 293 294 295 296 297 298 299
			}
			break;

		case GEOMETRY_SHADER :
			if (!srcInsertCodeAtMainFunctionBeginning(insertedCode, m_gShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionBeginnning : "
				<< "Unable to insert source code in geometry shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
300
				return false;
301 302
			}
			break;
303
	}
Maire Nicolas's avatar
Maire Nicolas committed
304 305

	return true;
306 307
}

Maire Nicolas's avatar
Maire Nicolas committed
308
bool ShaderMutator::insertCodeAtMainFunctionEnd(shaderSrcType srcType, const std::string& insertedCode)
309
{
310
	switch (srcType)
311
	{
312 313 314 315 316 317 318 319 320 321 322 323
		case VERTEX_SHADER :
			if (!srcInsertCodeAtMainFunctionEnd(insertedCode, m_vShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionEnd : "
				<< "Unable to insert source code in vertex shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration "
				<< "and as many '{' as '}' in main"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
324
				return false;
325 326
			}
			break;
327

328 329 330 331 332 333 334 335 336 337 338 339
		case FRAGMENT_SHADER :
			if (!srcInsertCodeAtMainFunctionEnd(insertedCode, m_fShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionEnd : "
				<< "Unable to insert source code in fragment shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration "
				<< "and as many '{' as '}' in main"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
340
				return false;
341 342
			}
			break;
343

344 345 346 347 348 349 350 351 352 353 354 355
		case GEOMETRY_SHADER :
			if (!srcInsertCodeAtMainFunctionEnd(insertedCode, m_gShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionEnd : "
				<< "Unable to insert source code in geometry shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration "
				<< "and as many '{' as '}' in main"
				<< CGoGNendl;

Maire Nicolas's avatar
Maire Nicolas committed
356
				return false;
357 358 359
			}
			break;
	}
Maire Nicolas's avatar
Maire Nicolas committed
360 361

	return true;
362
}
363 364


365 366 367 368 369
/***********************************************
 *
 * 		Private Section
 *
 ***********************************************/
370 371


372
bool ShaderMutator::srcIsCommented(size_t pos, const std::string& src)
373
{
374 375
	// Verify that the given position is not out of the source
	if (pos >= src.length())
376 377 378
	{
		CGoGNerr
		<< "ERROR - "
379
		<< "ShaderMutator::srcIsCommented : "
380 381 382 383 384
		<< "Given position is out of range"
		<< CGoGNendl;
		return false;
	}
	
385
	// Look backward in the source to see if there is any comment symbol (// or /* */)
386 387
	
	// First look for one-line comments
388
	if (srcIsOneLineCommented(pos, src))
389 390 391
		return true;
	
	// Now look for multi-line comments 
392
	for (size_t i = pos; i > 0; i--)
393
	{	
394
		if (src[i] == '/')
395 396
		{
			// End of multi-line comment
397
			if (src[i-1] == '*')
398 399
			{
				// Verify that the end of multi-line comment is not one-line commented !
400
				if (!srcIsOneLineCommented(i, src))
401 402 403
					return false;
			}
		}
404
		else if (src[i] == '*')
405 406
		{
			// Beginning of multi-line comment
407
			if (src[i-1] == '/')
408 409
			{
				// Verify that the beginning of multi-line comment is not one-line commented !
410
				if (!srcIsOneLineCommented(i, src))
411 412 413 414 415 416 417 418 419 420
					return true;
			}
		}
	}
	
	// No one-line or multi-line comments were found
	return false;
	
}

421
bool ShaderMutator::srcIsOneLineCommented(size_t pos, const std::string& src)
422
{
423 424
	// Verify that the given position is not out of the source
	if (pos >= src.length())
425 426 427
	{
		CGoGNerr
		<< "ERROR - "
428
		<< "ShaderMutator::srcIsOneLineCommented : "
429 430 431 432 433
		<< "Given position is out of range"
		<< CGoGNendl;
		return false;
	}
	
434
	// Look backward in the source to see if there is any "//"
435
	for (size_t i = pos; i > 0; i--)
436 437
	{
		// As soon as a '\n' is found, any other "//" will not affect this line anymore
438
		if (src[i] == '\n')
439
			return false;
440
		// Else if a '/' is found, look if it is followed by another
441 442
		else if (src[i] == '/')
			if (src[i-1] == '/')
443 444 445 446 447 448 449
				return true;
	}
	
	// No one-line comments were found
	return false;
}

450
bool ShaderMutator::srcContainsVariableDeclaration(const std::string& variableName, std::string& src)
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
{
	// Regular expression for variable declaration
	// <',' OR white-space[1 or more times]> <variableName> <',' OR ';' OR white-space>
	boost::regex var_re("(,|\\s+)" + variableName + "(,|;|\\s)");
	
	// Matches results
	boost::match_results <std::string::iterator> matches;
	
	// Search for the first expression that matches and isn't commented
	std::string::iterator start = src.begin();
	std::string::iterator end = src.end();
	while (regex_search(start, end, matches, var_re, boost::format_first_only))
	{
		// Start position of the match
		size_t startPosition = std::distance(src.begin(), matches[0].first);
		
		// Finish if the matched variable is the good one (i.e. not commented)
468
		if (!srcIsCommented(startPosition, src))
469 470 471 472 473 474 475 476 477 478
			return true;
		// Else continue to search for it after last match
		else
			start = matches[0].second;
	}
	
	// At this point no correct match was found
	return false;
}

479
bool ShaderMutator::srcSetMinShadingLanguageVersion(int version, std::string& modifiedSrc)
480 481
{
	// Regular expression for shading language version
482 483
	// <#version> <white-space>[1 or more times] <digit>[1 or more times]
	boost::regex version_re("#version\\s+(\\d+)");
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502

	// Matches results
	boost::match_results <std::string::iterator> matches;

	// Build the version string
	std::string versionStr;
	std::stringstream ss;
	ss << version;
	versionStr = ss.str();

	// Search for the first expression that matches and isn't commented
	std::string::iterator start = modifiedSrc.begin();
	std::string::iterator end = modifiedSrc.end();
	while (regex_search(start, end, matches, version_re, boost::format_first_only))
	{
		// Start position of the match
		size_t startPosition = std::distance(modifiedSrc.begin(), matches[0].first);

		// Change the version number if the matched "#version ..." is the good one (i.e. not commented)
503
		if (!srcIsCommented(startPosition, modifiedSrc))
504
		{
505
			// The submatch Match[1] should be the version number
506 507 508 509 510
			std::string oldVersion(matches[1].first, matches[1].second);
			int oldVersionValue = atoi(oldVersion.c_str());
			size_t oldVersionLength = oldVersion.length();
			size_t oldVersionPosition = std::distance(modifiedSrc.begin(), matches[1].first);

511
			// Replace the old version value only if it is lower than 'version'
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
			if (oldVersionValue < version)
			{
				modifiedSrc.replace(oldVersionPosition, oldVersionLength, versionStr);
				return true;
			}
			else
				return false;
		}
		// Else continue to search for it after last match
		else
		{
			start = matches[0].second;
		}
	}

	// At this point no correct match was found : insert directly the "#version ..." line
	std::string versionLineStr = "#version " + versionStr + "\n";
	modifiedSrc.insert(0, versionLineStr);

	return true;
}

534
bool ShaderMutator::srcChangeIntConstantValue(int newVal, const std::string& constantName, std::string& modifiedSrc)
535 536
{
	// Regular expression for constant expression
537 538
	// <#define> <white-space>[1 or more times] <constant name> <white-space>[1 or more times] <digit>[1 or more times]
	boost::regex const_re("#define\\s+" + constantName + "\\s+(\\d+)");
539 540 541 542 543 544 545 546 547 548

	// Matches results
	boost::match_results <std::string::iterator> matches;

	// Build the constant value string
	std::string newValStr;
	std::stringstream ss;
	ss << newVal;
	newValStr = ss.str();

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
	// Search for the first expression that matches and isn't commented
	std::string::iterator start = modifiedSrc.begin();
	std::string::iterator end = modifiedSrc.end();
	while (regex_search(start, end, matches, const_re, boost::format_first_only))
	{
		// Start position of the match
		size_t startPosition = std::distance(modifiedSrc.begin(), matches[0].first);

		// Change the constant value if the matched "#define ..." is the good one (i.e. not commented)
		if (!srcIsCommented(startPosition, modifiedSrc))
		{
			// The submatch Match[1] should be the old constant value
			std::string oldValStr(matches[1].first, matches[1].second);
			size_t oldValLength = oldValStr.length();
			size_t oldValPosition = std::distance(modifiedSrc.begin(), matches[1].first);

			// Replace the old constant value
			modifiedSrc.replace(oldValPosition, oldValLength, newValStr);
			return true;
		}
		// Else continue to search for it after last match
		else
		{
			start = matches[0].second;
		}
	}

	// At this point no correct match was found
	return false;
}

bool ShaderMutator::srcChangeFloatConstantValue(float newVal, const std::string& constantName, std::string& modifiedSrc)
{
	// Regular expression for constant expression
	// <#define> <white-space>[1 or more times] <constant name> <white-space>[1 or more times]
	// <digit>[1 or more times] <.>[0 or 1 time] <digit>[0 or more times]
	boost::regex const_re("#define\\s+" + constantName + "\\s+(\\d+\\.?\\d*)");

	// Matches results
	boost::match_results <std::string::iterator> matches;

	// Build the constant value string
	std::string newValStr;
	std::stringstream ss;
	ss << newVal;
	newValStr = ss.str();

596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
	// Search for the first expression that matches and isn't commented
	std::string::iterator start = modifiedSrc.begin();
	std::string::iterator end = modifiedSrc.end();
	while (regex_search(start, end, matches, const_re, boost::format_first_only))
	{
		// Start position of the match
		size_t startPosition = std::distance(modifiedSrc.begin(), matches[0].first);

		// Change the constant value if the matched "#define ..." is the good one (i.e. not commented)
		if (!srcIsCommented(startPosition, modifiedSrc))
		{
			// The submatch Match[1] should be the old constant value
			std::string oldValStr(matches[1].first, matches[1].second);
			size_t oldValLength = oldValStr.length();
			size_t oldValPosition = std::distance(modifiedSrc.begin(), matches[1].first);

612
			// Replace the old constant value
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
			modifiedSrc.replace(oldValPosition, oldValLength, newValStr);
			return true;
		}
		// Else continue to search for it after last match
		else
		{
			start = matches[0].second;
		}
	}

	// At this point no correct match was found
	return false;
}

bool ShaderMutator::srcInsertCodeBeforeMainFunction(const std::string& insertedCode, std::string& modifiedSrc)
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
{
	// Regular expression for main function
	// <void> <white-space>[1 or more times] <main> <white-space>[0 or more times] <'('>
	boost::regex main_re("(void)\\s+(main)\\s*\\(");
	
	// Matches results
	boost::match_results <std::string::iterator> matches;
	
	// Search for the first expression that matches and isn't commented
	std::string::iterator start = modifiedSrc.begin();
	std::string::iterator end = modifiedSrc.end();
	while (regex_search(start, end, matches, main_re, boost::format_first_only))
	{
		// Start position of the match
		size_t startPosition = std::distance(modifiedSrc.begin(), matches[0].first);
		
		// Insert and finish if the matched "main" is the good one (i.e. not commented)
645
		if (!srcIsCommented(startPosition, modifiedSrc))
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
		{
			modifiedSrc.insert(startPosition, insertedCode);
			return true;
		}
		// Else continue to search for it after last match
		else
		{
			start = matches[0].second;
		}
	}
	
	// At this point no correct match was found
	return false;
}

661
bool ShaderMutator::srcInsertCodeAtMainFunctionBeginning(const std::string& insertedCode, std::string& modifiedSrc)
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
{
	// Regular expression for main function
	// <void> <white-space>[1 or more times] <main> <white-space>[0 or more times]
	// <'('> <white-space>[0 or more times] <')'>
	// <white-space>[0 or more times] <'{'>
	boost::regex main_re("(void)\\s+(main)\\s*\\(\\s*\\)\\s*\\{");
	
	// Matches results
	boost::match_results <std::string::iterator> matches;
	
	// Search for the first expression that matches and isn't commented
	std::string::iterator start = modifiedSrc.begin();
	std::string::iterator end = modifiedSrc.end();
	while (regex_search(start, end, matches, main_re, boost::format_first_only))
	{
		// Start position of the match
		size_t startPosition = std::distance(modifiedSrc.begin(), matches[0].first);
		
		// End position of the match
		size_t endPosition = std::distance(modifiedSrc.begin(), matches[0].second);
		
		// Insert and finish if the matched "main" is the good one (i.e. not commented)
684
		if (!srcIsCommented(startPosition, modifiedSrc))
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
		{
			modifiedSrc.insert(endPosition, insertedCode);
			return true;
		}
		// Else continue to search for it after last match
		else
		{
			start = matches[0].second;
		}
	}
	
	// At this point no correct match was found
	return false;
}

700
bool ShaderMutator::srcInsertCodeAtMainFunctionEnd(const std::string& insertedCode, std::string& modifiedSrc)
701 702 703 704 705 706 707 708 709 710 711 712 713
{
	// Regular expression for main function
	// <void> <white-space>[1 or more times] <main> <white-space>[0 or more times]
	// <'('> <white-space>[0 or more times] <')'>
	// <white-space>[0 or more times] <'{'>
	boost::regex main_re("(void)\\s+(main)\\s*\\(\\s*\\)\\s*\\{");
	
	// Matches results
	boost::match_results <std::string::iterator> matches;
	
	// Search for the first expression that matches and isn't commented
	std::string::iterator start = modifiedSrc.begin();
	std::string::iterator end = modifiedSrc.end();
714
	size_t mainFirstBracePos = 0;  // The aim is first to find this position
715 716 717 718 719 720 721 722 723
	while (regex_search(start, end, matches, main_re, boost::format_first_only) && (mainFirstBracePos == 0))
	{
		// Start position of the match
		size_t startPosition = std::distance(modifiedSrc.begin(), matches[0].first);
		
		// End position of the match
		size_t endPosition = std::distance(modifiedSrc.begin(), matches[0].second);
		
		// Get the main first brace position if the matched "main" is the good one (i.e. not commented)
724
		if (!srcIsCommented(startPosition, modifiedSrc))
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
			mainFirstBracePos = endPosition;
		// Else continue to search for it after last match
		else
			start = matches[0].second;
	}
	
	// If mainFirstBracePos is still zero, no correct match was found
	if (mainFirstBracePos == 0)
		return false;
	
	// Else, it is now possible to count the opening and closing braces till the final closing brace of the main function is reached
	int bracesCounter = 1;  // =1 since the first opening brace is counted in, it will be =0 when the final closing brace is reached
	size_t closestBracePos = mainFirstBracePos;
	size_t closestOpeningBracePos;
	size_t closestClosingBracePos;
	while (bracesCounter != 0)
	{
		closestOpeningBracePos = modifiedSrc.find_first_of('{', closestBracePos + 1);
		// If this brace appears to be commented, try to get the next one
744
		while ((closestOpeningBracePos != std::string::npos) && srcIsCommented(closestOpeningBracePos, modifiedSrc))
745 746 747 748
			closestOpeningBracePos = modifiedSrc.find_first_of('{', closestOpeningBracePos + 1);
		
		closestClosingBracePos = modifiedSrc.find_first_of('}', closestBracePos + 1);
		// If this brace appears to be commented, try to get the next one
749
		while ((closestClosingBracePos != std::string::npos) && srcIsCommented(closestClosingBracePos, modifiedSrc))
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
			closestClosingBracePos = modifiedSrc.find_first_of('}', closestClosingBracePos + 1);

		// Happens if there is not enough "}" for the corresponding "{"
		if (closestClosingBracePos == std::string::npos)
			return false;

		// Refresh the closest brace position, and increment or decrement the counter
		if (closestClosingBracePos < closestOpeningBracePos)
		{
			closestBracePos = closestClosingBracePos;
			bracesCounter -= 1;
		}
		else
		{
			closestBracePos = closestOpeningBracePos;
			bracesCounter += 1;
		}
	}

	// We should now have the final '}' of the main function
	size_t mainLastBracePos = closestBracePos;
	
	// Insert the source there
	modifiedSrc.insert(mainLastBracePos, insertedCode);
	
	return true;
}

} // namespace Utils

} // namespace CGoGN