Programowanie w systemie UNIX/c grafika/OpenGL

Z Wikibooks, biblioteki wolnych podręczników.

Definicja[edytuj]

OpenGl API is used to interact with GPU [1]

Ścisła[edytuj]

OpenGL w ścisłym znaczeniu oznacza:

  • standard sposobu dostępu do karty graficznej w celu:
    • tworzenia grafiki (2D i 3D) - główny cel [2]
    • GPGPU - używając renderowania poza ekranem (ang. offscreen rendering): nie wysyła danych do bufora ramki[3] (ang. the frame buffer) ale do innej części pamięci karty graficznej (ang. the offscreen buffer)[4]
  • nie jest biblioteką lecz specyfikacją (API). Nie jest związane ze sprzętem i dzięki temu jest wieloplatformowe, uniwersalne i abstrakcyjne. Nie posiada kodu źródłowego
  • działa w architekturze klient-serwer
  • Nie ma okien, menu, procedur obsługi wejścia, czy inneych rodzajów interakcji
  • działa w czasie rzeczywistym dzięki przyspieszenie sprzętowe (ang. hardware acceleration) renderowania grafiki realizoanemu poprzez:
    • programowaniu równoległemu (procesor i program)
    • bezpośredniemu dostępowi do karty graficznej (z pominięciem systemu operacyjnego)[5]

Praktyczna[edytuj]

W potocznym i praktycznym znaczeniu OpenGL obejmuje następujące całe środowisko/platformę/kontekst:[6]

  • sprzęt ( hardware): karta graficzna z procesorem GPU[7]
  • oprogramowanie ( software):
    • system operacyjny
    • sterownik karty graficznej
    • biblioteki pomocnicze
    • program

Typy kodu OpenGL[edytuj]

grafika w linuksie

