Lazarus

Programming => Graphics and Multimedia => Games => Topic started by: Seenkao on December 21, 2020, 12:55:45 am

Title: ZenGL +android + MacOS Cocoa
Post by: Seenkao on December 21, 2020, 12:55:45 am
Rus:
Текущая версия: ZenGL (download) (https://sourceforge.net/projects/new-zengl/)

ZenGL - это библиотека создающая контекст окна для работы с OpenGL на разных платформах. Так же, это игровой 2D движок, позволяющий писать игры (приложение), без знаний OpenGL.
На данное время, есть возможность использования полного OpenGL и OpenGL ES.
Green Engine - это наработки над ZenGL, своеобразное API.

Среда разработки и поддерживаемые платформы для:
Lazarus/FreePascal:
   - Windows 32/64
   - Linux 32/64
   - Android ARM32(v5, v6, v7a)/ARM64(v8a)/x86/x86_64
   - Портативные компьютеры: Steam Deck, Rog Ally, Ayaneo и другие основанные на ОС Windows и Linux.
   - MacOS Cocoa beta version

Delphi:
   - Windows 32 (вероятно некоторые демо-версии будут работать и с Windows 64, но точно не все)

Эта тема более актуальная, стараюсь все изменения и поддержку выкладывать там. (https://forum.lazarus.freepascal.org/index.php/topic,49143.0.html)

вопросы, предложения можно оставлять здесь или отправлять на мыло M12Mirrel@yandex.ru

Благодарю за внимание.  :)
---------------------------------------------------------------------------------------------------------------------

Eng:
Google translate:
Current version: ZenGL (download) (https://sourceforge.net/projects/new-zengl/)

ZenGL is a window context library for working with OpenGL on different platforms. Also, this is a 2D game engine that allows you to write games (applications) without knowledge of OpenGL.
At this time, it is possible to use full OpenGL and OpenGL ES.
Green Engine are developments on ZenGL, a kind of API.

Development environment and supported platforms for:
Lazarus/FreePascal:
    - Windows 32/64
    - Linux 32/64
    - Android ARM32(v5, v6, v7a)/ARM64(v8a)/x86/x86_64
    - Portable computers: Steam Deck, Rog Ally, Ayaneo and others based on Windows and Linux OS.
    - MacOS Cocoa beta version

Delphi:
    - Windows 32 (probably some demos will work with Windows 64, but definitely not all)

This topic is more relevant, I try to post all changes and support there. (https://forum.lazarus.freepascal.org/index.php/topic,49143.0.html)

questions, suggestions can be left here or sent to email M12Mirrel@yandex.ru

Thank you for your attention. :)
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on December 21, 2020, 01:21:07 am
Если вы используете BigSur или CPU не x86_64 то вам надо:
установить библиотеки из brew (https://formulae.brew.sh/formula/)

If you are using BigSur or a CPU not x86_64 then you need:
install libraries from brew (https://formulae.brew.sh/formula/)
- zlib
- libzip
- libogg
- vorbis
и если знаете как запустить 15-ю и 16-ю демо-версии, то:
and if you know how to run the 15th and 16th demo versions, then:
- theora
- chipmunk

в файле "zgl_config.cfg" выставить
in the file "zgl_config.cfg" set
Code: Pascal  [Select][+][-]
  1. {$DEFINE MAC_COCOA}
and disable
Code: Pascal  [Select][+][-]
  1. {$IFDEF MAC_COCOA}
  2.   {$DEFINE NO_USE_STATIC_LIBRARY} // -> {.$DEFINE NO_USE_STATIC_LIBRARY}
  3. {$ENDIF}
If all libraries are installed by default, then the demo versions should work.

Если все библиотеки будут установлены по умолчанию, то демо-версии должны заработать.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: skalogryz on December 21, 2020, 02:51:05 am
zlib идёт в маке из коробки

с Маком вся тонкость как динамические либы распростронять.
Их обязательно нужно класть в нужную директорию в бандле!

иначе конечных пользователей тоже придёться просить ставить Brew. не камильфо!  :)
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on December 21, 2020, 07:23:03 am
skalogryz, и вот тут вырисовывается интересная проблема... о которой я даже не задумывался...
Допустим для своего процессора я добавлю эти самые библиотеки, это не проблема.

Но!!! Как обеспечить полную совместимость программы для разных процессоров по свое сути?!
Мне надо об этом заботится? Или всё же приложение скомпилированное на процессоре x86-64 будет работать на процессоре ARM64? Если да, то как мне получить библиотеки для процессора ARM?

Эта проблема, похоже, касается не только MacOS, но и Linux?

Я ни сколько не на Java программирую...

Google translate:
and here an interesting problem looms ... which I did not even think about ...
Suppose I add these same libraries for my processor, this is not a problem.

But!!! How to ensure full compatibility of the program for different processors in essence?!
Do I need to take care of this? Or will an application compiled on an x86-64 processor run on an ARM64 processor? If so, how do I get libraries for the ARM processor?

Does this problem seem to affect not only macOS but Linux as well?

I do not program in Java at all ...

P.S. skalogryz, мы не на русскоязычном форуме.  :)
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on July 18, 2021, 03:18:14 am
Всем привет! Обновил версию ZenGL до 3.28.
И с данного момента (так то и раньше уже было) теперь параллельно идёт разработка собственной библиотеки Green Engine. Работает только с ZenGL.

Прошу прощения, но на английском информации мало. Но по ходу разработки добавляю комментарии в код и демонстрационные версии.

GE - предоставляет в данное время только возможность работать с полем ввода, и виртуальной клавиатурой, которая ещё не доделана...  Для мобильных систем пока ни как не состыкована эта клавиатура, хотя для неё изначально только и делал.

Поле ввода пока только проверены на Windows и Linux. На MacOS должно работать, но пока не проверял. :-[

Надеюсь полезное видео, где я переделываю 3-ю демо-версию (https://youtu.be/qb8hxilAI_I). В конце видео показываю, как можно использовать несколько полей ввода.

Google translate:
Hello everyone! Updated ZenGL version to 3.28.
And from this moment (and it has already happened before), the development of its own Green Engine library is now going on in parallel. Works with ZenGL only.

Sorry, but there is little information in English. But in the course of development, I add comments to the code and demos.

GE - at this time only provides the ability to work with the input field, and the virtual keyboard, which has not yet been completed ... For mobile systems, this keyboard has not yet been docked, although it was originally only done for it.

The input field has only been tested on Windows and Linux so far. It should work on macOS, but haven't tested it yet. :-[

Hopefully helpful video of me remaking the 3rd demo (https://youtu.be/qb8hxilAI_I). (rus) At the end of the video, I show you how you can use multiple input fields.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Blade on September 16, 2021, 12:39:40 am
Very interesting and good to see the update.  Have seen various sources that had good things to say about ZenGL. 

Hopefully, ZenGL for iOS (https://github.com/skalogryz/zengl (https://github.com/skalogryz/zengl)) works or gets updated too.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Akira1364 on January 02, 2022, 11:20:16 am
FYI, the custom code used in https://github.com/Seenkao/New-ZenGL/blob/ZenGL_3_28/Zengl_SRC/src/zgl_opengles_all.pas (https://github.com/Seenkao/New-ZenGL/blob/ZenGL_3_28/Zengl_SRC/src/zgl_opengles_all.pas) is equally applicable to the desktop platforms that do not use OpenGLES, and significantly faster than just letting it use the default actual glBegin / glEnd that is usually does for them.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on January 05, 2022, 03:47:29 pm
Blade, благодарю. По поводу iOS я ни чего не могу сказать на данный момент. У меня времени не хватает поднять код и/или включить код skalogryz. Времени на всё надо очень много, а иногда желание просто пропадает.  :(

Akira1364, вероятно что и для OpenGL ES это так же. Но надо не забывать включать batch2d_Begin/batch2d_End. Я думал это работает только для OpenGL ES, но я ошибался. Andru лучше меня знал как работает "устаревший" OpenGL/OpenGL ES - и это даёт ускорение в обоих случаях. Но надо знать, что это будет работать только при использовании функций ZenGL, пользуясь напряму OpenGL мы не получим этого ускорения (если только сами не включим дополнительный код используемый в функциях ZenGL).

Google translate:
Blade, thanks. As for iOS, I can't say anything at the moment. I don’t have enough time to raise the code and / or include the code skalogryz. It takes a lot of time for everything, and sometimes the desire just disappears. :(

Akira1364, it is probably the same for OpenGL ES. But remember to enable batch2d_Begin/batch2d_End. I thought this only works for OpenGL ES, but I was wrong. Andru knew better than me how the "outdated" OpenGL / OpenGL ES works - and this gives acceleration in both cases. But you need to know that this will only work when using ZenGL functions, using OpenGL directly, we will not get this acceleration (unless we ourselves include additional code used in ZenGL functions).
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on February 27, 2022, 03:53:42 pm
Выпущена новая версия ZenGL 3.29 (https://github.com/Seenkao/New-ZenGL).
 8)
Изменения в файле Update_ZenGL.txt.

Основное из изменений: В ZenGL включён полный OpenGL по состоянию на конец 2021 года. По умолчанию включена минимальная версия, для использования основной функциональности ZenGL. Для использования полного OpenGL вам надо будет отключить в файле GLdefine.cfg дефайн USE_MIN_OPENGL (смотрите первую демо версию).

Окно и контекст окна создаются автоматически. Работу с View-портом надо настраивать. Эти функции были сделаны ещё Andru, для 2D под ZenGL подойдёт (может и вам подойдёт), для 3D надо самим настраивать функцию.
Займусь этим немного позже. Вы можете сами что-нибудь предложить.

Демки переделаны только под Lazarus, поэтому все изменения смотрите в них.

Демка LCL не будет работать в Windows 10. Я пока не решал этой проблемы. Зависает окно.

------------------------------------------------------------------------------------------------------------------------------------
Google translate:
New version ZenGL 3.29 (https://github.com/Seenkao/New-ZenGL) has been released.
 8)
Changes in the file Update_ZenGL.txt.

Key changes: ZenGL includes full OpenGL as of late 2021. By default, a minimum version is enabled to use the core functionality of ZenGL. To use full OpenGL you will need to disable USE_MIN_OPENGL in the GLdefine.cfg file (see the first demo).

The window and window context are created automatically. Work with the View-port must be configured. These functions were made by Andru, for 2D under ZenGL it will work (maybe it will work for you too), for 3D you need to configure the function yourself.
I'll deal with this a little later. You can offer something yourself.

Demos are remade only for Lazarus, so look at all the changes in them.

The LCL demo won't work on Windows 10. I haven't solved this problem yet. The window hangs.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on March 15, 2023, 08:37:02 pm
  Вышла новая версия ZenGL 3.30 (https://github.com/Seenkao/New-ZenGL/tree/ZenGL_3_30). Изменений достаточно немало и я не смогу их все упомнить. Всё постарался записать в файле Update_ZenGL.txt (к сожаленью только на Русском языке, прошу простить, но документацию стараюсь поддерживать и на Английском! ::)). Документирую функции в модулях. Документация на данный момент не полная.
  Основные изменения это то, что теперь для мобильных систем работает нативная клавиатура и она не зависит от системы!!! Её можно использовать как виртуальную клавиатуру для настольных ОС. Но вот про джойстики для мобильных систем - забыл... Они не доделаны.
  Клавиатура поддерживает кириллицу и латиницу. Для поддержки других раскладок клавиатур нужна помощь носителей данных языков. Если кого заинтересует, обращайтесь.

Google translate:
   New version ZenGL 3.30 (https://github.com/Seenkao/New-ZenGL/tree/ZenGL_3_30) has been released. There are so many changes that I can't remember them all. I tried to write everything in the file Update_ZenGL.txt (unfortunately, only in Russian, I'm sorry, but I try to support the documentation in English too! ::)). I document functions in modules. The documentation is currently incomplete.
   The main changes are that now a native keyboard works for mobile systems and it does not depend on the system!!! It can be used as a virtual keyboard for desktop OS. But I forgot about joysticks for mobile systems... They haven't been completed yet.
   The keyboard supports Cyrillic and Latin. Support for other keyboard layouts requires the assistance of native speakers of these languages. If anyone is interested, please contact.

Sorry for my English. But it's a translator...

Всем успехов!  ;D
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Akira1364 on May 27, 2023, 10:38:19 pm
FYI, the reimplementations of glBegin / glEnd etc from zgl_opengles_all.pas in terms of glDrawArrays and such (https://github.com/Seenkao/New-ZenGL/blob/05e76a5f22649aec80ce0ede31d7c1e241263dc2/Zengl_SRC/src/zgl_opengles_all.pas#L1720) should definitely also be used on desktop. Currently, ZenGL on desktop just actually uses the real immediate mode functions (https://github.com/Seenkao/New-ZenGL/blob/05e76a5f22649aec80ce0ede31d7c1e241263dc2/Zengl_SRC/src/zgl_opengl_all.pas#L111), which is much slower than the array-based wrappers from zgl_opengles.pas.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on May 28, 2023, 02:34:38 am
FYI, the reimplementations of glBegin / glEnd etc from zgl_opengles_all.pas in terms of glDrawArrays and such (https://github.com/Seenkao/New-ZenGL/blob/05e76a5f22649aec80ce0ede31d7c1e241263dc2/Zengl_SRC/src/zgl_opengles_all.pas#L1720) should definitely also be used on desktop. Currently, ZenGL on desktop just actually uses the real immediate mode functions (https://github.com/Seenkao/New-ZenGL/blob/05e76a5f22649aec80ce0ede31d7c1e241263dc2/Zengl_SRC/src/zgl_opengl_all.pas#L111), which is much slower than the array-based wrappers from zgl_opengles.pas.
Благодарю за замечание! Но для персональных компьютеров, в ZenGL мы не можем использовать функции и процедуры из zgl_opengles_all.pas, они замедлят работу настольных компьютеров  :( .
Если переделывать, то переделывать надо будет полностью и делать общие функции и для OpenGL и для OpenGL ES.
Я думал уже над этим, и,  вероятно я займусь этим. Но, так же это надо будет сделать и для версий OpenGL 3+ (на выбор пользователя-программиста).

Google translate:
Thanks for the note! But for personal computers, in ZenGL we can't use functions and procedures from zgl_opengles_all.pas, they will slow down desktop computers :( .
If you redo it, then you will have to completely redo it and make common functions for both OpenGL and OpenGL ES.
I've already thought about it, and I'll probably do it. But, it will also need to be done for versions of OpenGL 3+ (at the choice of the user-programmer).
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on September 16, 2023, 06:20:58 pm
Всем привет! :-[
На данный момент у меня получилось запустить пример с OpenGL 3.3. Вывод треугольника используя шейдер, VAO и VBO. Прикладываю код, который должен работать в последних версиях ZenGL, заодно его прокомментировал для новичков:
Google translate:
Hi all!
At the moment I was able to run the example with OpenGL 3.3. Drawing a triangle using a shader, VAO and VBO. I am attaching code that should work in the latest versions of ZenGL, at the same time commented on it for beginners:

Code: Pascal  [Select][+][-]
  1. program demo19;
  2.  
  3. // RU: Этот файл содержит некоторые настройки(например использовать ли статическую компиляцию) и определения ОС под которую происходит компиляция.
  4. // EN: This file contains some options(e.g. whether to use static compilation) and defines of OS for which is compilation going.
  5. {$I zglCustomConfig.cfg}
  6. {$I zgl_config.cfg}
  7.  
  8. {$IFDEF WINDOWS}
  9.   {$R *.res}
  10. {$ENDIF}
  11.  
  12. uses
  13.   {$IFDEF UNIX}
  14.   cthreads,
  15.   {$ENDIF}
  16.   Math,
  17.   zgl_window,
  18.   zgl_screen,
  19.   zgl_timers,
  20.   zgl_utils,
  21.   zgl_types,
  22.   zgl_pasOpenGL,
  23.   zgl_opengl_all,
  24.   zgl_gltypeconst,
  25.   zgl_matrix,    // new
  26.   zgl_file,
  27.   zgl_log;
  28.  
  29. const
  30.   _vertex = 0;
  31.   _color  = 1;
  32.  
  33. var
  34.   DirApp  : UTF8String;
  35.   DirHome : UTF8String;
  36.   DirShader: UTF8String = {$IfNDef MAC_COCOA}'shaders/'{$EndIf};
  37.  
  38.   TimeStart  : LongWord = 0;
  39.  
  40.   // RU: переменная для хранения индекса юниформа.
  41.   // EN: variable to store the uniform index.
  42.   projMatrLoc: GLuint;
  43.   // RU: шейдер, вершинный шейдер, фрагментный шейдер.
  44.   // EN: shader, vertex shader, fragment shader.
  45.   shadProg, vertShad, fragShad: GLuint;
  46.   // RU: вершины (3 координаты).
  47.   // EN: vertices (3 coordinates).
  48.   verticesData: array[0..11] of Single = (-1, 0, -2, 1,
  49.                                           1, 0, -1, 1,
  50.                                           3, 1, -2, 1);
  51.   // RU: цветю.
  52.   // EN: color.
  53.   colorData: array[0..11] of Single    = (1, 0, 0, 1,
  54.                                           0, 1, 0, 1,
  55.                                           0, 0, 1, 1);
  56.   vao: GLuint;
  57.   vboHandles: array[0..1] of GLuint;
  58.  
  59. {// RU: матрица перспективы.
  60. // EN: perspective matrix.
  61. procedure Matrix4Perspective(fovy, aspect, _near, _far: Single);
  62. var
  63.   f: Single;
  64. begin
  65.   f := 1 / tan(fovy * Pi / 180);
  66.   projMatr[0] := f / aspect;
  67.   projMatr[1] := 0;
  68.   projMatr[2] := 0;
  69.   projMatr[3] := 0;
  70.  
  71.   projMatr[4] := 0;
  72.   projMatr[5] := f;
  73.   projMatr[6] := 0;
  74.   projMatr[7] := 0;
  75.  
  76.   projMatr[8] := 0;
  77.   projMatr[9] := 0;
  78.   projMatr[10] := (_far + _near) / (_near - _far);
  79.   projMatr[11] := 2 * _far * _near / (_near - _far);
  80.  
  81.   projMatr[12] := 0;
  82.   projMatr[13] := 0;
  83.   projMatr[14] := - 1;
  84.   projMatr[15] := 0;
  85. end;
  86.  
  87. // RU: загрузка шейдера, компиляция и проверка на успех компиляции.
  88. // EN: loading the shader, compiling and checking for compilation success.
  89. function LoadAndCreateShader(name: string; shade: GLuint): Boolean;
  90. var
  91.   Ftext: zglTFile;
  92.   Fmem: zglTMemory;
  93.   status: GLint;
  94. begin
  95.   Result := False;
  96.   // RU: проверка существования загружаемого файла.
  97.   // EN: Checking the existence of the downloaded file.
  98.   if not file_Exists(name) then
  99.     Exit;
  100.   // RU: открываем файл.
  101.   // EN: open the file.
  102.   if file_Open(Ftext, name, FOM_OPENR)then
  103.   begin
  104.     Fmem.Size := file_GetSize(Ftext);
  105.     Fmem.Position := 0;
  106.     // RU: подготавливаем память для загрузки шейдера.
  107.     // EN: prepare memory for loading the shader.
  108.     zgl_GetMem(Fmem.Memory, Fmem.Size);
  109.     // RU: загружаем шейдер в память.
  110.     // EN: load the shader into memory.
  111.     file_Read(Ftext, Fmem.Memory^, Fmem.Size);
  112.     file_Close(Ftext);
  113.     // RU: исходный код шейдера и его компиляция. Обратите внимание, "Fmem.Memory"
  114.     //     это указатель на память, где находится строка. И мы передаём указатель
  115.     //     на данный участок памяти. Это работает правильно, потому что данные
  116.     //     должны идти под двойным указателем (PPGLchar).
  117.     // EN: shader source code and its compilation. Note that "Fmem.Memory" is a
  118.     //     pointer to the memory where the string is located. And we pass a
  119.     //     pointer to this memory location. This works correctly because the data
  120.     //     must go under a double pointer (PPGLchar).
  121.     glShaderSource(shade, 1, @Fmem.Memory, @Fmem.Size);
  122.     glCompileShader(shade);
  123.     // RU: освобождаем память, данный текст больше не нужен.
  124.     // EN: freeing up memory, this text is no longer needed.
  125.     zgl_FreeMem(Fmem.Memory);
  126.   end;
  127.  
  128.   // RU: проверяем на успех компиляции шейдера.
  129.   // EN: check for success of shader compilation.
  130.   glGetShaderiv(shade, GL_COMPILE_STATUS, @status);
  131.   if status <> 1 then
  132.     Exit;
  133.   Result := True;
  134. end;    }
  135.  
  136. // RU: создание VAO и VBO.
  137. // EN: creation of VAO and VBO.
  138. procedure createVBOAndVAO;
  139. begin
  140.   // RU: буферные объекты.
  141.   // EN: buffer objects.
  142.   glGenBuffers(2, @vboHandles);
  143.  
  144.   // RU: Создаём объект массива вершин (для того чтоб при прорисовке этого не делать).
  145.   // EN: We create an object of an array of vertices (so that we don’t have to do this when drawing).
  146.   glGenVertexArrays(1, @vao);
  147.   // установим созданный VAO как текущий
  148.   glBindVertexArray(vao);
  149.  
  150.   // RU: активируем массив вершинных атрибутов.
  151.   // EN: activate the array of vertex attributes.
  152.   glEnableVertexAttribArray(_vertex); // vertex
  153.   glEnableVertexAttribArray(_color);  // color
  154.  
  155.   // RU: закрепить индекс 0 за буфером координат.
  156.   // EN: assign index 0 to the coordinate buffer.
  157.   glBindBuffer(GL_ARRAY_BUFFER, vboHandles[_vertex]);
  158.   // RU: заполнить буфер координат.      Это позволительно, ошибки не создаёт.
  159.   // EN: fill the coordinate buffer.     This is permissible and does not create errors.
  160.   glBufferData(GL_ARRAY_BUFFER, SizeOf(verticesData), @verticesData, GL_STATIC_DRAW);
  161.   glVertexAttribPointer(_vertex, 4, GL_FLOAT, GL_FALSE, 0, nil);
  162.  
  163.   // RU: закрепить индекс 1 за буфером цвета.
  164.   // EN: assign index 1 to the color buffer.
  165.   glBindBuffer(GL_ARRAY_BUFFER, vboHandles[_color]);
  166.   // RU: заполнить буфер цвета.      Это позволительно, ошибки не создаёт.
  167.   // EN: fill the color buffer.      This is permissible and does not create errors.
  168.   glBufferData(GL_ARRAY_BUFFER, SizeOf(colorData), @colorData, GL_STATIC_DRAW);
  169.   glVertexAttribPointer(_color, 4, GL_FLOAT, GL_FALSE, 0, nil);
  170.  
  171. end;
  172.  
  173. // RU: определяем ViewPort для нашей программы.
  174. // EN: We define the ViewPort for our program.
  175. procedure UserSetViewPort;
  176. begin
  177.   // RU: вместо "zgl_Get(WINDOW_WIDTH)" и "zgl_Get(WINDOW_HEIGHT)" можно создать
  178.   //     константы для ширины и высоты окна и указать их во ViewPort.
  179.   // EN: Instead of "zgl_Get(WINDOW_WIDTH)" and "zgl_Get(WINDOW_HEIGHT)" you can
  180.   //     create constants for the width and height of the window and specify them
  181.   //     in the ViewPort.
  182.   glViewport(0, 0, zgl_Get(WINDOW_WIDTH), zgl_Get(WINDOW_HEIGHT));
  183. end;
  184.  
  185. // RU: используем свою матрицу проекции.
  186. // EN: We use our projection matrix.
  187. procedure UserMode;
  188. begin
  189.   Matrix4_Perspective(45, zgl_Get(WINDOW_WIDTH) / zgl_Get(WINDOW_HEIGHT), 1, 100);
  190. //  glUseProgram(shadProg);        // это не обязательно
  191.   // RU: если данная переменная не используется в шейдере, то и вызов делать не будем.
  192.   // EN: if this variable is not used in the shader, then we will not make the call.
  193.   if projMatrLoc <> -1 then
  194.     glUniformMatrix4fv(projMatrLoc, 1, GL_FALSE, @projMatr);
  195.   //  glUseProgram(0);             // это не обязательно
  196. end;
  197.  
  198. // RU: Тут можно выполнять загрузку основных ресурсов и производить инициализацию
  199. //     начальных данных программы.
  200. // EN: Here you can load the main resources and initialize the initial program data.
  201. procedure Init;
  202. var
  203.   status: GLint;
  204. begin
  205.   // RU: создаём буфера и привязываем их к VAO.
  206.   // EN: we create buffers and bind them to VAO.
  207.   createVBOAndVAO;
  208.   // RU: создание шедерной программы и шейдеров.
  209.   // EN: creating a shader program and shaders.
  210.   shadProg := glCreateProgram;
  211.   vertShad := glCreateShader(GL_VERTEX_SHADER);
  212.   fragShad := glCreateShader(GL_FRAGMENT_SHADER);
  213.   // RU: загружаем шейдера, компилируем и делаем проверку успешно скомпилирован
  214.   //     шейдер или нет.
  215.   // EN: we load the shader, compile it and check whether the shader compiled
  216.   //     successfully or not.
  217.   if not LoadAndCreateShader(DirShader + 'first.vs', vertShad) or not LoadAndCreateShader(DirShader + 'first.fs', fragShad) then
  218.   begin
  219.     log_Add('Shader not loaded!!!');
  220.     zgl_Exit;
  221.   end;
  222.   // RU: присоединяем шейдера к программе.
  223.   // EN: We attach the shader to the program.
  224.   glAttachShader(shadProg, vertShad);
  225.   glAttachShader(shadProg, fragShad);
  226.   // RU: линкуем программу.
  227.   // EN: link the program.
  228.   glLinkProgram(shadProg);
  229.   // RU: проверяем статус линковки.
  230.   // EN: check the status of the link.
  231.   glGetProgramiv(shadProg, GL_LINK_STATUS, @status);
  232.   if status <> 1 then
  233.   begin
  234.     log_Add('Shader program not link!!!');
  235.     zgl_Exit;
  236.   end;
  237.   // RU: получаем юниформ-индекс projMatr из шейдерной программы.
  238.   // EN: get the uniform index projMatr from the shader program.
  239.   projMatrLoc := glGetUniformLocation(shadProg, 'projMatr');
  240.   // RU: проверяем, указана ли данная матрица в шейдере.
  241.   // EN: we check whether this matrix is specified in the shader.
  242.   if projMatrLoc <> -1 then
  243.   begin
  244.     // RU: это может быть не критичной ошибкой. Просто данный аргумент не
  245.     //     используется в шейдере или удалён из шейдера, как не используемый.
  246.     // EN: this may not be a critical error. It’s just that this argument is not
  247.     //     used in the shader or has been removed from the shader as not being used.
  248.     log_Add('projMatr not found in shader.');
  249.   end;
  250.  
  251.   // RU: проверка корректности скомпилированной программы.
  252.   // EN: checking the correctness of the compiled program.
  253.   glValidateProgram(shadProg);
  254.   glGetProgramiv(shadProg, GL_VALIDATE_STATUS, @status);
  255.   if status <> 1 then
  256.   begin
  257.     log_Add('Shader program not validate!!!');
  258.     zgl_Exit;
  259.   end;
  260.  
  261.   glDeleteShader(vertShad);
  262.   glDeleteShader(fragShad);
  263.  
  264.   glUseProgram(shadProg);
  265.   zgl_Enable(DEPTH_BUFFER);
  266.   glDepthMask(GL_TRUE);
  267.   glDepthFunc(GL_LEQUAL);
  268.   glDepthRange(0.0, 1.0);
  269. end;
  270.  
  271. procedure Draw;
  272. begin
  273.   // RU: Тут "рисуем" что угодно :)
  274.   // EN: Here "draw" anything :)        // это не обязательно
  275.   glClearDepth(1);
  276. //  glUseProgram(shadProg);             // это не обязательно
  277. //  glBindVertexArray(vao);             // это не обязательно
  278.   glDrawArrays(GL_TRIANGLES, 0, 3);
  279.  
  280. //  glUseProgram(0);                    // это не обязательно
  281. end;
  282.  
  283. procedure Update( dt : Double );
  284. begin
  285.   // RU: Эта функция наземенима для реализация плавного движения чего-либо, т.к. точность таймеров ограничена FPS.
  286.   // EN: This function is the best way to implement smooth moving of something, because accuracy of timers are restricted by FPS.
  287. end;
  288.  
  289. // RU: Пример использования таймера.
  290. // EN: An example of using a timer.
  291. procedure Timer;
  292. begin
  293.   // RU: Будем в заголовке показывать количество кадров в секунду.
  294.   // EN: Caption will show the frames per second.
  295.   wnd_SetCaption( 'test OpenGL 3.3. [ FPS: ' + u_IntToStr( zgl_Get( RENDER_FPS ) ) + ' ]' );
  296. end;
  297.  
  298. procedure KeyMouseEvent;
  299. begin
  300.   // RU: Функция обработки клавиатуры, мыши, джойстика и тачпада. Все события связанные с ними очищаются после её обработки.
  301.   //     Все попытки обработать клавиатуру, мышь или тачпад в других функциях могут привести к непредвиденным ситуациям.
  302.   // EN: Keyboard, mouse, joystick and touchpad handling function. All events associated with them are cleared after processing it.
  303.   //     Any attempt to handle the keyboard, mouse, or touchpad in other functions may lead to unexpected situations.
  304. end;
  305.  
  306. procedure Quit;
  307. begin
  308.   // RU: События которые надо произвести по завершению программы.
  309.   // EN: Events to be performed at the end of the program.
  310.   // это нужно или нет?
  311.   glBindBuffer(GL_ARRAY_BUFFER, 0);
  312.   glDeleteBuffers(2, @vboHandles);
  313.   glBindVertexArray(0);
  314.   glDeleteVertexArrays(1, @vao);
  315.  
  316.   glUseProgram(0);
  317.  
  318.   glDeleteProgram(shadProg);
  319. end;
  320.  
  321. Begin
  322.   // RU: Для загрузки/создания каких-то своих настроек/профилей/etc. можно получить путь к домашенему каталогу пользователя, или к исполняемому файлу(не работает для GNU/Linux).
  323.   // EN: For loading/creating your own options/profiles/etc. you can get path to user home directory, or to executable file(not works for GNU/Linux).
  324.   DirApp  := utf8_Copy( PAnsiChar( zgl_Get( DIRECTORY_APPLICATION ) ) );
  325.   DirHome := utf8_Copy( PAnsiChar( zgl_Get( DIRECTORY_HOME ) ) );
  326.  
  327.   // RU: Устанавливаем интервал на обработку событий клавиатуры, мыши, тачпада. И регистрируем процедуру.
  328.   //     Вызывать zgl_SetEventInterval не обязательно. Значение 16 стоит по умолчанию.
  329.   // EN: We set the interval for processing keyboard, mouse, touchpad events. And we register the procedure.
  330.   //     Calling zgl_SetEventInterval is optional. The default is 16.
  331.   zgl_SetEventsInterval(16);
  332.   zgl_Reg(SYS_EVENTS, @KeyMouseEvent);
  333.  
  334.   // RU: Создаем таймер с интервалом 1000мс.
  335.   // EN: Create a timer with interval 1000ms.
  336.   TimeStart := timer_Add( @Timer, 1000, t_Start );
  337.  
  338.   // RU: Регистрируем процедуру, что выполнится сразу после инициализации ZenGL.
  339.   // EN: Register the procedure, that will be executed after ZenGL initialization.
  340.   zgl_Reg( SYS_LOAD, @Init );
  341.   // RU: Регистрируем процедуру, где будет происходить рендер.
  342.   // EN: Register the render procedure.
  343.   zgl_Reg( SYS_DRAW, @Draw );
  344.   // RU: Регистрируем процедуру, которая будет принимать разницу времени между кадрами.
  345.   // EN: Register the procedure, that will get delta time between the frames.
  346.   zgl_Reg( SYS_UPDATE, @Update );
  347.   // RU: Регистрируем процедуру, которая выполнится после завершения работы ZenGL.
  348.   // EN: Register the procedure, that will be executed after ZenGL shutdown.
  349.   zgl_Reg( SYS_EXIT, @Quit );
  350.   // RU: пользовательский ViewPort. В данном случае это не обязательно.
  351.   // EN: custom ViewPort. In this case it is not necessary.
  352.   zgl_Reg(OGL_VIEW_PORT, @UserSetViewPort);
  353.   // RU: пользовательский режим 2d или 3d.
  354.   // EN: custom 2d or 3d mode.
  355.   zgl_Reg(OGL_USER_MODE, @UserMode);
  356.  
  357.   // RU: Устанавливаем заголовок окна.
  358.   // EN: Set the caption of the window.
  359.   wnd_SetCaption(utf8_Copy('01 - Initialization'));
  360.   // RU: Разрешаем курсор мыши.
  361.   // EN: Allow to show the mouse cursor.
  362.   wnd_ShowCursor( TRUE );                        // по умолчанию стоит
  363.  
  364.   // RU: Указываем первоначальные настройки.
  365.   // EN: Set screen options.
  366.   zgl_SetParam(800, 600, false, false);
  367.  
  368.   {$IfDef GL_VERSION_3_0}
  369.   // RU: Устанавливаем контекст OpenGL 3.3. Для этого надо включить  дефайн "USE_GL_33" и отключить "USE_MIN_OPENGL" в GLdefine.cfg.
  370.   // EN: Setting context OpenGL 3.3. To do this, enable the "USE_GL_33" define and disable "USE_MIN_OPENGL" in GLdefine.cfg.
  371.   SetGLVersionAndFlags(3, 3);
  372.   {$EndIf}
  373.  
  374.   // RU: Инициализируем ZenGL.
  375.   // EN: Initialize ZenGL.
  376.   zgl_Init();
  377. End.
  378.  
Вы можете скопировать первую демку и дополнить её недостающим кодом что я привёл. В файле GLdefine.cfg включите определения USE_GL_21 и USE_GL_33.
Может кому пригодится! В дальнейшем определённый функционал будет включён в ZenGL чтобы не приходилось переписывать по нескольку раз один и тот же код. На самом деле я уже добавляю этот функционал в ZenGL, ведь я хочу подключить GLES 2.0 и выше в Android. Заголовки уже все переведены, а вот опыта работы с GLES не хватает. Поэтому и начал рассматривать демки по работе с шейдерами,VAO, VBO и матрицами. Чтоб потом ни чего не упустить.
Google translate:
You can copy the first demo and supplement it with the missing code that I provided. In the GLdefine.cfg file, include the USE_GL_21 and USE_GL_33 definitions.
Maybe someone will find it useful! In the future, certain functionality will be included in ZenGL so that the same code does not have to be rewritten several times. In fact, I'm already adding this functionality to ZenGL, because I want to connect GLES 2.0 and higher to Android. All the titles have already been translated, but there is not enough experience working with GLES. That's why I started looking at demos on working with shaders, VAO, VBO and matrices. So that you don’t miss anything later.  ;)
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on October 19, 2023, 02:41:41 pm
В связи с выпуском ZenGL 4.3 и возможностью сборки проектов используя FPC/Lazarus + Android Studio прикладываю видео показывающие как можно собрать демки ZenGL.
Необходимый минимум для сборки проектов. И сборка проектов с помощью FPC из командной строки и Android Studio. (https://youtu.be/0CFj8EgIkXc)
Сборка проектов используя Lazarus и Android Studio. (https://youtu.be/LrRwjJq8nBI)
Видео на русском языке, но я надеюсь основная часть будет понятна и без перевода.   :-[

------------------------------------------------------------
Google translate:
In connection with the release of ZenGL 4.3 and the ability to build projects using FPC/Lazarus + Android Studio, I am attaching a video showing how to build ZenGL demos.
The required minimum for assembling projects. And building projects using FPC from the command line and Android Studio. (https://youtu.be/0CFj8EgIkXc)
Building projects using Lazarus and Android Studio. (https://youtu.be/LrRwjJq8nBI)
The video is in Russian, but I hope the main part will be clear without translation. :-[

ZenGL 4.3 download. (https://sourceforge.net/projects/new-zengl/)
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on November 11, 2023, 07:08:55 am
Rus:
Обновлена последняя версия ZenGL. (https://sourceforge.net/projects/new-zengl/files/) В связи с утраченной функциональностью.
Там же добавлен Light Engine 2D с правками под последнюю версию ZenGL. Читайте вложенный ReadME.txt.
Скачать можно по той же ссылке.

Eng:
Latest version of ZenGL updated. (https://sourceforge.net/projects/new-zengl/files/) Due to lost functionality.
Light Engine 2D was also added there with edits for the latest version of ZenGL. Read the attached ReadME.txt.
You can download it from the same link.

 8-)
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on December 21, 2024, 05:46:08 pm
Выпущена (https://sourceforge.net/projects/new-zengl/) новая версия 4.14, изменений не много:
- корректирована работа с мышью, как оказалось, если окно не занимает всё рабочее пространство, то мышь могла работать не корректно.
- добавлен флаг "ERROR_MOUSE_DXDY", если мышь вне пределов окна, то "mouseDX" и "mouseDY" будут возвращать данные значения.
- таймера теперь работают с типом Double (раньше были LongWord), для большей точности, но требуется проверка.
- возвращены функции: "u_IntToStr", "u_StrToInt", "u_FloatToStr", "u_StrToFloat", "u_BoolToStr" и "u_StrToBool" (в версии 4.13 были удалены, но это вызвало не совсем верную работу логов).
- добавлены функции: "u_DoubleToStr" и "u_StrToDouble" (мне надоело бодаться с Delphi  и вместо переопределения я их сделал отдельно).
- добавлены флаги: "WINDOW_FOR_FULL_X", "WINDOW_FOR_FULL_Y", "WINDOW_FULL_WIDTH" и "WINDOW_FULL_HEIGHT" - возвращают значения полного рабочего окна (не корректированного). Теперь флаги: "WINDOW_X", "WINDOW_Y", "WINDOW_WIDTH" и "WINDOW_HEIGHT" - возвращают значения корректированного окна (значения результата функции zgl_Get для этих флагов могут совпадать, если корректировки не производилось).
- немного корректирован код для Mac.

Дополнительно ввёл новые функции в файл "zgl_text.pas", так как собираюсь создавать диалоговые окна: "procedure CreateDataDialog(font: LongWord; Width, Height: Integer);" и "procedure AddTextDialog(const Text: UTF8String; Flags: LongWord; Scale: Single = 1; Color: LongWord = cl_White);". Ни где примеров работы с ними нет. С их помощью можно выводить разнообразный текст в определённую область, но делал я её для вывода в текстуру.

--------------------------------------------
Google translate:
Released (https://sourceforge.net/projects/new-zengl/) new version 4.14, not many changes:
- corrected work with the mouse, as it turned out, if the window does not occupy the entire workspace, then the mouse could work incorrectly.
- added the flag "ERROR_MOUSE_DXDY", if the mouse is outside the window, then "mouseDX" and "mouseDY" will return these values.
- timers now work with the Double type (previously they were LongWord), for greater accuracy, but verification is required.
- returned functions: "u_IntToStr", "u_StrToInt", "u_FloatToStr", "u_StrToFloat", "u_BoolToStr" and "u_StrToBool" (in version 4.13 they were removed, but this caused not quite correct work of logs).
- added functions: "u_DoubleToStr" and "u_StrToDouble" (I got tired of butting heads with Delphi and instead of redefining them I made them separately).
- added flags: "WINDOW_FOR_FULL_X", "WINDOW_FOR_FULL_Y", "WINDOW_FULL_WIDTH" and "WINDOW_FULL_HEIGHT" - return values ​​of the full working window (not adjusted). Now the flags: "WINDOW_X", "WINDOW_Y", "WINDOW_WIDTH" and "WINDOW_HEIGHT" - return values ​​of the adjusted window (the values ​​of the zgl_Get function result for these flags may coincide if no adjustments were made).
- slightly adjusted code for Mac.

Additionally, I added new functions to the "zgl_text.pas" file, since I am going to create dialog boxes: "procedure CreateDataDialog(font: LongWord; Width, Height: Integer);" and "procedure AddTextDialog(const Text: UTF8String; Flags: LongWord; Scale: Single = 1; Color: LongWord = cl_White);". There are no examples of working with them anywhere. With their help, you can output various text to a certain area, but I did it for output to a texture.

 :-[
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: fireboxsoft on December 28, 2024, 03:10:00 am
please help me
windows7 + lazarus 3.6
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on December 28, 2024, 08:48:51 am
Прошу прощения, это очередной мой недочёт...

Я перезалил последнюю версию, скачайте заново пожалуйста.

На данный момент при проверке демок на Windows 7 (на ноутбуке) я поймал неожиданные недочёты. Неправильная коррекция экрана. Возможно из-за того, что разрешение монитора меньше чем создаваемое окно. В дальнейшем буду тестить и исправлять ошибку.

Благодарю за проверку! Если будут ещё какие-то ошибки или вопросы, обращайтесь.

--------------------------------------
Google translate:
Sorry, this is another of my shortcomings...

I re-uploaded the latest version, please download it again.

At the moment, when checking the demos on Windows 7 (on a laptop), I caught unexpected shortcomings. Incorrect screen correction. Perhaps because the monitor resolution is smaller than the window being created. In the future, I will test and fix the error.

Thank you for checking! If there are any other errors or questions, please contact me.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: fireboxsoft on December 28, 2024, 01:20:46 pm
Chinese:太感谢了!刚刚下载了最新版本,经过测试,成功编译,demo顺利运行!但对于中文的显示目前没有成功,中文显示是"?",我再研究研究
Eng:Thank you so much! I just downloaded the latest version. After testing, it was successfully compiled and the demo ran smoothly! However, the Chinese display has not been successful so far. The Chinese display is &quot;?&quot;. I will study it further.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: fireboxsoft on December 28, 2024, 02:22:05 pm
I have learned how to display Chinese and successfully displayed Chinese, thank you:)
utf8_Copy( PAnsiChar('中文'))
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on December 28, 2024, 02:57:02 pm
Да, я забыл, что для отображения дополнительного языка, нужно сделать дополнительный шрифт с символикой данного языка. Используя генератор шрифтов ZenFont. Привык что либо латиница, либо кириллица, где уже всё подготовлено для вывода.

Важно! Надо помнить, что не все шрифты поддерживают китайский язык (или какой-то дополнительный).
Меняйте шрифты один за другим, пока не добьётесь успеха, особенно если введённые вами символы отобразились в поле ввода Edit.

-------------------------------------
Google translate:
Yes, I forgot that to display an additional language, you need to make an additional font with the symbols of this language. Using the font generator ZenFont. I'm used to either Latin or Cyrillic, where everything is already prepared for output.

Important! Remember that not all fonts support Chinese (or any additional language).
Change fonts one by one until you succeed, especially if the characters you entered are displayed in the Edit input field.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on December 28, 2024, 03:17:56 pm
I have learned how to display Chinese and successfully displayed Chinese, thank you:)
utf8_Copy( PAnsiChar('中文'))
я наверняка дольше это делал.  :-[ Но тоже получилось.
Когда вы реализовали свой шрифт, то достаточно указать в начале страницы {$Codepage UTF8} и не обязательно будет указывать ни "PAnsiChar", ни делать преобразование "utf8_Copy". У меня отображалось и без этого, если я указал что кодовая страница UTF-8.

--------------------------------------
Google translate:
I probably did it longer. :-[ But it worked too.
When you have implemented your font, it is enough to specify {$Codepage UTF8} at the beginning of the page and it will not be necessary to specify either "PAnsiChar" or to do the "utf8_Copy" conversion. It was displayed for me without this, if I specified that the code page is UTF-8.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on December 28, 2024, 06:22:51 pm
Обновил версию 4.14 и исправил ошибки в Windows связанные со "ScreenResolution" окна и созданием полноэкранного окна (возможно не все ошибки исправил).

Google translate:
Updated version 4.14 and fixed errors in Windows related to "ScreenResolution" of the window and creating a full-screen window (maybe not all errors were fixed).

Download ZenGL. (https://sourceforge.net/projects/new-zengl/)
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: fireboxsoft on December 29, 2024, 08:14:36 am
eng:Thanks for the correction, but I failed to compile demo1 after downloading the latest version.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: fireboxsoft on December 29, 2024, 08:38:54 am
I changed the Width and Height in [u_Warning( &#39;Cannot set fullscreen mode: &#39; + u_IntToStr( Width ) + &#39;x&#39; + u_IntToStr( Height ) ); ] in line 1001 of zgl_screen.pas to [wndWidth] and [wndHeight] , compiled successfully, and the demo runs normally, and Chinese can be displayed directly.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on December 29, 2024, 09:31:19 am
fireboxsoft, благодарю! Это опять мой недочёт, делал на одном компьютере, а правки вносил на другом без проверки (хотя мог проверить, в очередной раз поспешил). Исправления внёс.

Google translate:
fireboxsoft, thank you! This is my mistake again, I did it on one computer and made the edits on another without checking (although I could have checked, I was in a hurry again). I made the edits.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: fcu on December 30, 2024, 02:06:59 pm
Hi SeenKao , is it possible to build ZenGL as a single DLL
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on December 30, 2024, 02:15:44 pm
fcu, да можно, но многой функциональности будет не хватать (что может вызвать ошибки при работе приложения), я потихоньку собираю все необходимые функции для создания динамических библиотек.

Google translate:
fcu, yes, it is possible, but a lot of functionality will be missing (which can cause errors when running the application), I am slowly collecting all the necessary functions for creating dynamic libraries.
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: fcu on December 30, 2024, 03:09:35 pm
thanks , if i remember correctly the old zengl has a shared library building option (https://github.com/goldsmile/zengl/tree/master/src/Lazarus) , could it be adapted with the new zengl ? 
Title: Re: ZenGL +android + MacOS Cocoa (beta)
Post by: Seenkao on December 30, 2024, 03:26:07 pm
fcu, новая версия - это улучшенная старая версия, которая исправляет множество мелких ошибок и работа определённой функциональности производится по другому. Именно из-за изменений нет возможности собрать динамическую библиотеку.

Для создания динамической библиотеки надо добавить как минимум основную функциональность новой библиотеки. Это может сработать, но если не будет полной функциональности, то может ломаться в любом месте программы (потому что может не хватать необходимых вызовов).

Да, я постараюсь побыстрее заняться этим и внести всю необходимую функциональность. И в дальнейшем её поддерживать.


-------------------------------
Google translate:
fcu, the new version is an improved old version that fixes many minor bugs and certain functionality works differently. It is because of the changes that it is not possible to build a dynamic library.

To create a dynamic library, you need to add at least the basic functionality of the new library. This may work, but if there is no full functionality, it may break anywhere in the program (because the necessary calls may be missing).

Yes, I will try to get to this as soon as possible and add all the necessary functionality. And support it in the future.
Title: Re: ZenGL +android + MacOS Cocoa
Post by: fcu on December 30, 2024, 04:09:39 pm
thank you very much
Title: Re: ZenGL +android + MacOS Cocoa
Post by: Seenkao on January 07, 2025, 11:42:40 am
Обновил версию до ZenGL 4.15 (https://sourceforge.net/projects/new-zengl/).

  Больших изменений нет, но какие-то критичные изменения присутствуют:
Quote
- исправлен баг для Linux, когда при вызове "zgl_SetParam" параметры рабочей области не менялись вместе с общей областью. Это критично для функционала мыши: например в игре "Змейка", если включить мышь, не работал нижний пункт меню, мышь якобы выходила за пределы окна.
- исправлены ошибки для Mac OS. В том числе и изменение размеров окна и переключения окна в полноэкранный режим и обратно (теперь 4-я демка правильно работает, кроме одного пункта).
- когда при создании окна задан хоть один параметр больше размера окна, приложение переходит в полноэкранный режим.
- исправлены ошибки связанные с Android. В том числе исправлена ошибка по работе с тачскрином, теперь корректированное окно возвращает значения касаний только в пределах рабочего окна (для полного окна есть глобальные координаты).
- исправлена "древняя" ошибка джойстиков (Linux) при отладке приложений (и сразу во все демки добавлены все флаги отладки) - благодарность Skvoznjak за напоминание и напоминание как обойти проблему.
- исправлена работа с мышкой в LCL-приложениях.
- исправлено возвращение дирректорий для LCL-приложений.

В общем где-то ошибки древние и руки до них не доходили, а где-то закравшиеся ошибки, из-за того, что пилю до сих пор внутрянку ZenGL. Пора бы уже достаточно стабильной ей стать, да всё равно мелочи вылазят.

Вот что это за баг выполз? Для Android-приложений. Если где-то в начале объявить одним из первых модулей Sysutils, то приложение просто "не запустится", и ошибок не выдаст. Просто будет висеть и пытаться проинициализироваться.
Отметьте для себя, что для Android не надо Sysutils ставить одним из первых модулей в главном модуле программы.

В общем, думаю достаточно стабильная версия. Я даже до Mac-а добрался, чтоб исправить ошибки (хотя, там исправлять то нечего было для изменения разрешения, сам давным давно пропустил момент обновления окна).

Всех с праздниками!  8-)


-------------------------------------------------
Google translate:
Updated to ZenGL 4.15 (https://sourceforge.net/projects/new-zengl/).

No major changes, but some critical changes are present:
Quote
- fixed a bug for Linux, when calling "zgl_SetParam" the parameters of the workspace did not change along with the general area. This is critical for the functionality of the mouse: for example, in the game "Snake", if you turn on the mouse, the bottom menu item did not work, the mouse allegedly went beyond the window.
- fixed bugs for Mac OS. Including changing the window size and switching the window to full-screen mode and back (now the 4th demo works correctly, except for one item).
- when at least one parameter larger than the window size is specified when creating a window, the application switches to full-screen mode.
- fixed bugs related to Android. Including the bug with working with the touchscreen fixed, now the adjusted window returns touch values ​​only within the working window (there are global coordinates for the full window).
- the "ancient" bug with joysticks (Linux) when debugging applications fixed (and all debug flags were added to all demos at once) - thanks to Skvoznjak for the reminder and reminder on how to get around the problem.
- working with the mouse in LCL applications fixed.
- returning directories for LCL applications fixed.

In general, some of the errors are ancient and I never got around to them, and some are errors that have crept in because I'm still sawing the internals of ZenGL. It's time for it to become stable enough, but little things still pop up.

What kind of bug is this? For Android applications. If somewhere at the beginning you declare Sysutils as one of the first modules, then the application simply "will not start" and will not give errors. It will simply hang and try to initialize.
Note for yourself that for Android you do not need to set Sysutils as one of the first modules in the main module of the program.

In general, I think it is a fairly stable version. I even got to Mac to fix the errors (although there was nothing to fix there to change the resolution, I myself missed the moment of updating the window a long time ago).

Happy holidays to all! 8-)
Title: Re: ZenGL +android + MacOS Cocoa
Post by: Seenkao on February 14, 2025, 03:52:25 am
Привет всем!  ;)

Выпущена новая версия --> ZenGL 4.16 (https://sourceforge.net/projects/new-zengl/). <--

Из важных изменений ZenGL это:
Quote
- созданы динамические библиотеки (в архиве содержаться, но можете собрать и сами).
- перебраны модули "zgl_sprite_2d.pas", "zgl_grid_2d.pas", "zgl_render_target.pas" и "zgl_textures.pas". Из-за чего новая версия обратно не совместима с прошлыми версиями.  :(

Теперь вы можете собрать четыре разных динамических библиотеки ZenGL! Обратите внимание на это.
- одна библиотека для стандартного функционала ZenGL.
- одна библиотека для использования ZenGL в LCL/VCL приложениях.
- одна библиотека для использования нужной вам версии OpenGL (можно использовать полную функциональность OpenGL, но в большинстве случаев не совместима с графическим функционалом ZenGL).
- одна библиотека для использования нужной вам версии OpenGL в LCL/VCL приложениях.

Из обновлений ZenGL:
Quote
- изменены константы для таймеров, теперь: TIMER_STOP, TIMER_START, TIMER_SLEEP_TO_START и TIMER_SLEEP_TO_STOP.
- в модуль "zgl_textures.pas" добавлены функции: "tex_GetWidth", "tex_GetHeight", "tex_GetTextireID" и "tex_GetZglPTexture".
- в модуль "zgl_render_target.pas" добавлена функция "rtarget_GetSurface".
- исправлена ошибка в процедуре "pr2d_Rect", при определённых данных прямоугольник мог не прорисоваться.
- добавлена процедура "mouse_LockInScreen", которая производит захват мыши в области экрана. Пока только для Windows и для Linux.
- исправлена давняя проблема в процедуре "tex_CalcAlpha". Пока не известно, влияла ли на что-то эта ошибка, но есть подозрения что это вызывало переполнение памяти в демках "LightEngine2D" для Delphi.
- добавлена 17-я демка, показывающая работу с полным OpenGL в LCL/VCL приложениях.
- в модуль "zgl_pasOpenGL" добавлены функции: "gl_GetVerMajor" и "gl_GetVerMinor". Нужны только для связи ZenGL с данным модулем.
- в модуль "zgl_font.pas" добавлена функция "zgl_GetFont".
- созданы демки для новых версий Delphi. С динамическими библиотеками теперь можно запускать 64-х битные приложения на Delphi.
- в модуль "zgl_application" добавлены процедуры "app_MainLoopHandle" и "app_MouseProc" для обратной связи с ZenGL. Нужно только для LCL/VCL приложений.
- другие множественные изменения.

Из обновлений Green Engine:
Quote
- добавлена функция "ge_GetEdit" - возвращает указатель на структуру поля ввода.
- функция "ge_GetEditToText" переименована в "ge_GetTextEdit".
- функция "ge_SetTextToEdit" переименована в "ge_SetTextEdit".
- некоторые другие корректировки кода.

Изменений очень много, если хотите с ними ознакомиться, читайте "Update_ZenGL.txt".

Множество примеров в демках и документированы! Так же лежат сопровождающие файлы "ReadMe.txt".

Всем успехов!  :D



-----------------------------------------------------------------------------
Google translate:
Hello everyone! ;)

A new version of --> ZenGL 4.16 (https://sourceforge.net/projects/new-zengl/) has been released. <--

Among the important changes in ZenGL are:
Quote
- dynamic libraries have been created (they are included in the archive, but you can compile them yourself).
- modules "zgl_sprite_2d.pas", "zgl_grid_2d.pas", "zgl_render_target.pas" and "zgl_textures.pas" have been rewritten. Because of this, the new version is not backward compatible with previous versions. :(

You can now build four different ZenGL dynamic libraries! Pay attention to this.
- one library for standard ZenGL functionality.
- one library for using ZenGL in LCL/VCL applications.
- one library for using the OpenGL version you need (you can use the full functionality of OpenGL, but in most cases it is not compatible with the graphics functionality of ZenGL).
- one library for using the version of OpenGL you need in LCL/VCL applications.

From the updates of ZenGL:
Quote
- changed constants for timers, now: TIMER_STOP, TIMER_START, TIMER_SLEEP_TO_START and TIMER_SLEEP_TO_STOP.
- the following functions have been added to the "zgl_textures.pas" module: "tex_GetWidth", "tex_GetHeight", "tex_GetTextireID" and "tex_GetZglPTexture".
- the "rtarget_GetSurface" function has been added to the "zgl_render_target.pas" module.
- a bug in the "pr2d_Rect" procedure has been fixed; with certain data, the rectangle might not be drawn.
- the "mouse_LockInScreen" procedure has been added, which captures the mouse in the screen area. So far only for Windows and Linux.
- a long-standing problem in the "tex_CalcAlpha" procedure has been fixed. It is not yet known whether this error affected anything, but there are suspicions that it caused a memory overflow in the "LightEngine2D" demos for Delphi.
- the 17th demo was added, showing work with full OpenGL in LCL/VCL applications.
- the following functions were added to the "zgl_pasOpenGL" module: "gl_GetVerMajor" and "gl_GetVerMinor". They are only needed to connect ZenGL with this module.
- the "zgl_font.pas" module added the "zgl_GetFont" function.
- demos for new versions of Delphi were created. With dynamic libraries, you can now run 64-bit Delphi applications.
- "app_MainLoopHandle" and "app_MouseProc" procedures for feedback with ZenGL have been added to the "zgl_application" module. This is only needed for LCL/VCL applications.
- other numerous changes.

From the Green Engine updates:
Quote
- added the "ge_GetEdit" function - returns a pointer to the input field structure.
- renamed the "ge_GetEditToText" function to "ge_GetTextEdit".
- renamed the "ge_SetTextToEdit" function to "ge_SetTextEdit".
- some other code adjustments.

There are a lot of changes, if you want to read them, read "Update_ZenGL.txt".

Lots of demos and documented examples! Also there are accompanying files "ReadMe.txt".

Good luck to everyone! :D

Title: Re: ZenGL +android + MacOS Cocoa
Post by: fcu on February 22, 2025, 10:12:18 am
nice, you've done an excellent work
about the particle editor application that was in the zengl ancient website (https://www.zengl.org/download.html)   
do you have a copy of it ?
Title: Re: ZenGL +android + MacOS Cocoa
Post by: Seenkao on March 02, 2025, 01:33:50 am
fcu, благодарю!
Извиняюсь что не сразу отвечаю. Я перебрал версию программы "Particle Engine", положите её в папку "tools" и соберите проект.
Делаёте сборку только со статической линковкой. С динамической могут быть проблемы.
Я проверял в Linux её, потому не могу 100% сказать что на других платформах она соберётся, но надеюсь должна.
На других платформах проверю позже.

------------------------------------------
Google translate:
fcu, thank you!
Sorry for not answering right away. I have reworked the version of the program "Particle Engine". Put it in the "tools" folder and build the project.
Build only with static linking. There may be problems with dynamic.
I checked it on Linux, so I can't say 100% that it will build on other platforms, but I hope it will work.
I'll check on other platforms later.
Title: Re: ZenGL +android + MacOS Cocoa
Post by: Seenkao on March 05, 2025, 04:21:00 pm
Всем привет!
Очередное обновление для --> ZenGL 0.4.17 (https://sourceforge.net/projects/new-zengl/). <--

Quote
- исправлены проблемы в работе многих менеджеров. Ранее могла проявляться ошибка когда ресурс якобы не загрузился/не создался.
- исправлена ошибка в функции text_Draw, это было при использовании выравнивания и проявлялось когда переносится только одно слово.
- теперь в функциях text_DrawEx и text_DrawInRectEx шкала размерности производит масштаб согласно заданному размеру шрифта.
- исправлена ошибка при переключении рендеринга с фреймбуфера на экран.
- добавлены проекты "LightEngine2D" и "Particle editor".
- в модуле zgl_primitives_2d.pas изменены процедуры: pr2d_Circle и pr2d_Ellipse. Теперь с помощью этих функций, при сплошной заливке, можно менять градиент цвета от центра к краям.
и некоторые другие изменения.

Динамические библиотеки были пересобраны.

--------------------------------------------------------
Google translate:

Hello everyone!
Another update for --> ZenGL 0.4.17 (https://sourceforge.net/projects/new-zengl/). <--

Quote
- fixed problems in many managers. Previously, an error could appear when the resource allegedly did not load/was not created.
- fixed a bug in the text_Draw function; this happened when using alignment and appeared when only one word was transferred.
- now in the text_DrawEx and text_DrawInRectEx functions the dimension scale produces a scale according to the specified font size.
- fixed an error when switching rendering from the framebuffer to the screen.
- added projects "LightEngine2D" and "Particle editor".
- in the module zgl_primitives_2d.pas the procedures pr2d_Circle and pr2d_Ellipse were changed. Now with the help of these functions, with a solid fill, you can change the color gradient from the center to the edges.
and some other changes.

Dynamic libraries have been rebuilt.

 8)
Title: Re: ZenGL +android + MacOS Cocoa
Post by: Seenkao on May 01, 2025, 10:03:34 pm
Всем привет! ;)
Выпущено очередное обновление для -->ZenGL 0.4.18 (https://sourceforge.net/projects/new-zengl/).<--
Quote
- Устранена утечка памяти для LCL/VCL приложений.
- Возвращены старые процедуры pr2d_Circle и pr2d_Ellipse. И "добавлены" новые pr2d_CircleEx и pr2d_EllipseEx - несут небольшое расширение для стандартных процедур, это возможность заливки разным цветом от центра к краям.
- Корректирован код для LightEngine2d.
- добавлены функции: u_ByteToHex, u_WordToHex, u_LWordToHex, u_ByteToBin, u_WordToBin и u_LWordToBin. В большинстве своём они нужны только для отладки.
- исправлены проблемы совместимости кода для OpenGL с кодом для OpenGL ES.
- добавлена процедура wnd_SetAutocenter - указывающая что дальшение изменения окна должны автоматически центрировать окно.
и некоторые другие изменения.

Динамические библиотеки были пересобраны (напоминаю, вы можете их собрать сами).
 :-[

-----------------------------------------------------------
Google translate:
Hello everyone! ::)
Another update has been released for -->ZenGL 0.4.18 (https://sourceforge.net/projects/new-zengl/).<--
Quote
- Fixed a memory leak for LCL/VCL applications.
- Old procedures pr2d_Circle and pr2d_Ellipse have been returned. And new pr2d_CircleEx and pr2d_EllipseEx have been "added" - they carry a small extension for standard procedures, this is the ability to fill with different colors from the center to the edges.
- Corrected code for LightEngine2d.
- added functions: u_ByteToHex, u_WordToHex, u_LWordToHex, u_ByteToBin, u_WordToBin and u_LWordToBin. Mostly they are needed only for debugging.
- fixed compatibility issues of code for OpenGL with code for OpenGL ES.
- added procedure wnd_SetAutocenter - indicating that further changes to the window should automatically center the window.
and some other changes.

Dynamic libraries were rebuilt (remember, you can build them yourself).
 :-[
Title: Re: ZenGL +android + MacOS Cocoa
Post by: fcu on May 02, 2025, 02:57:02 pm
hi seenkao  , i still couldn't compile the particle editor , got some error messages related to pr2d_Circle function
can you check please ?

i am using Lazarus 4 RC3 with FPC 3.2.2 64bits on windows 10 64bits   
Title: Re: ZenGL +android + MacOS Cocoa
Post by: Seenkao on May 02, 2025, 05:01:07 pm
fcu, благодарю за информацию!
Пока удалите в модуле "Zenrender.pas" в вызовах "pr2d_circle" второй "newColor[0]" второй "cl_Red" (если не удалите, процедура может не правильно работать).
Должно получиться:
"pr2d_circle(emitter.Params.Position.X + EndX, emitter.Params.Position.Y + EndY, 5, newColor[0], 16, PR2D_FILL);"
и
"pr2d_circle(emitter.Params.Position.X, emitter.Params.Position.Y, Tlength, cl_Red);"

Или замените все вызовы "pr2d_circle" на "pr2d_circleEx" (возможно это будет проще).

Я cделаю первый вариант и перезалью ZenGL.


Google translate:
fcu, thanks for the info!
For now, delete the second "newColor[0]" and the second "cl_Red" in the "pr2d_circle" calls in the "Zenrender.pas" module (if you don't, the procedure may not work correctly).
You should get:
"pr2d_circle(emitter.Params.Position.X + EndX, emitter.Params.Position.Y + EndY, 5, newColor[0], 16, PR2D_FILL);"
and
"pr2d_circle(emitter.Params.Position.X, emitter.Params.Position.Y, Tlength, cl_Red);"

Or replace all "pr2d_circle" calls with "pr2d_circleEx" (maybe it will be easier).

I will make the first version and reupload ZenGL.

Re-uploaded, you can just download it.
Title: Re: ZenGL +android + MacOS Cocoa
Post by: fcu on May 02, 2025, 07:20:43 pm
thanks
now i have problem building zengl.dll 32bits version
this is the error message i got
Title: Re: ZenGL +android + MacOS Cocoa
Post by: Seenkao on May 02, 2025, 09:33:33 pm
Code: Pascal  [Select][+][-]
  1. var
  2.   SetUserMode: procedure;

fcu, я извиняюсь, но я не могу получить вашей ошибки. Я не знаю по какой причине объявление для SetUserMode может определяться как LongWord.
Проверьте не давали ли вы ей случайно новое определение. Может что-то меняли в проекте?
На всякий случай напомню, для сборки динамической библиотеки для Windows надо пользоваться проектом ZenGL-win.


------------------------------------------
Google translate:
fcu, I'm sorry, but I can't get your error. I don't know why the declaration for SetUserMode can be defined as LongWord.
Check if you accidentally gave it a new definition. Maybe you changed something in the project?
Just in case, I'll remind you that to build a dynamic library for Windows, you need to use the ZenGL-win project.

Title: Re: ZenGL +android + MacOS Cocoa
Post by: fcu on May 02, 2025, 09:50:53 pm
it seems that FPC trunk 3.3.1 could not build zengl
i switched to 3.2.2 and it work perfect   
Title: Re: ZenGL +android + MacOS Cocoa
Post by: Seenkao on May 02, 2025, 10:19:08 pm
fcu, ранее вы писали, что использовали FPC 3.2.2.  :) Я и подумал, что собирали с его помощью.
Позже потестирую и для версии FPC 3.3.1. Может получится узнать в чём проблема (для Android приходилось уровень оптимизации понижать).

Хорошо, что вам всё удалось собрать! Успехов!


Google translate:
fcu
Earlier you wrote that you used FPC 3.2.2. :) I thought that you were compiling with it.
Later I will test for version FPC 3.3.1. Maybe I will be able to find out what the problem is (for Android I had to lower the optimization level).

It's good that you managed to compile everything! Good luck!
Title: Re: ZenGL +android + MacOS Cocoa
Post by: Seenkao on June 15, 2025, 08:57:55 pm
Hi All! ;)
Выпущена новая версия --> ZenGL 4.19. (https://sourceforge.net/projects/new-zengl/) <--
Изменения произошли достаточно глобальные и возможно версия не стабильна. Потому, если что, используйте предыдущую версию.

Основные изменения:
Quote
- изменена работа с загрузкой файлов. Теперь за счёт флага можно указать, что путь указан глобальный. Необходимо для LCL/VCL приложений, где используются OpenDialog и что-нибудь подобное.
- частицы: добавлены процедура и функция для передачи координат излучателя. В дальнейшем могут быть изменение их работы.
- изменена работа рендера. Исключена вся функциональность glBegin, glEnd, glVertex и другие из функциональности ZenGL. Теперь всё работает посредством использования glDrawArrays - кроссплатформенно по умолчанию.
- изменена работа с цветом. Теперь основа для цвета это zglTColor (zglPColor), ранее было LongWord.
- добавлены расширенные функции для рисования линии, в них можно задавать начальный и конечный цвет.
- множественные изменения согласно изменений выше.

Просьба сообщать о всех проблемах работы с библиотекой! Очень сложно всё протестировать. По возможности проверил всё что возможно, но наверняка что-то упустил.

Всем успехов! :)


-----------------------------------------------
Google translate:
A new version of --> ZenGL 4.19. (https://sourceforge.net/projects/new-zengl/) <--
The changes are quite global and the version may not be stable. Therefore, if anything, use the previous version.

Major changes:
Quote
- the work with file loading has been changed. Now, due to the flag, you can specify that the path is global. Necessary for LCL/VCL applications that use OpenDialog and something similar.
- particles: a procedure and a function for transmitting emitter coordinates have been added. In the future, their work may change.
- the renderer has been changed. All glBegin, glEnd, glVertex and other functionality from ZenGL functionality has been excluded. Now everything works using glDrawArrays - cross-platform by default.
- color handling has been changed. Now the basis for color is zglTColor (zglPColor), previously it was LongWord.
- extended functions for drawing a line have been added, you can set the start and end color in them.
- multiple changes according to the changes above.

Please report any problems with the library! It is very difficult to test everything. I checked everything I could, but I probably missed something.

Good luck to everyone! :)
Title: Re: ZenGL +android + MacOS Cocoa
Post by: Seenkao on March 02, 2026, 09:01:31 pm
Hi All! ::)

Встречайте очередное обновление >>> ZenGL 4.20 (https://sourceforge.net/projects/new-zengl/). <<<
Версия насколько возможно стабилизирована, надеюсь критических недоработок нет. Основной список изменений:
Quote
02.03.2026
   Исправлены проблемы для сборки програм под Delphi. Введено определение CPU64 именно для 64-х битного Delphi.
   Добавлен код для устранения бага, когда поле ввода (Green Engine) возвращая строку, могла "поломать" программу.
   Исправления в модуле "zgl_joystick.pas", теперь и динамические библиотеки правильно возвращают имя джойстиков. И если определилось несколько джойстиков, то и узнать "имена" можно у всех (не более 10, от 0 до 9).

26.02.2026
   Модифицирован проект для сборки динамических библиотек. Теперь достаточно выбрать под какую архитектуру собирать библиотеку (в настройках проекта).

23.02.2026
   Для LCL-приложений введена поддержка GTK3, QT5 и QT6. Реализация в основном в демках.

20.02.2026
   Изменена работа переменных "mouseDX" и "mouseDY", а так же соответствующих функций "mouse_DX" и "mouse_DY". Теперь они возвращают дельту X и дельту Y.
   Исправлены возможные проблемы при работе с ресурсами. Теперь придёт оповещение, если вы включили модуль в свой проект, но определение для модуля в файле "zgl_config.cfg" было отключено.
   Исправлены проблемы с загрузкой ресурсов, в частности со шрифтом. Приложение закрывается, если ресурсы не были загружены, а при создании шрифтов для таких случаев, устранены утечки.

16.02.2026
   LongWord в ZenGL переименован в Cardinal - везде. Так как Delphi, для 64-х битных систем считает LongWord равным LongLongWord (стараются соответствовать unix).
   Автоматически исправлены малые проблемы для 64-х битных программ, собранных в Delphi.

07.02.2026
   Оптимизирована процедура "tex_CalcAlpha" в модуле " zgl_textures". Оптимизирована под скорость работы, как часто используемая (требуется проверка, на всякий случай).
   Произведена оптимизация процедур в модуле "zgl_render_2d.pas" связанных с выводом изображения: "render_AddVertex4", "render_AddVertex6", "render_AddVertexTexture6", "render_AddColor4", "render_AddVCAColor4", "render_AddVCAColor6" и "render_AddColor6". Должно работать более быстро, но видно будет только на слабых машинах (для них и производилась оптимизация).

21.01.2026
   Внесены исправления в модуль "zgl_render_2d.pas". Исправления касаются пересылки массивов данных для вывода, что должно повысить производительность и уменьшило конечный код.

11.12.2025
   В модуль "zgl_matrix" введёно определение "USE_SINGLE", определяющее как будет производится работа с данными для матриц: Single или Double. Для использования обоих видов матриц следует создать свой модуль работы с матрицами.

03.11.2025.
   Корректировка возвращения mouseX и mouseY для Android. Теперь координаты для мыши только по нулевому тапу работают.

17.08.2025
   Удалены константы и переменные которые были реализованы для клавиатуры: KT_DOWN, KT_UP, keyDownRepeat, keyBoolRepeat, beginKeyDelay, repeatKeyDelay и keyDelayWork.
   Удалены процедуры с ними связанные: setKey_BeginRepeat и setKey_Repeat.

08.08.2025
   Исправлена проблема при попытке вывести не существующую текстуру.
   При создании нулевой текстуры "tex_CreateZero", если приходят нулевые данные, то они по умолчанию передаются в 1.

07.08.2025
   Корректирована работа ZenGUI. Теперь обработка мыши происходит нормально. Но по прежнему остались утечки при использовании диалоговых окон с эффектами и другие мелкие проблемы.

19.07.2025
   Устранены проблемы при попытке загружать файлы без указания имени и расширения.

18.07.2025
   Устранены возможные утечки (вероятно не полностью).
   Исправлена ошибка в имени функции "tex_GetTextureID" (было "tex_GetTextireID").
   Добавлен проект ZenGUI (вероятнее всего временно, нужен для тестов), но у него ещё много проблем.

17.07.2025
   Исправлена работа с мышью. Теперь очистка данных производится верно.

Так же в демках содержится последнее обновление эмулятора PZ Nes. Его можно собрать и под Android и потестировать. Только на android у вас должен быть контроллер, чтоб поиграть в игру. Запустить можно несколько игр, но я пока не реализовал выбор игр. Прощу прощения.

UPD: Забыл. Теперь все проекты для Android находятся в одном проекте с FPC/Lazarus. Под нужную платформу надо выбирать в настройках режим сборки (build mode). Они все настроены, потому нужно только выбрать нужный режим.
Так же были добавлены демки для старых версий Android. Мне это надо для тестирования.

Всем успехов!

---------------------------------------------------------

---------------------------------------------------------
Google translate:
Welcome to the next update >>> ZenGL 4.20 (https://sourceforge.net/projects/new-zengl/). <<<
This version is as stable as possible, and I hope there are no critical issues. The main changelog:
Quote
02.03.2026
Fixed issues with building programs for Delphi. CPU64 detection was introduced specifically for 64-bit Delphi.
Added code to fix a bug where the Green Engine input field, returning a string, could "break" the program.
Fixed the "zgl_joystick.pas" module; dynamic libraries now correctly return joystick names. If multiple joysticks are detected, you can find the names of all of them (up to 10, from 0 to 9).

26.02.2026
The project for building dynamic libraries has been modified. Now you only need to select the architecture for which to build the library (in the project settings).

23.02.2026
Support for GTK3, QT5, and QT6 has been added for LCL applications. The implementation is mainly in demos.

February 20, 2026
The behavior of the "mouseDX" and "mouseDY" variables, as well as the corresponding "mouse_DX" and "mouse_DY" functions, has been changed. They now return delta X and delta Y!
Fixed possible issues when working with resources. You will now receive a notification if you have included a module in your project but the module definition in the "zgl_config.cfg" file has been disabled.
Resource loading issues, particularly with fonts, have been fixed. The application closes if resources have not been loaded, and leaks have been eliminated when creating fonts for such cases.

February 16, 2026
LongWord in ZenGL has been renamed to Cardinal everywhere. Since Delphi treats LongWord as LongLongWord on 64-bit systems (trying to match Unix).
Minor issues have been automatically fixed for 64-bit programs built in Delphi.

February 7, 2026
The "tex_CalcAlpha" procedure in the "zgl_textures" module has been optimized for performance, as it is used frequently (this requires testing, just in case).
Optimizations have been made to the image output-related procedures in the "zgl_render_2d.pas" module: "render_AddVertex4", "render_AddVertex6", "render_AddVertexTexture6", "render_AddColor4", "render_AddVCAColor4", "render_AddVCAColor6", and "render_AddColor6". It should work faster, but it will only be visible on weak machines (for which the optimization was made).

January 21, 2026
Corrections have been made to the "zgl_render_2d.pas" module. These corrections affect the transfer of output data arrays, which should improve performance and reduce the final code size.

12/11/2025
The "USE_SINGLE" definition has been added to the "zgl_matrix" module. This defines how data is processed for matrices: Single or Double. To use both types of matrices, you should create your own matrix module.

November 3, 2025
Corrected mouseX and mouseY return values ​​for Android. Now, mouse coordinates only work with the zero-tap mouse.

August 17, 2025
Removed constants and variables that were implemented for the keyboard: KT_DOWN, KT_UP, keyDownRepeat, keyBoolRepeat, beginKeyDelay, repeatKeyDelay, and keyDelayWork.
Removed their associated procedures: setKey_BeginRepeat and setKey_Repeat.

August 8, 2025
Fixed an issue with attempting to display a non-existent texture. When creating a zero texture "tex_CreateZero," if zero data is received, it is passed to 1 by default.

07/08/2025
ZenGUI has been adjusted. Mouse handling now works properly. However, leaks remain when using dialog boxes with effects and other minor issues.

19/07/2025
Fixed issues when attempting to load files without specifying a name and extension.

18/07/2025
Possible leaks have been fixed (probably not completely).
Fixed an error in the name of the "tex_GetTextureID" function (was "tex_GetTextireID").
The ZenGUI project has been added (most likely temporary, needed for testing), but it still has many issues.

17/07/2025
Fixed mouse handling. Now data clearing is performed correctly.
The demos also contain the latest update to the PZ Nes emulator. You can also build it for Android and test it. However, on Android, you'll need a controller to play the game. You can run several games, but I haven't implemented a game selector yet. My apologies for that.

UPD: Forgot. Now all Android projects are in one project with FPC/Lazarus. For the required platform, you need to select the build mode in the settings. They're all configured, so you just need to select the desired mode.
Demos for older Android versions have also been added. I need them for testing.

Good luck everyone!
Title: Re: ZenGL +android + MacOS Cocoa
Post by: Seenkao on March 03, 2026, 12:31:11 pm
восстановил работу демок LightEngine. Надо бы перебрать движок, но желания нет...

Все обновления до ZenGL 4.20 на прошлой странице (https://forum.lazarus.freepascal.org/index.php/topic,52581.msg577543.html#msg577543).

Google translate:
I got the LightEngine demos working again. I should probably rebuild the engine, but I'm not feeling it.
All updates to ZenGL 4.20 on the previous page (https://forum.lazarus.freepascal.org/index.php/topic,52581.msg577543.html#msg577543).
TinyPortal © 2005-2018