
Introduccion
OpenSceneGraph (en lo sucesivo, OSG) es un marco abierto multiplataforma escrito en C ++ y que representa un motor gráfico que proporciona al programador una interfaz de objeto para OpenGL. En nuestro país, este motor no es particularmente popular, incluso en Habré vi solo una
publicación más o menos decente al respecto . OSG se usa mucho en el extranjero, donde, por ejemplo, es la base del simulador de vuelo gratuito
FlightGear , hay una implementación abierta del juego Morrowind, llamado
OpenMW, cuyo desarrollo también se transfiere a OSG desde el motor
Ogre . La documentación en ruso es muy pequeña y, entre la documentación en inglés, solo se puede observar una serie de libros de los desarrolladores:
OpenSceneGraph 3.0. Guía para principiantes y
OpenSceneGraph 3. Libro de cocina .
Sin embargo, el motor es bastante interesante por las siguientes razones:
- Una implementación abierta multiplataforma en C ++.
- Arquitectura modular
- Extensibilidad a través del sistema de complemento incorporado.
- Posibilidad de procesamiento multiproceso de datos gráficos y herramientas integradas para su implementación
- Gestión dinámica de la memoria a través del mecanismo de puntero inteligente
Creo que será interesante para los lectores de Habr familiarizarse con este proyecto con más detalle. La reposición de la base de conocimientos OSG en ruso no será superflua. Todos los materiales que publicaré sobre este tema se basan en el libro
OpenSceneGraph 3.0. Guía para principiantes , pero no son su traducción, sino más bien una revisión creativa del material presentado allí. Si está interesado en este tema, le pido un corte
La única forma segura de obtener la última versión de OSG en su máquina es construir la biblioteca desde la fuente. El instalador binario existente para Windows se centra en el compilador MS Visual C ++. Para mí, para mis proyectos es necesario usar el compilador GCC, o más bien su versión de MinGW32, que se incluye en el suministro de herramientas de desarrollo de framework Qt. Entonces necesitamos:
- Marco Qt instalado y configurado con el compilador MinGW32 versión 5.3 y QtCreator IDE
- Cliente Git para Windows
- Utilidad Cmake para Windows
Se espera que el lector esté familiarizado con QtCreator IDE y el sistema de compilación qmake utilizado en proyectos Qt. Además, se supone que el lector conoce los conceptos básicos del uso del sistema de control de versiones Git y, en principio, tiene habilidades de programación distintas de cero.
1. Obtener fuentes de OpenSceneGraph
Creamos un directorio en nuestro disco duro donde construiremos OSG, por ejemplo, a lo largo de la ruta D: \ OSG

Iremos a este directorio y obtendremos la fuente del
repositorio oficial de OSG en GithubD:\OSG> git clone https:
La duración del proceso de descarga depende de qué tan ancho sea su canal de acceso a Internet. Tarde o temprano, recibiremos una copia local del repositorio OSG.
Después de descargar las fuentes, cree el directorio build-win32-debug cercano

En este catálogo crearemos el kit de depuración OSG. Pero antes
2. Configurar cmake
Para que cmake funcione correctamente, necesitamos editar
el archivo install-path-cmake \ share \ cmake-3.13 \ Modules \ CMakeMinGWFindMake.cmake . Por defecto, se ve así
Comentamos algunas líneas, para que la utilidad no intente buscar un shell de Unix en nuestro sistema, y si no lo encuentra, termina con un error
3. Montaje e instalación de versiones de depuración y liberación del motor.
Ahora ejecute el cmd shell, el acceso directo que se encuentra en Inicio-> Programas-> Qt-> Qt 5.11.2-> Qt 5.11.2 para escritorio (MinGW 5.3.0 32bit)