Typy kodu OpenGL, podział wg:

  • OS (lokalizacja bibliotek)
  • język programowania: C, C++, C#, Ada, Java, JavaScript, Python, Ruby, PHP, Lua, R, Perl, OCaml, Common Lisp, Clojure, Fortran, D i wiele innych
  • środowiska (konsola / IDE)
  • platforma (OpenGL / OpenGL ES)
  • wersja OpenGL ( Core-profile vs Tryb natychmiastowy (Immediate mode)[8] :
    • legacy = 1 lub 2 . Może używać GLUT
    • modern = czyli 3 lub 4 (GLSL). Nie można korzystać z GLUT, ale zastęþuje go i rozszerza GLFW. Do rysowania i wyświetlania grafiki trzeba używać shaderów [9]
  • biblioteki podstawowe i ich wersje (Gl, Glu , GLew, ...)
  • GUI lub konsola
  • sprzętu (karta graficzna / GPU)
  • sterownika karty graficznej (program i jego wersja) i moduł jądra (ang. kernel module)


Ponieważ prawie dowolnie można łączyć powyższe cechy (9) liczba możliwych kombinacji jest bardzo duża, dlatego prawie każdy poradnik, program musimy zmodyfikować do naszych warunków.

Dostęp do GPU:

  • z poziomu X-window: DRI -> GPU (np. Mesa 3D)
  • z poziomu konsoli bez X-window: DRI -> GPU (np. DirectFB[10])


Zależność między Opengl i GlSL : [11]

OpenGL Version GLSL Version #version tag
1.2 none none
2.0 1.10.59 110
2.1 1.20.8 120
3.0 1.30.10 130
3.1 1.40.08 140
3.2 1.50.11 150
3.3 3.30.6 330
4.0 4.00.9 400
4.1 4.10.6 410
4.2 4.20.6 420
4.3 4.30.6 430

Potok[edytuj]

Schemat blokowy protokołu programowalnego OpenGL 3.3
Kolejność przekształceń punktów w Open GL3.3

Test[edytuj]

Konsolowe[edytuj]

Sprawdzamy instalację za pomocą konsolowego programu glxinfo (Mesa) [12][13]

glxinfo

lub

glxinfo | more

lub

glxinfo > gl.txt   

otrzymujemy:


name of display: :0
display: :0  screen: 0
direct rendering: Yes
server glx vendor string: NVIDIA Corporation
server glx version string: 1.4
server glx extensions:
    GLX_ARB_create_context, GLX_ARB_create_context_profile, 
    GLX_ARB_create_context_robustness, GLX_ARB_fbconfig_float, 
    GLX_ARB_multisample, GLX_EXT_buffer_age, 
    GLX_EXT_create_context_es2_profile, GLX_EXT_create_context_es_profile, 
    GLX_EXT_framebuffer_sRGB, GLX_EXT_swap_control, GLX_EXT_swap_control_tear, 
    GLX_EXT_texture_from_pixmap, GLX_EXT_visual_info, GLX_EXT_visual_rating, 
    GLX_NV_float_buffer, GLX_NV_multisample_coverage, GLX_SGIX_fbconfig, 
    GLX_SGIX_pbuffer, GLX_SGI_swap_control, GLX_SGI_video_sync
client glx vendor string: NVIDIA Corporation
client glx version string: 1.4
client glx extensions:
...


 glxinfo | grep "OpenGL version"

przykładowy wynik:

OpenGL version string: 3.0 Mesa 10.3.2

lub:

sudo /usr/lib/nux/unity_support_test -p -f

Przykładowy wynik:

OpenGL vendor string:   NVIDIA Corporation
OpenGL renderer string: GeForce GTX 770/PCIe/SSE2
OpenGL version string:  4.3.0 NVIDIA 319.32

Not software rendered:    yes
Not blacklisted:          yes
GLX fbconfig:             yes
GLX texture from pixmap:  yes
GL npot or rect textures: yes
GL vertex program:        yes
GL fragment program:      yes
GL vertex buffer object:  yes
GL framebuffer object:    yes
GL version is 1.4+:       yes

Unity 3D supported:       yes


glxinfo | grep 'shading language version string'

Przykładowy wynik:

OpenGL core profile shading language version string: 4.60 NVIDIA
OpenGL shading language version string: 4.60 NVIDIA
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.20

Program glxgears[14] to mały i prosty program demonstracyjny MESA OpenGL dostarczany z dystrybucją GNU. Technicznie rzecz biorąc, jest to część mesa-demos, ale jest dostarczany z pakietem glx-utils i dlatego jest instalowany domyślnie (w przeciwieństwie do innych programów mesa-demo, takich jak glxheads, Shape, Offset itp.).

glxgears -info
Running synchronized to the vertical refresh.  The framerate should be
approximately the same as the monitor refresh rate.
GL_RENDERER   = NVIDIA GeForce GTX 770/PCIe/SSE2
GL_VERSION    = 4.6.0 NVIDIA 470.199.02
GL_VENDOR     = NVIDIA Corporation
GL_EXTENSIONS = GL_AMD_multi_draw_indirect GL_AMD_seamless_cubemap_per_texture GL_ARB_arrays_of_arrays GL_ARB_base_instance GL_ARB_bindless_texture GL_ARB_blend_func_extended GL_ARB_buffer_storage GL_ARB_clear_buffer_object GL_ARB_clear_texture GL_ARB_clip_control GL_ARB_color_buffer_float GL_ARB_compatibility GL_ARB_compressed_texture_pixel_storage GL_ARB_conservative_depth GL_ARB_compute_shader GL_ARB_compute_variable_group_size GL_ARB_conditional_render_inverted GL_ARB_copy_buffer GL_ARB_copy_image GL_ARB_cull_distance GL_ARB_debug_output GL_ARB_depth_buffer_float GL_ARB_depth_clamp GL_ARB_depth_texture GL_ARB_derivative_control GL_ARB_direct_state_access GL_ARB_draw_buffers GL_ARB_draw_buffers_blend GL_ARB_draw_indirect GL_ARB_draw_elements_base_vertex GL_ARB_draw_instanced GL_ARB_enhanced_layouts GL_ARB_ES2_compatibility GL_ARB_ES3_compatibility GL_ARB_ES3_1_compatibility GL_ARB_ES3_2_compatibility GL_ARB_explicit_attrib_location GL_ARB_explicit_uniform_location GL_ARB_fragment_coord_conventions GL_ARB_fragment_layer_viewport GL_ARB_fragment_program GL_ARB_fragment_program_shadow GL_ARB_fragment_shader GL_ARB_framebuffer_no_attachments GL_ARB_framebuffer_object GL_ARB_framebuffer_sRGB GL_ARB_geometry_shader4 GL_ARB_get_program_binary GL_ARB_get_texture_sub_image GL_ARB_gl_spirv GL_ARB_gpu_shader5 GL_ARB_gpu_shader_fp64 GL_ARB_gpu_shader_int64 GL_ARB_half_float_pixel GL_ARB_half_float_vertex GL_ARB_imaging GL_ARB_indirect_parameters GL_ARB_instanced_arrays GL_ARB_internalformat_query GL_ARB_internalformat_query2 GL_ARB_invalidate_subdata GL_ARB_map_buffer_alignment GL_ARB_map_buffer_range GL_ARB_multi_bind GL_ARB_multi_draw_indirect GL_ARB_multisample GL_ARB_multitexture GL_ARB_occlusion_query GL_ARB_occlusion_query2 GL_ARB_parallel_shader_compile GL_ARB_pipeline_statistics_query GL_ARB_pixel_buffer_object GL_ARB_point_parameters GL_ARB_point_sprite GL_ARB_polygon_offset_clamp GL_ARB_program_interface_query GL_ARB_provoking_vertex GL_ARB_query_buffer_object GL_ARB_robust_buffer_access_behavior GL_ARB_robustness GL_ARB_sample_shading GL_ARB_sampler_objects GL_ARB_seamless_cube_map GL_ARB_seamless_cubemap_per_texture GL_ARB_separate_shader_objects GL_ARB_shader_atomic_counter_ops GL_ARB_shader_atomic_counters GL_ARB_shader_ballot GL_ARB_shader_bit_encoding GL_ARB_shader_clock GL_ARB_shader_draw_parameters GL_ARB_shader_group_vote GL_ARB_shader_image_load_store GL_ARB_shader_image_size GL_ARB_shader_objects GL_ARB_shader_precision GL_ARB_shader_storage_buffer_object GL_ARB_shader_subroutine GL_ARB_shader_texture_image_samples GL_ARB_shader_texture_lod GL_ARB_shading_language_100 GL_ARB_shading_language_420pack GL_ARB_shading_language_include GL_ARB_shading_language_packing GL_ARB_shadow GL_ARB_sparse_buffer GL_ARB_sparse_texture GL_ARB_spirv_extensions GL_ARB_stencil_texturing GL_ARB_sync GL_ARB_tessellation_shader GL_ARB_texture_barrier GL_ARB_texture_border_clamp GL_ARB_texture_buffer_object GL_ARB_texture_buffer_object_rgb32 GL_ARB_texture_buffer_range GL_ARB_texture_compression GL_ARB_texture_compression_bptc GL_ARB_texture_compression_rgtc GL_ARB_texture_cube_map GL_ARB_texture_cube_map_array GL_ARB_texture_env_add GL_ARB_texture_env_combine GL_ARB_texture_env_crossbar GL_ARB_texture_env_dot3 GL_ARB_texture_filter_anisotropic GL_ARB_texture_float GL_ARB_texture_gather GL_ARB_texture_mirror_clamp_to_edge GL_ARB_texture_mirrored_repeat GL_ARB_texture_multisample GL_ARB_texture_non_power_of_two GL_ARB_texture_query_levels GL_ARB_texture_query_lod GL_ARB_texture_rectangle GL_ARB_texture_rg GL_ARB_texture_rgb10_a2ui GL_ARB_texture_stencil8 GL_ARB_texture_storage GL_ARB_texture_storage_multisample GL_ARB_texture_swizzle GL_ARB_texture_view GL_ARB_timer_query GL_ARB_transform_feedback2 GL_ARB_transform_feedback3 GL_ARB_transform_feedback_instanced GL_ARB_transform_feedback_overflow_query GL_ARB_transpose_matrix GL_ARB_uniform_buffer_object GL_ARB_vertex_array_bgra GL_ARB_vertex_array_object GL_ARB_vertex_attrib_64bit GL_ARB_vertex_attrib_binding GL_ARB_vertex_buffer_object GL_ARB_vertex_program GL_ARB_vertex_shader GL_ARB_vertex_type_10f_11f_11f_rev GL_ARB_vertex_type_2_10_10_10_rev GL_ARB_viewport_array GL_ARB_window_pos GL_ATI_draw_buffers GL_ATI_texture_float GL_ATI_texture_mirror_once GL_S3_s3tc GL_EXT_texture_env_add GL_EXT_abgr GL_EXT_bgra GL_EXT_bindable_uniform GL_EXT_blend_color GL_EXT_blend_equation_separate GL_EXT_blend_func_separate GL_EXT_blend_minmax GL_EXT_blend_subtract GL_EXT_compiled_vertex_array GL_EXT_Cg_shader GL_EXT_depth_bounds_test GL_EXT_direct_state_access GL_EXT_draw_buffers2 GL_EXT_draw_instanced GL_EXT_draw_range_elements GL_EXT_fog_coord GL_EXT_framebuffer_blit GL_EXT_framebuffer_multisample GL_EXTX_framebuffer_mixed_formats GL_EXT_framebuffer_multisample_blit_scaled GL_EXT_framebuffer_object GL_EXT_framebuffer_sRGB GL_EXT_geometry_shader4 GL_EXT_gpu_program_parameters GL_EXT_gpu_shader4 GL_EXT_multi_draw_arrays GL_EXT_multiview_texture_multisample GL_EXT_multiview_timer_query GL_EXT_packed_depth_stencil GL_EXT_packed_float GL_EXT_packed_pixels GL_EXT_pixel_buffer_object GL_EXT_point_parameters GL_EXT_polygon_offset_clamp GL_EXT_provoking_vertex GL_EXT_rescale_normal GL_EXT_secondary_color GL_EXT_separate_shader_objects GL_EXT_separate_specular_color GL_EXT_shader_image_load_store GL_EXT_shader_integer_mix GL_EXT_shadow_funcs GL_EXT_stencil_two_side GL_EXT_stencil_wrap GL_EXT_texture3D GL_EXT_texture_array GL_EXT_texture_buffer_object GL_EXT_texture_compression_dxt1 GL_EXT_texture_compression_latc GL_EXT_texture_compression_rgtc GL_EXT_texture_compression_s3tc GL_EXT_texture_cube_map GL_EXT_texture_edge_clamp GL_EXT_texture_env_combine GL_EXT_texture_env_dot3 GL_EXT_texture_filter_anisotropic GL_EXT_texture_integer GL_EXT_texture_lod GL_EXT_texture_lod_bias GL_EXT_texture_mirror_clamp GL_EXT_texture_object GL_EXT_texture_shadow_lod GL_EXT_texture_shared_exponent GL_EXT_texture_sRGB GL_EXT_texture_sRGB_R8 GL_EXT_texture_sRGB_decode GL_EXT_texture_storage GL_EXT_texture_swizzle GL_EXT_timer_query GL_EXT_transform_feedback2 GL_EXT_vertex_array GL_EXT_vertex_array_bgra GL_EXT_vertex_attrib_64bit GL_EXT_window_rectangles GL_EXT_x11_sync_object GL_EXT_import_sync_object GL_NV_robustness_video_memory_purge GL_IBM_rasterpos_clip GL_IBM_texture_mirrored_repeat GL_KHR_context_flush_control GL_KHR_debug GL_EXT_memory_object GL_EXT_memory_object_fd GL_KHR_parallel_shader_compile GL_KHR_no_error GL_KHR_robust_buffer_access_behavior GL_KHR_robustness GL_EXT_semaphore GL_EXT_semaphore_fd GL_NV_timeline_semaphore GL_KHR_shader_subgroup GL_KTX_buffer_region GL_NV_alpha_to_coverage_dither_control GL_NV_bindless_multi_draw_indirect GL_NV_bindless_multi_draw_indirect_count GL_NV_bindless_texture GL_NV_blend_equation_advanced GL_NV_blend_square GL_NV_command_list GL_NV_compute_program5 GL_NV_conditional_render GL_NV_copy_depth_to_color GL_NV_copy_image GL_NV_depth_buffer_float GL_NV_depth_clamp GL_NV_draw_texture GL_NV_draw_vulkan_image GL_NV_ES1_1_compatibility GL_NV_ES3_1_compatibility GL_NV_explicit_multisample GL_NV_feature_query GL_NV_fence GL_NV_float_buffer GL_NV_fog_distance GL_NV_fragment_program GL_NV_fragment_program_option GL_NV_fragment_program2 GL_NV_framebuffer_multisample_coverage GL_NV_geometry_shader4 GL_NV_gpu_program4 GL_NV_internalformat_sample_query GL_NV_gpu_program4_1 GL_NV_gpu_program5 GL_NV_gpu_program5_mem_extended GL_NV_gpu_program_fp64 GL_NV_gpu_shader5 GL_NV_half_float GL_NV_light_max_exponent GL_NV_multisample_coverage GL_NV_multisample_filter_hint GL_NV_occlusion_query GL_NV_packed_depth_stencil GL_NV_parameter_buffer_object GL_NV_parameter_buffer_object2 GL_NV_path_rendering GL_NV_pixel_data_range GL_NV_point_sprite GL_NV_primitive_restart GL_NV_query_resource GL_NV_query_resource_tag GL_NV_register_combiners GL_NV_register_combiners2 GL_NV_shader_atomic_counters GL_NV_shader_atomic_float GL_NV_shader_buffer_load GL_NV_shader_storage_buffer_object GL_NV_shader_subgroup_partitioned GL_NV_texgen_reflection GL_NV_texture_barrier GL_NV_texture_compression_vtc GL_NV_texture_env_combine4 GL_NV_texture_multisample GL_NV_texture_rectangle GL_NV_texture_rectangle_compressed GL_NV_texture_shader GL_NV_texture_shader2 GL_NV_texture_shader3 GL_NV_transform_feedback GL_NV_transform_feedback2 GL_NV_uniform_buffer_unified_memory GL_NV_vdpau_interop GL_NV_vdpau_interop2 GL_NV_vertex_array_range GL_NV_vertex_array_range2 GL_NV_vertex_attrib_integer_64bit GL_NV_vertex_buffer_unified_memory GL_NV_vertex_program GL_NV_vertex_program1_1 GL_NV_vertex_program2 GL_NV_vertex_program2_option GL_NV_vertex_program3 GL_NVX_conditional_render GL_NV_gpu_multicast GL_NVX_progress_fence GL_NVX_gpu_memory_info GL_NVX_nvenc_interop GL_NV_shader_thread_group GL_NV_shader_thread_shuffle GL_KHR_blend_equation_advanced GL_OVR_multiview GL_OVR_multiview2 GL_SGIS_generate_mipmap GL_SGIS_texture_lod GL_SGIX_depth_texture GL_SGIX_shadow GL_SUN_slice_accum 
VisualID 39, 0x27
X connection to :1 broken (explicit kill or server shutdown).


Karta graficzna[edytuj]

Sprawdzamy kartę i jej sterownik używając lspci:

lspci | grep VGA


przykładowy wynik:

01:00.0 VGA compatible controller: NVIDIA Corporation GK104 [GeForce GTX 770] (rev a1)

lub nvidia-smi:

nvidia-smi[15]
Sat Jan 18 09:18:20 2014       
+------------------------------------------------------+                       
| NVIDIA-SMI 5.319.60   Driver Version: 319.60         |                       
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 770     Off  | 0000:01:00.0     N/A |                  N/A |
| 17%   29C  N/A     N/A /  N/A |      222MB /  2047MB |     N/A      Default |
+-------------------------------+----------------------+----------------------+
                                                                               
+-----------------------------------------------------------------------------+
| Compute processes:                                               GPU Memory |
|  GPU       PID  Process name                                     Usage      |
|=============================================================================|
|    0            Not Supported                                               |
+-----------------------------------------------------------------------------+


sudo lshw -c video


 *-display                 
      description: VGA compatible controller
      product: GK104 [GeForce GTX 770]
      vendor: NVIDIA Corporation
      physical id: 0
      bus info: pci@0000:01:00.0
      version: a1
      width: 64 bits
      clock: 33MHz
      capabilities: pm msi pciexpress vga_controller bus_master cap_list rom
      configuration: driver=nvidia latency=0
      resources: irq:31 memory:f6000000-f6ffffff memory:e8000000-efffffff memory:f0000000-f1ffffff ioport:e000(size=128) memory:c0000-dffff
 *-graphics
      product: EFI VGA
      physical id: 2
      logical name: /dev/fb0
      capabilities: fb
      configuration: depth=32 resolution=1024,768

lub

lspci -nn | grep -E 'VGA|Display'


Za pomocą cat otrzymujemy informacje o aktualnie załadowanym module jądra (ang. the version of the currently loaded NVIDIA kernel module):

 cat /proc/driver/nvidia/version

otrzymujemy:

NVRM version: NVIDIA UNIX x86_64 Kernel Module  319.60  Wed Sep 25 14:28:26 PDT 2013
GCC version:  gcc version 4.8.1 (Ubuntu/Linaro 4.8.1-10ubuntu9)


Za pomocą dkms:

 dkms status

otrzymujemy:

 nvidia-304-updates, 304.108, 3.11.0-15-generic, x86_64: installed


Program: nvidia-detect[16][17]


Szukamy zalecernego sterownika:

ubuntu-drivers devices

Przykładowy wynik:

== /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0 ==
modalias : pci:v000010DEd00001184sv00001458sd00003603bc03sc00i00
vendor   : NVIDIA Corporation
model    : GK104 [GeForce GTX 770]
driver   : nvidia-driver-470 - distro non-free recommended
driver   : nvidia-driver-390 - distro non-free
driver   : nvidia-driver-450-server - distro non-free
driver   : nvidia-driver-470-server - distro non-free
driver   : nvidia-driver-418-server - distro non-free
driver   : xserver-xorg-video-nouveau - distro free builtin

lista dostępnych sterowników dla twojego GPU:

apt search nvidia-driver


Automatyczna instlacja zaleconego sterownika[18]

sudo ubuntu-drivers autoinstall


apt list --installed | grep -e nvidia-driver-[0-9][0-9][0-9] -e nvidia-[0-9][0-9][0-9]

Przyspieszanie sprzętowe[edytuj]

Sprawdzamy czy mamy przyśpieszanie sprzętowe: [19]

glxinfo | grep renderer

otrzymujemy:

OpenGL renderer string: GeForce GTX 770/PCIe/SSE2

to znaczy, że mamy przyspieszanie sprzętowe. Jeśli otrzymamy:

Mesa GLX Indirect

to powinniśmy zainstalować odpowiednie do posiadanej karty graficznej sterowniki.


Inny :

 glxgear

Graficzne[edytuj]

  • /usr/bin/nvidia-setting
  • hardinfo
  • strona Nvidia: Smart Scan [20]
  • Gpu Test [21]
  • LuxRender [22]
  • w przeglądarce chrome wpisz: chrome://gpu[23]

Błędy[edytuj]

undefined reference to[edytuj]

Spróbujmy skompilować przeglądarkę dla programistów w Ubuntu używając komendy:

gcc v.c -lm -lGLU -lglut -Wall

Otrzymamy:

v.c: In function ‘readPPM’:
v.c:67:13: warning: variable ‘j’ set but not used [-Wunused-but-set-variable]
         int j ;
             ^
/usr/bin/ld: /tmp/cc2PsYvI.o: undefined reference to symbol 'glDrawPixels'
/usr/lib/nvidia-319/libGL.so.1: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

Błąd. Kompilator nie widzi definicji procedury glDrawPixels. W Ubuntu problem rozwiązuje dodanie biblioteki GL:

gcc v.c -lm -lGL -lGLU -lglut -Wall
v.c: In function ‘readPPM’:
v.c:67:13: warning: variable ‘j’ set but not used [-Wunused-but-set-variable]
        int j ;
            ^


Czasem kolejność też ma znaczenie[24]

Różne wersje sterownika karty graficznej i modułu jądra[edytuj]

Elementy OpenGL[edytuj]

Low-level -> High-level
Graphic card OpenGL  WGL (for Windows) EGL GLEW  GLUT  SFML Graphics, ClanLib... (2D)
OpenGL ES GLX (for X11) EAGL (iOS) Glee GLFW  Irrlicht, OGRE, Unity, (3D)
WebGL CGL/AGL (for OS X)  SDL, SFML OpenSG, OpenScenegraph...

Sterownik[edytuj]

Sprawdzamy sterownik ( ang. driver)/ moduł jądra ( ang. kernel module)[25]:

 lspci -k

przykładowy wynik ( fragment):

...
01:00.0 VGA compatible controller: NVIDIA Corporation GK104 [GeForce GTX 770] (rev a1)
	Subsystem: Gigabyte Technology Co., Ltd GK104 [GeForce GTX 770]
	Kernel driver in use: nvidia
	Kernel modules: nvidiafb, nouveau, nvidia_375_drm, nvidia_375
...

Wyjaśnienie:

  • the "kernel driver" line : refers to which driver is currently bound to the card ( = in use)
  • The "kernel modules" line : lists all of the drivers known to be capable of binding to this card

wersje[edytuj]

Wersje:[26][27]

  • własnościowe sterowniki (ang.: the proprietary drivers, GPU vendor's driver, binary driver, closed source unified NVIDIA drivers)[28]
  • otwarte sterowniki (ang.: the open source drivers)
    • Nouveau: Accelerated Open Source driver for nVidia cards. [30]
    • MESA (sterowniki zawarte w bibliotece programistycznej)
    • Intel
    • ATI/AMD (radeon, radeonhd)


Sterowniki własnościowe Nvidii powoduję konflikt ze sterownikami Nouvoux. [31]

Etapy instalacji[edytuj]

Ze żródeł

  • dodanie kodu do drzewa (ang. add)
  • kompilacja (build)
  • instalacja (ang. install)
  • ładowanie modułu do jądra

Etapy[32]

  • CTRL + F1
  • Login and stop lightdm: sudo service lightdm stop
  • Run the commands for terminal that I wrote on top and it should work fine.

Etapy instalacji sterowników:[33]

sudo telinit 3 # zmień na poziom pracy 3 za pomocą telinit
# CTRL+ALT+F1 
# zaloguj się za pomocą swojej nazwy użytkownika i hasła, aby otworzyć nową sesję TTY1 lub zaloguj się przez SSH
sudo bash NVIDIA-Linux-x86_64-470.94.run
sudo reboot

czasem

/etc/init.d/gdm stop

Elementy[edytuj]

kod źródłowy[edytuj]

  • jądra: /lib/module/kernel - version/build directory
  • modułu: /usr/src/module - module-version

Moduł jądra[edytuj]

Dynamic Kernel Module Support (DKMS)[34]


Moduł jądra:

/lib/modules/wersja_jadra/kernel/drivers/video/nvidia.ko

Sprawdźmy czy mamy załadowany moduł nvidia za pomocą lsmod:

lsmod | grep nvidia

przykładowy wynik:

nvidia               9430379  50 
drm                   297056  2 nvidia

Mamy więc próbujemy otrzymać więcej informacji o nim za pomocą modinfo:[35]

 modinfo nvidia

wynik:

ERROR: Module nvidia not found.

Przyczyną tego jest alias[36]. Znajdujemy właściwą nazwę:

 modprobe --resolve-alias nvidia

wynik:

nvidia_319

i:

modinfo nvidia_319

Wynik:

filename:       /lib/modules/3.11.0-19-generic/updates/dkms/nvidia_319.ko
alias:          char-major-195-*
version:        319.32
supported:      external
license:        NVIDIA
alias:          pci:v000010DEd00000E00sv*sd*bc04sc80i00*
alias:          pci:v000010DEd00000AA3sv*sd*bc0Bsc40i00*
alias:          pci:v000010DEd*sv*sd*bc03sc02i00*
alias:          pci:v000010DEd*sv*sd*bc03sc00i00*
depends:        drm
vermagic:       3.11.0-19-generic SMP mod_unload modversions 
parm:           NVreg_Mobile:int
parm:           NVreg_ResmanDebugLevel:int
parm:           NVreg_RmLogonRC:int
parm:           NVreg_ModifyDeviceFiles:int
parm:           NVreg_DeviceFileUID:int
parm:           NVreg_DeviceFileGID:int
parm:           NVreg_DeviceFileMode:int
parm:           NVreg_RemapLimit:int
parm:           NVreg_UpdateMemoryTypes:int
parm:           NVreg_InitializeSystemMemoryAllocations:int
parm:           NVreg_RMEdgeIntrCheck:int
parm:           NVreg_UsePageAttributeTable:int
parm:           NVreg_MapRegistersEarly:int
parm:           NVreg_RegisterForACPIEvents:int
parm:           NVreg_CheckPCIConfigSpace:int
parm:           NVreg_EnablePCIeGen3:int
parm:           NVreg_EnableMSI:int
parm:           NVreg_MemoryPoolSize:int
parm:           NVreg_RegistryDwords:charp
parm:           NVreg_RmMsg:charp

Biblioteki[edytuj]

Schemat stosu grafiki jądra Linuxa; Aktualna infrastruktura Direct Rendering, dostęp do GPU odbywa się za pośrednictwem Direct Rendering Manager.


Pakiety: [37]

  • freeglut3 freeglut3-dev
  • libglew1.5 libglew1.5-dev
  • libglu1-mesa, libglu1-mesa-dev, libgl1-mesa-glx , libgl1-mesa-dev

kompilacja:

 gcc -lglut -lGL -lGLU -lGLEW example.c 

W kodzie:

#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glext.h>

Pliki nagłówkowe bibliotek:

  • gl.h
  • glu.h
  • glut.h
  • glew.h
Includes Static Libs Dynamic Libs
/usr/X11R6/include/GL /usr/X11R6/lib/ /usr/X11R6/lib/
GL gl.h libGL.la libGL.so
GLU glu.h libGLU.la libGLU.so
GLUT glut.h libglut.la libglut.so



Kontekst/platforma[edytuj]

  • windows: WGL
  • linux/unix ( X-window): GLX
  • OS X : CGL i AGL
  • urządzenia przenośne :
    • OpenGL ES
    • EGL
  • www : WebGL
  • Vulkan API


Podstawowe[edytuj]

GL[edytuj]

GL = Graphic Library (ang.) = OpenGl core library

Jest to niskopoziomowa biblioteka zawierająca procedury do rysowania linii, koloru tła itp. Otrzymujemy dostęp do OpenGL-1.1. Na więcej potrzebujemy rozszerzeń, np. za pomocą biblioteki GLEW[38]

GLU[edytuj]

GLU = Graphics Library Utility (ang.) jest to średniopoziomowa biblioteka pozwalająca na dostęp do macierzy, renderowania powierzchni itp.

GUI[edytuj]

GUI czyli graficzny interfejs użytkownika ( okna = windows creation):

Podział wg złożoności i wersji OpenGl:

  • Lekkie/ proste ale tylko dla starej wersji OpenGl:
  • Złożone ( dla nowych wersji OpenGl):


Podział wg zależności od systemu operacyjnego ( OS )[41]

  • zależne od OS
    • bezpośredni ( rendering contexts and pixel formats )
      • direct rendering from OpenGl application to OpenGl DRIdriver
      • from framebuffer application to Direct Rendering Manager (DRM)
    • biblioteki
      • GLX (ang. OpenGL Extension to the X Window System) – interfejs łączący OpenGL z X Window System i zapewniający działającym w oknach X Window System dostęp do funkcji OpenGL
      • wgl
      • cgl
  • niezależne od OS
    • GLUT
    • GLFW
    • SDL
    • CPW
    • SFML

cimgui[edytuj]

DRM[edytuj]

Direct Rendering Manager(DRM) – komponent Direct Rendering Infrastructure (DRI), czyli systemu sprzętowej akceleracji grafiki pod Linuksa. DRM odpowiada za bezpieczeństwo oraz zarządzaniem zasobami.

DRM składa się z dwóch modułów jądra systemu operacyjnego. Jednego wspólnego dla wszystkich kart graficznych, oraz sterowników właściwych dla konkretnego urządzenia. Obydwa te moduły pozwalają klientowi serwera X, na bezpośredni dostęp do urządzenia (z pominięciem serwera X).

GLUT[edytuj]

GLFW[edytuj]

Wymagania:

  • gcc
  • OpenGL (OpenGL header packages)
  • X11
  • xorg-dev
  • libglu1-mesa-dev
  • libglfw-dev
  • cmake


Przykłady

pakiety[edytuj]
 sudo apt-get update
 sudo apt-get install libglfw3 libglfw3-dev
git[edytuj]

Etapy:

  • ściągnięcie kodu źródłowego biblioteki[42]
  • kompilacja biblioteki [43]


git clone https://github.com/glfw/glfw.git
cd <glfw-root-dir>
cmake .


Sprawdzamy:

sudo updatedb
locate glfw3.pc

przykładowy wynik:

/home/a/cn/glfw-3.0.4/src/glfw3.pc
/home/a/cn/glfw-3.0.4/src/glfw3.pc.in
/home/a/glfw/src/glfw3.pc
/home/a/glfw/src/glfw3.pc.in


sudo apt-get update
sudo apt-get install build-essential cmake git xorg-dev libglu1-mesa-dev
git clone https://github.com/glfw/glfw.git /tmp/glfw
cd /tmp/glfw
git checkout latest
cmake . -DBUILD_SHARED_LIBS=ON
make
sudo make install
sudo ldconfig
# rm -rf /tmp/glfw


przykład=[edytuj]
/*
http://www.glfw.org/documentation.html


gcc g.c -lGL -lGLU -lglut -lglfw

./a.out



*/

#include <GLFW/glfw3.h>

int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

SFML[edytuj]

SFML = Simple and Fast Multimedia Library (ang.)[44][45]

  • Build SFML and CSFML on Linux by Oleh Prypin[46]


sudo apt-get install libsfml-dev


-I/path/to/SFML/headers

Rozszerzenia[edytuj]

Biblioteki rozszerzeń (ang. OpenGL Loading Library, Extension Loading Library)

GLEW[edytuj]

GLEW = OpenGL Extension Wrangler Library (ang.) jest to programistyczna biblioteka międzyplatformowa, pomagająca w odpytywaniu i ładowaniu rozszerzeń OpenGL. GLEW dostarcza efektywne mechanizmy do określania w czasie uruchamiania programu dostępnych rozszerzeń na danej platformie. Wszystkie rozszerzenia OpenGL są wylistowane w jednym pliku nagłówkowym, który z kolei jest maszynowo generowany na podstawie oficjalnej listy rozszerzeń.

GLEW jest napisany w ANSI C.

#include<GL/glew.h>
#include<GL/gl.h>
#include<GL/glu.h>
#include<GL/glut.h>

Kompilacja:

-lGLEW -lGLU -lGL - lglut

GLEW zawiera dodatkowe programy konsolowe, np.: glewinfo

glewinfo>i.txt

W pliku i.txt jest informacja:

 ---------------------------
    GLEW Extension Info
---------------------------

GLEW version 1.8.0
Reporting capabilities of display :0, visual 0x2b
Running on a GeForce GTX 770/PCIe/SSE2 from NVIDIA Corporation
OpenGL version 4.3.0 NVIDIA 319.60 is supported

Następnie jest lista rozszerzeń i informacja o dostępności (OK/MISSING).

matematyczne[edytuj]

glm (linear algebra)[edytuj]

GLM - library for linear algebra operations [49]

to biblioteka matematyczna C++ (i zastępująca stałe funkcje potokowe OpenGL) dla oprogramowania 3D opartego na specyfikacji OpenGL Shading Language (GLSL).

  sudo apt-get install libglm-dev

graficzne[edytuj]

Przykłady[edytuj]

kolor[edytuj]

  • Renderowanie obrazu sRGB jest częścią wszystkich implementacji OpenGL w wersji 3.0 i nowszych
  • Nie ma potrzeby linearyzacji formatów obrazów zmiennoprzecinkowych, takich jak .hdr i .exr (32-bitowe), które są już dostępne w przestrzeni gamma 1.0.
  • większość obrazów jest zapisywana z korekcją gamma sRGB wynoszącą 0,45, nasze oprogramowanie musi wstępnie przetworzyć obrazy sRGB do liniowej wartości gamma 1,0

grafika 2d[edytuj]

Technika: [50]

  • old OpenGl ( GLUT)
    • glDrawPixels
  • modern OpenGl
    • rysowanie płaskiego czworoboku za pomocą kamery do projekcji prostokątnej
    • nakłada teksturę

Pierwszy program[edytuj]

Konsolowy program korzystający z bibliotek GL, GLU i GLUT. Tworzy okno wypełnione czerwonym kolorem [51]

/* 

gcc o.c -lGL -lGLU -lglut
./a.out

http://www.linuxforu.com/2013/04/graphics-programming-in-linux/

Graphics Programming in Linux

By Rajnish-Singh on April 1, 2013 in Developers, Features, Overview · 3 Comments

*/


# include <stdio.h>
#include<GL/gl.h>
#include<GL/glu.h>
#include<GL/glut.h> 


void display() 
{ 
    glClearColor(1,0,0,0); 
    glClear(GL_COLOR_BUFFER_BIT); 
    glFlush(); 
} 


void main(int argc, char**argv) { 
    glutInit(&argc, argv); 
    glutInitWindowPosition(100,100); 
    glutInitWindowSize(500,500); 
    glutCreateWindow("Hello World"); 
    glutDisplayFunc(display); 
    glutMainLoop(); 
}

GLEW[edytuj]

Konsolowy program korzystający z glew:

//gcc c.c  -lGLEW -lGL -lGLU -lglut 
//./a.out
#include <stdio.h>
#include<GL/glew.h>
#include<GL/glut.h>
#include<GL/gl.h>
#include<GL/glu.h>

void main(int argc, char **argv)
{
	glutInit(&argc, argv);
	
	glewInit();
	if ( GL_VERSION_4_0) printf("OpenGL 4.0 is supported\n");
}

Konsolowy program korzystający z bibliotek GL, GLU, GLUT i GLEW. Tworzy okno wypełnione czerwonym kolorem oraz sprawdza wersję biblioteki GLEW

/*
gcc g.c  -lGLEW -lGL -lGLU -lglut 
./a.out

http://www.linuxforu.com/2013/04/graphics-programming-in-linux/
Graphics Programming in Linux By Rajnish-Singh on April 1, 2013 in Developers, Features, Overview · 3 Comments
http://www.opengl.org/sdk/libs/GLEW/
call glewInit(); once you've obtained a OpenGL context in your program.

*/
#include <stdio.h>
#include <GL/glew.h> // glew before gl 
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h> 
 


void display() 
{ 
    glClearColor(1,0,0,0); 
    glClear(GL_COLOR_BUFFER_BIT); 
    glFlush(); 
} 


void main(int argc, char**argv) { 
    glutInit(&argc, argv); 
    glutInitWindowPosition(100,100); 
    glutInitWindowSize(500,500); 
    glutCreateWindow("Hello World");

    GLenum err = glewInit();
    if (GLEW_OK != err)
      fprintf(stderr, "Error: %s\n", glewGetErrorString(err));/* Problem: glewInit failed, something is seriously wrong. */
      else fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); 
    glutDisplayFunc(display); 
    glutMainLoop(); 
}

Sprawdzamy rozszerzenia:[52]

/*


gcc g.c  -lGLEW -lGL -lGLU -lglut 
./a.out

http://www.linuxforu.com/2013/04/graphics-programming-in-linux/

Graphics Programming in Linux By Rajnish-Singh on April 1, 2013 in Developers, Features, Overview · 3 Comments


http://www.opengl.org/sdk/libs/GLEW/
call glewInit(); once you've obtained a OpenGL context in your program.
http://steps3d.narod.ru/tutorials/glew-tutorial.html


*/

#include <stdio.h>
#include <GL/glew.h> // glew before gl 
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h> 
 


void display() 
{ 
    glClearColor(1,0,0,0); 
    glClear(GL_COLOR_BUFFER_BIT); 
    glFlush(); 
} 


int main(int argc, char**argv) { 
    glutInit(&argc, argv); 
    glutInitWindowPosition(100,100); 
    glutInitWindowSize(500,500); 
    glutCreateWindow("Hello World");

    GLenum err = glewInit();
    if (GLEW_OK != err)
      {
       fprintf(stderr, "Error: %s\n", glewGetErrorString(err));/* Problem: glewInit failed, something is seriously wrong. */
       return 1; 
      }    
    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
    
    // checking for extensions 
    if ( !GLEW_ARB_shading_language_100 )
    {
        printf ( "GL_ARB_shading_language_100 NOT supported.\n" );
        return 2;
    }
    printf ( "GL_ARB_shading_language_100 is supported.\n" );

    if ( !GLEW_ARB_shader_objects )
    {
        printf ( "GL_ARB_shader_objects NOT supported" );
        return 3;
    }
    printf ( "GL_ARB_shader_objects is supported" );
    if (!GLEW_ARB_vertex_shader || !GLEW_ARB_fragment_shader)
     {
           printf("No GLSL support\n");
          exit(4);
     }

   printf(" GLSL is supported\n");

    glutDisplayFunc(display); 
    glutMainLoop(); 
}

Zapisywanie obrazu[edytuj]

  • kod (paul bourke) [53]

Przeglądarka obrazów dla programistów[edytuj]

Ten program:

  • działa tylko dla legacy OpenGL API !
  • otwiera binarne pliki ppm (P6) i pgm (P5)
  • wyświetla je w nowym oknie (Glut)
  • na konsoli tekstowej wyświetla:
    • typ pliku,
    • szerokość, wysokość,
    • komentarz,
    • dane punktu nad którym znajduje się mysz (patrz procedura Motion, można to zmienić !!!)

Program służy do analizy plików graficznych.


/* 
 * image.c
 *
 * read in a PPM or PGM binary image and display it, full size
 
  Based on code by : 
   Dr. Lori L. Scarlatos
   Stony Brook University
   http://ms.cc.sunysb.edu/~lscarlatos/
   "I do not have a license for image.c; 
   it was created as an example for my students.
   Please feel free to use it.
   Best regards,
   Lori"

Warning: This article describes legacy OpenGL APIs that have been removed from core OpenGL 3.1 and above (they are only deprecated in OpenGL 3.0). It is recommended that you not use this functionality in your programs.
Fixed Function Pipeline
* ----------------------------
* it does not opens asci versions of these files 
* examples files : 
* http://people.sc.fsu.edu/~jburkardt/data/data.html


http://web.eecs.umich.edu/~sugih/courses/eecs487/glut-howto/sample.c

  // gcc v.c -lm -lGLU -lglut -Wall // ? windows 
    gcc v.c -lm -lglut -lGL -lGLU -Wall // ubuntu 
  ./a.out 5.pgm

 */

/*

locate glut.h
/usr/include/GL/freeglut.h
/usr/include/GL/glut.h

#ifdef FREEGLUT
#include <GL/freeglut.h>
#else
#include <GL/glut.h>
#endif

*/



//#include <Windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
//#include <GL/glut.h> // oryginal glut 
#include <GL/freeglut.h> // freeglut 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h> /* fabs*/
//#include <malloc.h>



/* Global variables */

#define MAXLINE 80	/* maximum length of a line of text */

/*

3.2 Conventions

In developing the freeglut library, we have taken careful steps to ensure consistency in function operation across the board, 
in such a manner as to maintain compatibility with GLUT's behavior whenever possible. In this section some of the important conventions of FreeGLUT, 
and their compatibility with GLUT, are made explicit.

3.2.1 Window placement and size

There is considerable confusion about the "right thing to do" concerning window size and position. GLUT itself is not consistent between Windows and UNIX/X11; 
since platform independence is a virtue for freeglut, we decided to break with GLUT's behaviour. 
Under UNIX/X11, it is apparently not possible to get the window border sizes in order to subtract them off the window's initial position until some time after the window has been created. 
Therefore we decided on the following behavior, both under Windows and under UNIX/X11:

When you create a window with position (x,y) and size (w,h), the upper left hand corner of the outside of the window (the non-client area) is at (x,y) and the size of the drawable (client) area is (w,h). 
The coordinates taken by glutInitPosition and glutPositionWindow, as well as the coordinates provided by FreeGLUT when it calls the glutPositionFunc callback, specify the top-left of the non-client area of the window.
When you query the size and position of the window using glutGet, FreeGLUT will return the size of the drawable area
--the (w,h) that you specified when you created the window
--and the coordinates of the upper left hand corner of the drawable (client) area
--which is NOT the (x,y) position of the window you specified when you created it.




*/




GLint ImageWidth, ImageHeight;	         /* size of the Image in pixels */
GLint WindowWidth, WindowHeight;	/* size of the window in pixels */
GLint MaxScreenWidth, MaxScreenHeight;	/* size of the screen in pixels */


GLubyte *Picture;	/* Array of colors (GLubyte)  */
int size; 



// mouse position as a global variables 
//static float mx=0.0f,my=0.0f ;
int iX, iY; // 
int centerX = 200, centerY = 200;
GLint iYmax,iXmax; // mouse coordinate inside image 

unsigned char pixel[3];

// change it manually !!!!!


const double  ZyMin=-1.0;
const double  ZxMin=-2.0;
const double  PixelHeight=0.0020010005002501  ;
const double  PixelWidth=0.0020010005002501  ;

int filetype;
enum {P2, P3, P5, P6};	/* possible file types */

/* gives position of point (iX,iY) in 1D array  ; uses also global variables */
unsigned int f(unsigned int _iX, unsigned int _iY)
{return (_iX + (iYmax-_iY-1)*iXmax );}

/* 
* Read from a PPM or PGM (binary) file 
* Output is a array of GLubyte 
*/
void readPPM (char *filename, GLubyte **pic) {

	FILE *fp;
	char line[MAXLINE];
	int i, rowsize;
        // int size; // moved to global var 
        int j ;
	GLubyte *ptr;

/* Read in file type */
  
  fp = fopen(filename, "r"); /* in Unix rb = r */
  if (fp==NULL) {perror(" perror : " ); printf("Error from fopen : I can't open %s file' ! ", filename); exit(1); }
  else printf("File %s has been opened !\n", filename);
  /* Each file starts with aa two-byte magic number (in ASCII) that explains :
   * - the type of file it is (PBM, PGM, and PPM) 
   * - its encoding (ASCII or binary). 
   * The magic number is a capital P followed by a single digit number. 
  */
  fgets (line, MAXLINE, fp); /* 1st line : Magic Number  */
  switch (line[1])
  {
   case '2':
       filetype = P2; 
       printf("This is PGM text file (P2), but now I do not have procedure for opening it \n");
       break;
   case '3' :
      filetype = P3;
      printf("This is PPM text file (P3), but now I do not have procedure for opening it !\n");
      break; 
   case '5':
       filetype = P5; 
       printf("This is PGM binary file (P5) and I can open it !\n");
       break;
   case '6' :
      filetype = P6;
      printf("This is PPM binary file (P6) and I can open it !\n");
      break;
   default : 
      printf("Error from readPPM : need binary PPM or binary PGM file as input!\n");
      exit(1);
   }
 /* if this is a comment, read next line. Maybe in binary files there is no comment ?*/
/* there maybe more then one line of comment */
 fgets (line, MAXLINE, fp); 
 while  (line[0]=='#') 
  { printf(" comment  = %s \n", line); /* 2nd or more line  starting with # =  comment, print it   */
    fgets (line, MAXLINE, fp); // read next line 
  } 

/* Read in width and height, & allocate space */
/* these 2 numbers should be in one line with space between them */
   /* 3nd line: width  and height */
  sscanf(line, "%d %d", &ImageWidth, &ImageHeight);
  printf ("iWidth = %d\n", ImageWidth);
  printf ("iHeight = %d\n",  ImageHeight);
  iXmax=ImageWidth-1;
  iYmax=ImageHeight-1;

  if (filetype == P5) {
	  size = ImageHeight * ImageWidth; /* greymap: 1 byte per pixel */
	  rowsize = ImageWidth;
  }
  else /* filetype == P6 */ {
	  size = ImageHeight * ImageWidth * 3; /* pixmap: 3 bytes per pixel */
	  rowsize = ImageWidth * 3;
  }
  *pic = (GLubyte *)malloc (size); /* create dynamic array */

/* Read in maximum value (ignore) */
  fgets (line, MAXLINE, fp); /* next  line */
  /*  */
  if (filetype==P5 || filetype==P6){
    /* Read in the pixel array row-by-row: 1st row = top scanline */
    ptr = *pic + (ImageHeight-1) * rowsize;
    for (i = ImageHeight; i > 0; i--) {
          /* For binary File I/O you use fread and fwrite */
	  j = fread((void *)ptr, 1, rowsize, fp); 
	  ptr -= rowsize;
    }
   if (j) printf("File %s has been read !\n", filename);
          else printf(" j Error from readPPM procedure : I can't read %d file !.\n", j);
  }
  else printf("Error from readPPM procedure : I can't read %s file !. It should be P5 or P6 file !\n", filename);
  fclose(fp);
  printf("File %s has been closed !\n", filename);
}






/* Draw the picture on the screen */

void Draw(void) {
        /* black background of GLUT window */
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Clear the background of our window to black
        glClear(GL_COLOR_BUFFER_BIT); //Clear the colour buffer (more buffers later on)
        glLoadIdentity(); // Load the Identity Matrix to reset our drawing locations
        glFlush(); // Flush the OpenGL buffers to the window
        // left lower corner of displayed image 
	glRasterPos2i(-1,-1); // By default, OpenGL assumes a system running from -1 to 1, 
        switch (filetype){
          case P5 : 	/* greymap: use as illumination values */
		glDrawPixels(ImageWidth, ImageHeight, GL_LUMINANCE, GL_UNSIGNED_BYTE, Picture);
                printf("P5 Image has been drawn !\n");
                break;
	  case  P6 :
		glDrawPixels(ImageWidth, ImageHeight, GL_RGB, GL_UNSIGNED_BYTE, Picture);
                printf("P6 Image has been drawn !\n");
                break;
         default : 
                printf("Error from Draw procedure : There is no image to draw !\n");
          }


       
}




// Detecting Mouse Clicks
// x and y specify the location (in window-relative coordinates) of the mouse when
// the event occurred
void MouseClicks (int button, int state, int x, int y)
{
switch (button)
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN)
// do something
case GLUT_RIGHT_BUTTON: ;
// etc., etc.
}





