1. C++ / Говнокод #18443

    +142

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    void BloomPattern::process(GLuint rectangleVao, float blurRadius) const
    {
       sptrFrameBufferTwo->enable();
       glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
       sptrBrightPassShaderProgram->enable();
       glActiveTexture(GL_TEXTURE0);
       glBindTexture(GL_TEXTURE_2D, sptrFrameBufferThree->getColorTexture().getTexture());
       sptrBrightPassShaderProgram->setUniform("colorTexture", 0);
       glBindVertexArray(rectangleVao);
       glViewport(0, 0, windowWidth >> 1, windowHeight >> 1);
       glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr);
       sptrFrameBufferOne->enable();
       glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
       sptrBlurShaderProgram->enable();
       glBindTexture(GL_TEXTURE_2D, sptrFrameBufferTwo->getColorTexture().getTexture());
       sptrBlurShaderProgram->setUniform("defaultTexture", 0);
       sptrBlurShaderProgram->setUniform("blurRadius", 1.0F / (windowWidth >> 1), 0.0F, blurRadius);
       glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr);
       sptrFrameBufferTwo->enable();
       glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
       glBindTexture(GL_TEXTURE_2D, sptrFrameBufferOne->getColorTexture().getTexture());
       sptrBlurShaderProgram->setUniform("defaultTexture", 0);
       sptrBlurShaderProgram->setUniform("blurRadius", 0.0F, 1.0F / (windowHeight >> 1), blurRadius);
       glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr);
       sptrFinalFrameBuffer->enable();
       glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
       sptrBloomShaderProgram->enable();
       glBindTexture(GL_TEXTURE_2D, sptrFrameBufferThree->getColorTexture().getTexture());
       glActiveTexture(GL_TEXTURE1);
       glBindTexture(GL_TEXTURE_2D, sptrFrameBufferTwo->getColorTexture().getTexture());
       sptrBloomShaderProgram->setUniform("defaultTexture", 0);
       sptrBloomShaderProgram->setUniform("brightpassTexture", 1);
       glViewport(0, 0, windowWidth, windowHeight);
       glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr);
       glBindFramebuffer(GL_FRAMEBUFFER, 0);
    }

    jangolare, 07 Июля 2015

    Комментарии (47)
  2. C++ / Говнокод #18440

    +64

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    XmlWriter<xhtml11::XHtmlDocument>(stream)
    <html
      <head
        <title
          <"Hello world!"
        >title
      >head
      <body
        <p
          <"Some nice paragraph text."
        >p
        <img(src="http://example.com/hello.jpg",alt="Hello")>img
      >body
    >html;

    кресты в квадрате. любителям темплейтов посвящается.

    http://www.vandenoever.info/blog/2015/07/05/literal-xml-in-c++.html

    Creating and processing XML feels awkward in most programming languages. With Blasien, a tiny C++11 header library, XML in C++ feels easy and natural. As an extra the XML that is written is mostly validated at compile time.

    Dummy00001, 06 Июля 2015

    Комментарии (56)
  3. C++ / Говнокод #18416

    +144

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    var::var (double initial) {
        (*this) = initial;
    }
    var::var (char *initial) {
        (*this) = initial;
    }

    С воландесайта.http://habrahabr.ru/post/261351

    roman-kashitsyn, 29 Июня 2015

    Комментарии (6)
  4. C++ / Говнокод #18411

    +142

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    RECT rect;
    GetWindowRect(hWnd, &rect);
    int iWidth = rect.right - rect.left;
    int iHeight = rect.bottom - rect.top;
    Line(hDC, 0, 0, 5000, 0);
    Line(hDC, 0, 0, 0, 5000);
    Line(hDC, 0, iHeight - 1, iWidth, iHeight - 1);
    Line(hDC, iWidth - 1, 0, iWidth - 1, iHeight - 1);

    Рисование линий на границе окна.

    Janycz, 27 Июня 2015

    Комментарии (5)
  5. C++ / Говнокод #18402

    +145

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    union Viewport
    {
    private:
      D3D10_VIEWPORT  viewport;
    public:  
      struct {
        INT    x;
        INT    y;
        UINT  width;
        UINT  height;
        FLOAT  minDepth;
        FLOAT  maxDepth;
      };
    
      Viewport(){}
      Viewport(const Viewport& viewport)
        :viewport(viewport.viewport) {}
      Viewport(D3D10_VIEWPORT viewport)
        :viewport(viewport) {}
      Viewport(INT x, INT y, UINT width, UINT height, FLOAT minDepth, FLOAT maxDepth)
        :x(x), y(y), width(width), height(height), minDepth(minDepth), maxDepth(maxDepth){}
      
      FLOAT GetAspectRatio();
      Vector3 Unproject(Vector3 source, Matrix projection, Matrix view, Matrix world);
      
    };

    LispGovno, 25 Июня 2015

    Комментарии (23)
  6. C++ / Говнокод #18380

    +142

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    float SGammaUIPanel::OnGetGamma() const
    {
      float DisplayGamma = GEngine->DisplayGamma;
      return GEngine ? DisplayGamma : 2.2f;
    }

    Этот и другие прелести из UE в статье https://www.unrealengine.com/blog/how-pvs-studio-team-improved-unreal-engines-code

    makc3d, 22 Июня 2015

    Комментарии (0)
  7. C++ / Говнокод #18376

    +145

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    #define pb push_back
    #define ll long long#define forit(it, r) for (auto it = r.begin(); it != r.end(); it++)
    #define forn(i, n) for (int i = 0; i < n; ++i)
    #define forn1(i, n) for (int i = 1; i < n; ++i)
    #define FOR(i, m, n) for (int i = m; i < n; ++i)
    #define ROF(i, m, n) for (int i = m; i >= n; --i)
    #define fori(n) for (int i = 0; i < n; ++i)
    #define forj(n) for (int j = 0; j < n; ++j)
    
    
    // ...
    
        string s;
        int k;
        while (i >= base)
            k = i % base,
            s.pb(k > 9 ? k + 'A' - 10 : k + 48),
            i /= base;
        k = i % base;
        s.pb(k > 9 ? k + 'A' - 10 : k + 48);
    
    // ...
    
        fori(s.size())
            if (i < s.size() - 1 && s[i] == '\\' && (s[i + 1] == 'n' || s[i + 1] == -47))
            {
                ret.append("%0A");
                i += 1 + (s[i + 1] == -47);//-47 -- russian t, because has the same place with n (\n == \t_russian)
            }
            else
                ret.append("%" + itoa((s[i] + 256) % 256, 16));

    Олимпиадники... Олимпиадники повсюду...

    Little-Horny, 21 Июня 2015

    Комментарии (6)
  8. C++ / Говнокод #18375

    +142

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    #define ADD_TYPE(type, tname, plname) \
    	int Get ## tname ## LocByName(string name) const\
    	{\
    		assert(MyInterface!=null);\
    		auto index=MyInterface.data->get_id_by_name(name);\
    		assert(index==-1 || MyInterface.data->Structure.Declarations[index].Type==ValueType::tname);\
    		return index;\
    	}\
    	ShaderParameters& Set ## tname (int loc, type val)\
    	{\
    		return Set ## plname (loc, &val, 0, 1);\
    	}\
    	ShaderParameters& Set ## tname (string name, type val)\
    	{\
    		return Set ## tname (Get ## tname ## LocByName(name), val);\
    	}\
    	ShaderParameters& Set ## plname (int loc, const type* vals, ushort first, ushort count)\
    	{\
    		if(loc==-1) return *this;\
    		assert(MyInterface!=null);\
    		update_id=++MyInterface.data->num_updates;\
    		values.Set(loc, vals, first, count);\
    		return *this;\
    	}\
    	ShaderParameters& Set ## plname (string name, const type* vals, ushort first, ushort count)\
    	{\
    		return Set ## plname (Get ## tname ## LocByName(name), vals, first, count);\
    	}\
    	type Get ## tname (int loc, ushort i=0) const\
    	{\
    		if(loc==-1) return type();\
    		return values.Get<type>(loc, i);\
    	}\
    	type Get ## tname (string name, ushort i=0) const\
    	{\
    		return Get ## tname (Get ## tname ## LocByName(name), i);\
    	}
    
    	ADD_TYPE(float, Float, Floats);
    	ADD_TYPE(Math::vec2, Vec2, Vecs2);
    	ADD_TYPE(Math::vec3, Vec3, Vecs3);
    	ADD_TYPE(Math::vec4, Vec4, Vecs4);
    	ADD_TYPE(int, Int, Ints);
    	ADD_TYPE(Math::ivec2, IVec2, IVecs2);
    	ADD_TYPE(Math::ivec3, IVec3, IVecs3);
    	ADD_TYPE(Math::ivec4, IVec4, IVecs4);
    	ADD_TYPE(Math::mat3, Mat3, Mats3);
    	ADD_TYPE(Math::mat4, Mat4, Mats4);
    
    #undef ADD_TYPE

    Вот так в моём движке идёт работа с параметрами шейдеров. Макросы делал, чтобы избежать копипаста. Выглядит ужасно, отлаживать неудобно, но зато использовать удобно. Буду думать, как красиво перевести это на шаблоны, чтобы не потерять удобство использования.

    gammaker, 20 Июня 2015

    Комментарии (0)
  9. C++ / Говнокод #18372

    +142

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    template<class T> 
    void KillGorynich()
    {
    	T counter = 1;
    
    	while (true)
    	{
    		T newCount = counter + counter;
    
    		if (newCount > counter)
    		{
    			std::cout << "Отрубил Илья Муромец змею горынчу " << counter << " голов, а на их месте " << newCount << " выросло\n";
    			counter = newCount;
    		}
    		else
    		{
    			std::cout << "Отрубил Илья Муромец змею горынчу " << counter << " голов, и умер змей горыныч\n";
    			char * bits = "";
    
    			switch (sizeof(T) * 8)
    			{
    			case 8:
    				printf("Потому что восьмибитный был\n");
    				break;
    			case 16:
    				printf("Потому что шестнадцатибитный был\n");
    				break;
    			case 32:
    				printf("Потому что тридцатидвухбитный был\n");
    				break;
    			case 64:
    				printf("Потому что шестидесятичетырехбитный был\n");
    				break;
    			}
    
    			break;
    		}
    	}
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	setlocale(LC_ALL, "russian");	
     	//KillGorynich<unsigned short>();
     	KillGorynich<unsigned int>();
     	//KillGorynich<unsigned long long>(); 
     	//KillGorynich<long double>();
    	
    	while (!_kbhit());
    	return 0;
    }

    Шаблонизм головного мозга.

    CrazyRussian, 19 Июня 2015

    Комментарии (1)
  10. C++ / Говнокод #18361

    +142

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    void AttachToParser(Parser* pParser)
    {
    	parser=pParser;
    		
    	static const char* const typeNames[]={"ShaderInterface", "ShaderModule", "ShaderModuleType", "ShaderModulePattern", "ShaderTemplate"};
    	typedef void (ShaderGeneratorParser::* StructureProcessor)();
    	static StructureProcessor processors[]={&ShaderGeneratorParser::ProcessShaderInterface, &ShaderGeneratorParser::ProcessShaderModule,
    		&ShaderGeneratorParser::ProcessShaderModuleType, &ShaderGeneratorParser::ProcessShaderModulePattern, &ShaderGeneratorParser::ProcessShaderTemplate};
    
    	for(uint i=0; i<numof(processors); i++)
    	{
    		auto processor=processors[i];
    		ShaderGeneratorParser mycopy=*this;
    		parser->DeclarationBlockParsers.Append(typeNames[i], [mycopy, processor]() mutable {(mycopy.*processor)();});
    	}
    }

    Делаю парсер конфигов для своего игрового движка. Он готов наверное всего на 10% и представлял собой один класс, который уже разросся. Стало неудобно по нему передвигаться. Решил разбить парсер на модули. Это код того, как один из модулей цепляется к основному классу парсера.
    Этот модуль умеет парсить 5 разных блоков, объединённых общим назначением - сборка шейдеров из модулей. За каждый тип блоков отвечает своя функция. Об этом функция и сообщает основному классу.

    Цель такая, чтобы модуль работал даже после удаления самого экземпляра. Для этого пришлось пропихнуть копию экземпляра внутрь std::function. Более нормального способа, чем через лямбду с замканием, я не нашёл.

    gammaker, 18 Июня 2015

    Комментарии (0)