Una sesión de línea de comandos en ejecución configura todo el entorno necesario para que las herramientas de compilación mingw32 funcionen. Ir al directorio fuente de OSG
C:\Qt\Qt5.11.2\5.11.2\mingw53_32>D: D:\> cd OSG\build-win32-debug
Dar una orden
D:\OSG\build-win32-debug>cmake -G "MinGW Makefiles" -DCMAKE_INSTALL_PREFIX=E:\Apps\OSG -DCMAKE_BUILD_TYPE=DEBUG ../OpenSceneGraph
Analicemos el significado de los parámetros con más detalle:
- -G "MinGW Makefiles": indica que es necesario generar un Makefile para la utilidad mingw32-make
- -DCMAKE_INSTALL_PREFIX = E: \ Apps \ OSG - establece la ruta donde se instalará OSG
- -DCMAKE_BUILD_TYPE = DEBUG - indica que se debe construir una versión de depuración del motor.
La ejecución del comando verifica la preparación del entorno para el ensamblaje, genera un script de compilación y el siguiente escape
Cmake escape al configurar OSG build -- The C compiler identification is GNU 5.3.0 -- The CXX compiler identification is GNU 5.3.0 -- Check for working C compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/gcc.exe -- Check for working C compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/gcc.exe -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/g++.exe -- Check for working CXX compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/g++.exe -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- Looking for pthread.h -- Looking for pthread.h - found -- Looking for pthread_create -- Looking for pthread_create - found -- Found Threads: TRUE -- Found OpenGL: opengl32 -- Could NOT find EGL (missing: EGL_INCLUDE_DIR) -- Checking windows version... -- Performing Test GL_HEADER_HAS_GLINT64 -- Performing Test GL_HEADER_HAS_GLINT64 - Failed -- Performing Test GL_HEADER_HAS_GLUINT64 -- Performing Test GL_HEADER_HAS_GLUINT64 - Failed -- 32 bit architecture detected -- Could NOT find Freetype (missing: FREETYPE_LIBRARY FREETYPE_INCLUDE_DIRS) -- Could NOT find JPEG (missing: JPEG_LIBRARY JPEG_INCLUDE_DIR) -- Could NOT find Jasper (missing: JASPER_LIBRARIES JASPER_INCLUDE_DIR JPEG_LIBRARIES) -- Could NOT find LibXml2 (missing: LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR) -- Could NOT find ZLIB (missing: ZLIB_INCLUDE_DIR) -- Could NOT find ZLIB (missing: ZLIB_INCLUDE_DIR) -- Could NOT find GDAL (missing: GDAL_LIBRARY GDAL_INCLUDE_DIR) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find CURL (missing: CURL_LIBRARY CURL_INCLUDE_DIR) -- Trying to find DCMTK expecting DCMTKConfig.cmake -- Trying to find DCMTK expecting DCMTKConfig.cmake - failed -- Trying to find DCMTK relying on FindDCMTK.cmake -- Please set DCMTK_DIR and re-run configure (missing: DCMTK_config_INCLUDE_DIR DCMTK_dcmdata_INCLUDE_DIR DCMTK_dcmimage_INCLUDE_DIR DCMTK_dcmimgle_INCLUDE_DIR DCMTK_dcmjpeg_INCLUDE_DIR DCMTK_dcmjpls_INCLUDE_DIR DCMTK_dcmnet_INCLUDE_DIR DCMTK_dcmpstat_INCLUDE_DIR DCMTK_dcmqrdb_INCLUDE_DIR DCMTK_dcmsign_INCLUDE_DIR DCMTK_dcmsr_INCLUDE_DIR DCMTK_dcmtls_INCLUDE_DIR DCMTK_ofstd_INCLUDE_DIR DCMTK_oflog_INCLUDE_DIR) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find GStreamer (missing: GSTREAMER_INCLUDE_DIRS GSTREAMER_LIBRARIES GSTREAMER_VERSION GSTREAMER_BASE_INCLUDE_DIRS GSTREAMER_BASE_LIBRARIES GSTREAMER_APP_INCLUDE_DIRS GSTREAMER_APP_LIBRARIES GSTREAMER_PBUTILS_INCLUDE_DIRS GSTREAMER_PBUTILS_LIBRARIES) (found version "") -- Could NOT find SDL2 (missing: SDL2_LIBRARY SDL2_INCLUDE_DIR) -- Could NOT find SDL (missing: SDL_LIBRARY SDL_INCLUDE_DIR) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find JPEG (missing: JPEG_LIBRARY JPEG_INCLUDE_DIR) -- Could NOT find ZLIB (missing: ZLIB_INCLUDE_DIR) -- Could NOT find PNG (missing: PNG_LIBRARY PNG_PNG_INCLUDE_DIR) -- Could NOT find TIFF (missing: TIFF_LIBRARY TIFF_INCLUDE_DIR) -- g++ version 5.3.0 -- Performing Test _OPENTHREADS_ATOMIC_USE_GCC_BUILTINS -- Performing Test _OPENTHREADS_ATOMIC_USE_GCC_BUILTINS - Success -- Performing Test _OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS -- Performing Test _OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS - Failed -- Performing Test _OPENTHREADS_ATOMIC_USE_SUN -- Performing Test _OPENTHREADS_ATOMIC_USE_SUN - Failed -- Performing Test _OPENTHREADS_ATOMIC_USE_WIN32_INTERLOCKED -- Performing Test _OPENTHREADS_ATOMIC_USE_WIN32_INTERLOCKED - Success -- Performing Test _OPENTHREADS_ATOMIC_USE_BSD_ATOMIC -- Performing Test _OPENTHREADS_ATOMIC_USE_BSD_ATOMIC - Failed -- Configuring done -- Generating done -- Build files have been written to: D:/OSG/build-win32-debug
configure (falta: DCMTK_config_INCLUDE_DIR DCMTK_dcmdata_INCLUDE_DIR DCMTK_dcmimage_INCLUDE_DIR DCMTK_dcmimgle_INCLUDE_DIR DCMTK_dcmjpeg_INCLUDE_DIR DCMTK_dcmjpls_INCLUDE_DIR DCMTK_dcmnet_INCLUDE_DIR DCMTK_dcmpstat_INCLUDE_DIR DCMTK_dcmqrdb_INCLUDE_DIR DCMTK_dcmsign_INCLUDE_DIR DCMTK_dcmsr_INCLUDE_DIR DCMTK_dcmtls_INCLUDE_DIR DCMTK_ofstd_INCLUDE_DIR DCMTK_oflog_INCLUDE_DIR) -- The C compiler identification is GNU 5.3.0 -- The CXX compiler identification is GNU 5.3.0 -- Check for working C compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/gcc.exe -- Check for working C compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/gcc.exe -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/g++.exe -- Check for working CXX compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/g++.exe -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- Looking for pthread.h -- Looking for pthread.h - found -- Looking for pthread_create -- Looking for pthread_create - found -- Found Threads: TRUE -- Found OpenGL: opengl32 -- Could NOT find EGL (missing: EGL_INCLUDE_DIR) -- Checking windows version... -- Performing Test GL_HEADER_HAS_GLINT64 -- Performing Test GL_HEADER_HAS_GLINT64 - Failed -- Performing Test GL_HEADER_HAS_GLUINT64 -- Performing Test GL_HEADER_HAS_GLUINT64 - Failed -- 32 bit architecture detected -- Could NOT find Freetype (missing: FREETYPE_LIBRARY FREETYPE_INCLUDE_DIRS) -- Could NOT find JPEG (missing: JPEG_LIBRARY JPEG_INCLUDE_DIR) -- Could NOT find Jasper (missing: JASPER_LIBRARIES JASPER_INCLUDE_DIR JPEG_LIBRARIES) -- Could NOT find LibXml2 (missing: LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR) -- Could NOT find ZLIB (missing: ZLIB_INCLUDE_DIR) -- Could NOT find ZLIB (missing: ZLIB_INCLUDE_DIR) -- Could NOT find GDAL (missing: GDAL_LIBRARY GDAL_INCLUDE_DIR) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find CURL (missing: CURL_LIBRARY CURL_INCLUDE_DIR) -- Trying to find DCMTK expecting DCMTKConfig.cmake -- Trying to find DCMTK expecting DCMTKConfig.cmake - failed -- Trying to find DCMTK relying on FindDCMTK.cmake -- Please set DCMTK_DIR and re-run configure (missing: DCMTK_config_INCLUDE_DIR DCMTK_dcmdata_INCLUDE_DIR DCMTK_dcmimage_INCLUDE_DIR DCMTK_dcmimgle_INCLUDE_DIR DCMTK_dcmjpeg_INCLUDE_DIR DCMTK_dcmjpls_INCLUDE_DIR DCMTK_dcmnet_INCLUDE_DIR DCMTK_dcmpstat_INCLUDE_DIR DCMTK_dcmqrdb_INCLUDE_DIR DCMTK_dcmsign_INCLUDE_DIR DCMTK_dcmsr_INCLUDE_DIR DCMTK_dcmtls_INCLUDE_DIR DCMTK_ofstd_INCLUDE_DIR DCMTK_oflog_INCLUDE_DIR) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find GStreamer (missing: GSTREAMER_INCLUDE_DIRS GSTREAMER_LIBRARIES GSTREAMER_VERSION GSTREAMER_BASE_INCLUDE_DIRS GSTREAMER_BASE_LIBRARIES GSTREAMER_APP_INCLUDE_DIRS GSTREAMER_APP_LIBRARIES GSTREAMER_PBUTILS_INCLUDE_DIRS GSTREAMER_PBUTILS_LIBRARIES) (found version "") -- Could NOT find SDL2 (missing: SDL2_LIBRARY SDL2_INCLUDE_DIR) -- Could NOT find SDL (missing: SDL_LIBRARY SDL_INCLUDE_DIR) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find JPEG (missing: JPEG_LIBRARY JPEG_INCLUDE_DIR) -- Could NOT find ZLIB (missing: ZLIB_INCLUDE_DIR) -- Could NOT find PNG (missing: PNG_LIBRARY PNG_PNG_INCLUDE_DIR) -- Could NOT find TIFF (missing: TIFF_LIBRARY TIFF_INCLUDE_DIR) -- g++ version 5.3.0 -- Performing Test _OPENTHREADS_ATOMIC_USE_GCC_BUILTINS -- Performing Test _OPENTHREADS_ATOMIC_USE_GCC_BUILTINS - Success -- Performing Test _OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS -- Performing Test _OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS - Failed -- Performing Test _OPENTHREADS_ATOMIC_USE_SUN -- Performing Test _OPENTHREADS_ATOMIC_USE_SUN - Failed -- Performing Test _OPENTHREADS_ATOMIC_USE_WIN32_INTERLOCKED -- Performing Test _OPENTHREADS_ATOMIC_USE_WIN32_INTERLOCKED - Success -- Performing Test _OPENTHREADS_ATOMIC_USE_BSD_ATOMIC -- Performing Test _OPENTHREADS_ATOMIC_USE_BSD_ATOMIC - Failed -- Configuring done -- Generating done -- Build files have been written to: D:/OSG/build-win32-debug
GSTREAMER_INCLUDE_DIRS GSTREAMER_LIBRARIES GSTREAMER_VERSION GSTREAMER_BASE_INCLUDE_DIRS GSTREAMER_BASE_LIBRARIES GSTREAMER_APP_INCLUDE_DIRS GSTREAMER_APP_LIBRARIES GSTREAMER_PBUTILS_INCLUDE_DIRS GSTREAMER_PBUTILS_LIBRARIES) (versión encontrada "") -- The C compiler identification is GNU 5.3.0 -- The CXX compiler identification is GNU 5.3.0 -- Check for working C compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/gcc.exe -- Check for working C compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/gcc.exe -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/g++.exe -- Check for working CXX compiler: C:/Qt/Qt5.11.2/Tools/mingw530_32/bin/g++.exe -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- Looking for pthread.h -- Looking for pthread.h - found -- Looking for pthread_create -- Looking for pthread_create - found -- Found Threads: TRUE -- Found OpenGL: opengl32 -- Could NOT find EGL (missing: EGL_INCLUDE_DIR) -- Checking windows version... -- Performing Test GL_HEADER_HAS_GLINT64 -- Performing Test GL_HEADER_HAS_GLINT64 - Failed -- Performing Test GL_HEADER_HAS_GLUINT64 -- Performing Test GL_HEADER_HAS_GLUINT64 - Failed -- 32 bit architecture detected -- Could NOT find Freetype (missing: FREETYPE_LIBRARY FREETYPE_INCLUDE_DIRS) -- Could NOT find JPEG (missing: JPEG_LIBRARY JPEG_INCLUDE_DIR) -- Could NOT find Jasper (missing: JASPER_LIBRARIES JASPER_INCLUDE_DIR JPEG_LIBRARIES) -- Could NOT find LibXml2 (missing: LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR) -- Could NOT find ZLIB (missing: ZLIB_INCLUDE_DIR) -- Could NOT find ZLIB (missing: ZLIB_INCLUDE_DIR) -- Could NOT find GDAL (missing: GDAL_LIBRARY GDAL_INCLUDE_DIR) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find CURL (missing: CURL_LIBRARY CURL_INCLUDE_DIR) -- Trying to find DCMTK expecting DCMTKConfig.cmake -- Trying to find DCMTK expecting DCMTKConfig.cmake - failed -- Trying to find DCMTK relying on FindDCMTK.cmake -- Please set DCMTK_DIR and re-run configure (missing: DCMTK_config_INCLUDE_DIR DCMTK_dcmdata_INCLUDE_DIR DCMTK_dcmimage_INCLUDE_DIR DCMTK_dcmimgle_INCLUDE_DIR DCMTK_dcmjpeg_INCLUDE_DIR DCMTK_dcmjpls_INCLUDE_DIR DCMTK_dcmnet_INCLUDE_DIR DCMTK_dcmpstat_INCLUDE_DIR DCMTK_dcmqrdb_INCLUDE_DIR DCMTK_dcmsign_INCLUDE_DIR DCMTK_dcmsr_INCLUDE_DIR DCMTK_dcmtls_INCLUDE_DIR DCMTK_ofstd_INCLUDE_DIR DCMTK_oflog_INCLUDE_DIR) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find GStreamer (missing: GSTREAMER_INCLUDE_DIRS GSTREAMER_LIBRARIES GSTREAMER_VERSION GSTREAMER_BASE_INCLUDE_DIRS GSTREAMER_BASE_LIBRARIES GSTREAMER_APP_INCLUDE_DIRS GSTREAMER_APP_LIBRARIES GSTREAMER_PBUTILS_INCLUDE_DIRS GSTREAMER_PBUTILS_LIBRARIES) (found version "") -- Could NOT find SDL2 (missing: SDL2_LIBRARY SDL2_INCLUDE_DIR) -- Could NOT find SDL (missing: SDL_LIBRARY SDL_INCLUDE_DIR) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) -- Could NOT find JPEG (missing: JPEG_LIBRARY JPEG_INCLUDE_DIR) -- Could NOT find ZLIB (missing: ZLIB_INCLUDE_DIR) -- Could NOT find PNG (missing: PNG_LIBRARY PNG_PNG_INCLUDE_DIR) -- Could NOT find TIFF (missing: TIFF_LIBRARY TIFF_INCLUDE_DIR) -- g++ version 5.3.0 -- Performing Test _OPENTHREADS_ATOMIC_USE_GCC_BUILTINS -- Performing Test _OPENTHREADS_ATOMIC_USE_GCC_BUILTINS - Success -- Performing Test _OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS -- Performing Test _OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS - Failed -- Performing Test _OPENTHREADS_ATOMIC_USE_SUN -- Performing Test _OPENTHREADS_ATOMIC_USE_SUN - Failed -- Performing Test _OPENTHREADS_ATOMIC_USE_WIN32_INTERLOCKED -- Performing Test _OPENTHREADS_ATOMIC_USE_WIN32_INTERLOCKED - Success -- Performing Test _OPENTHREADS_ATOMIC_USE_BSD_ATOMIC -- Performing Test _OPENTHREADS_ATOMIC_USE_BSD_ATOMIC - Failed -- Configuring done -- Generating done -- Build files have been written to: D:/OSG/build-win32-debug
nos dice que puedes comenzar a armar. Dar una orden
D:\OSG\build-win32-debug>mingw32-make -j9
puede, como en mi ejemplo, especificar el número de subprocesos de ensamblaje si tiene un procesador multinúcleo (conmutador -j). El proceso de compilación comenzará, tomando aproximadamente ocho minutos en mi computadora