// mouse motion 
//The x and y callback parameters 
// indicate the  mouse  location 
// in window relative coordinates
//
// x, y –> coordinates of the mouse relative to upper left corner of window

// setting the mouse position to be relative to the mouse
// position inside the window
//

void PassiveMouseMotion(int x, int y) {
  
   //double Zx,Zy;
   //double Ux; 
   //int index;
   //GLubyte Gray;

   // put your code here  ???? 
   iX = x;
   /* invert y axis */
   iY = WindowHeight - y -1 ; //+ (glutGet(GLUT_WINDOW_HEIGHT) - ImageHeight); ///glutGet(GLUT_WINDOW_HEIGHT) - y; // ????
   
  

   
   /* output : prints to console  */
  if ((filetype==P5 || filetype==P6) && -1<iX && iX< ImageWidth  && iY<ImageHeight) // && iY<ImageHeight
   {

     
     glReadPixels(iX, iY, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, pixel);
   // pixel coordinates of the mouse relative to upper left corner of window
   printf(" pixel iX=%3d / %d ;  iY=%3d  color = %d  \n", iX, MaxScreenWidth,  iY, pixel[1] );
  }
}




static void Key(unsigned char key, int x, int y)
{
    switch (key) {
	case 27 : {glutLeaveFullScreen(); break;}/* esc */
        case 'f': {glutFullScreen(); break; }
        case 'q': {printf("Key preseed and exit \n"); exit(1) ;}
        case 'Q': {printf("Key preseed and exit \n"); exit(1) ;}
        case 't': {glutFullScreenToggle(); break; } // GLUT does not include the glutLeaveFullScreen and glutFullScreenToggle functions from freeglut 
	default: return ;
    }
}



