demo03.lpr 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. library demo03;
  2. {$I zgl_config.cfg}
  3. {$I zglCustomConfig.cfg}
  4. // RU: Включите KEYBOARD_OLD_FUNCTION в zgl_config.cfg, если хотите использовать старые функции клавиатуры.
  5. // С введением Green Engine - они стали не актуальны, но я их пока оставляю.
  6. // EN: Enable KEYBOARD_OLD_FUNCTION in zgl_config.cfg if you want to use the old keyboard functions.
  7. // With the introduction of the Green Engine - they are no longer relevant, but I leave them for now.
  8. uses
  9. zgl_application,
  10. zgl_file,
  11. zgl_screen,
  12. zgl_window,
  13. zgl_timers,
  14. zgl_touch,
  15. zgl_keyboard,
  16. zgl_primitives_2d,
  17. zgl_font,
  18. zgl_text,
  19. zgl_render_2d,
  20. zgl_textures,
  21. zgl_textures_png,
  22. zgl_types,
  23. zgl_log,
  24. zgl_utils
  25. {$IfDef KEYBOARD_OLD_FUNCTION}
  26. zgl_collision_2d
  27. {$else}
  28. , gegl_draw_gui,
  29. gegl_menu_gui,
  30. gegl_VElements,
  31. gegl_utils,
  32. gegl_color
  33. {$EndIf}
  34. ;
  35. (* проблема данной демки, не в самой демке. Обработка клавиатуры - её проблема. Постоянные вызовы "setFontTextScale" убивают всю производительность
  36. необходимо перевести все кнопки в текстуры. Текстуры нажатия и отжатия. Тогда работа клавиатуры/джойстиков станет выше.
  37. Перевод в текстуры должен происходить однажды, при запуске программы и при восстановлении программы. Так как когда программа уходит в "спящий" режим
  38. все текстуры уничтожаются (как я понимаю, контекст уничтожается и из-за этого приходится всё восстанавливать).
  39. У меня уже есть демка, где я делал меню, там есть перевод графических данных в текстуры.
  40. не сделана обработка кругового джойстика.
  41. *)
  42. var
  43. dirRes : UTF8String = 'assets/';
  44. // RU: строка для получения значения из поля ввода
  45. // EN: string to get value from input field
  46. userInput : UTF8String;
  47. {$IfDef KEYBOARD_OLD_FUNCTION}
  48. trackInput : Boolean;
  49. inputRect : zglTRect;
  50. lineAlpha : LongWord;
  51. TimeStart : LongWord;
  52. {$Else}
  53. // Rus: номера шрифтов. Вся работа со шрифтами происходит именно от этих номеров.
  54. // Eng: font numbers. All work with fonts comes from these numbers.
  55. fntMain, fntEdit: LongWord;
  56. // Rus: номер цвета. Работа с цветом происходит именно от этого номера.
  57. // Eng: color number. Work with color comes from this number.
  58. EditColor: LongWord;
  59. // RU: прямоугольник описывающий поле ввода
  60. // EN: rectangle describing the input field
  61. myRect: zglTRect2D;
  62. // "перепись" полей ввода для того, чтоб знать с каким полем работаем.
  63. // RU: объявляем переменную для работы с полем ввода
  64. // EN: we declare a variable to work with the input field
  65. myEdit, myEdit2: LongWord;
  66. // RU: прорисовываем основание поля ввода. Всё ограничено только вашим воображением. )))
  67. // EN: draw the base of the input field. Everything is limited only by your imagination. )))
  68. procedure EditCont;
  69. begin
  70. // RU: при прорисовке поля ввода, смешение и поворот уже будут сделаны. Я показываю как нарисовать рамку.
  71. // Текст будет выведен поверх того, что вы здесь нарисуете.
  72. // EN: displacement and rotation will be done prior to performing the procedure. I am showing you how to draw a frame.
  73. // The text will be drawn on top of what you draw here.
  74. pr2d_Rect(- 2, - 1, myRect.W + 5, myRect.H, cl_White, PR2D_FILL);
  75. end;
  76. {$EndIf}
  77. procedure Init;
  78. {$IfNDef KEYBOARD_OLD_FUNCTION}
  79. var
  80. EScale: LongWord;
  81. {$EndIf}
  82. begin
  83. zgl_Enable(CORRECT_RESOLUTION);
  84. scr_CorrectResolution( 800, 600 );
  85. file_OpenArchive(PAnsiChar(zgl_Get(DIRECTORY_APPLICATION)));
  86. // RU: Загружаем данные о шрифтах.
  87. // EN: Loading font data.
  88. fntMain := font_LoadFromFile( dirRes + 'font.zfi' );
  89. fontUse := font_LoadFromFile( dirRes + 'CalibriBold50pt.zfi');
  90. // note
  91. // RU: Мы дважды загружаем один и тот же фонт для того, чтоб работать с ними по раздельности. Один фонт для клавиатуры, другой фонт для поля ввода.
  92. // EN: We download the same font twice in order to work with them separately. One font for the keyboard, another font for the input field.
  93. {$IfNDef KEYBOARD_OLD_FUNCTION}
  94. // обязательный код! Данные для отображения клавиатуры.
  95. // RU: Загружаем данные о шрифте.
  96. // EN: Load the font.
  97. fntEdit := font_LoadFromFile(dirRes + 'CalibriBold50pt.zfi');
  98. JoyArrow := tex_LoadFromFile(dirRes + 'arrow.png'); // загрузили текстуру
  99. tex_SetFrameSize(JoyArrow, 64, 64); // и разбили её на части, но в записях не будет указано количество полученных текстур
  100. // RU: Данные для виртуальной клавиатуры.
  101. // EN: Data for the virtual keyboard.
  102. txt_LoadFromFile(dirRes + 'Rus.txt', LoadText);
  103. // RU: Создаём виртуальную клавиатуру. Для мобильных систем это будет обязательным кодом в дальнейшем.
  104. // EN: We create a virtual keyboard. For mobile systems, this will be a mandatory code in the future.
  105. CreateTouchKeyboard;
  106. {$EndIf}
  107. file_CloseArchive();
  108. {$IfNDef KEYBOARD_OLD_FUNCTION}
  109. // RU: устанавливаем размеры шрифтов
  110. // EN: set font sizes
  111. setFontTextScale(15, fntMain);
  112. setFontTextScale(20, fntEdit);
  113. // RU: размер шрифта поля ввода (для понимания что происходит). Изменяя размер шрифта, мы должны менять и
  114. // размеры поля ввода - myRect в данном случае. Сами они не изменятся.
  115. // EN: the font size of the input field (to understand what's going on). By changing the font size,
  116. // we must also change the size of the input field - myRect in this case. They themselves will not change.
  117. EScale := 20;
  118. setFontTextScale(EScale, fntEdit);
  119. // RU: указываем размеры поля ввода
  120. // EN: specify the size of the input field
  121. myRect.X := 200;
  122. myRect.Y := 150;
  123. myRect.W := 200;
  124. myRect.H := 33;
  125. // RU: указываем точку вращения, в данном случае центр поля ввода (по необходимости) и угол поворота (например 45)
  126. // EN: specify the point of rotation, in this case the center of the input field (if necessary) and the angle of rotation (for example 45)
  127. SetOfRotateAngleAndPoint(myRect.x + myRect.W / 2, myRect.y + myRect.H / 2, 30);
  128. // RU: указываем цвет текста (добавляем новый номер цвета, хотя данная функция вам возвратит цвет, если он уже был прописан).
  129. // EN: specify the color of the text (we add a new color number, although this function will return the color to you if it
  130. // has already been assigned).
  131. EditColor := Color_FindOrAdd($208055FF);
  132. // Ru: устанавливаем цвета по умолчанию для всех элементов API. Эти цвета будут задействованы только при создании
  133. // определённого элемента. Для изменения цвета в самом (уже созданном) элементе, ни чего не прилагается.
  134. // Дальнейшие измениня этих значений цвета, ни как не скажется на уже созданных элементах.
  135. // En: set default colors for all API elements. These colors will only be used when creating a specific element.
  136. // To change the color in the (already created) element itself, nothing is attached. Further changes to these
  137. // color values will not affect the already created elements in any way.
  138. SetDefColor(EditColor, cl_Green, cl_Black);
  139. // RU: создаём само поле ввода с данными указанными выше и передаваемыми данными
  140. // EN: create the input field itself with the data specified above and the data that needs to be transferred
  141. myEdit := CreateEdit(myRect, fntEdit, EScale, @EditCont);
  142. // RU: корректируем курсор
  143. // EN: adjust the cursor
  144. CorrectEditCursor(myEdit, 2);
  145. // RU: задаём очистку экрана заданным цветом
  146. // EN: set the screen to clear with a specified color
  147. scr_SetClearColor(true, $7090af);
  148. {$Else}
  149. inputRect.X := 400 - 192;
  150. inputRect.Y := 300 - 100 - 32;
  151. inputRect.W := 384;
  152. inputRect.H := 96;
  153. setFontTextScale(15, fntMain);
  154. {$EndIf}
  155. log_Add('Initialization - end');
  156. end;
  157. procedure Draw;
  158. var
  159. w : Single;
  160. begin
  161. batch2d_Begin;
  162. setTextColor(Get_Color(cl_Blue));
  163. // RU: Координаты "пальцев" можно получить при помощи функций touch_X и touch_Y.
  164. // EN: "Finger" coordinates can be got using functions touch_X and touch_Y.
  165. text_Draw(fntMain, 0, 0, 'One X, Y: ' + u_IntToStr(touch_X(0)) + '; ' + u_IntToStr(touch_Y(0)));
  166. text_Draw(fntMain, 0, 16, 'Two X, Y: ' + u_IntToStr(touch_X(1)) + '; ' + u_IntToStr(touch_Y(1)));
  167. // расширю до 10 одновременных нажатий, некоторые телефоны это поддерживают
  168. text_Draw(fntMain, 0, 32, 'Three X, Y: ' + u_IntToStr(touch_X(2)) + '; ' + u_IntToStr(touch_Y(2)));
  169. text_Draw(fntMain, 0, 48, 'Four X, Y: ' + u_IntToStr(touch_X(3)) + '; ' + u_IntToStr(touch_Y(3)));
  170. text_Draw(fntMain, 0, 64, 'Five X, Y: ' + u_IntToStr(touch_X(4)) + '; ' + u_IntToStr(touch_Y(4)));
  171. text_Draw(fntMain, 0, 80, 'Six X, Y: ' + u_IntToStr(touch_X(5)) + '; ' + u_IntToStr(touch_Y(5)));
  172. text_Draw(fntMain, 0, 96, 'Seven X, Y: ' + u_IntToStr(touch_X(6)) + '; ' + u_IntToStr(touch_Y(6)));
  173. text_Draw(fntMain, 0, 112, 'Eigth X, Y: ' + u_IntToStr(touch_X(7)) + '; ' + u_IntToStr(touch_Y(7)));
  174. text_Draw(fntMain, 0, 128, 'Nine X, Y: ' + u_IntToStr(touch_X(8)) + '; ' + u_IntToStr(touch_Y(8)));
  175. text_Draw(fntMain, 0, 144, 'Ten X, Y: ' + u_IntToStr(touch_X(9)) + '; ' + u_IntToStr(touch_Y(9)));
  176. {$IfDef KEYBOARD_OLD_FUNCTION}
  177. // RU: Выводим введённый пользователем текст.
  178. // EN: Show the inputted text.
  179. pr2d_Rect( inputRect.X, inputRect.Y, inputRect.W, inputRect.H, $FFFFFF, 255 );
  180. if trackInput Then
  181. begin
  182. text_Draw( fntMain, 400, 300 - 100, 'Press Enter to stop track text input:', TEXT_HALIGN_CENTER );
  183. w := text_GetWidth( fntMain, userInput );
  184. pr2d_Rect( 400 + w / 2 + 2, 300 - 70, 10, 20, $FFFFFF, lineAlpha, PR2D_FILL );
  185. end else
  186. text_Draw( fntMain, 400, 300 - 100, 'Click here to enter text(maximum - 24 symbols):', TEXT_HALIGN_CENTER );
  187. text_Draw( fntMain, 400, 300 - 70, userInput, TEXT_HALIGN_CENTER );
  188. {$Else}
  189. text_Draw(fntMain, 0, 36, 'Press F5 to copy from Edit and draw'); // какой я нафиг англичанин? ))))
  190. text_Draw(fntMain, 0, 54, 'Press F12 - Rus/Eng');
  191. if userInput <> '' then
  192. text_Draw(fntMain, 400, 300 - 70, userInput, TEXT_HALIGN_CENTER);
  193. {$EndIf}
  194. batch2d_End;
  195. end;
  196. {$IfDef KEYBOARD_OLD_FUNCTION}
  197. procedure Timer;
  198. begin
  199. if lineAlpha > 5 Then
  200. DEC( lineAlpha, 10 )
  201. else
  202. lineAlpha := 255;
  203. end;
  204. {$EndIf}
  205. procedure KeyMouseEvent;
  206. begin
  207. {$IfDef KEYBOARD_OLD_FUNCTION}
  208. // RU: Проверить тапнул ли пользователь в пределах inputRect и начать отслеживать ввод текста.
  209. // EN: Check if there was tap inside inputRect and start to track text input.
  210. if touch_Tap( 0 ) and col2d_PointInRect( touch_X( 0 ), touch_Y( 0 ), inputRect ) Then
  211. begin
  212. trackInput := TRUE;
  213. key_BeginReadText( userInput, 24 );
  214. end;
  215. // RU: Если была нажата кнопка Done прекращаем отслеживать ввод текста.
  216. // EN: Finish to track text input if Done was pressed.
  217. if key_Press( K_ENTER ) Then
  218. begin
  219. trackInput := FALSE;
  220. key_EndReadText();
  221. end;
  222. // RU: Получаем введённый пользователем текст.
  223. // EN: Get inputted by user text.
  224. if trackInput Then
  225. userInput := key_GetText();
  226. {$Else}
  227. // RU: по нажатию F5 копируем то, что написано в поле ввода
  228. // EN: by pressing F5, copy what is written in the input field
  229. if keysDown[K_F5] then
  230. begin
  231. userInput := GetEditToText(myEdit);
  232. end;
  233. {$EndIf}
  234. end;
  235. procedure Restore;
  236. begin
  237. file_OpenArchive( PAnsiChar( zgl_Get( DIRECTORY_APPLICATION ) ) );
  238. font_RestoreFromFile( fntMain, dirRes + 'font.zfi' );
  239. {$IfNDef KEYBOARD_OLD_FUNCTION}
  240. font_RestoreFromFile( fntMain, dirRes + 'CalibriBold50pt.zfi' );
  241. tex_RestoreFromFile( JoyArrow, dirRes + 'arrow.png' );
  242. {$EndIf}
  243. file_CloseArchive();
  244. end;
  245. procedure Java_zengl_android_ZenGL_Main( var env; var thiz ); cdecl;
  246. begin
  247. {$IfDef KEYBOARD_OLD_FUNCTION}
  248. TimerStart := timer_Add( @Timer, 16, Start );
  249. {$EndIf}
  250. zgl_Reg(SYS_EVENTS, @KeyMouseEvent);
  251. zgl_Reg( SYS_LOAD, @Init );
  252. zgl_Reg( SYS_DRAW, @Draw );
  253. zgl_Reg( SYS_ANDROID_RESTORE, @Restore );
  254. scr_SetOptions();
  255. end;
  256. exports
  257. Java_zengl_android_ZenGL_Main,
  258. {$I android_export.inc}
  259. End.