Al final del ensamblaje, instale la biblioteca.
D:\OSG\build-win32-debug> mingw32-make install
después de ejecutar el comando, encontramos la biblioteca instalada en la ruta que hemos establecido previamente

Ahora construyamos la versión de lanzamiento del motor creando otro directorio de compilación
D:\OSG\build-win32-debug>cd .. D:\OSG> mkdir build-win32-release D:\OSG>cd build-win32-release D:\OSG\build-win32-release> cmake -G "MinGW Makefiles" -DCMAKE_INSTALL_PREFIX=E:\Apps\OSG ../OpenSceneGraph D:\OSG\build-win32-release> mingw32-make -j9 D:\OSG\build-win32-release> mingw32-make install
4. Establecer variables de entorno
La ubicación de las bibliotecas OSG después de la instalación puede ser cualquiera: está determinada por los deseos de un usuario en particular y su capacidad para colocar archivos en una computadora. Al mismo tiempo, cuando se configura un proyecto específico que usa datos, la biblioteca requiere una cierta unificación, abstrayéndose de la ubicación específica de las bibliotecas.
Creemos algunas variables de entorno del sistema que indiquen las rutas a bibliotecas, archivos de encabezado y complementos OSG. En mi ejemplo, se verá así

Es necesario crear variables cuyos nombres estén encerrados en rojo en la captura de pantalla. Después de crear las variables, para que sean visibles por las herramientas de desarrollo, en particular, QtCreator necesita al menos iniciar sesión en el sistema (cerrar sesión e iniciar sesión como usuario actual) o, posiblemente, reiniciar el sistema (¡esto es Windows!)
Después de eso, el procedimiento para instalar OSG en nuestra computadora puede considerarse completo.
5. Escribiendo Hello World a QtCreator
Comenzaremos a conocer el motor de gráficos OpenSceneGraph con un simple ejemplo, como es habitual en la programación con un cierto "¡Hola mundo!"
Antes de escribir cualquier código, configuraremos nuestro proyecto para el sistema de compilación qmake, que utilizaremos en toda la serie de artículos. En el lugar del sistema de archivos que nos interesa, cree la siguiente estructura de directorios
OSG-lessons/ |-data/ |-OSG-lessons/ | |-hello/ |-include/ |-src/
En el directorio hello, cree un archivo
hello.pro con el siguiente contenido
Texto completo hello.pro TEMPLATE = app TARGET = hello DESTDIR = ../../bin win32 { OSG_LIB_DIRECTORY = $$(OSG_BIN_PATH) OSG_INCLUDE_DIRECTORY = $$(OSG_INCLUDE_PATH) CONFIG(debug, debug|release) { TARGET = $$join(TARGET,,,_d) LIBS += -L$$OSG_LIB_DIRECTORY -losgd LIBS += -L$$OSG_LIB_DIRECTORY -losgViewerd LIBS += -L$$OSG_LIB_DIRECTORY -losgDBd LIBS += -L$$OSG_LIB_DIRECTORY -lOpenThreadsd } else { LIBS += -L$$OSG_LIB_DIRECTORY -losg LIBS += -L$$OSG_LIB_DIRECTORY -losgViewer LIBS += -L$$OSG_LIB_DIRECTORY -losgDB LIBS += -L$$OSG_LIB_DIRECTORY -lOpenThreads } INCLUDEPATH += $$OSG_INCLUDE_DIRECTORY } unix { CONFIG(debug, debug|release) { TARGET = $$join(TARGET,,,_d) LIBS += -losgd LIBS += -losgViewerd LIBS += -losgDBd LIBS += -lOpenThreadsd } else { LIBS += -losg LIBS += -losgViewer LIBS += -losgDB LIBS += -lOpenThreads } } INCLUDEPATH += ./include HEADERS += $$files(./include/*.h) SOURCES += $$files(./src/*.cpp)
Analizaremos estas letras con más detalle.
TEMPLATE = app TARGET = hello DESTDIR = ../../bin
Las variables especifican la plantilla del proyecto (aplicación - aplicación), el nombre del archivo ejecutable (hola) y el directorio donde se coloca el archivo ejecutable después del ensamblaje.
win32 { OSG_LIB_DIRECTORY = $$(OSG_BIN_PATH) OSG_INCLUDE_DIRECTORY = $$(OSG_INCLUDE_PATH) CONFIG(debug, debug|release) { TARGET = $$join(TARGET,,,_d) LIBS += -L$$OSG_LIB_DIRECTORY -losgd LIBS += -L$$OSG_LIB_DIRECTORY -losgViewerd LIBS += -L$$OSG_LIB_DIRECTORY -losgDBd LIBS += -L$$OSG_LIB_DIRECTORY -lOpenThreadsd } else { LIBS += -L$$OSG_LIB_DIRECTORY -losg LIBS += -L$$OSG_LIB_DIRECTORY -losgViewer LIBS += -L$$OSG_LIB_DIRECTORY -losgDB LIBS += -L$$OSG_LIB_DIRECTORY -lOpenThreads } INCLUDEPATH += $$OSG_INCLUDE_DIRECTORY }
Dependiendo del sistema operativo donde se ensambla el proyecto, definimos variables que indican las rutas a los directorios de la biblioteca y los archivos de encabezado OSG. Aquí es donde las variables de entorno OSG_BIN_PATH y OSG_INCLUDE_PATH fueron útiles, ahora no importa dónde esté instalada la biblioteca OSG. Cualquiera que quiera trabajar con este proyecto en su computadora simplemente escribirá las variables de entorno apropiadas en su sistema sin editar el script de compilación.
CONFIG(debug, debug|release) { TARGET = $$join(TARGET,,,_d) LIBS += -L$$OSG_LIB_DIRECTORY -losgd LIBS += -L$$OSG_LIB_DIRECTORY -losgViewerd LIBS += -L$$OSG_LIB_DIRECTORY -losgDBd LIBS += -L$$OSG_LIB_DIRECTORY -lOpenThreadsd } else { LIBS += -L$$OSG_LIB_DIRECTORY -losg LIBS += -L$$OSG_LIB_DIRECTORY -losgViewer LIBS += -L$$OSG_LIB_DIRECTORY -losgDB LIBS += -L$$OSG_LIB_DIRECTORY -lOpenThreads }
Escribir un script para construir en un sistema operativo tipo UNIX
unix { CONFIG(debug, debug|release) { TARGET = $$join(TARGET,,,_d) LIBS += -losgd LIBS += -losgViewerd LIBS += -losgDBd LIBS += -lOpenThreadsd } else { LIBS += -losg LIBS += -losgViewer LIBS += -losgDB LIBS += -lOpenThreads } }
Aquí configuramos el nombre del archivo ejecutable y especificamos las bibliotecas que deben compilarse con nuestro programa para varias opciones de compilación: tanto de depuración como de lanzamiento. Las bibliotecas de depuración OSG tienen el sufijo "d" después del nombre del archivo. Agregaremos el sufijo "_d" al archivo ejecutable del proyecto para distinguir la opción de depuración de la versión de lanzamiento.
INCLUDEPATH += $$OSG_INCLUDE_DIRECTORY INCLUDEPATH += ./include HEADERS += $$files(./include/*.h) SOURCES += $$files(./src/*.cpp)
Y finalmente, determinamos las rutas de búsqueda para los archivos de encabezado y los archivos incluidos en el árbol del proyecto. Cree un archivo main.h vacío en el directorio include / y un archivo main.cpp en el directorio src /. Abrimos este proyecto en QtCreator y lo configuramos como se muestra en la captura de pantalla

Después de abrir el proyecto, veremos la siguiente imagen.

Escribiremos dicho código en el archivo main.h
#ifndef MAIN_H #define MAIN_H #include <osgDB/ReadFile> #include <osgViewer/Viewer> #endif
A continuación, implementamos el cuerpo principal del programa en el archivo main.cpp
#include "main.h" int main(int argc, char *argv[]) { (void) argc; (void) argv; osg::ref_ptr<osg::Node> root = osgDB::readNodeFile("../data/cessna.osg"); osgViewer::Viewer viewer; viewer.setSceneData(root.get()); return viewer.run(); }
El archivo del modelo de avión debe copiarse en el directorio data /. Este archivo, así como gran parte de lo que se usará en esta serie de artículos, se puede descargar desde
el repositorio OpenSceneGraph-DataDespués de compilar y ejecutar, obtenemos algo como esto

Las dos primeras líneas de nuestro código.
(void) argc; (void) argv;
marque los parámetros de entrada de la función main () como no utilizados para evitar una advertencia del compilador. A continuación, se crea el nodo raíz de la escena, que es el modelo del avión cargado desde el archivo cessna.osg
osg::ref_ptr<osg::Node> root = osgDB::readNodeFile("../data/cessna.osg");
Luego se crea una instancia de la clase osgViewer :: Viewer, el llamado "visor", un objeto que controla la visualización de la escena en la pantalla. Los datos de la escena se pasan al espectador.
viewer.setSceneData(root.get());
y comienza el ciclo de renderizado de escenas
return viewer.run();
Este código más simple ya contiene una serie de conceptos básicos utilizados en OSG. Pero hablar de ellos irá un poco más tarde.
Conclusión
El código fuente completo para los ejemplos descritos a continuación
se puede obtener aquí . Espero que esta publicación tenga lectores interesados,
para continuar ...