/* 
 Resize the picture  ; OpenGL calls this function whenever the window is resized 
 Called when window is resized,  also when window is first created,    before the first call to display().
*/
void Reshape(GLint w, GLint h) {

/* save new screen dimensions */
     WindowWidth = w;
     WindowHeight = h;
    /* the viewport is the rectangular region of the window where the image is drawn */
   // Viewport : A rectangular region in the screen for display  (in screen coordinate system) 
    glViewport(0, 0, ImageWidth-1, ImageHeight-1); // glViewport( 0.f, 0.f, SCREEN_WIDTH, SCREEN_HEIGHT );
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    // Define a world window : A rectangular region in the world that is to be displayed (in world coordinate system)
    // By default, OpenGL assumes a system running from -1 to 1, 
    gluOrtho2D(-1, 1, -1, 1); // An orthographic projection is basically a 3D projection that does not have perspective
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}





/* 
Initialization: create window 
glutInitWindowSize(600, 600);
*/
void MyInit(int argc, char *argv[]) {
    char filename[MAXLINE];
  
  /* Read in the file (allocates space for Picture) */
  if (argc < 2) 
    {
	printf ("Enter the name of a binary PPM or PGM file: ");
	scanf("%s", filename);
	readPPM ((char *)filename, &Picture);
    }
    else { readPPM (argv[1], &Picture); }
  
  glutInit(&argc, argv);

  MaxScreenWidth  = glutGet(GLUT_SCREEN_WIDTH);
  MaxScreenHeight = glutGet(GLUT_SCREEN_HEIGHT);   
    
  glutInitWindowPosition(-1, 1); // upper  left  corner
  glutInitWindowSize(MaxScreenWidth, MaxScreenHeight ); // full screen of my monitor
 
  glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
  if (glutCreateWindow("OpenGl binary pgm/ppm Image viewer ") == GL_FALSE) 
      {printf("Error from  MyInit , glutCreateWindow\n"); exit(1);}
       
}


/* ------------------ Main program ---------------------------------------*/
int main(int argc, char **argv)
{
  
    MyInit(argc, argv);
    glutPassiveMotionFunc(PassiveMouseMotion); // mouse move with no key pressed 
    glutReshapeFunc(Reshape); //  move or resize of screen window 
    glutDisplayFunc(Draw); // 
    glutKeyboardFunc(Key);
    //
    glutMainLoop();
    return 0;
}


inne[edytuj]

Współrzędne[edytuj]

Współrzędne
world (float) screen (integer)
world
screen
screen window
world window viewport

Q: Czego lepiej używać, wymiarów typu 1.0f, -2,0f, czy wartości w pixelach 100, 550 - przy rysowaniu?

A: "Używaj tego co Ci wygodniej. Większość instrukcji operujących na wierzchołkach ma wersje dla liczb całkowitych - te z przedrostkiem i, jak i zmiennoprzecinkowych - te z przedrostkiem f(float) lub d(double)). np: glVertex2i(x,y), glVertex2f(x,y), glVertex3d(x,y,z) itd." [54]

Q: Gdzie definiujemy viewport?

A: W 2 miejscach:

  • w inicjalizacji, wtedy ma taki sam rozmiar jak całe okno
  • w funkcji zmieniającej rozmiar okna (glutReshapeFunc)

Typy[edytuj]

World[edytuj]

Domyślnie współrzędne okna światowego (world) w OpenGL mają zakres -1.0 do 1.0:

gluOrtho2D(-1.0, 1.0, -1.0, 1.0);


Miejsce lewego dolnego rogu wyświetlanego obrazu:

glRasterPos2i(-1.0, -1.0); // in Draw procedure 

Screen[edytuj]

W OpenGL mamy tu 3 elementy:

  • rozdzielczość ekranu (ang. screen)
  • wielkość okna ekranu (ang. window)
  • wielkość fragmentu okna ekranu gdzie jest wyświetlany obraz (ang. viewport) [55][56]


Współrzędne są liczbami całkowitymi:

 glutInitWindowSize(2560, 1440); // screen width, screen height in poixels 

 glViewport(50, 50, 350, 250); // viewport left down and upper right corners in window coordinate

Proporcje[edytuj]

Jeśli proporcja (ang. aspect ratio) r pomiędzy wymiarami World Window a VBiewport jest 1.0 to obraz nie jest zniekształcony.

r= width/height

Przeliczanie[edytuj]

Przeliczanie współrzędnych:[57]

  • World window: W_L, W_R, W_B, W_T
  • Viewport: V_L, V_R, V_B, V_T
  • punkt:
    • współrzędne world: (x,y)
    • współrzędne viewport: (sx, sy)
world_height=world_width*view_port_height/view_port_width
W_L=center_x‐world_width/2
W_B=center_y+world_height/2
W_R=center_x+world_width/2 
W_T=center_y+world_height/2
sx = (x ‐ W_L)(V_R ‐ V_L) / (W_R ‐ W_L) +V_L
sy = (y - W_B)(V_T ‐ V_B) / (W_T ‐ W_B) +V_B

Dokumentacja[edytuj]

Zobacz również[edytuj]

Źródła[edytuj]

  1. WebGPU Will Revolutionise the Web and Here's WHY! by codedamn
  2. OpenGl tutorial
  3. Bufor ramki w Wikipedii
  4. [http://www.mathematik.uni-dortmund.de/~goeddeke/gpgpu/tutorial.html GPGPU::Basic Math / FBO Tutorial Modified from Dominik Göddeke]
  5. Radosław Mantiuk - wprowadzenie do grafiki
  6. Getting Started with OpenGL by Ray Toal
  7. askubuntu question: how-do-i-find-out-the-model-of-my-graphics-card
  8. the Polish translation of Getting-started/OpenGL article of learnopengl.com tutorial series
  9. stackoverflow question : is-it-possible-to-draw-anything-in-opengl-3-without-writing-glsl-shaders-will
  10. directfb
  11. [http://antongerdelan.net/opengl/shaders.html OpenGL 4 Shaders Anton Gerdelan. 24 June 2014]
  12. glxinfo - linux command
  13. glxinfo code
  14. linux reviews : Glxgears
  15. How to get the nvidia driver version from the command line ? - stackoverflow
  16. nvidia-detect
  17. Installing Nvidia Drivers In Linux Mint
  18. phoenixnap: install-nvidia-drivers-ubuntu
  19. Using hardware accelerated 3D renderer on Linux from mgltools
  20. The NVIDIA Smart Scan page (requires the latest version of Java)
  21. Gpu test
  22. LuxRender
  23. askubuntu question: How to get GPU info?
  24. StackOverflow: undefined reference to symbol 'gluLookAt'
  25. unix.stackexchange question : what-is-the-difference-between-kernel-drivers-and-kernel-modules
  26. OpenGL - wsparcie przez sterowniki firmy Nvidia (ang.)
  27. How is Mesa different from OpenGL drivers - Stackoverflow
  28. Zyli: Instalacja zamkniętych (firmowych) sterowników Nvidia
  29. Nvidia Unix Driver Archive
  30. Nouveau: Accelerated Open Source driver for nVidia cards
  31. Ubuntu: BinaryDriverHowto/Nvidia
  32. askubuntu question: how-do-i-upgrade-my-gpu-drivers
  33. linuxconfig : how-to-install-the-nvidia-drivers-on-ubuntu-22-04
  34. Dynamic Kernel Module Support w wikipedii
  35. Why would modinfo say a module is not found when it appears with lsmod ?
  36. Alias w angielskiej Wikipedii
  37. stackoverflow question learning-opengl-in-ubuntu
  38. Różnice między bibliotekami
  39. GLFW
  40. GLUS
  41. opengl : window toolkits
  42. Kod źródłowy GLFW
  43. Kompilacja GLFW
  44. sfml home page
  45. stackoverflow question: fatal-error-sfml-graphics-hpp-no-such-file-or-directory-exists
  46. build-sfml-and-csfml-on-linux by O Prypin
  47. Unofficial OpenGL Software Development Kit
  48. gl3w
  49. OpenGL Mathematics GLSL + Optional features = OpenGL Mathematics (GLM) A C++ mathematics library for graphics programming
  50. stackoverflow question : how-to-draw-a-2d-image-using-opengl
  51. Graphics Programming in Linux By Rajnish-Singh
  52. glew tutorial - Alexey V. Boreskov
  53. Zapisywanie obrazu z aplikacji OpenGL - kod (paul bourke)
  54. Forum Serwisu programistycznego C i C++: [OPENGL glViewport a gluOtrho2d]
  55. glViewport
  56. The Viewport - Lazy Foo' Productions
  57. 2D Coordinate Systems and Drawing